driver

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package driver provides low-level Go bindings for the NVIDIA CUDA driver API.

This package provides bindings generated from cuda.h using github.com/ebitengine/purego for cgo-free dynamic loading of libcuda. Functions returning a C status report errors wrapping CUresult with descriptive messages from cuGetErrorName and cuGetErrorString.

CUDA binds the current context to the calling OS thread, and the Go scheduler moves goroutines between threads. A goroutine that makes a context current with Context.SetCurrent or Context.PushCurrent, such as the primary context from Device.PrimaryCtxRetain, should call runtime.LockOSThread first and keep the thread locked while it makes calls that use that context.

Errors

Kernel launches and asynchronous copies report their failures later, so a call may return the error of an earlier asynchronous launch rather than one of its own. CtxSynchronize waits for the context's outstanding work and returns such an error.

Array Management

Checkpointing

Debugging

Context Management

External Resources

Device Management

Driver Queries

Event Management

RDMA

Function Management

Graph Management

Initialization

  • Init: Initialize the CUDA driver API Initializes the driver API and must be called before any other function from the driver API in the current process.

IPC

Kernel Management

Kernel Execution

Library Management

Linker

Virtual Memory Management

Memory Management

Memory Pools

Texture Management

Module Management

Multicast

Occupancy

Stream Management

Stream Ordered Memory

  • Stream.BatchMemOp: Batch operations to synchronize the stream via memory operations.

Surface Management

Tensor Core

User Objects

Other

Functions bound at load time

Each function below binds, when the library loads, the first of its symbols that the library exports, newest first, so that it also runs against libraries older than the header. A shim takes the newest prototype and reaches its last symbol, an older version with fewer parameters, as its documentation describes.

Example

Example initializes the driver, takes a context on the first device, and round-trips a slice through device memory. It returns early when the CUDA driver is unavailable. Successful execution also requires a CUDA device.

package main

import (
	"fmt"
	"runtime"
	"unsafe"

	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	// A CUDA context is current on an OS thread, not on a goroutine.
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	if err := driver.Init(0); err != nil {
		fmt.Println("CUDA driver unavailable:", err)
		return
	}
	dev, err := driver.DeviceGet(0)
	if err != nil {
		fmt.Println("device:", err)
		return
	}
	name, err := dev.Name()
	if err != nil {
		fmt.Println("name:", err)
		return
	}
	ctx, err := driver.NewContext(dev, 0)
	if err != nil {
		fmt.Println("context:", err)
		return
	}
	defer ctx.Close()

	host := []float32{1, 2, 3, 4}
	size := uint(len(host)) * uint(unsafe.Sizeof(host[0]))
	dptr, err := driver.MemAllocBytes(size)
	if err != nil {
		fmt.Println("alloc:", err)
		return
	}
	defer dptr.Free()

	if err := dptr.CopyFromHost(host); err != nil {
		fmt.Println("copy in:", err)
		return
	}
	back := make([]float32, len(host))
	if err := dptr.CopyToHost(back); err != nil {
		fmt.Println("copy out:", err)
		return
	}
	fmt.Println(name, back)
}

Index

Examples

Constants

View Source
const (
	LaunchParamBufferPointer uintptr = LaunchParamBufferPointerAsInt
	LaunchParamBufferSize    uintptr = LaunchParamBufferSizeAsInt
	LaunchParamEnd           uintptr = LaunchParamEndAsInt
)

Driver uintptr tokens from cuda.h.

View Source
const (
	ArraySparsePropertiesSingleMiptail = 0x1
	ComputeAcceleratedTargetBase       = 0x10000
	ComputeFamilyTargetBase            = 0x20000
	GraphCondAssignDefault             = 0x1
	GraphKernelNodePortDefault         = 0
	GraphKernelNodePortLaunchOrder     = 2
	GraphKernelNodePortProgrammatic    = 1
	LaunchKernelRequiredBlockDim       = 1
	LaunchParamBufferPointerAsInt      = 0x01
	LaunchParamBufferSizeAsInt         = 0x02
	LaunchParamEndAsInt                = 0x00
	MemhostallocDevicemap              = 0x02
	MemhostallocPortable               = 0x01
	MemhostallocWritecombined          = 0x04
	MemhostregisterDevicemap           = 0x02
	MemhostregisterIomemory            = 0x04
	MemhostregisterPortable            = 0x01
	MemhostregisterReadOnly            = 0x08
	MemCreateUsageHwDecompress         = 0x2
	MemCreateUsageTilePool             = 0x1
	MemPoolCreateUsageHwDecompress     = 0x2
	ParamTrDefault                     = -1
	TrsaOverrideFormat                 = 0x01
	TrsfDisableTrilinearOptimization   = 0x20
	TrsfNormalizedCoordinates          = 0x02
	TrsfReadAsInteger                  = 0x01
	TrsfSeamlessCubemap                = 0x40
	TrsfSrgb                           = 0x10
)

Driver flags and numeric constants from cuda.h.

View Source
const (
	Array3dColorAttachment                       = 0x20
	Array3dCubemap                               = 0x04
	Array3dDeferredMapping                       = 0x80
	Array3dDepthTexture                          = 0x10
	Array3dLayered                               = 0x01
	Array3dSparse                                = 0x40
	Array3dSurfaceLdst                           = 0x02
	Array3dTextureGather                         = 0x08
	Array3dVideoEncodeDecode                     = 0x100
	CooperativeLaunchMultiDeviceNoPostLaunchSync = 0x02
	CooperativeLaunchMultiDeviceNoPreLaunchSync  = 0x01
	ExternalMemoryDedicated                      = 0x1
	ExternalSemaphoreSignalSkipNvscibufMemsync   = 0x01
	ExternalSemaphoreWaitSkipNvscibufMemsync     = 0x02
	NvscisyncAttrSignal                          = 0x1
	NvscisyncAttrWait                            = 0x2
)

Driver flags and numeric constants from cuda.h.

View Source
const (
	Array3d2darray = 0x01
)

Array3d2darray is an alias for Array3dLayered.

Deprecated: Use Array3dLayered instead.

View Source
const (
	// Version is CUDA_VERSION. CUDA API version number.
	//
	// This is the version of the headers the bindings were generated from, not of the library loaded at run time. [DriverGetVersion] reports that.
	Version = 13050
)

Variables

This section is empty.

Functions

func BoundSymbol

func BoundSymbol(name string) string

BoundSymbol returns the symbol the loaded library bound for the C function name, loading the library first if necessary, or "" if none bound. It answers for the functions that bind the first of several symbols the library exports: BoundSymbol("cuCtxCreate") returns "cuCtxCreate_v4" when the library exports it, and an older spelling otherwise. It returns "" for any other name.

func CheckpointProcessCheckpoint

func CheckpointProcessCheckpoint(pid int32, args *CheckpointCheckpointArgs) error

CheckpointProcessCheckpoint checkpoints a CUDA process’s GPU memory contents.

Checkpoints a CUDA process specified by pid. The GPU memory contents will be brought into host memory or mapped onto the calling process’s GPUs for user-defined behavior. Underlying GPU references are released when checkpointing completes. The process must be in the ProcessStateLocked state to checkpoint. When CheckpointCheckpointArgs.customStorageInfo_out is not NULL, all the GPU memory allocated by the process with pid will be mapped onto the calling process’s GPUs so the application can copy the memory to custom storage. Upon return of this call, the pointer referenced by CheckpointCheckpointArgs.customStorageInfo_out will point to a CheckpointCustomStorageInfo struct allocated and populated by the driver. For each GPU which contains data from the checkpointed process, there is a corresponding entry in the CheckpointCustomStoragePerDeviceData array.

The application is responsible for copying the mapped data from the GPU at the specified device address to custom storage. When checkpointing to custom storage, the application is expected to call CheckpointOperationHandle.Complete. The CheckpointCustomStorageInfo.handle set by this call should be passed to CheckpointOperationHandle.Complete in handle. The driver synchronizes all the streams in CheckpointOperationHandle.Complete, at which point the copy to custom storage is considered complete. When checkpointing to custom storage, the application is expected to retain primary contexts of all the devices used by the process to be checkpointed. Otherwise CheckpointProcessCheckpoint will return ErrInvalidContext. Unlike other checkpoint operations, checkpointing to custom storage requires Init to have been called before execution. Checkpointing the calling process’s GPU memory to custom storage is not supported. Upon successful return, the target process will be in the ProcessStateCheckpointing state. When CheckpointCheckpointArgs.customStorageInfo_out is NULL, the GPU memory contents will be brought into host memory by CheckpointProcessCheckpoint. The application is not expected to copy the GPU memory contents. The application is also not expected to call CheckpointOperationHandle.Complete. Upon successful return, the target process will be in the ProcessStateCheckpointed state.

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessCheckpoint.

  • pid: The process ID of the CUDA process
  • args: Optional checkpoint operation arguments

Errors:

Wraps cuCheckpointProcessCheckpoint.

func CheckpointProcessGetRestoreThreadId

func CheckpointProcessGetRestoreThreadId(pid int32) (int32, error)

CheckpointProcessGetRestoreThreadId returns the restore thread ID for a CUDA process.

Returns the thread ID of the CUDA restore thread for the process specified by pid.

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessGetRestoreThreadId.

  • pid: The process ID of the CUDA process

Errors:

Wraps cuCheckpointProcessGetRestoreThreadId.

func CheckpointProcessLock

func CheckpointProcessLock(pid int32, args *CheckpointLockArgs) error

CheckpointProcessLock locks a running CUDA process.

Lock the CUDA process specified by pid which will block further CUDA API calls. Process must be in the RUNNING state in order to lock. Upon successful return the process will be in the LOCKED state. If timeoutMs is specified and the timeout is reached the process will be left in the RUNNING state upon return.

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessLock.

  • pid: The process ID of the CUDA process
  • args: Optional lock operation arguments

Errors:

Wraps cuCheckpointProcessLock.

func CheckpointProcessRestore

func CheckpointProcessRestore(pid int32, args *CheckpointRestoreArgs) error

CheckpointProcessRestore restores a CUDA process’s GPU memory contents from its last checkpoint.

Restores a CUDA process specified by pid from its last checkpoint. Process must be in the ProcessStateCheckpointed state to restore. GPU UUID pairs can be specified in args to remap the process old GPUs onto new GPUs. The GPU to restore onto needs to have enough memory and be of the same chip type as the old GPU. If an array of GPU UUID pairs is specified, it must contain every checkpointed GPU. CUDA process restore requires persistence mode to be enabled or Init to have been called before execution. When CheckpointRestoreArgs.customStorageInfo_out is not NULL, all the GPU memory to be restored for the process with pid will be mapped onto the calling process’s GPUs so the application can copy the memory back to the GPU. Upon return of this call, the pointer referenced by CheckpointRestoreArgs.customStorageInfo_out will point to a CheckpointCustomStorageInfo struct allocated and populated by the driver. For each GPU which contains data from the restored process, there is a corresponding entry in the CheckpointCustomStoragePerDeviceData array.

The application is responsible for copying the data from custom storage to the GPU at the specified device address. When restoring from custom storage, the application is expected to call CheckpointOperationHandle.Complete. The CheckpointCustomStorageInfo.handle set by this call should be passed to CheckpointOperationHandle.Complete in handle. The driver synchronizes all the streams in CheckpointOperationHandle.Complete, at which point the copy from custom storage is considered complete. When restoring from custom storage, the application is expected to retain primary contexts of all the devices used by the process to be restored. Otherwise CheckpointProcessRestore will return ErrInvalidContext . Restoring the calling process’s GPU memory from custom storage is not supported. Upon successful return, the target process will be in the ProcessStateRestoring state. When CheckpointRestoreArgs.customStorageInfo_out is NULL, the GPU memory contents will be restored from host memory by CheckpointProcessRestore. The application is not expected to copy back the GPU memory contents. The application is also not expected to call CheckpointOperationHandle.Complete. Upon successful return, the target process will be in the ProcessStateLocked state.

See also: Init

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessRestore.

  • pid: The process ID of the CUDA process
  • args: Optional restore operation arguments

Errors:

Wraps cuCheckpointProcessRestore.

func CheckpointProcessUnlock

func CheckpointProcessUnlock(pid int32, args *CheckpointUnlockArgs) error

CheckpointProcessUnlock unlocks a CUDA process to allow CUDA API calls.

Unlocks a process specified by pid allowing it to resume making CUDA API calls. Process must be in the LOCKED state. Upon successful return the process will be in the RUNNING state.

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessUnlock.

  • pid: The process ID of the CUDA process
  • args: Optional unlock operation arguments

Errors:

Wraps cuCheckpointProcessUnlock.

func Close

func Close() error

Close unloads the library and clears all bound function pointers.

The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.

func CoredumpGetAttribute

func CoredumpGetAttribute(attrib CoredumpSettings, value unsafe.Pointer, size *uint) error

CoredumpGetAttribute allows caller to fetch a coredump attribute value for the current context.

Returns in *value the requested value specified by attrib. It is up to the caller to ensure that the data type and size of *value matches the request. If the caller calls this function with *value equal to NULL, the size of the memory region (in bytes) expected for attrib will be placed in size. The supported attributes are:

  • CoredumpEnableOnException: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CoredumpFile. The default value is false unless set to true globally or locally, or the CtxUserCoredumpEnable flag was set during context creation.
  • CoredumpTriggerHost: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CoredumpSkipAbort flag to disable host device abort() if needed.
  • CoredumpLightweight: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false unless set to true globally or locally. This attribute is deprecated as of CUDA 12.5, please use CoredumpSettingsCoredumpGenerationFlags instead.
  • CoredumpEnableUserTrigger: Bool where true means that a coredump can be created by writing to the system pipe specified by CoredumpPipe. The default value is false unless set to true globally or locally.
  • CoredumpFile: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application.
  • CoredumpPipe: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application.
  • CoredumpSettingsCoredumpGenerationFlags: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: CoredumpDefaultFlags - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access. CoredumpSkipNonrelocatedElfImages - Coredump will not include the data from CUDA source modules that are not relocated at runtime. CoredumpSkipGlobalMemory - Coredump will not include device-side global data that does not belong to any context. CoredumpSkipSharedMemory - Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. CoredumpSkipLocalMemory - Coredump will not include local memory from the kernel. CoredumpLightweightFlags - Enables all of the above options. Equiavlent to setting the CoredumpLightweight attribute to true. CoredumpSkipAbort - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CoredumpTriggerHost but better reflects the default behavior. CoredumpSkipConstbankMemory - Coredump will not include constbank memory. CoredumpGzipCompress - The generated coredump will be compressed with gzip, and .gz suffix will be appended to the filename, if it’s not a part of it already. CoredumpFaultedContextsOnly - The coredump will only include contexts that have encountered an exception or a trap. CoredumpNoErrbarAtExit - By default, when coredumps are requested, the GPU will ensure memory faults and other errors prevent warps from exiting, if possible. This can potentially affect the performance of the application. Setting this flag will disable this functionality, making it possible for faulted warps to exit, but also avoiding the potential performance hit. CoredumpLogOnly - Setting this flag will disable actual generation of the coredump file, but exception details will still be logged.

See also: CoredumpGetAttributeGlobal, CoredumpSetAttribute, CoredumpSetAttributeGlobal

  • attrib: The enum defining which value to fetch
  • value: void* containing the requested data
  • size: The size of the memory region value points to

Errors:

Wraps cuCoredumpGetAttribute.

func CoredumpGetAttributeGlobal

func CoredumpGetAttributeGlobal(attrib CoredumpSettings, value unsafe.Pointer, size *uint) error

CoredumpGetAttributeGlobal allows caller to fetch a coredump attribute value for the entire application.

Returns in *value the requested value specified by attrib. It is up to the caller to ensure that the data type and size of *value matches the request. If the caller calls this function with *value equal to NULL, the size of the memory region (in bytes) expected for attrib will be placed in size. The supported attributes are:

  • CoredumpEnableOnException: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CoredumpFile. The default value is false.
  • CoredumpTriggerHost: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CoredumpSkipAbort flag to disable host device abort() if needed.
  • CoredumpLightweight: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CoredumpSettingsCoredumpGenerationFlags instead.
  • CoredumpEnableUserTrigger: Bool where true means that a coredump can be created by writing to the system pipe specified by CoredumpPipe. The default value is false.
  • CoredumpFile: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application.
  • CoredumpPipe: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application.
  • CoredumpSettingsCoredumpGenerationFlags: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: CoredumpDefaultFlags - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access. CoredumpSkipNonrelocatedElfImages - Coredump will not include the data from CUDA source modules that are not relocated at runtime. CoredumpSkipGlobalMemory - Coredump will not include device-side global data that does not belong to any context. CoredumpSkipSharedMemory - Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. CoredumpSkipLocalMemory - Coredump will not include local memory from the kernel. CoredumpLightweightFlags - Enables all of the above options. Equiavlent to setting the CoredumpLightweight attribute to true. CoredumpSkipAbort - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CoredumpTriggerHost but better reflects the default behavior. CoredumpSkipConstbankMemory - Coredump will not include constbank memory. CoredumpGzipCompress - The generated coredump will be compressed with gzip, and .gz suffix will be appended to the filename, if it’s not a part of it already. CoredumpFaultedContextsOnly - The coredump will only include contexts that have encountered an exception or a trap. CoredumpNoErrbarAtExit - By default, when coredumps are requested, the GPU will ensure memory faults and other errors prevent warps from exiting, if possible. This can potentially affect the performance of the application. Setting this flag will disable this functionality, making it possible for faulted warps to exit, but also avoiding the potential performance hit. CoredumpLogOnly - Setting this flag will disable actual generation of the coredump file, but exception details will still be logged.

See also: CoredumpGetAttribute, CoredumpSetAttribute, CoredumpSetAttributeGlobal

  • attrib: The enum defining which value to fetch
  • value: void* containing the requested data
  • size: The size of the memory region value points to

Errors:

Wraps cuCoredumpGetAttributeGlobal.

func CoredumpSetAttribute

func CoredumpSetAttribute(attrib CoredumpSettings, value unsafe.Pointer, size *uint) error

CoredumpSetAttribute allows caller to set a coredump attribute value for the current context.

This function should be considered an alternate interface to the CUDA-GDB environment variables defined in this document: https://docs.nvidia.com/cuda/cuda-gdb/index.html#gpu-coredump An important design decision to note is that any coredump environment variable values set before CUDA initializes will take permanent precedence over any values set with this function. This decision was made to ensure no change in behavior for any users that may be currently using these variables to get coredumps. *value shall contain the requested value specified by set. It is up to the caller to ensure that the data type and size of *value matches the request. If the caller calls this function with *value equal to NULL, the size of the memory region (in bytes) expected for set will be placed in size. /note This function will return ErrNotSupported if the caller attempts to set CoredumpEnableOnException on a GPU of with Compute Capability < 6.0. CoredumpSetAttributeGlobal works on those platforms as an alternative. /note CoredumpEnableUserTrigger and CoredumpPipe cannot be set on a per-context basis. The supported attributes are:

  • CoredumpEnableOnException: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CoredumpFile. The default value is false.
  • CoredumpTriggerHost: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CoredumpSkipAbort flag to disable host device abort() if needed.
  • CoredumpLightweight: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CoredumpSettingsCoredumpGenerationFlags instead.
  • CoredumpFile: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application.
  • CoredumpSettingsCoredumpGenerationFlags: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: CoredumpDefaultFlags - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access. CoredumpSkipNonrelocatedElfImages - Coredump will not include the data from CUDA source modules that are not relocated at runtime. CoredumpSkipGlobalMemory - Coredump will not include device-side global data that does not belong to any context. CoredumpSkipSharedMemory - Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. CoredumpSkipLocalMemory - Coredump will not include local memory from the kernel. CoredumpLightweightFlags - Enables all of the above options. Equiavlent to setting the CoredumpLightweight attribute to true. CoredumpSkipAbort - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CoredumpTriggerHost but better reflects the default behavior. CoredumpSkipConstbankMemory - Coredump will not include constbank memory. CoredumpGzipCompress - The generated coredump will be compressed with gzip, and .gz suffix will be appended to the filename, if it’s not a part of it already. CoredumpFaultedContextsOnly - The coredump will only include contexts that have encountered an exception or a trap. CoredumpNoErrbarAtExit - By default, when coredumps are requested, the GPU will ensure memory faults and other errors prevent warps from exiting, if possible. This can potentially affect the performance of the application. Setting this flag will disable this functionality, making it possible for faulted warps to exit, but also avoiding the potential performance hit. CoredumpLogOnly - Setting this flag will disable actual generation of the coredump file, but exception details will still be logged.

Note: CoredumpSettingsCoredumpGenerationFlags replaces all previously set coredump flags. Mixing CoredumpSettingsCoredumpGenerationFlags with the deprecated boolean attributes (CoredumpTriggerHost, CoredumpLightweight) can result in undefined behavior. To avoid issues, either use only CoredumpSettingsCoredumpGenerationFlags or combine all desired flag bits (including CoredumpSkipAbort) in a single call.

See also: CoredumpGetAttributeGlobal, CoredumpGetAttribute, CoredumpSetAttributeGlobal

  • attrib: The enum defining which value to set
  • value: void* containing the requested data
  • size: The size of the memory region value points to

Errors:

Wraps cuCoredumpSetAttribute.

func CoredumpSetAttributeGlobal

func CoredumpSetAttributeGlobal(attrib CoredumpSettings, value unsafe.Pointer, size *uint) error

CoredumpSetAttributeGlobal allows caller to set a coredump attribute value globally.

This function should be considered an alternate interface to the CUDA-GDB environment variables defined in this document: https://docs.nvidia.com/cuda/cuda-gdb/index.html#gpu-coredump An important design decision to note is that any coredump environment variable values set before CUDA initializes will take permanent precedence over any values set with this function. This decision was made to ensure no change in behavior for any users that may be currently using these variables to get coredumps. *value shall contain the requested value specified by set. It is up to the caller to ensure that the data type and size of *value matches the request. If the caller calls this function with *value equal to NULL, the size of the memory region (in bytes) expected for set will be placed in size. The supported attributes are:

  • CoredumpEnableOnException: Bool where true means that GPU exceptions from this context will create a coredump at the location specified by CoredumpFile. The default value is false.
  • CoredumpTriggerHost: Bool where true means that the host CPU will also create a coredump. The default value is true unless set to false globally or or locally. This value is deprecated as of CUDA 12.5 - raise the CoredumpSkipAbort flag to disable host device abort() if needed.
  • CoredumpLightweight: Bool where true means that any resulting coredumps will not have a dump of GPU memory or non-reloc ELF images. The default value is false. This attribute is deprecated as of CUDA 12.5, please use CoredumpSettingsCoredumpGenerationFlags instead.
  • CoredumpEnableUserTrigger: Bool where true means that a coredump can be created by writing to the system pipe specified by CoredumpPipe. The default value is false.
  • CoredumpFile: String of up to 1023 characters that defines the location where any coredumps generated by this context will be written. The default value is core.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA applications and PID is the process ID of the CUDA application.
  • CoredumpPipe: String of up to 1023 characters that defines the name of the pipe that will be monitored if user-triggered coredumps are enabled. This value may not be changed after CoredumpEnableUserTrigger is set to true. The default value is corepipe.cuda.HOSTNAME.PID where HOSTNAME is the host name of the machine running the CUDA application and PID is the process ID of the CUDA application.
  • CoredumpSettingsCoredumpGenerationFlags: An integer with values to allow granular control the data contained in a coredump specified as a bitwise OR combination of the following values: CoredumpDefaultFlags - if set by itself, coredump generation returns to its default settings of including all memory regions that it is able to access. CoredumpSkipNonrelocatedElfImages - Coredump will not include the data from CUDA source modules that are not relocated at runtime. CoredumpSkipGlobalMemory - Coredump will not include device-side global data that does not belong to any context. CoredumpSkipSharedMemory - Coredump will not include grid-scale shared memory for the warp that the dumped kernel belonged to. CoredumpSkipLocalMemory - Coredump will not include local memory from the kernel. CoredumpLightweightFlags - Enables all of the above options. Equiavlent to setting the CoredumpLightweight attribute to true. CoredumpSkipAbort - If set, GPU exceptions will not raise an abort() in the host CPU process. Same functional goal as CoredumpTriggerHost but better reflects the default behavior. CoredumpSkipConstbankMemory - Coredump will not include constbank memory. CoredumpGzipCompress - The generated coredump will be compressed with gzip, and .gz suffix will be appended to the filename, if it’s not a part of it already. CoredumpFaultedContextsOnly - The coredump will only include contexts that have encountered an exception or a trap. CoredumpNoErrbarAtExit - By default, when coredumps are requested, the GPU will ensure memory faults and other errors prevent warps from exiting, if possible. This can potentially affect the performance of the application. Setting this flag will disable this functionality, making it possible for faulted warps to exit, but also avoiding the potential performance hit. CoredumpLogOnly - Setting this flag will disable actual generation of the coredump file, but exception details will still be logged.

Note: CoredumpSettingsCoredumpGenerationFlags replaces all previously set coredump flags. Mixing CoredumpSettingsCoredumpGenerationFlags with the deprecated boolean attributes (CoredumpTriggerHost, CoredumpLightweight) can result in undefined behavior. To avoid issues, either use only CoredumpSettingsCoredumpGenerationFlags or combine all desired flag bits (including CoredumpSkipAbort) in a single call.

See also: CoredumpGetAttribute, CoredumpGetAttributeGlobal, CoredumpSetAttribute

  • attrib: The enum defining which value to set
  • value: void* containing the requested data
  • size: The size of the memory region value points to

Errors:

Wraps cuCoredumpSetAttributeGlobal.

func CtxGetFlags

func CtxGetFlags() (uint32, error)

CtxGetFlags returns the flags for the current context.

Returns the flags of the current context. See NewContext for flag values.

See also: NewContext, Context.ApiVersion, CtxGetCacheConfig, CtxGetCurrent, CtxGetDevice, CtxGetLimit, CtxGetSharedMemConfig, CtxGetStreamPriorityRange, CtxSetFlags, cudaGetDeviceFlags

Errors:

Wraps cuCtxGetFlags.

func CtxGetLimit

func CtxGetLimit(limit Limit) (uint, error)

CtxGetLimit returns resource limits.

Returns the current size of limit. The supported Limit values are:

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize, cudaDeviceGetLimit

  • limit: Limit to query

Errors:

Wraps cuCtxGetLimit.

func CtxGetStreamPriorityRange

func CtxGetStreamPriorityRange() (leastPriority int32, greatestPriority int32, err error)

CtxGetStreamPriorityRange 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 meaningful range as specified by this API, the priority is automatically clamped down or up to either *leastPriority or *greatestPriority respectively. See StreamCreateWithPriority 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 Device.Attribute).

See also: StreamCreateWithPriority, Stream.Priority, CtxGetDevice, CtxGetFlags, CtxSetLimit, CtxSynchronize, cudaDeviceGetStreamPriorityRange

  • leastPriority: Pointer to an int in which the numerical value for least stream priority is returned
  • greatestPriority: Pointer to an int in which the numerical value for greatest stream priority is returned

Errors:

Wraps cuCtxGetStreamPriorityRange.

func CtxResetPersistingL2Cache

func CtxResetPersistingL2Cache() error

CtxResetPersistingL2Cache resets all persisting lines in cache to normal status.

CtxResetPersistingL2Cache Resets all persisting lines in cache to normal status. Takes effect on function return.

See also: AccessPolicyWindow

Errors:

Wraps cuCtxResetPersistingL2Cache.

func CtxSetCacheConfig

func CtxSetCacheConfig(config FuncCacheConfig) error

CtxSetCacheConfig sets the preferred cache configuration for the current context.

On devices where the L1 cache and shared memory use the same hardware resources, this sets through config the preferred cache configuration for the current context. This is only a preference. The driver 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 Function.SetCacheConfig or Kernel.SetCacheConfig will be preferred over this context-wide setting. Setting the context-wide cache configuration to FuncCachePreferNone 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:

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetLimit, CtxSynchronize, Function.SetCacheConfig, cudaDeviceSetCacheConfig, Kernel.SetCacheConfig

  • config: Requested cache configuration

Errors:

Wraps cuCtxSetCacheConfig.

func CtxSetFlags

func CtxSetFlags(flags uint32) error

CtxSetFlags sets the flags for the current context.

Sets the flags for the current context overwriting previously set ones. See Device.PrimaryCtxSetFlags for flag values.

See also: NewContext, Context.ApiVersion, CtxGetCacheConfig, CtxGetCurrent, CtxGetDevice, CtxGetLimit, CtxGetSharedMemConfig, CtxGetStreamPriorityRange, CtxGetFlags, cudaGetDeviceFlags, Device.PrimaryCtxSetFlags

  • flags: Flags to set on the current context

Errors:

Wraps cuCtxSetFlags.

func CtxSetLimit

func CtxSetLimit(limit Limit, value uint) error

CtxSetLimit sets resource limits.

Setting limit to value is a request by the application to update the current limit maintained by the context. 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 CtxGetLimit to find out exactly what the limit has been set to. Setting each Limit has its own specific restrictions, so each is discussed here.

  • LimitStackSize controls the stack size in bytes of each GPU thread. The driver automatically increases the per-thread stack size for each kernel launch as needed. This size isn’t reset back to the original value after each launch. Setting this value will take effect immediately, and if necessary, the device will block until all preceding requested tasks are complete.
  • LimitPrintfFifoSize controls the size in bytes of the FIFO used by the printf() device system call. Setting LimitPrintfFifoSize must be performed before launching any kernel that uses the printf() device system call, otherwise ErrInvalidValue will be returned.
  • LimitMallocHeapSize controls the size in bytes of the heap used by the malloc() and free() device system calls. Setting LimitMallocHeapSize must be performed before launching any kernel that uses the malloc() or free() device system calls, otherwise ErrInvalidValue will be returned.
  • LimitDevRuntimeSyncDepth controls the maximum nesting depth of a grid at which a thread can safely call cudaDeviceSynchronize(). Setting this limit must be performed before any launch of a kernel that uses the device runtime and calls cudaDeviceSynchronize() above the default sync depth, two levels of grids. Calls to cudaDeviceSynchronize() will fail with error code cudaErrorSyncDepthExceeded 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 driver to reserve large amounts of device memory which can no longer be used for user allocations. If these reservations of device memory fail, CtxSetLimit will return ErrOutOfMemory, 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 versions will result in the error ErrUnsupportedLimit being returned.
  • LimitDevRuntimePendingLaunchCount controls the maximum number of outstanding device runtime launches that can be made from the current context. 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 return cudaErrorLaunchPendingCountExceeded when cudaGetLastError() 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 driver to reserve larger amounts of device memory upfront which can no longer be used for allocations. If these reservations fail, CtxSetLimit will return ErrOutOfMemory, 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 error ErrUnsupportedLimit being returned.
  • LimitMaxL2FetchGranularity 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.
  • LimitPersistingL2CacheSize 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.
  • LimitPerBlockMemorySize constrols size in bytes of per-block memory.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSynchronize, cudaDeviceSetLimit

  • limit: Limit to set
  • value: Size of limit

Errors:

Wraps cuCtxSetLimit.

func CtxSetSharedMemConfig deprecated

func CtxSetSharedMemConfig(config Sharedconfig) error

CtxSetSharedMemConfig sets the shared memory configuration for the current context.

On devices with configurable shared memory banks, this function will set the context’s shared memory bank size which is used for subsequent kernel launches. Changed the shared memory configuration between launches may insert a device side synchronization point between those launches. 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:

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetLimit, CtxSynchronize, CtxGetSharedMemConfig, Function.SetCacheConfig, cudaDeviceSetSharedMemConfig

  • config: requested shared memory configuration

Errors:

Wraps cuCtxSetSharedMemConfig.

Deprecated: Deprecated by NVIDIA.

func CtxSynchronize

func CtxSynchronize() error

CtxSynchronize blocks for the current context’s tasks to complete.

Blocks until the current context has completed all preceding requested tasks. If the current context is the primary context, green contexts that have been created will also be synchronized. CtxSynchronize returns an error if one of the preceding tasks failed. If the context was created with the CtxSchedBlockingSync flag, the CPU thread will block until the GPU context has finished its work.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, cudaDeviceSynchronize

Errors:

Wraps cuCtxSynchronize.

func CtxSynchronizeV1

func CtxSynchronizeV1() error

CtxSynchronizeV1 blocks for the current context’s tasks to complete.

Blocks until the current context has completed all preceding requested tasks. If the current context is the primary context, green contexts that have been created will also be synchronized. CtxSynchronize returns an error if one of the preceding tasks failed. If the context was created with the CtxSchedBlockingSync flag, the CPU thread will block until the GPU context has finished its work.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, cudaDeviceSynchronize

Errors:

Wraps cuCtxSynchronize.

func DevSmResourceSplit

func DevSmResourceSplit(result *DevResource, nbGroups uint32, input *DevResource, remainder *DevResource, flags uint32, groupParams *CuDevSmResourceGroupParams) error

DevSmResourceSplit splits a DevResourceTypeSm resource into structured groups.

This API will split a resource of DevResourceTypeSm into nbGroups structured device resource groups (the result array), as well as an optional remainder, according to a set of requirements specified in the groupParams array. The term “structured” is a trait that specifies the result has SMs that are co-scheduled together. This co-scheduling can be specified via the coscheduledSmCount field of the groupParams structure, while the smCount will specify how many SMs are required in total for that result. The remainder is always “unstructured”, it does not have any set guarantees with respect to co-scheduling and those properties will need to either be queried via the occupancy set of APIs or further split into structured groups by this API. The API has a discovery mode for use cases where it is difficult to know ahead of time what the SM count should be. Discovery happens when the smCount field of a given groupParams array entry is set to 0 - the smCount will be filled in by the API with the derived SM count according to the provided groupParams fields and constraints. Discovery can be used with both a valid result array and with a NULL result pointer value. The latter is useful in situations where the smCount will end up being zero, which is an invalid value to create a result entry with, but allowed for discovery purposes when the result is NULL. The groupParams array is evaluated from index 0 to nbGroups - 1. For each index in the groupParams array, the API will evaluate which SMs may be a good fit based on constraints and assign those SMs to result. This evaluation order is important to consider when using discovery mode, as it helps discover the remaining SMs. For a valid call:

  • result should point to a DevResource array of size nbGroups, or alternatively, may be NULL, if the developer wishes for only the groupParams entries to be updated
  • input should be a valid DevResourceTypeSm resource that originates from querying the green context, device context, or device.
  • The remainder group may be NULL.
  • There are no API flags at this time, so the value passed in should be 0.
  • A CuDevSmResourceGroupParams array of size nbGroups. Each entry must be zero-initialized. smCount: must be either 0 or in the range of [2,inputSmCount] where inputSmCount is the amount of SMs the input resource has. smCount must be a multiple of 2, as well as a multiple of coscheduledSmCount if it is nonzero. When assigning SMs to a group (and if results are expected by having the result parameter set), smCount cannot end up with 0 or a value less than coscheduledSmCount otherwise ErrInvalidResourceConfiguration will be returned. coscheduledSmCount: allows grouping SMs together in order to be able to launch clusters on Compute Architecture 9.0+. The default value may be queried from the device’s DevResourceTypeSm resource (8 on Compute Architecture 9.0+ and 2 otherwise). The maximum is 32 on Compute Architecture 9.0+ and 2 otherwise. A coscheduledSmCount of 0 uses the default value internally while preserving 0 in groupParams. Cluster occupancy will be derived from the resulting SM topology. preferredCoscheduledSmCount: Attempts to merge coscheduledSmCount groups into larger groups, in order to make use of preferredClusterDimensions on Compute Architecture 10.0+. The default value is set to coscheduledSmCount. flags: DevSmResourceGroupBackfill: Treats constraints as a hint, ignoring them if necessary to reach the requested smCount. Lets smCount be a non-multiple of coscheduledSmCount, filling the difference between SM count and already assigned co-scheduled groupings with other SMs. This lets any resulting group behave similar to the remainder group for example. When used with DevSmResourceGroupLocalityDomainId, backfill fills up to the requested smCount using the target locality domain first, then SMs not attributed to any locality domain, then SMs from other locality domains. If no SMs can be found in the requested locality domain, ErrInvalidResourceConfiguration is returned. DevSmResourceGroupLocalityDomainId: Specifies that the SM partition should be localized to the specified localityDomainId. localityDomainId: Specifies the locality domain that the partitioned SMs must be located on. Only valid when DevSmResourceGroupLocalityDomainId is set in flags.

Example params and their effect:

The difference between a catch-all param group as the last entry and the remainder is in two aspects:

  • The remainder may be NULL / _TYPE_INVALID (if there are no SMs remaining), while a result group must always be valid.
  • The remainder does not have a structure, while the result group will always need to adhere to a structure of coscheduledSmCount (even if its just 2), and therefore must always have enough coscheduled SMs to cover that requirement (even with the DevSmResourceGroupBackfill flag enabled).

Splitting an input into N groups, can be accomplished by repeatedly splitting off 1 group and re-splitting the remainder (a bisect operation). However, it’s recommended to accomplish this with a single call wherever possible.

See also: GreenCtx.DevResource, Context.DevResource, Device.DevResource

Requires CUDA 13.1 (driver r590) or later; see HasDevSmResourceSplit.

  • result: Output array of DevResource resources. Can be NULL, alongside an smCount of 0, for discovery purpose
  • nbGroups: Specifies the number of groups in result and groupParams
  • input: Input SM resource to be split. Must be a valid DevResourceTypeSm resource
  • remainder: If splitting the input resource leaves any SMs, the remainder is placed in here
  • flags: Flags specifying how the API should behave. The value should be 0 for now
  • groupParams: Description of how the SMs should be split and assigned to the corresponding result entry

Errors:

Wraps cuDevSmResourceSplit.

func DevSmResourceSplitByCount

func DevSmResourceSplitByCount(result *DevResource, nbGroups *uint32, input *DevResource, remainder *DevResource, flags DevsmresourcesplitbycountFlags, minCount uint32) error

DevSmResourceSplitByCount splits DevResourceTypeSm resources.

Splits DevResourceTypeSm resources into nbGroups, adhering to the minimum SM count specified in minCount and the usage flags in flags. If result is NULL, the API simulates a split and provides the amount of groups that would be created in nbGroups. Otherwise, nbGroups must point to the amount of elements in result and on return, the API will overwrite nbGroups with the amount actually created. The groups are written to the array in result. nbGroups can be less than the total amount if a smaller number of groups is needed. This API is used to spatially partition the input resource. The input resource needs to come from one of Device.DevResource, Context.DevResource, or GreenCtx.DevResource. A limitation of the API is that the output results cannot be split again without first creating a descriptor and a green context with that descriptor. When creating the groups, the API will take into account the performance and functional characteristics of the input resource, and guarantee a split that will create a disjoint set of symmetrical partitions. This may lead to fewer groups created than purely dividing the total SM count by the minCount due to cluster requirements or alignment and granularity requirements for the minCount. These requirements can be queried with Device.DevResource, Context.DevResource, and GreenCtx.DevResource for DevResourceTypeSm, using the minSmPartitionSize and smCoscheduledAlignment fields to determine minimum partition size and alignment granularity, respectively. The remainder set does not have the same functional or performance guarantees as the groups in result. Its use should be carefully planned and future partitions of the remainder set are discouraged. The following flags are supported:

A successful API call must either have:

  • A valid array of result pointers of size passed in nbGroups, with input of type DevResourceTypeSm. Value of minCount must be between 0 and the SM count specified in input. remainder may be NULL.
  • NULL passed in for result, with a valid integer pointer in nbGroups and input of type DevResourceTypeSm. Value of minCount must be between 0 and the SM count specified in input. remainder may be NULL. This queries the number of groups that would be created by the API.

Note: The API is not supported on 32-bit platforms.

See also: GreenCtx.DevResource, Context.DevResource, Device.DevResource

Requires CUDA 12.4 (driver r550) or later; see HasDevSmResourceSplitByCount.

  • result: Output array of DevResource resources. Can be NULL to query the number of groups
  • nbGroups: This is a pointer, specifying the number of groups that would be or should be created as described below
  • input: Input SM resource to be split. Must be a valid DevResourceTypeSm resource
  • remainder: If the input resource cannot be cleanly split among nbGroups, the remainder is placed in here. Can be ommitted (NULL) if the user does not need the remaining set
  • flags: Flags specifying how these partitions are used or which constraints to abide by when splitting the input. Zero is valid for default behavior
  • minCount: Minimum number of SMs required

Errors:

Wraps cuDevSmResourceSplitByCount.

func DeviceGetCount

func DeviceGetCount() (int, error)

DeviceGetCount returns the number of compute-capable devices.

Returns the number of devices with compute capability greater than or equal to 2.0 that are available for execution. If there is no such device, DeviceGetCount returns 0.

See also: Device.Attribute, Device.Name, Device.Uuid, Device.Luid, DeviceGet, Device.TotalMem, Device.ExecAffinitySupport, cudaGetDeviceCount

Errors:

Wraps cuDeviceGetCount.

Example

ExampleDeviceGetCount prints the driver version and the name and compute capability of each device. It returns early when no CUDA driver is available. It has no Output comment, so it is compiled but not run: what it prints depends on the host's driver and devices.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	if err := driver.Init(0); err != nil {
		fmt.Println("CUDA driver unavailable:", err)
		return
	}
	version, err := driver.DriverGetVersion()
	if err != nil {
		fmt.Println("version:", err)
		return
	}
	count, err := driver.DeviceGetCount()
	if err != nil {
		fmt.Println("device count:", err)
		return
	}
	for i := range count {
		dev, err := driver.DeviceGet(i)
		if err != nil {
			fmt.Println("device:", err)
			return
		}
		name, err := dev.Name()
		if err != nil {
			fmt.Println("name:", err)
			return
		}
		major, err := dev.Attribute(driver.DevAttrComputeCapabilityMajor)
		if err != nil {
			fmt.Println("attribute:", err)
			return
		}
		minor, err := dev.Attribute(driver.DevAttrComputeCapabilityMinor)
		if err != nil {
			fmt.Println("attribute:", err)
			return
		}
		fmt.Printf("CUDA %d: device %d: %s (sm_%d%d)\n", version, i, name, major, minor)
	}
}

func DriverGetVersion

func DriverGetVersion() (int, error)

DriverGetVersion returns the latest CUDA version supported by driver.

Returns the version of CUDA supported by the driver. The version is returned as (1000 * major + 10 * minor). For example, CUDA 9.2 would be represented by 9020. This function automatically returns ErrInvalidValue if driverVersion is NULL.

See also: cudaDriverGetVersion, cudaRuntimeGetVersion

Errors:

Wraps cuDriverGetVersion.

func FlushGPUDirectRDMAWrites

func FlushGPUDirectRDMAWrites(target FlushGPUDirectRDMAWritesTarget, scope FlushGPUDirectRDMAWritesScope) error

FlushGPUDirectRDMAWrites blocks until remote writes are visible to the specified scope.

Blocks until GPUDirect RDMA writes to the target context via mappings created through 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 DevAttrGpuDirectRdmaWritesOrdering, 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. On platforms that support GPUDirect RDMA writes via more than one path in hardware (see MemRangeFlagDmaBufMappingTypePcie), the user should consider those paths as belonging to separate ordering domains. Note that in such cases CUDA driver will report both RDMA writes ordering and RDMA write scope as ALL_DEVICES and a call to cuFlushGPUDirectRDMA will be a no-op, but when these multiple paths are used simultaneously, it is the user’s responsibility to ensure ordering by using mechanisms outside the scope of CUDA. Users may query support for this API via CU_DEVICE_ATTRIBUTE_FLUSH_FLUSH_GPU_DIRECT_RDMA_OPTIONS.

Errors:

Wraps cuFlushGPUDirectRDMAWrites.

func GetExportTable

func GetExportTable(ppExportTable *uintptr, pExportTableId *Uuid) error

GetExportTable wraps cuGetExportTable.

func Has

func Has(symbol string) bool

Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.

func HasArray3DCreate

func HasArray3DCreate() bool

HasArray3DCreate reports whether cuArray3DCreate_v2 resolved in the loaded library.

func HasArray3DGetDescriptor

func HasArray3DGetDescriptor() bool

HasArray3DGetDescriptor reports whether cuArray3DGetDescriptor_v2 resolved in the loaded library.

func HasArrayCreate

func HasArrayCreate() bool

HasArrayCreate reports whether cuArrayCreate_v2 resolved in the loaded library.

func HasArrayDestroy

func HasArrayDestroy() bool

HasArrayDestroy reports whether cuArrayDestroy resolved in the loaded library.

func HasArrayGetDescriptor

func HasArrayGetDescriptor() bool

HasArrayGetDescriptor reports whether cuArrayGetDescriptor_v2 resolved in the loaded library.

func HasArrayGetMemoryRequirements

func HasArrayGetMemoryRequirements() bool

HasArrayGetMemoryRequirements reports whether cuArrayGetMemoryRequirements resolved in the loaded library.

func HasArrayGetPlane

func HasArrayGetPlane() bool

HasArrayGetPlane reports whether cuArrayGetPlane resolved in the loaded library.

func HasArrayGetSparseProperties

func HasArrayGetSparseProperties() bool

HasArrayGetSparseProperties reports whether cuArrayGetSparseProperties resolved in the loaded library.

func HasCheckpointOperationComplete

func HasCheckpointOperationComplete() bool

HasCheckpointOperationComplete reports whether cuCheckpointOperationComplete resolved in the loaded library.

func HasCheckpointProcessCheckpoint

func HasCheckpointProcessCheckpoint() bool

HasCheckpointProcessCheckpoint reports whether cuCheckpointProcessCheckpoint resolved in the loaded library.

func HasCheckpointProcessGetRestoreThreadId

func HasCheckpointProcessGetRestoreThreadId() bool

HasCheckpointProcessGetRestoreThreadId reports whether cuCheckpointProcessGetRestoreThreadId resolved in the loaded library.

func HasCheckpointProcessGetState

func HasCheckpointProcessGetState() bool

HasCheckpointProcessGetState reports whether cuCheckpointProcessGetState resolved in the loaded library.

func HasCheckpointProcessLock

func HasCheckpointProcessLock() bool

HasCheckpointProcessLock reports whether cuCheckpointProcessLock resolved in the loaded library.

func HasCheckpointProcessRestore

func HasCheckpointProcessRestore() bool

HasCheckpointProcessRestore reports whether cuCheckpointProcessRestore resolved in the loaded library.

func HasCheckpointProcessUnlock

func HasCheckpointProcessUnlock() bool

HasCheckpointProcessUnlock reports whether cuCheckpointProcessUnlock resolved in the loaded library.

func HasCoredumpDeregisterCompleteCallback

func HasCoredumpDeregisterCompleteCallback() bool

HasCoredumpDeregisterCompleteCallback reports whether cuCoredumpDeregisterCompleteCallback resolved in the loaded library.

func HasCoredumpDeregisterStartCallback

func HasCoredumpDeregisterStartCallback() bool

HasCoredumpDeregisterStartCallback reports whether cuCoredumpDeregisterStartCallback resolved in the loaded library.

func HasCoredumpGetAttribute

func HasCoredumpGetAttribute() bool

HasCoredumpGetAttribute reports whether cuCoredumpGetAttribute resolved in the loaded library.

func HasCoredumpGetAttributeGlobal

func HasCoredumpGetAttributeGlobal() bool

HasCoredumpGetAttributeGlobal reports whether cuCoredumpGetAttributeGlobal resolved in the loaded library.

func HasCoredumpRegisterCompleteCallback

func HasCoredumpRegisterCompleteCallback() bool

HasCoredumpRegisterCompleteCallback reports whether cuCoredumpRegisterCompleteCallback resolved in the loaded library.

func HasCoredumpRegisterStartCallback

func HasCoredumpRegisterStartCallback() bool

HasCoredumpRegisterStartCallback reports whether cuCoredumpRegisterStartCallback resolved in the loaded library.

func HasCoredumpSetAttribute

func HasCoredumpSetAttribute() bool

HasCoredumpSetAttribute reports whether cuCoredumpSetAttribute resolved in the loaded library.

func HasCoredumpSetAttributeGlobal

func HasCoredumpSetAttributeGlobal() bool

HasCoredumpSetAttributeGlobal reports whether cuCoredumpSetAttributeGlobal resolved in the loaded library.

func HasCtxAttach

func HasCtxAttach() bool

HasCtxAttach reports whether cuCtxAttach resolved in the loaded library.

func HasCtxCreate

func HasCtxCreate() bool

HasCtxCreate reports whether cuCtxCreate resolved in the loaded library.

It resolves as the first of cuCtxCreate_v4, cuCtxCreate_v2 that the library exports. BoundSymbol reports which.

func HasCtxCreateV2

func HasCtxCreateV2() bool

HasCtxCreateV2 reports whether cuCtxCreate_v2 resolved in the loaded library.

func HasCtxCreateV3

func HasCtxCreateV3() bool

HasCtxCreateV3 reports whether cuCtxCreate_v3 resolved in the loaded library.

func HasCtxCreateV4

func HasCtxCreateV4() bool

HasCtxCreateV4 reports whether cuCtxCreate_v4 resolved in the loaded library.

func HasCtxDestroy

func HasCtxDestroy() bool

HasCtxDestroy reports whether cuCtxDestroy_v2 resolved in the loaded library.

func HasCtxDetach

func HasCtxDetach() bool

HasCtxDetach reports whether cuCtxDetach resolved in the loaded library.

func HasCtxDisablePeerAccess

func HasCtxDisablePeerAccess() bool

HasCtxDisablePeerAccess reports whether cuCtxDisablePeerAccess resolved in the loaded library.

func HasCtxEnablePeerAccess

func HasCtxEnablePeerAccess() bool

HasCtxEnablePeerAccess reports whether cuCtxEnablePeerAccess resolved in the loaded library.

func HasCtxFromGreenCtx

func HasCtxFromGreenCtx() bool

HasCtxFromGreenCtx reports whether cuCtxFromGreenCtx resolved in the loaded library.

func HasCtxGetApiVersion

func HasCtxGetApiVersion() bool

HasCtxGetApiVersion reports whether cuCtxGetApiVersion resolved in the loaded library.

func HasCtxGetCacheConfig

func HasCtxGetCacheConfig() bool

HasCtxGetCacheConfig reports whether cuCtxGetCacheConfig resolved in the loaded library.

func HasCtxGetCurrent

func HasCtxGetCurrent() bool

HasCtxGetCurrent reports whether cuCtxGetCurrent resolved in the loaded library.

func HasCtxGetDevResource

func HasCtxGetDevResource() bool

HasCtxGetDevResource reports whether cuCtxGetDevResource resolved in the loaded library.

func HasCtxGetDevice

func HasCtxGetDevice() bool

HasCtxGetDevice reports whether cuCtxGetDevice resolved in the loaded library.

func HasCtxGetDeviceV1

func HasCtxGetDeviceV1() bool

HasCtxGetDeviceV1 reports whether cuCtxGetDevice resolved in the loaded library.

func HasCtxGetDeviceV2

func HasCtxGetDeviceV2() bool

HasCtxGetDeviceV2 reports whether cuCtxGetDevice_v2 resolved in the loaded library.

func HasCtxGetExecAffinity

func HasCtxGetExecAffinity() bool

HasCtxGetExecAffinity reports whether cuCtxGetExecAffinity resolved in the loaded library.

func HasCtxGetFlags

func HasCtxGetFlags() bool

HasCtxGetFlags reports whether cuCtxGetFlags resolved in the loaded library.

func HasCtxGetId

func HasCtxGetId() bool

HasCtxGetId reports whether cuCtxGetId resolved in the loaded library.

func HasCtxGetLimit

func HasCtxGetLimit() bool

HasCtxGetLimit reports whether cuCtxGetLimit resolved in the loaded library.

func HasCtxGetSharedMemConfig

func HasCtxGetSharedMemConfig() bool

HasCtxGetSharedMemConfig reports whether cuCtxGetSharedMemConfig resolved in the loaded library.

func HasCtxGetStreamPriorityRange

func HasCtxGetStreamPriorityRange() bool

HasCtxGetStreamPriorityRange reports whether cuCtxGetStreamPriorityRange resolved in the loaded library.

func HasCtxPopCurrent

func HasCtxPopCurrent() bool

HasCtxPopCurrent reports whether cuCtxPopCurrent_v2 resolved in the loaded library.

func HasCtxPushCurrent

func HasCtxPushCurrent() bool

HasCtxPushCurrent reports whether cuCtxPushCurrent_v2 resolved in the loaded library.

func HasCtxRecordEvent

func HasCtxRecordEvent() bool

HasCtxRecordEvent reports whether cuCtxRecordEvent resolved in the loaded library.

func HasCtxResetPersistingL2Cache

func HasCtxResetPersistingL2Cache() bool

HasCtxResetPersistingL2Cache reports whether cuCtxResetPersistingL2Cache resolved in the loaded library.

func HasCtxSetCacheConfig

func HasCtxSetCacheConfig() bool

HasCtxSetCacheConfig reports whether cuCtxSetCacheConfig resolved in the loaded library.

func HasCtxSetCurrent

func HasCtxSetCurrent() bool

HasCtxSetCurrent reports whether cuCtxSetCurrent resolved in the loaded library.

func HasCtxSetFlags

func HasCtxSetFlags() bool

HasCtxSetFlags reports whether cuCtxSetFlags resolved in the loaded library.

func HasCtxSetLimit

func HasCtxSetLimit() bool

HasCtxSetLimit reports whether cuCtxSetLimit resolved in the loaded library.

func HasCtxSetSharedMemConfig

func HasCtxSetSharedMemConfig() bool

HasCtxSetSharedMemConfig reports whether cuCtxSetSharedMemConfig resolved in the loaded library.

func HasCtxSynchronize

func HasCtxSynchronize() bool

HasCtxSynchronize reports whether cuCtxSynchronize resolved in the loaded library.

func HasCtxSynchronizeV1

func HasCtxSynchronizeV1() bool

HasCtxSynchronizeV1 reports whether cuCtxSynchronize resolved in the loaded library.

func HasCtxSynchronizeV2

func HasCtxSynchronizeV2() bool

HasCtxSynchronizeV2 reports whether cuCtxSynchronize_v2 resolved in the loaded library.

func HasCtxWaitEvent

func HasCtxWaitEvent() bool

HasCtxWaitEvent reports whether cuCtxWaitEvent resolved in the loaded library.

func HasDestroyExternalMemory

func HasDestroyExternalMemory() bool

HasDestroyExternalMemory reports whether cuDestroyExternalMemory resolved in the loaded library.

func HasDestroyExternalSemaphore

func HasDestroyExternalSemaphore() bool

HasDestroyExternalSemaphore reports whether cuDestroyExternalSemaphore resolved in the loaded library.

func HasDevResourceGenerateDesc

func HasDevResourceGenerateDesc() bool

HasDevResourceGenerateDesc reports whether cuDevResourceGenerateDesc resolved in the loaded library.

func HasDevSmResourceSplit

func HasDevSmResourceSplit() bool

HasDevSmResourceSplit reports whether cuDevSmResourceSplit resolved in the loaded library.

func HasDevSmResourceSplitByCount

func HasDevSmResourceSplitByCount() bool

HasDevSmResourceSplitByCount reports whether cuDevSmResourceSplitByCount resolved in the loaded library.

func HasDeviceCanAccessPeer

func HasDeviceCanAccessPeer() bool

HasDeviceCanAccessPeer reports whether cuDeviceCanAccessPeer resolved in the loaded library.

func HasDeviceComputeCapability

func HasDeviceComputeCapability() bool

HasDeviceComputeCapability reports whether cuDeviceComputeCapability resolved in the loaded library.

func HasDeviceGet

func HasDeviceGet() bool

HasDeviceGet reports whether cuDeviceGet resolved in the loaded library.

func HasDeviceGetAttribute

func HasDeviceGetAttribute() bool

HasDeviceGetAttribute reports whether cuDeviceGetAttribute resolved in the loaded library.

func HasDeviceGetByPCIBusId

func HasDeviceGetByPCIBusId() bool

HasDeviceGetByPCIBusId reports whether cuDeviceGetByPCIBusId resolved in the loaded library.

func HasDeviceGetCliqueCount

func HasDeviceGetCliqueCount() bool

HasDeviceGetCliqueCount reports whether cuDeviceGetCliqueCount resolved in the loaded library.

func HasDeviceGetCliqueInfo

func HasDeviceGetCliqueInfo() bool

HasDeviceGetCliqueInfo reports whether cuDeviceGetCliqueInfo resolved in the loaded library.

func HasDeviceGetCount

func HasDeviceGetCount() bool

HasDeviceGetCount reports whether cuDeviceGetCount resolved in the loaded library.

func HasDeviceGetDefaultMemPool

func HasDeviceGetDefaultMemPool() bool

HasDeviceGetDefaultMemPool reports whether cuDeviceGetDefaultMemPool resolved in the loaded library.

func HasDeviceGetDevResource

func HasDeviceGetDevResource() bool

HasDeviceGetDevResource reports whether cuDeviceGetDevResource resolved in the loaded library.

func HasDeviceGetExecAffinitySupport

func HasDeviceGetExecAffinitySupport() bool

HasDeviceGetExecAffinitySupport reports whether cuDeviceGetExecAffinitySupport resolved in the loaded library.

func HasDeviceGetFabricClusterUuid

func HasDeviceGetFabricClusterUuid() bool

HasDeviceGetFabricClusterUuid reports whether cuDeviceGetFabricClusterUuid resolved in the loaded library.

func HasDeviceGetGraphMemAttribute

func HasDeviceGetGraphMemAttribute() bool

HasDeviceGetGraphMemAttribute reports whether cuDeviceGetGraphMemAttribute resolved in the loaded library.

func HasDeviceGetHostAtomicCapabilities

func HasDeviceGetHostAtomicCapabilities() bool

HasDeviceGetHostAtomicCapabilities reports whether cuDeviceGetHostAtomicCapabilities resolved in the loaded library.

func HasDeviceGetLuid

func HasDeviceGetLuid() bool

HasDeviceGetLuid reports whether cuDeviceGetLuid resolved in the loaded library.

func HasDeviceGetMemPool

func HasDeviceGetMemPool() bool

HasDeviceGetMemPool reports whether cuDeviceGetMemPool resolved in the loaded library.

func HasDeviceGetName

func HasDeviceGetName() bool

HasDeviceGetName reports whether cuDeviceGetName resolved in the loaded library.

func HasDeviceGetNvSciSyncAttributes

func HasDeviceGetNvSciSyncAttributes() bool

HasDeviceGetNvSciSyncAttributes reports whether cuDeviceGetNvSciSyncAttributes resolved in the loaded library.

func HasDeviceGetP2PAtomicCapabilities

func HasDeviceGetP2PAtomicCapabilities() bool

HasDeviceGetP2PAtomicCapabilities reports whether cuDeviceGetP2PAtomicCapabilities resolved in the loaded library.

func HasDeviceGetP2PAttribute

func HasDeviceGetP2PAttribute() bool

HasDeviceGetP2PAttribute reports whether cuDeviceGetP2PAttribute resolved in the loaded library.

func HasDeviceGetPCIBusId

func HasDeviceGetPCIBusId() bool

HasDeviceGetPCIBusId reports whether cuDeviceGetPCIBusId resolved in the loaded library.

func HasDeviceGetProperties

func HasDeviceGetProperties() bool

HasDeviceGetProperties reports whether cuDeviceGetProperties resolved in the loaded library.

func HasDeviceGetTexture1DLinearMaxWidth

func HasDeviceGetTexture1DLinearMaxWidth() bool

HasDeviceGetTexture1DLinearMaxWidth reports whether cuDeviceGetTexture1DLinearMaxWidth resolved in the loaded library.

func HasDeviceGetUuid

func HasDeviceGetUuid() bool

HasDeviceGetUuid reports whether cuDeviceGetUuid resolved in the loaded library.

It resolves as the first of cuDeviceGetUuid_v2, cuDeviceGetUuid that the library exports. BoundSymbol reports which.

func HasDeviceGetUuidV1

func HasDeviceGetUuidV1() bool

HasDeviceGetUuidV1 reports whether cuDeviceGetUuid resolved in the loaded library.

func HasDeviceGetUuidV2

func HasDeviceGetUuidV2() bool

HasDeviceGetUuidV2 reports whether cuDeviceGetUuid_v2 resolved in the loaded library.

func HasDeviceGraphMemTrim

func HasDeviceGraphMemTrim() bool

HasDeviceGraphMemTrim reports whether cuDeviceGraphMemTrim resolved in the loaded library.

func HasDevicePrimaryCtxGetState

func HasDevicePrimaryCtxGetState() bool

HasDevicePrimaryCtxGetState reports whether cuDevicePrimaryCtxGetState resolved in the loaded library.

func HasDevicePrimaryCtxRelease

func HasDevicePrimaryCtxRelease() bool

HasDevicePrimaryCtxRelease reports whether cuDevicePrimaryCtxRelease_v2 resolved in the loaded library.

func HasDevicePrimaryCtxReset

func HasDevicePrimaryCtxReset() bool

HasDevicePrimaryCtxReset reports whether cuDevicePrimaryCtxReset_v2 resolved in the loaded library.

func HasDevicePrimaryCtxRetain

func HasDevicePrimaryCtxRetain() bool

HasDevicePrimaryCtxRetain reports whether cuDevicePrimaryCtxRetain resolved in the loaded library.

func HasDevicePrimaryCtxSetFlags

func HasDevicePrimaryCtxSetFlags() bool

HasDevicePrimaryCtxSetFlags reports whether cuDevicePrimaryCtxSetFlags_v2 resolved in the loaded library.

func HasDeviceRegisterAsyncNotification

func HasDeviceRegisterAsyncNotification() bool

HasDeviceRegisterAsyncNotification reports whether cuDeviceRegisterAsyncNotification resolved in the loaded library.

func HasDeviceSetGraphMemAttribute

func HasDeviceSetGraphMemAttribute() bool

HasDeviceSetGraphMemAttribute reports whether cuDeviceSetGraphMemAttribute resolved in the loaded library.

func HasDeviceSetMemPool

func HasDeviceSetMemPool() bool

HasDeviceSetMemPool reports whether cuDeviceSetMemPool resolved in the loaded library.

func HasDeviceTotalMem

func HasDeviceTotalMem() bool

HasDeviceTotalMem reports whether cuDeviceTotalMem_v2 resolved in the loaded library.

func HasDeviceUnregisterAsyncNotification

func HasDeviceUnregisterAsyncNotification() bool

HasDeviceUnregisterAsyncNotification reports whether cuDeviceUnregisterAsyncNotification resolved in the loaded library.

func HasDriverGetVersion

func HasDriverGetVersion() bool

HasDriverGetVersion reports whether cuDriverGetVersion resolved in the loaded library.

func HasEventCreate

func HasEventCreate() bool

HasEventCreate reports whether cuEventCreate resolved in the loaded library.

func HasEventDestroy

func HasEventDestroy() bool

HasEventDestroy reports whether cuEventDestroy_v2 resolved in the loaded library.

func HasEventElapsedTime

func HasEventElapsedTime() bool

HasEventElapsedTime reports whether cuEventElapsedTime resolved in the loaded library.

It resolves as the first of cuEventElapsedTime_v2, cuEventElapsedTime that the library exports. BoundSymbol reports which.

func HasEventElapsedTimeV1

func HasEventElapsedTimeV1() bool

HasEventElapsedTimeV1 reports whether cuEventElapsedTime resolved in the loaded library.

func HasEventElapsedTimeV2

func HasEventElapsedTimeV2() bool

HasEventElapsedTimeV2 reports whether cuEventElapsedTime_v2 resolved in the loaded library.

func HasEventQuery

func HasEventQuery() bool

HasEventQuery reports whether cuEventQuery resolved in the loaded library.

func HasEventRecord

func HasEventRecord() bool

HasEventRecord reports whether cuEventRecord resolved in the loaded library.

func HasEventRecordWithFlags

func HasEventRecordWithFlags() bool

HasEventRecordWithFlags reports whether cuEventRecordWithFlags resolved in the loaded library.

func HasEventSynchronize

func HasEventSynchronize() bool

HasEventSynchronize reports whether cuEventSynchronize resolved in the loaded library.

func HasExternalMemoryGetMappedBuffer

func HasExternalMemoryGetMappedBuffer() bool

HasExternalMemoryGetMappedBuffer reports whether cuExternalMemoryGetMappedBuffer resolved in the loaded library.

func HasExternalMemoryGetMappedMipmappedArray

func HasExternalMemoryGetMappedMipmappedArray() bool

HasExternalMemoryGetMappedMipmappedArray reports whether cuExternalMemoryGetMappedMipmappedArray resolved in the loaded library.

func HasFabricCpyBatchAsync

func HasFabricCpyBatchAsync() bool

HasFabricCpyBatchAsync reports whether cuFabricCpyBatchAsync resolved in the loaded library.

func HasFlushGPUDirectRDMAWrites

func HasFlushGPUDirectRDMAWrites() bool

HasFlushGPUDirectRDMAWrites reports whether cuFlushGPUDirectRDMAWrites resolved in the loaded library.

func HasFuncGetAttribute

func HasFuncGetAttribute() bool

HasFuncGetAttribute reports whether cuFuncGetAttribute resolved in the loaded library.

func HasFuncGetModule

func HasFuncGetModule() bool

HasFuncGetModule reports whether cuFuncGetModule resolved in the loaded library.

func HasFuncGetName

func HasFuncGetName() bool

HasFuncGetName reports whether cuFuncGetName resolved in the loaded library.

func HasFuncGetParamCount

func HasFuncGetParamCount() bool

HasFuncGetParamCount reports whether cuFuncGetParamCount resolved in the loaded library.

func HasFuncGetParamInfo

func HasFuncGetParamInfo() bool

HasFuncGetParamInfo reports whether cuFuncGetParamInfo resolved in the loaded library.

func HasFuncIsLoaded

func HasFuncIsLoaded() bool

HasFuncIsLoaded reports whether cuFuncIsLoaded resolved in the loaded library.

func HasFuncLoad

func HasFuncLoad() bool

HasFuncLoad reports whether cuFuncLoad resolved in the loaded library.

func HasFuncSetAttribute

func HasFuncSetAttribute() bool

HasFuncSetAttribute reports whether cuFuncSetAttribute resolved in the loaded library.

func HasFuncSetBlockShape

func HasFuncSetBlockShape() bool

HasFuncSetBlockShape reports whether cuFuncSetBlockShape resolved in the loaded library.

func HasFuncSetCacheConfig

func HasFuncSetCacheConfig() bool

HasFuncSetCacheConfig reports whether cuFuncSetCacheConfig resolved in the loaded library.

func HasFuncSetSharedMemConfig

func HasFuncSetSharedMemConfig() bool

HasFuncSetSharedMemConfig reports whether cuFuncSetSharedMemConfig resolved in the loaded library.

func HasFuncSetSharedSize

func HasFuncSetSharedSize() bool

HasFuncSetSharedSize reports whether cuFuncSetSharedSize resolved in the loaded library.

func HasGetErrorName

func HasGetErrorName() bool

HasGetErrorName reports whether cuGetErrorName resolved in the loaded library.

func HasGetErrorString

func HasGetErrorString() bool

HasGetErrorString reports whether cuGetErrorString resolved in the loaded library.

func HasGetExportTable

func HasGetExportTable() bool

HasGetExportTable reports whether cuGetExportTable resolved in the loaded library.

func HasGetProcAddress

func HasGetProcAddress() bool

HasGetProcAddress reports whether cuGetProcAddress_v2 resolved in the loaded library.

func HasGraphAddBatchMemOpNode

func HasGraphAddBatchMemOpNode() bool

HasGraphAddBatchMemOpNode reports whether cuGraphAddBatchMemOpNode resolved in the loaded library.

func HasGraphAddChildGraphNode

func HasGraphAddChildGraphNode() bool

HasGraphAddChildGraphNode reports whether cuGraphAddChildGraphNode resolved in the loaded library.

func HasGraphAddDependencies

func HasGraphAddDependencies() bool

HasGraphAddDependencies reports whether cuGraphAddDependencies resolved in the loaded library.

It resolves as the first of cuGraphAddDependencies_v2, cuGraphAddDependencies that the library exports. BoundSymbol reports which.

func HasGraphAddDependenciesV1

func HasGraphAddDependenciesV1() bool

HasGraphAddDependenciesV1 reports whether cuGraphAddDependencies resolved in the loaded library.

func HasGraphAddDependenciesV2

func HasGraphAddDependenciesV2() bool

HasGraphAddDependenciesV2 reports whether cuGraphAddDependencies_v2 resolved in the loaded library.

func HasGraphAddEmptyNode

func HasGraphAddEmptyNode() bool

HasGraphAddEmptyNode reports whether cuGraphAddEmptyNode resolved in the loaded library.

func HasGraphAddEventRecordNode

func HasGraphAddEventRecordNode() bool

HasGraphAddEventRecordNode reports whether cuGraphAddEventRecordNode resolved in the loaded library.

func HasGraphAddEventWaitNode

func HasGraphAddEventWaitNode() bool

HasGraphAddEventWaitNode reports whether cuGraphAddEventWaitNode resolved in the loaded library.

func HasGraphAddExternalSemaphoresSignalNode

func HasGraphAddExternalSemaphoresSignalNode() bool

HasGraphAddExternalSemaphoresSignalNode reports whether cuGraphAddExternalSemaphoresSignalNode resolved in the loaded library.

func HasGraphAddExternalSemaphoresWaitNode

func HasGraphAddExternalSemaphoresWaitNode() bool

HasGraphAddExternalSemaphoresWaitNode reports whether cuGraphAddExternalSemaphoresWaitNode resolved in the loaded library.

func HasGraphAddHostNode

func HasGraphAddHostNode() bool

HasGraphAddHostNode reports whether cuGraphAddHostNode resolved in the loaded library.

func HasGraphAddKernelNode

func HasGraphAddKernelNode() bool

HasGraphAddKernelNode reports whether cuGraphAddKernelNode_v2 resolved in the loaded library.

func HasGraphAddMemAllocNode

func HasGraphAddMemAllocNode() bool

HasGraphAddMemAllocNode reports whether cuGraphAddMemAllocNode resolved in the loaded library.

func HasGraphAddMemFreeNode

func HasGraphAddMemFreeNode() bool

HasGraphAddMemFreeNode reports whether cuGraphAddMemFreeNode resolved in the loaded library.

func HasGraphAddMemcpyNode

func HasGraphAddMemcpyNode() bool

HasGraphAddMemcpyNode reports whether cuGraphAddMemcpyNode resolved in the loaded library.

func HasGraphAddMemsetNode

func HasGraphAddMemsetNode() bool

HasGraphAddMemsetNode reports whether cuGraphAddMemsetNode resolved in the loaded library.

func HasGraphAddNode

func HasGraphAddNode() bool

HasGraphAddNode reports whether cuGraphAddNode resolved in the loaded library.

It resolves as the first of cuGraphAddNode_v2, cuGraphAddNode that the library exports. BoundSymbol reports which.

func HasGraphAddNodeV1

func HasGraphAddNodeV1() bool

HasGraphAddNodeV1 reports whether cuGraphAddNode resolved in the loaded library.

func HasGraphAddNodeV2

func HasGraphAddNodeV2() bool

HasGraphAddNodeV2 reports whether cuGraphAddNode_v2 resolved in the loaded library.

func HasGraphAddNodeV3

func HasGraphAddNodeV3() bool

HasGraphAddNodeV3 reports whether cuGraphAddNode_v3 resolved in the loaded library.

func HasGraphBatchMemOpNodeGetParams

func HasGraphBatchMemOpNodeGetParams() bool

HasGraphBatchMemOpNodeGetParams reports whether cuGraphBatchMemOpNodeGetParams resolved in the loaded library.

func HasGraphBatchMemOpNodeSetParams

func HasGraphBatchMemOpNodeSetParams() bool

HasGraphBatchMemOpNodeSetParams reports whether cuGraphBatchMemOpNodeSetParams resolved in the loaded library.

func HasGraphChildGraphNodeGetGraph

func HasGraphChildGraphNodeGetGraph() bool

HasGraphChildGraphNodeGetGraph reports whether cuGraphChildGraphNodeGetGraph resolved in the loaded library.

func HasGraphClone

func HasGraphClone() bool

HasGraphClone reports whether cuGraphClone resolved in the loaded library.

func HasGraphConditionalHandleCreate

func HasGraphConditionalHandleCreate() bool

HasGraphConditionalHandleCreate reports whether cuGraphConditionalHandleCreate resolved in the loaded library.

func HasGraphCreate

func HasGraphCreate() bool

HasGraphCreate reports whether cuGraphCreate resolved in the loaded library.

func HasGraphDebugDotPrint

func HasGraphDebugDotPrint() bool

HasGraphDebugDotPrint reports whether cuGraphDebugDotPrint resolved in the loaded library.

func HasGraphDestroy

func HasGraphDestroy() bool

HasGraphDestroy reports whether cuGraphDestroy resolved in the loaded library.

func HasGraphDestroyNode

func HasGraphDestroyNode() bool

HasGraphDestroyNode reports whether cuGraphDestroyNode resolved in the loaded library.

func HasGraphEventRecordNodeGetEvent

func HasGraphEventRecordNodeGetEvent() bool

HasGraphEventRecordNodeGetEvent reports whether cuGraphEventRecordNodeGetEvent resolved in the loaded library.

func HasGraphEventRecordNodeSetEvent

func HasGraphEventRecordNodeSetEvent() bool

HasGraphEventRecordNodeSetEvent reports whether cuGraphEventRecordNodeSetEvent resolved in the loaded library.

func HasGraphEventWaitNodeGetEvent

func HasGraphEventWaitNodeGetEvent() bool

HasGraphEventWaitNodeGetEvent reports whether cuGraphEventWaitNodeGetEvent resolved in the loaded library.

func HasGraphEventWaitNodeSetEvent

func HasGraphEventWaitNodeSetEvent() bool

HasGraphEventWaitNodeSetEvent reports whether cuGraphEventWaitNodeSetEvent resolved in the loaded library.

func HasGraphExecBatchMemOpNodeSetParams

func HasGraphExecBatchMemOpNodeSetParams() bool

HasGraphExecBatchMemOpNodeSetParams reports whether cuGraphExecBatchMemOpNodeSetParams resolved in the loaded library.

func HasGraphExecChildGraphNodeSetParams

func HasGraphExecChildGraphNodeSetParams() bool

HasGraphExecChildGraphNodeSetParams reports whether cuGraphExecChildGraphNodeSetParams resolved in the loaded library.

func HasGraphExecDestroy

func HasGraphExecDestroy() bool

HasGraphExecDestroy reports whether cuGraphExecDestroy resolved in the loaded library.

func HasGraphExecEventRecordNodeSetEvent

func HasGraphExecEventRecordNodeSetEvent() bool

HasGraphExecEventRecordNodeSetEvent reports whether cuGraphExecEventRecordNodeSetEvent resolved in the loaded library.

func HasGraphExecEventWaitNodeSetEvent

func HasGraphExecEventWaitNodeSetEvent() bool

HasGraphExecEventWaitNodeSetEvent reports whether cuGraphExecEventWaitNodeSetEvent resolved in the loaded library.

func HasGraphExecExternalSemaphoresSignalNodeSetParams

func HasGraphExecExternalSemaphoresSignalNodeSetParams() bool

HasGraphExecExternalSemaphoresSignalNodeSetParams reports whether cuGraphExecExternalSemaphoresSignalNodeSetParams resolved in the loaded library.

func HasGraphExecExternalSemaphoresWaitNodeSetParams

func HasGraphExecExternalSemaphoresWaitNodeSetParams() bool

HasGraphExecExternalSemaphoresWaitNodeSetParams reports whether cuGraphExecExternalSemaphoresWaitNodeSetParams resolved in the loaded library.

func HasGraphExecGetFlags

func HasGraphExecGetFlags() bool

HasGraphExecGetFlags reports whether cuGraphExecGetFlags resolved in the loaded library.

func HasGraphExecGetId

func HasGraphExecGetId() bool

HasGraphExecGetId reports whether cuGraphExecGetId resolved in the loaded library.

func HasGraphExecHostNodeSetParams

func HasGraphExecHostNodeSetParams() bool

HasGraphExecHostNodeSetParams reports whether cuGraphExecHostNodeSetParams resolved in the loaded library.

func HasGraphExecKernelNodeSetParams

func HasGraphExecKernelNodeSetParams() bool

HasGraphExecKernelNodeSetParams reports whether cuGraphExecKernelNodeSetParams_v2 resolved in the loaded library.

func HasGraphExecMemcpyNodeSetParams

func HasGraphExecMemcpyNodeSetParams() bool

HasGraphExecMemcpyNodeSetParams reports whether cuGraphExecMemcpyNodeSetParams resolved in the loaded library.

func HasGraphExecMemsetNodeSetParams

func HasGraphExecMemsetNodeSetParams() bool

HasGraphExecMemsetNodeSetParams reports whether cuGraphExecMemsetNodeSetParams resolved in the loaded library.

func HasGraphExecNodeSetParams

func HasGraphExecNodeSetParams() bool

HasGraphExecNodeSetParams reports whether cuGraphExecNodeSetParams resolved in the loaded library.

func HasGraphExecUpdate

func HasGraphExecUpdate() bool

HasGraphExecUpdate reports whether cuGraphExecUpdate_v2 resolved in the loaded library.

func HasGraphExternalSemaphoresSignalNodeGetParams

func HasGraphExternalSemaphoresSignalNodeGetParams() bool

HasGraphExternalSemaphoresSignalNodeGetParams reports whether cuGraphExternalSemaphoresSignalNodeGetParams resolved in the loaded library.

func HasGraphExternalSemaphoresSignalNodeSetParams

func HasGraphExternalSemaphoresSignalNodeSetParams() bool

HasGraphExternalSemaphoresSignalNodeSetParams reports whether cuGraphExternalSemaphoresSignalNodeSetParams resolved in the loaded library.

func HasGraphExternalSemaphoresWaitNodeGetParams

func HasGraphExternalSemaphoresWaitNodeGetParams() bool

HasGraphExternalSemaphoresWaitNodeGetParams reports whether cuGraphExternalSemaphoresWaitNodeGetParams resolved in the loaded library.

func HasGraphExternalSemaphoresWaitNodeSetParams

func HasGraphExternalSemaphoresWaitNodeSetParams() bool

HasGraphExternalSemaphoresWaitNodeSetParams reports whether cuGraphExternalSemaphoresWaitNodeSetParams resolved in the loaded library.

func HasGraphGetEdges

func HasGraphGetEdges() bool

HasGraphGetEdges reports whether cuGraphGetEdges resolved in the loaded library.

It resolves as the first of cuGraphGetEdges_v2, cuGraphGetEdges that the library exports. BoundSymbol reports which.

func HasGraphGetEdgesV1

func HasGraphGetEdgesV1() bool

HasGraphGetEdgesV1 reports whether cuGraphGetEdges resolved in the loaded library.

func HasGraphGetEdgesV2

func HasGraphGetEdgesV2() bool

HasGraphGetEdgesV2 reports whether cuGraphGetEdges_v2 resolved in the loaded library.

func HasGraphGetId

func HasGraphGetId() bool

HasGraphGetId reports whether cuGraphGetId resolved in the loaded library.

func HasGraphGetNodes

func HasGraphGetNodes() bool

HasGraphGetNodes reports whether cuGraphGetNodes resolved in the loaded library.

func HasGraphGetRootNodes

func HasGraphGetRootNodes() bool

HasGraphGetRootNodes reports whether cuGraphGetRootNodes resolved in the loaded library.

func HasGraphHostNodeGetParams

func HasGraphHostNodeGetParams() bool

HasGraphHostNodeGetParams reports whether cuGraphHostNodeGetParams resolved in the loaded library.

func HasGraphHostNodeSetParams

func HasGraphHostNodeSetParams() bool

HasGraphHostNodeSetParams reports whether cuGraphHostNodeSetParams resolved in the loaded library.

func HasGraphInstantiate

func HasGraphInstantiate() bool

HasGraphInstantiate reports whether cuGraphInstantiateWithFlags resolved in the loaded library.

func HasGraphInstantiateWithParams

func HasGraphInstantiateWithParams() bool

HasGraphInstantiateWithParams reports whether cuGraphInstantiateWithParams resolved in the loaded library.

func HasGraphKernelNodeCopyAttributes

func HasGraphKernelNodeCopyAttributes() bool

HasGraphKernelNodeCopyAttributes reports whether cuGraphKernelNodeCopyAttributes resolved in the loaded library.

func HasGraphKernelNodeGetAttribute

func HasGraphKernelNodeGetAttribute() bool

HasGraphKernelNodeGetAttribute reports whether cuGraphKernelNodeGetAttribute resolved in the loaded library.

func HasGraphKernelNodeGetParams

func HasGraphKernelNodeGetParams() bool

HasGraphKernelNodeGetParams reports whether cuGraphKernelNodeGetParams_v2 resolved in the loaded library.

func HasGraphKernelNodeSetAttribute

func HasGraphKernelNodeSetAttribute() bool

HasGraphKernelNodeSetAttribute reports whether cuGraphKernelNodeSetAttribute resolved in the loaded library.

func HasGraphKernelNodeSetParams

func HasGraphKernelNodeSetParams() bool

HasGraphKernelNodeSetParams reports whether cuGraphKernelNodeSetParams_v2 resolved in the loaded library.

func HasGraphLaunch

func HasGraphLaunch() bool

HasGraphLaunch reports whether cuGraphLaunch resolved in the loaded library.

func HasGraphMemAllocNodeGetParams

func HasGraphMemAllocNodeGetParams() bool

HasGraphMemAllocNodeGetParams reports whether cuGraphMemAllocNodeGetParams resolved in the loaded library.

func HasGraphMemFreeNodeGetParams

func HasGraphMemFreeNodeGetParams() bool

HasGraphMemFreeNodeGetParams reports whether cuGraphMemFreeNodeGetParams resolved in the loaded library.

func HasGraphMemcpyNodeGetParams

func HasGraphMemcpyNodeGetParams() bool

HasGraphMemcpyNodeGetParams reports whether cuGraphMemcpyNodeGetParams resolved in the loaded library.

func HasGraphMemcpyNodeSetParams

func HasGraphMemcpyNodeSetParams() bool

HasGraphMemcpyNodeSetParams reports whether cuGraphMemcpyNodeSetParams resolved in the loaded library.

func HasGraphMemsetNodeGetParams

func HasGraphMemsetNodeGetParams() bool

HasGraphMemsetNodeGetParams reports whether cuGraphMemsetNodeGetParams resolved in the loaded library.

func HasGraphMemsetNodeSetParams

func HasGraphMemsetNodeSetParams() bool

HasGraphMemsetNodeSetParams reports whether cuGraphMemsetNodeSetParams resolved in the loaded library.

func HasGraphNodeFindInClone

func HasGraphNodeFindInClone() bool

HasGraphNodeFindInClone reports whether cuGraphNodeFindInClone resolved in the loaded library.

func HasGraphNodeGetContainingGraph

func HasGraphNodeGetContainingGraph() bool

HasGraphNodeGetContainingGraph reports whether cuGraphNodeGetContainingGraph resolved in the loaded library.

func HasGraphNodeGetDependencies

func HasGraphNodeGetDependencies() bool

HasGraphNodeGetDependencies reports whether cuGraphNodeGetDependencies resolved in the loaded library.

It resolves as the first of cuGraphNodeGetDependencies_v2, cuGraphNodeGetDependencies that the library exports. BoundSymbol reports which.

func HasGraphNodeGetDependenciesV1

func HasGraphNodeGetDependenciesV1() bool

HasGraphNodeGetDependenciesV1 reports whether cuGraphNodeGetDependencies resolved in the loaded library.

func HasGraphNodeGetDependenciesV2

func HasGraphNodeGetDependenciesV2() bool

HasGraphNodeGetDependenciesV2 reports whether cuGraphNodeGetDependencies_v2 resolved in the loaded library.

func HasGraphNodeGetDependentNodes

func HasGraphNodeGetDependentNodes() bool

HasGraphNodeGetDependentNodes reports whether cuGraphNodeGetDependentNodes resolved in the loaded library.

It resolves as the first of cuGraphNodeGetDependentNodes_v2, cuGraphNodeGetDependentNodes that the library exports. BoundSymbol reports which.

func HasGraphNodeGetDependentNodesV1

func HasGraphNodeGetDependentNodesV1() bool

HasGraphNodeGetDependentNodesV1 reports whether cuGraphNodeGetDependentNodes resolved in the loaded library.

func HasGraphNodeGetDependentNodesV2

func HasGraphNodeGetDependentNodesV2() bool

HasGraphNodeGetDependentNodesV2 reports whether cuGraphNodeGetDependentNodes_v2 resolved in the loaded library.

func HasGraphNodeGetEnabled

func HasGraphNodeGetEnabled() bool

HasGraphNodeGetEnabled reports whether cuGraphNodeGetEnabled resolved in the loaded library.

func HasGraphNodeGetLocalId

func HasGraphNodeGetLocalId() bool

HasGraphNodeGetLocalId reports whether cuGraphNodeGetLocalId resolved in the loaded library.

func HasGraphNodeGetParams

func HasGraphNodeGetParams() bool

HasGraphNodeGetParams reports whether cuGraphNodeGetParams resolved in the loaded library.

func HasGraphNodeGetToolsId

func HasGraphNodeGetToolsId() bool

HasGraphNodeGetToolsId reports whether cuGraphNodeGetToolsId resolved in the loaded library.

func HasGraphNodeGetType

func HasGraphNodeGetType() bool

HasGraphNodeGetType reports whether cuGraphNodeGetType resolved in the loaded library.

func HasGraphNodeSetEnabled

func HasGraphNodeSetEnabled() bool

HasGraphNodeSetEnabled reports whether cuGraphNodeSetEnabled resolved in the loaded library.

func HasGraphNodeSetParams

func HasGraphNodeSetParams() bool

HasGraphNodeSetParams reports whether cuGraphNodeSetParams resolved in the loaded library.

It resolves as the first of cuGraphNodeSetParams_v2, cuGraphNodeSetParams that the library exports. BoundSymbol reports which.

func HasGraphNodeSetParamsV1

func HasGraphNodeSetParamsV1() bool

HasGraphNodeSetParamsV1 reports whether cuGraphNodeSetParams resolved in the loaded library.

func HasGraphNodeSetParamsV2

func HasGraphNodeSetParamsV2() bool

HasGraphNodeSetParamsV2 reports whether cuGraphNodeSetParams_v2 resolved in the loaded library.

func HasGraphReleaseUserObject

func HasGraphReleaseUserObject() bool

HasGraphReleaseUserObject reports whether cuGraphReleaseUserObject resolved in the loaded library.

func HasGraphRemoveDependencies

func HasGraphRemoveDependencies() bool

HasGraphRemoveDependencies reports whether cuGraphRemoveDependencies resolved in the loaded library.

It resolves as the first of cuGraphRemoveDependencies_v2, cuGraphRemoveDependencies that the library exports. BoundSymbol reports which.

func HasGraphRemoveDependenciesV1

func HasGraphRemoveDependenciesV1() bool

HasGraphRemoveDependenciesV1 reports whether cuGraphRemoveDependencies resolved in the loaded library.

func HasGraphRemoveDependenciesV2

func HasGraphRemoveDependenciesV2() bool

HasGraphRemoveDependenciesV2 reports whether cuGraphRemoveDependencies_v2 resolved in the loaded library.

func HasGraphRetainUserObject

func HasGraphRetainUserObject() bool

HasGraphRetainUserObject reports whether cuGraphRetainUserObject resolved in the loaded library.

func HasGraphUpload

func HasGraphUpload() bool

HasGraphUpload reports whether cuGraphUpload resolved in the loaded library.

func HasGraphicsMapResources

func HasGraphicsMapResources() bool

HasGraphicsMapResources reports whether cuGraphicsMapResources resolved in the loaded library.

func HasGraphicsResourceGetMappedMipmappedArray

func HasGraphicsResourceGetMappedMipmappedArray() bool

HasGraphicsResourceGetMappedMipmappedArray reports whether cuGraphicsResourceGetMappedMipmappedArray resolved in the loaded library.

func HasGraphicsResourceGetMappedPointer

func HasGraphicsResourceGetMappedPointer() bool

HasGraphicsResourceGetMappedPointer reports whether cuGraphicsResourceGetMappedPointer_v2 resolved in the loaded library.

func HasGraphicsResourceSetMapFlags

func HasGraphicsResourceSetMapFlags() bool

HasGraphicsResourceSetMapFlags reports whether cuGraphicsResourceSetMapFlags_v2 resolved in the loaded library.

func HasGraphicsSubResourceGetMappedArray

func HasGraphicsSubResourceGetMappedArray() bool

HasGraphicsSubResourceGetMappedArray reports whether cuGraphicsSubResourceGetMappedArray resolved in the loaded library.

func HasGraphicsUnmapResources

func HasGraphicsUnmapResources() bool

HasGraphicsUnmapResources reports whether cuGraphicsUnmapResources resolved in the loaded library.

func HasGraphicsUnregisterResource

func HasGraphicsUnregisterResource() bool

HasGraphicsUnregisterResource reports whether cuGraphicsUnregisterResource resolved in the loaded library.

func HasGreenCtxCreate

func HasGreenCtxCreate() bool

HasGreenCtxCreate reports whether cuGreenCtxCreate resolved in the loaded library.

func HasGreenCtxDestroy

func HasGreenCtxDestroy() bool

HasGreenCtxDestroy reports whether cuGreenCtxDestroy resolved in the loaded library.

func HasGreenCtxGetDevResource

func HasGreenCtxGetDevResource() bool

HasGreenCtxGetDevResource reports whether cuGreenCtxGetDevResource resolved in the loaded library.

func HasGreenCtxGetId

func HasGreenCtxGetId() bool

HasGreenCtxGetId reports whether cuGreenCtxGetId resolved in the loaded library.

func HasGreenCtxRecordEvent

func HasGreenCtxRecordEvent() bool

HasGreenCtxRecordEvent reports whether cuGreenCtxRecordEvent resolved in the loaded library.

func HasGreenCtxStreamCreate

func HasGreenCtxStreamCreate() bool

HasGreenCtxStreamCreate reports whether cuGreenCtxStreamCreate resolved in the loaded library.

func HasGreenCtxWaitEvent

func HasGreenCtxWaitEvent() bool

HasGreenCtxWaitEvent reports whether cuGreenCtxWaitEvent resolved in the loaded library.

func HasImportExternalMemory

func HasImportExternalMemory() bool

HasImportExternalMemory reports whether cuImportExternalMemory resolved in the loaded library.

func HasImportExternalSemaphore

func HasImportExternalSemaphore() bool

HasImportExternalSemaphore reports whether cuImportExternalSemaphore resolved in the loaded library.

func HasInit

func HasInit() bool

HasInit reports whether cuInit resolved in the loaded library.

func HasIpcCloseMemHandle

func HasIpcCloseMemHandle() bool

HasIpcCloseMemHandle reports whether cuIpcCloseMemHandle resolved in the loaded library.

func HasIpcGetEventHandle

func HasIpcGetEventHandle() bool

HasIpcGetEventHandle reports whether cuIpcGetEventHandle resolved in the loaded library.

func HasIpcGetMemHandle

func HasIpcGetMemHandle() bool

HasIpcGetMemHandle reports whether cuIpcGetMemHandle resolved in the loaded library.

func HasIpcOpenEventHandle

func HasIpcOpenEventHandle() bool

HasIpcOpenEventHandle reports whether cuIpcOpenEventHandle resolved in the loaded library.

func HasIpcOpenMemHandle

func HasIpcOpenMemHandle() bool

HasIpcOpenMemHandle reports whether cuIpcOpenMemHandle_v2 resolved in the loaded library.

func HasKernelGetAttribute

func HasKernelGetAttribute() bool

HasKernelGetAttribute reports whether cuKernelGetAttribute resolved in the loaded library.

func HasKernelGetFunction

func HasKernelGetFunction() bool

HasKernelGetFunction reports whether cuKernelGetFunction resolved in the loaded library.

func HasKernelGetLibrary

func HasKernelGetLibrary() bool

HasKernelGetLibrary reports whether cuKernelGetLibrary resolved in the loaded library.

func HasKernelGetName

func HasKernelGetName() bool

HasKernelGetName reports whether cuKernelGetName resolved in the loaded library.

func HasKernelGetParamCount

func HasKernelGetParamCount() bool

HasKernelGetParamCount reports whether cuKernelGetParamCount resolved in the loaded library.

func HasKernelGetParamInfo

func HasKernelGetParamInfo() bool

HasKernelGetParamInfo reports whether cuKernelGetParamInfo resolved in the loaded library.

func HasKernelSetAttribute

func HasKernelSetAttribute() bool

HasKernelSetAttribute reports whether cuKernelSetAttribute resolved in the loaded library.

func HasKernelSetCacheConfig

func HasKernelSetCacheConfig() bool

HasKernelSetCacheConfig reports whether cuKernelSetCacheConfig resolved in the loaded library.

func HasLaunch

func HasLaunch() bool

HasLaunch reports whether cuLaunch resolved in the loaded library.

func HasLaunchCooperativeKernel

func HasLaunchCooperativeKernel() bool

HasLaunchCooperativeKernel reports whether cuLaunchCooperativeKernel resolved in the loaded library.

func HasLaunchCooperativeKernelMultiDevice

func HasLaunchCooperativeKernelMultiDevice() bool

HasLaunchCooperativeKernelMultiDevice reports whether cuLaunchCooperativeKernelMultiDevice resolved in the loaded library.

func HasLaunchGrid

func HasLaunchGrid() bool

HasLaunchGrid reports whether cuLaunchGrid resolved in the loaded library.

func HasLaunchGridAsync

func HasLaunchGridAsync() bool

HasLaunchGridAsync reports whether cuLaunchGridAsync resolved in the loaded library.

func HasLaunchHostFunc

func HasLaunchHostFunc() bool

HasLaunchHostFunc reports whether cuLaunchHostFunc resolved in the loaded library.

func HasLaunchHostFuncV1

func HasLaunchHostFuncV1() bool

HasLaunchHostFuncV1 reports whether cuLaunchHostFunc resolved in the loaded library.

func HasLaunchHostFuncV2

func HasLaunchHostFuncV2() bool

HasLaunchHostFuncV2 reports whether cuLaunchHostFunc_v2 resolved in the loaded library.

func HasLaunchKernel

func HasLaunchKernel() bool

HasLaunchKernel reports whether cuLaunchKernel resolved in the loaded library.

func HasLaunchKernelEx

func HasLaunchKernelEx() bool

HasLaunchKernelEx reports whether cuLaunchKernelEx resolved in the loaded library.

func HasLibraryEnumerateKernels

func HasLibraryEnumerateKernels() bool

HasLibraryEnumerateKernels reports whether cuLibraryEnumerateKernels resolved in the loaded library.

func HasLibraryGetGlobal

func HasLibraryGetGlobal() bool

HasLibraryGetGlobal reports whether cuLibraryGetGlobal resolved in the loaded library.

func HasLibraryGetKernel

func HasLibraryGetKernel() bool

HasLibraryGetKernel reports whether cuLibraryGetKernel resolved in the loaded library.

func HasLibraryGetKernelCount

func HasLibraryGetKernelCount() bool

HasLibraryGetKernelCount reports whether cuLibraryGetKernelCount resolved in the loaded library.

func HasLibraryGetManaged

func HasLibraryGetManaged() bool

HasLibraryGetManaged reports whether cuLibraryGetManaged resolved in the loaded library.

func HasLibraryGetModule

func HasLibraryGetModule() bool

HasLibraryGetModule reports whether cuLibraryGetModule resolved in the loaded library.

func HasLibraryGetUnifiedFunction

func HasLibraryGetUnifiedFunction() bool

HasLibraryGetUnifiedFunction reports whether cuLibraryGetUnifiedFunction resolved in the loaded library.

func HasLibraryLoadData

func HasLibraryLoadData() bool

HasLibraryLoadData reports whether cuLibraryLoadData resolved in the loaded library.

func HasLibraryLoadFromFile

func HasLibraryLoadFromFile() bool

HasLibraryLoadFromFile reports whether cuLibraryLoadFromFile resolved in the loaded library.

func HasLibraryUnload

func HasLibraryUnload() bool

HasLibraryUnload reports whether cuLibraryUnload resolved in the loaded library.

func HasLinkAddData

func HasLinkAddData() bool

HasLinkAddData reports whether cuLinkAddData_v2 resolved in the loaded library.

func HasLinkAddFile

func HasLinkAddFile() bool

HasLinkAddFile reports whether cuLinkAddFile_v2 resolved in the loaded library.

func HasLinkComplete

func HasLinkComplete() bool

HasLinkComplete reports whether cuLinkComplete resolved in the loaded library.

func HasLinkCreate

func HasLinkCreate() bool

HasLinkCreate reports whether cuLinkCreate_v2 resolved in the loaded library.

func HasLinkDestroy

func HasLinkDestroy() bool

HasLinkDestroy reports whether cuLinkDestroy resolved in the loaded library.

func HasLogicalEndpointAddDevice

func HasLogicalEndpointAddDevice() bool

HasLogicalEndpointAddDevice reports whether cuLogicalEndpointAddDevice resolved in the loaded library.

func HasLogicalEndpointBindAddr

func HasLogicalEndpointBindAddr() bool

HasLogicalEndpointBindAddr reports whether cuLogicalEndpointBindAddr resolved in the loaded library.

func HasLogicalEndpointBindMem

func HasLogicalEndpointBindMem() bool

HasLogicalEndpointBindMem reports whether cuLogicalEndpointBindMem resolved in the loaded library.

func HasLogicalEndpointCreate

func HasLogicalEndpointCreate() bool

HasLogicalEndpointCreate reports whether cuLogicalEndpointCreate resolved in the loaded library.

func HasLogicalEndpointDestroy

func HasLogicalEndpointDestroy() bool

HasLogicalEndpointDestroy reports whether cuLogicalEndpointDestroy resolved in the loaded library.

func HasLogicalEndpointExport

func HasLogicalEndpointExport() bool

HasLogicalEndpointExport reports whether cuLogicalEndpointExport resolved in the loaded library.

func HasLogicalEndpointGetLimits

func HasLogicalEndpointGetLimits() bool

HasLogicalEndpointGetLimits reports whether cuLogicalEndpointGetLimits resolved in the loaded library.

func HasLogicalEndpointIdRelease

func HasLogicalEndpointIdRelease() bool

HasLogicalEndpointIdRelease reports whether cuLogicalEndpointIdRelease resolved in the loaded library.

func HasLogicalEndpointIdReserve

func HasLogicalEndpointIdReserve() bool

HasLogicalEndpointIdReserve reports whether cuLogicalEndpointIdReserve resolved in the loaded library.

func HasLogicalEndpointImport

func HasLogicalEndpointImport() bool

HasLogicalEndpointImport reports whether cuLogicalEndpointImport resolved in the loaded library.

func HasLogicalEndpointQuery

func HasLogicalEndpointQuery() bool

HasLogicalEndpointQuery reports whether cuLogicalEndpointQuery resolved in the loaded library.

func HasLogicalEndpointUnbind

func HasLogicalEndpointUnbind() bool

HasLogicalEndpointUnbind reports whether cuLogicalEndpointUnbind resolved in the loaded library.

func HasLogsCurrent

func HasLogsCurrent() bool

HasLogsCurrent reports whether cuLogsCurrent resolved in the loaded library.

func HasLogsDumpToFile

func HasLogsDumpToFile() bool

HasLogsDumpToFile reports whether cuLogsDumpToFile resolved in the loaded library.

func HasLogsDumpToMemory

func HasLogsDumpToMemory() bool

HasLogsDumpToMemory reports whether cuLogsDumpToMemory resolved in the loaded library.

func HasLogsRegisterCallback

func HasLogsRegisterCallback() bool

HasLogsRegisterCallback reports whether cuLogsRegisterCallback resolved in the loaded library.

func HasLogsUnregisterCallback

func HasLogsUnregisterCallback() bool

HasLogsUnregisterCallback reports whether cuLogsUnregisterCallback resolved in the loaded library.

func HasMemAddressFree

func HasMemAddressFree() bool

HasMemAddressFree reports whether cuMemAddressFree resolved in the loaded library.

func HasMemAddressReserve

func HasMemAddressReserve() bool

HasMemAddressReserve reports whether cuMemAddressReserve resolved in the loaded library.

func HasMemAdvise

func HasMemAdvise() bool

HasMemAdvise reports whether cuMemAdvise resolved in the loaded library.

func HasMemAdviseV1

func HasMemAdviseV1() bool

HasMemAdviseV1 reports whether cuMemAdvise resolved in the loaded library.

func HasMemAdviseV2

func HasMemAdviseV2() bool

HasMemAdviseV2 reports whether cuMemAdvise_v2 resolved in the loaded library.

func HasMemAlloc

func HasMemAlloc() bool

HasMemAlloc reports whether cuMemAlloc_v2 resolved in the loaded library.

func HasMemAllocAsync

func HasMemAllocAsync() bool

HasMemAllocAsync reports whether cuMemAllocAsync resolved in the loaded library.

func HasMemAllocFromPoolAsync

func HasMemAllocFromPoolAsync() bool

HasMemAllocFromPoolAsync reports whether cuMemAllocFromPoolAsync resolved in the loaded library.

func HasMemAllocHost

func HasMemAllocHost() bool

HasMemAllocHost reports whether cuMemAllocHost_v2 resolved in the loaded library.

func HasMemAllocManaged

func HasMemAllocManaged() bool

HasMemAllocManaged reports whether cuMemAllocManaged resolved in the loaded library.

func HasMemAllocPitch

func HasMemAllocPitch() bool

HasMemAllocPitch reports whether cuMemAllocPitch_v2 resolved in the loaded library.

func HasMemBatchDecompressAsync

func HasMemBatchDecompressAsync() bool

HasMemBatchDecompressAsync reports whether cuMemBatchDecompressAsync resolved in the loaded library.

func HasMemCreate

func HasMemCreate() bool

HasMemCreate reports whether cuMemCreate resolved in the loaded library.

func HasMemDiscardAndPrefetchBatchAsync

func HasMemDiscardAndPrefetchBatchAsync() bool

HasMemDiscardAndPrefetchBatchAsync reports whether cuMemDiscardAndPrefetchBatchAsync resolved in the loaded library.

func HasMemDiscardBatchAsync

func HasMemDiscardBatchAsync() bool

HasMemDiscardBatchAsync reports whether cuMemDiscardBatchAsync resolved in the loaded library.

func HasMemExportToShareableHandle

func HasMemExportToShareableHandle() bool

HasMemExportToShareableHandle reports whether cuMemExportToShareableHandle resolved in the loaded library.

func HasMemFree

func HasMemFree() bool

HasMemFree reports whether cuMemFree_v2 resolved in the loaded library.

func HasMemFreeAsync

func HasMemFreeAsync() bool

HasMemFreeAsync reports whether cuMemFreeAsync resolved in the loaded library.

func HasMemFreeHost

func HasMemFreeHost() bool

HasMemFreeHost reports whether cuMemFreeHost resolved in the loaded library.

func HasMemGetAccess

func HasMemGetAccess() bool

HasMemGetAccess reports whether cuMemGetAccess resolved in the loaded library.

func HasMemGetAddressRange

func HasMemGetAddressRange() bool

HasMemGetAddressRange reports whether cuMemGetAddressRange_v2 resolved in the loaded library.

func HasMemGetAllocationGranularity

func HasMemGetAllocationGranularity() bool

HasMemGetAllocationGranularity reports whether cuMemGetAllocationGranularity resolved in the loaded library.

func HasMemGetAllocationPropertiesFromHandle

func HasMemGetAllocationPropertiesFromHandle() bool

HasMemGetAllocationPropertiesFromHandle reports whether cuMemGetAllocationPropertiesFromHandle resolved in the loaded library.

func HasMemGetDefaultMemPool

func HasMemGetDefaultMemPool() bool

HasMemGetDefaultMemPool reports whether cuMemGetDefaultMemPool resolved in the loaded library.

func HasMemGetHandleForAddressRange

func HasMemGetHandleForAddressRange() bool

HasMemGetHandleForAddressRange reports whether cuMemGetHandleForAddressRange resolved in the loaded library.

func HasMemGetInfo

func HasMemGetInfo() bool

HasMemGetInfo reports whether cuMemGetInfo_v2 resolved in the loaded library.

func HasMemGetLocationInfo

func HasMemGetLocationInfo() bool

HasMemGetLocationInfo reports whether cuMemGetLocationInfo resolved in the loaded library.

func HasMemGetMemPool

func HasMemGetMemPool() bool

HasMemGetMemPool reports whether cuMemGetMemPool resolved in the loaded library.

func HasMemHostAlloc

func HasMemHostAlloc() bool

HasMemHostAlloc reports whether cuMemHostAlloc resolved in the loaded library.

func HasMemHostGetDevicePointer

func HasMemHostGetDevicePointer() bool

HasMemHostGetDevicePointer reports whether cuMemHostGetDevicePointer_v2 resolved in the loaded library.

func HasMemHostGetFlags

func HasMemHostGetFlags() bool

HasMemHostGetFlags reports whether cuMemHostGetFlags resolved in the loaded library.

func HasMemHostRegister

func HasMemHostRegister() bool

HasMemHostRegister reports whether cuMemHostRegister_v2 resolved in the loaded library.

func HasMemHostUnregister

func HasMemHostUnregister() bool

HasMemHostUnregister reports whether cuMemHostUnregister resolved in the loaded library.

func HasMemImportFromShareableHandle

func HasMemImportFromShareableHandle() bool

HasMemImportFromShareableHandle reports whether cuMemImportFromShareableHandle resolved in the loaded library.

func HasMemMap

func HasMemMap() bool

HasMemMap reports whether cuMemMap resolved in the loaded library.

func HasMemMapArrayAsync

func HasMemMapArrayAsync() bool

HasMemMapArrayAsync reports whether cuMemMapArrayAsync resolved in the loaded library.

func HasMemPoolCreate

func HasMemPoolCreate() bool

HasMemPoolCreate reports whether cuMemPoolCreate resolved in the loaded library.

func HasMemPoolDestroy

func HasMemPoolDestroy() bool

HasMemPoolDestroy reports whether cuMemPoolDestroy resolved in the loaded library.

func HasMemPoolExportPointer

func HasMemPoolExportPointer() bool

HasMemPoolExportPointer reports whether cuMemPoolExportPointer resolved in the loaded library.

func HasMemPoolExportToShareableHandle

func HasMemPoolExportToShareableHandle() bool

HasMemPoolExportToShareableHandle reports whether cuMemPoolExportToShareableHandle resolved in the loaded library.

func HasMemPoolGetAccess

func HasMemPoolGetAccess() bool

HasMemPoolGetAccess reports whether cuMemPoolGetAccess resolved in the loaded library.

func HasMemPoolGetAttribute

func HasMemPoolGetAttribute() bool

HasMemPoolGetAttribute reports whether cuMemPoolGetAttribute resolved in the loaded library.

func HasMemPoolImportFromShareableHandle

func HasMemPoolImportFromShareableHandle() bool

HasMemPoolImportFromShareableHandle reports whether cuMemPoolImportFromShareableHandle resolved in the loaded library.

func HasMemPoolImportPointer

func HasMemPoolImportPointer() bool

HasMemPoolImportPointer reports whether cuMemPoolImportPointer resolved in the loaded library.

func HasMemPoolSetAccess

func HasMemPoolSetAccess() bool

HasMemPoolSetAccess reports whether cuMemPoolSetAccess resolved in the loaded library.

func HasMemPoolSetAttribute

func HasMemPoolSetAttribute() bool

HasMemPoolSetAttribute reports whether cuMemPoolSetAttribute resolved in the loaded library.

func HasMemPoolTrimTo

func HasMemPoolTrimTo() bool

HasMemPoolTrimTo reports whether cuMemPoolTrimTo resolved in the loaded library.

func HasMemPrefetchAsync

func HasMemPrefetchAsync() bool

HasMemPrefetchAsync reports whether cuMemPrefetchAsync resolved in the loaded library.

func HasMemPrefetchAsyncV1

func HasMemPrefetchAsyncV1() bool

HasMemPrefetchAsyncV1 reports whether cuMemPrefetchAsync resolved in the loaded library.

func HasMemPrefetchAsyncV2

func HasMemPrefetchAsyncV2() bool

HasMemPrefetchAsyncV2 reports whether cuMemPrefetchAsync_v2 resolved in the loaded library.

func HasMemPrefetchBatchAsync

func HasMemPrefetchBatchAsync() bool

HasMemPrefetchBatchAsync reports whether cuMemPrefetchBatchAsync resolved in the loaded library.

func HasMemRangeGetAttribute

func HasMemRangeGetAttribute() bool

HasMemRangeGetAttribute reports whether cuMemRangeGetAttribute resolved in the loaded library.

func HasMemRangeGetAttributes

func HasMemRangeGetAttributes() bool

HasMemRangeGetAttributes reports whether cuMemRangeGetAttributes resolved in the loaded library.

func HasMemRelease

func HasMemRelease() bool

HasMemRelease reports whether cuMemRelease resolved in the loaded library.

func HasMemRetainAllocationHandle

func HasMemRetainAllocationHandle() bool

HasMemRetainAllocationHandle reports whether cuMemRetainAllocationHandle resolved in the loaded library.

func HasMemSetAccess

func HasMemSetAccess() bool

HasMemSetAccess reports whether cuMemSetAccess resolved in the loaded library.

func HasMemSetMemPool

func HasMemSetMemPool() bool

HasMemSetMemPool reports whether cuMemSetMemPool resolved in the loaded library.

func HasMemUnmap

func HasMemUnmap() bool

HasMemUnmap reports whether cuMemUnmap resolved in the loaded library.

func HasMemcpy

func HasMemcpy() bool

HasMemcpy reports whether cuMemcpy resolved in the loaded library.

func HasMemcpy2D

func HasMemcpy2D() bool

HasMemcpy2D reports whether cuMemcpy2D_v2 resolved in the loaded library.

func HasMemcpy2DAsync

func HasMemcpy2DAsync() bool

HasMemcpy2DAsync reports whether cuMemcpy2DAsync_v2 resolved in the loaded library.

func HasMemcpy2DUnaligned

func HasMemcpy2DUnaligned() bool

HasMemcpy2DUnaligned reports whether cuMemcpy2DUnaligned_v2 resolved in the loaded library.

func HasMemcpy3D

func HasMemcpy3D() bool

HasMemcpy3D reports whether cuMemcpy3D_v2 resolved in the loaded library.

func HasMemcpy3DAsync

func HasMemcpy3DAsync() bool

HasMemcpy3DAsync reports whether cuMemcpy3DAsync_v2 resolved in the loaded library.

func HasMemcpy3DBatchAsync

func HasMemcpy3DBatchAsync() bool

HasMemcpy3DBatchAsync reports whether cuMemcpy3DBatchAsync resolved in the loaded library.

It resolves as the first of cuMemcpy3DBatchAsync_v2, cuMemcpy3DBatchAsync that the library exports. BoundSymbol reports which.

func HasMemcpy3DBatchAsyncV1

func HasMemcpy3DBatchAsyncV1() bool

HasMemcpy3DBatchAsyncV1 reports whether cuMemcpy3DBatchAsync resolved in the loaded library.

func HasMemcpy3DBatchAsyncV2

func HasMemcpy3DBatchAsyncV2() bool

HasMemcpy3DBatchAsyncV2 reports whether cuMemcpy3DBatchAsync_v2 resolved in the loaded library.

func HasMemcpy3DPeer

func HasMemcpy3DPeer() bool

HasMemcpy3DPeer reports whether cuMemcpy3DPeer resolved in the loaded library.

func HasMemcpy3DPeerAsync

func HasMemcpy3DPeerAsync() bool

HasMemcpy3DPeerAsync reports whether cuMemcpy3DPeerAsync resolved in the loaded library.

func HasMemcpy3DWithAttributesAsync

func HasMemcpy3DWithAttributesAsync() bool

HasMemcpy3DWithAttributesAsync reports whether cuMemcpy3DWithAttributesAsync resolved in the loaded library.

func HasMemcpyAsync

func HasMemcpyAsync() bool

HasMemcpyAsync reports whether cuMemcpyAsync resolved in the loaded library.

func HasMemcpyAtoA

func HasMemcpyAtoA() bool

HasMemcpyAtoA reports whether cuMemcpyAtoA_v2 resolved in the loaded library.

func HasMemcpyAtoD

func HasMemcpyAtoD() bool

HasMemcpyAtoD reports whether cuMemcpyAtoD_v2 resolved in the loaded library.

func HasMemcpyAtoH

func HasMemcpyAtoH() bool

HasMemcpyAtoH reports whether cuMemcpyAtoH_v2 resolved in the loaded library.

func HasMemcpyAtoHAsync

func HasMemcpyAtoHAsync() bool

HasMemcpyAtoHAsync reports whether cuMemcpyAtoHAsync_v2 resolved in the loaded library.

func HasMemcpyBatchAsync

func HasMemcpyBatchAsync() bool

HasMemcpyBatchAsync reports whether cuMemcpyBatchAsync resolved in the loaded library.

It resolves as the first of cuMemcpyBatchAsync_v2, cuMemcpyBatchAsync that the library exports. BoundSymbol reports which.

func HasMemcpyBatchAsyncV1

func HasMemcpyBatchAsyncV1() bool

HasMemcpyBatchAsyncV1 reports whether cuMemcpyBatchAsync resolved in the loaded library.

func HasMemcpyBatchAsyncV2

func HasMemcpyBatchAsyncV2() bool

HasMemcpyBatchAsyncV2 reports whether cuMemcpyBatchAsync_v2 resolved in the loaded library.

func HasMemcpyDtoA

func HasMemcpyDtoA() bool

HasMemcpyDtoA reports whether cuMemcpyDtoA_v2 resolved in the loaded library.

func HasMemcpyDtoD

func HasMemcpyDtoD() bool

HasMemcpyDtoD reports whether cuMemcpyDtoD_v2 resolved in the loaded library.

func HasMemcpyDtoDAsync

func HasMemcpyDtoDAsync() bool

HasMemcpyDtoDAsync reports whether cuMemcpyDtoDAsync_v2 resolved in the loaded library.

func HasMemcpyDtoH

func HasMemcpyDtoH() bool

HasMemcpyDtoH reports whether cuMemcpyDtoH_v2 resolved in the loaded library.

func HasMemcpyDtoHAsync

func HasMemcpyDtoHAsync() bool

HasMemcpyDtoHAsync reports whether cuMemcpyDtoHAsync_v2 resolved in the loaded library.

func HasMemcpyHtoA

func HasMemcpyHtoA() bool

HasMemcpyHtoA reports whether cuMemcpyHtoA_v2 resolved in the loaded library.

func HasMemcpyHtoAAsync

func HasMemcpyHtoAAsync() bool

HasMemcpyHtoAAsync reports whether cuMemcpyHtoAAsync_v2 resolved in the loaded library.

func HasMemcpyHtoD

func HasMemcpyHtoD() bool

HasMemcpyHtoD reports whether cuMemcpyHtoD_v2 resolved in the loaded library.

func HasMemcpyHtoDAsync

func HasMemcpyHtoDAsync() bool

HasMemcpyHtoDAsync reports whether cuMemcpyHtoDAsync_v2 resolved in the loaded library.

func HasMemcpyPeer

func HasMemcpyPeer() bool

HasMemcpyPeer reports whether cuMemcpyPeer resolved in the loaded library.

func HasMemcpyPeerAsync

func HasMemcpyPeerAsync() bool

HasMemcpyPeerAsync reports whether cuMemcpyPeerAsync resolved in the loaded library.

func HasMemcpyWithAttributesAsync

func HasMemcpyWithAttributesAsync() bool

HasMemcpyWithAttributesAsync reports whether cuMemcpyWithAttributesAsync resolved in the loaded library.

func HasMemsetD2D8

func HasMemsetD2D8() bool

HasMemsetD2D8 reports whether cuMemsetD2D8_v2 resolved in the loaded library.

func HasMemsetD2D8Async

func HasMemsetD2D8Async() bool

HasMemsetD2D8Async reports whether cuMemsetD2D8Async resolved in the loaded library.

func HasMemsetD2D16

func HasMemsetD2D16() bool

HasMemsetD2D16 reports whether cuMemsetD2D16_v2 resolved in the loaded library.

func HasMemsetD2D16Async

func HasMemsetD2D16Async() bool

HasMemsetD2D16Async reports whether cuMemsetD2D16Async resolved in the loaded library.

func HasMemsetD2D32

func HasMemsetD2D32() bool

HasMemsetD2D32 reports whether cuMemsetD2D32_v2 resolved in the loaded library.

func HasMemsetD2D32Async

func HasMemsetD2D32Async() bool

HasMemsetD2D32Async reports whether cuMemsetD2D32Async resolved in the loaded library.

func HasMemsetD8

func HasMemsetD8() bool

HasMemsetD8 reports whether cuMemsetD8_v2 resolved in the loaded library.

func HasMemsetD8Async

func HasMemsetD8Async() bool

HasMemsetD8Async reports whether cuMemsetD8Async resolved in the loaded library.

func HasMemsetD16

func HasMemsetD16() bool

HasMemsetD16 reports whether cuMemsetD16_v2 resolved in the loaded library.

func HasMemsetD16Async

func HasMemsetD16Async() bool

HasMemsetD16Async reports whether cuMemsetD16Async resolved in the loaded library.

func HasMemsetD32

func HasMemsetD32() bool

HasMemsetD32 reports whether cuMemsetD32_v2 resolved in the loaded library.

func HasMemsetD32Async

func HasMemsetD32Async() bool

HasMemsetD32Async reports whether cuMemsetD32Async resolved in the loaded library.

func HasMipmappedArrayCreate

func HasMipmappedArrayCreate() bool

HasMipmappedArrayCreate reports whether cuMipmappedArrayCreate resolved in the loaded library.

func HasMipmappedArrayDestroy

func HasMipmappedArrayDestroy() bool

HasMipmappedArrayDestroy reports whether cuMipmappedArrayDestroy resolved in the loaded library.

func HasMipmappedArrayGetLevel

func HasMipmappedArrayGetLevel() bool

HasMipmappedArrayGetLevel reports whether cuMipmappedArrayGetLevel resolved in the loaded library.

func HasMipmappedArrayGetMemoryRequirements

func HasMipmappedArrayGetMemoryRequirements() bool

HasMipmappedArrayGetMemoryRequirements reports whether cuMipmappedArrayGetMemoryRequirements resolved in the loaded library.

func HasMipmappedArrayGetSparseProperties

func HasMipmappedArrayGetSparseProperties() bool

HasMipmappedArrayGetSparseProperties reports whether cuMipmappedArrayGetSparseProperties resolved in the loaded library.

func HasModuleEnumerateFunctions

func HasModuleEnumerateFunctions() bool

HasModuleEnumerateFunctions reports whether cuModuleEnumerateFunctions resolved in the loaded library.

func HasModuleGetFunction

func HasModuleGetFunction() bool

HasModuleGetFunction reports whether cuModuleGetFunction resolved in the loaded library.

func HasModuleGetFunctionCount

func HasModuleGetFunctionCount() bool

HasModuleGetFunctionCount reports whether cuModuleGetFunctionCount resolved in the loaded library.

func HasModuleGetGlobal

func HasModuleGetGlobal() bool

HasModuleGetGlobal reports whether cuModuleGetGlobal_v2 resolved in the loaded library.

func HasModuleGetLoadingMode

func HasModuleGetLoadingMode() bool

HasModuleGetLoadingMode reports whether cuModuleGetLoadingMode resolved in the loaded library.

func HasModuleGetSurfRef

func HasModuleGetSurfRef() bool

HasModuleGetSurfRef reports whether cuModuleGetSurfRef resolved in the loaded library.

func HasModuleGetTexRef

func HasModuleGetTexRef() bool

HasModuleGetTexRef reports whether cuModuleGetTexRef resolved in the loaded library.

func HasModuleLoad

func HasModuleLoad() bool

HasModuleLoad reports whether cuModuleLoad resolved in the loaded library.

func HasModuleLoadData

func HasModuleLoadData() bool

HasModuleLoadData reports whether cuModuleLoadData resolved in the loaded library.

func HasModuleLoadDataEx

func HasModuleLoadDataEx() bool

HasModuleLoadDataEx reports whether cuModuleLoadDataEx resolved in the loaded library.

func HasModuleLoadFatBinary

func HasModuleLoadFatBinary() bool

HasModuleLoadFatBinary reports whether cuModuleLoadFatBinary resolved in the loaded library.

func HasModuleUnload

func HasModuleUnload() bool

HasModuleUnload reports whether cuModuleUnload resolved in the loaded library.

func HasMulticastAddDevice

func HasMulticastAddDevice() bool

HasMulticastAddDevice reports whether cuMulticastAddDevice resolved in the loaded library.

func HasMulticastBindAddr

func HasMulticastBindAddr() bool

HasMulticastBindAddr reports whether cuMulticastBindAddr resolved in the loaded library.

func HasMulticastBindAddrV1

func HasMulticastBindAddrV1() bool

HasMulticastBindAddrV1 reports whether cuMulticastBindAddr resolved in the loaded library.

func HasMulticastBindAddrV2

func HasMulticastBindAddrV2() bool

HasMulticastBindAddrV2 reports whether cuMulticastBindAddr_v2 resolved in the loaded library.

func HasMulticastBindMem

func HasMulticastBindMem() bool

HasMulticastBindMem reports whether cuMulticastBindMem resolved in the loaded library.

func HasMulticastBindMemV1

func HasMulticastBindMemV1() bool

HasMulticastBindMemV1 reports whether cuMulticastBindMem resolved in the loaded library.

func HasMulticastBindMemV2

func HasMulticastBindMemV2() bool

HasMulticastBindMemV2 reports whether cuMulticastBindMem_v2 resolved in the loaded library.

func HasMulticastCreate

func HasMulticastCreate() bool

HasMulticastCreate reports whether cuMulticastCreate resolved in the loaded library.

func HasMulticastGetGranularity

func HasMulticastGetGranularity() bool

HasMulticastGetGranularity reports whether cuMulticastGetGranularity resolved in the loaded library.

func HasMulticastUnbind

func HasMulticastUnbind() bool

HasMulticastUnbind reports whether cuMulticastUnbind resolved in the loaded library.

func HasOccupancyAvailableDynamicSMemPerBlock

func HasOccupancyAvailableDynamicSMemPerBlock() bool

HasOccupancyAvailableDynamicSMemPerBlock reports whether cuOccupancyAvailableDynamicSMemPerBlock resolved in the loaded library.

func HasOccupancyMaxActiveBlocksPerMultiprocessor

func HasOccupancyMaxActiveBlocksPerMultiprocessor() bool

HasOccupancyMaxActiveBlocksPerMultiprocessor reports whether cuOccupancyMaxActiveBlocksPerMultiprocessor resolved in the loaded library.

func HasOccupancyMaxActiveBlocksPerMultiprocessorWithFlags

func HasOccupancyMaxActiveBlocksPerMultiprocessorWithFlags() bool

HasOccupancyMaxActiveBlocksPerMultiprocessorWithFlags reports whether cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags resolved in the loaded library.

func HasOccupancyMaxActiveClusters

func HasOccupancyMaxActiveClusters() bool

HasOccupancyMaxActiveClusters reports whether cuOccupancyMaxActiveClusters resolved in the loaded library.

func HasOccupancyMaxPotentialBlockSize

func HasOccupancyMaxPotentialBlockSize() bool

HasOccupancyMaxPotentialBlockSize reports whether cuOccupancyMaxPotentialBlockSize resolved in the loaded library.

func HasOccupancyMaxPotentialBlockSizeWithFlags

func HasOccupancyMaxPotentialBlockSizeWithFlags() bool

HasOccupancyMaxPotentialBlockSizeWithFlags reports whether cuOccupancyMaxPotentialBlockSizeWithFlags resolved in the loaded library.

func HasOccupancyMaxPotentialClusterSize

func HasOccupancyMaxPotentialClusterSize() bool

HasOccupancyMaxPotentialClusterSize reports whether cuOccupancyMaxPotentialClusterSize resolved in the loaded library.

func HasParamSetSize

func HasParamSetSize() bool

HasParamSetSize reports whether cuParamSetSize resolved in the loaded library.

func HasParamSetTexRef

func HasParamSetTexRef() bool

HasParamSetTexRef reports whether cuParamSetTexRef resolved in the loaded library.

func HasParamSetf

func HasParamSetf() bool

HasParamSetf reports whether cuParamSetf resolved in the loaded library.

func HasParamSeti

func HasParamSeti() bool

HasParamSeti reports whether cuParamSeti resolved in the loaded library.

func HasParamSetv

func HasParamSetv() bool

HasParamSetv reports whether cuParamSetv resolved in the loaded library.

func HasPointerGetAttribute

func HasPointerGetAttribute() bool

HasPointerGetAttribute reports whether cuPointerGetAttribute resolved in the loaded library.

func HasPointerGetAttributes

func HasPointerGetAttributes() bool

HasPointerGetAttributes reports whether cuPointerGetAttributes resolved in the loaded library.

func HasPointerSetAttribute

func HasPointerSetAttribute() bool

HasPointerSetAttribute reports whether cuPointerSetAttribute resolved in the loaded library.

func HasSignalExternalSemaphoresAsync

func HasSignalExternalSemaphoresAsync() bool

HasSignalExternalSemaphoresAsync reports whether cuSignalExternalSemaphoresAsync resolved in the loaded library.

func HasStreamAddCallback

func HasStreamAddCallback() bool

HasStreamAddCallback reports whether cuStreamAddCallback resolved in the loaded library.

func HasStreamAttachMemAsync

func HasStreamAttachMemAsync() bool

HasStreamAttachMemAsync reports whether cuStreamAttachMemAsync resolved in the loaded library.

func HasStreamBatchMemOp

func HasStreamBatchMemOp() bool

HasStreamBatchMemOp reports whether cuStreamBatchMemOp_v2 resolved in the loaded library.

func HasStreamBeginCapture

func HasStreamBeginCapture() bool

HasStreamBeginCapture reports whether cuStreamBeginCapture_v2 resolved in the loaded library.

func HasStreamBeginCaptureToCig

func HasStreamBeginCaptureToCig() bool

HasStreamBeginCaptureToCig reports whether cuStreamBeginCaptureToCig resolved in the loaded library.

func HasStreamBeginCaptureToGraph

func HasStreamBeginCaptureToGraph() bool

HasStreamBeginCaptureToGraph reports whether cuStreamBeginCaptureToGraph resolved in the loaded library.

func HasStreamBeginRecaptureToGraph

func HasStreamBeginRecaptureToGraph() bool

HasStreamBeginRecaptureToGraph reports whether cuStreamBeginRecaptureToGraph resolved in the loaded library.

func HasStreamCopyAttributes

func HasStreamCopyAttributes() bool

HasStreamCopyAttributes reports whether cuStreamCopyAttributes resolved in the loaded library.

func HasStreamCreate

func HasStreamCreate() bool

HasStreamCreate reports whether cuStreamCreate resolved in the loaded library.

func HasStreamCreateWithPriority

func HasStreamCreateWithPriority() bool

HasStreamCreateWithPriority reports whether cuStreamCreateWithPriority resolved in the loaded library.

func HasStreamDestroy

func HasStreamDestroy() bool

HasStreamDestroy reports whether cuStreamDestroy_v2 resolved in the loaded library.

func HasStreamEndCapture

func HasStreamEndCapture() bool

HasStreamEndCapture reports whether cuStreamEndCapture resolved in the loaded library.

func HasStreamEndCaptureToCig

func HasStreamEndCaptureToCig() bool

HasStreamEndCaptureToCig reports whether cuStreamEndCaptureToCig resolved in the loaded library.

func HasStreamGetAttribute

func HasStreamGetAttribute() bool

HasStreamGetAttribute reports whether cuStreamGetAttribute resolved in the loaded library.

func HasStreamGetCaptureInfo

func HasStreamGetCaptureInfo() bool

HasStreamGetCaptureInfo reports whether cuStreamGetCaptureInfo resolved in the loaded library.

It resolves as the first of cuStreamGetCaptureInfo_v3, cuStreamGetCaptureInfo_v2 that the library exports. BoundSymbol reports which.

func HasStreamGetCaptureInfoV2

func HasStreamGetCaptureInfoV2() bool

HasStreamGetCaptureInfoV2 reports whether cuStreamGetCaptureInfo_v2 resolved in the loaded library.

func HasStreamGetCaptureInfoV3

func HasStreamGetCaptureInfoV3() bool

HasStreamGetCaptureInfoV3 reports whether cuStreamGetCaptureInfo_v3 resolved in the loaded library.

func HasStreamGetCtx

func HasStreamGetCtx() bool

HasStreamGetCtx reports whether cuStreamGetCtx resolved in the loaded library.

func HasStreamGetCtxV1

func HasStreamGetCtxV1() bool

HasStreamGetCtxV1 reports whether cuStreamGetCtx resolved in the loaded library.

func HasStreamGetCtxV2

func HasStreamGetCtxV2() bool

HasStreamGetCtxV2 reports whether cuStreamGetCtx_v2 resolved in the loaded library.

func HasStreamGetDevResource

func HasStreamGetDevResource() bool

HasStreamGetDevResource reports whether cuStreamGetDevResource resolved in the loaded library.

func HasStreamGetDevice

func HasStreamGetDevice() bool

HasStreamGetDevice reports whether cuStreamGetDevice resolved in the loaded library.

func HasStreamGetFlags

func HasStreamGetFlags() bool

HasStreamGetFlags reports whether cuStreamGetFlags resolved in the loaded library.

func HasStreamGetGreenCtx

func HasStreamGetGreenCtx() bool

HasStreamGetGreenCtx reports whether cuStreamGetGreenCtx resolved in the loaded library.

func HasStreamGetId

func HasStreamGetId() bool

HasStreamGetId reports whether cuStreamGetId resolved in the loaded library.

func HasStreamGetPriority

func HasStreamGetPriority() bool

HasStreamGetPriority reports whether cuStreamGetPriority resolved in the loaded library.

func HasStreamIsCapturing

func HasStreamIsCapturing() bool

HasStreamIsCapturing reports whether cuStreamIsCapturing resolved in the loaded library.

func HasStreamQuery

func HasStreamQuery() bool

HasStreamQuery reports whether cuStreamQuery resolved in the loaded library.

func HasStreamSetAttribute

func HasStreamSetAttribute() bool

HasStreamSetAttribute reports whether cuStreamSetAttribute resolved in the loaded library.

func HasStreamSynchronize

func HasStreamSynchronize() bool

HasStreamSynchronize reports whether cuStreamSynchronize resolved in the loaded library.

func HasStreamUpdateCaptureDependencies

func HasStreamUpdateCaptureDependencies() bool

HasStreamUpdateCaptureDependencies reports whether cuStreamUpdateCaptureDependencies resolved in the loaded library.

It resolves as the first of cuStreamUpdateCaptureDependencies_v2, cuStreamUpdateCaptureDependencies that the library exports. BoundSymbol reports which.

func HasStreamUpdateCaptureDependenciesV1

func HasStreamUpdateCaptureDependenciesV1() bool

HasStreamUpdateCaptureDependenciesV1 reports whether cuStreamUpdateCaptureDependencies resolved in the loaded library.

func HasStreamUpdateCaptureDependenciesV2

func HasStreamUpdateCaptureDependenciesV2() bool

HasStreamUpdateCaptureDependenciesV2 reports whether cuStreamUpdateCaptureDependencies_v2 resolved in the loaded library.

func HasStreamWaitEvent

func HasStreamWaitEvent() bool

HasStreamWaitEvent reports whether cuStreamWaitEvent resolved in the loaded library.

func HasStreamWaitValue32

func HasStreamWaitValue32() bool

HasStreamWaitValue32 reports whether cuStreamWaitValue32_v2 resolved in the loaded library.

func HasStreamWaitValue64

func HasStreamWaitValue64() bool

HasStreamWaitValue64 reports whether cuStreamWaitValue64_v2 resolved in the loaded library.

func HasStreamWriteValue32

func HasStreamWriteValue32() bool

HasStreamWriteValue32 reports whether cuStreamWriteValue32_v2 resolved in the loaded library.

func HasStreamWriteValue64

func HasStreamWriteValue64() bool

HasStreamWriteValue64 reports whether cuStreamWriteValue64_v2 resolved in the loaded library.

func HasSurfObjectCreate

func HasSurfObjectCreate() bool

HasSurfObjectCreate reports whether cuSurfObjectCreate resolved in the loaded library.

func HasSurfObjectDestroy

func HasSurfObjectDestroy() bool

HasSurfObjectDestroy reports whether cuSurfObjectDestroy resolved in the loaded library.

func HasSurfObjectGetResourceDesc

func HasSurfObjectGetResourceDesc() bool

HasSurfObjectGetResourceDesc reports whether cuSurfObjectGetResourceDesc resolved in the loaded library.

func HasSurfRefGetArray

func HasSurfRefGetArray() bool

HasSurfRefGetArray reports whether cuSurfRefGetArray resolved in the loaded library.

func HasSurfRefSetArray

func HasSurfRefSetArray() bool

HasSurfRefSetArray reports whether cuSurfRefSetArray resolved in the loaded library.

func HasTensorMapEncodeIm2col

func HasTensorMapEncodeIm2col() bool

HasTensorMapEncodeIm2col reports whether cuTensorMapEncodeIm2col resolved in the loaded library.

func HasTensorMapEncodeIm2colWide

func HasTensorMapEncodeIm2colWide() bool

HasTensorMapEncodeIm2colWide reports whether cuTensorMapEncodeIm2colWide resolved in the loaded library.

func HasTensorMapEncodeTiled

func HasTensorMapEncodeTiled() bool

HasTensorMapEncodeTiled reports whether cuTensorMapEncodeTiled resolved in the loaded library.

func HasTensorMapReplaceAddress

func HasTensorMapReplaceAddress() bool

HasTensorMapReplaceAddress reports whether cuTensorMapReplaceAddress resolved in the loaded library.

func HasTensorMapSetAllocationClass

func HasTensorMapSetAllocationClass() bool

HasTensorMapSetAllocationClass reports whether cuTensorMapSetAllocationClass resolved in the loaded library.

func HasTexObjectCreate

func HasTexObjectCreate() bool

HasTexObjectCreate reports whether cuTexObjectCreate resolved in the loaded library.

func HasTexObjectDestroy

func HasTexObjectDestroy() bool

HasTexObjectDestroy reports whether cuTexObjectDestroy resolved in the loaded library.

func HasTexObjectGetResourceDesc

func HasTexObjectGetResourceDesc() bool

HasTexObjectGetResourceDesc reports whether cuTexObjectGetResourceDesc resolved in the loaded library.

func HasTexObjectGetResourceViewDesc

func HasTexObjectGetResourceViewDesc() bool

HasTexObjectGetResourceViewDesc reports whether cuTexObjectGetResourceViewDesc resolved in the loaded library.

func HasTexObjectGetTextureDesc

func HasTexObjectGetTextureDesc() bool

HasTexObjectGetTextureDesc reports whether cuTexObjectGetTextureDesc resolved in the loaded library.

func HasTexRefCreate

func HasTexRefCreate() bool

HasTexRefCreate reports whether cuTexRefCreate resolved in the loaded library.

func HasTexRefDestroy

func HasTexRefDestroy() bool

HasTexRefDestroy reports whether cuTexRefDestroy resolved in the loaded library.

func HasTexRefGetAddress

func HasTexRefGetAddress() bool

HasTexRefGetAddress reports whether cuTexRefGetAddress_v2 resolved in the loaded library.

func HasTexRefGetAddressMode

func HasTexRefGetAddressMode() bool

HasTexRefGetAddressMode reports whether cuTexRefGetAddressMode resolved in the loaded library.

func HasTexRefGetArray

func HasTexRefGetArray() bool

HasTexRefGetArray reports whether cuTexRefGetArray resolved in the loaded library.

func HasTexRefGetBorderColor

func HasTexRefGetBorderColor() bool

HasTexRefGetBorderColor reports whether cuTexRefGetBorderColor resolved in the loaded library.

func HasTexRefGetFilterMode

func HasTexRefGetFilterMode() bool

HasTexRefGetFilterMode reports whether cuTexRefGetFilterMode resolved in the loaded library.

func HasTexRefGetFlags

func HasTexRefGetFlags() bool

HasTexRefGetFlags reports whether cuTexRefGetFlags resolved in the loaded library.

func HasTexRefGetFormat

func HasTexRefGetFormat() bool

HasTexRefGetFormat reports whether cuTexRefGetFormat resolved in the loaded library.

func HasTexRefGetMaxAnisotropy

func HasTexRefGetMaxAnisotropy() bool

HasTexRefGetMaxAnisotropy reports whether cuTexRefGetMaxAnisotropy resolved in the loaded library.

func HasTexRefGetMipmapFilterMode

func HasTexRefGetMipmapFilterMode() bool

HasTexRefGetMipmapFilterMode reports whether cuTexRefGetMipmapFilterMode resolved in the loaded library.

func HasTexRefGetMipmapLevelBias

func HasTexRefGetMipmapLevelBias() bool

HasTexRefGetMipmapLevelBias reports whether cuTexRefGetMipmapLevelBias resolved in the loaded library.

func HasTexRefGetMipmapLevelClamp

func HasTexRefGetMipmapLevelClamp() bool

HasTexRefGetMipmapLevelClamp reports whether cuTexRefGetMipmapLevelClamp resolved in the loaded library.

func HasTexRefGetMipmappedArray

func HasTexRefGetMipmappedArray() bool

HasTexRefGetMipmappedArray reports whether cuTexRefGetMipmappedArray resolved in the loaded library.

func HasTexRefSetAddress

func HasTexRefSetAddress() bool

HasTexRefSetAddress reports whether cuTexRefSetAddress_v2 resolved in the loaded library.

func HasTexRefSetAddress2D

func HasTexRefSetAddress2D() bool

HasTexRefSetAddress2D reports whether cuTexRefSetAddress2D_v3 resolved in the loaded library.

func HasTexRefSetAddressMode

func HasTexRefSetAddressMode() bool

HasTexRefSetAddressMode reports whether cuTexRefSetAddressMode resolved in the loaded library.

func HasTexRefSetArray

func HasTexRefSetArray() bool

HasTexRefSetArray reports whether cuTexRefSetArray resolved in the loaded library.

func HasTexRefSetBorderColor

func HasTexRefSetBorderColor() bool

HasTexRefSetBorderColor reports whether cuTexRefSetBorderColor resolved in the loaded library.

func HasTexRefSetFilterMode

func HasTexRefSetFilterMode() bool

HasTexRefSetFilterMode reports whether cuTexRefSetFilterMode resolved in the loaded library.

func HasTexRefSetFlags

func HasTexRefSetFlags() bool

HasTexRefSetFlags reports whether cuTexRefSetFlags resolved in the loaded library.

func HasTexRefSetFormat

func HasTexRefSetFormat() bool

HasTexRefSetFormat reports whether cuTexRefSetFormat resolved in the loaded library.

func HasTexRefSetMaxAnisotropy

func HasTexRefSetMaxAnisotropy() bool

HasTexRefSetMaxAnisotropy reports whether cuTexRefSetMaxAnisotropy resolved in the loaded library.

func HasTexRefSetMipmapFilterMode

func HasTexRefSetMipmapFilterMode() bool

HasTexRefSetMipmapFilterMode reports whether cuTexRefSetMipmapFilterMode resolved in the loaded library.

func HasTexRefSetMipmapLevelBias

func HasTexRefSetMipmapLevelBias() bool

HasTexRefSetMipmapLevelBias reports whether cuTexRefSetMipmapLevelBias resolved in the loaded library.

func HasTexRefSetMipmapLevelClamp

func HasTexRefSetMipmapLevelClamp() bool

HasTexRefSetMipmapLevelClamp reports whether cuTexRefSetMipmapLevelClamp resolved in the loaded library.

func HasTexRefSetMipmappedArray

func HasTexRefSetMipmappedArray() bool

HasTexRefSetMipmappedArray reports whether cuTexRefSetMipmappedArray resolved in the loaded library.

func HasThreadExchangeStreamCaptureMode

func HasThreadExchangeStreamCaptureMode() bool

HasThreadExchangeStreamCaptureMode reports whether cuThreadExchangeStreamCaptureMode resolved in the loaded library.

func HasUserObjectCreate

func HasUserObjectCreate() bool

HasUserObjectCreate reports whether cuUserObjectCreate resolved in the loaded library.

func HasUserObjectRelease

func HasUserObjectRelease() bool

HasUserObjectRelease reports whether cuUserObjectRelease resolved in the loaded library.

func HasUserObjectRetain

func HasUserObjectRetain() bool

HasUserObjectRetain reports whether cuUserObjectRetain resolved in the loaded library.

func HasWaitExternalSemaphoresAsync

func HasWaitExternalSemaphoresAsync() bool

HasWaitExternalSemaphoresAsync reports whether cuWaitExternalSemaphoresAsync resolved in the loaded library.

func Init

func Init(flags uint32) error

Init initializes the CUDA driver API Initializes the driver API and must be called before any other function from the driver API in the current process.

Currently, the Flags parameter must be 0. If Init has not been called, any function from the driver API will return ErrNotInitialized.

Note: Init preloads various libraries needed for JIT compilation. To opt-out of this behavior, set the environment variable CUDA_FORCE_PRELOAD_LIBRARIES=0. CUDA will lazily load JIT libraries as needed. To disable JIT entirely, set the environment variable CUDA_DISABLE_JIT=1.

  • flags: Initialization flag for CUDA

Errors:

Wraps cuInit.

func LaunchCooperativeKernelMultiDevice deprecated

func LaunchCooperativeKernelMultiDevice(launchParamsList *LaunchParams, numDevices uint32, flags uint32) error

LaunchCooperativeKernelMultiDevice launches CUDA functions on multiple devices where thread blocks can cooperate and synchronize as they execute.

Invokes kernels as specified in the launchParamsList array where each element of the array specifies all the parameters required to perform a single kernel launch. These kernels can cooperate and synchronize as they execute. The size of the array is specified by numDevices. No two kernels can be launched on the same device. All the devices targeted by this multi-device launch must be identical. All devices must have a non-zero value for the device attribute DevAttrCooperativeMultiDeviceLaunch. All kernels launched must be identical with respect to the compiled code. Note that any device, constant or managed variables present in the module that owns the kernel launched on each device, are independently instantiated on every device. It is the application’s responsibility to ensure these variables are initialized and used appropriately. The size of the grids as specified in blocks, the size of the blocks themselves and the amount of shared memory used by each thread block must also match across all launched kernels. The streams used to launch these kernels must have been created via either NewStream or StreamCreateWithPriority. The NULL stream or CU_STREAM_LEGACY or CU_STREAM_PER_THREAD cannot be used. The total number of blocks launched per kernel cannot exceed the maximum number of blocks per multiprocessor as returned by Function.MaxActiveBlocksPerMultiprocessor (or Function.MaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors as specified by the device attribute DevAttrMultiprocessorCount. Since the total number of blocks launched per device has to match across all devices, the maximum number of blocks that can be launched per device will be limited by the device with the least number of multiprocessors. The kernels cannot make use of CUDA dynamic parallelism.

  • LaunchParams.function specifies the kernel to be launched. All functions must be identical with respect to the compiled code. Note that you can also specify context-less kernel Kernel by querying the handle using Library.Kernel and then casting to Function. In this case, the context to launch the kernel on be taken from the specified stream LaunchParams.hStream.
  • LaunchParams.gridDimX is the width of the grid in blocks. This must match across all kernels launched.
  • LaunchParams.gridDimY is the height of the grid in blocks. This must match across all kernels launched.
  • LaunchParams.gridDimZ is the depth of the grid in blocks. This must match across all kernels launched.
  • LaunchParams.blockDimX is the X dimension of each thread block. This must match across all kernels launched.
  • LaunchParams.blockDimX is the Y dimension of each thread block. This must match across all kernels launched.
  • LaunchParams.blockDimZ is the Z dimension of each thread block. This must match across all kernels launched.
  • LaunchParams.sharedMemBytes is the dynamic shared-memory size per thread block in bytes. This must match across all kernels launched.
  • LaunchParams.hStream is the handle to the stream to perform the launch in. This cannot be the NULL stream or CU_STREAM_LEGACY or CU_STREAM_PER_THREAD. The CUDA context associated with this stream must match that associated with LaunchParams.function.
  • LaunchParams.kernelParams is an array of pointers to kernel parameters. If LaunchParams.function has N parameters, then LaunchParams.kernelParams needs to be an array of N pointers. Each of LaunchParams.kernelParams[0] through LaunchParams.kernelParams[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel’s image.

By default, the kernel won’t begin execution on any GPU until all prior work in all the specified streams has completed. This behavior can be overridden by specifying the flag CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC. When this flag is specified, each kernel will only wait for prior work in the stream corresponding to that GPU to complete before it begins execution. Similarly, by default, any subsequent work pushed in any of the specified streams will not begin execution until the kernels on all GPUs have completed. This behavior can be overridden by specifying the flag CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC. When this flag is specified, any subsequent work pushed in any of the specified streams will only wait for the kernel launched on the GPU corresponding to that stream to complete before it begins execution. Calling LaunchCooperativeKernelMultiDevice sets persistent function state that is the same as function state set through Function.LaunchKernel API when called individually for each element in launchParamsList. When kernels are launched via LaunchCooperativeKernelMultiDevice, the previous block shape, shared size and parameter info associated with each LaunchParams.function in launchParamsList is overwritten. Note that to use LaunchCooperativeKernelMultiDevice, the kernels must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then LaunchCooperativeKernelMultiDevice will return ErrInvalidImage.

Note: This function uses standard default stream semantics.

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.Attribute, Function.LaunchCooperativeKernel, cudaLaunchCooperativeKernelMultiDevice

  • launchParamsList: List of launch parameters, one per device
  • numDevices: Size of the launchParamsList array
  • flags: Flags to control launch behavior

Errors:

Wraps cuLaunchCooperativeKernelMultiDevice.

Deprecated: Deprecated in CUDA 11.3. Use LaunchCooperativeKernelMultiDevice instead.

func Load

func Load(path string) error

Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.

Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.

func Loaded

func Loaded() bool

Loaded reports whether the library is currently loaded. It does not trigger a load.

func LogicalEndpointCreate

func LogicalEndpointCreate(leId LogicalEndpointId, prop *LogicalEndpointProp) error

LogicalEndpointCreate creates a logical endpoint with the requested properties and associates it with the logical endpoint id.

This creates a logical endpoint as described by prop. The number of participating devices is determined by the LogicalEndpointProp.type. If the type is LogicalEndpointTypeUnicast then LogicalEndpointProp.unicast.device specifies the owner device of the unicast logical endpoint. If the type is LogicalEndpointTypeMulticast then LogicalEndpointProp.multicast.numDevices specifies the number of devices in the multicast logical endpoint team. Devices can be added to a multicast logical endpoint via Device.LogicalEndpointAdd. After all the participating devices have been added, a call to LogicalEndpointQuery must be made to ensure that the logical endpoint is ready for memory binding and access. A unicast logical endpoint does not have a notion of adding devices via Device.LogicalEndpointAdd. However, a call to LogicalEndpointQuery must still be made to ensure that the logical endpoint is ready for memory binding and access. Memory is bound to the logical endpoint via either Device.LogicalEndpointBindAddr or Device.LogicalEndpointBindMem, and can be unbound via Device.LogicalEndpointUnbind. The total amount of memory that can be bound per device is specified by LogicalEndpointProp.size. This size must be a multiple of the value for bindAlignment as returned by LogicalEndpointGetLimits. The maximum size for the logical endpoint cannot exceed the value for maxSize as returned by LogicalEndpointGetLimits. The bind alignment and maximum size depend on the properties of the logical endpoint.

See also: LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointCreate.

  • leId: Logical endpoint id that will be associated with the newly created logical endpoint
  • prop: Properties of the logical endpoint to create

Errors:

Wraps cuLogicalEndpointCreate.

func LogicalEndpointDestroy

func LogicalEndpointDestroy(leId LogicalEndpointId) error

LogicalEndpointDestroy removes the association of the logical endpoint from the logical endpoint id.

Removes the association between the logical endpoint id and the logical endpoint resources. Any memory bound by this process to any device associated with the logical endpoint will be unbound. If this was the last reference to the logical endpoint, all associated resources will be destroyed.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointDestroy.

  • leId: Logical endpoint id of the logical endpoint to be destroyed

Errors:

Wraps cuLogicalEndpointDestroy.

func LogicalEndpointExport

func LogicalEndpointExport(handle uintptr, leId LogicalEndpointId, handleType LogicalEndpointIpcHandleType) error

LogicalEndpointExport exports a logical endpoint associated with leId to an IPC handle.

Given a logical endpoint id leId, create a shareable handle handle that can be used to share the logical endpoint with other processes. The recipient process can convert the shareable handle back into a logical endpoint id using LogicalEndpointImport. The implementation of what this handle is and how it can be transfered is defined by the requested handle type in handletype.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointExport.

  • handle: Pointer to the location in which to store the requested handle type
  • leId: Logical endpoint id of logical endpoint
  • handleType: Type of shareable handle requested. Defines type and size of the handle output parameter

Errors:

Wraps cuLogicalEndpointExport.

func LogicalEndpointGetLimits

func LogicalEndpointGetLimits(prop *LogicalEndpointProp) (bindAlignment uint64, maxSize uint64, err error)

LogicalEndpointGetLimits calculates the minimum alignment and the maximum size for the given logical endpoint properties.

The bindAlignment can be used as a multiple for size and bind offset values. The maxSize is the maximum size of the logical endpoint. If maxSize is less than LogicalEndpointProp:size the user must adjust the request to the smaller value.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointGetLimits.

  • bindAlignment: Minimum alignment granularity of the proposed logical endpoint
  • maxSize: Maximum size of the logical endpoint
  • prop: Properties of the logical endpoint

Errors:

Wraps cuLogicalEndpointGetLimits.

func LogicalEndpointIdRelease

func LogicalEndpointIdRelease(baseLeId LogicalEndpointId, count uint32) error

LogicalEndpointIdRelease releases a range of logical endpoint ids.

Releases up to count logical endpoint ids starting at baseLeId. The range of ids represented by [ baseLeId, baseLeId + count) must all be previously reserved. All logical endpoints in the range must be destroyed before they can be released.

See also: LogicalEndpointCreate, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointIdRelease.

  • baseLeId: First logical endpoint id to be released back to the system
  • count: Number of logical endpoint ids to release back to the system

Errors:

Wraps cuLogicalEndpointIdRelease.

func LogicalEndpointImport

func LogicalEndpointImport(leId LogicalEndpointId, handle uintptr, handleType LogicalEndpointIpcHandleType) error

LogicalEndpointImport imports a logical endpoint from the given IPC handle and associates it with a logical endpoint id.

Imports a logical endpoint from the given IPC handle and associates it with the logical endpoint id specified by leId. If the current process cannot support the logical endpoint described by the shareable handle, this API will error as ErrNotSupported. If handle is of type LogicalEndpointIpcHandleTypeFabric and the importer process does not have access permissions, then ErrNotPermitted will be returned

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointImport.

  • leId: Logical endpoint id that will be used to access the exported logical endpoint
  • handle: Shareable handle representing the logical endpoint that is to be imported
  • handleType: Handle type of the exported handle

Errors:

Wraps cuLogicalEndpointImport.

func LogicalEndpointQuery

func LogicalEndpointQuery(leId LogicalEndpointId, count uint32) (int32, error)

LogicalEndpointQuery determines if all logical endpoints in the range have been successfully constructed.

Queries the driver to determine if all logical endpoints in the given range starting at leId and extending for count have been successfully constructed. Provides a mechanism to ensure that it is safe to begin using a logical endpoint ID. Using a logical endpoint ID before verifying that it is fully constructed can result in undefined behavior. This is not a blocking API, it returns immediately with a queryStatus of 0 if any logical endpoint ID in the given range is not fully constructed, and a non-zero value otherwise. Construction of a multicast logical endpoint may fail here if the devices added via Device.LogicalEndpointAdd do not belong to the same clique. This API may return ErrIllegalState if no devices are found on which this logical endpoint can be accessed.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointQuery.

  • leId: First logical endpoint ID to be queried
  • count: Number of logical endpoints IDs to be queried

Errors:

Wraps cuLogicalEndpointQuery.

func LogsCurrent

func LogsCurrent(flags uint32) (uint32, error)

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

Requires CUDA 12.9 (driver r575) or later; see HasLogsCurrent.

  • flags: Reserved for future use, must be 0

Errors:

Wraps cuLogsCurrent.

func LogsDumpToFile

func LogsDumpToFile(iterator *uint32, pathToFile string, flags uint32) error

LogsDumpToFile dumps accumulated driver logs into a file.

Logs generated by the driver are stored in an internal buffer and can be copied out using this API. This API dumps all driver logs starting from iterator into pathToFile provided.

Note: iterator is auto-advancing. Dumping logs will update the value of iterator to receive the next generated log.

Note: The driver reserves limited memory for storing logs. The oldest logs may be overwritten and become unrecoverable. An indication will appear in the destination outupt if the logs have been truncated. Call dump after each failed API to mitigate this risk.

Requires CUDA 12.9 (driver r575) or later; see HasLogsDumpToFile.

  • iterator: Optional auto-advancing iterator specifying the starting log to read. NULL value dumps all logs
  • pathToFile: Path to output file for dumping logs
  • flags: Reserved for future use, must be 0

Errors:

Wraps cuLogsDumpToFile.

func LogsDumpToMemory

func LogsDumpToMemory(iterator *uint32, buffer *byte, size *uint, flags uint32) error

LogsDumpToMemory dumps accumulated driver logs into a buffer.

Logs generated by the driver are stored in an internal buffer and can be copied out using this API. This API dumps driver logs from iterator into buffer up to the size specified in *size. The driver will always null terminate the buffer but there will not be a null character between log entries, only a newline n. The driver will then return the actual number of bytes written in *size, excluding the null terminator. If there are no messages to dump, *size will be set to 0 and the function will return Success. If the provided buffer is not large enough to hold any messages, *size will be set to 0 and the function will return ErrInvalidValue.

Note: iterator is auto-advancing. Dumping logs will update the value of iterator to receive the next generated log.

Note: The driver reserves limited memory for storing logs. The maximum size of the buffer is 25600 bytes. The oldest logs may be overwritten and become unrecoverable. An indication will appear in the destination outupt if the logs have been truncated. Call dump after each failed API to mitigate this risk.

Note: If the provided value in *size is not large enough to hold all buffered messages, a message will be added at the head of the buffer indicating this. The driver then computes the number of messages it is able to store in buffer and writes it out. The final message in buffer will always be the most recent log message as of when the API is called.

Requires CUDA 12.9 (driver r575) or later; see HasLogsDumpToMemory.

  • iterator: Optional auto-advancing iterator specifying the starting log to read. NULL value dumps all logs
  • buffer: Pointer to dump logs
  • size: See description
  • flags: Reserved for future use, must be 0

Errors:

Wraps cuLogsDumpToMemory.

func MemAllocHost

func MemAllocHost(pp *uintptr, bytesize uint) error

MemAllocHost allocates page-locked host memory.

Allocates bytesize 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 DevicePtr.Memcpy. 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 as malloc(). On systems where DevAttrPageableMemoryAccessUsesHostPageTables is true, MemAllocHost may not page-lock the allocated memory. Page-locking excessive amounts of memory with MemAllocHost 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. Note all host memory allocated using MemAllocHost will automatically be immediately accessible to all contexts on all devices which support unified addressing (as may be queried using DevAttrUnifiedAddressing). The device pointer that may be used to access this host memory from those contexts is always equal to the returned host pointer *pp. See Unified Addressing for additional details.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMallocHost

  • pp: Returned pointer to host memory
  • bytesize: Requested allocation size in bytes

Errors:

Wraps cuMemAllocHost, bound as cuMemAllocHost_v2.

func MemCreate

func MemCreate(size uint, prop *MemAllocationProp, flags uint64) (uint64, error)

MemCreate creates a CUDA memory handle representing a memory allocation of a given size described by the given properties.

This creates a memory allocation on the target device specified through the prop structure. The created allocation will not have any device or host mappings. The generic memory handle for the allocation can be mapped to the address space of calling process via DevicePtr.MemMap. This handle cannot be transmitted directly to other processes (see MemExportToShareableHandle). On Windows, the caller must also pass an LPSECURITYATTRIBUTE in prop to be associated with this handle which limits or allows access to this handle for a recipient process (see MemAllocationProp.win32HandleMetaData for more). The size of this allocation must be a multiple of the the value given via MemGetAllocationGranularity with the MemAllocGranularityMinimum flag. To create a CPU allocation that doesn’t target any specific NUMA nodes, applications must set MemAllocationProp.MemLocation.type to MemLocationTypeHost. MemAllocationProp.MemLocation.id is ignored for HOST allocations. HOST allocations are not IPC capable and MemAllocationProp.requestedHandleTypes must be 0, any other value will result in ErrInvalidValue. To create a CPU allocation targeting a specific host NUMA node, applications must set MemAllocationProp.MemLocation.type to MemLocationTypeHostNuma and MemAllocationProp.MemLocation.id must specify the NUMA ID of the CPU. On systems where NUMA is not available MemAllocationProp.MemLocation.id must be set to 0. Specifying MemLocationTypeHostNumaCurrent as the MemLocation.type will result in ErrInvalidValue. Specifying MemLocationTypeDeviceLocalityDomain as the MemLocation.type will localize the allocation to the specified locality domain. MemAllocationProp.MemLocation.localized.deviceId must specify the device ID. MemAllocationProp.MemLocation.localized.localityDomainId must specify the locality domain ID. The locality domain ID must be a valid locality domain ID for the specified device. See also Device.Attribute with the attribute DevAttrLocalityDomainCount. Applications that intend to use MemHandleTypeFabric based memory sharing must ensure: (1) nvidia-caps-imex-channels character device is created by the driver and is listed under /proc/devices (2) have at least one IMEX channel file accessible by the user launching the application. When exporter and importer CUDA processes have been granted access to the same IMEX channel, they can securely share memory. The IMEX channel security model works on a per user basis. Which means all processes under a user can share memory if the user has access to a valid IMEX channel. When multi-user isolation is desired, a separate IMEX channel is required for each user. These channel files exist in /dev/nvidia-caps-imex-channels/channel* and can be created using standard OS native calls like mknod on Linux. For example: To create channel0 with the major number from /proc/devices users can execute the following command: mknod /dev/nvidia-caps-imex-channels/channel0 c <major number> 0 If MemAllocationProp.allocFlags.usage contains CU_MEM_CREATE_USAGE_TILE_POOL flag then the memory allocation is intended only to be used as backing tile pool for sparse CUDA arrays and sparse CUDA mipmapped arrays. (see Stream.MemMapArrayAsync).

Note: On devices with a single locality domain, MemLocationTypeDeviceLocalityDomain and localityDomainId 0 is equivalent to a full-device allocation created with MemLocationTypeDevice. The resulting allocation will be of type MemLocationTypeDevice.

See also: MemRelease, MemExportToShareableHandle, MemImportFromShareableHandle

  • size: Size of the allocation requested
  • prop: Properties of the allocation to create
  • flags: flags for future use, must be zero now

Errors:

Wraps cuMemCreate.

func MemExportToShareableHandle

func MemExportToShareableHandle(shareableHandle unsafe.Pointer, handle uint64, handleType MemAllocationHandleType, flags uint64) error

MemExportToShareableHandle exports an allocation to a requested shareable handle type.

Given a CUDA memory handle, create a shareable memory allocation handle that can be used to share the memory with other processes. The recipient process can convert the shareable handle back into a CUDA memory handle using MemImportFromShareableHandle and map it with DevicePtr.MemMap. The implementation of what this handle is and how it can be transferred is defined by the requested handle type in handleType Once all shareable handles are closed and the allocation is released, the allocated memory referenced will be released back to the OS and uses of the CUDA handle afterward will lead to undefined behavior. This API can also be used in conjunction with other APIs (e.g. Vulkan, OpenGL) that support importing memory from the shareable type

See also: MemImportFromShareableHandle

  • shareableHandle: Pointer to the location in which to store the requested handle type
  • handle: CUDA handle for the memory allocation
  • handleType: Type of shareable handle requested (defines type and size of the shareableHandle output parameter)
  • flags: Reserved, must be zero

Errors:

Wraps cuMemExportToShareableHandle.

func MemGetAllocationGranularity

func MemGetAllocationGranularity(prop *MemAllocationProp, option MemallocationgranularityFlags) (uint, error)

MemGetAllocationGranularity calculates either the minimal or recommended granularity.

Calculates either the minimal or recommended granularity for a given allocation specification and returns it. This granularity can be used as a multiple for alignment, size, or address mapping.

See also: MemCreate, DevicePtr.MemMap

  • prop: Property for which to determine the granularity for
  • option: Determines which granularity to return

Errors:

Wraps cuMemGetAllocationGranularity.

func MemGetInfo

func MemGetInfo() (free uint, total uint, err error)

MemGetInfo gets free and total 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.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemGetInfo

  • free: Returned free memory in bytes
  • total: Returned total memory in bytes

Errors:

Wraps cuMemGetInfo, bound as cuMemGetInfo_v2.

func MemHostAlloc

func MemHostAlloc(pp *uintptr, bytesize uint, flags uint32) error

MemHostAlloc allocates page-locked host memory.

Allocates bytesize 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 DevicePtr.CopyFromHost. 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 as malloc(). On systems where DevAttrPageableMemoryAccessUsesHostPageTables is true, MemHostAlloc may not page-lock the allocated memory. 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 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.

  • CU_MEMHOSTALLOC_PORTABLE: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation.
  • CU_MEMHOSTALLOC_DEVICEMAP: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by calling MemHostGetDevicePointer.
  • CU_MEMHOSTALLOC_WRITECOMBINED: 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 GPU 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. The CU_MEMHOSTALLOC_DEVICEMAP flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred to MemHostGetDevicePointer because the memory may be mapped into other CUDA contexts via the CU_MEMHOSTALLOC_PORTABLE flag. The memory allocated by this function must be freed with MemFreeHost. Note all host memory allocated using MemHostAlloc will automatically be immediately accessible to all contexts on all devices which support unified addressing (as may be queried using DevAttrUnifiedAddressing). Unless the flag CU_MEMHOSTALLOC_WRITECOMBINED is specified, the device pointer that may be used to access this host memory from those contexts is always equal to the returned host pointer *pp. If the flag CU_MEMHOSTALLOC_WRITECOMBINED is specified, then the function MemHostGetDevicePointer must be used to query the device pointer, even if the context supports unified addressing. See Unified Addressing for additional details.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaHostAlloc

  • pp: Returned pointer to host memory
  • bytesize: Requested allocation size in bytes
  • flags: Flags for allocation request

Errors:

Wraps cuMemHostAlloc.

func MemHostGetFlags

func MemHostGetFlags(p uintptr) (uint32, error)

MemHostGetFlags passes back flags that were used for a pinned allocation.

Passes back the flags pFlags that were specified when allocating the pinned host buffer p allocated by MemHostAlloc. MemHostGetFlags will fail if the pointer does not reside in an allocation performed by MemAllocHost or MemHostAlloc.

See also: MemAllocHost, MemHostAlloc, cudaHostGetFlags

  • p: Host pointer

Errors:

Wraps cuMemHostGetFlags.

func MemHostRegister

func MemHostRegister(p uintptr, bytesize uint, flags uint32) error

MemHostRegister registers an existing host memory range for use by CUDA.

Page-locks the memory range specified by p and bytesize and maps it for the device(s) as specified by Flags. This memory range also is added to the same tracking mechanism as MemHostAlloc to automatically accelerate calls to functions such as DevicePtr.CopyFromHost. 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 DevAttrPageableMemoryAccessUsesHostPageTables is true, MemHostRegister will not page-lock the memory range specified by ptr but only populate unpopulated pages. The Flags parameter enables different options to be specified that affect the allocation, as follows.

  • CU_MEMHOSTREGISTER_PORTABLE: The memory returned by this call will be considered as pinned memory by all CUDA contexts, not just the one that performed the allocation.
  • CU_MEMHOSTREGISTER_DEVICEMAP: Maps the allocation into the CUDA address space. The device pointer to the memory may be obtained by calling MemHostGetDevicePointer.
  • CU_MEMHOSTREGISTER_IOMEMORY: The pointer is treated as pointing to some I/O memory space, e.g. the PCI Express resource of a 3rd party device.
  • CU_MEMHOSTREGISTER_READ_ONLY: The pointer is treated as pointing to memory that is considered read-only by the device. On platforms without DevAttrPageableMemoryAccessUsesHostPageTables, 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 DevAttrReadOnlyHostRegisterSupported. Using this flag with a current context associated with a device that does not have this attribute set will cause MemHostRegister to error with ErrNotSupported.

All of these flags are orthogonal to one another: a developer may page-lock memory that is portable or mapped with no restrictions. The CU_MEMHOSTREGISTER_DEVICEMAP flag may be specified on CUDA contexts for devices that do not support mapped pinned memory. The failure is deferred to MemHostGetDevicePointer because the memory may be mapped into other CUDA contexts via the CU_MEMHOSTREGISTER_PORTABLE flag. For devices that have a non-zero value for the device attribute DevAttrCanUseHostPointerForRegisteredMem, the memory can also be accessed from the device using the host pointer p. The device pointer returned by MemHostGetDevicePointer 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 by MemHostGetDevicePointer 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 by MemHostGetDevicePointer 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 MemHostUnregister.

See also: MemHostUnregister, MemHostGetFlags, MemHostGetDevicePointer, cudaHostRegister

  • p: Host pointer to memory to page-lock
  • bytesize: Size in bytes of the address range to page-lock
  • flags: Flags for allocation request

Errors:

Wraps cuMemHostRegister, bound as cuMemHostRegister_v2.

func MemHostUnregister

func MemHostUnregister(p uintptr) error

MemHostUnregister unregisters a memory range that was registered with MemHostRegister.

Unmaps the memory range whose base address is specified by p, and makes it pageable again. The base address must be the same one specified to MemHostRegister.

See also: MemHostRegister, cudaHostUnregister

  • p: Host pointer to memory to unregister

Errors:

Wraps cuMemHostUnregister.

func MemImportFromShareableHandle

func MemImportFromShareableHandle(osHandle uintptr, shHandleType MemAllocationHandleType) (uint64, error)

MemImportFromShareableHandle imports an allocation from a requested shareable handle type.

If the current process cannot support the memory described by this shareable handle, this API will error as ErrNotSupported. If shHandleType is MemHandleTypeFabric and the importer process has not been granted access to the same IMEX channel as the exporter process, this API will error as ErrNotPermitted.

Note: Importing shareable handles exported from some graphics APIs(VUlkan, OpenGL, etc) created on devices under an SLI group may not be supported, and thus this API will return ErrNotSupported. There is no guarantee that the contents of handle will be the same CUDA memory handle for the same given OS shareable handle, or the same underlying allocation.

See also: MemExportToShareableHandle, DevicePtr.MemMap, MemRelease

  • osHandle: Shareable Handle representing the memory allocation that is to be imported
  • shHandleType: handle type of the exported handle MemAllocationHandleType

Errors:

Wraps cuMemImportFromShareableHandle.

func MemRelease

func MemRelease(handle uint64) error

MemRelease releases a memory handle representing a memory allocation which was previously allocated through MemCreate.

Frees the memory that was allocated on a device through MemCreate. The memory allocation will be freed when all outstanding mappings to the memory are unmapped and when all outstanding references to the handle (including it’s shareable counterparts) are also released. The generic memory handle can be freed when there are still outstanding mappings made with this handle. Each time a recipient process imports a shareable handle, it needs to pair it with MemRelease for the handle to be freed. If handle is not a valid handle the behavior is undefined.

See also: MemCreate

  • handle: Value of handle which was returned previously by MemCreate

Errors:

Wraps cuMemRelease.

func MemRetainAllocationHandle

func MemRetainAllocationHandle(addr uintptr) (uint64, error)

MemRetainAllocationHandle returns the allocation handle of the memory mapped at addr.

Given an address addr, returns the allocation handle of the backing memory allocation.

The handle is guaranteed to be the same handle value used to map the memory. If the address requested is not mapped, the function will fail. The returned handle must be released with corresponding number of calls to MemRelease.

Note: The address addr, can be any address in a range previously mapped by DevicePtr.MemMap, and not necessarily the start address.

See also: MemCreate, MemRelease, DevicePtr.MemMap

  • addr: Memory address to query, that has been mapped previously

Errors:

Wraps cuMemRetainAllocationHandle.

func Memcpy2D

func Memcpy2D(pCopy *Memcpy2d) error

Memcpy2D copies memory for 2D arrays.

Perform a 2D memory copy according to the parameters specified in pCopy.

  • srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively.
  • srcXInBytes and srcY specify the base address of the source data for the copy.

If srcMemoryType is MemoryTypeUnified, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. If srcMemoryType is MemoryTypeHost, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeDevice, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeArray, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. If dstMemoryType is MemoryTypeHost, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeUnified, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. If dstMemoryType is MemoryTypeDevice, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeArray, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored.

  • dstXInBytes and dstY specify the base address of the destination data for the copy.

For host pointers, the starting address is

void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes);

For device pointers, the starting address is

CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes;

For CUDA arrays, srcXInBytes must be evenly divisible by the array element size.

  • WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.

For host pointers, the base address is

void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes);

For device pointers, the starting address is

CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes;

For CUDA arrays, dstXInBytes must be evenly divisible by the array element size.

Memcpy2D returns an error if any pitch is greater than the maximum allowed ( DevAttrMaxPitch). MemAllocPitch passes back pitches that always work with Memcpy2D. On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), Memcpy2D may fail for pitches not computed by MemAllocPitch. Memcpy2DUnaligned does not have this restriction, but may run significantly slower in the cases where Memcpy2D would have returned an error code.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy2D, cudaMemcpy2DToArray, cudaMemcpy2DFromArray

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy2D, bound as cuMemcpy2D_v2.

func Memcpy2DUnaligned

func Memcpy2DUnaligned(pCopy *Memcpy2d) error

Memcpy2DUnaligned copies memory for 2D arrays.

Perform a 2D memory copy according to the parameters specified in pCopy.

  • srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively.
  • srcXInBytes and srcY specify the base address of the source data for the copy.

If srcMemoryType is MemoryTypeUnified, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. If srcMemoryType is MemoryTypeHost, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeDevice, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeArray, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. If dstMemoryType is MemoryTypeUnified, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. If dstMemoryType is MemoryTypeHost, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeDevice, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeArray, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored.

  • dstXInBytes and dstY specify the base address of the destination data for the copy.

For host pointers, the starting address is

void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes);

For device pointers, the starting address is

CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes;

For CUDA arrays, srcXInBytes must be evenly divisible by the array element size.

  • WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.

For host pointers, the base address is

void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes);

For device pointers, the starting address is

CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes;

For CUDA arrays, dstXInBytes must be evenly divisible by the array element size.

Memcpy2D returns an error if any pitch is greater than the maximum allowed ( DevAttrMaxPitch). MemAllocPitch passes back pitches that always work with Memcpy2D. On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), Memcpy2D may fail for pitches not computed by MemAllocPitch. Memcpy2DUnaligned does not have this restriction, but may run significantly slower in the cases where Memcpy2D would have returned an error code.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy2D, cudaMemcpy2DToArray, cudaMemcpy2DFromArray

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy2DUnaligned, bound as cuMemcpy2DUnaligned_v2.

func Memcpy3D

func Memcpy3D(pCopy *Memcpy3d) error

Memcpy3D copies memory for 3D arrays.

Perform a 3D memory copy according to the parameters specified in pCopy.

  • srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively.
  • srcXInBytes, srcY and srcZ specify the base address of the source data for the copy.

If srcMemoryType is MemoryTypeUnified, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. If srcMemoryType is MemoryTypeHost, srcHost, srcPitch and srcHeight specify the (host) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. If srcMemoryType is MemoryTypeDevice, srcDevice, srcPitch and srcHeight specify the (device) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. If srcMemoryType is MemoryTypeArray, srcArray specifies the handle of the source data. srcHost, srcDevice, srcPitch and srcHeight are ignored. If dstMemoryType is MemoryTypeUnified, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. If dstMemoryType is MemoryTypeHost, dstHost and dstPitch specify the (host) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. If dstMemoryType is MemoryTypeDevice, dstDevice and dstPitch specify the (device) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. If dstMemoryType is MemoryTypeArray, dstArray specifies the handle of the destination data. dstHost, dstDevice, dstPitch and dstHeight are ignored.

  • dstXInBytes, dstY and dstZ specify the base address of the destination data for the copy.

For host pointers, the starting address is

void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes);

For device pointers, the starting address is

CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes;

For CUDA arrays, srcXInBytes must be evenly divisible by the array element size.

  • WidthInBytes, Height and Depth specify the width (in bytes), height and depth of the 3D copy being performed.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.
  • If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height + dstY.

For host pointers, the base address is

void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes);

For device pointers, the starting address is

CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes;

For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. The srcLOD and dstLOD members of the Memcpy3d structure must be set to 0. Memcpy3D returns an error if any pitch is greater than the maximum allowed ( DevAttrMaxPitch).

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy3D

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy3D, bound as cuMemcpy3D_v2.

func Memcpy3DPeer

func Memcpy3DPeer(pCopy *Memcpy3dPeer) error

Memcpy3DPeer copies memory between contexts.

Perform a 3D memory copy according to the parameters specified in pCopy. See the definition of the Memcpy3dPeer structure for documentation of its parameters.

Note: This function exhibits synchronous behavior for most use cases.

See also: DevicePtr.CopyFromDevice, DevicePtr.CopyFromPeer, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyFromPeerAsync, Stream.Memcpy3DPeerAsync, cudaMemcpy3DPeer

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy3DPeer.

func MulticastBindMem

func MulticastBindMem(mcHandle uint64, mcOffset uint, memHandle uint64, memOffset uint, size uint, flags uint64) error

MulticastBindMem binds a memory allocation represented by a handle to a multicast object.

Binds a memory allocation specified by memHandle and created via MemCreate to a multicast object represented by mcHandle and created via MulticastCreate. The intended size of the bind, the offset in the multicast range mcOffset as well as the offset in the memory memOffset must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memOffset should be aligned to the granularity of the memory allocation(see MemGetAllocationGranularity) or to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memOffset may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. Also note that the ability to accept a memOffset that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull The memory allocation must have beeen created on one of the devices that was added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate, Device.MulticastBindMemV2

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into the multicast object for attachment
  • memHandle: Handle representing a memory allocation
  • memOffset: Offset into the memory for attachment
  • size: Size of the memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero for now

Errors:

Wraps cuMulticastBindMem.

func MulticastBindMemV1

func MulticastBindMemV1(mcHandle uint64, mcOffset uint, memHandle uint64, memOffset uint, size uint, flags uint64) error

MulticastBindMemV1 binds a memory allocation represented by a handle to a multicast object.

Binds a memory allocation specified by memHandle and created via MemCreate to a multicast object represented by mcHandle and created via MulticastCreate. The intended size of the bind, the offset in the multicast range mcOffset as well as the offset in the memory memOffset must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memOffset should be aligned to the granularity of the memory allocation(see MemGetAllocationGranularity) or to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memOffset may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. Also note that the ability to accept a memOffset that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull The memory allocation must have beeen created on one of the devices that was added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate, Device.MulticastBindMemV2

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into the multicast object for attachment
  • memHandle: Handle representing a memory allocation
  • memOffset: Offset into the memory for attachment
  • size: Size of the memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero for now

Errors:

Wraps cuMulticastBindMem.

func MulticastCreate

func MulticastCreate(prop *MulticastObjectProp) (uint64, error)

MulticastCreate creates a generic allocation handle representing a multicast object described by the given properties.

This creates a multicast object as described by prop. The number of participating devices is specified by MulticastObjectProp.numDevices. Devices can be added to the multicast object via Device.MulticastAdd. All participating devices must be added to the multicast object before memory can be bound to it. Memory is bound to the multicast object via MulticastBindMem, Device.MulticastBindMemV2, DevicePtr.MulticastBindAddr, or Device.MulticastBindAddrV2. and can be unbound via Device.MulticastUnbind. The total amount of memory that can be bound per device is specified by : MulticastObjectProp.size. This size must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, the size should be aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. After all participating devices have been added, multicast objects can also be mapped to a device’s virtual address space using the virtual memory management APIs (see DevicePtr.MemMap and DevicePtr.MemSetAccess). Multicast objects can also be shared with other processes by requesting a shareable handle via MemExportToShareableHandle. Note that the desired types of shareable handles must be specified in the bitmask MulticastObjectProp.handleTypes. Multicast objects can be released using the virtual memory management API MemRelease.

See also: Device.MulticastAdd, MulticastBindMem, DevicePtr.MulticastBindAddr, Device.MulticastUnbind, MemCreate, MemRelease, MemExportToShareableHandle, MemImportFromShareableHandle, Device.MulticastBindAddrV2, Device.MulticastBindMemV2

  • prop: Properties of the multicast object to create

Errors:

Wraps cuMulticastCreate.

func MulticastGetGranularity

func MulticastGetGranularity(prop *MulticastObjectProp, option MulticastgranularityFlags) (uint, error)

MulticastGetGranularity calculates either the minimal or recommended granularity for multicast object.

Calculates either the minimal or recommended granularity for a given set of multicast object properties and returns it. This granularity can be used as a multiple for size, bind offsets and address mappings of the multicast object.

See also: MulticastCreate, MulticastBindMem, DevicePtr.MulticastBindAddr, Device.MulticastUnbind, Device.MulticastBindMemV2, Device.MulticastBindAddrV2

  • prop: Properties of the multicast object
  • option: Determines which granularity to return

Errors:

Wraps cuMulticastGetGranularity.

func Path

func Path() string

Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.

func ProfilerStart

func ProfilerStart() error

ProfilerStart resumes collection by an attached external profiler after ProfilerStop. Collection starts on by default, so a program needs this only to trace a second region after stopping. It requires a current context.

Wraps cuProfilerStart.

func ProfilerStop

func ProfilerStop() error

ProfilerStop flushes an attached external profiler's buffers and stops collection for the process. It requires a current context, and succeeds with nothing to do when no profiler is attached.

A Go program must call this before it exits or a profiler that attaches through CUDA_INJECTION64_PATH, such as Nsight Systems, writes an empty report: the injected library flushes from a C atexit handler, and the Go runtime leaves through exit_group without running one. Programs that expect to be profiled stop next to their device teardown:

defer dev.WithContext(driver.ProfilerStop)

Collection is process-wide, so work after it returns goes untraced until ProfilerStart.

Wraps cuProfilerStop.

func SurfObjectCreate

func SurfObjectCreate(pResDesc *ResourceDesc) (uint64, error)

SurfObjectCreate creates a surface object.

Creates a surface object and returns it. pResDesc describes the data to perform surface load/stores on. ResourceDesc.resType must be ResourceTypeArray and ResourceDesc.res.array.hArray must be set to a valid CUDA array handle. ResourceDesc.flags must be set to zero. Surface objects are only supported on devices of compute capability 3.0 or higher. Additionally, a surface object is an opaque value, and, as such, should only be accessed through CUDA API calls.

See also: SurfObjectDestroy, cudaCreateSurfaceObject

  • pResDesc: Resource descriptor

Errors:

Wraps cuSurfObjectCreate.

func SurfObjectDestroy

func SurfObjectDestroy(surfObject uint64) error

SurfObjectDestroy destroys a surface object.

Destroys the surface object specified by surfObject.

See also: SurfObjectCreate, cudaDestroySurfaceObject

  • surfObject: Surface object to destroy

Errors:

Wraps cuSurfObjectDestroy.

func TensorMapEncodeIm2col

func TensorMapEncodeIm2col(tensorMap *TensorMap, tensorDataType TensorMapDataType, tensorRank uint32, globalAddress uintptr, globalDim *uint64, globalStrides *uint64, pixelBoxLowerCorner *int32, pixelBoxUpperCorner *int32, channelsPerPixel uint32, pixelsPerColumn uint32, elementStrides *uint32, interleave TensorMapInterleave, swizzle TensorMapSwizzle, l2Promotion TensorMapL2promotion, oobFill TensorMapFloatOOBfill) error

TensorMapEncodeIm2col creates a tensor map descriptor object representing im2col memory region.

Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a im2col memory layout and returns it in tensorMap. Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. The parameters passed are bound to the following requirements:

  • tensorMap address must be aligned to 64 bytes.
  • tensorDataType has to be an enum from TensorMapDataType.

TensorMapDataType16U4Align8b copies ‘16 x U4’ packed values to memory aligned as 8 bytes. There are no gaps between packed values. TensorMapDataType16U4Align16b copies ‘16 x U4’ packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. TensorMapDataType16U6Align16b copies ‘16 x U6’ packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values.

  • tensorRank, which specifies the number of tensor dimensions, must be 3, 4, or 5.
  • globalAddress, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: When interleave is TensorMapInterleave32B, globalAddress must be 32 byte aligned. When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, globalAddress must be 32 byte aligned.
  • globalDim array, which specifies tensor size of each of the tensorRank dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types: When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, globalDim[0] must be a multiple of 128. When tensorDataType is TensorMapDataType16U4Align8b, globalDim[0] must be a multiple of 2. Dimension for the packed data types must reflect the number of individual U# values.
  • globalStrides array, which specifies tensor stride of each of the lower tensorRank - 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met: When interleave is TensorMapInterleave32B, the strides must be a multiple of 32. When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride:
  • pixelBoxLowerCorner array specifies the coordinate offsets {D, H, W} of the bounding box from top/left/front corner. The number of offsets and their precision depend on the tensor dimensionality: When tensorRank is 3, one signed offset within range [-32768, 32767] is supported. When tensorRank is 4, two signed offsets each within range [-128, 127] are supported. When tensorRank is 5, three offsets each within range [-16, 15] are supported.
  • pixelBoxUpperCorner array specifies the coordinate offsets {D, H, W} of the bounding box from bottom/right/back corner. The number of offsets and their precision depend on the tensor dimensionality: When tensorRank is 3, one signed offset within range [-32768, 32767] is supported. When tensorRank is 4, two signed offsets each within range [-128, 127] are supported. When tensorRank is 5, three offsets each within range [-16, 15] are supported. The bounding box specified by pixelBoxLowerCorner and pixelBoxUpperCorner must have non-zero area.
  • channelsPerPixel, which specifies the number of elements which must be accessed along C dimension, must be less than or equal to 256. Additionally, when tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, channelsPerPixel must be 128.
  • pixelsPerColumn, which specifies the number of elements that must be accessed along the {N, D, H, W} dimensions, must be less than or equal to 1024.
  • elementStrides array, which specifies the iteration step along each of the tensorRank dimensions, must be non-zero and less than or equal to 8. Note that when interleave is TensorMapInterleaveNone, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of the elementStrides array are one, boxDim specifies the number of elements to load. However, if elementStridesi is not equal to one for some i, then TMA loads ceil( boxDimi / elementStridesi) number of elements along i-th dimension. To load N elements along i-th dimension, boxDimi must be set to N * elementStridesi.
  • interleave specifies the interleaved layout of type TensorMapInterleave.

TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When interleave is TensorMapInterleaveNone and swizzle is not TensorMapSwizzleNone, the bounding box inner dimension (computed as channelsPerPixel multiplied by element size in bytes derived from tensorDataType) must be less than or equal to the swizzle size. - TensorMapSwizzle32B requires the bounding box inner dimension to be <= 32.

Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When interleave is TensorMapInterleave32B, swizzle must be TensorMapSwizzle32B. Other interleave modes can have any swizzling pattern. When the tensorDataType is TensorMapDataType16U6Align16b, only the following swizzle modes are supported: - TensorMapSwizzleNone (Load & Store)

Note that TensorMapFloatOobFillNanRequestZeroFma can only be used when tensorDataType represents a floating-point data type, and when tensorDataType is not TensorMapDataType16U4Align8b, TensorMapDataType16U4Align16b, and TensorMapDataType16U6Align16b.

See also: TensorMapEncodeTiled, TensorMapEncodeIm2colWide, TensorMapReplaceAddress

  • tensorMap: Tensor map object to create
  • tensorDataType: Tensor data type
  • tensorRank: Dimensionality of tensor; must be at least 3
  • globalAddress: Starting address of memory region described by tensor
  • globalDim: Array containing tensor size (number of elements) along each of the tensorRank dimensions
  • globalStrides: Array containing stride size (in bytes) along each of the tensorRank - 1 dimensions
  • pixelBoxLowerCorner: Array containing DHW dimensions of lower box corner
  • pixelBoxUpperCorner: Array containing DHW dimensions of upper box corner
  • channelsPerPixel: Number of channels per pixel
  • pixelsPerColumn: Number of pixels per column
  • elementStrides: Array containing traversal stride in each of the tensorRank dimensions
  • interleave: Type of interleaved layout the tensor addresses
  • swizzle: Bank swizzling pattern inside shared memory
  • l2Promotion: L2 promotion size
  • oobFill: Indicate whether zero or special NaN constant will be used to fill out-of-bound elements

Errors:

Wraps cuTensorMapEncodeIm2col.

func TensorMapEncodeIm2colWide

func TensorMapEncodeIm2colWide(tensorMap *TensorMap, tensorDataType TensorMapDataType, tensorRank uint32, globalAddress uintptr, globalDim *uint64, globalStrides *uint64, pixelBoxLowerCornerWidth int32, pixelBoxUpperCornerWidth int32, channelsPerPixel uint32, pixelsPerColumn uint32, elementStrides *uint32, interleave TensorMapInterleave, mode TensorMapIm2ColWideMode, swizzle TensorMapSwizzle, l2Promotion TensorMapL2promotion, oobFill TensorMapFloatOOBfill) error

TensorMapEncodeIm2colWide creates a tensor map descriptor object representing im2col memory region, but where the elements are exclusively loaded along the W dimension.

Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a im2col memory layout and where the row is always loaded along the W dimensuin and returns it in tensorMap. This assumes the tensor layout in memory is either NDHWC, NHWC, or NWC. This API is only supported on devices of compute capability 10.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. The parameters passed are bound to the following requirements:

  • tensorMap address must be aligned to 64 bytes.
  • tensorDataType has to be an enum from TensorMapDataType.

TensorMapDataType16U4Align8b copies ‘16 x U4’ packed values to memory aligned as 8 bytes. There are no gaps between packed values. TensorMapDataType16U4Align16b copies ‘16 x U4’ packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. TensorMapDataType16U6Align16b copies ‘16 x U6’ packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values.

  • tensorRank, which specifies the number of tensor dimensions, must be 3, 4, or 5.
  • globalAddress, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: When interleave is TensorMapInterleave32B, globalAddress must be 32 byte aligned. When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, globalAddress must be 32 byte aligned.

globalDim array, which specifies tensor size of each of the tensorRank dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types:

globalStrides array, which specifies tensor stride of each of the lower tensorRank - 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met:

When interleave is TensorMapInterleave32B, the strides must be a multiple of 32.

When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride:

globalStrides[0] = globalDim[0] * elementSizeInBytes(tensorDataType) + padding[0];
for (i = 1; i < tensorRank - 1; i++)
      globalStrides[i] = globalStrides[i – 1] * (globalDim[i] + padding[i]);
      assert(globalStrides[i] >= globalDim[i]);

pixelBoxLowerCornerWidth specifies the coordinate offset W of the bounding box from left corner. The offset must be within range [-32768, 32767].

  • pixelBoxUpperCornerWidth specifies the coordinate offset W of the bounding box from right corner. The offset must be within range [-32768, 32767].

The bounding box specified by pixelBoxLowerCornerWidth and pixelBoxUpperCornerWidth must have non-zero area. Note that the size of the box along D and H dimensions is always equal to one.

  • channelsPerPixel, which specifies the number of elements which must be accessed along C dimension, must be less than or equal to 256. Additionally, when tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, channelsPerPixel must be 128.
  • pixelsPerColumn, which specifies the number of elements that must be accessed along the W dimension, must be less than or equal to 1024. This field is ignored when mode is TensorMapIm2colWideModeW128.
  • elementStrides array, which specifies the iteration step along each of the tensorRank dimensions, must be non-zero and less than or equal to 8. Note that when interleave is TensorMapInterleaveNone, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of the elementStrides array are one, boxDim specifies the number of elements to load. However, if elementStridesi is not equal to one for some i, then TMA loads ceil( boxDimi / elementStridesi) number of elements along i-th dimension. To load N elements along i-th dimension, boxDimi must be set to N * elementStridesi.
  • interleave specifies the interleaved layout of type TensorMapInterleave.

TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When interleave is TensorMapInterleaveNone, the bounding box inner dimension (computed as channelsPerPixel multiplied by element size in bytes derived from tensorDataType) must be less than or equal to the swizzle size. - TensorMapSwizzle64B requires the bounding box inner dimension to be <= 64.

TensorMapSwizzle128B* require the bounding box inner dimension to be <= 128. Additionally, tensorDataType of TensorMapDataType16U6Align16b requires interleave to be TensorMapInterleaveNone.

mode, which describes loading of elements loaded along the W dimension, has to be one of the following TensorMapIm2ColWideMode types:

CU_TENSOR_MAP_IM2COL_WIDE_MODE_W,
CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128

TensorMapIm2colWideModeW allows the number of elements loaded along the W dimension to be specified via the pixelsPerColumn field.

  • swizzle, which specifies the shared memory bank swizzling pattern, must be one of the following TensorMapSwizzle modes (other swizzle modes are not supported).

Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When the tensorDataType is TensorMapDataType16U6Align16b, only the following swizzle modes are supported: - TensorMapSwizzle64B (Store only)

Additionally, CU_TENSOR_MAP_SWIZZLE_96B is supported only when mode is TensorMapIm2colWideModeW.

  • l2Promotion specifies L2 fetch size which indicates the byte granularity at which L2 requests are filled from DRAM. It must be of type TensorMapL2promotion.
  • oobFill, which indicates whether zero or a special NaN constant should be used to fill out-of-bound elements, must be of type TensorMapFloatOOBfill.

Note that TensorMapFloatOobFillNanRequestZeroFma can only be used when tensorDataType represents a floating-point data type, and when tensorDataType is not TensorMapDataType16U4Align8b, TensorMapDataType16U4Align16b, and TensorMapDataType16U6Align16b.

See also: TensorMapEncodeTiled, TensorMapEncodeIm2col, TensorMapReplaceAddress

Requires CUDA 12.8 (driver r570) or later; see HasTensorMapEncodeIm2colWide.

  • tensorMap: Tensor map object to create
  • tensorDataType: Tensor data type
  • tensorRank: Dimensionality of tensor; must be at least 3
  • globalAddress: Starting address of memory region described by tensor
  • globalDim: Array containing tensor size (number of elements) along each of the tensorRank dimensions
  • globalStrides: Array containing stride size (in bytes) along each of the tensorRank - 1 dimensions
  • pixelBoxLowerCornerWidth: Width offset of left box corner
  • pixelBoxUpperCornerWidth: Width offset of right box corner
  • channelsPerPixel: Number of channels per pixel
  • pixelsPerColumn: Number of pixels per column
  • elementStrides: Array containing traversal stride in each of the tensorRank dimensions
  • interleave: Type of interleaved layout the tensor addresses
  • mode: W or W128 mode
  • swizzle: Bank swizzling pattern inside shared memory
  • l2Promotion: L2 promotion size
  • oobFill: Indicate whether zero or special NaN constant will be used to fill out-of-bound elements

Errors:

Wraps cuTensorMapEncodeIm2colWide.

func TensorMapEncodeTiled

func TensorMapEncodeTiled(tensorMap *TensorMap, tensorDataType TensorMapDataType, tensorRank uint32, globalAddress DevicePtr, globalDim *uint64, globalStrides *uint64, boxDim *uint32, elementStrides *uint32, interleave TensorMapInterleave, swizzle TensorMapSwizzle, l2Promotion TensorMapL2promotion, oobFill TensorMapFloatOOBfill) error

TensorMapEncodeTiled creates a tensor map descriptor object representing tiled memory region.

Creates a descriptor for Tensor Memory Access (TMA) object specified by the parameters describing a tiled region and returns it in tensorMap. Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA APIs and PTX. The parameters passed are bound to the following requirements:

  • tensorMap address must be aligned to 64 bytes.
  • tensorDataType has to be an enum from TensorMapDataType.

TensorMapDataType16U4Align8b copies ‘16 x U4’ packed values to memory aligned as 8 bytes. There are no gaps between packed values. TensorMapDataType16U4Align16b copies ‘16 x U4’ packed values to memory aligned as 16 bytes. There are 8 byte gaps between every 8 byte chunk of packed values. TensorMapDataType16U6Align16b copies ‘16 x U6’ packed values to memory aligned as 16 bytes. There are 4 byte gaps between every 12 byte chunk of packed values.

  • tensorRank must be non-zero and less than or equal to the maximum supported dimensionality of 5. If interleave is not TensorMapInterleaveNone, then tensorRank must additionally be greater than or equal to 3.
  • globalAddress, which specifies the starting address of the memory region described, must be 16 byte aligned. The following requirements need to also be met: When interleave is TensorMapInterleave32B, globalAddress must be 32 byte aligned. When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, globalAddress must be 32 byte aligned.

globalDim array, which specifies tensor size of each of the tensorRank dimensions, must be non-zero and less than or equal to 2^32. Additionally, the following requirements need to be met for the packed data types:

globalStrides array, which specifies tensor stride of each of the lower tensorRank - 1 dimensions in bytes, must be a multiple of 16 and less than 2^40. Additionally, the following requirements need to be met:

When interleave is TensorMapInterleave32B, the strides must be a multiple of 32.

When tensorDataType is TensorMapDataType16U6Align16b or TensorMapDataType16U4Align16b, the strides must be a multiple of 32. Each following dimension specified includes previous dimension stride:

globalStrides[0] = globalDim[0] * elementSizeInBytes(tensorDataType) + padding[0];
for (i = 1; i < tensorRank - 1; i++)
      globalStrides[i] = globalStrides[i – 1] * (globalDim[i] + padding[i]);
      assert(globalStrides[i] >= globalDim[i]);

boxDim array, which specifies number of elements to be traversed along each of the tensorRank dimensions, must be non-zero and less than or equal to 256. Additionally, the following requirements need to be met:

elementStrides array, which specifies the iteration step along each of the tensorRank dimensions, must be non-zero and less than or equal to 8. Note that when interleave is TensorMapInterleaveNone, the first element of this array is ignored since TMA doesn’t support the stride for dimension zero. When all elements of elementStrides array is one, boxDim specifies the number of elements to load. However, if the elementStridesi is not equal to one, then TMA loads ceil( boxDimi / elementStridesi) number of elements along i-th dimension. To load N elements along i-th dimension, boxDimi must be set to N * elementStridesi.

TMA supports interleaved layouts like NC/8HWC8 where C8 utilizes 16 bytes in memory assuming 2 byte per channel or NC/16HWC16 where C16 uses 32 bytes. When interleave is TensorMapInterleaveNone and swizzle is not TensorMapSwizzleNone, the bounding box inner dimension (computed as boxDim[0] multiplied by element size derived from tensorDataType) must be less than or equal to the swizzle size. - TensorMapSwizzle32B requires the bounding box inner dimension to be <= 32.

Data are organized in a specific order in global memory; however, this may not match the order in which the application accesses data in shared memory. This difference in data organization may cause bank conflicts when shared memory is accessed. In order to avoid this problem, data can be loaded to shared memory with shuffling across shared memory banks. When interleave is TensorMapInterleave32B, swizzle must be TensorMapSwizzle32B. Other interleave modes can have any swizzling pattern. When the tensorDataType is TensorMapDataType16U6Align16b, only the following swizzle modes are supported: - TensorMapSwizzleNone (Load & Store)

Note that TensorMapFloatOobFillNanRequestZeroFma can only be used when tensorDataType represents a floating-point data type, and when tensorDataType is not TensorMapDataType16U4Align8b, TensorMapDataType16U4Align16b, and TensorMapDataType16U6Align16b.

See also: TensorMapEncodeIm2col, TensorMapEncodeIm2colWide, TensorMapReplaceAddress

  • tensorMap: Tensor map object to create
  • tensorDataType: Tensor data type
  • tensorRank: Dimensionality of tensor
  • globalAddress: Starting address of memory region described by tensor
  • globalDim: Array containing tensor size (number of elements) along each of the tensorRank dimensions
  • globalStrides: Array containing stride size (in bytes) along each of the tensorRank - 1 dimensions
  • boxDim: Array containing traversal box size (number of elments) along each of the tensorRank dimensions. Specifies how many elements to be traversed along each tensor dimension
  • elementStrides: Array containing traversal stride in each of the tensorRank dimensions
  • interleave: Type of interleaved layout the tensor addresses
  • swizzle: Bank swizzling pattern inside shared memory
  • l2Promotion: L2 promotion size
  • oobFill: Indicate whether zero or special NaN constant must be used to fill out-of-bound elements

Errors:

Wraps cuTensorMapEncodeTiled.

func TensorMapReplaceAddress

func TensorMapReplaceAddress(tensorMap *TensorMap, globalAddress DevicePtr) error

TensorMapReplaceAddress modifies an existing tensor map descriptor with an updated global address.

Modifies the descriptor for Tensor Memory Access (TMA) object passed in tensorMap with an updated globalAddress. Tensor map objects are only supported on devices of compute capability 9.0 or higher. Additionally, a tensor map object is an opaque value, and, as such, should only be accessed through CUDA API calls.

See also: TensorMapEncodeTiled, TensorMapEncodeIm2col, TensorMapEncodeIm2colWide

  • tensorMap: Tensor map object to modify
  • globalAddress: Starting address of memory region described by tensor, must follow previous alignment requirements

Errors:

Wraps cuTensorMapReplaceAddress.

func TensorMapSetAllocationClass

func TensorMapSetAllocationClass(tensorMap *TensorMap, allocClass TensorMapAllocClass, outAllocClass *TensorMapAllocClass) error

TensorMapSetAllocationClass sets the allocation class of an already-encoded tensor map

Requests a Tensor Memory Accelerator (TMA) allocation class for an existing tensorMap that was previously initialized by a tensor-map encoding API. No re-encoding of the tensor is performed.

allocClass selects the class:

  • TensorMapAllocClassSmall requests the safe 4 KiB window.
  • TensorMapAllocClassLarge requests the 128 KiB window. When LARGE is the effective class, the caller guarantees that, before the tensor map is used, its effective base allocation is backed by a contiguous, accessible region of at least

DevAttrTensorMapLargeTensorMinSize bytes. Violating this is undefined behavior at kernel execution time, not an error of this API.

  • TensorMapAllocClassAuto re-evaluates the encoded tensor geometry using the driver's conservative contiguity policy. The global address is not inspected.

On architectures where allocation-class selection affects TMA OOB address generation, this function adjusts only the encoded selector through an in-place read-modify-write of tensorMap. The caller must externally synchronize this call with all other host and device access to the same descriptor storage, including device-side tensormap.replace operations.

If outAllocClass is non-NULL it receives the class actually in effect after the call, which is always TensorMapAllocClassSmall or TensorMapAllocClassLarge (never TensorMapAllocClassAuto). If outAllocClass is non-NULL, it is initialized to TensorMapAllocClassSmall before validation. On failure, tensorMap is not modified and outAllocClass remains SMALL.

On architectures where allocation-class selection has no effect, all three requests succeed without changing tensorMap and report TensorMapAllocClassSmall.

Requires CUDA 13.5 (driver r620) or later; see HasTensorMapSetAllocationClass.

  • tensorMap: Tensor map to modify in place
  • allocClass: Requested allocation class
  • outAllocClass: Optional; receives the resulting allocation class

See also: TensorMapEncodeTiled, TensorMapEncodeIm2col, TensorMapEncodeIm2colWide, TensorMapReplaceAddress

Wraps cuTensorMapSetAllocationClass.

func TexObjectCreate

func TexObjectCreate(pResDesc *ResourceDesc, pTexDesc *TextureDesc, pResViewDesc *ResourceViewDesc) (uint64, error)

TexObjectCreate creates a texture object.

Creates a texture object and returns it. pResDesc describes the data to texture from. pTexDesc describes how the data should be sampled. pResViewDesc is an optional argument that specifies an alternate format for the data described by pResDesc, and also describes the subresource region to restrict access to when texturing. pResViewDesc can only be specified if the type of resource is a CUDA array or a CUDA mipmapped array not in a block compressed format. Texture objects are only supported on devices of compute capability 3.0 or higher. Additionally, a texture object is an opaque value, and, as such, should only be accessed through CUDA API calls.

  • ResourceDesc.resType specifies the type of resource to texture from.
  • flags must be set to zero.

If ResourceDesc.resType is set to ResourceTypeArray, ResourceDesc.res.array.hArray must be set to a valid CUDA array handle. If ResourceDesc.resType is set to ResourceTypeMipmappedArray, ResourceDesc.res.mipmap.hMipmappedArray must be set to a valid CUDA mipmapped array handle. If ResourceDesc.resType is set to ResourceTypeLinear, ResourceDesc.res.linear.devPtr must be set to a valid device pointer, that is aligned to DevAttrTextureAlignment. ResourceDesc.res.linear.format and ResourceDesc.res.linear.numChannels describe the format of each component and the number of components per array element. ResourceDesc.res.linear.sizeInBytes specifies the size of the array in bytes. The total number of elements in the linear address range cannot exceed DevAttrMaximumTexture1dLinearWidth. The number of elements is computed as (sizeInBytes / (sizeof(format) * numChannels)). If ResourceDesc.resType is set to ResourceTypePitch2d, ResourceDesc.res.pitch2D.devPtr must be set to a valid device pointer, that is aligned to DevAttrTextureAlignment. ResourceDesc.res.pitch2D.format and ResourceDesc.res.pitch2D.numChannels describe the format of each component and the number of components per array element. ResourceDesc.res.pitch2D.width and ResourceDesc.res.pitch2D.height specify the width and height of the array in elements, and cannot exceed DevAttrMaximumTexture2dLinearWidth and DevAttrMaximumTexture2dLinearHeight respectively. ResourceDesc.res.pitch2D.pitchInBytes specifies the pitch between two rows in bytes and has to be aligned to DevAttrTexturePitchAlignment. Pitch cannot exceed DevAttrMaximumTexture2dLinearPitch.

  • TextureDesc.addressMode specifies the addressing mode for each dimension of the texture data.

This is ignored if ResourceDesc.resType is ResourceTypeLinear. Also, if the flag, CU_TRSF_NORMALIZED_COORDINATES is not set, the only supported address mode is TrAddressModeClamp.

  • TextureDesc.filterMode specifies the filtering mode to be used when fetching from the texture.

This is ignored if ResourceDesc.resType is ResourceTypeLinear.

  • TextureDesc.flags can be any combination of the following: CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of having the texture promote integer data to floating point data in the range [0, 1]. Note that texture with 32-bit integer format would not be promoted, regardless of whether or not this flag is specified. CU_TRSF_NORMALIZED_COORDINATES, which suppresses the default behavior of having the texture coordinates range from [0, Dim) where Dim is the width or height of the CUDA array. Instead, the texture coordinates [0, 1.0) reference the entire breadth of the array dimension; Note that for CUDA mipmapped arrays, this flag has to be set. CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear filtering optimizations. Trilinear optimizations improve texture filtering performance by allowing bilinear filtering on textures in scenarios where it can closely approximate the expected results. CU_TRSF_SEAMLESS_CUBEMAP, which enables seamless cube map filtering. This flag can only be specified if the underlying resource is a CUDA array or a CUDA mipmapped array that was created with the flag CUDA_ARRAY3D_CUBEMAP. When seamless cube map filtering is enabled, texture address modes specified by TextureDesc.addressMode are ignored. Instead, if the TextureDesc.filterMode is set to TrFilterModePoint the address mode TrAddressModeClamp will be applied for all dimensions. If the TextureDesc.filterMode is set to TrFilterModeLinear seamless cube map filtering will be performed when sampling along the cube face borders.
  • TextureDesc.maxAnisotropy specifies the maximum anisotropy ratio to be used when doing anisotropic filtering. This value will be clamped to the range [1,16].
  • TextureDesc.mipmapFilterMode specifies the filter mode when the calculated mipmap level lies between two defined mipmap levels.
  • TextureDesc.mipmapLevelBias specifies the offset to be applied to the calculated mipmap level.
  • TextureDesc.minMipmapLevelClamp specifies the lower end of the mipmap level range to clamp access to.
  • TextureDesc.maxMipmapLevelClamp specifies the upper end of the mipmap level range to clamp access to.
  • ResourceViewDesc.format specifies how the data contained in the CUDA array or CUDA mipmapped array should be interpreted. Note that this can incur a change in size of the texture data. If the resource view format is a block compressed format, then the underlying CUDA array or CUDA mipmapped array has to have a base of format AdFormatUnsignedInt32. with 2 or 4 channels, depending on the block compressed format. For ex., BC1 and BC4 require the underlying CUDA array to have a format of AdFormatUnsignedInt32 with 2 channels. The other BC formats require the underlying resource to have the same base format but with 4 channels.
  • ResourceViewDesc.width specifies the new width of the texture data. If the resource view format is a block compressed format, this value has to be 4 times the original width of the resource. For non block compressed formats, this value has to be equal to that of the original resource.
  • ResourceViewDesc.height specifies the new height of the texture data. If the resource view format is a block compressed format, this value has to be 4 times the original height of the resource. For non block compressed formats, this value has to be equal to that of the original resource.
  • ResourceViewDesc.depth specifies the new depth of the texture data. This value has to be equal to that of the original resource.
  • ResourceViewDesc.firstMipmapLevel specifies the most detailed mipmap level. This will be the new mipmap level zero. For non-mipmapped resources, this value has to be zero. TextureDesc.minMipmapLevelClamp and TextureDesc.maxMipmapLevelClamp will be relative to this value. For ex., if the firstMipmapLevel is set to 2, and a minMipmapLevelClamp of 1.2 is specified, then the actual minimum mipmap level clamp will be 3.2.
  • ResourceViewDesc.lastMipmapLevel specifies the least detailed mipmap level. For non-mipmapped resources, this value has to be zero.
  • ResourceViewDesc.firstLayer specifies the first layer index for layered textures. This will be the new layer zero. For non-layered resources, this value has to be zero.
  • ResourceViewDesc.lastLayer specifies the last layer index for layered textures. For non-layered resources, this value has to be zero.

See also: TexObjectDestroy, cudaCreateTextureObject

  • pResDesc: Resource descriptor
  • pTexDesc: Texture descriptor
  • pResViewDesc: Resource view descriptor

Errors:

Wraps cuTexObjectCreate.

func TexObjectDestroy

func TexObjectDestroy(texObject uint64) error

TexObjectDestroy destroys a texture object.

Destroys the texture object specified by texObject.

See also: TexObjectCreate, cudaDestroyTextureObject

  • texObject: Texture object to destroy

Errors:

Wraps cuTexObjectDestroy.

func ThreadExchangeStreamCaptureMode

func ThreadExchangeStreamCaptureMode(mode *StreamCaptureMode) error

ThreadExchangeStreamCaptureMode 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.

During stream capture (see Stream.BeginCapture), some actions, such as a call to cudaMalloc, may be unsafe. In the case of cudaMalloc, the operation is not enqueued asynchronously to a stream, and is not observed by stream capture. Therefore, if the sequence of operations captured via Stream.BeginCapture 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 Stream.BeginCapture- Stream.EndCapture sequence. This behavior can be controlled via this API and flags to Stream.BeginCapture. A thread’s mode is one of the following:

See also: Stream.BeginCapture

  • mode: Pointer to mode value to swap with the current mode

Errors:

Wraps cuThreadExchangeStreamCaptureMode.

Example

ExampleThreadExchangeStreamCaptureMode relaxes the calling thread's stream capture mode around a call that capture would otherwise prohibit, such as MemAllocBytes, and restores the previous mode on return. The mode belongs to the OS thread, so the goroutine stays locked to it throughout.

package main

import (
	"fmt"
	"runtime"

	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	mode := driver.StreamCaptureModeRelaxed
	if err := driver.ThreadExchangeStreamCaptureMode(&mode); err != nil {
		fmt.Println("capture mode:", err)
		return
	}
	// mode now holds the previous mode; exchanging again restores it.
	defer driver.ThreadExchangeStreamCaptureMode(&mode)

	p, err := driver.MemAllocBytes(1 << 20)
	if err != nil {
		fmt.Println("alloc:", err)
		return
	}
	defer p.Free()
}

Types

type AccessPolicyWindow

type AccessPolicyWindow struct {
	// Starting address of the access policy window. CUDA driver may align it.
	BasePtr uintptr
	// Size in bytes of the window policy. CUDA driver may restrict the maximum size and alignment.
	NumBytes uint
	// hitRatio specifies percentage of lines assigned hitProp, rest are assigned missProp.
	HitRatio float32
	// [AccessProperty] set for hit.
	HitProp AccessProperty
	// [AccessProperty] set for miss. Must be either NORMAL or STREAMING
	MissProp AccessProperty
}

AccessPolicyWindow specifies an access policy for a window, a contiguous extent of memory beginning at base_ptr and ending at base_ptr + num_bytes. num_bytes is limited by DevAttrMaxAccessPolicyWindowSize. Partition into many segments and assign segments such that: sum of "hit segments" / window == approx. ratio. sum of "miss segments" / window == approx 1-ratio. Segments and ratio specifications are fitted to the capabilities of the architecture. Accesses in a hit segment apply the hitProp access policy. Accesses in a miss segment apply the missProp access policy.

type AccessPolicyWindowV1

type AccessPolicyWindowV1 = AccessPolicyWindow

AccessPolicyWindowV1 is an alias for AccessPolicyWindow.

type AccessProperty

type AccessProperty int32

AccessProperty specifies performance hint with AccessPolicyWindow for hitProp and missProp members.

const (
	AccessPropertyNormal     AccessProperty = 0 // Normal cache persistence.
	AccessPropertyStreaming  AccessProperty = 1 // Streaming access is less likely to persit from cache.
	AccessPropertyPersisting AccessProperty = 2 // Persisting access is more likely to persist in cache.
)

func (AccessProperty) String

func (e AccessProperty) String() string

String returns the constant name, or a numeric representation for unknown values.

type AddressMode

type AddressMode int32

AddressMode represents texture reference addressing modes.

const (
	TrAddressModeWrap   AddressMode = 0 // Wrapping address mode
	TrAddressModeClamp  AddressMode = 1 // Clamp to edge address mode
	TrAddressModeMirror AddressMode = 2 // Mirror address mode
	TrAddressModeBorder AddressMode = 3 // Border address mode
)

func (AddressMode) String

func (e AddressMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type Array

type Array uintptr

Array is CUDA array.

func NewArray

func NewArray(pAllocateArray *ArrayDescriptor) (Array, error)

NewArray creates a 1D or 2D CUDA array.

Creates a CUDA array according to the ArrayDescriptor structure pAllocateArray and returns a handle to the new CUDA array.

  • Width, and Height are the width, and height of the CUDA array (in elements); the CUDA array is one-dimensional if height is 0, two-dimensional otherwise;
  • Format specifies the format of the elements.
  • NumChannels specifies the number of packed components per CUDA array element; it may be 1, 2, or 4;

Here are examples of CUDA array descriptions:

See also: NewArray3D, Array.Get3DDescriptor, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMallocArray

  • pAllocateArray: Array descriptor

Errors:

Wraps cuArrayCreate, bound as cuArrayCreate_v2.

func NewArray3D

func NewArray3D(pAllocateArray *Array3dDescriptor) (Array, error)

NewArray3D creates a 3D CUDA array.

Creates a CUDA array according to the Array3dDescriptor structure pAllocateArray and returns a handle to the new CUDA array.

  • Width, Height, and Depth are the width, height, and depth of the CUDA array (in elements); the following types of CUDA arrays can be allocated: A 1D array is allocated if Height and Depth extents are both zero. A 2D array is allocated if only 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 Height is zero and the CUDA_ARRAY3D_LAYERED 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 CUDA_ARRAY3D_LAYERED 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 CUDA_ARRAY3D_CUBEMAP 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 ArrayCubemapFace. A cubemap layered CUDA array is allocated if all three extents are non-zero, and both, CUDA_ARRAY3D_CUBEMAP and CUDA_ARRAY3D_LAYERED 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.
  • Format specifies the format of the elements.
  • NumChannels specifies the number of packed components per CUDA array element; it may be 1, 2, or 4;
  • Flags may be set to CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA arrays. If this flag is set, Depth specifies the number of layers, not the depth of a 3D array. CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to the CUDA array. If this flag is not set, SurfRef.SetArray will fail when attempting to bind the CUDA array to a surface reference. CUDA_ARRAY3D_CUBEMAP to enable creation of cubemaps. If this flag is set, Width must be equal to Height, and Depth must be six. If the CUDA_ARRAY3D_LAYERED flag is also set, then Depth must be a multiple of six. CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA array will be used for texture gather. Texture gather can only be performed on 2D CUDA arrays.

Width, Height and Depth must meet certain size requirements as listed in the following table. All values are specified in elements. Note that for brevity’s sake, the full name of the device attribute is not specified. For ex., TEXTURE1D_WIDTH refers to the device attribute DevAttrMaximumTexture1dWidth. Note that 2D CUDA arrays have different size requirements if the CUDA_ARRAY3D_TEXTURE_GATHER flag is set. Width and Height must not be greater than DevAttrMaximumTexture2dGatherWidth and DevAttrMaximumTexture2dGatherHeight respectively, in that case. Here are examples of CUDA array descriptions:

See also: Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMalloc3DArray

  • pAllocateArray: 3D array descriptor

Errors:

Wraps cuArray3DCreate, bound as cuArray3DCreate_v2.

func (Array) CopyFromArray

func (a Array) CopyFromArray(dstOffset uint, srcArray Array, srcOffset uint, byteCount uint) error

CopyFromArray copies memory from Array to Array.

Copies from one 1D CUDA array to another. dstArray and srcArray specify the handles of the destination and source CUDA arrays for the copy, respectively. dstOffset and srcOffset specify the destination and source offsets in bytes into the CUDA arrays. ByteCount is the number of bytes to be copied. The size of the elements in the CUDA arrays need not be the same format, but the elements must be the same size; and count must be evenly divisible by that size.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpyArrayToArray

  • dstOffset: Offset in bytes of destination array
  • srcArray: Source array
  • srcOffset: Offset in bytes of source array
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpyAtoA, bound as cuMemcpyAtoA_v2.

func (Array) CopyFromDevice

func (a Array) CopyFromDevice(dstOffset uint, srcDevice DevicePtr, byteCount uint) error

CopyFromDevice copies memory from Device to Array.

Copies from device memory to a 1D CUDA array. dstArray and dstOffset specify the CUDA array handle and starting index of the destination data. srcDevice specifies the base pointer of the source. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpyToArray

  • dstOffset: Offset in bytes of destination array
  • srcDevice: Source device pointer
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpyDtoA, bound as cuMemcpyDtoA_v2.

func (Array) CopyFromHost

func (a Array) CopyFromHost[T any](dstOffset uint, srcHost []T) error

CopyFromHost copies memory from Host to Array.

Copies from host memory to a 1D CUDA array. dstArray and dstOffset specify the CUDA array handle and starting offset in bytes of the destination data. pSrc specifies the base address of the source. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpyToArray

  • dstOffset: Offset in bytes of destination array
  • srcHost: Source host pointer

Errors:

The copy covers all of srcHost: len(srcHost) values of type T.

Wraps cuMemcpyHtoA, bound as cuMemcpyHtoA_v2.

func (Array) CopyFromHostAsync

func (a Array) CopyFromHostAsync[T any](dstOffset uint, srcHost []T, hStream Stream) error

CopyFromHostAsync copies memory from Host to Array.

Copies from host memory to a 1D CUDA array. dstArray and dstOffset specify the CUDA array handle and starting offset in bytes of the destination data. srcHost specifies the base address of the source. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyToArrayAsync

  • dstOffset: Offset in bytes of destination array
  • srcHost: Source host pointer
  • hStream: Stream identifier

Errors:

srcHost must remain valid, unmoved, and unmodified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

The copy covers all of srcHost: len(srcHost) values of type T.

Wraps cuMemcpyHtoAAsync, bound as cuMemcpyHtoAAsync_v2.

func (Array) CopyFromHostAsyncPtr

func (a Array) CopyFromHostAsyncPtr(dstOffset uint, srcHost unsafe.Pointer, byteCount uint, hStream Stream) error

CopyFromHostAsyncPtr is Array.CopyFromHostAsync with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

srcHost must remain valid, unmoved, and unmodified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

Wraps cuMemcpyHtoAAsync, bound as cuMemcpyHtoAAsync_v2.

func (Array) CopyFromHostPtr

func (a Array) CopyFromHostPtr(dstOffset uint, srcHost unsafe.Pointer, byteCount uint) error

CopyFromHostPtr is Array.CopyFromHost with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

Wraps cuMemcpyHtoA, bound as cuMemcpyHtoA_v2.

func (Array) CopyToHost

func (a Array) CopyToHost[T any](dstHost []T, srcOffset uint) error

CopyToHost copies memory from Array to Host.

Copies from one 1D CUDA array to host memory. dstHost specifies the base pointer of the destination. srcArray and srcOffset specify the CUDA array handle and starting offset in bytes of the source data. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpyFromArray

  • dstHost: Destination device pointer
  • srcOffset: Offset in bytes of source array

Errors:

The copy covers all of dstHost: len(dstHost) values of type T.

Wraps cuMemcpyAtoH, bound as cuMemcpyAtoH_v2.

func (Array) CopyToHostAsync

func (a Array) CopyToHostAsync[T any](dstHost []T, srcOffset uint, hStream Stream) error

CopyToHostAsync copies memory from Array to Host.

Copies from one 1D CUDA array to host memory. dstHost specifies the base pointer of the destination. srcArray and srcOffset specify the CUDA array handle and starting offset in bytes of the source data. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyFromArrayAsync

  • dstHost: Destination pointer
  • srcOffset: Offset in bytes of source array
  • hStream: Stream identifier

Errors:

dstHost must remain valid, unmoved, and neither read nor modified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

The copy covers all of dstHost: len(dstHost) values of type T.

Wraps cuMemcpyAtoHAsync, bound as cuMemcpyAtoHAsync_v2.

func (Array) CopyToHostAsyncPtr

func (a Array) CopyToHostAsyncPtr(dstHost unsafe.Pointer, srcOffset uint, byteCount uint, hStream Stream) error

CopyToHostAsyncPtr is Array.CopyToHostAsync with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

dstHost must remain valid, unmoved, and neither read nor modified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

Wraps cuMemcpyAtoHAsync, bound as cuMemcpyAtoHAsync_v2.

func (Array) CopyToHostPtr

func (a Array) CopyToHostPtr(dstHost unsafe.Pointer, srcOffset uint, byteCount uint) error

CopyToHostPtr is Array.CopyToHost with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

Wraps cuMemcpyAtoH, bound as cuMemcpyAtoH_v2.

func (Array) Get3DDescriptor

func (a Array) Get3DDescriptor() (Array3dDescriptor, error)

Get3DDescriptor gets a 3D CUDA array descriptor.

Returns a descriptor containing information on the format and dimensions of the CUDA array hArray. It is useful for subroutines that have been passed a CUDA array, but need to know the CUDA array parameters for validation or other purposes. This function may be called on 1D and 2D arrays, in which case the Height and/or Depth members of the descriptor struct will be set to 0.

See also: NewArray3D, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaArrayGetInfo

Errors:

Wraps cuArray3DGetDescriptor, bound as cuArray3DGetDescriptor_v2.

func (Array) MemoryRequirements

func (a Array) MemoryRequirements(device Device) (ArrayMemoryRequirements, error)

MemoryRequirements returns the memory requirements of a CUDA array.

Returns the memory requirements of a CUDA array If the CUDA array is not allocated with flag CUDA_ARRAY3D_DEFERRED_MAPPING ErrInvalidValue will be returned. The returned value in ArrayMemoryRequirements.size represents the total size of the CUDA array. The returned value in ArrayMemoryRequirements.alignment represents the alignment necessary for mapping the CUDA array.

See also: MipmappedArray.MemoryRequirements, Stream.MemMapArrayAsync

  • device: Device to get the memory requirements for

Errors:

Wraps cuArrayGetMemoryRequirements.

func (Array) Plane

func (a Array) Plane(planeIdx uint32) (Array, error)

Plane gets a CUDA array plane from a CUDA array.

Returns 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: AdFormatNV12, then ErrInvalidValue is returned. Note that if the hArray has format AdFormatNV12, then passing in 0 for planeIdx returns a CUDA array of the same size as hArray but with one channel and AdFormatUnsignedINT8 as its format. If 1 is passed for planeIdx, then the returned CUDA array has half the height and width of hArray with two channels and AdFormatUnsignedINT8 as its format.

See also: NewArray, cudaArrayGetPlane

  • planeIdx: Plane index

Errors:

Wraps cuArrayGetPlane.

func (Array) SparseProperties

func (a Array) SparseProperties() (ArraySparseProperties, error)

SparseProperties returns the layout properties of a sparse CUDA array.

Returns the layout properties of a sparse CUDA array If the CUDA array is not allocated with flag CUDA_ARRAY3D_SPARSE ErrInvalidValue will be returned. If the returned value in ArraySparseProperties.flags contains CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, then ArraySparseProperties.miptailSize represents the total size of the array. Otherwise, it will be zero. Also, the returned value in ArraySparseProperties.miptailFirstLevel is always zero. Note that the array must have been allocated using NewArray or NewArray3D. For CUDA arrays obtained using MipmappedArray.Level, ErrInvalidValue will be returned. Instead, MipmappedArray.SparseProperties must be used to obtain the sparse properties of the entire CUDA mipmapped array to which array belongs to.

See also: MipmappedArray.SparseProperties, Stream.MemMapArrayAsync

Errors:

Wraps cuArrayGetSparseProperties.

type Array3dDescriptor

type Array3dDescriptor struct {
	// Width of 3D array
	Width uint
	// Height of 3D array
	Height uint
	// Depth of 3D array
	Depth uint
	// Array format
	Format ArrayFormat
	// Channels per array element
	NumChannels uint32
	// Flags
	Flags uint32
}

Array3dDescriptor represents 3D array descriptor.

type Array3dDescriptorV2

type Array3dDescriptorV2 = Array3dDescriptor

Array3dDescriptorV2 is an alias for Array3dDescriptor.

type ArrayCubemapFace

type ArrayCubemapFace int32

ArrayCubemapFace represents array indices for cube faces.

const (
	CubemapFacePositiveX ArrayCubemapFace = 0x00 // Positive X face of cubemap
	CubemapFaceNegativeX ArrayCubemapFace = 0x01 // Negative X face of cubemap
	CubemapFacePositiveY ArrayCubemapFace = 0x02 // Positive Y face of cubemap
	CubemapFaceNegativeY ArrayCubemapFace = 0x03 // Negative Y face of cubemap
	CubemapFacePositiveZ ArrayCubemapFace = 0x04 // Positive Z face of cubemap
	CubemapFaceNegativeZ ArrayCubemapFace = 0x05 // Negative Z face of cubemap
)

func (ArrayCubemapFace) String

func (e ArrayCubemapFace) String() string

String returns the constant name, or a numeric representation for unknown values.

type ArrayDescriptor

type ArrayDescriptor struct {
	// Width of array
	Width uint
	// Height of array
	Height uint
	// Array format
	Format ArrayFormat
	// Channels per array element
	NumChannels uint32
}

ArrayDescriptor represents array descriptor.

type ArrayDescriptorV2

type ArrayDescriptorV2 = ArrayDescriptor

ArrayDescriptorV2 is an alias for ArrayDescriptor.

type ArrayFormat

type ArrayFormat int32

ArrayFormat represents array formats.

const (
	AdFormatUnsignedINT8  ArrayFormat = 0x01 // Unsigned 8-bit integers
	AdFormatUnsignedInt16 ArrayFormat = 0x02 // Unsigned 16-bit integers
	AdFormatUnsignedInt32 ArrayFormat = 0x03 // Unsigned 32-bit integers
	AdFormatSignedINT8    ArrayFormat = 0x08 // Signed 8-bit integers
	AdFormatSignedInt16   ArrayFormat = 0x09 // Signed 16-bit integers
	AdFormatSignedInt32   ArrayFormat = 0x0a // Signed 32-bit integers
	AdFormatHalf          ArrayFormat = 0x10 // 16-bit floating point
	AdFormatFloat         ArrayFormat = 0x20 // 32-bit floating point
	AdFormatNV12          ArrayFormat = 0xb0 // 8-bit YUV planar format, with 4:2:0 sampling
	AdFormatUnormInt8x1   ArrayFormat = 0xc0 // 1 channel unsigned 8-bit normalized integer
	AdFormatUnormInt8x2   ArrayFormat = 0xc1 // 2 channel unsigned 8-bit normalized integer
	AdFormatUnormInt8x4   ArrayFormat = 0xc2 // 4 channel unsigned 8-bit normalized integer
	AdFormatUnormInt16x1  ArrayFormat = 0xc3 // 1 channel unsigned 16-bit normalized integer
	AdFormatUnormInt16x2  ArrayFormat = 0xc4 // 2 channel unsigned 16-bit normalized integer
	AdFormatUnormInt16x4  ArrayFormat = 0xc5 // 4 channel unsigned 16-bit normalized integer
	AdFormatSnormInt8x1   ArrayFormat = 0xc6 // 1 channel signed 8-bit normalized integer
	AdFormatSnormInt8x2   ArrayFormat = 0xc7 // 2 channel signed 8-bit normalized integer
	AdFormatSnormInt8x4   ArrayFormat = 0xc8 // 4 channel signed 8-bit normalized integer
	AdFormatSnormInt16x1  ArrayFormat = 0xc9 // 1 channel signed 16-bit normalized integer
	AdFormatSnormInt16x2  ArrayFormat = 0xca // 2 channel signed 16-bit normalized integer
	AdFormatSnormInt16x4  ArrayFormat = 0xcb // 4 channel signed 16-bit normalized integer
	// AdFormatBC1Unorm: 4 channel unsigned normalized block-compressed (BC1 compression) format
	AdFormatBC1Unorm ArrayFormat = 0x91
	// AdFormatBC1UnormSrgb: 4 channel unsigned normalized block-compressed (BC1 compression) format with sRGB encoding
	AdFormatBC1UnormSrgb ArrayFormat = 0x92
	// AdFormatBC2Unorm: 4 channel unsigned normalized block-compressed (BC2 compression) format
	AdFormatBC2Unorm ArrayFormat = 0x93
	// AdFormatBC2UnormSrgb: 4 channel unsigned normalized block-compressed (BC2 compression) format with sRGB encoding
	AdFormatBC2UnormSrgb ArrayFormat = 0x94
	// AdFormatBC3Unorm: 4 channel unsigned normalized block-compressed (BC3 compression) format
	AdFormatBC3Unorm ArrayFormat = 0x95
	// AdFormatBC3UnormSrgb: 4 channel unsigned normalized block-compressed (BC3 compression) format with sRGB encoding
	AdFormatBC3UnormSrgb ArrayFormat = 0x96
	// AdFormatBC4Unorm: 1 channel unsigned normalized block-compressed (BC4 compression) format
	AdFormatBC4Unorm ArrayFormat = 0x97
	// AdFormatBC4Snorm: 1 channel signed normalized block-compressed (BC4 compression) format
	AdFormatBC4Snorm ArrayFormat = 0x98
	// AdFormatBC5Unorm: 2 channel unsigned normalized block-compressed (BC5 compression) format
	AdFormatBC5Unorm ArrayFormat = 0x99
	// AdFormatBC5Snorm: 2 channel signed normalized block-compressed (BC5 compression) format
	AdFormatBC5Snorm ArrayFormat = 0x9a
	// AdFormatBC6HUF16: 3 channel unsigned half-float block-compressed (BC6H compression) format
	AdFormatBC6HUF16 ArrayFormat = 0x9b
	// AdFormatBC6HSF16: 3 channel signed half-float block-compressed (BC6H compression) format
	AdFormatBC6HSF16 ArrayFormat = 0x9c
	// AdFormatBC7Unorm: 4 channel unsigned normalized block-compressed (BC7 compression) format
	AdFormatBC7Unorm ArrayFormat = 0x9d
	// AdFormatBC7UnormSrgb: 4 channel unsigned normalized block-compressed (BC7 compression) format with sRGB encoding
	AdFormatBC7UnormSrgb ArrayFormat = 0x9e
	AdFormatP010         ArrayFormat = 0x9f // 10-bit YUV planar format, with 4:2:0 sampling
	AdFormatP016         ArrayFormat = 0xa1 // 16-bit YUV planar format, with 4:2:0 sampling
	AdFormatNV16         ArrayFormat = 0xa2 // 8-bit YUV planar format, with 4:2:2 sampling
	AdFormatP210         ArrayFormat = 0xa3 // 10-bit YUV planar format, with 4:2:2 sampling
	AdFormatP216         ArrayFormat = 0xa4 // 16-bit YUV planar format, with 4:2:2 sampling
	// AdFormatYUY2: 2 channel, 8-bit YUV packed planar format, with 4:2:2 sampling
	AdFormatYUY2 ArrayFormat = 0xa5
	// AdFormatY210: 2 channel, 10-bit YUV packed planar format, with 4:2:2 sampling
	AdFormatY210 ArrayFormat = 0xa6
	// AdFormatY216: 2 channel, 16-bit YUV packed planar format, with 4:2:2 sampling
	AdFormatY216 ArrayFormat = 0xa7
	// AdFormatAyuv: 4 channel, 8-bit YUV packed planar format, with 4:4:4 sampling
	AdFormatAyuv ArrayFormat = 0xa8
	AdFormatY410 ArrayFormat = 0xa9 // 10-bit YUV packed planar format, with 4:4:4 sampling
	// AdFormatY416: 4 channel, 12-bit YUV packed planar format, with 4:4:4 sampling
	AdFormatY416                  ArrayFormat = 0xb1
	AdFormatY444Planar8           ArrayFormat = 0xb2 // 3 channel 8-bit YUV planar format, with 4:4:4 sampling
	AdFormatY444Planar10          ArrayFormat = 0xb3 // 3 channel 10-bit YUV planar format, with 4:4:4 sampling
	AdFormatYuv4448bitSemiplanar  ArrayFormat = 0xb4 // 3 channel 8-bit YUV semi-planar format, with 4:4:4 sampling
	AdFormatYuv44416bitSemiplanar ArrayFormat = 0xb5 // 3 channel 16-bit YUV semi-planar format, with 4:4:4 sampling
	AdFormatUnormInt1010102       ArrayFormat = 0x50 // 4 channel unorm R10G10B10A2 RGB format
	// AdFormatUint8Packed422: 4 channel unsigned 8-bit YUV packed format, with 4:2:2 sampling
	AdFormatUint8Packed422 ArrayFormat = 0x51
	// AdFormatUint8Packed444: 4 channel unsigned 8-bit YUV packed format, with 4:4:4 sampling
	AdFormatUint8Packed444 ArrayFormat = 0x52
	// AdFormatUint8Semiplanar420: 3 channel unsigned 8-bit YUV semi-planar format, with 4:2:0 sampling
	AdFormatUint8Semiplanar420 ArrayFormat = 0x53
	// AdFormatUint16Semiplanar420: 3 channel unsigned 16-bit YUV semi-planar format, with 4:2:0 sampling
	AdFormatUint16Semiplanar420 ArrayFormat = 0x54
	// AdFormatUint8Semiplanar422: 3 channel unsigned 8-bit YUV semi-planar format, with 4:2:2 sampling
	AdFormatUint8Semiplanar422 ArrayFormat = 0x55
	// AdFormatUint16Semiplanar422: 3 channel unsigned 16-bit YUV semi-planar format, with 4:2:2 sampling
	AdFormatUint16Semiplanar422 ArrayFormat = 0x56
	// AdFormatUint8Semiplanar444: 3 channel unsigned 8-bit YUV semi-planar format, with 4:4:4 sampling
	AdFormatUint8Semiplanar444 ArrayFormat = 0x57
	// AdFormatUint16Semiplanar444: 3 channel unsigned 16-bit YUV semi-planar format, with 4:4:4 sampling
	AdFormatUint16Semiplanar444 ArrayFormat = 0x58
	// AdFormatUint8Planar420: 3 channel unsigned 8-bit YUV planar format, with 4:2:0 sampling
	AdFormatUint8Planar420 ArrayFormat = 0x59
	// AdFormatUint16Planar420: 3 channel unsigned 16-bit YUV planar format, with 4:2:0 sampling
	AdFormatUint16Planar420 ArrayFormat = 0x5a
	// AdFormatUint8Planar422: 3 channel unsigned 8-bit YUV planar format, with 4:2:2 sampling
	AdFormatUint8Planar422 ArrayFormat = 0x5b
	// AdFormatUint16Planar422: 3 channel unsigned 16-bit YUV planar format, with 4:2:2 sampling
	AdFormatUint16Planar422 ArrayFormat = 0x5c
	// AdFormatUint8Planar444: 3 channel unsigned 8-bit YUV planar format, with 4:4:4 sampling
	AdFormatUint8Planar444 ArrayFormat = 0x5d
	// AdFormatUint16Planar444: 3 channel unsigned 16-bit YUV planar format, with 4:4:4 sampling
	AdFormatUint16Planar444 ArrayFormat = 0x5e
)

func (ArrayFormat) String

func (e ArrayFormat) String() string

String returns the constant name, or a numeric representation for unknown values.

type ArrayMapInfo

type ArrayMapInfo struct {
	// Resource type
	ResourceType Resourcetype
	Resource     [1]uint64
	// Sparse subresource type
	SubresourceType ArraySparseSubresourceType
	Subresource     [4]uint64
	// Memory operation type
	MemOperationType MemOperationType
	// Memory handle type
	MemHandleType MemHandleType
	MemHandle     [1]uint64
	// Offset within the memory
	Offset uint64
	// Device ordinal bit mask
	DeviceBitMask uint32
	// flags for future use, must be zero now.
	Flags uint32
	// Reserved for future use, must be zero now.
	Reserved [2]uint32
}

ArrayMapInfo specifies the CUDA array or CUDA mipmapped array memory mapping information.

type ArrayMapInfoV1

type ArrayMapInfoV1 = ArrayMapInfo

ArrayMapInfoV1 is an alias for ArrayMapInfo.

type ArrayMemoryRequirements

type ArrayMemoryRequirements struct {
	// Total required memory size
	Size uint
	// alignment requirement
	Alignment uint
	Reserved  [4]uint32
}

ArrayMemoryRequirements represents CUDA array memory requirements.

type ArrayMemoryRequirementsV1

type ArrayMemoryRequirementsV1 = ArrayMemoryRequirements

ArrayMemoryRequirementsV1 is an alias for ArrayMemoryRequirements.

type ArraySparseProperties

type ArraySparseProperties struct {
	TileExtent        [3]uint32
	MiptailFirstLevel uint32
	MiptailSize       uint64
	Flags             uint32
	Reserved          [4]uint32
}

ArraySparseProperties represents CUDA array sparse properties.

type ArraySparsePropertiesV1

type ArraySparsePropertiesV1 = ArraySparseProperties

ArraySparsePropertiesV1 is an alias for ArraySparseProperties.

type ArraySparseSubresourceType

type ArraySparseSubresourceType int32

ArraySparseSubresourceType represents sparse subresource types.

const (
	ArraySparseSubresourceTypeSparseLevel ArraySparseSubresourceType = 0
	ArraySparseSubresourceTypeMiptail     ArraySparseSubresourceType = 1
)

func (ArraySparseSubresourceType) String

String returns the constant name, or a numeric representation for unknown values.

type AsyncCallback

type AsyncCallback func(info uintptr, userData uintptr, callback AsyncCallbackHandle)

AsyncCallback is the Go form of CUasyncCallback.

It corresponds to the C signature

typedef void (*CUasyncCallback)(CUasyncNotificationInfo *info, void *userData, CUasyncCallbackHandle callback);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type AsyncCallbackHandle

type AsyncCallbackHandle uintptr

AsyncCallbackHandle is CUDA async notification callback handle.

type AsyncNotificationInfo

type AsyncNotificationInfo struct {
	// The type of notification being sent
	Type AsyncNotificationType
	Info [1]uint64
}

AsyncNotificationInfo represents information passed to the user via the async notification callback.

type AsyncNotificationType

type AsyncNotificationType int32

AsyncNotificationType represents types of async notification that can be sent.

const (
	AsyncNotificationTypeOverBudget AsyncNotificationType = 0x1 // Sent when the process has exceeded its device memory budget
)

func (AsyncNotificationType) String

func (e AsyncNotificationType) String() string

String returns the constant name, or a numeric representation for unknown values.

type AtomicOperation

type AtomicOperation int32

AtomicOperation represents CUDA-valid Atomic Operations.

const (
	AtomicOperationIntegerAdd       AtomicOperation = 0
	AtomicOperationIntegerMin       AtomicOperation = 1
	AtomicOperationIntegerMax       AtomicOperation = 2
	AtomicOperationIntegerIncrement AtomicOperation = 3
	AtomicOperationIntegerDecrement AtomicOperation = 4
	AtomicOperationAnd              AtomicOperation = 5
	AtomicOperationOr               AtomicOperation = 6
	AtomicOperationXor              AtomicOperation = 7
	AtomicOperationExchange         AtomicOperation = 8
	AtomicOperationCas              AtomicOperation = 9
	AtomicOperationFloatAdd         AtomicOperation = 10
	AtomicOperationFloatMin         AtomicOperation = 11
	AtomicOperationFloatMax         AtomicOperation = 12
)

func (AtomicOperation) String

func (e AtomicOperation) String() string

String returns the constant name, or a numeric representation for unknown values.

type AtomicOperationCapability

type AtomicOperationCapability int32

AtomicOperationCapability represents CUDA-valid Atomic Operation capabilities.

const (
	AtomicCapabilitySigned     AtomicOperationCapability = 1 << 0
	AtomicCapabilityUnsigned   AtomicOperationCapability = 1 << 1
	AtomicCapabilityReduction  AtomicOperationCapability = 1 << 2
	AtomicCapabilityScalar32   AtomicOperationCapability = 1 << 3
	AtomicCapabilityScalar64   AtomicOperationCapability = 1 << 4
	AtomicCapabilityScalar128  AtomicOperationCapability = 1 << 5
	AtomicCapabilityVector32x4 AtomicOperationCapability = 1 << 6
)

func (AtomicOperationCapability) String

func (e AtomicOperationCapability) String() string

String returns the constant name, or a numeric representation for unknown values.

type BatchMemOpNode

type BatchMemOpNode struct {
	GraphNode
}

BatchMemOpNode is a GraphNode of the batch mem op kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the BatchMemOpNode one takes the kind's own types.

func (BatchMemOpNode) Params

Params returns a batch mem op node’s parameters.

Returns the parameters of batch mem op node hNode. The paramArray returned is owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use BatchMemOpNode.SetParams to update the parameters of this node.

See also: GraphNode.Params, Stream.BatchMemOp, Graph.AddBatchMemOpNode, BatchMemOpNode.SetParams

Errors:

Wraps cuGraphBatchMemOpNodeGetParams.

func (BatchMemOpNode) SetParams

func (b BatchMemOpNode) SetParams(nodeParams *BatchMemOpNodeParams) error

SetParams sets a batch mem op node’s parameters.

Sets the parameters of batch mem op node hNode to nodeParams. The paramArray inside nodeParams is copied and therefore it can be freed after the call returns.

See also: GraphNode.SetParams, Stream.BatchMemOp, Graph.AddBatchMemOpNode, BatchMemOpNode.Params

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphBatchMemOpNodeSetParams.

type BatchMemOpNodeParams

type BatchMemOpNodeParams struct {
	Ctx        Context
	Count      uint32
	ParamArray uintptr
	Flags      uint32
}

BatchMemOpNodeParams represents batch memory operation node parameters.

Used in the legacy Graph.AddBatchMemOpNode api. New code should use Graph.AddNode

type BatchMemOpNodeParamsV1

type BatchMemOpNodeParamsV1 = BatchMemOpNodeParams

BatchMemOpNodeParamsV1 is an alias for BatchMemOpNodeParams.

type BatchMemOpNodeParamsV2

type BatchMemOpNodeParamsV2 struct {
	// Context to use for the operations.
	Ctx Context
	// Number of operations in paramArray.
	Count uint32
	// Array of batch memory operations.
	ParamArray uintptr
	// Flags to control the node.
	Flags uint32
}

BatchMemOpNodeParamsV2 represents batch memory operation node parameters.

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

BindFailure names a symbol the loaded library exports but that could not be bound, and why.

func BindFailures

func BindFailures() []BindFailure

BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.

A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.

type CallError

type CallError struct {
	Func   string // the C symbol called
	Result Result
}

CallError reports that a library call returned a failure result.

Unwrap returns Result, so errors.Is(err, c) reports whether the call returned the Result constant c, and errors.As(err, &r) with r of type Result recovers the code.

func (*CallError) Error

func (e *CallError) Error() string

Error reports the C symbol called and the result it returned.

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

Unwrap returns the result the call reported.

type CheckpointCheckpointArgs

type CheckpointCheckpointArgs struct {
	// Optional custom storage; if NULL, GPU memory is checkpointed to host
	CustomStorageInfoOut uintptr
	// Reserved for future use, must be zeroed
	Reserved [56]byte
}

CheckpointCheckpointArgs represents CUDA checkpoint optional checkpoint arguments.

type CheckpointCustomStorageInfo

type CheckpointCustomStorageInfo struct {
	// Handle returned that is needed to complete checkpoint or restore
	Handle CheckpointOperationHandle
	// Returned pointer to array of per-device data, one per device. User should set to NULL
	PerDeviceData uintptr
	// Number of devices (and elements in perDeviceData array)
	DeviceCount uint32
}

CheckpointCustomStorageInfo represents output from CUDA custom storage checkpoint/restore: per-GPU device pointers and a handle to complete the operation.

type CheckpointCustomStoragePerDeviceData

type CheckpointCustomStoragePerDeviceData struct {
	// Zero-copy mapped device memory pointer for the user to copy to/from
	DevPtr DevicePtr
	// Size of mapped memory
	Size uint
	// Stream the user may use for the copy; the CUDA driver synchronizes on this stream before completing checkpoint or restore
	Stream Stream
}

CheckpointCustomStoragePerDeviceData represents Per-GPU data for zero-copy mapped device memory used with CUDA checkpoint/restore on custom storage.

type CheckpointGpuPair

type CheckpointGpuPair struct {
	// UUID of the GPU that was checkpointed
	OldUuid Uuid
	// UUID of the GPU to restore onto
	NewUuid Uuid
}

CheckpointGpuPair represents CUDA checkpoint GPU UUID pairs for device remapping during restore.

type CheckpointLockArgs

type CheckpointLockArgs struct {
	// Timeout in milliseconds to attempt to lock the process, 0 indicates no timeout
	TimeoutMs uint32
	// Reserved for future use, must be zero
	Reserved0 uint32
	// Reserved for future use, must be zeroed
	Reserved1 [7]uint64
}

CheckpointLockArgs represents CUDA checkpoint optional lock arguments.

type CheckpointOperationHandle

type CheckpointOperationHandle uintptr

CheckpointOperationHandle is an opaque handle for CUcheckpointOperationHandle.

func (CheckpointOperationHandle) Complete

func (c CheckpointOperationHandle) Complete() error

Complete completes a custom-storage checkpoint or restores operation.

After CheckpointProcessCheckpoint or CheckpointProcessRestore with custom storage, CheckpointOperationHandle.Complete should be called when the application has finished or enqueued (on a stream) the required copies (for checkpoint, GPU mappings to custom storage and for restore, custom storage into GPU mappings) so the driver can finish the operation. CheckpointOperationHandle.Complete will first synchronize on the streams returned by CheckpointProcessCheckpoint or CheckpointProcessRestore. The driver assumes that the application has completed copying the memory to or from custom storage once synchronization is done. None of the streams returned by CheckpointProcessCheckpoint or CheckpointProcessRestore should be in stream capture mode; any attempt to do so would result in ErrStreamCaptureUnsupported. Once the synchronization is done, CheckpointOperationHandle.Complete will unmap the GPU memory that was mapped on each GPU in a particular CheckpointProcessCheckpoint or CheckpointProcessRestore operation. CheckpointOperationHandle.Complete identifies the operation to be completed using handle. This handle is set by CheckpointProcessCheckpoint or CheckpointProcessRestore. When the call returns successfully, the target process will be in the ProcessStateCheckpointed state when completing a checkpoint operation or the ProcessStateLocked state when completing a restore operation.

Requires CUDA 13.4 (driver r615) or later; see HasCheckpointOperationComplete.

Errors:

Wraps cuCheckpointOperationComplete.

type CheckpointRestoreArgs

type CheckpointRestoreArgs struct {
	// Pointer to array of gpu pairs that indicate how to remap GPUs during restore
	GpuPairs uintptr
	// Number of gpu pairs to remap
	GpuPairsCount uint32
	// Padding to align the following fields
	Padding0 uint32
	// Optional custom storage; if NULL, GPU memory is restored from host
	CustomStorageInfoOut uintptr
	// Reserved for future use, must be zeroed; includes alignment before customStorageInfo
	Reserved [40]byte
}

CheckpointRestoreArgs represents CUDA checkpoint optional restore arguments.

type CheckpointUnlockArgs

type CheckpointUnlockArgs struct {
	// Reserved for future use, must be zeroed
	Reserved [8]uint64
}

CheckpointUnlockArgs represents CUDA checkpoint optional unlock arguments.

type ChildGraphNode

type ChildGraphNode struct {
	GraphNode
}

ChildGraphNode is a GraphNode of the child graph kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the ChildGraphNode one takes the kind's own types.

func (ChildGraphNode) Graph

func (c ChildGraphNode) Graph() (Graph, error)

Graph gets a handle to the embedded graph of a child graph node.

Gets a handle to the embedded graph in a child graph node. This call does not clone the graph. Changes to the graph will be reflected in the node, and the node retains ownership of the graph. Allocation and free nodes cannot be added to the returned graph. Attempting to do so will return an error.

See also: Graph.AddChildGraphNode, GraphNode.FindInClone

Errors:

Wraps cuGraphChildGraphNodeGetGraph.

type ChildGraphNodeParams

type ChildGraphNodeParams struct {
	Graph Graph
	// The ownership relationship of the child graph node.
	Ownership GraphChildGraphNodeOwnership
}

ChildGraphNodeParams represents child graph node parameters.

type CigDataType

type CigDataType int32

CigDataType specifies the cig data type (CUcigDataType).

const (
	CigDataTypeD3d12CommandQueue CigDataType = 0x1 // D3D12 Command Queue Handle
	// CigDataTypeNvBlob: Nvidia specific data blob used for Vulkan and other NV clients
	CigDataTypeNvBlob CigDataType = 0x2
)

func (CigDataType) String

func (e CigDataType) String() string

String returns the constant name, or a numeric representation for unknown values.

type ClContextFlags

type ClContextFlags int32

ClContextFlags represents NVCL context scheduling flags.

const (
	ClContextFlagsCtxSchedAuto         ClContextFlags = 0x00 // Automatic scheduling
	ClContextFlagsCtxSchedSpin         ClContextFlags = 0x01 // Set spin as default scheduling
	ClContextFlagsCtxSchedYield        ClContextFlags = 0x02 // Set yield as default scheduling
	ClContextFlagsCtxSchedBlockingSync ClContextFlags = 0x04 // Set blocking synchronization as default scheduling
)

func (ClContextFlags) String

func (e ClContextFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type ClEventFlags

type ClEventFlags int32

ClEventFlags represents NVCL event scheduling flags.

const (
	ClEventFlagsEventSchedAuto         ClEventFlags = 0x00 // Automatic scheduling
	ClEventFlagsEventSchedSpin         ClEventFlags = 0x01 // Set spin as default scheduling
	ClEventFlagsEventSchedYield        ClEventFlags = 0x02 // Set yield as default scheduling
	ClEventFlagsEventSchedBlockingSync ClEventFlags = 0x04 // Set blocking synchronization as default scheduling
)

func (ClEventFlags) String

func (e ClEventFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type CliqueInfo

type CliqueInfo struct {
	// Type of the fabric clique
	Type CliqueType
	// ID of the fabric clique
	Id uint32
}

CliqueInfo represents fabric clique information.

type CliqueType

type CliqueType int32

CliqueType represents fabric clique types.

const (
	CliqueTypeUnicastPointer           CliqueType = 0 // Unicast pointer clique
	CliqueTypeMulticastPointer         CliqueType = 1 // Multicast pointer clique
	CliqueTypeUnicastLogicalEndpoint   CliqueType = 2 // Unicast logical endpoint clique
	CliqueTypeMulticastLogicalEndpoint CliqueType = 3 // Multicast logical endpoint clique
)

func (CliqueType) String

func (e CliqueType) String() string

String returns the constant name, or a numeric representation for unknown values.

type ClusterSchedulingPolicy

type ClusterSchedulingPolicy int32

ClusterSchedulingPolicy represents cluster scheduling policies.

These may be passed to Function.SetAttribute or Kernel.SetAttribute

const (
	ClusterSchedulingPolicyDefault ClusterSchedulingPolicy = 0 // the default policy
	ClusterSchedulingPolicySpread  ClusterSchedulingPolicy = 1 // spread the blocks within a cluster to the SMs
	// ClusterSchedulingPolicyLoadBalancing: allow the hardware to load-balance the blocks in a cluster to the SMs
	ClusterSchedulingPolicyLoadBalancing      ClusterSchedulingPolicy = 2
	ClusterSchedulingPolicyRubinDsmemLocality ClusterSchedulingPolicy = 3
)

func (ClusterSchedulingPolicy) String

func (e ClusterSchedulingPolicy) String() string

String returns the constant name, or a numeric representation for unknown values.

type Computemode

type Computemode int32

Computemode represents compute Modes.

const (
	ComputemodeDefault Computemode = 0 // Default compute mode (Multiple contexts allowed per device)
	// ComputemodeProhibited: Compute-prohibited mode (No contexts can be created on this device at this time)
	ComputemodeProhibited Computemode = 2
	// ComputemodeExclusiveProcess: Compute-exclusive-process mode (Only one context used by a single process can be present on this device at a time)
	ComputemodeExclusiveProcess Computemode = 3
)

func (Computemode) String

func (e Computemode) String() string

String returns the constant name, or a numeric representation for unknown values.

type ConditionalNodeParams

type ConditionalNodeParams struct {
	Handle uint64
	// Type of conditional node.
	Type       GraphConditionalNodeType
	Size       uint32
	PhGraphOut uintptr
	// Context on which to run the node. Must match context used to create the handle and all body nodes.
	Ctx Context
}

ConditionalNodeParams represents conditional node parameters.

type Context

type Context uintptr

Context is an opaque handle to a CUDA context. Created via NewContext and destroyed via [Context.Destroy].

func CtxAttach deprecated

func CtxAttach(flags uint32) (Context, error)

CtxAttach increments a context’s usage-count.

Increments the usage count of the context and passes back a context handle that must be passed to Context.Detach when the application is done with the context. CtxAttach fails if there is no context current to the thread. Currently, the flags parameter must be 0.

See also: NewContext, Context.Close, Context.Detach, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

  • flags: Context attach flags (must be 0)

Errors:

Wraps cuCtxAttach.

Deprecated: Deprecated by NVIDIA. This function is deprecated and should not be used.

func CtxCreateV2 deprecated

func CtxCreateV2(flags CtxFlags, dev Device) (Context, error)

CtxCreateV2 creates a CUDA context.

Creates a new CUDA context and associates it with the calling thread. The flags parameter is described below. The context is created with a usage count of 1 and the caller of NewContext must call Context.Close when done using the context. If a context is already current to the thread, it is supplanted by the newly created context and may be restored by a subsequent call to CtxPopCurrent. A regular CUDA context can be created by setting ctxCreateParams to NULL. A CUDA context can be created with execution affinity. The type and the amount of execution resource the context can use is limited by paramsArray and numExecAffinityParams in execAffinity. The paramsArray is an array of ExecAffinityParam and the numExecAffinityParams describes the size of the paramsArray. If two ExecAffinityParam in the array have the same type, the latter execution affinity parameter overrides the former execution affinity parameter. The supported execution affinity types are:

  • ExecAffinityTypeSmCount limits the portion of SMs that the context can use. The portion of SMs is specified as the number of SMs via ExecAffinitySmCount. This limit will be internally rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution affinity of the context via CtxGetExecAffinity after context creation. Currently, this attribute is only supported under Volta+ MPS.

A CUDA context can be created in CIG(CUDA in Graphics) mode by setting cigParams. Data from graphics client is shared with CUDA via the sharedData in cigParams. Support for D3D12 graphics client can be determined using Device.Attribute with DevAttrD3d12CigSupported. sharedData is a ID3D12CommandQueue handle. Support for Vulkan graphics client can be determined using Device.Attribute with DevAttrVulkanCigSupported. sharedData is a Nvidia specific data blob populated by calling vkGetExternalComputeQueueDataNV(). execAffinityParams and cigParams are mutually exclusive and cannot both be non-NULL. Setting both to non-NULL values will result in undefined behavior. If both execAffinityParams and cigParams are NULL, the context will be created as a regular CUDA context. The three LSBs of the flags parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context.

  • CtxSchedSpin: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
  • CtxSchedYield: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU.
  • CtxSchedBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work.
  • CtxBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. Deprecated: This flag was deprecated as of CUDA 4.0 and was replaced with CtxSchedBlockingSync.
  • CtxSchedAuto: 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 GPU ( CtxSchedYield), otherwise CUDA will not yield while waiting for results and actively spin on the processor ( CtxSchedSpin). Additionally, on Tegra devices, CtxSchedAuto uses a heuristic based on the power profile of the platform and may choose CtxSchedBlockingSync for low-powered devices.
  • CtxMapHost: Instruct CUDA to support mapped pinned allocations. This flag must be set in order to allocate pinned host memory that is accessible to the GPU.
  • CtxLmemResizeToMax: 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. Instead, the per-thread stack size can be controlled with CtxSetLimit.
  • CtxCoredumpEnable: If GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxUserCoredumpEnable: If user-triggered GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. It is important to note that the pipe name must be set with CoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CtxCoredumpEnable is set. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. Setting this flag on any context creation is equivalent to setting the CoredumpEnableUserTrigger attribute to true globally. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxSyncMemops: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled “API Synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

Context creation will fail with ErrUnknown if the compute mode of the device is ComputemodeProhibited. The function Device.Attribute can be used with DevAttrComputeMode to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for * devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. Context creation will fail with ErrInvalidValue if invalid parameter was passed by client to create the CUDA context. Context creation in CIG mode will fail with ErrNotSupported if CIG is not supported by the device or the driver.

See also: Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CoredumpSetAttributeGlobal, CoredumpSetAttribute, CtxSynchronize CtxGetExecAffinity

  • flags: Context creation flags
  • dev: Device to create context on

Errors:

Wraps cuCtxCreate_v2.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func CtxCreateV3 deprecated

func CtxCreateV3(paramsArray *ExecAffinityParam, numParams int32, flags CtxFlags, dev Device) (Context, error)

CtxCreateV3 creates a CUDA context.

Creates a new CUDA context and associates it with the calling thread. The flags parameter is described below. The context is created with a usage count of 1 and the caller of NewContext must call Context.Close when done using the context. If a context is already current to the thread, it is supplanted by the newly created context and may be restored by a subsequent call to CtxPopCurrent. A regular CUDA context can be created by setting ctxCreateParams to NULL. A CUDA context can be created with execution affinity. The type and the amount of execution resource the context can use is limited by paramsArray and numExecAffinityParams in execAffinity. The paramsArray is an array of ExecAffinityParam and the numExecAffinityParams describes the size of the paramsArray. If two ExecAffinityParam in the array have the same type, the latter execution affinity parameter overrides the former execution affinity parameter. The supported execution affinity types are:

  • ExecAffinityTypeSmCount limits the portion of SMs that the context can use. The portion of SMs is specified as the number of SMs via ExecAffinitySmCount. This limit will be internally rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution affinity of the context via CtxGetExecAffinity after context creation. Currently, this attribute is only supported under Volta+ MPS.

A CUDA context can be created in CIG(CUDA in Graphics) mode by setting cigParams. Data from graphics client is shared with CUDA via the sharedData in cigParams. Support for D3D12 graphics client can be determined using Device.Attribute with DevAttrD3d12CigSupported. sharedData is a ID3D12CommandQueue handle. Support for Vulkan graphics client can be determined using Device.Attribute with DevAttrVulkanCigSupported. sharedData is a Nvidia specific data blob populated by calling vkGetExternalComputeQueueDataNV(). execAffinityParams and cigParams are mutually exclusive and cannot both be non-NULL. Setting both to non-NULL values will result in undefined behavior. If both execAffinityParams and cigParams are NULL, the context will be created as a regular CUDA context. The three LSBs of the flags parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context.

  • CtxSchedSpin: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
  • CtxSchedYield: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU.
  • CtxSchedBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work.
  • CtxBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. Deprecated: This flag was deprecated as of CUDA 4.0 and was replaced with CtxSchedBlockingSync.
  • CtxSchedAuto: 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 GPU ( CtxSchedYield), otherwise CUDA will not yield while waiting for results and actively spin on the processor ( CtxSchedSpin). Additionally, on Tegra devices, CtxSchedAuto uses a heuristic based on the power profile of the platform and may choose CtxSchedBlockingSync for low-powered devices.
  • CtxMapHost: Instruct CUDA to support mapped pinned allocations. This flag must be set in order to allocate pinned host memory that is accessible to the GPU.
  • CtxLmemResizeToMax: 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. Instead, the per-thread stack size can be controlled with CtxSetLimit.
  • CtxCoredumpEnable: If GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxUserCoredumpEnable: If user-triggered GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. It is important to note that the pipe name must be set with CoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CtxCoredumpEnable is set. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. Setting this flag on any context creation is equivalent to setting the CoredumpEnableUserTrigger attribute to true globally. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxSyncMemops: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled “API Synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

Context creation will fail with ErrUnknown if the compute mode of the device is ComputemodeProhibited. The function Device.Attribute can be used with DevAttrComputeMode to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for * devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. Context creation will fail with ErrInvalidValue if invalid parameter was passed by client to create the CUDA context. Context creation in CIG mode will fail with ErrNotSupported if CIG is not supported by the device or the driver.

See also: Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CoredumpSetAttributeGlobal, CoredumpSetAttribute, CtxSynchronize CtxGetExecAffinity

  • paramsArray: Execution affinity parameters
  • numParams: Number of execution affinity parameters
  • flags: Context creation flags
  • dev: Device to create context on

Errors:

Wraps cuCtxCreate_v3.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func CtxCreateV4

func CtxCreateV4(ctxCreateParams *CtxCreateParams, flags CtxFlags, dev Device) (Context, error)

CtxCreateV4 creates a CUDA context.

Creates a new CUDA context and associates it with the calling thread. The flags parameter is described below. The context is created with a usage count of 1 and the caller of NewContext must call Context.Close when done using the context. If a context is already current to the thread, it is supplanted by the newly created context and may be restored by a subsequent call to CtxPopCurrent. A regular CUDA context can be created by setting ctxCreateParams to NULL. A CUDA context can be created with execution affinity. The type and the amount of execution resource the context can use is limited by paramsArray and numExecAffinityParams in execAffinity. The paramsArray is an array of ExecAffinityParam and the numExecAffinityParams describes the size of the paramsArray. If two ExecAffinityParam in the array have the same type, the latter execution affinity parameter overrides the former execution affinity parameter. The supported execution affinity types are:

  • ExecAffinityTypeSmCount limits the portion of SMs that the context can use. The portion of SMs is specified as the number of SMs via ExecAffinitySmCount. This limit will be internally rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution affinity of the context via CtxGetExecAffinity after context creation. Currently, this attribute is only supported under Volta+ MPS.

A CUDA context can be created in CIG(CUDA in Graphics) mode by setting cigParams. Data from graphics client is shared with CUDA via the sharedData in cigParams. Support for D3D12 graphics client can be determined using Device.Attribute with DevAttrD3d12CigSupported. sharedData is a ID3D12CommandQueue handle. Support for Vulkan graphics client can be determined using Device.Attribute with DevAttrVulkanCigSupported. sharedData is a Nvidia specific data blob populated by calling vkGetExternalComputeQueueDataNV(). execAffinityParams and cigParams are mutually exclusive and cannot both be non-NULL. Setting both to non-NULL values will result in undefined behavior. If both execAffinityParams and cigParams are NULL, the context will be created as a regular CUDA context. The three LSBs of the flags parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context.

  • CtxSchedSpin: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
  • CtxSchedYield: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU.
  • CtxSchedBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work.
  • CtxBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. Deprecated: This flag was deprecated as of CUDA 4.0 and was replaced with CtxSchedBlockingSync.
  • CtxSchedAuto: 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 GPU ( CtxSchedYield), otherwise CUDA will not yield while waiting for results and actively spin on the processor ( CtxSchedSpin). Additionally, on Tegra devices, CtxSchedAuto uses a heuristic based on the power profile of the platform and may choose CtxSchedBlockingSync for low-powered devices.
  • CtxMapHost: Instruct CUDA to support mapped pinned allocations. This flag must be set in order to allocate pinned host memory that is accessible to the GPU.
  • CtxLmemResizeToMax: 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. Instead, the per-thread stack size can be controlled with CtxSetLimit.
  • CtxCoredumpEnable: If GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxUserCoredumpEnable: If user-triggered GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. It is important to note that the pipe name must be set with CoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CtxCoredumpEnable is set. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. Setting this flag on any context creation is equivalent to setting the CoredumpEnableUserTrigger attribute to true globally. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxSyncMemops: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled “API Synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

Context creation will fail with ErrUnknown if the compute mode of the device is ComputemodeProhibited. The function Device.Attribute can be used with DevAttrComputeMode to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for * devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. Context creation will fail with ErrInvalidValue if invalid parameter was passed by client to create the CUDA context. Context creation in CIG mode will fail with ErrNotSupported if CIG is not supported by the device or the driver.

See also: Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CoredumpSetAttributeGlobal, CoredumpSetAttribute, CtxSynchronize CtxGetExecAffinity

Requires CUDA 12.5 (driver r555) or later; see HasCtxCreateV4.

  • ctxCreateParams: Context creation parameters. Can be NULL to create a regular CUDA context. See CtxCreateParams for details
  • flags: Context creation flags
  • dev: Device to create context on

Errors:

Wraps cuCtxCreate, bound as cuCtxCreate_v4.

func CtxFromGreenCtx

func CtxFromGreenCtx(hCtx GreenCtx) (Context, error)

CtxFromGreenCtx returns a Context handle for a green context.

This API returns a Context handle that represents the specified green context hCtx. The returned handle can be passed to CUDA APIs that accept a Context and will be treated as if it were a primary context, while still honoring the resources and configuration associated with hCtx as applicable. Applications that wish to use a green context with CUDA APIs that require a Context must use this API to obtain a handle to a Context representing the green context. Otherwise, passing a green context to such APIs will fail with ErrInvalidContext. The Context returned by CtxFromGreenCtx may be passed to CUDA Driver APIs that accept a Context.

  • For APIs whose semantics are independent of green context resources, the operation is performed identically to how it would perform with a primary context.
  • For APIs whose behavior depends on green context resources (for example, kernel launch), the operation is performed using the resources and configuration of the specified green context hCtx.

This call does not create a new independent context and does not change the underlying context lifetime. The validity of the returned pContext is tied to hCtx, and no additional destruction or release is required beyond correctly managing hCtx with the green context APIs. Destroying pContext via Context.Close is undefined behavior.

See also: NewGreenCtx

Requires CUDA 12.4 (driver r550) or later; see HasCtxFromGreenCtx.

  • hCtx: Green context to convert

Errors:

Wraps cuCtxFromGreenCtx.

func CtxGetCurrent

func CtxGetCurrent() (Context, error)

CtxGetCurrent returns the CUDA context bound to the calling CPU thread.

Returns the CUDA context bound to the calling CPU thread. If no context is bound to the calling CPU thread then the result is NULL and Success is returned.

See also: Context.SetCurrent, NewContext, Context.Close, cudaGetDevice

Errors:

Wraps cuCtxGetCurrent.

func CtxPopCurrent

func CtxPopCurrent() (Context, error)

CtxPopCurrent pops the current CUDA context from the current CPU thread.

Pops the current CUDA context from the CPU thread and passes back the old context handle. That context may then be made current to a different CPU thread by calling Context.PushCurrent. If a context was current to the CPU thread before NewContext or Context.PushCurrent was called, this function makes that context current to the CPU thread again.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuCtxPopCurrent, bound as cuCtxPopCurrent_v2.

func NewContext

func NewContext(dev Device, flags CtxFlags) (Context, error)

NewContext creates a CUDA context.

  • flags: Context creation flags
  • dev: Device to create context on

Errors:

It is NewContextParams with nil ctxCreateParams.

Wraps cuCtxCreate, bound to the first of cuCtxCreate_v4, cuCtxCreate_v2 that the library exports. On libraries without cuCtxCreate_v4, it calls cuCtxCreate_v2; a non-nil ctxCreateParams returns ErrNotSupported.

func NewContextParams

func NewContextParams(ctxCreateParams *CtxCreateParams, flags CtxFlags, dev Device) (Context, error)

NewContextParams creates a CUDA context.

Creates a new CUDA context and associates it with the calling thread. The flags parameter is described below. The context is created with a usage count of 1 and the caller of NewContext must call Context.Close when done using the context. If a context is already current to the thread, it is supplanted by the newly created context and may be restored by a subsequent call to CtxPopCurrent. A regular CUDA context can be created by setting ctxCreateParams to NULL. A CUDA context can be created with execution affinity. The type and the amount of execution resource the context can use is limited by paramsArray and numExecAffinityParams in execAffinity. The paramsArray is an array of ExecAffinityParam and the numExecAffinityParams describes the size of the paramsArray. If two ExecAffinityParam in the array have the same type, the latter execution affinity parameter overrides the former execution affinity parameter. The supported execution affinity types are:

  • ExecAffinityTypeSmCount limits the portion of SMs that the context can use. The portion of SMs is specified as the number of SMs via ExecAffinitySmCount. This limit will be internally rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution affinity of the context via CtxGetExecAffinity after context creation. Currently, this attribute is only supported under Volta+ MPS.

A CUDA context can be created in CIG(CUDA in Graphics) mode by setting cigParams. Data from graphics client is shared with CUDA via the sharedData in cigParams. Support for D3D12 graphics client can be determined using Device.Attribute with DevAttrD3d12CigSupported. sharedData is a ID3D12CommandQueue handle. Support for Vulkan graphics client can be determined using Device.Attribute with DevAttrVulkanCigSupported. sharedData is a Nvidia specific data blob populated by calling vkGetExternalComputeQueueDataNV(). execAffinityParams and cigParams are mutually exclusive and cannot both be non-NULL. Setting both to non-NULL values will result in undefined behavior. If both execAffinityParams and cigParams are NULL, the context will be created as a regular CUDA context. The three LSBs of the flags parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context.

  • CtxSchedSpin: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
  • CtxSchedYield: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU.
  • CtxSchedBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work.
  • CtxBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. Deprecated: This flag was deprecated as of CUDA 4.0 and was replaced with CtxSchedBlockingSync.
  • CtxSchedAuto: 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 GPU ( CtxSchedYield), otherwise CUDA will not yield while waiting for results and actively spin on the processor ( CtxSchedSpin). Additionally, on Tegra devices, CtxSchedAuto uses a heuristic based on the power profile of the platform and may choose CtxSchedBlockingSync for low-powered devices.
  • CtxMapHost: Instruct CUDA to support mapped pinned allocations. This flag must be set in order to allocate pinned host memory that is accessible to the GPU.
  • CtxLmemResizeToMax: 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. Instead, the per-thread stack size can be controlled with CtxSetLimit.
  • CtxCoredumpEnable: If GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxUserCoredumpEnable: If user-triggered GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. It is important to note that the pipe name must be set with CoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CtxCoredumpEnable is set. The initial attributes will be taken from the global attributes at the time of context creation. The other attributes that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current. Setting this flag on any context creation is equivalent to setting the CoredumpEnableUserTrigger attribute to true globally. This flag is not supported when CUDA context is created in CIG(CUDA in Graphics) mode.
  • CtxSyncMemops: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled “API Synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

Context creation will fail with ErrUnknown if the compute mode of the device is ComputemodeProhibited. The function Device.Attribute can be used with DevAttrComputeMode to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for * devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. Context creation will fail with ErrInvalidValue if invalid parameter was passed by client to create the CUDA context. Context creation in CIG mode will fail with ErrNotSupported if CIG is not supported by the device or the driver.

See also: Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CoredumpSetAttributeGlobal, CoredumpSetAttribute, CtxSynchronize CtxGetExecAffinity

  • ctxCreateParams: Context creation parameters. Can be NULL to create a regular CUDA context. See CtxCreateParams for details
  • flags: Context creation flags
  • dev: Device to create context on

Errors:

Wraps cuCtxCreate, bound to the first of cuCtxCreate_v4, cuCtxCreate_v2 that the library exports. On libraries without cuCtxCreate_v4, it calls cuCtxCreate_v2; a non-nil ctxCreateParams returns ErrNotSupported.

func (Context) ApiVersion

func (c Context) ApiVersion() (uint32, error)

ApiVersion gets the context’s API version.

Returns a version number corresponding to the capabilities of the context (e.g. 3010 or 3020), which library developers can use to direct callers to a specific API version. If ctx is NULL, returns the API version used to create the currently bound context. Note that new API versions are only introduced when context capabilities are changed that break binary compatibility, so the API version and driver version may be different. For example, it is valid for the API version to be 3020 while the driver version is 4020.

See also: NewContext, Context.Close, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuCtxGetApiVersion.

func (*Context) Close

func (c *Context) Close() error

Close destroys a CUDA context.

Destroys the CUDA context specified by ctx. The context ctx will be destroyed regardless of how many threads it is current to. It is the responsibility of the calling function to ensure that no API call issues using ctx while Context.Close is executing. Destroys and cleans up all resources associated with the context. It is the caller’s responsibility to ensure that the context or its resources are not accessed or passed in subsequent API calls and doing so will result in undefined behavior. These resources include CUDA types Module, Function, Stream, Event, Array, MipmappedArray, CUtexObject, CUsurfObject, TexRef, SurfRef, GraphicsResource, LinkState, ExternalMemory and ExternalSemaphore. These resources also include memory allocations by MemAlloc, MemAllocHost, MemAllocManaged and MemAllocPitch. If ctx is current to the calling thread then ctx will also be popped from the current thread’s context stack (as though CtxPopCurrent were called). If ctx is current to other threads, then ctx will remain current to those threads, and attempting to access ctx from those threads will result in the error ErrContextIsDestroyed.

Note: Context.Close will not destroy memory allocations by MemCreate, Stream.MemAllocAsync and MemoryPool.MemAllocFromPoolAsync. These memory allocations are not associated with any CUDA context and need to be destroyed explicitly.

See also: NewContext, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

If c is zero, Close returns nil. Otherwise Close sets c to zero when the call succeeds and leaves it unchanged when it fails. Only c is zeroed: a copy of it still refers to the released object.

Wraps cuCtxDestroy, bound as cuCtxDestroy_v2.

func (Context) Detach deprecated

func (c Context) Detach() error

Detach decrements a context’s usage-count.

Decrements the usage count of the context ctx, and destroys the context if the usage count goes to 0. The context must be a handle that was passed back by NewContext or CtxAttach, and must be current to the calling thread.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuCtxDetach.

Deprecated: Deprecated by NVIDIA. This function is deprecated and should not be used.

func (Context) DevResource

func (c Context) DevResource(type_ DevResourceType) (DevResource, error)

DevResource gets context resources.

Get the type resources available to the context represented by hCtx Note: The API is not supported on 32-bit platforms.

See also: DevResourceGenerateDesc

Requires CUDA 12.4 (driver r550) or later; see HasCtxGetDevResource.

  • type_: Type of resource to retrieve

Errors:

Wraps cuCtxGetDevResource.

func (Context) DeviceV2

func (c Context) DeviceV2() (Device, error)

DeviceV2 returns the device handle for the specified context.

Returns the handle of the specified context’s device. If the specified context is NULL, the API will return the current context’s device.

See also: CtxGetCurrent, CtxPopCurrent, Context.PushCurrent

Requires CUDA 13.0 (driver r580) or later; see HasCtxGetDeviceV2.

Errors:

Wraps cuCtxGetDevice_v2.

func (Context) DisablePeerAccess

func (c Context) DisablePeerAccess() error

DisablePeerAccess disables direct access to memory allocations in a peer context and unregisters any registered allocations.

Returns ErrPeerAccessNotEnabled if direct peer access has not yet been enabled from peerContext to the current context. Returns ErrInvalidContext if there is no current context, or if peerContext is not a valid context.

See also: Device.CanAccessPeer, Context.EnablePeerAccess, cudaDeviceDisablePeerAccess

Errors:

Wraps cuCtxDisablePeerAccess.

func (Context) EnablePeerAccess

func (c Context) EnablePeerAccess(flags uint32) error

EnablePeerAccess enables direct access to memory allocations in a peer context.

If both the current context and peerContext are on devices which support unified addressing (as may be queried using DevAttrUnifiedAddressing) and same major compute capability, then on success all allocations from peerContext will immediately be accessible by the current context. See Unified Addressing for additional details. Note that access granted by this call is unidirectional and that in order to access memory from the current context in peerContext, a separate symmetric call to Context.EnablePeerAccess is required. Note that there are both device-wide and system-wide limitations per system configuration, as noted in the CUDA Programming Guide under the section “Peer-to-Peer Memory Access”. Returns ErrPeerAccessUnsupported if Device.CanAccessPeer indicates that the Device of the current context cannot directly access memory from the Device of peerContext. Returns ErrPeerAccessAlreadyEnabled if direct access of peerContext from the current context has already been enabled. Returns ErrTooManyPeers if direct peer access is not possible because hardware resources required for peer access have been exhausted. Returns ErrInvalidContext if there is no current context, peerContext is not a valid context, or if the current context is peerContext. Returns ErrInvalidValue if Flags is not 0.

See also: Device.CanAccessPeer, Context.DisablePeerAccess, cudaDeviceEnablePeerAccess

  • flags: Reserved for future use and must be set to 0

Errors:

Wraps cuCtxEnablePeerAccess.

func (Context) Id

func (c Context) Id() (uint64, error)

Id returns the unique Id associated with the context supplied.

Returns the unique Id which is associated with a given context. The Id is unique for the life of the program for this instance of CUDA. If context is supplied as NULL and there is one current, the Id of the current context is returned.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, Context.PushCurrent

Errors:

Wraps cuCtxGetId.

func (Context) PushCurrent

func (c Context) PushCurrent() error

PushCurrent pushes a context on the current CPU thread.

Pushes the given context ctx onto the CPU thread’s stack of current contexts. The specified context becomes the CPU thread’s current context, so all CUDA functions that operate on the current context are affected. The previous current context may be made current again by calling Context.Close or CtxPopCurrent.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuCtxPushCurrent, bound as cuCtxPushCurrent_v2.

func (Context) RecordEvent

func (c Context) RecordEvent(hEvent Event) error

RecordEvent records an event.

Captures in hEvent all the activities of the context hCtx at the time of this call. hEvent and hCtx must be from the same CUDA context, otherwise ErrInvalidHandle will be returned. Calls such as Event.Query or Context.WaitEvent will then examine or wait for completion of the work that was captured. Uses of hCtx after this call do not modify hEvent. If the context passed to hCtx is the primary context, hEvent will capture all the activities of the primary context and its green contexts. If the context passed to hCtx is a context converted from green context via CtxFromGreenCtx, hEvent will capture only the activities of the green context.

Note: The API will return ErrStreamCaptureUnsupported if the specified context hCtx has a stream in the capture mode. In such a case, the call will invalidate all the conflicting captures.

See also: Context.WaitEvent, GreenCtx.RecordEvent, GreenCtx.WaitEvent, Event.Record

Requires CUDA 12.5 (driver r555) or later; see HasCtxRecordEvent.

  • hEvent: Event to record

Errors:

Wraps cuCtxRecordEvent.

func (Context) SetCurrent

func (c Context) SetCurrent() error

SetCurrent binds the specified CUDA context to the calling CPU thread.

If ctx is NULL then the CUDA context previously bound to the calling CPU thread is unbound and Success is returned. If there exists a CUDA context stack on the calling CPU thread, this will replace the top of that stack with ctx. If ctx is NULL then this will be equivalent to popping the top of the calling CPU thread’s CUDA context stack (or a no-op if the calling CPU thread’s CUDA context stack is empty).

See also: CtxGetCurrent, NewContext, Context.Close, cudaSetDevice

Errors:

Wraps cuCtxSetCurrent.

func (Context) SynchronizeV2

func (c Context) SynchronizeV2() error

SynchronizeV2 blocks for the specified context’s tasks to complete.

Blocks until the specified context has completed all preceding requested tasks. If the specified context is the primary context, green contexts that have been created will also be synchronized. The API returns an error if one of the preceding tasks failed. If the context was created with the CtxSchedBlockingSync flag, the CPU thread will block until the GPU context has finished its work. If the specified context is NULL, the API will operate on the current context.

See also: CtxGetCurrent, CtxPopCurrent, Context.PushCurrent, NewGreenCtx, CtxFromGreenCtx, cudaDeviceSynchronize

Requires CUDA 13.0 (driver r580) or later; see HasCtxSynchronizeV2.

Errors:

Wraps cuCtxSynchronize_v2.

func (Context) WaitEvent

func (c Context) WaitEvent(hEvent Event) error

WaitEvent makes a context wait on an event.

Makes all future work submitted to context hCtx wait for all work captured in hEvent. The synchronization will be performed on the device and will not block the calling CPU thread. See Context.RecordEvent for details on what is captured by an event. If the context passed to hCtx is the primary context, the primary context and its green contexts will wait for hEvent. If the context passed to hCtx is a context converted from green context via CtxFromGreenCtx, the green context will wait for hEvent.

Note: hEvent may be from a different context or device than hCtx.

Note: The API will return ErrStreamCaptureUnsupported and invalidate the capture if the specified event hEvent is part of an ongoing capture sequence or if the specified context hCtx has a stream in the capture mode.

See also: Context.RecordEvent, GreenCtx.RecordEvent, GreenCtx.WaitEvent, Stream.WaitEvent

Requires CUDA 12.5 (driver r555) or later; see HasCtxWaitEvent.

  • hEvent: Event to wait on

Errors:

Wraps cuCtxWaitEvent.

type CoredumpCallbackHandle

type CoredumpCallbackHandle uintptr

CoredumpCallbackHandle is an opaque handle for CUcoredumpCallbackHandle.

func CoredumpRegisterCompleteCallback

func CoredumpRegisterCompleteCallback(callback uintptr, userData uintptr) (CoredumpCallbackHandle, error)

CoredumpRegisterCompleteCallback registers a callback to be invoked when a GPU coredump completes.

This function registers a callback that will be called when a GPU coredump has been fully collected and written to disk. Callbacks are executed in the order they were registered. The same callback function can be registered multiple times with different userData, and each registration will receive a unique handle.

Note: Callbacks execute synchronously during the coredump process and will block coredump progress while running.

See also: CoredumpCallbackHandle.DeregisterCompleteCallback, CoredumpRegisterStartCallback

Requires CUDA 13.2 (driver r595) or later; see HasCoredumpRegisterCompleteCallback.

  • callback: The callback function to register (see CoredumpStatusCallback)
  • userData: User data pointer to pass to the callback

Errors:

Wraps cuCoredumpRegisterCompleteCallback.

func CoredumpRegisterStartCallback

func CoredumpRegisterStartCallback(callback uintptr, userData uintptr) (CoredumpCallbackHandle, error)

CoredumpRegisterStartCallback registers a callback to be invoked when a GPU coredump begins.

This function registers a callback that will be called when a GPU coredump is initiated, before any coredump data is collected. Callbacks are executed in the order they were registered. The same callback function can be registered multiple times with different userData, and each registration will receive a unique handle.

Note: Callbacks execute synchronously during the coredump process and will block coredump progress while running.

See also: CoredumpCallbackHandle.DeregisterStartCallback, CoredumpRegisterCompleteCallback

Requires CUDA 13.2 (driver r595) or later; see HasCoredumpRegisterStartCallback.

  • callback: The callback function to register (see CoredumpStatusCallback)
  • userData: User data pointer to pass to the callback

Errors:

Wraps cuCoredumpRegisterStartCallback.

func (CoredumpCallbackHandle) DeregisterCompleteCallback

func (c CoredumpCallbackHandle) DeregisterCompleteCallback() error

DeregisterCompleteCallback deregisters a previously registered coredump complete callback.

This function removes a callback that was registered with CoredumpRegisterCompleteCallback. The callback handle becomes invalid after this call.

Note: It is the caller’s responsibility to deregister callbacks before they go out of scope.

See also: CoredumpRegisterCompleteCallback

Requires CUDA 13.2 (driver r595) or later; see HasCoredumpDeregisterCompleteCallback.

Errors:

It is not named Close because CoredumpCallbackHandle has another release method, DeregisterStartCallback.

Wraps cuCoredumpDeregisterCompleteCallback.

func (CoredumpCallbackHandle) DeregisterStartCallback

func (c CoredumpCallbackHandle) DeregisterStartCallback() error

DeregisterStartCallback deregisters a previously registered coredump start callback.

This function removes a callback that was registered with CoredumpRegisterStartCallback. The callback handle becomes invalid after this call.

Note: It is the caller’s responsibility to deregister callbacks before they go out of scope.

See also: CoredumpRegisterStartCallback

Requires CUDA 13.2 (driver r595) or later; see HasCoredumpDeregisterStartCallback.

Errors:

It is not named Close because CoredumpCallbackHandle has another release method, DeregisterCompleteCallback.

Wraps cuCoredumpDeregisterStartCallback.

type CoredumpGenerationFlags

type CoredumpGenerationFlags uint32

CoredumpGenerationFlags represents flags for controlling coredump contents.

const (
	CoredumpDefaultFlags              CoredumpGenerationFlags = 0
	CoredumpSkipNonrelocatedElfImages CoredumpGenerationFlags = 1 << 0
	CoredumpSkipGlobalMemory          CoredumpGenerationFlags = 1 << 1
	CoredumpSkipSharedMemory          CoredumpGenerationFlags = 1 << 2
	CoredumpSkipLocalMemory           CoredumpGenerationFlags = 1 << 3
	CoredumpSkipAbort                 CoredumpGenerationFlags = 1 << 4
	CoredumpSkipConstbankMemory       CoredumpGenerationFlags = 1 << 5
	CoredumpGzipCompress              CoredumpGenerationFlags = 1 << 6
	CoredumpFaultedContextsOnly       CoredumpGenerationFlags = 1 << 7
	CoredumpSkipTensorMemory          CoredumpGenerationFlags = 1 << 8
	CoredumpNoErrbarAtExit            CoredumpGenerationFlags = 1 << 30
	CoredumpLogOnly                   CoredumpGenerationFlags = 1 << 31
	CoredumpLightweightFlags          CoredumpGenerationFlags = CoredumpSkipNonrelocatedElfImages | CoredumpSkipGlobalMemory | CoredumpSkipSharedMemory | CoredumpSkipLocalMemory | CoredumpSkipConstbankMemory | CoredumpSkipTensorMemory
)

func (CoredumpGenerationFlags) String

func (e CoredumpGenerationFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type CoredumpSettings

type CoredumpSettings int32

CoredumpSettings represents flags for choosing a coredump attribute to get/set.

const (
	CoredumpEnableOnException               CoredumpSettings = 1
	CoredumpTriggerHost                     CoredumpSettings = 2
	CoredumpLightweight                     CoredumpSettings = 3
	CoredumpEnableUserTrigger               CoredumpSettings = 4
	CoredumpFile                            CoredumpSettings = 5
	CoredumpPipe                            CoredumpSettings = 6
	CoredumpSettingsCoredumpGenerationFlags CoredumpSettings = 7
)

func (CoredumpSettings) String

func (e CoredumpSettings) String() string

String returns the constant name, or a numeric representation for unknown values.

type CoredumpStatusCallback

type CoredumpStatusCallback func(userData uintptr, pid int32, dev Device)

CoredumpStatusCallback is the Go form of CUcoredumpStatusCallback.

It corresponds to the C signature

typedef void (CUDA_CB *CUcoredumpStatusCallback)(void *userData, int pid, CUdevice dev);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type CtxCigParam

type CtxCigParam struct {
	// Type of shared data from graphics client (D3D12 or Vulkan).
	SharedDataType CigDataType
	// Graphics client data handle (ID3D12CommandQueue or Nvidia specific data blob).
	SharedData uintptr
}

CtxCigParam represents CIG Context Create Params.

type CtxCreateParams

type CtxCreateParams struct {
	// Array of execution affinity parameters to limit context resources (e.g., SM count). Only supported Volta+ MPS. Mutually exclusive with cigParams.
	ExecAffinityParams uintptr
	// Number of elements in execAffinityParams array. Must be 0 if execAffinityParams is NULL.
	NumExecAffinityParams int32
	// CIG (CUDA in Graphics) parameters for sharing data from D3D12/Vulkan graphics clients. Mutually exclusive with execAffinityParams.
	CigParams uintptr
}

CtxCreateParams represents params for creating CUDA context.

Both execAffinityParams and cigParams cannot be non-NULL at the same time. If both are NULL, the context will be created as a regular CUDA context.

type CtxFlags

type CtxFlags uint32

CtxFlags represents context creation flags.

const (
	CtxSchedAuto         CtxFlags = 0x00 // Automatic scheduling
	CtxSchedSpin         CtxFlags = 0x01 // Set spin as default scheduling
	CtxSchedYield        CtxFlags = 0x02 // Set yield as default scheduling
	CtxSchedBlockingSync CtxFlags = 0x04 // Set blocking synchronization as default scheduling
	// CtxBlockingSync: Set blocking synchronization as default scheduling
	//
	// Deprecated: Deprecated in CUDA 4.0. This flag was deprecated as of CUDA 4.0 and was replaced with [CtxSchedBlockingSync].
	CtxBlockingSync CtxFlags = 0x04
	CtxSchedMask    CtxFlags = 0x07
	// CtxMapHost: All contexts as of CUDA 3.2 behave as though the flag is enabled.
	//
	// Deprecated: Deprecated in CUDA 11.0. This flag was deprecated as of CUDA 11.0 and it no longer has any effect.
	CtxMapHost            CtxFlags = 0x08
	CtxLmemResizeToMax    CtxFlags = 0x10 // Keep local memory allocation after launch
	CtxCoredumpEnable     CtxFlags = 0x20 // Trigger coredumps from exceptions in this context
	CtxUserCoredumpEnable CtxFlags = 0x40 // Enable user pipe to trigger coredumps in this context
	// CtxSyncMemops: Ensure synchronous memory operations on this context will synchronize
	CtxSyncMemops CtxFlags = 0x80
	CtxFlagsMask  CtxFlags = 0xFF
)

func (CtxFlags) String

func (e CtxFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type CuDevSmResourceGroupParams

type CuDevSmResourceGroupParams struct {
	// The amount of SMs available in this resource.
	SmCount uint32
	// The amount of co-scheduled SMs grouped together for locality purposes.
	CoscheduledSmCount uint32
	// When possible, combine co-scheduled groups together into larger groups of this size.
	PreferredCoscheduledSmCount uint32
	// The flags set on this SM resource group. For possible values see [DevsmresourcegroupFlags].
	Flags uint32
	// Locality domain that the SM must be located on. Only valid if [DevSmResourceGroupLocalityDomainId] is set in flags
	LocalityDomainId uint32
	Reserved         [11]uint32
}

CuDevSmResourceGroupParams represents input data for splitting SMs.

type DevResource

type DevResource struct {
	Type            DevResourceType
	InternalPadding [92]uint8
	AnonymousUnion  [10]uint32
	NextResource    uintptr
}

DevResource represents CUdevResource_v1.

func (*DevResource) Oversize

func (d *DevResource) Oversize() *[40]uint8

Oversize returns a pointer to the _oversize member of CUdevResource_v1, which shares its storage with every other member of the union.

func (*DevResource) Sm

func (d *DevResource) Sm() *DevSmResource

Sm returns a pointer to the sm member of CUdevResource_v1, which shares its storage with every other member of the union.

func (*DevResource) Wq

Wq returns a pointer to the wq member of CUdevResource_v1, which shares its storage with every other member of the union.

func (*DevResource) WqConfig

func (d *DevResource) WqConfig() *DevWorkqueueConfigResource

WqConfig returns a pointer to the wqConfig member of CUdevResource_v1, which shares its storage with every other member of the union.

type DevResourceDesc

type DevResourceDesc uintptr

DevResourceDesc is an opaque handle for CUdevResourceDesc.

func DevResourceGenerateDesc

func DevResourceGenerateDesc(resources *DevResource, nbResources uint32) (DevResourceDesc, error)

DevResourceGenerateDesc generates a resource descriptor.

Generates a single resource descriptor with the set of resources specified in resources. The generated resource descriptor is necessary for the creation of green contexts via the NewGreenCtx API. Resources of the same type can be passed in, provided they meet the requirements as noted below. A successful API call must have:

  • A valid output pointer for the phDesc descriptor as well as a valid array of resources pointers, with the array size passed in nbResources. If multiple resources are provided in resources, the device they came from must be the same, otherwise ErrInvalidResourceConfiguration is returned. If multiple resources are provided in resources and they are of type DevResourceTypeSm, they must be outputs (whether result or remaining) from the same split API instance and have the same smCoscheduledAlignment and localityDomainId values, otherwise ErrInvalidResourceConfiguration is returned.

The output descriptor phDesc will remain valid for the lifetime of the process.

Note: The API is not supported on 32-bit platforms.

See also: DevSmResourceSplitByCount

Requires CUDA 12.4 (driver r550) or later; see HasDevResourceGenerateDesc.

  • resources: Array of resources to be included in the descriptor
  • nbResources: Number of resources passed in resources

Errors:

Wraps cuDevResourceGenerateDesc.

type DevResourceType

type DevResourceType int32

DevResourceType is a type of resource.

const (
	DevResourceTypeInvalid         DevResourceType = 0
	DevResourceTypeSm              DevResourceType = 1     // Streaming multiprocessors related information
	DevResourceTypeWorkqueueConfig DevResourceType = 1000  // Workqueue configuration related information
	DevResourceTypeWorkqueue       DevResourceType = 10000 // Pre-existing workqueue related information
)

func (DevResourceType) String

func (e DevResourceType) String() string

String returns the constant name, or a numeric representation for unknown values.

type DevResourceV1

type DevResourceV1 = DevResource

DevResourceV1 is an alias for DevResource.

type DevSmResource

type DevSmResource struct {
	// The amount of streaming multiprocessors available in this resource.
	SmCount uint32
	// The minimum number of streaming multiprocessors required to partition this resource.
	MinSmPartitionSize     uint32
	SmCoscheduledAlignment uint32
	// The flags set on this SM resource. For possible values see [DevsmresourcegroupFlags].
	Flags            uint32
	LocalityDomainId uint32
}

DevSmResource represents data for SM-related resources All parameters in this structure are OUTPUT only.

Do not write to any of the fields in this structure.

type DevWorkqueueConfigResource

type DevWorkqueueConfigResource struct {
	// The device on which the workqueue resources are available
	Device Device
	// The expected maximum number of concurrent stream-ordered workloads
	WqConcurrencyLimit uint32
	// The sharing scope for the workqueue resources
	SharingScope DevWorkqueueConfigScope
}

DevWorkqueueConfigResource represents data for workqueue configuration related resources.

type DevWorkqueueConfigScope

type DevWorkqueueConfigScope int32

DevWorkqueueConfigScope represents sharing scope for workqueues.

const (
	// WorkqueueScopeDeviceCtx: Use all shared workqueue resources across all contexts. Default driver behaviour.
	WorkqueueScopeDeviceCtx DevWorkqueueConfigScope = 0
	// WorkqueueScopeGreenCtxBalanced: When possible, use non-overlapping workqueue resources with other balanced green contexts.
	WorkqueueScopeGreenCtxBalanced DevWorkqueueConfigScope = 1
)

func (DevWorkqueueConfigScope) String

func (e DevWorkqueueConfigScope) String() string

String returns the constant name, or a numeric representation for unknown values.

type DevWorkqueueResource

type DevWorkqueueResource struct {
	// Reserved for future use
	Reserved [40]uint8
}

DevWorkqueueResource represents handle to a pre-existing workqueue related resource.

type Device

type Device int32

Device represents a CUDA device ordinal. Obtained from DeviceGet and used across the driver API.

const (
	DeviceCpu     Device = -1
	DeviceInvalid Device = -2
)

Driver Device tokens from cuda.h.

func CtxGetDevice

func CtxGetDevice() (Device, error)

CtxGetDevice returns the device handle for the current context.

Returns the handle of the current context’s device.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize, cudaGetDevice

Errors:

Wraps cuCtxGetDevice.

func CtxGetDeviceV1

func CtxGetDeviceV1() (Device, error)

CtxGetDeviceV1 returns the device handle for the current context.

Returns the handle of the current context’s device.

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize, cudaGetDevice

  • device: Returned device handle for the current context

Errors:

Wraps cuCtxGetDevice.

func DeviceGet

func DeviceGet(ordinal int) (Device, error)

DeviceGet returns a handle to a compute device.

Returns a device handle given an ordinal in the range [0, DeviceGetCount-1].

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Uuid, Device.Luid, Device.TotalMem, Device.ExecAffinitySupport

  • ordinal: Device number to get handle for

Errors:

Wraps cuDeviceGet.

func DeviceGetByPCIBusId

func DeviceGetByPCIBusId(pciBusId string) (Device, error)

DeviceGetByPCIBusId returns a handle to a compute device.

Returns in *device a device handle given a PCI bus ID string. where domain, bus, device, and function are all hexadecimal values

See also: DeviceGet, Device.Attribute, Device.PCIBusId, cudaDeviceGetByPCIBusId

  • pciBusId: String in one of the following forms:

Errors:

Wraps cuDeviceGetByPCIBusId.

func (Device) Attribute

func (d Device) Attribute(attrib DeviceAttribute) (int32, error)

Attribute returns information about the device.

Returns the integer value of the attribute attrib on device dev.

See also: DeviceGetCount, Device.Name, Device.Uuid, DeviceGet, Device.TotalMem, Device.ExecAffinitySupport, cudaDeviceGetAttribute, cudaGetDeviceProperties

  • attrib: Device attribute to query

Errors:

Wraps cuDeviceGetAttribute.

func (Device) CanAccessPeer

func (d Device) CanAccessPeer(peerDev Device) (int32, error)

CanAccessPeer queries if a device may directly access a peer device’s memory.

Returns a value of 1 if contexts on dev are capable of directly accessing memory from contexts on peerDev and 0 otherwise. If direct access of peerDev from dev is possible, then access may be enabled on two specific contexts by calling Context.EnablePeerAccess.

See also: Context.EnablePeerAccess, Context.DisablePeerAccess, cudaDeviceCanAccessPeer

  • peerDev: Device on which the allocations to be directly accessed by dev reside

Errors:

Wraps cuDeviceCanAccessPeer.

func (Device) CliqueCount

func (d Device) CliqueCount() (uint, error)

CliqueCount retrieves the number of fabric cliques.

Retrieves the number of fabric cliques that the device is part of.

Requires CUDA 13.4 (driver r615) or later; see HasDeviceGetCliqueCount.

Errors:

Wraps cuDeviceGetCliqueCount.

func (Device) CliqueInfo

func (d Device) CliqueInfo(cliqueInfo *CliqueInfo, count *uint) error

CliqueInfo retrieves fabric clique information.

Returns the fabric clique information for the cliques that the device is a part of. User must specify the size of the cliqueInfo array in count. The same parameter count will return the actual number of entries updated in the cliqueInfo array.

Requires CUDA 13.4 (driver r615) or later; see HasDeviceGetCliqueInfo.

  • cliqueInfo: Array to store the fabric clique information
  • count: Input: Size of the cliqueInfo array. Output: Number of entries updated in the cliqueInfo array

Errors:

Wraps cuDeviceGetCliqueInfo.

func (Device) ComputeCapability

func (d Device) ComputeCapability() (major int, minor int, err error)

ComputeCapability returns the major and minor revision numbers of the device's compute capability.

It calls Device.Attribute, which supersedes the deprecated cuDeviceComputeCapability.

func (Device) DefaultMemPool

func (d Device) DefaultMemPool() (MemoryPool, error)

DefaultMemPool returns the default mempool of a device.

The default mempool of a device contains device memory from that device.

See also: Stream.MemAllocAsync, MemoryPool.TrimTo, MemoryPool.Attribute, MemoryPool.SetAttribute, MemoryPool.SetAccess, Device.MemPool, NewMemoryPool

Errors:

Wraps cuDeviceGetDefaultMemPool.

func (Device) DevResource

func (d Device) DevResource(type_ DevResourceType) (DevResource, error)

DevResource gets device resources.

Get the type resources available to the device. This may often be the starting point for further partitioning or configuring of resources.

Note: The API is not supported on 32-bit platforms.

See also: DevResourceGenerateDesc

Requires CUDA 12.4 (driver r550) or later; see HasDeviceGetDevResource.

  • type_: Type of resource to retrieve

Errors:

Wraps cuDeviceGetDevResource.

func (Device) ExecAffinitySupport

func (d Device) ExecAffinitySupport(type_ ExecAffinityType) (int32, error)

ExecAffinitySupport returns information about the execution affinity support of the device.

Returns whether execution affinity type type is supported by device dev. The supported types are:

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Uuid, DeviceGet, Device.TotalMem

  • type_: Execution affinity type to query

Errors:

Wraps cuDeviceGetExecAffinitySupport.

func (Device) FabricClusterUuid

func (d Device) FabricClusterUuid() (Uuid, error)

FabricClusterUuid retrieves the fabric cluster UUID.

Retrieves the fabric cluster UUID for the given device.

Requires CUDA 13.4 (driver r615) or later; see HasDeviceGetFabricClusterUuid.

Errors:

Wraps cuDeviceGetFabricClusterUuid.

func (Device) GraphMemAttribute

func (d Device) GraphMemAttribute(attr GraphmemAttribute, value unsafe.Pointer) error

GraphMemAttribute queries asynchronous allocation attributes related to graphs.

Valid attributes are:

See also: Device.SetGraphMemAttribute, Graph.AddMemAllocNode, Graph.AddMemFreeNode

  • attr: attribute to get
  • value: retrieved value

Errors:

Wraps cuDeviceGetGraphMemAttribute.

func (Device) GraphMemTrim

func (d Device) GraphMemTrim() error

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

Blocks which are not in use by a graph that is either currently executing or scheduled to execute are freed back to the operating system.

See also: Graph.AddMemAllocNode, Graph.AddMemFreeNode, Device.SetGraphMemAttribute, Device.GraphMemAttribute

Errors:

Wraps cuDeviceGraphMemTrim.

func (Device) HostAtomicCapabilities

func (d Device) HostAtomicCapabilities(operations *AtomicOperation, count uint32) (uint32, error)

HostAtomicCapabilities queries details about atomic operations supported between the device and host.

Returns the details about requested atomic *operations over the the link between dev and the host. The allocated size of *operations and *capabilities must be count. For each AtomicOperation in *operations, the corresponding result in *capabilities will be a bitmask indicating which of AtomicOperationCapability the link supports natively. Returns ErrInvalidDevice if dev is not valid. Returns ErrInvalidValue if *capabilities or *operations is NULL, if count is 0, or if any of *operations is not valid.

See also: Device.Attribute, Device.P2PAtomicCapabilities, cudaDeviceGeHostAtomicCapabilities

Requires CUDA 13.0 (driver r580) or later; see HasDeviceGetHostAtomicCapabilities.

  • operations: Requested operations
  • count: Count of requested operations and size of capabilities

Errors:

Wraps cuDeviceGetHostAtomicCapabilities.

func (Device) LogicalEndpointAdd

func (d Device) LogicalEndpointAdd(leId LogicalEndpointId) error

LogicalEndpointAdd associates a device to a multicast logical endpoint.

Associates a device to a logical endpoint. The type of the logical endpoint must be LogicalEndpointTypeMulticast. The added device will be a part of the multicast team of size specified by LogicalEndpointProp.multicast.numDevices during LogicalEndpointCreate. The association of the device to the multicast logical endpoint is permanent during the life time of the multicast logical endpoint. All devices must be added to the multicast logical endpoint before any memory can be bound to any device in the team. A multicast logical endpoint will not be ready for use until all devices have been added. User can query whether the logical endpoint is ready for use via LogicalEndpointQuery. This call may fail with ErrInvalidDevice if the device specified by dev does not belong to the same clique as the other devices previously added to this multicast logical endpoint.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointAddDevice.

  • leId: Logical endpoint id representing a multicast logical endpoint

Errors:

Wraps cuLogicalEndpointAddDevice.

func (Device) LogicalEndpointBindAddr

func (d Device) LogicalEndpointBindAddr(leId LogicalEndpointId, offset uint64, ptr uintptr, size uint64, flags uint64) error

LogicalEndpointBindAddr binds a memory allocation represented by a virtual address to a logical endpoint.

Binds the memory allocation specified by its mapped address ptr to a logical endpoint represented by leId at the offset offset. The memory must have been allocated via MemCreate or cudaMallocAsync. The intended size of the bind, the offset in the logical endpoint range and ptr must be multiples of the value for bindAlignment as returned by LogicalEndpointGetLimits. The size cannot be larger than the size of the allocated memory. Similarly the size + offset cannot be larger than the total size of the logical endpoint. For device memory, i.e., type MemLocationTypeDevice, the memory allocation must have been created on the device specified by dev. For host NUMA memory, i.e., type MemLocationTypeHostNuma, the memory allocation must have been created on the CPU NUMA node closest to dev. That is, the value returned when querying DevAttrHostNumaId for dev, must be the CPU NUMA node where the memory was allocated. For multicast endpoints, the device named by dev must have been added to the multicast team via Device.LogicalEndpointAdd. For unicast endpoints the device named by dev must be the owner device specified during LogicalEndpointCreate via LogicalEndpointProp.unicast.device. Externally shareable as well as imported multicast endpoints can be bound only to externally shareable memory. Imported unicast endpoints cannot be bound to any memory. This call will return ErrInvalidValue if LogicalEndpointQuery has not been called for the logical endpoint to ensure that the endpoint is ready for memory binding. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using logical endpoints, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointBindAddr.

  • leId: Logical endpoint to which memory will be associated
  • offset: Offset into the logical endpoint space
  • ptr: Virtual address of the memory allocation
  • size: Size of memory that will be bound to the logical endpoint
  • flags: Flags for future use, must be zero for now

Errors:

Wraps cuLogicalEndpointBindAddr.

func (Device) LogicalEndpointBindMem

func (d Device) LogicalEndpointBindMem(leId LogicalEndpointId, offset uint64, memHandle uint64, memOffset uint64, size uint64, flags uint64) error

LogicalEndpointBindMem binds memory object represented by a handle to the logical endpoint.

Binds the memory allocation specified by memHandle to a logical endpoint represented by leId at the offset offset. The memory must have been allocated via MemCreate. The intended size of the bind, the offset in the logical endpoint range offset and the offset in the memory handle memOffset must be multiples of the value for bindAlignment as returned by LogicalEndpointGetLimits. The size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + offset cannot be larger than the total size of the logical endpoint. For device memory, i.e., type MemLocationTypeDevice, the memory allocation must have been created on the device specified by dev. For host NUMA memory, i.e., type MemLocationTypeHostNuma, the memory allocation must have been created on the CPU NUMA node closest to dev. That is, the value returned when querying DevAttrHostNumaId for dev, must be the CPU NUMA node where the memory was allocated. For multicast endpoints, the device named by dev must have been added to the multicast team via Device.LogicalEndpointAdd. For unicast endpoints the device named by dev must be the owner device specified during LogicalEndpointCreate via LogicalEndpointProp.unicast.device. Externally shareable as well as imported multicast endpoints can be bound only to externally shareable memory. Imported unicast endpoints cannot be bound to any memory. This call will return ErrInvalidValue if LogicalEndpointQuery has not been called for the logical endpoint to ensure that the endpoint is ready for memory binding. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using logical endpoints, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointBindMem.

  • leId: Logical endpoint to which memory will be associated
  • offset: Offset into the logical endpoint space
  • memHandle: Handle representing a memory allocation
  • memOffset: Offset into the memory for the attachment
  • size: Size of memory that will be bound to the logical endpoint
  • flags: Flags for future use, must be zero for now

Errors:

Wraps cuLogicalEndpointBindMem.

func (Device) LogicalEndpointUnbind

func (d Device) LogicalEndpointUnbind(leId LogicalEndpointId, offset uint64, size uint64) error

LogicalEndpointUnbind unbinds any binding at offset from the logical endpoint.

Unbinds any memory allocations bound to the logical endpoint on dev at offset and up to the given size. The intended size of the unbind and the offset in the logical endpoint range offset must be multiples of the value for bindAlignment as returned by LogicalEndpointGetLimits.

Note: The offset must correspond to a value specified during a bind call. The size must either match the bind call of the offset or be the combined size of multiple bind calls. The size + offset must fully enclose all bindings that are covered.

See also: LogicalEndpointCreate, LogicalEndpointIdReserve, LogicalEndpointIdRelease, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointUnbind.

  • leId: Logical endpoint id representing a logical endpoint
  • offset: Offset into the logical endpoint
  • size: Desired size to unbind

Errors:

Wraps cuLogicalEndpointUnbind.

func (Device) Luid

func (d Device) Luid(luid *byte) (uint32, error)

Luid returns an LUID and device node mask for the device.

Return identifying information ( luid and deviceNodeMask) to allow matching device with graphics APIs.

See also: Device.Attribute, DeviceGetCount, Device.Name, DeviceGet, Device.TotalMem, Device.ExecAffinitySupport, cudaGetDeviceProperties

  • luid: Returned LUID

Errors:

Wraps cuDeviceGetLuid.

func (Device) MemPool

func (d Device) MemPool() (MemoryPool, error)

MemPool gets the current mempool for a device.

Returns the last pool provided to Device.SetMemPool for this device or the device’s default memory pool if Device.SetMemPool has never been called. By default the current mempool is the default mempool for a device. Otherwise the returned pool must have been set with Device.SetMemPool.

See also: Device.DefaultMemPool, NewMemoryPool, Device.SetMemPool

Errors:

Wraps cuDeviceGetMemPool.

func (Device) MulticastAdd

func (d Device) MulticastAdd(mcHandle uint64) error

MulticastAdd associates a device to a multicast object.

Associates a device to a multicast object. The added device will be a part of the multicast team of size specified by MulticastObjectProp.numDevices during MulticastCreate. The association of the device to the multicast object is permanent during the life time of the multicast object. All devices must be added to the multicast team before any memory can be bound to any device in the team. Any calls to MulticastBindMem, Device.MulticastBindMemV2, DevicePtr.MulticastBindAddr, or Device.MulticastBindAddrV2 will block until all devices have been added. Similarly all devices must be added to the multicast team before a virtual address range can be mapped to the multicast object. A call to DevicePtr.MemMap will block until all devices have been added. This call may fail with ErrInvalidDevice if the device specified by dev does not belong to the same clique as the other devices previously added to this multicast object.

See also: MulticastCreate, MulticastBindMem, DevicePtr.MulticastBindAddr

  • mcHandle: Handle representing a multicast object

Errors:

Wraps cuMulticastAddDevice.

func (Device) MulticastBindAddrV2

func (d Device) MulticastBindAddrV2(mcHandle uint64, mcOffset uint, memptr DevicePtr, size uint, flags uint64) error

MulticastBindAddrV2 binds a memory allocation represented by a virtual address to a multicast object.

Binds a memory allocation specified by its mapped address memptr to a multicast object represented by mcHandle. The binding will be applicable for the device dev. The memory must have been allocated via MemCreate or cudaMallocAsync. The intended size of the bind, the offset in the multicast range mcOffset and memptr must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memptr should be aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the total size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memptr may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memptr cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum Also note that the ability to accept a memptr that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull For device memory, i.e., type MemLocationTypeDevice, the memory allocation must have been created on the device specified by dev. For host NUMA memory, i.e., type MemLocationTypeHostNuma, the memory allocation must have been created on the CPU NUMA node closest to dev. That is, the value returned when querying DevAttrHostNumaId for dev, must be the CPU NUMA node where the memory was allocated. In both cases, the device named by dev must have been added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate

Requires CUDA 13.1 (driver r590) or later; see HasMulticastBindAddrV2.

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into multicast va range for attachment
  • memptr: Virtual address of the memory allocation
  • size: Size of memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMulticastBindAddr_v2.

func (Device) MulticastBindMemV2

func (d Device) MulticastBindMemV2(mcHandle uint64, mcOffset uint, memHandle uint64, memOffset uint, size uint, flags uint64) error

MulticastBindMemV2 binds a memory allocation represented by a handle to a multicast object.

Binds a memory allocation specified by memHandle and created via MemCreate to a multicast object represented by mcHandle and created via MulticastCreate. The binding will be applicable for the device dev. The intended size of the bind, the offset in the multicast range mcOffset as well as the offset in the memory memOffset must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memOffset should be aligned to the granularity of the memory allocation(see MemGetAllocationGranularity) or to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memOffset may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memOffset cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. Also note that the ability to accept a memOffset that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull The memory allocation must have beeen created on one of the devices that was added to the multicast team via Device.MulticastAdd. For device memory, i.e., type MemLocationTypeDevice, the memory allocation must have been created on the device specified by dev. For host NUMA memory, i.e., type MemLocationTypeHostNuma, the memory allocation must have been created on the CPU NUMA node closest to dev. That is, the value returned when querying DevAttrHostNumaId for dev, must be the CPU NUMA node where the memory was allocated. In both cases, the device named by dev must have been added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate

Requires CUDA 13.1 (driver r590) or later; see HasMulticastBindMemV2.

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into the multicast object for attachment
  • memHandle: Handle representing a memory allocation
  • memOffset: Offset into the memory for attachment
  • size: Size of the memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero for now

Errors:

Wraps cuMulticastBindMem_v2.

func (Device) MulticastUnbind

func (d Device) MulticastUnbind(mcHandle uint64, mcOffset uint, size uint) error

MulticastUnbind unbinds any memory allocations bound to a multicast object at a given offset and upto a given size.

Unbinds any memory allocations hosted on dev and bound to a multicast object at mcOffset and upto a given size. The intended size of the unbind and the offset in the multicast range ( mcOffset ) must be a multiple of the value returned by MulticastGetGranularity flag MulticastGranularityMinimum. The size + mcOffset cannot be larger than the total size of the multicast object.

Warning: The mcOffset and the size must match the corresponding values specified during the bind call. Any other values may result in undefined behavior.

See also: MulticastBindMem, DevicePtr.MulticastBindAddr, Device.MulticastBindMemV2, Device.MulticastBindAddrV2

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into the multicast object
  • size: Desired size to unbind

Errors:

Wraps cuMulticastUnbind.

func (Device) Name

func (d Device) Name() (string, error)

Name returns an identifier string for the device.

Returns an ASCII string identifying the device dev in the NULL-terminated string pointed to by name. len specifies the maximum length of the string that may be returned. name is shortened to the specified len, if len is less than the device name

See also: Device.Attribute, Device.Uuid, Device.Luid, DeviceGetCount, DeviceGet, Device.TotalMem, Device.ExecAffinitySupport, cudaGetDeviceProperties

Errors:

Wraps cuDeviceGetName.

func (Device) NvSciSyncAttributes

func (d Device) NvSciSyncAttributes(nvSciSyncAttrList unsafe.Pointer, flags int32) error

NvSciSyncAttributes returns 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 object that matches this device’s capabilities. If NvSciSyncAttrKey_RequiredPerm field in nvSciSyncAttrList is already set this API will return ErrInvalidValue. The applications should set nvSciSyncAttrList to a valid NvSciSyncAttrList failing which this API will return ErrInvalidHandle. The flags controls how applications intends to use the NvSciSync created from the nvSciSyncAttrList. The valid flags are:

  • CUDA_NVSCISYNC_ATTR_SIGNAL, specifies that the applications intends to signal an NvSciSync on this CUDA device.
  • CUDA_NVSCISYNC_ATTR_WAIT, 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 ErrInvalidValue. 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 CUDA_NVSCISYNC_ATTR_SIGNAL is set in flags.
  • NvSciSyncAccessPerm_WaitOnly if CUDA_NVSCISYNC_ATTR_WAIT is set in flags.
  • NvSciSyncAccessPerm_WaitSignal if both CUDA_NVSCISYNC_ATTR_WAIT and CUDA_NVSCISYNC_ATTR_SIGNAL are set in flags. NvSciSyncAttrKey_PrimitiveInfo is set to
  • NvSciSyncAttrValPrimitiveType_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 for this device from Device.Uuid.

See also: ImportExternalSemaphore, ExternalSemaphore.Close, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

  • nvSciSyncAttrList: Return NvSciSync attributes supported
  • flags: flags describing NvSciSync usage

Errors:

Wraps cuDeviceGetNvSciSyncAttributes.

func (Device) P2PAtomicCapabilities

func (d Device) P2PAtomicCapabilities(operations *AtomicOperation, count uint32, dstDevice Device) (uint32, error)

P2PAtomicCapabilities queries details about atomic operations supported between two devices.

Returns the details about requested atomic *operations over the the link between srcDevice and dstDevice. The allocated size of *operations and *capabilities must be count. For each AtomicOperation in *operations, the corresponding result in *capabilities will be a bitmask indicating which of AtomicOperationCapability the link supports natively. Returns ErrInvalidDevice if srcDevice or dstDevice are not valid or if they represent the same device. Returns ErrInvalidValue if *capabilities or *operations is NULL, if count is 0, or if any of *operations is not valid.

See also: Device.P2PAttribute, cudaDeviceGetP2PAttribute, cudaDeviceGetP2PAtomicCapabilities

Requires CUDA 13.0 (driver r580) or later; see HasDeviceGetP2PAtomicCapabilities.

  • operations: Requested operations
  • count: Count of requested operations and size of capabilities
  • dstDevice: The destination device of the target link

Errors:

Wraps cuDeviceGetP2PAtomicCapabilities.

func (Device) P2PAttribute

func (d Device) P2PAttribute(attrib DeviceP2pattribute, dstDevice Device) (int32, error)

P2PAttribute queries attributes of the link between two devices.

Returns the value of the requested attribute attrib of the link between srcDevice and dstDevice. The supported attributes are:

Returns ErrInvalidDevice if srcDevice or dstDevice are not valid or if they represent the same device. Returns ErrInvalidValue if attrib is not valid or if value is a null pointer.

See also: Context.EnablePeerAccess, Context.DisablePeerAccess, Device.CanAccessPeer, Device.P2PAtomicCapabilities, cudaDeviceGetP2PAttribute

  • attrib: The requested attribute of the link between srcDevice and dstDevice
  • dstDevice: The destination device of the target link

Errors:

Wraps cuDeviceGetP2PAttribute.

func (Device) PCIBusId

func (d Device) PCIBusId() (string, error)

PCIBusId 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. len 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.

See also: DeviceGet, Device.Attribute, DeviceGetByPCIBusId, cudaDeviceGetPCIBusId

Errors:

Wraps cuDeviceGetPCIBusId.

func (Device) PrimaryCtxGetState

func (d Device) PrimaryCtxGetState() (flags uint32, active int32, err error)

PrimaryCtxGetState gets the state of the primary context.

Returns in *flags the flags for the primary context of dev, and in *active whether it is active. See Device.PrimaryCtxSetFlags for flag values.

See also: Device.PrimaryCtxSetFlags, CtxGetFlags, CtxSetFlags, cudaGetDeviceFlags

  • flags: Flags
  • active: Context state; 0 = inactive, 1 = active

Errors:

Wraps cuDevicePrimaryCtxGetState.

func (Device) PrimaryCtxRelease

func (d Device) PrimaryCtxRelease() error

PrimaryCtxRelease releases the primary context on the GPU.

Releases the primary context interop on the device. A retained context should always be released once the user is done using it. The context is automatically reset once the last reference to it is released. This behavior is different when the primary context was retained by the CUDA runtime from CUDA 4.0 and earlier. In this case, the primary context remains always active. Releasing a primary context that has not been previously retained will fail with ErrInvalidContext. Please note that unlike Context.Close this method does not pop the context from stack in any circumstances.

See also: Device.PrimaryCtxRetain, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuDevicePrimaryCtxRelease, bound as cuDevicePrimaryCtxRelease_v2.

func (Device) PrimaryCtxReset

func (d Device) PrimaryCtxReset() error

PrimaryCtxReset destroys all allocations and resets all state on the primary context.

Explicitly destroys and cleans up all resources associated with the current device in the current process. Note that it is responsibility of the calling function to ensure that no other module in the process is using the device any more. For that reason it is recommended to use Device.PrimaryCtxRelease in most cases. However it is safe for other modules to call Device.PrimaryCtxRelease even after resetting the device. Resetting the primary context does not release it, an application that has retained the primary context should explicitly release its usage.

See also: Device.PrimaryCtxRetain, Device.PrimaryCtxRelease, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize, cudaDeviceReset

Errors:

Wraps cuDevicePrimaryCtxReset, bound as cuDevicePrimaryCtxReset_v2.

func (Device) PrimaryCtxRetain

func (d Device) PrimaryCtxRetain() (Context, error)

PrimaryCtxRetain retains the primary context on the GPU.

Retains the primary context on the device. Once the user successfully retains the primary context, the primary context will be active and available to the user until the user releases it with Device.PrimaryCtxRelease or resets it with Device.PrimaryCtxReset. Unlike NewContext the newly retained context is not pushed onto the stack. Retaining the primary context for the first time will fail with ErrUnknown if the compute mode of the device is ComputemodeProhibited. The function Device.Attribute can be used with DevAttrComputeMode to determine the compute mode of the device. The nvidia-smi tool can be used to set the compute mode for devices. Documentation for nvidia-smi can be obtained by passing a -h option to it. Please note that the primary context always supports pinned allocations. Other flags can be specified by Device.PrimaryCtxSetFlags.

See also: Device.PrimaryCtxRelease, Device.PrimaryCtxSetFlags, NewContext, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize

Errors:

Wraps cuDevicePrimaryCtxRetain.

func (Device) PrimaryCtxSetFlags

func (d Device) PrimaryCtxSetFlags(flags CtxFlags) error

PrimaryCtxSetFlags sets flags for the primary context.

Sets the flags for the primary context on the device overwriting perviously set ones. The three LSBs of the flags parameter can be used to control how the OS thread, which owns the CUDA context at the time of an API call, interacts with the OS scheduler when waiting for results from the GPU. Only one of the scheduling flags can be set when creating a context.

  • CtxSchedSpin: Instruct CUDA to actively spin when waiting for results from the GPU. This can decrease latency when waiting for the GPU, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
  • CtxSchedYield: Instruct CUDA to yield its thread when waiting for results from the GPU. This can increase latency when waiting for the GPU, but can increase the performance of CPU threads performing work in parallel with the GPU.
  • CtxSchedBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work.
  • CtxBlockingSync: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the GPU to finish work. Deprecated: This flag was deprecated as of CUDA 4.0 and was replaced with CtxSchedBlockingSync.
  • CtxSchedAuto: 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 GPU ( CtxSchedYield), otherwise CUDA will not yield while waiting for results and actively spin on the processor ( CtxSchedSpin). Additionally, on Tegra devices, CtxSchedAuto uses a heuristic based on the power profile of the platform and may choose CtxSchedBlockingSync for low-powered devices.
  • CtxLmemResizeToMax: 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.
  • CtxCoredumpEnable: If GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if this context raises an exception during execution. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. The initial settings will be taken from the global settings at the time of context creation. The other settings that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current.
  • CtxUserCoredumpEnable: If user-triggered GPU coredumps have not been enabled globally with CoredumpSetAttributeGlobal or environment variables, this flag can be set during context creation to instruct CUDA to create a coredump if data is written to a certain pipe that is present in the OS space. These environment variables are described in the CUDA-GDB user guide under the “GPU core dump support” section. It is important to note that the pipe name must be set with CoredumpSetAttributeGlobal before creating the context if this flag is used. Setting this flag implies that CtxCoredumpEnable is set. The initial settings will be taken from the global settings at the time of context creation. The other settings that control coredump output can be modified by calling CoredumpSetAttribute from the created context after it becomes current.
  • CtxSyncMemops: Ensures that synchronous memory operations initiated on this context will always synchronize. See further documentation in the section titled “API Synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

See also: Device.PrimaryCtxRetain, Device.PrimaryCtxGetState, NewContext, CtxGetFlags, CtxSetFlags, cudaSetDeviceFlags

  • flags: New flags for the device

Errors:

Wraps cuDevicePrimaryCtxSetFlags, bound as cuDevicePrimaryCtxSetFlags_v2.

func (Device) Properties deprecated

func (d Device) Properties() (Devprop, error)

Properties returns properties for a selected device.

Returns the properties of device dev.

  • maxThreadsPerBlock is the maximum number of threads per block;
  • maxThreadsDim[3] is the maximum sizes of each dimension of a block;
  • maxGridSize[3] is the maximum sizes of each dimension of a grid;
  • sharedMemPerBlock is the total amount of shared memory available per block in bytes;
  • totalConstantMemory is the total amount of constant memory available on the device in bytes;
  • SIMDWidth is the warp size;
  • memPitch is the maximum pitch allowed by the memory copy functions that involve memory regions allocated through MemAllocPitch;
  • regsPerBlock is the total number of registers available per block;
  • clockRate is the clock frequency in kilohertz;
  • textureAlign is the alignment requirement; texture base addresses that are aligned to textureAlign bytes do not need an offset applied to texture fetches.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Uuid, DeviceGet, Device.TotalMem

Errors:

Wraps cuDeviceGetProperties.

Deprecated: Deprecated in CUDA 5.0. This function was deprecated as of CUDA 5.0 and replaced by Device.Attribute.

func (Device) RegisterAsyncNotification

func (d Device) RegisterAsyncNotification(callbackFunc uintptr, userData uintptr) (AsyncCallbackHandle, error)

RegisterAsyncNotification registers a callback function to receive async notifications.

Registers callbackFunc to receive async notifications. The userData parameter is passed to the callback function at async notification time. Likewise, callback is also passed to the callback function to distinguish between multiple registered callbacks. The callback function being registered should be designed to return quickly (~10ms). Any long running tasks should be queued for execution on an application thread. Callbacks may not call Device.RegisterAsyncNotification or Device.UnregisterAsyncNotification. Doing so will result in ErrNotPermitted. Async notification callbacks execute in an undefined order and may be serialized. Returns a handle representing the registered callback instance.

See also: Device.UnregisterAsyncNotification

Requires CUDA 12.4 (driver r550) or later; see HasDeviceRegisterAsyncNotification.

  • callbackFunc: The function to register as a callback (see AsyncCallback)
  • userData: A generic pointer to user data. This is passed into the callback function

Errors:

Wraps cuDeviceRegisterAsyncNotification.

func (Device) SetGraphMemAttribute

func (d Device) SetGraphMemAttribute(attr GraphmemAttribute, value unsafe.Pointer) error

SetGraphMemAttribute sets asynchronous allocation attributes related to graphs.

Valid attributes are:

  • GraphMemAttrUsedMemHigh: High watermark of memory, in bytes, associated with graphs since the last time it was reset. High watermark can only be reset to zero.
  • GraphMemAttrReservedMemHigh: High watermark of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator.

See also: Device.GraphMemAttribute, Graph.AddMemAllocNode, Graph.AddMemFreeNode

  • attr: attribute to get
  • value: pointer to value to set

Errors:

Wraps cuDeviceSetGraphMemAttribute.

func (Device) SetMemPool

func (d Device) SetMemPool(pool MemoryPool) error

SetMemPool sets the current memory pool of a device.

The memory pool must be local to the specified device. Stream.MemAllocAsync allocates from the current mempool of the provided stream’s device. By default, a device’s current memory pool is its default memory pool.

Note: Use MemoryPool.MemAllocFromPoolAsync to specify asynchronous allocations from a device different than the one the stream runs on.

See also: Device.DefaultMemPool, Device.MemPool, NewMemoryPool, MemoryPool.Close, MemoryPool.MemAllocFromPoolAsync

Errors:

Wraps cuDeviceSetMemPool.

func (Device) Texture1DLinearMaxWidth

func (d Device) Texture1DLinearMaxWidth(format ArrayFormat, numChannels uint32) (uint, error)

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

Returns the maximum number of texture elements allocatable in a 1D linear texture for given format and numChannels.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Uuid, DeviceGet, cudaMemGetInfo, Device.TotalMem

  • format: Texture format
  • numChannels: Number of channels per texture element

Errors:

Wraps cuDeviceGetTexture1DLinearMaxWidth.

func (Device) TotalMem

func (d Device) TotalMem() (uint, error)

TotalMem returns the total amount of memory on the device.

Returns the total amount of memory available on the device dev in bytes.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Uuid, DeviceGet, Device.ExecAffinitySupport, cudaMemGetInfo

Errors:

Wraps cuDeviceTotalMem, bound as cuDeviceTotalMem_v2.

func (Device) UnregisterAsyncNotification

func (d Device) UnregisterAsyncNotification(callback AsyncCallbackHandle) error

UnregisterAsyncNotification unregisters an async notification callback.

Unregisters callback so that the corresponding callback function will stop receiving async notifications.

See also: Device.RegisterAsyncNotification

Requires CUDA 12.4 (driver r550) or later; see HasDeviceUnregisterAsyncNotification.

  • callback: The callback instance to unregister from receiving async notifications

Errors:

It is not named Close because it takes more than the handle.

Wraps cuDeviceUnregisterAsyncNotification.

func (Device) Uuid

func (d Device) Uuid() (Uuid, error)

Uuid returns an UUID for the device.

Returns 16-octets identifying the device dev in the structure pointed by the uuid. If the device is in MIG mode, returns its MIG UUID which uniquely identifies the subscribed MIG compute instance.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Luid, DeviceGet, Device.TotalMem, cudaGetDeviceProperties

Errors:

Wraps cuDeviceGetUuid, bound to the first of cuDeviceGetUuid_v2, cuDeviceGetUuid that the library exports.

func (Device) UuidV1 deprecated

func (d Device) UuidV1() (Uuid, error)

UuidV1 returns an UUID for the device.

Returns 16-octets identifying the device dev in the structure pointed by the uuid. If the device is in MIG mode, returns its MIG UUID which uniquely identifies the subscribed MIG compute instance.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Luid, DeviceGet, Device.TotalMem, cudaGetDeviceProperties

Errors:

Wraps cuDeviceGetUuid_v1, bound as cuDeviceGetUuid.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Device) UuidV2

func (d Device) UuidV2() (Uuid, error)

UuidV2 returns an UUID for the device.

Returns 16-octets identifying the device dev in the structure pointed by the uuid. If the device is in MIG mode, returns its MIG UUID which uniquely identifies the subscribed MIG compute instance.

See also: Device.Attribute, DeviceGetCount, Device.Name, Device.Luid, DeviceGet, Device.TotalMem, cudaGetDeviceProperties

Errors:

Wraps cuDeviceGetUuid, bound as cuDeviceGetUuid_v2.

type DeviceAttribute

type DeviceAttribute int32

DeviceAttribute represents device properties.

const (
	DevAttrMaxThreadsPerBlock      DeviceAttribute = 1 // Maximum number of threads per block
	DevAttrMaxBlockDimX            DeviceAttribute = 2 // Maximum block dimension X
	DevAttrMaxBlockDimY            DeviceAttribute = 3 // Maximum block dimension Y
	DevAttrMaxBlockDimZ            DeviceAttribute = 4 // Maximum block dimension Z
	DevAttrMaxGridDimX             DeviceAttribute = 5 // Maximum grid dimension X
	DevAttrMaxGridDimY             DeviceAttribute = 6 // Maximum grid dimension Y
	DevAttrMaxGridDimZ             DeviceAttribute = 7 // Maximum grid dimension Z
	DevAttrMaxSharedMemoryPerBlock DeviceAttribute = 8 // Maximum shared memory available per block in bytes
	//
	// Deprecated: Use [DevAttrMaxSharedMemoryPerBlock] instead.
	DevAttrSharedMemoryPerBlock DeviceAttribute = 8
	// DevAttrTotalConstantMemory: Memory available on device for __constant__ variables in a CUDA C kernel in bytes
	DevAttrTotalConstantMemory  DeviceAttribute = 9
	DevAttrWarpSize             DeviceAttribute = 10 // Warp size in threads
	DevAttrMaxPitch             DeviceAttribute = 11 // Maximum pitch in bytes allowed by memory copies
	DevAttrMaxRegistersPerBlock DeviceAttribute = 12 // Maximum number of 32-bit registers available per block
	//
	// Deprecated: Use [DevAttrMaxRegistersPerBlock] instead.
	DevAttrRegistersPerBlock DeviceAttribute = 12
	DevAttrClockRate         DeviceAttribute = 13 // Typical clock frequency in kilohertz
	DevAttrTextureAlignment  DeviceAttribute = 14 // Alignment requirement for textures
	// DevAttrGpuOverlap: Device can possibly copy memory and execute a kernel concurrently.
	//
	// Deprecated: Use [DevAttrAsyncEngineCount] instead.
	DevAttrGpuOverlap                    DeviceAttribute = 15
	DevAttrMultiprocessorCount           DeviceAttribute = 16 // Number of multiprocessors on device
	DevAttrKernelExecTimeout             DeviceAttribute = 17 // Specifies whether there is a run time limit on kernels
	DevAttrIntegrated                    DeviceAttribute = 18 // Device is integrated with host memory
	DevAttrCanMapHostMemory              DeviceAttribute = 19 // Device can map host memory into CUDA address space
	DevAttrComputeMode                   DeviceAttribute = 20 // Compute mode (See [Computemode] for details)
	DevAttrMaximumTexture1dWidth         DeviceAttribute = 21 // Maximum 1D texture width
	DevAttrMaximumTexture2dWidth         DeviceAttribute = 22 // Maximum 2D texture width
	DevAttrMaximumTexture2dHeight        DeviceAttribute = 23 // Maximum 2D texture height
	DevAttrMaximumTexture3dWidth         DeviceAttribute = 24 // Maximum 3D texture width
	DevAttrMaximumTexture3dHeight        DeviceAttribute = 25 // Maximum 3D texture height
	DevAttrMaximumTexture3dDepth         DeviceAttribute = 26 // Maximum 3D texture depth
	DevAttrMaximumTexture2dLayeredWidth  DeviceAttribute = 27 // Maximum 2D layered texture width
	DevAttrMaximumTexture2dLayeredHeight DeviceAttribute = 28 // Maximum 2D layered texture height
	DevAttrMaximumTexture2dLayeredLayers DeviceAttribute = 29 // Maximum layers in a 2D layered texture
	//
	// Deprecated: Use [DevAttrMaximumTexture2dLayeredWidth] instead.
	DevAttrMaximumTexture2dArrayWidth DeviceAttribute = 27
	//
	// Deprecated: Use [DevAttrMaximumTexture2dLayeredHeight] instead.
	DevAttrMaximumTexture2dArrayHeight DeviceAttribute = 28
	//
	// Deprecated: Use [DevAttrMaximumTexture2dLayeredLayers] instead.
	DevAttrMaximumTexture2dArrayNumslices DeviceAttribute = 29
	DevAttrSurfaceAlignment               DeviceAttribute = 30 // Alignment requirement for surfaces
	DevAttrConcurrentKernels              DeviceAttribute = 31 // Device can possibly execute multiple kernels concurrently
	DevAttrEccEnabled                     DeviceAttribute = 32 // Device has ECC support enabled
	DevAttrPciBusId                       DeviceAttribute = 33 // PCI bus ID of the device
	DevAttrPciDeviceId                    DeviceAttribute = 34 // PCI device ID of the device
	DevAttrTccDriver                      DeviceAttribute = 35 // Device is using TCC driver model
	DevAttrMemoryClockRate                DeviceAttribute = 36 // Peak memory clock frequency in kilohertz
	DevAttrGlobalMemoryBusWidth           DeviceAttribute = 37 // Global memory bus width in bits
	DevAttrL2CacheSize                    DeviceAttribute = 38 // Size of L2 cache in bytes
	DevAttrMaxThreadsPerMultiprocessor    DeviceAttribute = 39 // Maximum resident threads per multiprocessor
	DevAttrAsyncEngineCount               DeviceAttribute = 40 // Number of asynchronous engines
	DevAttrUnifiedAddressing              DeviceAttribute = 41 // Device shares a unified address space with the host
	DevAttrMaximumTexture1dLayeredWidth   DeviceAttribute = 42 // Maximum 1D layered texture width
	DevAttrMaximumTexture1dLayeredLayers  DeviceAttribute = 43 // Maximum layers in a 1D layered texture
	//
	// Deprecated: Deprecated by NVIDIA. Do not use.
	DevAttrCanTex2dGather DeviceAttribute = 44
	// DevAttrMaximumTexture2dGatherWidth: Maximum 2D texture width if CUDA_ARRAY3D_TEXTURE_GATHER is set
	DevAttrMaximumTexture2dGatherWidth DeviceAttribute = 45
	// DevAttrMaximumTexture2dGatherHeight: Maximum 2D texture height if CUDA_ARRAY3D_TEXTURE_GATHER is set
	DevAttrMaximumTexture2dGatherHeight       DeviceAttribute = 46
	DevAttrMaximumTexture3dWidthAlternate     DeviceAttribute = 47 // Alternate maximum 3D texture width
	DevAttrMaximumTexture3dHeightAlternate    DeviceAttribute = 48 // Alternate maximum 3D texture height
	DevAttrMaximumTexture3dDepthAlternate     DeviceAttribute = 49 // Alternate maximum 3D texture depth
	DevAttrPciDomainId                        DeviceAttribute = 50 // PCI domain ID of the device
	DevAttrTexturePitchAlignment              DeviceAttribute = 51 // Pitch alignment requirement for textures
	DevAttrMaximumTexturecubemapWidth         DeviceAttribute = 52 // Maximum cubemap texture width/height
	DevAttrMaximumTexturecubemapLayeredWidth  DeviceAttribute = 53 // Maximum cubemap layered texture width/height
	DevAttrMaximumTexturecubemapLayeredLayers DeviceAttribute = 54 // Maximum layers in a cubemap layered texture
	DevAttrMaximumSurface1dWidth              DeviceAttribute = 55 // Maximum 1D surface width
	DevAttrMaximumSurface2dWidth              DeviceAttribute = 56 // Maximum 2D surface width
	DevAttrMaximumSurface2dHeight             DeviceAttribute = 57 // Maximum 2D surface height
	DevAttrMaximumSurface3dWidth              DeviceAttribute = 58 // Maximum 3D surface width
	DevAttrMaximumSurface3dHeight             DeviceAttribute = 59 // Maximum 3D surface height
	DevAttrMaximumSurface3dDepth              DeviceAttribute = 60 // Maximum 3D surface depth
	DevAttrMaximumSurface1dLayeredWidth       DeviceAttribute = 61 // Maximum 1D layered surface width
	DevAttrMaximumSurface1dLayeredLayers      DeviceAttribute = 62 // Maximum layers in a 1D layered surface
	DevAttrMaximumSurface2dLayeredWidth       DeviceAttribute = 63 // Maximum 2D layered surface width
	DevAttrMaximumSurface2dLayeredHeight      DeviceAttribute = 64 // Maximum 2D layered surface height
	DevAttrMaximumSurface2dLayeredLayers      DeviceAttribute = 65 // Maximum layers in a 2D layered surface
	DevAttrMaximumSurfacecubemapWidth         DeviceAttribute = 66 // Maximum cubemap surface width
	DevAttrMaximumSurfacecubemapLayeredWidth  DeviceAttribute = 67 // Maximum cubemap layered surface width
	DevAttrMaximumSurfacecubemapLayeredLayers DeviceAttribute = 68 // Maximum layers in a cubemap layered surface
	//
	// Deprecated: Deprecated by NVIDIA. Do not use. Use cudaDeviceGetTexture1DLinearMaxWidth() or [Device.Texture1DLinearMaxWidth] instead.
	DevAttrMaximumTexture1dLinearWidth      DeviceAttribute = 69
	DevAttrMaximumTexture2dLinearWidth      DeviceAttribute = 70 // Maximum 2D linear texture width
	DevAttrMaximumTexture2dLinearHeight     DeviceAttribute = 71 // Maximum 2D linear texture height
	DevAttrMaximumTexture2dLinearPitch      DeviceAttribute = 72 // Maximum 2D linear texture pitch in bytes
	DevAttrMaximumTexture2dMipmappedWidth   DeviceAttribute = 73 // Maximum mipmapped 2D texture width
	DevAttrMaximumTexture2dMipmappedHeight  DeviceAttribute = 74 // Maximum mipmapped 2D texture height
	DevAttrComputeCapabilityMajor           DeviceAttribute = 75 // Major compute capability version number
	DevAttrComputeCapabilityMinor           DeviceAttribute = 76 // Minor compute capability version number
	DevAttrMaximumTexture1dMipmappedWidth   DeviceAttribute = 77 // Maximum mipmapped 1D texture width
	DevAttrStreamPrioritiesSupported        DeviceAttribute = 78 // Device supports stream priorities
	DevAttrGlobalL1CacheSupported           DeviceAttribute = 79 // Device supports caching globals in L1
	DevAttrLocalL1CacheSupported            DeviceAttribute = 80 // Device supports caching locals in L1
	DevAttrMaxSharedMemoryPerMultiprocessor DeviceAttribute = 81 // Maximum shared memory available per multiprocessor in bytes
	// DevAttrMaxRegistersPerMultiprocessor: Maximum number of 32-bit registers available per multiprocessor
	DevAttrMaxRegistersPerMultiprocessor DeviceAttribute = 82
	DevAttrManagedMemory                 DeviceAttribute = 83 // Device can allocate managed memory on this system
	DevAttrMultiGpuBoard                 DeviceAttribute = 84 // Device is on a multi-GPU board
	DevAttrMultiGpuBoardGroupId          DeviceAttribute = 85 // Unique id for a group of devices on the same multi-GPU board
	// DevAttrHostNativeAtomicSupported: Link between the device and the host supports all native atomic operations
	DevAttrHostNativeAtomicSupported DeviceAttribute = 86
	// DevAttrSingleToDoublePrecisionPerfRatio: Ratio of single precision performance (in floating-point operations per second) to double precision performance
	DevAttrSingleToDoublePrecisionPerfRatio DeviceAttribute = 87
	// DevAttrPageableMemoryAccess: Device supports coherently accessing pageable memory without calling cudaHostRegister on it
	DevAttrPageableMemoryAccess DeviceAttribute = 88
	// DevAttrConcurrentManagedAccess: Device can coherently access managed memory concurrently with the CPU
	DevAttrConcurrentManagedAccess    DeviceAttribute = 89
	DevAttrComputePreemptionSupported DeviceAttribute = 90 // Device supports compute preemption.
	// DevAttrCanUseHostPointerForRegisteredMem: Device can access host registered memory at the same virtual address as the CPU
	DevAttrCanUseHostPointerForRegisteredMem DeviceAttribute = 91
	// DevAttrCanUseStreamMemOpsV1: [Stream.BatchMemOp] and related APIs are supported.
	//
	// Deprecated: Deprecated by NVIDIA. This constant is deprecated along with v1 MemOps API.
	DevAttrCanUseStreamMemOpsV1 DeviceAttribute = 92
	// DevAttrCanUse64BitStreamMemOpsV1: 64-bit operations are supported in [Stream.BatchMemOp] and related APIs.
	//
	// Deprecated: Deprecated by NVIDIA. This constant is deprecated along with v1 MemOps API.
	DevAttrCanUse64BitStreamMemOpsV1 DeviceAttribute = 93
	// DevAttrCanUseStreamWaitValueNorV1: [StreamWaitValueNor] is supported.
	//
	// Deprecated: Deprecated by NVIDIA. This constant is deprecated along with v1 MemOps API.
	DevAttrCanUseStreamWaitValueNorV1 DeviceAttribute = 94
	// DevAttrCooperativeLaunch: Device supports launching cooperative kernels via [Function.LaunchCooperativeKernel]
	DevAttrCooperativeLaunch DeviceAttribute = 95
	//
	// Deprecated: Deprecated by NVIDIA. [LaunchCooperativeKernelMultiDevice] is deprecated.
	DevAttrCooperativeMultiDeviceLaunch DeviceAttribute = 96
	// DevAttrMaxSharedMemoryPerBlockOptin: Maximum optin shared memory per block. That is shared memory that is available for dynamic allocation or static allocation (including architecture specific static shared memory) on this device but is not guaranteed to be portable.
	DevAttrMaxSharedMemoryPerBlockOptin DeviceAttribute = 97
	// DevAttrCanFlushRemoteWrites: The [StreamWaitValueFlush] flag and the [StreamMemOpFlushRemoteWrites] MemOp are supported on the device. See CUDA_MEMOP for additional details.
	DevAttrCanFlushRemoteWrites DeviceAttribute = 98
	// DevAttrHostRegisterSupported: Device supports host memory registration via cudaHostRegister.
	DevAttrHostRegisterSupported                  DeviceAttribute = 99
	DevAttrPageableMemoryAccessUsesHostPageTables DeviceAttribute = 100 // Device accesses pageable memory via the host's page tables.
	// DevAttrDirectManagedMemAccessFromHost: The host can directly access managed memory on the device without migration.
	DevAttrDirectManagedMemAccessFromHost DeviceAttribute = 101
	//
	// Deprecated: Use [DevAttrVirtualMemoryManagementSupported] instead.
	DevAttrVirtualAddressManagementSupported DeviceAttribute = 102
	// DevAttrVirtualMemoryManagementSupported: Device supports virtual memory management APIs like [DevicePtr.MemAddressReserve], [MemCreate], [DevicePtr.MemMap] and related APIs
	DevAttrVirtualMemoryManagementSupported DeviceAttribute = 102
	// DevAttrHandleTypePosixFileDescriptorSupported: Device supports exporting memory to a posix file descriptor with [MemExportToShareableHandle], if requested via [MemCreate]
	DevAttrHandleTypePosixFileDescriptorSupported DeviceAttribute = 103
	// DevAttrHandleTypeWin32HandleSupported: Device supports exporting memory to a Win32 NT handle with [MemExportToShareableHandle], if requested via [MemCreate]
	DevAttrHandleTypeWin32HandleSupported DeviceAttribute = 104
	// DevAttrHandleTypeWin32KmtHandleSupported: Device supports exporting memory to a Win32 KMT handle with [MemExportToShareableHandle], if requested via [MemCreate]
	DevAttrHandleTypeWin32KmtHandleSupported DeviceAttribute = 105
	DevAttrMaxBlocksPerMultiprocessor        DeviceAttribute = 106 // Maximum number of blocks per multiprocessor
	DevAttrGenericCompressionSupported       DeviceAttribute = 107 // Device supports compression of memory
	DevAttrMaxPersistingL2CacheSize          DeviceAttribute = 108 // Maximum L2 persisting lines capacity setting in bytes.
	DevAttrMaxAccessPolicyWindowSize         DeviceAttribute = 109 // Maximum value of [AccessPolicyWindow].num_bytes.
	// DevAttrGpuDirectRdmaWithCudaVmmSupported: Device supports specifying the GPUDirect RDMA flag with [MemCreate]
	DevAttrGpuDirectRdmaWithCudaVmmSupported DeviceAttribute = 110
	DevAttrReservedSharedMemoryPerBlock      DeviceAttribute = 111 // Shared memory reserved by CUDA driver per block in bytes
	// DevAttrSparseCudaArraySupported: Device supports sparse CUDA arrays and sparse CUDA mipmapped arrays
	DevAttrSparseCudaArraySupported DeviceAttribute = 112
	// DevAttrReadOnlyHostRegisterSupported: Device supports using the [MemHostRegister] flag CU_MEMHOSTERGISTER_READ_ONLY to register memory that must be mapped as read-only to the GPU
	DevAttrReadOnlyHostRegisterSupported DeviceAttribute = 113
	// DevAttrTimelineSemaphoreInteropSupported: External timeline semaphore interop is supported on the device
	DevAttrTimelineSemaphoreInteropSupported DeviceAttribute = 114
	// DevAttrMemoryPoolsSupported: Device supports using the [Stream.MemAllocAsync] and cuMemPool family of APIs
	DevAttrMemoryPoolsSupported DeviceAttribute = 115
	// DevAttrGpuDirectRdmaSupported: Device supports GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information)
	DevAttrGpuDirectRdmaSupported DeviceAttribute = 116
	// DevAttrGpuDirectRdmaFlushWritesOptions: The returned attribute shall be interpreted as a bitmask, where the individual bits are described by the [FlushGPUDirectRDMAWritesOptions] enum
	DevAttrGpuDirectRdmaFlushWritesOptions DeviceAttribute = 117
	// DevAttrGpuDirectRdmaWritesOrdering: GPUDirect RDMA writes to the device do not need to be flushed for consumers within the scope indicated by the returned attribute. See [GPUDirectRDMAWritesOrdering] for the numerical values returned here.
	DevAttrGpuDirectRdmaWritesOrdering DeviceAttribute = 118
	DevAttrMempoolSupportedHandleTypes DeviceAttribute = 119 // Handle types supported with mempool based IPC
	DevAttrClusterLaunch               DeviceAttribute = 120 // Indicates device supports cluster launch
	// DevAttrDeferredMappingCudaArraySupported: Device supports deferred mapping CUDA arrays and CUDA mipmapped arrays
	DevAttrDeferredMappingCudaArraySupported DeviceAttribute = 121
	// DevAttrCanUse64BitStreamMemOps: 64-bit operations are supported in [Stream.BatchMemOp] and related MemOp APIs.
	DevAttrCanUse64BitStreamMemOps  DeviceAttribute = 122
	DevAttrCanUseStreamWaitValueNor DeviceAttribute = 123 // [StreamWaitValueNor] is supported by MemOp APIs.
	DevAttrDmaBufSupported          DeviceAttribute = 124 // Device supports buffer sharing with dma_buf mechanism.
	DevAttrIpcEventSupported        DeviceAttribute = 125 // Device supports IPC Events.
	DevAttrMemSyncDomainCount       DeviceAttribute = 126 // Number of memory domains the device supports.
	DevAttrTensorMapAccessSupported DeviceAttribute = 127 // Device supports accessing memory using Tensor Map.
	// DevAttrHandleTypeFabricSupported: Device supports exporting memory to a fabric handle with [MemExportToShareableHandle] or requested with [MemCreate]
	DevAttrHandleTypeFabricSupported DeviceAttribute = 128
	DevAttrUnifiedFunctionPointers   DeviceAttribute = 129 // Device supports unified function pointers.
	// DevAttrNumaConfig: NUMA configuration of a device: value is of type [DeviceNumaConfig] enum
	DevAttrNumaConfig         DeviceAttribute = 130
	DevAttrNumaId             DeviceAttribute = 131 // NUMA node ID of the GPU memory
	DevAttrMulticastSupported DeviceAttribute = 132 // Device supports switch multicast and reduction operations.
	// DevAttrMpsEnabled: Indicates if contexts created on this device will be shared via MPS
	DevAttrMpsEnabled DeviceAttribute = 133
	// DevAttrHostNumaId: NUMA ID of the host node closest to the device. Returns -1 when system does not support NUMA.
	DevAttrHostNumaId        DeviceAttribute = 134
	DevAttrD3d12CigSupported DeviceAttribute = 135 // Device supports CIG with D3D12.
	// DevAttrMemDecompressAlgorithmMask: The returned valued shall be interpreted as a bitmask, where the individual bits are described by the [MemDecompressAlgorithm] enum.
	DevAttrMemDecompressAlgorithmMask DeviceAttribute = 136
	// DevAttrMemDecompressMaximumLength: The returned valued is the maximum length in bytes of a single decompress operation that is allowed.
	DevAttrMemDecompressMaximumLength DeviceAttribute = 137
	DevAttrVulkanCigSupported         DeviceAttribute = 138 // Device supports CIG with Vulkan.
	DevAttrGpuPciDeviceId             DeviceAttribute = 139 // The combined 16-bit PCI device ID and 16-bit PCI vendor ID.
	// DevAttrGpuPciSubsystemId: The combined 16-bit PCI subsystem ID and 16-bit PCI subsystem vendor ID.
	DevAttrGpuPciSubsystemId DeviceAttribute = 140
	// DevAttrHostNumaVirtualMemoryManagementSupported: Device supports HOST_NUMA location with the virtual memory management APIs like [MemCreate], [DevicePtr.MemMap] and related APIs
	DevAttrHostNumaVirtualMemoryManagementSupported DeviceAttribute = 141
	// DevAttrHostNumaMemoryPoolsSupported: Device supports HOST_NUMA location with the [Stream.MemAllocAsync] and cuMemPool family of APIs
	DevAttrHostNumaMemoryPoolsSupported DeviceAttribute = 142
	// DevAttrHostNumaMultinodeIpcSupported: Device supports HOST_NUMA location IPC between nodes in a multi-node system.
	DevAttrHostNumaMultinodeIpcSupported DeviceAttribute = 143
	// DevAttrHostMemoryPoolsSupported: Device suports HOST location with the [Stream.MemAllocAsync] and cuMemPool family of APIs
	DevAttrHostMemoryPoolsSupported DeviceAttribute = 144
	// DevAttrHostVirtualMemoryManagementSupported: Device supports HOST location with the virtual memory management APIs like [MemCreate], [DevicePtr.MemMap] and related APIs
	DevAttrHostVirtualMemoryManagementSupported DeviceAttribute = 145
	// DevAttrHostAllocDmaBufSupported: Device supports page-locked host memory buffer sharing with dma_buf mechanism.
	DevAttrHostAllocDmaBufSupported DeviceAttribute = 146
	// DevAttrOnlyPartialHostNativeAtomicSupported: Link between the device and the host supports only some native atomic operations
	DevAttrOnlyPartialHostNativeAtomicSupported DeviceAttribute = 147
	// DevAttrAtomicReductionSupported: Device supports atomic reduction operations in stream batch memory operations
	DevAttrAtomicReductionSupported         DeviceAttribute = 148
	DevAttrLocalityDomainCount              DeviceAttribute = 149 // Number of locality domains
	DevAttrMaxOversizedSharedMemoryPerBlock DeviceAttribute = 150 // Maximum oversized shared memory per block
	DevAttrD3d12CigStreamsSupported         DeviceAttribute = 151 // Device supports CIG streams with D3D12
	// DevAttrDmaBufMmapSupported: Device supports mmap() of dmabuf file descriptors for CUDA device memory allocations
	DevAttrDmaBufMmapSupported                DeviceAttribute = 152
	DevAttrLogicalEndpointUnicastSupported    DeviceAttribute = 153 // Device supports unicast logical endpoints
	DevAttrLogicalEndpointMulticastSupported  DeviceAttribute = 154 // Device supports multicast logical endpoints
	DevAttrLogicalEndpointCountedOpsSupported DeviceAttribute = 155 // Device supports counted operations via logical endpoints
	// DevAttrLogicalEndpointUnicastAccessOnOwnerDeviceSupported: Device supports unicast logical endpoint access on the owner device
	DevAttrLogicalEndpointUnicastAccessOnOwnerDeviceSupported DeviceAttribute = 156
	DevAttrLocalityDomainMultiprocessorCount                  DeviceAttribute = 157 // Number of multiprocessors on each locality domain
	DevAttrLogicalEndpointSupportedHandleTypes                DeviceAttribute = 158 // Handle types supported with logical endpoint IPC
	DevAttrVulkanCigStreamsSupported                          DeviceAttribute = 159 // Device supports CIG streams with Vulkan
	// DevAttrTensorMapLargeTensorMinSize: Minimum contiguous, accessible size in bytes required when the large tensor-map allocation class is effective. Devices with a 128 KiB backing precondition report 131072; devices where allocation-class selection is a no-op report INT_MAX.
	DevAttrTensorMapLargeTensorMinSize DeviceAttribute = 160
	// DevAttrGpuDirectRdmaWithLocalizedMemorySupported: Device supports GPUDirect RDMA with localized memory using the default RDMA mapping link
	DevAttrGpuDirectRdmaWithLocalizedMemorySupported DeviceAttribute = 161
)

func (DeviceAttribute) String

func (e DeviceAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type DeviceNumaConfig

type DeviceNumaConfig int32

DeviceNumaConfig represents CUDA device NUMA configuration.

const (
	DeviceNumaConfigNone     DeviceNumaConfig = 0 // The GPU is not a NUMA node
	DeviceNumaConfigNumaNode DeviceNumaConfig = 1 // The GPU is a NUMA node, [DevAttrNumaId] contains its NUMA ID
)

func (DeviceNumaConfig) String

func (e DeviceNumaConfig) String() string

String returns the constant name, or a numeric representation for unknown values.

type DeviceP2pattribute

type DeviceP2pattribute int32

DeviceP2pattribute represents P2P Attributes.

const (
	// DeviceP2PAttributePerformanceRank: A relative value indicating the performance of the link between two devices
	DeviceP2PAttributePerformanceRank       DeviceP2pattribute = 0x01
	DeviceP2PAttributeAccessSupported       DeviceP2pattribute = 0x02 // P2P Access is enable
	DeviceP2PAttributeNativeAtomicSupported DeviceP2pattribute = 0x03 // All CUDA-valid atomic operation over the link are supported
	//
	// Deprecated: Use [DeviceP2PAttributeCudaArrayAccessSupported] instead.
	DeviceP2PAttributeAccessAccessSupported    DeviceP2pattribute = 0x04
	DeviceP2PAttributeCudaArrayAccessSupported DeviceP2pattribute = 0x04 // Accessing CUDA arrays over the link supported
	// DeviceP2PAttributeOnlyPartialNativeAtomicSupported: Only some CUDA-valid atomic operations over the link are supported.
	DeviceP2PAttributeOnlyPartialNativeAtomicSupported DeviceP2pattribute = 0x05
)

func (DeviceP2pattribute) String

func (e DeviceP2pattribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type DevicePtr

type DevicePtr uint64

DevicePtr is a CUDA device memory pointer. The size matches the platform pointer size (64-bit on 64-bit systems).

func IpcOpenMemHandle

func IpcOpenMemHandle(handle IpcMemHandle, flags IpcmemFlags) (DevicePtr, error)

IpcOpenMemHandle 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 DevicePtr.IpcGetMemHandle into the current device address space. For contexts on different devices IpcOpenMemHandle can attempt to enable peer access between the devices as if the user called Context.EnablePeerAccess. This behavior is controlled by the IpcMemLazyEnablePeerAccess flag. Device.CanAccessPeer can determine if a mapping is possible. Contexts that may open CUipcMemHandles are restricted in the following way. CUipcMemHandles 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 IpcOpenMemHandle must be freed with DevicePtr.IpcCloseMemHandle. Calling DevicePtr.Free on an exported memory region before calling DevicePtr.IpcCloseMemHandle 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 supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with DevAttrIpcEventSupported

Note: No guarantees are made about the address returned. In particular, multiple processes may not receive the same address for the same handle.

See also: MemAlloc, DevicePtr.Free, Event.IpcGetEventHandle, IpcOpenEventHandle, DevicePtr.IpcGetMemHandle, DevicePtr.IpcCloseMemHandle, Context.EnablePeerAccess, Device.CanAccessPeer, cudaIpcOpenMemHandle

Errors:

Wraps cuIpcOpenMemHandle, bound as cuIpcOpenMemHandle_v2.

func MemAlloc

func MemAlloc[T any](n int) (DevicePtr, error)

MemAlloc allocates device memory.

Allocates bytesize bytes of linear memory on the device and returns a pointer to the allocated memory. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. If bytesize is 0, MemAlloc returns ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMalloc

Errors:

The allocation holds n values of type T: bytesize is n times the size of T. A negative n, or one whose size overflows uint, is an error. T must not contain Go pointers: the garbage collector does not scan device memory.

Wraps cuMemAlloc, bound as cuMemAlloc_v2.

func MemAllocBytes

func MemAllocBytes(bytesize uint) (DevicePtr, error)

MemAllocBytes is MemAlloc with the size given in bytes.

  • bytesize: Requested allocation size in bytes

Wraps cuMemAlloc, bound as cuMemAlloc_v2.

func MemAllocManaged

func MemAllocManaged[T any](n int, flags MemattachFlags) (DevicePtr, error)

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

Allocates bytesize bytes of managed memory on the device and returns a pointer to the allocated memory. If the device doesn’t support allocating managed memory, ErrNotSupported is returned. Support for managed memory can be queried using the device attribute DevAttrManagedMemory. The allocated memory is suitably aligned for any kind of variable. The memory is not cleared. If bytesize is 0, MemAllocManaged returns ErrInvalidValue. 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 MemAttachGlobal or MemAttachHost. If MemAttachGlobal is specified, then this memory is accessible from any stream on any device. If MemAttachHost is specified, then the allocation should not be accessed from devices that have a zero value for the device attribute DevAttrConcurrentManagedAccess; an explicit call to Stream.AttachMemAsync will be required to enable access on such devices. If the association is later changed via Stream.AttachMemAsync to a single stream, the default association as specified during MemAllocManaged is restored when that stream is destroyed. For managed variables, the default association is always MemAttachGlobal. 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 MemAllocManaged should be released with DevicePtr.Free. Device memory oversubscription is possible for GPUs that have a non-zero value for the device attribute DevAttrConcurrentManagedAccess. 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 system where all GPUs have a non-zero value for the device attribute DevAttrConcurrentManagedAccess, 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 via DevicePtr.MemAdvise. The application can also explicitly migrate memory to a desired processor’s memory via DevicePtr.MemPrefetchAsync. In a multi-GPU system where all of the GPUs have a zero value for the device attribute DevAttrConcurrentManagedAccess 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 time MemAllocManaged 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 DevAttrConcurrentManagedAccess 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 DevAttrConcurrentManagedAccess. 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 contexts created in that process on devices that support managed memory have to be peer-to-peer compatible with each other. Context creation will fail if a context is created on a device that supports managed memory and is not peer-to-peer compatible with any of the other managed memory supporting devices on which contexts were previously created, even if those contexts have been destroyed. These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section.
  • On ARM, managed memory is not available on discrete gpu with Drive PX-2.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, Device.Attribute, Stream.AttachMemAsync, cudaMallocManaged

Errors:

The allocation holds n values of type T: bytesize is n times the size of T. A negative n, or one whose size overflows uint, is an error. T must not contain Go pointers: the garbage collector does not scan device memory.

Wraps cuMemAllocManaged.

func MemAllocManagedBytes

func MemAllocManagedBytes(bytesize uint, flags MemattachFlags) (DevicePtr, error)

MemAllocManagedBytes is MemAllocManaged with the size given in bytes.

  • bytesize: Requested allocation size in bytes

Wraps cuMemAllocManaged.

func MemAllocPitch

func MemAllocPitch(widthInBytes uint, height uint, elementSizeBytes uint32) (dptr DevicePtr, pPitch uint, err error)

MemAllocPitch allocates pitched device memory.

Allocates at least WidthInBytes * Height bytes of linear memory on the device and returns in *dptr 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. ElementSizeBytes specifies the size of the largest reads and writes that will be performed on the memory range. ElementSizeBytes may be 4, 8 or 16 (since coalesced memory transactions are not possible on other data sizes). If ElementSizeBytes is smaller than the actual read/write size of a kernel, the kernel will run correctly, but possibly at reduced speed. The pitch returned in *pPitch by MemAllocPitch 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:

T* pElement = (T*)((char*)BaseAddress + Row * Pitch) + Column;

The pitch returned by MemAllocPitch is guaranteed to work with Memcpy2D under all circumstances. For allocations of 2D arrays, it is recommended that programmers consider performing pitch allocations using MemAllocPitch. Due to 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). The byte alignment of the pitch returned by MemAllocPitch is guaranteed to match or exceed the alignment requirement for texture binding with TexRef.SetAddress2D.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMallocPitch

  • dptr: Returned device pointer
  • pPitch: Returned pitch of allocation in bytes
  • widthInBytes: Requested allocation width in bytes
  • height: Requested allocation height in rows
  • elementSizeBytes: Size of largest reads/writes for range

Errors:

Wraps cuMemAllocPitch, bound as cuMemAllocPitch_v2.

func MemHostGetDevicePointer

func MemHostGetDevicePointer(p uintptr, flags uint32) (DevicePtr, error)

MemHostGetDevicePointer passes back device pointer of mapped pinned memory.

Passes back the device pointer pdptr corresponding to the mapped, pinned host buffer p allocated by MemHostAlloc. MemHostGetDevicePointer will fail if the CU_MEMHOSTALLOC_DEVICEMAP flag was not specified at the time the memory was allocated, or if the function is called on a GPU that does not support mapped pinned memory. For devices that have a non-zero value for the device attribute DevAttrCanUseHostPointerForRegisteredMem, the memory can also be accessed from the device using the host pointer p. The device pointer returned by MemHostGetDevicePointer may or may not match the original host pointer p 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 by MemHostGetDevicePointer will match the original pointer p. If any device visible to the application has a zero value for the device attribute, the device pointer returned by MemHostGetDevicePointer will not match the original host pointer p, 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 one of the two pointers and not both. Flags provides for future releases. For now, it must be set to 0.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaHostGetDevicePointer

  • p: Host pointer
  • flags: Options (must be 0)

Errors:

Wraps cuMemHostGetDevicePointer, bound as cuMemHostGetDevicePointer_v2.

func (DevicePtr) CopyFromArray

func (d DevicePtr) CopyFromArray(srcArray Array, srcOffset uint, byteCount uint) error

CopyFromArray copies memory from Array to Device.

Copies from one 1D CUDA array to device memory. dstDevice specifies the base pointer of the destination and must be naturally aligned with the CUDA array elements. srcArray and srcOffset specify the CUDA array handle and the offset in bytes into the array where the copy is to begin. ByteCount specifies the number of bytes to copy and must be evenly divisible by the array element size.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpyFromArray

  • srcArray: Source array
  • srcOffset: Offset in bytes of source array
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpyAtoD, bound as cuMemcpyAtoD_v2.

func (DevicePtr) CopyFromDevice

func (d DevicePtr) CopyFromDevice(srcDevice DevicePtr, byteCount uint) error

CopyFromDevice copies memory from Device to Device.

Copies from device memory to device memory. dstDevice and srcDevice are the base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy, cudaMemcpyToSymbol, cudaMemcpyFromSymbol

  • srcDevice: Source device pointer
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpyDtoD, bound as cuMemcpyDtoD_v2.

func (DevicePtr) CopyFromDeviceAsync

func (d DevicePtr) CopyFromDeviceAsync(srcDevice DevicePtr, byteCount uint, hStream Stream) error

CopyFromDeviceAsync copies memory from Device to Device.

Copies from device memory to device memory. dstDevice and srcDevice are the base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyAsync, cudaMemcpyToSymbolAsync, cudaMemcpyFromSymbolAsync

  • srcDevice: Source device pointer
  • byteCount: Size of memory copy in bytes
  • hStream: Stream identifier

Errors:

Wraps cuMemcpyDtoDAsync, bound as cuMemcpyDtoDAsync_v2.

func (DevicePtr) CopyFromHost

func (d DevicePtr) CopyFromHost[T any](srcHost []T) error

CopyFromHost copies memory from Host to Device.

Copies from host memory to device memory. dstDevice and srcHost are the base addresses of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy, cudaMemcpyToSymbol

  • srcHost: Source host pointer

Errors:

The copy covers all of srcHost: len(srcHost) values of type T.

Wraps cuMemcpyHtoD, bound as cuMemcpyHtoD_v2.

func (DevicePtr) CopyFromHostAsync

func (d DevicePtr) CopyFromHostAsync[T any](srcHost []T, hStream Stream) error

CopyFromHostAsync copies memory from Host to Device.

Copies from host memory to device memory. dstDevice and srcHost are the base addresses of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyAsync, cudaMemcpyToSymbolAsync

  • srcHost: Source host pointer
  • hStream: Stream identifier

Errors:

srcHost must remain valid, unmoved, and unmodified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

The copy covers all of srcHost: len(srcHost) values of type T.

Wraps cuMemcpyHtoDAsync, bound as cuMemcpyHtoDAsync_v2.

func (DevicePtr) CopyFromHostAsyncPtr

func (d DevicePtr) CopyFromHostAsyncPtr(srcHost unsafe.Pointer, byteCount uint, hStream Stream) error

CopyFromHostAsyncPtr is DevicePtr.CopyFromHostAsync with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

srcHost must remain valid, unmoved, and unmodified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

Wraps cuMemcpyHtoDAsync, bound as cuMemcpyHtoDAsync_v2.

func (DevicePtr) CopyFromHostPtr

func (d DevicePtr) CopyFromHostPtr(srcHost unsafe.Pointer, byteCount uint) error

CopyFromHostPtr is DevicePtr.CopyFromHost with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

Wraps cuMemcpyHtoD, bound as cuMemcpyHtoD_v2.

func (DevicePtr) CopyFromPeer

func (d DevicePtr) CopyFromPeer(dstContext Context, srcDevice DevicePtr, srcContext Context, byteCount uint) error

CopyFromPeer copies device memory between two contexts.

Copies from device memory in one context to device memory in another context. dstDevice is the base device pointer of the destination memory and dstContext is the destination context. srcDevice is the base device pointer of the source memory and srcContext is the source pointer. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

See also: DevicePtr.CopyFromDevice, Memcpy3DPeer, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyFromPeerAsync, Stream.Memcpy3DPeerAsync, cudaMemcpyPeer

  • dstContext: Destination context
  • srcDevice: Source device pointer
  • srcContext: Source context
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpyPeer.

func (DevicePtr) CopyFromPeerAsync

func (d DevicePtr) CopyFromPeerAsync(dstContext Context, srcDevice DevicePtr, srcContext Context, byteCount uint, hStream Stream) error

CopyFromPeerAsync copies device memory between two contexts asynchronously.

Copies from device memory in one context to device memory in another context. dstDevice is the base device pointer of the destination memory and dstContext is the destination context. srcDevice is the base device pointer of the source memory and srcContext is the source pointer. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.CopyFromDevice, DevicePtr.CopyFromPeer, Memcpy3DPeer, DevicePtr.CopyFromDeviceAsync, Stream.Memcpy3DPeerAsync, cudaMemcpyPeerAsync

  • dstContext: Destination context
  • srcDevice: Source device pointer
  • srcContext: Source context
  • byteCount: Size of memory copy in bytes
  • hStream: Stream identifier

Errors:

Wraps cuMemcpyPeerAsync.

func (DevicePtr) CopyToHost

func (d DevicePtr) CopyToHost[T any](dstHost []T) error

CopyToHost copies memory from Device to Host.

Copies from device to host memory. dstHost and srcDevice specify the base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits synchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy, cudaMemcpyFromSymbol

  • dstHost: Destination host pointer

Errors:

The copy covers all of dstHost: len(dstHost) values of type T.

Wraps cuMemcpyDtoH, bound as cuMemcpyDtoH_v2.

func (DevicePtr) CopyToHostAsync

func (d DevicePtr) CopyToHostAsync[T any](dstHost []T, hStream Stream) error

CopyToHostAsync copies memory from Device to Host.

Copies from device to host memory. dstHost and srcDevice specify the base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyAsync, cudaMemcpyFromSymbolAsync

  • dstHost: Destination host pointer
  • hStream: Stream identifier

Errors:

dstHost must remain valid, unmoved, and neither read nor modified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

The copy covers all of dstHost: len(dstHost) values of type T.

Wraps cuMemcpyDtoHAsync, bound as cuMemcpyDtoHAsync_v2.

func (DevicePtr) CopyToHostAsyncPtr

func (d DevicePtr) CopyToHostAsyncPtr(dstHost unsafe.Pointer, byteCount uint, hStream Stream) error

CopyToHostAsyncPtr is DevicePtr.CopyToHostAsync with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

dstHost must remain valid, unmoved, and neither read nor modified until the stream work completes. The memory must be pinned (page-locked, or a Go value pinned with runtime.Pinner) and kept alive until the stream work completes. Do not pass stack memory.

Wraps cuMemcpyDtoHAsync, bound as cuMemcpyDtoHAsync_v2.

func (DevicePtr) CopyToHostPtr

func (d DevicePtr) CopyToHostPtr(dstHost unsafe.Pointer, byteCount uint) error

CopyToHostPtr is DevicePtr.CopyToHost with the host memory given as a pointer and a byte count, for memory Go does not own.

  • byteCount: Size of memory copy in bytes

Wraps cuMemcpyDtoH, bound as cuMemcpyDtoH_v2.

func (DevicePtr) Free

func (d DevicePtr) Free() error

Free frees device memory.

Frees the memory space pointed to by dptr, which must have been returned by a previous call to one of the following memory allocation APIs - MemAlloc, MemAllocPitch, MemAllocManaged, Stream.MemAllocAsync, MemoryPool.MemAllocFromPoolAsync Note - This API will not perform any implict synchronization when the pointer was allocated with Stream.MemAllocAsync or MemoryPool.MemAllocFromPoolAsync. Callers must ensure that all accesses to these pointer have completed before invoking DevicePtr.Free. For best performance and memory reuse, users should use DevicePtr.FreeAsync to free memory allocated via the stream ordered memory allocator. For all other pointers, this API may perform implicit synchronization.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, MemAllocManaged, Stream.MemAllocAsync, MemoryPool.MemAllocFromPoolAsync, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, DevicePtr.FreeAsync, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaFree

Errors:

It is not named Close because DevicePtr has another release method, FreeAsync.

Wraps cuMemFree, bound as cuMemFree_v2.

func (DevicePtr) FreeAsync

func (d DevicePtr) FreeAsync(hStream Stream) error

FreeAsync 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.

Note: During stream capture, this function results in the creation of a free node and must therefore be passed the address of a graph allocation.

  • hStream: The stream establishing the stream ordering contract

Errors:

It is not named Close because DevicePtr has another release method, Free.

Wraps cuMemFreeAsync.

func (DevicePtr) IpcCloseMemHandle

func (d DevicePtr) IpcCloseMemHandle() error

IpcCloseMemHandle attempts to close memory mapped with IpcOpenMemHandle.

Decrements the reference count of the memory returned by IpcOpenMemHandle 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 supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with DevAttrIpcEventSupported

See also: MemAlloc, DevicePtr.Free, Event.IpcGetEventHandle, IpcOpenEventHandle, DevicePtr.IpcGetMemHandle, IpcOpenMemHandle, cudaIpcCloseMemHandle

Errors:

Wraps cuIpcCloseMemHandle.

func (DevicePtr) IpcGetMemHandle

func (d DevicePtr) IpcGetMemHandle() (IpcMemHandle, error)

IpcGetMemHandle 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 MemAlloc 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 DevicePtr.Free and a subsequent call to MemAlloc returns memory with the same device address, DevicePtr.IpcGetMemHandle 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 supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with DevAttrIpcEventSupported

See also: MemAlloc, DevicePtr.Free, Event.IpcGetEventHandle, IpcOpenEventHandle, IpcOpenMemHandle, DevicePtr.IpcCloseMemHandle, cudaIpcGetMemHandle

Errors:

Wraps cuIpcGetMemHandle.

func (DevicePtr) MemAddressFree

func (d DevicePtr) MemAddressFree(size uint) error

MemAddressFree frees an address range reservation.

Frees a virtual address range reserved by DevicePtr.MemAddressReserve. The size must match what was given to memAddressReserve and the ptr given must match what was returned from memAddressReserve.

See also: DevicePtr.MemAddressReserve

  • size: Size of the virtual address region to free

Errors:

Wraps cuMemAddressFree.

func (DevicePtr) MemAddressReserve

func (d DevicePtr) MemAddressReserve(size uint, alignment uint, flags uint64) (DevicePtr, error)

MemAddressReserve allocates an address range reservation.

Reserves a virtual address range based on the given parameters, giving the starting address of the range in ptr. This API requires a system that supports UVA. The size and address parameters must be a multiple of the host page size and the alignment must be a power of two or zero for default alignment. If addr is 0, then the driver chooses the address at which to place the start of the reservation whereas when it is non-zero then the driver treats it as a hint about where to place the reservation.

See also: DevicePtr.MemAddressFree

  • size: Size of the reserved virtual address range requested
  • alignment: Alignment of the reserved virtual address range requested
  • flags: Currently unused, must be zero

Errors:

Wraps cuMemAddressReserve.

func (DevicePtr) MemAdvise deprecated

func (d DevicePtr) MemAdvise(count uint, advice MemAdvise, device Device) error

MemAdvise advises 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 MemAllocManaged 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:

  • MemAdviseSetReadMostly: 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, if DevicePtr.MemPrefetchAsync is called on this region, it will create a read-only copy of the data on the destination processor. If the target location for DevicePtr.MemPrefetchAsync is a host NUMA node and a read-only copy already exists on another host NUMA node, that copy will be migrated to the targeted host NUMA node. If any processor writes to this region, all copies of the corresponding page will be invalidated except for the one where the write occurred. If the writing processor is the CPU and the preferred location of the page is a host NUMA node, then the page will also be migrated to that host NUMA node. The location 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 attribute DevAttrConcurrentManagedAccess. Also, if a context is created on a device that does not have the device attribute DevAttrConcurrentManagedAccess 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 attribute DevAttrPageableMemoryAccess 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 attribute DevAttrPageableMemoryAccessUsesHostPageTables, then setting this advice will not create a read-only copy when that device accesses this memory region.
  • MemAdviseUnsetReadMostly: Undoes the effect of MemAdviseSetReadMostly 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. Note: The location argument is ignored for this advice.
  • MemAdviseSetPreferredLocation: This advice sets the preferred location for the data to be the memory belonging to location. When MemLocation.type is MemLocationTypeHost, MemLocation.id is ignored and the preferred location is set to be host memory. To set the preferred location to a specific host NUMA node, applications must set MemLocation.type to MemLocationTypeHostNuma and MemLocation.id must specify the NUMA ID of the host NUMA node. If MemLocation.type is set to MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored and the the host NUMA node closest to the calling thread’s CPU will be used as the preferred location. If MemLocation.type is a MemLocationTypeDevice, then MemLocation.id must be a valid device ordinal and the device must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess. A MemLocation.type of MemLocationTypeDeviceLocalityDomain is unsupported. 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 using DevicePtr.MemPrefetchAsync. 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. If MemAdviseSetReadMostly 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 location will not result in a read-only copy being created on that procesor as outlined in description for the advice MemAdviseSetReadMostly. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then MemLocation.id must be a valid device that has a non-zero alue for the device attribute DevAttrPageableMemoryAccess.
  • MemAdviseUnsetPreferredLocation: Undoes the effect of MemAdviseSetPreferredLocation and changes the preferred location to none. The location argument is ignored for this advice.
  • MemAdviseSetAccessedBy: This advice implies that the data will be accessed by processor location. The MemLocation.type must be either MemLocationTypeDevice with MemLocation.id representing a valid device ordinal or MemLocationTypeHost and MemLocation.id will be ignored. All other location types are invalid. If MemLocation.id is a GPU, then the device attribute DevAttrConcurrentManagedAccess 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 the MemAdviseSetAccessedBy flag set for this data will now have its mapping updated to point to the page in host memory. If MemAdviseSetReadMostly 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 location, then the policies associated with MemAdviseSetPreferredLocation will override the policies of this advice. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.
  • MemAdviseUnsetAccessedBy: Undoes the effect of MemAdviseSetAccessedBy. Any mappings to the data from location 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, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemPrefetchAsync, cudaMemAdvise

  • count: Size in bytes of the memory range
  • advice: Advice to be applied for the specified memory range
  • device: Device to apply the advice for

Errors:

Wraps cuMemAdvise_v1, bound as cuMemAdvise.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (DevicePtr) MemAdviseV1 deprecated

func (d DevicePtr) MemAdviseV1(count uint, advice MemAdvise, device Device) error

MemAdviseV1 advises 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 MemAllocManaged 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:

  • MemAdviseSetReadMostly: 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, if DevicePtr.MemPrefetchAsync is called on this region, it will create a read-only copy of the data on the destination processor. If the target location for DevicePtr.MemPrefetchAsync is a host NUMA node and a read-only copy already exists on another host NUMA node, that copy will be migrated to the targeted host NUMA node. If any processor writes to this region, all copies of the corresponding page will be invalidated except for the one where the write occurred. If the writing processor is the CPU and the preferred location of the page is a host NUMA node, then the page will also be migrated to that host NUMA node. The location 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 attribute DevAttrConcurrentManagedAccess. Also, if a context is created on a device that does not have the device attribute DevAttrConcurrentManagedAccess 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 attribute DevAttrPageableMemoryAccess 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 attribute DevAttrPageableMemoryAccessUsesHostPageTables, then setting this advice will not create a read-only copy when that device accesses this memory region.
  • MemAdviseUnsetReadMostly: Undoes the effect of MemAdviseSetReadMostly 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. Note: The location argument is ignored for this advice.
  • MemAdviseSetPreferredLocation: This advice sets the preferred location for the data to be the memory belonging to location. When MemLocation.type is MemLocationTypeHost, MemLocation.id is ignored and the preferred location is set to be host memory. To set the preferred location to a specific host NUMA node, applications must set MemLocation.type to MemLocationTypeHostNuma and MemLocation.id must specify the NUMA ID of the host NUMA node. If MemLocation.type is set to MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored and the the host NUMA node closest to the calling thread’s CPU will be used as the preferred location. If MemLocation.type is a MemLocationTypeDevice, then MemLocation.id must be a valid device ordinal and the device must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess. A MemLocation.type of MemLocationTypeDeviceLocalityDomain is unsupported. 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 using DevicePtr.MemPrefetchAsync. 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. If MemAdviseSetReadMostly 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 location will not result in a read-only copy being created on that procesor as outlined in description for the advice MemAdviseSetReadMostly. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then MemLocation.id must be a valid device that has a non-zero alue for the device attribute DevAttrPageableMemoryAccess.
  • MemAdviseUnsetPreferredLocation: Undoes the effect of MemAdviseSetPreferredLocation and changes the preferred location to none. The location argument is ignored for this advice.
  • MemAdviseSetAccessedBy: This advice implies that the data will be accessed by processor location. The MemLocation.type must be either MemLocationTypeDevice with MemLocation.id representing a valid device ordinal or MemLocationTypeHost and MemLocation.id will be ignored. All other location types are invalid. If MemLocation.id is a GPU, then the device attribute DevAttrConcurrentManagedAccess 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 the MemAdviseSetAccessedBy flag set for this data will now have its mapping updated to point to the page in host memory. If MemAdviseSetReadMostly 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 location, then the policies associated with MemAdviseSetPreferredLocation will override the policies of this advice. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.
  • MemAdviseUnsetAccessedBy: Undoes the effect of MemAdviseSetAccessedBy. Any mappings to the data from location 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, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemPrefetchAsync, cudaMemAdvise

  • count: Size in bytes of the memory range
  • advice: Advice to be applied for the specified memory range
  • device: Device to apply the advice for

Errors:

Wraps cuMemAdvise_v1, bound as cuMemAdvise.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (DevicePtr) MemAdviseV2

func (d DevicePtr) MemAdviseV2(count uint, advice MemAdvise, location MemLocation) error

MemAdviseV2 advises 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 MemAllocManaged 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:

  • MemAdviseSetReadMostly: 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, if DevicePtr.MemPrefetchAsync is called on this region, it will create a read-only copy of the data on the destination processor. If the target location for DevicePtr.MemPrefetchAsync is a host NUMA node and a read-only copy already exists on another host NUMA node, that copy will be migrated to the targeted host NUMA node. If any processor writes to this region, all copies of the corresponding page will be invalidated except for the one where the write occurred. If the writing processor is the CPU and the preferred location of the page is a host NUMA node, then the page will also be migrated to that host NUMA node. The location 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 attribute DevAttrConcurrentManagedAccess. Also, if a context is created on a device that does not have the device attribute DevAttrConcurrentManagedAccess 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 attribute DevAttrPageableMemoryAccess 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 attribute DevAttrPageableMemoryAccessUsesHostPageTables, then setting this advice will not create a read-only copy when that device accesses this memory region.
  • MemAdviseUnsetReadMostly: Undoes the effect of MemAdviseSetReadMostly 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. Note: The location argument is ignored for this advice.
  • MemAdviseSetPreferredLocation: This advice sets the preferred location for the data to be the memory belonging to location. When MemLocation.type is MemLocationTypeHost, MemLocation.id is ignored and the preferred location is set to be host memory. To set the preferred location to a specific host NUMA node, applications must set MemLocation.type to MemLocationTypeHostNuma and MemLocation.id must specify the NUMA ID of the host NUMA node. If MemLocation.type is set to MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored and the the host NUMA node closest to the calling thread’s CPU will be used as the preferred location. If MemLocation.type is a MemLocationTypeDevice, then MemLocation.id must be a valid device ordinal and the device must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess. A MemLocation.type of MemLocationTypeDeviceLocalityDomain is unsupported. 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 using DevicePtr.MemPrefetchAsync. 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. If MemAdviseSetReadMostly 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 location will not result in a read-only copy being created on that procesor as outlined in description for the advice MemAdviseSetReadMostly. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then MemLocation.id must be a valid device that has a non-zero alue for the device attribute DevAttrPageableMemoryAccess.
  • MemAdviseUnsetPreferredLocation: Undoes the effect of MemAdviseSetPreferredLocation and changes the preferred location to none. The location argument is ignored for this advice.
  • MemAdviseSetAccessedBy: This advice implies that the data will be accessed by processor location. The MemLocation.type must be either MemLocationTypeDevice with MemLocation.id representing a valid device ordinal or MemLocationTypeHost and MemLocation.id will be ignored. All other location types are invalid. If MemLocation.id is a GPU, then the device attribute DevAttrConcurrentManagedAccess 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 the MemAdviseSetAccessedBy flag set for this data will now have its mapping updated to point to the page in host memory. If MemAdviseSetReadMostly 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 location, then the policies associated with MemAdviseSetPreferredLocation will override the policies of this advice. If the memory region refers to valid system-allocated pageable memory, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.
  • MemAdviseUnsetAccessedBy: Undoes the effect of MemAdviseSetAccessedBy. Any mappings to the data from location 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, and MemLocation.type is MemLocationTypeDevice then device in MemLocation.id must have a non-zero value for the device attribute DevAttrPageableMemoryAccess. Additionally, if MemLocation.id has a non-zero value for the device attribute DevAttrPageableMemoryAccessUsesHostPageTables, then this call has no effect.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemPrefetchAsync, cudaMemAdvise

  • count: Size in bytes of the memory range
  • advice: Advice to be applied for the specified memory range
  • location: location to apply the advice for

Errors:

Wraps cuMemAdvise, bound as cuMemAdvise_v2.

func (DevicePtr) MemGetAccess

func (d DevicePtr) MemGetAccess(location *MemLocation) (uint64, error)

MemGetAccess gets the access flags set for the given location and ptr.

See also: DevicePtr.MemSetAccess

  • location: Location in which to check the flags for

Errors:

Wraps cuMemGetAccess.

func (DevicePtr) MemGetAddressRange

func (d DevicePtr) MemGetAddressRange() (pbase DevicePtr, psize uint, err error)

MemGetAddressRange gets information on memory allocations.

Returns the base address in *pbase and size in *psize of the allocation that contains the input pointer dptr. Both parameters pbase and psize are optional. If one of them is NULL, it is ignored.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32

  • pbase: Returned base address
  • psize: Returned size of device memory allocation

Errors:

Wraps cuMemGetAddressRange, bound as cuMemGetAddressRange_v2.

func (DevicePtr) MemGetHandleForAddressRange

func (d DevicePtr) MemGetHandleForAddressRange(handle unsafe.Pointer, size uint, handleType MemRangeHandleType, flags MemRangeFlags) error

MemGetHandleForAddressRange retrieves handle for an address range.

Get a handle of the specified type to an address range. When requesting MemRangeHandleType.MemRangeHandleTypeDmaBufFd, address range obtained by a prior call to either MemAlloc or DevicePtr.MemAddressReserve is supported if the DevAttrDmaBufSupported device attribute returns true. If the address range was obtained via DevicePtr.MemAddressReserve, it must also be fully mapped via DevicePtr.MemMap. Address range obtained by a prior call to either MemAllocHost or MemHostAlloc is supported if the DevAttrHostAllocDmaBufSupported device attribute returns true. As of CUDA 13.0, querying support for address range obtained by calling MemAllocHost or MemHostAlloc using the DevAttrDmaBufSupported device attribute is deprecated. Users must ensure the dptr and size are aligned to the host page size. The handle will be interpreted as a pointer to an integer to store the dma_buf file descriptor. Users must ensure the entire address range is backed and mapped when the address range is allocated by DevicePtr.MemAddressReserve. All the physical allocations backing the address range must be resident on the same device and have identical allocation properties. Users are also expected to retrieve a new handle every time the underlying physical allocation(s) corresponding to a previously queried VA range are changed. For MemRangeHandleType.MemRangeHandleTypeDmaBufFd, users may set flags to MemRangeFlagDmaBufMappingTypePcie. Which when set on a supported platform, will give a DMA_BUF handle mapped via PCIE BAR1 or will return an error otherwise. If the device attribute DevAttrDmaBufMmapSupported is set and a MemRangeHandleType.MemRangeHandleTypeDmaBufFd is requested for a device memory range then the returned dmabuf file descriptor may be passed as the file descriptor argument to the mmap() system call. For device memory on x86 systems the mapping will be a write combined mapping. On coherent ARM platforms these mappings will be regular cached memory. On all other platforms these mappings will be uncached.

Errors:

Wraps cuMemGetHandleForAddressRange.

func (DevicePtr) MemGetLocationInfo

func (d DevicePtr) MemGetLocationInfo(size uint, summaryGranularity uint, samplingGranularity uint, locationOut *MemLocation) error

MemGetLocationInfo gets residency information for a memory address range.

Retrieves memory location information for the specified address range starting at ptr with size size. The API summarizes the location information with a granularity specified by summaryGranularity. For each summary region, the API determines the most common location by sampling memory at intervals defined by samplingGranularity within that region. The location information is returned in the locationOut array, with one entry per summary region. The total number of locations returned will be ceil(size/summaryGranularity). The user is expected to allocate the locationOut array with sufficient memory. For example, with an address range of 1GB, a summaryGranularity of 128MB, and a samplingGranularity of 2MB, the function will:

  • Divide the 1GB range into 8 summary regions of 128MB each
  • Within each 128MB region, sample every 2MB to determine the most common location. If there is a tie a random winner is chosen.
  • Populate the locationOut array with 8 entries, one for each 128MB region summaryGranularity should be less than or equal to size and greater than 0. samplingGranularity should be less than or equal to summaryGranularity. If the samplingGranularity is set to 0, a system dependent value is used as the granularity. In all other cases, the call returns ErrInvalidValue.

When the memory is not resident on any processor, the call returns Success and the returned location type for that interval is MemLocationTypeNone. The memory range must refer to one of the following:

  • Managed memory allocated via MemAllocManaged, via cuMemAllocFromPool from a managed memory pool or declared via managed variables.
  • System-allocated pageable memory that is not registered via MemHostRegister. If the memory range does not refer to one of the above, the call returns ErrInvalidValue.

All devices on the system must have non-zero value of device attribute DevAttrConcurrentManagedAccess. If not, this call returns ErrNotSupported.

Requires CUDA 13.4 (driver r615) or later; see HasMemGetLocationInfo.

  • size: Size in bytes of the memory range to query
  • summaryGranularity: Granularity in bytes at which to summarize location information
  • samplingGranularity: Granularity in bytes at which to sample memory within each summary region
  • locationOut: Array to store location information, one entry per summary region

Errors:

Wraps cuMemGetLocationInfo.

func (DevicePtr) MemMap

func (d DevicePtr) MemMap(size uint, offset uint, handle uint64, flags uint64) error

MemMap maps an allocation handle to a reserved virtual address range.

Maps bytes of memory represented by handle starting from byte offset to size to address range [ addr, addr + size]. This range must be an address reservation previously reserved with DevicePtr.MemAddressReserve, and offset + size must be less than the size of the memory allocation. Both ptr, size, and offset must be a multiple of the value given via MemGetAllocationGranularity with the MemAllocGranularityMinimum flag. If handle represents a multicast object, ptr, size and offset must be aligned to the value returned by MulticastGetGranularity with the flag CU_MULTICAST_MINIMUM_GRANULARITY. For best performance however, it is recommended that ptr, size and offset be aligned to the value returned by MulticastGetGranularity with the flag CU_MULTICAST_RECOMMENDED_GRANULARITY. When handle represents a multicast object, this call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. When handle represents a multicast object, this call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly. Please note calling DevicePtr.MemMap does not make the address accessible, the caller needs to update accessibility of a contiguous mapped VA range by calling DevicePtr.MemSetAccess. Once a recipient process obtains a shareable memory handle from MemImportFromShareableHandle, the process must use DevicePtr.MemMap to map the memory into its address ranges before setting accessibility with DevicePtr.MemSetAccess. DevicePtr.MemMap can only create mappings on VA range reservations that are not currently mapped.

See also: DevicePtr.MemUnmap, DevicePtr.MemSetAccess, MemCreate, DevicePtr.MemAddressReserve, MemImportFromShareableHandle

  • size: Size of the memory mapping
  • offset: Offset into the memory represented byhandle from which to start mappingNote: currently must be zero
  • handle: Handle to a shareable memory
  • flags: flags for future use, must be zero now

Errors:

Wraps cuMemMap.

func (DevicePtr) MemPoolExportPointer

func (d DevicePtr) MemPoolExportPointer() (MemPoolPtrExportData, error)

MemPoolExportPointer exports data to share a memory pool allocation between processes.

Constructs shareDataOut for sharing a specific allocation from an already shared memory pool. The recipient process can import the allocation with the MemoryPool.ImportPointer api. The data is not a handle and may be shared through any IPC mechanism.

See also: MemoryPool.ExportToShareableHandle, MemPoolImportFromShareableHandle, MemoryPool.ImportPointer

Errors:

Wraps cuMemPoolExportPointer.

func (DevicePtr) MemPrefetchAsync deprecated

func (d DevicePtr) MemPrefetchAsync(count uint, dstDevice Device, hStream Stream) error

MemPrefetchAsync prefetches memory to the specified destination location.

devPtr is the base device pointer of the memory to be prefetched and location specifies the destination location. count specifies the number of bytes to copy. hStream is the stream in which the operation is enqueued. The memory range must refer to managed memory allocated via MemAllocManaged, via cuMemAllocFromPool from a managed memory pool or declared via managed variables. Specifying MemLocationTypeDevice for MemLocation.type will prefetch memory to GPU specified by device ordinal MemLocation.id which must have non-zero value for the device attribute DevAttrConcurrentManagedAccess. Additionally, hStream must be associated with a device that has a non-zero value for the device attribute DevAttrConcurrentManagedAccess. Specifying MemLocationTypeHost as MemLocation.type will prefetch data to host memory. Applications can request prefetching memory to a specific host NUMA node by specifying MemLocationTypeHostNuma for MemLocation.type and a valid host NUMA node id in MemLocation.id Users can also request prefetching memory to the host NUMA node closest to the current thread’s CPU by specifying MemLocationTypeHostNumaCurrent for MemLocation.type. Note when MemLocation.type is etiher MemLocationTypeHost OR MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored. Prefetching to MemLocationTypeDeviceLocalityDomain locations is not supported. 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 MemAllocManaged allocations to host memory in order to make room. Device memory allocated using MemAlloc or NewArray 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 the destination location. The exact behavior however also depends on the settings applied to this memory range via DevicePtr.MemAdvise as described below: If MemAdviseSetReadMostly was set on any subset of this memory range, then that subset will create a read-only copy of the pages on destination location. If however the destination location is a host NUMA node, then any pages of that subset that are already in another host NUMA node will be transferred to the destination. If MemAdviseSetPreferredLocation was called on any subset of this memory range, then the pages will be migrated to location even if location is not the preferred location of any pages in the memory range. If MemAdviseSetAccessedBy 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.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemAdvise, cudaMemPrefetchAsync

  • count: Size in bytes
  • dstDevice: Destination device to prefetch to
  • hStream: Stream to enqueue prefetch operation

Errors:

Wraps cuMemPrefetchAsync_v1, bound as cuMemPrefetchAsync.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (DevicePtr) MemPrefetchAsyncV1 deprecated

func (d DevicePtr) MemPrefetchAsyncV1(count uint, dstDevice Device, hStream Stream) error

MemPrefetchAsyncV1 prefetches memory to the specified destination location.

devPtr is the base device pointer of the memory to be prefetched and location specifies the destination location. count specifies the number of bytes to copy. hStream is the stream in which the operation is enqueued. The memory range must refer to managed memory allocated via MemAllocManaged, via cuMemAllocFromPool from a managed memory pool or declared via managed variables. Specifying MemLocationTypeDevice for MemLocation.type will prefetch memory to GPU specified by device ordinal MemLocation.id which must have non-zero value for the device attribute DevAttrConcurrentManagedAccess. Additionally, hStream must be associated with a device that has a non-zero value for the device attribute DevAttrConcurrentManagedAccess. Specifying MemLocationTypeHost as MemLocation.type will prefetch data to host memory. Applications can request prefetching memory to a specific host NUMA node by specifying MemLocationTypeHostNuma for MemLocation.type and a valid host NUMA node id in MemLocation.id Users can also request prefetching memory to the host NUMA node closest to the current thread’s CPU by specifying MemLocationTypeHostNumaCurrent for MemLocation.type. Note when MemLocation.type is etiher MemLocationTypeHost OR MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored. Prefetching to MemLocationTypeDeviceLocalityDomain locations is not supported. 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 MemAllocManaged allocations to host memory in order to make room. Device memory allocated using MemAlloc or NewArray 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 the destination location. The exact behavior however also depends on the settings applied to this memory range via DevicePtr.MemAdvise as described below: If MemAdviseSetReadMostly was set on any subset of this memory range, then that subset will create a read-only copy of the pages on destination location. If however the destination location is a host NUMA node, then any pages of that subset that are already in another host NUMA node will be transferred to the destination. If MemAdviseSetPreferredLocation was called on any subset of this memory range, then the pages will be migrated to location even if location is not the preferred location of any pages in the memory range. If MemAdviseSetAccessedBy 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.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemAdvise, cudaMemPrefetchAsync

  • count: Size in bytes
  • dstDevice: Destination device to prefetch to
  • hStream: Stream to enqueue prefetch operation

Errors:

Wraps cuMemPrefetchAsync_v1, bound as cuMemPrefetchAsync.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (DevicePtr) MemPrefetchAsyncV2

func (d DevicePtr) MemPrefetchAsyncV2(count uint, location MemLocation, flags uint32, hStream Stream) error

MemPrefetchAsyncV2 prefetches memory to the specified destination location.

devPtr is the base device pointer of the memory to be prefetched and location specifies the destination location. count specifies the number of bytes to copy. hStream is the stream in which the operation is enqueued. The memory range must refer to managed memory allocated via MemAllocManaged, via cuMemAllocFromPool from a managed memory pool or declared via managed variables. Specifying MemLocationTypeDevice for MemLocation.type will prefetch memory to GPU specified by device ordinal MemLocation.id which must have non-zero value for the device attribute DevAttrConcurrentManagedAccess. Additionally, hStream must be associated with a device that has a non-zero value for the device attribute DevAttrConcurrentManagedAccess. Specifying MemLocationTypeHost as MemLocation.type will prefetch data to host memory. Applications can request prefetching memory to a specific host NUMA node by specifying MemLocationTypeHostNuma for MemLocation.type and a valid host NUMA node id in MemLocation.id Users can also request prefetching memory to the host NUMA node closest to the current thread’s CPU by specifying MemLocationTypeHostNumaCurrent for MemLocation.type. Note when MemLocation.type is etiher MemLocationTypeHost OR MemLocationTypeHostNumaCurrent, MemLocation.id will be ignored. Prefetching to MemLocationTypeDeviceLocalityDomain locations is not supported. 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 MemAllocManaged allocations to host memory in order to make room. Device memory allocated using MemAlloc or NewArray 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 the destination location. The exact behavior however also depends on the settings applied to this memory range via DevicePtr.MemAdvise as described below: If MemAdviseSetReadMostly was set on any subset of this memory range, then that subset will create a read-only copy of the pages on destination location. If however the destination location is a host NUMA node, then any pages of that subset that are already in another host NUMA node will be transferred to the destination. If MemAdviseSetPreferredLocation was called on any subset of this memory range, then the pages will be migrated to location even if location is not the preferred location of any pages in the memory range. If MemAdviseSetAccessedBy 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.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.Memcpy, DevicePtr.CopyFromPeer, DevicePtr.MemcpyAsync, Stream.Memcpy3DPeerAsync, DevicePtr.MemAdvise, cudaMemPrefetchAsync

  • count: Size in bytes
  • location: Location to prefetch to
  • flags: flags for future use, must be zero now
  • hStream: Stream to enqueue prefetch operation

Errors:

Wraps cuMemPrefetchAsync, bound as cuMemPrefetchAsync_v2.

func (DevicePtr) MemRangeGetAttribute

func (d DevicePtr) MemRangeGetAttribute(data unsafe.Pointer, dataSize uint, attribute MemRangeAttribute, count uint) error

MemRangeGetAttribute queries 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 MemAllocManaged or declared via managed variables. The attribute parameter can take the following values:

  • MemRangeAttributeReadMostly: 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.
  • MemRangeAttributePreferredLocation: 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 CU_DEVICE_CPU if all pages in the memory range have the CPU as their preferred location, or it will be CU_DEVICE_INVALID 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.
  • MemRangeAttributeAccessedBy: 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 had MemAdviseSetAccessedBy 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, CU_DEVICE_INVALID 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, CU_DEVICE_INVALID, CU_DEVICE_INVALID }. 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.
  • MemRangeAttributeLastPrefetchLocation: 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 via DevicePtr.MemPrefetchAsync. This will either be a GPU id or CU_DEVICE_CPU 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, CU_DEVICE_INVALID will be returned. Note that this simply returns the last location that the application 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.
  • MemRangeAttributePreferredLocationType: If this attribute is specified, data will be interpreted as a MemLocationType, and dataSize must be sizeof(MemLocationType). The MemLocationType returned will be MemLocationTypeDevice if all pages in the memory range have the same GPU as their preferred location, or MemLocationType will be MemLocationTypeHost if all pages in the memory range have the CPU as their preferred location, or it will be MemLocationTypeHostNuma if all the pages in the memory range have the same host NUMA node ID as their preferred location or it will be MemLocationTypeInvalid 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 type of the pages in the memory range at the time of the query may be different from the preferred location type. MemRangeAttributePreferredLocationId: If this attribute is specified, data will be interpreted as a 32-bit integer, and dataSize must be 4. If the MemRangeAttributePreferredLocationType query for the same address range returns MemLocationTypeDevice, it will be a valid device ordinal or if it returns MemLocationTypeHostNuma, it will be a valid host NUMA node ID or if it returns any other location type, the id should be ignored.
  • MemRangeAttributeLastPrefetchLocationType: If this attribute is specified, data will be interpreted as a MemLocationType, and dataSize must be sizeof(MemLocationType). The result returned will be the last location to which all pages in the memory range were prefetched explicitly via DevicePtr.MemPrefetchAsync. The MemLocationType returned will be MemLocationTypeDevice if the last prefetch location was a GPU or MemLocationTypeHost if it was the CPU or MemLocationTypeHostNuma if the last prefetch location was a specific host NUMA node. If any page in the memory range was never explicitly prefetched or if all pages were not prefetched to the same location, MemLocationType will be MemLocationTypeInvalid. Note that this simply returns the last location type that the application 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. MemRangeAttributeLastPrefetchLocationId: If this attribute is specified, data will be interpreted as a 32-bit integer, and dataSize must be 4. If the MemRangeAttributeLastPrefetchLocationType query for the same address range returns MemLocationTypeDevice, it will be a valid device ordinal or if it returns MemLocationTypeHostNuma, it will be a valid host NUMA node ID or if it returns any other location type, the id should be ignored.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.MemRangeGetAttributes, DevicePtr.MemPrefetchAsync, DevicePtr.MemAdvise, cudaMemRangeGetAttribute

  • data: A pointers to a memory location where the result of each attribute query will be written to
  • dataSize: Array containing the size of data
  • attribute: The attribute to query
  • count: Size of the range to query

Errors:

Wraps cuMemRangeGetAttribute.

func (DevicePtr) MemRangeGetAttributes

func (d DevicePtr) MemRangeGetAttributes(data []unsafe.Pointer, dataSizes *uint, attributes *MemRangeAttribute, numAttributes uint, count uint) error

MemRangeGetAttributes queries 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 MemAllocManaged 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 DevicePtr.MemRangeGetAttribute for attribute descriptions and restrictions.

See also: DevicePtr.MemRangeGetAttribute, DevicePtr.MemAdvise, DevicePtr.MemPrefetchAsync, cudaMemRangeGetAttributes

  • data: A two-dimensional array containing pointers to memory locations where the result of each attribute query will be written to
  • dataSizes: Array containing the sizes of each result
  • attributes: An array of attributes to query (numAttributes and the number of attributes in this array should match)
  • numAttributes: Number of attributes to query
  • count: Size of the range to query

Errors:

Wraps cuMemRangeGetAttributes.

func (DevicePtr) MemSetAccess

func (d DevicePtr) MemSetAccess(size uint, desc *MemAccessDesc, count uint) error

MemSetAccess sets the access flags for each location specified in desc for the given virtual address range.

Given the virtual address range via ptr and size, and the locations in the array given by desc and count, set the access flags for the target locations. The range must be a fully mapped address range containing all allocations created by DevicePtr.MemMap / MemCreate. Users cannot specify MemLocationTypeHostNuma accessibility for allocations created on with other location types. Note: When MemAccessDesc.MemLocation.type is MemLocationTypeHostNuma, MemAccessDesc.MemLocation.id is ignored. When setting the access flags for a virtual address range mapping a multicast object, ptr and size must be aligned to the value returned by MulticastGetGranularity with the flag CU_MULTICAST_MINIMUM_GRANULARITY. For best performance however, it is recommended that ptr and size be aligned to the value returned by MulticastGetGranularity with the flag CU_MULTICAST_RECOMMENDED_GRANULARITY.

Note: This function exhibits synchronous behavior for most use cases.

See also: DevicePtr.MemSetAccess, MemCreate, : DevicePtr.MemMap

  • size: Length of the virtual address range
  • desc: Array of MemAccessDesc that describe how to change the mapping for each location specified
  • count: Number of MemAccessDesc in desc

Errors:

Wraps cuMemSetAccess.

func (DevicePtr) MemUnmap

func (d DevicePtr) MemUnmap(size uint) error

MemUnmap unmaps the backing memory of a given address range.

The range must be the entire contiguous address range that was mapped to. In other words, DevicePtr.MemUnmap cannot unmap a sub-range of an address range mapped by MemCreate / DevicePtr.MemMap. Any backing memory allocations will be freed if there are no existing mappings and there are no unreleased memory handles. When DevicePtr.MemUnmap returns successfully the address range is converted to an address reservation and can be used for a future calls to DevicePtr.MemMap. Any new mapping to this virtual address will need to have access granted through DevicePtr.MemSetAccess, as all mappings start with no accessibility setup.

Note: This function exhibits synchronous behavior for most use cases.

See also: MemCreate, DevicePtr.MemAddressReserve

  • size: Size of the virtual address range to unmap

Errors:

Wraps cuMemUnmap.

func (DevicePtr) Memcpy

func (d DevicePtr) Memcpy(src DevicePtr, byteCount uint) error

Memcpy copies memory.

Copies data between two pointers. dst and src are base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy. Note that this function infers the type of the transfer (host to host, host to device, device to device, or device to host) from the pointer values. This function is only allowed in contexts which support unified addressing.

Note: This function exhibits synchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD16, DevicePtr.MemsetD32, cudaMemcpy, cudaMemcpyToSymbol, cudaMemcpyFromSymbol

  • src: Source unified virtual address space pointer
  • byteCount: Size of memory copy in bytes

Errors:

Wraps cuMemcpy.

func (DevicePtr) MemcpyAsync

func (d DevicePtr) MemcpyAsync(src DevicePtr, byteCount uint, hStream Stream) error

MemcpyAsync copies memory asynchronously.

Copies data between two pointers. dst and src are base pointers of the destination and source, respectively. ByteCount specifies the number of bytes to copy. Note that this function infers the type of the transfer (host to host, host to device, device to device, or device to host) from the pointer values. This function is only allowed in contexts which support unified addressing.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpyAsync, cudaMemcpyToSymbolAsync, cudaMemcpyFromSymbolAsync

  • src: Source unified virtual address space pointer
  • byteCount: Size of memory copy in bytes
  • hStream: Stream identifier

Errors:

Wraps cuMemcpyAsync.

func (DevicePtr) MemcpyWithAttributesAsync

func (d DevicePtr) MemcpyWithAttributesAsync(src DevicePtr, size uint, attr *MemcpyAttributes, hStream Stream) error

MemcpyWithAttributesAsync performs asynchronous memory copy operation with the specified attributes.

Performs asynchronous memory copy operation where dst and src are the destination and source pointers respectively. size specifies the number of bytes to copy. attr specifies the attributes for the copy and hStream specifies the stream to enqueue the operation in. For more information regarding the attributes, please refer to MemcpyAttributes and it’s usage desciption in Stream.MemcpyBatchAsync

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: Stream.MemcpyBatchAsync

Requires CUDA 13.2 (driver r595) or later; see HasMemcpyWithAttributesAsync.

  • src: Source device pointer
  • size: Number of bytes to copy
  • attr: Attributes for the copy
  • hStream: Stream to enqueue the operation in

Errors:

Wraps cuMemcpyWithAttributesAsync.

func (DevicePtr) MemsetD2D8

func (d DevicePtr) MemsetD2D8(dstPitch uint, uc uint8, width uint, height uint) error

MemsetD2D8 initializes device memory.

Sets the 2D memory range of Width 8-bit values to the specified value uc. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2D

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • uc: Value to set
  • width: Width of row
  • height: Number of rows

Errors:

Wraps cuMemsetD2D8, bound as cuMemsetD2D8_v2.

func (DevicePtr) MemsetD2D8Async

func (d DevicePtr) MemsetD2D8Async(dstPitch uint, uc uint8, width uint, height uint, hStream Stream) error

MemsetD2D8Async sets device memory.

Sets the 2D memory range of Width 8-bit values to the specified value uc. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2DAsync

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • uc: Value to set
  • width: Width of row
  • height: Number of rows
  • hStream: Stream identifier

Errors:

Wraps cuMemsetD2D8Async.

func (DevicePtr) MemsetD2D16

func (d DevicePtr) MemsetD2D16(dstPitch uint, us uint16, width uint, height uint) error

MemsetD2D16 initializes device memory.

Sets the 2D memory range of Width 16-bit values to the specified value us. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. The dstDevice pointer and dstPitch offset must be two byte aligned. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2D

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • us: Value to set
  • width: Width of row
  • height: Number of rows

Errors:

Wraps cuMemsetD2D16, bound as cuMemsetD2D16_v2.

func (DevicePtr) MemsetD2D16Async

func (d DevicePtr) MemsetD2D16Async(dstPitch uint, us uint16, width uint, height uint, hStream Stream) error

MemsetD2D16Async sets device memory.

Sets the 2D memory range of Width 16-bit values to the specified value us. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. The dstDevice pointer and dstPitch offset must be two byte aligned. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2DAsync

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • us: Value to set
  • width: Width of row
  • height: Number of rows
  • hStream: Stream identifier

Errors:

Wraps cuMemsetD2D16Async.

func (DevicePtr) MemsetD2D32

func (d DevicePtr) MemsetD2D32(dstPitch uint, ui uint32, width uint, height uint) error

MemsetD2D32 initializes device memory.

Sets the 2D memory range of Width 32-bit values to the specified value ui. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. The dstDevice pointer and dstPitch offset must be four byte aligned. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2D

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • ui: Value to set
  • width: Width of row
  • height: Number of rows

Errors:

Wraps cuMemsetD2D32, bound as cuMemsetD2D32_v2.

func (DevicePtr) MemsetD2D32Async

func (d DevicePtr) MemsetD2D32Async(dstPitch uint, ui uint32, width uint, height uint, hStream Stream) error

MemsetD2D32Async sets device memory.

Sets the 2D memory range of Width 32-bit values to the specified value ui. Height specifies the number of rows to set, and dstPitch specifies the number of bytes between each row. The dstDevice pointer and dstPitch offset must be four byte aligned. This function performs fastest when the pitch is one that has been passed back by MemAllocPitch.

Note: See also memset synchronization details.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemset2DAsync

  • dstPitch: Pitch of destination device pointer(Unused if Height is 1)
  • ui: Value to set
  • width: Width of row
  • height: Number of rows
  • hStream: Stream identifier

Errors:

Wraps cuMemsetD2D32Async.

func (DevicePtr) MulticastBindAddr

func (d DevicePtr) MulticastBindAddr(mcHandle uint64, mcOffset uint, size uint, flags uint64) error

MulticastBindAddr binds a memory allocation represented by a virtual address to a multicast object.

Binds a memory allocation specified by its mapped address memptr to a multicast object represented by mcHandle. The memory must have been allocated via MemCreate or cudaMallocAsync. The intended size of the bind, the offset in the multicast range mcOffset and memptr must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memptr should be aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the total size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memptr may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memptr cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum Also note that the ability to accept a memptr that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull The memory allocation must have beeen created on one of the devices that was added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate, Device.MulticastBindAddrV2

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into multicast va range for attachment
  • size: Size of memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMulticastBindAddr.

func (DevicePtr) MulticastBindAddrV1

func (d DevicePtr) MulticastBindAddrV1(mcHandle uint64, mcOffset uint, size uint, flags uint64) error

MulticastBindAddrV1 binds a memory allocation represented by a virtual address to a multicast object.

Binds a memory allocation specified by its mapped address memptr to a multicast object represented by mcHandle. The memory must have been allocated via MemCreate or cudaMallocAsync. The intended size of the bind, the offset in the multicast range mcOffset and memptr must be a multiple of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum. For best performance however, size, mcOffset and memptr should be aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityRecommended. The size cannot be larger than the size of the allocated memory. Similarly the size + mcOffset cannot be larger than the total size of the multicast object. On systems with Rubin+ (SM_107+) GPUs, memptr may be aligned to 256 instead of the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended. In such a case the size + memptr cannot be larger than the size of the allocated memory. Similarly the size + mcOffset + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum cannot be larger than the size of the than the size of the multicast object. The next available mcOffset for the next bind will be mcOffset + size + the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum Also note that the ability to accept a memptr that is not aligned to the value returned by MulticastGetGranularity with the flag MulticastGranularityMinimum or MulticastGranularityRecommended is limited by HW resources and may result in error ErrMulticastResourceFull The memory allocation must have beeen created on one of the devices that was added to the multicast team via Device.MulticastAdd. Externally shareable as well as imported multicast objects can be bound only to externally shareable memory. Note that this call will return ErrOutOfMemory if there are insufficient resources required to perform the bind. This call may also return ErrSystemNotReady if the necessary system software is not initialized or running. This call may fail if the devices added via Device.MulticastAdd do not belong to the same clique. This call may return ErrIllegalState if the system configuration is in an illegal state. In such cases, to continue using multicast, verify that the system configuration is in a valid state and all required driver daemons are running properly.

See also: MulticastCreate, Device.MulticastAdd, MemCreate, Device.MulticastBindAddrV2

  • mcHandle: Handle representing a multicast object
  • mcOffset: Offset into multicast va range for attachment
  • size: Size of memory that will be bound to the multicast object
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMulticastBindAddr.

func (DevicePtr) PointerGetAttribute

func (d DevicePtr) PointerGetAttribute(data unsafe.Pointer, attribute PointerAttribute) error

PointerGetAttribute returns information about a pointer.

The supported attributes are:

Returns in *data the Context in which ptr was allocated or registered. The type of data must be Context *. If ptr was not allocated by, mapped by, or registered with a Context which uses unified virtual addressing then ErrInvalidValue is returned.

Returns in *data the physical memory type of the memory that ptr addresses as a MemoryType enumerated value. The type of data must be unsigned int. If ptr addresses device memory then *data is set to MemoryTypeDevice. The particular Device on which the memory resides is the Device of the Context returned by the PointerAttributeContext attribute of ptr. If ptr addresses host memory then *data is set to MemoryTypeHost. If ptr was not allocated by, mapped by, or registered with a Context which uses unified virtual addressing then ErrInvalidValue is returned. If the current Context does not support unified virtual addressing then ErrInvalidContext is returned.

Returns in *data the device pointer value through which ptr may be accessed by kernels running in the current Context. The type of data must be DevicePtr *. If there exists no device pointer value through which kernels running in the current Context may access ptr then ErrInvalidValue is returned. If there is no current Context then ErrInvalidContext is returned. Except in the exceptional disjoint addressing cases discussed below, the value returned in *data will equal the input value ptr.

Returns in *data the host pointer value through which ptr may be accessed by by the host program. The type of data must be void **. If there exists no host pointer value through which the host program may directly access ptr then ErrInvalidValue is returned. Except in the exceptional disjoint addressing cases discussed below, the value returned in *data will equal the input value ptr.

Returns in *data two tokens for use with the nv-p2p.h Linux kernel interface. data must be a struct of type PointerAttributeP2PTokens. ptr must be a pointer to memory obtained from :MemAlloc. Note that p2pToken and vaSpaceToken are only valid for the lifetime of the source allocation. A subsequent allocation at the same address may return completely different tokens. Querying this attribute has a side effect of setting the attribute PointerAttributeSyncMemops for the region of memory that ptr points to.

A boolean attribute which when set, ensures that synchronous memory operations initiated on the region of memory that ptr points to will always synchronize. See further documentation in the section titled “API synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.

Returns in *data a buffer ID which is guaranteed to be unique within the process. data must point to an unsigned long long. ptr must be a pointer to memory obtained from a CUDA memory allocation API. Every memory allocation from any of the CUDA memory allocation APIs will have a unique ID over a process lifetime. Subsequent allocations do not reuse IDs from previous freed allocations. IDs are only unique within a single process.

Returns in *data a boolean that indicates whether the pointer points to managed memory or not. If ptr is not a valid CUDA pointer then ErrInvalidValue is returned.

Returns in *data an integer representing a device ordinal of a device against which the memory was allocated or registered.

Returns in *data a boolean that indicates if this pointer maps to an allocation that is suitable for cudaIpcGetMemHandle.

Returns in *data the starting address for the allocation referenced by the device pointer ptr. Note that this is not necessarily the address of the mapped region, but the address of the mappable address range ptr references (e.g. from DevicePtr.MemAddressReserve).

Returns in *data the size for the allocation referenced by the device pointer ptr. Note that this is not necessarily the size of the mapped region, but the size of the mappable address range ptr references (e.g. from DevicePtr.MemAddressReserve). To retrieve the size of the mapped region, see DevicePtr.MemGetAddressRange

Returns in *data a boolean that indicates if this pointer is in a valid address range that is mapped to a backing allocation.

Returns a bitmask of the allowed handle types for an allocation that may be passed to MemExportToShareableHandle.

Returns in *data a boolean that indicates if the memory this pointer is referencing can be used with the GPUDirect RDMA API.

Returns in *data the handle to the mempool that the allocation was obtained from.

Returns in *data a boolean that indicates whether the pointer points to memory that is capable to be used for hardware accelerated decompression.

Returns in *data an integer representing the locality domain ordinal of the allocation, or -1 if the allocation is not localized to a locality domain. Note that for most allocations in the unified virtual address space the host and device pointer for accessing the allocation will be the same. The exceptions to this are

  • user memory registered using MemHostRegister
  • host memory allocated using MemHostAlloc with the CU_MEMHOSTALLOC_WRITECOMBINED flag For these types of allocation there will exist separate, disjoint host and device addresses for accessing the allocation. In particular
  • The host address will correspond to an invalid unmapped device address (which will result in an exception if accessed from the device)
  • The device address will correspond to an invalid unmapped host address (which will result in an exception if accessed from the host). For these types of allocations, querying PointerAttributeHostPointer and PointerAttributeDevicePointer may be used to retrieve the host and device addresses from either address.

See also: DevicePtr.PointerSetAttribute, MemAlloc, DevicePtr.Free, MemAllocHost, MemFreeHost, MemHostAlloc, MemHostRegister, MemHostUnregister, cudaPointerGetAttributes

  • data: Returned pointer attribute value
  • attribute: Pointer attribute to query

Errors:

Wraps cuPointerGetAttribute.

func (DevicePtr) PointerGetAttributes

func (d DevicePtr) PointerGetAttributes(numAttributes uint32, attributes *PointerAttribute, data []unsafe.Pointer) error

PointerGetAttributes returns information about a pointer.

The supported attributes are (refer to DevicePtr.PointerGetAttribute for attribute descriptions and restrictions):

Unlike DevicePtr.PointerGetAttribute, this function will not return an error when the ptr encountered is not a valid CUDA pointer. Instead, the attributes are assigned default NULL values and Success is returned. If ptr was not allocated by, mapped by, or registered with a Context which uses UVA (Unified Virtual Addressing), ErrInvalidContext is returned.

See also: DevicePtr.PointerGetAttribute, DevicePtr.PointerSetAttribute, cudaPointerGetAttributes

  • numAttributes: Number of attributes to query
  • attributes: An array of attributes to query (numAttributes and the number of attributes in this array should match)
  • data: A two-dimensional array containing pointers to memory locations where the result of each attribute query will be written to

Errors:

Wraps cuPointerGetAttributes.

func (DevicePtr) PointerSetAttribute

func (d DevicePtr) PointerSetAttribute(value unsafe.Pointer, attribute PointerAttribute) error

PointerSetAttribute sets attributes on a previously allocated memory region.

The supported attributes are:

A boolean attribute that can either be set (1) or unset (0). When set, the region of memory that ptr points to is guaranteed to always synchronize memory operations that are synchronous. If there are some previously initiated synchronous memory operations that are pending when this attribute is set, the function does not return until those memory operations are complete. See further documentation in the section titled “API synchronization behavior” to learn more about cases when synchronous memory operations can exhibit asynchronous behavior. value will be considered as a pointer to an unsigned integer to which this attribute is to be set.

See also: DevicePtr.PointerGetAttribute, DevicePtr.PointerGetAttributes, MemAlloc, DevicePtr.Free, MemAllocHost, MemFreeHost, MemHostAlloc, MemHostRegister, MemHostUnregister

  • value: Pointer to memory containing the value to be set
  • attribute: Pointer attribute to set

Errors:

Wraps cuPointerSetAttribute.

type Devprop

type Devprop struct {
	// Maximum number of threads per block
	MaxThreadsPerBlock int32
	// Maximum size of each dimension of a block
	MaxThreadsDim [3]int32
	// Maximum size of each dimension of a grid
	MaxGridSize [3]int32
	// Shared memory available per block in bytes
	SharedMemPerBlock int32
	// Constant memory available on device in bytes
	TotalConstantMemory int32
	// Warp size in threads
	SIMDWidth int32
	// Maximum pitch in bytes allowed by memory copies
	MemPitch int32
	// 32-bit registers available per block
	RegsPerBlock int32
	// Clock frequency in kilohertz
	ClockRate int32
	// Alignment requirement for textures
	TextureAlign int32
}

Devprop represents legacy device properties.

type DevpropV1

type DevpropV1 = Devprop

DevpropV1 is an alias for Devprop.

type DevsmresourcegroupFlags

type DevsmresourcegroupFlags int32

DevsmresourcegroupFlags represents flags for a DevSmResource group.

const (
	DevSmResourceGroupDefault  DevsmresourcegroupFlags = 0
	DevSmResourceGroupBackfill DevsmresourcegroupFlags = 0x1
	// DevSmResourceGroupLocalityDomainId: The SMs must be located on a specific locality domain, specified by localityDomainId
	DevSmResourceGroupLocalityDomainId DevsmresourcegroupFlags = 0x1 << 1
	// DevSmResourceGroupLocalityDomainSupplementalSms: Modifier to [DevSmResourceGroupLocalityDomainId] which allows selection of SMs in the locality domain exceeding the [DeviceAttribute].[DevAttrLocalityDomainMultiprocessorCount]
	DevSmResourceGroupLocalityDomainSupplementalSms DevsmresourcegroupFlags = 0x1 << 2
)

func (DevsmresourcegroupFlags) String

func (e DevsmresourcegroupFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type DevsmresourcesplitbycountFlags

type DevsmresourcesplitbycountFlags int32

DevsmresourcesplitbycountFlags specifies the devsmresourcesplitbycount flags (CUdevSmResourceSplitByCount_flags).

const (
	DevSmResourceSplitIgnoreSmCoscheduling    DevsmresourcesplitbycountFlags = 0x1
	DevSmResourceSplitMaxPotentialClusterSize DevsmresourcesplitbycountFlags = 0x2
)

func (DevsmresourcesplitbycountFlags) String

String returns the constant name, or a numeric representation for unknown values.

type Dim3

type Dim3 struct {
	X, Y, Z uint32
}

Dim3 is an extent along X, Y and Z, such as the size of a grid in blocks or of a block in threads. It has the layout of three consecutive unsigned int members.

func Dims

func Dims(x, y, z uint32) Dim3

Dims returns the Dim3 {x, y, z}. Unlike CUDA's dim3, it has no default extents: a launch rejects a zero member.

func GridFor

func GridFor(n, block uint32) Dim3

GridFor returns the one-dimensional grid of blocks of block threads that covers n threads: Dims(ceil(n/block), 1, 1). It returns the zero Dim3 if block is zero, and a grid with a zero member if n is zero; a launch rejects both.

func (Dim3) String

func (d Dim3) String() string

String returns d as XxYxZ, such as 64x1x1.

type DriverProcAddressQueryResult

type DriverProcAddressQueryResult int32

DriverProcAddressQueryResult represents flags to indicate search status.

For more details see GetProcAddress

const (
	GetProcAddressSuccess              DriverProcAddressQueryResult = 0 // Symbol was succesfully found
	GetProcAddressSymbolNotFound       DriverProcAddressQueryResult = 1 // Symbol was not found in search
	GetProcAddressVersionNotSufficient DriverProcAddressQueryResult = 2 // Symbol was found but version supplied was not sufficient
)

func GetProcAddress

func GetProcAddress(symbol string, cudaVersion int32, flags DriverprocaddressFlags) (pfn uintptr, symbolStatus DriverProcAddressQueryResult, err error)

GetProcAddress returns the requested driver API function pointer.

Returns in **pfn the address of the CUDA driver function for the requested CUDA version and flags. The CUDA version is specified as (1000 * major + 10 * minor), so CUDA 11.2 should be specified as 11020. For a requested driver symbol, if the specified CUDA version is greater than or equal to the CUDA version in which the driver symbol was introduced, this API will return the function pointer to the corresponding versioned function. If the specified CUDA version is greater than the driver version, the API will return ErrInvalidValue. The pointer returned by the API should be cast to a function pointer matching the requested driver function’s definition in the API header file. The function pointer typedef can be picked up from the corresponding typedefs header file. For example, cudaTypedefs.h consists of function pointer typedefs for driver APIs defined in cuda.h. The API will return Success and set the returned pfn to NULL if the requested driver function is not supported on the platform, no ABI compatible driver function exists for the specified cudaVersion or if the driver symbol is invalid. It will also set the optional symbolStatus to one of the values in DriverProcAddressQueryResult with the following meanings:

The requested flags can be:

Note: Version mixing among CUDA-defined types and driver API versions is strongly discouraged and doing so can result in an undefined behavior.

See also: cudaGetDriverEntryPointByVersion

  • symbol: The base name of the driver API function to look for. As an example, for the driver API MemAlloc, symbol would be MemAlloc and cudaVersion would be the ABI compatible CUDA version for the _v2 variant
  • pfn: The function pointer to the requested driver function
  • cudaVersion: The CUDA version to look for the requested driver symbol
  • flags: Flags to specify search options
  • symbolStatus: The status of the search for symbol based on cudaVersion. See DriverProcAddressQueryResult for possible values

Errors:

Wraps cuGetProcAddress, bound as cuGetProcAddress_v2.

func (DriverProcAddressQueryResult) String

String returns the constant name, or a numeric representation for unknown values.

type DriverprocaddressFlags

type DriverprocaddressFlags int32

DriverprocaddressFlags represents flags to specify search options.

For more details see GetProcAddress

const (
	GetProcAddressDefault                DriverprocaddressFlags = 0      // Default search mode for driver symbols.
	GetProcAddressLegacyStream           DriverprocaddressFlags = 1 << 0 // Search for legacy versions of driver symbols.
	GetProcAddressPerThreadDefaultStream DriverprocaddressFlags = 1 << 1 // Search for per-thread versions of driver symbols.
)

func (DriverprocaddressFlags) String

func (e DriverprocaddressFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type Event

type Event uintptr

Event is an opaque handle to a CUDA event. Created via NewEvent and destroyed via [Event.Destroy].

func IpcOpenEventHandle

func IpcOpenEventHandle(handle IpcEventHandle) (Event, error)

IpcOpenEventHandle opens an interprocess event handle for use in the current process.

Opens an interprocess event handle exported from another process with Event.IpcGetEventHandle. This function returns a Event that behaves like a locally created event with the EventDisableTiming flag specified. This event must be freed with Event.Close. Performing operations on the imported event after the exported event has been freed with Event.Close 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 supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling cuapiDeviceGetAttribute with DevAttrIpcEventSupported

See also: NewEvent, Event.Close, Event.Synchronize, Event.Query, Stream.WaitEvent, Event.IpcGetEventHandle, DevicePtr.IpcGetMemHandle, IpcOpenMemHandle, DevicePtr.IpcCloseMemHandle, cudaIpcOpenEventHandle

  • handle: Interprocess handle to open

Errors:

Wraps cuIpcOpenEventHandle.

func NewEvent

func NewEvent(flags EventFlags) (Event, error)

NewEvent creates an event.

Creates an event for the current context with the flags specified via Flags. Valid flags include:

See also: Event.Record, Event.Query, Event.Synchronize, Event.Close, Event.ElapsedTime, cudaEventCreate, cudaEventCreateWithFlags

  • flags: Event creation flags

Errors:

Wraps cuEventCreate.

func (*Event) Close

func (e *Event) Close() error

Close destroys an event.

Destroys the event specified by hEvent. An event may be destroyed before it is complete (i.e., while Event.Query would return ErrNotReady). In this case, the call does not block on completion of the event, and any associated resources will automatically be released asynchronously at completion.

See also: NewEvent, Event.Record, Event.Query, Event.Synchronize, Event.ElapsedTime, cudaEventDestroy

Errors:

If e is zero, Close returns nil. Otherwise Close sets e to zero when the call succeeds and leaves it unchanged when it fails. Only e is zeroed: a copy of it still refers to the released object.

Wraps cuEventDestroy, bound as cuEventDestroy_v2.

func (Event) ElapsedTime

func (e Event) ElapsedTime(hEnd Event) (float32, error)

ElapsedTime computes the elapsed time between two events.

Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds). Note this API is not guaranteed to return the latest errors for pending work. As such this API is intended to serve as an elapsed time calculation only and any polling for completion on the events to be compared should be done with Event.Query instead. 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 Event.Record 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 Event.Record has not been called on either event then ErrInvalidHandle is returned. If Event.Record has been called on both events but one or both of them has not yet been completed (that is, Event.Query would return ErrNotReady on at least one of the events), ErrNotReady is returned. If either event was created with the EventDisableTiming flag, then this function will return ErrInvalidHandle.

See also: NewEvent, Event.Record, Event.Query, Event.Synchronize, Event.Close, cudaEventElapsedTime

  • hEnd: Ending event

Errors:

Wraps cuEventElapsedTime, bound to the first of cuEventElapsedTime_v2, cuEventElapsedTime that the library exports.

func (Event) ElapsedTimeV1 deprecated

func (e Event) ElapsedTimeV1(hEnd Event) (float32, error)

ElapsedTimeV1 computes the elapsed time between two events.

Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds). Note this API is not guaranteed to return the latest errors for pending work. As such this API is intended to serve as an elapsed time calculation only and any polling for completion on the events to be compared should be done with Event.Query instead. 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 Event.Record 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 Event.Record has not been called on either event then ErrInvalidHandle is returned. If Event.Record has been called on both events but one or both of them has not yet been completed (that is, Event.Query would return ErrNotReady on at least one of the events), ErrNotReady is returned. If either event was created with the EventDisableTiming flag, then this function will return ErrInvalidHandle.

See also: NewEvent, Event.Record, Event.Query, Event.Synchronize, Event.Close, cudaEventElapsedTime

  • hEnd: Ending event

Errors:

Wraps cuEventElapsedTime_v1, bound as cuEventElapsedTime.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Event) ElapsedTimeV2

func (e Event) ElapsedTimeV2(hEnd Event) (float32, error)

ElapsedTimeV2 computes the elapsed time between two events.

Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds). Note this API is not guaranteed to return the latest errors for pending work. As such this API is intended to serve as an elapsed time calculation only and any polling for completion on the events to be compared should be done with Event.Query instead. 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 Event.Record 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 Event.Record has not been called on either event then ErrInvalidHandle is returned. If Event.Record has been called on both events but one or both of them has not yet been completed (that is, Event.Query would return ErrNotReady on at least one of the events), ErrNotReady is returned. If either event was created with the EventDisableTiming flag, then this function will return ErrInvalidHandle.

See also: NewEvent, Event.Record, Event.Query, Event.Synchronize, Event.Close, cudaEventElapsedTime

Requires CUDA 12.8 (driver r570) or later; see HasEventElapsedTimeV2.

  • hEnd: Ending event

Errors:

Wraps cuEventElapsedTime, bound as cuEventElapsedTime_v2.

func (Event) IpcGetEventHandle

func (e Event) IpcGetEventHandle() (IpcEventHandle, error)

IpcGetEventHandle gets an interprocess handle for a previously allocated event.

Takes as input a previously allocated event. This event must have been created with the EventInterprocess and EventDisableTiming flags set. This opaque handle may be copied into other processes and opened with IpcOpenEventHandle to allow efficient hardware synchronization between GPU work in different processes. After the event has been opened in the importing process, Event.Record, Event.Synchronize, Stream.WaitEvent and Event.Query may be used in either process. Performing operations on the imported event after the exported event has been freed with Event.Close 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 supported for compatibility purposes but not recommended as it comes with performance cost. Users can test their device for IPC functionality by calling Device.Attribute with DevAttrIpcEventSupported

See also: NewEvent, Event.Close, Event.Synchronize, Event.Query, Stream.WaitEvent, IpcOpenEventHandle, DevicePtr.IpcGetMemHandle, IpcOpenMemHandle, DevicePtr.IpcCloseMemHandle, cudaIpcGetEventHandle

Errors:

Wraps cuIpcGetEventHandle.

func (Event) Query

func (e Event) Query() error

Query queries an event’s status.

Queries the status of all work currently captured by hEvent. See Event.Record for details on what is captured by an event. Returns Success if all captured work has been completed, or ErrNotReady if any captured work is incomplete. For the purposes of Unified Memory, a return value of Success is equivalent to having called Event.Synchronize.

See also: NewEvent, Event.Record, Event.Synchronize, Event.Close, Event.ElapsedTime, cudaEventQuery

Errors:

Wraps cuEventQuery.

func (Event) Record

func (e Event) Record(hStream Stream) error

Record records an event.

Captures in hEvent the contents of hStream at the time of this call. hEvent and hStream must be from the same context otherwise ErrInvalidHandle is returned. Calls such as Event.Query or Stream.WaitEvent will then examine or wait for completion of the work that was captured. Uses of hStream after this call do not modify hEvent. See note on default stream behavior for what is captured in the default case. Event.Record can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such as Stream.WaitEvent use the most recently captured state at the time of the API call, and are not affected by later calls to Event.Record. Before the first call to Event.Record, an event represents an empty set of work, so for example Event.Query would return Success.

Note: This function uses standard default stream semantics.

See also: NewEvent, Event.Query, Event.Synchronize, Stream.WaitEvent, Event.Close, Event.ElapsedTime, cudaEventRecord, Event.RecordWithFlags

  • hStream: Stream to record event for

Errors:

Wraps cuEventRecord.

func (Event) RecordWithFlags

func (e Event) RecordWithFlags(hStream Stream, flags EventRecordFlags) error

RecordWithFlags records an event.

Captures in hEvent the contents of hStream at the time of this call. hEvent and hStream must be from the same context otherwise ErrInvalidHandle is returned. Calls such as Event.Query or Stream.WaitEvent will then examine or wait for completion of the work that was captured. Uses of hStream after this call do not modify hEvent. See note on default stream behavior for what is captured in the default case. Event.RecordWithFlags can be called multiple times on the same event and will overwrite the previously captured state. Other APIs such as Stream.WaitEvent use the most recently captured state at the time of the API call, and are not affected by later calls to Event.RecordWithFlags. Before the first call to Event.RecordWithFlags, an event represents an empty set of work, so for example Event.Query would return Success. flags include:

  • EventRecordDefault: Default event creation flag.
  • EventRecordExternal: Event is captured in the graph as an external event node when performing stream capture. This flag is invalid outside of stream capture.

Note: This function uses standard default stream semantics.

See also: NewEvent, Event.Query, Event.Synchronize, Stream.WaitEvent, Event.Close, Event.ElapsedTime, Event.Record, cudaEventRecord

  • hStream: Stream to record event for
  • flags: See CUevent_capture_flags

Errors:

Wraps cuEventRecordWithFlags.

func (Event) Synchronize

func (e Event) Synchronize() error

Synchronize waits for an event to complete.

Waits until the completion of all work currently captured in hEvent. See Event.Record for details on what is captured by an event. Waiting for an event that was created with the EventBlockingSync flag will cause the calling CPU thread to block until the event has been completed by the device. If the EventBlockingSync flag has not been set, then the CPU thread will busy-wait until the event has been completed by the device.

See also: NewEvent, Event.Record, Event.Query, Event.Close, Event.ElapsedTime, cudaEventSynchronize

Errors:

Wraps cuEventSynchronize.

type EventFlags

type EventFlags uint32

EventFlags represents event creation flags.

const (
	EventDefault       EventFlags = 0x0 // Default event flag
	EventBlockingSync  EventFlags = 0x1 // Event uses blocking synchronization
	EventDisableTiming EventFlags = 0x2 // Event will not record timing data
	// EventInterprocess: Event is suitable for interprocess use. [EventDisableTiming] must be set
	EventInterprocess EventFlags = 0x4
)

func (EventFlags) String

func (e EventFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type EventRecordFlags

type EventRecordFlags int32

EventRecordFlags represents event record flags.

const (
	EventRecordDefault EventRecordFlags = 0x0 // Default event record flag
	// EventRecordExternal: When using stream capture, create an event record node instead of the default behavior. This flag is invalid when used outside of capture.
	EventRecordExternal EventRecordFlags = 0x1
)

func (EventRecordFlags) String

func (e EventRecordFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type EventRecordNode

type EventRecordNode struct {
	GraphNode
}

EventRecordNode is a GraphNode of the event record kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the EventRecordNode one takes the kind's own types.

func (EventRecordNode) Event

func (e EventRecordNode) Event() (Event, error)

Event returns the event associated with an event record node.

Returns the event of event record node hNode.

See also: Graph.AddEventRecordNode, EventRecordNode.SetEvent, EventWaitNode.Event, Event.RecordWithFlags, Stream.WaitEvent

Errors:

Wraps cuGraphEventRecordNodeGetEvent.

func (EventRecordNode) SetEvent

func (e EventRecordNode) SetEvent(event Event) error

SetEvent sets an event record node’s event.

Sets the event of event record node hNode to event.

Note: This function will reset the node’s context to the event’s device context.

See also: GraphNode.SetParams, Graph.AddEventRecordNode, EventRecordNode.Event, EventWaitNode.SetEvent, Event.RecordWithFlags, Stream.WaitEvent

  • event: Event to use

Errors:

Wraps cuGraphEventRecordNodeSetEvent.

type EventRecordNodeParams

type EventRecordNodeParams struct {
	// The event to record when the node executes
	Event          Event
	AnonymousUnion [1]uint64
}

EventRecordNodeParams represents event record node parameters.

func (*EventRecordNodeParams) Ctx

func (e *EventRecordNodeParams) Ctx() *Context

Ctx returns a pointer to the ctx member of CUDA_EVENT_RECORD_NODE_PARAMS, which shares its storage with every other member of the union.

func (*EventRecordNodeParams) GCtx

func (e *EventRecordNodeParams) GCtx() *GreenCtx

GCtx returns a pointer to the gCtx member of CUDA_EVENT_RECORD_NODE_PARAMS, which shares its storage with every other member of the union.

type EventSchedFlags

type EventSchedFlags int32

EventSchedFlags represents event sched flags.

const (
	EventSchedAuto         EventSchedFlags = 0x00 // Automatic scheduling
	EventSchedSpin         EventSchedFlags = 0x01 // Set spin as default scheduling
	EventSchedYield        EventSchedFlags = 0x02 // Set yield as default scheduling
	EventSchedBlockingSync EventSchedFlags = 0x04 // Set blocking synchronization as default scheduling
)

func (EventSchedFlags) String

func (e EventSchedFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type EventWaitFlags

type EventWaitFlags int32

EventWaitFlags represents event wait flags.

const (
	EventWaitDefault EventWaitFlags = 0x0 // Default event wait flag
	// EventWaitExternal: When using stream capture, create an event wait node instead of the default behavior. This flag is invalid when used outside of capture.
	EventWaitExternal EventWaitFlags = 0x1
)

func (EventWaitFlags) String

func (e EventWaitFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type EventWaitNode

type EventWaitNode struct {
	GraphNode
}

EventWaitNode is a GraphNode of the event wait kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the EventWaitNode one takes the kind's own types.

func (EventWaitNode) Event

func (e EventWaitNode) Event() (Event, error)

Event returns the event associated with an event wait node.

Returns the event of event wait node hNode.

See also: Graph.AddEventWaitNode, EventWaitNode.SetEvent, EventRecordNode.Event, Event.RecordWithFlags, Stream.WaitEvent

Errors:

Wraps cuGraphEventWaitNodeGetEvent.

func (EventWaitNode) SetEvent

func (e EventWaitNode) SetEvent(event Event) error

SetEvent sets an event wait node’s event.

Sets the event of event wait node hNode to event.

See also: GraphNode.SetParams, Graph.AddEventWaitNode, EventWaitNode.Event, EventRecordNode.SetEvent, Event.RecordWithFlags, Stream.WaitEvent

  • event: Event to use

Errors:

Wraps cuGraphEventWaitNodeSetEvent.

type EventWaitNodeParams

type EventWaitNodeParams struct {
	// The event to wait on from the node
	Event Event
}

EventWaitNodeParams represents event wait node parameters.

type ExecAffinityParam

type ExecAffinityParam struct {
	// Type of execution affinity.
	Type  ExecAffinityType
	Param [1]uint32
}

ExecAffinityParam represents execution Affinity Parameters.

func CtxGetExecAffinity

func CtxGetExecAffinity(type_ ExecAffinityType) (ExecAffinityParam, error)

CtxGetExecAffinity returns the execution affinity setting for the current context.

Returns the current value of type. The supported ExecAffinityType values are:

See also: ExecAffinityParam

  • type_: Execution affinity type to query

Errors:

Wraps cuCtxGetExecAffinity.

type ExecAffinityParamV1

type ExecAffinityParamV1 = ExecAffinityParam

ExecAffinityParamV1 is an alias for ExecAffinityParam.

type ExecAffinitySmCount

type ExecAffinitySmCount struct {
	// The number of SMs the context is limited to use.
	Val uint32
}

ExecAffinitySmCount represents value for ExecAffinityTypeSmCount.

type ExecAffinitySmCountV1

type ExecAffinitySmCountV1 = ExecAffinitySmCount

ExecAffinitySmCountV1 is an alias for ExecAffinitySmCount.

type ExecAffinityType

type ExecAffinityType int32

ExecAffinityType represents execution Affinity Types.

const (
	ExecAffinityTypeSmCount ExecAffinityType = 0 // Create a context with limited SMs.
)

func (ExecAffinityType) String

func (e ExecAffinityType) String() string

String returns the constant name, or a numeric representation for unknown values.

type ExtSemSignalNodeParams

type ExtSemSignalNodeParams struct {
	// Array of external semaphore handles.
	ExtSemArray uintptr
	// Array of external semaphore signal parameters.
	ParamsArray uintptr
	// Number of handles and parameters supplied in extSemArray and paramsArray.
	NumExtSems uint32
}

ExtSemSignalNodeParams represents semaphore signal node parameters.

type ExtSemSignalNodeParamsV1

type ExtSemSignalNodeParamsV1 = ExtSemSignalNodeParams

ExtSemSignalNodeParamsV1 is an alias for ExtSemSignalNodeParams.

type ExtSemSignalNodeParamsV2

type ExtSemSignalNodeParamsV2 struct {
	// Array of external semaphore handles.
	ExtSemArray uintptr
	// Array of external semaphore signal parameters.
	ParamsArray uintptr
	// Number of handles and parameters supplied in extSemArray and paramsArray.
	NumExtSems     uint32
	AnonymousUnion [1]uint64
}

ExtSemSignalNodeParamsV2 represents semaphore signal node parameters.

func (*ExtSemSignalNodeParamsV2) Ctx

Ctx returns a pointer to the ctx member of CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2, which shares its storage with every other member of the union.

func (*ExtSemSignalNodeParamsV2) GCtx

GCtx returns a pointer to the gCtx member of CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2, which shares its storage with every other member of the union.

type ExtSemWaitNodeParams

type ExtSemWaitNodeParams struct {
	// Array of external semaphore handles.
	ExtSemArray uintptr
	// Array of external semaphore wait parameters.
	ParamsArray uintptr
	// Number of handles and parameters supplied in extSemArray and paramsArray.
	NumExtSems uint32
}

ExtSemWaitNodeParams represents semaphore wait node parameters.

type ExtSemWaitNodeParamsV1

type ExtSemWaitNodeParamsV1 = ExtSemWaitNodeParams

ExtSemWaitNodeParamsV1 is an alias for ExtSemWaitNodeParams.

type ExtSemWaitNodeParamsV2

type ExtSemWaitNodeParamsV2 struct {
	// Array of external semaphore handles.
	ExtSemArray uintptr
	// Array of external semaphore wait parameters.
	ParamsArray uintptr
	// Number of handles and parameters supplied in extSemArray and paramsArray.
	NumExtSems     uint32
	AnonymousUnion [1]uint64
}

ExtSemWaitNodeParamsV2 represents semaphore wait node parameters.

func (*ExtSemWaitNodeParamsV2) Ctx

func (e *ExtSemWaitNodeParamsV2) Ctx() *Context

Ctx returns a pointer to the ctx member of CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2, which shares its storage with every other member of the union.

func (*ExtSemWaitNodeParamsV2) GCtx

func (e *ExtSemWaitNodeParamsV2) GCtx() *GreenCtx

GCtx returns a pointer to the gCtx member of CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2, which shares its storage with every other member of the union.

type Extent3D

type Extent3D struct {
	Width  uint
	Height uint
	Depth  uint
}

Extent3D represents width/height/depth of a Array in elements.

type Extent3DV1

type Extent3DV1 = Extent3D

Extent3DV1 is an alias for Extent3D.

type ExternalMemory

type ExternalMemory uintptr

ExternalMemory is CUDA external memory.

func ImportExternalMemory

func ImportExternalMemory(memHandleDesc *ExternalMemoryHandleDesc) (ExternalMemory, error)

ImportExternalMemory imports an external memory object.

Imports an externally allocated memory object and returns a handle to that. The properties of the handle being imported must be described in memHandleDesc.

ExternalMemoryHandleDesc.type specifies the type of handle being imported.

If ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeOpaqueFd, then ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeOpaqueWin32, then exactly one of ExternalMemoryHandleDesc.handle.win32.handle and ExternalMemoryHandleDesc.handle.win32.name must not be NULL. If ExternalMemoryHandleDesc.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. If ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeOpaqueWin32Kmt, then ExternalMemoryHandleDesc.handle.win32.handle must be non-NULL and ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeD3d12Heap, then exactly one of ExternalMemoryHandleDesc.handle.win32.handle and ExternalMemoryHandleDesc.handle.win32.name must not be NULL. If ExternalMemoryHandleDesc.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. If ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeD3d12Resource, then exactly one of ExternalMemoryHandleDesc.handle.win32.handle and ExternalMemoryHandleDesc.handle.win32.name must not be NULL. If ExternalMemoryHandleDesc.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. If ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeD3d11Resource, then ExternalMemoryHandleDesc.handle.win32.handle must represent a valid shared NT handle that is returned by IDXGIResource1.CreateSharedHandle when referring to a ID3D11Resource object. If ExternalMemoryHandleDesc.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 ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeD3d11ResourceKmt, then ExternalMemoryHandleDesc.handle.win32.handle must represent a valid shared KMT handle that is returned by IDXGIResource.GetSharedHandle when referring to a ID3D11Resource object and ExternalMemoryHandleDesc.handle.win32.name must be NULL. If ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeNvscibuf, then ExternalMemoryHandleDesc.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 use Stream.WaitExternalSemaphoresAsync or Stream.SignalExternalSemaphoresAsync as appropriate barriers to maintain coherence between CUDA and the other drivers. See CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC and CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC for memory synchronization. If ExternalMemoryHandleDesc.type is ExternalMemoryHandleTypeDmabufFd, then ExternalMemoryHandleDesc.handle.fd must be a valid file descriptor referencing a dma_buf object and ExternalMemoryHandleDesc.flags must be zero. Importing a dma_buf object is supported only on Tegra platform starting with Thor series. Mapping an imported dma_buf object as CUDA mipmapped array using ExternalMemory.MappedMipmappedArray is not supported. The size of the memory object must be specified in ExternalMemoryHandleDesc.size. Specifying the flag CUDA_EXTERNAL_MEMORY_DEDICATED in ExternalMemoryHandleDesc.flags 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 if ExternalMemoryHandleDesc.type is one of the following: ExternalMemoryHandleTypeD3d12Resource ExternalMemoryHandleTypeD3d11Resource ExternalMemoryHandleTypeD3d11ResourceKmt

Note: 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.

See also: ExternalMemory.Close, ExternalMemory.MappedBuffer, ExternalMemory.MappedMipmappedArray

  • memHandleDesc: Memory import handle descriptor

Errors:

Wraps cuImportExternalMemory.

func (*ExternalMemory) Close

func (e *ExternalMemory) Close() error

Close 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 DevicePtr.Free and MipmappedArray.Close respectively.

See also: ImportExternalMemory, ExternalMemory.MappedBuffer, ExternalMemory.MappedMipmappedArray

Errors:

If e is zero, Close returns nil. Otherwise Close sets e to zero when the call succeeds and leaves it unchanged when it fails. Only e is zeroed: a copy of it still refers to the released object.

Wraps cuDestroyExternalMemory.

func (ExternalMemory) MappedBuffer

func (e ExternalMemory) MappedBuffer(bufferDesc *ExternalMemoryBufferDesc) (DevicePtr, error)

MappedBuffer maps a buffer onto an imported memory object.

Maps a buffer onto an imported memory object and returns a device pointer. The properties of the buffer being mapped must be described in bufferDesc.

ExternalMemoryBufferDesc.offset is the offset in the memory object where the buffer’s base address is. ExternalMemoryBufferDesc.size is the size of the buffer. ExternalMemoryBufferDesc.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 DevicePtr.Free.

See also: ImportExternalMemory, ExternalMemory.Close, ExternalMemory.MappedMipmappedArray

  • bufferDesc: Buffer descriptor

Errors:

Wraps cuExternalMemoryGetMappedBuffer.

func (ExternalMemory) MappedMipmappedArray

func (e ExternalMemory) MappedMipmappedArray(mipmapDesc *ExternalMemoryMipmappedArrayDesc) (MipmappedArray, error)

MappedMipmappedArray 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. The properties of the CUDA mipmapped array being mapped must be described in mipmapDesc.

ExternalMemoryMipmappedArrayDesc.offset is the offset in the memory object where the base level of the mipmap chain is. ExternalMemoryMipmappedArrayDesc.arrayDesc describes the format, dimensions and type of the base level of the mipmap chain. For further details on these parameters, please refer to the documentation for NewMipmappedArray. Note that if the mipmapped array is bound as a color target in the graphics API, then the flag CUDA_ARRAY3D_COLOR_ATTACHMENT must be specified in ExternalMemoryMipmappedArrayDesc.arrayDesc.Flags. ExternalMemoryMipmappedArrayDesc.numLevels specifies the total number of levels in the mipmap chain. If extMem was imported from a handle of type ExternalMemoryHandleTypeNvscibuf, then ExternalMemoryMipmappedArrayDesc.numLevels must be equal to 1. Mapping extMem imported from a handle of type ExternalMemoryHandleTypeDmabufFd, is not supported. The returned CUDA mipmapped array must be freed using MipmappedArray.Close.

See also: ImportExternalMemory, ExternalMemory.Close, ExternalMemory.MappedBuffer

  • mipmapDesc: CUDA array descriptor

Errors:

Wraps cuExternalMemoryGetMappedMipmappedArray.

type ExternalMemoryBufferDesc

type ExternalMemoryBufferDesc struct {
	Offset   uint64
	Size     uint64
	Flags    uint32
	Reserved [16]uint32
}

ExternalMemoryBufferDesc represents external memory buffer descriptor.

type ExternalMemoryBufferDescV1

type ExternalMemoryBufferDescV1 = ExternalMemoryBufferDesc

ExternalMemoryBufferDescV1 is an alias for ExternalMemoryBufferDesc.

type ExternalMemoryHandleDesc

type ExternalMemoryHandleDesc struct {
	Type     ExternalMemoryHandleType
	Handle   [2]uint64
	Size     uint64
	Flags    uint32
	Reserved [16]uint32
}

ExternalMemoryHandleDesc represents external memory handle descriptor.

type ExternalMemoryHandleDescV1

type ExternalMemoryHandleDescV1 = ExternalMemoryHandleDesc

ExternalMemoryHandleDescV1 is an alias for ExternalMemoryHandleDesc.

type ExternalMemoryHandleType

type ExternalMemoryHandleType int32

ExternalMemoryHandleType represents external memory handle types.

const (
	ExternalMemoryHandleTypeOpaqueFd         ExternalMemoryHandleType = 1 // Handle is an opaque file descriptor
	ExternalMemoryHandleTypeOpaqueWin32      ExternalMemoryHandleType = 2 // Handle is an opaque shared NT handle
	ExternalMemoryHandleTypeOpaqueWin32Kmt   ExternalMemoryHandleType = 3 // Handle is an opaque, globally shared handle
	ExternalMemoryHandleTypeD3d12Heap        ExternalMemoryHandleType = 4 // Handle is a D3D12 heap object
	ExternalMemoryHandleTypeD3d12Resource    ExternalMemoryHandleType = 5 // Handle is a D3D12 committed resource
	ExternalMemoryHandleTypeD3d11Resource    ExternalMemoryHandleType = 6 // Handle is a shared NT handle to a D3D11 resource
	ExternalMemoryHandleTypeD3d11ResourceKmt ExternalMemoryHandleType = 7 // Handle is a globally shared handle to a D3D11 resource
	ExternalMemoryHandleTypeNvscibuf         ExternalMemoryHandleType = 8 // Handle is an NvSciBuf object
	ExternalMemoryHandleTypeDmabufFd         ExternalMemoryHandleType = 9
)

func (ExternalMemoryHandleType) String

func (e ExternalMemoryHandleType) String() string

String returns the constant name, or a numeric representation for unknown values.

type ExternalMemoryMipmappedArrayDesc

type ExternalMemoryMipmappedArrayDesc struct {
	Offset    uint64
	ArrayDesc Array3dDescriptor
	NumLevels uint32
	Reserved  [16]uint32
}

ExternalMemoryMipmappedArrayDesc represents external memory mipmap descriptor.

type ExternalMemoryMipmappedArrayDescV1

type ExternalMemoryMipmappedArrayDescV1 = ExternalMemoryMipmappedArrayDesc

ExternalMemoryMipmappedArrayDescV1 is an alias for ExternalMemoryMipmappedArrayDesc.

type ExternalSemaphore

type ExternalSemaphore uintptr

ExternalSemaphore is CUDA external semaphore.

func ImportExternalSemaphore

func ImportExternalSemaphore(semHandleDesc *ExternalSemaphoreHandleDesc) (ExternalSemaphore, error)

ImportExternalSemaphore imports an external semaphore.

Imports an externally allocated synchronization object and returns a handle to that. The properties of the handle being imported must be described in semHandleDesc.

ExternalSemaphoreHandleDesc.type specifies the type of handle being imported.

If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeOpaqueFd, then ExternalSemaphoreHandleDesc.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 ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeOpaqueWin32, then exactly one of ExternalSemaphoreHandleDesc.handle.win32.handle and ExternalSemaphoreHandleDesc.handle.win32.name must not be NULL. If ExternalSemaphoreHandleDesc.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. If ExternalSemaphoreHandleDesc.handle.win32.name is not NULL, then it must name a valid synchronization object. If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeOpaqueWin32Kmt, then ExternalSemaphoreHandleDesc.handle.win32.handle must be non-NULL and ExternalSemaphoreHandleDesc.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 ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeD3d12Fence, then exactly one of ExternalSemaphoreHandleDesc.handle.win32.handle and ExternalSemaphoreHandleDesc.handle.win32.name must not be NULL. If ExternalSemaphoreHandleDesc.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. If ExternalSemaphoreHandleDesc.handle.win32.name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D12Fence object. If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeD3d11Fence, then ExternalSemaphoreHandleDesc.handle.win32.handle represents a valid shared NT handle that is returned by ID3D11Fence.CreateSharedHandle. If ExternalSemaphoreHandleDesc.handle.win32.name is not NULL, then it must name a valid synchronization object that refers to a valid ID3D11Fence object. If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeNvscisync, then ExternalSemaphoreHandleDesc.handle.nvSciSyncObj represents a valid NvSciSyncObj. ExternalSemaphoreHandleTypeD3d11KeyedMutex, then ExternalSemaphoreHandleDesc.handle.win32.handle represents a valid shared NT handle that is returned by IDXGIResource1.CreateSharedHandle when referring to a IDXGIKeyedMutex object. If ExternalSemaphoreHandleDesc.handle.win32.name is not NULL, then it must name a valid synchronization object that refers to a valid IDXGIKeyedMutex object. If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeD3d11KeyedMutexKmt, then ExternalSemaphoreHandleDesc.handle.win32.handle represents a valid shared KMT handle that is returned by IDXGIResource.GetSharedHandle when referring to a IDXGIKeyedMutex object and ExternalSemaphoreHandleDesc.handle.win32.name must be NULL. If ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeTimelineSemaphoreFd, then ExternalSemaphoreHandleDesc.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 ExternalSemaphoreHandleDesc.type is ExternalSemaphoreHandleTypeTimelineSemaphoreWin32, then exactly one of ExternalSemaphoreHandleDesc.handle.win32.handle and ExternalSemaphoreHandleDesc.handle.win32.name must not be NULL. If ExternalSemaphoreHandleDesc.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. If ExternalSemaphoreHandleDesc.handle.win32.name is not NULL, then it must name a valid synchronization object.

See also: ExternalSemaphore.Close, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

  • semHandleDesc: Semaphore import handle descriptor

Errors:

Wraps cuImportExternalSemaphore.

func (*ExternalSemaphore) Close

func (e *ExternalSemaphore) Close() error

Close 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.

See also: ImportExternalSemaphore, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

Errors:

If e is zero, Close returns nil. Otherwise Close sets e to zero when the call succeeds and leaves it unchanged when it fails. Only e is zeroed: a copy of it still refers to the released object.

Wraps cuDestroyExternalSemaphore.

type ExternalSemaphoreHandleDesc

type ExternalSemaphoreHandleDesc struct {
	Type     ExternalSemaphoreHandleType
	Handle   [2]uint64
	Flags    uint32
	Reserved [16]uint32
}

ExternalSemaphoreHandleDesc represents external semaphore handle descriptor.

type ExternalSemaphoreHandleDescV1

type ExternalSemaphoreHandleDescV1 = ExternalSemaphoreHandleDesc

ExternalSemaphoreHandleDescV1 is an alias for ExternalSemaphoreHandleDesc.

type ExternalSemaphoreHandleType

type ExternalSemaphoreHandleType int32

ExternalSemaphoreHandleType represents external semaphore handle types.

const (
	ExternalSemaphoreHandleTypeOpaqueFd       ExternalSemaphoreHandleType = 1 // Handle is an opaque file descriptor
	ExternalSemaphoreHandleTypeOpaqueWin32    ExternalSemaphoreHandleType = 2 // Handle is an opaque shared NT handle
	ExternalSemaphoreHandleTypeOpaqueWin32Kmt ExternalSemaphoreHandleType = 3 // Handle is an opaque, globally shared handle
	// ExternalSemaphoreHandleTypeD3d12Fence: Handle is a shared NT handle referencing a D3D12 fence object
	ExternalSemaphoreHandleTypeD3d12Fence ExternalSemaphoreHandleType = 4
	// ExternalSemaphoreHandleTypeD3d11Fence: Handle is a shared NT handle referencing a D3D11 fence object
	ExternalSemaphoreHandleTypeD3d11Fence ExternalSemaphoreHandleType = 5
	ExternalSemaphoreHandleTypeNvscisync  ExternalSemaphoreHandleType = 6 // Opaque handle to NvSciSync Object
	// ExternalSemaphoreHandleTypeD3d11KeyedMutex: Handle is a shared NT handle referencing a D3D11 keyed mutex object
	ExternalSemaphoreHandleTypeD3d11KeyedMutex ExternalSemaphoreHandleType = 7
	// ExternalSemaphoreHandleTypeD3d11KeyedMutexKmt: Handle is a globally shared handle referencing a D3D11 keyed mutex object
	ExternalSemaphoreHandleTypeD3d11KeyedMutexKmt ExternalSemaphoreHandleType = 8
	// ExternalSemaphoreHandleTypeTimelineSemaphoreFd: Handle is an opaque file descriptor referencing a timeline semaphore
	ExternalSemaphoreHandleTypeTimelineSemaphoreFd    ExternalSemaphoreHandleType = 9
	ExternalSemaphoreHandleTypeTimelineSemaphoreWin32 ExternalSemaphoreHandleType = 10
)

func (ExternalSemaphoreHandleType) String

String returns the constant name, or a numeric representation for unknown values.

type ExternalSemaphoreSignalParams

type ExternalSemaphoreSignalParams struct {
	Params   [9]uint64
	Flags    uint32
	Reserved [16]uint32
}

ExternalSemaphoreSignalParams represents external semaphore signal parameters.

type ExternalSemaphoreSignalParamsV1

type ExternalSemaphoreSignalParamsV1 = ExternalSemaphoreSignalParams

ExternalSemaphoreSignalParamsV1 is an alias for ExternalSemaphoreSignalParams.

type ExternalSemaphoreWaitParams

type ExternalSemaphoreWaitParams struct {
	Params   [9]uint64
	Flags    uint32
	Reserved [16]uint32
}

ExternalSemaphoreWaitParams represents external semaphore wait parameters.

type ExternalSemaphoreWaitParamsV1

type ExternalSemaphoreWaitParamsV1 = ExternalSemaphoreWaitParams

ExternalSemaphoreWaitParamsV1 is an alias for ExternalSemaphoreWaitParams.

type ExternalSemaphoresSignalNode

type ExternalSemaphoresSignalNode struct {
	GraphNode
}

ExternalSemaphoresSignalNode is a GraphNode of the external semaphores signal kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the ExternalSemaphoresSignalNode one takes the kind's own types.

func (ExternalSemaphoresSignalNode) Params

Params returns an external semaphore signal node’s parameters.

Returns the parameters of an external semaphore signal node hNode. The extSemArray and paramsArray returned, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use ExternalSemaphoresSignalNode.SetParams to update the parameters of this node.

See also: GraphNode.Params, Function.LaunchKernel, Graph.AddExternalSemaphoresSignalNode, ExternalSemaphoresSignalNode.SetParams, Graph.AddExternalSemaphoresWaitNode, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

Errors:

Wraps cuGraphExternalSemaphoresSignalNodeGetParams.

func (ExternalSemaphoresSignalNode) SetParams

SetParams sets an external semaphore signal node’s parameters.

Sets the parameters of an external semaphore signal node hNode to nodeParams.

See also: GraphNode.SetParams, Graph.AddExternalSemaphoresSignalNode, ExternalSemaphoresSignalNode.SetParams, Graph.AddExternalSemaphoresWaitNode, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphExternalSemaphoresSignalNodeSetParams.

type ExternalSemaphoresWaitNode

type ExternalSemaphoresWaitNode struct {
	GraphNode
}

ExternalSemaphoresWaitNode is a GraphNode of the external semaphores wait kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the ExternalSemaphoresWaitNode one takes the kind's own types.

func (ExternalSemaphoresWaitNode) Params

Params returns an external semaphore wait node’s parameters.

Returns the parameters of an external semaphore wait node hNode. The extSemArray and paramsArray returned, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use ExternalSemaphoresSignalNode.SetParams to update the parameters of this node.

See also: GraphNode.Params, Function.LaunchKernel, Graph.AddExternalSemaphoresWaitNode, ExternalSemaphoresWaitNode.SetParams, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

Errors:

Wraps cuGraphExternalSemaphoresWaitNodeGetParams.

func (ExternalSemaphoresWaitNode) SetParams

func (e ExternalSemaphoresWaitNode) SetParams(nodeParams *ExtSemWaitNodeParams) error

SetParams sets an external semaphore wait node’s parameters.

Sets the parameters of an external semaphore wait node hNode to nodeParams.

See also: GraphNode.SetParams, Graph.AddExternalSemaphoresWaitNode, ExternalSemaphoresWaitNode.SetParams, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphExternalSemaphoresWaitNodeSetParams.

type FabricCopyBatchOp

type FabricCopyBatchOp struct {
	// Source copy operand.
	Src FabricCpyOperand
	// Destination copy operand.
	Dst FabricCpyOperand
	// Size in bytes. Zero makes this operation a no-op.
	Size uint
	// Additional flags for fabric copy. Must be 0.
	Flags uint32
}

FabricCopyBatchOp represents a single copy operation for use with Stream.FabricCpyBatchAsync.

type FabricCopyBatchOpV1

type FabricCopyBatchOpV1 = FabricCopyBatchOp

FabricCopyBatchOpV1 is an alias for FabricCopyBatchOp.

type FabricCpyBatchNodeParams

type FabricCpyBatchNodeParams struct {
	NumOps         uint
	OpList         uintptr
	Flags          uint64
	AnonymousUnion [1]uint64
}

FabricCpyBatchNodeParams represents CUDA fabric copy batch node parameters.

The application must keep every logical endpoint ID referenced by opList valid and bound for as long as a graph or executable graph may use the node. Fabric copy batch nodes are not supported in device-launched graphs or conditional nodes.

func (*FabricCpyBatchNodeParams) Ctx

Ctx returns a pointer to the ctx member of CUDA_FABRIC_CPY_BATCH_NODE_PARAMS_V1, which shares its storage with every other member of the union.

func (*FabricCpyBatchNodeParams) GCtx

GCtx returns a pointer to the gCtx member of CUDA_FABRIC_CPY_BATCH_NODE_PARAMS_V1, which shares its storage with every other member of the union.

type FabricCpyBatchNodeParamsV1

type FabricCpyBatchNodeParamsV1 = FabricCpyBatchNodeParams

FabricCpyBatchNodeParamsV1 is an alias for FabricCpyBatchNodeParams.

type FabricCpyOperand

type FabricCpyOperand struct {
	Type FabricCpyOperandType
	Op   [2]uint64
}

FabricCpyOperand represents an operand for copy with Stream.FabricCpyBatchAsync.

type FabricCpyOperandType

type FabricCpyOperandType int32

FabricCpyOperandType represents flags that allow applications to convey the operand type for individual copies specified in Stream.FabricCpyBatchAsync.

const (
	FabricCopyOperandTypePointer         FabricCpyOperandType = 0x1 // Copy operand is a valid pointer.
	FabricCopyOperandTypeLogicalEndpoint FabricCpyOperandType = 0x2 // Copy operand is a logical endpoint.
)

func (FabricCpyOperandType) String

func (e FabricCpyOperandType) String() string

String returns the constant name, or a numeric representation for unknown values.

type FilterMode

type FilterMode int32

FilterMode represents texture reference filtering modes.

const (
	TrFilterModePoint  FilterMode = 0 // Point filter mode
	TrFilterModeLinear FilterMode = 1 // Linear filter mode
)

func (FilterMode) String

func (e FilterMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type FlushGPUDirectRDMAWritesOptions

type FlushGPUDirectRDMAWritesOptions int32

FlushGPUDirectRDMAWritesOptions represents bitmasks for DevAttrGpuDirectRdmaFlushWritesOptions.

const (
	// FlushGpuDirectRdmaWritesOptionHost: [FlushGPUDirectRDMAWrites] and its CUDA Runtime API counterpart are supported on the device.
	FlushGpuDirectRdmaWritesOptionHost FlushGPUDirectRDMAWritesOptions = 1 << 0
	// FlushGpuDirectRdmaWritesOptionMemops: The [StreamWaitValueFlush] flag and the [StreamMemOpFlushRemoteWrites] MemOp are supported on the device.
	FlushGpuDirectRdmaWritesOptionMemops FlushGPUDirectRDMAWritesOptions = 1 << 1
)

func (FlushGPUDirectRDMAWritesOptions) String

String returns the constant name, or a numeric representation for unknown values.

type FlushGPUDirectRDMAWritesScope

type FlushGPUDirectRDMAWritesScope int32

FlushGPUDirectRDMAWritesScope represents the scopes for FlushGPUDirectRDMAWrites.

const (
	// FlushGpuDirectRdmaWritesToOwner: Blocks until remote writes are visible to the CUDA device context owning the data.
	FlushGpuDirectRdmaWritesToOwner FlushGPUDirectRDMAWritesScope = 100
	// FlushGpuDirectRdmaWritesToAllDevices: Blocks until remote writes are visible to all CUDA device contexts.
	FlushGpuDirectRdmaWritesToAllDevices FlushGPUDirectRDMAWritesScope = 200
)

func (FlushGPUDirectRDMAWritesScope) String

String returns the constant name, or a numeric representation for unknown values.

type FlushGPUDirectRDMAWritesTarget

type FlushGPUDirectRDMAWritesTarget int32

FlushGPUDirectRDMAWritesTarget represents the targets for FlushGPUDirectRDMAWrites.

const (
	// FlushGpuDirectRdmaWritesTargetCurrentCtx: Sets the target for [FlushGPUDirectRDMAWrites] to the currently active CUDA device context.
	FlushGpuDirectRdmaWritesTargetCurrentCtx FlushGPUDirectRDMAWritesTarget = 0
)

func (FlushGPUDirectRDMAWritesTarget) String

String returns the constant name, or a numeric representation for unknown values.

type FuncCacheConfig

type FuncCacheConfig int32

FuncCacheConfig represents function cache configurations.

const (
	FuncCachePreferNone   FuncCacheConfig = 0x00 // no preference for shared memory or L1 (default)
	FuncCachePreferShared FuncCacheConfig = 0x01 // prefer larger shared memory and smaller L1 cache
	FuncCachePreferL1     FuncCacheConfig = 0x02 // prefer larger L1 cache and smaller shared memory
	FuncCachePreferEqual  FuncCacheConfig = 0x03 // prefer equal sized L1 cache and shared memory
)

func CtxGetCacheConfig

func CtxGetCacheConfig() (FuncCacheConfig, error)

CtxGetCacheConfig returns the preferred cache configuration for the current context.

On devices where the L1 cache and shared memory use the same hardware resources, this function returns through pconfig the preferred cache configuration for the current context. This is only a preference. The driver 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 pconfig of FuncCachePreferNone on devices where the size of the L1 cache and shared memory are fixed. The supported cache configurations are:

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetCacheConfig, CtxSetLimit, CtxSynchronize, Function.SetCacheConfig, cudaDeviceGetCacheConfig

Errors:

Wraps cuCtxGetCacheConfig.

func (FuncCacheConfig) String

func (e FuncCacheConfig) String() string

String returns the constant name, or a numeric representation for unknown values.

type Function

type Function uintptr

Function is an opaque handle to a CUDA kernel function within a module. Obtained via Module.Function and used with Function.LaunchKernel.

func (Function) Attribute

func (f Function) Attribute(attrib FunctionAttribute) (int32, error)

Attribute returns information about a function.

Returns the integer value of the attribute attrib on the kernel given by hfunc. The supported attributes are:

  • FuncAttributeMaxThreadsPerBlock: The maximum number of threads per block, beyond which a launch of the function would fail. This number depends on both the function and the device on which the function is currently loaded.
  • FuncAttributeSharedSizeBytes: The size in bytes of statically-allocated shared memory per block required by this function. This does not include dynamically-allocated shared memory requested by the user at runtime.
  • FuncAttributeConstSizeBytes: The size in bytes of user-allocated constant memory required by this function.
  • FuncAttributeLocalSizeBytes: The size in bytes of local memory used by each thread of this function.
  • FuncAttributeNumRegs: The number of registers used by each thread of this function.
  • FuncAttributePtxVersion: The PTX virtual architecture version for which the function was compiled. This value is the major PTX version * 10 + the minor PTX version, so a PTX version 1.3 function would return the value 13. Note that this may return the undefined value of 0 for cubins compiled prior to CUDA 3.0.
  • FuncAttributeBinaryVersion: The binary architecture version for which the function was compiled. This value is the major binary version * 10 + the minor binary version, so a binary version 1.3 function would return the value 13. Note that this will return a value of 10 for legacy cubins that do not have a properly-encoded binary architecture version.
  • CU_FUNC_CACHE_MODE_CA: The attribute to indicate whether the function has been compiled with user specified option “-Xptxas –dlcm=ca” set .
  • FuncAttributeMaxDynamicSharedSizeBytes: The maximum size in bytes of dynamically-allocated shared memory.
  • FuncAttributePreferredSharedMemoryCarveout: Preferred shared memory-L1 cache split ratio in percent of total shared memory.
  • FuncAttributeClusterSizeMustBeSet: If this attribute is set, the kernel must launch with a valid cluster size specified.
  • FuncAttributeRequiredClusterWidth: The required cluster width in blocks.
  • FuncAttributeRequiredClusterHeight: The required cluster height in blocks.
  • FuncAttributeRequiredClusterDepth: The required cluster depth in blocks.
  • FuncAttributeNonPortableClusterSizeAllowed: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. A non-portable cluster size may only function on the specific SKUs the program is tested on. The launch might fail if the program is run on a different hardware platform. CUDA API provides cudaOccupancyMaxActiveClusters to assist with checking whether the desired size can be launched on the current device. A portable cluster size is guaranteed to be functional on all compute capabilities higher than the target compute capability. The portable cluster size for sm_90 is 8 blocks per cluster. This value may increase for future compute capabilities. The specific hardware unit may support higher cluster sizes that’s not guaranteed to be portable.
  • FuncAttributeClusterSchedulingPolicyPreference: The block scheduling policy of a function. The value type is ClusterSchedulingPolicy.
  • FuncAttributeSharedMemoryMode: The shared memory mode of a function. The value type is SharedMemoryMode / cudaSharedMemoryMode.

With a few execeptions, function attributes may also be queried on unloaded function handles returned from Module.EnumerateFunctions. ErrFunctionNotLoaded is returned if the attribute requires a fully loaded function but the function is not loaded. The loading state of a function may be queried using cuFuncIsloaded. Function.Load may be called to explicitly load a function before querying the following attributes that require the function to be loaded:

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.LaunchKernel, cudaFuncGetAttributes, cudaFuncSetAttribute, Function.IsLoaded, Function.Load, Kernel.Attribute

  • attrib: Attribute requested

Errors:

Wraps cuFuncGetAttribute.

func (Function) AvailableDynamicSMemPerBlock

func (f Function) AvailableDynamicSMemPerBlock(numBlocks int32, blockSize int32) (uint, error)

AvailableDynamicSMemPerBlock returns dynamic shared memory available per block when launching numBlocks blocks on SM.

Returns the maximum size of dynamic shared memory to allow numBlocks blocks per SM. Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will be the current context.

  • numBlocks: Number of blocks to fit on SM
  • blockSize: Size of the blocks

Errors:

Wraps cuOccupancyAvailableDynamicSMemPerBlock.

func (Function) IsLoaded

func (f Function) IsLoaded() (FunctionLoadingState, error)

IsLoaded returns if the function is loaded.

Returns the loading state of function.

See also: Function.Load, Module.EnumerateFunctions

Requires CUDA 12.4 (driver r550) or later; see HasFuncIsLoaded.

Errors:

Wraps cuFuncIsLoaded.

func (Function) Launch deprecated

func (f Function) Launch() error

Launch launches a CUDA function.

Invokes the kernel f on a 1 x 1 x 1 grid of blocks. The block contains the number of threads specified by a previous call to Function.SetBlockShape. The block shape, dynamic shared memory size, and parameter information must be set using Function.SetBlockShape, Function.SetSharedSize, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, and Function.ParamSetv prior to calling this function. Launching a function via Function.LaunchKernel invalidates the function’s block shape, dynamic shared memory size, and parameter information. After launching via Function.LaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSetf, Function.ParamSeti, Function.ParamSetv, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

Errors:

Wraps cuLaunch.

Deprecated: Deprecated by NVIDIA.

func (Function) LaunchCooperativeKernel

func (f Function) LaunchCooperativeKernel(gridDim Dim3, blockDim Dim3, sharedMemBytes uint32, hStream Stream, kernelParams []unsafe.Pointer) error

LaunchCooperativeKernel launches a CUDA function Function or a CUDA kernel Kernel where thread blocks can cooperate and synchronize as they execute.

Invokes the function Function or the kernel Kernel f on a gridDimX x gridDimY x gridDimZ grid of blocks. Each block contains blockDimX x blockDimY x blockDimZ threads. sharedMemBytes sets the amount of dynamic shared memory that will be available to each thread block. The device on which this kernel is invoked must have a non-zero value for the device attribute DevAttrCooperativeLaunch. The total number of blocks launched cannot exceed the maximum number of blocks per multiprocessor as returned by Function.MaxActiveBlocksPerMultiprocessor (or Function.MaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors as specified by the device attribute DevAttrMultiprocessorCount. The kernel cannot make use of CUDA dynamic parallelism. Kernel parameters must be specified via kernelParams. If f has N parameters, then kernelParams needs to be an array of N pointers. Each of kernelParams[0] through kernelParams[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel’s image. Calling Function.LaunchCooperativeKernel sets persistent function state that is the same as function state set through Function.LaunchKernel API When the kernel f is launched via Function.LaunchCooperativeKernel, the previous block shape, shared size and parameter info associated with f is overwritten. Note that to use Function.LaunchCooperativeKernel, the kernel f must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then Function.LaunchCooperativeKernel will return ErrInvalidImage. Note that the API can also be used to launch context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to launch the kernel on will either be taken from the specified stream hStream or the current context in case of NULL stream.

Note: This function uses standard default stream semantics.

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.Attribute, LaunchCooperativeKernelMultiDevice, cudaLaunchCooperativeKernel, Library.Kernel, Kernel.SetCacheConfig, Kernel.Attribute, Kernel.SetAttribute

  • gridDim.X: Width of grid in blocks
  • gridDim.Y: Height of grid in blocks
  • gridDim.Z: Depth of grid in blocks
  • blockDim.X: X dimension of each thread block
  • blockDim.Y: Y dimension of each thread block
  • blockDim.Z: Z dimension of each thread block
  • sharedMemBytes: Dynamic shared-memory size per thread block in bytes
  • hStream: Stream identifier
  • kernelParams: Array of pointers to kernel parameters

Errors:

Wraps cuLaunchCooperativeKernel.

func (Function) LaunchGrid deprecated

func (f Function) LaunchGrid(gridWidth int32, gridHeight int32) error

LaunchGrid launches a CUDA function.

Invokes the kernel f on a gridWidth x gridHeight grid of blocks. Each block contains the number of threads specified by a previous call to Function.SetBlockShape. The block shape, dynamic shared memory size, and parameter information must be set using Function.SetBlockShape, Function.SetSharedSize, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, and Function.ParamSetv prior to calling this function. Launching a function via Function.LaunchKernel invalidates the function’s block shape, dynamic shared memory size, and parameter information. After launching via Function.LaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSetf, Function.ParamSeti, Function.ParamSetv, Function.Launch, Function.LaunchGridAsync, Function.LaunchKernel

  • gridWidth: Width of grid in blocks
  • gridHeight: Height of grid in blocks

Errors:

Wraps cuLaunchGrid.

Deprecated: Deprecated by NVIDIA.

func (Function) LaunchGridAsync deprecated

func (f Function) LaunchGridAsync(gridWidth int32, gridHeight int32, hStream Stream) error

LaunchGridAsync launches a CUDA function.

Invokes the kernel f on a gridWidth x gridHeight grid of blocks. Each block contains the number of threads specified by a previous call to Function.SetBlockShape. The block shape, dynamic shared memory size, and parameter information must be set using Function.SetBlockShape, Function.SetSharedSize, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, and Function.ParamSetv prior to calling this function. Launching a function via Function.LaunchKernel invalidates the function’s block shape, dynamic shared memory size, and parameter information. After launching via Function.LaunchKernel, this state must be re-initialized prior to calling this function. Failure to do so results in undefined behavior.

Note: In certain cases where cubins are created with no ABI (i.e., using ptxas --abi-compile no), this function may serialize kernel launches. The CUDA driver retains asynchronous behavior by growing the per-thread stack as needed per launch and not shrinking it afterwards.

Note: This function uses standard default stream semantics.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSetf, Function.ParamSeti, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchKernel

  • gridWidth: Width of grid in blocks
  • gridHeight: Height of grid in blocks
  • hStream: Stream identifier

Errors:

Wraps cuLaunchGridAsync.

Deprecated: Deprecated by NVIDIA.

func (Function) LaunchKernel

func (f Function) LaunchKernel(gridDim Dim3, blockDim Dim3, sharedMemBytes uint32, hStream Stream, kernelParams []unsafe.Pointer) error

LaunchKernel launches a CUDA function Function or a CUDA kernel Kernel.

Invokes the function Function or the kernel Kernel f on a gridDimX x gridDimY x gridDimZ grid of blocks. Each block contains blockDimX x blockDimY x blockDimZ threads. sharedMemBytes sets the amount of dynamic shared memory that will be available to each thread block. Kernel parameters to f can be specified in one of two ways:

  • Kernel parameters can be specified via kernelParams. If f has N parameters, then kernelParams needs to be an array of N pointers. Each of kernelParams[0] through kernelParams[N-1] must point to a region of memory from which the actual kernel parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel’s image.
  • Kernel parameters can also be packaged by the application into a single buffer that is passed in via the extra parameter. This places the burden on the application of knowing each kernel parameter’s size and alignment/padding within the buffer.

The extra parameter exists to allow Function.LaunchKernel to take additional less commonly used arguments. extra specifies a list of names of extra settings and their corresponding values. Each extra setting name is immediately followed by the corresponding value. The list must be terminated with either NULL or CU_LAUNCH_PARAM_END.

  • CU_LAUNCH_PARAM_END, which indicates the end of the extra array;
  • CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next value in extra will be a pointer to a buffer containing all the kernel parameters for launching kernel f;
  • CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next value in extra will be a pointer to a size_t containing the size of the buffer specified with CU_LAUNCH_PARAM_BUFFER_POINTER;

The error ErrInvalidValue will be returned if kernel parameters are specified with both kernelParams and extra (i.e. both kernelParams and extra are non-NULL). Calling Function.LaunchKernel invalidates the persistent function state set through the following deprecated APIs: Function.SetBlockShape, Function.SetSharedSize, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, Function.ParamSetv. Note that to use Function.LaunchKernel, the kernel f must either have been compiled with toolchain version 3.2 or later so that it will contain kernel parameter information, or have no kernel parameters. If either of these conditions is not met, then Function.LaunchKernel will return ErrInvalidImage. Note that the API can also be used to launch context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to launch the kernel on will either be taken from the specified stream hStream or the current context in case of NULL stream.

Note: This function uses standard default stream semantics.

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.Attribute, cudaLaunchKernel, Library.Kernel, Kernel.SetCacheConfig, Kernel.Attribute, Kernel.SetAttribute

  • gridDim.X: Width of grid in blocks
  • gridDim.Y: Height of grid in blocks
  • gridDim.Z: Depth of grid in blocks
  • blockDim.X: X dimension of each thread block
  • blockDim.Y: Y dimension of each thread block
  • blockDim.Z: Z dimension of each thread block
  • sharedMemBytes: Dynamic shared-memory size per thread block in bytes
  • hStream: Stream identifier
  • kernelParams: Array of pointers to kernel parameters

Errors:

Wraps cuLaunchKernel.

Example

ExampleFunction_LaunchKernel loads a module and launches

extern "C" __global__ void scale(float *x, float a, int n)

over n elements. Each kernel parameter is a pointer to the argument's value, in declaration order. It needs a current CUDA context.

package main

import (
	"fmt"
	"unsafe"

	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	var image []byte // PTX or cubin, e.g. compiled with the nvrtc package

	mod, err := driver.ModuleLoadData(image)
	if err != nil {
		fmt.Println("load module:", err)
		return
	}
	defer mod.Close()
	scale, err := mod.Function("scale")
	if err != nil {
		fmt.Println("function:", err)
		return
	}

	const n, block = 1 << 20, 256
	x, err := driver.MemAllocBytes(n * 4)
	if err != nil {
		fmt.Println("alloc:", err)
		return
	}
	defer x.Free()

	a, count := float32(2), int32(n)
	params := []unsafe.Pointer{unsafe.Pointer(&x), unsafe.Pointer(&a), unsafe.Pointer(&count)}
	err = scale.LaunchKernel(driver.Dims((n+block-1)/block, 1, 1), driver.Dims(block, 1, 1), 0, 0, params)
	if err != nil {
		fmt.Println("launch:", err)
		return
	}
	if err := driver.CtxSynchronize(); err != nil {
		fmt.Println("synchronize:", err)
	}
}

func (Function) LaunchKernelEx

func (f Function) LaunchKernelEx(config *LaunchConfig, kernelParams []unsafe.Pointer) error

LaunchKernelEx launches a CUDA function Function or a CUDA kernel Kernel with launch-time configuration.

Invokes the function Function or the kernel Kernel f with the specified launch-time configuration config.

  • LaunchConfig.gridDimX is the width of the grid in blocks.
  • LaunchConfig.gridDimY is the height of the grid in blocks.
  • LaunchConfig.gridDimZ is the depth of the grid in blocks.
  • LaunchConfig.blockDimX is the X dimension of each thread block.
  • LaunchConfig.blockDimX is the Y dimension of each thread block.
  • LaunchConfig.blockDimZ is the Z dimension of each thread block.
  • LaunchConfig.sharedMemBytes is the dynamic shared-memory size per thread block in bytes.
  • LaunchConfig.hStream is the handle to the stream to perform the launch in. The CUDA context associated with this stream must match that associated with function f.
  • LaunchConfig.attrs is an array of LaunchConfig.numAttrs continguous LaunchAttribute elements. The value of this pointer is not considered if LaunchConfig.numAttrs is zero. However, in that case, it is recommended to set the pointer to NULL.
  • LaunchConfig.numAttrs is the number of attributes populating the first LaunchConfig.numAttrs positions of the LaunchConfig.attrs array.

Launch-time configuration is specified by adding entries to LaunchConfig.attrs. Each entry is an attribute ID and a corresponding attribute value.

Setting LaunchAttributeCooperative to a non-zero value causes the kernel launch to be a cooperative launch, with exactly the same usage and semantics of Function.LaunchCooperativeKernel. Setting LaunchAttributeProgrammaticStreamSerialization to a non-zero values causes the kernel to use programmatic means to resolve its stream dependency — enabling the CUDA runtime to opportunistically allow the grid’s execution to overlap with the previous kernel in the stream, if that kernel requests the overlap. LaunchAttributeProgrammaticEvent records an event along with the kernel launch. Event recorded through this launch attribute is guaranteed to only trigger after all block in the associated kernel trigger the event. A block can trigger the event through PTX launchdep.release or CUDA builtin function cudaTriggerProgrammaticLaunchCompletion(). A trigger can also be inserted at the beginning of each block’s execution if triggerAtBlockStart is set to non-0. Note that dependents (including the CPU thread calling Event.Synchronize) are not guaranteed to observe the release precisely when it is released. For example, Event.Synchronize may only observe the event trigger long after the associated kernel has completed. This recording type is primarily meant for establishing programmatic dependency between device tasks. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. created with EventDisableTiming flag set). LaunchAttributeLaunchCompletionEvent records an event along with the kernel launch. Nominally, the event is triggered once all blocks of the kernel have begun execution. Currently this is a best effort. If a kernel B has a launch completion dependency on a kernel A, B may wait until A is complete. Alternatively, blocks of B may begin before all blocks of A have begun, for example:

  • If B can claim execution resources unavailable to A, for example if they run on different GPUs.
  • If B is a higher priority than A.

Exercise caution if such an ordering inversion could lead to deadlock. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. must be created with the EventDisableTiming flag set). Setting LaunchAttributeDeviceUpdatableKernelNode to 1 on a captured launch causes the resulting kernel node to be device-updatable. This attribute is specific to graphs, and passing it to a launch in a non-capturing stream results in an error. Passing a value other than 0 or 1 is not allowed. On success, a handle will be returned via LaunchAttributeValue.deviceUpdatableKernelNode.devNode which can be passed to the various device-side update functions to update the node’s kernel parameters from within another kernel. For more information on the types of device updates that can be made, as well as the relevant limitations thereof, see cudaGraphKernelNodeUpdatesApply. Kernel nodes which are device-updatable have additional restrictions compared to regular kernel nodes. Firstly, device-updatable nodes cannot be removed from their graph via GraphNode.Close. Additionally, once opted-in to this functionality, a node cannot opt out, and any attempt to set the attribute to 0 will result in an error. Graphs containing one or more device-updatable node also do not allow multiple instantiation. LaunchAttributePreferredClusterDimension allows the kernel launch to specify a preferred substitute cluster dimension. Blocks may be grouped according to either the dimensions specified with this attribute (grouped into a “preferred substitute cluster”), or the one specified with LaunchAttributeClusterDimension attribute (grouped into a “regular cluster”). The cluster dimensions of a “preferred substitute cluster” shall be an integer multiple greater than zero of the regular cluster dimensions. The device will attempt - on a best-effort basis - to group thread blocks into preferred clusters over grouping them into regular clusters. When it deems necessary (primarily when the device temporarily runs out of physical resources to launch the larger preferred clusters), the device may switch to launch the regular clusters instead to attempt to utilize as much of the physical device resources as possible. Each type of cluster will have its enumeration / coordinate setup as if the grid consists solely of its type of cluster. For example, if the preferred substitute cluster dimensions double the regular cluster dimensions, there might be simultaneously a regular cluster indexed at (1,0,0), and a preferred cluster indexed at (1,0,0). In this example, the preferred substitute cluster (1,0,0) replaces regular clusters (2,0,0) and (3,0,0) and groups their blocks. This attribute will only take effect when a regular cluster dimension has been specified. The preferred substitute The preferred substitute cluster dimension must be an integer multiple greater than zero of the regular cluster dimension and must divide the grid. It must also be no more than maxBlocksPerCluster, if it is set in the kernel’s __launch_bounds__. Otherwise it must be less than the maximum value the driver can support. Otherwise, setting this attribute to a value physically unable to fit on any particular device is permitted. The effect of other attributes is consistent with their effect when set via persistent APIs. See Stream.SetAttribute for

See Function.SetAttribute for

Kernel parameters to f can be specified in the same ways that they can be using Function.LaunchKernel. Note that the API can also be used to launch context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to launch the kernel on will either be taken from the specified stream LaunchConfig.hStream or the current context in case of NULL stream.

Note: This function uses standard default stream semantics.

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.Attribute, cudaLaunchKernel, cudaLaunchKernelEx, Library.Kernel, Kernel.SetCacheConfig, Kernel.Attribute, Kernel.SetAttribute

  • config: Config to launch
  • kernelParams: Array of pointers to kernel parameters

Errors:

Wraps cuLaunchKernelEx.

func (Function) Load

func (f Function) Load() error

Load loads a function.

Finalizes function loading for function. Calling this API with a fully loaded function has no effect.

See also: Module.EnumerateFunctions, Function.IsLoaded

Requires CUDA 12.4 (driver r550) or later; see HasFuncLoad.

Errors:

Wraps cuFuncLoad.

func (Function) MaxActiveBlocksPerMultiprocessor

func (f Function) MaxActiveBlocksPerMultiprocessor(blockSize int32, dynamicSMemSize uint) (int32, error)

MaxActiveBlocksPerMultiprocessor returns occupancy of a function.

Returns the number of the maximum active blocks per streaming multiprocessor. Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will be the current context.

See also: cudaOccupancyMaxActiveBlocksPerMultiprocessor

  • blockSize: Block size the kernel is intended to be launched with
  • dynamicSMemSize: Per-block dynamic shared memory usage intended, in bytes

Errors:

Wraps cuOccupancyMaxActiveBlocksPerMultiprocessor.

func (Function) MaxActiveBlocksPerMultiprocessorWithFlags

func (f Function) MaxActiveBlocksPerMultiprocessorWithFlags(blockSize int32, dynamicSMemSize uint, flags OccupancyFlags) (int32, error)

MaxActiveBlocksPerMultiprocessorWithFlags returns occupancy of a function.

Returns the number of the maximum active blocks per streaming multiprocessor. The Flags parameter controls how special cases are handled. The valid flags are:

  • OccupancyDefault, which maintains the default behavior as Function.MaxActiveBlocksPerMultiprocessor;
  • OccupancyDisableCachingOverride, which 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 OccupancyDisableCachingOverride 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.

Note that the API can also be with launch context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will be the current context.

See also: cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags

  • blockSize: Block size the kernel is intended to be launched with
  • dynamicSMemSize: Per-block dynamic shared memory usage intended, in bytes
  • flags: Requested behavior for the occupancy calculator

Errors:

Wraps cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags.

func (Function) MaxActiveClusters

func (f Function) MaxActiveClusters(config *LaunchConfig) (int32, error)

MaxActiveClusters returns the maximum number of clusters of the function that could coexist on the device under the launch configuration config.

Given the kernel function ( func) and launch configuration ( config), return the maximum number of clusters that could co-exist on the target device.

If the function has required cluster size already set (see cudaFuncGetAttributes / Function.Attribute), the cluster size from config must either be unspecified or match the required size. Without required sizes, the cluster size must be specified in config, else the function will return an error. Note that various attributes of the kernel function may affect occupancy calculation. Runtime environment may affect how the hardware schedules the clusters, so the calculated occupancy is not guaranteed to be achievable. Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will either be taken from the specified stream config->hStream or the current context in case of NULL stream.

See also: cudaFuncGetAttributes, Function.Attribute

  • config: Launch configuration for the given kernel function

Errors:

Wraps cuOccupancyMaxActiveClusters.

func (Function) MaxPotentialBlockSize

func (f Function) MaxPotentialBlockSize(blockSizeToDynamicSMemSize uintptr, dynamicSMemSize uint, blockSizeLimit int32) (minGridSize int32, blockSize int32, err error)

MaxPotentialBlockSize suggests a launch configuration with reasonable occupancy.

Returns in *blockSize a reasonable block size that can achieve the maximum occupancy (or, the maximum number of active warps with the fewest blocks per multiprocessor), and in *minGridSize the minimum grid size to achieve the maximum occupancy. If blockSizeLimit is 0, the configurator will use the maximum block size permitted by the device / function instead. If per-block dynamic shared memory allocation is not needed, the user should leave both blockSizeToDynamicSMemSize and dynamicSMemSize as 0. If per-block dynamic shared memory allocation is needed, then if the dynamic shared memory size is constant regardless of block size, the size should be passed through dynamicSMemSize, and blockSizeToDynamicSMemSize should be NULL. Otherwise, if the per-block dynamic shared memory size varies with different block sizes, the user needs to provide a unary function through blockSizeToDynamicSMemSize that computes the dynamic shared memory needed by func for any given block size. dynamicSMemSize is ignored.

Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will be the current context.

See also: cudaOccupancyMaxPotentialBlockSize

  • minGridSize: Returned minimum grid size needed to achieve the maximum occupancy
  • blockSize: Returned maximum block size that can achieve the maximum occupancy
  • blockSizeToDynamicSMemSize: A function that calculates how much per-block dynamic shared memory func uses based on the block size (see OccupancyB2DSize)
  • dynamicSMemSize: Dynamic shared memory usage intended, in bytes
  • blockSizeLimit: The maximum block size func is designed to handle

Errors:

Wraps cuOccupancyMaxPotentialBlockSize.

func (Function) MaxPotentialBlockSizeWithFlags

func (f Function) MaxPotentialBlockSizeWithFlags(blockSizeToDynamicSMemSize uintptr, dynamicSMemSize uint, blockSizeLimit int32, flags OccupancyFlags) (minGridSize int32, blockSize int32, err error)

MaxPotentialBlockSizeWithFlags suggests a launch configuration with reasonable occupancy.

An extended version of Function.MaxPotentialBlockSize. In addition to arguments passed to Function.MaxPotentialBlockSize, Function.MaxPotentialBlockSizeWithFlags also takes a Flags parameter. The Flags parameter controls how special cases are handled. The valid flags are:

  • OccupancyDefault, which maintains the default behavior as Function.MaxPotentialBlockSize;
  • OccupancyDisableCachingOverride, which suppresses the default behavior on platform where global caching affects occupancy. On such platforms, the launch configurations that produces maximal occupancy might not support global caching. Setting OccupancyDisableCachingOverride guarantees that the the produced launch configuration is global caching compatible at a potential cost of occupancy. More information can be found about this feature in the “Unified L1/Texture Cache” section of the Maxwell tuning guide.

Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will be the current context.

See also: cudaOccupancyMaxPotentialBlockSizeWithFlags

  • minGridSize: Returned minimum grid size needed to achieve the maximum occupancy
  • blockSize: Returned maximum block size that can achieve the maximum occupancy
  • blockSizeToDynamicSMemSize: A function that calculates how much per-block dynamic shared memory func uses based on the block size (see OccupancyB2DSize)
  • dynamicSMemSize: Dynamic shared memory usage intended, in bytes
  • blockSizeLimit: The maximum block size func is designed to handle
  • flags: Options

Errors:

Wraps cuOccupancyMaxPotentialBlockSizeWithFlags.

func (Function) MaxPotentialClusterSize

func (f Function) MaxPotentialClusterSize(config *LaunchConfig) (int32, error)

MaxPotentialClusterSize returns the maximum cluster size of the function under the launch configuration config.

Given the kernel function ( func) and launch configuration ( config), return the maximum cluster size.

The cluster dimensions in config are ignored. If func has a required cluster size set (see cudaFuncGetAttributes / Function.Attribute), the result will reflect the required cluster size. By default this function will always return a value that’s portable on future hardware. A higher value may be returned if the kernel function allows non-portable cluster sizes. This function will respect the compile time launch bounds. Note that the API can also be used with context-less kernel Kernel by querying the handle using Library.Kernel and then passing it to the API by casting to Function. Here, the context to use for calculations will either be taken from the specified stream config->hStream or the current context in case of NULL stream.

See also: cudaFuncGetAttributes, Function.Attribute

  • config: Launch configuration for the given kernel function

Errors:

Wraps cuOccupancyMaxPotentialClusterSize.

func (Function) Module

func (f Function) Module() (Module, error)

Module returns a module handle.

Returns the handle of the module that function hfunc is located in. The lifetime of the module corresponds to the lifetime of the context it was loaded in or until the module is explicitly unloaded. The CUDA runtime manages its own modules loaded into the primary context. If the handle returned by this API refers to a module loaded by the CUDA runtime, calling Module.Close on that module will result in undefined behavior.

Errors:

Wraps cuFuncGetModule.

func (Function) Name

func (f Function) Name() (string, error)

Name returns the function name for a Function handle.

Returns in **name the function name associated with the function handle hfunc . The function name is returned as a null-terminated string. The returned name is only valid when the function handle is valid. If the module is unloaded or reloaded, one must call the API again to get the updated name. This API may return a mangled name if the function is not declared as having C linkage. If either **name or hfunc is NULL, ErrInvalidValue is returned.

Requires CUDA 12.3 (driver r545) or later; see HasFuncGetName.

Errors:

Wraps cuFuncGetName.

func (Function) ParamCount

func (f Function) ParamCount() (uint, error)

ParamCount returns the number of parameters used by the function.

Queries the number of kernel parameters used by func and returns it.

See also: Function.ParamInfo

Requires CUDA 13.2 (driver r595) or later; see HasFuncGetParamCount.

Errors:

Wraps cuFuncGetParamCount.

func (Function) ParamInfo

func (f Function) ParamInfo(paramIndex uint) (paramOffset uint, paramSize uint, err error)

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

Queries the kernel parameter at paramIndex into func's list of parameters, and returns in paramOffset and paramSize the offset and size, respectively, where the parameter will reside in the device-side parameter layout. This information can be used to update kernel node parameters from the device via cudaGraphKernelNodeSetParam() and cudaGraphKernelNodeUpdatesApply(). paramIndex must be less than the number of parameters that func takes. paramSize can be set to NULL if only the parameter offset is desired.

See also: Kernel.ParamInfo

Requires CUDA 12.4 (driver r550) or later; see HasFuncGetParamInfo.

  • paramIndex: The parameter index to query
  • paramOffset: Returns the offset into the device-side parameter layout at which the parameter resides
  • paramSize: Optionally returns the size of the parameter in the device-side parameter layout

Errors:

Wraps cuFuncGetParamInfo.

func (Function) ParamSetSize deprecated

func (f Function) ParamSetSize(numbytes uint32) error

ParamSetSize sets the parameter size for the function.

Sets through numbytes the total size in bytes needed by the function parameters of the kernel corresponding to hfunc.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetf, Function.ParamSeti, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • numbytes: Size of parameter list in bytes

Errors:

Wraps cuParamSetSize.

Deprecated: Deprecated by NVIDIA.

func (Function) ParamSetTexRef deprecated

func (f Function) ParamSetTexRef(texunit int32, hTexRef TexRef) error

ParamSetTexRef adds a texture-reference to the function’s argument list.

Makes the CUDA array or linear memory bound to the texture reference hTexRef available to a device program as a texture. In this version of CUDA, the texture-reference must be obtained via Module.TexRef and the texunit parameter must be set to CU_PARAM_TR_DEFAULT.

  • texunit: Texture unit (must be CU_PARAM_TR_DEFAULT)
  • hTexRef: Texture-reference to add to argument list

Errors:

Wraps cuParamSetTexRef.

Deprecated: Deprecated by NVIDIA.

func (Function) ParamSetf deprecated

func (f Function) ParamSetf(offset int32, value float32) error

ParamSetf adds a floating-point parameter to the function’s argument list.

Sets a floating-point parameter that will be specified the next time the kernel corresponding to hfunc will be invoked. offset is a byte offset.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • offset: Offset to add parameter to argument list
  • value: Value of parameter

Errors:

Wraps cuParamSetf.

Deprecated: Deprecated by NVIDIA.

func (Function) ParamSeti deprecated

func (f Function) ParamSeti(offset int32, value uint32) error

ParamSeti adds an integer parameter to the function’s argument list.

Sets an integer parameter that will be specified the next time the kernel corresponding to hfunc will be invoked. offset is a byte offset.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSetf, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • offset: Offset to add parameter to argument list
  • value: Value of parameter

Errors:

Wraps cuParamSeti.

Deprecated: Deprecated by NVIDIA.

func (Function) ParamSetv deprecated

func (f Function) ParamSetv(offset int32, ptr unsafe.Pointer, numbytes uint32) error

ParamSetv adds arbitrary data to the function’s argument list.

Copies an arbitrary amount of data (specified in numbytes) from ptr into the parameter space of the kernel corresponding to hfunc. offset is a byte offset.

See also: Function.SetBlockShape, Function.SetSharedSize, Function.Attribute, Function.ParamSetSize, Function.ParamSetf, Function.ParamSeti, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • offset: Offset to add data to argument list
  • ptr: Pointer to arbitrary data
  • numbytes: Size of data to copy in bytes

Errors:

Wraps cuParamSetv.

Deprecated: Deprecated by NVIDIA.

func (Function) SetAttribute

func (f Function) SetAttribute(attrib FunctionAttribute, value int32) error

SetAttribute sets information about a function.

This call sets the value of a specified attribute attrib on the kernel given by hfunc to an integer value specified by val This function returns Success if the new value of the attribute could be successfully set. If the set fails, this call will return an error. Not all attributes can have values set. Attempting to set a value on a read-only attribute will result in an error (ErrInvalidValue) Supported attributes for the Function.SetAttribute call are:

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.SetCacheConfig, Function.LaunchKernel, cudaFuncGetAttributes, cudaFuncSetAttribute, Kernel.SetAttribute

  • attrib: Attribute requested
  • value: The value to set

Errors:

Wraps cuFuncSetAttribute.

func (Function) SetBlockShape deprecated

func (f Function) SetBlockShape(x int32, y int32, z int32) error

SetBlockShape sets the block-dimensions for the function.

Specifies the x, y, and z dimensions of the thread blocks that are created when the kernel given by hfunc is launched.

See also: Function.SetSharedSize, Function.SetCacheConfig, Function.Attribute, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • x: X dimension
  • y: Y dimension
  • z: Z dimension

Errors:

Wraps cuFuncSetBlockShape.

Deprecated: Deprecated by NVIDIA.

func (Function) SetCacheConfig

func (f Function) SetCacheConfig(config FuncCacheConfig) error

SetCacheConfig 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 config the preferred cache configuration for the device function hfunc. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute hfunc. Any context-wide preference set via CtxSetCacheConfig will be overridden by this per-function setting unless the per-function setting is FuncCachePreferNone. In that case, the current context-wide setting will be used. 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:

See also: CtxGetCacheConfig, CtxSetCacheConfig, Function.Attribute, Function.LaunchKernel, cudaFuncSetCacheConfig, Kernel.SetCacheConfig

  • config: Requested cache configuration

Errors:

Wraps cuFuncSetCacheConfig.

func (Function) SetSharedMemConfig deprecated

func (f Function) SetSharedMemConfig(config Sharedconfig) error

SetSharedMemConfig 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 Function.SetSharedMemConfig will override the context wide setting set with CtxSetSharedMemConfig. 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:

See also: CtxGetCacheConfig, CtxSetCacheConfig, CtxGetSharedMemConfig, CtxSetSharedMemConfig, Function.Attribute, Function.LaunchKernel, cudaFuncSetSharedMemConfig

  • config: requested shared memory configuration

Errors:

Wraps cuFuncSetSharedMemConfig.

Deprecated: Deprecated by NVIDIA.

func (Function) SetSharedSize deprecated

func (f Function) SetSharedSize(bytes uint32) error

SetSharedSize sets the dynamic shared-memory size for the function.

Sets through bytes the amount of dynamic shared memory that will be available to each thread block when the kernel given by hfunc is launched.

See also: Function.SetBlockShape, Function.SetCacheConfig, Function.Attribute, Function.ParamSetSize, Function.ParamSeti, Function.ParamSetf, Function.ParamSetv, Function.Launch, Function.LaunchGrid, Function.LaunchGridAsync, Function.LaunchKernel

  • bytes: Dynamic shared-memory size per thread in bytes

Errors:

Wraps cuFuncSetSharedSize.

Deprecated: Deprecated by NVIDIA.

type FunctionAttribute

type FunctionAttribute int32

FunctionAttribute represents function properties.

const (
	// FuncAttributeMaxThreadsPerBlock: The maximum number of threads per block, beyond which a launch of the function would fail. This number depends on both the function and the device on which the function is currently loaded.
	FuncAttributeMaxThreadsPerBlock FunctionAttribute = 0
	// FuncAttributeSharedSizeBytes: The size in bytes of statically-allocated shared memory required by this function. This does not include dynamically-allocated shared memory requested by the user at runtime.
	FuncAttributeSharedSizeBytes FunctionAttribute = 1
	// FuncAttributeConstSizeBytes: The size in bytes of user-allocated constant memory required by this function.
	FuncAttributeConstSizeBytes FunctionAttribute = 2
	// FuncAttributeLocalSizeBytes: The size in bytes of local memory used by each thread of this function.
	FuncAttributeLocalSizeBytes FunctionAttribute = 3
	// FuncAttributeNumRegs: The number of registers used by each thread of this function.
	FuncAttributeNumRegs FunctionAttribute = 4
	// FuncAttributePtxVersion: The PTX virtual architecture version for which the function was compiled. This value is the major PTX version * 10 + the minor PTX version, so a PTX version 1.3 function would return the value 13. Note that this may return the undefined value of 0 for cubins compiled prior to CUDA 3.0.
	FuncAttributePtxVersion FunctionAttribute = 5
	// FuncAttributeBinaryVersion: The binary architecture version for which the function was compiled. This value is the major binary version * 10 + the minor binary version, so a binary version 1.3 function would return the value 13. Note that this will return a value of 10 for legacy cubins that do not have a properly-encoded binary architecture version.
	FuncAttributeBinaryVersion FunctionAttribute = 6
	// FuncAttributeCacheModeCa: The attribute to indicate whether the function has been compiled with user specified option "-Xptxas --dlcm=ca" set .
	FuncAttributeCacheModeCa FunctionAttribute = 7
	// FuncAttributeMaxDynamicSharedSizeBytes: The maximum size in bytes of dynamically-allocated shared memory that can be used by this function. If the user-specified dynamic shared memory size is larger than this value, the launch will fail. The default value of this attribute is [DevAttrMaxSharedMemoryPerBlock] - [FuncAttributeSharedSizeBytes], except when [FuncAttributeSharedSizeBytes] is greater than [DevAttrMaxSharedMemoryPerBlock], then the default value of this attribute is 0. The value can be increased to [DevAttrMaxSharedMemoryPerBlockOptin] - [FuncAttributeSharedSizeBytes]. This attribute is ignored if [FuncAttributeSharedMemoryMode] or [LaunchAttributeSharedMemoryMode] is set. This attribute cannot be used to access oversized shared memory. Oversized shared memory can only be accessed by setting [FuncAttributeSharedMemoryMode] or [LaunchAttributeSharedMemoryMode]. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeMaxDynamicSharedSizeBytes FunctionAttribute = 8
	// FuncAttributePreferredSharedMemoryCarveout: 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. Refer to [DevAttrMaxSharedMemoryPerMultiprocessor]. This is only a hint, and the driver can choose a different ratio if required to execute the function. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributePreferredSharedMemoryCarveout FunctionAttribute = 9
	// FuncAttributeClusterSizeMustBeSet: If this attribute is set, the kernel must launch with a valid cluster size specified. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeClusterSizeMustBeSet FunctionAttribute = 10
	// FuncAttributeRequiredClusterWidth: The required cluster width in blocks. The values must either all be 0 or all be positive. The validity of the cluster dimensions is otherwise checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime will return [ErrNotPermitted]. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeRequiredClusterWidth FunctionAttribute = 11
	// FuncAttributeRequiredClusterHeight: The required cluster height in blocks. The values must either all be 0 or all be positive. The validity of the cluster dimensions is otherwise checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime should return [ErrNotPermitted]. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeRequiredClusterHeight FunctionAttribute = 12
	// FuncAttributeRequiredClusterDepth: The required cluster depth in blocks. The values must either all be 0 or all be positive. The validity of the cluster dimensions is otherwise checked at launch time. If the value is set during compile time, it cannot be set at runtime. Setting it at runtime should return [ErrNotPermitted]. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeRequiredClusterDepth FunctionAttribute = 13
	// FuncAttributeNonPortableClusterSizeAllowed: Whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. A non-portable cluster size may only function on the specific SKUs the program is tested on. The launch might fail if the program is run on a different hardware platform. CUDA API provides cudaOccupancyMaxActiveClusters to assist with checking whether the desired size can be launched on the current device. Portable Cluster Size. A portable cluster size is guaranteed to be functional on all compute capabilities higher than the target compute capability. The portable cluster size for sm_90 is 8 blocks per cluster. This value may increase for future compute capabilities. The specific hardware unit may support higher cluster sizes that’s not guaranteed to be portable. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeNonPortableClusterSizeAllowed FunctionAttribute = 14
	// FuncAttributeClusterSchedulingPolicyPreference: The block scheduling policy of a function. The value type is [ClusterSchedulingPolicy] / cudaClusterSchedulingPolicy. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeClusterSchedulingPolicyPreference FunctionAttribute = 15
	// FuncAttributeDeviceNodeUpdateSupported: Whether the function can be updated on device. 1 means device node update is supported, 0 is unsupported. See [Function.Attribute].
	FuncAttributeDeviceNodeUpdateSupported FunctionAttribute = 16
	// FuncAttributeSharedMemoryMode: The shared memory mode of a function. The value type is [SharedMemoryMode] / cudaSharedMemoryMode. See [Function.SetAttribute], [Kernel.SetAttribute]
	FuncAttributeSharedMemoryMode FunctionAttribute = 17
)

func (FunctionAttribute) String

func (e FunctionAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type FunctionLoadingState

type FunctionLoadingState int32

FunctionLoadingState specifies the function loading state (CUfunctionLoadingState).

const (
	FunctionLoadingStateUnloaded FunctionLoadingState = 0
	FunctionLoadingStateLoaded   FunctionLoadingState = 1
)

func (FunctionLoadingState) String

func (e FunctionLoadingState) String() string

String returns the constant name, or a numeric representation for unknown values.

type GPUDirectRDMAWritesOrdering

type GPUDirectRDMAWritesOrdering int32

GPUDirectRDMAWritesOrdering represents platform native ordering for GPUDirect RDMA writes.

const (
	// GpuDirectRdmaWritesOrderingNone: The device does not natively support ordering of remote writes. [FlushGPUDirectRDMAWrites] can be leveraged if supported.
	GpuDirectRdmaWritesOrderingNone GPUDirectRDMAWritesOrdering = 0
	// GpuDirectRdmaWritesOrderingOwner: Natively, the device can consistently consume remote writes, although other CUDA devices may not.
	GpuDirectRdmaWritesOrderingOwner GPUDirectRDMAWritesOrdering = 100
	// GpuDirectRdmaWritesOrderingAllDevices: Any CUDA device in the system can consistently consume remote writes to this device.
	GpuDirectRdmaWritesOrderingAllDevices GPUDirectRDMAWritesOrdering = 200
)

func (GPUDirectRDMAWritesOrdering) String

String returns the constant name, or a numeric representation for unknown values.

type Graph

type Graph uintptr

Graph is CUDA graph.

Graph objects are not thread safe. Serialize all calls that use the same graph, including ones that only read it, such as Graph.Clone and Graph.Instantiate.

func NewGraph

func NewGraph(flags uint32) (Graph, error)

NewGraph creates a graph.

Creates an empty graph, which is returned.

See also: Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemcpyNode, Graph.AddMemsetNode, Graph.Instantiate, Graph.Destroy, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.Clone

  • flags: Graph creation flags, must be 0

Errors:

Wraps cuGraphCreate.

func (Graph) AddBatchMemOpNode

func (g Graph) AddBatchMemOpNode(dependencies *GraphNode, numDependencies uint, nodeParams *BatchMemOpNodeParams) (BatchMemOpNode, error)

AddBatchMemOpNode creates a batch memory operation node and adds it to a graph.

Creates a new batch memory operation node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. When the node is added, the paramArray inside nodeParams is copied and therefore it can be freed after the call returns.

Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order.

See also: Graph.AddNode, Stream.BatchMemOp, Stream.WaitValue32, Stream.WriteValue32, Stream.WaitValue64, Stream.WriteValue64, BatchMemOpNode.Params, BatchMemOpNode.SetParams, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the node

Errors:

Wraps cuGraphAddBatchMemOpNode.

func (Graph) AddChildGraphNode

func (g Graph) AddChildGraphNode(dependencies *GraphNode, numDependencies uint, childGraph Graph) (ChildGraphNode, error)

AddChildGraphNode creates a child graph node and adds it to a graph.

Creates a new node which executes an embedded graph, and adds it to hGraph with numDependencies dependencies specified via dependencies. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. If childGraph contains allocation nodes, free nodes, or conditional nodes, this call will return an error. The node executes an embedded child graph. The child graph is cloned in this call.

See also: Graph.AddNode, ChildGraphNode.Graph, NewGraph, GraphNode.Close, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemcpyNode, Graph.AddMemsetNode, Graph.Clone

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • childGraph: The graph to clone into this node

Errors:

Wraps cuGraphAddChildGraphNode.

func (Graph) AddDependencies

func (g Graph) AddDependencies(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numDependencies uint) error

AddDependencies adds dependency edges to a graph.

The number of dependencies to be added is defined by numDependencies Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an existing dependency will return an error.

See also: Graph.RemoveDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • edgeData: Optional array of edge data. If NULL, default (zeroed) edge data is assumed
  • numDependencies: Number of dependencies to be added

Errors:

Wraps cuGraphAddDependencies, bound to the first of cuGraphAddDependencies_v2, cuGraphAddDependencies that the library exports. On libraries without cuGraphAddDependencies_v2, it calls cuGraphAddDependencies; a non-nil edgeData returns ErrNotSupported.

func (Graph) AddDependenciesV1 deprecated

func (g Graph) AddDependenciesV1(from *GraphNode, to *GraphNode, numDependencies uint) error

AddDependenciesV1 adds dependency edges to a graph.

The number of dependencies to be added is defined by numDependencies Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an existing dependency will return an error.

See also: Graph.RemoveDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • numDependencies: Number of dependencies to be added

Errors:

Wraps cuGraphAddDependencies_v1, bound as cuGraphAddDependencies.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Graph) AddDependenciesV2

func (g Graph) AddDependenciesV2(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numDependencies uint) error

AddDependenciesV2 adds dependency edges to a graph.

The number of dependencies to be added is defined by numDependencies Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an existing dependency will return an error.

See also: Graph.RemoveDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

Requires CUDA 12.3 (driver r545) or later; see HasGraphAddDependenciesV2.

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • edgeData: Optional array of edge data. If NULL, default (zeroed) edge data is assumed
  • numDependencies: Number of dependencies to be added

Errors:

Wraps cuGraphAddDependencies, bound as cuGraphAddDependencies_v2.

func (Graph) AddEmptyNode

func (g Graph) AddEmptyNode(dependencies *GraphNode, numDependencies uint) (GraphNode, error)

AddEmptyNode creates an empty node and adds it to a graph.

Creates a new node which performs no operation, and adds it to hGraph with numDependencies dependencies specified via dependencies. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. An empty node performs no operation during execution, but can be used for transitive ordering. For example, a phased execution graph with 2 groups of n nodes with a barrier between them can be represented using an empty node and 2*n dependency edges, rather than no empty node and n^2 dependency edges.

See also: Graph.AddNode, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies

Errors:

Wraps cuGraphAddEmptyNode.

func (Graph) AddEventRecordNode

func (g Graph) AddEventRecordNode(dependencies *GraphNode, numDependencies uint, event Event) (EventRecordNode, error)

AddEventRecordNode creates an event record node and adds it to a graph.

Creates a new event record node and adds it to hGraph with numDependencies dependencies specified via dependencies and event specified in event. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. Each launch of the graph will record event to capture execution of the node’s dependencies.

See also: Graph.AddNode, Graph.AddEventWaitNode, Event.RecordWithFlags, Stream.WaitEvent, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • event: Event for the node

Errors:

Wraps cuGraphAddEventRecordNode.

func (Graph) AddEventWaitNode

func (g Graph) AddEventWaitNode(dependencies *GraphNode, numDependencies uint, event Event) (EventWaitNode, error)

AddEventWaitNode creates an event wait node and adds it to a graph.

Creates a new event wait node and adds it to hGraph with numDependencies dependencies specified via dependencies and event specified in event. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. The graph node will wait for all work captured in event. See Event.Record for details on what is captured by an event. event may be from a different context or device than the launch stream.

See also: Graph.AddNode, Graph.AddEventRecordNode, Event.RecordWithFlags, Stream.WaitEvent, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • event: Event for the node

Errors:

Wraps cuGraphAddEventWaitNode.

func (Graph) AddExternalSemaphoresSignalNode

func (g Graph) AddExternalSemaphoresSignalNode(dependencies *GraphNode, numDependencies uint, nodeParams *ExtSemSignalNodeParams) (ExternalSemaphoresSignalNode, error)

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

Creates a new external semaphore signal node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. Performs a signal operation on a set of externally allocated semaphore objects when the node is launched. The operation(s) will occur after all of the node’s dependencies have completed.

See also: Graph.AddNode, ExternalSemaphoresSignalNode.Params, ExternalSemaphoresSignalNode.SetParams, GraphExec.ExternalSemaphoresSignalNodeSetParams, Graph.AddExternalSemaphoresWaitNode, ImportExternalSemaphore, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync, NewGraph, GraphNode.Close, Graph.AddEventRecordNode, Graph.AddEventWaitNode, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the node

Errors:

Wraps cuGraphAddExternalSemaphoresSignalNode.

func (Graph) AddExternalSemaphoresWaitNode

func (g Graph) AddExternalSemaphoresWaitNode(dependencies *GraphNode, numDependencies uint, nodeParams *ExtSemWaitNodeParams) (ExternalSemaphoresWaitNode, error)

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

Creates a new external semaphore wait node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. Performs a wait operation on a set of externally allocated semaphore objects when the node is launched. The node’s dependencies will not be launched until the wait operation has completed.

See also: Graph.AddNode, ExternalSemaphoresWaitNode.Params, ExternalSemaphoresWaitNode.SetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, Graph.AddExternalSemaphoresSignalNode, ImportExternalSemaphore, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync, NewGraph, GraphNode.Close, Graph.AddEventRecordNode, Graph.AddEventWaitNode, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the node

Errors:

Wraps cuGraphAddExternalSemaphoresWaitNode.

func (Graph) AddHostNode

func (g Graph) AddHostNode(dependencies *GraphNode, numDependencies uint, nodeParams *HostNodeParams) (HostNode, error)

AddHostNode creates a host execution node and adds it to a graph.

Creates a new CPU execution node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. When the graph is launched, the node will invoke the specified CPU function. Host nodes are not supported under MPS with pre-Volta GPUs.

See also: Graph.AddNode, Stream.LaunchHostFunc, HostNode.Params, HostNode.SetParams, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the host node

Errors:

Wraps cuGraphAddHostNode.

func (Graph) AddKernelNode

func (g Graph) AddKernelNode(dependencies *GraphNode, numDependencies uint, nodeParams *KernelNodeParams) (KernelNode, error)

AddKernelNode creates a kernel execution node and adds it to a graph.

Creates a new kernel execution node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned.

When the graph is launched, the node will invoke kernel func on a ( gridDimX x gridDimY x gridDimZ) grid of blocks. Each block contains ( blockDimX x blockDimY x blockDimZ) threads. sharedMemBytes sets the amount of dynamic shared memory that will be available to each thread block. Kernel parameters to func can be specified in one of two ways:

  • Kernel parameters can be specified via kernelParams. If the kernel has N parameters, then kernelParams needs to be an array of N pointers. Each pointer, from kernelParams[0] to kernelParams[N-1], points to the region of memory from which the actual parameter will be copied. The number of kernel parameters and their offsets and sizes do not need to be specified as that information is retrieved directly from the kernel’s image.
  • Kernel parameters for non-cooperative kernels can also be packaged by the application into a single buffer that is passed in via extra. This places the burden on the application of knowing each kernel parameter’s size and alignment/padding within the buffer. The extra parameter exists to allow this function to take additional less commonly used arguments. extra specifies a list of names of extra settings and their corresponding values. Each extra setting name is immediately followed by the corresponding value. The list must be terminated with either NULL or CU_LAUNCH_PARAM_END.
  • CU_LAUNCH_PARAM_END, which indicates the end of the extra array;
  • CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next value in extra will be a pointer to a buffer containing all the kernel parameters for launching kernel func;
  • CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next value in extra will be a pointer to a size_t containing the size of the buffer specified with CU_LAUNCH_PARAM_BUFFER_POINTER;

The error ErrInvalidValue will be returned if kernel parameters are specified with both kernelParams and extra (i.e. both kernelParams and extra are non-NULL). ErrInvalidValue will be returned if extra is used for a cooperative kernel. The kernelParams or extra array, as well as the argument values it points to, are copied during this call.

Note: Kernels launched using graphs 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.

See also: Graph.AddNode, Function.LaunchKernel, Function.LaunchCooperativeKernel, KernelNode.Params, KernelNode.SetParams, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddHostNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the GPU execution node

Errors:

Wraps cuGraphAddKernelNode, bound as cuGraphAddKernelNode_v2.

func (Graph) AddMemAllocNode

func (g Graph) AddMemAllocNode(dependencies *GraphNode, numDependencies uint, nodeParams *MemAllocNodeParams) (MemAllocNode, error)

AddMemAllocNode creates an allocation node and adds it to a graph.

Creates a new allocation node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. When Graph.AddMemAllocNode creates an allocation node, it returns the address of the allocation in nodeParams.dptr. The allocation’s address remains fixed across instantiations and launches. If the allocation is freed in the same graph, by creating a free node using Graph.AddMemFreeNode, the allocation can be accessed by nodes ordered after the allocation node but before the free node. These allocations cannot be freed outside the owning graph, and they can only be freed once in the owning graph. If the allocation is not freed in the same graph, then it can be accessed not only by nodes in the graph which are ordered after the allocation node, but also by stream operations ordered after the graph’s execution but before the allocation is freed. Allocations which are not freed in the same graph can be freed by:

It is not possible to free an allocation in both the owning graph and another graph. If the allocation is freed in the same graph, a free node cannot be added to another graph. If the allocation is freed in another graph, a free node can no longer be added to the owning graph. The following restrictions apply to graphs which contain allocation and/or memory free nodes:

  • Nodes and edges of the graph cannot be deleted.
  • The graph can only be used in a child node if the ownership is moved to the parent.
  • Only one instantiation of the graph may exist at any point in time.
  • The graph cannot be cloned.

See also: Graph.AddNode, Graph.AddMemFreeNode, MemAllocNode.Params, Device.GraphMemTrim, Device.GraphMemAttribute, Device.SetGraphMemAttribute, Stream.MemAllocAsync, DevicePtr.FreeAsync, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddEventRecordNode, Graph.AddEventWaitNode, Graph.AddExternalSemaphoresSignalNode, Graph.AddExternalSemaphoresWaitNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Parameters for the node

Errors:

Wraps cuGraphAddMemAllocNode.

func (Graph) AddMemFreeNode

func (g Graph) AddMemFreeNode(dependencies *GraphNode, numDependencies uint, dptr DevicePtr) (MemFreeNode, error)

AddMemFreeNode creates a memory free node and adds it to a graph.

Creates a new memory free node and adds it to hGraph with numDependencies dependencies specified via dependencies and arguments specified in nodeParams. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. Graph.AddMemFreeNode will return ErrInvalidValue if the user attempts to free:

  • an allocation twice in the same graph.
  • an address that was not returned by an allocation node.
  • an invalid address.

The following restrictions apply to graphs which contain allocation and/or memory free nodes:

  • Nodes and edges of the graph cannot be deleted.
  • The graph can only be used in a child node if the ownership is moved to the parent.
  • Only one instantiation of the graph may exist at any point in time.
  • The graph cannot be cloned.

See also: Graph.AddNode, Graph.AddMemAllocNode, MemFreeNode.Params, Device.GraphMemTrim, Device.GraphMemAttribute, Device.SetGraphMemAttribute, Stream.MemAllocAsync, DevicePtr.FreeAsync, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddEventRecordNode, Graph.AddEventWaitNode, Graph.AddExternalSemaphoresSignalNode, Graph.AddExternalSemaphoresWaitNode, Graph.AddKernelNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • dptr: Address of memory to free

Errors:

Wraps cuGraphAddMemFreeNode.

func (Graph) AddMemcpyNode

func (g Graph) AddMemcpyNode(dependencies *GraphNode, numDependencies uint, copyParams *Memcpy3d, ctx Context) (MemcpyNode, error)

AddMemcpyNode creates a memcpy node and adds it to a graph.

Creates a new memcpy node and adds it to hGraph with numDependencies dependencies specified via dependencies. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. When the graph is launched, the node will perform the memcpy described by copyParams. See Memcpy3D for a description of the structure and its restrictions. Memcpy nodes have some additional restrictions with regards to managed memory, if the system contains at least one device which has a zero value for the device attribute DevAttrConcurrentManagedAccess. If one or more of the operands refer to managed memory, then using the memory type MemoryTypeUnified is disallowed for those operand(s). The managed memory will be treated as residing on either the host or the device, depending on which memory type is specified.

See also: Graph.AddNode, Memcpy3D, MemcpyNode.Params, MemcpyNode.SetParams, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemsetNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • copyParams: Parameters for the memory copy
  • ctx: Context on which to run the node

Errors:

Wraps cuGraphAddMemcpyNode.

func (Graph) AddMemsetNode

func (g Graph) AddMemsetNode(dependencies *GraphNode, numDependencies uint, memsetParams *MemsetNodeParams, ctx Context) (MemsetNode, error)

AddMemsetNode creates a memset node and adds it to a graph.

Creates a new memset node and adds it to hGraph with numDependencies dependencies specified via dependencies. It is possible for numDependencies to be 0, in which case the node will be placed at the root of the graph. dependencies may not have any duplicate entries. A handle to the new node will be returned. The element size must be 1, 2, or 4 bytes. When the graph is launched, the node will perform the memset described by memsetParams.

See also: Graph.AddNode, DevicePtr.MemsetD2D32, MemsetNode.Params, MemsetNode.SetParams, NewGraph, GraphNode.Close, Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemcpyNode

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • memsetParams: Parameters for the memory set
  • ctx: Context on which to run the node

Errors:

Wraps cuGraphAddMemsetNode.

func (Graph) AddNode

func (g Graph) AddNode(dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, nodeParams *GraphNodeParams) (GraphNode, error)

AddNode adds a node of arbitrary type to a graph.

Creates a new node in hGraph described by nodeParams with numDependencies dependencies specified via dependencies. numDependencies may be 0. dependencies may be null if numDependencies is 0. dependencies may not have any duplicate entries. nodeParams is a tagged union. The node type should be specified in the type field, and type-specific parameters in the corresponding union member. All unused bytes - that is, reserved0 and all bytes past the utilized union member - must be set to zero. It is recommended to use brace initialization or memset to ensure all bytes are initialized. Note that for some node types, nodeParams may contain “out parameters” which are modified during the call, such as nodeParams->alloc.dptr. A handle to the new node will be returned.

See also: NewGraph, GraphNode.SetParams, GraphExec.NodeSetParams

  • dependencies: Dependencies of the node
  • dependencyData: Optional edge data for the dependencies. If NULL, the data is assumed to be default (zeroed) for all dependencies
  • numDependencies: Number of dependencies
  • nodeParams: Specification of the node

Errors:

Wraps cuGraphAddNode, bound to the first of cuGraphAddNode_v2, cuGraphAddNode that the library exports. On libraries without cuGraphAddNode_v2, it calls cuGraphAddNode; a non-nil dependencyData returns ErrNotSupported.

func (Graph) AddNodeV1 deprecated

func (g Graph) AddNodeV1(dependencies *GraphNode, numDependencies uint, nodeParams *GraphNodeParams) (GraphNode, error)

AddNodeV1 adds a node of arbitrary type to a graph.

Creates a new node in hGraph described by nodeParams with numDependencies dependencies specified via dependencies. numDependencies may be 0. dependencies may be null if numDependencies is 0. dependencies may not have any duplicate entries. nodeParams is a tagged union. The node type should be specified in the type field, and type-specific parameters in the corresponding union member. All unused bytes - that is, reserved0 and all bytes past the utilized union member - must be set to zero. It is recommended to use brace initialization or memset to ensure all bytes are initialized. Note that for some node types, nodeParams may contain “out parameters” which are modified during the call, such as nodeParams->alloc.dptr. A handle to the new node will be returned.

See also: NewGraph, GraphNode.SetParams, GraphExec.NodeSetParams

  • dependencies: Dependencies of the node
  • numDependencies: Number of dependencies
  • nodeParams: Specification of the node

Errors:

Wraps cuGraphAddNode_v1, bound as cuGraphAddNode.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Graph) AddNodeV2

func (g Graph) AddNodeV2(dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, nodeParams *GraphNodeParams) (GraphNode, error)

AddNodeV2 adds a node of arbitrary type to a graph.

Creates a new node in hGraph described by nodeParams with numDependencies dependencies specified via dependencies. numDependencies may be 0. dependencies may be null if numDependencies is 0. dependencies may not have any duplicate entries. nodeParams is a tagged union. The node type should be specified in the type field, and type-specific parameters in the corresponding union member. All unused bytes - that is, reserved0 and all bytes past the utilized union member - must be set to zero. It is recommended to use brace initialization or memset to ensure all bytes are initialized. Note that for some node types, nodeParams may contain “out parameters” which are modified during the call, such as nodeParams->alloc.dptr. A handle to the new node will be returned.

See also: NewGraph, GraphNode.SetParams, GraphExec.NodeSetParams

Requires CUDA 12.3 (driver r545) or later; see HasGraphAddNodeV2.

  • dependencies: Dependencies of the node
  • dependencyData: Optional edge data for the dependencies. If NULL, the data is assumed to be default (zeroed) for all dependencies
  • numDependencies: Number of dependencies
  • nodeParams: Specification of the node

Errors:

Wraps cuGraphAddNode, bound as cuGraphAddNode_v2.

func (Graph) AddNodeV3

func (g Graph) AddNodeV3(dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, nodeParams *GraphNodeParams) (GraphNode, error)

AddNodeV3 adds a node of arbitrary type to a graph.

Creates a new node in hGraph described by nodeParams with numDependencies dependencies specified via dependencies. numDependencies may be 0. dependencies may be null if numDependencies is 0. dependencies may not have any duplicate entries. nodeParams is a tagged union. The node type should be specified in the type field, and type-specific parameters in the corresponding union member. All unused bytes - that is, reserved0 and all bytes past the utilized union member - must be set to zero. It is recommended to use brace initialization or memset to ensure all bytes are initialized. Note that for some node types, nodeParams may contain “out parameters” which are modified during the call, such as nodeParams->alloc.dptr. For kernel nodes, if both the kernel node’s Function and ctx are non-NULL, the underlying device context of ctx must match the device context that the Function was loaded into; otherwise the call returns ErrInvalidContext. A handle to the new node will be returned.

See also: NewGraph, GraphNode.SetParamsV2, GraphExec.NodeSetParams

Requires CUDA 13.4 (driver r615) or later; see HasGraphAddNodeV3.

  • dependencies: Dependencies of the node
  • dependencyData: Optional edge data for the dependencies. If NULL, the data is assumed to be default (zeroed) for all dependencies
  • numDependencies: Number of dependencies
  • nodeParams: Specification of the node

Errors:

Wraps cuGraphAddNode_v3.

func (Graph) Clone

func (g Graph) Clone() (Graph, error)

Clone clones a graph.

This function creates a copy of originalGraph and returns it. All parameters are copied into the cloned graph. The original graph may be modified after this call without affecting the clone. Child graph nodes in the original graph are recursively copied into the clone.

Note: : Cloning is not supported for graphs which contain memory allocation nodes, memory free nodes, or conditional nodes.

See also: NewGraph, GraphNode.FindInClone

Errors:

Wraps cuGraphClone.

func (Graph) ConditionalHandleCreate

func (g Graph) ConditionalHandleCreate(ctx Context, defaultLaunchValue uint32, flags uint32) (uint64, error)

ConditionalHandleCreate creates a conditional handle.

Creates a conditional handle associated with hGraph. The conditional handle must be associated with a conditional node in this graph or one of its children. Handles not associated with a conditional node may cause graph instantiation to fail. Handles can only be set from the context with which they are associated.

See also: Graph.AddNode

Requires CUDA 12.3 (driver r545) or later; see HasGraphConditionalHandleCreate.

  • ctx: Context for the handle and associated conditional node
  • defaultLaunchValue: Optional initial value for the conditional variable. Applied at the beginning of each graph execution if CU_GRAPH_COND_ASSIGN_DEFAULT is set in flags
  • flags: Currently must be CU_GRAPH_COND_ASSIGN_DEFAULT or 0

Errors:

Wraps cuGraphConditionalHandleCreate.

func (Graph) DebugDotPrint

func (g Graph) DebugDotPrint(path string, flags GraphdebugdotFlags) error

DebugDotPrint writes a DOT file describing graph structure.

Using the provided hGraph, write to path a DOT formatted description of the graph. By default this includes the graph topology, node types, node id, kernel names and memcpy direction. flags can be specified to write more detailed information about each node type such as parameter values, kernel attributes, node and function handles.

  • path: The path to write the DOT file to
  • flags: Flags from GraphdebugdotFlags for specifying which additional node information to write

Errors:

Wraps cuGraphDebugDotPrint.

func (Graph) Destroy

func (g Graph) Destroy() error

Destroy destroys a graph.

Destroys the graph specified by hGraph, as well as all of its nodes.

See also: NewGraph

Errors:

It is not named Close because Graph has another release method, ReleaseUserObject.

Wraps cuGraphDestroy.

func (Graph) Edges

func (g Graph) Edges(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numEdges *uint) error

Edges returns a graph’s dependency edges.

Returns a list of hGraph's dependency edges. Edges are returned via corresponding indices in from, to and edgeData; that is, the node in toi has a dependency on the node in fromi with data edgeDatai. from and to may both be NULL, in which case this function only returns the number of edges in numEdges. Otherwise, numEdges entries will be filled in. If numEdges is higher than the actual number of edges, the remaining entries in from and to will be set to NULL, and the number of edges actually returned will be written to numEdges. edgeData may alone be NULL, in which case the edges must all have default (zeroed) edge data. Attempting a lossy query via NULL edgeData will result in ErrLossyQuery. If edgeData is non-NULL then from and to must be as well.

See also: Graph.GetNodes, Graph.RootNodes, Graph.AddDependencies, Graph.RemoveDependencies, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Location to return edge endpoints
  • to: Location to return edge endpoints
  • edgeData: Optional location to return edge data
  • numEdges: See description

Errors:

Wraps cuGraphGetEdges, bound to the first of cuGraphGetEdges_v2, cuGraphGetEdges that the library exports. On libraries without cuGraphGetEdges_v2, it calls cuGraphGetEdges; a non-nil edgeData returns ErrNotSupported.

func (Graph) EdgesV1 deprecated

func (g Graph) EdgesV1(from *GraphNode, to *GraphNode, numEdges *uint) error

EdgesV1 returns a graph’s dependency edges.

Returns a list of hGraph's dependency edges. Edges are returned via corresponding indices in from, to and edgeData; that is, the node in toi has a dependency on the node in fromi with data edgeDatai. from and to may both be NULL, in which case this function only returns the number of edges in numEdges. Otherwise, numEdges entries will be filled in. If numEdges is higher than the actual number of edges, the remaining entries in from and to will be set to NULL, and the number of edges actually returned will be written to numEdges. edgeData may alone be NULL, in which case the edges must all have default (zeroed) edge data. Attempting a lossy query via NULL edgeData will result in ErrLossyQuery. If edgeData is non-NULL then from and to must be as well.

See also: Graph.GetNodes, Graph.RootNodes, Graph.AddDependencies, Graph.RemoveDependencies, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Location to return edge endpoints
  • to: Location to return edge endpoints
  • numEdges: See description

Errors:

Wraps cuGraphGetEdges_v1, bound as cuGraphGetEdges.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Graph) EdgesV2

func (g Graph) EdgesV2(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numEdges *uint) error

EdgesV2 returns a graph’s dependency edges.

Returns a list of hGraph's dependency edges. Edges are returned via corresponding indices in from, to and edgeData; that is, the node in toi has a dependency on the node in fromi with data edgeDatai. from and to may both be NULL, in which case this function only returns the number of edges in numEdges. Otherwise, numEdges entries will be filled in. If numEdges is higher than the actual number of edges, the remaining entries in from and to will be set to NULL, and the number of edges actually returned will be written to numEdges. edgeData may alone be NULL, in which case the edges must all have default (zeroed) edge data. Attempting a lossy query via NULL edgeData will result in ErrLossyQuery. If edgeData is non-NULL then from and to must be as well.

See also: Graph.GetNodes, Graph.RootNodes, Graph.AddDependencies, Graph.RemoveDependencies, GraphNode.Dependencies, GraphNode.DependentNodes

Requires CUDA 12.3 (driver r545) or later; see HasGraphGetEdgesV2.

  • from: Location to return edge endpoints
  • to: Location to return edge endpoints
  • edgeData: Optional location to return edge data
  • numEdges: See description

Errors:

Wraps cuGraphGetEdges, bound as cuGraphGetEdges_v2.

func (Graph) GetNodes

func (g Graph) GetNodes(nodes *GraphNode, numNodes *uint) error

GetNodes returns a graph’s nodes.

Returns a list of hGraph's nodes. nodes may be NULL, in which case this function will return the number of nodes in numNodes. Otherwise, numNodes entries will be filled in. If numNodes is higher than the actual number of nodes, the remaining entries in nodes will be set to NULL, and the number of nodes actually obtained will be returned in numNodes.

See also: NewGraph, Graph.RootNodes, Graph.Edges, GraphNode.Type, GraphNode.Dependencies, GraphNode.DependentNodes

  • nodes: Pointer to return the nodes
  • numNodes: See description

Errors:

Wraps cuGraphGetNodes.

func (Graph) Id

func (g Graph) Id() (uint32, error)

Id returns the id of a given graph.

Returns the id of hGraph. The result will match that referenced by Graph.DebugDotPrint.

See also: Graph.GetNodes, Graph.DebugDotPrint GraphNode.ContainingGraph GraphNode.LocalId GraphNode.ToolsId GraphExec.Id

Requires CUDA 13.1 (driver r590) or later; see HasGraphGetId.

Errors:

Wraps cuGraphGetId.

func (Graph) Instantiate

func (g Graph) Instantiate(flags GraphinstantiateFlags) (GraphExec, error)

Instantiate creates an executable graph from a graph.

Instantiates hGraph as an executable graph. The graph is validated for any structural constraints or intra-node constraints which were not previously validated. If instantiation is successful, a handle to the instantiated graph is returned. The flags parameter controls the behavior of instantiation and subsequent graph launches. Valid flags are:

  • GraphInstantiateFlagAutoFreeOnLaunch, which configures a graph containing memory allocation nodes to automatically free any unfreed memory allocations before the graph is relaunched.
  • GraphInstantiateFlagDeviceLaunch, which configures the graph for launch from the device. If this flag is passed, the executable graph handle returned can be used to launch the graph from both the host and device. This flag can only be used on platforms which support unified addressing. This flag cannot be used in conjunction with GraphInstantiateFlagAutoFreeOnLaunch.
  • GraphInstantiateFlagUseNodePriority, which causes the graph to use the priorities from the per-node attributes rather than the priority of the launch stream during execution. Note that priorities are only available on kernel nodes, and are copied from stream priority during stream capture.

If hGraph contains any allocation or free nodes, there can be at most one executable graph in existence for that graph at a time. An attempt to instantiate a second executable graph before destroying the first with GraphExec.Close will result in an error. The same also applies if hGraph contains any device-updatable kernel nodes. If hGraph contains kernels which call device-side cudaGraphLaunch() from multiple contexts, this will result in an error. Graphs instantiated for launch on the device have additional restrictions which do not apply to host graphs:

  • The graph’s nodes must reside on a single context.
  • The graph can only contain kernel nodes, memcpy nodes, memset nodes, and child graph nodes.
  • The graph cannot be empty and must contain at least one kernel, memcpy, or memset node. Operation-specific restrictions are outlined below.
  • Kernel nodes: Use of CUDA Dynamic Parallelism is not permitted. Cooperative launches are permitted as long as MPS is not in use.
  • Memcpy nodes: Only copies involving device memory and/or pinned device-mapped host memory are permitted. Copies involving CUDA arrays are not permitted. Both operands must be accessible from the current context, and the current context must match the context of other nodes in the graph.

See also: Graph.Instantiate, NewGraph, GraphExec.Upload, GraphExec.Launch, GraphExec.Close

Errors:

Wraps cuGraphInstantiate, bound as cuGraphInstantiateWithFlags.

func (Graph) InstantiateWithParams

func (g Graph) InstantiateWithParams(instantiateParams *GraphInstantiateParams) (GraphExec, error)

InstantiateWithParams creates an executable graph from a graph.

Instantiates hGraph as an executable graph according to the instantiateParams structure. The graph is validated for any structural constraints or intra-node constraints which were not previously validated. If instantiation is successful, a handle to the instantiated graph is returned. instantiateParams controls the behavior of instantiation and subsequent graph launches, as well as returning more detailed information in the event of an error.

The flags field controls the behavior of instantiation and subsequent graph launches. Valid flags are:

  • GraphInstantiateFlagAutoFreeOnLaunch, which configures a graph containing memory allocation nodes to automatically free any unfreed memory allocations before the graph is relaunched.
  • GraphInstantiateFlagUpload, which will perform an upload of the graph into hUploadStream once the graph has been instantiated.
  • GraphInstantiateFlagDeviceLaunch, which configures the graph for launch from the device. If this flag is passed, the executable graph handle returned can be used to launch the graph from both the host and device. This flag can only be used on platforms which support unified addressing. This flag cannot be used in conjunction with GraphInstantiateFlagAutoFreeOnLaunch.
  • GraphInstantiateFlagUseNodePriority, which causes the graph to use the priorities from the per-node attributes rather than the priority of the launch stream during execution. Note that priorities are only available on kernel nodes, and are copied from stream priority during stream capture.

If hGraph contains any allocation or free nodes, there can be at most one executable graph in existence for that graph at a time. An attempt to instantiate a second executable graph before destroying the first with GraphExec.Close will result in an error. The same also applies if hGraph contains any device-updatable kernel nodes. If hGraph contains kernels which call device-side cudaGraphLaunch() from multiple contexts, this will result in an error. Graphs instantiated for launch on the device have additional restrictions which do not apply to host graphs:

  • The graph’s nodes must reside on a single context.
  • The graph can only contain kernel nodes, memcpy nodes, memset nodes, and child graph nodes.
  • The graph cannot be empty and must contain at least one kernel, memcpy, or memset node. Operation-specific restrictions are outlined below.
  • Kernel nodes: Use of CUDA Dynamic Parallelism is not permitted. Cooperative launches are permitted as long as MPS is not in use.
  • Memcpy nodes: Only copies involving device memory and/or pinned device-mapped host memory are permitted. Copies involving CUDA arrays are not permitted. Both operands must be accessible from the current context, and the current context must match the context of other nodes in the graph.

In the event of an error, the result_out and hErrNode_out fields will contain more information about the nature of the error. Possible error reporting includes:

  • GraphInstantiateError, if passed an invalid value or if an unexpected error occurred which is described by the return value of the function. hErrNode_out will be set to NULL.
  • GraphInstantiateInvalidStructure, if the graph structure is invalid. hErrNode_out will be set to one of the offending nodes.
  • GraphInstantiateNodeOperationNotSupported, if the graph is instantiated for device launch but contains a node of an unsupported node type, or a node which performs unsupported operations, such as use of CUDA dynamic parallelism within a kernel node. hErrNode_out will be set to this node.
  • GraphInstantiateMultipleCtxsNotSupported, if the graph is instantiated for device launch but a node’s context differs from that of another node. This error can also be returned if a graph is not instantiated for device launch and it contains kernels which call device-side cudaGraphLaunch() from multiple contexts. hErrNode_out will be set to this node.

If instantiation is successful, result_out will be set to GraphInstantiateSuccess, and hErrNode_out will be set to NULL.

See also: NewGraph, Graph.Instantiate, GraphExec.Close

  • instantiateParams: Instantiation parameters

Errors:

Wraps cuGraphInstantiateWithParams.

func (Graph) Nodes

func (g Graph) Nodes() ([]GraphNode, error)

Nodes returns all nodes in the graph.

func (Graph) NodesBounded

func (g Graph) NodesBounded(limit int) ([]GraphNode, error)

NodesBounded returns the graph's nodes, rejecting counts above limit. The graph must not be changed concurrently. The returned slice owns the complete output array required by cuGraphGetNodes.

Example
_, err := Graph(0).NodesBounded(0)
fmt.Println(err)
Output:
driver: invalid graph node limit 0

func (Graph) ReleaseUserObject

func (g Graph) ReleaseUserObject(object UserObject, count uint32) error

ReleaseUserObject releases a user object reference from a graph.

Releases user object references owned by a graph. See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects.

See also: NewUserObject, UserObject.Retain, UserObject.Release, Graph.RetainUserObject, NewGraph

  • object: The user object to release a reference for
  • count: The number of references to release, typically 1. Must be nonzero and not larger than INT_MAX

Errors:

It is not named Close because Graph has another release method, Destroy.

Wraps cuGraphReleaseUserObject.

func (Graph) RemoveDependencies

func (g Graph) RemoveDependencies(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numDependencies uint) error

RemoveDependencies removes dependency edges from a graph.

The number of dependencies to be removed is defined by numDependencies. Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an edge that does not exist in the graph, with data matching edgeData, results in an error. edgeData is nullable, which is equivalent to passing default (zeroed) data for each edge. Dependencies cannot be removed from graphs which contain allocation or free nodes. Any attempt to do so will return an error.

See also: Graph.AddDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • edgeData: Optional array of edge data. If NULL, edge data is assumed to be default (zeroed)
  • numDependencies: Number of dependencies to be removed

Errors:

Wraps cuGraphRemoveDependencies, bound to the first of cuGraphRemoveDependencies_v2, cuGraphRemoveDependencies that the library exports. On libraries without cuGraphRemoveDependencies_v2, it calls cuGraphRemoveDependencies; a non-nil edgeData returns ErrNotSupported.

func (Graph) RemoveDependenciesV1 deprecated

func (g Graph) RemoveDependenciesV1(from *GraphNode, to *GraphNode, numDependencies uint) error

RemoveDependenciesV1 removes dependency edges from a graph.

The number of dependencies to be removed is defined by numDependencies. Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an edge that does not exist in the graph, with data matching edgeData, results in an error. edgeData is nullable, which is equivalent to passing default (zeroed) data for each edge. Dependencies cannot be removed from graphs which contain allocation or free nodes. Any attempt to do so will return an error.

See also: Graph.AddDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • numDependencies: Number of dependencies to be removed

Errors:

Wraps cuGraphRemoveDependencies_v1, bound as cuGraphRemoveDependencies.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Graph) RemoveDependenciesV2

func (g Graph) RemoveDependenciesV2(from *GraphNode, to *GraphNode, edgeData *GraphEdgeData, numDependencies uint) error

RemoveDependenciesV2 removes dependency edges from a graph.

The number of dependencies to be removed is defined by numDependencies. Elements in from and to at corresponding indices define a dependency. Each node in from and to must belong to hGraph. If numDependencies is 0, elements in from and to will be ignored. Specifying an edge that does not exist in the graph, with data matching edgeData, results in an error. edgeData is nullable, which is equivalent to passing default (zeroed) data for each edge. Dependencies cannot be removed from graphs which contain allocation or free nodes. Any attempt to do so will return an error.

See also: Graph.AddDependencies, Graph.Edges, GraphNode.Dependencies, GraphNode.DependentNodes

Requires CUDA 12.3 (driver r545) or later; see HasGraphRemoveDependenciesV2.

  • from: Array of nodes that provide the dependencies
  • to: Array of dependent nodes
  • edgeData: Optional array of edge data. If NULL, edge data is assumed to be default (zeroed)
  • numDependencies: Number of dependencies to be removed

Errors:

Wraps cuGraphRemoveDependencies, bound as cuGraphRemoveDependencies_v2.

func (Graph) RetainUserObject

func (g Graph) RetainUserObject(object UserObject, count uint32, flags UserobjectretainFlags) error

RetainUserObject retains a reference to a user object from a graph.

Creates or moves user object references that will be owned by a CUDA graph. See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects.

See also: NewUserObject, UserObject.Retain, UserObject.Release, Graph.ReleaseUserObject, NewGraph

  • object: The user object to retain a reference for
  • count: The number of references to add to the graph, typically 1. Must be nonzero and not larger than INT_MAX
  • flags: The optional flag GraphUserObjectMove transfers references from the calling thread, rather than create new references. Pass 0 to create new references

Errors:

Wraps cuGraphRetainUserObject.

func (Graph) RootNodes

func (g Graph) RootNodes(rootNodes *GraphNode, numRootNodes *uint) error

RootNodes returns a graph’s root nodes.

Returns a list of hGraph's root nodes. rootNodes may be NULL, in which case this function will return the number of root nodes in numRootNodes. Otherwise, numRootNodes entries will be filled in. If numRootNodes is higher than the actual number of root nodes, the remaining entries in rootNodes will be set to NULL, and the number of nodes actually obtained will be returned in numRootNodes.

See also: NewGraph, Graph.GetNodes, Graph.Edges, GraphNode.Type, GraphNode.Dependencies, GraphNode.DependentNodes

  • rootNodes: Pointer to return the root nodes
  • numRootNodes: See description

Errors:

Wraps cuGraphGetRootNodes.

type GraphChildGraphNodeOwnership

type GraphChildGraphNodeOwnership int32

GraphChildGraphNodeOwnership represents child graph node ownership.

const (
	// GraphChildGraphOwnershipClone: Default behavior for a child graph node. Child graph is cloned into the parent and memory allocation/free nodes can't be present in the child graph.
	GraphChildGraphOwnershipClone GraphChildGraphNodeOwnership = 0
	// GraphChildGraphOwnershipMove: The child graph is moved to the parent. The handle to the child graph is owned by the parent and will be destroyed when the parent is destroyed. The following restrictions apply to child graphs after they have been moved: Cannot be independently instantiated or destroyed; Cannot be added as a child graph of a separate parent graph; Cannot be used as an argument to [GraphExec.Update]; Cannot have additional memory allocation or free nodes added.
	GraphChildGraphOwnershipMove GraphChildGraphNodeOwnership = 1
	// GraphChildGraphOwnershipInvalid: Invalid ownership flag. Set when params are queried to prevent accidentally reusing the driver-owned graph object
	GraphChildGraphOwnershipInvalid GraphChildGraphNodeOwnership = -1
)

func (GraphChildGraphNodeOwnership) String

String returns the constant name, or a numeric representation for unknown values.

type GraphConditionalNodeType

type GraphConditionalNodeType int32

GraphConditionalNodeType represents conditional node types.

const (
	// GraphCondTypeIf: Conditional 'if/else' Node. Body[0] executed if condition is non-zero. If size == 2, an optional ELSE graph is created and this is executed if the condition is zero.
	GraphCondTypeIf GraphConditionalNodeType = 0
	// GraphCondTypeWhile: Conditional 'while' Node. Body executed repeatedly while condition value is non-zero.
	GraphCondTypeWhile GraphConditionalNodeType = 1
	// GraphCondTypeSwitch: Conditional 'switch' Node. Bodyn is executed once, where 'n' is the value of the condition. If the condition does not match a body index, no body is launched.
	GraphCondTypeSwitch GraphConditionalNodeType = 2
)

func (GraphConditionalNodeType) String

func (e GraphConditionalNodeType) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphDependencyType

type GraphDependencyType int32

GraphDependencyType represents type annotations that can be applied to graph edges as part of GraphEdgeData.

const (
	GraphDependencyTypeDefault GraphDependencyType = 0 // This is an ordinary dependency.
	// GraphDependencyTypeProgrammatic: This dependency type allows the downstream node to use cudaGridDependencySynchronize(). It may only be used between kernel nodes, and must be used with either the CU_GRAPH_KERNEL_NODE_PORT_PROGRAMMATIC or CU_GRAPH_KERNEL_NODE_PORT_LAUNCH_ORDER outgoing port.
	GraphDependencyTypeProgrammatic GraphDependencyType = 1
)

func (GraphDependencyType) String

func (e GraphDependencyType) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphDeviceNode

type GraphDeviceNode uintptr

GraphDeviceNode is CUDA graph device node handle.

type GraphEdgeData

type GraphEdgeData struct {
	FromPort uint8
	ToPort   uint8
	Type     uint8
	Reserved [5]uint8
}

GraphEdgeData represents optional annotation for edges in a CUDA graph.

Note, all edges implicitly have annotations and default to a zero-initialized value if not specified. A zero-initialized struct indicates a standard full serialization of two nodes with memory visibility.

type GraphExec

type GraphExec uintptr

GraphExec is CUDA executable graph.

Graph objects are not thread safe. Serialize all calls that use the same graph, including ones that only read it, such as Graph.Clone and Graph.Instantiate.

func (GraphExec) BatchMemOpNodeSetParams

func (g GraphExec) BatchMemOpNodeSetParams(hNode BatchMemOpNode, nodeParams *BatchMemOpNodeParams) error

BatchMemOpNodeSetParams sets the parameters for a batch mem op node in the given graphExec.

Sets the parameters of a batch mem op node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. The following fields on operations may be modified on an executable graph: op.waitValue.address op.waitValue.value[64] op.waitValue.flags bits corresponding to wait type (i.e. StreamWaitValueFlush bit cannot be modified) op.writeValue.address op.writeValue.value[64] Other fields, such as the context, count or type of operations, and other types of operations such as membars, may not be modified. hNode must not have been removed from the original graph. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. The paramArray inside nodeParams is copied and therefore it can be freed after the call returns.

See also: GraphExec.NodeSetParams, Stream.BatchMemOp, Graph.AddBatchMemOpNode, BatchMemOpNode.Params, BatchMemOpNode.SetParams, Graph.Instantiate

  • hNode: Batch mem op node from the graph from which graphExec was instantiated
  • nodeParams: Updated Parameters to set

Errors:

Wraps cuGraphExecBatchMemOpNodeSetParams.

func (GraphExec) ChildGraphNodeSetParams

func (g GraphExec) ChildGraphNodeSetParams(hNode ChildGraphNode, childGraph Graph) error

ChildGraphNodeSetParams updates node parameters in the child graph node in the given graphExec.

Updates the work represented by hNode in hGraphExec as though the nodes contained in hNode's graph had the parameters contained in childGraph's nodes at instantiation. hNode must remain in the graph which was used to instantiate hGraphExec. Changed edges to and from hNode are ignored. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. The topology of childGraph, as well as the node insertion order, must match that of the graph contained in hNode. See GraphExec.Update for a list of restrictions on what can be updated in an instantiated graph. The update is recursive, so child graph nodes contained within the top level child graph will also be updated.

See also: GraphExec.NodeSetParams, Graph.AddChildGraphNode, ChildGraphNode.Graph, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: Host node from the graph which was used to instantiate graphExec
  • childGraph: The graph supplying the updated parameters

Errors:

Wraps cuGraphExecChildGraphNodeSetParams.

func (*GraphExec) Close

func (g *GraphExec) Close() error

Close destroys an executable graph.

Destroys the executable graph specified by hGraphExec, as well as all of its executable nodes. If the executable graph is in-flight, it will not be terminated, but rather freed asynchronously on completion.

See also: Graph.Instantiate, GraphExec.Upload, GraphExec.Launch

Errors:

If g is zero, Close returns nil. Otherwise Close sets g to zero when the call succeeds and leaves it unchanged when it fails. Only g is zeroed: a copy of it still refers to the released object.

Wraps cuGraphExecDestroy.

func (GraphExec) EventRecordNodeSetEvent

func (g GraphExec) EventRecordNodeSetEvent(hNode EventRecordNode, event Event) error

EventRecordNodeSetEvent sets the event for an event record node in the given graphExec.

Sets the event of an event record node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call.

See also: GraphExec.NodeSetParams, Graph.AddEventRecordNode, EventRecordNode.Event, EventWaitNode.SetEvent, Event.RecordWithFlags, Stream.WaitEvent, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: event record node from the graph from which graphExec was instantiated
  • event: Updated event to use

Errors:

Wraps cuGraphExecEventRecordNodeSetEvent.

func (GraphExec) EventWaitNodeSetEvent

func (g GraphExec) EventWaitNodeSetEvent(hNode EventWaitNode, event Event) error

EventWaitNodeSetEvent sets the event for an event wait node in the given graphExec.

Sets the event of an event wait node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call.

See also: GraphExec.NodeSetParams, Graph.AddEventWaitNode, EventWaitNode.Event, EventRecordNode.SetEvent, Event.RecordWithFlags, Stream.WaitEvent, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: event wait node from the graph from which graphExec was instantiated
  • event: Updated event to use

Errors:

Wraps cuGraphExecEventWaitNodeSetEvent.

func (GraphExec) ExternalSemaphoresSignalNodeSetParams

func (g GraphExec) ExternalSemaphoresSignalNodeSetParams(hNode ExternalSemaphoresSignalNode, nodeParams *ExtSemSignalNodeParams) error

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

Sets the parameters of an external semaphore signal node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. hNode must not have been removed from the original graph. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. Changing nodeParams->numExtSems is not supported.

See also: GraphExec.NodeSetParams, Graph.AddExternalSemaphoresSignalNode, ImportExternalSemaphore, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: semaphore signal node from the graph from which graphExec was instantiated
  • nodeParams: Updated Parameters to set

Errors:

Wraps cuGraphExecExternalSemaphoresSignalNodeSetParams.

func (GraphExec) ExternalSemaphoresWaitNodeSetParams

func (g GraphExec) ExternalSemaphoresWaitNodeSetParams(hNode ExternalSemaphoresWaitNode, nodeParams *ExtSemWaitNodeParams) error

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

Sets the parameters of an external semaphore wait node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. hNode must not have been removed from the original graph. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. Changing nodeParams->numExtSems is not supported.

See also: GraphExec.NodeSetParams, Graph.AddExternalSemaphoresWaitNode, ImportExternalSemaphore, Stream.SignalExternalSemaphoresAsync, Stream.WaitExternalSemaphoresAsync, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: semaphore wait node from the graph from which graphExec was instantiated
  • nodeParams: Updated Parameters to set

Errors:

Wraps cuGraphExecExternalSemaphoresWaitNodeSetParams.

func (GraphExec) Flags

func (g GraphExec) Flags() (uint64, error)

Flags queries the instantiation flags of an executable graph.

Returns the flags that were passed to instantiation for the given executable graph. GraphInstantiateFlagUpload will not be returned by this API as it does not affect the resulting executable graph.

See also: Graph.Instantiate, Graph.InstantiateWithParams

Errors:

Wraps cuGraphExecGetFlags.

func (GraphExec) HostNodeSetParams

func (g GraphExec) HostNodeSetParams(hNode HostNode, nodeParams *HostNodeParams) error

HostNodeSetParams sets the parameters for a host node in the given graphExec.

Updates the work represented by hNode in hGraphExec as though hNode had contained nodeParams at instantiation. hNode must remain in the graph which was used to instantiate hGraphExec. Changed edges to and from hNode are ignored. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call.

See also: GraphExec.NodeSetParams, Graph.AddHostNode, HostNode.SetParams, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: Host node from the graph which was used to instantiate graphExec
  • nodeParams: The updated parameters to set

Errors:

Wraps cuGraphExecHostNodeSetParams.

func (GraphExec) Id

func (g GraphExec) Id() (uint32, error)

Id returns the id of a given graph exec.

Returns the id of hGraphExec. The result will match that referenced by Graph.DebugDotPrint.

See also: Graph.GetNodes, Graph.DebugDotPrint GraphNode.ContainingGraph GraphNode.LocalId GraphNode.ToolsId Graph.Id

Requires CUDA 13.1 (driver r590) or later; see HasGraphExecGetId.

Errors:

Wraps cuGraphExecGetId.

func (GraphExec) KernelNodeSetParams

func (g GraphExec) KernelNodeSetParams(hNode KernelNode, nodeParams *KernelNodeParams) error

KernelNodeSetParams sets the parameters for a kernel node in the given graphExec.

Sets the parameters of a kernel node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. hNode must not have been removed from the original graph. All nodeParams fields may change, but the following restrictions apply to func updates:

  • The owning context of the function cannot change.
  • A node whose function originally did not use CUDA dynamic parallelism cannot be updated to a function which uses CDP
  • A node whose function originally did not make device-side update calls cannot be updated to a function which makes device-side update calls.
  • If hGraphExec was not instantiated for device launch, a node whose function originally did not use device-side cudaGraphLaunch() cannot be updated to a function which uses device-side cudaGraphLaunch() unless the node resides on the same context as nodes which contained such calls at instantiate-time. If no such calls were present at instantiation, these updates cannot be performed at all.

The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. If hNode is a device-updatable kernel node, the next upload/launch of hGraphExec will overwrite any previous device-side updates. Additionally, applying host updates to a device-updatable kernel node while it is being updated from the device will result in undefined behavior.

See also: GraphExec.NodeSetParams, Graph.AddKernelNode, KernelNode.SetParams, GraphExec.MemcpyNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: kernel node from the graph from which graphExec was instantiated
  • nodeParams: Updated Parameters to set

Errors:

Wraps cuGraphExecKernelNodeSetParams, bound as cuGraphExecKernelNodeSetParams_v2.

func (GraphExec) Launch

func (g GraphExec) Launch(hStream Stream) error

Launch launches an executable graph in a stream.

Executes hGraphExec in hStream. Only one instance of hGraphExec may be executing at a time. Each launch is ordered behind both any previous work in hStream and any previous launches of hGraphExec. To execute a graph concurrently, it must be instantiated multiple times into multiple executable graphs. If any allocations created by hGraphExec remain unfreed (from a previous launch) and hGraphExec was not instantiated with GraphInstantiateFlagAutoFreeOnLaunch, the launch will fail with ErrInvalidValue.

See also: Graph.Instantiate, GraphExec.Upload, GraphExec.Close

  • hStream: Stream in which to launch the graph

Errors:

Wraps cuGraphLaunch.

func (GraphExec) MemcpyNodeSetParams

func (g GraphExec) MemcpyNodeSetParams(hNode MemcpyNode, copyParams *Memcpy3d, ctx Context) error

MemcpyNodeSetParams sets the parameters for a memcpy node in the given graphExec.

Updates the work represented by hNode in hGraphExec as though hNode had contained copyParams at instantiation. hNode must remain in the graph which was used to instantiate hGraphExec. Changed edges to and from hNode are ignored. The source and destination memory in copyParams must be allocated from the same contexts as the original source and destination memory. Both the instantiation-time memory operands and the memory operands in copyParams must be 1-dimensional. Zero-length operations are not supported. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. Returns ErrInvalidValue if the memory operands’ mappings changed or either the original or new memory operands are multidimensional.

See also: GraphExec.NodeSetParams, Graph.AddMemcpyNode, MemcpyNode.SetParams, GraphExec.KernelNodeSetParams, GraphExec.MemsetNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: Memcpy node from the graph which was used to instantiate graphExec
  • copyParams: The updated parameters to set
  • ctx: Context on which to run the node

Errors:

Wraps cuGraphExecMemcpyNodeSetParams.

func (GraphExec) MemsetNodeSetParams

func (g GraphExec) MemsetNodeSetParams(hNode MemsetNode, memsetParams *MemsetNodeParams, ctx Context) error

MemsetNodeSetParams sets the parameters for a memset node in the given graphExec.

Updates the work represented by hNode in hGraphExec as though hNode had contained memsetParams at instantiation. hNode must remain in the graph which was used to instantiate hGraphExec. Changed edges to and from hNode are ignored. Zero sized operations are not supported. The new destination pointer in memsetParams must be to the same kind of allocation as the original destination pointer and have the same context association and device mapping as the original destination pointer. Both the value and pointer address may be updated. Changing other aspects of the memset (width, height, element size or pitch) may cause the update to be rejected. Specifically, for 2d memsets, all dimension changes are rejected. For 1d memsets, changes in height are explicitly rejected and other changes are opportunistically allowed if the resulting work maps onto the work resources already allocated for the node. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call.

See also: GraphExec.NodeSetParams, Graph.AddMemsetNode, MemsetNode.SetParams, GraphExec.KernelNodeSetParams, GraphExec.MemcpyNodeSetParams, GraphExec.HostNodeSetParams, GraphExec.ChildGraphNodeSetParams, GraphExec.EventRecordNodeSetEvent, GraphExec.EventWaitNodeSetEvent, GraphExec.ExternalSemaphoresSignalNodeSetParams, GraphExec.ExternalSemaphoresWaitNodeSetParams, GraphExec.Update, Graph.Instantiate

  • hNode: Memset node from the graph which was used to instantiate graphExec
  • memsetParams: The updated parameters to set
  • ctx: Context on which to run the node

Errors:

Wraps cuGraphExecMemsetNodeSetParams.

func (GraphExec) NodeSetParams

func (g GraphExec) NodeSetParams(hNode GraphNode, nodeParams *GraphNodeParams) error

NodeSetParams updates a graph node’s parameters in an instantiated graph.

Sets the parameters of a node in an executable graph hGraphExec. The node is identified by the corresponding node hNode in the non-executable graph from which the executable graph was instantiated. hNode must not have been removed from the original graph. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. Allowed changes to parameters on executable graphs are as follows:

  • kernel: See GraphExec.KernelNodeSetParams
  • memcpy: Addresses for 1-dimensional copies if allocated in same context; see GraphExec.MemcpyNodeSetParams
  • memset: Addresses for 1-dimensional memsets if allocated in same context; see GraphExec.MemsetNodeSetParams
  • host: Context changes are not allowed
  • child graph: Topology must match and restrictions apply recursively; see GraphExec.Update
  • event wait: Unrestricted
  • event record: Event only, context changes are not allowed
  • external semaphore signal: Number of semaphore operations and context cannot change
  • external semaphore wait: Number of semaphore operations and context cannot change
  • memory allocation: API unsupported
  • memory free: API unsupported
  • batch memops: Addresses, values, and operation type for wait operations; see GraphExec.BatchMemOpNodeSetParams

See also: Graph.AddNode, GraphNode.SetParams GraphExec.Update, Graph.Instantiate

  • hNode: Corresponding node from the graph from which graphExec was instantiated
  • nodeParams: Updated Parameters to set

Errors:

Wraps cuGraphExecNodeSetParams.

func (GraphExec) Update

func (g GraphExec) Update(hGraph Graph, resultInfo *GraphExecUpdateResultInfo) error

Update checks whether an executable graph can be updated with a graph and performs the update if possible.

Updates the node parameters in the instantiated graph specified by hGraphExec with the node parameters in a topologically identical graph specified by hGraph. Limitations:

  • Kernel nodes: The owning context of the function cannot change. A node whose function originally did not use CUDA dynamic parallelism cannot be updated to a function which uses CDP. A node whose function originally did not make device-side update calls cannot be updated to a function which makes device-side update calls. A cooperative node cannot be updated to a non-cooperative node, and vice-versa. If the graph was instantiated with GraphInstantiateFlagUseNodePriority, the priority attribute cannot change. Equality is checked on the originally requested priority values, before they are clamped to the device’s supported range. If hGraphExec was not instantiated for device launch, a node whose function originally did not use device-side cudaGraphLaunch() cannot be updated to a function which uses device-side cudaGraphLaunch() unless the node resides on the same context as nodes which contained such calls at instantiate-time. If no such calls were present at instantiation, these updates cannot be performed at all. Neither hGraph nor hGraphExec may contain device-updatable kernel nodes.
  • Memset and memcpy nodes: The CUDA device(s) to which the operand(s) was allocated/mapped cannot change. The source/destination memory must be allocated from the same contexts as the original source/destination memory. For 2d memsets, only address and assigned value may be updated. For 1d memsets, updating dimensions is also allowed, but may fail if the resulting operation doesn’t map onto the work resources already allocated for the node.
  • Additional memcpy node restrictions: Changing either the source or destination memory type(i.e. MemoryTypeDevice, MemoryTypeArray, etc.) is not supported.
  • External semaphore wait nodes and record nodes: Changing the number of semaphores is not supported.
  • Conditional nodes: Changing node parameters is not supported. Changing parameters of nodes within the conditional body graph is subject to the rules above. Conditional handle flags and default values are updated as part of the graph update.

Note: The API may add further restrictions in future releases. The return code should always be checked. GraphExec.Update sets the result member of resultInfo to GraphExecUpdateErrorTopologyChanged under the following conditions:

  • The count of nodes directly in hGraphExec and hGraph differ, in which case resultInfo->errorNode is set to NULL.
  • hGraph has more exit nodes than hGraph, in which case resultInfo->errorNode is set to one of the exit nodes in hGraph.
  • A node in hGraph has a different number of dependencies than the node from hGraphExec it is paired with, in which case resultInfo->errorNode is set to the node from hGraph.
  • A node in hGraph has a dependency that does not match with the corresponding dependency of the paired node from hGraphExec. resultInfo->errorNode will be set to the node from hGraph. resultInfo->errorFromNode will be set to the mismatched dependency. The dependencies are paired based on edge order and a dependency does not match when the nodes are already paired based on other edges examined in the graph.

GraphExec.Update sets the result member of resultInfo to:

If the update fails for a reason not listed above, the result member of resultInfo will be set to GraphExecUpdateError. If the update succeeds, the result member will be set to GraphExecUpdateSuccess. GraphExec.Update returns Success when the updated was performed successfully. It returns ErrGraphExecUpdateFailure if the graph update was not performed because it included changes which violated constraints specific to instantiated graph update.

See also: Graph.Instantiate

  • hGraph: The graph containing the updated parameters
  • resultInfo: the error info structure

Errors:

Wraps cuGraphExecUpdate, bound as cuGraphExecUpdate_v2.

func (GraphExec) Upload

func (g GraphExec) Upload(hStream Stream) error

Upload uploads an executable graph in a stream.

Uploads hGraphExec to the device in hStream without executing it. Uploads of the same hGraphExec will be serialized. Each upload is ordered behind both any previous work in hStream and any previous launches of hGraphExec. Uses memory cached by stream to back the allocations owned by hGraphExec.

See also: Graph.Instantiate, GraphExec.Launch, GraphExec.Close

  • hStream: Stream in which to upload the graph

Errors:

Wraps cuGraphUpload.

type GraphExecUpdateResult

type GraphExecUpdateResult int32

GraphExecUpdateResult represents CUDA Graph Update error types.

const (
	GraphExecUpdateSuccess GraphExecUpdateResult = 0x0 // The update succeeded
	// GraphExecUpdateError: The update failed for an unexpected reason which is described in the return value of the function
	GraphExecUpdateError                GraphExecUpdateResult = 0x1
	GraphExecUpdateErrorTopologyChanged GraphExecUpdateResult = 0x2 // The update failed because the topology changed
	GraphExecUpdateErrorNodeTypeChanged GraphExecUpdateResult = 0x3 // The update failed because a node type changed
	// GraphExecUpdateErrorFunctionChanged: The update failed because the function of a kernel node changed (CUDA driver < 11.2)
	GraphExecUpdateErrorFunctionChanged GraphExecUpdateResult = 0x4
	// GraphExecUpdateErrorParametersChanged: The update failed because the parameters changed in a way that is not supported
	GraphExecUpdateErrorParametersChanged GraphExecUpdateResult = 0x5
	// GraphExecUpdateErrorNotSupported: The update failed because something about the node is not supported
	GraphExecUpdateErrorNotSupported GraphExecUpdateResult = 0x6
	// GraphExecUpdateErrorUnsupportedFunctionChange: The update failed because the function of a kernel node changed in an unsupported way
	GraphExecUpdateErrorUnsupportedFunctionChange GraphExecUpdateResult = 0x7
	// GraphExecUpdateErrorAttributesChanged: The update failed because the node attributes changed in a way that is not supported
	GraphExecUpdateErrorAttributesChanged GraphExecUpdateResult = 0x8
)

func (GraphExecUpdateResult) String

func (e GraphExecUpdateResult) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphExecUpdateResultInfo

type GraphExecUpdateResultInfo struct {
	Result        GraphExecUpdateResult
	ErrorNode     GraphNode
	ErrorFromNode GraphNode
}

GraphExecUpdateResultInfo represents result information returned by GraphExec.Update.

type GraphExecUpdateResultInfoV1

type GraphExecUpdateResultInfoV1 = GraphExecUpdateResultInfo

GraphExecUpdateResultInfoV1 is an alias for GraphExecUpdateResultInfo.

type GraphInstantiateParams

type GraphInstantiateParams struct {
	// Instantiation flags
	Flags uint64
	// Upload stream
	HUploadStream Stream
	// The node which caused instantiation to fail, if any
	HErrNodeOut GraphNode
	// Whether instantiation was successful. If it failed, the reason why
	ResultOut GraphInstantiateResult
}

GraphInstantiateParams represents graph instantiation parameters.

type GraphInstantiateResult

type GraphInstantiateResult int32

GraphInstantiateResult represents graph instantiation results.

const (
	GraphInstantiateSuccess GraphInstantiateResult = 0 // Instantiation succeeded
	// GraphInstantiateError: Instantiation failed for an unexpected reason which is described in the return value of the function
	GraphInstantiateError GraphInstantiateResult = 1
	// GraphInstantiateInvalidStructure: Instantiation failed due to invalid structure, such as cycles
	GraphInstantiateInvalidStructure GraphInstantiateResult = 2
	// GraphInstantiateNodeOperationNotSupported: Instantiation for device launch failed because the graph contained an unsupported operation
	GraphInstantiateNodeOperationNotSupported GraphInstantiateResult = 3
	// GraphInstantiateMultipleCtxsNotSupported: Instantiation for device launch failed due to the nodes belonging to different contexts
	GraphInstantiateMultipleCtxsNotSupported GraphInstantiateResult = 4
	// GraphInstantiateConditionalHandleUnused: One or more conditional handles are not associated with conditional nodes
	GraphInstantiateConditionalHandleUnused GraphInstantiateResult = 5
)

func (GraphInstantiateResult) String

func (e GraphInstantiateResult) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphNode

type GraphNode uintptr

GraphNode is CUDA graph node.

A node follows the thread-safety rule of its Graph.

func (*GraphNode) Close

func (g *GraphNode) Close() error

Close removes a node from the graph.

Removes hNode from its graph. This operation also severs any dependencies of other nodes on hNode and vice versa. Nodes which belong to a graph which contains allocation or free nodes cannot be destroyed. Any attempt to do so will return an error.

See also: Graph.AddChildGraphNode, Graph.AddEmptyNode, Graph.AddKernelNode, Graph.AddHostNode, Graph.AddMemcpyNode, Graph.AddMemsetNode

Errors:

If g is zero, Close returns nil. Otherwise Close sets g to zero when the call succeeds and leaves it unchanged when it fails. Only g is zeroed: a copy of it still refers to the released object.

Wraps cuGraphDestroyNode.

func (GraphNode) ContainingGraph

func (g GraphNode) ContainingGraph() (Graph, error)

ContainingGraph returns the graph that contains a given graph node.

Returns the graph that contains hNode. If hNode is in a child graph, the child graph it is in is returned.

See also: Graph.GetNodes, Graph.DebugDotPrint GraphNode.LocalId GraphNode.ToolsId Graph.Id GraphExec.Id

Requires CUDA 13.1 (driver r590) or later; see HasGraphNodeGetContainingGraph.

Errors:

Wraps cuGraphNodeGetContainingGraph.

func (GraphNode) Dependencies

func (g GraphNode) Dependencies(dependencies *GraphNode, edgeData *GraphEdgeData, numDependencies *uint) error

Dependencies returns a node’s dependencies.

Returns a list of node's dependencies. dependencies may be NULL, in which case this function will return the number of dependencies in numDependencies. Otherwise, numDependencies entries will be filled in. If numDependencies is higher than the actual number of dependencies, the remaining entries in dependencies will be set to NULL, and the number of nodes actually obtained will be returned in numDependencies. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependencies must be as well.

See also: GraphNode.DependentNodes, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

  • dependencies: Pointer to return the dependencies
  • edgeData: Optional array to return edge data for each dependency
  • numDependencies: See description

Errors:

Wraps cuGraphNodeGetDependencies, bound to the first of cuGraphNodeGetDependencies_v2, cuGraphNodeGetDependencies that the library exports. On libraries without cuGraphNodeGetDependencies_v2, it calls cuGraphNodeGetDependencies; a non-nil edgeData returns ErrNotSupported.

func (GraphNode) DependenciesV1 deprecated

func (g GraphNode) DependenciesV1(dependencies *GraphNode, numDependencies *uint) error

DependenciesV1 returns a node’s dependencies.

Returns a list of node's dependencies. dependencies may be NULL, in which case this function will return the number of dependencies in numDependencies. Otherwise, numDependencies entries will be filled in. If numDependencies is higher than the actual number of dependencies, the remaining entries in dependencies will be set to NULL, and the number of nodes actually obtained will be returned in numDependencies. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependencies must be as well.

See also: GraphNode.DependentNodes, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

  • dependencies: Pointer to return the dependencies
  • numDependencies: See description

Errors:

Wraps cuGraphNodeGetDependencies_v1, bound as cuGraphNodeGetDependencies.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (GraphNode) DependenciesV2

func (g GraphNode) DependenciesV2(dependencies *GraphNode, edgeData *GraphEdgeData, numDependencies *uint) error

DependenciesV2 returns a node’s dependencies.

Returns a list of node's dependencies. dependencies may be NULL, in which case this function will return the number of dependencies in numDependencies. Otherwise, numDependencies entries will be filled in. If numDependencies is higher than the actual number of dependencies, the remaining entries in dependencies will be set to NULL, and the number of nodes actually obtained will be returned in numDependencies. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependencies must be as well.

See also: GraphNode.DependentNodes, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

Requires CUDA 12.3 (driver r545) or later; see HasGraphNodeGetDependenciesV2.

  • dependencies: Pointer to return the dependencies
  • edgeData: Optional array to return edge data for each dependency
  • numDependencies: See description

Errors:

Wraps cuGraphNodeGetDependencies, bound as cuGraphNodeGetDependencies_v2.

func (GraphNode) DependentNodes

func (g GraphNode) DependentNodes(dependentNodes *GraphNode, edgeData *GraphEdgeData, numDependentNodes *uint) error

DependentNodes returns a node’s dependent nodes.

Returns a list of node's dependent nodes. dependentNodes may be NULL, in which case this function will return the number of dependent nodes in numDependentNodes. Otherwise, numDependentNodes entries will be filled in. If numDependentNodes is higher than the actual number of dependent nodes, the remaining entries in dependentNodes will be set to NULL, and the number of nodes actually obtained will be returned in numDependentNodes. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependentNodes must be as well.

See also: GraphNode.Dependencies, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

  • dependentNodes: Pointer to return the dependent nodes
  • edgeData: Optional pointer to return edge data for dependent nodes
  • numDependentNodes: See description

Errors:

Wraps cuGraphNodeGetDependentNodes, bound to the first of cuGraphNodeGetDependentNodes_v2, cuGraphNodeGetDependentNodes that the library exports. On libraries without cuGraphNodeGetDependentNodes_v2, it calls cuGraphNodeGetDependentNodes; a non-nil edgeData returns ErrNotSupported.

func (GraphNode) DependentNodesV1 deprecated

func (g GraphNode) DependentNodesV1(dependentNodes *GraphNode, numDependentNodes *uint) error

DependentNodesV1 returns a node’s dependent nodes.

Returns a list of node's dependent nodes. dependentNodes may be NULL, in which case this function will return the number of dependent nodes in numDependentNodes. Otherwise, numDependentNodes entries will be filled in. If numDependentNodes is higher than the actual number of dependent nodes, the remaining entries in dependentNodes will be set to NULL, and the number of nodes actually obtained will be returned in numDependentNodes. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependentNodes must be as well.

See also: GraphNode.Dependencies, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

  • dependentNodes: Pointer to return the dependent nodes
  • numDependentNodes: See description

Errors:

Wraps cuGraphNodeGetDependentNodes_v1, bound as cuGraphNodeGetDependentNodes.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (GraphNode) DependentNodesV2

func (g GraphNode) DependentNodesV2(dependentNodes *GraphNode, edgeData *GraphEdgeData, numDependentNodes *uint) error

DependentNodesV2 returns a node’s dependent nodes.

Returns a list of node's dependent nodes. dependentNodes may be NULL, in which case this function will return the number of dependent nodes in numDependentNodes. Otherwise, numDependentNodes entries will be filled in. If numDependentNodes is higher than the actual number of dependent nodes, the remaining entries in dependentNodes will be set to NULL, and the number of nodes actually obtained will be returned in numDependentNodes. Note that if an edge has non-zero (non-default) edge data and edgeData is NULL, this API will return ErrLossyQuery. If edgeData is non-NULL, then dependentNodes must be as well.

See also: GraphNode.Dependencies, Graph.GetNodes, Graph.RootNodes, Graph.Edges, Graph.AddDependencies, Graph.RemoveDependencies

Requires CUDA 12.3 (driver r545) or later; see HasGraphNodeGetDependentNodesV2.

  • dependentNodes: Pointer to return the dependent nodes
  • edgeData: Optional pointer to return edge data for dependent nodes
  • numDependentNodes: See description

Errors:

Wraps cuGraphNodeGetDependentNodes, bound as cuGraphNodeGetDependentNodes_v2.

func (GraphNode) Enabled

func (g GraphNode) Enabled(hGraphExec GraphExec) (uint32, error)

Enabled queries whether a node in the given graphExec is enabled.

Sets isEnabled to 1 if hNode is enabled, or 0 if hNode is disabled. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. hNode must not have been removed from the original graph.

Note: Currently only kernel, memset and memcpy nodes are supported.

Note: This function will not reflect device-side updates for device-updatable kernel nodes.

See also: GraphNode.SetEnabled, GraphExec.Update, Graph.Instantiate GraphExec.Launch

  • hGraphExec: The executable graph in which to set the specified node

Errors:

Wraps cuGraphNodeGetEnabled.

func (GraphNode) FindInClone

func (g GraphNode) FindInClone(hClonedGraph Graph) (GraphNode, error)

FindInClone finds a cloned version of a node.

This function returns the node in hClonedGraph corresponding to hOriginalNode in the original graph. hClonedGraph must have been cloned from hOriginalGraph via Graph.Clone. hOriginalNode must have been in hOriginalGraph at the time of the call to Graph.Clone, and the corresponding cloned node in hClonedGraph must not have been removed. The cloned node is then returned via phClonedNode.

See also: Graph.Clone

  • hClonedGraph: Cloned graph to query

Errors:

Wraps cuGraphNodeFindInClone.

func (GraphNode) LocalId

func (g GraphNode) LocalId() (uint32, error)

LocalId returns the local node id of a given graph node.

Returns the node id of hNode. The nodeId matches that referenced by Graph.DebugDotPrint. The local nodeId and graphId together can uniquely identify the node.

See also: Graph.GetNodes, Graph.DebugDotPrint GraphNode.ContainingGraph GraphNode.ToolsId Graph.Id GraphExec.Id

Requires CUDA 13.1 (driver r590) or later; see HasGraphNodeGetLocalId.

Errors:

Wraps cuGraphNodeGetLocalId.

func (GraphNode) Params

func (g GraphNode) Params() (GraphNodeParams, error)

Params returns a graph node’s parameters.

Returns the parameters of graph node hNode. Any pointers returned point to driver-owned memory associated with the node. This memory remains valid until the node is destroyed. Any memory pointed to from *nodeParams must not be modified. The returned parameters are a description of the node, but may not be identical to the struct provided at creation and may not be suitable for direct creation of identical nodes. This is because parameters may be partially unspecified and filled in by the driver at creation, may reference non-copyable handles, or may describe ownership semantics or other parameters that govern behavior of node creation but are not part of the final functional descriptor.

See also: GraphNode.SetParams, Graph.AddNode, GraphExec.NodeSetParams

Requires CUDA 13.2 (driver r595) or later; see HasGraphNodeGetParams.

Errors:

Wraps cuGraphNodeGetParams.

func (GraphNode) SetEnabled

func (g GraphNode) SetEnabled(hGraphExec GraphExec, isEnabled uint32) error

SetEnabled enables or disables the specified node in the given graphExec.

Sets hNode to be either enabled or disabled. Disabled nodes are functionally equivalent to empty nodes until they are reenabled. Existing node parameters are not affected by disabling/enabling the node. The node is identified by the corresponding node hNode in the non-executable graph, from which the executable graph was instantiated. hNode must not have been removed from the original graph. The modifications only affect future launches of hGraphExec. Already enqueued or running launches of hGraphExec are not affected by this call. hNode is also not modified by this call. If hNode is a device-updatable kernel node, the next upload/launch of hGraphExec will overwrite any previous device-side updates. Additionally, applying host updates to a device-updatable kernel node while it is being updated from the device will result in undefined behavior.

Note: Currently only kernel, memset and memcpy nodes are supported.

See also: GraphNode.Enabled, GraphExec.Update, Graph.Instantiate GraphExec.Launch

  • hGraphExec: The executable graph in which to set the specified node
  • isEnabled: Node is enabled if != 0, otherwise the node is disabled

Errors:

Wraps cuGraphNodeSetEnabled.

func (GraphNode) SetParams

func (g GraphNode) SetParams(nodeParams *GraphNodeParams) error

SetParams updates a graph node’s parameters.

Sets the parameters of graph node hNode to nodeParams. The node type specified by nodeParams->type must match the type of hNode. nodeParams must be fully initialized and all unused bytes (reserved, padding) zeroed. Modifying parameters is not supported for node types GraphNodeTypeMemAlloc and GraphNodeTypeMemFree. For kernel nodes, if both the kernel node’s Function and ctx are non-NULL, the underlying device context of ctx must match the device context that the Function was loaded into; otherwise the call returns ErrInvalidContext.

See also: Graph.AddNodeV3, GraphNode.Params, GraphExec.NodeSetParams

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphNodeSetParams, bound to the first of cuGraphNodeSetParams_v2, cuGraphNodeSetParams that the library exports.

func (GraphNode) SetParamsV1

func (g GraphNode) SetParamsV1(nodeParams *GraphNodeParams) error

SetParamsV1 updates a graph node’s parameters.

Sets the parameters of graph node hNode to nodeParams. The node type specified by nodeParams->type must match the type of hNode. nodeParams must be fully initialized and all unused bytes (reserved, padding) zeroed. Modifying parameters is not supported for node types GraphNodeTypeMemAlloc and GraphNodeTypeMemFree.

See also: Graph.AddNode, GraphNode.Params, GraphExec.NodeSetParams

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphNodeSetParams.

func (GraphNode) SetParamsV2

func (g GraphNode) SetParamsV2(nodeParams *GraphNodeParams) error

SetParamsV2 updates a graph node’s parameters.

Sets the parameters of graph node hNode to nodeParams. The node type specified by nodeParams->type must match the type of hNode. nodeParams must be fully initialized and all unused bytes (reserved, padding) zeroed. Modifying parameters is not supported for node types GraphNodeTypeMemAlloc and GraphNodeTypeMemFree. For kernel nodes, if both the kernel node’s Function and ctx are non-NULL, the underlying device context of ctx must match the device context that the Function was loaded into; otherwise the call returns ErrInvalidContext.

See also: Graph.AddNodeV3, GraphNode.Params, GraphExec.NodeSetParams

Requires CUDA 13.4 (driver r615) or later; see HasGraphNodeSetParamsV2.

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphNodeSetParams_v2.

func (GraphNode) ToolsId

func (g GraphNode) ToolsId() (uint64, error)

ToolsId returns an id used by tools to identify a given node.

See also: Graph.GetNodes, Graph.DebugDotPrint GraphNode.ContainingGraph GraphNode.LocalId Graph.Id GraphExec.Id

Requires CUDA 13.1 (driver r590) or later; see HasGraphNodeGetToolsId.

Errors:

Wraps cuGraphNodeGetToolsId.

type GraphNodeParams

type GraphNodeParams struct {
	// Type of the node
	Type GraphNodeType
	// Reserved. Must be zero.
	Reserved0      [3]int32
	AnonymousUnion [29]uint64
	// Reserved bytes. Must be zero.
	Reserved2 int64
}

GraphNodeParams represents graph node parameters.

See Graph.AddNode.

func (*GraphNodeParams) Alloc

Alloc returns a pointer to the alloc member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) AsBytes

func (g *GraphNodeParams) AsBytes() *[232]byte

AsBytes returns a pointer to the asBytes member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Conditional

func (g *GraphNodeParams) Conditional() *ConditionalNodeParams

Conditional returns a pointer to the conditional member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) EventRecord

func (g *GraphNodeParams) EventRecord() *EventRecordNodeParams

EventRecord returns a pointer to the eventRecord member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) EventWait

func (g *GraphNodeParams) EventWait() *EventWaitNodeParams

EventWait returns a pointer to the eventWait member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) ExtSemSignal

func (g *GraphNodeParams) ExtSemSignal() *ExtSemSignalNodeParamsV2

ExtSemSignal returns a pointer to the extSemSignal member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) ExtSemWait

func (g *GraphNodeParams) ExtSemWait() *ExtSemWaitNodeParamsV2

ExtSemWait returns a pointer to the extSemWait member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) FabricCpyBatch

func (g *GraphNodeParams) FabricCpyBatch() *FabricCpyBatchNodeParams

FabricCpyBatch returns a pointer to the fabricCpyBatch member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Free

Free returns a pointer to the free member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Graph

Graph returns a pointer to the graph member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Host

func (g *GraphNodeParams) Host() *HostNodeParamsV2

Host returns a pointer to the host member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Kernel

func (g *GraphNodeParams) Kernel() *KernelNodeParamsV3

Kernel returns a pointer to the kernel member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) MemOp

MemOp returns a pointer to the memOp member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Memcpy

func (g *GraphNodeParams) Memcpy() *MemcpyNodeParams

Memcpy returns a pointer to the memcpy member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) MemcpyBatch

func (g *GraphNodeParams) MemcpyBatch() *MemcpyBatchNodeParams

MemcpyBatch returns a pointer to the memcpyBatch member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Memset

func (g *GraphNodeParams) Memset() *MemsetNodeParamsV2

Memset returns a pointer to the memset member of CUgraphNodeParams, which shares its storage with every other member of the union.

func (*GraphNodeParams) Reserved1

func (g *GraphNodeParams) Reserved1() *[29]int64

Reserved1 returns a pointer to the reserved1 member of CUgraphNodeParams, which shares its storage with every other member of the union.

type GraphNodeType

type GraphNodeType int32

GraphNodeType represents graph node types.

const (
	GraphNodeTypeKernel         GraphNodeType = 0  // GPU kernel node
	GraphNodeTypeMemcpy         GraphNodeType = 1  // Memcpy node
	GraphNodeTypeMemset         GraphNodeType = 2  // Memset node
	GraphNodeTypeHost           GraphNodeType = 3  // Host (executable) node
	GraphNodeTypeGraph          GraphNodeType = 4  // Node which executes an embedded graph
	GraphNodeTypeEmpty          GraphNodeType = 5  // Empty (no-op) node
	GraphNodeTypeWaitEvent      GraphNodeType = 6  // External event wait node
	GraphNodeTypeEventRecord    GraphNodeType = 7  // External event record node
	GraphNodeTypeExtSemasSignal GraphNodeType = 8  // External semaphore signal node
	GraphNodeTypeExtSemasWait   GraphNodeType = 9  // External semaphore wait node
	GraphNodeTypeMemAlloc       GraphNodeType = 10 // Memory Allocation Node
	GraphNodeTypeMemFree        GraphNodeType = 11 // Memory Free Node
	// GraphNodeTypeBatchMemOp: Batch MemOp Node See [Stream.BatchMemOp] and [StreamBatchMemOpType] for what these nodes can do.
	GraphNodeTypeBatchMemOp GraphNodeType = 12
	// GraphNodeTypeConditional: Conditional Node. May be used to implement a conditional execution path or loop inside of a graph. The graph(s) contained within the body of the conditional node can be selectively executed or iterated upon based on the value of a conditional variable. Handles must be created in advance of creating the node using [Graph.ConditionalHandleCreate]. The following restrictions apply to graphs which contain conditional nodes: The graph cannot be used in a child node. Only one instantiation of the graph may exist at any point in time. The graph cannot be cloned. To set the control value, supply a default value when creating the handle and/or call cudaGraphSetConditional from device code.
	GraphNodeTypeConditional    GraphNodeType = 13
	GraphNodeTypeMemcpyBatch    GraphNodeType = 14 // Batch Memcpy Node
	GraphNodeTypeReserved16     GraphNodeType = 16 // Reserved
	GraphNodeTypeExternalEngine GraphNodeType = 17 // Reserved for External Engine node
	GraphNodeTypeFabricCpyBatch GraphNodeType = 18 // Fabric copy batch node
)

func (GraphNodeType) String

func (e GraphNodeType) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphRecaptureCallback

type GraphRecaptureCallback func(data uintptr, node GraphNode, originalParams uintptr, recaptureParams uintptr, status GraphRecaptureStatus) Result

GraphRecaptureCallback is the Go form of CUgraphRecaptureCallback.

It corresponds to the C signature

typedef CUresult (CUDA_CB *CUgraphRecaptureCallback)(void *data, CUgraphNode node, const CUgraphNodeParams *originalParams, const CUgraphNodeParams *recaptureParams, CUgraphRecaptureStatus status);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type GraphRecaptureStatus

type GraphRecaptureStatus int32

GraphRecaptureStatus specifies the graph recapture status (CUgraphRecaptureStatus).

const (
	GraphRecaptureEligibleForUpdate GraphRecaptureStatus = 0 // Node is eligible for update in an instantiated graph.
	// GraphRecaptureIneligibleForUpdate: Parameter changes in the node cannot be applied to an instantiated graph.
	GraphRecaptureIneligibleForUpdate GraphRecaptureStatus = 1
	// GraphRecaptureError: Error while attempting to recapture the node. The recapture will be ended regardless of the return value from the callback.
	GraphRecaptureError GraphRecaptureStatus = 2
)

func (GraphRecaptureStatus) String

func (e GraphRecaptureStatus) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphdebugdotFlags

type GraphdebugdotFlags int32

GraphdebugdotFlags represents the additional write options for Graph.DebugDotPrint.

const (
	GraphDebugDotFlagsVerbose                  GraphdebugdotFlags = 1 << 0  // Output all debug data as if every debug flag is enabled
	GraphDebugDotFlagsRuntimeTypes             GraphdebugdotFlags = 1 << 1  // Use CUDA Runtime structures for output
	GraphDebugDotFlagsKernelNodeParams         GraphdebugdotFlags = 1 << 2  // Adds [KernelNodeParams] values to output
	GraphDebugDotFlagsMemcpyNodeParams         GraphdebugdotFlags = 1 << 3  // Adds [Memcpy3d] values to output
	GraphDebugDotFlagsMemsetNodeParams         GraphdebugdotFlags = 1 << 4  // Adds [MemsetNodeParams] values to output
	GraphDebugDotFlagsHostNodeParams           GraphdebugdotFlags = 1 << 5  // Adds [HostNodeParams] values to output
	GraphDebugDotFlagsEventNodeParams          GraphdebugdotFlags = 1 << 6  // Adds [Event] handle from record and wait nodes to output
	GraphDebugDotFlagsExtSemasSignalNodeParams GraphdebugdotFlags = 1 << 7  // Adds [ExtSemSignalNodeParams] values to output
	GraphDebugDotFlagsExtSemasWaitNodeParams   GraphdebugdotFlags = 1 << 8  // Adds [ExtSemWaitNodeParams] values to output
	GraphDebugDotFlagsKernelNodeAttributes     GraphdebugdotFlags = 1 << 9  // Adds CUkernelNodeAttrValue values to output
	GraphDebugDotFlagsHandles                  GraphdebugdotFlags = 1 << 10 // Adds node handles and every kernel function handle to output
	GraphDebugDotFlagsMemAllocNodeParams       GraphdebugdotFlags = 1 << 11 // Adds memory alloc node parameters to output
	GraphDebugDotFlagsMemFreeNodeParams        GraphdebugdotFlags = 1 << 12 // Adds memory free node parameters to output
	GraphDebugDotFlagsBatchMemOpNodeParams     GraphdebugdotFlags = 1 << 13 // Adds batch mem op node parameters to output
	GraphDebugDotFlagsExtraTopoInfo            GraphdebugdotFlags = 1 << 14 // Adds edge numbering information
	GraphDebugDotFlagsConditionalNodeParams    GraphdebugdotFlags = 1 << 15 // Adds conditional node parameters to output
	GraphDebugDotFlagsMemcpyBatchNodeParams    GraphdebugdotFlags = 1 << 16 // Adds batch memcpy node parameters to the output
	GraphDebugDotFlagsFabricCpyBatchNodeParams GraphdebugdotFlags = 1 << 17 // Adds fabric copy batch node parameters
)

func (GraphdebugdotFlags) String

func (e GraphdebugdotFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphicsMapResourceFlags

type GraphicsMapResourceFlags int32

GraphicsMapResourceFlags represents flags for mapping and unmapping interop resources.

const (
	GraphicsMapResourceFlagsNone         GraphicsMapResourceFlags = 0x00
	GraphicsMapResourceFlagsReadOnly     GraphicsMapResourceFlags = 0x01
	GraphicsMapResourceFlagsWriteDiscard GraphicsMapResourceFlags = 0x02
)

func (GraphicsMapResourceFlags) String

func (e GraphicsMapResourceFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphicsRegisterFlags

type GraphicsRegisterFlags int32

GraphicsRegisterFlags represents flags to register a graphics resource.

const (
	GraphicsRegisterFlagsNone          GraphicsRegisterFlags = 0x00
	GraphicsRegisterFlagsReadOnly      GraphicsRegisterFlags = 0x01
	GraphicsRegisterFlagsWriteDiscard  GraphicsRegisterFlags = 0x02
	GraphicsRegisterFlagsSurfaceLdst   GraphicsRegisterFlags = 0x04
	GraphicsRegisterFlagsTextureGather GraphicsRegisterFlags = 0x08
)

func (GraphicsRegisterFlags) String

func (e GraphicsRegisterFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphicsResource

type GraphicsResource uintptr

GraphicsResource is CUDA graphics interop resource.

func (*GraphicsResource) Close

func (g *GraphicsResource) Close() error

Close unregisters a graphics resource for access by CUDA.

Unregisters the graphics resource resource so it is not accessible by CUDA unless registered again. If resource is invalid then ErrInvalidHandle is returned.

See also: cuGraphicsD3D9RegisterResource, cuGraphicsD3D10RegisterResource, cuGraphicsD3D11RegisterResource, cuGraphicsGLRegisterBuffer, cuGraphicsGLRegisterImage, cudaGraphicsUnregisterResource

Errors:

If g is zero, Close returns nil. Otherwise Close sets g to zero when the call succeeds and leaves it unchanged when it fails. Only g is zeroed: a copy of it still refers to the released object.

Wraps cuGraphicsUnregisterResource.

func (GraphicsResource) MappedMipmappedArray

func (g GraphicsResource) MappedMipmappedArray() (MipmappedArray, error)

MappedMipmappedArray gets a mipmapped array through which to access a mapped graphics resource.

Returns a mipmapped array through which the mapped graphics resource resource. The result may change every time that resource is mapped. If resource is not a texture then it cannot be accessed via a mipmapped array and ErrNotMappedAsArray is returned. If resource is not mapped then ErrNotMapped is returned.

See also: GraphicsResource.MappedPointer, cudaGraphicsResourceGetMappedMipmappedArray

Errors:

Wraps cuGraphicsResourceGetMappedMipmappedArray.

func (GraphicsResource) MappedPointer

func (g GraphicsResource) MappedPointer() (pDevPtr DevicePtr, pSize uint, err error)

MappedPointer gets a device pointer through which to access a mapped graphics resource.

Returns in *pDevPtr a pointer through which the mapped graphics resource resource may be accessed. Returns in pSize the size of the memory in bytes which may be accessed from that pointer. The value set in pPointer may change every time that resource is mapped. If resource is not a buffer then it cannot be accessed via a pointer and ErrNotMappedAsPointer is returned. If resource is not mapped then ErrNotMapped is returned.

  • See also

Stream.GraphicsMapResources, GraphicsResource.SubResourceGetMappedArray, cudaGraphicsResourceGetMappedPointer

  • pDevPtr: Returned pointer through which resource may be accessed
  • pSize: Returned size of the buffer accessible starting at *pPointer

Errors:

See also: Stream.GraphicsMapResources, GraphicsResource.SubResourceGetMappedArray

Wraps cuGraphicsResourceGetMappedPointer, bound as cuGraphicsResourceGetMappedPointer_v2.

func (GraphicsResource) SetMapFlags

func (g GraphicsResource) SetMapFlags(flags GraphicsMapResourceFlags) error

SetMapFlags sets usage flags for mapping a graphics resource.

Set flags for mapping the graphics resource resource. Changes to flags will take effect the next time resource is mapped. The flags argument may be any of the following:

  • GraphicsMapResourceFlagsNone: Specifies no hints about how this resource will be used. It is therefore assumed that this resource will be read from and written to by CUDA kernels. This is the default value.
  • CU_GRAPHICS_MAP_RESOURCE_FLAGS_READONLY: Specifies that CUDA kernels which access this resource will not write to this resource.
  • CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITEDISCARD: Specifies that CUDA kernels which access this resource will not read from this resource and will write over the entire contents of the resource, so none of the data previously stored in the resource will be preserved.

If resource is presently mapped for access by CUDA then ErrAlreadyMapped is returned. If flags is not one of the above values then ErrInvalidValue is returned.

See also: Stream.GraphicsMapResources, cudaGraphicsResourceSetMapFlags

  • flags: Parameters for resource mapping

Errors:

Wraps cuGraphicsResourceSetMapFlags, bound as cuGraphicsResourceSetMapFlags_v2.

func (GraphicsResource) SubResourceGetMappedArray

func (g GraphicsResource) SubResourceGetMappedArray(arrayIndex uint32, mipLevel uint32) (Array, error)

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

Returns an array through which the subresource of the mapped graphics resource resource which corresponds to array index arrayIndex and mipmap level mipLevel may be accessed. The result may change every time that resource is mapped. If resource is not a texture then it cannot be accessed via an array and ErrNotMappedAsArray is returned. If arrayIndex is not a valid array index for resource then ErrInvalidValue is returned. If mipLevel is not a valid mipmap level for resource then ErrInvalidValue is returned. If resource is not mapped then ErrNotMapped is returned.

See also: GraphicsResource.MappedPointer, cudaGraphicsSubResourceGetMappedArray

  • arrayIndex: Array index for array textures or cubemap face index as defined by ArrayCubemapFace for cubemap textures for the subresource to access
  • mipLevel: Mipmap level for the subresource to access

Errors:

Wraps cuGraphicsSubResourceGetMappedArray.

type GraphinstantiateFlags

type GraphinstantiateFlags int32

GraphinstantiateFlags represents flags for instantiating a graph.

const (
	// GraphInstantiateFlagAutoFreeOnLaunch: Automatically free memory allocated in a graph before relaunching.
	GraphInstantiateFlagAutoFreeOnLaunch GraphinstantiateFlags = 1
	// GraphInstantiateFlagUpload: Automatically upload the graph after instantiation. Only supported by [Graph.InstantiateWithParams]. The upload will be performed using the stream provided in instantiateParams.
	GraphInstantiateFlagUpload GraphinstantiateFlags = 2
	// GraphInstantiateFlagDeviceLaunch: Instantiate the graph to be launchable from the device. This flag can only be used on platforms which support unified addressing. This flag cannot be used in conjunction with [GraphInstantiateFlagAutoFreeOnLaunch].
	GraphInstantiateFlagDeviceLaunch GraphinstantiateFlags = 4
	// GraphInstantiateFlagUseNodePriority: Run the graph using the per-node priority attributes rather than the priority of the stream it is launched into.
	GraphInstantiateFlagUseNodePriority GraphinstantiateFlags = 8
)

func (GraphinstantiateFlags) String

func (e GraphinstantiateFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type GraphmemAttribute

type GraphmemAttribute int32

GraphmemAttribute specifies the graphmem attribute (CUgraphMem_attribute).

const (
	GraphMemAttrUsedMemCurrent     GraphmemAttribute = 0
	GraphMemAttrUsedMemHigh        GraphmemAttribute = 1
	GraphMemAttrReservedMemCurrent GraphmemAttribute = 2
	GraphMemAttrReservedMemHigh    GraphmemAttribute = 3
)

func (GraphmemAttribute) String

func (e GraphmemAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type GreenCtx

type GreenCtx uintptr

GreenCtx is an opaque handle for CUgreenCtx.

func NewGreenCtx

func NewGreenCtx(desc DevResourceDesc, dev Device, flags GreenctxcreateFlags) (GreenCtx, error)

NewGreenCtx creates a green context with a specified set of resources.

This API creates a green context with the resources specified in the descriptor desc and returns it in the handle represented by phCtx. This API will retain the primary context on device dev, which will is released when the green context is destroyed. It is advised to have the primary context active before calling this API to avoid the heavy cost of triggering primary context initialization and deinitialization multiple times. The API does not set the green context current. In order to set it current, you need to explicitly set it current by first converting the green context to a Context using CtxFromGreenCtx and subsequently calling Context.SetCurrent / Context.PushCurrent. It should be noted that a green context can be current to only one thread at a time. There is no internal synchronization to make API calls accessing the same green context from multiple threads work.

Note: The API is not supported on 32-bit platforms. The supported flags are:

See also: GreenCtx.Close, CtxFromGreenCtx, Context.SetCurrent, Context.PushCurrent, DevResourceGenerateDesc, Device.PrimaryCtxRetain, NewContext

Requires CUDA 12.4 (driver r550) or later; see HasGreenCtxCreate.

  • desc: Descriptor generated via DevResourceGenerateDesc which contains the set of resources to be used
  • dev: Device on which to create the green context
  • flags: One of the supported green context creation flags

Errors:

Wraps cuGreenCtxCreate.

func (*GreenCtx) Close

func (g *GreenCtx) Close() error

Close destroys a green context.

Destroys the green context, releasing the primary context of the device that this green context was created for. Any resources provisioned for this green context (that were initially available via the resource descriptor) are released as well. The API does not destroy streams created via GreenCtx.StreamCreate, NewStream, or StreamCreateWithPriority. Users are expected to destroy these streams explicitly using Stream.Close to avoid resource leaks. Once the green context is destroyed, any subsequent API calls involving these streams will return ErrStreamDetached with the exception of the following APIs:

Additionally, the API will invalidate all active captures on these streams.

See also: NewGreenCtx, Context.Close

Requires CUDA 12.4 (driver r550) or later; see HasGreenCtxDestroy.

Errors:

If g is zero, Close returns nil. Otherwise Close sets g to zero when the call succeeds and leaves it unchanged when it fails. Only g is zeroed: a copy of it still refers to the released object.

Wraps cuGreenCtxDestroy.

func (GreenCtx) DevResource

func (g GreenCtx) DevResource(type_ DevResourceType) (DevResource, error)

DevResource gets green context resources.

Get the type resources available to the green context represented by hCtx

See also: DevResourceGenerateDesc

Requires CUDA 12.4 (driver r550) or later; see HasGreenCtxGetDevResource.

  • type_: Type of resource to retrieve

Errors:

Wraps cuGreenCtxGetDevResource.

func (GreenCtx) Id

func (g GreenCtx) Id() (uint64, error)

Id returns the unique Id associated with the green context supplied.

Returns the unique Id which is associated with a given green context. The Id is unique for the life of the program for this instance of CUDA. If green context is supplied as NULL and the current context is set to a green context, the Id of the current green context is returned.

See also: NewGreenCtx, GreenCtx.Close, Context.Id

Requires CUDA 13.0 (driver r580) or later; see HasGreenCtxGetId.

Errors:

Wraps cuGreenCtxGetId.

func (GreenCtx) RecordEvent

func (g GreenCtx) RecordEvent(hEvent Event) error

RecordEvent records an event.

Captures in hEvent all the activities of the green context of hCtx at the time of this call. hEvent and hCtx must be from the same primary context otherwise ErrInvalidHandle is returned. Calls such as Event.Query or GreenCtx.WaitEvent will then examine or wait for completion of the work that was captured. Uses of hCtx after this call do not modify hEvent.

Note: The API will return ErrStreamCaptureUnsupported if the specified green context hCtx has a stream in the capture mode. In such a case, the call will invalidate all the conflicting captures.

See also: GreenCtx.WaitEvent, Event.Record, Context.RecordEvent, Context.WaitEvent

Requires CUDA 12.4 (driver r550) or later; see HasGreenCtxRecordEvent.

  • hEvent: Event to record

Errors:

Wraps cuGreenCtxRecordEvent.

func (GreenCtx) StreamCreate

func (g GreenCtx) StreamCreate(flags StreamFlags, priority int32) (Stream, error)

StreamCreate creates a stream for use in the green context.

Creates a stream for use in the specified green context greenCtx and returns a handle. The stream can be destroyed by calling Stream.Close. Note that the API ignores the context that is current to the calling thread and creates a stream in the specified green context greenCtx. The supported values for flags are:

  • StreamNonBlocking: This must be specified. It indicates that work running in the created stream may run concurrently with work in the default stream, and that the created stream should perform no implicit synchronization with the default stream.

Specifying priority affects the scheduling priority of work in the stream. Priorities provide a hint to preferentially run work with higher priority when possible, but do not preempt already-running work or provide any other functional guarantee on execution order. priority follows a convention where lower numbers represent higher priorities. ‘0’ represents default priority. The range of meaningful numerical priorities can be queried using CtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by CtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range.

Note: 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.

See also: Stream.Close, NewGreenCtx NewStream, Stream.Priority, CtxGetStreamPriorityRange, Stream.Flags, Stream.Device, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreateWithPriority

Requires CUDA 12.5 (driver r555) or later; see HasGreenCtxStreamCreate.

  • flags: Flags for stream creation. StreamNonBlocking must be specified
  • priority: Stream priority. Lower numbers represent higher priorities. See CtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed

Errors:

Wraps cuGreenCtxStreamCreate.

func (GreenCtx) WaitEvent

func (g GreenCtx) WaitEvent(hEvent Event) error

WaitEvent makes a green context wait on an event.

Makes all future work submitted to green context hCtx wait for all work captured in hEvent. The synchronization will be performed on the device and will not block the calling CPU thread. See GreenCtx.RecordEvent or Event.Record, for details on what is captured by an event.

Note: hEvent may be from a different context or device than hCtx.

Note: The API will return ErrStreamCaptureUnsupported and invalidate the capture if the specified event hEvent is part of an ongoing capture sequence or if the specified green context hCtx has a stream in the capture mode.

See also: GreenCtx.RecordEvent, Stream.WaitEvent, Context.RecordEvent, Context.WaitEvent

Requires CUDA 12.4 (driver r550) or later; see HasGreenCtxWaitEvent.

  • hEvent: Event to wait on

Errors:

Wraps cuGreenCtxWaitEvent.

type GreenctxcreateFlags

type GreenctxcreateFlags int32

GreenctxcreateFlags represents flags for green context creation.

const (
	GreenCtxNone          GreenctxcreateFlags = 0x0
	GreenCtxDefaultStream GreenctxcreateFlags = 0x1 // Creates a default stream to use inside the green context
)

func (GreenctxcreateFlags) String

func (e GreenctxcreateFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type HostFn

type HostFn func(userData uintptr)

HostFn is the Go form of CUhostFn.

It corresponds to the C signature

typedef void (CUDA_CB *CUhostFn)(void *userData);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type HostNode

type HostNode struct {
	GraphNode
}

HostNode is a GraphNode of the host kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the HostNode one takes the kind's own types.

func (HostNode) Params

func (h HostNode) Params() (HostNodeParams, error)

Params returns a host node’s parameters.

Returns the parameters of host node hNode.

See also: GraphNode.Params, Stream.LaunchHostFunc, Graph.AddHostNode, HostNode.SetParams

Errors:

Wraps cuGraphHostNodeGetParams.

func (HostNode) SetParams

func (h HostNode) SetParams(nodeParams *HostNodeParams) error

SetParams sets a host node’s parameters.

Sets the parameters of host node hNode to nodeParams.

See also: GraphNode.SetParams, Stream.LaunchHostFunc, Graph.AddHostNode, HostNode.Params

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphHostNodeSetParams.

type HostNodeParams

type HostNodeParams struct {
	// The function to call when the node executes
	Fn uintptr
	// Argument to pass to the function
	UserData uintptr
}

HostNodeParams represents host node parameters.

type HostNodeParamsV1

type HostNodeParamsV1 = HostNodeParams

HostNodeParamsV1 is an alias for HostNodeParams.

type HostNodeParamsV2

type HostNodeParamsV2 struct {
	// The function to call when the node executes
	Fn uintptr
	// Argument to pass to the function
	UserData uintptr
	// The sync mode to use for the host task
	SyncMode       uint32
	AnonymousUnion [1]uint64
}

HostNodeParamsV2 represents host node parameters.

func (*HostNodeParamsV2) Ctx

func (h *HostNodeParamsV2) Ctx() *Context

Ctx returns a pointer to the ctx member of CUDA_HOST_NODE_PARAMS_v2, which shares its storage with every other member of the union.

func (*HostNodeParamsV2) GCtx

func (h *HostNodeParamsV2) GCtx() *GreenCtx

GCtx returns a pointer to the gCtx member of CUDA_HOST_NODE_PARAMS_v2, which shares its storage with every other member of the union.

type HostTaskSyncMode

type HostTaskSyncMode int32

HostTaskSyncMode specifies the host task sync mode (CUhostTaskSyncMode).

const (
	// HostTaskBlocking: The execution thread will block until new host tasks are ready to run
	HostTaskBlocking HostTaskSyncMode = 0x0
	// HostTaskSpinwait: The execution thread will spin wait until new host tasks are ready to run
	HostTaskSpinwait HostTaskSyncMode = 0x1
)

func (HostTaskSyncMode) String

func (e HostTaskSyncMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type IpcEventHandle

type IpcEventHandle struct {
	Reserved [64]byte
}

IpcEventHandle represents CUDA IPC event handle.

type IpcEventHandleV1

type IpcEventHandleV1 = IpcEventHandle

IpcEventHandleV1 is an alias for IpcEventHandle.

type IpcMemHandle

type IpcMemHandle struct {
	Reserved [64]byte
}

IpcMemHandle represents CUDA IPC mem handle.

type IpcMemHandleV1

type IpcMemHandleV1 = IpcMemHandle

IpcMemHandleV1 is an alias for IpcMemHandle.

type IpcmemFlags

type IpcmemFlags int32

IpcmemFlags represents CUDA Ipc Mem Flags.

const (
	// IpcMemLazyEnablePeerAccess: Automatically enable peer access between remote devices as needed
	IpcMemLazyEnablePeerAccess IpcmemFlags = 0x1
)

func (IpcmemFlags) String

func (e IpcmemFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type JITOption

type JITOption int32

JITOption represents online compiler and linker options.

const (
	// JITMaxRegisters: Max number of registers that a thread may use. Option type: unsigned int. Applies to: compiler only
	JITMaxRegisters JITOption = 0
	// JITThreadsPerBlock: IN: Specifies minimum number of threads per block to target compilation for. OUT: Returns the number of threads the compiler actually targeted. This restricts the resource utilization of the compiler (e.g. max registers) such that a block with the given number of threads should be able to launch based on register limitations. Note, this option does not currently take into account any other resource limitations, such as shared memory utilization. Cannot be combined with [JITTarget]. Option type: unsigned int. Applies to: compiler only
	JITThreadsPerBlock JITOption = 1
	// JITWallTime: Overwrites the option value with the total wall clock time, in milliseconds, spent in the compiler and linker. Option type: float. Applies to: compiler and linker
	JITWallTime JITOption = 2
	// JITInfoLogBuffer: Pointer to a buffer in which to print any log messages that are informational in nature (the buffer size is specified via option [JITInfoLogBufferSizeBytes]). Option type: char * Applies to: compiler and linker
	JITInfoLogBuffer JITOption = 3
	// JITInfoLogBufferSizeBytes: IN: Log buffer size in bytes. Log messages will be capped at this size (including null terminator). OUT: Amount of log buffer filled with messages. Option type: unsigned int. Applies to: compiler and linker
	JITInfoLogBufferSizeBytes JITOption = 4
	// JITErrorLogBuffer: Pointer to a buffer in which to print any log messages that reflect errors (the buffer size is specified via option [JITErrorLogBufferSizeBytes]). Option type: char * Applies to: compiler and linker
	JITErrorLogBuffer JITOption = 5
	// JITErrorLogBufferSizeBytes: IN: Log buffer size in bytes. Log messages will be capped at this size (including null terminator). OUT: Amount of log buffer filled with messages. Option type: unsigned int. Applies to: compiler and linker
	JITErrorLogBufferSizeBytes JITOption = 6
	// JITOptimizationLevel: Level of optimizations to apply to generated code (0 - 4), with 4 being the default and highest level of optimizations. Option type: unsigned int. Applies to: compiler only
	JITOptimizationLevel JITOption = 7
	// JITTargetFromCucontext: No option value required. Determines the target based on the current attached context (default). Option type: No option value needed. Applies to: compiler and linker
	JITTargetFromCucontext JITOption = 8
	// JITTarget: Target is chosen based on supplied [JitTarget]. Cannot be combined with [JITThreadsPerBlock]. Option type: unsigned int for enumerated type [JitTarget]. Applies to: compiler and linker
	JITTarget JITOption = 9
	// JITFallbackStrategy: Specifies choice of fallback strategy if matching cubin is not found. Choice is based on supplied [JitFallback]. This option cannot be used with cuLink* APIs as the linker requires exact matches. Option type: unsigned int for enumerated type [JitFallback]. Applies to: compiler only
	JITFallbackStrategy JITOption = 10
	// JITGenerateDebugInfo: Specifies whether to create debug information in output (-g) (0: false, default). Option type: int. Applies to: compiler and linker
	JITGenerateDebugInfo JITOption = 11
	// JITLogVerbose: Generate verbose log messages (0: false, default). Option type: int. Applies to: compiler and linker
	JITLogVerbose JITOption = 12
	// JITGenerateLineInfo: Generate line number information (-lineinfo) (0: false, default). Option type: int. Applies to: compiler only
	JITGenerateLineInfo JITOption = 13
	// JITCacheMode: Specifies whether to enable caching explicitly (-dlcm). Choice is based on supplied CUjit_cacheMode_enum. Option type: unsigned int for enumerated type CUjit_cacheMode_enum. Applies to: compiler only
	JITCacheMode JITOption = 14
	//
	// Deprecated: Deprecated by NVIDIA. This jit option is deprecated and should not be used.
	JITNewSM3XOpt  JITOption = 15
	JITFastCompile JITOption = 16 // This jit option is used for internal purpose only.
	// JITGlobalSymbolNames: Array of device symbol names that will be relocated to the corresponding host addresses stored in [JITGlobalSymbolAddresses]. Must contain [JITGlobalSymbolCount] entries. When loading a device module, driver will relocate all encountered unresolved symbols to the host addresses. It is only allowed to register symbols that correspond to unresolved global variables. It is illegal to register the same device symbol at multiple addresses. Option type: const char ** Applies to: dynamic linker only
	JITGlobalSymbolNames JITOption = 17
	// JITGlobalSymbolAddresses: Array of host addresses that will be used to relocate corresponding device symbols stored in [JITGlobalSymbolNames]. Must contain [JITGlobalSymbolCount] entries. Option type: void ** Applies to: dynamic linker only
	JITGlobalSymbolAddresses JITOption = 18
	// JITGlobalSymbolCount: Number of entries in [JITGlobalSymbolNames] and [JITGlobalSymbolAddresses] arrays. Option type: unsigned int. Applies to: dynamic linker only
	JITGlobalSymbolCount JITOption = 19
	// JITLto: Enable link-time optimization (-dlto) for device code (Disabled by default). This option is not supported on 32-bit platforms. Option type: int. Applies to: compiler and linker. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITLto JITOption = 20
	// JITFtz: Control single-precision denormals (-ftz) support (0: false, default). 1 : flushes denormal values to zero 0 : preserves denormal values Option type: int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITFtz JITOption = 21
	// JITPrecDiv: Control single-precision floating-point division and reciprocals (-prec-div) support (1: true, default). 1 : Enables the IEEE round-to-nearest mode 0 : Enables the fast approximation mode Option type: int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITPrecDiv JITOption = 22
	// JITPrecSqrt: Control single-precision floating-point square root (-prec-sqrt) support (1: true, default). 1 : Enables the IEEE round-to-nearest mode 0 : Enables the fast approximation mode Option type: int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITPrecSqrt JITOption = 23
	// JITFma: Enable/Disable the contraction of floating-point multiplies and adds/subtracts into floating-point multiply-add (-fma) operations (1: Enable, default; 0: Disable). Option type: int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITFma JITOption = 24
	// JITReferencedKernelNames: Array of kernel names that should be preserved at link time while others can be removed. Must contain [JITReferencedKernelCount] entries. Note that kernel names can be mangled by the compiler in which case the mangled name needs to be specified. Wildcard "*" can be used to represent zero or more characters instead of specifying the full or mangled name. It is important to note that the wildcard "*" is also added implicitly. For example, specifying "foo" will match "foobaz", "barfoo", "barfoobaz" and thus preserve all kernels with those names. This can be avoided by providing a more specific name like "barfoobaz". Option type: const char ** Applies to: dynamic linker only. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITReferencedKernelNames JITOption = 25
	// JITReferencedKernelCount: Number of entries in [JITReferencedKernelNames] array. Option type: unsigned int. Applies to: dynamic linker only. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITReferencedKernelCount JITOption = 26
	// JITReferencedVariableNames: Array of variable names (__device__ and/or __constant__) that should be preserved at link time while others can be removed. Must contain [JITReferencedVariableCount] entries. Note that variable names can be mangled by the compiler in which case the mangled name needs to be specified. Wildcard "*" can be used to represent zero or more characters instead of specifying the full or mangled name. It is important to note that the wildcard "*" is also added implicitly. For example, specifying "foo" will match "foobaz", "barfoo", "barfoobaz" and thus preserve all variables with those names. This can be avoided by providing a more specific name like "barfoobaz". Option type: const char ** Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITReferencedVariableNames JITOption = 27
	// JITReferencedVariableCount: Number of entries in [JITReferencedVariableNames] array. Option type: unsigned int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITReferencedVariableCount JITOption = 28
	// JITOptimizeUnusedDeviceVariables: This option serves as a hint to enable the JIT compiler/linker to remove constant (__constant__) and device (__device__) variables unreferenced in device code (Disabled by default). Note that host references to constant and device variables using APIs like [Module.Global] with this option specified may result in undefined behavior unless the variables are explicitly specified using [JITReferencedVariableNames]. Option type: int. Applies to: link-time optimization specified with [JITLto]. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JITOptimizeUnusedDeviceVariables JITOption = 29
	// JITPositionIndependentCode: Generate position independent code (0: false). This option is no longer functional and specifying this option doesn't take any effect and is ignored. Option type: int. Applies to: compiler only
	//
	// Deprecated: Deprecated by NVIDIA.
	JITPositionIndependentCode JITOption = 30
	// JITMinCtaPerSm: This option hints to the JIT compiler the minimum number of CTAs from the kernel’s grid to be mapped to a SM. This option is ignored when used together with [JITMaxRegisters] or [JITThreadsPerBlock]. Optimizations based on this option need [JITMaxThreadsPerBlock] to be specified as well. For kernels already using PTX directive .minnctapersm, this option will be ignored by default. Use [JITOverrideDirectiveValues] to let this option take precedence over the PTX directive. Option type: unsigned int. Applies to: compiler only
	JITMinCtaPerSm JITOption = 31
	// JITMaxThreadsPerBlock: Maximum number threads in a thread block, computed as the product of the maximum extent specifed for each dimension of the block. This limit is guaranteed not to be exeeded in any invocation of the kernel. Exceeding the the maximum number of threads results in runtime error or kernel launch failure. For kernels already using PTX directive .maxntid, this option will be ignored by default. Use [JITOverrideDirectiveValues] to let this option take precedence over the PTX directive. Option type: int. Applies to: compiler only
	JITMaxThreadsPerBlock JITOption = 32
	// JITOverrideDirectiveValues: This option lets the values specified using [JITMaxRegisters], [JITThreadsPerBlock], [JITMaxThreadsPerBlock] and [JITMinCtaPerSm] take precedence over any PTX directives. (0: Disable, default; 1: Enable) Option type: int. Applies to: compiler only
	JITOverrideDirectiveValues JITOption = 33
	// JITSplitCompile: This option specifies the maximum number of concurrent threads to use when running compiler optimizations. If the specified value is 1, the option will be ignored. If the specified value is 0, the number of threads will match the number of CPUs on the underlying machine. Otherwise, if the option is N, then up to N threads will be used. Option type: unsigned int. Applies to: compiler only
	JITSplitCompile JITOption = 34
	// JITBinaryLoaderThreadCount: This option specifies the maximum number of concurrent threads to use when compiling device code. If the specified value is 1, the option will be ignored. If the specified value is 0, the number of threads will match the number of CPUs on the underlying machine. Otherwise, if the option is N, then up to N threads will be used. This option is ignored if the env var CUDA_BINARY_LOADER_THREAD_COUNT is set. Option type: unsigned int. Applies to: compiler and linker
	JITBinaryLoaderThreadCount JITOption = 35
	JITNumOptions              JITOption = 36
)

func (JITOption) String

func (e JITOption) String() string

String returns the constant name, or a numeric representation for unknown values.

type JitCachemode

type JitCachemode int32

JitCachemode represents caching modes for dlcm.

const (
	JitCacheOptionNone JitCachemode = 0 // Compile with no -dlcm flag specified
	JitCacheOptionCg   JitCachemode = 1 // Compile with L1 cache disabled
	JitCacheOptionCa   JitCachemode = 2 // Compile with L1 cache enabled
)

func (JitCachemode) String

func (e JitCachemode) String() string

String returns the constant name, or a numeric representation for unknown values.

type JitFallback

type JitFallback int32

JitFallback represents cubin matching fallback strategies.

const (
	PreferPtx JitFallback = 0 // Prefer to compile ptx if exact binary match not found
	// PreferBinary: Prefer to fall back to compatible binary code if exact match not found
	PreferBinary JitFallback = 1
)

func (JitFallback) String

func (e JitFallback) String() string

String returns the constant name, or a numeric representation for unknown values.

type JitInputType

type JitInputType int32

JitInputType represents device code formats.

const (
	// JitInputCubin: Compiled device-class-specific device code. Applicable options: none
	JitInputCubin JitInputType = 0
	JitInputPtx   JitInputType = 1 // PTX source code. Applicable options: PTX compiler options
	// JitInputFatbinary: Bundle of multiple cubins and/or PTX of some device code. Applicable options: PTX compiler options, [JITFallbackStrategy]
	JitInputFatbinary JitInputType = 2
	// JitInputObject: Host object with embedded device code. Applicable options: PTX compiler options, [JITFallbackStrategy]
	JitInputObject JitInputType = 3
	// JitInputLibrary: Archive of host objects with embedded device code. Applicable options: PTX compiler options, [JITFallbackStrategy]
	JitInputLibrary JitInputType = 4
	// JitInputNvvm: High-level intermediate code for link-time optimization. Applicable options: NVVM compiler options, PTX compiler options. Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0
	//
	// Deprecated: Deprecated by NVIDIA.
	JitInputNvvm     JitInputType = 5
	JitNumInputTypes JitInputType = 6
)

func (JitInputType) String

func (e JitInputType) String() string

String returns the constant name, or a numeric representation for unknown values.

type JitTarget

type JitTarget int32

JitTarget represents online compilation targets.

const (
	TargetCompute30   JitTarget = 30  // Compute device class 3.0
	TargetCompute32   JitTarget = 32  // Compute device class 3.2
	TargetCompute35   JitTarget = 35  // Compute device class 3.5
	TargetCompute37   JitTarget = 37  // Compute device class 3.7
	TargetCompute50   JitTarget = 50  // Compute device class 5.0
	TargetCompute52   JitTarget = 52  // Compute device class 5.2
	TargetCompute53   JitTarget = 53  // Compute device class 5.3
	TargetCompute60   JitTarget = 60  // Compute device class 6.0.
	TargetCompute61   JitTarget = 61  // Compute device class 6.1.
	TargetCompute62   JitTarget = 62  // Compute device class 6.2.
	TargetCompute70   JitTarget = 70  // Compute device class 7.0.
	TargetCompute72   JitTarget = 72  // Compute device class 7.2.
	TargetCompute75   JitTarget = 75  // Compute device class 7.5.
	TargetCompute80   JitTarget = 80  // Compute device class 8.0.
	TargetCompute86   JitTarget = 86  // Compute device class 8.6.
	TargetCompute87   JitTarget = 87  // Compute device class 8.7.
	TargetCompute89   JitTarget = 89  // Compute device class 8.9.
	TargetCompute90   JitTarget = 90  // Compute device class 9.0.
	TargetCompute100  JitTarget = 100 // Compute device class 10.0.
	TargetCompute110  JitTarget = 110 // Compute device class 11.0.
	TargetCompute103  JitTarget = 103 // Compute device class 10.3.
	TargetCompute107  JitTarget = 107 // Compute device class 10.7.
	TargetCompute120  JitTarget = 120 // Compute device class 12.0.
	TargetCompute121  JitTarget = 121 // Compute device class 12.1.
	TargetCompute90A  JitTarget = 65626
	TargetCompute100A JitTarget = 65636
	TargetCompute110A JitTarget = 65646
	TargetCompute103A JitTarget = 65639
	TargetCompute107A JitTarget = 65643
	TargetCompute120A JitTarget = 65656
	TargetCompute121A JitTarget = 65657
	TargetCompute100F JitTarget = 131172
	TargetCompute110F JitTarget = 131182
	TargetCompute103F JitTarget = 131175
	TargetCompute107F JitTarget = 131179
	TargetCompute120F JitTarget = 131192
	TargetCompute121F JitTarget = 131193
)

func (JitTarget) String

func (e JitTarget) String() string

String returns the constant name, or a numeric representation for unknown values.

type Kernel

type Kernel uintptr

Kernel is an opaque handle to a CUDA kernel within a library. Used with the CUDA library management APIs.

func (Kernel) Attribute

func (k Kernel) Attribute(attrib FunctionAttribute, dev Device) (int32, error)

Attribute returns information about a kernel.

Returns the integer value of the attribute attrib for the kernel kernel for the requested device dev. The supported attributes are:

  • FuncAttributeMaxThreadsPerBlock: The maximum number of threads per block, beyond which a launch of the kernel would fail. This number depends on both the kernel and the requested device.
  • FuncAttributeSharedSizeBytes: The size in bytes of statically-allocated shared memory per block required by this kernel. This does not include dynamically-allocated shared memory requested by the user at runtime.
  • FuncAttributeConstSizeBytes: The size in bytes of user-allocated constant memory required by this kernel.
  • FuncAttributeLocalSizeBytes: The size in bytes of local memory used by each thread of this kernel.
  • FuncAttributeNumRegs: The number of registers used by each thread of this kernel.
  • FuncAttributePtxVersion: The PTX virtual architecture version for which the kernel was compiled. This value is the major PTX version * 10 + the minor PTX version, so a PTX version 1.3 function would return the value 13. Note that this may return the undefined value of 0 for cubins compiled prior to CUDA 3.0.
  • FuncAttributeBinaryVersion: The binary architecture version for which the kernel was compiled. This value is the major binary version * 10 + the minor binary version, so a binary version 1.3 function would return the value 13. Note that this will return a value of 10 for legacy cubins that do not have a properly-encoded binary architecture version.
  • CU_FUNC_CACHE_MODE_CA: The attribute to indicate whether the kernel has been compiled with user specified option “-Xptxas –dlcm=ca” set.
  • FuncAttributeMaxDynamicSharedSizeBytes: The maximum size in bytes of dynamically-allocated shared memory.
  • FuncAttributePreferredSharedMemoryCarveout: Preferred shared memory-L1 cache split ratio in percent of total shared memory.
  • FuncAttributeClusterSizeMustBeSet: If this attribute is set, the kernel must launch with a valid cluster size specified.
  • FuncAttributeRequiredClusterWidth: The required cluster width in blocks.
  • FuncAttributeRequiredClusterHeight: The required cluster height in blocks.
  • FuncAttributeRequiredClusterDepth: The required cluster depth in blocks.
  • FuncAttributeNonPortableClusterSizeAllowed: Indicates whether the function can be launched with non-portable cluster size. 1 is allowed, 0 is disallowed. A non-portable cluster size may only function on the specific SKUs the program is tested on. The launch might fail if the program is run on a different hardware platform. CUDA API provides cudaOccupancyMaxActiveClusters to assist with checking whether the desired size can be launched on the current device. A portable cluster size is guaranteed to be functional on all compute capabilities higher than the target compute capability. The portable cluster size for sm_90 is 8 blocks per cluster. This value may increase for future compute capabilities. The specific hardware unit may support higher cluster sizes that’s not guaranteed to be portable.
  • FuncAttributeClusterSchedulingPolicyPreference: The block scheduling policy of a function. The value type is ClusterSchedulingPolicy.
  • FuncAttributeSharedMemoryMode: The shared memory mode of a function. The value type is SharedMemoryMode / cudaSharedMemoryMode.

Note: If another thread is trying to set the same attribute on the same device using Kernel.SetAttribute simultaneously, the attribute query will give the old or new value depending on the interleavings chosen by the OS scheduler and memory consistency.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Kernel.SetAttribute, Library.Kernel, Function.LaunchKernel, Kernel.Function, Library.Module, Module.Function, Function.Attribute

  • attrib: Attribute requested
  • dev: Device to query attribute of

Errors:

Wraps cuKernelGetAttribute.

func (Kernel) Function

func (k Kernel) Function() (Function, error)

Function returns a function handle.

Returns the handle of the function for the requested kernel kernel and the current context. If function handle is not found, the call returns ErrNotFound.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Library.Kernel, Library.Module, Module.Function

Errors:

Wraps cuKernelGetFunction.

func (Kernel) Library

func (k Kernel) Library() (Library, error)

Library returns a library handle.

Returns the handle of the library for the requested kernel kernel

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Library.Kernel

Requires CUDA 12.5 (driver r555) or later; see HasKernelGetLibrary.

Errors:

Wraps cuKernelGetLibrary.

func (Kernel) Name

func (k Kernel) Name() (string, error)

Name returns the function name for a Kernel handle.

Returns in **name the function name associated with the kernel handle hfunc . The function name is returned as a null-terminated string. The returned name is only valid when the kernel handle is valid. If the library is unloaded or reloaded, one must call the API again to get the updated name. This API may return a mangled name if the function is not declared as having C linkage. If either **name or hfunc is NULL, ErrInvalidValue is returned.

Requires CUDA 12.3 (driver r545) or later; see HasKernelGetName.

Errors:

Wraps cuKernelGetName.

func (Kernel) ParamCount

func (k Kernel) ParamCount() (uint, error)

ParamCount returns the number of parameters used by the kernel.

Queries the number of kernel parameters used by kernel and returns it.

See also: Kernel.ParamInfo

Requires CUDA 13.2 (driver r595) or later; see HasKernelGetParamCount.

Errors:

Wraps cuKernelGetParamCount.

func (Kernel) ParamInfo

func (k Kernel) ParamInfo(paramIndex uint) (paramOffset uint, paramSize uint, err error)

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

Queries the kernel parameter at paramIndex into kernel's list of parameters, and returns in paramOffset and paramSize the offset and size, respectively, where the parameter will reside in the device-side parameter layout. This information can be used to update kernel node parameters from the device via cudaGraphKernelNodeSetParam() and cudaGraphKernelNodeUpdatesApply(). paramIndex must be less than the number of parameters that kernel takes. paramSize can be set to NULL if only the parameter offset is desired.

See also: Function.ParamInfo

Requires CUDA 12.4 (driver r550) or later; see HasKernelGetParamInfo.

  • paramIndex: The parameter index to query
  • paramOffset: Returns the offset into the device-side parameter layout at which the parameter resides
  • paramSize: Optionally returns the size of the parameter in the device-side parameter layout

Errors:

Wraps cuKernelGetParamInfo.

func (Kernel) SetAttribute

func (k Kernel) SetAttribute(attrib FunctionAttribute, val int32, dev Device) error

SetAttribute sets information about a kernel.

This call sets the value of a specified attribute attrib on the kernel kernel for the requested device dev to an integer value specified by val. This function returns Success if the new value of the attribute could be successfully set. If the set fails, this call will return an error. Not all attributes can have values set. Attempting to set a value on a read-only attribute will result in an error (ErrInvalidValue) Note that attributes set using Function.SetAttribute will override the attribute set by this API irrespective of whether the call to Function.SetAttribute is made before or after this API call. However, Kernel.Attribute will always return the attribute value set by this API. Supported attributes are:

Note: The API has stricter locking requirements in comparison to its legacy counterpart Function.SetAttribute due to device-wide semantics. If multiple threads are trying to set the same attribute on the same device simultaneously, the attribute setting will depend on the interleavings chosen by the OS scheduler and memory consistency.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Kernel.Attribute, Library.Kernel, Function.LaunchKernel, Kernel.Function, Library.Module, Module.Function, Function.SetAttribute

  • attrib: Attribute requested
  • val: Value to set
  • dev: Device to set attribute of

Errors:

Wraps cuKernelSetAttribute.

func (Kernel) SetCacheConfig

func (k Kernel) SetCacheConfig(config FuncCacheConfig, dev Device) error

SetCacheConfig sets the preferred cache configuration for a device kernel.

On devices where the L1 cache and shared memory use the same hardware resources, this sets through config the preferred cache configuration for the device kernel kernel on the requested device dev. This is only a preference. The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute kernel. Any context-wide preference set via CtxSetCacheConfig will be overridden by this per-kernel setting. Note that attributes set using Function.SetCacheConfig will override the attribute set by this API irrespective of whether the call to Function.SetCacheConfig is made before or after this API call. 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:

Note: The API has stricter locking requirements in comparison to its legacy counterpart Function.SetCacheConfig due to device-wide semantics. If multiple threads are trying to set a config on the same device simultaneously, the cache config setting will depend on the interleavings chosen by the OS scheduler and memory consistency.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Library.Kernel, Kernel.Function, Library.Module, Module.Function, Function.SetCacheConfig, CtxSetCacheConfig, Function.LaunchKernel

  • config: Requested cache configuration
  • dev: Device to set attribute of

Errors:

Wraps cuKernelSetCacheConfig.

type KernelNode

type KernelNode struct {
	GraphNode
}

KernelNode is a GraphNode of the kernel kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the KernelNode one takes the kind's own types.

func (KernelNode) Attribute

func (k KernelNode) Attribute(attr int32) ([8]uint64, error)

Attribute queries node attribute.

Queries attribute attr from node hNode and stores it in corresponding member of valueOut.

See also: AccessPolicyWindow

Errors:

Wraps cuGraphKernelNodeGetAttribute.

func (KernelNode) CopyAttributes

func (k KernelNode) CopyAttributes(src KernelNode) error

CopyAttributes copies attributes from source node to destination node.

Copies attributes from source node src to destination node dst. Both node must have the same context.

See also: AccessPolicyWindow

  • src: Source node For list of attributes see CUkernelNodeAttrID

Errors:

Wraps cuGraphKernelNodeCopyAttributes.

func (KernelNode) Params

func (k KernelNode) Params() (KernelNodeParams, error)

Params returns a kernel node’s parameters.

Returns the parameters of kernel node hNode. The kernelParams or extra array returned, as well as the argument values it points to, are owned by the node. This memory remains valid until the node is destroyed or its parameters are modified, and should not be modified directly. Use KernelNode.SetParams to update the parameters of this node. The params will contain either kernelParams or extra, according to which of these was most recently set on the node.

See also: GraphNode.Params, Function.LaunchKernel, Graph.AddKernelNode, KernelNode.SetParams

Errors:

Wraps cuGraphKernelNodeGetParams, bound as cuGraphKernelNodeGetParams_v2.

func (KernelNode) SetAttribute

func (k KernelNode) SetAttribute(attr int32, value *[8]uint64) error

SetAttribute sets node attribute.

Sets attribute attr on node hNode from corresponding attribute of value.

See also: AccessPolicyWindow

Errors:

Wraps cuGraphKernelNodeSetAttribute.

func (KernelNode) SetParams

func (k KernelNode) SetParams(nodeParams *KernelNodeParams) error

SetParams sets a kernel node’s parameters.

Sets the parameters of kernel node hNode to nodeParams.

See also: GraphNode.SetParams, Function.LaunchKernel, Graph.AddKernelNode, KernelNode.Params

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphKernelNodeSetParams, bound as cuGraphKernelNodeSetParams_v2.

type KernelNodeParams

type KernelNodeParams struct {
	// Kernel to launch
	Func Function
	// X: Width of grid in blocks
	// Y: Height of grid in blocks
	// Z: Depth of grid in blocks
	GridDim Dim3
	// X: X dimension of each thread block
	// Y: Y dimension of each thread block
	// Z: Z dimension of each thread block
	BlockDim Dim3
	// Dynamic shared-memory size per thread block in bytes
	SharedMemBytes uint32
	// Array of pointers to kernel parameters
	KernelParams uintptr
	// Extra options
	Extra uintptr
	// Kernel to launch, will only be referenced if func is NULL
	Kern Kernel
	// Context for the kernel task to run in. The value NULL will indicate the current context should be used by the api. This field is ignored if func is set.
	Ctx Context
}

KernelNodeParams represents GPU kernel node parameters.

type KernelNodeParamsV1

type KernelNodeParamsV1 struct {
	// Kernel to launch
	Func Function
	// X: Width of grid in blocks
	// Y: Height of grid in blocks
	// Z: Depth of grid in blocks
	GridDim Dim3
	// X: X dimension of each thread block
	// Y: Y dimension of each thread block
	// Z: Z dimension of each thread block
	BlockDim Dim3
	// Dynamic shared-memory size per thread block in bytes
	SharedMemBytes uint32
	// Array of pointers to kernel parameters
	KernelParams uintptr
	// Extra options
	Extra uintptr
}

KernelNodeParamsV1 represents GPU kernel node parameters.

type KernelNodeParamsV2

type KernelNodeParamsV2 = KernelNodeParams

KernelNodeParamsV2 is an alias for KernelNodeParams.

type KernelNodeParamsV3

type KernelNodeParamsV3 struct {
	// Kernel to launch
	Func Function
	// X: Width of grid in blocks
	// Y: Height of grid in blocks
	// Z: Depth of grid in blocks
	GridDim Dim3
	// X: X dimension of each thread block
	// Y: Y dimension of each thread block
	// Z: Z dimension of each thread block
	BlockDim Dim3
	// Dynamic shared-memory size per thread block in bytes
	SharedMemBytes uint32
	// Array of pointers to kernel parameters
	KernelParams uintptr
	// Extra options
	Extra uintptr
	// Kernel to launch, will only be referenced if func is NULL
	Kern Kernel
	// Context for the kernel task to run in. The value NULL will indicate the current context should be used by the api. This field is ignored if func is set.
	Ctx Context
}

KernelNodeParamsV3 represents GPU kernel node parameters.

type LaunchAttribute

type LaunchAttribute struct {
	// Attribute to set
	Id  LaunchAttributeID
	Pad [4]byte
	// Value of the attribute
	Value LaunchAttributeValue
}

LaunchAttribute represents launch attribute.

type LaunchAttributeID

type LaunchAttributeID int32

LaunchAttributeID represents launch attributes enum; used as id field of LaunchAttribute.

const (
	LaunchAttributeIgnore LaunchAttributeID = 0 // Ignored entry, for convenient composition
	// LaunchAttributeAccessPolicyWindow: Valid for streams, graph nodes, launches. See [LaunchAttributeValue].accessPolicyWindow.
	LaunchAttributeAccessPolicyWindow LaunchAttributeID = 1
	// LaunchAttributeCooperative: Valid for graph nodes, launches. See [LaunchAttributeValue].cooperative.
	LaunchAttributeCooperative           LaunchAttributeID = 2
	LaunchAttributeSynchronizationPolicy LaunchAttributeID = 3 // Valid for streams. See [LaunchAttributeValue].syncPolicy.
	// LaunchAttributeClusterDimension: Valid for graph nodes, launches. See [LaunchAttributeValue].clusterDim.
	LaunchAttributeClusterDimension LaunchAttributeID = 4
	// LaunchAttributeClusterSchedulingPolicyPreference: Valid for graph nodes, launches. See [LaunchAttributeValue].clusterSchedulingPolicyPreference.
	LaunchAttributeClusterSchedulingPolicyPreference LaunchAttributeID = 5
	// LaunchAttributeProgrammaticStreamSerialization: Valid for launches. Setting [LaunchAttributeValue].programmaticStreamSerializationAllowed to non-0 signals that the kernel will use programmatic means to resolve its stream dependency, so that the CUDA runtime should opportunistically allow the grid's execution to overlap with the previous kernel in the stream, if that kernel requests the overlap. The dependent launches can choose to wait on the dependency using the programmatic sync (cudaGridDependencySynchronize() or equivalent PTX instructions).
	LaunchAttributeProgrammaticStreamSerialization LaunchAttributeID = 6
	// LaunchAttributeProgrammaticEvent: Valid for launches. Set [LaunchAttributeValue].programmaticEvent to record the event. Event recorded through this launch attribute is guaranteed to only trigger after all block in the associated kernel trigger the event. A block can trigger the event through PTX launchdep.release or CUDA builtin function cudaTriggerProgrammaticLaunchCompletion(). A trigger can also be inserted at the beginning of each block's execution if triggerAtBlockStart is set to non-0. The dependent launches can choose to wait on the dependency using the programmatic sync (cudaGridDependencySynchronize() or equivalent PTX instructions). Note that dependents (including the CPU thread calling [Event.Synchronize]) are not guaranteed to observe the release precisely when it is released. For example, [Event.Synchronize] may only observe the event trigger long after the associated kernel has completed. This recording type is primarily meant for establishing programmatic dependency between device tasks. Note also this type of dependency allows, but does not guarantee, concurrent execution of tasks. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. must be created with the [EventDisableTiming] flag set).
	LaunchAttributeProgrammaticEvent LaunchAttributeID = 7
	// LaunchAttributePriority: Valid for streams, graph nodes, launches. See [LaunchAttributeValue].priority.
	LaunchAttributePriority LaunchAttributeID = 8
	// LaunchAttributeMemSyncDomainMap: Valid for streams, graph nodes, launches. See [LaunchAttributeValue].memSyncDomainMap.
	LaunchAttributeMemSyncDomainMap LaunchAttributeID = 9
	// LaunchAttributeMemSyncDomain: Valid for streams, graph nodes, launches. See [LaunchAttributeValue].memSyncDomain.
	LaunchAttributeMemSyncDomain LaunchAttributeID = 10
	// LaunchAttributePreferredClusterDimension: Valid for graph nodes, launches. Set [LaunchAttributeValue].preferredClusterDim to allow the kernel launch to specify a preferred substitute cluster dimension. Blocks may be grouped according to either the dimensions specified with this attribute (grouped into a "preferred substitute cluster"), or the one specified with [LaunchAttributeClusterDimension] attribute (grouped into a "regular cluster"). The cluster dimensions of a "preferred substitute cluster" shall be an integer multiple greater than zero of the regular cluster dimensions. The device will attempt - on a best-effort basis - to group thread blocks into preferred clusters over grouping them into regular clusters. When it deems necessary (primarily when the device temporarily runs out of physical resources to launch the larger preferred clusters), the device may switch to launch the regular clusters instead to attempt to utilize as much of the physical device resources as possible. Each type of cluster will have its enumeration / coordinate setup as if the grid consists solely of its type of cluster. For example, if the preferred substitute cluster dimensions double the regular cluster dimensions, there might be simultaneously a regular cluster indexed at (1,0,0), and a preferred cluster indexed at (1,0,0). In this example, the preferred substitute cluster (1,0,0) replaces regular clusters (2,0,0) and (3,0,0) and groups their blocks. This attribute will only take effect when a regular cluster dimension has been specified. The preferred substitute cluster dimension must be an integer multiple greater than zero of the regular cluster dimension and must divide the grid. It must also be no more than `maxBlocksPerCluster`, if it is set in the kernel's `__launch_bounds__`. Otherwise it must be less than the maximum value the driver can support. Otherwise, setting this attribute to a value physically unable to fit on any particular device is permitted.
	LaunchAttributePreferredClusterDimension LaunchAttributeID = 11
	// LaunchAttributeLaunchCompletionEvent: Valid for launches. Set [LaunchAttributeValue].launchCompletionEvent to record the event. Nominally, the event is triggered once all blocks of the kernel have begun execution. Currently this is a best effort. If a kernel B has a launch completion dependency on a kernel A, B may wait until A is complete. Alternatively, blocks of B may begin before all blocks of A have begun, for example if B can claim execution resources unavailable to A (e.g. they run on different GPUs) or if B is a higher priority than A. Exercise caution if such an ordering inversion could lead to deadlock. A launch completion event is nominally similar to a programmatic event with triggerAtBlockStart set except that it is not visible to cudaGridDependencySynchronize() and can be used with compute capability less than 9.0. The event supplied must not be an interprocess or interop event. The event must disable timing (i.e. must be created with the [EventDisableTiming] flag set).
	LaunchAttributeLaunchCompletionEvent LaunchAttributeID = 12
	// LaunchAttributeDeviceUpdatableKernelNode: Valid for graph nodes, launches. This attribute is graphs-only, and passing it to a launch in a non-capturing stream will result in an error. [LaunchAttributeValue].deviceUpdatableKernelNode.deviceUpdatable can only be set to 0 or 1. Setting the field to 1 indicates that the corresponding kernel node should be device-updatable. On success, a handle will be returned via [LaunchAttributeValue].deviceUpdatableKernelNode.devNode which can be passed to the various device-side update functions to update the node's kernel parameters from within another kernel. For more information on the types of device updates that can be made, as well as the relevant limitations thereof, see cudaGraphKernelNodeUpdatesApply. Nodes which are device-updatable have additional restrictions compared to regular kernel nodes. Firstly, device-updatable nodes cannot be removed from their graph via [GraphNode.Close]. Additionally, once opted-in to this functionality, a node cannot opt out, and any attempt to set the deviceUpdatable attribute to 0 will result in an error. Device-updatable kernel nodes also cannot have their attributes copied to/from another kernel node via [KernelNode.CopyAttributes]. Graphs containing one or more device-updatable nodes also do not allow multiple instantiation, and neither the graph nor its instantiated version can be passed to [GraphExec.Update]. If a graph contains device-updatable nodes and updates those nodes from the device from within the graph, the graph must be uploaded with [GraphExec.Upload] before it is launched. For such a graph, if host-side executable graph updates are made to the device-updatable nodes, the graph must be uploaded before it is launched again.
	LaunchAttributeDeviceUpdatableKernelNode LaunchAttributeID = 13
	// LaunchAttributePreferredSharedMemoryCarveout: Valid for launches. On devices where the L1 cache and shared memory use the same hardware resources, setting [LaunchAttributeValue].sharedMemCarveout to a percentage between 0-100 signals the CUDA driver to set the shared memory carveout preference, in percent of the total shared memory for that kernel launch. This attribute takes precedence over [FuncAttributePreferredSharedMemoryCarveout]. This is only a hint, and the CUDA driver can choose a different configuration if required for the launch.
	LaunchAttributePreferredSharedMemoryCarveout LaunchAttributeID = 14
	// LaunchAttributeNvlinkUtilCentricScheduling: Valid for streams, graph nodes, launches. This attribute is a hint to the CUDA runtime that the launch should attempt to make the kernel maximize its NVLINK utilization. When possible to honor this hint, CUDA will assume each block in the grid launch will carry out an even amount of NVLINK traffic, and make a best-effort attempt to adjust the kernel launch based on that assumption. This attribute is a hint only. CUDA makes no functional or performance guarantee. Its applicability can be affected by many different factors, including driver version (i.e. CUDA doesn't guarantee the performance characteristics will be maintained between driver versions or a driver update could alter or regress previously observed perf characteristics.) It also doesn't guarantee a successful result, i.e. applying the attribute may not improve the performance of either the targeted kernel or the encapsulating application. Valid values for [LaunchAttributeValue].nvlinkUtilCentricScheduling are 0 (disabled) and 1 (enabled).
	LaunchAttributeNvlinkUtilCentricScheduling LaunchAttributeID = 16
	// LaunchAttributePortableClusterSizeMode: Valid for graph nodes, launches. This controls whether the kernel launch is allowed to use a non-portable cluster size. Valid values for [LaunchAttributeValue].portableClusterSizeMode are described in [LaunchAttributePortableClusterMode]. Any other value will return [ErrInvalidValue]
	LaunchAttributePortableClusterSizeMode LaunchAttributeID = 17
	// LaunchAttributeSharedMemoryMode: Valid for graph nodes, launches. This controls a kernel's use of non-portable or oversized shared memory configurations.
	LaunchAttributeSharedMemoryMode LaunchAttributeID = 18
)

func (LaunchAttributeID) String

func (e LaunchAttributeID) String() string

String returns the constant name, or a numeric representation for unknown values.

type LaunchAttributePortableClusterMode

type LaunchAttributePortableClusterMode int32

LaunchAttributePortableClusterMode is an enum for defining applicability of portable cluster size, used with Function.LaunchKernelEx.

const (
	// LaunchPortableClusterModeDefault: The default to use for allowing non-portable cluster size on launch - uses current function attribute for [FuncAttributeNonPortableClusterSizeAllowed]
	LaunchPortableClusterModeDefault LaunchAttributePortableClusterMode = 0
	// LaunchPortableClusterModeRequirePortable: Specifies that the cluster size requested must be a portable size
	LaunchPortableClusterModeRequirePortable LaunchAttributePortableClusterMode = 1
	// LaunchPortableClusterModeAllowNonPortable: Specifies that the cluster size requested may be a non-portable size
	LaunchPortableClusterModeAllowNonPortable LaunchAttributePortableClusterMode = 2
)

func (LaunchAttributePortableClusterMode) String

String returns the constant name, or a numeric representation for unknown values.

type LaunchAttributeValue

type LaunchAttributeValue struct {
	// Data stores the raw bytes of the underlying C union.
	Data [8]uint64
}

LaunchAttributeValue represents launch attributes union; used as value field of LaunchAttribute.

func (*LaunchAttributeValue) AccessPolicyWindow

func (l *LaunchAttributeValue) AccessPolicyWindow() *AccessPolicyWindow

AccessPolicyWindow returns a pointer to the accessPolicyWindow member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) ClusterDim

func (l *LaunchAttributeValue) ClusterDim() *Dim3

ClusterDim returns a pointer to the clusterDim member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) ClusterSchedulingPolicyPreference

func (l *LaunchAttributeValue) ClusterSchedulingPolicyPreference() *ClusterSchedulingPolicy

ClusterSchedulingPolicyPreference returns a pointer to the clusterSchedulingPolicyPreference member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) Cooperative

func (l *LaunchAttributeValue) Cooperative() *int32

Cooperative returns a pointer to the cooperative member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) DeviceUpdatableKernelNode

DeviceUpdatableKernelNode returns a pointer to the deviceUpdatableKernelNode member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) LaunchCompletionEvent

LaunchCompletionEvent returns a pointer to the launchCompletionEvent member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) MemSyncDomain

func (l *LaunchAttributeValue) MemSyncDomain() *LaunchMemSyncDomain

MemSyncDomain returns a pointer to the memSyncDomain member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) MemSyncDomainMap

func (l *LaunchAttributeValue) MemSyncDomainMap() *LaunchMemSyncDomainMap

MemSyncDomainMap returns a pointer to the memSyncDomainMap member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) NvlinkUtilCentricScheduling

func (l *LaunchAttributeValue) NvlinkUtilCentricScheduling() *uint32

NvlinkUtilCentricScheduling returns a pointer to the nvlinkUtilCentricScheduling member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) Pad

func (l *LaunchAttributeValue) Pad() *[64]byte

Pad returns a pointer to the pad member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) PortableClusterSizeMode

func (l *LaunchAttributeValue) PortableClusterSizeMode() *LaunchAttributePortableClusterMode

PortableClusterSizeMode returns a pointer to the portableClusterSizeMode member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) PreferredClusterDim

func (l *LaunchAttributeValue) PreferredClusterDim() *Dim3

PreferredClusterDim returns a pointer to the preferredClusterDim member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) Priority

func (l *LaunchAttributeValue) Priority() *int32

Priority returns a pointer to the priority member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) ProgrammaticEvent

ProgrammaticEvent returns a pointer to the programmaticEvent member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) ProgrammaticStreamSerializationAllowed

func (l *LaunchAttributeValue) ProgrammaticStreamSerializationAllowed() *int32

ProgrammaticStreamSerializationAllowed returns a pointer to the programmaticStreamSerializationAllowed member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) SharedMemCarveout

func (l *LaunchAttributeValue) SharedMemCarveout() *uint32

SharedMemCarveout returns a pointer to the sharedMemCarveout member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) SharedMemoryMode

func (l *LaunchAttributeValue) SharedMemoryMode() *SharedMemoryMode

SharedMemoryMode returns a pointer to the sharedMemoryMode member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

func (*LaunchAttributeValue) SyncPolicy

SyncPolicy returns a pointer to the syncPolicy member of CUlaunchAttributeValue, which shares its storage with every other member of the union.

type LaunchAttributeValueDeviceUpdatableKernelNode

type LaunchAttributeValueDeviceUpdatableKernelNode struct {
	DeviceUpdatable int32
	DevNode         GraphDeviceNode
}

LaunchAttributeValueDeviceUpdatableKernelNode is the type of the deviceUpdatableKernelNode member of LaunchAttributeValue.

type LaunchAttributeValueLaunchCompletionEvent

type LaunchAttributeValueLaunchCompletionEvent struct {
	Event Event
	Flags int32
}

LaunchAttributeValueLaunchCompletionEvent is the type of the launchCompletionEvent member of LaunchAttributeValue.

type LaunchAttributeValueProgrammaticEvent

type LaunchAttributeValueProgrammaticEvent struct {
	Event               Event
	Flags               int32
	TriggerAtBlockStart int32
}

LaunchAttributeValueProgrammaticEvent is the type of the programmaticEvent member of LaunchAttributeValue.

type LaunchConfig

type LaunchConfig struct {
	// X: Width of grid in blocks
	// Y: Height of grid in blocks
	// Z: Depth of grid in blocks
	GridDim Dim3
	// X: X dimension of each thread block
	// Y: Y dimension of each thread block
	// Z: Z dimension of each thread block
	BlockDim Dim3
	// Dynamic shared-memory size per thread block in bytes
	SharedMemBytes uint32
	// Stream identifier
	HStream Stream
	// List of attributes.
	// The call passes len(Attrs) as numAttrs.
	Attrs []LaunchAttribute
}

LaunchConfig represents CUDA extensible launch configuration.

type LaunchMemSyncDomain

type LaunchMemSyncDomain int32

LaunchMemSyncDomain represents memory Synchronization Domain.

A kernel can be launched in a specified memory synchronization domain that affects all memory operations issued by that kernel. A memory barrier issued in one domain will only order memory operations in that domain, thus eliminating latency increase from memory barriers ordering unrelated traffic. By default, kernels are launched in domain 0. Kernel launched with LaunchMemSyncDomainRemote will have a different domain ID. User may also alter the domain ID with LaunchMemSyncDomainMap for a specific stream / graph node / kernel launch. See LaunchAttributeMemSyncDomain, Stream.SetAttribute, Function.LaunchKernelEx, KernelNode.SetAttribute. Memory operations done in kernels launched in different domains are considered system-scope distanced. In other words, a GPU scoped memory synchronization is not sufficient for memory order to be observed by kernels in another memory synchronization domain even if they are on the same GPU.

const (
	LaunchMemSyncDomainDefault LaunchMemSyncDomain = 0 // Launch kernels in the default domain
	LaunchMemSyncDomainRemote  LaunchMemSyncDomain = 1 // Launch kernels in the remote domain
)

func (LaunchMemSyncDomain) String

func (e LaunchMemSyncDomain) String() string

String returns the constant name, or a numeric representation for unknown values.

type LaunchMemSyncDomainMap

type LaunchMemSyncDomainMap struct {
	// The default domain ID to use for designated kernels
	Default uint8
	// The remote domain ID to use for designated kernels
	Remote uint8
}

LaunchMemSyncDomainMap represents memory Synchronization Domain map.

See cudaLaunchMemSyncDomain. By default, kernels are launched in domain 0. Kernel launched with LaunchMemSyncDomainRemote will have a different domain ID. User may also alter the domain ID with LaunchMemSyncDomainMap for a specific stream / graph node / kernel launch. See LaunchAttributeMemSyncDomainMap. Domain ID range is available through DevAttrMemSyncDomainCount.

type LaunchParams

type LaunchParams struct {
	// Kernel to launch
	Function Function
	// X: Width of grid in blocks
	// Y: Height of grid in blocks
	// Z: Depth of grid in blocks
	GridDim Dim3
	// X: X dimension of each thread block
	// Y: Y dimension of each thread block
	// Z: Z dimension of each thread block
	BlockDim Dim3
	// Dynamic shared-memory size per thread block in bytes
	SharedMemBytes uint32
	// Stream identifier
	HStream Stream
	// Array of pointers to kernel parameters
	KernelParams uintptr
}

LaunchParams represents kernel launch parameters.

type LaunchParamsV1

type LaunchParamsV1 = LaunchParams

LaunchParamsV1 is an alias for LaunchParams.

type Library

type Library uintptr

Library is an opaque handle to a CUDA library. Used with the CUDA library management APIs.

func LibraryLoadData

func LibraryLoadData(code []byte, jitOptions *JITOption, jitOptionsValues *uintptr, numJitOptions uint32, libraryOptions *LibraryOption, libraryOptionValues *uintptr, numLibraryOptions uint32) (Library, error)

LibraryLoadData loads a library with specified code and options.

Takes code and loads the corresponding library library based on the application defined library loading mode:

  • If module loading is set to EAGER, via the environment variables described in “Module loading”, library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with Library.Close.
  • If the environment variables are set to LAZY, library is not immediately loaded onto all existent contexts and will only be loaded when a function is needed for that context, such as a kernel launch.

These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section. The code may be a cubin or fatbin as output by nvcc, or a PTX, either as output by nvcc or hand-written, or Tile IR data. A fatbin should also contain relocatable code when doing separate compilation. Options are passed as an array via jitOptions and any corresponding parameters are passed in jitOptionsValues. The number of total JIT options is supplied via numJitOptions. Any outputs will be returned via jitOptionsValues. Library load options are passed as an array via libraryOptions and any corresponding parameters are passed in libraryOptionValues. The number of total library load options is supplied via numLibraryOptions.

Note: If the library contains managed variables and no device in the system supports managed variables this call is expected to return ErrNotSupported

See also: LibraryLoadFromFile, Library.Close, ModuleLoad, ModuleLoadData, ModuleLoadDataEx

  • code: Code to load
  • jitOptions: Options for JIT
  • jitOptionsValues: Option values for JIT
  • numJitOptions: Number of options
  • libraryOptions: Options for loading
  • libraryOptionValues: Option values for loading
  • numLibraryOptions: Number of options for loading

Errors:

The wrapper passes code to C without copying if a NUL byte ends it or follows it in its capacity, as one does in text a generated getter returns, or if it starts with the ELF or fatbin magic number. Otherwise code is text, and the wrapper copies it once to append a NUL.

Wraps cuLibraryLoadData.

func LibraryLoadFromFile

func LibraryLoadFromFile(fileName string, jitOptions *JITOption, jitOptionsValues *uintptr, numJitOptions uint32, libraryOptions *LibraryOption, libraryOptionValues *uintptr, numLibraryOptions uint32) (Library, error)

LibraryLoadFromFile loads a library with specified file and options.

Takes a pointer code and loads the corresponding library library based on the application defined library loading mode:

  • If module loading is set to EAGER, via the environment variables described in “Module loading”, library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with Library.Close.
  • If the environment variables are set to LAZY, library is not immediately loaded onto all existent contexts and will only be loaded when a function is needed for that context, such as a kernel launch.

These environment variables are described in the CUDA programming guide under the “CUDA environment variables” section. The file should be a cubin file as output by nvcc, or a PTX file either as output by nvcc or handwritten, or a fatbin file as output by nvcc or hand-written, or Tile IR file. A fatbin should also contain relocatable code when doing separate compilation. Options are passed as an array via jitOptions and any corresponding parameters are passed in jitOptionsValues. The number of total options is supplied via numJitOptions. Any outputs will be returned via jitOptionsValues. Library load options are passed as an array via libraryOptions and any corresponding parameters are passed in libraryOptionValues. The number of total library load options is supplied via numLibraryOptions.

Note: If the library contains managed variables and no device in the system supports managed variables this call is expected to return ErrNotSupported

See also: LibraryLoadData, Library.Close, ModuleLoad, ModuleLoadData, ModuleLoadDataEx

  • fileName: File to load from
  • jitOptions: Options for JIT
  • jitOptionsValues: Option values for JIT
  • numJitOptions: Number of options
  • libraryOptions: Options for loading
  • libraryOptionValues: Option values for loading
  • numLibraryOptions: Number of options for loading

Errors:

Wraps cuLibraryLoadFromFile.

func (*Library) Close

func (l *Library) Close() error

Close unloads a library.

Unloads the library specified with library

See also: LibraryLoadData, LibraryLoadFromFile, Module.Close

Errors:

If l is zero, Close returns nil. Otherwise Close sets l to zero when the call succeeds and leaves it unchanged when it fails. Only l is zeroed: a copy of it still refers to the released object.

Wraps cuLibraryUnload.

func (Library) EnumerateKernels

func (l Library) EnumerateKernels(kernels *Kernel, numKernels uint32) error

EnumerateKernels retrieves the kernel handles within a library.

Returns in kernels a maximum number of numKernels kernel handles within lib. The returned kernel handle becomes invalid when the library is unloaded.

See also: Library.KernelCount

Requires CUDA 12.4 (driver r550) or later; see HasLibraryEnumerateKernels.

  • kernels: Buffer where the kernel handles are returned to
  • numKernels: Maximum number of kernel handles may be returned to the buffer

Errors:

Wraps cuLibraryEnumerateKernels.

func (Library) Global

func (l Library) Global(name string) (dptr DevicePtr, bytes uint, err error)

Global returns a global device pointer.

Returns in *dptr and *bytes the base pointer and size of the global with name name for the requested library library and the current context. If no global for the requested name name exists, the call returns ErrNotFound. One of the parameters dptr or bytes (not both) can be NULL in which case it is ignored.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Library.Module, Module.Global

  • dptr: Returned global device pointer for the requested context
  • bytes: Returned global size in bytes
  • name: Name of global to retrieve

Errors:

Wraps cuLibraryGetGlobal.

func (Library) Kernel

func (l Library) Kernel(name string) (Kernel, error)

Kernel returns a kernel handle.

Returns the handle of the kernel with name name located in library library. If kernel handle is not found, the call returns ErrNotFound.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Kernel.Function, Library.Module, Module.Function

  • name: Name of kernel to retrieve

Errors:

Wraps cuLibraryGetKernel.

func (Library) KernelCount

func (l Library) KernelCount() (uint32, error)

KernelCount returns the number of kernels within a library.

Returns the number of kernels in lib.

Requires CUDA 12.4 (driver r550) or later; see HasLibraryGetKernelCount.

Errors:

Wraps cuLibraryGetKernelCount.

func (Library) Managed

func (l Library) Managed(name string) (dptr DevicePtr, bytes uint, err error)

Managed returns a pointer to managed memory.

Returns in *dptr and *bytes the base pointer and size of the managed memory with name name for the requested library library. If no managed memory with the requested name name exists, the call returns ErrNotFound. One of the parameters dptr or bytes (not both) can be NULL in which case it is ignored. Note that managed memory for library library is shared across devices and is registered when the library is loaded into atleast one context.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close

  • dptr: Returned pointer to the managed memory
  • bytes: Returned memory size in bytes
  • name: Name of managed memory to retrieve

Errors:

Wraps cuLibraryGetManaged.

func (Library) Module

func (l Library) Module() (Module, error)

Module returns a module handle.

Returns the module handle associated with the current context located in library library. If module handle is not found, the call returns ErrNotFound.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close, Module.Function

Errors:

Wraps cuLibraryGetModule.

func (Library) UnifiedFunction

func (l Library) UnifiedFunction(symbol string) (uintptr, error)

UnifiedFunction returns a pointer to a unified function.

Returns the function pointer to a unified function denoted by symbol. If no unified function with name symbol exists, the call returns ErrNotFound. If there is no device with attribute DevAttrUnifiedFunctionPointers present in the system, the call may return ErrNotFound.

See also: LibraryLoadData, LibraryLoadFromFile, Library.Close

  • symbol: Name of function pointer to retrieve

Errors:

Wraps cuLibraryGetUnifiedFunction.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

LibraryAttempt records one failed attempt to open the shared library.

type LibraryConflictError

type LibraryConflictError struct {
	Loaded    string
	Requested string

	// Implicit reports that the loaded library was opened lazily and no
	// successful Load has since acknowledged it. A
	// caller that sees this called some
	// other function first, and that call took the default search list.
	Implicit bool
}

LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.

func (*LibraryConflictError) Error

func (e *LibraryConflictError) Error() string

Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.

type LibraryError

type LibraryError struct {
	Library  string
	Env      string
	Path     string
	Attempts []LibraryAttempt
	Hint     string
}

LibraryError reports that libcuda could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or CUDA_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.

func (*LibraryError) Error

func (e *LibraryError) Error() string

Error describes the library load attempts and their errors.

func (*LibraryError) Unwrap

func (e *LibraryError) Unwrap() []error

Unwrap returns the error from each attempt.

type LibraryHostUniversalFunctionAndDataTable

type LibraryHostUniversalFunctionAndDataTable struct {
	FunctionTable      uintptr
	FunctionWindowSize uint
	DataTable          uintptr
	DataWindowSize     uint
}

LibraryHostUniversalFunctionAndDataTable represents CUlibraryHostUniversalFunctionAndDataTable.

type LibraryOption

type LibraryOption int32

LibraryOption represents library options to be specified with LibraryLoadData or LibraryLoadFromFile.

const (
	LibraryOptionLibraryHostUniversalFunctionAndDataTable LibraryOption = 0
	// LibraryBinaryIsPreserved: Specifes that the argument code passed to [LibraryLoadData] will be preserved. Specifying this option will let the driver know that code can be accessed at any point until [Library.Close]. The default behavior is for the driver to allocate and maintain its own copy of code. Note that this is only a memory usage optimization hint and the driver can choose to ignore it if required. Specifying this option with [LibraryLoadFromFile] is invalid and will return [ErrInvalidValue].
	LibraryBinaryIsPreserved LibraryOption = 1
	LibraryNumOptions        LibraryOption = 2
)

func (LibraryOption) String

func (e LibraryOption) String() string

String returns the constant name, or a numeric representation for unknown values.

type Limit

type Limit uint32

Limit represents limits.

const (
	LimitStackSize                    Limit = 0x00 // GPU thread stack size
	LimitPrintfFifoSize               Limit = 0x01 // GPU printf FIFO size
	LimitMallocHeapSize               Limit = 0x02 // GPU malloc heap size
	LimitDevRuntimeSyncDepth          Limit = 0x03 // GPU device runtime launch synchronize depth
	LimitDevRuntimePendingLaunchCount Limit = 0x04 // GPU device runtime pending launch count
	// LimitMaxL2FetchGranularity: A value between 0 and 128 that indicates the maximum fetch granularity of L2 (in Bytes). This is a hint
	LimitMaxL2FetchGranularity Limit = 0x05
	LimitPersistingL2CacheSize Limit = 0x06 // A size in bytes for L2 persisting lines cache size
	// LimitShmemSize: A maximum size in bytes of shared memory available to CUDA kernels on a CIG context. Can only be queried, cannot be set
	LimitShmemSize Limit = 0x07
	// LimitCigEnabled: A non-zero value indicates this CUDA context is a CIG-enabled context. Can only be queried, cannot be set
	LimitCigEnabled Limit = 0x08
	// LimitCigShmemFallbackEnabled: When set to zero, CUDA will fail to launch a kernel on a CIG context, instead of using the fallback path, if the kernel uses more shared memory than available
	LimitCigShmemFallbackEnabled Limit = 0x09
	LimitPerBlockMemorySize      Limit = 0x0A // Per-block memory size
)

func (Limit) String

func (e Limit) String() string

String returns the constant name, or a numeric representation for unknown values.

type LinkState

type LinkState uintptr

LinkState is an opaque handle for CUlinkState.

func LinkCreate

func LinkCreate(numOptions uint32, options *JITOption, optionValues *uintptr) (LinkState, error)

LinkCreate creates a pending JIT linker invocation.

If the call is successful, the caller owns the returned LinkState, which should eventually be destroyed with LinkState.Close. The device code machine size (32 or 64 bit) will match the calling application. Both linker and compiler options may be specified. Compiler options will be applied to inputs to this linker action which must be compiled from PTX. The options JITWallTime, JITInfoLogBufferSizeBytes, and JITErrorLogBufferSizeBytes will accumulate data until the LinkState is destroyed. The data passed in via LinkState.AddData and LinkState.AddFile will be treated as relocatable (-rdc=true to nvcc) when linking the final cubin during LinkState.Complete and will have similar consequences as offline relocatable device code linking. optionValues must remain valid for the life of the LinkState if output options are used. No other references to inputs are maintained after this call returns.

Note: For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted

See also: LinkState.AddData, LinkState.AddFile, LinkState.Complete, LinkState.Close

  • numOptions: Size of options arrays
  • options: Array of linker and compiler options
  • optionValues: Array of option values, each cast to void *

Errors:

Wraps cuLinkCreate, bound as cuLinkCreate_v2.

func (LinkState) AddData

func (l LinkState) AddData(type_ JitInputType, data []byte, name *byte, numOptions uint32, options *JITOption, optionValues *uintptr) error

AddData adds an input to a pending linker invocation.

Ownership of data is retained by the caller. No reference is retained to any inputs after this call returns. This method accepts only compiler options, which are used if the data must be compiled from PTX, and does not accept any of JITWallTime, JITInfoLogBuffer, JITErrorLogBuffer, JITTargetFromCucontext, or JITTarget.

Note: For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted

See also: LinkCreate, LinkState.AddFile, LinkState.Complete, LinkState.Close

  • type_: The type of the input data
  • data: The input data
  • name: An optional name for this input in log messages
  • numOptions: Size of options
  • options: Options to be applied only for this input (overrides options from LinkCreate)
  • optionValues: Array of option values, each cast to void *

Errors:

The wrapper passes data to C without copying if a NUL byte ends it or follows it in its capacity, as one does in text a generated getter returns, or if it starts with the ELF or fatbin magic number. Otherwise data is text, and the wrapper copies it once to append a NUL.

Wraps cuLinkAddData, bound as cuLinkAddData_v2.

func (LinkState) AddFile

func (l LinkState) AddFile(type_ JitInputType, path *byte, numOptions uint32, options *JITOption, optionValues *uintptr) error

AddFile adds a file input to a pending linker invocation.

No reference is retained to any inputs after this call returns. This method accepts only compiler options, which are used if the input must be compiled from PTX, and does not accept any of JITWallTime, JITInfoLogBuffer, JITErrorLogBuffer, JITTargetFromCucontext, or JITTarget. This method is equivalent to invoking LinkState.AddData on the contents of the file.

Note: For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 will be accepted

See also: LinkCreate, LinkState.AddData, LinkState.Complete, LinkState.Close

  • type_: The type of the input data
  • path: Path to the input file
  • numOptions: Size of options
  • options: Options to be applied only for this input (overrides options from LinkCreate)
  • optionValues: Array of option values, each cast to void *

Errors:

Wraps cuLinkAddFile, bound as cuLinkAddFile_v2.

func (*LinkState) Close

func (l *LinkState) Close() error

Close destroys state for a JIT linker invocation.

See also: LinkCreate

Errors:

If l is zero, Close returns nil. Otherwise Close sets l to zero when the call succeeds and leaves it unchanged when it fails. Only l is zeroed: a copy of it still refers to the released object.

Wraps cuLinkDestroy.

func (LinkState) Complete

func (l LinkState) Complete() (cubinOut uintptr, sizeOut uint, err error)

Complete completes a pending linker invocation.

Completes the pending linker action and returns the cubin image for the linked device code, which can be used with ModuleLoadData. The cubin is owned by state, so it should be loaded before state is destroyed via LinkState.Close. This call does not destroy state.

See also: LinkCreate, LinkState.AddData, LinkState.AddFile, LinkState.Close, ModuleLoadData

  • cubinOut: On success, this will point to the output image
  • sizeOut: Optional parameter to receive the size of the generated image

Errors:

Wraps cuLinkComplete.

type LogLevel

type LogLevel int32

LogLevel specifies the log level (CUlogLevel).

const (
	LogLevelError   LogLevel = 0
	LogLevelWarning LogLevel = 1
)

func (LogLevel) String

func (e LogLevel) String() string

String returns the constant name, or a numeric representation for unknown values.

type LogicalEndpointFabricHandle

type LogicalEndpointFabricHandle struct {
	Data [64]uint8
}

LogicalEndpointFabricHandle represents fabric handle for a logical endpoint.

type LogicalEndpointFlag

type LogicalEndpointFlag int32

LogicalEndpointFlag represents flags for LogicalEndpointProp.

const (
	LogicalEndpointFlagNone LogicalEndpointFlag = 0x0 // Default flag for logical endpoint construction
	// LogicalEndpointFlagCountedOps: Indicate the programmer's intention to use counted operations with the logical endpoint
	LogicalEndpointFlagCountedOps LogicalEndpointFlag = 0x1
)

func (LogicalEndpointFlag) String

func (e LogicalEndpointFlag) String() string

String returns the constant name, or a numeric representation for unknown values.

type LogicalEndpointId

type LogicalEndpointId uint32

LogicalEndpointId represents CUlogicalEndpointId.

func LogicalEndpointIdReserve

func LogicalEndpointIdReserve(count uint32) (LogicalEndpointId, error)

LogicalEndpointIdReserve reserves a range of logical endpoint ids.

Reserves a range of logical endpoint ids starting at *baseLeId and extending for count. The reserved ids can be used to create or import logical endpoints via LogicalEndpointCreate or LogicalEndpointImport respectively.

See also: LogicalEndpointCreate, Device.LogicalEndpointAdd, LogicalEndpointDestroy, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem, Device.LogicalEndpointUnbind, LogicalEndpointExport, LogicalEndpointImport, LogicalEndpointGetLimits, LogicalEndpointQuery

Requires CUDA 13.3 (driver r610) or later; see HasLogicalEndpointIdReserve.

  • count: The number of logical endpoint ids to reserve

Errors:

Wraps cuLogicalEndpointIdReserve.

type LogicalEndpointIpcHandleType

type LogicalEndpointIpcHandleType int32

LogicalEndpointIpcHandleType represents IPC handle types that can be requested/queried for a given logical endpoint.

const (
	LogicalEndpointIpcHandleTypeNone LogicalEndpointIpcHandleType = 0 // Does not allow any export mechanism
	// LogicalEndpointIpcHandleTypeFabric: Allows export to a fabric handle ([LogicalEndpointFabricHandle])
	LogicalEndpointIpcHandleTypeFabric LogicalEndpointIpcHandleType = 1
)

func (LogicalEndpointIpcHandleType) String

String returns the constant name, or a numeric representation for unknown values.

type LogicalEndpointProp

type LogicalEndpointProp struct {
	// Type of the logical endpoint defined in [LogicalEndpointType]
	Type           LogicalEndpointType
	AnonymousUnion [1]uint32
	// Size of the logical endpoint
	Size uint64
	// A bitmask of IPC handle types defined in [LogicalEndpointIpcHandleType]
	IpcHandleTypes uint32
	// A bitmask of flags defined in [LogicalEndpointFlag]
	Flags uint32
}

LogicalEndpointProp represents properties of a logical endpoint construction.

func (*LogicalEndpointProp) Multicast

Multicast returns a pointer to the multicast member of CUlogicalEndpointProp, which shares its storage with every other member of the union.

func (*LogicalEndpointProp) Unicast

Unicast returns a pointer to the unicast member of CUlogicalEndpointProp, which shares its storage with every other member of the union.

type LogicalEndpointPropMulticast

type LogicalEndpointPropMulticast struct {
	NumDevices uint32
}

LogicalEndpointPropMulticast is the type of the multicast member of LogicalEndpointProp.

type LogicalEndpointPropUnicast

type LogicalEndpointPropUnicast struct {
	Device Device
}

LogicalEndpointPropUnicast is the type of the unicast member of LogicalEndpointProp.

type LogicalEndpointType

type LogicalEndpointType int32

LogicalEndpointType represents logical endpoint type.

const (
	LogicalEndpointTypeInvalid   LogicalEndpointType = 0
	LogicalEndpointTypeUnicast   LogicalEndpointType = 1
	LogicalEndpointTypeMulticast LogicalEndpointType = 2
)

func (LogicalEndpointType) String

func (e LogicalEndpointType) String() string

String returns the constant name, or a numeric representation for unknown values.

type LogsCallback

type LogsCallback func(data uintptr, logLevel LogLevel, message uintptr, length uint)

LogsCallback is the Go form of CUlogsCallback.

It corresponds to the C signature

typedef void (CUDA_CB *CUlogsCallback)(void *data, CUlogLevel logLevel, char *message, size_t length);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type LogsCallbackHandle

type LogsCallbackHandle uintptr

LogsCallbackHandle is an opaque handle for CUlogsCallbackHandle.

func LogsRegisterCallback

func LogsRegisterCallback(callbackFunc uintptr, userData uintptr) (LogsCallbackHandle, error)

LogsRegisterCallback registers a callback function to receive error log messages.

Requires CUDA 12.9 (driver r575) or later; see HasLogsRegisterCallback.

  • callbackFunc: The function to register as a callback (see LogsCallback)
  • userData: A generic pointer to user data. This is passed into the callback function

Errors:

Wraps cuLogsRegisterCallback.

func (*LogsCallbackHandle) Close

func (l *LogsCallbackHandle) Close() error

Close unregisters a log message callback.

Requires CUDA 12.9 (driver r575) or later; see HasLogsUnregisterCallback.

Errors:

If l is zero, Close returns nil. Otherwise Close sets l to zero when the call succeeds and leaves it unchanged when it fails. Only l is zeroed: a copy of it still refers to the released object.

Wraps cuLogsUnregisterCallback.

type MemAccessDesc

type MemAccessDesc struct {
	// Location on which the request is to change it's accessibility
	Location MemLocation
	// CUmemProt accessibility flags to set on the request
	Flags MemaccessFlags
}

MemAccessDesc represents memory access descriptor.

type MemAccessDescV1

type MemAccessDescV1 = MemAccessDesc

MemAccessDescV1 is an alias for MemAccessDesc.

type MemAdvise

type MemAdvise int32

MemAdvise represents memory advise values.

const (
	MemAdviseSetReadMostly   MemAdvise = 1 // Data will mostly be read and only occasionally be written to
	MemAdviseUnsetReadMostly MemAdvise = 2 // Undo the effect of [MemAdviseSetReadMostly]
	// MemAdviseSetPreferredLocation: Set the preferred location for the data as the specified device
	MemAdviseSetPreferredLocation   MemAdvise = 3
	MemAdviseUnsetPreferredLocation MemAdvise = 4 // Clear the preferred location for the data
	// MemAdviseSetAccessedBy: Data will be accessed by the specified device, so prevent page faults as much as possible
	MemAdviseSetAccessedBy MemAdvise = 5
	// MemAdviseUnsetAccessedBy: Let the Unified Memory subsystem decide on the page faulting policy for the specified device
	MemAdviseUnsetAccessedBy MemAdvise = 6
)

func (MemAdvise) String

func (e MemAdvise) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemAllocNode

type MemAllocNode struct {
	GraphNode
}

MemAllocNode is a GraphNode of the mem alloc kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the MemAllocNode one takes the kind's own types.

func (MemAllocNode) Params

func (m MemAllocNode) Params() (MemAllocNodeParams, error)

Params returns a memory alloc node’s parameters.

Returns the parameters of a memory alloc node hNode. The poolProps and accessDescs returned, are owned by the node. This memory remains valid until the node is destroyed. The returned parameters must not be modified.

See also: GraphNode.Params, Graph.AddMemAllocNode, MemFreeNode.Params

Errors:

Wraps cuGraphMemAllocNodeGetParams.

type MemAllocNodeParams

type MemAllocNodeParams struct {
	PoolProps MemPoolProps
	// in: array of memory access descriptors. Used to describe peer GPU access
	AccessDescs uintptr
	// in: number of memory access descriptors. Must not exceed the number of GPUs.
	AccessDescCount uint
	// in: size in bytes of the requested allocation
	Bytesize uint
	// out: address of the allocation returned by CUDA
	Dptr DevicePtr
}

MemAllocNodeParams represents memory allocation node parameters.

type MemAllocNodeParamsV1

type MemAllocNodeParamsV1 = MemAllocNodeParams

MemAllocNodeParamsV1 is an alias for MemAllocNodeParams.

type MemAllocNodeParamsV2

type MemAllocNodeParamsV2 struct {
	PoolProps MemPoolProps
	// in: array of memory access descriptors. Used to describe peer GPU access
	AccessDescs uintptr
	// in: number of memory access descriptors. Must not exceed the number of GPUs.
	AccessDescCount uint
	// in: size in bytes of the requested allocation
	Bytesize uint
	// out: address of the allocation returned by CUDA
	Dptr DevicePtr
}

MemAllocNodeParamsV2 represents memory allocation node parameters.

type MemAllocationCompType

type MemAllocationCompType int32

MemAllocationCompType specifies compression attribute for an allocation.

const (
	MemAllocationCompNone    MemAllocationCompType = 0x0 // Allocating non-compressible memory
	MemAllocationCompGeneric MemAllocationCompType = 0x1 // Allocating compressible memory
)

func (MemAllocationCompType) String

func (e MemAllocationCompType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemAllocationHandleType

type MemAllocationHandleType int32

MemAllocationHandleType represents flags for specifying particular handle types.

const (
	MemHandleTypeNone MemAllocationHandleType = 0x0 // Does not allow any export mechanism. >
	// MemHandleTypePosixFileDescriptor: Allows a file descriptor to be used for exporting. Permitted only on POSIX systems. (int)
	MemHandleTypePosixFileDescriptor MemAllocationHandleType = 0x1
	MemHandleTypeWin32               MemAllocationHandleType = 0x2 // Allows a Win32 NT handle to be used for exporting. (HANDLE)
	// MemHandleTypeWin32Kmt: Allows a Win32 KMT handle to be used for exporting. (D3DKMT_HANDLE)
	MemHandleTypeWin32Kmt MemAllocationHandleType = 0x4
	// MemHandleTypeFabric: Allows a fabric handle to be used for exporting. ([MemFabricHandle])
	MemHandleTypeFabric MemAllocationHandleType = 0x8
)

func (MemAllocationHandleType) String

func (e MemAllocationHandleType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemAllocationProp

type MemAllocationProp struct {
	Type                 MemAllocationType
	RequestedHandleTypes MemAllocationHandleType
	Location             MemLocation
	Win32HandleMetaData  uintptr
	AllocFlags           [4]uint16
}

MemAllocationProp specifies the allocation properties for a allocation.

func MemGetAllocationPropertiesFromHandle

func MemGetAllocationPropertiesFromHandle(handle uint64) (MemAllocationProp, error)

MemGetAllocationPropertiesFromHandle retrieves the contents of the property structure defining properties for this handle.

See also: MemCreate, MemImportFromShareableHandle

  • handle: Handle which to perform the query on

Errors:

Wraps cuMemGetAllocationPropertiesFromHandle.

type MemAllocationPropV1

type MemAllocationPropV1 = MemAllocationProp

MemAllocationPropV1 is an alias for MemAllocationProp.

type MemAllocationType

type MemAllocationType int32

MemAllocationType defines the allocation types available.

const (
	MemAllocationTypeInvalid MemAllocationType = 0x0
	MemAllocationTypePinned  MemAllocationType = 0x1
	MemAllocationTypeManaged MemAllocationType = 0x2
)

func (MemAllocationType) String

func (e MemAllocationType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemDecompressAlgorithm

type MemDecompressAlgorithm int32

MemDecompressAlgorithm represents bitmasks for DevAttrMemDecompressAlgorithmMask.

const (
	MemDecompressUnsupported      MemDecompressAlgorithm = 0      // Decompression is unsupported.
	MemDecompressAlgorithmDeflate MemDecompressAlgorithm = 1 << 0 // Deflate is supported.
	MemDecompressAlgorithmSnappy  MemDecompressAlgorithm = 1 << 1 // Snappy is supported.
	MemDecompressAlgorithmLZ4     MemDecompressAlgorithm = 1 << 2 // LZ4 is supported.
)

func (MemDecompressAlgorithm) String

func (e MemDecompressAlgorithm) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemDecompressParams

type MemDecompressParams struct {
	SrcNumBytes uint
	DstNumBytes uint
	DstActBytes uintptr
	Src         uintptr
	Dst         uintptr
	Algo        MemDecompressAlgorithm
	Padding     [20]uint8
}

MemDecompressParams describes the parameters that compose a single decompression operation.

type MemFabricHandle

type MemFabricHandle struct {
	Data [64]uint8
}

MemFabricHandle represents fabric handle - An opaque handle representing a memory allocation that can be exported to processes in same or different nodes. For IPC between processes on different nodes they must be connected via the NVSwitch fabric.

type MemFabricHandleV1

type MemFabricHandleV1 = MemFabricHandle

MemFabricHandleV1 is an alias for MemFabricHandle.

type MemFreeNode

type MemFreeNode struct {
	GraphNode
}

MemFreeNode is a GraphNode of the mem free kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the MemFreeNode one takes the kind's own types.

func (MemFreeNode) Params

func (m MemFreeNode) Params() (DevicePtr, error)

Params returns a memory free node’s parameters.

Returns the address of a memory free node hNode.

See also: GraphNode.Params, Graph.AddMemFreeNode, MemAllocNode.Params

Errors:

Wraps cuGraphMemFreeNodeGetParams.

type MemFreeNodeParams

type MemFreeNodeParams struct {
	// in: the pointer to free
	Dptr DevicePtr
}

MemFreeNodeParams represents memory free node parameters.

type MemHandleType

type MemHandleType int32

MemHandleType represents memory handle types.

const (
	MemHandleTypeGeneric MemHandleType = 0
)

func (MemHandleType) String

func (e MemHandleType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemLocation

type MemLocation struct {
	// Specifies the location type, which modifies the meaning of id.
	Type MemLocationType
	Id   int32
}

MemLocation specifies a memory location.

func (*MemLocation) Localized

func (m *MemLocation) Localized() *MemLocationLocalized

Localized returns a pointer to the localized member of CUmemLocation_v1, which shares its storage with every other member of the union.

type MemLocationLocalized

type MemLocationLocalized struct {
	DeviceId         uint8
	LocalityDomainId uint8
}

MemLocationLocalized is the type of the localized member of MemLocation.

type MemLocationType

type MemLocationType int32

MemLocationType specifies the type of location.

const (
	MemLocationTypeInvalid MemLocationType = 0x0
	// MemLocationTypeNone: Location is unspecified. This is used when creating a managed memory pool to indicate no preferred location for the pool
	MemLocationTypeNone     MemLocationType = 0x0
	MemLocationTypeDevice   MemLocationType = 0x1 // Location is a device location, thus id is a device ordinal
	MemLocationTypeHost     MemLocationType = 0x2 // Location is host, id is ignored
	MemLocationTypeHostNuma MemLocationType = 0x3 // Location is a host NUMA node, thus id is a host NUMA node id
	// MemLocationTypeHostNumaCurrent: Location is a host NUMA node of the current thread, id is ignored
	MemLocationTypeHostNumaCurrent MemLocationType = 0x4
	// MemLocationTypeInvisible: Location is not visible but device is accessible, id is always CU_DEVICE_INVALID
	MemLocationTypeInvisible MemLocationType = 0x5
	// MemLocationTypeDeviceLocalityDomain: Location is a portion of device memory, specified by the locality domain ID.
	MemLocationTypeDeviceLocalityDomain MemLocationType = 0x6
)

func (MemLocationType) String

func (e MemLocationType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemLocationV1

type MemLocationV1 = MemLocation

MemLocationV1 is an alias for MemLocation.

type MemOperationType

type MemOperationType int32

MemOperationType represents memory operation types.

const (
	MemOperationTypeMap   MemOperationType = 1
	MemOperationTypeUnmap MemOperationType = 2
)

func (MemOperationType) String

func (e MemOperationType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemPoolProps

type MemPoolProps struct {
	// Allocation type. Currently must be specified as [MemAllocationTypePinned]
	AllocType MemAllocationType
	// Handle types that will be supported by allocations from the pool.
	HandleTypes MemAllocationHandleType
	// Location where allocations should reside.
	Location                MemLocation
	Win32SecurityAttributes uintptr
	// Maximum pool size. When set to 0, defaults to a system dependent value.
	MaxSize uint
	// Bitmask indicating intended usage for the pool.
	Usage                uint16
	GpuDirectRDMACapable uint8
	// reserved for future use, must be 0
	Reserved [53]uint8
}

MemPoolProps specifies the properties of allocations made from the pool.

type MemPoolPropsV1

type MemPoolPropsV1 = MemPoolProps

MemPoolPropsV1 is an alias for MemPoolProps.

type MemPoolPtrExportData

type MemPoolPtrExportData struct {
	Reserved [64]uint8
}

MemPoolPtrExportData represents opaque data for exporting a pool allocation.

type MemPoolPtrExportDataV1

type MemPoolPtrExportDataV1 = MemPoolPtrExportData

MemPoolPtrExportDataV1 is an alias for MemPoolPtrExportData.

type MemRangeAttribute

type MemRangeAttribute int32

MemRangeAttribute specifies the mem range attribute (CUmem_range_attribute).

const (
	// MemRangeAttributeReadMostly: Whether the range will mostly be read and only occasionally be written to
	MemRangeAttributeReadMostly        MemRangeAttribute = 1
	MemRangeAttributePreferredLocation MemRangeAttribute = 2 // The preferred location of the range
	// MemRangeAttributeAccessedBy: Memory range has [MemAdviseSetAccessedBy] set for specified device
	MemRangeAttributeAccessedBy               MemRangeAttribute = 3
	MemRangeAttributeLastPrefetchLocation     MemRangeAttribute = 4 // The last location to which the range was prefetched
	MemRangeAttributePreferredLocationType    MemRangeAttribute = 5 // The preferred location type of the range
	MemRangeAttributePreferredLocationId      MemRangeAttribute = 6 // The preferred location id of the range
	MemRangeAttributeLastPrefetchLocationType MemRangeAttribute = 7 // The last location type to which the range was prefetched
	MemRangeAttributeLastPrefetchLocationId   MemRangeAttribute = 8 // The last location id to which the range was prefetched
)

func (MemRangeAttribute) String

func (e MemRangeAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemRangeFlags

type MemRangeFlags int32

MemRangeFlags represents flag for requesting handle type for address range.

const (
	MemRangeFlagDmaBufMappingTypePcie MemRangeFlags = 0x1 // Indicates that DMA_BUF handle should be mapped via PCIe BAR1
)

func (MemRangeFlags) String

func (e MemRangeFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemRangeHandleType

type MemRangeHandleType int32

MemRangeHandleType specifies the handle type for address range.

const (
	MemRangeHandleTypeDmaBufFd MemRangeHandleType = 0x1
)

func (MemRangeHandleType) String

func (e MemRangeHandleType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemaccessFlags

type MemaccessFlags int32

MemaccessFlags specifies the memory protection flags for mapping.

const (
	MemAccessFlagsProtNone      MemaccessFlags = 0x0 // Default, make the address range not accessible
	MemAccessFlagsProtRead      MemaccessFlags = 0x1 // Make the address range read accessible
	MemAccessFlagsProtReadwrite MemaccessFlags = 0x3 // Make the address range read-write accessible
)

func (MemaccessFlags) String

func (e MemaccessFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemallocationgranularityFlags

type MemallocationgranularityFlags int32

MemallocationgranularityFlags represents flag for requesting different optimal and required granularities for an allocation.

const (
	MemAllocGranularityMinimum     MemallocationgranularityFlags = 0x0 // Minimum required granularity for allocation
	MemAllocGranularityRecommended MemallocationgranularityFlags = 0x1 // Recommended granularity for allocation for best performance
)

func (MemallocationgranularityFlags) String

String returns the constant name, or a numeric representation for unknown values.

type MemattachFlags

type MemattachFlags int32

MemattachFlags represents CUDA Mem Attach Flags.

const (
	MemAttachGlobal MemattachFlags = 0x1 // Memory can be accessed by any stream on any device
	MemAttachHost   MemattachFlags = 0x2 // Memory cannot be accessed by any stream on any device
	// MemAttachSingle: Memory can only be accessed by a single stream on the associated device
	MemAttachSingle MemattachFlags = 0x4
)

func (MemattachFlags) String

func (e MemattachFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type Memcpy2d

type Memcpy2d struct {
	// Source X in bytes
	SrcXInBytes uint
	// Source Y
	SrcY uint
	// Source memory type (host, device, array)
	SrcMemoryType MemoryType
	// Source host pointer
	SrcHost uintptr
	// Source device pointer
	SrcDevice DevicePtr
	// Source array reference
	SrcArray Array
	// Source pitch (ignored when src is array)
	SrcPitch uint
	// Destination X in bytes
	DstXInBytes uint
	// Destination Y
	DstY uint
	// Destination memory type (host, device, array)
	DstMemoryType MemoryType
	// Destination host pointer
	DstHost uintptr
	// Destination device pointer
	DstDevice DevicePtr
	// Destination array reference
	DstArray Array
	// Destination pitch (ignored when dst is array)
	DstPitch uint
	// Width of 2D memory copy in bytes
	WidthInBytes uint
	// Height of 2D memory copy
	Height uint
}

Memcpy2d represents 2D memory copy parameters.

type Memcpy2dV2

type Memcpy2dV2 = Memcpy2d

Memcpy2dV2 is an alias for Memcpy2d.

type Memcpy3DOperand

type Memcpy3DOperand struct {
	Type Memcpy3DOperandType
	Op   [4]uint64
}

Memcpy3DOperand represents an operand for copy with Stream.Memcpy3DBatchAsync.

type Memcpy3DOperandType

type Memcpy3DOperandType int32

Memcpy3DOperandType represents flags that allow applications to convey the operand type for individual copies specified in Stream.Memcpy3DBatchAsync.

const (
	MemcpyOperandTypePointer Memcpy3DOperandType = 0x1 // Memcpy operand is a valid pointer.
	MemcpyOperandTypeArray   Memcpy3DOperandType = 0x2 // Memcpy operand is a [Array].
)

func (Memcpy3DOperandType) String

func (e Memcpy3DOperandType) String() string

String returns the constant name, or a numeric representation for unknown values.

type Memcpy3DOperandV1

type Memcpy3DOperandV1 = Memcpy3DOperand

Memcpy3DOperandV1 is an alias for Memcpy3DOperand.

type Memcpy3d

type Memcpy3d struct {
	// Source X in bytes
	SrcXInBytes uint
	// Source Y
	SrcY uint
	// Source Z
	SrcZ uint
	// Source LOD
	SrcLOD uint
	// Source memory type (host, device, array)
	SrcMemoryType MemoryType
	// Source host pointer
	SrcHost uintptr
	// Source device pointer
	SrcDevice DevicePtr
	// Source array reference
	SrcArray Array
	// Must be NULL
	Reserved0 uintptr
	// Source pitch (ignored when src is array)
	SrcPitch uint
	// Source height (ignored when src is array; may be 0 if Depth==1)
	SrcHeight uint
	// Destination X in bytes
	DstXInBytes uint
	// Destination Y
	DstY uint
	// Destination Z
	DstZ uint
	// Destination LOD
	DstLOD uint
	// Destination memory type (host, device, array)
	DstMemoryType MemoryType
	// Destination host pointer
	DstHost uintptr
	// Destination device pointer
	DstDevice DevicePtr
	// Destination array reference
	DstArray Array
	// Must be NULL
	Reserved1 uintptr
	// Destination pitch (ignored when dst is array)
	DstPitch uint
	// Destination height (ignored when dst is array; may be 0 if Depth==1)
	DstHeight uint
	// Width of 3D memory copy in bytes
	WidthInBytes uint
	// Height of 3D memory copy
	Height uint
	// Depth of 3D memory copy
	Depth uint
}

Memcpy3d represents 3D memory copy parameters.

type Memcpy3dBatchOp

type Memcpy3dBatchOp struct {
	// Source memcpy operand.
	Src Memcpy3DOperand
	// Destination memcpy operand.
	Dst Memcpy3DOperand
	// Extents of the memcpy between src and dst. The width, height and depth components must not be 0.
	Extent Extent3D
	// Source access ordering to be observed for copy from src to dst.
	SrcAccessOrder MemcpySrcAccessOrder
	// Additional flags for copies with this attribute. See [MemcpyFlags]
	Flags uint32
}

Memcpy3dBatchOp represents CUDA_MEMCPY3D_BATCH_OP_v1.

type Memcpy3dBatchOpV1

type Memcpy3dBatchOpV1 = Memcpy3dBatchOp

Memcpy3dBatchOpV1 is an alias for Memcpy3dBatchOp.

type Memcpy3dPeer

type Memcpy3dPeer struct {
	// Source X in bytes
	SrcXInBytes uint
	// Source Y
	SrcY uint
	// Source Z
	SrcZ uint
	// Source LOD
	SrcLOD uint
	// Source memory type (host, device, array)
	SrcMemoryType MemoryType
	// Source host pointer
	SrcHost uintptr
	// Source device pointer
	SrcDevice DevicePtr
	// Source array reference
	SrcArray Array
	// Source context (ignored with srcMemoryType is [MemoryTypeArray])
	SrcContext Context
	// Source pitch (ignored when src is array)
	SrcPitch uint
	// Source height (ignored when src is array; may be 0 if Depth==1)
	SrcHeight uint
	// Destination X in bytes
	DstXInBytes uint
	// Destination Y
	DstY uint
	// Destination Z
	DstZ uint
	// Destination LOD
	DstLOD uint
	// Destination memory type (host, device, array)
	DstMemoryType MemoryType
	// Destination host pointer
	DstHost uintptr
	// Destination device pointer
	DstDevice DevicePtr
	// Destination array reference
	DstArray Array
	// Destination context (ignored with dstMemoryType is [MemoryTypeArray])
	DstContext Context
	// Destination pitch (ignored when dst is array)
	DstPitch uint
	// Destination height (ignored when dst is array; may be 0 if Depth==1)
	DstHeight uint
	// Width of 3D memory copy in bytes
	WidthInBytes uint
	// Height of 3D memory copy
	Height uint
	// Depth of 3D memory copy
	Depth uint
}

Memcpy3dPeer represents 3D memory cross-context copy parameters.

type Memcpy3dPeerV1

type Memcpy3dPeerV1 = Memcpy3dPeer

Memcpy3dPeerV1 is an alias for Memcpy3dPeer.

type Memcpy3dV2

type Memcpy3dV2 = Memcpy3d

Memcpy3dV2 is an alias for Memcpy3d.

type MemcpyAttributes

type MemcpyAttributes struct {
	// Source access ordering to be observed for copies with this attribute.
	SrcAccessOrder MemcpySrcAccessOrder
	// Hint location for the source operand. Ignored when the pointers are not managed memory or memory allocated outside CUDA.
	SrcLocHint MemLocation
	// Hint location for the destination operand. Ignored when the pointers are not managed memory or memory allocated outside CUDA.
	DstLocHint MemLocation
	// Additional flags for copies with this attribute. See [MemcpyFlags]
	Flags uint32
}

MemcpyAttributes represents attributes specific to copies within a batch.

For more details on usage see Stream.MemcpyBatchAsync.

type MemcpyAttributesV1

type MemcpyAttributesV1 = MemcpyAttributes

MemcpyAttributesV1 is an alias for MemcpyAttributes.

type MemcpyBatchNodeParams

type MemcpyBatchNodeParams struct {
	Count uint
	Dsts  uintptr
	// Array of source pointers. This field can be updated in an instantiated graph.
	Srcs           uintptr
	Sizes          uintptr
	Attrs          uintptr
	AttrsIdxs      uintptr
	NumAttrs       uint
	AnonymousUnion [1]uint64
}

MemcpyBatchNodeParams represents CUDA Batch Memcpy Node Parameters.

func (*MemcpyBatchNodeParams) Ctx

func (m *MemcpyBatchNodeParams) Ctx() *Context

Ctx returns a pointer to the ctx member of CUDA_MEMCPY_BATCH_NODE_PARAMS_V1, which shares its storage with every other member of the union.

func (*MemcpyBatchNodeParams) GCtx

func (m *MemcpyBatchNodeParams) GCtx() *GreenCtx

GCtx returns a pointer to the gCtx member of CUDA_MEMCPY_BATCH_NODE_PARAMS_V1, which shares its storage with every other member of the union.

type MemcpyBatchNodeParamsV1

type MemcpyBatchNodeParamsV1 = MemcpyBatchNodeParams

MemcpyBatchNodeParamsV1 is an alias for MemcpyBatchNodeParams.

type MemcpyFlags

type MemcpyFlags int32

MemcpyFlags represents flags to specify for copies within a batch.

For more details see Stream.MemcpyBatchAsync.

const (
	MemcpyFlagDefault                  MemcpyFlags = 0x0
	MemcpyFlagPreferOverlapWithCompute MemcpyFlags = 0x1
)

func (MemcpyFlags) String

func (e MemcpyFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemcpyNode

type MemcpyNode struct {
	GraphNode
}

MemcpyNode is a GraphNode of the memcpy kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the MemcpyNode one takes the kind's own types.

func (MemcpyNode) Params

func (m MemcpyNode) Params() (Memcpy3d, error)

Params returns a memcpy node’s parameters.

Returns the parameters of memcpy node hNode.

See also: GraphNode.Params, Memcpy3D, Graph.AddMemcpyNode, MemcpyNode.SetParams

Errors:

Wraps cuGraphMemcpyNodeGetParams.

func (MemcpyNode) SetParams

func (m MemcpyNode) SetParams(nodeParams *Memcpy3d) error

SetParams sets a memcpy node’s parameters.

Sets the parameters of memcpy node hNode to nodeParams.

See also: GraphNode.SetParams, Memcpy3D, Graph.AddMemcpyNode, MemcpyNode.Params

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphMemcpyNodeSetParams.

type MemcpyNodeParams

type MemcpyNodeParams struct {
	// Must be zero
	Flags int32
	// Must be zero
	Reserved int32
	// Context on which to run the node
	CopyCtx Context
	// Parameters for the memory copy
	CopyParams Memcpy3d
}

MemcpyNodeParams represents memcpy node parameters.

type MemcpySrcAccessOrder

type MemcpySrcAccessOrder int32

MemcpySrcAccessOrder represents flags that allow applications to convey the source access ordering CUDA must maintain.

The destination will always be accessed in stream order.

const (
	MemcpySrcAccessOrderInvalid MemcpySrcAccessOrder = 0x0 // Default invalid.
	// MemcpySrcAccessOrderStream: Indicates that access to the source pointer must be in stream order.
	MemcpySrcAccessOrderStream MemcpySrcAccessOrder = 0x1
	// MemcpySrcAccessOrderDuringApiCall: Indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it's known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call.
	MemcpySrcAccessOrderDuringApiCall MemcpySrcAccessOrder = 0x2
	// MemcpySrcAccessOrderAny: Indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it's known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms.
	MemcpySrcAccessOrderAny MemcpySrcAccessOrder = 0x3
)

func (MemcpySrcAccessOrder) String

func (e MemcpySrcAccessOrder) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemoryPool

type MemoryPool uintptr

MemoryPool is CUDA memory pool.

func MemGetDefaultMemPool

func MemGetDefaultMemPool(location *MemLocation, type_ MemAllocationType) (MemoryPool, error)

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

The memory location can be of one of MemLocationTypeDevice, MemLocationTypeHost, MemLocationTypeHostNuma, or MemLocationTypeDeviceLocalityDomain. The allocation type can be one of MemAllocationTypePinned or MemAllocationTypeManaged. When the allocation type is MemAllocationTypeManaged, the location type can also be MemLocationTypeNone to indicate no preferred location for the managed memory pool. MemAllocationTypeManaged can not be used with MemLocationTypeDeviceLocalityDomain.

See also: Stream.MemAllocAsync, MemoryPool.TrimTo, MemoryPool.Attribute, MemoryPool.SetAttribute, MemoryPool.SetAccess, MemGetMemPool, NewMemoryPool

Requires CUDA 13.0 (driver r580) or later; see HasMemGetDefaultMemPool.

Errors:

Wraps cuMemGetDefaultMemPool.

func MemGetMemPool

func MemGetMemPool(location *MemLocation, type_ MemAllocationType) (MemoryPool, error)

MemGetMemPool gets the current memory pool for a memory location and of a particular allocation type.

The memory location can be of one of MemLocationTypeDevice, MemLocationTypeHost or MemLocationTypeHostNuma, MemLocationTypeHostNuma, or MemLocationTypeDeviceLocalityDomain. The allocation type can be one of MemAllocationTypePinned or MemAllocationTypeManaged. When the allocation type is MemAllocationTypeManaged, the location type can also be MemLocationTypeNone to indicate no preferred location for the managed memory pool. MemAllocationTypeManaged can not be used with MemLocationTypeDeviceLocalityDomain. In all other cases, the call returns ErrInvalidValue Returns the last pool provided to MemoryPool.MemSetMemPool or Device.SetMemPool for this location and allocation type or the location’s default memory pool if MemoryPool.MemSetMemPool or Device.SetMemPool for that allocType and location has never been called. By default the current mempool of a location is the default mempool for a device. Otherwise the returned pool must have been set with Device.SetMemPool.

See also: Device.DefaultMemPool, NewMemoryPool, Device.SetMemPool, MemoryPool.MemSetMemPool

Requires CUDA 13.0 (driver r580) or later; see HasMemGetMemPool.

Errors:

Wraps cuMemGetMemPool.

func MemPoolImportFromShareableHandle

func MemPoolImportFromShareableHandle(handle uintptr, handleType MemAllocationHandleType, flags uint64) (MemoryPool, error)

MemPoolImportFromShareableHandle imports a memory pool from a shared handle.

Specific allocations can be imported from the imported pool with MemoryPool.ImportPointer. If handleType is MemHandleTypeFabric and the importer process has not been granted access to the same IMEX channel as the exporter process, this API will error as ErrNotPermitted.

Note: Imported memory pools do not support creating new allocations. As such imported memory pools may not be used in Device.SetMemPool or MemoryPool.MemAllocFromPoolAsync calls.

See also: MemoryPool.ExportToShareableHandle, DevicePtr.MemPoolExportPointer, MemoryPool.ImportPointer

  • handle: OS handle of the pool to open
  • handleType: The type of handle being imported
  • flags: must be 0

Errors:

Wraps cuMemPoolImportFromShareableHandle.

func NewMemoryPool

func NewMemoryPool(poolProps *MemPoolProps) (MemoryPool, error)

NewMemoryPool creates a memory pool.

Creates a CUDA memory pool and returns the handle. The poolProps determines the properties of the pool such as the backing device and IPC capabilities. To create a memory pool for HOST memory not targeting a specific NUMA node, applications must set set MemPoolProps.MemLocation.type to MemLocationTypeHost. MemPoolProps.MemLocation.id is ignored for such pools. Pools created with the type MemLocationTypeHost are not IPC capable and MemPoolProps.handleTypes must be 0, any other values will result in ErrInvalidValue. To create a memory pool targeting a specific host NUMA node, applications must set MemPoolProps.MemLocation.type to MemLocationTypeHostNuma and MemPoolProps.MemLocation.id must specify the NUMA ID of the host memory node. Specifying MemLocationTypeHostNumaCurrent as the MemPoolProps.MemLocation.type will result in ErrInvalidValue. To create a memory pool targeting a specific device locality domain, applications must set MemPoolProps.MemLocation.type to MemLocationTypeDeviceLocalityDomain, MemPoolProps.MemLocation.localized.deviceId must specify the device ID, and MemPoolProps.MemLocation.localized.localityDomainId must specify the locality domain ID. The locality domain ID must be a valid locality domain ID for the specified device. See also Device.Attribute with the attribute DevAttrLocalityDomainCount. By default, the pool’s memory will be accessible from the device it is allocated on. In the case of pools created with MemLocationTypeHostNuma or MemLocationTypeHost, their default accessibility will be from the host CPU. Applications can control the maximum size of the pool by specifying a non-zero value for MemPoolProps.maxSize. If set to 0, the maximum size of the pool will default to a system dependent value. Applications that intend to use MemHandleTypeFabric based memory sharing must ensure: (1) nvidia-caps-imex-channels character device is created by the driver and is listed under /proc/devices (2) have at least one IMEX channel file accessible by the user launching the application. When exporter and importer CUDA processes have been granted access to the same IMEX channel, they can securely share memory. The IMEX channel security model works on a per user basis. Which means all processes under a user can share memory if the user has access to a valid IMEX channel. When multi-user isolation is desired, a separate IMEX channel is required for each user. These channel files exist in /dev/nvidia-caps-imex-channels/channel* and can be created using standard OS native calls like mknod on Linux. For example: To create channel0 with the major number from /proc/devices users can execute the following command: mknod /dev/nvidia-caps-imex-channels/channel0 c <major number> 0 To create a managed memory pool, applications must set MemPoolProps.MemAllocationType to MemAllocationTypeManaged. MemPoolProps.MemAllocationHandleType must also be set to MemHandleTypeNone since IPC is not supported. For managed memory pools, MemPoolProps.MemLocation will be treated as the preferred location for all allocations created from the pool. An application can also set MemLocationTypeNone to indicate no preferred location. MemPoolProps.maxSize must be set to zero for managed memory pools. MemPoolProps.usage should be zero as decompress for managed memory is not supported. For managed memory pools, all devices on the system must have non-zero concurrentManagedAccess. If not, this call returns ErrNotSupported

Note: On devices with a single locality domain, a memory pool created with MemLocationTypeDeviceLocalityDomain and localityDomainId 0 is equivalent to a full-device memory pool created with MemLocationTypeDevice. The pool will report MemLocationTypeDevice for MempoolAttrLocationType and -1 for MempoolAttrLocalityDomainId.

Note: Specifying MemHandleTypeNone creates a memory pool that will not support IPC.

See also: Device.SetMemPool, Device.MemPool, Device.DefaultMemPool, MemoryPool.MemAllocFromPoolAsync, MemoryPool.ExportToShareableHandle

Errors:

Wraps cuMemPoolCreate.

func (MemoryPool) Access

func (m MemoryPool) Access(location *MemLocation) (MemaccessFlags, error)

Access returns the accessibility of a pool from a device.

Returns the accessibility of the pool’s memory from the specified location.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool

  • location: the location accessing the pool

Wraps cuMemPoolGetAccess.

func (MemoryPool) Attribute

func (m MemoryPool) Attribute(attr MempoolAttribute, value unsafe.Pointer) error

Attribute gets attributes of a memory pool.

Supported attributes are:

  • MempoolAttrReleaseThreshold: (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)
  • MempoolAttrReuseFollowEventDependencies: (value type = int) Allow Stream.MemAllocAsync 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)
  • MempoolAttrReuseAllowOpportunistic: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled)
  • MempoolAttrReuseAllowInternalDependencies: (value type = int) Allow Stream.MemAllocAsync to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released by DevicePtr.FreeAsync (default enabled).
  • MempoolAttrReservedMemCurrent: (value type = cuuint64_t) Amount of backing memory currently allocated for the mempool
  • MempoolAttrReservedMemHigh: (value type = cuuint64_t) High watermark of backing memory allocated for the mempool since the last time it was reset.
  • MempoolAttrUsedMemCurrent: (value type = cuuint64_t) Amount of memory from the pool that is currently in use by the application.
  • MempoolAttrUsedMemHigh: (value type = cuuint64_t) High watermark of the amount of memory from the pool that was in use by the application.

The following properties can be also be queried on imported and default pools:

Note: On devices with a single locality domain, mempools created with MemLocationTypeDeviceLocalityDomain and localityDomainId 0 are equivalent to full-device mempools created with MemLocationTypeDevice. The value of this attribute will be -1 for such mempools.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool

  • attr: The attribute to get
  • value: Retrieved value

Errors:

Wraps cuMemPoolGetAttribute.

func (*MemoryPool) Close

func (m *MemoryPool) Close() error

Close 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 MemoryPool.Close 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.

Note: A device’s default memory pool cannot be destroyed.

See also: DevicePtr.FreeAsync, Device.SetMemPool, Device.MemPool, Device.DefaultMemPool, NewMemoryPool

Errors:

If m is zero, Close returns nil. Otherwise Close sets m to zero when the call succeeds and leaves it unchanged when it fails. Only m is zeroed: a copy of it still refers to the released object.

Wraps cuMemPoolDestroy.

func (MemoryPool) ExportToShareableHandle

func (m MemoryPool) ExportToShareableHandle(handleOut unsafe.Pointer, handleType MemAllocationHandleType, flags uint64) error

ExportToShareableHandle 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 MemPoolImportFromShareableHandle. Individual pointers can then be shared with the DevicePtr.MemPoolExportPointer and MemoryPool.ImportPointer APIs. The implementation of what the shareable handle is and how it can be transferred is defined by the requested handle type.

Note: : To create an IPC capable mempool, create a mempool with a MemAllocationHandleType other than MemHandleTypeNone.

See also: MemPoolImportFromShareableHandle, DevicePtr.MemPoolExportPointer, MemoryPool.ImportPointer, Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool, MemoryPool.SetAccess, MemoryPool.SetAttribute

  • handleOut: Returned OS handle
  • handleType: the type of handle to create
  • flags: must be 0

Errors:

Wraps cuMemPoolExportToShareableHandle.

func (MemoryPool) ImportPointer

func (m MemoryPool) ImportPointer(shareData *MemPoolPtrExportData) (DevicePtr, error)

ImportPointer imports a memory pool allocation from another process.

Returns a pointer to the imported memory. The imported memory must not be accessed before the allocation operation completes in the exporting process. The imported memory must be freed from all importing processes before being freed in the exporting process. The pointer may be freed with DevicePtr.Free or DevicePtr.FreeAsync. If DevicePtr.FreeAsync is used, the free must be completed on the importing process before the free operation on the exporting process.

Note: The DevicePtr.FreeAsync api may be used in the exporting process before the DevicePtr.FreeAsync operation completes in its stream as long as the DevicePtr.FreeAsync in the exporting process specifies a stream with a stream dependency on the importing process’s DevicePtr.FreeAsync.

See also: MemoryPool.ExportToShareableHandle, MemPoolImportFromShareableHandle, DevicePtr.MemPoolExportPointer

  • shareData: data specifying the memory to import

Errors:

Wraps cuMemPoolImportPointer.

func (MemoryPool) MemAllocFromPoolAsync

func (m MemoryPool) MemAllocFromPoolAsync[T any](n int, hStream Stream) (DevicePtr, error)

MemAllocFromPoolAsync 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. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the specified memory pool.

Note: The specified memory pool may be from a device different than that of the specified hStream.

Note: 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.

Note: 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.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool, MemoryPool.SetAccess, MemoryPool.SetAttribute

  • hStream: The stream establishing the stream ordering semantic

Errors:

The allocation holds n values of type T: bytesize is n times the size of T. A negative n, or one whose size overflows uint, is an error. T must not contain Go pointers: the garbage collector does not scan device memory.

Wraps cuMemAllocFromPoolAsync.

func (MemoryPool) MemAllocFromPoolAsyncBytes

func (m MemoryPool) MemAllocFromPoolAsyncBytes(bytesize uint, hStream Stream) (DevicePtr, error)

MemAllocFromPoolAsyncBytes is MemoryPool.MemAllocFromPoolAsync with the size given in bytes.

  • bytesize: Number of bytes to allocate

Wraps cuMemAllocFromPoolAsync.

func (MemoryPool) MemSetMemPool

func (m MemoryPool) MemSetMemPool(location *MemLocation, type_ MemAllocationType) error

MemSetMemPool sets the current memory pool for a memory location and allocation type.

The memory location can be of one of MemLocationTypeDevice, MemLocationTypeHost or MemLocationTypeHostNuma, MemLocationTypeDeviceLocalityDomain. The allocation type can be one of MemAllocationTypePinned or MemAllocationTypeManaged. When the allocation type is MemAllocationTypeManaged, the location type can also be MemLocationTypeNone to indicate no preferred location for the managed memory pool. In all other cases, the call returns ErrInvalidValue. When a memory pool is set as the current memory pool, the location parameter should be the same as the location of the pool. The location and allocation type specified must match those of the pool otherwise ErrInvalidValue is returned. By default, a memory location’s current memory pool is its default memory pool that can be obtained via MemGetDefaultMemPool. If the location type is MemLocationTypeDevice and the allocation type is MemAllocationTypePinned, then this API is the equivalent of calling Device.SetMemPool with the location id as the device. For further details on the implications, please refer to the documentation for Device.SetMemPool.

Note: Use MemoryPool.MemAllocFromPoolAsync to specify asynchronous allocations from a device different than the one the stream runs on.

See also: Device.DefaultMemPool, Device.MemPool, MemGetMemPool, NewMemoryPool, MemoryPool.Close, MemoryPool.MemAllocFromPoolAsync

Requires CUDA 13.0 (driver r580) or later; see HasMemSetMemPool.

Errors:

Wraps cuMemSetMemPool.

func (MemoryPool) SetAccess

func (m MemoryPool) SetAccess(map_ *MemAccessDesc, count uint) error

SetAccess controls visibility of pools between devices.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool

  • map_: Array of access descriptors. Each descriptor instructs the access to enable for a single gpu
  • count: Number of descriptors in the map array

Errors:

Wraps cuMemPoolSetAccess.

func (MemoryPool) SetAttribute

func (m MemoryPool) SetAttribute(attr MempoolAttribute, value unsafe.Pointer) error

SetAttribute sets attributes of a memory pool.

Supported attributes are:

  • MempoolAttrReleaseThreshold: (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)
  • MempoolAttrReuseFollowEventDependencies: (value type = int) Allow Stream.MemAllocAsync 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)
  • MempoolAttrReuseAllowOpportunistic: (value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled)
  • MempoolAttrReuseAllowInternalDependencies: (value type = int) Allow Stream.MemAllocAsync to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released by DevicePtr.FreeAsync (default enabled).
  • MempoolAttrReservedMemHigh: (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.
  • MempoolAttrUsedMemHigh: (value type = cuuint64_t) Reset the high watermark that tracks the amount of used memory that was allocated for the memory pool.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool

  • attr: The attribute to modify
  • value: Pointer to the value to assign

Errors:

Wraps cuMemPoolSetAttribute.

func (MemoryPool) TrimTo

func (m MemoryPool) TrimTo(minBytesToKeep uint) error

TrimTo 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.

Note: : Allocations that have not been freed count as outstanding.

Note: : Allocations that have been asynchronously freed but whose completion has not been observed on the host (eg. by a synchronize) can count as outstanding.

See also: Stream.MemAllocAsync, DevicePtr.FreeAsync, Device.DefaultMemPool, Device.MemPool, NewMemoryPool

  • minBytesToKeep: 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

Errors:

Wraps cuMemPoolTrimTo.

type MemoryType

type MemoryType uint32

MemoryType represents memory types.

const (
	MemoryTypeHost    MemoryType = 0x01 // Host memory
	MemoryTypeDevice  MemoryType = 0x02 // Device memory
	MemoryTypeArray   MemoryType = 0x03 // Array memory
	MemoryTypeUnified MemoryType = 0x04 // Unified device or host memory
)

func (MemoryType) String

func (e MemoryType) String() string

String returns the constant name, or a numeric representation for unknown values.

type MempoolAttribute

type MempoolAttribute int32

MempoolAttribute represents CUDA memory pool attributes.

const (
	// MempoolAttrReuseFollowEventDependencies: (value type = int) Allow [Stream.MemAllocAsync] to use memory asynchronously freed in another streams 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)
	MempoolAttrReuseFollowEventDependencies   MempoolAttribute = 1
	MempoolAttrReuseAllowOpportunistic        MempoolAttribute = 2
	MempoolAttrReuseAllowInternalDependencies MempoolAttribute = 3
	MempoolAttrReleaseThreshold               MempoolAttribute = 4
	MempoolAttrReservedMemCurrent             MempoolAttribute = 5
	MempoolAttrReservedMemHigh                MempoolAttribute = 6
	MempoolAttrUsedMemCurrent                 MempoolAttribute = 7
	MempoolAttrUsedMemHigh                    MempoolAttribute = 8
	MempoolAttrAllocationType                 MempoolAttribute = 9
	MempoolAttrExportHandleTypes              MempoolAttribute = 10
	MempoolAttrLocationId                     MempoolAttribute = 11
	MempoolAttrLocationType                   MempoolAttribute = 12
	MempoolAttrMaxPoolSize                    MempoolAttribute = 13
	MempoolAttrHwDecompressEnabled            MempoolAttribute = 14
	MempoolAttrLocalityDomainId               MempoolAttribute = 15
)

func (MempoolAttribute) String

func (e MempoolAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type MemsetNode

type MemsetNode struct {
	GraphNode
}

MemsetNode is a GraphNode of the memset kind. It has the methods that apply only to that kind, and embeds the GraphNode for those that apply to every kind. Where both have a method of the same name, the MemsetNode one takes the kind's own types.

func (MemsetNode) Params

func (m MemsetNode) Params() (MemsetNodeParams, error)

Params returns a memset node’s parameters.

Returns the parameters of memset node hNode.

See also: GraphNode.Params, DevicePtr.MemsetD2D32, Graph.AddMemsetNode, MemsetNode.SetParams

Errors:

Wraps cuGraphMemsetNodeGetParams.

func (MemsetNode) SetParams

func (m MemsetNode) SetParams(nodeParams *MemsetNodeParams) error

SetParams sets a memset node’s parameters.

Sets the parameters of memset node hNode to nodeParams.

See also: GraphNode.SetParams, DevicePtr.MemsetD2D32, Graph.AddMemsetNode, MemsetNode.Params

  • nodeParams: Parameters to copy

Errors:

Wraps cuGraphMemsetNodeSetParams.

type MemsetNodeParams

type MemsetNodeParams struct {
	// Destination device pointer
	Dst DevicePtr
	// Pitch of destination device pointer. Unused if height is 1
	Pitch uint
	// Value to be set
	Value uint32
	// Size of each element in bytes. Must be 1, 2, or 4.
	ElementSize uint32
	// Width of the row in elements
	Width uint
	// Number of rows
	Height uint
}

MemsetNodeParams represents memset node parameters.

type MemsetNodeParamsV1

type MemsetNodeParamsV1 = MemsetNodeParams

MemsetNodeParamsV1 is an alias for MemsetNodeParams.

type MemsetNodeParamsV2

type MemsetNodeParamsV2 struct {
	// Destination device pointer
	Dst DevicePtr
	// Pitch of destination device pointer. Unused if height is 1
	Pitch uint
	// Value to be set
	Value uint32
	// Size of each element in bytes. Must be 1, 2, or 4.
	ElementSize uint32
	// Width of the row in elements
	Width uint
	// Number of rows
	Height uint
	// Context on which to run the node
	Ctx Context
}

MemsetNodeParamsV2 represents memset node parameters.

type MipmappedArray

type MipmappedArray uintptr

MipmappedArray is CUDA mipmapped array.

func NewMipmappedArray

func NewMipmappedArray(pMipmappedArrayDesc *Array3dDescriptor, numMipmapLevels uint32) (MipmappedArray, error)

NewMipmappedArray creates a CUDA mipmapped array.

Creates a CUDA mipmapped array according to the Array3dDescriptor structure pMipmappedArrayDesc and returns a handle to the new CUDA mipmapped array. numMipmapLevels specifies the number of mipmap levels to be allocated. This value is clamped to the range [1, 1 + floor(log2(max(width, height, depth)))].

  • Width, Height, and Depth are the width, height, and depth of the CUDA array (in elements); the following types of CUDA arrays can be allocated: A 1D mipmapped array is allocated if Height and Depth extents are both zero. A 2D mipmapped array is allocated if only 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 Height is zero and the CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 1D 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 CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 2D 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 CUDA_ARRAY3D_CUBEMAP 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 ArrayCubemapFace. A cubemap layered CUDA mipmapped array is allocated if all three extents are non-zero, and both, CUDA_ARRAY3D_CUBEMAP and CUDA_ARRAY3D_LAYERED 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.
  • Format specifies the format of the elements.
  • NumChannels specifies the number of packed components per CUDA array element; it may be 1, 2, or 4;
  • Flags may be set to CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA mipmapped arrays. If this flag is set, Depth specifies the number of layers, not the depth of a 3D array. CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to individual mipmap levels of the CUDA mipmapped array. If this flag is not set, SurfRef.SetArray will fail when attempting to bind a mipmap level of the CUDA mipmapped array to a surface reference. CUDA_ARRAY3D_CUBEMAP to enable creation of mipmapped cubemaps. If this flag is set, Width must be equal to Height, and Depth must be six. If the CUDA_ARRAY3D_LAYERED flag is also set, then Depth must be a multiple of six. CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA mipmapped array will be used for texture gather. Texture gather can only be performed on 2D CUDA mipmapped arrays.

Width, Height and Depth must meet certain size requirements as listed in the following table. All values are specified in elements. Note that for brevity’s sake, the full name of the device attribute is not specified. For ex., TEXTURE1D_MIPMAPPED_WIDTH refers to the device attribute DevAttrMaximumTexture1dMipmappedWidth.

See also: MipmappedArray.Close, MipmappedArray.Level, NewArray, cudaMallocMipmappedArray

  • pMipmappedArrayDesc: mipmapped array descriptor
  • numMipmapLevels: Number of mipmap levels

Errors:

Wraps cuMipmappedArrayCreate.

func (*MipmappedArray) Close

func (m *MipmappedArray) Close() error

Close destroys a CUDA mipmapped array.

Destroys the CUDA mipmapped array hMipmappedArray.

See also: NewMipmappedArray, MipmappedArray.Level, NewArray, cudaFreeMipmappedArray

Errors:

If m is zero, Close returns nil. Otherwise Close sets m to zero when the call succeeds and leaves it unchanged when it fails. Only m is zeroed: a copy of it still refers to the released object.

Wraps cuMipmappedArrayDestroy.

func (MipmappedArray) Level

func (m MipmappedArray) Level(level uint32) (Array, error)

Level gets a mipmap level of a CUDA mipmapped array.

Returns a CUDA array that represents a single mipmap level of the CUDA mipmapped array hMipmappedArray. If level is greater than the maximum number of levels in this mipmapped array, ErrInvalidValue is returned.

See also: NewMipmappedArray, MipmappedArray.Close, NewArray, cudaGetMipmappedArrayLevel

  • level: Mipmap level

Errors:

Wraps cuMipmappedArrayGetLevel.

func (MipmappedArray) MemoryRequirements

func (m MipmappedArray) MemoryRequirements(device Device) (ArrayMemoryRequirements, error)

MemoryRequirements returns the memory requirements of a CUDA mipmapped array.

Returns the memory requirements of a CUDA mipmapped array If the CUDA mipmapped array is not allocated with flag CUDA_ARRAY3D_DEFERRED_MAPPING ErrInvalidValue will be returned. The returned value in ArrayMemoryRequirements.size represents the total size of the CUDA mipmapped array. The returned value in ArrayMemoryRequirements.alignment represents the alignment necessary for mapping the CUDA mipmapped array.

See also: Array.MemoryRequirements, Stream.MemMapArrayAsync

  • device: Device to get the memory requirements for

Errors:

Wraps cuMipmappedArrayGetMemoryRequirements.

func (MipmappedArray) SparseProperties

func (m MipmappedArray) SparseProperties() (ArraySparseProperties, error)

SparseProperties returns the layout properties of a sparse CUDA mipmapped array.

Returns the sparse array layout properties If the CUDA mipmapped array is not allocated with flag CUDA_ARRAY3D_SPARSE ErrInvalidValue will be returned. For non-layered CUDA mipmapped arrays, ArraySparseProperties.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, if ArraySparseProperties.flags contains CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, then ArraySparseProperties.miptailSize specifies the size of the mip tail of all layers combined. Otherwise, ArraySparseProperties.miptailSize specifies mip tail size per layer. The returned value of ArraySparseProperties.miptailFirstLevel is valid only if ArraySparseProperties.miptailSize is non-zero.

See also: Array.SparseProperties, Stream.MemMapArrayAsync

Errors:

Wraps cuMipmappedArrayGetSparseProperties.

type Module

type Module uintptr

Module is an opaque handle to a loaded CUDA module. Created via ModuleLoad or ModuleLoadData and destroyed via [Module.Unload].

func ModuleLoad

func ModuleLoad(fname string) (Module, error)

ModuleLoad loads a compute module.

Takes a filename fname and loads the corresponding module module into the current context. The CUDA driver API does not attempt to lazily allocate the resources needed by a module; if the memory for functions and data (constant and global) needed by the module cannot be allocated, ModuleLoad fails. The file should be a cubin file as output by nvcc, or a PTX file either as output by nvcc or handwritten, or a fatbin file as output by nvcc from toolchain 4.0 or later, or a Tile IR file.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close

  • fname: Filename of module to load

Errors:

Wraps cuModuleLoad.

func ModuleLoadData

func ModuleLoadData(image []byte) (Module, error)

ModuleLoadData loads a module’s data.

Takes image and loads the corresponding module module into the current context. The image may be a cubin or fatbin as output by nvcc, or a PTX, either as output by nvcc or hand-written, or Tile IR data.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoad, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close

  • image: Module data to load

Errors:

The wrapper passes image to C without copying if a NUL byte ends it or follows it in its capacity, as one does in text a generated getter returns, or if it starts with the ELF or fatbin magic number. Otherwise image is text, and the wrapper copies it once to append a NUL.

Wraps cuModuleLoadData.

func ModuleLoadDataEx

func ModuleLoadDataEx(image []byte, numOptions uint32, options *JITOption, optionValues *uintptr) (Module, error)

ModuleLoadDataEx loads a module’s data with options.

Takes image and loads the corresponding module module into the current context. The image may be a cubin or fatbin as output by nvcc, or a PTX, either as output by nvcc or hand-written, or Tile IR data.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadFatBinary, Module.Close

  • image: Module data to load
  • numOptions: Number of options
  • options: Options for JIT
  • optionValues: Option values for JIT

Errors:

The wrapper passes image to C without copying if a NUL byte ends it or follows it in its capacity, as one does in text a generated getter returns, or if it starts with the ELF or fatbin magic number. Otherwise image is text, and the wrapper copies it once to append a NUL.

Wraps cuModuleLoadDataEx.

func ModuleLoadFatBinary

func ModuleLoadFatBinary(fatCubin []byte) (Module, error)

ModuleLoadFatBinary loads a module’s data.

Takes fatCubin and loads the corresponding module module into the current context. The pointer represents a fat binary object, which is a collection of different cubin and/or PTX files, all representing the same device code, but compiled and optimized for different architectures. Prior to CUDA 4.0, there was no documented API for constructing and using fat binary objects by programmers. Starting with CUDA 4.0, fat binary objects can be constructed by providing the -fatbin option to nvcc. More information can be found in the nvcc document.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, Module.Close

  • fatCubin: Fat binary to load

Errors:

Wraps cuModuleLoadFatBinary.

func (*Module) Close

func (m *Module) Close() error

Close unloads a module.

Unloads a module hmod from the current context. Attempting to unload a module which was obtained from the Library Management API such as Library.Module will return ErrNotPermitted.

Note: Use of the handle after this call is undefined behavior.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary

Errors:

If m is zero, Close returns nil. Otherwise Close sets m to zero when the call succeeds and leaves it unchanged when it fails. Only m is zeroed: a copy of it still refers to the released object.

Wraps cuModuleUnload.

func (Module) EnumerateFunctions

func (m Module) EnumerateFunctions(functions *Function, numFunctions uint32) error

EnumerateFunctions returns the function handles within a module.

Returns in functions a maximum number of numFunctions function handles within mod. When function loading mode is set to LAZY the function retrieved may be partially loaded. The loading state of a function can be queried using cuFunctionIsLoaded. CUDA APIs may load the function automatically when called with partially loaded function handle which may incur additional latency. Alternatively, cuFunctionLoad can be used to explicitly load a function. The returned function handles become invalid when the module is unloaded.

See also: Module.Function, Module.FunctionCount, Function.IsLoaded, Function.Load

Requires CUDA 12.4 (driver r550) or later; see HasModuleEnumerateFunctions.

  • functions: Buffer where the function handles are returned to
  • numFunctions: Maximum number of function handles may be returned to the buffer

Errors:

Wraps cuModuleEnumerateFunctions.

func (Module) Function

func (m Module) Function(name string) (Function, error)

Function returns a function handle.

Returns the handle of the function of name name located in module hmod. If no function of that name exists, Module.Function returns ErrNotFound.

See also: Module.Global, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close

  • name: Name of function to retrieve

Errors:

Wraps cuModuleGetFunction.

func (Module) FunctionCount

func (m Module) FunctionCount() (uint32, error)

FunctionCount returns the number of functions within a module.

Returns the number of functions in mod.

Requires CUDA 12.4 (driver r550) or later; see HasModuleGetFunctionCount.

Errors:

Wraps cuModuleGetFunctionCount.

func (Module) Global

func (m Module) Global(name string) (dptr DevicePtr, bytes uint, err error)

Global returns a global pointer from a module.

Returns in *dptr and *bytes the base pointer and size of the global of name name located in module hmod. If no variable of that name exists, Module.Global returns ErrNotFound. One of the parameters dptr or bytes (not both) can be NULL in which case it is ignored.

See also: Module.Function, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close, cudaGetSymbolAddress, cudaGetSymbolSize

  • dptr: Returned global device pointer
  • bytes: Returned global size in bytes
  • name: Name of global to retrieve

Errors:

Wraps cuModuleGetGlobal, bound as cuModuleGetGlobal_v2.

func (Module) SurfRef deprecated

func (m Module) SurfRef(name *byte) (SurfRef, error)

SurfRef returns a handle to a surface reference.

Returns the handle of the surface reference of name name in the module hmod. If no surface reference of that name exists, Module.SurfRef returns ErrNotFound.

See also: Module.Function, Module.Global, Module.TexRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close

  • name: Name of surface reference to retrieve

Errors:

Wraps cuModuleGetSurfRef.

Deprecated: Deprecated by NVIDIA.

func (Module) TexRef deprecated

func (m Module) TexRef(name *byte) (TexRef, error)

TexRef returns a handle to a texture reference.

Returns the handle of the texture reference of name name in the module hmod. If no texture reference of that name exists, Module.TexRef returns ErrNotFound. This texture reference handle should not be destroyed, since it will be destroyed when the module is unloaded.

See also: Module.Function, Module.Global, Module.SurfRef, ModuleLoad, ModuleLoadData, ModuleLoadDataEx, ModuleLoadFatBinary, Module.Close

  • name: Name of texture reference to retrieve

Errors:

Wraps cuModuleGetTexRef.

Deprecated: Deprecated by NVIDIA.

type ModuleLoadingMode

type ModuleLoadingMode int32

ModuleLoadingMode represents CUDA Lazy Loading status.

const (
	ModuleEagerLoading ModuleLoadingMode = 0x1 // Lazy Kernel Loading is not enabled
	ModuleLazyLoading  ModuleLoadingMode = 0x2 // Lazy Kernel Loading is enabled
)

func ModuleGetLoadingMode

func ModuleGetLoadingMode() (ModuleLoadingMode, error)

ModuleGetLoadingMode queries lazy loading mode.

Returns lazy loading mode Module loading mode is controlled by CUDA_MODULE_LOADING env variable

See also: ModuleLoad

Errors:

Wraps cuModuleGetLoadingMode.

func (ModuleLoadingMode) String

func (e ModuleLoadingMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type MulticastObjectProp

type MulticastObjectProp struct {
	NumDevices  uint32
	Size        uint
	HandleTypes uint64
	Flags       uint64
}

MulticastObjectProp specifies the properties for a multicast object.

type MulticastObjectPropV1

type MulticastObjectPropV1 = MulticastObjectProp

MulticastObjectPropV1 is an alias for MulticastObjectProp.

type MulticastgranularityFlags

type MulticastgranularityFlags int32

MulticastgranularityFlags represents flags for querying different granularities for a multicast object.

const (
	MulticastGranularityMinimum     MulticastgranularityFlags = 0x0 // Minimum required granularity
	MulticastGranularityRecommended MulticastgranularityFlags = 0x1 // Recommended granularity for best performance
)

func (MulticastgranularityFlags) String

func (e MulticastgranularityFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type OccupancyB2DSize

type OccupancyB2DSize func(blockSize int32) uint

OccupancyB2DSize is the Go form of CUoccupancyB2DSize.

It corresponds to the C signature

typedef size_t (CUDA_CB *CUoccupancyB2DSize)(int blockSize);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type OccupancyFlags

type OccupancyFlags int32

OccupancyFlags represents occupancy calculator flag.

const (
	OccupancyDefault OccupancyFlags = 0x0 // Default behavior
	// OccupancyDisableCachingOverride: Assume global caching is enabled and cannot be automatically turned off
	OccupancyDisableCachingOverride OccupancyFlags = 0x1
)

func (OccupancyFlags) String

func (e OccupancyFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type Offset3D

type Offset3D struct {
	X uint
	Y uint
	Z uint
}

Offset3D represents a 3D offset.

type Offset3DV1

type Offset3DV1 = Offset3D

Offset3DV1 is an alias for Offset3D.

type PointerAttribute

type PointerAttribute int32

PointerAttribute represents pointer information.

const (
	PointerAttributeContext PointerAttribute = 1 // The [Context] on which a pointer was allocated or registered
	// PointerAttributeMemoryType: The [MemoryType] describing the physical location of a pointer
	PointerAttributeMemoryType PointerAttribute = 2
	// PointerAttributeDevicePointer: The address at which a pointer's memory may be accessed on the device
	PointerAttributeDevicePointer PointerAttribute = 3
	// PointerAttributeHostPointer: The address at which a pointer's memory may be accessed on the host
	PointerAttributeHostPointer PointerAttribute = 4
	// PointerAttributePointerAttributeP2PTokens: A pair of tokens for use with the nv-p2p.h Linux kernel interface
	PointerAttributePointerAttributeP2PTokens PointerAttribute = 5
	// PointerAttributeSyncMemops: Synchronize every synchronous memory operation initiated on this region
	PointerAttributeSyncMemops PointerAttribute = 6
	PointerAttributeBufferId   PointerAttribute = 7 // A process-wide unique ID for an allocated memory region
	PointerAttributeIsManaged  PointerAttribute = 8 // Indicates if the pointer points to managed memory
	// PointerAttributeDeviceOrdinal: A device ordinal of a device on which a pointer was allocated or registered
	PointerAttributeDeviceOrdinal PointerAttribute = 9
	// PointerAttributeIsLegacyCudaIpcCapable: 1 if this pointer maps to an allocation that is suitable for cudaIpcGetMemHandle, 0 otherwise *
	PointerAttributeIsLegacyCudaIpcCapable PointerAttribute = 10
	PointerAttributeRangeStartAddr         PointerAttribute = 11 // Starting address for this requested pointer
	PointerAttributeRangeSize              PointerAttribute = 12 // Size of the address range for this requested pointer
	// PointerAttributeMapped: 1 if this pointer is in a valid address range that is mapped to a backing allocation, 0 otherwise *
	PointerAttributeMapped PointerAttribute = 13
	// PointerAttributeAllowedHandleTypes: Bitmask of allowed [MemAllocationHandleType] for this allocation *
	PointerAttributeAllowedHandleTypes PointerAttribute = 14
	// PointerAttributeIsGpuDirectRdmaCapable: 1 if the memory this pointer is referencing can be used with the GPUDirect RDMA API *
	PointerAttributeIsGpuDirectRdmaCapable PointerAttribute = 15
	// PointerAttributePointerAttributeAccessFlags: Returns the access flags the device associated with the current context has on the corresponding memory referenced by the pointer given
	PointerAttributePointerAttributeAccessFlags PointerAttribute = 16
	// PointerAttributeMempoolHandle: Returns the mempool handle for the allocation if it was allocated from a mempool. Otherwise returns NULL. *
	PointerAttributeMempoolHandle PointerAttribute = 17
	// PointerAttributeMappingSize: Size of the actual underlying mapping that the pointer belongs to *
	PointerAttributeMappingSize PointerAttribute = 18
	// PointerAttributeMappingBaseAddr: The start address of the mapping that the pointer belongs to *
	PointerAttributeMappingBaseAddr PointerAttribute = 19
	// PointerAttributeMemoryBlockId: A process-wide unique id corresponding to the physical allocation the pointer belongs to *
	PointerAttributeMemoryBlockId PointerAttribute = 20
	// PointerAttributeIsHwDecompressCapable: Returns in *data a boolean that indicates whether the pointer points to memory that is capable to be used for hardware accelerated decompression.
	PointerAttributeIsHwDecompressCapable PointerAttribute = 21
	// PointerAttributeLocalityDomainOrdinal: Returns in *data an integer representing the locality domain ordinal of the memory allocation, or -1 if the allocation is not localized to a locality domain.
	PointerAttributeLocalityDomainOrdinal PointerAttribute = 22
)

func (PointerAttribute) String

func (e PointerAttribute) String() string

String returns the constant name, or a numeric representation for unknown values.

type PointerAttributeAccessFlags

type PointerAttributeAccessFlags int32

PointerAttributeAccessFlags represents access flags that specify the level of access the current context’s device has on the memory referenced.

const (
	// PointerAttributeAccessFlagNone: No access, meaning the device cannot access this memory at all, thus must be staged through accessible memory in order to complete certain operations
	PointerAttributeAccessFlagNone PointerAttributeAccessFlags = 0x0
	// PointerAttributeAccessFlagRead: Read-only access, meaning writes to this memory are considered invalid accesses and thus return error in that case.
	PointerAttributeAccessFlagRead PointerAttributeAccessFlags = 0x1
	// PointerAttributeAccessFlagReadwrite: Read-write access, the device has full read-write access to the memory
	PointerAttributeAccessFlagReadwrite PointerAttributeAccessFlags = 0x3
)

func (PointerAttributeAccessFlags) String

String returns the constant name, or a numeric representation for unknown values.

type PointerAttributeP2PTokens

type PointerAttributeP2PTokens struct {
	P2pToken     uint64
	VaSpaceToken uint32
}

PointerAttributeP2PTokens represents GPU Direct v3 tokens.

type PointerAttributeP2PTokensV1

type PointerAttributeP2PTokensV1 = PointerAttributeP2PTokens

PointerAttributeP2PTokensV1 is an alias for PointerAttributeP2PTokens.

type ProcessState

type ProcessState int32

ProcessState represents CUDA Process States.

const (
	ProcessStateRunning ProcessState = 0 // Default process state
	// ProcessStateLocked: CUDA API locks are taken so further CUDA API calls will block
	ProcessStateLocked ProcessState = 1
	// ProcessStateCheckpointed: Application memory contents have been checkpointed and underlying allocations and device handles have been released
	ProcessStateCheckpointed ProcessState = 2
	// ProcessStateFailed: Application entered an uncorrectable error during the checkpoint/restore process
	ProcessStateFailed        ProcessState = 3
	ProcessStateCheckpointing ProcessState = 4 // Application memory contents are being checkpointed
	ProcessStateRestoring     ProcessState = 5 // Application memory contents are being restored
)

func CheckpointProcessGetState

func CheckpointProcessGetState(pid int32) (ProcessState, error)

CheckpointProcessGetState returns the process state of a CUDA process.

Returns the current state of the CUDA process specified by pid.

Requires CUDA 12.8 (driver r570) or later; see HasCheckpointProcessGetState.

  • pid: The process ID of the CUDA process

Errors:

Wraps cuCheckpointProcessGetState.

func (ProcessState) String

func (e ProcessState) String() string

String returns the constant name, or a numeric representation for unknown values.

type ResourceDesc

type ResourceDesc struct {
	// Resource type
	ResType Resourcetype
	Res     [16]uint64
	// Flags (must be zero)
	Flags uint32
}

ResourceDesc represents CUDA Resource descriptor.

func SurfObjectGetResourceDesc

func SurfObjectGetResourceDesc(surfObject uint64) (ResourceDesc, error)

SurfObjectGetResourceDesc returns a surface object’s resource descriptor.

Returns the resource descriptor for the surface object specified by surfObject.

See also: SurfObjectCreate, cudaGetSurfaceObjectResourceDesc

  • surfObject: Surface object

Errors:

Wraps cuSurfObjectGetResourceDesc.

func TexObjectGetResourceDesc

func TexObjectGetResourceDesc(texObject uint64) (ResourceDesc, error)

TexObjectGetResourceDesc returns a texture object’s resource descriptor.

Returns the resource descriptor for the texture object specified by texObject.

See also: TexObjectCreate, cudaGetTextureObjectResourceDesc

  • texObject: Texture object

Errors:

Wraps cuTexObjectGetResourceDesc.

type ResourceDescV1

type ResourceDescV1 = ResourceDesc

ResourceDescV1 is an alias for ResourceDesc.

type ResourceViewDesc

type ResourceViewDesc struct {
	// Resource view format
	Format ResourceViewFormat
	// Width of the resource view
	Width uint
	// Height of the resource view
	Height uint
	// Depth of the resource view
	Depth uint
	// First defined mipmap level
	FirstMipmapLevel uint32
	// Last defined mipmap level
	LastMipmapLevel uint32
	// First layer index
	FirstLayer uint32
	// Last layer index
	LastLayer uint32
	Reserved  [16]uint32
}

ResourceViewDesc represents resource view descriptor.

func TexObjectGetResourceViewDesc

func TexObjectGetResourceViewDesc(texObject uint64) (ResourceViewDesc, error)

TexObjectGetResourceViewDesc returns a texture object’s resource view descriptor.

Returns the resource view descriptor for the texture object specified by texObject. If no resource view was set for texObject, the ErrInvalidValue is returned.

See also: TexObjectCreate, cudaGetTextureObjectResourceViewDesc

  • texObject: Texture object

Errors:

Wraps cuTexObjectGetResourceViewDesc.

type ResourceViewDescV1

type ResourceViewDescV1 = ResourceViewDesc

ResourceViewDescV1 is an alias for ResourceViewDesc.

type ResourceViewFormat

type ResourceViewFormat int32

ResourceViewFormat represents resource view format.

const (
	ResViewFormatNone         ResourceViewFormat = 0x00 // No resource view format (use underlying resource format)
	ResViewFormatUint1X8      ResourceViewFormat = 0x01 // 1 channel unsigned 8-bit integers
	ResViewFormatUint2X8      ResourceViewFormat = 0x02 // 2 channel unsigned 8-bit integers
	ResViewFormatUint4X8      ResourceViewFormat = 0x03 // 4 channel unsigned 8-bit integers
	ResViewFormatSint1X8      ResourceViewFormat = 0x04 // 1 channel signed 8-bit integers
	ResViewFormatSint2X8      ResourceViewFormat = 0x05 // 2 channel signed 8-bit integers
	ResViewFormatSint4X8      ResourceViewFormat = 0x06 // 4 channel signed 8-bit integers
	ResViewFormatUint1X16     ResourceViewFormat = 0x07 // 1 channel unsigned 16-bit integers
	ResViewFormatUint2X16     ResourceViewFormat = 0x08 // 2 channel unsigned 16-bit integers
	ResViewFormatUint4X16     ResourceViewFormat = 0x09 // 4 channel unsigned 16-bit integers
	ResViewFormatSint1X16     ResourceViewFormat = 0x0a // 1 channel signed 16-bit integers
	ResViewFormatSint2X16     ResourceViewFormat = 0x0b // 2 channel signed 16-bit integers
	ResViewFormatSint4X16     ResourceViewFormat = 0x0c // 4 channel signed 16-bit integers
	ResViewFormatUint1X32     ResourceViewFormat = 0x0d // 1 channel unsigned 32-bit integers
	ResViewFormatUint2X32     ResourceViewFormat = 0x0e // 2 channel unsigned 32-bit integers
	ResViewFormatUint4X32     ResourceViewFormat = 0x0f // 4 channel unsigned 32-bit integers
	ResViewFormatSint1X32     ResourceViewFormat = 0x10 // 1 channel signed 32-bit integers
	ResViewFormatSint2X32     ResourceViewFormat = 0x11 // 2 channel signed 32-bit integers
	ResViewFormatSint4X32     ResourceViewFormat = 0x12 // 4 channel signed 32-bit integers
	ResViewFormatFloat1X16    ResourceViewFormat = 0x13 // 1 channel 16-bit floating point
	ResViewFormatFloat2X16    ResourceViewFormat = 0x14 // 2 channel 16-bit floating point
	ResViewFormatFloat4X16    ResourceViewFormat = 0x15 // 4 channel 16-bit floating point
	ResViewFormatFloat1X32    ResourceViewFormat = 0x16 // 1 channel 32-bit floating point
	ResViewFormatFloat2X32    ResourceViewFormat = 0x17 // 2 channel 32-bit floating point
	ResViewFormatFloat4X32    ResourceViewFormat = 0x18 // 4 channel 32-bit floating point
	ResViewFormatUnsignedBC1  ResourceViewFormat = 0x19 // Block compressed 1
	ResViewFormatUnsignedBC2  ResourceViewFormat = 0x1a // Block compressed 2
	ResViewFormatUnsignedBC3  ResourceViewFormat = 0x1b // Block compressed 3
	ResViewFormatUnsignedBC4  ResourceViewFormat = 0x1c // Block compressed 4 unsigned
	ResViewFormatSignedBC4    ResourceViewFormat = 0x1d // Block compressed 4 signed
	ResViewFormatUnsignedBC5  ResourceViewFormat = 0x1e // Block compressed 5 unsigned
	ResViewFormatSignedBC5    ResourceViewFormat = 0x1f // Block compressed 5 signed
	ResViewFormatUnsignedBC6H ResourceViewFormat = 0x20 // Block compressed 6 unsigned half-float
	ResViewFormatSignedBC6H   ResourceViewFormat = 0x21 // Block compressed 6 signed half-float
	ResViewFormatUnsignedBC7  ResourceViewFormat = 0x22 // Block compressed 7
)

func (ResourceViewFormat) String

func (e ResourceViewFormat) String() string

String returns the constant name, or a numeric representation for unknown values.

type Resourcetype

type Resourcetype int32

Resourcetype represents resource types.

const (
	ResourceTypeArray          Resourcetype = 0x00 // Array resource
	ResourceTypeMipmappedArray Resourcetype = 0x01 // Mipmapped array resource
	ResourceTypeLinear         Resourcetype = 0x02 // Linear resource
	ResourceTypePitch2d        Resourcetype = 0x03 // Pitch 2D resource
)

func (Resourcetype) String

func (e Resourcetype) String() string

String returns the constant name, or a numeric representation for unknown values.

type Result

type Result int32

Result represents a cuda API error code (CUresult).

When the library is loaded, Result.Error returns rich messages from GetErrorName and GetErrorString. When the library is not loaded, it falls back to the numeric error code and Go-defined name.

const (
	Success             Result = 0 // The API call returned with no errors. In the case of query calls, this also means that the operation being queried is complete (see [Event.Query] and [Stream.Query]).
	ErrInvalidValue     Result = 1 // This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values.
	ErrOutOfMemory      Result = 2 // The API call failed because it was unable to allocate enough memory or other resources to perform the requested operation.
	ErrNotInitialized   Result = 3 // This indicates that the CUDA driver has not been initialized with [Init] or that initialization has failed.
	ErrDeinitialized    Result = 4 // This indicates that the CUDA driver is in the process of shutting down.
	ErrProfilerDisabled Result = 5 // This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler.
	//
	// Deprecated: Deprecated in CUDA 5.0. This error return is deprecated as of CUDA 5.0. It is no longer an error to attempt to enable/disable the profiling via cuProfilerStart or cuProfilerStop without initialization.
	ErrProfilerNotInitialized Result = 6
	//
	// Deprecated: Deprecated in CUDA 5.0. This error return is deprecated as of CUDA 5.0. It is no longer an error to call cuProfilerStart() when profiling is already enabled.
	ErrProfilerAlreadyStarted Result = 7
	//
	// Deprecated: Deprecated in CUDA 5.0. This error return is deprecated as of CUDA 5.0. It is no longer an error to call cuProfilerStop() when profiling is already disabled.
	ErrProfilerAlreadyStopped  Result = 8
	ErrStubLibrary             Result = 34  // This indicates that the CUDA driver that the application has loaded is a stub library. Applications that run with the stub rather than a real driver loaded will result in CUDA API returning this error.
	ErrCallRequiresNewerDriver Result = 36  // This indicates that the API call requires a newer CUDA driver than the one currently installed. Users should install an updated NVIDIA CUDA driver to allow the API call to succeed.
	ErrDeviceUnavailable       Result = 46  // This indicates that requested CUDA device is unavailable at the current time. Devices are often unavailable due to use of [ComputemodeExclusiveProcess] or [ComputemodeProhibited].
	ErrMulticastResourceFull   Result = 47  // The API call failed because of a hardware resource required to bind memory to a multicast object is unavailable.
	ErrNoDevice                Result = 100 // This indicates that no CUDA-capable devices were detected by the installed CUDA driver.
	ErrInvalidDevice           Result = 101 // This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device or that the action requested is invalid for the specified device.
	ErrDeviceNotLicensed       Result = 102 // This error indicates that the Grid license is not applied.
	ErrInvalidImage            Result = 200 // This indicates that the device kernel image is invalid. This can also indicate an invalid CUDA module.
	ErrInvalidContext          Result = 201 // This most frequently indicates that there is no context bound to the current thread. This can also be returned if the context passed to an API call is not a valid handle (such as a context that has had [Context.Close] invoked on it). This can also be returned if a user mixes different API versions (i.e. 3010 context with 3020 API calls). See [Context.ApiVersion] for more details. This can also be returned if the green context passed to an API call was not converted to a [Context] using [CtxFromGreenCtx] API.
	// ErrContextAlreadyCurrent: This indicated that the context being supplied as a parameter to the API call was already the active context.
	//
	// Deprecated: Deprecated in CUDA 3.2. This error return is deprecated as of CUDA 3.2. It is no longer an error to attempt to push the active context via [Context.PushCurrent].
	ErrContextAlreadyCurrent        Result = 202
	ErrMapFailed                    Result = 205 // This indicates that a map or register operation has failed.
	ErrUnmapFailed                  Result = 206 // This indicates that an unmap or unregister operation has failed.
	ErrArrayIsMapped                Result = 207 // This indicates that the specified array is currently mapped and thus cannot be destroyed.
	ErrAlreadyMapped                Result = 208 // This indicates that the resource is already mapped.
	ErrNoBinaryForGpu               Result = 209 // This indicates that there is no kernel image available that is suitable for the device. This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration.
	ErrAlreadyAcquired              Result = 210 // This indicates that a resource has already been acquired.
	ErrNotMapped                    Result = 211 // This indicates that a resource is not mapped.
	ErrNotMappedAsArray             Result = 212 // This indicates that a mapped resource is not available for access as an array.
	ErrNotMappedAsPointer           Result = 213 // This indicates that a mapped resource is not available for access as a pointer.
	ErrEccUncorrectable             Result = 214 // This indicates that an uncorrectable ECC error was detected during execution.
	ErrUnsupportedLimit             Result = 215 // This indicates that the [Limit] passed to the API call is not supported by the active device.
	ErrContextAlreadyInUse          Result = 216 // This indicates that the [Context] passed to the API call can only be bound to a single CPU thread at a time but is already bound to a CPU thread.
	ErrPeerAccessUnsupported        Result = 217 // This indicates that peer access is not supported across the given devices.
	ErrInvalidPtx                   Result = 218 // This indicates that a PTX JIT compilation failed.
	ErrInvalidGraphicsContext       Result = 219 // This indicates an error with OpenGL or DirectX context.
	ErrNvlinkUncorrectable          Result = 220 // This indicates that an uncorrectable NVLink error was detected during the execution.
	ErrJitCompilerNotFound          Result = 221 // This indicates that the PTX JIT compiler library was not found.
	ErrUnsupportedPtxVersion        Result = 222 // This indicates that the provided PTX was compiled with an unsupported toolchain.
	ErrJitCompilationDisabled       Result = 223 // This indicates that the PTX JIT compilation was disabled.
	ErrUnsupportedExecAffinity      Result = 224 // This indicates that the [ExecAffinityType] passed to the API call is not supported by the active device.
	ErrUnsupportedDevsideSync       Result = 225 // This indicates that the code to be compiled by the PTX JIT contains unsupported call to cudaDeviceSynchronize.
	ErrContained                    Result = 226 // This indicates that an exception occurred on the device that is now contained by the GPU's error containment capability. Common causes are - a. Certain types of invalid accesses of peer GPU memory over nvlink b. Certain classes of hardware errors This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrInsufficientLoaderVersion    Result = 227 // This indicates that the Loader version is insufficient for fatbin
	ErrInvalidSource                Result = 300 // This indicates that the device kernel source is invalid. This includes compilation/linker errors encountered in device code or user error.
	ErrFileNotFound                 Result = 301 // This indicates that the file specified was not found.
	ErrSharedObjectSymbolNotFound   Result = 302 // This indicates that a link to a shared object failed to resolve.
	ErrSharedObjectInitFailed       Result = 303 // This indicates that initialization of a shared object failed.
	ErrOperatingSystem              Result = 304 // This indicates that an OS call failed.
	ErrInvalidHandle                Result = 400 // This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like [Stream] and [Event].
	ErrIllegalState                 Result = 401 // This indicates that a resource required by the API call is not in a valid state to perform the requested operation.
	ErrLossyQuery                   Result = 402 // This indicates an attempt was made to introspect an object in a way that would discard semantically important information. This is either due to the object using funtionality newer than the API version used to introspect it or omission of optional return arguments.
	ErrNotFound                     Result = 500 // This indicates that a named symbol was not found. Examples of symbols are global/constant variable names, driver function names, texture names, and surface names.
	ErrNotReady                     Result = 600 // This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than [Success] (which indicates completion). Calls that may return this value include [Event.Query] and [Stream.Query].
	ErrIllegalAddress               Result = 700 // While executing a kernel, the device encountered a load or store instruction on an invalid memory address. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrLaunchOutOfResources         Result = 701 // This indicates that a launch did not occur because it did not have appropriate resources. This error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count. Passing arguments of the wrong size (i.e. a 64-bit pointer when a 32-bit int is expected) is equivalent to passing too many arguments and can also result in this error.
	ErrLaunchTimeout                Result = 702 // This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device attribute [DevAttrKernelExecTimeout] for more information. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrLaunchIncompatibleTexturing  Result = 703 // This error indicates a kernel launch that uses an incompatible texturing mode.
	ErrPeerAccessAlreadyEnabled     Result = 704 // This error indicates that a call to [Context.EnablePeerAccess] is trying to re-enable peer access to a context which has already had peer access to it enabled.
	ErrPeerAccessNotEnabled         Result = 705 // This error indicates that [Context.DisablePeerAccess] is trying to disable peer access which has not been enabled yet via [Context.EnablePeerAccess].
	ErrPrimaryContextActive         Result = 708 // This error indicates that the primary context for the specified device has already been initialized.
	ErrContextIsDestroyed           Result = 709 // This error indicates that the context current to the calling thread has been destroyed using [Context.Close], or is a primary context which has not yet been initialized.
	ErrAssert                       Result = 710 // A device-side assert triggered during kernel execution. The context cannot be used anymore, and must be destroyed. All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA.
	ErrTooManyPeers                 Result = 711 // This error indicates that the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to [Context.EnablePeerAccess].
	ErrHostMemoryAlreadyRegistered  Result = 712 // This error indicates that the memory range passed to [MemHostRegister] has already been registered.
	ErrHostMemoryNotRegistered      Result = 713 // This error indicates that the pointer passed to [MemHostUnregister] does not correspond to any currently registered memory region.
	ErrHardwareStackError           Result = 714 // While executing a kernel, the device encountered a stack error. This can be due to stack corruption or exceeding the stack size limit. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrIllegalInstruction           Result = 715 // While executing a kernel, the device encountered an illegal instruction. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrMisalignedAddress            Result = 716 // While executing a kernel, the device encountered a load or store instruction on a memory address which is not aligned. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrInvalidAddressSpace          Result = 717 // While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrInvalidPc                    Result = 718 // While executing a kernel, the device program counter wrapped its address space. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrLaunchFailed                 Result = 719 // An exception occurred on the device while executing a kernel. Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory. Less common cases can be system specific - more information about these cases can be found in the system specific user guide. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrCooperativeLaunchTooLarge    Result = 720 // This error indicates that the number of blocks launched per grid for a kernel that was launched via either [Function.LaunchCooperativeKernel] or [LaunchCooperativeKernelMultiDevice] exceeds the maximum number of blocks as allowed by [Function.MaxActiveBlocksPerMultiprocessor] or [Function.MaxActiveBlocksPerMultiprocessorWithFlags] times the number of multiprocessors as specified by the device attribute [DevAttrMultiprocessorCount].
	ErrTensorMemoryLeak             Result = 721 // An exception occurred on the device while exiting a kernel using tensor memory: the tensor memory was not completely deallocated. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched.
	ErrNotPermitted                 Result = 800 // This error indicates that the attempted operation is not permitted.
	ErrNotSupported                 Result = 801 // This error indicates that the attempted operation is not supported on the current system or device.
	ErrSystemNotReady               Result = 802 // This error indicates that the system is not yet ready to start any CUDA work. To continue using CUDA, verify the system configuration is in a valid state and all required driver daemons are actively running. More information about this error can be found in the system specific user guide.
	ErrSystemDriverMismatch         Result = 803 // This error indicates that there is a mismatch between the versions of the display driver and the CUDA driver. Refer to the compatibility documentation for supported versions.
	ErrCompatNotSupportedOnDevice   Result = 804 // This error indicates that the system was upgraded to run with forward compatibility but the visible hardware detected by CUDA does not support this configuration. Refer to the compatibility documentation for the supported hardware matrix or ensure that only supported hardware is visible during initialization via the CUDA_VISIBLE_DEVICES environment variable.
	ErrMpsConnectionFailed          Result = 805 // This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server.
	ErrMpsRpcFailure                Result = 806 // This error indicates that the remote procedural call between the MPS server and the MPS client failed.
	ErrMpsServerNotReady            Result = 807 // This error indicates that the MPS server is not ready to accept new MPS client requests. This error can be returned when the MPS server is in the process of recovering from a fatal failure.
	ErrMpsMaxClientsReached         Result = 808 // This error indicates that the hardware resources required to create MPS client have been exhausted.
	ErrMpsMaxConnectionsReached     Result = 809 // This error indicates the the hardware resources required to support device connections have been exhausted.
	ErrMpsClientTerminated          Result = 810 // This error indicates that the MPS client has been terminated by the server. To continue using CUDA, the process must be terminated and relaunched.
	ErrCdpNotSupported              Result = 811 // This error indicates that the module is using CUDA Dynamic Parallelism, but the current configuration, like MPS, does not support it.
	ErrCdpVersionMismatch           Result = 812 // This error indicates that a module contains an unsupported interaction between different versions of CUDA Dynamic Parallelism.
	ErrStreamCaptureUnsupported     Result = 900 // This error indicates that the operation is not permitted when the stream is capturing.
	ErrStreamCaptureInvalidated     Result = 901 // This error indicates that the current capture sequence on the stream has been invalidated due to a previous error.
	ErrStreamCaptureMerge           Result = 902 // This error indicates that the operation would have resulted in a merge of two independent capture sequences.
	ErrStreamCaptureUnmatched       Result = 903 // This error indicates that the capture was not initiated in this stream.
	ErrStreamCaptureUnjoined        Result = 904 // This error indicates that the capture sequence contains a fork that was not joined to the primary stream.
	ErrStreamCaptureIsolation       Result = 905 // This error indicates that a dependency would have been created which crosses the capture sequence boundary. Only implicit in-stream ordering dependencies are allowed to cross the boundary.
	ErrStreamCaptureImplicit        Result = 906 // This error indicates a disallowed implicit dependency on a current capture sequence from cudaStreamLegacy.
	ErrCapturedEvent                Result = 907 // This error indicates that the operation is not permitted on an event which was last recorded in a capturing stream.
	ErrStreamCaptureWrongThread     Result = 908 // A stream capture sequence not initiated with the [StreamCaptureModeRelaxed] argument to [Stream.BeginCapture] was passed to [Stream.EndCapture] in a different thread.
	ErrTimeout                      Result = 909 // This error indicates that the timeout specified for the wait operation has lapsed.
	ErrGraphExecUpdateFailure       Result = 910 // This error indicates that the graph update was not performed because it included changes which violated constraints specific to instantiated graph update.
	ErrExternalDevice               Result = 911 // This indicates that an error has occurred in a device outside of GPU. It can be a synchronous error w.r.t. CUDA API or an asynchronous error from the external device. In case of asynchronous error, it means that if cuda was waiting for an external device's signal before consuming shared data, the external device signaled an error indicating that the data is not valid for consumption. This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched. In case of synchronous error, it means that one or more external devices have encountered an error and cannot complete the operation.
	ErrInvalidClusterSize           Result = 912 // Indicates a kernel launch error due to cluster misconfiguration.
	ErrFunctionNotLoaded            Result = 913 // Indiciates a function handle is not loaded when calling an API that requires a loaded function.
	ErrInvalidResourceType          Result = 914 // This error indicates one or more resources passed in are not valid resource types for the operation.
	ErrInvalidResourceConfiguration Result = 915 // This error indicates one or more resources are insufficient or non-applicable for the operation.
	ErrKeyRotation                  Result = 916 // This error indicates that an error happened during the key rotation sequence.
	ErrStreamDetached               Result = 917 // This error indicates that the requested operation is not permitted because the stream is in a detached state. This can occur if the green context associated with the stream has been destroyed, limiting the stream's operational capabilities.
	ErrGraphRecaptureFailure        Result = 918 // This error indicates that a graph recapture failed and had to be terminated.
	ErrFabricNotReady               Result = 919 // The GPU fabric is not ready within the bounded wait while the fabric manager probe is still in progress (or not converging in time). Applications may retry after a delay; for the initialization wait budget, see environment variables such as CUDA_FABRIC_INIT_TIMEOUT_MS. The CUDA Runtime uses the same value as cudaErrorFabricNotReady.
	ErrUnknown                      Result = 999
)

cuda error codes from cuda.h.

func (Result) Code

func (r Result) Code() int32

Code returns the underlying result code for programmatic error handling.

func (Result) Error

func (r Result) Error() string

Error implements the error interface. When the library is loaded, it returns rich messages from GetErrorName and GetErrorString. Otherwise it returns a fallback string with the Go constant name and numeric code.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type SharedCarveout

type SharedCarveout int32

SharedCarveout represents shared memory carveout configurations.

These may be passed to Function.SetAttribute or Kernel.SetAttribute

const (
	SharedmemCarveoutDefault   SharedCarveout = -1  // No preference for shared memory or L1 (default)
	SharedmemCarveoutMaxShared SharedCarveout = 100 // Prefer maximum available shared memory, minimum L1 cache
	SharedmemCarveoutMaxL1     SharedCarveout = 0   // Prefer maximum available L1 cache, minimum shared memory
)

func (SharedCarveout) String

func (e SharedCarveout) String() string

String returns the constant name, or a numeric representation for unknown values.

type SharedMemoryMode

type SharedMemoryMode int32

SharedMemoryMode represents shared memory related attributes for use with Function.LaunchKernelEx.

const (
	// SharedMemoryModeDefault: The default to use for shared memory on launch - uses current function attribute for [FuncAttributeMaxDynamicSharedSizeBytes]
	SharedMemoryModeDefault SharedMemoryMode = 0
	// SharedMemoryModeRequirePortable: Specifies that the dynamic shared size bytes requested must be a portable size within the bounds of [DevAttrMaxSharedMemoryPerBlock]
	SharedMemoryModeRequirePortable SharedMemoryMode = 1
	// SharedMemoryModeAllowNonPortable: Specifies that the dynamic shared size bytes requested may be a non-portable size but still within the bounds of [DevAttrMaxSharedMemoryPerBlockOptin]
	SharedMemoryModeAllowNonPortable SharedMemoryMode = 2
	// SharedMemoryModeAllowOversizedSharedMemory: Specifies that oversized shared memory configurations may be used (with the limitation of only 8kB L1 cache)
	SharedMemoryModeAllowOversizedSharedMemory SharedMemoryMode = 3
	// SharedMemoryModePreferOversizedSharedMemory: Specifies that oversized shared memory configurations may be used (with the limitation of only 8kB L1 cache), and prefer an oversized shared memory configuration
	SharedMemoryModePreferOversizedSharedMemory SharedMemoryMode = 4
)

func (SharedMemoryMode) String

func (e SharedMemoryMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type Sharedconfig deprecated

type Sharedconfig int32

Sharedconfig represents shared memory configurations.

Deprecated: Deprecated by NVIDIA.

const (
	SharedMemConfigDefaultBankSize   Sharedconfig = 0x00 // set default shared memory bank size
	SharedMemConfigFourByteBankSize  Sharedconfig = 0x01 // set shared memory bank width to four bytes
	SharedMemConfigEightByteBankSize Sharedconfig = 0x02 // set shared memory bank width to eight bytes
)

func CtxGetSharedMemConfig deprecated

func CtxGetSharedMemConfig() (Sharedconfig, error)

CtxGetSharedMemConfig returns the current shared memory configuration for the current context.

This function will return the current size of shared memory banks in the current context. On devices with configurable shared memory banks, CtxSetSharedMemConfig can be used to change this setting, so that all subsequent kernel launches will by default use the new bank size. When CtxGetSharedMemConfig 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:

See also: NewContext, Context.Close, Context.ApiVersion, CtxGetCacheConfig, CtxGetDevice, CtxGetFlags, CtxGetLimit, CtxPopCurrent, Context.PushCurrent, CtxSetLimit, CtxSynchronize, CtxGetSharedMemConfig, Function.SetCacheConfig, cudaDeviceGetSharedMemConfig

Errors:

Wraps cuCtxGetSharedMemConfig.

Deprecated: Deprecated by NVIDIA.

func (Sharedconfig) String

func (e Sharedconfig) String() string

String returns the constant name, or a numeric representation for unknown values.

type Stream

type Stream uintptr

Stream is an opaque handle to a CUDA stream. Created via NewStream and destroyed via [Stream.Destroy].

const (
	StreamLegacy    Stream = 0x1
	StreamPerThread Stream = 0x2
)

Driver Stream tokens from cuda.h.

func NewStream

func NewStream(flags StreamFlags) (Stream, error)

NewStream creates a stream.

Creates a stream and returns a handle. The Flags argument determines behaviors of the stream. Valid values for Flags are:

  • StreamDefault: Default stream creation flag.
  • StreamNonBlocking: 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.

See also: Stream.Close, StreamCreateWithPriority, GreenCtx.StreamCreate, Stream.Priority, Stream.Flags, Stream.Device Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreate, cudaStreamCreateWithFlags

  • flags: Parameters for stream creation

Errors:

Wraps cuStreamCreate.

func StreamCreateWithPriority

func StreamCreateWithPriority(flags uint32, priority int32) (Stream, error)

StreamCreateWithPriority creates a stream with the given priority.

Creates a stream with the specified priority and returns a handle. This affects the scheduling priority of work in the stream. Priorities provide a hint to preferentially run work with higher priority when possible, but do not preempt already-running work or provide any other functional guarantee on execution order. priority follows a convention where lower numbers represent higher priorities. ‘0’ represents default priority. The range of meaningful numerical priorities can be queried using CtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by CtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range.

Note: Stream priorities are supported only on GPUs with compute capability 3.5 or higher.

Note: 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.

See also: Stream.Close, NewStream, GreenCtx.StreamCreate, Stream.Priority, CtxGetStreamPriorityRange, Stream.Flags, Stream.Device, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreateWithPriority

  • flags: Flags for stream creation. See NewStream for a list of valid flags
  • priority: Stream priority. Lower numbers represent higher priorities. See CtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed

Errors:

Wraps cuStreamCreateWithPriority.

func (Stream) AddCallback

func (s Stream) AddCallback(callback uintptr, userData uintptr, flags uint32) error

AddCallback adds 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 Stream.AddCallback call, the callback will be executed exactly once. The callback will block later work in the stream until it is finished. The callback may be passed Success or an error code. In the event of a device error, all subsequently executed callbacks will receive an appropriate Result. Callbacks must not make any CUDA API calls. Attempting to use a CUDA API will result in ErrNotPermitted. 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 host functions and stream callbacks have executed. Thus, for example, a callback might use global attached memory even if work has been added to another stream, if the work has been ordered behind the callback 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.

Note: 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 Stream.LaunchHostFunc. Additionally, this function is not supported with Stream.BeginCapture and Stream.EndCapture, unlike Stream.LaunchHostFunc.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Query, Stream.Synchronize, Stream.WaitEvent, Stream.Close, MemAllocManaged, Stream.AttachMemAsync, Stream.LaunchHostFunc, cudaStreamAddCallback

  • callback: The function to call once preceding stream operations are complete (see StreamCallback)
  • userData: User specified data to be passed to the callback function
  • flags: Reserved for future use, must be 0

Errors:

Wraps cuStreamAddCallback.

func (Stream) AttachMemAsync

func (s Stream) AttachMemAsync(dptr DevicePtr, length uint, flags MemattachFlags) error

AttachMemAsync attaches memory to a stream asynchronously.

Enqueues an operation in hStream to specify stream association of length bytes of memory starting from dptr. 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. dptr must point to one of the following types of memories:

  • managed memory declared using the managed keyword or allocated with MemAllocManaged.
  • 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 DevAttrPageableMemoryAccess.

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 host allocations, length must be non-zero. The stream association is specified using flags which must be one of MemattachFlags. If the MemAttachGlobal flag is specified, the memory can be accessed by any stream on any device. If the MemAttachHost 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 attribute DevAttrConcurrentManagedAccess. If the MemAttachSingle flag is specified and hStream is associated with a device that has a zero value for the device attribute DevAttrConcurrentManagedAccess, the program makes a guarantee that it will only access the memory on the device from hStream. 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 hStream 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 Stream.AttachMemAsync 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 hStream 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 MemAllocManaged. For managed variables, the default association is always MemAttachGlobal. 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.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Query, Stream.Synchronize, Stream.WaitEvent, Stream.Close, MemAllocManaged, cudaStreamAttachMemAsync

  • dptr: Pointer to memory (must be a pointer to managed memory or to a valid host-accessible region of system-allocated pageable memory)
  • length: Length of memory
  • flags: Must be one of MemattachFlags

Errors:

Wraps cuStreamAttachMemAsync.

func (Stream) Attribute

func (s Stream) Attribute(attr int32) ([8]uint64, error)

Attribute queries stream attribute.

Queries attribute attr from hStream and stores it in corresponding member of valueOut.

See also: AccessPolicyWindow

Errors:

Wraps cuStreamGetAttribute.

func (Stream) BatchMemOp

func (s Stream) BatchMemOp(count uint32, paramArray *[6]uint64, flags uint32) error

BatchMemOp enqueues a batch of memory operations that synchronize the stream.

Batch operations to synchronize the stream via memory operations.

This is a batch version of Stream.WaitValue32 and Stream.WriteValue32. Batching operations may avoid some performance overhead in both the API call and the device execution versus adding them to the stream in separate API calls. The operations are enqueued in the order they appear in the array. See StreamBatchMemOpType for the full set of supported operations, and Stream.WaitValue32, Stream.WaitValue64, Stream.WriteValue32, and Stream.WriteValue64 for details of specific operations. See related APIs for details on querying support for specific operations.

Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order.

See also: Stream.WaitValue32, Stream.WaitValue64, Stream.WriteValue32, Stream.WriteValue64, MemHostRegister

  • count: The number of operations in the array. Must be less than 256
  • paramArray: The types and parameters of the individual operations
  • flags: Reserved for future expansion; must be 0

Errors:

Wraps cuStreamBatchMemOp, bound as cuStreamBatchMemOp_v2.

func (Stream) BeginCapture

func (s Stream) BeginCapture(mode StreamCaptureMode) error

BeginCapture begins graph capture on a stream.

Begin graph capture on hStream. 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 Stream.EndCapture. Capture may not be initiated if stream is CU_STREAM_LEGACY. 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 via Stream.IsCapturing. A unique id representing the capture sequence may be queried via Stream.CaptureInfo. If mode is not StreamCaptureModeRelaxed, Stream.EndCapture must be called on this stream from the same thread.

Note: 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.

See also: NewStream, Stream.IsCapturing, Stream.EndCapture, ThreadExchangeStreamCaptureMode

  • mode: Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details see ThreadExchangeStreamCaptureMode

Errors:

Wraps cuStreamBeginCapture, bound as cuStreamBeginCapture_v2.

func (Stream) BeginCaptureToCig

func (s Stream) BeginCaptureToCig(streamCigCaptureParams *StreamCigCaptureParams) error

BeginCaptureToCig begins capture to CIG on a stream.

Support for CIG streams with D3D12 can be determined using Device.Attribute with DevAttrD3d12CigStreamsSupported. Begin CIG (CUDA in Graphics) capture on hStream for the graphics API as provided in streamCigCaptureParams. When a stream is in CIG capture mode, all operations pushed into the stream will not be executed, but will instead be captured into a graphics API command list/command buffer. All kernel launches and memory copy/memory set operations on the CIG stream will be recorded. When the command list is executed by the graphics API, all the stream’s operations will execute in order along with other graphics API commands in the command list. CIG stream capture may not be initiated if stream is CU_STREAM_LEGACY. 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 CIG capture mode. The context must be also created in CIG mode previously, otherwise this operation will fail and ErrInvalidContext will be returned. Data from the graphics client can be shared with CUDA via the streamSharedData in streamCigCaptureParams. The format of streamSharedData is dependent on the type of the graphics client. For D3D12, streamSharedData is an ID3D12CommandList object pointer. The command list must be in ready state for recording commands whenever kernels are launched on the stream. The command list provided must belong to the graphics API device that the CIG context was created with, otherwise the behavior will be undefined. The stream object may not be destroyed until its associated command list has finished executing on the GPU. The command list/command buffer used for capture may not be submitted for execution before a call to Stream.EndCaptureToCig is made on the associated stream. Graphics resources to be accessed by work recorded on the CIG stream must use UAV barriers on the command list prior to recording work that accesses them on the stream. Resubmission of the same recorded command list is not allowed. Further more, care must be taken for the order of execution of the recorded CUDA work with regards to other CUDA work submitted under the same CIG context. Out-of-order execution can lead to device hangs or exceptions. CIG capture mode operates similarly to Stream.BeginCapture with the StreamCaptureModeRelaxed option. There are additional limitations to streams in CIG capture mode. The following functions are not allowed for CIG streams whether directly or indirectly via a recorded graph launch: Stream.LaunchHostFunc Stream.AddCallback Stream.Synchronize Stream.WaitValue32 Stream.WaitValue64 Stream.BatchMemOp Stream.BeginCapture Stream.BeginCaptureToGraph Stream.MemAllocAsync DevicePtr.FreeAsync

See also: Stream.EndCaptureToCig, Stream.BeginCapture, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback

Requires CUDA 13.2 (driver r595) or later; see HasStreamBeginCaptureToCig.

  • streamCigCaptureParams: CIG capture parameters

Errors:

Wraps cuStreamBeginCaptureToCig.

func (Stream) BeginCaptureToGraph

func (s Stream) BeginCaptureToGraph(hGraph Graph, dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, mode StreamCaptureMode) error

BeginCaptureToGraph begins graph capture on a stream to an existing graph.

Begin graph capture on hStream, placing new nodes into an existing graph. When a stream is in capture mode, all operations pushed into the stream will not be executed, but will instead be captured into hGraph. The graph will not be instantiable until the user calls Stream.EndCapture. Capture may not be initiated if stream is CU_STREAM_LEGACY. 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 via Stream.IsCapturing. A unique id representing the capture sequence may be queried via Stream.CaptureInfo. If mode is not StreamCaptureModeRelaxed, Stream.EndCapture must be called on this stream from the same thread.

Note: 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.

See also: Stream.BeginCapture, NewStream, Stream.IsCapturing, Stream.EndCapture, ThreadExchangeStreamCaptureMode, Graph.AddNode

Requires CUDA 12.3 (driver r545) or later; see HasStreamBeginCaptureToGraph.

  • hGraph: Graph to capture into
  • dependencies: Dependencies of the first node captured in the stream. Can be NULL if numDependencies is 0
  • dependencyData: Optional array of data associated with each dependency
  • numDependencies: Number of dependencies
  • mode: Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details see ThreadExchangeStreamCaptureMode

Errors:

Wraps cuStreamBeginCaptureToGraph.

func (Stream) BeginRecaptureToGraph

func (s Stream) BeginRecaptureToGraph(mode StreamCaptureMode, hGraph Graph, callbackFunc uintptr, userData uintptr) error

BeginRecaptureToGraph begins graph capture on a stream to an existing graph.

Begin graph capture on hStream to the existing hGraph. The node creation order while recapturing the graph must be identical to the original graph. The recapture will fail immediately for:

  • Topology mismatches between the existing graph and the recaptured graph
  • Parameter mismatches for memory allocation or free nodes

Any other node parameter mismatches during recapture can be configured to call the function provided in callbackFunc. The recapture will fail immediately if the callback returns anything other than Success. If the recapture fails for any reason, the graph will be in an undefined state and should be destroyed. See Stream.BeginCapture for additional detail on beginning the capture.

Note: Any user objects associated with graph will be released prior to the recapture.

See also: NewStream, Stream.BeginCapture, Stream.IsCapturing, Stream.EndCapture, ThreadExchangeStreamCaptureMode

Requires CUDA 13.3 (driver r610) or later; see HasStreamBeginRecaptureToGraph.

  • mode: Controls the interaction of this capture sequence with other API calls that are potentially unsafe. For more details see ThreadExchangeStreamCaptureMode
  • hGraph: Existing CUDA graph to be captured into
  • callbackFunc: Function that will be called for all parameter mismatches from the original graph (see GraphRecaptureCallback)
  • userData: A generic pointer to user data that is passed into the callback function

Errors:

Wraps cuStreamBeginRecaptureToGraph.

func (Stream) CaptureInfo

func (s Stream) CaptureInfo(captureStatusOut *StreamCaptureStatus, idOut *uint64, graphOut *Graph, dependenciesOut **GraphNode, edgeDataOut **GraphEdgeData, numDependenciesOut *uint) error

CaptureInfo queries a stream’s capture state.

Query stream state related to stream capture. If called on CU_STREAM_LEGACY (the “null stream”) while a stream not created with StreamNonBlocking is capturing, returns ErrStreamCaptureImplicit. Valid data (other than capture status) is returned only if both of the following are true:

If edgeDataOut is non-NULL then dependenciesOut must be as well. If dependenciesOut is non-NULL and edgeDataOut is NULL, but there is non-zero edge data for one or more of the current stream dependencies, the call will return ErrLossyQuery.

See also: Stream.BeginCapture, Stream.IsCapturing, Stream.UpdateCaptureDependencies

  • captureStatusOut: Location to return the capture status of the stream; required
  • idOut: Optional location to return an id for the capture sequence, which is unique over the lifetime of the process
  • graphOut: 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 at Stream.EndCapture. 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 at Stream.EndCapture due to direct actions on the graph do not trigger ErrStreamCaptureUnjoined
  • dependenciesOut: 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 the capture is terminated. 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
  • edgeDataOut: Optional location to store a pointer to an array of graph edge data. This array parallels dependenciesOut; the next node to be added has an edge to dependencies_outi with annotation edgeData_outi for each i. The array pointer is valid until the next API call which operates on the stream or until the capture is terminated
  • numDependenciesOut: Optional location to store the size of the array returned in dependenciesOut

Errors:

Wraps cuStreamGetCaptureInfo, bound to the first of cuStreamGetCaptureInfo_v3, cuStreamGetCaptureInfo_v2 that the library exports. On libraries without cuStreamGetCaptureInfo_v3, it calls cuStreamGetCaptureInfo_v2; a non-nil edgeDataOut returns ErrNotSupported.

func (Stream) CaptureInfoV2 deprecated

func (s Stream) CaptureInfoV2(captureStatusOut *StreamCaptureStatus, idOut *uint64, graphOut *Graph, dependenciesOut **GraphNode, numDependenciesOut *uint) error

CaptureInfoV2 queries a stream’s capture state.

Query stream state related to stream capture. If called on CU_STREAM_LEGACY (the “null stream”) while a stream not created with StreamNonBlocking is capturing, returns ErrStreamCaptureImplicit. Valid data (other than capture status) is returned only if both of the following are true:

If edgeData_out is non-NULL then dependenciesOut must be as well. If dependenciesOut is non-NULL and edgeData_out is NULL, but there is non-zero edge data for one or more of the current stream dependencies, the call will return ErrLossyQuery.

See also: Stream.BeginCapture, Stream.IsCapturing, Stream.UpdateCaptureDependencies

  • captureStatusOut: Location to return the capture status of the stream; required
  • idOut: Optional location to return an id for the capture sequence, which is unique over the lifetime of the process
  • graphOut: 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 at Stream.EndCapture. 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 at Stream.EndCapture due to direct actions on the graph do not trigger ErrStreamCaptureUnjoined
  • dependenciesOut: 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 the capture is terminated. 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
  • numDependenciesOut: Optional location to store the size of the array returned in dependenciesOut

Errors:

Wraps cuStreamGetCaptureInfo_v2.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Stream) CaptureInfoV3

func (s Stream) CaptureInfoV3(captureStatusOut *StreamCaptureStatus, idOut *uint64, graphOut *Graph, dependenciesOut **GraphNode, edgeDataOut **GraphEdgeData, numDependenciesOut *uint) error

CaptureInfoV3 queries a stream’s capture state.

Query stream state related to stream capture. If called on CU_STREAM_LEGACY (the “null stream”) while a stream not created with StreamNonBlocking is capturing, returns ErrStreamCaptureImplicit. Valid data (other than capture status) is returned only if both of the following are true:

If edgeDataOut is non-NULL then dependenciesOut must be as well. If dependenciesOut is non-NULL and edgeDataOut is NULL, but there is non-zero edge data for one or more of the current stream dependencies, the call will return ErrLossyQuery.

See also: Stream.BeginCapture, Stream.IsCapturing, Stream.UpdateCaptureDependencies

Requires CUDA 12.3 (driver r545) or later; see HasStreamGetCaptureInfoV3.

  • captureStatusOut: Location to return the capture status of the stream; required
  • idOut: Optional location to return an id for the capture sequence, which is unique over the lifetime of the process
  • graphOut: 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 at Stream.EndCapture. 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 at Stream.EndCapture due to direct actions on the graph do not trigger ErrStreamCaptureUnjoined
  • dependenciesOut: 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 the capture is terminated. 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
  • edgeDataOut: Optional location to store a pointer to an array of graph edge data. This array parallels dependenciesOut; the next node to be added has an edge to dependencies_outi with annotation edgeData_outi for each i. The array pointer is valid until the next API call which operates on the stream or until the capture is terminated
  • numDependenciesOut: Optional location to store the size of the array returned in dependenciesOut

Errors:

Wraps cuStreamGetCaptureInfo, bound as cuStreamGetCaptureInfo_v3.

func (*Stream) Close

func (s *Stream) Close() error

Close destroys a stream.

Destroys the stream specified by hStream. In case the device is still doing work in the stream hStream when Stream.Close is called, the function will return immediately and the resources associated with hStream will be released automatically once the device has completed all work in hStream.

See also: NewStream, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamDestroy

Errors:

If s is zero, Close returns nil. Otherwise Close sets s to zero when the call succeeds and leaves it unchanged when it fails. Only s is zeroed: a copy of it still refers to the released object.

Wraps cuStreamDestroy, bound as cuStreamDestroy_v2.

func (Stream) CopyAttributes

func (s Stream) CopyAttributes(src Stream) error

CopyAttributes 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.

See also: AccessPolicyWindow

  • src: Source stream For list of attributes see CUstreamAttrID

Errors:

Wraps cuStreamCopyAttributes.

func (Stream) Ctx

func (s Stream) Ctx() (Context, error)

Ctx queries the context associated with a stream.

Returns the CUDA context that the stream is associated with. If the stream was created via the API GreenCtx.StreamCreate, the returned context is equivalent to the one returned by CtxFromGreenCtx on the green context associated with the stream at creation time. The stream handle hStream can refer to any of the following:

  • a stream created via any of the CUDA driver APIs such as NewStream and StreamCreateWithPriority, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. The returned context is the context that was active in the calling thread when the stream was created. Passing an invalid handle will result in undefined behavior.
  • any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. Specifying any of the special handles will return the context current to the calling thread. If no context is current to the calling thread, ErrInvalidContext is returned.

See also: Stream.Close, StreamCreateWithPriority, Stream.Priority, Stream.Flags, Stream.Device Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreate, cudaStreamCreateWithFlags

Errors:

Wraps cuStreamGetCtx.

func (Stream) CtxV1

func (s Stream) CtxV1() (Context, error)

CtxV1 queries the context associated with a stream.

Returns the CUDA context that the stream is associated with. If the stream was created via the API GreenCtx.StreamCreate, the returned context is equivalent to the one returned by CtxFromGreenCtx on the green context associated with the stream at creation time. The stream handle hStream can refer to any of the following:

  • a stream created via any of the CUDA driver APIs such as NewStream and StreamCreateWithPriority, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. The returned context is the context that was active in the calling thread when the stream was created. Passing an invalid handle will result in undefined behavior.
  • any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. Specifying any of the special handles will return the context current to the calling thread. If no context is current to the calling thread, ErrInvalidContext is returned.

See also: Stream.Close, StreamCreateWithPriority, Stream.Priority, Stream.Flags, Stream.Device Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreate, cudaStreamCreateWithFlags

Errors:

Wraps cuStreamGetCtx.

func (Stream) CtxV2

func (s Stream) CtxV2() (pCtx Context, pGreenCtx GreenCtx, err error)

CtxV2 queries the contexts associated with a stream.

Returns the contexts that the stream is associated with. If the stream is associated with a green context, the API returns the green context in pGreenCtx and the primary context of the associated device in pCtx. If the stream is associated with a regular context, the API returns the regular context in pCtx and NULL in pGreenCtx. The stream handle hStream can refer to any of the following:

  • a stream created via any of the CUDA driver APIs such as NewStream, StreamCreateWithPriority and GreenCtx.StreamCreate, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. Passing an invalid handle will result in undefined behavior.
  • any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively. If any of the special handles are specified, the API will operate on the context current to the calling thread. If a green context (that was converted via CtxFromGreenCtx before setting it current) is current to the calling thread, the API will return the green context in pGreenCtx and the primary context of the associated device in pCtx. If a regular context is current, the API returns the regular context in pCtx and NULL in pGreenCtx. Note that specifying CU_STREAM_PER_THREAD or cudaStreamPerThread will return ErrInvalidHandle if a green context is current to the calling thread. If no context is current to the calling thread, ErrInvalidContext is returned.

See also: Stream.Close, NewStream StreamCreateWithPriority, GreenCtx.StreamCreate, Stream.Priority, Stream.Flags, Stream.Device, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreate, cudaStreamCreateWithFlags

Requires CUDA 12.5 (driver r555) or later; see HasStreamGetCtxV2.

  • pCtx: Returned regular context associated with the stream
  • pGreenCtx: Returned green context if the stream is associated with a green context or NULL if not

Errors:

Wraps cuStreamGetCtx_v2.

func (Stream) DevResource

func (s Stream) DevResource(type_ DevResourceType) (DevResource, error)

DevResource gets stream resources.

Get the type resources available to the hStream and return them.

Note: The API will return ErrInvalidResourceType is type is DevResourceTypeWorkqueueConfig or DevResourceTypeWorkqueue.

See also: NewGreenCtx, GreenCtx.StreamCreate, NewStream, DevSmResourceSplitByCount, DevResourceGenerateDesc, cudaStreamGetDevResource

Requires CUDA 13.1 (driver r590) or later; see HasStreamGetDevResource.

  • type_: Type of resource to retrieve

Errors:

Wraps cuStreamGetDevResource.

func (Stream) Device

func (s Stream) Device() (Device, error)

Device returns the device handle of the stream.

Returns the device handle of the stream

See also: Stream.Close, NewStream, GreenCtx.StreamCreate, Stream.Flags

Requires CUDA 12.8 (driver r570) or later; see HasStreamGetDevice.

Errors:

Wraps cuStreamGetDevice.

func (Stream) EndCapture

func (s Stream) EndCapture() (Graph, error)

EndCapture ends capture on a stream, returning the captured graph.

End capture on hStream, returning the captured graph via phGraph. Capture must have been initiated on hStream via a call to Stream.BeginCapture. 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 Stream.BeginCapture was not StreamCaptureModeRelaxed, this call must be from the same thread as Stream.BeginCapture.

See also: NewStream, Stream.BeginCapture, Stream.IsCapturing, Graph.Destroy

Errors:

Wraps cuStreamEndCapture.

func (Stream) EndCaptureToCig

func (s Stream) EndCaptureToCig() error

EndCaptureToCig ends CIG capture on a stream.

End CIG capture on hStream. Capture must have been initiated on hStream via a call to Stream.BeginCaptureToCig. Once this function is called, hStream will exit CIG capture mode and return to its original state, thus removing all CIG stream restrictions. Also, the command list/command buffer that was associated with hStream in the previous call to Stream.BeginCaptureToCig is now allowed to be submitted for execution on the graphics API. However, the stream may not be destroyed until execution of the command list is fully done on the GPU. This requirements extends also to all streams dependant on the CIG stream (e.g. via event waits).

See also: Stream.BeginCaptureToCig

Requires CUDA 13.2 (driver r595) or later; see HasStreamEndCaptureToCig.

Errors:

Wraps cuStreamEndCaptureToCig.

func (Stream) FabricCpyBatchAsync

func (s Stream) FabricCpyBatchAsync(numOps uint, opList *FabricCopyBatchOp, flags uint64) error

FabricCpyBatchAsync performs a batch of copies over a fabric asynchronously.

The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. Specifying dependent copies within a single batch results in undefined behavior.

Performs copies as specified in the opList array. The length of this array is specified in numOps. Each entry describes a copy operation including source and destination operands (FabricCopyBatchOp.src and FabricCopyBatchOp.dst) and the size in bytes (FabricCopyBatchOp.size). A size of zero makes that operation a no-op while preserving its position in the batch. Its operands are still validated.

The following operand type combinations are supported:

Copy between two device-accessible pointers. At least one operand must be local to the stream's device.

-- copy from a local pointer to a remote UNICAST or MULTICAST logical endpoint at the specified offset.

-- copy from a remote UNICAST logical endpoint at the specified offset to a local pointer.

A single batch may contain a heterogeneous mix of operation types.

For a POINTER operand, FabricCpyOperand.op.ptr.ptr must contain the pointer where the copy begins. For managed memory or pageable memory on supported devices, FabricCpyOperand.op.ptr.locHint may hint the location of the operand.

For a LOGICAL_ENDPOINT operand, FabricCpyOperand.op.le.id specifies the logical endpoint and FabricCpyOperand.op.le.offset specifies the byte offset into that endpoint.

1. Source and destination are always accessed in stream order. So care must be taken to ensure that neither operand is deallocated before the copy has completed. In particular, if the source is ephemeral, e.g., a stack variable, then the stream must be synchronized before the variable goes out of scope. 2. For pointer-to-pointer copies, at least one operand must be local. For copies involving a pointer and a logical endpoint, the pointer must be local. Being "local" means it resides either on the stream's device, or in the host memory. 3. All operands must be accessible from the stream's device. 4. This API is only available on platforms that support logical endpoints. It returns ErrNotSupported on all other configurations.

Requires CUDA 13.5 (driver r620) or later; see HasFabricCpyBatchAsync.

  • numOps: Total number of copy operations
  • opList: Array of size numOps containing the copy operations
  • flags: Flags for future use, must be zero

See also: LogicalEndpointCreate, Device.LogicalEndpointBindAddr, Device.LogicalEndpointBindMem

Wraps cuFabricCpyBatchAsync.

func (Stream) Flags

func (s Stream) Flags() (uint32, error)

Flags queries the flags of a given stream.

Query the flags of a stream created using NewStream, StreamCreateWithPriority or GreenCtx.StreamCreate and return the flags.

See also: Stream.Close, NewStream, GreenCtx.StreamCreate, Stream.Priority, cudaStreamGetFlags, Stream.Device

Errors:

Wraps cuStreamGetFlags.

func (Stream) GraphicsMapResources

func (s Stream) GraphicsMapResources(count uint32, resources *GraphicsResource) error

GraphicsMapResources maps graphics resources for access by CUDA.

Maps the count graphics resources in resources for access by CUDA. The resources in resources may be accessed by CUDA until they are unmapped. The graphics API from which resources were registered should not access any resources while they are mapped by CUDA. If an application does so, the results are undefined. This function provides the synchronization guarantee that any graphics calls issued before Stream.GraphicsMapResources will complete before any subsequent CUDA work issued in stream begins. If resources includes any duplicate entries then ErrInvalidHandle is returned. If any of resources are presently mapped for access by CUDA then ErrAlreadyMapped is returned.

Note: This function uses standard default stream semantics.

See also: GraphicsResource.MappedPointer, GraphicsResource.SubResourceGetMappedArray, Stream.GraphicsUnmapResources, cudaGraphicsMapResources

  • count: Number of resources to map
  • resources: Resources to map for CUDA usage

Errors:

Wraps cuGraphicsMapResources.

func (Stream) GraphicsUnmapResources

func (s Stream) GraphicsUnmapResources(count uint32, resources *GraphicsResource) error

GraphicsUnmapResources unmaps graphics resources.

Unmaps the count graphics resources in resources. Once unmapped, the resources in resources may not be accessed by CUDA until they are mapped again. This function provides the synchronization guarantee that any CUDA work issued in stream before Stream.GraphicsUnmapResources will complete before any subsequently issued graphics work begins. If resources includes any duplicate entries then ErrInvalidHandle is returned. If any of resources are not presently mapped for access by CUDA then ErrNotMapped is returned.

Note: This function uses standard default stream semantics.

See also: Stream.GraphicsMapResources, cudaGraphicsUnmapResources

  • count: Number of resources to unmap
  • resources: Resources to unmap

Errors:

Wraps cuGraphicsUnmapResources.

func (Stream) GreenCtx

func (s Stream) GreenCtx() (GreenCtx, error)

GreenCtx queries the green context associated with a stream.

Returns the CUDA green context that the stream is associated with, or NULL if the stream is not associated with any green context. The stream handle hStream can refer to any of the following:

  • a stream created via any of the CUDA driver APIs such as NewStream, StreamCreateWithPriority and GreenCtx.StreamCreate, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. If during stream creation the context that was active in the calling thread was obtained with CtxFromGreenCtx, that green context is returned in phCtx. Otherwise, the result is NULL instead.
  • special stream such as the NULL stream or CU_STREAM_LEGACY. In that case if context that is active in the calling thread was obtained with CtxFromGreenCtx, that green context is returned. Otherwise, the result is NULL instead.

Passing an invalid handle will result in undefined behavior.

See also: Stream.Close, NewStream, StreamCreateWithPriority, Stream.Ctx, GreenCtx.StreamCreate, Stream.Priority, Stream.Flags, Stream.Device, Stream.WaitEvent, Stream.Query, Stream.Synchronize, Stream.AddCallback, cudaStreamCreate, cudaStreamCreateWithFlags

Requires CUDA 12.4 (driver r550) or later; see HasStreamGetGreenCtx.

Errors:

Wraps cuStreamGetGreenCtx.

func (Stream) Id

func (s Stream) Id() (uint64, error)

Id returns the unique Id associated with the stream handle supplied.

Returns the unique Id which is associated with the given stream handle. 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 driver APIs such as NewStream and StreamCreateWithPriority, or their runtime API equivalents such as cudaStreamCreate, cudaStreamCreateWithFlags and cudaStreamCreateWithPriority. Passing an invalid handle will result in undefined behavior.
  • any of the special streams such as the NULL stream, CU_STREAM_LEGACY and CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, which are NULL, cudaStreamLegacy and cudaStreamPerThread respectively.

See also: Stream.Close, NewStream, Stream.Priority, cudaStreamGetId

Errors:

Wraps cuStreamGetId.

func (Stream) IsCapturing

func (s Stream) IsCapturing() (StreamCaptureStatus, error)

IsCapturing returns a stream’s capture status.

Return the capture status of hStream via captureStatus. After a successful call, the result will contain one of the following:

Note that, if this is called on CU_STREAM_LEGACY (the “null stream”) while a blocking stream in the same context is capturing, it will return ErrStreamCaptureImplicit and the result 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).

See also: NewStream, Stream.BeginCapture, Stream.EndCapture

Errors:

Wraps cuStreamIsCapturing.

func (Stream) LaunchHostFunc

func (s Stream) LaunchHostFunc(fn uintptr, userData uintptr) error

LaunchHostFunc 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 ErrNotPermitted, 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 contrast to Stream.AddCallback, the function will not be called in the event of an error in the CUDA context.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Query, Stream.Synchronize, Stream.WaitEvent, Stream.Close, MemAllocManaged, Stream.AttachMemAsync, Stream.AddCallback

  • fn: The function to call once preceding stream operations are complete (see HostFn)
  • userData: User-specified data to be passed to the function

Errors:

Wraps cuLaunchHostFunc.

func (Stream) LaunchHostFuncV1

func (s Stream) LaunchHostFuncV1(fn uintptr, userData uintptr) error

LaunchHostFuncV1 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 ErrNotPermitted, 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 contrast to Stream.AddCallback, the function will not be called in the event of an error in the CUDA context.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Query, Stream.Synchronize, Stream.WaitEvent, Stream.Close, MemAllocManaged, Stream.AttachMemAsync, Stream.AddCallback

  • fn: The function to call once preceding stream operations are complete (see HostFn)
  • userData: User-specified data to be passed to the function

Errors:

Wraps cuLaunchHostFunc.

func (Stream) LaunchHostFuncV2

func (s Stream) LaunchHostFuncV2(fn uintptr, userData uintptr, syncMode uint32) error

LaunchHostFuncV2 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 ErrNotPermitted, 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 contrast to Stream.AddCallback, the function will not be called in the event of an error in the CUDA context.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Query, Stream.Synchronize, Stream.WaitEvent, Stream.Close, MemAllocManaged, Stream.AttachMemAsync, Stream.AddCallback

Requires CUDA 13.2 (driver r595) or later; see HasLaunchHostFuncV2.

  • fn: The function to call once preceding stream operations are complete (see HostFn)
  • userData: User-specified data to be passed to the function
  • syncMode: Synchronization mode for the host function

Errors:

Wraps cuLaunchHostFunc_v2.

func (Stream) MemAllocAsync

func (s Stream) MemAllocAsync[T any](n int) (DevicePtr, error)

MemAllocAsync allocates memory with stream ordered semantics.

Inserts an allocation operation into hStream. A pointer to the allocated memory is returned immediately. The allocation must not be accessed until the the allocation operation completes. The allocation comes from the memory pool current to the stream’s device.

Note: The default memory pool of a device contains device memory from that device.

Note: 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.

Note: 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.

See also: MemoryPool.MemAllocFromPoolAsync, DevicePtr.FreeAsync, Device.SetMemPool, Device.DefaultMemPool, Device.MemPool, NewMemoryPool, MemoryPool.SetAccess, MemoryPool.SetAttribute

Errors:

The allocation holds n values of type T: bytesize is n times the size of T. A negative n, or one whose size overflows uint, is an error. T must not contain Go pointers: the garbage collector does not scan device memory.

Wraps cuMemAllocAsync.

func (Stream) MemAllocAsyncBytes

func (s Stream) MemAllocAsyncBytes(bytesize uint) (DevicePtr, error)

MemAllocAsyncBytes is Stream.MemAllocAsync with the size given in bytes.

  • bytesize: Number of bytes to allocate

Wraps cuMemAllocAsync.

func (Stream) MemBatchDecompressAsync

func (s Stream) MemBatchDecompressAsync(paramsArray *MemDecompressParams, count uint, flags uint32) (uint, error)

MemBatchDecompressAsync submits a batch of count independent decompression operations.

Each of the count decompression operations is described by a single entry in the paramsArray array. Once the batch has been submitted, the function will return, and decompression will happen asynchronously w.r.t. the CPU. To the work completion tracking mechanisms in the CUDA driver, the batch will be considered a single unit of work and processed according to stream semantics, i.e., it is not possible to query the completion of individual decompression operations within a batch. The memory pointed to by each of MemDecompressParams.src, MemDecompressParams.dst, and MemDecompressParams.dstActBytes, must be capable of usage with the hardware decompress feature. That is, for each of said pointers, the pointer attribute PointerAttributeIsHwDecompressCapable should give a non-zero value. To ensure this, the memory backing the pointers should have been allocated using one of the following CUDA memory allocators:

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: MemAlloc, NewMemoryPool, MemoryPool.MemAllocFromPoolAsync

Requires CUDA 12.8 (driver r570) or later; see HasMemBatchDecompressAsync.

  • paramsArray: The array of structures describing the independent decompression operations
  • count: The number of entries in paramsArray array
  • flags: Must be 0

Errors:

Wraps cuMemBatchDecompressAsync.

func (Stream) MemDiscardAndPrefetchBatchAsync

func (s Stream) MemDiscardAndPrefetchBatchAsync(dptrs *DevicePtr, sizes *uint, count uint, prefetchLocs *MemLocation, prefetchLocIdxs *uint, numPrefetchLocs uint, flags uint64) error

MemDiscardAndPrefetchBatchAsync performs a batch of memory discards and prefetches asynchronously.

Performs a batch of memory discards followed by prefetches. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess otherwise the API will return an error. Calling Stream.MemDiscardAndPrefetchBatchAsync is semantically equivalent to calling Stream.MemDiscardBatchAsync followed by Stream.MemPrefetchBatchAsync, but is more optimal. For more details on what discarding and prefetching imply, please refer to Stream.MemDiscardBatchAsync and Stream.MemPrefetchBatchAsync respectively. Note that any reads, writes or prefetches to any part of the memory range that occur simultaneously with this combined discard+prefetch operation result in undefined behavior. Performs memory discard and prefetch on address ranges specified in dptrs and sizes. Both arrays must be of the same length as specified by count. Each memory range specified must refer to managed memory allocated via MemAllocManaged or declared via managed variables or it may also refer to system-allocated memory when all devices have a non-zero value for DevAttrPageableMemoryAccess. Every operation in the batch has to be associated with a valid location to prefetch the address range to and specified in the prefetchLocs array. Each entry in this array can apply to more than one operation. This can be done by specifying in the prefetchLocIdxs array, the index of the first operation that the corresponding entry in the prefetchLocs array applies to. Both prefetchLocs and prefetchLocIdxs must be of the same length as specified by numPrefetchLocs. For example, if a batch has 10 operations listed in dptrs/sizes, the first 6 of which are to be prefetched to one location and the remaining 4 are to be prefetched to another, then numPrefetchLocs will be 2, prefetchLocIdxs will be {0, 6} and prefetchLocs will contain the two set of locations. Note the first entry in prefetchLocIdxs must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than count. Furthermore, numPrefetchLocs must be lesser than or equal to count.

Requires CUDA 13.0 (driver r580) or later; see HasMemDiscardAndPrefetchBatchAsync.

  • dptrs: Array of pointers to be discarded
  • sizes: Array of sizes for memory discard operations
  • count: Size of dptrs and sizes arrays
  • prefetchLocs: Array of locations to prefetch to
  • prefetchLocIdxs: Array of indices to specify which operands each entry in the prefetchLocs array applies to. The locations specified in prefetchLocsk will be applied to operations starting from prefetchLocIdxsk through prefetchLocIdxs[k+1] - 1. Also prefetchLocs[numPrefetchLocs - 1] will apply to copies starting from prefetchLocIdxs[numPrefetchLocs - 1] through count - 1
  • numPrefetchLocs: Size of prefetchLocs and prefetchLocIdxs arrays
  • flags: Flags reserved for future use. Must be zero

Wraps cuMemDiscardAndPrefetchBatchAsync.

func (Stream) MemDiscardBatchAsync

func (s Stream) MemDiscardBatchAsync(dptrs *DevicePtr, sizes *uint, count uint, flags uint64) error

MemDiscardBatchAsync performs a batch of memory discards asynchronously.

Performs a batch of memory discards. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess otherwise the API will return an error. Discarding a memory range informs the driver that the contents of that range are no longer useful. Discarding memory ranges allows the driver to optimize certain data migrations and can also help reduce memory pressure. This operation can be undone on any part of the range by either writing to it or prefetching it via DevicePtr.MemPrefetchAsync or Stream.MemPrefetchBatchAsync. Reading from a discarded range, without a subsequent write or prefetch to that part of the range, will return an indeterminate value. Note that any reads, writes or prefetches to any part of the memory range that occur simultaneously with the discard operation result in undefined behavior. Performs memory discard on address ranges specified in dptrs and sizes. Both arrays must be of the same length as specified by count. Each memory range specified must refer to managed memory allocated via MemAllocManaged or declared via managed variables or it may also refer to system-allocated memory when all devices have a non-zero value for DevAttrPageableMemoryAccess.

Requires CUDA 13.0 (driver r580) or later; see HasMemDiscardBatchAsync.

  • dptrs: Array of pointers to be discarded
  • sizes: Array of sizes for memory discard operations
  • count: Size of dptrs and sizes arrays
  • flags: Flags reserved for future use. Must be zero

Wraps cuMemDiscardBatchAsync.

func (Stream) MemMapArrayAsync

func (s Stream) MemMapArrayAsync(mapInfoList *ArrayMapInfo, count uint32) error

MemMapArrayAsync maps or unmaps subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays.

Performs map or unmap operations on subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays. Each operation is specified by a ArrayMapInfo entry in the mapInfoList array of size count.

ArrayMapInfo.resourceType specifies the type of resource to be operated on. If ArrayMapInfo.resourceType is set to Resourcetype.ResourceTypeArray then ArrayMapInfo.resource.array must be set to a valid sparse CUDA array handle. The CUDA array must be either a 2D, 2D layered or 3D CUDA array and must have been allocated using NewArray or NewArray3D with the flag CUDA_ARRAY3D_SPARSE or CUDA_ARRAY3D_DEFERRED_MAPPING. For CUDA arrays obtained using MipmappedArray.Level, ErrInvalidValue will be returned. If ArrayMapInfo.resourceType is set to Resourcetype.ResourceTypeMipmappedArray then ArrayMapInfo.resource.mipmap must be set to a valid sparse CUDA mipmapped array handle. The CUDA mipmapped array must be either a 2D, 2D layered or 3D CUDA mipmapped array and must have been allocated using NewMipmappedArray with the flag CUDA_ARRAY3D_SPARSE or CUDA_ARRAY3D_DEFERRED_MAPPING. ArrayMapInfo.subresourceType specifies the type of subresource within the resource.

ArraySparseSubresourceType.ArraySparseSubresourceTypeSparseLevel indicates a sparse-miplevel which spans at least one tile in every dimension. The remaining miplevels which are too small to span at least one tile in any dimension constitute the mip tail region as indicated by ArraySparseSubresourceType.ArraySparseSubresourceTypeMiptail subresource type. If ArrayMapInfo.subresourceType is set to ArraySparseSubresourceType.ArraySparseSubresourceTypeSparseLevel then ArrayMapInfo.subresource.sparseLevel struct must contain valid array subregion offsets and extents. The ArrayMapInfo.subresource.sparseLevel.offsetX, ArrayMapInfo.subresource.sparseLevel.offsetY and ArrayMapInfo.subresource.sparseLevel.offsetZ must specify valid X, Y and Z offsets respectively. The ArrayMapInfo.subresource.sparseLevel.extentWidth, ArrayMapInfo.subresource.sparseLevel.extentHeight and ArrayMapInfo.subresource.sparseLevel.extentDepth must specify valid width, height and depth extents respectively. These offsets and extents must be aligned to the corresponding tile dimension. For CUDA mipmapped arrays ArrayMapInfo.subresource.sparseLevel.level must specify a valid mip level index. Otherwise, must be zero. For layered CUDA arrays and layered CUDA mipmapped arrays ArrayMapInfo.subresource.sparseLevel.layer must specify a valid layer index. Otherwise, must be zero. ArrayMapInfo.subresource.sparseLevel.offsetZ must be zero and ArrayMapInfo.subresource.sparseLevel.extentDepth must be set to 1 for 2D and 2D layered CUDA arrays and CUDA mipmapped arrays. Tile extents can be obtained by calling Array.SparseProperties and MipmappedArray.SparseProperties If ArrayMapInfo.subresourceType is set to ArraySparseSubresourceType.ArraySparseSubresourceTypeMiptail then ArrayMapInfo.subresource.miptail struct must contain valid mip tail offset in ArrayMapInfo.subresource.miptail.offset and size in ArrayMapInfo.subresource.miptail.size. Both, mip tail offset and mip tail size must be aligned to the tile size. For layered CUDA mipmapped arrays which don’t have the flag CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL set in ArraySparseProperties.flags as returned by MipmappedArray.SparseProperties, ArrayMapInfo.subresource.miptail.layer must specify a valid layer index. Otherwise, must be zero. If ArrayMapInfo.resource.array or ArrayMapInfo.resource.mipmap was created with CUDA_ARRAY3D_DEFERRED_MAPPING flag set the ArrayMapInfo.subresourceType and the contents of ArrayMapInfo.subresource will be ignored. ArrayMapInfo.memOperationType specifies the type of operation.

If ArrayMapInfo.memOperationType is set to MemOperationType.MemOperationTypeMap then the subresource will be mapped onto the tile pool memory specified by ArrayMapInfo.memHandle at offset ArrayMapInfo.offset. The tile pool allocation has to be created by specifying the CU_MEM_CREATE_USAGE_TILE_POOL flag when calling MemCreate. Also, ArrayMapInfo.memHandleType must be set to MemHandleType.MemHandleTypeGeneric. If ArrayMapInfo.memOperationType is set to MemOperationType.MemOperationTypeUnmap then an unmapping operation is performed. ArrayMapInfo.memHandle must be NULL. ArrayMapInfo.deviceBitMask specifies the list of devices that must map or unmap physical memory. Currently, this mask must have exactly one bit set, and the corresponding device must match the device associated with the stream. If ArrayMapInfo.memOperationType is set to MemOperationType.MemOperationTypeMap, the device must also match the device associated with the tile pool memory allocation as specified by ArrayMapInfo.memHandle. ArrayMapInfo.flags and ArrayMapInfo.reserved[] are unused and must be set to zero.

See also: NewMipmappedArray, NewArray, NewArray3D, MemCreate, Array.SparseProperties, MipmappedArray.SparseProperties

Errors:

Wraps cuMemMapArrayAsync.

func (Stream) MemPrefetchBatchAsync

func (s Stream) MemPrefetchBatchAsync(dptrs *DevicePtr, sizes *uint, count uint, prefetchLocs *MemLocation, prefetchLocIdxs *uint, numPrefetchLocs uint, flags uint64) error

MemPrefetchBatchAsync performs a batch of memory prefetches asynchronously.

Performs a batch of memory prefetches. The batch as a whole executes in stream order but operations within a batch are not guaranteed to execute in any specific order. All devices in the system must have a non-zero value for the device attribute DevAttrConcurrentManagedAccess otherwise the API will return an error. The semantics of the individual prefetch operations are as described in DevicePtr.MemPrefetchAsync. Performs memory prefetch on address ranges specified in dptrs and sizes. Both arrays must be of the same length as specified by count. Each memory range specified must refer to managed memory allocated via MemAllocManaged or declared via managed variables or it may also refer to system-allocated memory when all devices have a non-zero value for DevAttrPageableMemoryAccess. The prefetch location for every operation in the batch is specified in the prefetchLocs array. Each entry in this array can apply to more than one operation. This can be done by specifying in the prefetchLocIdxs array, the index of the first prefetch operation that the corresponding entry in the prefetchLocs array applies to. Both prefetchLocs and prefetchLocIdxs must be of the same length as specified by numPrefetchLocs. For example, if a batch has 10 prefetches listed in dptrs/sizes, the first 4 of which are to be prefetched to one location and the remaining 6 are to be prefetched to another, then numPrefetchLocs will be 2, prefetchLocIdxs will be {0, 4} and prefetchLocs will contain the two locations. Note the first entry in prefetchLocIdxs must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than count. Furthermore, numPrefetchLocs must be lesser than or equal to count.

Requires CUDA 13.0 (driver r580) or later; see HasMemPrefetchBatchAsync.

  • dptrs: Array of pointers to be prefetched
  • sizes: Array of sizes for memory prefetch operations
  • count: Size of dptrs and sizes arrays
  • prefetchLocs: Array of locations to prefetch to
  • prefetchLocIdxs: Array of indices to specify which operands each entry in the prefetchLocs array applies to. The locations specified in prefetchLocsk will be applied to copies starting from prefetchLocIdxsk through prefetchLocIdxs[k+1] - 1. Also prefetchLocs[numPrefetchLocs - 1] will apply to prefetches starting from prefetchLocIdxs[numPrefetchLocs - 1] through count - 1
  • numPrefetchLocs: Size of prefetchLocs and prefetchLocIdxs arrays
  • flags: Flags reserved for future use. Must be zero

Wraps cuMemPrefetchBatchAsync.

func (Stream) Memcpy2DAsync

func (s Stream) Memcpy2DAsync(pCopy *Memcpy2d) error

Memcpy2DAsync copies memory for 2D arrays.

Perform a 2D memory copy according to the parameters specified in pCopy.

  • srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively.
  • srcXInBytes and srcY specify the base address of the source data for the copy.

If srcMemoryType is MemoryTypeHost, srcHost and srcPitch specify the (host) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeUnified, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. If srcMemoryType is MemoryTypeDevice, srcDevice and srcPitch specify the (device) base address of the source data and the bytes per row to apply. srcArray is ignored. If srcMemoryType is MemoryTypeArray, srcArray specifies the handle of the source data. srcHost, srcDevice and srcPitch are ignored. If dstMemoryType is MemoryTypeUnified, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. If dstMemoryType is MemoryTypeHost, dstHost and dstPitch specify the (host) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeDevice, dstDevice and dstPitch specify the (device) base address of the destination data and the bytes per row to apply. dstArray is ignored. If dstMemoryType is MemoryTypeArray, dstArray specifies the handle of the destination data. dstHost, dstDevice and dstPitch are ignored.

  • dstXInBytes and dstY specify the base address of the destination data for the copy.

For host pointers, the starting address is

void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes);

For device pointers, the starting address is

CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes;

For CUDA arrays, srcXInBytes must be evenly divisible by the array element size.

  • WidthInBytes and Height specify the width (in bytes) and height of the 2D copy being performed.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.
  • If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height + dstY.

For host pointers, the base address is

void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes);

For device pointers, the starting address is

CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes;

For CUDA arrays, dstXInBytes must be evenly divisible by the array element size.

Stream.Memcpy2DAsync returns an error if any pitch is greater than the maximum allowed ( DevAttrMaxPitch). MemAllocPitch passes back pitches that always work with Memcpy2D. On intra-device memory copies (device to device, CUDA array to device, CUDA array to CUDA array), Stream.Memcpy2DAsync may fail for pitches not computed by MemAllocPitch.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Memcpy2DUnaligned, Memcpy3D, Stream.Memcpy3DAsync, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpy2DAsync, cudaMemcpy2DToArrayAsync, cudaMemcpy2DFromArrayAsync

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy2DAsync, bound as cuMemcpy2DAsync_v2.

func (Stream) Memcpy3DAsync

func (s Stream) Memcpy3DAsync(pCopy *Memcpy3d) error

Memcpy3DAsync copies memory for 3D arrays.

Perform a 3D memory copy according to the parameters specified in pCopy.

  • srcMemoryType and dstMemoryType specify the type of memory of the source and destination, respectively.
  • srcXInBytes, srcY and srcZ specify the base address of the source data for the copy.

If srcMemoryType is MemoryTypeUnified, srcDevice and srcPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. srcArray is ignored. This value may be used only if unified addressing is supported in the calling context. If srcMemoryType is MemoryTypeHost, srcHost, srcPitch and srcHeight specify the (host) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. If srcMemoryType is MemoryTypeDevice, srcDevice, srcPitch and srcHeight specify the (device) base address of the source data, the bytes per row, and the height of each 2D slice of the 3D array. srcArray is ignored. If srcMemoryType is MemoryTypeArray, srcArray specifies the handle of the source data. srcHost, srcDevice, srcPitch and srcHeight are ignored. If dstMemoryType is MemoryTypeUnified, dstDevice and dstPitch specify the (unified virtual address space) base address of the source data and the bytes per row to apply. dstArray is ignored. This value may be used only if unified addressing is supported in the calling context. If dstMemoryType is MemoryTypeHost, dstHost and dstPitch specify the (host) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. If dstMemoryType is MemoryTypeDevice, dstDevice and dstPitch specify the (device) base address of the destination data, the bytes per row, and the height of each 2D slice of the 3D array. dstArray is ignored. If dstMemoryType is MemoryTypeArray, dstArray specifies the handle of the destination data. dstHost, dstDevice, dstPitch and dstHeight are ignored.

  • dstXInBytes, dstY and dstZ specify the base address of the destination data for the copy.

For host pointers, the starting address is

void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes);

For device pointers, the starting address is

CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes;

For CUDA arrays, srcXInBytes must be evenly divisible by the array element size.

  • WidthInBytes, Height and Depth specify the width (in bytes), height and depth of the 3D copy being performed.
  • If specified, srcPitch must be greater than or equal to WidthInBytes + srcXInBytes, and dstPitch must be greater than or equal to WidthInBytes + dstXInBytes.
  • If specified, srcHeight must be greater than or equal to Height + srcY, and dstHeight must be greater than or equal to Height + dstY.

For host pointers, the base address is

void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes);

For device pointers, the starting address is

CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes;

For CUDA arrays, dstXInBytes must be evenly divisible by the array element size. The srcLOD and dstLOD members of the Memcpy3d structure must be set to 0. Stream.Memcpy3DAsync returns an error if any pitch is greater than the maximum allowed ( DevAttrMaxPitch).

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: NewArray3D, Array.Get3DDescriptor, NewArray, Array.Close, Array.Descriptor, MemAlloc, MemAllocHost, MemAllocPitch, Memcpy2D, Stream.Memcpy2DAsync, Memcpy2DUnaligned, Memcpy3D, Array.CopyFromArray, DevicePtr.CopyFromArray, Array.CopyToHost, Array.CopyToHostAsync, Array.CopyFromDevice, DevicePtr.CopyFromDevice, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyToHost, DevicePtr.CopyToHostAsync, Array.CopyFromHost, Array.CopyFromHostAsync, DevicePtr.CopyFromHost, DevicePtr.CopyFromHostAsync, DevicePtr.Free, MemFreeHost, DevicePtr.MemGetAddressRange, MemGetInfo, MemHostAlloc, MemHostGetDevicePointer, DevicePtr.MemsetD2D8, DevicePtr.MemsetD2D8Async, DevicePtr.MemsetD2D16, DevicePtr.MemsetD2D16Async, DevicePtr.MemsetD2D32, DevicePtr.MemsetD2D32Async, DevicePtr.MemsetD8, DevicePtr.MemsetD8Async, DevicePtr.MemsetD16, DevicePtr.MemsetD16Async, DevicePtr.MemsetD32, DevicePtr.MemsetD32Async, cudaMemcpy3DAsync

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy3DAsync, bound as cuMemcpy3DAsync_v2.

func (Stream) Memcpy3DBatchAsync

func (s Stream) Memcpy3DBatchAsync(numOps uint, opList *Memcpy3dBatchOp, flags uint64) error

Memcpy3DBatchAsync performs a batch of 3D memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. Note that this means specifying any dependent copies within a batch will result in undefined behavior. Performs memory copies as specified in the opList array. The length of this array is specified in numOps. Each entry in this array describes a copy operation. This includes among other things, the source and destination operands for the copy as specified in Memcpy3dBatchOp.src and Memcpy3dBatchOp.dst respectively. The source and destination operands of a copy can either be a pointer or a CUDA array. The width, height and depth of a copy is specified in Memcpy3dBatchOp.extent. The width, height and depth of a copy are specified in elements and must not be zero. For pointer-to-pointer copies, the element size is considered to be 1. For pointer to CUDA array or vice versa copies, the element size is determined by the CUDA array. For CUDA array to CUDA array copies, the element size of the two CUDA arrays must match. For a given operand, if Memcpy3DOperand.type is specified as MemcpyOperandTypePointer, then Memcpy3DOperand.op.ptr will be used. The Memcpy3DOperand.op.ptr.ptr field must contain the pointer where the copy should begin. The Memcpy3DOperand.op.ptr.rowLength field specifies the length of each row in elements and must either be zero or be greater than or equal to the width of the copy specified in Memcpy3dBatchOp.extent.width. The Memcpy3DOperand.op.ptr.layerHeight field specifies the height of each layer and must either be zero or be greater than or equal to the height of the copy specified in Memcpy3dBatchOp.extent.height. When either of these values is zero, that aspect of the operand is considered to be tightly packed according to the copy extent. For managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true, the Memcpy3DOperand.op.ptr.locHint field can be used to hint the location of the operand. If an operand’s type is specified as MemcpyOperandTypeArray, then Memcpy3DOperand.op.array will be used. The Memcpy3DOperand.op.array.array field specifies the CUDA array and Memcpy3DOperand.op.array.offset specifies the 3D offset into that array where the copy begins. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcopy operation in opList must have a valid srcAccessOrder setting, otherwise this API will return ErrInvalidValue. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 12.8 (driver r570) or later; see HasMemcpy3DBatchAsync.

  • numOps: Total number of memcpy operations
  • opList: Array of size numOps containing the actual memcpy operations
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMemcpy3DBatchAsync, bound to the first of cuMemcpy3DBatchAsync_v2, cuMemcpy3DBatchAsync that the library exports. On libraries without cuMemcpy3DBatchAsync_v2, it calls cuMemcpy3DBatchAsync, discarding its failIdx.

func (Stream) Memcpy3DBatchAsyncV1 deprecated

func (s Stream) Memcpy3DBatchAsyncV1(numOps uint, opList *Memcpy3dBatchOp, flags uint64) (uint, error)

Memcpy3DBatchAsyncV1 performs a batch of 3D memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. Note that this means specifying any dependent copies within a batch will result in undefined behavior. Performs memory copies as specified in the opList array. The length of this array is specified in numOps. Each entry in this array describes a copy operation. This includes among other things, the source and destination operands for the copy as specified in Memcpy3dBatchOp.src and Memcpy3dBatchOp.dst respectively. The source and destination operands of a copy can either be a pointer or a CUDA array. The width, height and depth of a copy is specified in Memcpy3dBatchOp.extent. The width, height and depth of a copy are specified in elements and must not be zero. For pointer-to-pointer copies, the element size is considered to be 1. For pointer to CUDA array or vice versa copies, the element size is determined by the CUDA array. For CUDA array to CUDA array copies, the element size of the two CUDA arrays must match. For a given operand, if Memcpy3DOperand.type is specified as MemcpyOperandTypePointer, then Memcpy3DOperand.op.ptr will be used. The Memcpy3DOperand.op.ptr.ptr field must contain the pointer where the copy should begin. The Memcpy3DOperand.op.ptr.rowLength field specifies the length of each row in elements and must either be zero or be greater than or equal to the width of the copy specified in Memcpy3dBatchOp.extent.width. The Memcpy3DOperand.op.ptr.layerHeight field specifies the height of each layer and must either be zero or be greater than or equal to the height of the copy specified in Memcpy3dBatchOp.extent.height. When either of these values is zero, that aspect of the operand is considered to be tightly packed according to the copy extent. For managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true, the Memcpy3DOperand.op.ptr.locHint field can be used to hint the location of the operand. If an operand’s type is specified as MemcpyOperandTypeArray, then Memcpy3DOperand.op.array will be used. The Memcpy3DOperand.op.array.array field specifies the CUDA array and Memcpy3DOperand.op.array.offset specifies the 3D offset into that array where the copy begins. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcopy operation in opList must have a valid srcAccessOrder setting, otherwise this API will return ErrInvalidValue. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 12.8 (driver r570) or later; see HasMemcpy3DBatchAsyncV1.

  • numOps: Total number of memcpy operations
  • opList: Array of size numOps containing the actual memcpy operations
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMemcpy3DBatchAsync_v1, bound as cuMemcpy3DBatchAsync.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Stream) Memcpy3DBatchAsyncV2

func (s Stream) Memcpy3DBatchAsyncV2(numOps uint, opList *Memcpy3dBatchOp, flags uint64) error

Memcpy3DBatchAsyncV2 performs a batch of 3D memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. Note that this means specifying any dependent copies within a batch will result in undefined behavior. Performs memory copies as specified in the opList array. The length of this array is specified in numOps. Each entry in this array describes a copy operation. This includes among other things, the source and destination operands for the copy as specified in Memcpy3dBatchOp.src and Memcpy3dBatchOp.dst respectively. The source and destination operands of a copy can either be a pointer or a CUDA array. The width, height and depth of a copy is specified in Memcpy3dBatchOp.extent. The width, height and depth of a copy are specified in elements and must not be zero. For pointer-to-pointer copies, the element size is considered to be 1. For pointer to CUDA array or vice versa copies, the element size is determined by the CUDA array. For CUDA array to CUDA array copies, the element size of the two CUDA arrays must match. For a given operand, if Memcpy3DOperand.type is specified as MemcpyOperandTypePointer, then Memcpy3DOperand.op.ptr will be used. The Memcpy3DOperand.op.ptr.ptr field must contain the pointer where the copy should begin. The Memcpy3DOperand.op.ptr.rowLength field specifies the length of each row in elements and must either be zero or be greater than or equal to the width of the copy specified in Memcpy3dBatchOp.extent.width. The Memcpy3DOperand.op.ptr.layerHeight field specifies the height of each layer and must either be zero or be greater than or equal to the height of the copy specified in Memcpy3dBatchOp.extent.height. When either of these values is zero, that aspect of the operand is considered to be tightly packed according to the copy extent. For managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true, the Memcpy3DOperand.op.ptr.locHint field can be used to hint the location of the operand. If an operand’s type is specified as MemcpyOperandTypeArray, then Memcpy3DOperand.op.array will be used. The Memcpy3DOperand.op.array.array field specifies the CUDA array and Memcpy3DOperand.op.array.offset specifies the 3D offset into that array where the copy begins. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcopy operation in opList must have a valid srcAccessOrder setting, otherwise this API will return ErrInvalidValue. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 13.0 (driver r580) or later; see HasMemcpy3DBatchAsyncV2.

  • numOps: Total number of memcpy operations
  • opList: Array of size numOps containing the actual memcpy operations
  • flags: Flags for future use, must be zero now

Errors:

Wraps cuMemcpy3DBatchAsync, bound as cuMemcpy3DBatchAsync_v2.

func (Stream) Memcpy3DPeerAsync

func (s Stream) Memcpy3DPeerAsync(pCopy *Memcpy3dPeer) error

Memcpy3DPeerAsync copies memory between contexts asynchronously.

Perform a 3D memory copy according to the parameters specified in pCopy. See the definition of the Memcpy3dPeer structure for documentation of its parameters.

Note: This function exhibits asynchronous behavior for most use cases.

Note: This function uses standard default stream semantics.

See also: DevicePtr.CopyFromDevice, DevicePtr.CopyFromPeer, DevicePtr.CopyFromDeviceAsync, DevicePtr.CopyFromPeerAsync, Stream.Memcpy3DPeerAsync, cudaMemcpy3DPeerAsync

  • pCopy: Parameters for the memory copy

Errors:

Wraps cuMemcpy3DPeerAsync.

func (Stream) Memcpy3DWithAttributesAsync

func (s Stream) Memcpy3DWithAttributesAsync(op *Memcpy3dBatchOp, flags uint64) error

Memcpy3DWithAttributesAsync performs 3D memory copy with attributes asynchronously.

Performs the copy operation specified in op. flags specifies the flags for the copy and hStream specifies the stream to enqueue the operation in. For more information regarding the operation, please refer to Memcpy3dBatchOp and it’s usage desciption in Stream.Memcpy3DBatchAsync

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

See also: Stream.Memcpy3DBatchAsync

Requires CUDA 13.2 (driver r595) or later; see HasMemcpy3DWithAttributesAsync.

  • op: Operation to perform
  • flags: Flags for the copy, must be zero now

Errors:

Wraps cuMemcpy3DWithAttributesAsync.

func (Stream) MemcpyBatchAsync

func (s Stream) MemcpyBatchAsync(dsts *DevicePtr, srcs *DevicePtr, sizes *uint, count uint, attrs *MemcpyAttributes, attrsIdxs *uint, numAttrs uint) error

MemcpyBatchAsync performs a batch of memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. This API only supports pointer-to-pointer copies. For copies involving CUDA arrays, please see Stream.Memcpy3DBatchAsync. Performs memory copies from source buffers specified in srcs to destination buffers specified in dsts. The size of each copy is specified in sizes. All three arrays must be of the same length as specified by count. Since there are no ordering guarantees for copies within a batch, specifying any dependent copies within a batch will result in undefined behavior. Every copy in the batch has to be associated with a set of attributes specified in the attrs array. Each entry in this array can apply to more than one copy. This can be done by specifying in the attrsIdxs array, the index of the first copy that the corresponding entry in the attrs array applies to. Both attrs and attrsIdxs must be of the same length as specified by numAttrs. For example, if a batch has 10 copies listed in dst/src/sizes, the first 6 of which have one set of attributes and the remaining 4 another, then numAttrs will be 2, attrsIdxs will be {0, 6} and attrs will contains the two sets of attributes. Note that the first entry in attrsIdxs must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than count. Furthermore, numAttrs must be lesser than or equal to count. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcpy operation in the batch must have a valid MemcpyAttributes corresponding to it including the appropriate srcAccessOrder setting, otherwise the API will return ErrInvalidValue. The MemcpyAttributes.srcLocHint and MemcpyAttributes.dstLocHint allows applications to specify hint locations for operands of a copy when the operand doesn’t have a fixed location. That is, these hints are only applicable for managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true. For other cases, these hints are ignored. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 12.8 (driver r570) or later; see HasMemcpyBatchAsync.

  • dsts: Array of destination pointers
  • srcs: Array of memcpy source pointers
  • sizes: Array of sizes for memcpy operations
  • count: Size of dsts, srcs and sizes arrays
  • attrs: Array of memcpy attributes
  • attrsIdxs: Array of indices to specify which copies each entry in the attrs array applies to. The attributes specified in attrsk will be applied to copies starting from attrsIdxsk through attrsIdxs[k+1] - 1. Also attrs[numAttrs-1] will apply to copies starting from attrsIdxs[numAttrs-1] through count - 1
  • numAttrs: Size of attrs and attrsIdxs arrays

Errors:

Wraps cuMemcpyBatchAsync, bound to the first of cuMemcpyBatchAsync_v2, cuMemcpyBatchAsync that the library exports. On libraries without cuMemcpyBatchAsync_v2, it calls cuMemcpyBatchAsync, discarding its failIdx.

func (Stream) MemcpyBatchAsyncV1 deprecated

func (s Stream) MemcpyBatchAsyncV1(dsts *DevicePtr, srcs *DevicePtr, sizes *uint, count uint, attrs *MemcpyAttributes, attrsIdxs *uint, numAttrs uint, failIdx *uint) error

MemcpyBatchAsyncV1 performs a batch of memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. This API only supports pointer-to-pointer copies. For copies involving CUDA arrays, please see Stream.Memcpy3DBatchAsync. Performs memory copies from source buffers specified in srcs to destination buffers specified in dsts. The size of each copy is specified in sizes. All three arrays must be of the same length as specified by count. Since there are no ordering guarantees for copies within a batch, specifying any dependent copies within a batch will result in undefined behavior. Every copy in the batch has to be associated with a set of attributes specified in the attrs array. Each entry in this array can apply to more than one copy. This can be done by specifying in the attrsIdxs array, the index of the first copy that the corresponding entry in the attrs array applies to. Both attrs and attrsIdxs must be of the same length as specified by numAttrs. For example, if a batch has 10 copies listed in dst/src/sizes, the first 6 of which have one set of attributes and the remaining 4 another, then numAttrs will be 2, attrsIdxs will be {0, 6} and attrs will contains the two sets of attributes. Note that the first entry in attrsIdxs must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than count. Furthermore, numAttrs must be lesser than or equal to count. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcpy operation in the batch must have a valid MemcpyAttributes corresponding to it including the appropriate srcAccessOrder setting, otherwise the API will return ErrInvalidValue. The MemcpyAttributes.srcLocHint and MemcpyAttributes.dstLocHint allows applications to specify hint locations for operands of a copy when the operand doesn’t have a fixed location. That is, these hints are only applicable for managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true. For other cases, these hints are ignored. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 12.8 (driver r570) or later; see HasMemcpyBatchAsyncV1.

  • dsts: Array of destination pointers
  • srcs: Array of memcpy source pointers
  • sizes: Array of sizes for memcpy operations
  • count: Size of dsts, srcs and sizes arrays
  • attrs: Array of memcpy attributes
  • attrsIdxs: Array of indices to specify which copies each entry in the attrs array applies to. The attributes specified in attrsk will be applied to copies starting from attrsIdxsk through attrsIdxs[k+1] - 1. Also attrs[numAttrs-1] will apply to copies starting from attrsIdxs[numAttrs-1] through count - 1
  • numAttrs: Size of attrs and attrsIdxs arrays
  • failIdx: Pointer to a location to return the index of the copy where a failure was encountered. The value will be SIZE_MAX if the error doesn't pertain to any specific copy

Errors:

Wraps cuMemcpyBatchAsync_v1, bound as cuMemcpyBatchAsync.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Stream) MemcpyBatchAsyncV2

func (s Stream) MemcpyBatchAsyncV2(dsts *DevicePtr, srcs *DevicePtr, sizes *uint, count uint, attrs *MemcpyAttributes, attrsIdxs *uint, numAttrs uint) error

MemcpyBatchAsyncV2 performs a batch of memory copies asynchronously.

Performs a batch of memory copies. The batch as a whole executes in stream order but copies within a batch are not guaranteed to execute in any specific order. This API only supports pointer-to-pointer copies. For copies involving CUDA arrays, please see Stream.Memcpy3DBatchAsync. Performs memory copies from source buffers specified in srcs to destination buffers specified in dsts. The size of each copy is specified in sizes. All three arrays must be of the same length as specified by count. Since there are no ordering guarantees for copies within a batch, specifying any dependent copies within a batch will result in undefined behavior. Every copy in the batch has to be associated with a set of attributes specified in the attrs array. Each entry in this array can apply to more than one copy. This can be done by specifying in the attrsIdxs array, the index of the first copy that the corresponding entry in the attrs array applies to. Both attrs and attrsIdxs must be of the same length as specified by numAttrs. For example, if a batch has 10 copies listed in dst/src/sizes, the first 6 of which have one set of attributes and the remaining 4 another, then numAttrs will be 2, attrsIdxs will be {0, 6} and attrs will contains the two sets of attributes. Note that the first entry in attrsIdxs must always be 0. Also, each entry must be greater than the previous entry and the last entry should be less than count. Furthermore, numAttrs must be lesser than or equal to count. The MemcpyAttributes.srcAccessOrder indicates the source access ordering to be observed for copies associated with the attribute. If the source access order is set to MemcpySrcAccessOrderStream, then the source will be accessed in stream order. If the source access order is set to MemcpySrcAccessOrderDuringApiCall then it indicates that access to the source pointer can be out of stream order and all accesses must be complete before the API call returns. This flag is suited for ephemeral sources (ex., stack variables) when it’s known that no prior operations in the stream can be accessing the memory and also that the lifetime of the memory is limited to the scope that the source variable was declared in. Specifying this flag allows the driver to optimize the copy and removes the need for the user to synchronize the stream after the API call. If the source access order is set to MemcpySrcAccessOrderAny then it indicates that access to the source pointer can be out of stream order and the accesses can happen even after the API call returns. This flag is suited for host pointers allocated outside CUDA (ex., via malloc) when it’s known that no prior operations in the stream can be accessing the memory. Specifying this flag allows the driver to optimize the copy on certain platforms. Each memcpy operation in the batch must have a valid MemcpyAttributes corresponding to it including the appropriate srcAccessOrder setting, otherwise the API will return ErrInvalidValue. The MemcpyAttributes.srcLocHint and MemcpyAttributes.dstLocHint allows applications to specify hint locations for operands of a copy when the operand doesn’t have a fixed location. That is, these hints are only applicable for managed memory pointers on devices where DevAttrConcurrentManagedAccess is true or system-allocated pageable memory on devices where DevAttrPageableMemoryAccess is true. For other cases, these hints are ignored. The MemcpyAttributes.flags field can be used to specify certain flags for copies. Setting the MemcpyFlagPreferOverlapWithCompute flag indicates that the associated copies should preferably overlap with any compute work. Note that this flag is a hint and can be ignored depending on the platform and other parameters of the copy.

Note: This function exhibits asynchronous behavior for most use cases.

Note: Memory regions requested must be either entirely registered with CUDA, or in the case of host pageable transfers, not registered at all. Memory regions spanning over allocations that are both registered and not registered with CUDA are not supported and will return ErrInvalidValue.

Requires CUDA 13.0 (driver r580) or later; see HasMemcpyBatchAsyncV2.

  • dsts: Array of destination pointers
  • srcs: Array of memcpy source pointers
  • sizes: Array of sizes for memcpy operations
  • count: Size of dsts, srcs and sizes arrays
  • attrs: Array of memcpy attributes
  • attrsIdxs: Array of indices to specify which copies each entry in the attrs array applies to. The attributes specified in attrsk will be applied to copies starting from attrsIdxsk through attrsIdxs[k+1] - 1. Also attrs[numAttrs-1] will apply to copies starting from attrsIdxs[numAttrs-1] through count - 1
  • numAttrs: Size of attrs and attrsIdxs arrays

Errors:

Wraps cuMemcpyBatchAsync, bound as cuMemcpyBatchAsync_v2.

func (Stream) Priority

func (s Stream) Priority() (int32, error)

Priority queries the priority of a given stream.

Query the priority of a stream created using NewStream, StreamCreateWithPriority or GreenCtx.StreamCreate and return the priority. Note that if the stream was created with a priority outside the numerical range returned by CtxGetStreamPriorityRange, this function returns the clamped priority. See StreamCreateWithPriority for details about priority clamping.

See also: Stream.Close, NewStream, StreamCreateWithPriority, GreenCtx.StreamCreate, CtxGetStreamPriorityRange, Stream.Flags, Stream.Device, cudaStreamGetPriority

Errors:

Wraps cuStreamGetPriority.

func (Stream) Query

func (s Stream) Query() error

Query determines status of a compute stream.

Returns Success if all operations in the stream specified by hStream have completed, or ErrNotReady if not. For the purposes of Unified Memory, a return value of Success is equivalent to having called Stream.Synchronize.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.WaitEvent, Stream.Close, Stream.Synchronize, Stream.AddCallback, cudaStreamQuery

Errors:

Wraps cuStreamQuery.

func (Stream) SetAttribute

func (s Stream) SetAttribute(attr int32, value *[8]uint64) error

SetAttribute 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.

See also: AccessPolicyWindow

Errors:

Wraps cuStreamSetAttribute.

func (Stream) SignalExternalSemaphoresAsync

func (s Stream) SignalExternalSemaphoresAsync(extSemArray *ExternalSemaphore, paramsArray *ExternalSemaphoreSignalParams, numExtSems uint32) error

SignalExternalSemaphoresAsync 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: ExternalSemaphoreHandleTypeOpaqueFd, ExternalSemaphoreHandleTypeOpaqueWin32, ExternalSemaphoreHandleTypeOpaqueWin32Kmt then signaling the semaphore will set it to the signaled state. If the semaphore object is any one of the following types: ExternalSemaphoreHandleTypeD3d12Fence, ExternalSemaphoreHandleTypeD3d11Fence, ExternalSemaphoreHandleTypeTimelineSemaphoreFd, ExternalSemaphoreHandleTypeTimelineSemaphoreWin32 then the semaphore will be set to the value specified in ExternalSemaphoreSignalParams.params.fence.value. If the semaphore object is of the type ExternalSemaphoreHandleTypeNvscisync this API sets ExternalSemaphoreSignalParams.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 of ExternalSemaphoreSignalParams.params.nvSciSync.fence. By default, signaling such an external semaphore object causes appropriate memory synchronization operations to be performed over all external memory objects that are imported as ExternalMemoryHandleTypeNvscibuf. 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 flag CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC, 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 type ExternalSemaphoreHandleTypeNvscisync, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in Device.NvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_SIGNAL, this API will return ErrNotSupported. NvSciSyncFence associated with semaphore object of the type ExternalSemaphoreHandleTypeNvscisync 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. NvSciSyncFence associated with semaphore object of the type ExternalSemaphoreHandleTypeNvscisync can be timestamp enabled. For this the NvSciSyncAttrList used to create the object must have the value of NvSciSyncAttrKey_WaiterRequireTimestamps key set to true. Timestamps are emitted asynchronously by the GPU and CUDA saves the GPU timestamp in the corresponding NvSciSyncFence at the time of signal on GPU. Users are expected to convert GPU clocks to CPU clocks using appropriate scaling functions. Users are expected to wait for the completion of the fence before extracting timestamp using appropriate NvSciSync APIs. Users are expected to ensure that there is only one outstanding timestamp enabled fence per Cuda-NvSciSync object at any point of time, failing which leads to undefined behavior. Extracting the timestamp before the corresponding fence is signalled could lead to undefined behaviour. Timestamp extracted via appropriate NvSciSync API would be in microseconds. If the semaphore object is any one of the following types: ExternalSemaphoreHandleTypeD3d11KeyedMutex, ExternalSemaphoreHandleTypeD3d11KeyedMutexKmt then the keyed mutex will be released with the key specified in CUDA_EXTERNAL_SEMAPHORE_PARAMS.params.keyedmutex.key.

See also: ImportExternalSemaphore, ExternalSemaphore.Close, Stream.WaitExternalSemaphoresAsync

  • extSemArray: Set of external semaphores to be signaled
  • paramsArray: Array of semaphore parameters
  • numExtSems: Number of semaphores to signal

Errors:

Wraps cuSignalExternalSemaphoresAsync.

func (Stream) Synchronize

func (s Stream) Synchronize() error

Synchronize waits until a stream’s tasks are completed.

Waits until the device has completed all operations in the stream specified by hStream. If the context was created with the CtxSchedBlockingSync flag, the CPU thread will block until the stream is finished with all of its tasks.

Note: This function uses standard default stream semantics.

See also: NewStream, Stream.Close, Stream.WaitEvent, Stream.Query, Stream.AddCallback, cudaStreamSynchronize

Errors:

Wraps cuStreamSynchronize.

func (Stream) UpdateCaptureDependencies

func (s Stream) UpdateCaptureDependencies(dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, flags StreamupdatecapturedependenciesFlags) error

UpdateCaptureDependencies updates the set of dependencies in a capturing stream.

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 along with the edge data for those dependencies. Valid flags are StreamAddCaptureDependencies and StreamSetCaptureDependencies. These control whether the set passed to the API is added to the existing set or replaces it. A flags value of 0 defaults to StreamAddCaptureDependencies. Nodes that are removed from the dependency set via this API do not result in ErrStreamCaptureUnjoined if they are unreachable from the stream at Stream.EndCapture. Returns ErrIllegalState if the stream is not capturing.

See also: Stream.BeginCapture, Stream.CaptureInfo

  • dependencies: The set of dependencies to add
  • dependencyData: Optional array of data associated with each dependency
  • numDependencies: The size of the dependencies array
  • flags: See above

Errors:

Wraps cuStreamUpdateCaptureDependencies, bound to the first of cuStreamUpdateCaptureDependencies_v2, cuStreamUpdateCaptureDependencies that the library exports. On libraries without cuStreamUpdateCaptureDependencies_v2, it calls cuStreamUpdateCaptureDependencies; a non-nil dependencyData returns ErrNotSupported.

func (Stream) UpdateCaptureDependenciesV1 deprecated

func (s Stream) UpdateCaptureDependenciesV1(dependencies *GraphNode, numDependencies uint, flags StreamupdatecapturedependenciesFlags) error

UpdateCaptureDependenciesV1 updates the set of dependencies in a capturing stream.

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 along with the edge data for those dependencies. Valid flags are StreamAddCaptureDependencies and StreamSetCaptureDependencies. These control whether the set passed to the API is added to the existing set or replaces it. A flags value of 0 defaults to StreamAddCaptureDependencies. Nodes that are removed from the dependency set via this API do not result in ErrStreamCaptureUnjoined if they are unreachable from the stream at Stream.EndCapture. Returns ErrIllegalState if the stream is not capturing.

See also: Stream.BeginCapture, Stream.CaptureInfo

  • dependencies: The set of dependencies to add
  • numDependencies: The size of the dependencies array
  • flags: See above

Errors:

Wraps cuStreamUpdateCaptureDependencies_v1, bound as cuStreamUpdateCaptureDependencies.

Deprecated: NVIDIA removed this function in CUDA 13.0.

func (Stream) UpdateCaptureDependenciesV2

func (s Stream) UpdateCaptureDependenciesV2(dependencies *GraphNode, dependencyData *GraphEdgeData, numDependencies uint, flags StreamupdatecapturedependenciesFlags) error

UpdateCaptureDependenciesV2 updates the set of dependencies in a capturing stream.

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 along with the edge data for those dependencies. Valid flags are StreamAddCaptureDependencies and StreamSetCaptureDependencies. These control whether the set passed to the API is added to the existing set or replaces it. A flags value of 0 defaults to StreamAddCaptureDependencies. Nodes that are removed from the dependency set via this API do not result in ErrStreamCaptureUnjoined if they are unreachable from the stream at Stream.EndCapture. Returns ErrIllegalState if the stream is not capturing.

See also: Stream.BeginCapture, Stream.CaptureInfo

Requires CUDA 12.3 (driver r545) or later; see HasStreamUpdateCaptureDependenciesV2.

  • dependencies: The set of dependencies to add
  • dependencyData: Optional array of data associated with each dependency
  • numDependencies: The size of the dependencies array
  • flags: See above

Errors:

Wraps cuStreamUpdateCaptureDependencies, bound as cuStreamUpdateCaptureDependencies_v2.

func (Stream) WaitEvent

func (s Stream) WaitEvent(hEvent Event, flags EventWaitFlags) error

WaitEvent makes a compute stream wait on an event.

Makes all future work submitted to hStream wait for all work captured in hEvent. See Event.Record for details on what is captured by an event. The synchronization will be performed efficiently on the device when applicable. hEvent may be from a different context or device than hStream. flags include:

  • EventWaitDefault: Default event creation flag.
  • EventWaitExternal: Event is captured in the graph as an external event node when performing stream capture. This flag is invalid outside of stream capture.

Note: This function uses standard default stream semantics.

See also: NewStream, Event.Record, Stream.Query, Stream.Synchronize, Stream.AddCallback, Stream.Close, cudaStreamWaitEvent

  • hEvent: Event to wait on (may not be NULL)
  • flags: See CUevent_capture_flags

Errors:

Wraps cuStreamWaitEvent.

func (Stream) WaitExternalSemaphoresAsync

func (s Stream) WaitExternalSemaphoresAsync(extSemArray *ExternalSemaphore, paramsArray *ExternalSemaphoreWaitParams, numExtSems uint32) error

WaitExternalSemaphoresAsync 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: ExternalSemaphoreHandleTypeOpaqueFd, ExternalSemaphoreHandleTypeOpaqueWin32, ExternalSemaphoreHandleTypeOpaqueWin32Kmt 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: ExternalSemaphoreHandleTypeD3d12Fence, ExternalSemaphoreHandleTypeD3d11Fence, ExternalSemaphoreHandleTypeTimelineSemaphoreFd, ExternalSemaphoreHandleTypeTimelineSemaphoreWin32 then waiting on the semaphore will wait until the value of the semaphore is greater than or equal to ExternalSemaphoreWaitParams.params.fence.value. If the semaphore object is of the type ExternalSemaphoreHandleTypeNvscisync then, waiting on the semaphore will wait until the ExternalSemaphoreSignalParams.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 as ExternalMemoryHandleTypeNvscibuf. 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 flag CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC, 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 type ExternalSemaphoreHandleTypeNvscisync, if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in Device.NvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_WAIT, this API will return ErrNotSupported. If the semaphore object is any one of the following types: ExternalSemaphoreHandleTypeD3d11KeyedMutex, ExternalSemaphoreHandleTypeD3d11KeyedMutexKmt then the keyed mutex will be acquired when it is released with the key specified in ExternalSemaphoreWaitParams.params.keyedmutex.key or until the timeout specified by ExternalSemaphoreWaitParams.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.

See also: ImportExternalSemaphore, ExternalSemaphore.Close, Stream.SignalExternalSemaphoresAsync

  • extSemArray: External semaphores to be waited on
  • paramsArray: Array of semaphore parameters
  • numExtSems: Number of semaphores to wait on

Errors:

Wraps cuWaitExternalSemaphoresAsync.

func (Stream) WaitValue32

func (s Stream) WaitValue32(addr DevicePtr, value uint32, flags StreamwaitvalueFlags) error

WaitValue32 waits on a memory location.

Enqueues a synchronization of the stream on the given memory location. Work ordered after the operation will block until the given condition on the memory is satisfied. By default, the condition is to wait for (int32_t)(*addr - value) >= 0, a cyclic greater-or-equal. Other condition types can be specified via flags. If the memory was registered via MemHostRegister, the device pointer should be obtained with MemHostGetDevicePointer. This function cannot be used with managed memory ( MemAllocManaged). Support for StreamWaitValueNor can be queried with Device.Attribute and CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V2.

Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order.

See also: Stream.WaitValue64, Stream.WriteValue32, Stream.WriteValue64, Stream.BatchMemOp, MemHostRegister, Stream.WaitEvent

  • addr: The memory location to wait on
  • value: The value to compare with the memory location
  • flags: See StreamwaitvalueFlags

Errors:

Wraps cuStreamWaitValue32, bound as cuStreamWaitValue32_v2.

func (Stream) WaitValue64

func (s Stream) WaitValue64(addr DevicePtr, value uint64, flags StreamwaitvalueFlags) error

WaitValue64 waits on a memory location.

Enqueues a synchronization of the stream on the given memory location. Work ordered after the operation will block until the given condition on the memory is satisfied. By default, the condition is to wait for (int64_t)(*addr - value) >= 0, a cyclic greater-or-equal. Other condition types can be specified via flags. If the memory was registered via MemHostRegister, the device pointer should be obtained with MemHostGetDevicePointer. Support for this can be queried with Device.Attribute and DevAttrCanUse64BitStreamMemOps.

Warning: Improper use of this API may deadlock the application. Synchronization ordering established through this API is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by this API should also have that order expressed with CUDA-visible dependencies such as events. This ensures that the scheduler does not serialize them in an improper order.

See also: Stream.WaitValue32, Stream.WriteValue32, Stream.WriteValue64, Stream.BatchMemOp, MemHostRegister, Stream.WaitEvent

  • addr: The memory location to wait on
  • value: The value to compare with the memory location
  • flags: See StreamwaitvalueFlags

Errors:

Wraps cuStreamWaitValue64, bound as cuStreamWaitValue64_v2.

func (Stream) WriteValue32

func (s Stream) WriteValue32(addr DevicePtr, value uint32, flags StreamwritevalueFlags) error

WriteValue32 writes a value to memory.

If the memory was registered via MemHostRegister, the device pointer should be obtained with MemHostGetDevicePointer. This function cannot be used with managed memory ( MemAllocManaged).

See also: Stream.WriteValue64, Stream.WaitValue32, Stream.WaitValue64, Stream.BatchMemOp, MemHostRegister, Event.Record

Errors:

Wraps cuStreamWriteValue32, bound as cuStreamWriteValue32_v2.

func (Stream) WriteValue64

func (s Stream) WriteValue64(addr DevicePtr, value uint64, flags StreamwritevalueFlags) error

WriteValue64 writes a value to memory.

If the memory was registered via MemHostRegister, the device pointer should be obtained with MemHostGetDevicePointer. Support for this can be queried with Device.Attribute and DevAttrCanUse64BitStreamMemOps.

See also: Stream.WriteValue32, Stream.WaitValue32, Stream.WaitValue64, Stream.BatchMemOp, MemHostRegister, Event.Record

Errors:

Wraps cuStreamWriteValue64, bound as cuStreamWriteValue64_v2.

type StreamAtomicReductionDataType

type StreamAtomicReductionDataType int32

StreamAtomicReductionDataType represents atomic reduction data types for CUstreamBatchMemOpParams.atomicReduction.dataType.

const (
	StreamAtomicReductionUnsigned32 StreamAtomicReductionDataType = 1<<1 | 1<<3 | 1<<2
	StreamAtomicReductionUnsigned64 StreamAtomicReductionDataType = 1<<1 | 1<<4 | 1<<2
)

func (StreamAtomicReductionDataType) String

String returns the constant name, or a numeric representation for unknown values.

type StreamAtomicReductionOpType

type StreamAtomicReductionOpType int32

StreamAtomicReductionOpType represents atomic reduction operation types for CUstreamBatchMemOpParams.atomicReduction.reductionOp.

const (
	StreamAtomicReductionOpOr  StreamAtomicReductionOpType = 6 // Performs an atomic OR: *(address) = *(address) | value
	StreamAtomicReductionOpAnd StreamAtomicReductionOpType = 5 // Performs an atomic AND: *(address) = *(address) & value
	StreamAtomicReductionOpAdd StreamAtomicReductionOpType = 0 // Performs an atomic ADD: *(address) = *(address) + value
)

func (StreamAtomicReductionOpType) String

String returns the constant name, or a numeric representation for unknown values.

type StreamBatchMemOpParams

type StreamBatchMemOpParams struct {
	// Data stores the raw bytes of the underlying C union.
	Data [6]uint64
}

StreamBatchMemOpParams represents per-operation parameters for Stream.BatchMemOp.

func (*StreamBatchMemOpParams) AtomicReduction

AtomicReduction returns a pointer to the atomicReduction member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) FlushRemoteWrites

FlushRemoteWrites returns a pointer to the flushRemoteWrites member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) MemoryBarrier

MemoryBarrier returns a pointer to the memoryBarrier member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) Operation

Operation returns a pointer to the operation member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) Pad

func (s *StreamBatchMemOpParams) Pad() *[6]uint64

Pad returns a pointer to the pad member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) WaitValue

WaitValue returns a pointer to the waitValue member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

func (*StreamBatchMemOpParams) WriteValue

WriteValue returns a pointer to the writeValue member of CUstreamBatchMemOpParams_v1, which shares its storage with every other member of the union.

type StreamBatchMemOpParamsV1

type StreamBatchMemOpParamsV1 = StreamBatchMemOpParams

StreamBatchMemOpParamsV1 is an alias for StreamBatchMemOpParams.

type StreamBatchMemOpType

type StreamBatchMemOpType int32

StreamBatchMemOpType represents operations for Stream.BatchMemOp.

const (
	StreamMemOpWaitValue32  StreamBatchMemOpType = 1 // Represents a [Stream.WaitValue32] operation
	StreamMemOpWriteValue32 StreamBatchMemOpType = 2 // Represents a [Stream.WriteValue32] operation
	StreamMemOpWaitValue64  StreamBatchMemOpType = 4 // Represents a [Stream.WaitValue64] operation
	StreamMemOpWriteValue64 StreamBatchMemOpType = 5 // Represents a [Stream.WriteValue64] operation
	StreamMemOpBarrier      StreamBatchMemOpType = 6 // Insert a memory barrier of the specified type
	// StreamMemOpAtomicReduction: Perform a atomic reduction. See CUstreamBatchMemOpParams.atomicReduction
	StreamMemOpAtomicReduction StreamBatchMemOpType = 8
	// StreamMemOpFlushRemoteWrites: This has the same effect as [StreamWaitValueFlush], but as a standalone operation.
	StreamMemOpFlushRemoteWrites StreamBatchMemOpType = 3
)

func (StreamBatchMemOpType) String

func (e StreamBatchMemOpType) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamCallback

type StreamCallback func(hStream Stream, status Result, userData uintptr)

StreamCallback is the Go form of CUstreamCallback.

It corresponds to the C signature

typedef void (CUDA_CB *CUstreamCallback)(CUstream hStream, CUresult status, void *userData);

Pass one to the API by converting it with purego.NewCallback, which is why every pointer argument is a uintptr rather than a Go pointer: the memory belongs to the C library and must not be traced by the collector.

type StreamCaptureMode

type StreamCaptureMode int32

StreamCaptureMode represents possible modes for stream capture thread interactions.

For more details see Stream.BeginCapture and ThreadExchangeStreamCaptureMode

const (
	StreamCaptureModeGlobal      StreamCaptureMode = 0
	StreamCaptureModeThreadLocal StreamCaptureMode = 1
	StreamCaptureModeRelaxed     StreamCaptureMode = 2
)

func (StreamCaptureMode) String

func (e StreamCaptureMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamCaptureStatus

type StreamCaptureStatus int32

StreamCaptureStatus represents possible stream capture statuses returned by Stream.IsCapturing.

const (
	StreamCaptureStatusNone   StreamCaptureStatus = 0 // Stream is not capturing
	StreamCaptureStatusActive StreamCaptureStatus = 1 // Stream is actively capturing
	// StreamCaptureStatusInvalidated: Stream is part of a capture sequence that has been invalidated, but not terminated
	StreamCaptureStatusInvalidated StreamCaptureStatus = 2
)

func (StreamCaptureStatus) String

func (e StreamCaptureStatus) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamCigCaptureParams

type StreamCigCaptureParams struct {
	// CIG (CUDA in Graphics) parameters for sharing command list data from D3D12 graphics clients.
	StreamCigParams uintptr
}

StreamCigCaptureParams represents params for capturing CUDA stream to CIG streamCigParams must be non-NULL.

type StreamCigDataType

type StreamCigDataType int32

StreamCigDataType specifies the stream cig data type (CUstreamCigDataType).

const (
	StreamCigDataTypeD3d12CommandList            StreamCigDataType = 0x1 // D3D12 Command List Handle
	StreamCigDataTypeVulkanCommandBufferHandleNv StreamCigDataType = 0x2 // Vulkan Command Buffer Internal NVIDIA Handle
)

func (StreamCigDataType) String

func (e StreamCigDataType) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamCigParam

type StreamCigParam struct {
	// Type of shared data from graphics client (D3D12).
	StreamSharedDataType StreamCigDataType
	// Graphics client data handle (ID3D12CommandList/ID3D12GraphicsCommandList).
	StreamSharedData uintptr
}

StreamCigParam represents CIG Stream Capture Params.

type StreamFlags

type StreamFlags uint32

StreamFlags represents stream creation flags.

const (
	StreamDefault     StreamFlags = 0x0 // Default stream flag
	StreamNonBlocking StreamFlags = 0x1 // Stream does not synchronize with stream 0 (the NULL stream)
)

func (StreamFlags) String

func (e StreamFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreammemopatomicreductionparamsSt

type StreammemopatomicreductionparamsSt struct {
	Operation   StreamBatchMemOpType
	Flags       uint32
	ReductionOp StreamAtomicReductionOpType
	DataType    StreamAtomicReductionDataType
	Address     DevicePtr
	Value       uint64
	Alias       DevicePtr
}

StreammemopatomicreductionparamsSt represents CUstreamMemOpAtomicReductionParams_st.

type StreammemopflushremotewritesparamsSt

type StreammemopflushremotewritesparamsSt struct {
	Operation StreamBatchMemOpType
	Flags     uint32
}

StreammemopflushremotewritesparamsSt represents CUstreamMemOpFlushRemoteWritesParams_st.

type StreammemopmemorybarrierparamsSt

type StreammemopmemorybarrierparamsSt struct {
	Operation StreamBatchMemOpType
	Flags     uint32
}

StreammemopmemorybarrierparamsSt represents CUstreamMemOpMemoryBarrierParams_st.

type StreammemopwaitvalueparamsSt

type StreammemopwaitvalueparamsSt struct {
	Operation      StreamBatchMemOpType
	Address        DevicePtr
	AnonymousUnion [1]uint64
	Flags          uint32
	Alias          DevicePtr
}

StreammemopwaitvalueparamsSt represents CUstreamMemOpWaitValueParams_st.

func (*StreammemopwaitvalueparamsSt) Value

Value returns a pointer to the value member of CUstreamMemOpWaitValueParams_st, which shares its storage with every other member of the union.

func (*StreammemopwaitvalueparamsSt) Value64

func (s *StreammemopwaitvalueparamsSt) Value64() *uint64

Value64 returns a pointer to the value64 member of CUstreamMemOpWaitValueParams_st, which shares its storage with every other member of the union.

type StreammemopwritevalueparamsSt

type StreammemopwritevalueparamsSt struct {
	Operation      StreamBatchMemOpType
	Address        DevicePtr
	AnonymousUnion [1]uint64
	Flags          uint32
	Alias          DevicePtr
}

StreammemopwritevalueparamsSt represents CUstreamMemOpWriteValueParams_st.

func (*StreammemopwritevalueparamsSt) Value

Value returns a pointer to the value member of CUstreamMemOpWriteValueParams_st, which shares its storage with every other member of the union.

func (*StreammemopwritevalueparamsSt) Value64

func (s *StreammemopwritevalueparamsSt) Value64() *uint64

Value64 returns a pointer to the value64 member of CUstreamMemOpWriteValueParams_st, which shares its storage with every other member of the union.

type StreammemorybarrierFlags

type StreammemorybarrierFlags int32

StreammemorybarrierFlags represents flags for CUstreamBatchMemOpParams.memoryBarrier.

const (
	StreamMemoryBarrierTypeSys StreammemorybarrierFlags = 0x0 // System-wide memory barrier.
	StreamMemoryBarrierTypeGpu StreammemorybarrierFlags = 0x1 // Limit memory barrier scope to the GPU.
)

func (StreammemorybarrierFlags) String

func (e StreammemorybarrierFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamupdatecapturedependenciesFlags

type StreamupdatecapturedependenciesFlags int32

StreamupdatecapturedependenciesFlags represents flags for Stream.UpdateCaptureDependencies.

const (
	StreamAddCaptureDependencies StreamupdatecapturedependenciesFlags = 0x0 // Add new nodes to the dependency set
	StreamSetCaptureDependencies StreamupdatecapturedependenciesFlags = 0x1 // Replace the dependency set with the new nodes
)

func (StreamupdatecapturedependenciesFlags) String

String returns the constant name, or a numeric representation for unknown values.

type StreamwaitvalueFlags

type StreamwaitvalueFlags int32

StreamwaitvalueFlags represents flags for Stream.WaitValue32 and Stream.WaitValue64.

const (
	// StreamWaitValueGeq: Wait until (int32_t)(*addr - value) >= 0 (or int64_t for 64 bit values). Note this is a cyclic comparison which ignores wraparound. (Default behavior.)
	StreamWaitValueGeq StreamwaitvalueFlags = 0x0
	StreamWaitValueEq  StreamwaitvalueFlags = 0x1 // Wait until *addr == value.
	StreamWaitValueAnd StreamwaitvalueFlags = 0x2 // Wait until (*addr & value) != 0.
	// StreamWaitValueNor: Wait until ~(*addr | value) != 0. Support for this operation can be queried with [Device.Attribute] and [DevAttrCanUseStreamWaitValueNor].
	StreamWaitValueNor StreamwaitvalueFlags = 0x3
	// StreamWaitValueFlush: Follow the wait operation with a flush of outstanding remote writes. This means that, if a remote write operation is guaranteed to have reached the device before the wait can be satisfied, that write is guaranteed to be visible to downstream device work. The device is permitted to reorder remote writes internally. For example, this flag would be required if two remote writes arrive in a defined order, the wait is satisfied by the second write, and downstream work needs to observe the first write. Support for this operation is restricted to selected platforms and can be queried with [DevAttrCanFlushRemoteWrites].
	StreamWaitValueFlush StreamwaitvalueFlags = 1 << 30
)

func (StreamwaitvalueFlags) String

func (e StreamwaitvalueFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type StreamwritevalueFlags

type StreamwritevalueFlags int32

StreamwritevalueFlags represents flags for Stream.WriteValue32.

const (
	StreamWriteValueDefault StreamwritevalueFlags = 0x0 // Default behavior
	// StreamWriteValueNoMemoryBarrier: Permits the write to be reordered with writes which were issued before it, as a performance optimization. Normally, [Stream.WriteValue32] will provide a memory fence before the write, which has similar semantics to __threadfence_system() but is scoped to the stream rather than a CUDA thread. This flag is not supported in the v2 API.
	StreamWriteValueNoMemoryBarrier StreamwritevalueFlags = 0x1
)

func (StreamwritevalueFlags) String

func (e StreamwritevalueFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type SurfRef

type SurfRef uintptr

SurfRef is CUDA surface reference.

func (SurfRef) Array deprecated

func (s SurfRef) Array() (Array, error)

Array passes back the CUDA array bound to a surface reference.

Returns the CUDA array bound to the surface reference hSurfRef, or returns ErrInvalidValue if the surface reference is not bound to any CUDA array.

See also: Module.SurfRef, SurfRef.SetArray

Errors:

Wraps cuSurfRefGetArray.

Deprecated: Deprecated by NVIDIA.

func (SurfRef) SetArray deprecated

func (s SurfRef) SetArray(hArray Array, flags uint32) error

SetArray sets the CUDA array for a surface reference.

Sets the CUDA array hArray to be read and written by the surface reference hSurfRef. Any previous CUDA array state associated with the surface reference is superseded by this function. Flags must be set to 0. The CUDA_ARRAY3D_SURFACE_LDST flag must have been set for the CUDA array. Any CUDA array previously bound to hSurfRef is unbound.

See also: Module.SurfRef, SurfRef.Array

  • hArray: CUDA array handle
  • flags: set to 0

Errors:

Wraps cuSurfRefSetArray.

Deprecated: Deprecated by NVIDIA.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

SymbolError reports that a symbol is not callable.

Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.

func (*SymbolError) Error

func (e *SymbolError) Error() string

Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.

type SynchronizationPolicy

type SynchronizationPolicy int32

SynchronizationPolicy specifies the synchronization policy (CUsynchronizationPolicy).

const (
	SyncPolicyAuto         SynchronizationPolicy = 1
	SyncPolicySpin         SynchronizationPolicy = 2
	SyncPolicyYield        SynchronizationPolicy = 3
	SyncPolicyBlockingSync SynchronizationPolicy = 4
)

func (SynchronizationPolicy) String

func (e SynchronizationPolicy) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMap

type TensorMap struct {
	Opaque [16]uint64
}

TensorMap represents tensor map descriptor.

Requires compiler support for aligning to 128 bytes.

C declares CUtensorMap with 128-byte alignment, which a Go type cannot express: a TensorMap declared as a variable or allocated with new is at most 8-byte aligned. NewTensorMap returns a zero TensorMap at a 128-byte-aligned address, for when its address is handed to something that relies on the C alignment. The driver does not require this alignment of a host address: TensorMapEncodeTiled and TensorMapReplaceAddress accept a TensorMap at any offset. It matters once the map is in memory a kernel reads, such as a __grid_constant__ parameter or a copy in global or constant memory.

func NewTensorMap

func NewTensorMap() *TensorMap

NewTensorMap returns a pointer to a zero TensorMap aligned to 128 bytes, as C aligns CUtensorMap. The alignment belongs to the storage: a copy of the value is aligned only as Go aligns a TensorMap.

Example
package main

import (
	"fmt"
	"unsafe"

	"github.com/tmc/lib/nvidia/driver"
)

func main() {
	descriptor := driver.NewTensorMap()
	fmt.Println(unsafe.Sizeof(*descriptor))
	fmt.Println(uintptr(unsafe.Pointer(descriptor)) % 128)
}
Output:
128
0

type TensorMapAllocClass

type TensorMapAllocClass int32

TensorMapAllocClass represents tensor-map allocation class.

On devices where allocation-class selection affects Tensor Memory Accelerator (TMA) out-of-bounds address generation, this controls the mode encoded in a TensorMap. The "large" class enables a wider (128 KiB) OOB address-generation window that improves performance but is only safe when the tensor's base allocation is backed by a contiguous, accessible region of at least DevAttrTensorMapLargeTensorMinSize bytes. On devices where allocation-class selection has no effect, all requests have the same SMALL effective behavior.

const (
	// TensorMapAllocClassAuto: Recompute the effective allocation class from the tensor-map layout.
	TensorMapAllocClassAuto  TensorMapAllocClass = 0
	TensorMapAllocClassSmall TensorMapAllocClass = 1 // Request the "small" class (safe 4 KiB OOB window).
	// TensorMapAllocClassLarge: Request the "large" class (128 KiB OOB window); when LARGE is effective, the caller guarantees the effective base allocation is accessible for at least [DevAttrTensorMapLargeTensorMinSize] bytes before use.
	TensorMapAllocClassLarge TensorMapAllocClass = 2
)

func (TensorMapAllocClass) String

func (e TensorMapAllocClass) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapDataType

type TensorMapDataType int32

TensorMapDataType represents tensor map data type.

const (
	TensorMapDataTypeUint8        TensorMapDataType = 0
	TensorMapDataTypeUint16       TensorMapDataType = 1
	TensorMapDataTypeUint32       TensorMapDataType = 2
	TensorMapDataTypeInt32        TensorMapDataType = 3
	TensorMapDataTypeUint64       TensorMapDataType = 4
	TensorMapDataTypeInt64        TensorMapDataType = 5
	TensorMapDataTypeFloat16      TensorMapDataType = 6
	TensorMapDataTypeFloat32      TensorMapDataType = 7
	TensorMapDataTypeFloat64      TensorMapDataType = 8
	TensorMapDataTypeBfloat16     TensorMapDataType = 9
	TensorMapDataTypeFloat32Ftz   TensorMapDataType = 10
	TensorMapDataTypeTfloat32     TensorMapDataType = 11
	TensorMapDataTypeTfloat32Ftz  TensorMapDataType = 12
	TensorMapDataType16U4Align8b  TensorMapDataType = 13
	TensorMapDataType16U4Align16b TensorMapDataType = 14
	TensorMapDataType16U6Align16b TensorMapDataType = 15
)

func (TensorMapDataType) String

func (e TensorMapDataType) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapFloatOOBfill

type TensorMapFloatOOBfill int32

TensorMapFloatOOBfill represents tensor map out-of-bounds fill type.

const (
	TensorMapFloatOobFillNone              TensorMapFloatOOBfill = 0
	TensorMapFloatOobFillNanRequestZeroFma TensorMapFloatOOBfill = 1
)

func (TensorMapFloatOOBfill) String

func (e TensorMapFloatOOBfill) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapIm2ColWideMode

type TensorMapIm2ColWideMode int32

TensorMapIm2ColWideMode represents tensor map Im2Col wide mode.

const (
	TensorMapIm2colWideModeW    TensorMapIm2ColWideMode = 0
	TensorMapIm2colWideModeW128 TensorMapIm2ColWideMode = 1
)

func (TensorMapIm2ColWideMode) String

func (e TensorMapIm2ColWideMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapInterleave

type TensorMapInterleave int32

TensorMapInterleave represents tensor map interleave layout type.

const (
	TensorMapInterleaveNone TensorMapInterleave = 0
	TensorMapInterleave16B  TensorMapInterleave = 1
	TensorMapInterleave32B  TensorMapInterleave = 2
)

func (TensorMapInterleave) String

func (e TensorMapInterleave) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapL2promotion

type TensorMapL2promotion int32

TensorMapL2promotion represents tensor map L2 promotion type.

const (
	TensorMapL2PromotionNone   TensorMapL2promotion = 0
	TensorMapL2PromotionL264B  TensorMapL2promotion = 1
	TensorMapL2PromotionL2128B TensorMapL2promotion = 2
	TensorMapL2PromotionL2256B TensorMapL2promotion = 3
)

func (TensorMapL2promotion) String

func (e TensorMapL2promotion) String() string

String returns the constant name, or a numeric representation for unknown values.

type TensorMapSwizzle

type TensorMapSwizzle int32

TensorMapSwizzle represents tensor map swizzling mode of shared memory banks.

const (
	TensorMapSwizzleNone              TensorMapSwizzle = 0
	TensorMapSwizzle32B               TensorMapSwizzle = 1
	TensorMapSwizzle64B               TensorMapSwizzle = 2
	TensorMapSwizzle128B              TensorMapSwizzle = 3
	TensorMapSwizzle128BAtom32B       TensorMapSwizzle = 4
	TensorMapSwizzle128BAtom32BFlip8B TensorMapSwizzle = 5
	TensorMapSwizzle128BAtom64B       TensorMapSwizzle = 6
)

func (TensorMapSwizzle) String

func (e TensorMapSwizzle) String() string

String returns the constant name, or a numeric representation for unknown values.

type TexRef

type TexRef uintptr

TexRef is CUDA texture reference.

func NewTexRef deprecated

func NewTexRef() (TexRef, error)

NewTexRef creates a texture reference.

Creates a texture reference and returns its handle. Once created, the application must call TexRef.SetArray or TexRef.SetAddress to associate the reference with allocated memory. Other texture reference functions are used to specify the format and interpretation (addressing, filtering, etc.) to be used when the memory is read through this texture reference.

See also: TexRef.Close

Errors:

Wraps cuTexRefCreate.

Deprecated: Deprecated by NVIDIA.

func (TexRef) Address deprecated

func (t TexRef) Address() (DevicePtr, error)

Address gets the address associated with a texture reference.

Returns the base address bound to the texture reference hTexRef, or returns ErrInvalidValue if the texture reference is not bound to any device memory range.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetAddress, bound as cuTexRefGetAddress_v2.

Deprecated: Deprecated by NVIDIA.

func (TexRef) AddressMode deprecated

func (t TexRef) AddressMode(dim int32) (AddressMode, error)

AddressMode gets the addressing mode used by a texture reference.

Returns the addressing mode corresponding to the dimension dim of the texture reference hTexRef. Currently, the only valid value for dim are 0 and 1.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • dim: Dimension

Errors:

Wraps cuTexRefGetAddressMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) Array deprecated

func (t TexRef) Array() (Array, error)

Array gets the array bound to a texture reference.

Returns the CUDA array bound to the texture reference hTexRef, or returns ErrInvalidValue if the texture reference is not bound to any CUDA array.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetArray.

Deprecated: Deprecated by NVIDIA.

func (TexRef) BorderColor deprecated

func (t TexRef) BorderColor() (float32, error)

BorderColor gets the border color used by a texture reference.

Returns in pBorderColor, values of the RGBA color used by the texture reference hTexRef. The color value is of type float and holds color components in the following sequence: pBorderColor[0] holds ‘R’ component pBorderColor[1] holds ‘G’ component pBorderColor[2] holds ‘B’ component pBorderColor[3] holds ‘A’ component

See also: TexRef.SetAddressMode, TexRef.SetBorderColor

Errors:

Wraps cuTexRefGetBorderColor.

Deprecated: Deprecated by NVIDIA.

func (*TexRef) Close deprecated

func (t *TexRef) Close() error

Close destroys a texture reference.

Destroys the texture reference specified by hTexRef.

See also: NewTexRef

Errors:

If t is zero, Close returns nil. Otherwise Close sets t to zero when the call succeeds and leaves it unchanged when it fails. Only t is zeroed: a copy of it still refers to the released object.

Wraps cuTexRefDestroy.

Deprecated: Deprecated by NVIDIA.

func (TexRef) FilterMode deprecated

func (t TexRef) FilterMode() (FilterMode, error)

FilterMode gets the filter-mode used by a texture reference.

Returns the filtering mode of the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetFilterMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) Flags deprecated

func (t TexRef) Flags() (uint32, error)

Flags gets the flags used by a texture reference.

Returns the flags of the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Format

Errors:

Wraps cuTexRefGetFlags.

Deprecated: Deprecated by NVIDIA.

func (TexRef) Format deprecated

func (t TexRef) Format() (pFormat ArrayFormat, pNumChannels int32, err error)

Format gets the format used by a texture reference.

Returns in *pFormat and *pNumChannels the format and number of components of the CUDA array bound to the texture reference hTexRef. If pFormat or pNumChannels is NULL, it will be ignored.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags

  • pFormat: Returned format
  • pNumChannels: Returned number of components

Errors:

Wraps cuTexRefGetFormat.

Deprecated: Deprecated by NVIDIA.

func (TexRef) MaxAnisotropy deprecated

func (t TexRef) MaxAnisotropy() (int32, error)

MaxAnisotropy gets the maximum anisotropy for a texture reference.

Returns the maximum anisotropy that’s used when reading memory through the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetMaxAnisotropy.

Deprecated: Deprecated by NVIDIA.

func (TexRef) MipmapFilterMode deprecated

func (t TexRef) MipmapFilterMode() (FilterMode, error)

MipmapFilterMode gets the mipmap filtering mode for a texture reference.

Returns the mipmap filtering mode that’s used when reading memory through the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetMipmapFilterMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) MipmapLevelBias deprecated

func (t TexRef) MipmapLevelBias() (float32, error)

MipmapLevelBias gets the mipmap level bias for a texture reference.

Returns the mipmap level bias in pBias that’s added to the specified mipmap level when reading memory through the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetMipmapLevelBias.

Deprecated: Deprecated by NVIDIA.

func (TexRef) MipmapLevelClamp deprecated

func (t TexRef) MipmapLevelClamp() (pminMipmapLevelClamp float32, pmaxMipmapLevelClamp float32, err error)

MipmapLevelClamp gets the min/max mipmap level clamps for a texture reference.

Returns the min/max mipmap level clamps in pminMipmapLevelClamp and pmaxMipmapLevelClamp that’s used when reading memory through the texture reference hTexRef.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • pminMipmapLevelClamp: Returned mipmap min level clamp
  • pmaxMipmapLevelClamp: Returned mipmap max level clamp

Errors:

Wraps cuTexRefGetMipmapLevelClamp.

Deprecated: Deprecated by NVIDIA.

func (TexRef) MipmappedArray deprecated

func (t TexRef) MipmappedArray() (MipmappedArray, error)

MipmappedArray gets the mipmapped array bound to a texture reference.

Returns the CUDA mipmapped array bound to the texture reference hTexRef, or returns ErrInvalidValue if the texture reference is not bound to any CUDA mipmapped array.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.FilterMode, TexRef.Flags, TexRef.Format

Errors:

Wraps cuTexRefGetMipmappedArray.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetAddress deprecated

func (t TexRef) SetAddress(dptr DevicePtr, bytes uint) (uint, error)

SetAddress binds an address as a texture reference.

Binds a linear address range to the texture reference hTexRef. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Any memory previously bound to hTexRef is unbound. Since the hardware enforces an alignment requirement on texture base addresses, TexRef.SetAddress passes back a byte offset that must be applied to texture fetches in order to read from the desired memory. This offset must be divided by the texel size and passed to kernels that read from the texture so they can be applied to the tex1Dfetch() function. If the device memory pointer was returned from MemAlloc, the offset is guaranteed to be 0 and NULL may be passed as the ByteOffset parameter. The total number of elements (or texels) in the linear address range cannot exceed DevAttrMaximumTexture1dLinearWidth. The number of elements is computed as ( bytes / bytesPerElement), where bytesPerElement is determined from the data format and number of components set using TexRef.SetFormat.

See also: TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • dptr: Device pointer to bind
  • bytes: Size of memory to bind in bytes

Errors:

Wraps cuTexRefSetAddress, bound as cuTexRefSetAddress_v2.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetAddress2D deprecated

func (t TexRef) SetAddress2D(desc *ArrayDescriptor, dptr DevicePtr, pitch uint) error

SetAddress2D binds an address as a 2D texture reference.

Binds a linear address range to the texture reference hTexRef. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Any memory previously bound to hTexRef is unbound. Using a tex2D() function inside a kernel requires a call to either TexRef.SetArray to bind the corresponding texture reference to an array, or TexRef.SetAddress2D to bind the texture reference to linear memory. Function calls to TexRef.SetFormat cannot follow calls to TexRef.SetAddress2D for the same texture reference. It is required that dptr be aligned to the appropriate hardware-specific texture alignment. You can query this value using the device attribute DevAttrTextureAlignment. If an unaligned dptr is supplied, ErrInvalidValue is returned. Pitch has to be aligned to the hardware-specific texture pitch alignment. This value can be queried using the device attribute DevAttrTexturePitchAlignment. If an unaligned Pitch is supplied, ErrInvalidValue is returned. Width and Height, which are specified in elements (or texels), cannot exceed DevAttrMaximumTexture2dLinearWidth and DevAttrMaximumTexture2dLinearHeight respectively. Pitch, which is specified in bytes, cannot exceed DevAttrMaximumTexture2dLinearPitch.

See also: TexRef.SetAddress, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • desc: Descriptor of CUDA array
  • dptr: Device pointer to bind
  • pitch: Line pitch in bytes

Errors:

Wraps cuTexRefSetAddress2D, bound as cuTexRefSetAddress2D_v3.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetAddressMode deprecated

func (t TexRef) SetAddressMode(dim int32, am AddressMode) error

SetAddressMode sets the addressing mode for a texture reference.

Specifies the addressing mode am for the given dimension dim of the texture reference hTexRef. If dim is zero, the addressing mode is applied to the first parameter of the functions used to fetch from the texture; if dim is 1, the second, and so on.

Note that this call has no effect if hTexRef is bound to linear memory. Also, if the flag, CU_TRSF_NORMALIZED_COORDINATES, is not set, the only supported address mode is TrAddressModeClamp.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • dim: Dimension
  • am: Addressing mode to set

Errors:

Wraps cuTexRefSetAddressMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetArray deprecated

func (t TexRef) SetArray(hArray Array, flags uint32) error

SetArray binds an array as a texture reference.

Binds the CUDA array hArray to the texture reference hTexRef. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Flags must be set to CU_TRSA_OVERRIDE_FORMAT. Any CUDA array previously bound to hTexRef is unbound.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • hArray: Array to bind
  • flags: Options (must be CU_TRSA_OVERRIDE_FORMAT)

Errors:

Wraps cuTexRefSetArray.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetBorderColor deprecated

func (t TexRef) SetBorderColor() (float32, error)

SetBorderColor sets the border color for a texture reference.

Specifies the value of the RGBA color via the pBorderColor to the texture reference hTexRef. The color value supports only float type and holds color components in the following sequence: pBorderColor[0] holds ‘R’ component pBorderColor[1] holds ‘G’ component pBorderColor[2] holds ‘B’ component pBorderColor[3] holds ‘A’ component Note that the color values can be set only when the Address mode is set to TrAddressModeBorder using TexRef.SetAddressMode. Applications using integer border color values have to “reinterpret_cast” their values to float.

See also: TexRef.SetAddressMode, TexRef.AddressMode, TexRef.BorderColor

Errors:

Wraps cuTexRefSetBorderColor.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetFilterMode deprecated

func (t TexRef) SetFilterMode(fm FilterMode) error

SetFilterMode sets the filtering mode for a texture reference.

Specifies the filtering mode fm to be used when reading memory through the texture reference hTexRef.

Note that this call has no effect if hTexRef is bound to linear memory.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • fm: Filtering mode to set

Errors:

Wraps cuTexRefSetFilterMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetFlags deprecated

func (t TexRef) SetFlags(flags uint32) error

SetFlags sets the flags for a texture reference.

Specifies optional flags via Flags to specify the behavior of data returned through the texture reference hTexRef. The valid flags are:

  • CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of having the texture promote integer data to floating point data in the range [0, 1]. Note that texture with 32-bit integer format would not be promoted, regardless of whether or not this flag is specified;
  • CU_TRSF_NORMALIZED_COORDINATES, which suppresses the default behavior of having the texture coordinates range from [0, Dim) where Dim is the width or height of the CUDA array. Instead, the texture coordinates [0, 1.0) reference the entire breadth of the array dimension;
  • CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear filtering optimizations. Trilinear optimizations improve texture filtering performance by allowing bilinear filtering on textures in scenarios where it can closely approximate the expected results.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • flags: Optional flags to set

Errors:

Wraps cuTexRefSetFlags.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetFormat deprecated

func (t TexRef) SetFormat(fmt ArrayFormat, numPackedComponents int32) error

SetFormat sets the format for a texture reference.

Specifies the format of the data to be read by the texture reference hTexRef. fmt and NumPackedComponents are exactly analogous to the Format and NumChannels members of the ArrayDescriptor structure: They specify the format of each component and the number of components per array element.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format, cudaCreateChannelDesc

  • fmt: Format to set
  • numPackedComponents: Number of components per array element

Errors:

Wraps cuTexRefSetFormat.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetMaxAnisotropy deprecated

func (t TexRef) SetMaxAnisotropy(maxAniso uint32) error

SetMaxAnisotropy sets the maximum anisotropy for a texture reference.

Specifies the maximum anisotropy maxAniso to be used when reading memory through the texture reference hTexRef. Note that this call has no effect if hTexRef is bound to linear memory.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • maxAniso: Maximum anisotropy

Errors:

Wraps cuTexRefSetMaxAnisotropy.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetMipmapFilterMode deprecated

func (t TexRef) SetMipmapFilterMode(fm FilterMode) error

SetMipmapFilterMode sets the mipmap filtering mode for a texture reference.

Specifies the mipmap filtering mode fm to be used when reading memory through the texture reference hTexRef.

Note that this call has no effect if hTexRef is not bound to a mipmapped array.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • fm: Filtering mode to set

Errors:

Wraps cuTexRefSetMipmapFilterMode.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetMipmapLevelBias deprecated

func (t TexRef) SetMipmapLevelBias(bias float32) error

SetMipmapLevelBias sets the mipmap level bias for a texture reference.

Specifies the mipmap level bias bias to be added to the specified mipmap level when reading memory through the texture reference hTexRef. Note that this call has no effect if hTexRef is not bound to a mipmapped array.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • bias: Mipmap level bias

Errors:

Wraps cuTexRefSetMipmapLevelBias.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetMipmapLevelClamp deprecated

func (t TexRef) SetMipmapLevelClamp(minMipmapLevelClamp float32, maxMipmapLevelClamp float32) error

SetMipmapLevelClamp sets the mipmap min/max mipmap level clamps for a texture reference.

Specifies the min/max mipmap level clamps, minMipmapLevelClamp and maxMipmapLevelClamp respectively, to be used when reading memory through the texture reference hTexRef. Note that this call has no effect if hTexRef is not bound to a mipmapped array.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetArray, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • minMipmapLevelClamp: Mipmap min level clamp
  • maxMipmapLevelClamp: Mipmap max level clamp

Errors:

Wraps cuTexRefSetMipmapLevelClamp.

Deprecated: Deprecated by NVIDIA.

func (TexRef) SetMipmappedArray deprecated

func (t TexRef) SetMipmappedArray(hMipmappedArray MipmappedArray, flags uint32) error

SetMipmappedArray binds a mipmapped array to a texture reference.

Binds the CUDA mipmapped array hMipmappedArray to the texture reference hTexRef. Any previous address or CUDA array state associated with the texture reference is superseded by this function. Flags must be set to CU_TRSA_OVERRIDE_FORMAT. Any CUDA array previously bound to hTexRef is unbound.

See also: TexRef.SetAddress, TexRef.SetAddress2D, TexRef.SetAddressMode, TexRef.SetFilterMode, TexRef.SetFlags, TexRef.SetFormat, TexRef.Address, TexRef.AddressMode, TexRef.Array, TexRef.FilterMode, TexRef.Flags, TexRef.Format

  • hMipmappedArray: Mipmapped array to bind
  • flags: Options (must be CU_TRSA_OVERRIDE_FORMAT)

Errors:

Wraps cuTexRefSetMipmappedArray.

Deprecated: Deprecated by NVIDIA.

type TextureDesc

type TextureDesc struct {
	// Address modes
	AddressMode [3]AddressMode
	// Filter mode
	FilterMode FilterMode
	// Flags
	Flags uint32
	// Maximum anisotropy ratio
	MaxAnisotropy uint32
	// Mipmap filter mode
	MipmapFilterMode FilterMode
	// Mipmap level bias
	MipmapLevelBias float32
	// Mipmap minimum level clamp
	MinMipmapLevelClamp float32
	// Mipmap maximum level clamp
	MaxMipmapLevelClamp float32
	// Border Color
	BorderColor [4]float32
	Reserved    [12]int32
}

TextureDesc represents texture descriptor.

func TexObjectGetTextureDesc

func TexObjectGetTextureDesc(texObject uint64) (TextureDesc, error)

TexObjectGetTextureDesc returns a texture object’s texture descriptor.

Returns the texture descriptor for the texture object specified by texObject.

See also: TexObjectCreate, cudaGetTextureObjectTextureDesc

  • texObject: Texture object

Errors:

Wraps cuTexObjectGetTextureDesc.

type TextureDescV1

type TextureDescV1 = TextureDesc

TextureDescV1 is an alias for TextureDesc.

type UserObject

type UserObject uintptr

UserObject is CUDA user object for graphs.

func NewUserObject

func NewUserObject(ptr uintptr, destroy uintptr, initialRefcount uint32, flags UserobjectFlags) (UserObject, error)

NewUserObject creates a user object.

Create a user object with the specified destructor callback and initial reference count. The initial references are owned by the caller. Destructor callbacks cannot make CUDA API calls and should avoid blocking behavior, as they are executed by a shared internal thread. Another thread may be signaled to perform such actions, if it does not block forward progress of tasks scheduled through CUDA. See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects.

See also: UserObject.Retain, UserObject.Release, Graph.RetainUserObject, Graph.ReleaseUserObject, NewGraph

  • ptr: The pointer to pass to the destroy function
  • destroy: Callback to free the user object when it is no longer in use (see HostFn)
  • initialRefcount: The initial refcount to create the object with, typically 1. The initial references are owned by the calling thread
  • flags: Currently it is required to pass UserObjectNoDestructorSync, which is the only defined flag. This indicates that the destroy callback cannot be waited on by any CUDA API. Users requiring synchronization of the callback should signal its completion manually

Errors:

Wraps cuUserObjectCreate.

func (UserObject) Release

func (u UserObject) Release(count uint32) error

Release releases a reference to a user object.

Releases user object references owned by the caller. The object’s destructor is invoked if the reference count reaches zero. It is undefined behavior to release references not owned by the caller, or to use a user object handle after all references are released. See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects.

See also: NewUserObject, UserObject.Retain, Graph.RetainUserObject, Graph.ReleaseUserObject, NewGraph

  • count: The number of references to release, typically 1. Must be nonzero and not larger than INT_MAX

Errors:

It is not named Close because it takes more than the handle.

Wraps cuUserObjectRelease.

func (UserObject) Retain

func (u UserObject) Retain(count uint32) error

Retain retains a reference to a user object.

Retains new references to a user object. The new references are owned by the caller. See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects.

See also: NewUserObject, UserObject.Release, Graph.RetainUserObject, Graph.ReleaseUserObject, NewGraph

  • count: The number of references to retain, typically 1. Must be nonzero and not larger than INT_MAX

Errors:

Wraps cuUserObjectRetain.

type UserobjectFlags

type UserobjectFlags int32

UserobjectFlags represents flags for user objects for graphs.

const (
	// UserObjectNoDestructorSync: Indicates the destructor execution is not synchronized by any CUDA handle.
	UserObjectNoDestructorSync UserobjectFlags = 1
)

func (UserobjectFlags) String

func (e UserobjectFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type UserobjectretainFlags

type UserobjectretainFlags int32

UserobjectretainFlags represents flags for retaining user object references for graphs.

const (
	// GraphUserObjectMove: Transfer references from the caller rather than creating new references.
	GraphUserObjectMove UserobjectretainFlags = 1
)

func (UserobjectretainFlags) String

func (e UserobjectretainFlags) String() string

String returns the constant name, or a numeric representation for unknown values.

type Uuid

type Uuid struct {
	Bytes [16]byte
}

Uuid represents CUuuid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL