diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 62220467b71..a0e62a309df 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -108,7 +108,7 @@ repos: rev: "3e8a8703264a2f4a69428a0aa4dcb512790b2c8c" # frozen: v6.0.0 hooks: - id: check-added-large-files - exclude: cuda_bindings/cuda/bindings/nvml.pyx + exclude: cuda_bindings/cuda/bindings/nvml.pyx|cuda_bindings/cuda/bindings/_v2/driver.pyx - id: check-case-conflict - id: check-docstring-first - id: check-merge-conflict diff --git a/cuda_bindings/cuda/bindings/_example_helpers/common.py b/cuda_bindings/cuda/bindings/_example_helpers/common.py index 6335d3e3e4a..89c025a69b7 100644 --- a/cuda_bindings/cuda/bindings/_example_helpers/common.py +++ b/cuda_bindings/cuda/bindings/_example_helpers/common.py @@ -8,8 +8,8 @@ import numpy as np from cuda import pathfinder -from cuda.bindings import driver as cuda from cuda.bindings import runtime as cudart +from cuda.bindings._v2 import driver as cuda from cuda.bindings._v2 import nvrtc from .helper_cuda import check_cuda_errors @@ -84,7 +84,9 @@ def __init__(self, code, dev_id): else: data = nvrtc.get_ptx(prog) - self.module = check_cuda_errors(cuda.cuModuleLoadData(np.char.array(data))) + self.module = cuda.module_load_data(np.char.array(data)) def get_function(self, name): - return check_cuda_errors(cuda.cuModuleGetFunction(self.module, name)) + if isinstance(name, bytes): + name = name.decode() + return cuda.module_get_function(self.module, name) diff --git a/cuda_bindings/cuda/bindings/_example_helpers/helper_cuda.py b/cuda_bindings/cuda/bindings/_example_helpers/helper_cuda.py index 18fbecf59b9..5b0b92b6601 100644 --- a/cuda_bindings/cuda/bindings/_example_helpers/helper_cuda.py +++ b/cuda_bindings/cuda/bindings/_example_helpers/helper_cuda.py @@ -4,6 +4,7 @@ from cuda.bindings import driver as cuda from cuda.bindings import nvrtc from cuda.bindings import runtime as cudart +from cuda.bindings._v2 import driver as cuda_v2 from .helper_string import check_cmd_line_flag, get_cmd_line_argument_int @@ -43,6 +44,6 @@ def find_cuda_device_drv(): dev_id = 0 if check_cmd_line_flag("device="): dev_id = get_cmd_line_argument_int("device=") - check_cuda_errors(cuda.cuInit(0)) - cu_device = check_cuda_errors(cuda.cuDeviceGet(dev_id)) + cuda_v2.init(0) + cu_device = cuda_v2.device_get(dev_id) return cu_device diff --git a/cuda_bindings/cuda/bindings/_v2/driver.pxd b/cuda_bindings/cuda/bindings/_v2/driver.pxd new file mode 100644 index 00000000000..713d95ca4d7 --- /dev/null +++ b/cuda_bindings/cuda/bindings/_v2/driver.pxd @@ -0,0 +1,725 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +# This code was automatically generated across versions from 12.9.0 to 13.3.0. Do not modify it directly. +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=377ebd633ccf0026ef03aa0e76efb005906ba573d36899cc076b886f19486f7a + + +# <<<< PREAMBLE CONTENT >>>> + +from libc.stdint cimport ( + intptr_t, + uint32_t, + uint64_t, +) + + +# <<<< END OF PREAMBLE CONTENT >>>> + +from libc.stdint cimport intptr_t + +from ..cydriver cimport * +# Named cimport so enum class bodies can use cydriver.TYPE.CONST syntax, which +# causes Cython to emit C-level PyLong_From_TYPE() instead of a Python global +# name lookup that fails at module init time. +cimport cuda.bindings.cydriver as cydriver + + +############################################################################### +# Types +############################################################################### + +ctypedef CUcontext context +ctypedef CUmodule module +ctypedef CUfunction function +ctypedef CUlibrary library +ctypedef CUkernel kernel +ctypedef CUarray array +ctypedef CUmipmappedArray mipmappedArray +ctypedef CUtexref texref +ctypedef CUsurfref surfref +ctypedef CUevent event +ctypedef CUstream stream +ctypedef CUgraphicsResource graphicsResource +ctypedef CUexternalMemory externalMemory +ctypedef CUexternalSemaphore externalSemaphore +ctypedef CUgraph graph +ctypedef CUgraphNode graphNode +ctypedef CUgraphExec graphExec +ctypedef CUmemoryPool memoryPool +ctypedef CUuserObject userObject +ctypedef CUgraphDeviceNode graphDeviceNode +ctypedef CUasyncCallbackHandle asyncCallbackHandle +ctypedef CUgreenCtx greenCtx +ctypedef CUlinkState linkState +ctypedef CUdevResourceDesc devResourceDesc +ctypedef CUlogsCallbackHandle logsCallbackHandle +ctypedef CUcoredumpCallbackHandle coredumpCallbackHandle +ctypedef CUhostFn hostFn +ctypedef CUoccupancyB2DSize occupancyB2DSize +ctypedef CUlogsCallback logsCallback +ctypedef CUDA_KERNEL_NODE_PARAMS_v1 KernelNodeParams_v1 +ctypedef CUstreamCallback streamCallback +ctypedef CUstreamCigCaptureParams StreamCigCaptureParams +ctypedef CUcoredumpStatusCallback coredumpStatusCallback +ctypedef CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 ExternalMemoryMipmappedArrayDesc_v1 +ctypedef CUlaunchAttributeValue LaunchAttributeValue +ctypedef CUcheckpointRestoreArgs CheckpointRestoreArgs +ctypedef CUasyncNotificationInfo AsyncNotificationInfo +ctypedef CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 ExternalMemoryHandleDesc_v1 +ctypedef CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 ExternalSemaphoreHandleDesc_v1 +ctypedef CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 ExternalSemaphoreSignalParams_v1 +ctypedef CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 ExternalSemaphoreWaitParams_v1 +ctypedef CUlaunchAttribute LaunchAttribute +ctypedef CUasyncCallback asyncCallback +ctypedef CUDA_RESOURCE_DESC_v1 ResourceDesc_v1 +ctypedef CUlogicalEndpointProp LogicalEndpointProp +ctypedef CUmemcpy3DOperand_v1 Memcpy3DOperand_v1 +ctypedef CUDA_MEMCPY3D_BATCH_OP_v1 Memcpy3dBatchOp_v1 +ctypedef CUgraphRecaptureCallback graphRecaptureCallback + + +############################################################################### +# Enum +############################################################################### + +ctypedef CUipcMem_flags _IpcMemFlags +ctypedef CUmemAttach_flags _MemAttachFlags +ctypedef CUctx_flags _CtxFlags +ctypedef CUevent_sched_flags _EventSchedFlags +ctypedef CUevent_flags _EventFlags +ctypedef cl_context_flags _ContextFlags +ctypedef CUstream_flags _StreamFlags +ctypedef CUevent_record_flags _EventRecordFlags +ctypedef CUevent_wait_flags _EventWaitFlags +ctypedef CUstreamWaitValue_flags _StreamWaitValueFlags +ctypedef CUstreamWriteValue_flags _StreamWriteValueFlags +ctypedef CUstreamBatchMemOpType _StreamBatchMemOpType +ctypedef CUstreamMemoryBarrier_flags _StreamMemoryBarrierFlags +ctypedef CUoccupancy_flags _OccupancyFlags +ctypedef CUstreamUpdateCaptureDependencies_flags _StreamUpdateCaptureDependenciesFlags +ctypedef CUasyncNotificationType _AsyncNotificationType +ctypedef CUarray_format _ArrayFormat +ctypedef CUaddress_mode _AddressMode +ctypedef CUfilter_mode _FilterMode +ctypedef CUdevice_attribute _DeviceAttribute +ctypedef CUpointer_attribute _PointerAttribute +ctypedef CUfunction_attribute _FunctionAttribute +ctypedef CUfunc_cache _FuncCache +ctypedef CUsharedconfig _Sharedconfig +ctypedef CUshared_carveout _SharedCarveout +ctypedef CUmemorytype _Memorytype +ctypedef CUcomputemode _Computemode +ctypedef CUmem_advise _MemAdvise +ctypedef CUmem_range_attribute _MemRangeAttribute +ctypedef CUjit_option _JitOption +ctypedef CUjit_target _JitTarget +ctypedef CUjit_fallback _JitFallback +ctypedef CUjit_cacheMode _JitCacheMode +ctypedef CUjitInputType _JitInputType +ctypedef CUgraphicsRegisterFlags _GraphicsRegisterFlags +ctypedef CUgraphicsMapResourceFlags _GraphicsMapResourceFlags +ctypedef CUarray_cubemap_face _ArrayCubemapFace +ctypedef CUlimit _Limit +ctypedef CUresourcetype _Resourcetype +ctypedef CUaccessProperty _AccessProperty +ctypedef CUgraphConditionalNodeType _GraphConditionalNodeType +ctypedef CUgraphNodeType _GraphNodeType +ctypedef CUgraphDependencyType _GraphDependencyType +ctypedef CUgraphInstantiateResult _GraphInstantiateResult +ctypedef CUsynchronizationPolicy _SynchronizationPolicy +ctypedef CUclusterSchedulingPolicy _ClusterSchedulingPolicy +ctypedef CUlaunchMemSyncDomain _LaunchMemSyncDomain +ctypedef CUlaunchAttributeID _LaunchAttributeID +ctypedef CUstreamCaptureStatus _StreamCaptureStatus +ctypedef CUstreamCaptureMode _StreamCaptureMode +ctypedef CUdriverProcAddress_flags _DriverProcAddressFlags +ctypedef CUdriverProcAddressQueryResult _DriverProcAddressQueryResult +ctypedef CUexecAffinityType _ExecAffinityType +ctypedef CUcigDataType _CigDataType +ctypedef CUlibraryOption _LibraryOption +ctypedef CUresult _Result +ctypedef CUdevice_P2PAttribute _DeviceP2PAttribute +ctypedef CUresourceViewFormat _ResourceViewFormat +ctypedef CUtensorMapDataType _TensorMapDataType +ctypedef CUtensorMapInterleave _TensorMapInterleave +ctypedef CUtensorMapSwizzle _TensorMapSwizzle +ctypedef CUtensorMapL2promotion _TensorMapL2promotion +ctypedef CUtensorMapFloatOOBfill _TensorMapFloatOOBfill +ctypedef CUtensorMapIm2ColWideMode _TensorMapIm2ColWideMode +ctypedef CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS _PointerAttributeAccessFlags +ctypedef CUexternalMemoryHandleType _ExternalMemoryHandleType +ctypedef CUexternalSemaphoreHandleType _ExternalSemaphoreHandleType +ctypedef CUmemAllocationHandleType _MemAllocationHandleType +ctypedef CUmemAccess_flags _MemAccessFlags +ctypedef CUmemLocationType _MemLocationType +ctypedef CUmemAllocationType _MemAllocationType +ctypedef CUmemAllocationGranularity_flags _MemAllocationGranularityFlags +ctypedef CUmemRangeHandleType _MemRangeHandleType +ctypedef CUmemRangeFlags _MemRangeFlags +ctypedef CUarraySparseSubresourceType _ArraySparseSubresourceType +ctypedef CUmemOperationType _MemOperationType +ctypedef CUmemHandleType _MemHandleType +ctypedef CUmemAllocationCompType _MemAllocationCompType +ctypedef CUmulticastGranularity_flags _MulticastGranularityFlags +ctypedef CUgraphExecUpdateResult _GraphExecUpdateResult +ctypedef CUmemPool_attribute _MemPoolAttribute +ctypedef CUmemcpyFlags _MemcpyFlags +ctypedef CUmemcpySrcAccessOrder _MemcpySrcAccessOrder +ctypedef CUmemcpy3DOperandType _Memcpy3DOperandType +ctypedef CUgraphMem_attribute _GraphMemAttribute +ctypedef CUgraphChildGraphNodeOwnership _GraphChildGraphNodeOwnership +ctypedef CUflushGPUDirectRDMAWritesOptions _FlushGPUDirectRDMAWritesOptions +ctypedef CUGPUDirectRDMAWritesOrdering _GPUDirectRDMAWritesOrdering +ctypedef CUflushGPUDirectRDMAWritesScope _FlushGPUDirectRDMAWritesScope +ctypedef CUflushGPUDirectRDMAWritesTarget _FlushGPUDirectRDMAWritesTarget +ctypedef CUgraphDebugDot_flags _GraphDebugDotFlags +ctypedef CUuserObject_flags _UserObjectFlags +ctypedef CUuserObjectRetain_flags _UserObjectRetainFlags +ctypedef CUgraphInstantiate_flags _GraphInstantiateFlags +ctypedef CUdeviceNumaConfig _DeviceNumaConfig +ctypedef CUprocessState _ProcessState +ctypedef CUmoduleLoadingMode _ModuleLoadingMode +ctypedef CUmemDecompressAlgorithm _MemDecompressAlgorithm +ctypedef CUfunctionLoadingState _FunctionLoadingState +ctypedef CUcoredumpSettings _CoredumpSettings +ctypedef CUCoredumpGenerationFlags _CoredumpGenerationFlags +ctypedef CUgreenCtxCreate_flags _GreenCtxCreateFlags +ctypedef CUdevResourceType _DevResourceType +ctypedef CUlogLevel _LogLevel +ctypedef CUeglFrameType _EglFrameType +ctypedef CUeglResourceLocationFlags _EglResourceLocationFlags +ctypedef CUeglColorFormat _EglColorFormat +ctypedef CUGLmap_flags _GLmapFlags +ctypedef CUoutput_mode _OutputMode +ctypedef CUatomicOperation _AtomicOperation +ctypedef CUatomicOperationCapability _AtomicOperationCapability +ctypedef CUstreamAtomicReductionOpType _StreamAtomicReductionOpType +ctypedef CUstreamAtomicReductionDataType _StreamAtomicReductionDataType +ctypedef CUdevSmResourceGroup_flags _DevSmResourceGroupFlags +ctypedef CUdevSmResourceSplitByCount_flags _DevSmResourceSplitByCountFlags +ctypedef CUdevWorkqueueConfigScope _DevWorkqueueConfigScope +ctypedef CUhostTaskSyncMode _HostTaskSyncMode +ctypedef CUlaunchAttributePortableClusterMode _LaunchAttributePortableClusterMode +ctypedef CUsharedMemoryMode _SharedMemoryMode +ctypedef CUstreamCigDataType _StreamCigDataType +ctypedef CUlogicalEndpointIpcHandleType _LogicalEndpointIpcHandleType +ctypedef CUlogicalEndpointType _LogicalEndpointType +ctypedef CUlogicalEndpointFlag _LogicalEndpointFlag +ctypedef CUgraphRecaptureStatus _GraphRecaptureStatus + + +############################################################################### +# Functions +############################################################################### + +cpdef str get_error_string(int error) +cpdef str get_error_name(int error) +cpdef object device_get_host_atomic_capabilities(object operations, int dev) +cpdef tuple graph_get_edges(intptr_t h_graph) +cpdef tuple graph_node_get_dependencies(intptr_t h_node) +cpdef tuple graph_node_get_dependent_nodes(intptr_t h_node) +cpdef egl_stream_producer_present_frame(intptr_t conn, intptr_t eglframe, intptr_t p_stream) +cpdef egl_stream_producer_return_frame(intptr_t conn, intptr_t eglframe, intptr_t p_stream) +cpdef graphics_resource_get_mapped_egl_frame(intptr_t egl_frame, intptr_t resource, unsigned int index, unsigned int mip_level) +cpdef intptr_t device_get_nv_sci_sync_attributes(intptr_t nv_sci_sync_attr_list, int dev, int flags) +cpdef object gl_get_devices_v2(int device_list) +cpdef launch_kernel(intptr_t f, unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, unsigned int block_dim_x, unsigned int block_dim_y, unsigned int block_dim_z, unsigned int shared_mem_bytes, intptr_t h_stream, kernel_params, intptr_t extra) +cpdef launch_kernel_ex(config, intptr_t f, kernel_params, intptr_t extra) +cpdef launch_cooperative_kernel(intptr_t f, unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, unsigned int block_dim_x, unsigned int block_dim_y, unsigned int block_dim_z, unsigned int shared_mem_bytes, intptr_t h_stream, kernel_params) + +cpdef init(unsigned int flags) +cpdef int driver_get_version() except? -1 +cpdef int device_get(int ordinal) except? -1 +cpdef int device_get_count() except? -1 +cpdef bytes device_get_name(int len, int dev) +cpdef object device_get_uuid_v2(int dev) +cpdef tuple device_get_luid(int dev) +cpdef size_t device_total_mem_v2(int dev) except? 0 +cpdef size_t device_get_texture_1d_linear_max_width(int format, unsigned num_channels, int dev) except? 0 +cpdef int device_get_attribute(int attrib, int dev) except? -1 +cpdef device_set_mem_pool(int dev, intptr_t pool) +cpdef intptr_t device_get_mem_pool(int dev) except? 0 +cpdef intptr_t device_get_default_mem_pool(int dev) except? 0 +cpdef int device_get_exec_affinity_support(int type, int dev) except? -1 +cpdef flush_gpu_direct_rdma_writes(int target, int scope) +cpdef object device_get_properties(int dev) +cpdef tuple device_compute_capability(int dev) +cpdef intptr_t device_primary_ctx_retain(int dev) except? 0 +cpdef device_primary_ctx_release_v2(int dev) +cpdef device_primary_ctx_set_flags_v2(int dev, unsigned int flags) +cpdef tuple device_primary_ctx_get_state(int dev) +cpdef device_primary_ctx_reset_v2(int dev) +cpdef intptr_t ctx_create_v2(unsigned int flags, int dev) except? 0 +cpdef intptr_t ctx_create_v3(params_array, int num_params, unsigned int flags, int dev) except? 0 +cpdef intptr_t ctx_create_v4(ctx_create_params, unsigned int flags, int dev) except? 0 +cpdef ctx_destroy_v2(intptr_t ctx) +cpdef ctx_push_current_v2(intptr_t ctx) +cpdef intptr_t ctx_pop_current_v2() except? 0 +cpdef ctx_set_current(intptr_t ctx) +cpdef intptr_t ctx_get_current() except? 0 +cpdef int ctx_get_device() except? -1 +cpdef unsigned int ctx_get_flags() except? 0 +cpdef ctx_set_flags(unsigned int flags) +cpdef unsigned long long ctx_get_id(intptr_t ctx) except? 0 +cpdef ctx_synchronize() +cpdef ctx_set_limit(int limit, size_t value) +cpdef size_t ctx_get_limit(int limit) except? 0 +cpdef int ctx_get_cache_config() except? -1 +cpdef ctx_set_cache_config(int config) +cpdef unsigned int ctx_get_api_version(intptr_t ctx) except? 0 +cpdef tuple ctx_get_stream_priority_range() +cpdef ctx_reset_persisting_l2cache() +cpdef object ctx_get_exec_affinity(int type) +cpdef ctx_record_event(intptr_t h_ctx, intptr_t h_event) +cpdef ctx_wait_event(intptr_t h_ctx, intptr_t h_event) +cpdef intptr_t ctx_attach(unsigned int flags) except? 0 +cpdef ctx_detach(intptr_t ctx) +cpdef int ctx_get_shared_mem_config() except? -1 +cpdef ctx_set_shared_mem_config(int config) +cpdef intptr_t module_load(fname) except? 0 +cpdef intptr_t module_load_data(image) except? 0 +cpdef intptr_t module_load_data_ex(image, unsigned int num_options, intptr_t options, intptr_t option_values) except? 0 +cpdef intptr_t module_load_fat_binary(fat_cubin) except? 0 +cpdef module_unload(intptr_t hmod) +cpdef int module_get_loading_mode() except? -1 +cpdef intptr_t module_get_function(intptr_t hmod, name) except? 0 +cpdef unsigned int module_get_function_count(intptr_t mod) except? 0 +cpdef object module_enumerate_functions(intptr_t mod) +cpdef tuple module_get_global_v2(intptr_t hmod, name) +cpdef intptr_t link_create_v2(unsigned int num_options, intptr_t options, intptr_t option_values) except? 0 +cpdef link_add_data_v2(intptr_t state, int type, intptr_t data, size_t size, name, unsigned int num_options, intptr_t options, intptr_t option_values) +cpdef link_add_file_v2(intptr_t state, int type, path, unsigned int num_options, intptr_t options, intptr_t option_values) +cpdef bytes link_complete(intptr_t state) +cpdef link_destroy(intptr_t state) +cpdef intptr_t module_get_tex_ref(intptr_t hmod, name) except? 0 +cpdef intptr_t module_get_surf_ref(intptr_t hmod, name) except? 0 +cpdef intptr_t library_load_data(code, intptr_t jit_options, intptr_t jit_options_values, unsigned int num_jit_options, intptr_t library_options, intptr_t library_option_values, unsigned int num_library_options) except? 0 +cpdef intptr_t library_load_from_file(file_name, intptr_t jit_options, intptr_t jit_options_values, unsigned int num_jit_options, intptr_t library_options, intptr_t library_option_values, unsigned int num_library_options) except? 0 +cpdef library_unload(intptr_t library) +cpdef intptr_t library_get_kernel(intptr_t library, name) except? 0 +cpdef unsigned int library_get_kernel_count(intptr_t lib) except? 0 +cpdef object library_enumerate_kernels(intptr_t lib) +cpdef intptr_t library_get_module(intptr_t library) except? 0 +cpdef intptr_t kernel_get_function(intptr_t kernel) except? 0 +cpdef intptr_t kernel_get_library(intptr_t kernel) except? 0 +cpdef tuple library_get_global(intptr_t library, name) +cpdef tuple library_get_managed(intptr_t library, name) +cpdef intptr_t library_get_unified_function(intptr_t library, symbol) except? 0 +cpdef int kernel_get_attribute(int attrib, intptr_t kernel, int dev) except? -1 +cpdef kernel_set_attribute(int attrib, int val, intptr_t kernel, int dev) +cpdef kernel_set_cache_config(intptr_t kernel, int config, int dev) +cpdef tuple kernel_get_param_info(intptr_t kernel, size_t param_index) +cpdef tuple mem_get_info_v2() +cpdef unsigned long long mem_alloc_v2(size_t bytesize) except? 0 +cpdef tuple mem_alloc_pitch_v2(size_t width_in_bytes, size_t height, unsigned int element_size_bytes) +cpdef mem_free_v2(unsigned long long dptr) +cpdef tuple mem_get_address_range_v2(unsigned long long dptr) +cpdef intptr_t mem_alloc_host_v2(size_t bytesize) except? 0 +cpdef mem_free_host(p) +cpdef intptr_t mem_host_alloc(size_t bytesize, unsigned int flags) except? 0 +cpdef unsigned long long mem_host_get_device_pointer_v2(intptr_t p, unsigned int flags) except? 0 +cpdef unsigned int mem_host_get_flags(intptr_t p) except? 0 +cpdef unsigned long long mem_alloc_managed(size_t bytesize, unsigned int flags) except? 0 +cpdef intptr_t device_register_async_notification(int device, intptr_t callback_func, intptr_t user_data) except? 0 +cpdef device_unregister_async_notification(int device, intptr_t callback) +cpdef int device_get_by_pci_bus_id(pci_bus_id) except? -1 +cpdef bytes device_get_pci_bus_id(int len, int dev) +cpdef object ipc_get_event_handle(intptr_t event) +cpdef intptr_t ipc_open_event_handle(handle) except? 0 +cpdef object ipc_get_mem_handle(unsigned long long dptr) +cpdef unsigned long long ipc_open_mem_handle_v2(handle, unsigned int flags) except? 0 +cpdef ipc_close_mem_handle(unsigned long long dptr) +cpdef mem_host_register_v2(p, size_t bytesize, unsigned int flags) +cpdef mem_host_unregister(p) +cpdef cu_memcpy(unsigned long long dst, unsigned long long src, size_t byte_count) +cpdef memcpy_peer(unsigned long long dst_device, intptr_t dst_context, unsigned long long src_device, intptr_t src_context, size_t byte_count) +cpdef memcpy_htod_v2(unsigned long long dst_device, src_host, size_t byte_count) +cpdef memcpy_dtoh_v2(dst_host, unsigned long long src_device, size_t byte_count) +cpdef memcpy_dtod_v2(unsigned long long dst_device, unsigned long long src_device, size_t byte_count) +cpdef memcpy_dtoa_v2(intptr_t dst_array, size_t dst_offset, unsigned long long src_device, size_t byte_count) +cpdef memcpy_atod_v2(unsigned long long dst_device, intptr_t src_array, size_t src_offset, size_t byte_count) +cpdef memcpy_htoa_v2(intptr_t dst_array, size_t dst_offset, src_host, size_t byte_count) +cpdef memcpy_atoh_v2(dst_host, intptr_t src_array, size_t src_offset, size_t byte_count) +cpdef memcpy_atoa_v2(intptr_t dst_array, size_t dst_offset, intptr_t src_array, size_t src_offset, size_t byte_count) +cpdef memcpy_2d_v2(p_copy) +cpdef memcpy_2d_unaligned_v2(p_copy) +cpdef memcpy_3d_v2(p_copy) +cpdef memcpy_3d_peer(p_copy) +cpdef memcpy_async(unsigned long long dst, unsigned long long src, size_t byte_count, intptr_t h_stream) +cpdef memcpy_peer_async(unsigned long long dst_device, intptr_t dst_context, unsigned long long src_device, intptr_t src_context, size_t byte_count, intptr_t h_stream) +cpdef memcpy_htod_async_v2(unsigned long long dst_device, src_host, size_t byte_count, intptr_t h_stream) +cpdef memcpy_dtoh_async_v2(dst_host, unsigned long long src_device, size_t byte_count, intptr_t h_stream) +cpdef memcpy_dtod_async_v2(unsigned long long dst_device, unsigned long long src_device, size_t byte_count, intptr_t h_stream) +cpdef memcpy_htoa_async_v2(intptr_t dst_array, size_t dst_offset, src_host, size_t byte_count, intptr_t h_stream) +cpdef memcpy_atoh_async_v2(dst_host, intptr_t src_array, size_t src_offset, size_t byte_count, intptr_t h_stream) +cpdef memcpy_2d_async_v2(p_copy, intptr_t h_stream) +cpdef memcpy_3d_async_v2(p_copy, intptr_t h_stream) +cpdef memcpy_3d_peer_async(p_copy, intptr_t h_stream) +cpdef memset_d8_v2(unsigned long long dst_device, unsigned char uc, size_t n) +cpdef memset_d16_v2(unsigned long long dst_device, unsigned short us, size_t n) +cpdef memset_d32_v2(unsigned long long dst_device, unsigned int ui, size_t n) +cpdef memset_d2d8_v2(unsigned long long dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height) +cpdef memset_d2d16_v2(unsigned long long dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height) +cpdef memset_d2d32_v2(unsigned long long dst_device, size_t dst_pitch, unsigned int ui, size_t width, size_t height) +cpdef memset_d8_async(unsigned long long dst_device, unsigned char uc, size_t n, intptr_t h_stream) +cpdef memset_d16_async(unsigned long long dst_device, unsigned short us, size_t n, intptr_t h_stream) +cpdef memset_d32_async(unsigned long long dst_device, unsigned int ui, size_t n, intptr_t h_stream) +cpdef memset_d2d8_async(unsigned long long dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height, intptr_t h_stream) +cpdef memset_d2d16_async(unsigned long long dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height, intptr_t h_stream) +cpdef memset_d2d32_async(unsigned long long dst_device, size_t dst_pitch, unsigned int ui, size_t width, size_t height, intptr_t h_stream) +cpdef intptr_t array_create_v2(p_allocate_array) except? 0 +cpdef object array_get_descriptor_v2(intptr_t h_array) +cpdef object array_get_sparse_properties(intptr_t array) +cpdef object mipmapped_array_get_sparse_properties(intptr_t mipmap) +cpdef object array_get_memory_requirements(intptr_t array, int device) +cpdef object mipmapped_array_get_memory_requirements(intptr_t mipmap, int device) +cpdef intptr_t array_get_plane(intptr_t h_array, unsigned int plane_idx) except? 0 +cpdef array_destroy(intptr_t h_array) +cpdef intptr_t array_3d_create_v2(p_allocate_array) except? 0 +cpdef object array_3d_get_descriptor_v2(intptr_t h_array) +cpdef intptr_t mipmapped_array_create(p_mipmapped_array_desc, unsigned int num_mipmap_levels) except? 0 +cpdef intptr_t mipmapped_array_get_level(intptr_t h_mipmapped_array, unsigned int level) except? 0 +cpdef mipmapped_array_destroy(intptr_t h_mipmapped_array) +cpdef mem_get_handle_for_address_range(intptr_t handle, unsigned long long dptr, size_t size, int handle_type, unsigned long long flags) +cpdef mem_batch_decompress_async(params_array, size_t count, unsigned int flags, intptr_t error_index, intptr_t stream) +cpdef unsigned long long mem_address_reserve(size_t size, size_t alignment, unsigned long long addr, unsigned long long flags) except? 0 +cpdef mem_address_free(unsigned long long ptr, size_t size) +cpdef unsigned long long mem_create(size_t size, prop, unsigned long long flags) except? 0 +cpdef mem_release(unsigned long long handle) +cpdef mem_map(unsigned long long ptr, size_t size, size_t offset, unsigned long long handle, unsigned long long flags) +cpdef mem_map_array_async(map_info_list, unsigned int count, intptr_t h_stream) +cpdef mem_unmap(unsigned long long ptr, size_t size) +cpdef mem_set_access(unsigned long long ptr, size_t size, desc, size_t count) +cpdef unsigned long long mem_get_access(location, unsigned long long ptr) except? 0 +cpdef mem_export_to_shareable_handle(intptr_t shareable_handle, unsigned long long handle, int handle_type, unsigned long long flags) +cpdef unsigned long long mem_import_from_shareable_handle(intptr_t os_handle, int sh_handle_type) except? 0 +cpdef size_t mem_get_allocation_granularity(prop, int option) except? 0 +cpdef mem_get_allocation_properties_from_handle(prop, unsigned long long handle) +cpdef unsigned long long mem_retain_allocation_handle(intptr_t addr) except? 0 +cpdef mem_free_async(unsigned long long dptr, intptr_t h_stream) +cpdef unsigned long long mem_alloc_async(size_t bytesize, intptr_t h_stream) except? 0 +cpdef mem_pool_trim_to(intptr_t pool, size_t min_bytes_to_keep) +cpdef mem_pool_set_attribute(intptr_t pool, int attr, intptr_t value) +cpdef mem_pool_get_attribute(intptr_t pool, int attr, intptr_t value) +cpdef mem_pool_set_access(intptr_t pool, map, size_t count) +cpdef int mem_pool_get_access(intptr_t mem_pool, location) except? 0 +cpdef intptr_t mem_pool_create(pool_props) except? 0 +cpdef mem_pool_destroy(intptr_t pool) +cpdef unsigned long long mem_alloc_from_pool_async(size_t bytesize, intptr_t pool, intptr_t h_stream) except? 0 +cpdef mem_pool_export_to_shareable_handle(intptr_t handle_out, intptr_t pool, int handle_type, unsigned long long flags) +cpdef intptr_t mem_pool_import_from_shareable_handle(intptr_t handle, int handle_type, unsigned long long flags) except? 0 +cpdef object mem_pool_export_pointer(unsigned long long ptr) +cpdef unsigned long long mem_pool_import_pointer(intptr_t pool, share_data) except? 0 +cpdef unsigned long long multicast_create(prop) except? 0 +cpdef multicast_add_device(unsigned long long mc_handle, int dev) +cpdef multicast_bind_mem(unsigned long long mc_handle, size_t mc_offset, unsigned long long mem_handle, size_t mem_offset, size_t size, unsigned long long flags) +cpdef multicast_bind_addr(unsigned long long mc_handle, size_t mc_offset, unsigned long long memptr, size_t size, unsigned long long flags) +cpdef multicast_unbind(unsigned long long mc_handle, int dev, size_t mc_offset, size_t size) +cpdef size_t multicast_get_granularity(prop, int option) except? 0 +cpdef pointer_get_attribute(intptr_t data, int attribute, unsigned long long ptr) +cpdef mem_prefetch_async_v2(unsigned long long dev_ptr, size_t count, location, unsigned int flags, intptr_t h_stream) +cpdef mem_advise_v2(unsigned long long dev_ptr, size_t count, int advice, location) +cpdef mem_range_get_attribute(intptr_t data, size_t data_size, int attribute, unsigned long long dev_ptr, size_t count) +cpdef mem_range_get_attributes(intptr_t data, intptr_t data_sizes, intptr_t attributes, size_t num_attributes, unsigned long long dev_ptr, size_t count) +cpdef pointer_set_attribute(value, int attribute, unsigned long long ptr) +cpdef pointer_get_attributes(unsigned int num_attributes, intptr_t attributes, intptr_t data, unsigned long long ptr) +cpdef intptr_t stream_create(unsigned int flags) except? 0 +cpdef intptr_t stream_create_with_priority(unsigned int flags, int priority) except? 0 +cpdef int stream_get_priority(intptr_t h_stream) except? -1 +cpdef int stream_get_device(intptr_t h_stream) except? -1 +cpdef unsigned int stream_get_flags(intptr_t h_stream) except? 0 +cpdef unsigned long long stream_get_id(intptr_t h_stream) except? 0 +cpdef intptr_t stream_get_ctx(intptr_t h_stream) except? 0 +cpdef tuple stream_get_ctx_v2(intptr_t h_stream) +cpdef stream_wait_event(intptr_t h_stream, intptr_t h_event, unsigned int flags) +cpdef stream_add_callback(intptr_t h_stream, intptr_t callback, intptr_t user_data, unsigned int flags) +cpdef stream_begin_capture_v2(intptr_t h_stream, int mode) +cpdef stream_begin_capture_to_graph(intptr_t h_stream, intptr_t h_graph, intptr_t dependencies, dependency_data, size_t num_dependencies, int mode) +cpdef int thread_exchange_stream_capture_mode() except? -1 +cpdef intptr_t stream_end_capture(intptr_t h_stream) except? 0 +cpdef int stream_is_capturing(intptr_t h_stream) except? -1 +cpdef tuple stream_get_capture_info_v2(intptr_t h_stream) +cpdef tuple stream_get_capture_info_v3(intptr_t h_stream) +cpdef stream_update_capture_dependencies_v2(intptr_t h_stream, intptr_t dependencies, dependency_data, size_t num_dependencies, unsigned int flags) +cpdef stream_attach_mem_async(intptr_t h_stream, unsigned long long dptr, size_t length, unsigned int flags) +cpdef stream_query(intptr_t h_stream) +cpdef stream_synchronize(intptr_t h_stream) +cpdef stream_destroy_v2(intptr_t h_stream) +cpdef stream_copy_attributes(intptr_t dst, intptr_t src) +cpdef stream_get_attribute(intptr_t h_stream, int attr, intptr_t value_out) +cpdef stream_set_attribute(intptr_t h_stream, int attr, intptr_t value) +cpdef intptr_t event_create(unsigned int flags) except? 0 +cpdef event_record(intptr_t h_event, intptr_t h_stream) +cpdef event_record_with_flags(intptr_t h_event, intptr_t h_stream, unsigned int flags) +cpdef event_query(intptr_t h_event) +cpdef event_synchronize(intptr_t h_event) +cpdef event_destroy_v2(intptr_t h_event) +cpdef float event_elapsed_time_v2(intptr_t h_start, intptr_t h_end) except? -1.0 +cpdef intptr_t import_external_memory(intptr_t mem_handle_desc) except? 0 +cpdef unsigned long long external_memory_get_mapped_buffer(intptr_t ext_mem, buffer_desc) except? 0 +cpdef intptr_t external_memory_get_mapped_mipmapped_array(intptr_t ext_mem, intptr_t mipmap_desc) except? 0 +cpdef destroy_external_memory(intptr_t ext_mem) +cpdef intptr_t import_external_semaphore(intptr_t sem_handle_desc) except? 0 +cpdef signal_external_semaphores_async(intptr_t ext_sem_array, intptr_t params_array, unsigned int num_ext_sems, intptr_t stream) +cpdef wait_external_semaphores_async(intptr_t ext_sem_array, intptr_t params_array, unsigned int num_ext_sems, intptr_t stream) +cpdef destroy_external_semaphore(intptr_t ext_sem) +cpdef stream_wait_value32_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags) +cpdef stream_wait_value64_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags) +cpdef stream_write_value32_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags) +cpdef stream_write_value64_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags) +cpdef stream_batch_mem_op_v2(intptr_t stream, unsigned int count, param_array, unsigned int flags) +cpdef int func_get_attribute(int attrib, intptr_t hfunc) except? -1 +cpdef func_set_attribute(intptr_t hfunc, int attrib, int value) +cpdef func_set_cache_config(intptr_t hfunc, int config) +cpdef intptr_t func_get_module(intptr_t hfunc) except? 0 +cpdef tuple func_get_param_info(intptr_t func, size_t param_index) +cpdef int func_is_loaded(intptr_t function) except? -1 +cpdef func_load(intptr_t function) +cpdef launch_cooperative_kernel_multi_device(launch_params_list, unsigned int num_devices, unsigned int flags) +cpdef launch_host_func(intptr_t h_stream, intptr_t fn, intptr_t user_data) +cpdef func_set_block_shape(intptr_t hfunc, int x, int y, int z) +cpdef func_set_shared_size(intptr_t hfunc, unsigned int bytes) +cpdef param_set_size(intptr_t hfunc, unsigned int numbytes) +cpdef param_seti(intptr_t hfunc, int offset, unsigned int value) +cpdef param_setf(intptr_t hfunc, int offset, float value) +cpdef param_setv(intptr_t hfunc, int offset, intptr_t ptr, unsigned int numbytes) +cpdef launch(intptr_t f) +cpdef launch_grid(intptr_t f, int grid_width, int grid_height) +cpdef launch_grid_async(intptr_t f, int grid_width, int grid_height, intptr_t h_stream) +cpdef param_set_tex_ref(intptr_t hfunc, int texunit, intptr_t h_tex_ref) +cpdef func_set_shared_mem_config(intptr_t hfunc, int config) +cpdef intptr_t graph_create(unsigned int flags) except? 0 +cpdef intptr_t graph_add_kernel_node_v2(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_kernel_node_get_params_v2(intptr_t h_node, node_params) +cpdef graph_kernel_node_set_params_v2(intptr_t h_node, node_params) +cpdef intptr_t graph_add_memcpy_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, copy_params, intptr_t ctx) except? 0 +cpdef graph_memcpy_node_get_params(intptr_t h_node, node_params) +cpdef graph_memcpy_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_memset_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, memset_params, intptr_t ctx) except? 0 +cpdef object graph_memset_node_get_params(intptr_t h_node) +cpdef graph_memset_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_host_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_host_node_get_params(intptr_t h_node, node_params) +cpdef graph_host_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_child_graph_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t child_graph) except? 0 +cpdef intptr_t graph_child_graph_node_get_graph(intptr_t h_node) except? 0 +cpdef intptr_t graph_add_empty_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies) except? 0 +cpdef intptr_t graph_add_event_record_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t event) except? 0 +cpdef intptr_t graph_event_record_node_get_event(intptr_t h_node) except? 0 +cpdef graph_event_record_node_set_event(intptr_t h_node, intptr_t event) +cpdef intptr_t graph_add_event_wait_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t event) except? 0 +cpdef intptr_t graph_event_wait_node_get_event(intptr_t h_node) except? 0 +cpdef graph_event_wait_node_set_event(intptr_t h_node, intptr_t event) +cpdef intptr_t graph_add_external_semaphores_signal_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_external_semaphores_signal_node_get_params(intptr_t h_node, params_out) +cpdef graph_external_semaphores_signal_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_external_semaphores_wait_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_external_semaphores_wait_node_get_params(intptr_t h_node, params_out) +cpdef graph_external_semaphores_wait_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_batch_mem_op_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_batch_mem_op_node_get_params(intptr_t h_node, node_params_out) +cpdef graph_batch_mem_op_node_set_params(intptr_t h_node, node_params) +cpdef graph_exec_batch_mem_op_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef intptr_t graph_add_mem_alloc_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0 +cpdef graph_mem_alloc_node_get_params(intptr_t h_node, params_out) +cpdef intptr_t graph_add_mem_free_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, unsigned long long dptr) except? 0 +cpdef unsigned long long graph_mem_free_node_get_params(intptr_t h_node) except? 0 +cpdef device_graph_mem_trim(int device) +cpdef device_get_graph_mem_attribute(int device, int attr, intptr_t value) +cpdef device_set_graph_mem_attribute(int device, int attr, intptr_t value) +cpdef intptr_t graph_clone(intptr_t original_graph) except? 0 +cpdef intptr_t graph_node_find_in_clone(intptr_t h_original_node, intptr_t h_cloned_graph) except? 0 +cpdef int graph_node_get_type(intptr_t h_node) except? -1 +cpdef object graph_get_nodes(intptr_t h_graph) +cpdef object graph_get_root_nodes(intptr_t h_graph) +cpdef tuple graph_get_edges_v2(intptr_t h_graph) +cpdef tuple graph_node_get_dependencies_v2(intptr_t h_node) +cpdef tuple graph_node_get_dependent_nodes_v2(intptr_t h_node) +cpdef graph_add_dependencies_v2(intptr_t h_graph, intptr_t from_, intptr_t to, edge_data, size_t num_dependencies) +cpdef graph_remove_dependencies_v2(intptr_t h_graph, intptr_t from_, intptr_t to, edge_data, size_t num_dependencies) +cpdef graph_destroy_node(intptr_t h_node) +cpdef intptr_t graph_instantiate_with_flags(intptr_t h_graph, unsigned long long flags) except? 0 +cpdef intptr_t graph_instantiate_with_params(intptr_t h_graph, instantiate_params) except? 0 +cpdef uint64_t graph_exec_get_flags(intptr_t h_graph_exec) except? 0 +cpdef graph_exec_kernel_node_set_params_v2(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef graph_exec_memcpy_node_set_params(intptr_t h_graph_exec, intptr_t h_node, copy_params, intptr_t ctx) +cpdef graph_exec_memset_node_set_params(intptr_t h_graph_exec, intptr_t h_node, memset_params, intptr_t ctx) +cpdef graph_exec_host_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef graph_exec_child_graph_node_set_params(intptr_t h_graph_exec, intptr_t h_node, intptr_t child_graph) +cpdef graph_exec_event_record_node_set_event(intptr_t h_graph_exec, intptr_t h_node, intptr_t event) +cpdef graph_exec_event_wait_node_set_event(intptr_t h_graph_exec, intptr_t h_node, intptr_t event) +cpdef graph_exec_external_semaphores_signal_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef graph_exec_external_semaphores_wait_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef graph_node_set_enabled(intptr_t h_graph_exec, intptr_t h_node, unsigned int is_enabled) +cpdef unsigned int graph_node_get_enabled(intptr_t h_graph_exec, intptr_t h_node) except? 0 +cpdef graph_upload(intptr_t h_graph_exec, intptr_t h_stream) +cpdef graph_launch(intptr_t h_graph_exec, intptr_t h_stream) +cpdef graph_exec_destroy(intptr_t h_graph_exec) +cpdef graph_destroy(intptr_t h_graph) +cpdef graph_exec_update_v2(intptr_t h_graph_exec, intptr_t h_graph, result_info) +cpdef graph_kernel_node_copy_attributes(intptr_t dst, intptr_t src) +cpdef graph_kernel_node_get_attribute(intptr_t h_node, int attr, intptr_t value_out) +cpdef graph_kernel_node_set_attribute(intptr_t h_node, int attr, intptr_t value) +cpdef graph_debug_dot_print(intptr_t h_graph, path, unsigned int flags) +cpdef intptr_t user_object_create(ptr, intptr_t destroy, unsigned int initial_refcount, unsigned int flags) except? 0 +cpdef user_object_retain(intptr_t object, unsigned int count) +cpdef user_object_release(intptr_t object, unsigned int count) +cpdef graph_retain_user_object(intptr_t graph, intptr_t object, unsigned int count, unsigned int flags) +cpdef graph_release_user_object(intptr_t graph, intptr_t object, unsigned int count) +cpdef intptr_t graph_add_node_v2(intptr_t h_graph, intptr_t dependencies, dependency_data, size_t num_dependencies, node_params) except? 0 +cpdef graph_node_set_params(intptr_t h_node, node_params) +cpdef graph_exec_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params) +cpdef uint64_t graph_conditional_handle_create(intptr_t h_graph, intptr_t ctx, unsigned int default_launch_value, unsigned int flags) except? 0 +cpdef int occupancy_max_active_blocks_per_multiprocessor(intptr_t func, int block_size, size_t dynamic_s_mem_size) except? -1 +cpdef int occupancy_max_active_blocks_per_multiprocessor_with_flags(intptr_t func, int block_size, size_t dynamic_s_mem_size, unsigned int flags) except? -1 +cpdef tuple occupancy_max_potential_block_size(intptr_t func, intptr_t block_size_to_dynamic_s_mem_size, size_t dynamic_s_mem_size, int block_size_limit) +cpdef tuple occupancy_max_potential_block_size_with_flags(intptr_t func, intptr_t block_size_to_dynamic_s_mem_size, size_t dynamic_s_mem_size, int block_size_limit, unsigned int flags) +cpdef size_t occupancy_available_dynamic_smem_per_block(intptr_t func, int num_blocks, int block_size) except? 0 +cpdef int occupancy_max_potential_cluster_size(intptr_t func, config) except? -1 +cpdef int occupancy_max_active_clusters(intptr_t func, config) except? -1 +cpdef tex_ref_set_array(intptr_t h_tex_ref, intptr_t h_array, unsigned int flags) +cpdef tex_ref_set_mipmapped_array(intptr_t h_tex_ref, intptr_t h_mipmapped_array, unsigned int flags) +cpdef size_t tex_ref_set_address_v2(intptr_t h_tex_ref, unsigned long long dptr, size_t bytes) except? 0 +cpdef tex_ref_set_address2d_v3(intptr_t h_tex_ref, desc, unsigned long long dptr, size_t pitch) +cpdef tex_ref_set_format(intptr_t h_tex_ref, int fmt, int num_packed_components) +cpdef tex_ref_set_address_mode(intptr_t h_tex_ref, int dim, int am) +cpdef tex_ref_set_filter_mode(intptr_t h_tex_ref, int fm) +cpdef tex_ref_set_mipmap_filter_mode(intptr_t h_tex_ref, int fm) +cpdef tex_ref_set_mipmap_level_bias(intptr_t h_tex_ref, float bias) +cpdef tex_ref_set_mipmap_level_clamp(intptr_t h_tex_ref, float min_mipmap_level_clamp, float max_mipmap_level_clamp) +cpdef tex_ref_set_max_anisotropy(intptr_t h_tex_ref, unsigned int max_aniso) +cpdef tex_ref_set_border_color(intptr_t h_tex_ref, intptr_t p_border_color) +cpdef tex_ref_set_flags(intptr_t h_tex_ref, unsigned int flags) +cpdef unsigned long long tex_ref_get_address_v2(intptr_t h_tex_ref) except? 0 +cpdef intptr_t tex_ref_get_array(intptr_t h_tex_ref) except? 0 +cpdef intptr_t tex_ref_get_mipmapped_array(intptr_t h_tex_ref) except? 0 +cpdef int tex_ref_get_address_mode(intptr_t h_tex_ref, int dim) except? -1 +cpdef int tex_ref_get_filter_mode(intptr_t h_tex_ref) except? -1 +cpdef tuple tex_ref_get_format(intptr_t h_tex_ref) +cpdef int tex_ref_get_mipmap_filter_mode(intptr_t h_tex_ref) except? -1 +cpdef float tex_ref_get_mipmap_level_bias(intptr_t h_tex_ref) except? -1.0 +cpdef tuple tex_ref_get_mipmap_level_clamp(intptr_t h_tex_ref) +cpdef int tex_ref_get_max_anisotropy(intptr_t h_tex_ref) except? -1 +cpdef tex_ref_get_border_color(intptr_t p_border_color, intptr_t h_tex_ref) +cpdef unsigned int tex_ref_get_flags(intptr_t h_tex_ref) except? 0 +cpdef intptr_t tex_ref_create() except? 0 +cpdef tex_ref_destroy(intptr_t h_tex_ref) +cpdef surf_ref_set_array(intptr_t h_surf_ref, intptr_t h_array, unsigned int flags) +cpdef intptr_t surf_ref_get_array(intptr_t h_surf_ref) except? 0 +cpdef unsigned long long tex_object_create(intptr_t p_res_desc, p_tex_desc, p_res_view_desc) except? 0 +cpdef tex_object_destroy(unsigned long long tex_object) +cpdef tex_object_get_resource_desc(intptr_t p_res_desc, unsigned long long tex_object) +cpdef tex_object_get_texture_desc(p_tex_desc, unsigned long long tex_object) +cpdef object tex_object_get_resource_view_desc(unsigned long long tex_object) +cpdef unsigned long long surf_object_create(intptr_t p_res_desc) except? 0 +cpdef surf_object_destroy(unsigned long long surf_object) +cpdef surf_object_get_resource_desc(intptr_t p_res_desc, unsigned long long surf_object) +cpdef tensor_map_encode_tiled(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, intptr_t box_dim, intptr_t element_strides, int interleave, int swizzle, int l2promotion, int oob_fill) +cpdef tensor_map_encode_im2col(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, intptr_t pixel_box_lower_corner, intptr_t pixel_box_upper_corner, uint64_t channels_per_pixel, uint64_t pixels_per_column, intptr_t element_strides, int interleave, int swizzle, int l2promotion, int oob_fill) +cpdef tensor_map_encode_im2col_wide(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, int pixel_box_lower_corner_width, int pixel_box_upper_corner_width, uint64_t channels_per_pixel, uint64_t pixels_per_column, intptr_t element_strides, int interleave, int mode, int swizzle, int l2promotion, int oob_fill) +cpdef tensor_map_replace_address(tensor_map, intptr_t global_address) +cpdef int device_can_access_peer(int dev, int peer_dev) except? -1 +cpdef ctx_enable_peer_access(intptr_t peer_context, unsigned int flags) +cpdef ctx_disable_peer_access(intptr_t peer_context) +cpdef int device_get_p2p_attribute(int attrib, int src_device, int dst_device) except? -1 +cpdef graphics_unregister_resource(intptr_t resource) +cpdef intptr_t graphics_sub_resource_get_mapped_array(intptr_t resource, unsigned int array_index, unsigned int mip_level) except? 0 +cpdef intptr_t graphics_resource_get_mapped_mipmapped_array(intptr_t resource) except? 0 +cpdef tuple graphics_resource_get_mapped_pointer_v2(intptr_t resource) +cpdef graphics_resource_set_map_flags_v2(intptr_t resource, unsigned int flags) +cpdef graphics_map_resources(unsigned int count, intptr_t resources, intptr_t h_stream) +cpdef graphics_unmap_resources(unsigned int count, intptr_t resources, intptr_t h_stream) +cpdef get_proc_address_v2(symbol, intptr_t pfn, int cuda_version, uint64_t flags, intptr_t symbol_status) +cpdef coredump_get_attribute(int attrib, intptr_t value, intptr_t size) +cpdef coredump_get_attribute_global(int attrib, intptr_t value, intptr_t size) +cpdef coredump_set_attribute(int attrib, intptr_t value, intptr_t size) +cpdef coredump_set_attribute_global(int attrib, intptr_t value, intptr_t size) +cpdef intptr_t get_export_table(p_export_table_id) except? 0 +cpdef intptr_t green_ctx_create(intptr_t desc, int dev, unsigned int flags) except? 0 +cpdef green_ctx_destroy(intptr_t h_ctx) +cpdef intptr_t ctx_from_green_ctx(intptr_t h_ctx) except? 0 +cpdef device_get_dev_resource(int device, resource, int type) +cpdef ctx_get_dev_resource(intptr_t h_ctx, resource, int type) +cpdef green_ctx_get_dev_resource(intptr_t h_ctx, resource, int type) +cpdef dev_sm_resource_split_by_count(result, intptr_t nb_groups, input, remainder, unsigned int flags, unsigned int min_count) +cpdef intptr_t dev_resource_generate_desc(resources, unsigned int nb_resources) except? 0 +cpdef green_ctx_record_event(intptr_t h_ctx, intptr_t h_event) +cpdef green_ctx_wait_event(intptr_t h_ctx, intptr_t h_event) +cpdef intptr_t stream_get_green_ctx(intptr_t h_stream) except? 0 +cpdef intptr_t green_ctx_stream_create(intptr_t green_ctx, unsigned int flags, int priority) except? 0 +cpdef intptr_t logs_register_callback(intptr_t callback_func, intptr_t user_data) except? 0 +cpdef logs_unregister_callback(intptr_t callback) +cpdef unsigned int logs_current(unsigned int flags) except? 0 +cpdef logs_dump_to_file(intptr_t iterator, path_to_file, unsigned int flags) +cpdef logs_dump_to_memory(intptr_t iterator, intptr_t buffer, intptr_t size, unsigned int flags) +cpdef int checkpoint_process_get_restore_thread_id(int pid) except? -1 +cpdef int checkpoint_process_get_state(int pid) except? -1 +cpdef checkpoint_process_lock(int pid, args) +cpdef checkpoint_process_checkpoint(int pid, args) +cpdef checkpoint_process_restore(int pid, intptr_t args) +cpdef checkpoint_process_unlock(int pid, args) +cpdef graphics_egl_register_image(intptr_t p_cuda_resource, intptr_t image, unsigned int flags) +cpdef intptr_t egl_stream_consumer_connect(intptr_t stream) except? 0 +cpdef intptr_t egl_stream_consumer_connect_with_flags(intptr_t stream, unsigned int flags) except? 0 +cpdef egl_stream_consumer_disconnect(intptr_t conn) +cpdef intptr_t egl_stream_consumer_acquire_frame(intptr_t conn, intptr_t p_stream, unsigned int timeout) except? 0 +cpdef egl_stream_consumer_release_frame(intptr_t conn, intptr_t p_cuda_resource, intptr_t p_stream) +cpdef intptr_t egl_stream_producer_connect(intptr_t stream, unsigned int width, unsigned int height) except? 0 +cpdef egl_stream_producer_disconnect(intptr_t conn) +cpdef intptr_t event_create_from_egl_sync(intptr_t egl_sync, unsigned int flags) except? 0 +cpdef intptr_t graphics_gl_register_buffer(GLuint buffer, unsigned int flags) except? 0 +cpdef intptr_t graphics_gl_register_image(GLuint image, GLenum target, unsigned int flags) except? 0 +cpdef profiler_start() +cpdef profiler_stop() +cpdef int vdpau_get_device(VdpDevice vdp_device, intptr_t vdp_get_proc_address) except? -1 +cpdef intptr_t vdpau_ctx_create_v2(unsigned int flags, int device, VdpDevice vdp_device, intptr_t vdp_get_proc_address) except? 0 +cpdef intptr_t graphics_vdpau_register_video_surface(VdpVideoSurface vdp_surface, unsigned int flags) except? 0 +cpdef intptr_t graphics_vdpau_register_output_surface(VdpOutputSurface vdp_surface, unsigned int flags) except? 0 +cpdef int ctx_get_device_v2(intptr_t ctx) except? -1 +cpdef ctx_synchronize_v2(intptr_t ctx) +cpdef memcpy_batch_async_v2(intptr_t dsts, intptr_t srcs, intptr_t sizes, size_t count, attrs, intptr_t attrs_idxs, size_t num_attrs, intptr_t h_stream) +cpdef memcpy_3d_batch_async_v2(size_t num_ops, intptr_t op_list, unsigned long long flags, intptr_t h_stream) +cpdef intptr_t mem_get_default_mem_pool(location, int type) except? 0 +cpdef intptr_t mem_get_mem_pool(location, int type) except? 0 +cpdef mem_set_mem_pool(location, int type, intptr_t pool) +cpdef mem_prefetch_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, prefetch_locs, intptr_t prefetch_loc_idxs, size_t num_prefetch_locs, unsigned long long flags, intptr_t h_stream) +cpdef mem_discard_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, unsigned long long flags, intptr_t h_stream) +cpdef mem_discard_and_prefetch_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, prefetch_locs, intptr_t prefetch_loc_idxs, size_t num_prefetch_locs, unsigned long long flags, intptr_t h_stream) +cpdef unsigned int device_get_p2p_atomic_capabilities(intptr_t operations, unsigned int count, int src_device, int dst_device) except? 0 +cpdef unsigned long long green_ctx_get_id(intptr_t green_ctx) except? 0 +cpdef multicast_bind_mem_v2(unsigned long long mc_handle, int dev, size_t mc_offset, unsigned long long mem_handle, size_t mem_offset, size_t size, unsigned long long flags) +cpdef multicast_bind_addr_v2(unsigned long long mc_handle, int dev, size_t mc_offset, unsigned long long memptr, size_t size, unsigned long long flags) +cpdef intptr_t graph_node_get_containing_graph(intptr_t h_node) except? 0 +cpdef unsigned int graph_node_get_local_id(intptr_t h_node) except? 0 +cpdef unsigned long long graph_node_get_tools_id(intptr_t h_node) except? 0 +cpdef unsigned int graph_get_id(intptr_t h_graph) except? 0 +cpdef unsigned int graph_exec_get_id(intptr_t h_graph_exec) except? 0 +cpdef dev_sm_resource_split(result, unsigned int nb_groups, input, remainder, unsigned int flags, group_params) +cpdef stream_get_dev_resource(intptr_t h_stream, resource, int type) +cpdef size_t kernel_get_param_count(intptr_t kernel) except? 0 +cpdef memcpy_with_attributes_async(unsigned long long dst, unsigned long long src, size_t size, attr, intptr_t h_stream) +cpdef memcpy_3d_with_attributes_async(intptr_t op, unsigned long long flags, intptr_t h_stream) +cpdef stream_begin_capture_to_cig(intptr_t h_stream, intptr_t stream_cig_capture_params) +cpdef stream_end_capture_to_cig(intptr_t h_stream) +cpdef size_t func_get_param_count(intptr_t func) except? 0 +cpdef launch_host_func_v2(intptr_t h_stream, intptr_t fn, intptr_t user_data, unsigned int sync_mode) +cpdef graph_node_get_params(intptr_t h_node, node_params) +cpdef intptr_t coredump_register_start_callback(intptr_t callback, intptr_t user_data) except? 0 +cpdef intptr_t coredump_register_complete_callback(intptr_t callback, intptr_t user_data) except? 0 +cpdef coredump_deregister_start_callback(intptr_t callback) +cpdef coredump_deregister_complete_callback(intptr_t callback) +cpdef uint32_t logical_endpoint_id_reserve(uint64_t count) except? 0 +cpdef logical_endpoint_id_release(uint32_t base_le_id, uint64_t count) +cpdef logical_endpoint_create(uint32_t le_id, intptr_t prop) +cpdef logical_endpoint_add_device(uint32_t le_id, int dev) +cpdef logical_endpoint_destroy(uint32_t le_id) +cpdef logical_endpoint_bind_addr(uint32_t le_id, int dev, uint64_t offset, intptr_t ptr, uint64_t size, unsigned long long flags) +cpdef logical_endpoint_bind_mem(uint32_t le_id, int dev, uint64_t offset, unsigned long long mem_handle, uint64_t mem_offset, uint64_t size, unsigned long long flags) +cpdef logical_endpoint_unbind(uint32_t le_id, int dev, uint64_t offset, uint64_t size) +cpdef logical_endpoint_export(intptr_t handle, uint32_t le_id, int handle_type) +cpdef logical_endpoint_import(uint32_t le_id, handle, int handle_type) +cpdef tuple logical_endpoint_get_limits(intptr_t prop) +cpdef logical_endpoint_query(uint32_t le_id, uint64_t count, intptr_t query_status) +cpdef stream_begin_recapture_to_graph(intptr_t h_stream, int mode, intptr_t h_graph, intptr_t callback_func, intptr_t user_data) diff --git a/cuda_bindings/cuda/bindings/_v2/driver.pyx b/cuda_bindings/cuda/bindings/_v2/driver.pyx new file mode 100644 index 00000000000..5905bd25dc3 --- /dev/null +++ b/cuda_bindings/cuda/bindings/_v2/driver.pyx @@ -0,0 +1,37349 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +# This code was automatically generated across versions from 12.9.0 to 13.3.0. Do not modify it directly. +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=c8d296eebce8a97e0c1a3d765b0e3fa3b2888a272a5c606c9c7c61034dbefd87 + + +# <<<< PREAMBLE CONTENT >>>> + +cimport cpython as _cyb_cpython +cimport cpython.buffer as _cyb_cpython_buffer +from cpython.buffer cimport PyBUF_READ as _cyb_PyBUF_READ +cimport cpython.memoryview as _cyb_cpython_memoryview +from cpython.memoryview cimport PyMemoryView_FromMemory as _cyb_PyMemoryView_FromMemory +from libc.stdint cimport ( + intptr_t, + uint32_t, + uint64_t, +) +from libc.stdlib cimport ( + calloc as _cyb_calloc, + free as _cyb_free, + malloc as _cyb_malloc, +) +from libc.string cimport ( + memcmp as _cyb_memcmp, + memcpy as _cyb_memcpy, +) + +from cuda.bindings._internal._fast_enum import FastEnum as _cyb_FastEnum + +import numpy as _numpy + +cdef _cyb___getbuffer(object self, _cyb_cpython.Py_buffer *buffer, void *ptr, int size, bint readonly): + buffer.buf = ptr + buffer.format = 'b' + buffer.internal = NULL + buffer.itemsize = 1 + buffer.len = size + buffer.ndim = 1 + buffer.obj = self + buffer.readonly = readonly + buffer.shape = &buffer.len + buffer.strides = &buffer.itemsize + buffer.suboffsets = NULL + +cdef _cyb_from_buffer(buffer, size, lowpp_type): + cdef _cyb_cpython.Py_buffer view + if _cyb_cpython.PyObject_GetBuffer(buffer, &view, _cyb_cpython_buffer.PyBUF_SIMPLE) != 0: + raise TypeError("buffer argument does not support the buffer protocol") + try: + if view.itemsize != 1: + raise ValueError("buffer itemsize must be 1 byte") + if view.len != size: + raise ValueError(f"buffer length must be {size} bytes") + return lowpp_type.from_ptr(view.buf, not view.readonly, buffer) + finally: + _cyb_cpython.PyBuffer_Release(&view) + +cdef _cyb_from_data(data, dtype_name, expected_dtype, lowpp_type): + # _numpy.recarray is a subclass of _numpy.ndarray, so implicitly handled here. + if isinstance(data, lowpp_type): + return data + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.size != 1: + raise ValueError("data array must have a size of 1") + if data.dtype != expected_dtype: + raise ValueError(f"data array must be of dtype {dtype_name}") + return lowpp_type.from_ptr(data.ctypes.data, not data.flags.writeable, data) + +cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) except?-1: + cdef intptr_t ptr + cdef int flags = _cyb_cpython.PyBUF_ANY_CONTIGUOUS + if not readonly: + flags |= _cyb_cpython.PyBUF_WRITABLE + cdef int status = -1 + cdef _cyb_cpython.Py_buffer view + if buf is None: + ptr = 0 + elif isinstance(buf, int): + ptr = buf + else: + try: + status = _cyb_cpython.PyObject_GetBuffer(buf, &view, flags) + if size != -1: + assert view.len == size + assert view.ndim == 1 + except Exception as e: + adj = "writable " if not readonly else "" + raise ValueError( + "buf must be None, a Python int representing the pointer " + f"address to a valid buffer, or a 1D contiguous {adj}" + f"buffer, of size {size}" + ) from e + else: + ptr = view.buf + finally: + if status == 0: + _cyb_cpython.PyBuffer_Release(&view) + return ptr + + +# <<<< END OF PREAMBLE CONTENT >>>> + +cimport cython # NOQA +from cpython.buffer cimport (Py_buffer, PyObject_GetBuffer, PyBuffer_Release, + PyBUF_ANY_CONTIGUOUS, PyObject_CheckBuffer, + PyBUF_SIMPLE) +from libc.stdlib cimport calloc, free +from libc.string cimport memcpy + +cimport cuda.bindings._lib.param_packer as _param_packer + +from cuda.bindings._internal._fast_enum import FastEnum as _FastEnum +import ctypes as _ctypes + + +############################################################################### +# Constants +############################################################################### + +# from ..cydriver cimport * brings CUDA_VERSION into scope as a C-level cdef +# enum constant (non-lvalue), so we cannot use a direct name assignment. +# Access it via the named module prefix to get the rvalue, then inject the +# Python module attribute through globals(). +globals()['CUDA_VERSION'] = cydriver.CUDA_VERSION + + +############################################################################### +# Enum +############################################################################### + +class IpcMemFlags(_cyb_FastEnum): + """ + CUDA Ipc Mem Flags + + See `CUipcMem_flags`. + """ + CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = (cydriver.CUipcMem_flags_enum.CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS, 'Automatically enable peer access between remote devices as needed') + +class MemAttachFlags(_cyb_FastEnum): + """ + CUDA Mem Attach Flags + + See `CUmemAttach_flags`. + """ + CU_MEM_ATTACH_GLOBAL = (cydriver.CUmemAttach_flags_enum.CU_MEM_ATTACH_GLOBAL, 'Memory can be accessed by any stream on any device') + CU_MEM_ATTACH_HOST = (cydriver.CUmemAttach_flags_enum.CU_MEM_ATTACH_HOST, 'Memory cannot be accessed by any stream on any device') + CU_MEM_ATTACH_SINGLE = (cydriver.CUmemAttach_flags_enum.CU_MEM_ATTACH_SINGLE, 'Memory can only be accessed by a single stream on the associated device') + +class CtxFlags(_cyb_FastEnum): + """ + Context creation flags + + See `CUctx_flags`. + """ + CU_CTX_SCHED_AUTO = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_AUTO, 'Automatic scheduling') + CU_CTX_SCHED_SPIN = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_SPIN, 'Set spin as default scheduling') + CU_CTX_SCHED_YIELD = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_YIELD, 'Set yield as default scheduling') + CU_CTX_SCHED_BLOCKING_SYNC = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + CU_CTX_BLOCKING_SYNC = (cydriver.CUctx_flags_enum.CU_CTX_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling [Deprecated]') + CU_CTX_SCHED_MASK = cydriver.CUctx_flags_enum.CU_CTX_SCHED_MASK + CU_CTX_MAP_HOST = (cydriver.CUctx_flags_enum.CU_CTX_MAP_HOST, '[Deprecated]') + CU_CTX_LMEM_RESIZE_TO_MAX = (cydriver.CUctx_flags_enum.CU_CTX_LMEM_RESIZE_TO_MAX, 'Keep local memory allocation after launch') + CU_CTX_COREDUMP_ENABLE = (cydriver.CUctx_flags_enum.CU_CTX_COREDUMP_ENABLE, 'Trigger coredumps from exceptions in this context') + CU_CTX_USER_COREDUMP_ENABLE = (cydriver.CUctx_flags_enum.CU_CTX_USER_COREDUMP_ENABLE, 'Enable user pipe to trigger coredumps in this context') + CU_CTX_SYNC_MEMOPS = (cydriver.CUctx_flags_enum.CU_CTX_SYNC_MEMOPS, 'Ensure synchronous memory operations on this context will synchronize') + CU_MASK = cydriver.CUctx_flags_enum.CU_CTX_FLAGS_MASK + +class EventSchedFlags(_cyb_FastEnum): + """ + Event sched flags + + See `CUevent_sched_flags`. + """ + CU_EVENT_SCHED_AUTO = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_AUTO, 'Automatic scheduling') + CU_EVENT_SCHED_SPIN = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_SPIN, 'Set spin as default scheduling') + CU_EVENT_SCHED_YIELD = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_YIELD, 'Set yield as default scheduling') + CU_EVENT_SCHED_BLOCKING_SYNC = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + +class EventFlags(_cyb_FastEnum): + """ + NVCL event scheduling flags + + See `cl_event_flags`. + """ + NVCL_EVENT_SCHED_AUTO = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_AUTO, 'Automatic scheduling') + NVCL_EVENT_SCHED_SPIN = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_SPIN, 'Set spin as default scheduling') + NVCL_EVENT_SCHED_YIELD = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_YIELD, 'Set yield as default scheduling') + NVCL_EVENT_SCHED_BLOCKING_SYNC = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + +class ContextFlags(_cyb_FastEnum): + """ + NVCL context scheduling flags + + See `cl_context_flags`. + """ + NVCL_CTX_SCHED_AUTO = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_AUTO, 'Automatic scheduling') + NVCL_CTX_SCHED_SPIN = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_SPIN, 'Set spin as default scheduling') + NVCL_CTX_SCHED_YIELD = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_YIELD, 'Set yield as default scheduling') + NVCL_CTX_SCHED_BLOCKING_SYNC = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + +class StreamFlags(_cyb_FastEnum): + """ + Stream creation flags + + See `CUstream_flags`. + """ + CU_STREAM_DEFAULT = (cydriver.CUstream_flags_enum.CU_STREAM_DEFAULT, 'Default stream flag') + CU_STREAM_NON_BLOCKING = (cydriver.CUstream_flags_enum.CU_STREAM_NON_BLOCKING, 'Stream does not synchronize with stream 0 (the NULL stream)') + +class EventFlags(_cyb_FastEnum): + """ + Event creation flags + + See `CUevent_flags`. + """ + CU_EVENT_DEFAULT = (cydriver.CUevent_flags_enum.CU_EVENT_DEFAULT, 'Default event flag') + CU_EVENT_BLOCKING_SYNC = (cydriver.CUevent_flags_enum.CU_EVENT_BLOCKING_SYNC, 'Event uses blocking synchronization') + CU_EVENT_DISABLE_TIMING = (cydriver.CUevent_flags_enum.CU_EVENT_DISABLE_TIMING, 'Event will not record timing data') + CU_EVENT_INTERPROCESS = (cydriver.CUevent_flags_enum.CU_EVENT_INTERPROCESS, 'Event is suitable for interprocess use. CU_EVENT_DISABLE_TIMING must be set') + +class EventRecordFlags(_cyb_FastEnum): + """ + Event record flags + + See `CUevent_record_flags`. + """ + CU_EVENT_RECORD_DEFAULT = (cydriver.CUevent_record_flags_enum.CU_EVENT_RECORD_DEFAULT, 'Default event record flag') + CU_EVENT_RECORD_EXTERNAL = (cydriver.CUevent_record_flags_enum.CU_EVENT_RECORD_EXTERNAL, 'When using stream capture, create an event record node instead of the default behavior. This flag is invalid when used outside of capture.') + +class EventWaitFlags(_cyb_FastEnum): + """ + Event wait flags + + See `CUevent_wait_flags`. + """ + CU_EVENT_WAIT_DEFAULT = (cydriver.CUevent_wait_flags_enum.CU_EVENT_WAIT_DEFAULT, 'Default event wait flag') + CU_EVENT_WAIT_EXTERNAL = (cydriver.CUevent_wait_flags_enum.CU_EVENT_WAIT_EXTERNAL, 'When using stream capture, create an event wait node instead of the default behavior. This flag is invalid when used outside of capture.') + +class StreamWaitValueFlags(_cyb_FastEnum): + """ + Flags for `cuStreamWaitValue32` and `cuStreamWaitValue64` + + See `CUstreamWaitValue_flags`. + """ + CU_STREAM_WAIT_VALUE_GEQ = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_GEQ, '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.)') + CU_STREAM_WAIT_VALUE_EQ = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_EQ, 'Wait until *addr == value.') + CU_STREAM_WAIT_VALUE_AND = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_AND, 'Wait until (*addr & value) != 0.') + CU_STREAM_WAIT_VALUE_NOR = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_NOR, 'Wait until ~(*addr | value) != 0. Support for this operation can be queried with `cuDeviceGetAttribute()` and `CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR`.') + CU_STREAM_WAIT_VALUE_FLUSH = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_FLUSH, '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 `CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES`.') + +class StreamWriteValueFlags(_cyb_FastEnum): + """ + Flags for `cuStreamWriteValue32` + + See `CUstreamWriteValue_flags`. + """ + CU_STREAM_WRITE_VALUE_DEFAULT = (cydriver.CUstreamWriteValue_flags_enum.CU_STREAM_WRITE_VALUE_DEFAULT, 'Default behavior') + CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER = (cydriver.CUstreamWriteValue_flags_enum.CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER, 'Permits the write to be reordered with writes which were issued before it, as a performance optimization. Normally, `cuStreamWriteValue32` 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.') + +class StreamBatchMemOpType(_cyb_FastEnum): + """ + Operations for `cuStreamBatchMemOp` + + See `CUstreamBatchMemOpType`. + """ + CU_STREAM_MEM_OP_WAIT_VALUE_32 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WAIT_VALUE_32, 'Represents a `cuStreamWaitValue32` operation') + CU_STREAM_MEM_OP_WRITE_VALUE_32 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WRITE_VALUE_32, 'Represents a `cuStreamWriteValue32` operation') + CU_STREAM_MEM_OP_WAIT_VALUE_64 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WAIT_VALUE_64, 'Represents a `cuStreamWaitValue64` operation') + CU_STREAM_MEM_OP_WRITE_VALUE_64 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WRITE_VALUE_64, 'Represents a `cuStreamWriteValue64` operation') + CU_STREAM_MEM_OP_BARRIER = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_BARRIER, 'Insert a memory barrier of the specified type') + CU_STREAM_MEM_OP_ATOMIC_REDUCTION = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_ATOMIC_REDUCTION, 'Perform a atomic reduction. See `CUstreamBatchMemOpParams.atomicReduction`') + CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES, 'This has the same effect as `CU_STREAM_WAIT_VALUE_FLUSH`, but as a standalone operation.') + +class StreamMemoryBarrierFlags(_cyb_FastEnum): + """ + Flags for `CUstreamBatchMemOpParams.memoryBarrier` + + See `CUstreamMemoryBarrier_flags`. + """ + CU_STREAM_MEMORY_BARRIER_TYPE_SYS = (cydriver.CUstreamMemoryBarrier_flags_enum.CU_STREAM_MEMORY_BARRIER_TYPE_SYS, 'System-wide memory barrier.') + CU_STREAM_MEMORY_BARRIER_TYPE_GPU = (cydriver.CUstreamMemoryBarrier_flags_enum.CU_STREAM_MEMORY_BARRIER_TYPE_GPU, 'Limit memory barrier scope to the GPU.') + +class OccupancyFlags(_cyb_FastEnum): + """ + Occupancy calculator flag + + See `CUoccupancy_flags`. + """ + CU_OCCUPANCY_DEFAULT = (cydriver.CUoccupancy_flags_enum.CU_OCCUPANCY_DEFAULT, 'Default behavior') + CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = (cydriver.CUoccupancy_flags_enum.CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE, 'Assume global caching is enabled and cannot be automatically turned off') + +class StreamUpdateCaptureDependenciesFlags(_cyb_FastEnum): + """ + Flags for `cuStreamUpdateCaptureDependencies` + + See `CUstreamUpdateCaptureDependencies_flags`. + """ + CU_STREAM_ADD_CAPTURE_DEPENDENCIES = (cydriver.CUstreamUpdateCaptureDependencies_flags_enum.CU_STREAM_ADD_CAPTURE_DEPENDENCIES, 'Add new nodes to the dependency set') + CU_STREAM_SET_CAPTURE_DEPENDENCIES = (cydriver.CUstreamUpdateCaptureDependencies_flags_enum.CU_STREAM_SET_CAPTURE_DEPENDENCIES, 'Replace the dependency set with the new nodes') + +class AsyncNotificationType(_cyb_FastEnum): + """ + Types of async notification that can be sent + + See `CUasyncNotificationType`. + """ + CU_OVER_BUDGET = (cydriver.CUasyncNotificationType_enum.CU_ASYNC_NOTIFICATION_TYPE_OVER_BUDGET, 'Sent when the process has exceeded its device memory budget') + +class ArrayFormat(_cyb_FastEnum): + """ + Array formats + + See `CUarray_format`. + """ + CU_AD_FORMAT_UNSIGNED_INT8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT8, 'Unsigned 8-bit integers') + CU_AD_FORMAT_UNSIGNED_INT16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT16, 'Unsigned 16-bit integers') + CU_AD_FORMAT_UNSIGNED_INT32 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT32, 'Unsigned 32-bit integers') + CU_AD_FORMAT_SIGNED_INT8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT8, 'Signed 8-bit integers') + CU_AD_FORMAT_SIGNED_INT16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT16, 'Signed 16-bit integers') + CU_AD_FORMAT_SIGNED_INT32 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT32, 'Signed 32-bit integers') + CU_AD_FORMAT_HALF = (cydriver.CUarray_format_enum.CU_AD_FORMAT_HALF, '16-bit floating point') + CU_AD_FORMAT_FLOAT = (cydriver.CUarray_format_enum.CU_AD_FORMAT_FLOAT, '32-bit floating point') + CU_AD_FORMAT_NV12 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_NV12, '8-bit YUV planar format, with 4:2:0 sampling') + CU_AD_FORMAT_UNORM_INT8X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X1, '1 channel unsigned 8-bit normalized integer') + CU_AD_FORMAT_UNORM_INT8X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X2, '2 channel unsigned 8-bit normalized integer') + CU_AD_FORMAT_UNORM_INT8X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X4, '4 channel unsigned 8-bit normalized integer') + CU_AD_FORMAT_UNORM_INT16X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X1, '1 channel unsigned 16-bit normalized integer') + CU_AD_FORMAT_UNORM_INT16X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X2, '2 channel unsigned 16-bit normalized integer') + CU_AD_FORMAT_UNORM_INT16X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X4, '4 channel unsigned 16-bit normalized integer') + CU_AD_FORMAT_SNORM_INT8X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X1, '1 channel signed 8-bit normalized integer') + CU_AD_FORMAT_SNORM_INT8X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X2, '2 channel signed 8-bit normalized integer') + CU_AD_FORMAT_SNORM_INT8X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X4, '4 channel signed 8-bit normalized integer') + CU_AD_FORMAT_SNORM_INT16X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X1, '1 channel signed 16-bit normalized integer') + CU_AD_FORMAT_SNORM_INT16X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X2, '2 channel signed 16-bit normalized integer') + CU_AD_FORMAT_SNORM_INT16X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X4, '4 channel signed 16-bit normalized integer') + CU_AD_FORMAT_BC1_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC1_UNORM, '4 channel unsigned normalized block-compressed (BC1 compression) format') + CU_AD_FORMAT_BC1_UNORM_SRGB = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC1_UNORM_SRGB, '4 channel unsigned normalized block-compressed (BC1 compression) format with sRGB encoding') + CU_AD_FORMAT_BC2_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC2_UNORM, '4 channel unsigned normalized block-compressed (BC2 compression) format') + CU_AD_FORMAT_BC2_UNORM_SRGB = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC2_UNORM_SRGB, '4 channel unsigned normalized block-compressed (BC2 compression) format with sRGB encoding') + CU_AD_FORMAT_BC3_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC3_UNORM, '4 channel unsigned normalized block-compressed (BC3 compression) format') + CU_AD_FORMAT_BC3_UNORM_SRGB = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC3_UNORM_SRGB, '4 channel unsigned normalized block-compressed (BC3 compression) format with sRGB encoding') + CU_AD_FORMAT_BC4_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC4_UNORM, '1 channel unsigned normalized block-compressed (BC4 compression) format') + CU_AD_FORMAT_BC4_SNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC4_SNORM, '1 channel signed normalized block-compressed (BC4 compression) format') + CU_AD_FORMAT_BC5_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC5_UNORM, '2 channel unsigned normalized block-compressed (BC5 compression) format') + CU_AD_FORMAT_BC5_SNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC5_SNORM, '2 channel signed normalized block-compressed (BC5 compression) format') + CU_AD_FORMAT_BC6H_UF16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC6H_UF16, '3 channel unsigned half-float block-compressed (BC6H compression) format') + CU_AD_FORMAT_BC6H_SF16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC6H_SF16, '3 channel signed half-float block-compressed (BC6H compression) format') + CU_AD_FORMAT_BC7_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC7_UNORM, '4 channel unsigned normalized block-compressed (BC7 compression) format') + CU_AD_FORMAT_BC7_UNORM_SRGB = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC7_UNORM_SRGB, '4 channel unsigned normalized block-compressed (BC7 compression) format with sRGB encoding') + CU_AD_FORMAT_P010 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P010, '10-bit YUV planar format, with 4:2:0 sampling') + CU_AD_FORMAT_P016 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P016, '16-bit YUV planar format, with 4:2:0 sampling') + CU_AD_FORMAT_NV16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_NV16, '8-bit YUV planar format, with 4:2:2 sampling') + CU_AD_FORMAT_P210 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P210, '10-bit YUV planar format, with 4:2:2 sampling') + CU_AD_FORMAT_P216 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P216, '16-bit YUV planar format, with 4:2:2 sampling') + CU_AD_FORMAT_YUY2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_YUY2, '2 channel, 8-bit YUV packed planar format, with 4:2:2 sampling') + CU_AD_FORMAT_Y210 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y210, '2 channel, 10-bit YUV packed planar format, with 4:2:2 sampling') + CU_AD_FORMAT_Y216 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y216, '2 channel, 16-bit YUV packed planar format, with 4:2:2 sampling') + CU_AD_FORMAT_AYUV = (cydriver.CUarray_format_enum.CU_AD_FORMAT_AYUV, '4 channel, 8-bit YUV packed planar format, with 4:4:4 sampling') + CU_AD_FORMAT_Y410 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y410, '10-bit YUV packed planar format, with 4:4:4 sampling') + CU_AD_FORMAT_Y416 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y416, '4 channel, 12-bit YUV packed planar format, with 4:4:4 sampling') + CU_AD_FORMAT_Y444_PLANAR8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y444_PLANAR8, '3 channel 8-bit YUV planar format, with 4:4:4 sampling') + CU_AD_FORMAT_Y444_PLANAR10 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y444_PLANAR10, '3 channel 10-bit YUV planar format, with 4:4:4 sampling') + CU_AD_FORMAT_YUV444_8bit_SemiPlanar = (cydriver.CUarray_format_enum.CU_AD_FORMAT_YUV444_8bit_SemiPlanar, '3 channel 8-bit YUV semi-planar format, with 4:4:4 sampling') + CU_AD_FORMAT_YUV444_16bit_SemiPlanar = (cydriver.CUarray_format_enum.CU_AD_FORMAT_YUV444_16bit_SemiPlanar, '3 channel 16-bit YUV semi-planar format, with 4:4:4 sampling') + CU_AD_FORMAT_UNORM_INT_101010_2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT_101010_2, '4 channel unorm R10G10B10A2 RGB format') + CU_AD_FORMAT_UINT8_PACKED_422 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_PACKED_422, '4 channel unsigned 8-bit YUV packed format, with 4:2:2 sampling') + CU_AD_FORMAT_UINT8_PACKED_444 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_PACKED_444, '4 channel unsigned 8-bit YUV packed format, with 4:4:4 sampling') + CU_AD_FORMAT_UINT8_SEMIPLANAR_420 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_SEMIPLANAR_420, '3 channel unsigned 8-bit YUV semi-planar format, with 4:2:0 sampling') + CU_AD_FORMAT_UINT16_SEMIPLANAR_420 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_SEMIPLANAR_420, '3 channel unsigned 16-bit YUV semi-planar format, with 4:2:0 sampling') + CU_AD_FORMAT_UINT8_SEMIPLANAR_422 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_SEMIPLANAR_422, '3 channel unsigned 8-bit YUV semi-planar format, with 4:2:2 sampling') + CU_AD_FORMAT_UINT16_SEMIPLANAR_422 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_SEMIPLANAR_422, '3 channel unsigned 16-bit YUV semi-planar format, with 4:2:2 sampling') + CU_AD_FORMAT_UINT8_SEMIPLANAR_444 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_SEMIPLANAR_444, '3 channel unsigned 8-bit YUV semi-planar format, with 4:4:4 sampling') + CU_AD_FORMAT_UINT16_SEMIPLANAR_444 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_SEMIPLANAR_444, '3 channel unsigned 16-bit YUV semi-planar format, with 4:4:4 sampling') + CU_AD_FORMAT_UINT8_PLANAR_420 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_PLANAR_420, '3 channel unsigned 8-bit YUV planar format, with 4:2:0 sampling') + CU_AD_FORMAT_UINT16_PLANAR_420 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_PLANAR_420, '3 channel unsigned 16-bit YUV planar format, with 4:2:0 sampling') + CU_AD_FORMAT_UINT8_PLANAR_422 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_PLANAR_422, '3 channel unsigned 8-bit YUV planar format, with 4:2:2 sampling') + CU_AD_FORMAT_UINT16_PLANAR_422 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_PLANAR_422, '3 channel unsigned 16-bit YUV planar format, with 4:2:2 sampling') + CU_AD_FORMAT_UINT8_PLANAR_444 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT8_PLANAR_444, '3 channel unsigned 8-bit YUV planar format, with 4:4:4 sampling') + CU_AD_FORMAT_UINT16_PLANAR_444 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UINT16_PLANAR_444, '3 channel unsigned 16-bit YUV planar format, with 4:4:4 sampling') + CU_AD_FORMAT_MAX = cydriver.CUarray_format_enum.CU_AD_FORMAT_MAX + +class AddressMode(_cyb_FastEnum): + """ + Texture reference addressing modes + + See `CUaddress_mode`. + """ + CU_TR_WRAP = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_WRAP, 'Wrapping address mode') + CU_TR_CLAMP = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_CLAMP, 'Clamp to edge address mode') + CU_TR_MIRROR = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_MIRROR, 'Mirror address mode') + CU_TR_BORDER = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_BORDER, 'Border address mode') + +class FilterMode(_cyb_FastEnum): + """ + Texture reference filtering modes + + See `CUfilter_mode`. + """ + CU_TR_POINT = (cydriver.CUfilter_mode_enum.CU_TR_FILTER_MODE_POINT, 'Point filter mode') + CU_TR_LINEAR = (cydriver.CUfilter_mode_enum.CU_TR_FILTER_MODE_LINEAR, 'Linear filter mode') + +class DeviceAttribute(_cyb_FastEnum): + """ + Device properties + + See `CUdevice_attribute`. + """ + CU_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, 'Maximum number of threads per block') + CU_ATTRIBUTE_MAX_BLOCK_DIM_X = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, 'Maximum block dimension X') + CU_ATTRIBUTE_MAX_BLOCK_DIM_Y = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, 'Maximum block dimension Y') + CU_ATTRIBUTE_MAX_BLOCK_DIM_Z = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, 'Maximum block dimension Z') + CU_ATTRIBUTE_MAX_GRID_DIM_X = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, 'Maximum grid dimension X') + CU_ATTRIBUTE_MAX_GRID_DIM_Y = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, 'Maximum grid dimension Y') + CU_ATTRIBUTE_MAX_GRID_DIM_Z = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, 'Maximum grid dimension Z') + CU_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, 'Maximum shared memory available per block in bytes') + CU_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK') + CU_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, 'Memory available on device for constant variables in a CUDA C kernel in bytes') + CU_ATTRIBUTE_WARP_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_WARP_SIZE, 'Warp size in threads') + CU_ATTRIBUTE_MAX_PITCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_PITCH, 'Maximum pitch in bytes allowed by memory copies') + CU_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, 'Maximum number of 32-bit registers available per block') + CU_ATTRIBUTE_REGISTERS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK') + CU_ATTRIBUTE_CLOCK_RATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CLOCK_RATE, 'Typical clock frequency in kilohertz') + CU_ATTRIBUTE_TEXTURE_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, 'Alignment requirement for textures') + CU_ATTRIBUTE_GPU_OVERLAP = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, 'Device can possibly copy memory and execute a kernel concurrently. Deprecated. Use instead CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT.') + CU_ATTRIBUTE_MULTIPROCESSOR_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, 'Number of multiprocessors on device') + CU_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, 'Specifies whether there is a run time limit on kernels') + CU_ATTRIBUTE_INTEGRATED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_INTEGRATED, 'Device is integrated with host memory') + CU_ATTRIBUTE_CAN_MAP_HOST_MEMORY = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, 'Device can map host memory into CUDA address space') + CU_ATTRIBUTE_COMPUTE_MODE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, 'Compute mode (See `CUcomputemode` for details)') + CU_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH, 'Maximum 1D texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH, 'Maximum 2D texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT, 'Maximum 2D texture height') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH, 'Maximum 3D texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT, 'Maximum 3D texture height') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH, 'Maximum 3D texture depth') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH, 'Maximum 2D layered texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT, 'Maximum 2D layered texture height') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS, 'Maximum layers in a 2D layered texture') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS') + CU_ATTRIBUTE_SURFACE_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT, 'Alignment requirement for surfaces') + CU_ATTRIBUTE_CONCURRENT_KERNELS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, 'Device can possibly execute multiple kernels concurrently') + CU_ATTRIBUTE_ECC_ENABLED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ECC_ENABLED, 'Device has ECC support enabled') + CU_ATTRIBUTE_PCI_BUS_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_BUS_ID, 'PCI bus ID of the device') + CU_ATTRIBUTE_PCI_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID, 'PCI device ID of the device') + CU_ATTRIBUTE_TCC_DRIVER = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TCC_DRIVER, 'Device is using TCC driver model') + CU_ATTRIBUTE_MEMORY_CLOCK_RATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, 'Peak memory clock frequency in kilohertz') + CU_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, 'Global memory bus width in bits') + CU_ATTRIBUTE_L2_CACHE_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, 'Size of L2 cache in bytes') + CU_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, 'Maximum resident threads per multiprocessor') + CU_ATTRIBUTE_ASYNC_ENGINE_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, 'Number of asynchronous engines') + CU_ATTRIBUTE_UNIFIED_ADDRESSING = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, 'Device shares a unified address space with the host') + CU_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH, 'Maximum 1D layered texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS, 'Maximum layers in a 1D layered texture') + CU_ATTRIBUTE_CAN_TEX2D_GATHER = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER, 'Deprecated, do not use.') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH, 'Maximum 2D texture width if CUDA_ARRAY3D_TEXTURE_GATHER is set') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT, 'Maximum 2D texture height if CUDA_ARRAY3D_TEXTURE_GATHER is set') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE, 'Alternate maximum 3D texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE, 'Alternate maximum 3D texture height') + CU_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE, 'Alternate maximum 3D texture depth') + CU_ATTRIBUTE_PCI_DOMAIN_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID, 'PCI domain ID of the device') + CU_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT, 'Pitch alignment requirement for textures') + CU_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH, 'Maximum cubemap texture width/height') + CU_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH, 'Maximum cubemap layered texture width/height') + CU_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS, 'Maximum layers in a cubemap layered texture') + CU_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH, 'Maximum 1D surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH, 'Maximum 2D surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT, 'Maximum 2D surface height') + CU_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH, 'Maximum 3D surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT, 'Maximum 3D surface height') + CU_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH, 'Maximum 3D surface depth') + CU_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH, 'Maximum 1D layered surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS, 'Maximum layers in a 1D layered surface') + CU_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH, 'Maximum 2D layered surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT, 'Maximum 2D layered surface height') + CU_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS, 'Maximum layers in a 2D layered surface') + CU_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH, 'Maximum cubemap surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH, 'Maximum cubemap layered surface width') + CU_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS, 'Maximum layers in a cubemap layered surface') + CU_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH, 'Deprecated, do not use. Use cudaDeviceGetTexture1DLinearMaxWidth() or `cuDeviceGetTexture1DLinearMaxWidth()` instead.') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH, 'Maximum 2D linear texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT, 'Maximum 2D linear texture height') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH, 'Maximum 2D linear texture pitch in bytes') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH, 'Maximum mipmapped 2D texture width') + CU_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT, 'Maximum mipmapped 2D texture height') + CU_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, 'Major compute capability version number') + CU_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, 'Minor compute capability version number') + CU_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH, 'Maximum mipmapped 1D texture width') + CU_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED, 'Device supports stream priorities') + CU_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED, 'Device supports caching globals in L1') + CU_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED, 'Device supports caching locals in L1') + CU_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR, 'Maximum shared memory available per multiprocessor in bytes') + CU_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR, 'Maximum number of 32-bit registers available per multiprocessor') + CU_ATTRIBUTE_MANAGED_MEMORY = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, 'Device can allocate managed memory on this system') + CU_ATTRIBUTE_MULTI_GPU_BOARD = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, 'Device is on a multi-GPU board') + CU_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID, 'Unique id for a group of devices on the same multi-GPU board') + CU_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED, 'Link between the device and the host supports all native atomic operations') + CU_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO, 'Ratio of single precision performance (in floating-point operations per second) to double precision performance') + CU_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS, 'Device supports coherently accessing pageable memory without calling cudaHostRegister on it') + CU_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, 'Device can coherently access managed memory concurrently with the CPU') + CU_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, 'Device supports compute preemption.') + CU_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, 'Device can access host registered memory at the same virtual address as the CPU') + CU_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS_V1 = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS_V1, 'Deprecated, along with v1 MemOps API, `cuStreamBatchMemOp` and related APIs are supported.') + CU_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS_V1 = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS_V1, 'Deprecated, along with v1 MemOps API, 64-bit operations are supported in `cuStreamBatchMemOp` and related APIs.') + CU_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V1 = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V1, 'Deprecated, along with v1 MemOps API, `CU_STREAM_WAIT_VALUE_NOR` is supported.') + CU_ATTRIBUTE_COOPERATIVE_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, 'Device supports launching cooperative kernels via `cuLaunchCooperativeKernel`') + CU_ATTRIBUTE_COOPERATIVE_MULTI_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH, 'Deprecated, `cuLaunchCooperativeKernelMultiDevice` is deprecated.') + CU_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, '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.') + CU_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES, 'The `CU_STREAM_WAIT_VALUE_FLUSH` flag and the `CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES` MemOp are supported on the device. See `Stream Memory Operations` for additional details.') + CU_ATTRIBUTE_HOST_REGISTER_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, 'Device supports host memory registration via `cudaHostRegister`.') + CU_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, "Device accesses pageable memory via the host's page tables.") + CU_ATTRIBUTE_DIRECT_MANAGED_MEM_ACCESS_FROM_HOST = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_DIRECT_MANAGED_MEM_ACCESS_FROM_HOST, 'The host can directly access managed memory on the device without migration.') + CU_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED, 'Deprecated, Use CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED') + CU_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, 'Device supports virtual memory management APIs like `cuMemAddressReserve`, `cuMemCreate`, `cuMemMap` and related APIs') + CU_ATTRIBUTE_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR_SUPPORTED, 'Device supports exporting memory to a posix file descriptor with `cuMemExportToShareableHandle`, if requested via `cuMemCreate`') + CU_ATTRIBUTE_HANDLE_TYPE_WIN32_HANDLE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_HANDLE_SUPPORTED, 'Device supports exporting memory to a Win32 NT handle with `cuMemExportToShareableHandle`, if requested via `cuMemCreate`') + CU_ATTRIBUTE_HANDLE_TYPE_WIN32_KMT_HANDLE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_KMT_HANDLE_SUPPORTED, 'Device supports exporting memory to a Win32 KMT handle with `cuMemExportToShareableHandle`, if requested via `cuMemCreate`') + CU_ATTRIBUTE_MAX_BLOCKS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCKS_PER_MULTIPROCESSOR, 'Maximum number of blocks per multiprocessor') + CU_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED, 'Device supports compression of memory') + CU_ATTRIBUTE_MAX_PERSISTING_L2_CACHE_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_PERSISTING_L2_CACHE_SIZE, 'Maximum L2 persisting lines capacity setting in bytes.') + CU_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE, 'Maximum value of `CUaccessPolicyWindow.num_bytes`.') + CU_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_CUDA_VMM_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_CUDA_VMM_SUPPORTED, 'Device supports specifying the GPUDirect RDMA flag with `cuMemCreate`') + CU_ATTRIBUTE_RESERVED_SHARED_MEMORY_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_RESERVED_SHARED_MEMORY_PER_BLOCK, 'Shared memory reserved by CUDA driver per block in bytes') + CU_ATTRIBUTE_SPARSE_CUDA_ARRAY_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_SPARSE_CUDA_ARRAY_SUPPORTED, 'Device supports sparse CUDA arrays and sparse CUDA mipmapped arrays') + CU_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED, 'Device supports using the `cuMemHostRegister` flag `CU_MEMHOSTERGISTER_READ_ONLY` to register memory that must be mapped as read-only to the GPU') + CU_ATTRIBUTE_TIMELINE_SEMAPHORE_INTEROP_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TIMELINE_SEMAPHORE_INTEROP_SUPPORTED, 'External timeline semaphore interop is supported on the device') + CU_ATTRIBUTE_MEMORY_POOLS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED, 'Device supports using the `cuMemAllocAsync` and `cuMemPool` family of APIs') + CU_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED, 'Device supports GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information)') + CU_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS, 'The returned attribute shall be interpreted as a bitmask, where the individual bits are described by the `CUflushGPUDirectRDMAWritesOptions` enum') + CU_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING, 'GPUDirect RDMA writes to the device do not need to be flushed for consumers within the scope indicated by the returned attribute. See `CUGPUDirectRDMAWritesOrdering` for the numerical values returned here.') + CU_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES, 'Handle types supported with mempool based IPC') + CU_ATTRIBUTE_CLUSTER_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CLUSTER_LAUNCH, 'Indicates device supports cluster launch') + CU_ATTRIBUTE_DEFERRED_MAPPING_CUDA_ARRAY_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_DEFERRED_MAPPING_CUDA_ARRAY_SUPPORTED, 'Device supports deferred mapping CUDA arrays and CUDA mipmapped arrays') + CU_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS, '64-bit operations are supported in `cuStreamBatchMemOp` and related MemOp APIs.') + CU_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR, '`CU_STREAM_WAIT_VALUE_NOR` is supported by MemOp APIs.') + CU_ATTRIBUTE_DMA_BUF_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED, 'Device supports buffer sharing with dma_buf mechanism.') + CU_ATTRIBUTE_IPC_EVENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED, 'Device supports IPC Events.') + CU_ATTRIBUTE_MEM_SYNC_DOMAIN_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEM_SYNC_DOMAIN_COUNT, 'Number of memory domains the device supports.') + CU_ATTRIBUTE_TENSOR_MAP_ACCESS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TENSOR_MAP_ACCESS_SUPPORTED, 'Device supports accessing memory using Tensor Map.') + CU_ATTRIBUTE_HANDLE_TYPE_FABRIC_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_FABRIC_SUPPORTED, 'Device supports exporting memory to a fabric handle with `cuMemExportToShareableHandle()` or requested with `cuMemCreate()`') + CU_ATTRIBUTE_UNIFIED_FUNCTION_POINTERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_UNIFIED_FUNCTION_POINTERS, 'Device supports unified function pointers.') + CU_ATTRIBUTE_NUMA_CONFIG = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_NUMA_CONFIG, 'NUMA configuration of a device: value is of type `CUdeviceNumaConfig` enum') + CU_ATTRIBUTE_NUMA_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_NUMA_ID, 'NUMA node ID of the GPU memory') + CU_ATTRIBUTE_MULTICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTICAST_SUPPORTED, 'Device supports switch multicast and reduction operations.') + CU_ATTRIBUTE_MPS_ENABLED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MPS_ENABLED, 'Indicates if contexts created on this device will be shared via MPS') + CU_ATTRIBUTE_HOST_NUMA_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID, 'NUMA ID of the host node closest to the device. Returns -1 when system does not support NUMA.') + CU_ATTRIBUTE_D3D12_CIG_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_D3D12_CIG_SUPPORTED, 'Device supports CIG with D3D12.') + CU_ATTRIBUTE_MEM_DECOMPRESS_ALGORITHM_MASK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEM_DECOMPRESS_ALGORITHM_MASK, 'The returned valued shall be interpreted as a bitmask, where the individual bits are described by the `CUmemDecompressAlgorithm` enum.') + CU_ATTRIBUTE_MEM_DECOMPRESS_MAXIMUM_LENGTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEM_DECOMPRESS_MAXIMUM_LENGTH, 'The returned valued is the maximum length in bytes of a single decompress operation that is allowed.') + CU_ATTRIBUTE_VULKAN_CIG_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_VULKAN_CIG_SUPPORTED, 'Device supports CIG with Vulkan.') + CU_ATTRIBUTE_GPU_PCI_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_PCI_DEVICE_ID, 'The combined 16-bit PCI device ID and 16-bit PCI vendor ID.') + CU_ATTRIBUTE_GPU_PCI_SUBSYSTEM_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_PCI_SUBSYSTEM_ID, 'The combined 16-bit PCI subsystem ID and 16-bit PCI subsystem vendor ID.') + CU_ATTRIBUTE_HOST_NUMA_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_NUMA_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, 'Device supports HOST_NUMA location with the virtual memory management APIs like `cuMemCreate`, `cuMemMap` and related APIs') + CU_ATTRIBUTE_HOST_NUMA_MEMORY_POOLS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_NUMA_MEMORY_POOLS_SUPPORTED, 'Device supports HOST_NUMA location with the `cuMemAllocAsync` and `cuMemPool` family of APIs') + CU_ATTRIBUTE_HOST_NUMA_MULTINODE_IPC_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_NUMA_MULTINODE_IPC_SUPPORTED, 'Device supports HOST_NUMA location IPC between nodes in a multi-node system.') + CU_ATTRIBUTE_HOST_MEMORY_POOLS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_MEMORY_POOLS_SUPPORTED, 'Device suports HOST location with the `cuMemAllocAsync` and `cuMemPool` family of APIs') + CU_ATTRIBUTE_HOST_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, 'Device supports HOST location with the virtual memory management APIs like `cuMemCreate`, `cuMemMap` and related APIs') + CU_ATTRIBUTE_HOST_ALLOC_DMA_BUF_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_ALLOC_DMA_BUF_SUPPORTED, 'Device supports page-locked host memory buffer sharing with dma_buf mechanism.') + CU_ATTRIBUTE_ONLY_PARTIAL_HOST_NATIVE_ATOMIC_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ONLY_PARTIAL_HOST_NATIVE_ATOMIC_SUPPORTED, 'Link between the device and the host supports only some native atomic operations') + CU_ATTRIBUTE_ATOMIC_REDUCTION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ATOMIC_REDUCTION_SUPPORTED, 'Device supports atomic reduction operations in stream batch memory operations') + CU_ATTRIBUTE_D3D12_CIG_STREAMS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_D3D12_CIG_STREAMS_SUPPORTED, 'Device supports CIG streams with D3D12') + CU_ATTRIBUTE_DMA_BUF_MMAP_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_DMA_BUF_MMAP_SUPPORTED, 'Device supports mmap() of dmabuf file descriptors for CUDA device memory allocations') + CU_ATTRIBUTE_LOGICAL_ENDPOINT_UNICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_UNICAST_SUPPORTED, 'Device supports unicast logical endpoints') + CU_ATTRIBUTE_LOGICAL_ENDPOINT_MULTICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_MULTICAST_SUPPORTED, 'Device supports multicast logical endpoints') + CU_ATTRIBUTE_LOGICAL_ENDPOINT_COUNTED_OPS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_COUNTED_OPS_SUPPORTED, 'Device supports counted operations via logical endpoints') + CU_ATTRIBUTE_LOGICAL_ENDPOINT_UNICAST_ACCESS_ON_OWNER_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_UNICAST_ACCESS_ON_OWNER_DEVICE_SUPPORTED, 'Device supports unicast logical endpoint access on the owner device') + CU_ATTRIBUTE_MAX = cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX + +class PointerAttribute(_cyb_FastEnum): + """ + Pointer information + + See `CUpointer_attribute`. + """ + CU_ATTRIBUTE_CONTEXT = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_CONTEXT, 'The `CUcontext` on which a pointer was allocated or registered') + CU_ATTRIBUTE_MEMORY_TYPE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MEMORY_TYPE, 'The `CUmemorytype` describing the physical location of a pointer') + CU_ATTRIBUTE_DEVICE_POINTER = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_DEVICE_POINTER, "The address at which a pointer's memory may be accessed on the device") + CU_ATTRIBUTE_HOST_POINTER = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_HOST_POINTER, "The address at which a pointer's memory may be accessed on the host") + CU_ATTRIBUTE_P2P_TOKENS = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_P2P_TOKENS, 'A pair of tokens for use with the nv-p2p.h Linux kernel interface') + CU_ATTRIBUTE_SYNC_MEMOPS = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, 'Synchronize every synchronous memory operation initiated on this region') + CU_ATTRIBUTE_BUFFER_ID = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_BUFFER_ID, 'A process-wide unique ID for an allocated memory region') + CU_ATTRIBUTE_IS_MANAGED = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_IS_MANAGED, 'Indicates if the pointer points to managed memory') + CU_ATTRIBUTE_DEVICE_ORDINAL = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, 'A device ordinal of a device on which a pointer was allocated or registered') + CU_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE, '1 if this pointer maps to an allocation that is suitable for `cudaIpcGetMemHandle`, 0 otherwise') + CU_ATTRIBUTE_RANGE_START_ADDR = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_RANGE_START_ADDR, 'Starting address for this requested pointer') + CU_ATTRIBUTE_RANGE_SIZE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_RANGE_SIZE, 'Size of the address range for this requested pointer') + CU_ATTRIBUTE_MAPPED = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MAPPED, '1 if this pointer is in a valid address range that is mapped to a backing allocation, 0 otherwise') + CU_ATTRIBUTE_ALLOWED_HANDLE_TYPES = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, 'Bitmask of allowed `CUmemAllocationHandleType` for this allocation') + CU_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE, '1 if the memory this pointer is referencing can be used with the GPUDirect RDMA API') + CU_ATTRIBUTE_ACCESS_FLAGS = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_ACCESS_FLAGS, 'Returns the access flags the device associated with the current context has on the corresponding memory referenced by the pointer given') + CU_ATTRIBUTE_MEMPOOL_HANDLE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE, 'Returns the mempool handle for the allocation if it was allocated from a mempool. Otherwise returns NULL.') + CU_ATTRIBUTE_MAPPING_SIZE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MAPPING_SIZE, 'Size of the actual underlying mapping that the pointer belongs to') + CU_ATTRIBUTE_MAPPING_BASE_ADDR = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR, 'The start address of the mapping that the pointer belongs to') + CU_ATTRIBUTE_MEMORY_BLOCK_ID = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MEMORY_BLOCK_ID, 'A process-wide unique id corresponding to the physical allocation the pointer belongs to') + CU_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE, 'Returns in `*data` a boolean that indicates whether the pointer points to memory that is capable to be used for hardware accelerated decompression.') + +class FunctionAttribute(_cyb_FastEnum): + """ + Function properties + + See `CUfunction_attribute`. + """ + CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, '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.') + CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, '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.') + CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES, 'The size in bytes of user-allocated constant memory required by this function.') + CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES, 'The size in bytes of local memory used by each thread of this function.') + CU_FUNC_ATTRIBUTE_NUM_REGS = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_NUM_REGS, 'The number of registers used by each thread of this function.') + CU_FUNC_ATTRIBUTE_PTX_VERSION = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_PTX_VERSION, '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.') + CU_FUNC_ATTRIBUTE_BINARY_VERSION = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_BINARY_VERSION, '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_ATTRIBUTE_CACHE_MODE_CA = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_CACHE_MODE_CA, 'The attribute to indicate whether the function has been compiled with user specified option "-Xptxas --dlcm=ca" set .') + CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, '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 `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK` - `CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES`, except when `CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES` is greater than `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK`, then the default value of this attribute is 0. The value can be increased to `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN` - `CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES`. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT, '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 `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR`. This is only a hint, and the driver can choose a different ratio if required to execute the function. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET, 'If this attribute is set, the kernel must launch with a valid cluster size specified. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH, '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 CUDA_ERROR_NOT_PERMITTED. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT, '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 CUDA_ERROR_NOT_PERMITTED. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH, '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 CUDA_ERROR_NOT_PERMITTED. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED, '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 `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE, 'The block scheduling policy of a function. The value type is `CUclusterSchedulingPolicy` / cudaClusterSchedulingPolicy. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + CU_FUNC_ATTRIBUTE_DEVICE_NODE_UPDATE_SUPPORTED = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_DEVICE_NODE_UPDATE_SUPPORTED, 'Whether the function can be updated on device. 1 means device node update is supported, 0 is unsupported. See `cuFuncGetAttribute`.') + CU_FUNC_ATTRIBUTE_MAX = cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_MAX + +class FuncCache(_cyb_FastEnum): + """ + Function cache configurations + + See `CUfunc_cache`. + """ + CU_PREFER_NONE = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_NONE, 'no preference for shared memory or L1 (default)') + CU_PREFER_SHARED = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_SHARED, 'prefer larger shared memory and smaller L1 cache') + CU_PREFER_L1 = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_L1, 'prefer larger L1 cache and smaller shared memory') + CU_PREFER_EQUAL = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_EQUAL, 'prefer equal sized L1 cache and shared memory') + +class Sharedconfig(_cyb_FastEnum): + """ + [Deprecated] Shared memory configurations + + See `CUsharedconfig`. + """ + CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = (cydriver.CUsharedconfig_enum.CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE, 'set default shared memory bank size') + CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = (cydriver.CUsharedconfig_enum.CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE, 'set shared memory bank width to four bytes') + CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = (cydriver.CUsharedconfig_enum.CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE, 'set shared memory bank width to eight bytes') + +class SharedCarveout(_cyb_FastEnum): + """ + Shared memory carveout configurations. These may be passed to + `cuFuncSetAttribute` or `cuKernelSetAttribute` + + See `CUshared_carveout`. + """ + CU_SHAREDMEM_CARVEOUT_DEFAULT = (cydriver.CUshared_carveout_enum.CU_SHAREDMEM_CARVEOUT_DEFAULT, 'No preference for shared memory or L1 (default)') + CU_SHAREDMEM_CARVEOUT_MAX_SHARED = (cydriver.CUshared_carveout_enum.CU_SHAREDMEM_CARVEOUT_MAX_SHARED, 'Prefer maximum available shared memory, minimum L1 cache') + CU_SHAREDMEM_CARVEOUT_MAX_L1 = (cydriver.CUshared_carveout_enum.CU_SHAREDMEM_CARVEOUT_MAX_L1, 'Prefer maximum available L1 cache, minimum shared memory') + +class Memorytype(_cyb_FastEnum): + """ + Memory types + + See `CUmemorytype`. + """ + CU_HOST = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_HOST, 'Host memory') + CU_DEVICE = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_DEVICE, 'Device memory') + CU_ARRAY = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_ARRAY, 'Array memory') + CU_UNIFIED = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_UNIFIED, 'Unified device or host memory') + +class Computemode(_cyb_FastEnum): + """ + Compute Modes + + See `CUcomputemode`. + """ + CU_DEFAULT = (cydriver.CUcomputemode_enum.CU_COMPUTEMODE_DEFAULT, 'Default compute mode (Multiple contexts allowed per device)') + CU_PROHIBITED = (cydriver.CUcomputemode_enum.CU_COMPUTEMODE_PROHIBITED, 'Compute-prohibited mode (No contexts can be created on this device at this time)') + CU_EXCLUSIVE_PROCESS = (cydriver.CUcomputemode_enum.CU_COMPUTEMODE_EXCLUSIVE_PROCESS, 'Compute-exclusive-process mode (Only one context used by a single process can be present on this device at a time)') + +class MemAdvise(_cyb_FastEnum): + """ + Memory advise values + + See `CUmem_advise`. + """ + CU_SET_READ_MOSTLY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_SET_READ_MOSTLY, 'Data will mostly be read and only occasionally be written to') + CU_UNSET_READ_MOSTLY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_UNSET_READ_MOSTLY, 'Undo the effect of `CU_MEM_ADVISE_SET_READ_MOSTLY`') + CU_SET_PREFERRED_LOCATION = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_SET_PREFERRED_LOCATION, 'Set the preferred location for the data as the specified device') + CU_UNSET_PREFERRED_LOCATION = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION, 'Clear the preferred location for the data') + CU_SET_ACCESSED_BY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_SET_ACCESSED_BY, 'Data will be accessed by the specified device, so prevent page faults as much as possible') + CU_UNSET_ACCESSED_BY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_UNSET_ACCESSED_BY, 'Let the Unified Memory subsystem decide on the page faulting policy for the specified device') + +class MemRangeAttribute(_cyb_FastEnum): + """ + See `CUmem_range_attribute`. + """ + CU_ATTRIBUTE_READ_MOSTLY = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY, 'Whether the range will mostly be read and only occasionally be written to') + CU_ATTRIBUTE_PREFERRED_LOCATION = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION, 'The preferred location of the range') + CU_ATTRIBUTE_ACCESSED_BY = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY, 'Memory range has `CU_MEM_ADVISE_SET_ACCESSED_BY` set for specified device') + CU_ATTRIBUTE_LAST_PREFETCH_LOCATION = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION, 'The last location to which the range was prefetched') + CU_ATTRIBUTE_PREFERRED_LOCATION_TYPE = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE, 'The preferred location type of the range') + CU_ATTRIBUTE_PREFERRED_LOCATION_ID = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID, 'The preferred location id of the range') + CU_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE, 'The last location type to which the range was prefetched') + CU_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID, 'The last location id to which the range was prefetched') + +class JitOption(_cyb_FastEnum): + """ + Online compiler and linker options + + See `CUjit_option`. + """ + CU_JIT_MAX_REGISTERS = (cydriver.CUjit_option_enum.CU_JIT_MAX_REGISTERS, 'Max number of registers that a thread may use. Option type: unsigned int Applies to: compiler only') + CU_JIT_THREADS_PER_BLOCK = (cydriver.CUjit_option_enum.CU_JIT_THREADS_PER_BLOCK, '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 `CU_JIT_TARGET`. Option type: unsigned int Applies to: compiler only') + CU_JIT_WALL_TIME = (cydriver.CUjit_option_enum.CU_JIT_WALL_TIME, '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') + CU_JIT_INFO_LOG_BUFFER = (cydriver.CUjit_option_enum.CU_JIT_INFO_LOG_BUFFER, 'Pointer to a buffer in which to print any log messages that are informational in nature (the buffer size is specified via option `CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES`) Option type: char * Applies to: compiler and linker') + CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = (cydriver.CUjit_option_enum.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, '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') + CU_JIT_ERROR_LOG_BUFFER = (cydriver.CUjit_option_enum.CU_JIT_ERROR_LOG_BUFFER, 'Pointer to a buffer in which to print any log messages that reflect errors (the buffer size is specified via option `CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES`) Option type: char * Applies to: compiler and linker') + CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = (cydriver.CUjit_option_enum.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, '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') + CU_JIT_OPTIMIZATION_LEVEL = (cydriver.CUjit_option_enum.CU_JIT_OPTIMIZATION_LEVEL, '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') + CU_JIT_TARGET_FROM_CUCONTEXT = (cydriver.CUjit_option_enum.CU_JIT_TARGET_FROM_CUCONTEXT, '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') + CU_JIT_TARGET = (cydriver.CUjit_option_enum.CU_JIT_TARGET, 'Target is chosen based on supplied `CUjit_target`. Cannot be combined with `CU_JIT_THREADS_PER_BLOCK`. Option type: unsigned int for enumerated type `CUjit_target` Applies to: compiler and linker') + CU_JIT_FALLBACK_STRATEGY = (cydriver.CUjit_option_enum.CU_JIT_FALLBACK_STRATEGY, 'Specifies choice of fallback strategy if matching cubin is not found. Choice is based on supplied `CUjit_fallback`. This option cannot be used with cuLink* APIs as the linker requires exact matches. Option type: unsigned int for enumerated type `CUjit_fallback` Applies to: compiler only') + CU_JIT_GENERATE_DEBUG_INFO = (cydriver.CUjit_option_enum.CU_JIT_GENERATE_DEBUG_INFO, 'Specifies whether to create debug information in output (-g) (0: false, default) Option type: int Applies to: compiler and linker') + CU_JIT_LOG_VERBOSE = (cydriver.CUjit_option_enum.CU_JIT_LOG_VERBOSE, 'Generate verbose log messages (0: false, default) Option type: int Applies to: compiler and linker') + CU_JIT_GENERATE_LINE_INFO = (cydriver.CUjit_option_enum.CU_JIT_GENERATE_LINE_INFO, 'Generate line number information (-lineinfo) (0: false, default) Option type: int Applies to: compiler only') + CU_JIT_CACHE_MODE = (cydriver.CUjit_option_enum.CU_JIT_CACHE_MODE, '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') + CU_JIT_NEW_SM3X_OPT = (cydriver.CUjit_option_enum.CU_JIT_NEW_SM3X_OPT, '[Deprecated]') + CU_JIT_FAST_COMPILE = (cydriver.CUjit_option_enum.CU_JIT_FAST_COMPILE, 'This jit option is used for internal purpose only.') + CU_JIT_GLOBAL_SYMBOL_NAMES = (cydriver.CUjit_option_enum.CU_JIT_GLOBAL_SYMBOL_NAMES, 'Array of device symbol names that will be relocated to the corresponding host addresses stored in `CU_JIT_GLOBAL_SYMBOL_ADDRESSES`. Must contain `CU_JIT_GLOBAL_SYMBOL_COUNT` 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') + CU_JIT_GLOBAL_SYMBOL_ADDRESSES = (cydriver.CUjit_option_enum.CU_JIT_GLOBAL_SYMBOL_ADDRESSES, 'Array of host addresses that will be used to relocate corresponding device symbols stored in `CU_JIT_GLOBAL_SYMBOL_NAMES`. Must contain `CU_JIT_GLOBAL_SYMBOL_COUNT` entries. Option type: void ** Applies to: dynamic linker only') + CU_JIT_GLOBAL_SYMBOL_COUNT = (cydriver.CUjit_option_enum.CU_JIT_GLOBAL_SYMBOL_COUNT, 'Number of entries in `CU_JIT_GLOBAL_SYMBOL_NAMES` and `CU_JIT_GLOBAL_SYMBOL_ADDRESSES` arrays. Option type: unsigned int Applies to: dynamic linker only') + CU_JIT_LTO = (cydriver.CUjit_option_enum.CU_JIT_LTO, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_FTZ = (cydriver.CUjit_option_enum.CU_JIT_FTZ, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_PREC_DIV = (cydriver.CUjit_option_enum.CU_JIT_PREC_DIV, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_PREC_SQRT = (cydriver.CUjit_option_enum.CU_JIT_PREC_SQRT, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_FMA = (cydriver.CUjit_option_enum.CU_JIT_FMA, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_REFERENCED_KERNEL_NAMES = (cydriver.CUjit_option_enum.CU_JIT_REFERENCED_KERNEL_NAMES, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_REFERENCED_KERNEL_COUNT = (cydriver.CUjit_option_enum.CU_JIT_REFERENCED_KERNEL_COUNT, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_REFERENCED_VARIABLE_NAMES = (cydriver.CUjit_option_enum.CU_JIT_REFERENCED_VARIABLE_NAMES, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_REFERENCED_VARIABLE_COUNT = (cydriver.CUjit_option_enum.CU_JIT_REFERENCED_VARIABLE_COUNT, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_OPTIMIZE_UNUSED_DEVICE_VARIABLES = (cydriver.CUjit_option_enum.CU_JIT_OPTIMIZE_UNUSED_DEVICE_VARIABLES, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_POSITION_INDEPENDENT_CODE = (cydriver.CUjit_option_enum.CU_JIT_POSITION_INDEPENDENT_CODE, 'Generate position independent code (0: false) Option type: int Applies to: compiler only') + CU_JIT_MIN_CTA_PER_SM = (cydriver.CUjit_option_enum.CU_JIT_MIN_CTA_PER_SM, '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 `CU_JIT_MAX_REGISTERS` or `CU_JIT_THREADS_PER_BLOCK`. Optimizations based on this option need `CU_JIT_MAX_THREADS_PER_BLOCK` to be specified as well. For kernels already using PTX directive .minnctapersm, this option will be ignored by default. Use `CU_JIT_OVERRIDE_DIRECTIVE_VALUES` to let this option take precedence over the PTX directive. Option type: unsigned int Applies to: compiler only') + CU_JIT_MAX_THREADS_PER_BLOCK = (cydriver.CUjit_option_enum.CU_JIT_MAX_THREADS_PER_BLOCK, '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 `CU_JIT_OVERRIDE_DIRECTIVE_VALUES` to let this option take precedence over the PTX directive. Option type: int Applies to: compiler only') + CU_JIT_OVERRIDE_DIRECTIVE_VALUES = (cydriver.CUjit_option_enum.CU_JIT_OVERRIDE_DIRECTIVE_VALUES, 'This option lets the values specified using `CU_JIT_MAX_REGISTERS`, `CU_JIT_THREADS_PER_BLOCK`, `CU_JIT_MAX_THREADS_PER_BLOCK` and `CU_JIT_MIN_CTA_PER_SM` take precedence over any PTX directives. (0: Disable, default; 1: Enable) Option type: int Applies to: compiler only') + CU_JIT_SPLIT_COMPILE = (cydriver.CUjit_option_enum.CU_JIT_SPLIT_COMPILE, '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') + CU_JIT_BINARY_LOADER_THREAD_COUNT = (cydriver.CUjit_option_enum.CU_JIT_BINARY_LOADER_THREAD_COUNT, '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') + CU_JIT_NUM_OPTIONS = cydriver.CUjit_option_enum.CU_JIT_NUM_OPTIONS + +class JitTarget(_cyb_FastEnum): + """ + Online compilation targets + + See `CUjit_target`. + """ + CU_TARGET_COMPUTE_30 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_30, 'Compute device class 3.0') + CU_TARGET_COMPUTE_32 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_32, 'Compute device class 3.2') + CU_TARGET_COMPUTE_35 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_35, 'Compute device class 3.5') + CU_TARGET_COMPUTE_37 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_37, 'Compute device class 3.7') + CU_TARGET_COMPUTE_50 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_50, 'Compute device class 5.0') + CU_TARGET_COMPUTE_52 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_52, 'Compute device class 5.2') + CU_TARGET_COMPUTE_53 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_53, 'Compute device class 5.3') + CU_TARGET_COMPUTE_60 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_60, 'Compute device class 6.0.') + CU_TARGET_COMPUTE_61 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_61, 'Compute device class 6.1.') + CU_TARGET_COMPUTE_62 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_62, 'Compute device class 6.2.') + CU_TARGET_COMPUTE_70 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_70, 'Compute device class 7.0.') + CU_TARGET_COMPUTE_72 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_72, 'Compute device class 7.2.') + CU_TARGET_COMPUTE_75 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_75, 'Compute device class 7.5.') + CU_TARGET_COMPUTE_80 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_80, 'Compute device class 8.0.') + CU_TARGET_COMPUTE_86 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_86, 'Compute device class 8.6.') + CU_TARGET_COMPUTE_87 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_87, 'Compute device class 8.7.') + CU_TARGET_COMPUTE_89 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_89, 'Compute device class 8.9.') + CU_TARGET_COMPUTE_90 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_90, 'Compute device class 9.0.') + CU_TARGET_COMPUTE_100 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100, 'Compute device class 10.0.') + CU_TARGET_COMPUTE_110 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110, 'Compute device class 11.0.') + CU_TARGET_COMPUTE_103 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103, 'Compute device class 10.3.') + CU_TARGET_COMPUTE_120 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120, 'Compute device class 12.0.') + CU_TARGET_COMPUTE_121 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121, 'Compute device class 12.1. Compute device class 9.0. with accelerated features.') + CU_TARGET_COMPUTE_90A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_90A, 'Compute device class 10.0. with accelerated features.') + CU_TARGET_COMPUTE_100A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100A, 'Compute device class 11.0 with accelerated features.') + CU_TARGET_COMPUTE_110A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110A, 'Compute device class 10.3. with accelerated features.') + CU_TARGET_COMPUTE_103A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103A, 'Compute device class 12.0. with accelerated features.') + CU_TARGET_COMPUTE_120A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120A, 'Compute device class 12.1. with accelerated features.') + CU_TARGET_COMPUTE_121A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121A, 'Compute device class 10.x with family features.') + CU_TARGET_COMPUTE_100F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100F, 'Compute device class 11.0 with family features.') + CU_TARGET_COMPUTE_110F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110F, 'Compute device class 10.3. with family features.') + CU_TARGET_COMPUTE_103F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103F, 'Compute device class 12.0. with family features.') + CU_TARGET_COMPUTE_120F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120F, 'Compute device class 12.1. with family features.') + CU_TARGET_COMPUTE_121F = cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121F + +class JitFallback(_cyb_FastEnum): + """ + Cubin matching fallback strategies + + See `CUjit_fallback`. + """ + CU_PREFER_PTX = (cydriver.CUjit_fallback_enum.CU_PREFER_PTX, 'Prefer to compile ptx if exact binary match not found') + CU_PREFER_BINARY = (cydriver.CUjit_fallback_enum.CU_PREFER_BINARY, 'Prefer to fall back to compatible binary code if exact match not found') + +class JitCacheMode(_cyb_FastEnum): + """ + Caching modes for dlcm + + See `CUjit_cacheMode`. + """ + CU_JIT_CACHE_OPTION_NONE = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_NONE, 'Compile with no -dlcm flag specified') + CU_JIT_CACHE_OPTION_CG = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_CG, 'Compile with L1 cache disabled') + CU_JIT_CACHE_OPTION_CA = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_CA, 'Compile with L1 cache enabled') + +class JitInputType(_cyb_FastEnum): + """ + Device code formats + + See `CUjitInputType`. + """ + CU_JIT_INPUT_CUBIN = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_CUBIN, 'Compiled device-class-specific device code Applicable options: none') + CU_JIT_INPUT_PTX = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_PTX, 'PTX source code Applicable options: PTX compiler options') + CU_JIT_INPUT_FATBINARY = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_FATBINARY, 'Bundle of multiple cubins and/or PTX of some device code Applicable options: PTX compiler options, `CU_JIT_FALLBACK_STRATEGY`') + CU_JIT_INPUT_OBJECT = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_OBJECT, 'Host object with embedded device code Applicable options: PTX compiler options, `CU_JIT_FALLBACK_STRATEGY`') + CU_JIT_INPUT_LIBRARY = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_LIBRARY, 'Archive of host objects with embedded device code Applicable options: PTX compiler options, `CU_JIT_FALLBACK_STRATEGY`') + CU_JIT_INPUT_NVVM = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_NVVM, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + CU_JIT_NUM_INPUT_TYPES = cydriver.CUjitInputType_enum.CU_JIT_NUM_INPUT_TYPES + +class GraphicsRegisterFlags(_cyb_FastEnum): + """ + Flags to register a graphics resource + + See `CUgraphicsRegisterFlags`. + """ + CU_NONE = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_NONE + CU_READ_ONLY = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY + CU_WRITE_DISCARD = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD + CU_SURFACE_LDST = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST + CU_TEXTURE_GATHER = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER + +class GraphicsMapResourceFlags(_cyb_FastEnum): + """ + Flags for mapping and unmapping interop resources + + See `CUgraphicsMapResourceFlags`. + """ + CU_NONE = cydriver.CUgraphicsMapResourceFlags_enum.CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE + CU_READ_ONLY = cydriver.CUgraphicsMapResourceFlags_enum.CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY + CU_WRITE_DISCARD = cydriver.CUgraphicsMapResourceFlags_enum.CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD + +class ArrayCubemapFace(_cyb_FastEnum): + """ + Array indices for cube faces + + See `CUarray_cubemap_face`. + """ + CU_CUBEMAP_FACE_POSITIVE_X = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_X, 'Positive X face of cubemap') + CU_CUBEMAP_FACE_NEGATIVE_X = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_X, 'Negative X face of cubemap') + CU_CUBEMAP_FACE_POSITIVE_Y = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_Y, 'Positive Y face of cubemap') + CU_CUBEMAP_FACE_NEGATIVE_Y = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_Y, 'Negative Y face of cubemap') + CU_CUBEMAP_FACE_POSITIVE_Z = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_Z, 'Positive Z face of cubemap') + CU_CUBEMAP_FACE_NEGATIVE_Z = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_Z, 'Negative Z face of cubemap') + +class Limit(_cyb_FastEnum): + """ + Limits + + See `CUlimit`. + """ + CU_STACK_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_STACK_SIZE, 'GPU thread stack size') + CU_PRINTF_FIFO_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_PRINTF_FIFO_SIZE, 'GPU printf FIFO size') + CU_MALLOC_HEAP_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_MALLOC_HEAP_SIZE, 'GPU malloc heap size') + CU_DEV_RUNTIME_SYNC_DEPTH = (cydriver.CUlimit_enum.CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH, 'GPU device runtime launch synchronize depth') + CU_DEV_RUNTIME_PENDING_LAUNCH_COUNT = (cydriver.CUlimit_enum.CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT, 'GPU device runtime pending launch count') + CU_MAX_L2_FETCH_GRANULARITY = (cydriver.CUlimit_enum.CU_LIMIT_MAX_L2_FETCH_GRANULARITY, 'A value between 0 and 128 that indicates the maximum fetch granularity of L2 (in Bytes). This is a hint') + CU_PERSISTING_L2_CACHE_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_PERSISTING_L2_CACHE_SIZE, 'A size in bytes for L2 persisting lines cache size') + CU_SHMEM_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_SHMEM_SIZE, 'A maximum size in bytes of shared memory available to CUDA kernels on a CIG context. Can only be queried, cannot be set') + CU_CIG_ENABLED = (cydriver.CUlimit_enum.CU_LIMIT_CIG_ENABLED, 'A non-zero value indicates this CUDA context is a CIG-enabled context. Can only be queried, cannot be set') + CU_CIG_SHMEM_FALLBACK_ENABLED = (cydriver.CUlimit_enum.CU_LIMIT_CIG_SHMEM_FALLBACK_ENABLED, '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') + CU_MAX = cydriver.CUlimit_enum.CU_LIMIT_MAX + +class Resourcetype(_cyb_FastEnum): + """ + Resource types + + See `CUresourcetype`. + """ + CU_RESOURCE_TYPE_ARRAY = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_ARRAY, 'Array resource') + CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_MIPMAPPED_ARRAY, 'Mipmapped array resource') + CU_RESOURCE_TYPE_LINEAR = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_LINEAR, 'Linear resource') + CU_RESOURCE_TYPE_PITCH2D = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_PITCH2D, 'Pitch 2D resource') + +class AccessProperty(_cyb_FastEnum): + """ + Specifies performance hint with `CUaccessPolicyWindow` for hitProp and + missProp members. + + See `CUaccessProperty`. + """ + CU_NORMAL = (cydriver.CUaccessProperty_enum.CU_ACCESS_PROPERTY_NORMAL, 'Normal cache persistence.') + CU_STREAMING = (cydriver.CUaccessProperty_enum.CU_ACCESS_PROPERTY_STREAMING, 'Streaming access is less likely to persit from cache.') + CU_PERSISTING = (cydriver.CUaccessProperty_enum.CU_ACCESS_PROPERTY_PERSISTING, 'Persisting access is more likely to persist in cache.') + +class GraphConditionalNodeType(_cyb_FastEnum): + """ + Conditional node types + + See `CUgraphConditionalNodeType`. + """ + CU_GRAPH_COND_TYPE_IF = (cydriver.CUgraphConditionalNodeType_enum.CU_GRAPH_COND_TYPE_IF, "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.") + CU_GRAPH_COND_TYPE_WHILE = (cydriver.CUgraphConditionalNodeType_enum.CU_GRAPH_COND_TYPE_WHILE, "Conditional 'while' Node. Body executed repeatedly while condition value is non-zero.") + CU_GRAPH_COND_TYPE_SWITCH = (cydriver.CUgraphConditionalNodeType_enum.CU_GRAPH_COND_TYPE_SWITCH, "Conditional 'switch' Node. Body[n] is executed once, where 'n' is the value of the condition. If the condition does not match a body index, no body is launched.") + +class GraphNodeType(_cyb_FastEnum): + """ + Graph node types + + See `CUgraphNodeType`. + """ + CU_KERNEL = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_KERNEL, 'GPU kernel node') + CU_MEMCPY = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEMCPY, 'Memcpy node') + CU_MEMSET = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEMSET, 'Memset node') + CU_HOST = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_HOST, 'Host (executable) node') + CU_GRAPH = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_GRAPH, 'Node which executes an embedded graph') + CU_EMPTY = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EMPTY, 'Empty (no-op) node') + CU_WAIT_EVENT = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_WAIT_EVENT, 'External event wait node') + CU_EVENT_RECORD = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EVENT_RECORD, 'External event record node') + CU_EXT_SEMAS_SIGNAL = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL, 'External semaphore signal node') + CU_EXT_SEMAS_WAIT = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT, 'External semaphore wait node') + CU_MEM_ALLOC = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEM_ALLOC, 'Memory Allocation Node') + CU_MEM_FREE = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEM_FREE, 'Memory Free Node') + CU_BATCH_MEM_OP = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_BATCH_MEM_OP, 'Batch MemOp Node See `cuStreamBatchMemOp` and `CUstreamBatchMemOpType` for what these nodes can do.') + CU_CONDITIONAL = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_CONDITIONAL, '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 `cuGraphConditionalHandleCreate`. 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.') + CU_RESERVED_16 = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_RESERVED_16, 'Reserved') + +class GraphDependencyType(_cyb_FastEnum): + """ + Type annotations that can be applied to graph edges as part of + `CUgraphEdgeData`. + + See `CUgraphDependencyType`. + """ + CU_DEFAULT = (cydriver.CUgraphDependencyType_enum.CU_GRAPH_DEPENDENCY_TYPE_DEFAULT, 'This is an ordinary dependency.') + CU_PROGRAMMATIC = (cydriver.CUgraphDependencyType_enum.CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC, '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.') + +class GraphInstantiateResult(_cyb_FastEnum): + """ + Graph instantiation results + + See `CUgraphInstantiateResult`. + """ + CUDA_GRAPH_INSTANTIATE_SUCCESS = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_SUCCESS, 'Instantiation succeeded') + CUDA_GRAPH_INSTANTIATE_ERROR = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_ERROR, 'Instantiation failed for an unexpected reason which is described in the return value of the function') + CUDA_GRAPH_INSTANTIATE_INVALID_STRUCTURE = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_INVALID_STRUCTURE, 'Instantiation failed due to invalid structure, such as cycles') + CUDA_GRAPH_INSTANTIATE_NODE_OPERATION_NOT_SUPPORTED = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_NODE_OPERATION_NOT_SUPPORTED, 'Instantiation for device launch failed because the graph contained an unsupported operation') + CUDA_GRAPH_INSTANTIATE_MULTIPLE_CTXS_NOT_SUPPORTED = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_MULTIPLE_CTXS_NOT_SUPPORTED, 'Instantiation for device launch failed due to the nodes belonging to different contexts') + CUDA_GRAPH_INSTANTIATE_CONDITIONAL_HANDLE_UNUSED = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_CONDITIONAL_HANDLE_UNUSED, 'One or more conditional handles are not associated with conditional nodes') + +class SynchronizationPolicy(_cyb_FastEnum): + """ + See `CUsynchronizationPolicy`. + """ + CU_SYNC_POLICY_AUTO = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_AUTO + CU_SYNC_POLICY_SPIN = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_SPIN + CU_SYNC_POLICY_YIELD = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_YIELD + CU_SYNC_POLICY_BLOCKING_SYNC = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_BLOCKING_SYNC + +class ClusterSchedulingPolicy(_cyb_FastEnum): + """ + Cluster scheduling policies. These may be passed to + `cuFuncSetAttribute` or `cuKernelSetAttribute` + + See `CUclusterSchedulingPolicy`. + """ + CU_DEFAULT = (cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_DEFAULT, 'the default policy') + CU_SPREAD = (cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_SPREAD, 'spread the blocks within a cluster to the SMs') + CU_LOAD_BALANCING = (cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_LOAD_BALANCING, 'allow the hardware to load-balance the blocks in a cluster to the SMs') + +class LaunchMemSyncDomain(_cyb_FastEnum): + """ + 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 + `CU_LAUNCH_MEM_SYNC_DOMAIN_REMOTE` will have a different domain ID. + User may also alter the domain ID with `CUlaunchMemSyncDomainMap` for a + specific stream / graph node / kernel launch. See + `CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN`, `cuStreamSetAttribute`, + `cuLaunchKernelEx`, `cuGraphKernelNodeSetAttribute`. 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. + + See `CUlaunchMemSyncDomain`. + """ + CU_DEFAULT = (cydriver.CUlaunchMemSyncDomain_enum.CU_LAUNCH_MEM_SYNC_DOMAIN_DEFAULT, 'Launch kernels in the default domain') + CU_REMOTE = (cydriver.CUlaunchMemSyncDomain_enum.CU_LAUNCH_MEM_SYNC_DOMAIN_REMOTE, 'Launch kernels in the remote domain') + +class LaunchAttributeID(_cyb_FastEnum): + """ + Launch attributes enum; used as id field of `CUlaunchAttribute` + + See `CUlaunchAttributeID`. + """ + CU_LAUNCH_ATTRIBUTE_IGNORE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_IGNORE, 'Ignored entry, for convenient composition') + CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.accessPolicyWindow`.') + CU_LAUNCH_ATTRIBUTE_COOPERATIVE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_COOPERATIVE, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.cooperative`.') + CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY, 'Valid for streams. See `CUlaunchAttributeValue.syncPolicy`.') + CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.clusterDim`.') + CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.clusterSchedulingPolicyPreference`.') + CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION, "Valid for launches. Setting `CUlaunchAttributeValue.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).") + CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT, "Valid for launches. Set `CUlaunchAttributeValue.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 `cuEventSynchronize()`) are not guaranteed to observe the release precisely when it is released. For example, `cuEventSynchronize()` 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 `CU_EVENT_DISABLE_TIMING` flag set).") + CU_LAUNCH_ATTRIBUTE_PRIORITY = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PRIORITY, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.priority`.') + CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN_MAP = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN_MAP, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.memSyncDomainMap`.') + CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.memSyncDomain`.') + CU_LAUNCH_ATTRIBUTE_PREFERRED_CLUSTER_DIMENSION = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PREFERRED_CLUSTER_DIMENSION, 'Valid for graph nodes, launches. Set `CUlaunchAttributeValue.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 `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION` 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.') + CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT, 'Valid for launches. Set `CUlaunchAttributeValue.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 `CU_EVENT_DISABLE_TIMING` flag set).') + CU_LAUNCH_ATTRIBUTE_DEVICE_UPDATABLE_KERNEL_NODE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_DEVICE_UPDATABLE_KERNEL_NODE, "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. `CUlaunchAttributeValue.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 `CUlaunchAttributeValue.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 `cuGraphDestroyNode`. 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 `cuGraphKernelNodeCopyAttributes`. 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 `cuGraphExecUpdate`. If a graph contains device-updatable nodes and updates those nodes from the device from within the graph, the graph must be uploaded with `cuGraphUpload` 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.") + CU_LAUNCH_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT, 'Valid for launches. On devices where the L1 cache and shared memory use the same hardware resources, setting `CUlaunchAttributeValue.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 `CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT`. This is only a hint, and the CUDA driver can choose a different configuration if required for the launch.') + CU_LAUNCH_ATTRIBUTE_NVLINK_UTIL_CENTRIC_SCHEDULING = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_NVLINK_UTIL_CENTRIC_SCHEDULING, "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 `CUlaunchAttributeValue.nvlinkUtilCentricScheduling` are 0 (disabled) and 1 (enabled).") + CU_LAUNCH_ATTRIBUTE_PORTABLE_CLUSTER_SIZE_MODE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PORTABLE_CLUSTER_SIZE_MODE, 'Valid for graph nodes, launches. This controls whether the kernel launch is allowed to use a non-portable cluster size. Valid values for `CUlaunchAttributeValue.portableClusterSizeMode` are described in `CUlaunchAttributePortableClusterMode`. Any other value will return `CUDA_ERROR_INVALID_VALUE`') + CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE, 'Valid for graph nodes, launches. This indicates if the kernel is allowed to use a non-portable dynamic shared memory mode.') + +class StreamCaptureStatus(_cyb_FastEnum): + """ + Possible stream capture statuses returned by `cuStreamIsCapturing` + + See `CUstreamCaptureStatus`. + """ + CU_NONE = (cydriver.CUstreamCaptureStatus_enum.CU_STREAM_CAPTURE_STATUS_NONE, 'Stream is not capturing') + CU_ACTIVE = (cydriver.CUstreamCaptureStatus_enum.CU_STREAM_CAPTURE_STATUS_ACTIVE, 'Stream is actively capturing') + CU_INVALIDATED = (cydriver.CUstreamCaptureStatus_enum.CU_STREAM_CAPTURE_STATUS_INVALIDATED, 'Stream is part of a capture sequence that has been invalidated, but not terminated') + +class StreamCaptureMode(_cyb_FastEnum): + """ + Possible modes for stream capture thread interactions. For more details + see `cuStreamBeginCapture` and `cuThreadExchangeStreamCaptureMode` + + See `CUstreamCaptureMode`. + """ + CU_GLOBAL = cydriver.CUstreamCaptureMode_enum.CU_STREAM_CAPTURE_MODE_GLOBAL + CU_THREAD_LOCAL = cydriver.CUstreamCaptureMode_enum.CU_STREAM_CAPTURE_MODE_THREAD_LOCAL + CU_RELAXED = cydriver.CUstreamCaptureMode_enum.CU_STREAM_CAPTURE_MODE_RELAXED + +class DriverProcAddressFlags(_cyb_FastEnum): + """ + Flags to specify search options. For more details see + `cuGetProcAddress` + + See `CUdriverProcAddress_flags`. + """ + CU_GET_PROC_ADDRESS_DEFAULT = (cydriver.CUdriverProcAddress_flags_enum.CU_GET_PROC_ADDRESS_DEFAULT, 'Default search mode for driver symbols.') + CU_GET_PROC_ADDRESS_LEGACY_STREAM = (cydriver.CUdriverProcAddress_flags_enum.CU_GET_PROC_ADDRESS_LEGACY_STREAM, 'Search for legacy versions of driver symbols.') + CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM = (cydriver.CUdriverProcAddress_flags_enum.CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM, 'Search for per-thread versions of driver symbols.') + +class DriverProcAddressQueryResult(_cyb_FastEnum): + """ + Flags to indicate search status. For more details see + `cuGetProcAddress` + + See `CUdriverProcAddressQueryResult`. + """ + CU_GET_PROC_ADDRESS_SUCCESS = (cydriver.CUdriverProcAddressQueryResult_enum.CU_GET_PROC_ADDRESS_SUCCESS, 'Symbol was succesfully found') + CU_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND = (cydriver.CUdriverProcAddressQueryResult_enum.CU_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND, 'Symbol was not found in search') + CU_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT = (cydriver.CUdriverProcAddressQueryResult_enum.CU_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT, 'Symbol was found but version supplied was not sufficient') + +class ExecAffinityType(_cyb_FastEnum): + """ + Execution Affinity Types + + See `CUexecAffinityType`. + """ + CU_SM_COUNT = (cydriver.CUexecAffinityType_enum.CU_EXEC_AFFINITY_TYPE_SM_COUNT, 'Create a context with limited SMs.') + CU_MAX = cydriver.CUexecAffinityType_enum.CU_EXEC_AFFINITY_TYPE_MAX + +class CigDataType(_cyb_FastEnum): + """ + See `CUcigDataType`. + """ + D3D12_COMMAND_QUEUE = (cydriver.CUcigDataType_enum.CIG_DATA_TYPE_D3D12_COMMAND_QUEUE, 'D3D12 Command Queue Handle') + NV_BLOB = (cydriver.CUcigDataType_enum.CIG_DATA_TYPE_NV_BLOB, 'Nvidia specific data blob used for Vulkan and other NV clients') + +class LibraryOption(_cyb_FastEnum): + """ + Library options to be specified with `cuLibraryLoadData()` or + `cuLibraryLoadFromFile()` + + See `CUlibraryOption`. + """ + CU_LIBRARY_HOST_UNIVERSAL_FUNCTION_AND_DATA_TABLE = cydriver.CUlibraryOption_enum.CU_LIBRARY_HOST_UNIVERSAL_FUNCTION_AND_DATA_TABLE + CU_LIBRARY_BINARY_IS_PRESERVED = (cydriver.CUlibraryOption_enum.CU_LIBRARY_BINARY_IS_PRESERVED, 'Specifes that the argument `code` passed to `cuLibraryLoadData()` will be preserved. Specifying this option will let the driver know that `code` can be accessed at any point until `cuLibraryUnload()`. 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 `cuLibraryLoadFromFile()` is invalid and will return `CUDA_ERROR_INVALID_VALUE`.') + CU_LIBRARY_NUM_OPTIONS = cydriver.CUlibraryOption_enum.CU_LIBRARY_NUM_OPTIONS + +class Result(_cyb_FastEnum): + """ + Error codes + + See `CUresult`. + """ + CUDA_SUCCESS = (cydriver.cudaError_enum.CUDA_SUCCESS, 'The API call returned with no errors. In the case of query calls, this also means that the operation being queried is complete (see `cuEventQuery()` and `cuStreamQuery()`).') + CUDA_ERROR_INVALID_VALUE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_VALUE, 'This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values.') + CUDA_ERROR_OUT_OF_MEMORY = (cydriver.cudaError_enum.CUDA_ERROR_OUT_OF_MEMORY, 'The API call failed because it was unable to allocate enough memory or other resources to perform the requested operation.') + CUDA_ERROR_NOT_INITIALIZED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_INITIALIZED, 'This indicates that the CUDA driver has not been initialized with `cuInit()` or that initialization has failed.') + CUDA_ERROR_DEINITIALIZED = (cydriver.cudaError_enum.CUDA_ERROR_DEINITIALIZED, 'This indicates that the CUDA driver is in the process of shutting down.') + CUDA_ERROR_PROFILER_DISABLED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_DISABLED, 'This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler.') + CUDA_ERROR_PROFILER_NOT_INITIALIZED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_NOT_INITIALIZED, '[Deprecated]') + CUDA_ERROR_PROFILER_ALREADY_STARTED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_ALREADY_STARTED, '[Deprecated]') + CUDA_ERROR_PROFILER_ALREADY_STOPPED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_ALREADY_STOPPED, '[Deprecated]') + CUDA_ERROR_STUB_LIBRARY = (cydriver.cudaError_enum.CUDA_ERROR_STUB_LIBRARY, '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.') + CUDA_ERROR_CALL_REQUIRES_NEWER_DRIVER = (cydriver.cudaError_enum.CUDA_ERROR_CALL_REQUIRES_NEWER_DRIVER, '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.') + CUDA_ERROR_DEVICE_UNAVAILABLE = (cydriver.cudaError_enum.CUDA_ERROR_DEVICE_UNAVAILABLE, 'This indicates that requested CUDA device is unavailable at the current time. Devices are often unavailable due to use of `CU_COMPUTEMODE_EXCLUSIVE_PROCESS` or `CU_COMPUTEMODE_PROHIBITED`.') + CUDA_ERROR_NO_DEVICE = (cydriver.cudaError_enum.CUDA_ERROR_NO_DEVICE, 'This indicates that no CUDA-capable devices were detected by the installed CUDA driver.') + CUDA_ERROR_INVALID_DEVICE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_DEVICE, '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.') + CUDA_ERROR_DEVICE_NOT_LICENSED = (cydriver.cudaError_enum.CUDA_ERROR_DEVICE_NOT_LICENSED, 'This error indicates that the Grid license is not applied.') + CUDA_ERROR_INVALID_IMAGE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_IMAGE, 'This indicates that the device kernel image is invalid. This can also indicate an invalid CUDA module.') + CUDA_ERROR_INVALID_CONTEXT = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_CONTEXT, '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 `cuCtxDestroy()` invoked on it). This can also be returned if a user mixes different API versions (i.e. 3010 context with 3020 API calls). See `cuCtxGetApiVersion()` for more details. This can also be returned if the green context passed to an API call was not converted to a `CUcontext` using `cuCtxFromGreenCtx` API.') + CUDA_ERROR_CONTEXT_ALREADY_CURRENT = (cydriver.cudaError_enum.CUDA_ERROR_CONTEXT_ALREADY_CURRENT, 'This indicated that the context being supplied as a parameter to the API call was already the active context. [Deprecated]') + CUDA_ERROR_MAP_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_MAP_FAILED, 'This indicates that a map or register operation has failed.') + CUDA_ERROR_UNMAP_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_UNMAP_FAILED, 'This indicates that an unmap or unregister operation has failed.') + CUDA_ERROR_ARRAY_IS_MAPPED = (cydriver.cudaError_enum.CUDA_ERROR_ARRAY_IS_MAPPED, 'This indicates that the specified array is currently mapped and thus cannot be destroyed.') + CUDA_ERROR_ALREADY_MAPPED = (cydriver.cudaError_enum.CUDA_ERROR_ALREADY_MAPPED, 'This indicates that the resource is already mapped.') + CUDA_ERROR_NO_BINARY_FOR_GPU = (cydriver.cudaError_enum.CUDA_ERROR_NO_BINARY_FOR_GPU, '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.') + CUDA_ERROR_ALREADY_ACQUIRED = (cydriver.cudaError_enum.CUDA_ERROR_ALREADY_ACQUIRED, 'This indicates that a resource has already been acquired.') + CUDA_ERROR_NOT_MAPPED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_MAPPED, 'This indicates that a resource is not mapped.') + CUDA_ERROR_NOT_MAPPED_AS_ARRAY = (cydriver.cudaError_enum.CUDA_ERROR_NOT_MAPPED_AS_ARRAY, 'This indicates that a mapped resource is not available for access as an array.') + CUDA_ERROR_NOT_MAPPED_AS_POINTER = (cydriver.cudaError_enum.CUDA_ERROR_NOT_MAPPED_AS_POINTER, 'This indicates that a mapped resource is not available for access as a pointer.') + CUDA_ERROR_ECC_UNCORRECTABLE = (cydriver.cudaError_enum.CUDA_ERROR_ECC_UNCORRECTABLE, 'This indicates that an uncorrectable ECC error was detected during execution.') + CUDA_ERROR_UNSUPPORTED_LIMIT = (cydriver.cudaError_enum.CUDA_ERROR_UNSUPPORTED_LIMIT, 'This indicates that the `CUlimit` passed to the API call is not supported by the active device.') + CUDA_ERROR_CONTEXT_ALREADY_IN_USE = (cydriver.cudaError_enum.CUDA_ERROR_CONTEXT_ALREADY_IN_USE, 'This indicates that the `CUcontext` 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.') + CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = (cydriver.cudaError_enum.CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, 'This indicates that peer access is not supported across the given devices.') + CUDA_ERROR_INVALID_PTX = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_PTX, 'This indicates that a PTX JIT compilation failed.') + CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT, 'This indicates an error with OpenGL or DirectX context.') + CUDA_ERROR_NVLINK_UNCORRECTABLE = (cydriver.cudaError_enum.CUDA_ERROR_NVLINK_UNCORRECTABLE, 'This indicates that an uncorrectable NVLink error was detected during the execution.') + CUDA_ERROR_JIT_COMPILER_NOT_FOUND = (cydriver.cudaError_enum.CUDA_ERROR_JIT_COMPILER_NOT_FOUND, 'This indicates that the PTX JIT compiler library was not found.') + CUDA_ERROR_UNSUPPORTED_PTX_VERSION = (cydriver.cudaError_enum.CUDA_ERROR_UNSUPPORTED_PTX_VERSION, 'This indicates that the provided PTX was compiled with an unsupported toolchain.') + CUDA_ERROR_JIT_COMPILATION_DISABLED = (cydriver.cudaError_enum.CUDA_ERROR_JIT_COMPILATION_DISABLED, 'This indicates that the PTX JIT compilation was disabled.') + CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY = (cydriver.cudaError_enum.CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY, 'This indicates that the `CUexecAffinityType` passed to the API call is not supported by the active device.') + CUDA_ERROR_UNSUPPORTED_DEVSIDE_SYNC = (cydriver.cudaError_enum.CUDA_ERROR_UNSUPPORTED_DEVSIDE_SYNC, 'This indicates that the code to be compiled by the PTX JIT contains unsupported call to cudaDeviceSynchronize.') + CUDA_ERROR_CONTAINED = (cydriver.cudaError_enum.CUDA_ERROR_CONTAINED, "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.") + CUDA_ERROR_INVALID_SOURCE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_SOURCE, 'This indicates that the device kernel source is invalid. This includes compilation/linker errors encountered in device code or user error.') + CUDA_ERROR_FILE_NOT_FOUND = (cydriver.cudaError_enum.CUDA_ERROR_FILE_NOT_FOUND, 'This indicates that the file specified was not found.') + CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = (cydriver.cudaError_enum.CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, 'This indicates that a link to a shared object failed to resolve.') + CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, 'This indicates that initialization of a shared object failed.') + CUDA_ERROR_OPERATING_SYSTEM = (cydriver.cudaError_enum.CUDA_ERROR_OPERATING_SYSTEM, 'This indicates that an OS call failed.') + CUDA_ERROR_INVALID_HANDLE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_HANDLE, 'This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like `CUstream` and `CUevent`.') + CUDA_ERROR_ILLEGAL_STATE = (cydriver.cudaError_enum.CUDA_ERROR_ILLEGAL_STATE, 'This indicates that a resource required by the API call is not in a valid state to perform the requested operation.') + CUDA_ERROR_LOSSY_QUERY = (cydriver.cudaError_enum.CUDA_ERROR_LOSSY_QUERY, '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.') + CUDA_ERROR_NOT_FOUND = (cydriver.cudaError_enum.CUDA_ERROR_NOT_FOUND, '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.') + CUDA_ERROR_NOT_READY = (cydriver.cudaError_enum.CUDA_ERROR_NOT_READY, 'This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than `CUDA_SUCCESS` (which indicates completion). Calls that may return this value include `cuEventQuery()` and `cuStreamQuery()`.') + CUDA_ERROR_ILLEGAL_ADDRESS = (cydriver.cudaError_enum.CUDA_ERROR_ILLEGAL_ADDRESS, '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.') + CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = (cydriver.cudaError_enum.CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, "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.") + CUDA_ERROR_LAUNCH_TIMEOUT = (cydriver.cudaError_enum.CUDA_ERROR_LAUNCH_TIMEOUT, 'This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device attribute `CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT` 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.') + CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = (cydriver.cudaError_enum.CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, 'This error indicates a kernel launch that uses an incompatible texturing mode.') + CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = (cydriver.cudaError_enum.CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED, 'This error indicates that a call to `cuCtxEnablePeerAccess()` is trying to re-enable peer access to a context which has already had peer access to it enabled.') + CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = (cydriver.cudaError_enum.CUDA_ERROR_PEER_ACCESS_NOT_ENABLED, 'This error indicates that `cuCtxDisablePeerAccess()` is trying to disable peer access which has not been enabled yet via `cuCtxEnablePeerAccess()`.') + CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = (cydriver.cudaError_enum.CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE, 'This error indicates that the primary context for the specified device has already been initialized.') + CUDA_ERROR_CONTEXT_IS_DESTROYED = (cydriver.cudaError_enum.CUDA_ERROR_CONTEXT_IS_DESTROYED, 'This error indicates that the context current to the calling thread has been destroyed using `cuCtxDestroy`, or is a primary context which has not yet been initialized.') + CUDA_ERROR_ASSERT = (cydriver.cudaError_enum.CUDA_ERROR_ASSERT, '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.') + CUDA_ERROR_TOO_MANY_PEERS = (cydriver.cudaError_enum.CUDA_ERROR_TOO_MANY_PEERS, 'This error indicates that the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to `cuCtxEnablePeerAccess()`.') + CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = (cydriver.cudaError_enum.CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED, 'This error indicates that the memory range passed to `cuMemHostRegister()` has already been registered.') + CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = (cydriver.cudaError_enum.CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED, 'This error indicates that the pointer passed to `cuMemHostUnregister()` does not correspond to any currently registered memory region.') + CUDA_ERROR_HARDWARE_STACK_ERROR = (cydriver.cudaError_enum.CUDA_ERROR_HARDWARE_STACK_ERROR, '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.') + CUDA_ERROR_ILLEGAL_INSTRUCTION = (cydriver.cudaError_enum.CUDA_ERROR_ILLEGAL_INSTRUCTION, '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.') + CUDA_ERROR_MISALIGNED_ADDRESS = (cydriver.cudaError_enum.CUDA_ERROR_MISALIGNED_ADDRESS, '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.') + CUDA_ERROR_INVALID_ADDRESS_SPACE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_ADDRESS_SPACE, '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.') + CUDA_ERROR_INVALID_PC = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_PC, '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.') + CUDA_ERROR_LAUNCH_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_LAUNCH_FAILED, '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.') + CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE = (cydriver.cudaError_enum.CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, 'This error indicates that the number of blocks launched per grid for a kernel that was launched via either `cuLaunchCooperativeKernel` or `cuLaunchCooperativeKernelMultiDevice` exceeds the maximum number of blocks as allowed by `cuOccupancyMaxActiveBlocksPerMultiprocessor` or `cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags` times the number of multiprocessors as specified by the device attribute `CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT`.') + CUDA_ERROR_TENSOR_MEMORY_LEAK = (cydriver.cudaError_enum.CUDA_ERROR_TENSOR_MEMORY_LEAK, '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.') + CUDA_ERROR_NOT_PERMITTED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_PERMITTED, 'This error indicates that the attempted operation is not permitted.') + CUDA_ERROR_NOT_SUPPORTED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_SUPPORTED, 'This error indicates that the attempted operation is not supported on the current system or device.') + CUDA_ERROR_SYSTEM_NOT_READY = (cydriver.cudaError_enum.CUDA_ERROR_SYSTEM_NOT_READY, '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.') + CUDA_ERROR_SYSTEM_DRIVER_MISMATCH = (cydriver.cudaError_enum.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH, '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.') + CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE = (cydriver.cudaError_enum.CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE, '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.') + CUDA_ERROR_MPS_CONNECTION_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_MPS_CONNECTION_FAILED, 'This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server.') + CUDA_ERROR_MPS_RPC_FAILURE = (cydriver.cudaError_enum.CUDA_ERROR_MPS_RPC_FAILURE, 'This error indicates that the remote procedural call between the MPS server and the MPS client failed.') + CUDA_ERROR_MPS_SERVER_NOT_READY = (cydriver.cudaError_enum.CUDA_ERROR_MPS_SERVER_NOT_READY, '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.') + CUDA_ERROR_MPS_MAX_CLIENTS_REACHED = (cydriver.cudaError_enum.CUDA_ERROR_MPS_MAX_CLIENTS_REACHED, 'This error indicates that the hardware resources required to create MPS client have been exhausted.') + CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED = (cydriver.cudaError_enum.CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED, 'This error indicates the the hardware resources required to support device connections have been exhausted.') + CUDA_ERROR_MPS_CLIENT_TERMINATED = (cydriver.cudaError_enum.CUDA_ERROR_MPS_CLIENT_TERMINATED, 'This error indicates that the MPS client has been terminated by the server. To continue using CUDA, the process must be terminated and relaunched.') + CUDA_ERROR_CDP_NOT_SUPPORTED = (cydriver.cudaError_enum.CUDA_ERROR_CDP_NOT_SUPPORTED, 'This error indicates that the module is using CUDA Dynamic Parallelism, but the current configuration, like MPS, does not support it.') + CUDA_ERROR_CDP_VERSION_MISMATCH = (cydriver.cudaError_enum.CUDA_ERROR_CDP_VERSION_MISMATCH, 'This error indicates that a module contains an unsupported interaction between different versions of CUDA Dynamic Parallelism.') + CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED, 'This error indicates that the operation is not permitted when the stream is capturing.') + CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_INVALIDATED, 'This error indicates that the current capture sequence on the stream has been invalidated due to a previous error.') + CUDA_ERROR_STREAM_CAPTURE_MERGE = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_MERGE, 'This error indicates that the operation would have resulted in a merge of two independent capture sequences.') + CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_UNMATCHED, 'This error indicates that the capture was not initiated in this stream.') + CUDA_ERROR_STREAM_CAPTURE_UNJOINED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_UNJOINED, 'This error indicates that the capture sequence contains a fork that was not joined to the primary stream.') + CUDA_ERROR_STREAM_CAPTURE_ISOLATION = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_ISOLATION, '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.') + CUDA_ERROR_STREAM_CAPTURE_IMPLICIT = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_IMPLICIT, 'This error indicates a disallowed implicit dependency on a current capture sequence from cudaStreamLegacy.') + CUDA_ERROR_CAPTURED_EVENT = (cydriver.cudaError_enum.CUDA_ERROR_CAPTURED_EVENT, 'This error indicates that the operation is not permitted on an event which was last recorded in a capturing stream.') + CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD, 'A stream capture sequence not initiated with the `CU_STREAM_CAPTURE_MODE_RELAXED` argument to `cuStreamBeginCapture` was passed to `cuStreamEndCapture` in a different thread.') + CUDA_ERROR_TIMEOUT = (cydriver.cudaError_enum.CUDA_ERROR_TIMEOUT, 'This error indicates that the timeout specified for the wait operation has lapsed.') + CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE = (cydriver.cudaError_enum.CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE, 'This error indicates that the graph update was not performed because it included changes which violated constraints specific to instantiated graph update.') + CUDA_ERROR_EXTERNAL_DEVICE = (cydriver.cudaError_enum.CUDA_ERROR_EXTERNAL_DEVICE, "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.") + CUDA_ERROR_INVALID_CLUSTER_SIZE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_CLUSTER_SIZE, 'Indicates a kernel launch error due to cluster misconfiguration.') + CUDA_ERROR_FUNCTION_NOT_LOADED = (cydriver.cudaError_enum.CUDA_ERROR_FUNCTION_NOT_LOADED, 'Indiciates a function handle is not loaded when calling an API that requires a loaded function.') + CUDA_ERROR_INVALID_RESOURCE_TYPE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_RESOURCE_TYPE, 'This error indicates one or more resources passed in are not valid resource types for the operation.') + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION, 'This error indicates one or more resources are insufficient or non-applicable for the operation.') + CUDA_ERROR_KEY_ROTATION = (cydriver.cudaError_enum.CUDA_ERROR_KEY_ROTATION, 'This error indicates that an error happened during the key rotation sequence.') + CUDA_ERROR_STREAM_DETACHED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_DETACHED, "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.") + CUDA_ERROR_GRAPH_RECAPTURE_FAILURE = (cydriver.cudaError_enum.CUDA_ERROR_GRAPH_RECAPTURE_FAILURE, 'This error indicates that a graph recapture failed and had to be terminated.') + CUDA_ERROR_UNKNOWN = (cydriver.cudaError_enum.CUDA_ERROR_UNKNOWN, 'This indicates that an unknown internal error has occurred.') + +class DeviceP2PAttribute(_cyb_FastEnum): + """ + P2P Attributes + + See `CUdevice_P2PAttribute`. + """ + CU_ATTRIBUTE_PERFORMANCE_RANK = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK, 'A relative value indicating the performance of the link between two devices') + CU_ATTRIBUTE_ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED, 'P2P Access is enable') + CU_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED, 'All CUDA-valid atomic operation over the link are supported') + CU_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED, '[Deprecated]') + CU_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED, 'Accessing CUDA arrays over the link supported') + CU_ATTRIBUTE_ONLY_PARTIAL_NATIVE_ATOMIC_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_ONLY_PARTIAL_NATIVE_ATOMIC_SUPPORTED, 'Only some CUDA-valid atomic operations over the link are supported.') + +class ResourceViewFormat(_cyb_FastEnum): + """ + Resource view format + + See `CUresourceViewFormat`. + """ + CU_RES_VIEW_FORMAT_NONE = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_NONE, 'No resource view format (use underlying resource format)') + CU_RES_VIEW_FORMAT_UINT_1X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X8, '1 channel unsigned 8-bit integers') + CU_RES_VIEW_FORMAT_UINT_2X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X8, '2 channel unsigned 8-bit integers') + CU_RES_VIEW_FORMAT_UINT_4X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X8, '4 channel unsigned 8-bit integers') + CU_RES_VIEW_FORMAT_SINT_1X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X8, '1 channel signed 8-bit integers') + CU_RES_VIEW_FORMAT_SINT_2X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X8, '2 channel signed 8-bit integers') + CU_RES_VIEW_FORMAT_SINT_4X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X8, '4 channel signed 8-bit integers') + CU_RES_VIEW_FORMAT_UINT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X16, '1 channel unsigned 16-bit integers') + CU_RES_VIEW_FORMAT_UINT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X16, '2 channel unsigned 16-bit integers') + CU_RES_VIEW_FORMAT_UINT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X16, '4 channel unsigned 16-bit integers') + CU_RES_VIEW_FORMAT_SINT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X16, '1 channel signed 16-bit integers') + CU_RES_VIEW_FORMAT_SINT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X16, '2 channel signed 16-bit integers') + CU_RES_VIEW_FORMAT_SINT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X16, '4 channel signed 16-bit integers') + CU_RES_VIEW_FORMAT_UINT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X32, '1 channel unsigned 32-bit integers') + CU_RES_VIEW_FORMAT_UINT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X32, '2 channel unsigned 32-bit integers') + CU_RES_VIEW_FORMAT_UINT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X32, '4 channel unsigned 32-bit integers') + CU_RES_VIEW_FORMAT_SINT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X32, '1 channel signed 32-bit integers') + CU_RES_VIEW_FORMAT_SINT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X32, '2 channel signed 32-bit integers') + CU_RES_VIEW_FORMAT_SINT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X32, '4 channel signed 32-bit integers') + CU_RES_VIEW_FORMAT_FLOAT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_1X16, '1 channel 16-bit floating point') + CU_RES_VIEW_FORMAT_FLOAT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_2X16, '2 channel 16-bit floating point') + CU_RES_VIEW_FORMAT_FLOAT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_4X16, '4 channel 16-bit floating point') + CU_RES_VIEW_FORMAT_FLOAT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_1X32, '1 channel 32-bit floating point') + CU_RES_VIEW_FORMAT_FLOAT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_2X32, '2 channel 32-bit floating point') + CU_RES_VIEW_FORMAT_FLOAT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_4X32, '4 channel 32-bit floating point') + CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC1, 'Block compressed 1') + CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC2, 'Block compressed 2') + CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC3, 'Block compressed 3') + CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC4, 'Block compressed 4 unsigned') + CU_RES_VIEW_FORMAT_SIGNED_BC4 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC4, 'Block compressed 4 signed') + CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC5, 'Block compressed 5 unsigned') + CU_RES_VIEW_FORMAT_SIGNED_BC5 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC5, 'Block compressed 5 signed') + CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC6H, 'Block compressed 6 unsigned half-float') + CU_RES_VIEW_FORMAT_SIGNED_BC6H = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC6H, 'Block compressed 6 signed half-float') + CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC7, 'Block compressed 7') + +class TensorMapDataType(_cyb_FastEnum): + """ + Tensor map data type + + See `CUtensorMapDataType`. + """ + CU_UINT8 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT8 + CU_UINT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT16 + CU_UINT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT32 + CU_INT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_INT32 + CU_UINT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT64 + CU_INT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_INT64 + CU_FLOAT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT16 + CU_FLOAT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT32 + CU_FLOAT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT64 + CU_BFLOAT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_BFLOAT16 + CU_FLOAT32_FTZ = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ + CU_TFLOAT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_TFLOAT32 + CU_TFLOAT32_FTZ = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ + CU_16U4_ALIGN8B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B + CU_16U4_ALIGN16B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B + CU_16U6_ALIGN16B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B + +class TensorMapInterleave(_cyb_FastEnum): + """ + Tensor map interleave layout type + + See `CUtensorMapInterleave`. + """ + CU_NONE = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_NONE + CU_16B = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_16B + CU_32B = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_32B + +class TensorMapSwizzle(_cyb_FastEnum): + """ + Tensor map swizzling mode of shared memory banks + + See `CUtensorMapSwizzle`. + """ + CU_NONE = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_NONE + CU_32B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_32B + CU_64B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_64B + CU_128B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B + CU_128B_ATOM_32B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B + CU_128B_ATOM_32B_FLIP_8B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B + CU_128B_ATOM_64B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B + +class TensorMapL2promotion(_cyb_FastEnum): + """ + Tensor map L2 promotion type + + See `CUtensorMapL2promotion`. + """ + CU_TENSOR_MAP_L2_PROMOTION_NONE = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_NONE + CU_TENSOR_MAP_L2_PROMOTION_L2_64B = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_L2_64B + CU_TENSOR_MAP_L2_PROMOTION_L2_128B = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_L2_128B + CU_TENSOR_MAP_L2_PROMOTION_L2_256B = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_L2_256B + +class TensorMapFloatOOBfill(_cyb_FastEnum): + """ + Tensor map out-of-bounds fill type + + See `CUtensorMapFloatOOBfill`. + """ + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE = cydriver.CUtensorMapFloatOOBfill_enum.CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE + CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA = cydriver.CUtensorMapFloatOOBfill_enum.CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA + +class TensorMapIm2ColWideMode(_cyb_FastEnum): + """ + Tensor map Im2Col wide mode + + See `CUtensorMapIm2ColWideMode`. + """ + CU_W = cydriver.CUtensorMapIm2ColWideMode_enum.CU_TENSOR_MAP_IM2COL_WIDE_MODE_W + CU_W128 = cydriver.CUtensorMapIm2ColWideMode_enum.CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128 + +class PointerAttributeAccessFlags(_cyb_FastEnum): + """ + Access flags that specify the level of access the current context's + device has on the memory referenced. + + See `CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS`. + """ + CU_POINTER_ATTRIBUTE_ACCESS_FLAG_NONE = (cydriver.CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS_enum.CU_POINTER_ATTRIBUTE_ACCESS_FLAG_NONE, 'No access, meaning the device cannot access this memory at all, thus must be staged through accessible memory in order to complete certain operations') + CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READ = (cydriver.CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS_enum.CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READ, 'Read-only access, meaning writes to this memory are considered invalid accesses and thus return error in that case.') + CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READWRITE = (cydriver.CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS_enum.CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READWRITE, 'Read-write access, the device has full read-write access to the memory') + +class ExternalMemoryHandleType(_cyb_FastEnum): + """ + External memory handle types + + See `CUexternalMemoryHandleType`. + """ + CU_OPAQUE_FD = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD, 'Handle is an opaque file descriptor') + CU_OPAQUE_WIN32 = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32, 'Handle is an opaque shared NT handle') + CU_OPAQUE_WIN32_KMT = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT, 'Handle is an opaque, globally shared handle') + CU_D3D12_HEAP = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP, 'Handle is a D3D12 heap object') + CU_D3D12_RESOURCE = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE, 'Handle is a D3D12 committed resource') + CU_D3D11_RESOURCE = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE, 'Handle is a shared NT handle to a D3D11 resource') + CU_D3D11_RESOURCE_KMT = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT, 'Handle is a globally shared handle to a D3D11 resource') + CU_NVSCIBUF = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, 'Handle is an NvSciBuf object') + CU_DMABUF_FD = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD, 'Handle is a dma_buf file descriptor') + +class ExternalSemaphoreHandleType(_cyb_FastEnum): + """ + External semaphore handle types + + See `CUexternalSemaphoreHandleType`. + """ + CU_OPAQUE_FD = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, 'Handle is an opaque file descriptor') + CU_OPAQUE_WIN32 = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, 'Handle is an opaque shared NT handle') + CU_OPAQUE_WIN32_KMT = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT, 'Handle is an opaque, globally shared handle') + CU_D3D12_FENCE = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, 'Handle is a shared NT handle referencing a D3D12 fence object') + CU_D3D11_FENCE = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, 'Handle is a shared NT handle referencing a D3D11 fence object') + CU_NVSCISYNC = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, 'Opaque handle to NvSciSync Object') + CU_D3D11_KEYED_MUTEX = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, 'Handle is a shared NT handle referencing a D3D11 keyed mutex object') + CU_D3D11_KEYED_MUTEX_KMT = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT, 'Handle is a globally shared handle referencing a D3D11 keyed mutex object') + CU_TIMELINE_SEMAPHORE_FD = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, 'Handle is an opaque file descriptor referencing a timeline semaphore') + CU_TIMELINE_SEMAPHORE_WIN32 = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32, 'Handle is an opaque shared NT handle referencing a timeline semaphore') + +class MemAllocationHandleType(_cyb_FastEnum): + """ + Flags for specifying particular handle types + + See `CUmemAllocationHandleType`. + """ + CU_MEM_HANDLE_TYPE_NONE = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_NONE, 'Does not allow any export mechanism. >') + CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR, 'Allows a file descriptor to be used for exporting. Permitted only on POSIX systems. (int)') + CU_MEM_HANDLE_TYPE_WIN32 = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_WIN32, 'Allows a Win32 NT handle to be used for exporting. (HANDLE)') + CU_MEM_HANDLE_TYPE_WIN32_KMT = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_WIN32_KMT, 'Allows a Win32 KMT handle to be used for exporting. (D3DKMT_HANDLE)') + CU_MEM_HANDLE_TYPE_FABRIC = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_FABRIC, 'Allows a fabric handle to be used for exporting. (`CUmemFabricHandle`)') + CU_MEM_HANDLE_TYPE_MAX = cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_MAX + +class MemAccessFlags(_cyb_FastEnum): + """ + Specifies the memory protection flags for mapping. + + See `CUmemAccess_flags`. + """ + CU_PROT_NONE = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_NONE, 'Default, make the address range not accessible') + CU_PROT_READ = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_READ, 'Make the address range read accessible') + CU_PROT_READWRITE = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_READWRITE, 'Make the address range read-write accessible') + CU_PROT_MAX = cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_MAX + +class MemLocationType(_cyb_FastEnum): + """ + Specifies the type of location + + See `CUmemLocationType`. + """ + CU_INVALID = cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_INVALID + CU_NONE = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_NONE, 'Location is unspecified. This is used when creating a managed memory pool to indicate no preferred location for the pool') + CU_DEVICE = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_DEVICE, 'Location is a device location, thus id is a device ordinal') + CU_HOST = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_HOST, 'Location is host, id is ignored') + CU_HOST_NUMA = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_HOST_NUMA, 'Location is a host NUMA node, thus id is a host NUMA node id') + CU_HOST_NUMA_CURRENT = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT, 'Location is a host NUMA node of the current thread, id is ignored') + CU_INVISIBLE = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_INVISIBLE, 'Location is not visible but device is accessible, id is always CU_DEVICE_INVALID') + CU_MAX = cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_MAX + +class MemAllocationType(_cyb_FastEnum): + """ + Defines the allocation types available + + See `CUmemAllocationType`. + """ + CU_INVALID = cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_INVALID + CU_PINNED = (cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_PINNED, "This allocation type is 'pinned', i.e. cannot migrate from its current location while the application is actively using it") + CU_MANAGED = (cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_MANAGED, 'This allocation type is managed memory') + CU_MAX = cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_MAX + +class MemAllocationGranularityFlags(_cyb_FastEnum): + """ + Flag for requesting different optimal and required granularities for an + allocation. + + See `CUmemAllocationGranularity_flags`. + """ + CU_MEM_ALLOC_GRANULARITY_MINIMUM = (cydriver.CUmemAllocationGranularity_flags_enum.CU_MEM_ALLOC_GRANULARITY_MINIMUM, 'Minimum required granularity for allocation') + CU_MEM_ALLOC_GRANULARITY_RECOMMENDED = (cydriver.CUmemAllocationGranularity_flags_enum.CU_MEM_ALLOC_GRANULARITY_RECOMMENDED, 'Recommended granularity for allocation for best performance') + +class MemRangeHandleType(_cyb_FastEnum): + """ + Specifies the handle type for address range + + See `CUmemRangeHandleType`. + """ + CU_DMA_BUF_FD = cydriver.CUmemRangeHandleType_enum.CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD + CU_MAX = cydriver.CUmemRangeHandleType_enum.CU_MEM_RANGE_HANDLE_TYPE_MAX + +class MemRangeFlags(_cyb_FastEnum): + """ + Flag for requesting handle type for address range. + + See `CUmemRangeFlags`. + """ + CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE = (cydriver.CUmemRangeFlags_enum.CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE, 'Indicates that DMA_BUF handle should be mapped via PCIe BAR1') + +class ArraySparseSubresourceType(_cyb_FastEnum): + """ + Sparse subresource types + + See `CUarraySparseSubresourceType`. + """ + CU_SPARSE_LEVEL = cydriver.CUarraySparseSubresourceType_enum.CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL + CU_MIPTAIL = cydriver.CUarraySparseSubresourceType_enum.CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL + +class MemOperationType(_cyb_FastEnum): + """ + Memory operation types + + See `CUmemOperationType`. + """ + CU_MAP = cydriver.CUmemOperationType_enum.CU_MEM_OPERATION_TYPE_MAP + CU_UNMAP = cydriver.CUmemOperationType_enum.CU_MEM_OPERATION_TYPE_UNMAP + +class MemHandleType(_cyb_FastEnum): + """ + Memory handle types + + See `CUmemHandleType`. + """ + CU_GENERIC = cydriver.CUmemHandleType_enum.CU_MEM_HANDLE_TYPE_GENERIC + +class MemAllocationCompType(_cyb_FastEnum): + """ + Specifies compression attribute for an allocation. + + See `CUmemAllocationCompType`. + """ + CU_MEM_ALLOCATION_COMP_NONE = (cydriver.CUmemAllocationCompType_enum.CU_MEM_ALLOCATION_COMP_NONE, 'Allocating non-compressible memory') + CU_MEM_ALLOCATION_COMP_GENERIC = (cydriver.CUmemAllocationCompType_enum.CU_MEM_ALLOCATION_COMP_GENERIC, 'Allocating compressible memory') + +class MulticastGranularityFlags(_cyb_FastEnum): + """ + Flags for querying different granularities for a multicast object + + See `CUmulticastGranularity_flags`. + """ + CU_MULTICAST_GRANULARITY_MINIMUM = (cydriver.CUmulticastGranularity_flags_enum.CU_MULTICAST_GRANULARITY_MINIMUM, 'Minimum required granularity') + CU_MULTICAST_GRANULARITY_RECOMMENDED = (cydriver.CUmulticastGranularity_flags_enum.CU_MULTICAST_GRANULARITY_RECOMMENDED, 'Recommended granularity for best performance') + +class GraphExecUpdateResult(_cyb_FastEnum): + """ + CUDA Graph Update error types + + See `CUgraphExecUpdateResult`. + """ + CU_GRAPH_EXEC_UPDATE_SUCCESS = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_SUCCESS, 'The update succeeded') + CU_GRAPH_EXEC_UPDATE_ERROR = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR, 'The update failed for an unexpected reason which is described in the return value of the function') + CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED, 'The update failed because the topology changed') + CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED, 'The update failed because a node type changed') + CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED, 'The update failed because the function of a kernel node changed (CUDA driver < 11.2)') + CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED, 'The update failed because the parameters changed in a way that is not supported') + CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED, 'The update failed because something about the node is not supported') + CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE, 'The update failed because the function of a kernel node changed in an unsupported way') + CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED, 'The update failed because the node attributes changed in a way that is not supported') + +class MemPoolAttribute(_cyb_FastEnum): + """ + CUDA memory pool attributes + + See `CUmemPool_attribute`. + """ + CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, '(value type = int) Allow cuMemAllocAsync 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)') + CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, '(value type = int) Allow reuse of already completed frees when there is no dependency between the free and allocation. (default enabled)') + CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, '(value type = int) Allow cuMemAllocAsync to insert new stream dependencies in order to establish the stream ordering required to reuse a piece of memory released by cuMemFreeAsync (default enabled).') + CU_MEMPOOL_ATTR_RELEASE_THRESHOLD = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, '(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)') + CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT, '(value type = `cuuint64_t`) Amount of backing memory currently allocated for the mempool.') + CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH, '(value type = `cuuint64_t`) High watermark of backing memory allocated for the mempool since the last time it was reset. High watermark can only be reset to zero.') + CU_MEMPOOL_ATTR_USED_MEM_CURRENT = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_USED_MEM_CURRENT, '(value type = `cuuint64_t`) Amount of memory from the pool that is currently in use by the application.') + CU_MEMPOOL_ATTR_USED_MEM_HIGH = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_USED_MEM_HIGH, '(value type = `cuuint64_t`) High watermark of the amount of memory from the pool that was in use by the application since the last time it was reset. High watermark can only be reset to zero.') + CU_MEMPOOL_ATTR_ALLOCATION_TYPE = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_ALLOCATION_TYPE, '(value type = `CUmemAllocationType`) The allocation type of the mempool') + CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES, '(value type = `CUmemAllocationHandleType`) Available export handle types for the mempool. For imported pools this value is always CU_MEM_HANDLE_TYPE_NONE as an imported pool cannot be re-exported') + CU_MEMPOOL_ATTR_LOCATION_ID = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_LOCATION_ID, '(value type = int) The location id for the mempool. If the location type for this pool is CU_MEM_LOCATION_TYPE_INVISIBLE then ID will be CU_DEVICE_INVALID.') + CU_MEMPOOL_ATTR_LOCATION_TYPE = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_LOCATION_TYPE, '(value type = `CUmemLocationType`) The location type for the mempool. For imported memory pools where the device is not directly visible to the importing process or pools imported via fabric handles across nodes this will be CU_MEM_LOCATION_TYPE_INVISIBLE.') + CU_MEMPOOL_ATTR_MAX_POOL_SIZE = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_MAX_POOL_SIZE, '(value type = `cuuint64_t`) Maximum size of the pool in bytes, this value may be higher than what was initially passed to cuMemPoolCreate due to alignment requirements. A value of 0 indicates no maximum size. For CU_MEM_ALLOCATION_TYPE_MANAGED and IPC imported pools this value will be system dependent.') + CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED, '(value type = int) Indicates whether the pool has hardware compresssion enabled') + +class MemcpyFlags(_cyb_FastEnum): + """ + Flags to specify for copies within a batch. For more details see + `cuMemcpyBatchAsync`. + + See `CUmemcpyFlags`. + """ + CU_MEMCPY_FLAG_DEFAULT = cydriver.CUmemcpyFlags_enum.CU_MEMCPY_FLAG_DEFAULT + CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE = (cydriver.CUmemcpyFlags_enum.CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE, 'Hint to the driver to try and overlap the copy with compute work on the SMs.') + +class MemcpySrcAccessOrder(_cyb_FastEnum): + """ + These flags allow applications to convey the source access ordering + CUDA must maintain. The destination will always be accessed in stream + order. + + See `CUmemcpySrcAccessOrder`. + """ + CU_INVALID = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_INVALID, 'Default invalid.') + CU_STREAM = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_STREAM, 'Indicates that access to the source pointer must be in stream order.') + CU_DURING_API_CALL = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL, "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.") + CU_ANY = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_ANY, "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.") + CU_MAX = cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_MAX + +class Memcpy3DOperandType(_cyb_FastEnum): + """ + These flags allow applications to convey the operand type for + individual copies specified in `cuMemcpy3DBatchAsync`. + + See `CUmemcpy3DOperandType`. + """ + CU_MEMCPY_OPERAND_TYPE_POINTER = (cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_POINTER, 'Memcpy operand is a valid pointer.') + CU_MEMCPY_OPERAND_TYPE_ARRAY = (cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_ARRAY, 'Memcpy operand is a `CUarray`.') + CU_MEMCPY_OPERAND_TYPE_MAX = cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_MAX + +class GraphMemAttribute(_cyb_FastEnum): + """ + See `CUgraphMem_attribute`. + """ + CU_ATTR_USED_MEM_CURRENT = (cydriver.CUgraphMem_attribute_enum.CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT, '(value type = `cuuint64_t`) Amount of memory, in bytes, currently associated with graphs') + CU_ATTR_USED_MEM_HIGH = (cydriver.CUgraphMem_attribute_enum.CU_GRAPH_MEM_ATTR_USED_MEM_HIGH, '(value type = `cuuint64_t`) High watermark of memory, in bytes, associated with graphs since the last time it was reset. High watermark can only be reset to zero.') + CU_ATTR_RESERVED_MEM_CURRENT = (cydriver.CUgraphMem_attribute_enum.CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT, '(value type = `cuuint64_t`) Amount of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator.') + CU_ATTR_RESERVED_MEM_HIGH = (cydriver.CUgraphMem_attribute_enum.CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH, '(value type = `cuuint64_t`) High watermark of memory, in bytes, currently allocated for use by the CUDA graphs asynchronous allocator.') + +class GraphChildGraphNodeOwnership(_cyb_FastEnum): + """ + Child graph node ownership + + See `CUgraphChildGraphNodeOwnership`. + """ + CU_GRAPH_CHILD_GRAPH_OWNERSHIP_CLONE = (cydriver.CUgraphChildGraphNodeOwnership_enum.CU_GRAPH_CHILD_GRAPH_OWNERSHIP_CLONE, "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.") + CU_GRAPH_CHILD_GRAPH_OWNERSHIP_MOVE = (cydriver.CUgraphChildGraphNodeOwnership_enum.CU_GRAPH_CHILD_GRAPH_OWNERSHIP_MOVE, '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 cuGraphExecUpdate; Cannot have additional memory allocation or free nodes added.') + CU_GRAPH_CHILD_GRAPH_OWNERSHIP_INVALID = (cydriver.CUgraphChildGraphNodeOwnership_enum.CU_GRAPH_CHILD_GRAPH_OWNERSHIP_INVALID, 'Invalid ownership flag. Set when params are queried to prevent accidentally reusing the driver-owned graph object') + +class FlushGPUDirectRDMAWritesOptions(_cyb_FastEnum): + """ + Bitmasks for `CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS` + + See `CUflushGPUDirectRDMAWritesOptions`. + """ + CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_HOST = (cydriver.CUflushGPUDirectRDMAWritesOptions_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_HOST, '`cuFlushGPUDirectRDMAWrites()` and its CUDA Runtime API counterpart are supported on the device.') + CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_MEMOPS = (cydriver.CUflushGPUDirectRDMAWritesOptions_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_MEMOPS, 'The `CU_STREAM_WAIT_VALUE_FLUSH` flag and the `CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES` MemOp are supported on the device.') + +class GPUDirectRDMAWritesOrdering(_cyb_FastEnum): + """ + Platform native ordering for GPUDirect RDMA writes + + See `CUGPUDirectRDMAWritesOrdering`. + """ + CU_NONE = (cydriver.CUGPUDirectRDMAWritesOrdering_enum.CU_GPU_DIRECT_RDMA_WRITES_ORDERING_NONE, 'The device does not natively support ordering of remote writes. `cuFlushGPUDirectRDMAWrites()` can be leveraged if supported.') + CU_OWNER = (cydriver.CUGPUDirectRDMAWritesOrdering_enum.CU_GPU_DIRECT_RDMA_WRITES_ORDERING_OWNER, 'Natively, the device can consistently consume remote writes, although other CUDA devices may not.') + CU_ALL_DEVICES = (cydriver.CUGPUDirectRDMAWritesOrdering_enum.CU_GPU_DIRECT_RDMA_WRITES_ORDERING_ALL_DEVICES, 'Any CUDA device in the system can consistently consume remote writes to this device.') + +class FlushGPUDirectRDMAWritesScope(_cyb_FastEnum): + """ + The scopes for `cuFlushGPUDirectRDMAWrites` + + See `CUflushGPUDirectRDMAWritesScope`. + """ + CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_OWNER = (cydriver.CUflushGPUDirectRDMAWritesScope_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_OWNER, 'Blocks until remote writes are visible to the CUDA device context owning the data.') + CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_ALL_DEVICES = (cydriver.CUflushGPUDirectRDMAWritesScope_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_ALL_DEVICES, 'Blocks until remote writes are visible to all CUDA device contexts.') + +class FlushGPUDirectRDMAWritesTarget(_cyb_FastEnum): + """ + The targets for `cuFlushGPUDirectRDMAWrites` + + See `CUflushGPUDirectRDMAWritesTarget`. + """ + CU_CURRENT_CTX = (cydriver.CUflushGPUDirectRDMAWritesTarget_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TARGET_CURRENT_CTX, 'Sets the target for `cuFlushGPUDirectRDMAWrites()` to the currently active CUDA device context.') + +class GraphDebugDotFlags(_cyb_FastEnum): + """ + The additional write options for `cuGraphDebugDotPrint` + + See `CUgraphDebugDot_flags`. + """ + CU_VERBOSE = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE, 'Output all debug data as if every debug flag is enabled') + CU_RUNTIME_TYPES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES, 'Use CUDA Runtime structures for output') + CU_KERNEL_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS, 'Adds `CUDA_KERNEL_NODE_PARAMS` values to output') + CU_MEMCPY_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS, 'Adds `CUDA_MEMCPY3D` values to output') + CU_MEMSET_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS, 'Adds `CUDA_MEMSET_NODE_PARAMS` values to output') + CU_HOST_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS, 'Adds `CUDA_HOST_NODE_PARAMS` values to output') + CU_EVENT_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_EVENT_NODE_PARAMS, 'Adds `CUevent` handle from record and wait nodes to output') + CU_EXT_SEMAS_SIGNAL_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_SIGNAL_NODE_PARAMS, 'Adds `CUDA_EXT_SEM_SIGNAL_NODE_PARAMS` values to output') + CU_EXT_SEMAS_WAIT_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_WAIT_NODE_PARAMS, 'Adds `CUDA_EXT_SEM_WAIT_NODE_PARAMS` values to output') + CU_KERNEL_NODE_ATTRIBUTES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES, 'Adds `CUkernelNodeAttrValue` values to output') + CU_HANDLES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES, 'Adds node handles and every kernel function handle to output') + CU_MEM_ALLOC_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS, 'Adds memory alloc node parameters to output') + CU_MEM_FREE_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS, 'Adds memory free node parameters to output') + CU_BATCH_MEM_OP_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_BATCH_MEM_OP_NODE_PARAMS, 'Adds batch mem op node parameters to output') + CU_EXTRA_TOPO_INFO = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_EXTRA_TOPO_INFO, 'Adds edge numbering information') + CU_CONDITIONAL_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_CONDITIONAL_NODE_PARAMS, 'Adds conditional node parameters to output') + +class UserObjectFlags(_cyb_FastEnum): + """ + Flags for user objects for graphs + + See `CUuserObject_flags`. + """ + CU_USER_OBJECT_NO_DESTRUCTOR_SYNC = (cydriver.CUuserObject_flags_enum.CU_USER_OBJECT_NO_DESTRUCTOR_SYNC, 'Indicates the destructor execution is not synchronized by any CUDA handle.') + +class UserObjectRetainFlags(_cyb_FastEnum): + """ + Flags for retaining user object references for graphs + + See `CUuserObjectRetain_flags`. + """ + CU_GRAPH_USER_OBJECT_MOVE = (cydriver.CUuserObjectRetain_flags_enum.CU_GRAPH_USER_OBJECT_MOVE, 'Transfer references from the caller rather than creating new references.') + +class GraphInstantiateFlags(_cyb_FastEnum): + """ + Flags for instantiating a graph + + See `CUgraphInstantiate_flags`. + """ + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH = (cydriver.CUgraphInstantiate_flags_enum.CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, 'Automatically free memory allocated in a graph before relaunching.') + CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD = (cydriver.CUgraphInstantiate_flags_enum.CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD, 'Automatically upload the graph after instantiation. Only supported by `cuGraphInstantiateWithParams`. The upload will be performed using the stream provided in `instantiateParams`.') + CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH = (cydriver.CUgraphInstantiate_flags_enum.CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH, '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 CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH.') + CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY = (cydriver.CUgraphInstantiate_flags_enum.CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, 'Run the graph using the per-node priority attributes rather than the priority of the stream it is launched into.') + +class DeviceNumaConfig(_cyb_FastEnum): + """ + CUDA device NUMA configuration + + See `CUdeviceNumaConfig`. + """ + CU_NONE = (cydriver.CUdeviceNumaConfig_enum.CU_DEVICE_NUMA_CONFIG_NONE, 'The GPU is not a NUMA node') + CU_NUMA_NODE = (cydriver.CUdeviceNumaConfig_enum.CU_DEVICE_NUMA_CONFIG_NUMA_NODE, 'The GPU is a NUMA node, CU_DEVICE_ATTRIBUTE_NUMA_ID contains its NUMA ID') + +class ProcessState(_cyb_FastEnum): + """ + CUDA Process States + + See `CUprocessState`. + """ + CU_RUNNING = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_RUNNING, 'Default process state') + CU_LOCKED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_LOCKED, 'CUDA API locks are taken so further CUDA API calls will block') + CU_CHECKPOINTED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_CHECKPOINTED, 'Application memory contents have been checkpointed and underlying allocations and device handles have been released') + CU_FAILED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_FAILED, 'Application entered an uncorrectable error during the checkpoint/restore process') + +class ModuleLoadingMode(_cyb_FastEnum): + """ + CUDA Lazy Loading status + + See `CUmoduleLoadingMode`. + """ + CU_MODULE_EAGER_LOADING = (cydriver.CUmoduleLoadingMode_enum.CU_MODULE_EAGER_LOADING, 'Lazy Kernel Loading is not enabled') + CU_MODULE_LAZY_LOADING = (cydriver.CUmoduleLoadingMode_enum.CU_MODULE_LAZY_LOADING, 'Lazy Kernel Loading is enabled') + +class MemDecompressAlgorithm(_cyb_FastEnum): + """ + Bitmasks for CU_DEVICE_ATTRIBUTE_MEM_DECOMPRESS_ALGORITHM_MASK. + + See `CUmemDecompressAlgorithm`. + """ + CU_MEM_DECOMPRESS_UNSUPPORTED = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_UNSUPPORTED, 'Decompression is unsupported.') + CU_DEFLATE = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_DEFLATE, 'Deflate is supported.') + CU_SNAPPY = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_SNAPPY, 'Snappy is supported.') + CU_LZ4 = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_LZ4, 'LZ4 is supported.') + +class FunctionLoadingState(_cyb_FastEnum): + """ + See `CUfunctionLoadingState`. + """ + CU_UNLOADED = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_UNLOADED + CU_LOADED = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_LOADED + CU_MAX = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_MAX + +class CoredumpSettings(_cyb_FastEnum): + """ + Flags for choosing a coredump attribute to get/set + + See `CUcoredumpSettings`. + """ + CU_COREDUMP_ENABLE_ON_EXCEPTION = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_ENABLE_ON_EXCEPTION + CU_COREDUMP_TRIGGER_HOST = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_TRIGGER_HOST + CU_COREDUMP_LIGHTWEIGHT = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_LIGHTWEIGHT + CU_COREDUMP_ENABLE_USER_TRIGGER = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_ENABLE_USER_TRIGGER + CU_COREDUMP_FILE = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_FILE + CU_COREDUMP_PIPE = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_PIPE + CU_COREDUMP_GENERATION_FLAGS = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_GENERATION_FLAGS + CU_COREDUMP_MAX = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_MAX + +class CoredumpGenerationFlags(_cyb_FastEnum): + """ + Flags for controlling coredump contents + + See `CUCoredumpGenerationFlags`. + """ + CU_COREDUMP_DEFAULT_FLAGS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_DEFAULT_FLAGS + CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES + CU_COREDUMP_SKIP_GLOBAL_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_GLOBAL_MEMORY + CU_COREDUMP_SKIP_SHARED_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_SHARED_MEMORY + CU_COREDUMP_SKIP_LOCAL_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_LOCAL_MEMORY + CU_COREDUMP_SKIP_ABORT = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_ABORT + CU_COREDUMP_SKIP_CONSTBANK_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_CONSTBANK_MEMORY + CU_COREDUMP_GZIP_COMPRESS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_GZIP_COMPRESS + CU_COREDUMP_FAULTED_CONTEXTS_ONLY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_FAULTED_CONTEXTS_ONLY + CU_COREDUMP_NO_ERRBAR_AT_EXIT = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_NO_ERRBAR_AT_EXIT + CU_COREDUMP_LOG_ONLY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_LOG_ONLY + CU_COREDUMP_LIGHTWEIGHT_FLAGS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_LIGHTWEIGHT_FLAGS + +class GreenCtxCreateFlags(_cyb_FastEnum): + """ + Flags for green context creation + + See `CUgreenCtxCreate_flags`. + """ + CU_GREEN_CTX_NONE = cydriver.CUgreenCtxCreate_flags.CU_GREEN_CTX_NONE + CU_GREEN_CTX_DEFAULT_STREAM = (cydriver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM, 'Creates a default stream to use inside the green context') + +class DevResourceType(_cyb_FastEnum): + """ + Type of resource + + See `CUdevResourceType`. + """ + CU_INVALID = cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_INVALID + CU_SM = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM, 'Streaming multiprocessors related information') + CU_WORKQUEUE_CONFIG = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG, 'Workqueue configuration related information') + CU_WORKQUEUE = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE, 'Pre-existing workqueue related information') + +class LogLevel(_cyb_FastEnum): + """ + See `CUlogLevel`. + """ + CU_ERROR = cydriver.CUlogLevel_enum.CU_LOG_LEVEL_ERROR + CU_WARNING = cydriver.CUlogLevel_enum.CU_LOG_LEVEL_WARNING + +class EglFrameType(_cyb_FastEnum): + """ + CUDA EglFrame type - array or pointer + + See `CUeglFrameType`. + """ + CU_ARRAY = (cydriver.CUeglFrameType_enum.CU_EGL_FRAME_TYPE_ARRAY, 'Frame type CUDA array') + CU_PITCH = (cydriver.CUeglFrameType_enum.CU_EGL_FRAME_TYPE_PITCH, 'Frame type pointer') + +class EglResourceLocationFlags(_cyb_FastEnum): + """ + Resource location flags- sysmem or vidmem For CUDA context on iGPU, + since video and system memory are equivalent - these flags will not + have an effect on the execution. For CUDA context on dGPU, + applications can use the flag `CUeglResourceLocationFlags` to give a + hint about the desired location. `CU_EGL_RESOURCE_LOCATION_SYSMEM` - + the frame data is made resident on the system memory to be accessed by + CUDA. `CU_EGL_RESOURCE_LOCATION_VIDMEM` - the frame data is made + resident on the dedicated video memory to be accessed by CUDA. There + may be an additional latency due to new allocation and data migration, + if the frame is produced on a different memory. + + See `CUeglResourceLocationFlags`. + """ + CU_EGL_RESOURCE_LOCATION_SYSMEM = (cydriver.CUeglResourceLocationFlags_enum.CU_EGL_RESOURCE_LOCATION_SYSMEM, 'Resource location sysmem') + CU_EGL_RESOURCE_LOCATION_VIDMEM = (cydriver.CUeglResourceLocationFlags_enum.CU_EGL_RESOURCE_LOCATION_VIDMEM, 'Resource location vidmem') + +class EglColorFormat(_cyb_FastEnum): + """ + CUDA EGL Color Format - The different planar and multiplanar formats + currently supported for CUDA_EGL interops. Three channel formats are + currently not supported for `CU_EGL_FRAME_TYPE_ARRAY` + + See `CUeglColorFormat`. + """ + CU_YUV420_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_PLANAR, 'Y, U, V in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YUV420_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_SEMIPLANAR, 'Y, UV in two surfaces (UV as one surface) with VU byte ordering, width, height ratio same as YUV420Planar.') + CU_YUV422_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV422_PLANAR, 'Y, U, V each in a separate surface, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YUV422_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV422_SEMIPLANAR, 'Y, UV in two surfaces with VU byte ordering, width, height ratio same as YUV422Planar.') + CU_RGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_RGB, 'R/G/B three channels in one surface with BGR byte ordering. Only pitch linear format supported.') + CU_BGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BGR, 'R/G/B three channels in one surface with RGB byte ordering. Only pitch linear format supported.') + CU_ARGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_ARGB, 'R/G/B/A four channels in one surface with BGRA byte ordering.') + CU_RGBA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_RGBA, 'R/G/B/A four channels in one surface with ABGR byte ordering.') + CU_L = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_L, 'single luminance channel in one surface.') + CU_R = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_R, 'single color channel in one surface.') + CU_YUV444_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV444_PLANAR, 'Y, U, V in three surfaces, each in a separate surface, U/V width = Y width, U/V height = Y height.') + CU_YUV444_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV444_SEMIPLANAR, 'Y, UV in two surfaces (UV as one surface) with VU byte ordering, width, height ratio same as YUV444Planar.') + CU_YUYV_422 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUYV_422, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + CU_UYVY_422 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_422, 'Y, U, V in one surface, interleaved as YUYV in one channel.') + CU_ABGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_ABGR, 'R/G/B/A four channels in one surface with RGBA byte ordering.') + CU_BGRA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BGRA, 'R/G/B/A four channels in one surface with ARGB byte ordering.') + CU_A = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_A, 'Alpha color format - one channel in one surface.') + CU_RG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_RG, 'R/G color format - two channels in one surface with GR byte ordering') + CU_AYUV = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_AYUV, 'Y, U, V, A four channels in one surface, interleaved as VUYA.') + CU_YVU444_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU444_SEMIPLANAR, 'Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height.') + CU_YVU422_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU422_SEMIPLANAR, 'Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YVU420_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_SEMIPLANAR, 'Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_444_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_444_SEMIPLANAR, 'Y10, V10U10 in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height.') + CU_Y10V10U10_420_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_420_SEMIPLANAR, 'Y10, V10U10 in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y12V12U12_444_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_444_SEMIPLANAR, 'Y12, V12U12 in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height.') + CU_Y12V12U12_420_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_420_SEMIPLANAR, 'Y12, V12U12 in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_VYUY_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_VYUY_ER, 'Extended Range Y, U, V in one surface, interleaved as YVYU in one channel.') + CU_UYVY_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_ER, 'Extended Range Y, U, V in one surface, interleaved as YUYV in one channel.') + CU_YUYV_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUYV_ER, 'Extended Range Y, U, V in one surface, interleaved as UYVY in one channel.') + CU_YVYU_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVYU_ER, 'Extended Range Y, U, V in one surface, interleaved as VYUY in one channel.') + CU_YUV_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV_ER, 'Extended Range Y, U, V three channels in one surface, interleaved as VUY. Only pitch linear format supported.') + CU_YUVA_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUVA_ER, 'Extended Range Y, U, V, A four channels in one surface, interleaved as AVUY.') + CU_AYUV_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_AYUV_ER, 'Extended Range Y, U, V, A four channels in one surface, interleaved as VUYA.') + CU_YUV444_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV444_PLANAR_ER, 'Extended Range Y, U, V in three surfaces, U/V width = Y width, U/V height = Y height.') + CU_YUV422_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV422_PLANAR_ER, 'Extended Range Y, U, V in three surfaces, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YUV420_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_PLANAR_ER, 'Extended Range Y, U, V in three surfaces, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YUV444_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV444_SEMIPLANAR_ER, 'Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = Y width, U/V height = Y height.') + CU_YUV422_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV422_SEMIPLANAR_ER, 'Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YUV420_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_SEMIPLANAR_ER, 'Extended Range Y, UV in two surfaces (UV as one surface) with VU byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YVU444_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU444_PLANAR_ER, 'Extended Range Y, V, U in three surfaces, U/V width = Y width, U/V height = Y height.') + CU_YVU422_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU422_PLANAR_ER, 'Extended Range Y, V, U in three surfaces, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YVU420_PLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_PLANAR_ER, 'Extended Range Y, V, U in three surfaces, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YVU444_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU444_SEMIPLANAR_ER, 'Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = Y width, U/V height = Y height.') + CU_YVU422_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU422_SEMIPLANAR_ER, 'Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YVU420_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_SEMIPLANAR_ER, 'Extended Range Y, VU in two surfaces (VU as one surface) with UV byte ordering, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_BAYER_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_RGGB, 'Bayer format - one channel in one surface with interleaved RGGB ordering.') + CU_BAYER_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_BGGR, 'Bayer format - one channel in one surface with interleaved BGGR ordering.') + CU_BAYER_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_GRBG, 'Bayer format - one channel in one surface with interleaved GRBG ordering.') + CU_BAYER_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_GBRG, 'Bayer format - one channel in one surface with interleaved GBRG ordering.') + CU_BAYER10_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER10_RGGB, 'Bayer10 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 10 bits used 6 bits No-op.') + CU_BAYER10_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER10_BGGR, 'Bayer10 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 10 bits used 6 bits No-op.') + CU_BAYER10_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER10_GRBG, 'Bayer10 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 10 bits used 6 bits No-op.') + CU_BAYER10_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER10_GBRG, 'Bayer10 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 10 bits used 6 bits No-op.') + CU_BAYER12_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_RGGB, 'Bayer12 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_BGGR, 'Bayer12 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_GRBG, 'Bayer12 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_GBRG, 'Bayer12 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER14_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER14_RGGB, 'Bayer14 format - one channel in one surface with interleaved RGGB ordering. Out of 16 bits, 14 bits used 2 bits No-op.') + CU_BAYER14_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER14_BGGR, 'Bayer14 format - one channel in one surface with interleaved BGGR ordering. Out of 16 bits, 14 bits used 2 bits No-op.') + CU_BAYER14_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER14_GRBG, 'Bayer14 format - one channel in one surface with interleaved GRBG ordering. Out of 16 bits, 14 bits used 2 bits No-op.') + CU_BAYER14_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER14_GBRG, 'Bayer14 format - one channel in one surface with interleaved GBRG ordering. Out of 16 bits, 14 bits used 2 bits No-op.') + CU_BAYER20_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER20_RGGB, 'Bayer20 format - one channel in one surface with interleaved RGGB ordering. Out of 32 bits, 20 bits used 12 bits No-op.') + CU_BAYER20_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER20_BGGR, 'Bayer20 format - one channel in one surface with interleaved BGGR ordering. Out of 32 bits, 20 bits used 12 bits No-op.') + CU_BAYER20_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER20_GRBG, 'Bayer20 format - one channel in one surface with interleaved GRBG ordering. Out of 32 bits, 20 bits used 12 bits No-op.') + CU_BAYER20_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER20_GBRG, 'Bayer20 format - one channel in one surface with interleaved GBRG ordering. Out of 32 bits, 20 bits used 12 bits No-op.') + CU_YVU444_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU444_PLANAR, 'Y, V, U in three surfaces, each in a separate surface, U/V width = Y width, U/V height = Y height.') + CU_YVU422_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU422_PLANAR, 'Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = Y height.') + CU_YVU420_PLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_PLANAR, 'Y, V, U in three surfaces, each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_BAYER_ISP_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_ISP_RGGB, 'Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved RGGB ordering and mapped to opaque integer datatype.') + CU_BAYER_ISP_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_ISP_BGGR, 'Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved BGGR ordering and mapped to opaque integer datatype.') + CU_BAYER_ISP_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_ISP_GRBG, 'Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved GRBG ordering and mapped to opaque integer datatype.') + CU_BAYER_ISP_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_ISP_GBRG, 'Nvidia proprietary Bayer ISP format - one channel in one surface with interleaved GBRG ordering and mapped to opaque integer datatype.') + CU_BAYER_BCCR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_BCCR, 'Bayer format - one channel in one surface with interleaved BCCR ordering.') + CU_BAYER_RCCB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_RCCB, 'Bayer format - one channel in one surface with interleaved RCCB ordering.') + CU_BAYER_CRBC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_CRBC, 'Bayer format - one channel in one surface with interleaved CRBC ordering.') + CU_BAYER_CBRC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_CBRC, 'Bayer format - one channel in one surface with interleaved CBRC ordering.') + CU_BAYER10_CCCC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER10_CCCC, 'Bayer10 format - one channel in one surface with interleaved CCCC ordering. Out of 16 bits, 10 bits used 6 bits No-op.') + CU_BAYER12_BCCR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_BCCR, 'Bayer12 format - one channel in one surface with interleaved BCCR ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_RCCB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_RCCB, 'Bayer12 format - one channel in one surface with interleaved RCCB ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_CRBC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_CRBC, 'Bayer12 format - one channel in one surface with interleaved CRBC ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_CBRC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_CBRC, 'Bayer12 format - one channel in one surface with interleaved CBRC ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_BAYER12_CCCC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER12_CCCC, 'Bayer12 format - one channel in one surface with interleaved CCCC ordering. Out of 16 bits, 12 bits used 4 bits No-op.') + CU_Y = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y, 'Color format for single Y plane.') + CU_YUV420_SEMIPLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_SEMIPLANAR_2020, 'Y, UV in two surfaces (UV as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YVU420_SEMIPLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_SEMIPLANAR_2020, 'Y, VU in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YUV420_PLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_PLANAR_2020, 'Y, U, V each in a separate surface, U/V width = 1/2 Y width, U/V height= 1/2 Y height.') + CU_YVU420_PLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_PLANAR_2020, 'Y, V, U each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YUV420_SEMIPLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_SEMIPLANAR_709, 'Y, UV in two surfaces (UV as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YVU420_SEMIPLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_SEMIPLANAR_709, 'Y, VU in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YUV420_PLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV420_PLANAR_709, 'Y, U, V each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_YVU420_PLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVU420_PLANAR_709, 'Y, V, U each in a separate surface, U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_420_SEMIPLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_420_SEMIPLANAR_709, 'Y10, V10U10 in two surfaces (VU as one surface), U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_420_SEMIPLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_420_SEMIPLANAR_2020, 'Y10, V10U10 in two surfaces (VU as one surface), U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_422_SEMIPLANAR_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_422_SEMIPLANAR_2020, 'Y10, V10U10 in two surfaces(VU as one surface) U/V width = 1/2 Y width, U/V height = Y height.') + CU_Y10V10U10_422_SEMIPLANAR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_422_SEMIPLANAR, 'Y10, V10U10 in two surfaces(VU as one surface) U/V width = 1/2 Y width, U/V height = Y height.') + CU_Y10V10U10_422_SEMIPLANAR_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_422_SEMIPLANAR_709, 'Y10, V10U10 in two surfaces(VU as one surface) U/V width = 1/2 Y width, U/V height = Y height.') + CU_Y_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y_ER, 'Extended Range Color format for single Y plane.') + CU_Y_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y_709_ER, 'Extended Range Color format for single Y plane.') + CU_Y10_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10_ER, 'Extended Range Color format for single Y10 plane.') + CU_Y10_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10_709_ER, 'Extended Range Color format for single Y10 plane.') + CU_Y12_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12_ER, 'Extended Range Color format for single Y12 plane.') + CU_Y12_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12_709_ER, 'Extended Range Color format for single Y12 plane.') + CU_YUVA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUVA, 'Y, U, V, A four channels in one surface, interleaved as AVUY.') + CU_YUV = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUV, 'Y, U, V three channels in one surface, interleaved as VUY. Only pitch linear format supported.') + CU_YVYU = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVYU, 'Y, U, V in one surface, interleaved as YVYU in one channel.') + CU_VYUY = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_VYUY, 'Y, U, V in one surface, interleaved as VYUY in one channel.') + CU_Y10V10U10_420_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_420_SEMIPLANAR_ER, 'Extended Range Y10, V10U10 in two surfaces(VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_420_SEMIPLANAR_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_420_SEMIPLANAR_709_ER, 'Extended Range Y10, V10U10 in two surfaces(VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y10V10U10_444_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_444_SEMIPLANAR_ER, 'Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height.') + CU_Y10V10U10_444_SEMIPLANAR_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10V10U10_444_SEMIPLANAR_709_ER, 'Extended Range Y10, V10U10 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height.') + CU_Y12V12U12_420_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_420_SEMIPLANAR_ER, 'Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y12V12U12_420_SEMIPLANAR_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_420_SEMIPLANAR_709_ER, 'Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = 1/2 Y width, U/V height = 1/2 Y height.') + CU_Y12V12U12_444_SEMIPLANAR_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_444_SEMIPLANAR_ER, 'Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height.') + CU_Y12V12U12_444_SEMIPLANAR_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12V12U12_444_SEMIPLANAR_709_ER, 'Extended Range Y12, V12U12 in two surfaces (VU as one surface) U/V width = Y width, U/V height = Y height.') + CU_UYVY_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_709, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + CU_UYVY_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_709_ER, 'Extended Range Y, U, V in one surface, interleaved as UYVY in one channel.') + CU_UYVY_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_2020, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + CU_MAX = cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_MAX + +class GLmapFlags(_cyb_FastEnum): + """ + Flags to map or unmap a resource + + See `CUGLmap_flags`. + """ + CU_GL_MAP_RESOURCE_FLAGS_NONE = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_NONE + CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY + CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD + +class OutputMode(_cyb_FastEnum): + """ + Profiler Output Modes + + See `CUoutput_mode`. + """ + CU_OUT_KEY_VALUE_PAIR = (cydriver.CUoutput_mode_enum.CU_OUT_KEY_VALUE_PAIR, 'Output mode Key-Value pair format.') + CU_OUT_CSV = (cydriver.CUoutput_mode_enum.CU_OUT_CSV, 'Output mode Comma separated values format.') + +class AtomicOperation(_cyb_FastEnum): + """ + CUDA-valid Atomic Operations + + See `CUatomicOperation`. + """ + CU_INTEGER_ADD = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_ADD + CU_INTEGER_MIN = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_MIN + CU_INTEGER_MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_MAX + CU_INTEGER_INCREMENT = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_INCREMENT + CU_INTEGER_DECREMENT = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_DECREMENT + CU_AND = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_AND + CU_OR = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_OR + CU_XOR = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_XOR + CU_EXCHANGE = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_EXCHANGE + CU_CAS = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_CAS + CU_FLOAT_ADD = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_ADD + CU_FLOAT_MIN = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_MIN + CU_FLOAT_MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_MAX + CU_MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_MAX + +class AtomicOperationCapability(_cyb_FastEnum): + """ + CUDA-valid Atomic Operation capabilities + + See `CUatomicOperationCapability`. + """ + CU_ATOMIC_CAPABILITY_SIGNED = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SIGNED + CU_ATOMIC_CAPABILITY_UNSIGNED = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_UNSIGNED + CU_ATOMIC_CAPABILITY_REDUCTION = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_REDUCTION + CU_ATOMIC_CAPABILITY_SCALAR_32 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_32 + CU_ATOMIC_CAPABILITY_SCALAR_64 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_64 + CU_ATOMIC_CAPABILITY_SCALAR_128 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_128 + CU_ATOMIC_CAPABILITY_VECTOR_32x4 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_VECTOR_32x4 + +class StreamAtomicReductionOpType(_cyb_FastEnum): + """ + Atomic reduction operation types for + `CUstreamBatchMemOpParams`::atomicReduction::reductionOp + + See `CUstreamAtomicReductionOpType`. + """ + CU_STREAM_ATOMIC_REDUCTION_OP_OR = (cydriver.CUstreamAtomicReductionOpType_enum.CU_STREAM_ATOMIC_REDUCTION_OP_OR, 'Performs an atomic OR: *(address) = *(address) | value') + CU_STREAM_ATOMIC_REDUCTION_OP_AND = (cydriver.CUstreamAtomicReductionOpType_enum.CU_STREAM_ATOMIC_REDUCTION_OP_AND, 'Performs an atomic AND: *(address) = *(address) & value') + CU_STREAM_ATOMIC_REDUCTION_OP_ADD = (cydriver.CUstreamAtomicReductionOpType_enum.CU_STREAM_ATOMIC_REDUCTION_OP_ADD, 'Performs an atomic ADD: *(address) = *(address) + value') + +class StreamAtomicReductionDataType(_cyb_FastEnum): + """ + Atomic reduction data types for + `CUstreamBatchMemOpParams`::atomicReduction::dataType + + See `CUstreamAtomicReductionDataType`. + """ + CU_STREAM_ATOMIC_REDUCTION_UNSIGNED_32 = cydriver.CUstreamAtomicReductionDataType_enum.CU_STREAM_ATOMIC_REDUCTION_UNSIGNED_32 + CU_STREAM_ATOMIC_REDUCTION_UNSIGNED_64 = cydriver.CUstreamAtomicReductionDataType_enum.CU_STREAM_ATOMIC_REDUCTION_UNSIGNED_64 + +class DevSmResourceGroupFlags(_cyb_FastEnum): + """ + Flags for a `CUdevSmResource` group + + See `CUdevSmResourceGroup_flags`. + """ + CU_DEV_SM_RESOURCE_GROUP_DEFAULT = cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_DEFAULT + CU_DEV_SM_RESOURCE_GROUP_BACKFILL = cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_BACKFILL + +class DevSmResourceSplitByCountFlags(_cyb_FastEnum): + """ + See `CUdevSmResourceSplitByCount_flags`. + """ + CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING = cydriver.CUdevSmResourceSplitByCount_flags.CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING + CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE = cydriver.CUdevSmResourceSplitByCount_flags.CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE + +class DevWorkqueueConfigScope(_cyb_FastEnum): + """ + Sharing scope for workqueues + + See `CUdevWorkqueueConfigScope`. + """ + CU_WORKQUEUE_SCOPE_DEVICE_CTX = (cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_DEVICE_CTX, 'Use all shared workqueue resources across all contexts. Default driver behaviour.') + CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED = (cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED, 'When possible, use non-overlapping workqueue resources with other balanced green contexts.') + +class HostTaskSyncMode(_cyb_FastEnum): + """ + See `CUhostTaskSyncMode`. + """ + CU_HOST_TASK_BLOCKING = (cydriver.CUhostTaskSyncMode_enum.CU_HOST_TASK_BLOCKING, 'The execution thread will block until new host tasks are ready to run') + CU_HOST_TASK_SPINWAIT = (cydriver.CUhostTaskSyncMode_enum.CU_HOST_TASK_SPINWAIT, 'The execution thread will spin wait until new host tasks are ready to run') + +class LaunchAttributePortableClusterMode(_cyb_FastEnum): + """ + Enum for defining applicability of portable cluster size, used with + `cuLaunchKernelEx` + + See `CUlaunchAttributePortableClusterMode`. + """ + CU_LAUNCH_PORTABLE_CLUSTER_MODE_DEFAULT = (cydriver.CUlaunchAttributePortableClusterMode_enum.CU_LAUNCH_PORTABLE_CLUSTER_MODE_DEFAULT, 'The default to use for allowing non-portable cluster size on launch - uses current function attribute for `CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED`') + CU_LAUNCH_PORTABLE_CLUSTER_MODE_REQUIRE_PORTABLE = (cydriver.CUlaunchAttributePortableClusterMode_enum.CU_LAUNCH_PORTABLE_CLUSTER_MODE_REQUIRE_PORTABLE, 'Specifies that the cluster size requested must be a portable size') + CU_LAUNCH_PORTABLE_CLUSTER_MODE_ALLOW_NON_PORTABLE = (cydriver.CUlaunchAttributePortableClusterMode_enum.CU_LAUNCH_PORTABLE_CLUSTER_MODE_ALLOW_NON_PORTABLE, 'Specifies that the cluster size requested may be a non-portable size') + +class SharedMemoryMode(_cyb_FastEnum): + """ + Shared memory related attributes for use with `cuLaunchKernelEx` + + See `CUsharedMemoryMode`. + """ + CU_DEFAULT = (cydriver.CUsharedMemoryMode_enum.CU_SHARED_MEMORY_MODE_DEFAULT, 'The default to use for shared memory on launch - uses current function attribute for `CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES`') + CU_REQUIRE_PORTABLE = (cydriver.CUsharedMemoryMode_enum.CU_SHARED_MEMORY_MODE_REQUIRE_PORTABLE, 'Specifies that the dynamic shared size bytes requested must be a portable size within the bounds of `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK`') + CU_ALLOW_NON_PORTABLE = (cydriver.CUsharedMemoryMode_enum.CU_SHARED_MEMORY_MODE_ALLOW_NON_PORTABLE, 'Specifies that the dynamic shared size bytes requested may be a non-portable size but still within the bounds of `CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN`') + +class StreamCigDataType(_cyb_FastEnum): + """ + See `CUstreamCigDataType`. + """ + D3D12_COMMAND_LIST = (cydriver.CUstreamCigDataType_enum.STREAM_CIG_DATA_TYPE_D3D12_COMMAND_LIST, 'D3D12 Command List Handle') + +class LogicalEndpointIpcHandleType(_cyb_FastEnum): + """ + IPC handle types that can be requested/queried for a given logical + endpoint + + See `CUlogicalEndpointIpcHandleType`. + """ + CU_NONE = cydriver.CUlogicalEndpointIpcHandleType_enum.CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_NONE + CU_FABRIC = cydriver.CUlogicalEndpointIpcHandleType_enum.CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_FABRIC + +class LogicalEndpointType(_cyb_FastEnum): + """ + Logical endpoint type + + See `CUlogicalEndpointType`. + """ + CU_INVALID = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_INVALID + CU_UNICAST = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_UNICAST + CU_MULTICAST = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_MULTICAST + +class LogicalEndpointFlag(_cyb_FastEnum): + """ + Flags for `CUlogicalEndpointProp` + + See `CUlogicalEndpointFlag`. + """ + CU_NONE = (cydriver.CUlogicalEndpointFlag_enum.CU_LOGICAL_ENDPOINT_FLAG_NONE, 'Default flag for logical endpoint construction') + CU_COUNTED_OPS = (cydriver.CUlogicalEndpointFlag_enum.CU_LOGICAL_ENDPOINT_FLAG_COUNTED_OPS, "Indicate the programmer's intention to use counted operations with the logical endpoint") + +class GraphRecaptureStatus(_cyb_FastEnum): + """ + See `CUgraphRecaptureStatus`. + """ + CU_GRAPH_RECAPTURE_ELIGIBLE_FOR_UPDATE = (cydriver.CUgraphRecaptureStatus_enum.CU_GRAPH_RECAPTURE_ELIGIBLE_FOR_UPDATE, 'Node is eligible for update in an instantiated graph.') + CU_GRAPH_RECAPTURE_INELIGIBLE_FOR_UPDATE = (cydriver.CUgraphRecaptureStatus_enum.CU_GRAPH_RECAPTURE_INELIGIBLE_FOR_UPDATE, 'Parameter changes in the node cannot be applied to an instantiated graph.') + CU_GRAPH_RECAPTURE_ERROR = (cydriver.CUgraphRecaptureStatus_enum.CU_GRAPH_RECAPTURE_ERROR, 'Error while attempting to recapture the node. The recapture will be ended regardless of the return value from the callback.') + + +############################################################################### +# Error handling +############################################################################### + + +class DriverError(Exception): + def __init__(self, status): + self.status = status + s = Result(status) + cdef str err = f"{s.name} ({s.value})" + super(DriverError, self).__init__(err) + + def __reduce__(self): + return (type(self), (self.status,)) + +class InvalidValueError(DriverError): + pass +class OutOfMemoryError(DriverError): + pass +class NotInitializedError(DriverError): + pass +class DeinitializedError(DriverError): + pass +class ProfilerDisabledError(DriverError): + pass +class ProfilerNotInitializedError(DriverError): + pass +class ProfilerAlreadyStartedError(DriverError): + pass +class ProfilerAlreadyStoppedError(DriverError): + pass +class StubLibraryError(DriverError): + pass +class CallRequiresNewerDriverError(DriverError): + pass +class DeviceUnavailableError(DriverError): + pass +class NoDeviceError(DriverError): + pass +class InvalidDeviceError(DriverError): + pass +class DeviceNotLicensedError(DriverError): + pass +class InvalidImageError(DriverError): + pass +class InvalidContextError(DriverError): + pass +class ContextAlreadyCurrentError(DriverError): + pass +class MapFailedError(DriverError): + pass +class UnmapFailedError(DriverError): + pass +class ArrayIsMappedError(DriverError): + pass +class AlreadyMappedError(DriverError): + pass +class NoBinaryForGpuError(DriverError): + pass +class AlreadyAcquiredError(DriverError): + pass +class NotMappedError(DriverError): + pass +class NotMappedAsArrayError(DriverError): + pass +class NotMappedAsPointerError(DriverError): + pass +class EccUncorrectableError(DriverError): + pass +class UnsupportedLimitError(DriverError): + pass +class ContextAlreadyInUseError(DriverError): + pass +class PeerAccessUnsupportedError(DriverError): + pass +class InvalidPtxError(DriverError): + pass +class InvalidGraphicsContextError(DriverError): + pass +class NvlinkUncorrectableError(DriverError): + pass +class JitCompilerNotFoundError(DriverError): + pass +class UnsupportedPtxVersionError(DriverError): + pass +class JitCompilationDisabledError(DriverError): + pass +class UnsupportedExecAffinityError(DriverError): + pass +class UnsupportedDevsideSyncError(DriverError): + pass +class ContainedError(DriverError): + pass +class InvalidSourceError(DriverError): + pass +class FileNotFoundError(DriverError): + pass +class SharedObjectSymbolNotFoundError(DriverError): + pass +class SharedObjectInitFailedError(DriverError): + pass +class OperatingSystemError(DriverError): + pass +class InvalidHandleError(DriverError): + pass +class IllegalStateError(DriverError): + pass +class LossyQueryError(DriverError): + pass +class NotFoundError(DriverError): + pass +class NotReadyError(DriverError): + pass +class IllegalAddressError(DriverError): + pass +class LaunchOutOfResourcesError(DriverError): + pass +class LaunchTimeoutError(DriverError): + pass +class LaunchIncompatibleTexturingError(DriverError): + pass +class PeerAccessAlreadyEnabledError(DriverError): + pass +class PeerAccessNotEnabledError(DriverError): + pass +class PrimaryContextActiveError(DriverError): + pass +class ContextIsDestroyedError(DriverError): + pass +class AssertError(DriverError): + pass +class TooManyPeersError(DriverError): + pass +class HostMemoryAlreadyRegisteredError(DriverError): + pass +class HostMemoryNotRegisteredError(DriverError): + pass +class HardwareStackErrorError(DriverError): + pass +class IllegalInstructionError(DriverError): + pass +class MisalignedAddressError(DriverError): + pass +class InvalidAddressSpaceError(DriverError): + pass +class InvalidPcError(DriverError): + pass +class LaunchFailedError(DriverError): + pass +class CooperativeLaunchTooLargeError(DriverError): + pass +class TensorMemoryLeakError(DriverError): + pass +class NotPermittedError(DriverError): + pass +class NotSupportedError(DriverError): + pass +class SystemNotReadyError(DriverError): + pass +class SystemDriverMismatchError(DriverError): + pass +class CompatNotSupportedOnDeviceError(DriverError): + pass +class MpsConnectionFailedError(DriverError): + pass +class MpsRpcFailureError(DriverError): + pass +class MpsServerNotReadyError(DriverError): + pass +class MpsMaxClientsReachedError(DriverError): + pass +class MpsMaxConnectionsReachedError(DriverError): + pass +class MpsClientTerminatedError(DriverError): + pass +class CdpNotSupportedError(DriverError): + pass +class CdpVersionMismatchError(DriverError): + pass +class StreamCaptureUnsupportedError(DriverError): + pass +class StreamCaptureInvalidatedError(DriverError): + pass +class StreamCaptureMergeError(DriverError): + pass +class StreamCaptureUnmatchedError(DriverError): + pass +class StreamCaptureUnjoinedError(DriverError): + pass +class StreamCaptureIsolationError(DriverError): + pass +class StreamCaptureImplicitError(DriverError): + pass +class CapturedEventError(DriverError): + pass +class StreamCaptureWrongThreadError(DriverError): + pass +class TimeoutError(DriverError): + pass +class GraphExecUpdateFailureError(DriverError): + pass +class ExternalDeviceError(DriverError): + pass +class InvalidClusterSizeError(DriverError): + pass +class FunctionNotLoadedError(DriverError): + pass +class InvalidResourceTypeError(DriverError): + pass +class InvalidResourceConfigurationError(DriverError): + pass +class KeyRotationError(DriverError): + pass +class StreamDetachedError(DriverError): + pass +class GraphRecaptureFailureError(DriverError): + pass +class UnknownError(DriverError): + pass +cdef object _driver_error_factory(int status): + cdef object pystatus = status + if status == 1: + return InvalidValueError(pystatus) + elif status == 2: + return OutOfMemoryError(pystatus) + elif status == 3: + return NotInitializedError(pystatus) + elif status == 4: + return DeinitializedError(pystatus) + elif status == 5: + return ProfilerDisabledError(pystatus) + elif status == 6: + return ProfilerNotInitializedError(pystatus) + elif status == 7: + return ProfilerAlreadyStartedError(pystatus) + elif status == 8: + return ProfilerAlreadyStoppedError(pystatus) + elif status == 34: + return StubLibraryError(pystatus) + elif status == 36: + return CallRequiresNewerDriverError(pystatus) + elif status == 46: + return DeviceUnavailableError(pystatus) + elif status == 100: + return NoDeviceError(pystatus) + elif status == 101: + return InvalidDeviceError(pystatus) + elif status == 102: + return DeviceNotLicensedError(pystatus) + elif status == 200: + return InvalidImageError(pystatus) + elif status == 201: + return InvalidContextError(pystatus) + elif status == 202: + return ContextAlreadyCurrentError(pystatus) + elif status == 205: + return MapFailedError(pystatus) + elif status == 206: + return UnmapFailedError(pystatus) + elif status == 207: + return ArrayIsMappedError(pystatus) + elif status == 208: + return AlreadyMappedError(pystatus) + elif status == 209: + return NoBinaryForGpuError(pystatus) + elif status == 210: + return AlreadyAcquiredError(pystatus) + elif status == 211: + return NotMappedError(pystatus) + elif status == 212: + return NotMappedAsArrayError(pystatus) + elif status == 213: + return NotMappedAsPointerError(pystatus) + elif status == 214: + return EccUncorrectableError(pystatus) + elif status == 215: + return UnsupportedLimitError(pystatus) + elif status == 216: + return ContextAlreadyInUseError(pystatus) + elif status == 217: + return PeerAccessUnsupportedError(pystatus) + elif status == 218: + return InvalidPtxError(pystatus) + elif status == 219: + return InvalidGraphicsContextError(pystatus) + elif status == 220: + return NvlinkUncorrectableError(pystatus) + elif status == 221: + return JitCompilerNotFoundError(pystatus) + elif status == 222: + return UnsupportedPtxVersionError(pystatus) + elif status == 223: + return JitCompilationDisabledError(pystatus) + elif status == 224: + return UnsupportedExecAffinityError(pystatus) + elif status == 225: + return UnsupportedDevsideSyncError(pystatus) + elif status == 226: + return ContainedError(pystatus) + elif status == 300: + return InvalidSourceError(pystatus) + elif status == 301: + return FileNotFoundError(pystatus) + elif status == 302: + return SharedObjectSymbolNotFoundError(pystatus) + elif status == 303: + return SharedObjectInitFailedError(pystatus) + elif status == 304: + return OperatingSystemError(pystatus) + elif status == 400: + return InvalidHandleError(pystatus) + elif status == 401: + return IllegalStateError(pystatus) + elif status == 402: + return LossyQueryError(pystatus) + elif status == 500: + return NotFoundError(pystatus) + elif status == 600: + return NotReadyError(pystatus) + elif status == 700: + return IllegalAddressError(pystatus) + elif status == 701: + return LaunchOutOfResourcesError(pystatus) + elif status == 702: + return LaunchTimeoutError(pystatus) + elif status == 703: + return LaunchIncompatibleTexturingError(pystatus) + elif status == 704: + return PeerAccessAlreadyEnabledError(pystatus) + elif status == 705: + return PeerAccessNotEnabledError(pystatus) + elif status == 708: + return PrimaryContextActiveError(pystatus) + elif status == 709: + return ContextIsDestroyedError(pystatus) + elif status == 710: + return AssertError(pystatus) + elif status == 711: + return TooManyPeersError(pystatus) + elif status == 712: + return HostMemoryAlreadyRegisteredError(pystatus) + elif status == 713: + return HostMemoryNotRegisteredError(pystatus) + elif status == 714: + return HardwareStackErrorError(pystatus) + elif status == 715: + return IllegalInstructionError(pystatus) + elif status == 716: + return MisalignedAddressError(pystatus) + elif status == 717: + return InvalidAddressSpaceError(pystatus) + elif status == 718: + return InvalidPcError(pystatus) + elif status == 719: + return LaunchFailedError(pystatus) + elif status == 720: + return CooperativeLaunchTooLargeError(pystatus) + elif status == 721: + return TensorMemoryLeakError(pystatus) + elif status == 800: + return NotPermittedError(pystatus) + elif status == 801: + return NotSupportedError(pystatus) + elif status == 802: + return SystemNotReadyError(pystatus) + elif status == 803: + return SystemDriverMismatchError(pystatus) + elif status == 804: + return CompatNotSupportedOnDeviceError(pystatus) + elif status == 805: + return MpsConnectionFailedError(pystatus) + elif status == 806: + return MpsRpcFailureError(pystatus) + elif status == 807: + return MpsServerNotReadyError(pystatus) + elif status == 808: + return MpsMaxClientsReachedError(pystatus) + elif status == 809: + return MpsMaxConnectionsReachedError(pystatus) + elif status == 810: + return MpsClientTerminatedError(pystatus) + elif status == 811: + return CdpNotSupportedError(pystatus) + elif status == 812: + return CdpVersionMismatchError(pystatus) + elif status == 900: + return StreamCaptureUnsupportedError(pystatus) + elif status == 901: + return StreamCaptureInvalidatedError(pystatus) + elif status == 902: + return StreamCaptureMergeError(pystatus) + elif status == 903: + return StreamCaptureUnmatchedError(pystatus) + elif status == 904: + return StreamCaptureUnjoinedError(pystatus) + elif status == 905: + return StreamCaptureIsolationError(pystatus) + elif status == 906: + return StreamCaptureImplicitError(pystatus) + elif status == 907: + return CapturedEventError(pystatus) + elif status == 908: + return StreamCaptureWrongThreadError(pystatus) + elif status == 909: + return TimeoutError(pystatus) + elif status == 910: + return GraphExecUpdateFailureError(pystatus) + elif status == 911: + return ExternalDeviceError(pystatus) + elif status == 912: + return InvalidClusterSizeError(pystatus) + elif status == 913: + return FunctionNotLoadedError(pystatus) + elif status == 914: + return InvalidResourceTypeError(pystatus) + elif status == 915: + return InvalidResourceConfigurationError(pystatus) + elif status == 916: + return KeyRotationError(pystatus) + elif status == 917: + return StreamDetachedError(pystatus) + elif status == 918: + return GraphRecaptureFailureError(pystatus) + elif status == 999: + return UnknownError(pystatus) + return DriverError(status) + +@cython.profile(False) +cdef int check_status(int status) except 1 nogil: + if status != 0: + with gil: + raise _driver_error_factory(status) + return status + + +@cython.profile(False) +cdef int check_status_size(int status) except 1 nogil: + return check_status(status) + + +############################################################################### +# POD definitions +############################################################################### + +cdef _get_uuid_dtype_offsets(): + cdef CUuuid pod + return _numpy.dtype({ + 'names': ['bytes'], + 'formats': [(_numpy.int8, 16)], + 'offsets': [ + (&(pod.bytes)) - (&pod), + ], + 'itemsize': sizeof(CUuuid), + }) + +uuid_dtype = _get_uuid_dtype_offsets() + +cdef class Uuid: + """Empty-initialize an instance of `CUuuid`. + + + .. seealso:: `CUuuid` + """ + cdef: + CUuuid *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUuuid)) + if self._ptr == NULL: + raise MemoryError("Error allocating Uuid") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUuuid *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Uuid object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Uuid other_ + if not isinstance(other, Uuid): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUuuid)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUuuid), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUuuid)) + if self._ptr == NULL: + raise MemoryError("Error allocating Uuid") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUuuid)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def bytes(self): + """~_numpy.int8: (array of length 16).""" + return _cyb_cpython.PyUnicode_FromString(self._ptr[0].bytes) + + @bytes.setter + def bytes(self, val): + if self._readonly: + raise ValueError("This Uuid instance is read-only") + cdef bytes buf = val.encode() + if len(buf) >= 16: + raise ValueError("String too long for field bytes, max length is 15") + cdef char *ptr = buf + _cyb_memcpy((self._ptr[0].bytes), ptr, 16) + + @staticmethod + def from_buffer(buffer): + """Create an Uuid instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUuuid), Uuid) + + @staticmethod + def from_data(data): + """Create an Uuid instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `uuid_dtype` holding the data. + """ + return _cyb_from_data(data, "uuid_dtype", uuid_dtype, Uuid) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Uuid instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Uuid obj = Uuid.__new__(Uuid) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUuuid)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Uuid") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUuuid)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_fabric_handle_v1_dtype_offsets(): + cdef CUmemFabricHandle_v1 pod + return _numpy.dtype({ + 'names': ['data_'], + 'formats': [(_numpy.uint8, 64)], + 'offsets': [ + (&(pod.data)) - (&pod), + ], + 'itemsize': sizeof(CUmemFabricHandle_v1), + }) + +mem_fabric_handle_v1_dtype = _get_mem_fabric_handle_v1_dtype_offsets() + +cdef class MemFabricHandle_v1: + """Empty-initialize an instance of `CUmemFabricHandle_v1`. + + + .. seealso:: `CUmemFabricHandle_v1` + """ + cdef: + CUmemFabricHandle_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemFabricHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemFabricHandle_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemFabricHandle_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemFabricHandle_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemFabricHandle_v1 other_ + if not isinstance(other, MemFabricHandle_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemFabricHandle_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemFabricHandle_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemFabricHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemFabricHandle_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemFabricHandle_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def data_(self): + """~_numpy.uint8: (array of length 64).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].data)), + (sizeof(unsigned char) * (64)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) + + @data_.setter + def data_(self, val): + if self._readonly: + raise ValueError("This MemFabricHandle_v1 instance is read-only") + if len(val) != 64: + raise ValueError(f"Expected length { 64 } for field data_, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].data)), (_val_.ctypes.data), sizeof(unsigned char) * (64)) + + @staticmethod + def from_buffer(buffer): + """Create an MemFabricHandle_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemFabricHandle_v1), MemFabricHandle_v1) + + @staticmethod + def from_data(data): + """Create an MemFabricHandle_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_fabric_handle_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_fabric_handle_v1_dtype", mem_fabric_handle_v1_dtype, MemFabricHandle_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemFabricHandle_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemFabricHandle_v1 obj = MemFabricHandle_v1.__new__(MemFabricHandle_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemFabricHandle_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemFabricHandle_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemFabricHandle_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ipc_event_handle_v1_dtype_offsets(): + cdef CUipcEventHandle_v1 pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.int8, 64)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUipcEventHandle_v1), + }) + +ipc_event_handle_v1_dtype = _get_ipc_event_handle_v1_dtype_offsets() + +cdef class IpcEventHandle_v1: + """Empty-initialize an instance of `CUipcEventHandle_v1`. + + + .. seealso:: `CUipcEventHandle_v1` + """ + cdef: + CUipcEventHandle_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUipcEventHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating IpcEventHandle_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUipcEventHandle_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.IpcEventHandle_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef IpcEventHandle_v1 other_ + if not isinstance(other, IpcEventHandle_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUipcEventHandle_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUipcEventHandle_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUipcEventHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating IpcEventHandle_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUipcEventHandle_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an IpcEventHandle_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUipcEventHandle_v1), IpcEventHandle_v1) + + @staticmethod + def from_data(data): + """Create an IpcEventHandle_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ipc_event_handle_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "ipc_event_handle_v1_dtype", ipc_event_handle_v1_dtype, IpcEventHandle_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an IpcEventHandle_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef IpcEventHandle_v1 obj = IpcEventHandle_v1.__new__(IpcEventHandle_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUipcEventHandle_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating IpcEventHandle_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUipcEventHandle_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ipc_mem_handle_v1_dtype_offsets(): + cdef CUipcMemHandle_v1 pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.int8, 64)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUipcMemHandle_v1), + }) + +ipc_mem_handle_v1_dtype = _get_ipc_mem_handle_v1_dtype_offsets() + +cdef class IpcMemHandle_v1: + """Empty-initialize an instance of `CUipcMemHandle_v1`. + + + .. seealso:: `CUipcMemHandle_v1` + """ + cdef: + CUipcMemHandle_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUipcMemHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating IpcMemHandle_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUipcMemHandle_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.IpcMemHandle_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef IpcMemHandle_v1 other_ + if not isinstance(other, IpcMemHandle_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUipcMemHandle_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUipcMemHandle_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUipcMemHandle_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating IpcMemHandle_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUipcMemHandle_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an IpcMemHandle_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUipcMemHandle_v1), IpcMemHandle_v1) + + @staticmethod + def from_data(data): + """Create an IpcMemHandle_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ipc_mem_handle_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "ipc_mem_handle_v1_dtype", ipc_mem_handle_v1_dtype, IpcMemHandle_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an IpcMemHandle_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef IpcMemHandle_v1 obj = IpcMemHandle_v1.__new__(IpcMemHandle_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUipcMemHandle_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating IpcMemHandle_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUipcMemHandle_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_batch_mem_op_node_params_v1_dtype_offsets(): + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['ctx', 'count', 'param_array', 'flags_'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.ctx)) - (&pod), + (&(pod.count)) - (&pod), + (&(pod.paramArray)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1), + }) + +batch_mem_op_node_params_v1_dtype = _get_batch_mem_op_node_params_v1_dtype_offsets() + +cdef class BatchMemOpNodeParams_v1: + """Empty-initialize an instance of `CUDA_BATCH_MEM_OP_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_BATCH_MEM_OP_NODE_PARAMS_v1` + """ + cdef: + CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.BatchMemOpNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef BatchMemOpNodeParams_v1 other_ + if not isinstance(other, BatchMemOpNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v1 instance is read-only") + self._ptr[0].ctx = val + + @property + def count(self): + """int: """ + return self._ptr[0].count + + @count.setter + def count(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v1 instance is read-only") + self._ptr[0].count = val + + @property + def param_array(self): + """int: """ + return (self._ptr[0].paramArray) + + @param_array.setter + def param_array(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v1 instance is read-only") + self._ptr[0].paramArray = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an BatchMemOpNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1), BatchMemOpNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an BatchMemOpNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `batch_mem_op_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "batch_mem_op_node_params_v1_dtype", batch_mem_op_node_params_v1_dtype, BatchMemOpNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an BatchMemOpNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef BatchMemOpNodeParams_v1 obj = BatchMemOpNodeParams_v1.__new__(BatchMemOpNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_batch_mem_op_node_params_v2_dtype_offsets(): + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['ctx', 'count', 'param_array', 'flags_'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.ctx)) - (&pod), + (&(pod.count)) - (&pod), + (&(pod.paramArray)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2), + }) + +batch_mem_op_node_params_v2_dtype = _get_batch_mem_op_node_params_v2_dtype_offsets() + +cdef class BatchMemOpNodeParams_v2: + """Empty-initialize an instance of `CUDA_BATCH_MEM_OP_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_BATCH_MEM_OP_NODE_PARAMS_v2` + """ + cdef: + CUDA_BATCH_MEM_OP_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.BatchMemOpNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef BatchMemOpNodeParams_v2 other_ + if not isinstance(other, BatchMemOpNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @property + def count(self): + """int: """ + return self._ptr[0].count + + @count.setter + def count(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v2 instance is read-only") + self._ptr[0].count = val + + @property + def param_array(self): + """int: """ + return (self._ptr[0].paramArray) + + @param_array.setter + def param_array(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v2 instance is read-only") + self._ptr[0].paramArray = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v2 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an BatchMemOpNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2), BatchMemOpNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an BatchMemOpNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `batch_mem_op_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "batch_mem_op_node_params_v2_dtype", batch_mem_op_node_params_v2_dtype, BatchMemOpNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an BatchMemOpNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef BatchMemOpNodeParams_v2 obj = BatchMemOpNodeParams_v2.__new__(BatchMemOpNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating BatchMemOpNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_devprop_v1_dtype_offsets(): + cdef CUdevprop_v1 pod + return _numpy.dtype({ + 'names': ['max_threads_per_block', 'max_threads_dim', 'max_grid_size', 'shared_mem_per_block', 'total_constant_memory', 'simd_width', 'mem_pitch', 'regs_per_block', 'clock_rate', 'texture_align'], + 'formats': [_numpy.int32, (_numpy.int32, 3), (_numpy.int32, 3), _numpy.int32, _numpy.int32, _numpy.int32, _numpy.int32, _numpy.int32, _numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.maxThreadsPerBlock)) - (&pod), + (&(pod.maxThreadsDim)) - (&pod), + (&(pod.maxGridSize)) - (&pod), + (&(pod.sharedMemPerBlock)) - (&pod), + (&(pod.totalConstantMemory)) - (&pod), + (&(pod.SIMDWidth)) - (&pod), + (&(pod.memPitch)) - (&pod), + (&(pod.regsPerBlock)) - (&pod), + (&(pod.clockRate)) - (&pod), + (&(pod.textureAlign)) - (&pod), + ], + 'itemsize': sizeof(CUdevprop_v1), + }) + +devprop_v1_dtype = _get_devprop_v1_dtype_offsets() + +cdef class Devprop_v1: + """Empty-initialize an instance of `CUdevprop_v1`. + + + .. seealso:: `CUdevprop_v1` + """ + cdef: + CUdevprop_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevprop_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Devprop_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUdevprop_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Devprop_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Devprop_v1 other_ + if not isinstance(other, Devprop_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUdevprop_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUdevprop_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUdevprop_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Devprop_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUdevprop_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def max_threads_per_block(self): + """int: """ + return self._ptr[0].maxThreadsPerBlock + + @max_threads_per_block.setter + def max_threads_per_block(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].maxThreadsPerBlock = val + + @property + def max_threads_dim(self): + """~_numpy.int32: (array of length 3).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].maxThreadsDim)), + (sizeof(int) * (3)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.int32) + + @max_threads_dim.setter + def max_threads_dim(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + if len(val) != 3: + raise ValueError(f"Expected length { 3 } for field max_threads_dim, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.int32)) + _cyb_memcpy((&(self._ptr[0].maxThreadsDim)), (_val_.ctypes.data), sizeof(int) * (3)) + + @property + def max_grid_size(self): + """~_numpy.int32: (array of length 3).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].maxGridSize)), + (sizeof(int) * (3)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.int32) + + @max_grid_size.setter + def max_grid_size(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + if len(val) != 3: + raise ValueError(f"Expected length { 3 } for field max_grid_size, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.int32)) + _cyb_memcpy((&(self._ptr[0].maxGridSize)), (_val_.ctypes.data), sizeof(int) * (3)) + + @property + def shared_mem_per_block(self): + """int: """ + return self._ptr[0].sharedMemPerBlock + + @shared_mem_per_block.setter + def shared_mem_per_block(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].sharedMemPerBlock = val + + @property + def total_constant_memory(self): + """int: """ + return self._ptr[0].totalConstantMemory + + @total_constant_memory.setter + def total_constant_memory(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].totalConstantMemory = val + + @property + def simd_width(self): + """int: """ + return self._ptr[0].SIMDWidth + + @simd_width.setter + def simd_width(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].SIMDWidth = val + + @property + def mem_pitch(self): + """int: """ + return self._ptr[0].memPitch + + @mem_pitch.setter + def mem_pitch(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].memPitch = val + + @property + def regs_per_block(self): + """int: """ + return self._ptr[0].regsPerBlock + + @regs_per_block.setter + def regs_per_block(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].regsPerBlock = val + + @property + def clock_rate(self): + """int: """ + return self._ptr[0].clockRate + + @clock_rate.setter + def clock_rate(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].clockRate = val + + @property + def texture_align(self): + """int: """ + return self._ptr[0].textureAlign + + @texture_align.setter + def texture_align(self, val): + if self._readonly: + raise ValueError("This Devprop_v1 instance is read-only") + self._ptr[0].textureAlign = val + + @staticmethod + def from_buffer(buffer): + """Create an Devprop_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUdevprop_v1), Devprop_v1) + + @staticmethod + def from_data(data): + """Create an Devprop_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `devprop_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "devprop_v1_dtype", devprop_v1_dtype, Devprop_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Devprop_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Devprop_v1 obj = Devprop_v1.__new__(Devprop_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUdevprop_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Devprop_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUdevprop_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_access_policy_window_v1_dtype_offsets(): + cdef CUaccessPolicyWindow_v1 pod + return _numpy.dtype({ + 'names': ['base_ptr', 'num_bytes', 'hit_ratio', 'hit_prop', 'miss_prop'], + 'formats': [_numpy.intp, _numpy.uint64, _numpy.float32, _numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.base_ptr)) - (&pod), + (&(pod.num_bytes)) - (&pod), + (&(pod.hitRatio)) - (&pod), + (&(pod.hitProp)) - (&pod), + (&(pod.missProp)) - (&pod), + ], + 'itemsize': sizeof(CUaccessPolicyWindow_v1), + }) + +access_policy_window_v1_dtype = _get_access_policy_window_v1_dtype_offsets() + +cdef class AccessPolicyWindow_v1: + """Empty-initialize an instance of `CUaccessPolicyWindow_v1`. + + + .. seealso:: `CUaccessPolicyWindow_v1` + """ + cdef: + CUaccessPolicyWindow_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUaccessPolicyWindow_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating AccessPolicyWindow_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUaccessPolicyWindow_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.AccessPolicyWindow_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef AccessPolicyWindow_v1 other_ + if not isinstance(other, AccessPolicyWindow_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUaccessPolicyWindow_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUaccessPolicyWindow_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUaccessPolicyWindow_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating AccessPolicyWindow_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUaccessPolicyWindow_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def base_ptr(self): + """int: """ + return (self._ptr[0].base_ptr) + + @base_ptr.setter + def base_ptr(self, val): + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + self._ptr[0].base_ptr = val + + @property + def num_bytes(self): + """int: """ + return self._ptr[0].num_bytes + + @num_bytes.setter + def num_bytes(self, val): + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + self._ptr[0].num_bytes = val + + @property + def hit_ratio(self): + """float: """ + return self._ptr[0].hitRatio + + @hit_ratio.setter + def hit_ratio(self, val): + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + self._ptr[0].hitRatio = val + + @property + def hit_prop(self): + """int: """ + return (self._ptr[0].hitProp) + + @hit_prop.setter + def hit_prop(self, val): + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + self._ptr[0].hitProp = val + + @property + def miss_prop(self): + """int: """ + return (self._ptr[0].missProp) + + @miss_prop.setter + def miss_prop(self, val): + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + self._ptr[0].missProp = val + + @staticmethod + def from_buffer(buffer): + """Create an AccessPolicyWindow_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUaccessPolicyWindow_v1), AccessPolicyWindow_v1) + + @staticmethod + def from_data(data): + """Create an AccessPolicyWindow_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `access_policy_window_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "access_policy_window_v1_dtype", access_policy_window_v1_dtype, AccessPolicyWindow_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an AccessPolicyWindow_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef AccessPolicyWindow_v1 obj = AccessPolicyWindow_v1.__new__(AccessPolicyWindow_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUaccessPolicyWindow_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating AccessPolicyWindow_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUaccessPolicyWindow_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_kernel_node_params_v2_dtype_offsets(): + cdef CUDA_KERNEL_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['func', 'grid_dim_x', 'grid_dim_y', 'grid_dim_z', 'block_dim_x', 'block_dim_y', 'block_dim_z', 'shared_mem_bytes', 'kernel_params', 'extra', 'kern', 'ctx'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.intp, _numpy.intp, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.func)) - (&pod), + (&(pod.gridDimX)) - (&pod), + (&(pod.gridDimY)) - (&pod), + (&(pod.gridDimZ)) - (&pod), + (&(pod.blockDimX)) - (&pod), + (&(pod.blockDimY)) - (&pod), + (&(pod.blockDimZ)) - (&pod), + (&(pod.sharedMemBytes)) - (&pod), + (&(pod.kernelParams)) - (&pod), + (&(pod.extra)) - (&pod), + (&(pod.kern)) - (&pod), + (&(pod.ctx)) - (&pod), + ], + 'itemsize': sizeof(CUDA_KERNEL_NODE_PARAMS_v2), + }) + +kernel_node_params_v2_dtype = _get_kernel_node_params_v2_dtype_offsets() + +cdef class KernelNodeParams_v2: + """Empty-initialize an instance of `CUDA_KERNEL_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_KERNEL_NODE_PARAMS_v2` + """ + cdef: + CUDA_KERNEL_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_KERNEL_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.KernelNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef KernelNodeParams_v2 other_ + if not isinstance(other, KernelNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_KERNEL_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def func(self): + """int: """ + return (self._ptr[0].func) + + @func.setter + def func(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].func = val + + @property + def grid_dim_x(self): + """int: """ + return self._ptr[0].gridDimX + + @grid_dim_x.setter + def grid_dim_x(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].gridDimX = val + + @property + def grid_dim_y(self): + """int: """ + return self._ptr[0].gridDimY + + @grid_dim_y.setter + def grid_dim_y(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].gridDimY = val + + @property + def grid_dim_z(self): + """int: """ + return self._ptr[0].gridDimZ + + @grid_dim_z.setter + def grid_dim_z(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].gridDimZ = val + + @property + def block_dim_x(self): + """int: """ + return self._ptr[0].blockDimX + + @block_dim_x.setter + def block_dim_x(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].blockDimX = val + + @property + def block_dim_y(self): + """int: """ + return self._ptr[0].blockDimY + + @block_dim_y.setter + def block_dim_y(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].blockDimY = val + + @property + def block_dim_z(self): + """int: """ + return self._ptr[0].blockDimZ + + @block_dim_z.setter + def block_dim_z(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].blockDimZ = val + + @property + def shared_mem_bytes(self): + """int: """ + return self._ptr[0].sharedMemBytes + + @shared_mem_bytes.setter + def shared_mem_bytes(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].sharedMemBytes = val + + @property + def kernel_params(self): + """int: """ + return (self._ptr[0].kernelParams) + + @kernel_params.setter + def kernel_params(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].kernelParams = val + + @property + def extra(self): + """int: """ + return (self._ptr[0].extra) + + @extra.setter + def extra(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].extra = val + + @property + def kern(self): + """int: """ + return (self._ptr[0].kern) + + @kern.setter + def kern(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].kern = val + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @staticmethod + def from_buffer(buffer): + """Create an KernelNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_KERNEL_NODE_PARAMS_v2), KernelNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an KernelNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `kernel_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "kernel_node_params_v2_dtype", kernel_node_params_v2_dtype, KernelNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an KernelNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef KernelNodeParams_v2 obj = KernelNodeParams_v2.__new__(KernelNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_kernel_node_params_v3_dtype_offsets(): + cdef CUDA_KERNEL_NODE_PARAMS_v3 pod + return _numpy.dtype({ + 'names': ['func', 'grid_dim_x', 'grid_dim_y', 'grid_dim_z', 'block_dim_x', 'block_dim_y', 'block_dim_z', 'shared_mem_bytes', 'kernel_params', 'extra', 'kern', 'ctx'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.intp, _numpy.intp, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.func)) - (&pod), + (&(pod.gridDimX)) - (&pod), + (&(pod.gridDimY)) - (&pod), + (&(pod.gridDimZ)) - (&pod), + (&(pod.blockDimX)) - (&pod), + (&(pod.blockDimY)) - (&pod), + (&(pod.blockDimZ)) - (&pod), + (&(pod.sharedMemBytes)) - (&pod), + (&(pod.kernelParams)) - (&pod), + (&(pod.extra)) - (&pod), + (&(pod.kern)) - (&pod), + (&(pod.ctx)) - (&pod), + ], + 'itemsize': sizeof(CUDA_KERNEL_NODE_PARAMS_v3), + }) + +kernel_node_params_v3_dtype = _get_kernel_node_params_v3_dtype_offsets() + +cdef class KernelNodeParams_v3: + """Empty-initialize an instance of `CUDA_KERNEL_NODE_PARAMS_v3`. + + + .. seealso:: `CUDA_KERNEL_NODE_PARAMS_v3` + """ + cdef: + CUDA_KERNEL_NODE_PARAMS_v3 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + if self._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v3") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_KERNEL_NODE_PARAMS_v3 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.KernelNodeParams_v3 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef KernelNodeParams_v3 other_ + if not isinstance(other, KernelNodeParams_v3): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_KERNEL_NODE_PARAMS_v3), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + if self._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v3") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def func(self): + """int: """ + return (self._ptr[0].func) + + @func.setter + def func(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].func = val + + @property + def grid_dim_x(self): + """int: """ + return self._ptr[0].gridDimX + + @grid_dim_x.setter + def grid_dim_x(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].gridDimX = val + + @property + def grid_dim_y(self): + """int: """ + return self._ptr[0].gridDimY + + @grid_dim_y.setter + def grid_dim_y(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].gridDimY = val + + @property + def grid_dim_z(self): + """int: """ + return self._ptr[0].gridDimZ + + @grid_dim_z.setter + def grid_dim_z(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].gridDimZ = val + + @property + def block_dim_x(self): + """int: """ + return self._ptr[0].blockDimX + + @block_dim_x.setter + def block_dim_x(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].blockDimX = val + + @property + def block_dim_y(self): + """int: """ + return self._ptr[0].blockDimY + + @block_dim_y.setter + def block_dim_y(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].blockDimY = val + + @property + def block_dim_z(self): + """int: """ + return self._ptr[0].blockDimZ + + @block_dim_z.setter + def block_dim_z(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].blockDimZ = val + + @property + def shared_mem_bytes(self): + """int: """ + return self._ptr[0].sharedMemBytes + + @shared_mem_bytes.setter + def shared_mem_bytes(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].sharedMemBytes = val + + @property + def kernel_params(self): + """int: """ + return (self._ptr[0].kernelParams) + + @kernel_params.setter + def kernel_params(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].kernelParams = val + + @property + def extra(self): + """int: """ + return (self._ptr[0].extra) + + @extra.setter + def extra(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].extra = val + + @property + def kern(self): + """int: """ + return (self._ptr[0].kern) + + @kern.setter + def kern(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].kern = val + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + self._ptr[0].ctx = val + + @staticmethod + def from_buffer(buffer): + """Create an KernelNodeParams_v3 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_KERNEL_NODE_PARAMS_v3), KernelNodeParams_v3) + + @staticmethod + def from_data(data): + """Create an KernelNodeParams_v3 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `kernel_node_params_v3_dtype` holding the data. + """ + return _cyb_from_data(data, "kernel_node_params_v3_dtype", kernel_node_params_v3_dtype, KernelNodeParams_v3) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an KernelNodeParams_v3 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef KernelNodeParams_v3 obj = KernelNodeParams_v3.__new__(KernelNodeParams_v3) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + if obj._ptr == NULL: + raise MemoryError("Error allocating KernelNodeParams_v3") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memset_node_params_v1_dtype_offsets(): + cdef CUDA_MEMSET_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['dst', 'pitch', 'value', 'element_size', 'width', 'height'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint32, _numpy.uint32, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.dst)) - (&pod), + (&(pod.pitch)) - (&pod), + (&(pod.value)) - (&pod), + (&(pod.elementSize)) - (&pod), + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMSET_NODE_PARAMS_v1), + }) + +memset_node_params_v1_dtype = _get_memset_node_params_v1_dtype_offsets() + +cdef class MemsetNodeParams_v1: + """Empty-initialize an instance of `CUDA_MEMSET_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_MEMSET_NODE_PARAMS_v1` + """ + cdef: + CUDA_MEMSET_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMSET_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemsetNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemsetNodeParams_v1 other_ + if not isinstance(other, MemsetNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMSET_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def dst(self): + """int: """ + return (self._ptr[0].dst) + + @dst.setter + def dst(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].dst = val + + @property + def pitch(self): + """int: """ + return self._ptr[0].pitch + + @pitch.setter + def pitch(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].pitch = val + + @property + def value(self): + """int: """ + return self._ptr[0].value + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].value = val + + @property + def element_size(self): + """int: """ + return self._ptr[0].elementSize + + @element_size.setter + def element_size(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].elementSize = val + + @property + def width(self): + """int: """ + return self._ptr[0].width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].width = val + + @property + def height(self): + """int: """ + return self._ptr[0].height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v1 instance is read-only") + self._ptr[0].height = val + + @staticmethod + def from_buffer(buffer): + """Create an MemsetNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMSET_NODE_PARAMS_v1), MemsetNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an MemsetNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memset_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "memset_node_params_v1_dtype", memset_node_params_v1_dtype, MemsetNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemsetNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemsetNodeParams_v1 obj = MemsetNodeParams_v1.__new__(MemsetNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memset_node_params_v2_dtype_offsets(): + cdef CUDA_MEMSET_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['dst', 'pitch', 'value', 'element_size', 'width', 'height', 'ctx'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint32, _numpy.uint32, _numpy.uint64, _numpy.uint64, _numpy.intp], + 'offsets': [ + (&(pod.dst)) - (&pod), + (&(pod.pitch)) - (&pod), + (&(pod.value)) - (&pod), + (&(pod.elementSize)) - (&pod), + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + (&(pod.ctx)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMSET_NODE_PARAMS_v2), + }) + +memset_node_params_v2_dtype = _get_memset_node_params_v2_dtype_offsets() + +cdef class MemsetNodeParams_v2: + """Empty-initialize an instance of `CUDA_MEMSET_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_MEMSET_NODE_PARAMS_v2` + """ + cdef: + CUDA_MEMSET_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMSET_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemsetNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemsetNodeParams_v2 other_ + if not isinstance(other, MemsetNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMSET_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def dst(self): + """int: """ + return (self._ptr[0].dst) + + @dst.setter + def dst(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].dst = val + + @property + def pitch(self): + """int: """ + return self._ptr[0].pitch + + @pitch.setter + def pitch(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].pitch = val + + @property + def value(self): + """int: """ + return self._ptr[0].value + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].value = val + + @property + def element_size(self): + """int: """ + return self._ptr[0].elementSize + + @element_size.setter + def element_size(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].elementSize = val + + @property + def width(self): + """int: """ + return self._ptr[0].width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].width = val + + @property + def height(self): + """int: """ + return self._ptr[0].height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].height = val + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This MemsetNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @staticmethod + def from_buffer(buffer): + """Create an MemsetNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMSET_NODE_PARAMS_v2), MemsetNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an MemsetNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memset_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "memset_node_params_v2_dtype", memset_node_params_v2_dtype, MemsetNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemsetNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemsetNodeParams_v2 obj = MemsetNodeParams_v2.__new__(MemsetNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemsetNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_host_node_params_v1_dtype_offsets(): + cdef CUDA_HOST_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['fn', 'user_data'], + 'formats': [_numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.fn)) - (&pod), + (&(pod.userData)) - (&pod), + ], + 'itemsize': sizeof(CUDA_HOST_NODE_PARAMS_v1), + }) + +host_node_params_v1_dtype = _get_host_node_params_v1_dtype_offsets() + +cdef class HostNodeParams_v1: + """Empty-initialize an instance of `CUDA_HOST_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_HOST_NODE_PARAMS_v1` + """ + cdef: + CUDA_HOST_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_HOST_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_HOST_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.HostNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef HostNodeParams_v1 other_ + if not isinstance(other, HostNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_HOST_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_HOST_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_HOST_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_HOST_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def fn(self): + """int: """ + return (self._ptr[0].fn) + + @fn.setter + def fn(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v1 instance is read-only") + self._ptr[0].fn = val + + @property + def user_data(self): + """int: """ + return (self._ptr[0].userData) + + @user_data.setter + def user_data(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v1 instance is read-only") + self._ptr[0].userData = val + + @staticmethod + def from_buffer(buffer): + """Create an HostNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_HOST_NODE_PARAMS_v1), HostNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an HostNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `host_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "host_node_params_v1_dtype", host_node_params_v1_dtype, HostNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an HostNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef HostNodeParams_v1 obj = HostNodeParams_v1.__new__(HostNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_HOST_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_HOST_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_host_node_params_v2_dtype_offsets(): + cdef CUDA_HOST_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['fn', 'user_data', 'sync_mode'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.fn)) - (&pod), + (&(pod.userData)) - (&pod), + (&(pod.syncMode)) - (&pod), + ], + 'itemsize': sizeof(CUDA_HOST_NODE_PARAMS_v2), + }) + +host_node_params_v2_dtype = _get_host_node_params_v2_dtype_offsets() + +cdef class HostNodeParams_v2: + """Empty-initialize an instance of `CUDA_HOST_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_HOST_NODE_PARAMS_v2` + """ + cdef: + CUDA_HOST_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_HOST_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_HOST_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.HostNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef HostNodeParams_v2 other_ + if not isinstance(other, HostNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_HOST_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_HOST_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_HOST_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_HOST_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def fn(self): + """int: """ + return (self._ptr[0].fn) + + @fn.setter + def fn(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + self._ptr[0].fn = val + + @property + def user_data(self): + """int: """ + return (self._ptr[0].userData) + + @user_data.setter + def user_data(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + self._ptr[0].userData = val + + @property + def sync_mode(self): + """int: """ + return self._ptr[0].syncMode + + @sync_mode.setter + def sync_mode(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + self._ptr[0].syncMode = val + + @staticmethod + def from_buffer(buffer): + """Create an HostNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_HOST_NODE_PARAMS_v2), HostNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an HostNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `host_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "host_node_params_v2_dtype", host_node_params_v2_dtype, HostNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an HostNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef HostNodeParams_v2 obj = HostNodeParams_v2.__new__(HostNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_HOST_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating HostNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_HOST_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_conditional_node_params_dtype_offsets(): + cdef CUDA_CONDITIONAL_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['handle', 'type', 'size_', 'ph_graph_out', 'ctx'], + 'formats': [_numpy.uint64, _numpy.int32, _numpy.uint32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.handle)) - (&pod), + (&(pod.type)) - (&pod), + (&(pod.size)) - (&pod), + (&(pod.phGraph_out)) - (&pod), + (&(pod.ctx)) - (&pod), + ], + 'itemsize': sizeof(CUDA_CONDITIONAL_NODE_PARAMS), + }) + +conditional_node_params_dtype = _get_conditional_node_params_dtype_offsets() + +cdef class ConditionalNodeParams: + """Empty-initialize an instance of `CUDA_CONDITIONAL_NODE_PARAMS`. + + + .. seealso:: `CUDA_CONDITIONAL_NODE_PARAMS` + """ + cdef: + CUDA_CONDITIONAL_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating ConditionalNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_CONDITIONAL_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ConditionalNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ConditionalNodeParams other_ + if not isinstance(other, ConditionalNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_CONDITIONAL_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating ConditionalNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def handle(self): + """int: Conditional node handle. Handles must be created in advance of creating the node using cuGraphConditionalHandleCreate.""" + return (self._ptr[0].handle) + + @handle.setter + def handle(self, val): + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + self._ptr[0].handle = val + + @property + def type(self): + """int: Type of conditional node.""" + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + self._ptr[0].type = val + + @property + def size_(self): + """int: Size of graph output array. Allowed values are 1 for CU_GRAPH_COND_TYPE_WHILE, 1 or 2 for CU_GRAPH_COND_TYPE_IF, or any value greater than zero for CU_GRAPH_COND_TYPE_SWITCH.""" + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + self._ptr[0].size = val + + @property + def ph_graph_out(self): + """int: CUDA-owned array populated with conditional node child graphs during creation of the node. Valid for the lifetime of the conditional node. The contents of the graph(s) are subject to the following constraints: - Allowed node types are kernel nodes, empty nodes, child graphs, memsets, memcopies, and conditionals. This applies recursively to child graphs and conditional bodies. - All kernels, including kernels in nested conditionals or child graphs at any level, must belong to the same CUDA context. These graphs may be populated using graph node creation APIs or cuStreamBeginCaptureToGraph. CU_GRAPH_COND_TYPE_IF: phGraph_out[0] is executed when the condition is non-zero. If ``size`` == 2, phGraph_out[1] will be executed when the condition is zero. CU_GRAPH_COND_TYPE_WHILE: phGraph_out[0] is executed as long as the condition is non-zero. CU_GRAPH_COND_TYPE_SWITCH: phGraph_out[n] is executed when the condition is equal to n. If the condition >= ``size``, no body graph is executed.""" + return (self._ptr[0].phGraph_out) + + @ph_graph_out.setter + def ph_graph_out(self, val): + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + self._ptr[0].phGraph_out = val + + @property + def ctx(self): + """int: Context on which to run the node. Must match context used to create the handle and all body nodes.""" + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + self._ptr[0].ctx = val + + @staticmethod + def from_buffer(buffer): + """Create an ConditionalNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_CONDITIONAL_NODE_PARAMS), ConditionalNodeParams) + + @staticmethod + def from_data(data): + """Create an ConditionalNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `conditional_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "conditional_node_params_dtype", conditional_node_params_dtype, ConditionalNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ConditionalNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ConditionalNodeParams obj = ConditionalNodeParams.__new__(ConditionalNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ConditionalNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_graph_edge_data_dtype_offsets(): + cdef CUgraphEdgeData pod + return _numpy.dtype({ + 'names': ['from_port', 'to_port', 'type', 'reserved'], + 'formats': [_numpy.uint8, _numpy.uint8, _numpy.uint8, (_numpy.uint8, 5)], + 'offsets': [ + (&(pod.from_port)) - (&pod), + (&(pod.to_port)) - (&pod), + (&(pod.type)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUgraphEdgeData), + }) + +graph_edge_data_dtype = _get_graph_edge_data_dtype_offsets() + +cdef class GraphEdgeData: + """Empty-initialize an array of `CUgraphEdgeData`. + The resulting object is of length `size` and of dtype `graph_edge_data_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUgraphEdgeData` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=graph_edge_data_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUgraphEdgeData), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUgraphEdgeData) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.GraphEdgeData_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.GraphEdgeData object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, GraphEdgeData)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def from_port(self): + """Union[~_numpy.uint8, int]: """ + if self._data.size == 1: + return int(self._data.from_port[0]) + return self._data.from_port + + @from_port.setter + def from_port(self, val): + self._data.from_port = val + + @property + def to_port(self): + """Union[~_numpy.uint8, int]: """ + if self._data.size == 1: + return int(self._data.to_port[0]) + return self._data.to_port + + @to_port.setter + def to_port(self, val): + self._data.to_port = val + + @property + def type(self): + """Union[~_numpy.uint8, int]: """ + if self._data.size == 1: + return int(self._data.type[0]) + return self._data.type + + @type.setter + def type(self, val): + self._data.type = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return GraphEdgeData.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == graph_edge_data_dtype: + return GraphEdgeData.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an GraphEdgeData instance with the memory from the given buffer.""" + return GraphEdgeData.from_data(_numpy.frombuffer(buffer, dtype=graph_edge_data_dtype)) + + @staticmethod + def from_data(data): + """Create an GraphEdgeData instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `graph_edge_data_dtype` holding the data. + """ + cdef GraphEdgeData obj = GraphEdgeData.__new__(GraphEdgeData) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != graph_edge_data_dtype: + raise ValueError("data array must be of dtype graph_edge_data_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an GraphEdgeData instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef GraphEdgeData obj = GraphEdgeData.__new__(GraphEdgeData) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUgraphEdgeData) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=graph_edge_data_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_graph_instantiate_params_dtype_offsets(): + cdef CUDA_GRAPH_INSTANTIATE_PARAMS pod + return _numpy.dtype({ + 'names': ['flags_', 'h_upload_stream', 'h_err_node_out', 'result_out'], + 'formats': [_numpy.uint64, _numpy.intp, _numpy.intp, _numpy.int32], + 'offsets': [ + (&(pod.flags)) - (&pod), + (&(pod.hUploadStream)) - (&pod), + (&(pod.hErrNode_out)) - (&pod), + (&(pod.result_out)) - (&pod), + ], + 'itemsize': sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS), + }) + +graph_instantiate_params_dtype = _get_graph_instantiate_params_dtype_offsets() + +cdef class GraphInstantiateParams: + """Empty-initialize an instance of `CUDA_GRAPH_INSTANTIATE_PARAMS`. + + + .. seealso:: `CUDA_GRAPH_INSTANTIATE_PARAMS` + """ + cdef: + CUDA_GRAPH_INSTANTIATE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphInstantiateParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_GRAPH_INSTANTIATE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.GraphInstantiateParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef GraphInstantiateParams other_ + if not isinstance(other, GraphInstantiateParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphInstantiateParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def flags_(self): + """int: """ + return (self._ptr[0].flags) + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This GraphInstantiateParams instance is read-only") + self._ptr[0].flags = val + + @property + def h_upload_stream(self): + """int: """ + return (self._ptr[0].hUploadStream) + + @h_upload_stream.setter + def h_upload_stream(self, val): + if self._readonly: + raise ValueError("This GraphInstantiateParams instance is read-only") + self._ptr[0].hUploadStream = val + + @property + def h_err_node_out(self): + """int: """ + return (self._ptr[0].hErrNode_out) + + @h_err_node_out.setter + def h_err_node_out(self, val): + if self._readonly: + raise ValueError("This GraphInstantiateParams instance is read-only") + self._ptr[0].hErrNode_out = val + + @property + def result_out(self): + """int: """ + return (self._ptr[0].result_out) + + @result_out.setter + def result_out(self, val): + if self._readonly: + raise ValueError("This GraphInstantiateParams instance is read-only") + self._ptr[0].result_out = val + + @staticmethod + def from_buffer(buffer): + """Create an GraphInstantiateParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS), GraphInstantiateParams) + + @staticmethod + def from_data(data): + """Create an GraphInstantiateParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `graph_instantiate_params_dtype` holding the data. + """ + return _cyb_from_data(data, "graph_instantiate_params_dtype", graph_instantiate_params_dtype, GraphInstantiateParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an GraphInstantiateParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef GraphInstantiateParams obj = GraphInstantiateParams.__new__(GraphInstantiateParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating GraphInstantiateParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_launch_mem_sync_domain_map_dtype_offsets(): + cdef CUlaunchMemSyncDomainMap pod + return _numpy.dtype({ + 'names': ['default_', 'remote'], + 'formats': [_numpy.uint8, _numpy.uint8], + 'offsets': [ + (&(pod.default_)) - (&pod), + (&(pod.remote)) - (&pod), + ], + 'itemsize': sizeof(CUlaunchMemSyncDomainMap), + }) + +launch_mem_sync_domain_map_dtype = _get_launch_mem_sync_domain_map_dtype_offsets() + +cdef class LaunchMemSyncDomainMap: + """Empty-initialize an instance of `CUlaunchMemSyncDomainMap`. + + + .. seealso:: `CUlaunchMemSyncDomainMap` + """ + cdef: + CUlaunchMemSyncDomainMap *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlaunchMemSyncDomainMap)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchMemSyncDomainMap") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUlaunchMemSyncDomainMap *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LaunchMemSyncDomainMap object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef LaunchMemSyncDomainMap other_ + if not isinstance(other, LaunchMemSyncDomainMap): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlaunchMemSyncDomainMap)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlaunchMemSyncDomainMap), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUlaunchMemSyncDomainMap)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchMemSyncDomainMap") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUlaunchMemSyncDomainMap)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def default_(self): + """int: """ + return self._ptr[0].default_ + + @default_.setter + def default_(self, val): + if self._readonly: + raise ValueError("This LaunchMemSyncDomainMap instance is read-only") + self._ptr[0].default_ = val + + @property + def remote(self): + """int: """ + return self._ptr[0].remote + + @remote.setter + def remote(self, val): + if self._readonly: + raise ValueError("This LaunchMemSyncDomainMap instance is read-only") + self._ptr[0].remote = val + + @staticmethod + def from_buffer(buffer): + """Create an LaunchMemSyncDomainMap instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlaunchMemSyncDomainMap), LaunchMemSyncDomainMap) + + @staticmethod + def from_data(data): + """Create an LaunchMemSyncDomainMap instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `launch_mem_sync_domain_map_dtype` holding the data. + """ + return _cyb_from_data(data, "launch_mem_sync_domain_map_dtype", launch_mem_sync_domain_map_dtype, LaunchMemSyncDomainMap) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LaunchMemSyncDomainMap instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef LaunchMemSyncDomainMap obj = LaunchMemSyncDomainMap.__new__(LaunchMemSyncDomainMap) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUlaunchMemSyncDomainMap)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LaunchMemSyncDomainMap") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUlaunchMemSyncDomainMap)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod4_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod4 pod + return _numpy.dtype({ + 'names': ['x', 'y', 'z'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.x)) - (&pod), + (&(pod.y)) - (&pod), + (&(pod.z)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod4), + }) + +_py_anon_pod4_dtype = _get__py_anon_pod4_dtype_offsets() + +cdef class _py_anon_pod4: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod4`. + + + .. seealso:: `cuda_bindings_driver__anon_pod4` + """ + cdef: + cuda_bindings_driver__anon_pod4 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod4)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod4") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod4 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod4 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod4 other_ + if not isinstance(other, _py_anon_pod4): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod4)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod4), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod4)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod4") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod4)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def x(self): + """int: """ + return self._ptr[0].x + + @x.setter + def x(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod4 instance is read-only") + self._ptr[0].x = val + + @property + def y(self): + """int: """ + return self._ptr[0].y + + @y.setter + def y(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod4 instance is read-only") + self._ptr[0].y = val + + @property + def z(self): + """int: """ + return self._ptr[0].z + + @z.setter + def z(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod4 instance is read-only") + self._ptr[0].z = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod4 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod4), _py_anon_pod4) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod4 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod4_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod4_dtype", _py_anon_pod4_dtype, _py_anon_pod4) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod4 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod4 obj = _py_anon_pod4.__new__(_py_anon_pod4) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod4)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod4") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod4)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod5_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod5 pod + return _numpy.dtype({ + 'names': ['event', 'flags_', 'trigger_at_block_start'], + 'formats': [_numpy.intp, _numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.event)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.triggerAtBlockStart)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod5), + }) + +_py_anon_pod5_dtype = _get__py_anon_pod5_dtype_offsets() + +cdef class _py_anon_pod5: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod5`. + + + .. seealso:: `cuda_bindings_driver__anon_pod5` + """ + cdef: + cuda_bindings_driver__anon_pod5 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod5)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod5") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod5 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod5 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod5 other_ + if not isinstance(other, _py_anon_pod5): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod5)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod5), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod5)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod5") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod5)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def event(self): + """int: """ + return (self._ptr[0].event) + + @event.setter + def event(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod5 instance is read-only") + self._ptr[0].event = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod5 instance is read-only") + self._ptr[0].flags = val + + @property + def trigger_at_block_start(self): + """int: """ + return self._ptr[0].triggerAtBlockStart + + @trigger_at_block_start.setter + def trigger_at_block_start(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod5 instance is read-only") + self._ptr[0].triggerAtBlockStart = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod5 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod5), _py_anon_pod5) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod5 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod5_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod5_dtype", _py_anon_pod5_dtype, _py_anon_pod5) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod5 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod5 obj = _py_anon_pod5.__new__(_py_anon_pod5) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod5)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod5") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod5)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod6_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod6 pod + return _numpy.dtype({ + 'names': ['event', 'flags_'], + 'formats': [_numpy.intp, _numpy.int32], + 'offsets': [ + (&(pod.event)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod6), + }) + +_py_anon_pod6_dtype = _get__py_anon_pod6_dtype_offsets() + +cdef class _py_anon_pod6: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod6`. + + + .. seealso:: `cuda_bindings_driver__anon_pod6` + """ + cdef: + cuda_bindings_driver__anon_pod6 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod6)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod6") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod6 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod6 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod6 other_ + if not isinstance(other, _py_anon_pod6): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod6)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod6), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod6)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod6") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod6)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def event(self): + """int: """ + return (self._ptr[0].event) + + @event.setter + def event(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod6 instance is read-only") + self._ptr[0].event = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod6 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod6 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod6), _py_anon_pod6) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod6 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod6_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod6_dtype", _py_anon_pod6_dtype, _py_anon_pod6) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod6 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod6 obj = _py_anon_pod6.__new__(_py_anon_pod6) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod6)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod6") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod6)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod7_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod7 pod + return _numpy.dtype({ + 'names': ['x', 'y', 'z'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.x)) - (&pod), + (&(pod.y)) - (&pod), + (&(pod.z)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod7), + }) + +_py_anon_pod7_dtype = _get__py_anon_pod7_dtype_offsets() + +cdef class _py_anon_pod7: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod7`. + + + .. seealso:: `cuda_bindings_driver__anon_pod7` + """ + cdef: + cuda_bindings_driver__anon_pod7 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod7)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod7") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod7 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod7 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod7 other_ + if not isinstance(other, _py_anon_pod7): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod7)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod7), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod7)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod7") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod7)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def x(self): + """int: """ + return self._ptr[0].x + + @x.setter + def x(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod7 instance is read-only") + self._ptr[0].x = val + + @property + def y(self): + """int: """ + return self._ptr[0].y + + @y.setter + def y(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod7 instance is read-only") + self._ptr[0].y = val + + @property + def z(self): + """int: """ + return self._ptr[0].z + + @z.setter + def z(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod7 instance is read-only") + self._ptr[0].z = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod7 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod7), _py_anon_pod7) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod7 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod7_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod7_dtype", _py_anon_pod7_dtype, _py_anon_pod7) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod7 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod7 obj = _py_anon_pod7.__new__(_py_anon_pod7) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod7)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod7") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod7)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod8_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod8 pod + return _numpy.dtype({ + 'names': ['device_updatable', 'dev_node'], + 'formats': [_numpy.int32, _numpy.intp], + 'offsets': [ + (&(pod.deviceUpdatable)) - (&pod), + (&(pod.devNode)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod8), + }) + +_py_anon_pod8_dtype = _get__py_anon_pod8_dtype_offsets() + +cdef class _py_anon_pod8: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod8`. + + + .. seealso:: `cuda_bindings_driver__anon_pod8` + """ + cdef: + cuda_bindings_driver__anon_pod8 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod8)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod8") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod8 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod8 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod8 other_ + if not isinstance(other, _py_anon_pod8): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod8)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod8), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod8)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod8") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod8)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def device_updatable(self): + """int: """ + return self._ptr[0].deviceUpdatable + + @device_updatable.setter + def device_updatable(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod8 instance is read-only") + self._ptr[0].deviceUpdatable = val + + @property + def dev_node(self): + """int: """ + return (self._ptr[0].devNode) + + @dev_node.setter + def dev_node(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod8 instance is read-only") + self._ptr[0].devNode = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod8 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod8), _py_anon_pod8) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod8 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod8_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod8_dtype", _py_anon_pod8_dtype, _py_anon_pod8) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod8 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod8 obj = _py_anon_pod8.__new__(_py_anon_pod8) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod8)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod8") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod8)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_exec_affinity_sm_count_v1_dtype_offsets(): + cdef CUexecAffinitySmCount_v1 pod + return _numpy.dtype({ + 'names': ['val'], + 'formats': [_numpy.uint32], + 'offsets': [ + (&(pod.val)) - (&pod), + ], + 'itemsize': sizeof(CUexecAffinitySmCount_v1), + }) + +exec_affinity_sm_count_v1_dtype = _get_exec_affinity_sm_count_v1_dtype_offsets() + +cdef class ExecAffinitySmCount_v1: + """Empty-initialize an instance of `CUexecAffinitySmCount_v1`. + + + .. seealso:: `CUexecAffinitySmCount_v1` + """ + cdef: + CUexecAffinitySmCount_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUexecAffinitySmCount_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExecAffinitySmCount_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUexecAffinitySmCount_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExecAffinitySmCount_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExecAffinitySmCount_v1 other_ + if not isinstance(other, ExecAffinitySmCount_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUexecAffinitySmCount_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUexecAffinitySmCount_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUexecAffinitySmCount_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExecAffinitySmCount_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUexecAffinitySmCount_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def val(self): + """int: """ + return self._ptr[0].val + + @val.setter + def val(self, val): + if self._readonly: + raise ValueError("This ExecAffinitySmCount_v1 instance is read-only") + self._ptr[0].val = val + + @staticmethod + def from_buffer(buffer): + """Create an ExecAffinitySmCount_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUexecAffinitySmCount_v1), ExecAffinitySmCount_v1) + + @staticmethod + def from_data(data): + """Create an ExecAffinitySmCount_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `exec_affinity_sm_count_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "exec_affinity_sm_count_v1_dtype", exec_affinity_sm_count_v1_dtype, ExecAffinitySmCount_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExecAffinitySmCount_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExecAffinitySmCount_v1 obj = ExecAffinitySmCount_v1.__new__(ExecAffinitySmCount_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUexecAffinitySmCount_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExecAffinitySmCount_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUexecAffinitySmCount_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod9_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod9 pod + return _numpy.dtype({ + 'names': ['sm_count'], + 'formats': [exec_affinity_sm_count_v1_dtype], + 'offsets': [ + (&(pod.smCount)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod9), + }) + +_py_anon_pod9_dtype = _get__py_anon_pod9_dtype_offsets() + +cdef class _py_anon_pod9: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod9`. + + + .. seealso:: `cuda_bindings_driver__anon_pod9` + """ + cdef: + cuda_bindings_driver__anon_pod9 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod9)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod9") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod9 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod9 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod9 other_ + if not isinstance(other, _py_anon_pod9): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod9)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod9), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod9)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod9") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod9)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def sm_count(self): + """ExecAffinitySmCount_v1: """ + return ExecAffinitySmCount_v1.from_ptr( + &(self._ptr[0].smCount), + readonly=self._readonly, + owner=self, + ) + + @sm_count.setter + def sm_count(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod9 instance is read-only") + cdef ExecAffinitySmCount_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].smCount), (val_._get_ptr()), sizeof(CUexecAffinitySmCount) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod9 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod9), _py_anon_pod9) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod9 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod9_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod9_dtype", _py_anon_pod9_dtype, _py_anon_pod9) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod9 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod9 obj = _py_anon_pod9.__new__(_py_anon_pod9) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod9)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod9") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod9)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ctx_cig_param_dtype_offsets(): + cdef CUctxCigParam pod + return _numpy.dtype({ + 'names': ['shared_data_type', 'shared_data'], + 'formats': [_numpy.int32, _numpy.intp], + 'offsets': [ + (&(pod.sharedDataType)) - (&pod), + (&(pod.sharedData)) - (&pod), + ], + 'itemsize': sizeof(CUctxCigParam), + }) + +ctx_cig_param_dtype = _get_ctx_cig_param_dtype_offsets() + +cdef class CtxCigParam: + """Empty-initialize an instance of `CUctxCigParam`. + + + .. seealso:: `CUctxCigParam` + """ + cdef: + CUctxCigParam *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUctxCigParam)) + if self._ptr == NULL: + raise MemoryError("Error allocating CtxCigParam") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUctxCigParam *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CtxCigParam object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CtxCigParam other_ + if not isinstance(other, CtxCigParam): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUctxCigParam)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUctxCigParam), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUctxCigParam)) + if self._ptr == NULL: + raise MemoryError("Error allocating CtxCigParam") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUctxCigParam)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def shared_data_type(self): + """int: """ + return (self._ptr[0].sharedDataType) + + @shared_data_type.setter + def shared_data_type(self, val): + if self._readonly: + raise ValueError("This CtxCigParam instance is read-only") + self._ptr[0].sharedDataType = val + + @property + def shared_data(self): + """int: """ + return (self._ptr[0].sharedData) + + @shared_data.setter + def shared_data(self, val): + if self._readonly: + raise ValueError("This CtxCigParam instance is read-only") + self._ptr[0].sharedData = val + + @staticmethod + def from_buffer(buffer): + """Create an CtxCigParam instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUctxCigParam), CtxCigParam) + + @staticmethod + def from_data(data): + """Create an CtxCigParam instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ctx_cig_param_dtype` holding the data. + """ + return _cyb_from_data(data, "ctx_cig_param_dtype", ctx_cig_param_dtype, CtxCigParam) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CtxCigParam instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CtxCigParam obj = CtxCigParam.__new__(CtxCigParam) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUctxCigParam)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CtxCigParam") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUctxCigParam)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_library_host_universal_function_and_data_table_dtype_offsets(): + cdef CUlibraryHostUniversalFunctionAndDataTable pod + return _numpy.dtype({ + 'names': ['function_table', 'function_window_size', 'data_table', 'data_window_size'], + 'formats': [_numpy.intp, _numpy.uint64, _numpy.intp, _numpy.uint64], + 'offsets': [ + (&(pod.functionTable)) - (&pod), + (&(pod.functionWindowSize)) - (&pod), + (&(pod.dataTable)) - (&pod), + (&(pod.dataWindowSize)) - (&pod), + ], + 'itemsize': sizeof(CUlibraryHostUniversalFunctionAndDataTable), + }) + +library_host_universal_function_and_data_table_dtype = _get_library_host_universal_function_and_data_table_dtype_offsets() + +cdef class LibraryHostUniversalFunctionAndDataTable: + """Empty-initialize an instance of `CUlibraryHostUniversalFunctionAndDataTable`. + + + .. seealso:: `CUlibraryHostUniversalFunctionAndDataTable` + """ + cdef: + CUlibraryHostUniversalFunctionAndDataTable *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + if self._ptr == NULL: + raise MemoryError("Error allocating LibraryHostUniversalFunctionAndDataTable") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUlibraryHostUniversalFunctionAndDataTable *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LibraryHostUniversalFunctionAndDataTable object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef LibraryHostUniversalFunctionAndDataTable other_ + if not isinstance(other, LibraryHostUniversalFunctionAndDataTable): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlibraryHostUniversalFunctionAndDataTable)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlibraryHostUniversalFunctionAndDataTable), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + if self._ptr == NULL: + raise MemoryError("Error allocating LibraryHostUniversalFunctionAndDataTable") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def function_table(self): + """int: """ + return (self._ptr[0].functionTable) + + @function_table.setter + def function_table(self, val): + if self._readonly: + raise ValueError("This LibraryHostUniversalFunctionAndDataTable instance is read-only") + self._ptr[0].functionTable = val + + @property + def function_window_size(self): + """int: """ + return self._ptr[0].functionWindowSize + + @function_window_size.setter + def function_window_size(self, val): + if self._readonly: + raise ValueError("This LibraryHostUniversalFunctionAndDataTable instance is read-only") + self._ptr[0].functionWindowSize = val + + @property + def data_table(self): + """int: """ + return (self._ptr[0].dataTable) + + @data_table.setter + def data_table(self, val): + if self._readonly: + raise ValueError("This LibraryHostUniversalFunctionAndDataTable instance is read-only") + self._ptr[0].dataTable = val + + @property + def data_window_size(self): + """int: """ + return self._ptr[0].dataWindowSize + + @data_window_size.setter + def data_window_size(self, val): + if self._readonly: + raise ValueError("This LibraryHostUniversalFunctionAndDataTable instance is read-only") + self._ptr[0].dataWindowSize = val + + @staticmethod + def from_buffer(buffer): + """Create an LibraryHostUniversalFunctionAndDataTable instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlibraryHostUniversalFunctionAndDataTable), LibraryHostUniversalFunctionAndDataTable) + + @staticmethod + def from_data(data): + """Create an LibraryHostUniversalFunctionAndDataTable instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `library_host_universal_function_and_data_table_dtype` holding the data. + """ + return _cyb_from_data(data, "library_host_universal_function_and_data_table_dtype", library_host_universal_function_and_data_table_dtype, LibraryHostUniversalFunctionAndDataTable) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LibraryHostUniversalFunctionAndDataTable instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef LibraryHostUniversalFunctionAndDataTable obj = LibraryHostUniversalFunctionAndDataTable.__new__(LibraryHostUniversalFunctionAndDataTable) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LibraryHostUniversalFunctionAndDataTable") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memcpy2d_v2_dtype_offsets(): + cdef CUDA_MEMCPY2D_v2 pod + return _numpy.dtype({ + 'names': ['src_x_in_bytes', 'src_y', 'src_memory_type', 'src_host', 'src_device', 'src_array', 'src_pitch', 'dst_x_in_bytes', 'dst_y', 'dst_memory_type', 'dst_host', 'dst_device', 'dst_array', 'dst_pitch', 'width_in_bytes', 'height'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.srcXInBytes)) - (&pod), + (&(pod.srcY)) - (&pod), + (&(pod.srcMemoryType)) - (&pod), + (&(pod.srcHost)) - (&pod), + (&(pod.srcDevice)) - (&pod), + (&(pod.srcArray)) - (&pod), + (&(pod.srcPitch)) - (&pod), + (&(pod.dstXInBytes)) - (&pod), + (&(pod.dstY)) - (&pod), + (&(pod.dstMemoryType)) - (&pod), + (&(pod.dstHost)) - (&pod), + (&(pod.dstDevice)) - (&pod), + (&(pod.dstArray)) - (&pod), + (&(pod.dstPitch)) - (&pod), + (&(pod.WidthInBytes)) - (&pod), + (&(pod.Height)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY2D_v2), + }) + +memcpy2d_v2_dtype = _get_memcpy2d_v2_dtype_offsets() + +cdef class Memcpy2d_v2: + """Empty-initialize an instance of `CUDA_MEMCPY2D_v2`. + + + .. seealso:: `CUDA_MEMCPY2D_v2` + """ + cdef: + CUDA_MEMCPY2D_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMCPY2D_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy2d_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMCPY2D_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Memcpy2d_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Memcpy2d_v2 other_ + if not isinstance(other, Memcpy2d_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMCPY2D_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMCPY2D_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY2D_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy2d_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMCPY2D_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def src_x_in_bytes(self): + """int: """ + return self._ptr[0].srcXInBytes + + @src_x_in_bytes.setter + def src_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcXInBytes = val + + @property + def src_y(self): + """int: """ + return self._ptr[0].srcY + + @src_y.setter + def src_y(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcY = val + + @property + def src_memory_type(self): + """int: """ + return (self._ptr[0].srcMemoryType) + + @src_memory_type.setter + def src_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcMemoryType = val + + @property + def src_host(self): + """int: """ + return (self._ptr[0].srcHost) + + @src_host.setter + def src_host(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcHost = val + + @property + def src_device(self): + """int: """ + return (self._ptr[0].srcDevice) + + @src_device.setter + def src_device(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcDevice = val + + @property + def src_array(self): + """int: """ + return (self._ptr[0].srcArray) + + @src_array.setter + def src_array(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcArray = val + + @property + def src_pitch(self): + """int: """ + return self._ptr[0].srcPitch + + @src_pitch.setter + def src_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].srcPitch = val + + @property + def dst_x_in_bytes(self): + """int: """ + return self._ptr[0].dstXInBytes + + @dst_x_in_bytes.setter + def dst_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstXInBytes = val + + @property + def dst_y(self): + """int: """ + return self._ptr[0].dstY + + @dst_y.setter + def dst_y(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstY = val + + @property + def dst_memory_type(self): + """int: """ + return (self._ptr[0].dstMemoryType) + + @dst_memory_type.setter + def dst_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstMemoryType = val + + @property + def dst_host(self): + """int: """ + return (self._ptr[0].dstHost) + + @dst_host.setter + def dst_host(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstHost = val + + @property + def dst_device(self): + """int: """ + return (self._ptr[0].dstDevice) + + @dst_device.setter + def dst_device(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstDevice = val + + @property + def dst_array(self): + """int: """ + return (self._ptr[0].dstArray) + + @dst_array.setter + def dst_array(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstArray = val + + @property + def dst_pitch(self): + """int: """ + return self._ptr[0].dstPitch + + @dst_pitch.setter + def dst_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].dstPitch = val + + @property + def width_in_bytes(self): + """int: """ + return self._ptr[0].WidthInBytes + + @width_in_bytes.setter + def width_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].WidthInBytes = val + + @property + def height(self): + """int: """ + return self._ptr[0].Height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This Memcpy2d_v2 instance is read-only") + self._ptr[0].Height = val + + @staticmethod + def from_buffer(buffer): + """Create an Memcpy2d_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMCPY2D_v2), Memcpy2d_v2) + + @staticmethod + def from_data(data): + """Create an Memcpy2d_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memcpy2d_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "memcpy2d_v2_dtype", memcpy2d_v2_dtype, Memcpy2d_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Memcpy2d_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Memcpy2d_v2 obj = Memcpy2d_v2.__new__(Memcpy2d_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY2D_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Memcpy2d_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMCPY2D_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memcpy3d_v2_dtype_offsets(): + cdef CUDA_MEMCPY3D_v2 pod + return _numpy.dtype({ + 'names': ['src_x_in_bytes', 'src_y', 'src_z', 'src_lod', 'src_memory_type', 'src_host', 'src_device', 'src_array', 'reserved0', 'src_pitch', 'src_height', 'dst_x_in_bytes', 'dst_y', 'dst_z', 'dst_lod', 'dst_memory_type', 'dst_host', 'dst_device', 'dst_array', 'reserved1', 'dst_pitch', 'dst_height', 'width_in_bytes', 'height', 'depth'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.srcXInBytes)) - (&pod), + (&(pod.srcY)) - (&pod), + (&(pod.srcZ)) - (&pod), + (&(pod.srcLOD)) - (&pod), + (&(pod.srcMemoryType)) - (&pod), + (&(pod.srcHost)) - (&pod), + (&(pod.srcDevice)) - (&pod), + (&(pod.srcArray)) - (&pod), + (&(pod.reserved0)) - (&pod), + (&(pod.srcPitch)) - (&pod), + (&(pod.srcHeight)) - (&pod), + (&(pod.dstXInBytes)) - (&pod), + (&(pod.dstY)) - (&pod), + (&(pod.dstZ)) - (&pod), + (&(pod.dstLOD)) - (&pod), + (&(pod.dstMemoryType)) - (&pod), + (&(pod.dstHost)) - (&pod), + (&(pod.dstDevice)) - (&pod), + (&(pod.dstArray)) - (&pod), + (&(pod.reserved1)) - (&pod), + (&(pod.dstPitch)) - (&pod), + (&(pod.dstHeight)) - (&pod), + (&(pod.WidthInBytes)) - (&pod), + (&(pod.Height)) - (&pod), + (&(pod.Depth)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY3D_v2), + }) + +memcpy3d_v2_dtype = _get_memcpy3d_v2_dtype_offsets() + +cdef class Memcpy3d_v2: + """Empty-initialize an instance of `CUDA_MEMCPY3D_v2`. + + + .. seealso:: `CUDA_MEMCPY3D_v2` + """ + cdef: + CUDA_MEMCPY3D_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMCPY3D_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy3d_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMCPY3D_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Memcpy3d_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Memcpy3d_v2 other_ + if not isinstance(other, Memcpy3d_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMCPY3D_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMCPY3D_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY3D_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy3d_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMCPY3D_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def src_x_in_bytes(self): + """int: """ + return self._ptr[0].srcXInBytes + + @src_x_in_bytes.setter + def src_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcXInBytes = val + + @property + def src_y(self): + """int: """ + return self._ptr[0].srcY + + @src_y.setter + def src_y(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcY = val + + @property + def src_z(self): + """int: """ + return self._ptr[0].srcZ + + @src_z.setter + def src_z(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcZ = val + + @property + def src_lod(self): + """int: """ + return self._ptr[0].srcLOD + + @src_lod.setter + def src_lod(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcLOD = val + + @property + def src_memory_type(self): + """int: """ + return (self._ptr[0].srcMemoryType) + + @src_memory_type.setter + def src_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcMemoryType = val + + @property + def src_host(self): + """int: """ + return (self._ptr[0].srcHost) + + @src_host.setter + def src_host(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcHost = val + + @property + def src_device(self): + """int: """ + return (self._ptr[0].srcDevice) + + @src_device.setter + def src_device(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcDevice = val + + @property + def src_array(self): + """int: """ + return (self._ptr[0].srcArray) + + @src_array.setter + def src_array(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcArray = val + + @property + def src_pitch(self): + """int: """ + return self._ptr[0].srcPitch + + @src_pitch.setter + def src_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcPitch = val + + @property + def src_height(self): + """int: """ + return self._ptr[0].srcHeight + + @src_height.setter + def src_height(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].srcHeight = val + + @property + def dst_x_in_bytes(self): + """int: """ + return self._ptr[0].dstXInBytes + + @dst_x_in_bytes.setter + def dst_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstXInBytes = val + + @property + def dst_y(self): + """int: """ + return self._ptr[0].dstY + + @dst_y.setter + def dst_y(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstY = val + + @property + def dst_z(self): + """int: """ + return self._ptr[0].dstZ + + @dst_z.setter + def dst_z(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstZ = val + + @property + def dst_lod(self): + """int: """ + return self._ptr[0].dstLOD + + @dst_lod.setter + def dst_lod(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstLOD = val + + @property + def dst_memory_type(self): + """int: """ + return (self._ptr[0].dstMemoryType) + + @dst_memory_type.setter + def dst_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstMemoryType = val + + @property + def dst_host(self): + """int: """ + return (self._ptr[0].dstHost) + + @dst_host.setter + def dst_host(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstHost = val + + @property + def dst_device(self): + """int: """ + return (self._ptr[0].dstDevice) + + @dst_device.setter + def dst_device(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstDevice = val + + @property + def dst_array(self): + """int: """ + return (self._ptr[0].dstArray) + + @dst_array.setter + def dst_array(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstArray = val + + @property + def dst_pitch(self): + """int: """ + return self._ptr[0].dstPitch + + @dst_pitch.setter + def dst_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstPitch = val + + @property + def dst_height(self): + """int: """ + return self._ptr[0].dstHeight + + @dst_height.setter + def dst_height(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].dstHeight = val + + @property + def width_in_bytes(self): + """int: """ + return self._ptr[0].WidthInBytes + + @width_in_bytes.setter + def width_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].WidthInBytes = val + + @property + def height(self): + """int: """ + return self._ptr[0].Height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].Height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].Depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This Memcpy3d_v2 instance is read-only") + self._ptr[0].Depth = val + + @staticmethod + def from_buffer(buffer): + """Create an Memcpy3d_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMCPY3D_v2), Memcpy3d_v2) + + @staticmethod + def from_data(data): + """Create an Memcpy3d_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memcpy3d_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "memcpy3d_v2_dtype", memcpy3d_v2_dtype, Memcpy3d_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Memcpy3d_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Memcpy3d_v2 obj = Memcpy3d_v2.__new__(Memcpy3d_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY3D_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Memcpy3d_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMCPY3D_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memcpy3d_peer_v1_dtype_offsets(): + cdef CUDA_MEMCPY3D_PEER_v1 pod + return _numpy.dtype({ + 'names': ['src_x_in_bytes', 'src_y', 'src_z', 'src_lod', 'src_memory_type', 'src_host', 'src_device', 'src_array', 'src_context', 'src_pitch', 'src_height', 'dst_x_in_bytes', 'dst_y', 'dst_z', 'dst_lod', 'dst_memory_type', 'dst_host', 'dst_device', 'dst_array', 'dst_context', 'dst_pitch', 'dst_height', 'width_in_bytes', 'height', 'depth'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.intp, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.srcXInBytes)) - (&pod), + (&(pod.srcY)) - (&pod), + (&(pod.srcZ)) - (&pod), + (&(pod.srcLOD)) - (&pod), + (&(pod.srcMemoryType)) - (&pod), + (&(pod.srcHost)) - (&pod), + (&(pod.srcDevice)) - (&pod), + (&(pod.srcArray)) - (&pod), + (&(pod.srcContext)) - (&pod), + (&(pod.srcPitch)) - (&pod), + (&(pod.srcHeight)) - (&pod), + (&(pod.dstXInBytes)) - (&pod), + (&(pod.dstY)) - (&pod), + (&(pod.dstZ)) - (&pod), + (&(pod.dstLOD)) - (&pod), + (&(pod.dstMemoryType)) - (&pod), + (&(pod.dstHost)) - (&pod), + (&(pod.dstDevice)) - (&pod), + (&(pod.dstArray)) - (&pod), + (&(pod.dstContext)) - (&pod), + (&(pod.dstPitch)) - (&pod), + (&(pod.dstHeight)) - (&pod), + (&(pod.WidthInBytes)) - (&pod), + (&(pod.Height)) - (&pod), + (&(pod.Depth)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY3D_PEER_v1), + }) + +memcpy3d_peer_v1_dtype = _get_memcpy3d_peer_v1_dtype_offsets() + +cdef class Memcpy3dPeer_v1: + """Empty-initialize an instance of `CUDA_MEMCPY3D_PEER_v1`. + + + .. seealso:: `CUDA_MEMCPY3D_PEER_v1` + """ + cdef: + CUDA_MEMCPY3D_PEER_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMCPY3D_PEER_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy3dPeer_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMCPY3D_PEER_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Memcpy3dPeer_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Memcpy3dPeer_v1 other_ + if not isinstance(other, Memcpy3dPeer_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMCPY3D_PEER_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMCPY3D_PEER_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY3D_PEER_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Memcpy3dPeer_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMCPY3D_PEER_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def src_x_in_bytes(self): + """int: """ + return self._ptr[0].srcXInBytes + + @src_x_in_bytes.setter + def src_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcXInBytes = val + + @property + def src_y(self): + """int: """ + return self._ptr[0].srcY + + @src_y.setter + def src_y(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcY = val + + @property + def src_z(self): + """int: """ + return self._ptr[0].srcZ + + @src_z.setter + def src_z(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcZ = val + + @property + def src_lod(self): + """int: """ + return self._ptr[0].srcLOD + + @src_lod.setter + def src_lod(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcLOD = val + + @property + def src_memory_type(self): + """int: """ + return (self._ptr[0].srcMemoryType) + + @src_memory_type.setter + def src_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcMemoryType = val + + @property + def src_host(self): + """int: """ + return (self._ptr[0].srcHost) + + @src_host.setter + def src_host(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcHost = val + + @property + def src_device(self): + """int: """ + return (self._ptr[0].srcDevice) + + @src_device.setter + def src_device(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcDevice = val + + @property + def src_array(self): + """int: """ + return (self._ptr[0].srcArray) + + @src_array.setter + def src_array(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcArray = val + + @property + def src_context(self): + """int: """ + return (self._ptr[0].srcContext) + + @src_context.setter + def src_context(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcContext = val + + @property + def src_pitch(self): + """int: """ + return self._ptr[0].srcPitch + + @src_pitch.setter + def src_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcPitch = val + + @property + def src_height(self): + """int: """ + return self._ptr[0].srcHeight + + @src_height.setter + def src_height(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].srcHeight = val + + @property + def dst_x_in_bytes(self): + """int: """ + return self._ptr[0].dstXInBytes + + @dst_x_in_bytes.setter + def dst_x_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstXInBytes = val + + @property + def dst_y(self): + """int: """ + return self._ptr[0].dstY + + @dst_y.setter + def dst_y(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstY = val + + @property + def dst_z(self): + """int: """ + return self._ptr[0].dstZ + + @dst_z.setter + def dst_z(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstZ = val + + @property + def dst_lod(self): + """int: """ + return self._ptr[0].dstLOD + + @dst_lod.setter + def dst_lod(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstLOD = val + + @property + def dst_memory_type(self): + """int: """ + return (self._ptr[0].dstMemoryType) + + @dst_memory_type.setter + def dst_memory_type(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstMemoryType = val + + @property + def dst_host(self): + """int: """ + return (self._ptr[0].dstHost) + + @dst_host.setter + def dst_host(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstHost = val + + @property + def dst_device(self): + """int: """ + return (self._ptr[0].dstDevice) + + @dst_device.setter + def dst_device(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstDevice = val + + @property + def dst_array(self): + """int: """ + return (self._ptr[0].dstArray) + + @dst_array.setter + def dst_array(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstArray = val + + @property + def dst_context(self): + """int: """ + return (self._ptr[0].dstContext) + + @dst_context.setter + def dst_context(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstContext = val + + @property + def dst_pitch(self): + """int: """ + return self._ptr[0].dstPitch + + @dst_pitch.setter + def dst_pitch(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstPitch = val + + @property + def dst_height(self): + """int: """ + return self._ptr[0].dstHeight + + @dst_height.setter + def dst_height(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].dstHeight = val + + @property + def width_in_bytes(self): + """int: """ + return self._ptr[0].WidthInBytes + + @width_in_bytes.setter + def width_in_bytes(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].WidthInBytes = val + + @property + def height(self): + """int: """ + return self._ptr[0].Height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].Height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].Depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This Memcpy3dPeer_v1 instance is read-only") + self._ptr[0].Depth = val + + @staticmethod + def from_buffer(buffer): + """Create an Memcpy3dPeer_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMCPY3D_PEER_v1), Memcpy3dPeer_v1) + + @staticmethod + def from_data(data): + """Create an Memcpy3dPeer_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memcpy3d_peer_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "memcpy3d_peer_v1_dtype", memcpy3d_peer_v1_dtype, Memcpy3dPeer_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Memcpy3dPeer_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Memcpy3dPeer_v1 obj = Memcpy3dPeer_v1.__new__(Memcpy3dPeer_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY3D_PEER_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Memcpy3dPeer_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMCPY3D_PEER_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memcpy_node_params_dtype_offsets(): + cdef CUDA_MEMCPY_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['flags_', 'reserved', 'copy_ctx', 'copy_params'], + 'formats': [_numpy.int32, _numpy.int32, _numpy.intp, memcpy3d_v2_dtype], + 'offsets': [ + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + (&(pod.copyCtx)) - (&pod), + (&(pod.copyParams)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY_NODE_PARAMS), + }) + +memcpy_node_params_dtype = _get_memcpy_node_params_dtype_offsets() + +cdef class MemcpyNodeParams: + """Empty-initialize an instance of `CUDA_MEMCPY_NODE_PARAMS`. + + + .. seealso:: `CUDA_MEMCPY_NODE_PARAMS` + """ + cdef: + CUDA_MEMCPY_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEMCPY_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemcpyNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMCPY_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemcpyNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemcpyNodeParams other_ + if not isinstance(other, MemcpyNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMCPY_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMCPY_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemcpyNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEMCPY_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def copy_params(self): + """Memcpy3d_v2: """ + return Memcpy3d_v2.from_ptr( + &(self._ptr[0].copyParams), + readonly=self._readonly, + owner=self, + ) + + @copy_params.setter + def copy_params(self, val): + if self._readonly: + raise ValueError("This MemcpyNodeParams instance is read-only") + cdef Memcpy3d_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].copyParams), (val_._get_ptr()), sizeof(CUDA_MEMCPY3D) * 1) + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This MemcpyNodeParams instance is read-only") + self._ptr[0].flags = val + + @property + def copy_ctx(self): + """int: """ + return (self._ptr[0].copyCtx) + + @copy_ctx.setter + def copy_ctx(self, val): + if self._readonly: + raise ValueError("This MemcpyNodeParams instance is read-only") + self._ptr[0].copyCtx = val + + @staticmethod + def from_buffer(buffer): + """Create an MemcpyNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMCPY_NODE_PARAMS), MemcpyNodeParams) + + @staticmethod + def from_data(data): + """Create an MemcpyNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memcpy_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "memcpy_node_params_dtype", memcpy_node_params_dtype, MemcpyNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemcpyNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemcpyNodeParams obj = MemcpyNodeParams.__new__(MemcpyNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEMCPY_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemcpyNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEMCPY_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_array_descriptor_v2_dtype_offsets(): + cdef CUDA_ARRAY_DESCRIPTOR_v2 pod + return _numpy.dtype({ + 'names': ['width', 'height', 'format', 'num_channels'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.Width)) - (&pod), + (&(pod.Height)) - (&pod), + (&(pod.Format)) - (&pod), + (&(pod.NumChannels)) - (&pod), + ], + 'itemsize': sizeof(CUDA_ARRAY_DESCRIPTOR_v2), + }) + +array_descriptor_v2_dtype = _get_array_descriptor_v2_dtype_offsets() + +cdef class ArrayDescriptor_v2: + """Empty-initialize an instance of `CUDA_ARRAY_DESCRIPTOR_v2`. + + + .. seealso:: `CUDA_ARRAY_DESCRIPTOR_v2` + """ + cdef: + CUDA_ARRAY_DESCRIPTOR_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArrayDescriptor_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_ARRAY_DESCRIPTOR_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ArrayDescriptor_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ArrayDescriptor_v2 other_ + if not isinstance(other, ArrayDescriptor_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_ARRAY_DESCRIPTOR_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArrayDescriptor_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def width(self): + """int: """ + return self._ptr[0].Width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This ArrayDescriptor_v2 instance is read-only") + self._ptr[0].Width = val + + @property + def height(self): + """int: """ + return self._ptr[0].Height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This ArrayDescriptor_v2 instance is read-only") + self._ptr[0].Height = val + + @property + def format(self): + """int: """ + return (self._ptr[0].Format) + + @format.setter + def format(self, val): + if self._readonly: + raise ValueError("This ArrayDescriptor_v2 instance is read-only") + self._ptr[0].Format = val + + @property + def num_channels(self): + """int: """ + return self._ptr[0].NumChannels + + @num_channels.setter + def num_channels(self, val): + if self._readonly: + raise ValueError("This ArrayDescriptor_v2 instance is read-only") + self._ptr[0].NumChannels = val + + @staticmethod + def from_buffer(buffer): + """Create an ArrayDescriptor_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_ARRAY_DESCRIPTOR_v2), ArrayDescriptor_v2) + + @staticmethod + def from_data(data): + """Create an ArrayDescriptor_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `array_descriptor_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "array_descriptor_v2_dtype", array_descriptor_v2_dtype, ArrayDescriptor_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ArrayDescriptor_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ArrayDescriptor_v2 obj = ArrayDescriptor_v2.__new__(ArrayDescriptor_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ArrayDescriptor_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_array3d_descriptor_v2_dtype_offsets(): + cdef CUDA_ARRAY3D_DESCRIPTOR_v2 pod + return _numpy.dtype({ + 'names': ['width', 'height', 'depth', 'format', 'num_channels', 'flags_'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.int32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.Width)) - (&pod), + (&(pod.Height)) - (&pod), + (&(pod.Depth)) - (&pod), + (&(pod.Format)) - (&pod), + (&(pod.NumChannels)) - (&pod), + (&(pod.Flags)) - (&pod), + ], + 'itemsize': sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2), + }) + +array3d_descriptor_v2_dtype = _get_array3d_descriptor_v2_dtype_offsets() + +cdef class Array3dDescriptor_v2: + """Empty-initialize an instance of `CUDA_ARRAY3D_DESCRIPTOR_v2`. + + + .. seealso:: `CUDA_ARRAY3D_DESCRIPTOR_v2` + """ + cdef: + CUDA_ARRAY3D_DESCRIPTOR_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Array3dDescriptor_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_ARRAY3D_DESCRIPTOR_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Array3dDescriptor_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Array3dDescriptor_v2 other_ + if not isinstance(other, Array3dDescriptor_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating Array3dDescriptor_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def width(self): + """int: """ + return self._ptr[0].Width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].Width = val + + @property + def height(self): + """int: """ + return self._ptr[0].Height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].Height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].Depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].Depth = val + + @property + def format(self): + """int: """ + return (self._ptr[0].Format) + + @format.setter + def format(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].Format = val + + @property + def num_channels(self): + """int: """ + return self._ptr[0].NumChannels + + @num_channels.setter + def num_channels(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].NumChannels = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].Flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + self._ptr[0].Flags = val + + @staticmethod + def from_buffer(buffer): + """Create an Array3dDescriptor_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2), Array3dDescriptor_v2) + + @staticmethod + def from_data(data): + """Create an Array3dDescriptor_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `array3d_descriptor_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "array3d_descriptor_v2_dtype", array3d_descriptor_v2_dtype, Array3dDescriptor_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Array3dDescriptor_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Array3dDescriptor_v2 obj = Array3dDescriptor_v2.__new__(Array3dDescriptor_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Array3dDescriptor_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod10_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod10 pod + return _numpy.dtype({ + 'names': ['width', 'height', 'depth'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + (&(pod.depth)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod10), + }) + +_py_anon_pod10_dtype = _get__py_anon_pod10_dtype_offsets() + +cdef class _py_anon_pod10: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod10`. + + + .. seealso:: `cuda_bindings_driver__anon_pod10` + """ + cdef: + cuda_bindings_driver__anon_pod10 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod10)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod10") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod10 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod10 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod10 other_ + if not isinstance(other, _py_anon_pod10): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod10)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod10), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod10)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod10") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod10)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def width(self): + """int: """ + return self._ptr[0].width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod10 instance is read-only") + self._ptr[0].width = val + + @property + def height(self): + """int: """ + return self._ptr[0].height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod10 instance is read-only") + self._ptr[0].height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod10 instance is read-only") + self._ptr[0].depth = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod10 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod10), _py_anon_pod10) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod10 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod10_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod10_dtype", _py_anon_pod10_dtype, _py_anon_pod10) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod10 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod10 obj = _py_anon_pod10.__new__(_py_anon_pod10) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod10)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod10") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod10)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_array_memory_requirements_v1_dtype_offsets(): + cdef CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 pod + return _numpy.dtype({ + 'names': ['size_', 'alignment', 'reserved'], + 'formats': [_numpy.uint64, _numpy.uint64, (_numpy.uint32, 4)], + 'offsets': [ + (&(pod.size)) - (&pod), + (&(pod.alignment)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1), + }) + +array_memory_requirements_v1_dtype = _get_array_memory_requirements_v1_dtype_offsets() + +cdef class ArrayMemoryRequirements_v1: + """Empty-initialize an instance of `CUDA_ARRAY_MEMORY_REQUIREMENTS_v1`. + + + .. seealso:: `CUDA_ARRAY_MEMORY_REQUIREMENTS_v1` + """ + cdef: + CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArrayMemoryRequirements_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ArrayMemoryRequirements_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ArrayMemoryRequirements_v1 other_ + if not isinstance(other, ArrayMemoryRequirements_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArrayMemoryRequirements_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This ArrayMemoryRequirements_v1 instance is read-only") + self._ptr[0].size = val + + @property + def alignment(self): + """int: """ + return self._ptr[0].alignment + + @alignment.setter + def alignment(self, val): + if self._readonly: + raise ValueError("This ArrayMemoryRequirements_v1 instance is read-only") + self._ptr[0].alignment = val + + @staticmethod + def from_buffer(buffer): + """Create an ArrayMemoryRequirements_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1), ArrayMemoryRequirements_v1) + + @staticmethod + def from_data(data): + """Create an ArrayMemoryRequirements_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `array_memory_requirements_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "array_memory_requirements_v1_dtype", array_memory_requirements_v1_dtype, ArrayMemoryRequirements_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ArrayMemoryRequirements_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ArrayMemoryRequirements_v1 obj = ArrayMemoryRequirements_v1.__new__(ArrayMemoryRequirements_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ArrayMemoryRequirements_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_texture_desc_v1_dtype_offsets(): + cdef CUDA_TEXTURE_DESC_v1 pod + return _numpy.dtype({ + 'names': ['address_mode', 'filter_mode', 'flags_', 'max_anisotropy', 'mipmap_filter_mode', 'mipmap_level_bias', 'min_mipmap_level_clamp', 'max_mipmap_level_clamp', 'border_color', 'reserved'], + 'formats': [(_numpy.int32, 3), _numpy.int32, _numpy.uint32, _numpy.uint32, _numpy.int32, _numpy.float32, _numpy.float32, _numpy.float32, (_numpy.float32, 4), (_numpy.int32, 12)], + 'offsets': [ + (&(pod.addressMode)) - (&pod), + (&(pod.filterMode)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.maxAnisotropy)) - (&pod), + (&(pod.mipmapFilterMode)) - (&pod), + (&(pod.mipmapLevelBias)) - (&pod), + (&(pod.minMipmapLevelClamp)) - (&pod), + (&(pod.maxMipmapLevelClamp)) - (&pod), + (&(pod.borderColor)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_TEXTURE_DESC_v1), + }) + +texture_desc_v1_dtype = _get_texture_desc_v1_dtype_offsets() + +cdef class TextureDesc_v1: + """Empty-initialize an instance of `CUDA_TEXTURE_DESC_v1`. + + + .. seealso:: `CUDA_TEXTURE_DESC_v1` + """ + cdef: + CUDA_TEXTURE_DESC_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_TEXTURE_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating TextureDesc_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_TEXTURE_DESC_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.TextureDesc_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef TextureDesc_v1 other_ + if not isinstance(other, TextureDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_TEXTURE_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_TEXTURE_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_TEXTURE_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating TextureDesc_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_TEXTURE_DESC_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def address_mode(self): + """~_numpy.int32: (array of length 3).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].addressMode)), + (sizeof(intptr_t) * (3)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.intp) + + @address_mode.setter + def address_mode(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + if len(val) != 3: + raise ValueError(f"Expected length { 3 } for field address_mode, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.intp)) + _cyb_memcpy((&(self._ptr[0].addressMode)), (_val_.ctypes.data), sizeof(intptr_t) * (3)) + + @property + def filter_mode(self): + """int: """ + return (self._ptr[0].filterMode) + + @filter_mode.setter + def filter_mode(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].filterMode = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].flags = val + + @property + def max_anisotropy(self): + """int: """ + return self._ptr[0].maxAnisotropy + + @max_anisotropy.setter + def max_anisotropy(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].maxAnisotropy = val + + @property + def mipmap_filter_mode(self): + """int: """ + return (self._ptr[0].mipmapFilterMode) + + @mipmap_filter_mode.setter + def mipmap_filter_mode(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].mipmapFilterMode = val + + @property + def mipmap_level_bias(self): + """float: """ + return self._ptr[0].mipmapLevelBias + + @mipmap_level_bias.setter + def mipmap_level_bias(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].mipmapLevelBias = val + + @property + def min_mipmap_level_clamp(self): + """float: """ + return self._ptr[0].minMipmapLevelClamp + + @min_mipmap_level_clamp.setter + def min_mipmap_level_clamp(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].minMipmapLevelClamp = val + + @property + def max_mipmap_level_clamp(self): + """float: """ + return self._ptr[0].maxMipmapLevelClamp + + @max_mipmap_level_clamp.setter + def max_mipmap_level_clamp(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + self._ptr[0].maxMipmapLevelClamp = val + + @property + def border_color(self): + """~_numpy.float32: (array of length 4).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].borderColor)), + (sizeof(float) * (4)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.float32) + + @border_color.setter + def border_color(self, val): + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + if len(val) != 4: + raise ValueError(f"Expected length { 4 } for field border_color, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.float32)) + _cyb_memcpy((&(self._ptr[0].borderColor)), (_val_.ctypes.data), sizeof(float) * (4)) + + @staticmethod + def from_buffer(buffer): + """Create an TextureDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_TEXTURE_DESC_v1), TextureDesc_v1) + + @staticmethod + def from_data(data): + """Create an TextureDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `texture_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "texture_desc_v1_dtype", texture_desc_v1_dtype, TextureDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an TextureDesc_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef TextureDesc_v1 obj = TextureDesc_v1.__new__(TextureDesc_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_TEXTURE_DESC_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating TextureDesc_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_TEXTURE_DESC_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_resource_view_desc_v1_dtype_offsets(): + cdef CUDA_RESOURCE_VIEW_DESC_v1 pod + return _numpy.dtype({ + 'names': ['format', 'width', 'height', 'depth', 'first_mipmap_level', 'last_mipmap_level', 'first_layer', 'last_layer', 'reserved'], + 'formats': [_numpy.int32, _numpy.uint64, _numpy.uint64, _numpy.uint64, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.format)) - (&pod), + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + (&(pod.depth)) - (&pod), + (&(pod.firstMipmapLevel)) - (&pod), + (&(pod.lastMipmapLevel)) - (&pod), + (&(pod.firstLayer)) - (&pod), + (&(pod.lastLayer)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_RESOURCE_VIEW_DESC_v1), + }) + +resource_view_desc_v1_dtype = _get_resource_view_desc_v1_dtype_offsets() + +cdef class ResourceViewDesc_v1: + """Empty-initialize an instance of `CUDA_RESOURCE_VIEW_DESC_v1`. + + + .. seealso:: `CUDA_RESOURCE_VIEW_DESC_v1` + """ + cdef: + CUDA_RESOURCE_VIEW_DESC_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ResourceViewDesc_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_RESOURCE_VIEW_DESC_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ResourceViewDesc_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ResourceViewDesc_v1 other_ + if not isinstance(other, ResourceViewDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_RESOURCE_VIEW_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ResourceViewDesc_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def format(self): + """int: """ + return (self._ptr[0].format) + + @format.setter + def format(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].format = val + + @property + def width(self): + """int: """ + return self._ptr[0].width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].width = val + + @property + def height(self): + """int: """ + return self._ptr[0].height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].depth = val + + @property + def first_mipmap_level(self): + """int: """ + return self._ptr[0].firstMipmapLevel + + @first_mipmap_level.setter + def first_mipmap_level(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].firstMipmapLevel = val + + @property + def last_mipmap_level(self): + """int: """ + return self._ptr[0].lastMipmapLevel + + @last_mipmap_level.setter + def last_mipmap_level(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].lastMipmapLevel = val + + @property + def first_layer(self): + """int: """ + return self._ptr[0].firstLayer + + @first_layer.setter + def first_layer(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].firstLayer = val + + @property + def last_layer(self): + """int: """ + return self._ptr[0].lastLayer + + @last_layer.setter + def last_layer(self, val): + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + self._ptr[0].lastLayer = val + + @staticmethod + def from_buffer(buffer): + """Create an ResourceViewDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_RESOURCE_VIEW_DESC_v1), ResourceViewDesc_v1) + + @staticmethod + def from_data(data): + """Create an ResourceViewDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `resource_view_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "resource_view_desc_v1_dtype", resource_view_desc_v1_dtype, ResourceViewDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ResourceViewDesc_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ResourceViewDesc_v1 obj = ResourceViewDesc_v1.__new__(ResourceViewDesc_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ResourceViewDesc_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_tensor_map_dtype_offsets(): + cdef CUtensorMap pod + return _numpy.dtype({ + 'names': ['opaque'], + 'formats': [(_numpy.uint64, 16)], + 'offsets': [ + (&(pod.opaque)) - (&pod), + ], + 'itemsize': sizeof(CUtensorMap), + }) + +tensor_map_dtype = _get_tensor_map_dtype_offsets() + +cdef class TensorMap: + """Empty-initialize an instance of `CUtensorMap`. + + + .. seealso:: `CUtensorMap` + """ + cdef: + CUtensorMap *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUtensorMap)) + if self._ptr == NULL: + raise MemoryError("Error allocating TensorMap") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUtensorMap *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.TensorMap object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef TensorMap other_ + if not isinstance(other, TensorMap): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUtensorMap)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUtensorMap), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUtensorMap)) + if self._ptr == NULL: + raise MemoryError("Error allocating TensorMap") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUtensorMap)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def opaque(self): + """~_numpy.uint64: (array of length 16).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].opaque)), + (sizeof(intptr_t) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.intp) + + @opaque.setter + def opaque(self, val): + if self._readonly: + raise ValueError("This TensorMap instance is read-only") + if len(val) != 16: + raise ValueError(f"Expected length { 16 } for field opaque, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.intp)) + _cyb_memcpy((&(self._ptr[0].opaque)), (_val_.ctypes.data), sizeof(intptr_t) * (16)) + + @staticmethod + def from_buffer(buffer): + """Create an TensorMap instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUtensorMap), TensorMap) + + @staticmethod + def from_data(data): + """Create an TensorMap instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `tensor_map_dtype` holding the data. + """ + return _cyb_from_data(data, "tensor_map_dtype", tensor_map_dtype, TensorMap) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an TensorMap instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef TensorMap obj = TensorMap.__new__(TensorMap) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUtensorMap)) + if obj._ptr == NULL: + raise MemoryError("Error allocating TensorMap") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUtensorMap)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_pointer_attribute_p2p_tokens_v1_dtype_offsets(): + cdef CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 pod + return _numpy.dtype({ + 'names': ['p2p_token', 'va_space_token'], + 'formats': [_numpy.uint64, _numpy.uint32], + 'offsets': [ + (&(pod.p2pToken)) - (&pod), + (&(pod.vaSpaceToken)) - (&pod), + ], + 'itemsize': sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1), + }) + +pointer_attribute_p2p_tokens_v1_dtype = _get_pointer_attribute_p2p_tokens_v1_dtype_offsets() + +cdef class PointerAttributeP2pTokens_v1: + """Empty-initialize an instance of `CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1`. + + + .. seealso:: `CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1` + """ + cdef: + CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating PointerAttributeP2pTokens_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.PointerAttributeP2pTokens_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef PointerAttributeP2pTokens_v1 other_ + if not isinstance(other, PointerAttributeP2pTokens_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating PointerAttributeP2pTokens_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def p2p_token(self): + """int: """ + return self._ptr[0].p2pToken + + @p2p_token.setter + def p2p_token(self, val): + if self._readonly: + raise ValueError("This PointerAttributeP2pTokens_v1 instance is read-only") + self._ptr[0].p2pToken = val + + @property + def va_space_token(self): + """int: """ + return self._ptr[0].vaSpaceToken + + @va_space_token.setter + def va_space_token(self, val): + if self._readonly: + raise ValueError("This PointerAttributeP2pTokens_v1 instance is read-only") + self._ptr[0].vaSpaceToken = val + + @staticmethod + def from_buffer(buffer): + """Create an PointerAttributeP2pTokens_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1), PointerAttributeP2pTokens_v1) + + @staticmethod + def from_data(data): + """Create an PointerAttributeP2pTokens_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `pointer_attribute_p2p_tokens_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "pointer_attribute_p2p_tokens_v1_dtype", pointer_attribute_p2p_tokens_v1_dtype, PointerAttributeP2pTokens_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an PointerAttributeP2pTokens_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef PointerAttributeP2pTokens_v1 obj = PointerAttributeP2pTokens_v1.__new__(PointerAttributeP2pTokens_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating PointerAttributeP2pTokens_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_launch_params_v1_dtype_offsets(): + cdef CUDA_LAUNCH_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['function', 'grid_dim_x', 'grid_dim_y', 'grid_dim_z', 'block_dim_x', 'block_dim_y', 'block_dim_z', 'shared_mem_bytes', 'h_stream', 'kernel_params'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.function)) - (&pod), + (&(pod.gridDimX)) - (&pod), + (&(pod.gridDimY)) - (&pod), + (&(pod.gridDimZ)) - (&pod), + (&(pod.blockDimX)) - (&pod), + (&(pod.blockDimY)) - (&pod), + (&(pod.blockDimZ)) - (&pod), + (&(pod.sharedMemBytes)) - (&pod), + (&(pod.hStream)) - (&pod), + (&(pod.kernelParams)) - (&pod), + ], + 'itemsize': sizeof(CUDA_LAUNCH_PARAMS_v1), + }) + +launch_params_v1_dtype = _get_launch_params_v1_dtype_offsets() + +cdef class LaunchParams_v1: + """Empty-initialize an instance of `CUDA_LAUNCH_PARAMS_v1`. + + + .. seealso:: `CUDA_LAUNCH_PARAMS_v1` + """ + cdef: + CUDA_LAUNCH_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_LAUNCH_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_LAUNCH_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LaunchParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef LaunchParams_v1 other_ + if not isinstance(other, LaunchParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_LAUNCH_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_LAUNCH_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_LAUNCH_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_LAUNCH_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def function(self): + """int: """ + return (self._ptr[0].function) + + @function.setter + def function(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].function = val + + @property + def grid_dim_x(self): + """int: """ + return self._ptr[0].gridDimX + + @grid_dim_x.setter + def grid_dim_x(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].gridDimX = val + + @property + def grid_dim_y(self): + """int: """ + return self._ptr[0].gridDimY + + @grid_dim_y.setter + def grid_dim_y(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].gridDimY = val + + @property + def grid_dim_z(self): + """int: """ + return self._ptr[0].gridDimZ + + @grid_dim_z.setter + def grid_dim_z(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].gridDimZ = val + + @property + def block_dim_x(self): + """int: """ + return self._ptr[0].blockDimX + + @block_dim_x.setter + def block_dim_x(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].blockDimX = val + + @property + def block_dim_y(self): + """int: """ + return self._ptr[0].blockDimY + + @block_dim_y.setter + def block_dim_y(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].blockDimY = val + + @property + def block_dim_z(self): + """int: """ + return self._ptr[0].blockDimZ + + @block_dim_z.setter + def block_dim_z(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].blockDimZ = val + + @property + def shared_mem_bytes(self): + """int: """ + return self._ptr[0].sharedMemBytes + + @shared_mem_bytes.setter + def shared_mem_bytes(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].sharedMemBytes = val + + @property + def h_stream(self): + """int: """ + return (self._ptr[0].hStream) + + @h_stream.setter + def h_stream(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].hStream = val + + @property + def kernel_params(self): + """int: """ + return (self._ptr[0].kernelParams) + + @kernel_params.setter + def kernel_params(self, val): + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + self._ptr[0].kernelParams = val + + @staticmethod + def from_buffer(buffer): + """Create an LaunchParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_LAUNCH_PARAMS_v1), LaunchParams_v1) + + @staticmethod + def from_data(data): + """Create an LaunchParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `launch_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "launch_params_v1_dtype", launch_params_v1_dtype, LaunchParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LaunchParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef LaunchParams_v1 obj = LaunchParams_v1.__new__(LaunchParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_LAUNCH_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LaunchParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_LAUNCH_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_external_memory_buffer_desc_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 pod + return _numpy.dtype({ + 'names': ['offset', 'size_', 'flags_', 'reserved'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.offset)) - (&pod), + (&(pod.size)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1), + }) + +external_memory_buffer_desc_v1_dtype = _get_external_memory_buffer_desc_v1_dtype_offsets() + +cdef class ExternalMemoryBufferDesc_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1`. + + + .. seealso:: `CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1` + """ + cdef: + CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExternalMemoryBufferDesc_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExternalMemoryBufferDesc_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExternalMemoryBufferDesc_v1 other_ + if not isinstance(other, ExternalMemoryBufferDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExternalMemoryBufferDesc_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def offset(self): + """int: """ + return self._ptr[0].offset + + @offset.setter + def offset(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryBufferDesc_v1 instance is read-only") + self._ptr[0].offset = val + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryBufferDesc_v1 instance is read-only") + self._ptr[0].size = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryBufferDesc_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalMemoryBufferDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1), ExternalMemoryBufferDesc_v1) + + @staticmethod + def from_data(data): + """Create an ExternalMemoryBufferDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_memory_buffer_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_memory_buffer_desc_v1_dtype", external_memory_buffer_desc_v1_dtype, ExternalMemoryBufferDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalMemoryBufferDesc_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExternalMemoryBufferDesc_v1 obj = ExternalMemoryBufferDesc_v1.__new__(ExternalMemoryBufferDesc_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExternalMemoryBufferDesc_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ext_sem_signal_node_params_v1_dtype_offsets(): + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['ext_sem_array', 'params_array', 'num_ext_sems'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1), + }) + +ext_sem_signal_node_params_v1_dtype = _get_ext_sem_signal_node_params_v1_dtype_offsets() + +cdef class ExtSemSignalNodeParams_v1: + """Empty-initialize an instance of `CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1` + """ + cdef: + CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExtSemSignalNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExtSemSignalNodeParams_v1 other_ + if not isinstance(other, ExtSemSignalNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ext_sem_array(self): + """int: """ + return (self._ptr[0].extSemArray) + + @ext_sem_array.setter + def ext_sem_array(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v1 instance is read-only") + self._ptr[0].extSemArray = val + + @property + def params_array(self): + """int: """ + return (self._ptr[0].paramsArray) + + @params_array.setter + def params_array(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v1 instance is read-only") + self._ptr[0].paramsArray = val + + @property + def num_ext_sems(self): + """int: """ + return self._ptr[0].numExtSems + + @num_ext_sems.setter + def num_ext_sems(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v1 instance is read-only") + self._ptr[0].numExtSems = val + + @staticmethod + def from_buffer(buffer): + """Create an ExtSemSignalNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1), ExtSemSignalNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an ExtSemSignalNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ext_sem_signal_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "ext_sem_signal_node_params_v1_dtype", ext_sem_signal_node_params_v1_dtype, ExtSemSignalNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExtSemSignalNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExtSemSignalNodeParams_v1 obj = ExtSemSignalNodeParams_v1.__new__(ExtSemSignalNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ext_sem_signal_node_params_v2_dtype_offsets(): + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['ext_sem_array', 'params_array', 'num_ext_sems'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2), + }) + +ext_sem_signal_node_params_v2_dtype = _get_ext_sem_signal_node_params_v2_dtype_offsets() + +cdef class ExtSemSignalNodeParams_v2: + """Empty-initialize an instance of `CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2` + """ + cdef: + CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExtSemSignalNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExtSemSignalNodeParams_v2 other_ + if not isinstance(other, ExtSemSignalNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ext_sem_array(self): + """int: """ + return (self._ptr[0].extSemArray) + + @ext_sem_array.setter + def ext_sem_array(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + self._ptr[0].extSemArray = val + + @property + def params_array(self): + """int: """ + return (self._ptr[0].paramsArray) + + @params_array.setter + def params_array(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + self._ptr[0].paramsArray = val + + @property + def num_ext_sems(self): + """int: """ + return self._ptr[0].numExtSems + + @num_ext_sems.setter + def num_ext_sems(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + self._ptr[0].numExtSems = val + + @staticmethod + def from_buffer(buffer): + """Create an ExtSemSignalNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2), ExtSemSignalNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an ExtSemSignalNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ext_sem_signal_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "ext_sem_signal_node_params_v2_dtype", ext_sem_signal_node_params_v2_dtype, ExtSemSignalNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExtSemSignalNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExtSemSignalNodeParams_v2 obj = ExtSemSignalNodeParams_v2.__new__(ExtSemSignalNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExtSemSignalNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ext_sem_wait_node_params_v1_dtype_offsets(): + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['ext_sem_array', 'params_array', 'num_ext_sems'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1), + }) + +ext_sem_wait_node_params_v1_dtype = _get_ext_sem_wait_node_params_v1_dtype_offsets() + +cdef class ExtSemWaitNodeParams_v1: + """Empty-initialize an instance of `CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1` + """ + cdef: + CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExtSemWaitNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExtSemWaitNodeParams_v1 other_ + if not isinstance(other, ExtSemWaitNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ext_sem_array(self): + """int: """ + return (self._ptr[0].extSemArray) + + @ext_sem_array.setter + def ext_sem_array(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v1 instance is read-only") + self._ptr[0].extSemArray = val + + @property + def params_array(self): + """int: """ + return (self._ptr[0].paramsArray) + + @params_array.setter + def params_array(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v1 instance is read-only") + self._ptr[0].paramsArray = val + + @property + def num_ext_sems(self): + """int: """ + return self._ptr[0].numExtSems + + @num_ext_sems.setter + def num_ext_sems(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v1 instance is read-only") + self._ptr[0].numExtSems = val + + @staticmethod + def from_buffer(buffer): + """Create an ExtSemWaitNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1), ExtSemWaitNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an ExtSemWaitNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ext_sem_wait_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "ext_sem_wait_node_params_v1_dtype", ext_sem_wait_node_params_v1_dtype, ExtSemWaitNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExtSemWaitNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExtSemWaitNodeParams_v1 obj = ExtSemWaitNodeParams_v1.__new__(ExtSemWaitNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_ext_sem_wait_node_params_v2_dtype_offsets(): + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['ext_sem_array', 'params_array', 'num_ext_sems'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2), + }) + +ext_sem_wait_node_params_v2_dtype = _get_ext_sem_wait_node_params_v2_dtype_offsets() + +cdef class ExtSemWaitNodeParams_v2: + """Empty-initialize an instance of `CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2` + """ + cdef: + CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ExtSemWaitNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ExtSemWaitNodeParams_v2 other_ + if not isinstance(other, ExtSemWaitNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def ext_sem_array(self): + """int: """ + return (self._ptr[0].extSemArray) + + @ext_sem_array.setter + def ext_sem_array(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + self._ptr[0].extSemArray = val + + @property + def params_array(self): + """int: """ + return (self._ptr[0].paramsArray) + + @params_array.setter + def params_array(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + self._ptr[0].paramsArray = val + + @property + def num_ext_sems(self): + """int: """ + return self._ptr[0].numExtSems + + @num_ext_sems.setter + def num_ext_sems(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + self._ptr[0].numExtSems = val + + @staticmethod + def from_buffer(buffer): + """Create an ExtSemWaitNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2), ExtSemWaitNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an ExtSemWaitNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ext_sem_wait_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "ext_sem_wait_node_params_v2_dtype", ext_sem_wait_node_params_v2_dtype, ExtSemWaitNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExtSemWaitNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExtSemWaitNodeParams_v2 obj = ExtSemWaitNodeParams_v2.__new__(ExtSemWaitNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ExtSemWaitNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod29_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod29 pod + return _numpy.dtype({ + 'names': ['mipmap', 'array'], + 'formats': [_numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.mipmap)) - (&pod), + (&(pod.array)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod29), + }) + +_py_anon_pod29_dtype = _get__py_anon_pod29_dtype_offsets() + +cdef class _py_anon_pod29: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod29`. + + + .. seealso:: `cuda_bindings_driver__anon_pod29` + """ + cdef: + cuda_bindings_driver__anon_pod29 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod29)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod29") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod29 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod29 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod29 other_ + if not isinstance(other, _py_anon_pod29): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod29)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod29), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod29)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod29") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod29)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def mipmap(self): + """int: """ + return (self._ptr[0].mipmap) + + @mipmap.setter + def mipmap(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod29 instance is read-only") + self._ptr[0].mipmap = val + + @property + def array(self): + """int: """ + return (self._ptr[0].array) + + @array.setter + def array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod29 instance is read-only") + self._ptr[0].array = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod29 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod29), _py_anon_pod29) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod29 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod29_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod29_dtype", _py_anon_pod29_dtype, _py_anon_pod29) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod29 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod29 obj = _py_anon_pod29.__new__(_py_anon_pod29) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod29)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod29") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod29)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod31_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod31 pod + return _numpy.dtype({ + 'names': ['level', 'layer', 'offset_x', 'offset_y', 'offset_z', 'extent_width', 'extent_height', 'extent_depth'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.level)) - (&pod), + (&(pod.layer)) - (&pod), + (&(pod.offsetX)) - (&pod), + (&(pod.offsetY)) - (&pod), + (&(pod.offsetZ)) - (&pod), + (&(pod.extentWidth)) - (&pod), + (&(pod.extentHeight)) - (&pod), + (&(pod.extentDepth)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod31), + }) + +_py_anon_pod31_dtype = _get__py_anon_pod31_dtype_offsets() + +cdef class _py_anon_pod31: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod31`. + + + .. seealso:: `cuda_bindings_driver__anon_pod31` + """ + cdef: + cuda_bindings_driver__anon_pod31 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod31)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod31") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod31 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod31 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod31 other_ + if not isinstance(other, _py_anon_pod31): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod31)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod31), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod31)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod31") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod31)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def level(self): + """int: """ + return self._ptr[0].level + + @level.setter + def level(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].level = val + + @property + def layer(self): + """int: """ + return self._ptr[0].layer + + @layer.setter + def layer(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].layer = val + + @property + def offset_x(self): + """int: """ + return self._ptr[0].offsetX + + @offset_x.setter + def offset_x(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].offsetX = val + + @property + def offset_y(self): + """int: """ + return self._ptr[0].offsetY + + @offset_y.setter + def offset_y(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].offsetY = val + + @property + def offset_z(self): + """int: """ + return self._ptr[0].offsetZ + + @offset_z.setter + def offset_z(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].offsetZ = val + + @property + def extent_width(self): + """int: """ + return self._ptr[0].extentWidth + + @extent_width.setter + def extent_width(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].extentWidth = val + + @property + def extent_height(self): + """int: """ + return self._ptr[0].extentHeight + + @extent_height.setter + def extent_height(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].extentHeight = val + + @property + def extent_depth(self): + """int: """ + return self._ptr[0].extentDepth + + @extent_depth.setter + def extent_depth(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod31 instance is read-only") + self._ptr[0].extentDepth = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod31 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod31), _py_anon_pod31) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod31 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod31_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod31_dtype", _py_anon_pod31_dtype, _py_anon_pod31) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod31 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod31 obj = _py_anon_pod31.__new__(_py_anon_pod31) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod31)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod31") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod31)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod32_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod32 pod + return _numpy.dtype({ + 'names': ['layer', 'offset', 'size_'], + 'formats': [_numpy.uint32, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.layer)) - (&pod), + (&(pod.offset)) - (&pod), + (&(pod.size)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod32), + }) + +_py_anon_pod32_dtype = _get__py_anon_pod32_dtype_offsets() + +cdef class _py_anon_pod32: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod32`. + + + .. seealso:: `cuda_bindings_driver__anon_pod32` + """ + cdef: + cuda_bindings_driver__anon_pod32 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod32)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod32") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod32 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod32 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod32 other_ + if not isinstance(other, _py_anon_pod32): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod32)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod32), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod32)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod32") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod32)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def layer(self): + """int: """ + return self._ptr[0].layer + + @layer.setter + def layer(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod32 instance is read-only") + self._ptr[0].layer = val + + @property + def offset(self): + """int: """ + return self._ptr[0].offset + + @offset.setter + def offset(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod32 instance is read-only") + self._ptr[0].offset = val + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod32 instance is read-only") + self._ptr[0].size = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod32 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod32), _py_anon_pod32) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod32 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod32_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod32_dtype", _py_anon_pod32_dtype, _py_anon_pod32) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod32 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod32 obj = _py_anon_pod32.__new__(_py_anon_pod32) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod32)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod32") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod32)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod33_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod33 pod + return _numpy.dtype({ + 'names': ['mem_handle'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.memHandle)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod33), + }) + +_py_anon_pod33_dtype = _get__py_anon_pod33_dtype_offsets() + +cdef class _py_anon_pod33: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod33`. + + + .. seealso:: `cuda_bindings_driver__anon_pod33` + """ + cdef: + cuda_bindings_driver__anon_pod33 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod33)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod33") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod33 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod33 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod33 other_ + if not isinstance(other, _py_anon_pod33): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod33)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod33), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod33)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod33") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod33)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def mem_handle(self): + """int: """ + return (self._ptr[0].memHandle) + + @mem_handle.setter + def mem_handle(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod33 instance is read-only") + self._ptr[0].memHandle = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod33 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod33), _py_anon_pod33) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod33 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod33_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod33_dtype", _py_anon_pod33_dtype, _py_anon_pod33) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod33 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod33 obj = _py_anon_pod33.__new__(_py_anon_pod33) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod33)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod33") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod33)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod35_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod35 pod + return _numpy.dtype({ + 'names': ['compression_type', 'gpu_direct_rdma_capable', 'usage', 'reserved'], + 'formats': [_numpy.uint8, _numpy.uint8, _numpy.uint16, (_numpy.uint8, 4)], + 'offsets': [ + (&(pod.compressionType)) - (&pod), + (&(pod.gpuDirectRDMACapable)) - (&pod), + (&(pod.usage)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod35), + }) + +_py_anon_pod35_dtype = _get__py_anon_pod35_dtype_offsets() + +cdef class _py_anon_pod35: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod35`. + + + .. seealso:: `cuda_bindings_driver__anon_pod35` + """ + cdef: + cuda_bindings_driver__anon_pod35 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod35)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod35") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod35 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod35 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod35 other_ + if not isinstance(other, _py_anon_pod35): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod35)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod35), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod35)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod35") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod35)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def compression_type(self): + """int: """ + return self._ptr[0].compressionType + + @compression_type.setter + def compression_type(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod35 instance is read-only") + self._ptr[0].compressionType = val + + @property + def gpu_direct_rdma_capable(self): + """int: """ + return self._ptr[0].gpuDirectRDMACapable + + @gpu_direct_rdma_capable.setter + def gpu_direct_rdma_capable(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod35 instance is read-only") + self._ptr[0].gpuDirectRDMACapable = val + + @property + def usage(self): + """int: """ + return self._ptr[0].usage + + @usage.setter + def usage(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod35 instance is read-only") + self._ptr[0].usage = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod35 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod35), _py_anon_pod35) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod35 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod35_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod35_dtype", _py_anon_pod35_dtype, _py_anon_pod35) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod35 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod35 obj = _py_anon_pod35.__new__(_py_anon_pod35) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod35)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod35") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod35)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_multicast_object_prop_v1_dtype_offsets(): + cdef CUmulticastObjectProp_v1 pod + return _numpy.dtype({ + 'names': ['num_devices', 'size_', 'handle_types', 'flags_'], + 'formats': [_numpy.uint32, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.numDevices)) - (&pod), + (&(pod.size)) - (&pod), + (&(pod.handleTypes)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUmulticastObjectProp_v1), + }) + +multicast_object_prop_v1_dtype = _get_multicast_object_prop_v1_dtype_offsets() + +cdef class MulticastObjectProp_v1: + """Empty-initialize an instance of `CUmulticastObjectProp_v1`. + + + .. seealso:: `CUmulticastObjectProp_v1` + """ + cdef: + CUmulticastObjectProp_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmulticastObjectProp_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MulticastObjectProp_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmulticastObjectProp_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MulticastObjectProp_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MulticastObjectProp_v1 other_ + if not isinstance(other, MulticastObjectProp_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmulticastObjectProp_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmulticastObjectProp_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmulticastObjectProp_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MulticastObjectProp_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmulticastObjectProp_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def num_devices(self): + """int: """ + return self._ptr[0].numDevices + + @num_devices.setter + def num_devices(self, val): + if self._readonly: + raise ValueError("This MulticastObjectProp_v1 instance is read-only") + self._ptr[0].numDevices = val + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This MulticastObjectProp_v1 instance is read-only") + self._ptr[0].size = val + + @property + def handle_types(self): + """int: """ + return self._ptr[0].handleTypes + + @handle_types.setter + def handle_types(self, val): + if self._readonly: + raise ValueError("This MulticastObjectProp_v1 instance is read-only") + self._ptr[0].handleTypes = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This MulticastObjectProp_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an MulticastObjectProp_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmulticastObjectProp_v1), MulticastObjectProp_v1) + + @staticmethod + def from_data(data): + """Create an MulticastObjectProp_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `multicast_object_prop_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "multicast_object_prop_v1_dtype", multicast_object_prop_v1_dtype, MulticastObjectProp_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MulticastObjectProp_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MulticastObjectProp_v1 obj = MulticastObjectProp_v1.__new__(MulticastObjectProp_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmulticastObjectProp_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MulticastObjectProp_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmulticastObjectProp_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_access_desc_v1_dtype_offsets(): + cdef CUmemAccessDesc_v1 pod + return _numpy.dtype({ + 'names': ['location', 'flags_'], + 'formats': [_numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.location)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUmemAccessDesc_v1), + }) + +mem_access_desc_v1_dtype = _get_mem_access_desc_v1_dtype_offsets() + +cdef class MemAccessDesc_v1: + """Empty-initialize an array of `CUmemAccessDesc_v1`. + The resulting object is of length `size` and of dtype `mem_access_desc_v1_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUmemAccessDesc_v1` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=mem_access_desc_v1_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUmemAccessDesc_v1), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUmemAccessDesc_v1) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.MemAccessDesc_v1_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.MemAccessDesc_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, MemAccessDesc_v1)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def location(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.location[0]) + return self._data.location + + @location.setter + def location(self, val): + self._data.location = val + + @property + def flags_(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.flags_[0]) + return self._data.flags_ + + @flags_.setter + def flags_(self, val): + self._data.flags_ = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return MemAccessDesc_v1.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == mem_access_desc_v1_dtype: + return MemAccessDesc_v1.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an MemAccessDesc_v1 instance with the memory from the given buffer.""" + return MemAccessDesc_v1.from_data(_numpy.frombuffer(buffer, dtype=mem_access_desc_v1_dtype)) + + @staticmethod + def from_data(data): + """Create an MemAccessDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `mem_access_desc_v1_dtype` holding the data. + """ + cdef MemAccessDesc_v1 obj = MemAccessDesc_v1.__new__(MemAccessDesc_v1) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != mem_access_desc_v1_dtype: + raise ValueError("data array must be of dtype mem_access_desc_v1_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an MemAccessDesc_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemAccessDesc_v1 obj = MemAccessDesc_v1.__new__(MemAccessDesc_v1) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUmemAccessDesc_v1) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=mem_access_desc_v1_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_graph_exec_update_result_info_v1_dtype_offsets(): + cdef CUgraphExecUpdateResultInfo_v1 pod + return _numpy.dtype({ + 'names': ['result', 'error_node', 'error_from_node'], + 'formats': [_numpy.int32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.result)) - (&pod), + (&(pod.errorNode)) - (&pod), + (&(pod.errorFromNode)) - (&pod), + ], + 'itemsize': sizeof(CUgraphExecUpdateResultInfo_v1), + }) + +graph_exec_update_result_info_v1_dtype = _get_graph_exec_update_result_info_v1_dtype_offsets() + +cdef class GraphExecUpdateResultInfo_v1: + """Empty-initialize an instance of `CUgraphExecUpdateResultInfo_v1`. + + + .. seealso:: `CUgraphExecUpdateResultInfo_v1` + """ + cdef: + CUgraphExecUpdateResultInfo_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUgraphExecUpdateResultInfo_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphExecUpdateResultInfo_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUgraphExecUpdateResultInfo_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.GraphExecUpdateResultInfo_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef GraphExecUpdateResultInfo_v1 other_ + if not isinstance(other, GraphExecUpdateResultInfo_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUgraphExecUpdateResultInfo_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUgraphExecUpdateResultInfo_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUgraphExecUpdateResultInfo_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphExecUpdateResultInfo_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUgraphExecUpdateResultInfo_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def result(self): + """int: """ + return (self._ptr[0].result) + + @result.setter + def result(self, val): + if self._readonly: + raise ValueError("This GraphExecUpdateResultInfo_v1 instance is read-only") + self._ptr[0].result = val + + @property + def error_node(self): + """int: """ + return (self._ptr[0].errorNode) + + @error_node.setter + def error_node(self, val): + if self._readonly: + raise ValueError("This GraphExecUpdateResultInfo_v1 instance is read-only") + self._ptr[0].errorNode = val + + @property + def error_from_node(self): + """int: """ + return (self._ptr[0].errorFromNode) + + @error_from_node.setter + def error_from_node(self, val): + if self._readonly: + raise ValueError("This GraphExecUpdateResultInfo_v1 instance is read-only") + self._ptr[0].errorFromNode = val + + @staticmethod + def from_buffer(buffer): + """Create an GraphExecUpdateResultInfo_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUgraphExecUpdateResultInfo_v1), GraphExecUpdateResultInfo_v1) + + @staticmethod + def from_data(data): + """Create an GraphExecUpdateResultInfo_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `graph_exec_update_result_info_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "graph_exec_update_result_info_v1_dtype", graph_exec_update_result_info_v1_dtype, GraphExecUpdateResultInfo_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an GraphExecUpdateResultInfo_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef GraphExecUpdateResultInfo_v1 obj = GraphExecUpdateResultInfo_v1.__new__(GraphExecUpdateResultInfo_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUgraphExecUpdateResultInfo_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating GraphExecUpdateResultInfo_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUgraphExecUpdateResultInfo_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_pool_props_v1_dtype_offsets(): + cdef CUmemPoolProps_v1 pod + return _numpy.dtype({ + 'names': ['alloc_type', 'handle_types', 'location', 'win32security_attributes', 'max_size', 'usage', 'reserved'], + 'formats': [_numpy.int32, _numpy.int32, _numpy.int32, _numpy.intp, _numpy.uint64, _numpy.uint16, (_numpy.uint8, 54)], + 'offsets': [ + (&(pod.allocType)) - (&pod), + (&(pod.handleTypes)) - (&pod), + (&(pod.location)) - (&pod), + (&(pod.win32SecurityAttributes)) - (&pod), + (&(pod.maxSize)) - (&pod), + (&(pod.usage)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUmemPoolProps_v1), + }) + +mem_pool_props_v1_dtype = _get_mem_pool_props_v1_dtype_offsets() + +cdef class MemPoolProps_v1: + """Empty-initialize an instance of `CUmemPoolProps_v1`. + + + .. seealso:: `CUmemPoolProps_v1` + """ + cdef: + CUmemPoolProps_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemPoolProps_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemPoolProps_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemPoolProps_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemPoolProps_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemPoolProps_v1 other_ + if not isinstance(other, MemPoolProps_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemPoolProps_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemPoolProps_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemPoolProps_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemPoolProps_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemPoolProps_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def location(self): + """MemLocation_v1: """ + return MemLocation_v1.from_ptr( + &(self._ptr[0].location), + readonly=self._readonly, + owner=self, + ) + + @location.setter + def location(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + cdef MemLocation_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].location), (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @property + def alloc_type(self): + """int: """ + return (self._ptr[0].allocType) + + @alloc_type.setter + def alloc_type(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + self._ptr[0].allocType = val + + @property + def handle_types(self): + """int: """ + return (self._ptr[0].handleTypes) + + @handle_types.setter + def handle_types(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + self._ptr[0].handleTypes = val + + @property + def win32security_attributes(self): + """int: """ + return (self._ptr[0].win32SecurityAttributes) + + @win32security_attributes.setter + def win32security_attributes(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + self._ptr[0].win32SecurityAttributes = val + + @property + def max_size(self): + """int: """ + return self._ptr[0].maxSize + + @max_size.setter + def max_size(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + self._ptr[0].maxSize = val + + @property + def usage(self): + """int: """ + return self._ptr[0].usage + + @usage.setter + def usage(self, val): + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + self._ptr[0].usage = val + + @staticmethod + def from_buffer(buffer): + """Create an MemPoolProps_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemPoolProps_v1), MemPoolProps_v1) + + @staticmethod + def from_data(data): + """Create an MemPoolProps_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_pool_props_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_pool_props_v1_dtype", mem_pool_props_v1_dtype, MemPoolProps_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemPoolProps_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemPoolProps_v1 obj = MemPoolProps_v1.__new__(MemPoolProps_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemPoolProps_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemPoolProps_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemPoolProps_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_pool_ptr_export_data_v1_dtype_offsets(): + cdef CUmemPoolPtrExportData_v1 pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.uint8, 64)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUmemPoolPtrExportData_v1), + }) + +mem_pool_ptr_export_data_v1_dtype = _get_mem_pool_ptr_export_data_v1_dtype_offsets() + +cdef class MemPoolPtrExportData_v1: + """Empty-initialize an instance of `CUmemPoolPtrExportData_v1`. + + + .. seealso:: `CUmemPoolPtrExportData_v1` + """ + cdef: + CUmemPoolPtrExportData_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemPoolPtrExportData_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemPoolPtrExportData_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemPoolPtrExportData_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemPoolPtrExportData_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemPoolPtrExportData_v1 other_ + if not isinstance(other, MemPoolPtrExportData_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemPoolPtrExportData_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemPoolPtrExportData_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemPoolPtrExportData_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemPoolPtrExportData_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemPoolPtrExportData_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an MemPoolPtrExportData_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemPoolPtrExportData_v1), MemPoolPtrExportData_v1) + + @staticmethod + def from_data(data): + """Create an MemPoolPtrExportData_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_pool_ptr_export_data_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_pool_ptr_export_data_v1_dtype", mem_pool_ptr_export_data_v1_dtype, MemPoolPtrExportData_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemPoolPtrExportData_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemPoolPtrExportData_v1 obj = MemPoolPtrExportData_v1.__new__(MemPoolPtrExportData_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemPoolPtrExportData_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemPoolPtrExportData_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemPoolPtrExportData_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_memcpy_attributes_v1_dtype_offsets(): + cdef CUmemcpyAttributes_v1 pod + return _numpy.dtype({ + 'names': ['src_access_order', 'src_loc_hint', 'dst_loc_hint', 'flags_'], + 'formats': [_numpy.int32, _numpy.int32, _numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.srcAccessOrder)) - (&pod), + (&(pod.srcLocHint)) - (&pod), + (&(pod.dstLocHint)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUmemcpyAttributes_v1), + }) + +memcpy_attributes_v1_dtype = _get_memcpy_attributes_v1_dtype_offsets() + +cdef class MemcpyAttributes_v1: + """Empty-initialize an instance of `CUmemcpyAttributes_v1`. + + + .. seealso:: `CUmemcpyAttributes_v1` + """ + cdef: + CUmemcpyAttributes_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemcpyAttributes_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemcpyAttributes_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemcpyAttributes_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemcpyAttributes_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemcpyAttributes_v1 other_ + if not isinstance(other, MemcpyAttributes_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemcpyAttributes_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemcpyAttributes_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemcpyAttributes_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemcpyAttributes_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemcpyAttributes_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def src_loc_hint(self): + """MemLocation_v1: """ + return MemLocation_v1.from_ptr( + &(self._ptr[0].srcLocHint), + readonly=self._readonly, + owner=self, + ) + + @src_loc_hint.setter + def src_loc_hint(self, val): + if self._readonly: + raise ValueError("This MemcpyAttributes_v1 instance is read-only") + cdef MemLocation_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].srcLocHint), (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @property + def dst_loc_hint(self): + """MemLocation_v1: """ + return MemLocation_v1.from_ptr( + &(self._ptr[0].dstLocHint), + readonly=self._readonly, + owner=self, + ) + + @dst_loc_hint.setter + def dst_loc_hint(self, val): + if self._readonly: + raise ValueError("This MemcpyAttributes_v1 instance is read-only") + cdef MemLocation_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].dstLocHint), (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @property + def src_access_order(self): + """int: """ + return (self._ptr[0].srcAccessOrder) + + @src_access_order.setter + def src_access_order(self, val): + if self._readonly: + raise ValueError("This MemcpyAttributes_v1 instance is read-only") + self._ptr[0].srcAccessOrder = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This MemcpyAttributes_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an MemcpyAttributes_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemcpyAttributes_v1), MemcpyAttributes_v1) + + @staticmethod + def from_data(data): + """Create an MemcpyAttributes_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `memcpy_attributes_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "memcpy_attributes_v1_dtype", memcpy_attributes_v1_dtype, MemcpyAttributes_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemcpyAttributes_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemcpyAttributes_v1 obj = MemcpyAttributes_v1.__new__(MemcpyAttributes_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemcpyAttributes_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemcpyAttributes_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemcpyAttributes_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_offset3d_v1_dtype_offsets(): + cdef CUoffset3D_v1 pod + return _numpy.dtype({ + 'names': ['x', 'y', 'z'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.x)) - (&pod), + (&(pod.y)) - (&pod), + (&(pod.z)) - (&pod), + ], + 'itemsize': sizeof(CUoffset3D_v1), + }) + +offset3d_v1_dtype = _get_offset3d_v1_dtype_offsets() + +cdef class Offset3D_v1: + """Empty-initialize an instance of `CUoffset3D_v1`. + + + .. seealso:: `CUoffset3D_v1` + """ + cdef: + CUoffset3D_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUoffset3D_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Offset3D_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUoffset3D_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Offset3D_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Offset3D_v1 other_ + if not isinstance(other, Offset3D_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUoffset3D_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUoffset3D_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUoffset3D_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Offset3D_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUoffset3D_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def x(self): + """int: """ + return self._ptr[0].x + + @x.setter + def x(self, val): + if self._readonly: + raise ValueError("This Offset3D_v1 instance is read-only") + self._ptr[0].x = val + + @property + def y(self): + """int: """ + return self._ptr[0].y + + @y.setter + def y(self, val): + if self._readonly: + raise ValueError("This Offset3D_v1 instance is read-only") + self._ptr[0].y = val + + @property + def z(self): + """int: """ + return self._ptr[0].z + + @z.setter + def z(self, val): + if self._readonly: + raise ValueError("This Offset3D_v1 instance is read-only") + self._ptr[0].z = val + + @staticmethod + def from_buffer(buffer): + """Create an Offset3D_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUoffset3D_v1), Offset3D_v1) + + @staticmethod + def from_data(data): + """Create an Offset3D_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `offset3d_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "offset3d_v1_dtype", offset3d_v1_dtype, Offset3D_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Offset3D_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Offset3D_v1 obj = Offset3D_v1.__new__(Offset3D_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUoffset3D_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Offset3D_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUoffset3D_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_extent3d_v1_dtype_offsets(): + cdef CUextent3D_v1 pod + return _numpy.dtype({ + 'names': ['width', 'height', 'depth'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + (&(pod.depth)) - (&pod), + ], + 'itemsize': sizeof(CUextent3D_v1), + }) + +extent3d_v1_dtype = _get_extent3d_v1_dtype_offsets() + +cdef class Extent3D_v1: + """Empty-initialize an instance of `CUextent3D_v1`. + + + .. seealso:: `CUextent3D_v1` + """ + cdef: + CUextent3D_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUextent3D_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Extent3D_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUextent3D_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.Extent3D_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef Extent3D_v1 other_ + if not isinstance(other, Extent3D_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUextent3D_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUextent3D_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUextent3D_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating Extent3D_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUextent3D_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def width(self): + """int: """ + return self._ptr[0].width + + @width.setter + def width(self, val): + if self._readonly: + raise ValueError("This Extent3D_v1 instance is read-only") + self._ptr[0].width = val + + @property + def height(self): + """int: """ + return self._ptr[0].height + + @height.setter + def height(self, val): + if self._readonly: + raise ValueError("This Extent3D_v1 instance is read-only") + self._ptr[0].height = val + + @property + def depth(self): + """int: """ + return self._ptr[0].depth + + @depth.setter + def depth(self, val): + if self._readonly: + raise ValueError("This Extent3D_v1 instance is read-only") + self._ptr[0].depth = val + + @staticmethod + def from_buffer(buffer): + """Create an Extent3D_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUextent3D_v1), Extent3D_v1) + + @staticmethod + def from_data(data): + """Create an Extent3D_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `extent3d_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "extent3d_v1_dtype", extent3d_v1_dtype, Extent3D_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an Extent3D_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef Extent3D_v1 obj = Extent3D_v1.__new__(Extent3D_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUextent3D_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating Extent3D_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUextent3D_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_alloc_node_params_v1_dtype_offsets(): + cdef CUDA_MEM_ALLOC_NODE_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['pool_props', 'access_descs', 'access_desc_count', 'bytesize', 'dptr'], + 'formats': [mem_pool_props_v1_dtype, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.poolProps)) - (&pod), + (&(pod.accessDescs)) - (&pod), + (&(pod.accessDescCount)) - (&pod), + (&(pod.bytesize)) - (&pod), + (&(pod.dptr)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1), + }) + +mem_alloc_node_params_v1_dtype = _get_mem_alloc_node_params_v1_dtype_offsets() + +cdef class MemAllocNodeParams_v1: + """Empty-initialize an instance of `CUDA_MEM_ALLOC_NODE_PARAMS_v1`. + + + .. seealso:: `CUDA_MEM_ALLOC_NODE_PARAMS_v1` + """ + cdef: + CUDA_MEM_ALLOC_NODE_PARAMS_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEM_ALLOC_NODE_PARAMS_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemAllocNodeParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemAllocNodeParams_v1 other_ + if not isinstance(other, MemAllocNodeParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def pool_props(self): + """MemPoolProps_v1: """ + return MemPoolProps_v1.from_ptr( + &(self._ptr[0].poolProps), + readonly=self._readonly, + owner=self, + ) + + @pool_props.setter + def pool_props(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + cdef MemPoolProps_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].poolProps), (val_._get_ptr()), sizeof(CUmemPoolProps) * 1) + + @property + def access_descs(self): + """int: """ + return (self._ptr[0].accessDescs) + + @access_descs.setter + def access_descs(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + self._ptr[0].accessDescs = val + + @property + def access_desc_count(self): + """int: """ + return self._ptr[0].accessDescCount + + @access_desc_count.setter + def access_desc_count(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + self._ptr[0].accessDescCount = val + + @property + def bytesize(self): + """int: """ + return self._ptr[0].bytesize + + @bytesize.setter + def bytesize(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + self._ptr[0].bytesize = val + + @property + def dptr(self): + """int: """ + return (self._ptr[0].dptr) + + @dptr.setter + def dptr(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + self._ptr[0].dptr = val + + @staticmethod + def from_buffer(buffer): + """Create an MemAllocNodeParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1), MemAllocNodeParams_v1) + + @staticmethod + def from_data(data): + """Create an MemAllocNodeParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_alloc_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_alloc_node_params_v1_dtype", mem_alloc_node_params_v1_dtype, MemAllocNodeParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemAllocNodeParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemAllocNodeParams_v1 obj = MemAllocNodeParams_v1.__new__(MemAllocNodeParams_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_alloc_node_params_v2_dtype_offsets(): + cdef CUDA_MEM_ALLOC_NODE_PARAMS_v2 pod + return _numpy.dtype({ + 'names': ['pool_props', 'access_descs', 'access_desc_count', 'bytesize', 'dptr'], + 'formats': [mem_pool_props_v1_dtype, _numpy.intp, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.poolProps)) - (&pod), + (&(pod.accessDescs)) - (&pod), + (&(pod.accessDescCount)) - (&pod), + (&(pod.bytesize)) - (&pod), + (&(pod.dptr)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2), + }) + +mem_alloc_node_params_v2_dtype = _get_mem_alloc_node_params_v2_dtype_offsets() + +cdef class MemAllocNodeParams_v2: + """Empty-initialize an instance of `CUDA_MEM_ALLOC_NODE_PARAMS_v2`. + + + .. seealso:: `CUDA_MEM_ALLOC_NODE_PARAMS_v2` + """ + cdef: + CUDA_MEM_ALLOC_NODE_PARAMS_v2 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v2") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEM_ALLOC_NODE_PARAMS_v2 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemAllocNodeParams_v2 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemAllocNodeParams_v2 other_ + if not isinstance(other, MemAllocNodeParams_v2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v2") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def pool_props(self): + """MemPoolProps_v1: """ + return MemPoolProps_v1.from_ptr( + &(self._ptr[0].poolProps), + readonly=self._readonly, + owner=self, + ) + + @pool_props.setter + def pool_props(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + cdef MemPoolProps_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].poolProps), (val_._get_ptr()), sizeof(CUmemPoolProps) * 1) + + @property + def access_descs(self): + """int: """ + return (self._ptr[0].accessDescs) + + @access_descs.setter + def access_descs(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + self._ptr[0].accessDescs = val + + @property + def access_desc_count(self): + """int: """ + return self._ptr[0].accessDescCount + + @access_desc_count.setter + def access_desc_count(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + self._ptr[0].accessDescCount = val + + @property + def bytesize(self): + """int: """ + return self._ptr[0].bytesize + + @bytesize.setter + def bytesize(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + self._ptr[0].bytesize = val + + @property + def dptr(self): + """int: """ + return (self._ptr[0].dptr) + + @dptr.setter + def dptr(self, val): + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + self._ptr[0].dptr = val + + @staticmethod + def from_buffer(buffer): + """Create an MemAllocNodeParams_v2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2), MemAllocNodeParams_v2) + + @staticmethod + def from_data(data): + """Create an MemAllocNodeParams_v2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_alloc_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_alloc_node_params_v2_dtype", mem_alloc_node_params_v2_dtype, MemAllocNodeParams_v2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemAllocNodeParams_v2 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemAllocNodeParams_v2 obj = MemAllocNodeParams_v2.__new__(MemAllocNodeParams_v2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemAllocNodeParams_v2") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_free_node_params_dtype_offsets(): + cdef CUDA_MEM_FREE_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['dptr'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.dptr)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEM_FREE_NODE_PARAMS), + }) + +mem_free_node_params_dtype = _get_mem_free_node_params_dtype_offsets() + +cdef class MemFreeNodeParams: + """Empty-initialize an instance of `CUDA_MEM_FREE_NODE_PARAMS`. + + + .. seealso:: `CUDA_MEM_FREE_NODE_PARAMS` + """ + cdef: + CUDA_MEM_FREE_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemFreeNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEM_FREE_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemFreeNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemFreeNodeParams other_ + if not isinstance(other, MemFreeNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEM_FREE_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEM_FREE_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemFreeNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def dptr(self): + """int: """ + return (self._ptr[0].dptr) + + @dptr.setter + def dptr(self, val): + if self._readonly: + raise ValueError("This MemFreeNodeParams instance is read-only") + self._ptr[0].dptr = val + + @staticmethod + def from_buffer(buffer): + """Create an MemFreeNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEM_FREE_NODE_PARAMS), MemFreeNodeParams) + + @staticmethod + def from_data(data): + """Create an MemFreeNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_free_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_free_node_params_dtype", mem_free_node_params_dtype, MemFreeNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemFreeNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemFreeNodeParams obj = MemFreeNodeParams.__new__(MemFreeNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemFreeNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_child_graph_node_params_dtype_offsets(): + cdef CUDA_CHILD_GRAPH_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['graph', 'ownership'], + 'formats': [_numpy.intp, _numpy.int32], + 'offsets': [ + (&(pod.graph)) - (&pod), + (&(pod.ownership)) - (&pod), + ], + 'itemsize': sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS), + }) + +child_graph_node_params_dtype = _get_child_graph_node_params_dtype_offsets() + +cdef class ChildGraphNodeParams: + """Empty-initialize an instance of `CUDA_CHILD_GRAPH_NODE_PARAMS`. + + + .. seealso:: `CUDA_CHILD_GRAPH_NODE_PARAMS` + """ + cdef: + CUDA_CHILD_GRAPH_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating ChildGraphNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_CHILD_GRAPH_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ChildGraphNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ChildGraphNodeParams other_ + if not isinstance(other, ChildGraphNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating ChildGraphNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def graph(self): + """int: """ + return (self._ptr[0].graph) + + @graph.setter + def graph(self, val): + if self._readonly: + raise ValueError("This ChildGraphNodeParams instance is read-only") + self._ptr[0].graph = val + + @property + def ownership(self): + """int: """ + return (self._ptr[0].ownership) + + @ownership.setter + def ownership(self, val): + if self._readonly: + raise ValueError("This ChildGraphNodeParams instance is read-only") + self._ptr[0].ownership = val + + @staticmethod + def from_buffer(buffer): + """Create an ChildGraphNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS), ChildGraphNodeParams) + + @staticmethod + def from_data(data): + """Create an ChildGraphNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `child_graph_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "child_graph_node_params_dtype", child_graph_node_params_dtype, ChildGraphNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ChildGraphNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ChildGraphNodeParams obj = ChildGraphNodeParams.__new__(ChildGraphNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ChildGraphNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_event_record_node_params_dtype_offsets(): + cdef CUDA_EVENT_RECORD_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['event'], + 'formats': [_numpy.intp], + 'offsets': [ + (&(pod.event)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EVENT_RECORD_NODE_PARAMS), + }) + +event_record_node_params_dtype = _get_event_record_node_params_dtype_offsets() + +cdef class EventRecordNodeParams: + """Empty-initialize an instance of `CUDA_EVENT_RECORD_NODE_PARAMS`. + + + .. seealso:: `CUDA_EVENT_RECORD_NODE_PARAMS` + """ + cdef: + CUDA_EVENT_RECORD_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating EventRecordNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EVENT_RECORD_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.EventRecordNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef EventRecordNodeParams other_ + if not isinstance(other, EventRecordNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating EventRecordNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def event(self): + """int: """ + return (self._ptr[0].event) + + @event.setter + def event(self, val): + if self._readonly: + raise ValueError("This EventRecordNodeParams instance is read-only") + self._ptr[0].event = val + + @staticmethod + def from_buffer(buffer): + """Create an EventRecordNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS), EventRecordNodeParams) + + @staticmethod + def from_data(data): + """Create an EventRecordNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `event_record_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "event_record_node_params_dtype", event_record_node_params_dtype, EventRecordNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an EventRecordNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef EventRecordNodeParams obj = EventRecordNodeParams.__new__(EventRecordNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating EventRecordNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_event_wait_node_params_dtype_offsets(): + cdef CUDA_EVENT_WAIT_NODE_PARAMS pod + return _numpy.dtype({ + 'names': ['event'], + 'formats': [_numpy.intp], + 'offsets': [ + (&(pod.event)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EVENT_WAIT_NODE_PARAMS), + }) + +event_wait_node_params_dtype = _get_event_wait_node_params_dtype_offsets() + +cdef class EventWaitNodeParams: + """Empty-initialize an instance of `CUDA_EVENT_WAIT_NODE_PARAMS`. + + + .. seealso:: `CUDA_EVENT_WAIT_NODE_PARAMS` + """ + cdef: + CUDA_EVENT_WAIT_NODE_PARAMS *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating EventWaitNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EVENT_WAIT_NODE_PARAMS *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.EventWaitNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef EventWaitNodeParams other_ + if not isinstance(other, EventWaitNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + if self._ptr == NULL: + raise MemoryError("Error allocating EventWaitNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def event(self): + """int: """ + return (self._ptr[0].event) + + @event.setter + def event(self, val): + if self._readonly: + raise ValueError("This EventWaitNodeParams instance is read-only") + self._ptr[0].event = val + + @staticmethod + def from_buffer(buffer): + """Create an EventWaitNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS), EventWaitNodeParams) + + @staticmethod + def from_data(data): + """Create an EventWaitNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `event_wait_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "event_wait_node_params_dtype", event_wait_node_params_dtype, EventWaitNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an EventWaitNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef EventWaitNodeParams obj = EventWaitNodeParams.__new__(EventWaitNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + if obj._ptr == NULL: + raise MemoryError("Error allocating EventWaitNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_lock_args_dtype_offsets(): + cdef CUcheckpointLockArgs pod + return _numpy.dtype({ + 'names': ['timeout_ms', 'reserved0', 'reserved1'], + 'formats': [_numpy.uint32, _numpy.uint32, (_numpy.uint64, 7)], + 'offsets': [ + (&(pod.timeoutMs)) - (&pod), + (&(pod.reserved0)) - (&pod), + (&(pod.reserved1)) - (&pod), + ], + 'itemsize': sizeof(CUcheckpointLockArgs), + }) + +checkpoint_lock_args_dtype = _get_checkpoint_lock_args_dtype_offsets() + +cdef class CheckpointLockArgs: + """Empty-initialize an instance of `CUcheckpointLockArgs`. + + + .. seealso:: `CUcheckpointLockArgs` + """ + cdef: + CUcheckpointLockArgs *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUcheckpointLockArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointLockArgs") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUcheckpointLockArgs *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CheckpointLockArgs object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CheckpointLockArgs other_ + if not isinstance(other, CheckpointLockArgs): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUcheckpointLockArgs)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUcheckpointLockArgs), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUcheckpointLockArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointLockArgs") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUcheckpointLockArgs)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def timeout_ms(self): + """int: """ + return self._ptr[0].timeoutMs + + @timeout_ms.setter + def timeout_ms(self, val): + if self._readonly: + raise ValueError("This CheckpointLockArgs instance is read-only") + self._ptr[0].timeoutMs = val + + @staticmethod + def from_buffer(buffer): + """Create an CheckpointLockArgs instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUcheckpointLockArgs), CheckpointLockArgs) + + @staticmethod + def from_data(data): + """Create an CheckpointLockArgs instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `checkpoint_lock_args_dtype` holding the data. + """ + return _cyb_from_data(data, "checkpoint_lock_args_dtype", checkpoint_lock_args_dtype, CheckpointLockArgs) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CheckpointLockArgs instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CheckpointLockArgs obj = CheckpointLockArgs.__new__(CheckpointLockArgs) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUcheckpointLockArgs)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CheckpointLockArgs") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUcheckpointLockArgs)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_checkpoint_args_dtype_offsets(): + cdef CUcheckpointCheckpointArgs pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.uint64, 8)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUcheckpointCheckpointArgs), + }) + +checkpoint_checkpoint_args_dtype = _get_checkpoint_checkpoint_args_dtype_offsets() + +cdef class CheckpointCheckpointArgs: + """Empty-initialize an instance of `CUcheckpointCheckpointArgs`. + + + .. seealso:: `CUcheckpointCheckpointArgs` + """ + cdef: + CUcheckpointCheckpointArgs *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUcheckpointCheckpointArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointCheckpointArgs") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUcheckpointCheckpointArgs *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CheckpointCheckpointArgs object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CheckpointCheckpointArgs other_ + if not isinstance(other, CheckpointCheckpointArgs): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUcheckpointCheckpointArgs)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUcheckpointCheckpointArgs), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUcheckpointCheckpointArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointCheckpointArgs") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUcheckpointCheckpointArgs)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an CheckpointCheckpointArgs instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUcheckpointCheckpointArgs), CheckpointCheckpointArgs) + + @staticmethod + def from_data(data): + """Create an CheckpointCheckpointArgs instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `checkpoint_checkpoint_args_dtype` holding the data. + """ + return _cyb_from_data(data, "checkpoint_checkpoint_args_dtype", checkpoint_checkpoint_args_dtype, CheckpointCheckpointArgs) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CheckpointCheckpointArgs instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CheckpointCheckpointArgs obj = CheckpointCheckpointArgs.__new__(CheckpointCheckpointArgs) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUcheckpointCheckpointArgs)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CheckpointCheckpointArgs") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUcheckpointCheckpointArgs)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_unlock_args_dtype_offsets(): + cdef CUcheckpointUnlockArgs pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.uint64, 8)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUcheckpointUnlockArgs), + }) + +checkpoint_unlock_args_dtype = _get_checkpoint_unlock_args_dtype_offsets() + +cdef class CheckpointUnlockArgs: + """Empty-initialize an instance of `CUcheckpointUnlockArgs`. + + + .. seealso:: `CUcheckpointUnlockArgs` + """ + cdef: + CUcheckpointUnlockArgs *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUcheckpointUnlockArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointUnlockArgs") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUcheckpointUnlockArgs *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CheckpointUnlockArgs object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CheckpointUnlockArgs other_ + if not isinstance(other, CheckpointUnlockArgs): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUcheckpointUnlockArgs)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUcheckpointUnlockArgs), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUcheckpointUnlockArgs)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointUnlockArgs") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUcheckpointUnlockArgs)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an CheckpointUnlockArgs instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUcheckpointUnlockArgs), CheckpointUnlockArgs) + + @staticmethod + def from_data(data): + """Create an CheckpointUnlockArgs instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `checkpoint_unlock_args_dtype` holding the data. + """ + return _cyb_from_data(data, "checkpoint_unlock_args_dtype", checkpoint_unlock_args_dtype, CheckpointUnlockArgs) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CheckpointUnlockArgs instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CheckpointUnlockArgs obj = CheckpointUnlockArgs.__new__(CheckpointUnlockArgs) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUcheckpointUnlockArgs)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CheckpointUnlockArgs") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUcheckpointUnlockArgs)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_decompress_params_dtype_offsets(): + cdef CUmemDecompressParams pod + return _numpy.dtype({ + 'names': ['src_num_bytes', 'dst_num_bytes', 'dst_act_bytes', 'src', 'dst', 'algo', 'padding'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.intp, _numpy.intp, _numpy.intp, _numpy.int32, (_numpy.uint8, 20)], + 'offsets': [ + (&(pod.srcNumBytes)) - (&pod), + (&(pod.dstNumBytes)) - (&pod), + (&(pod.dstActBytes)) - (&pod), + (&(pod.src)) - (&pod), + (&(pod.dst)) - (&pod), + (&(pod.algo)) - (&pod), + (&(pod.padding)) - (&pod), + ], + 'itemsize': sizeof(CUmemDecompressParams), + }) + +mem_decompress_params_dtype = _get_mem_decompress_params_dtype_offsets() + +cdef class MemDecompressParams: + """Empty-initialize an instance of `CUmemDecompressParams`. + + + .. seealso:: `CUmemDecompressParams` + """ + cdef: + CUmemDecompressParams *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemDecompressParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemDecompressParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemDecompressParams *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemDecompressParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemDecompressParams other_ + if not isinstance(other, MemDecompressParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemDecompressParams)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemDecompressParams), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemDecompressParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemDecompressParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemDecompressParams)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def src_num_bytes(self): + """int: """ + return self._ptr[0].srcNumBytes + + @src_num_bytes.setter + def src_num_bytes(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].srcNumBytes = val + + @property + def dst_num_bytes(self): + """int: """ + return self._ptr[0].dstNumBytes + + @dst_num_bytes.setter + def dst_num_bytes(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].dstNumBytes = val + + @property + def dst_act_bytes(self): + """int: """ + return (self._ptr[0].dstActBytes) + + @dst_act_bytes.setter + def dst_act_bytes(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].dstActBytes = val + + @property + def src(self): + """int: """ + return (self._ptr[0].src) + + @src.setter + def src(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].src = val + + @property + def dst(self): + """int: """ + return (self._ptr[0].dst) + + @dst.setter + def dst(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].dst = val + + @property + def algo(self): + """int: """ + return (self._ptr[0].algo) + + @algo.setter + def algo(self, val): + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + self._ptr[0].algo = val + + @staticmethod + def from_buffer(buffer): + """Create an MemDecompressParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemDecompressParams), MemDecompressParams) + + @staticmethod + def from_data(data): + """Create an MemDecompressParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_decompress_params_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_decompress_params_dtype", mem_decompress_params_dtype, MemDecompressParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemDecompressParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemDecompressParams obj = MemDecompressParams.__new__(MemDecompressParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemDecompressParams)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemDecompressParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemDecompressParams)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_dev_sm_resource_dtype_offsets(): + cdef CUdevSmResource pod + return _numpy.dtype({ + 'names': ['sm_count', 'min_sm_partition_size', 'sm_coscheduled_alignment', 'flags_'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.smCount)) - (&pod), + (&(pod.minSmPartitionSize)) - (&pod), + (&(pod.smCoscheduledAlignment)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUdevSmResource), + }) + +dev_sm_resource_dtype = _get_dev_sm_resource_dtype_offsets() + +cdef class DevSmResource: + """Empty-initialize an instance of `CUdevSmResource`. + + + .. seealso:: `CUdevSmResource` + """ + cdef: + CUdevSmResource *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevSmResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevSmResource") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUdevSmResource *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.DevSmResource object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef DevSmResource other_ + if not isinstance(other, DevSmResource): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUdevSmResource)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUdevSmResource), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUdevSmResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevSmResource") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUdevSmResource)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def sm_count(self): + """int: """ + return self._ptr[0].smCount + + @sm_count.setter + def sm_count(self, val): + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + self._ptr[0].smCount = val + + @property + def min_sm_partition_size(self): + """int: """ + return self._ptr[0].minSmPartitionSize + + @min_sm_partition_size.setter + def min_sm_partition_size(self, val): + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + self._ptr[0].minSmPartitionSize = val + + @property + def sm_coscheduled_alignment(self): + """int: """ + return self._ptr[0].smCoscheduledAlignment + + @sm_coscheduled_alignment.setter + def sm_coscheduled_alignment(self, val): + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + self._ptr[0].smCoscheduledAlignment = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an DevSmResource instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUdevSmResource), DevSmResource) + + @staticmethod + def from_data(data): + """Create an DevSmResource instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `dev_sm_resource_dtype` holding the data. + """ + return _cyb_from_data(data, "dev_sm_resource_dtype", dev_sm_resource_dtype, DevSmResource) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an DevSmResource instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef DevSmResource obj = DevSmResource.__new__(DevSmResource) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUdevSmResource)) + if obj._ptr == NULL: + raise MemoryError("Error allocating DevSmResource") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUdevSmResource)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_dev_workqueue_config_resource_dtype_offsets(): + cdef CUdevWorkqueueConfigResource pod + return _numpy.dtype({ + 'names': ['device_', 'wq_concurrency_limit', 'sharing_scope'], + 'formats': [_numpy.int32, _numpy.uint32, _numpy.int32], + 'offsets': [ + (&(pod.device)) - (&pod), + (&(pod.wqConcurrencyLimit)) - (&pod), + (&(pod.sharingScope)) - (&pod), + ], + 'itemsize': sizeof(CUdevWorkqueueConfigResource), + }) + +dev_workqueue_config_resource_dtype = _get_dev_workqueue_config_resource_dtype_offsets() + +cdef class DevWorkqueueConfigResource: + """Empty-initialize an instance of `CUdevWorkqueueConfigResource`. + + + .. seealso:: `CUdevWorkqueueConfigResource` + """ + cdef: + CUdevWorkqueueConfigResource *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevWorkqueueConfigResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueConfigResource") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUdevWorkqueueConfigResource *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.DevWorkqueueConfigResource object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef DevWorkqueueConfigResource other_ + if not isinstance(other, DevWorkqueueConfigResource): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUdevWorkqueueConfigResource)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUdevWorkqueueConfigResource), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUdevWorkqueueConfigResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueConfigResource") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUdevWorkqueueConfigResource)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def device_(self): + """int: """ + return (self._ptr[0].device) + + @device_.setter + def device_(self, val): + if self._readonly: + raise ValueError("This DevWorkqueueConfigResource instance is read-only") + self._ptr[0].device = val + + @property + def wq_concurrency_limit(self): + """int: """ + return self._ptr[0].wqConcurrencyLimit + + @wq_concurrency_limit.setter + def wq_concurrency_limit(self, val): + if self._readonly: + raise ValueError("This DevWorkqueueConfigResource instance is read-only") + self._ptr[0].wqConcurrencyLimit = val + + @property + def sharing_scope(self): + """int: """ + return (self._ptr[0].sharingScope) + + @sharing_scope.setter + def sharing_scope(self, val): + if self._readonly: + raise ValueError("This DevWorkqueueConfigResource instance is read-only") + self._ptr[0].sharingScope = val + + @staticmethod + def from_buffer(buffer): + """Create an DevWorkqueueConfigResource instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUdevWorkqueueConfigResource), DevWorkqueueConfigResource) + + @staticmethod + def from_data(data): + """Create an DevWorkqueueConfigResource instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `dev_workqueue_config_resource_dtype` holding the data. + """ + return _cyb_from_data(data, "dev_workqueue_config_resource_dtype", dev_workqueue_config_resource_dtype, DevWorkqueueConfigResource) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an DevWorkqueueConfigResource instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef DevWorkqueueConfigResource obj = DevWorkqueueConfigResource.__new__(DevWorkqueueConfigResource) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUdevWorkqueueConfigResource)) + if obj._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueConfigResource") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUdevWorkqueueConfigResource)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_dev_workqueue_resource_dtype_offsets(): + cdef CUdevWorkqueueResource pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.uint8, 40)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUdevWorkqueueResource), + }) + +dev_workqueue_resource_dtype = _get_dev_workqueue_resource_dtype_offsets() + +cdef class DevWorkqueueResource: + """Empty-initialize an instance of `CUdevWorkqueueResource`. + + + .. seealso:: `CUdevWorkqueueResource` + """ + cdef: + CUdevWorkqueueResource *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevWorkqueueResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueResource") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUdevWorkqueueResource *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.DevWorkqueueResource object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef DevWorkqueueResource other_ + if not isinstance(other, DevWorkqueueResource): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUdevWorkqueueResource)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUdevWorkqueueResource), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUdevWorkqueueResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueResource") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUdevWorkqueueResource)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an DevWorkqueueResource instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUdevWorkqueueResource), DevWorkqueueResource) + + @staticmethod + def from_data(data): + """Create an DevWorkqueueResource instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `dev_workqueue_resource_dtype` holding the data. + """ + return _cyb_from_data(data, "dev_workqueue_resource_dtype", dev_workqueue_resource_dtype, DevWorkqueueResource) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an DevWorkqueueResource instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef DevWorkqueueResource obj = DevWorkqueueResource.__new__(DevWorkqueueResource) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUdevWorkqueueResource)) + if obj._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueResource") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUdevWorkqueueResource)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__dev_sm_resource_group_params_dtype_offsets(): + cdef CU_DEV_SM_RESOURCE_GROUP_PARAMS pod + return _numpy.dtype({ + 'names': ['sm_count', 'coscheduled_sm_count', 'preferred_coscheduled_sm_count', 'flags_', 'reserved'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, (_numpy.uint32, 12)], + 'offsets': [ + (&(pod.smCount)) - (&pod), + (&(pod.coscheduledSmCount)) - (&pod), + (&(pod.preferredCoscheduledSmCount)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CU_DEV_SM_RESOURCE_GROUP_PARAMS), + }) + +_dev_sm_resource_group_params_dtype = _get__dev_sm_resource_group_params_dtype_offsets() + +cdef class _DevSmResourceGroupParams: + """Empty-initialize an array of `CU_DEV_SM_RESOURCE_GROUP_PARAMS`. + The resulting object is of length `size` and of dtype `_dev_sm_resource_group_params_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CU_DEV_SM_RESOURCE_GROUP_PARAMS` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=_dev_sm_resource_group_params_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CU_DEV_SM_RESOURCE_GROUP_PARAMS), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CU_DEV_SM_RESOURCE_GROUP_PARAMS) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}._DevSmResourceGroupParams_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}._DevSmResourceGroupParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, _DevSmResourceGroupParams)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def sm_count(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.sm_count[0]) + return self._data.sm_count + + @sm_count.setter + def sm_count(self, val): + self._data.sm_count = val + + @property + def coscheduled_sm_count(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.coscheduled_sm_count[0]) + return self._data.coscheduled_sm_count + + @coscheduled_sm_count.setter + def coscheduled_sm_count(self, val): + self._data.coscheduled_sm_count = val + + @property + def preferred_coscheduled_sm_count(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.preferred_coscheduled_sm_count[0]) + return self._data.preferred_coscheduled_sm_count + + @preferred_coscheduled_sm_count.setter + def preferred_coscheduled_sm_count(self, val): + self._data.preferred_coscheduled_sm_count = val + + @property + def flags_(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.flags_[0]) + return self._data.flags_ + + @flags_.setter + def flags_(self, val): + self._data.flags_ = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return _DevSmResourceGroupParams.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == _dev_sm_resource_group_params_dtype: + return _DevSmResourceGroupParams.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an _DevSmResourceGroupParams instance with the memory from the given buffer.""" + return _DevSmResourceGroupParams.from_data(_numpy.frombuffer(buffer, dtype=_dev_sm_resource_group_params_dtype)) + + @staticmethod + def from_data(data): + """Create an _DevSmResourceGroupParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `_dev_sm_resource_group_params_dtype` holding the data. + """ + cdef _DevSmResourceGroupParams obj = _DevSmResourceGroupParams.__new__(_DevSmResourceGroupParams) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != _dev_sm_resource_group_params_dtype: + raise ValueError("data array must be of dtype _dev_sm_resource_group_params_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an _DevSmResourceGroupParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _DevSmResourceGroupParams obj = _DevSmResourceGroupParams.__new__(_DevSmResourceGroupParams) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CU_DEV_SM_RESOURCE_GROUP_PARAMS) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=_dev_sm_resource_group_params_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_stream_cig_param_dtype_offsets(): + cdef CUstreamCigParam pod + return _numpy.dtype({ + 'names': ['stream_shared_data_type', 'stream_shared_data'], + 'formats': [_numpy.int32, _numpy.intp], + 'offsets': [ + (&(pod.streamSharedDataType)) - (&pod), + (&(pod.streamSharedData)) - (&pod), + ], + 'itemsize': sizeof(CUstreamCigParam), + }) + +stream_cig_param_dtype = _get_stream_cig_param_dtype_offsets() + +cdef class StreamCigParam: + """Empty-initialize an instance of `CUstreamCigParam`. + + + .. seealso:: `CUstreamCigParam` + """ + cdef: + CUstreamCigParam *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamCigParam)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamCigParam") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUstreamCigParam *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamCigParam object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef StreamCigParam other_ + if not isinstance(other, StreamCigParam): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamCigParam)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamCigParam), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUstreamCigParam)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamCigParam") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUstreamCigParam)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def stream_shared_data_type(self): + """int: """ + return (self._ptr[0].streamSharedDataType) + + @stream_shared_data_type.setter + def stream_shared_data_type(self, val): + if self._readonly: + raise ValueError("This StreamCigParam instance is read-only") + self._ptr[0].streamSharedDataType = val + + @property + def stream_shared_data(self): + """int: """ + return (self._ptr[0].streamSharedData) + + @stream_shared_data.setter + def stream_shared_data(self, val): + if self._readonly: + raise ValueError("This StreamCigParam instance is read-only") + self._ptr[0].streamSharedData = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamCigParam instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamCigParam), StreamCigParam) + + @staticmethod + def from_data(data): + """Create an StreamCigParam instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_cig_param_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_cig_param_dtype", stream_cig_param_dtype, StreamCigParam) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamCigParam instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef StreamCigParam obj = StreamCigParam.__new__(StreamCigParam) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamCigParam)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamCigParam") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamCigParam)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_logical_endpoint_fabric_handle_dtype_offsets(): + cdef CUlogicalEndpointFabricHandle pod + return _numpy.dtype({ + 'names': ['data_'], + 'formats': [(_numpy.uint8, 64)], + 'offsets': [ + (&(pod.data)) - (&pod), + ], + 'itemsize': sizeof(CUlogicalEndpointFabricHandle), + }) + +logical_endpoint_fabric_handle_dtype = _get_logical_endpoint_fabric_handle_dtype_offsets() + +cdef class LogicalEndpointFabricHandle: + """Empty-initialize an instance of `CUlogicalEndpointFabricHandle`. + + + .. seealso:: `CUlogicalEndpointFabricHandle` + """ + cdef: + CUlogicalEndpointFabricHandle *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlogicalEndpointFabricHandle)) + if self._ptr == NULL: + raise MemoryError("Error allocating LogicalEndpointFabricHandle") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUlogicalEndpointFabricHandle *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LogicalEndpointFabricHandle object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef LogicalEndpointFabricHandle other_ + if not isinstance(other, LogicalEndpointFabricHandle): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlogicalEndpointFabricHandle)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlogicalEndpointFabricHandle), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUlogicalEndpointFabricHandle)) + if self._ptr == NULL: + raise MemoryError("Error allocating LogicalEndpointFabricHandle") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUlogicalEndpointFabricHandle)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def data_(self): + """~_numpy.uint8: (array of length 64).""" + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].data)), + (sizeof(unsigned char) * (64)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) + + @data_.setter + def data_(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointFabricHandle instance is read-only") + if len(val) != 64: + raise ValueError(f"Expected length { 64 } for field data_, got {len(val)}") + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].data)), (_val_.ctypes.data), sizeof(unsigned char) * (64)) + + @staticmethod + def from_buffer(buffer): + """Create an LogicalEndpointFabricHandle instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlogicalEndpointFabricHandle), LogicalEndpointFabricHandle) + + @staticmethod + def from_data(data): + """Create an LogicalEndpointFabricHandle instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `logical_endpoint_fabric_handle_dtype` holding the data. + """ + return _cyb_from_data(data, "logical_endpoint_fabric_handle_dtype", logical_endpoint_fabric_handle_dtype, LogicalEndpointFabricHandle) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LogicalEndpointFabricHandle instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef LogicalEndpointFabricHandle obj = LogicalEndpointFabricHandle.__new__(LogicalEndpointFabricHandle) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUlogicalEndpointFabricHandle)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LogicalEndpointFabricHandle") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUlogicalEndpointFabricHandle)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_gpu_pair_dtype_offsets(): + cdef CUcheckpointGpuPair pod + return _numpy.dtype({ + 'names': ['old_uuid', 'new_uuid'], + 'formats': [uuid_dtype, uuid_dtype], + 'offsets': [ + (&(pod.oldUuid)) - (&pod), + (&(pod.newUuid)) - (&pod), + ], + 'itemsize': sizeof(CUcheckpointGpuPair), + }) + +checkpoint_gpu_pair_dtype = _get_checkpoint_gpu_pair_dtype_offsets() + +cdef class CheckpointGpuPair: + """Empty-initialize an instance of `CUcheckpointGpuPair`. + + + .. seealso:: `CUcheckpointGpuPair` + """ + cdef: + CUcheckpointGpuPair *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUcheckpointGpuPair)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointGpuPair") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUcheckpointGpuPair *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CheckpointGpuPair object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CheckpointGpuPair other_ + if not isinstance(other, CheckpointGpuPair): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUcheckpointGpuPair)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUcheckpointGpuPair), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUcheckpointGpuPair)) + if self._ptr == NULL: + raise MemoryError("Error allocating CheckpointGpuPair") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUcheckpointGpuPair)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def old_uuid(self): + """Uuid: """ + return Uuid.from_ptr( + &(self._ptr[0].oldUuid), + readonly=self._readonly, + owner=self, + ) + + @old_uuid.setter + def old_uuid(self, val): + if self._readonly: + raise ValueError("This CheckpointGpuPair instance is read-only") + cdef Uuid val_ = val + _cyb_memcpy(&(self._ptr[0].oldUuid), (val_._get_ptr()), sizeof(CUuuid) * 1) + + @property + def new_uuid(self): + """Uuid: """ + return Uuid.from_ptr( + &(self._ptr[0].newUuid), + readonly=self._readonly, + owner=self, + ) + + @new_uuid.setter + def new_uuid(self, val): + if self._readonly: + raise ValueError("This CheckpointGpuPair instance is read-only") + cdef Uuid val_ = val + _cyb_memcpy(&(self._ptr[0].newUuid), (val_._get_ptr()), sizeof(CUuuid) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an CheckpointGpuPair instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUcheckpointGpuPair), CheckpointGpuPair) + + @staticmethod + def from_data(data): + """Create an CheckpointGpuPair instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `checkpoint_gpu_pair_dtype` holding the data. + """ + return _cyb_from_data(data, "checkpoint_gpu_pair_dtype", checkpoint_gpu_pair_dtype, CheckpointGpuPair) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CheckpointGpuPair instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CheckpointGpuPair obj = CheckpointGpuPair.__new__(CheckpointGpuPair) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUcheckpointGpuPair)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CheckpointGpuPair") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUcheckpointGpuPair)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_exec_affinity_param_v1_dtype_offsets(): + cdef CUexecAffinityParam_v1 pod + return _numpy.dtype({ + 'names': ['type', 'param'], + 'formats': [_numpy.int32, _py_anon_pod9_dtype], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.param)) - (&pod), + ], + 'itemsize': sizeof(CUexecAffinityParam_v1), + }) + +exec_affinity_param_v1_dtype = _get_exec_affinity_param_v1_dtype_offsets() + +cdef class ExecAffinityParam_v1: + """Empty-initialize an array of `CUexecAffinityParam_v1`. + The resulting object is of length `size` and of dtype `exec_affinity_param_v1_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUexecAffinityParam_v1` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=exec_affinity_param_v1_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUexecAffinityParam_v1), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUexecAffinityParam_v1) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.ExecAffinityParam_v1_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.ExecAffinityParam_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, ExecAffinityParam_v1)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.type[0]) + return self._data.type + + @type.setter + def type(self, val): + self._data.type = val + + @property + def param(self): + """_py_anon_pod9_dtype: """ + return self._data.param + + @param.setter + def param(self, val): + self._data.param = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return ExecAffinityParam_v1.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == exec_affinity_param_v1_dtype: + return ExecAffinityParam_v1.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an ExecAffinityParam_v1 instance with the memory from the given buffer.""" + return ExecAffinityParam_v1.from_data(_numpy.frombuffer(buffer, dtype=exec_affinity_param_v1_dtype)) + + @staticmethod + def from_data(data): + """Create an ExecAffinityParam_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `exec_affinity_param_v1_dtype` holding the data. + """ + cdef ExecAffinityParam_v1 obj = ExecAffinityParam_v1.__new__(ExecAffinityParam_v1) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != exec_affinity_param_v1_dtype: + raise ValueError("data array must be of dtype exec_affinity_param_v1_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an ExecAffinityParam_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ExecAffinityParam_v1 obj = ExecAffinityParam_v1.__new__(ExecAffinityParam_v1) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUexecAffinityParam_v1) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=exec_affinity_param_v1_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_ctx_create_params_dtype_offsets(): + cdef CUctxCreateParams pod + return _numpy.dtype({ + 'names': ['exec_affinity_params', 'num_exec_affinity_params', 'cig_params'], + 'formats': [_numpy.intp, _numpy.int32, _numpy.intp], + 'offsets': [ + (&(pod.execAffinityParams)) - (&pod), + (&(pod.numExecAffinityParams)) - (&pod), + (&(pod.cigParams)) - (&pod), + ], + 'itemsize': sizeof(CUctxCreateParams), + }) + +ctx_create_params_dtype = _get_ctx_create_params_dtype_offsets() + +cdef class CtxCreateParams: + """Empty-initialize an instance of `CUctxCreateParams`. + + + .. seealso:: `CUctxCreateParams` + """ + cdef: + CUctxCreateParams *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUctxCreateParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating CtxCreateParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUctxCreateParams *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.CtxCreateParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef CtxCreateParams other_ + if not isinstance(other, CtxCreateParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUctxCreateParams)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUctxCreateParams), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUctxCreateParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating CtxCreateParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUctxCreateParams)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def exec_affinity_params(self): + """int: """ + return (self._ptr[0].execAffinityParams) + + @exec_affinity_params.setter + def exec_affinity_params(self, val): + if self._readonly: + raise ValueError("This CtxCreateParams instance is read-only") + self._ptr[0].execAffinityParams = val + + @property + def num_exec_affinity_params(self): + """int: """ + return self._ptr[0].numExecAffinityParams + + @num_exec_affinity_params.setter + def num_exec_affinity_params(self, val): + if self._readonly: + raise ValueError("This CtxCreateParams instance is read-only") + self._ptr[0].numExecAffinityParams = val + + @property + def cig_params(self): + """int: """ + return (self._ptr[0].cigParams) + + @cig_params.setter + def cig_params(self, val): + if self._readonly: + raise ValueError("This CtxCreateParams instance is read-only") + self._ptr[0].cigParams = val + + @staticmethod + def from_buffer(buffer): + """Create an CtxCreateParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUctxCreateParams), CtxCreateParams) + + @staticmethod + def from_data(data): + """Create an CtxCreateParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `ctx_create_params_dtype` holding the data. + """ + return _cyb_from_data(data, "ctx_create_params_dtype", ctx_create_params_dtype, CtxCreateParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CtxCreateParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef CtxCreateParams obj = CtxCreateParams.__new__(CtxCreateParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUctxCreateParams)) + if obj._ptr == NULL: + raise MemoryError("Error allocating CtxCreateParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUctxCreateParams)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_array_sparse_properties_v1_dtype_offsets(): + cdef CUDA_ARRAY_SPARSE_PROPERTIES_v1 pod + return _numpy.dtype({ + 'names': ['tile_extent', 'miptail_first_level', 'miptail_size', 'flags_', 'reserved'], + 'formats': [_py_anon_pod10_dtype, _numpy.uint32, _numpy.uint64, _numpy.uint32, (_numpy.uint32, 4)], + 'offsets': [ + (&(pod.tileExtent)) - (&pod), + (&(pod.miptailFirstLevel)) - (&pod), + (&(pod.miptailSize)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1), + }) + +array_sparse_properties_v1_dtype = _get_array_sparse_properties_v1_dtype_offsets() + +cdef class ArraySparseProperties_v1: + """Empty-initialize an instance of `CUDA_ARRAY_SPARSE_PROPERTIES_v1`. + + + .. seealso:: `CUDA_ARRAY_SPARSE_PROPERTIES_v1` + """ + cdef: + CUDA_ARRAY_SPARSE_PROPERTIES_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArraySparseProperties_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUDA_ARRAY_SPARSE_PROPERTIES_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.ArraySparseProperties_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef ArraySparseProperties_v1 other_ + if not isinstance(other, ArraySparseProperties_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating ArraySparseProperties_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def tile_extent(self): + """_py_anon_pod10: """ + return _py_anon_pod10.from_ptr( + &(self._ptr[0].tileExtent), + readonly=self._readonly, + owner=self, + ) + + @tile_extent.setter + def tile_extent(self, val): + if self._readonly: + raise ValueError("This ArraySparseProperties_v1 instance is read-only") + cdef _py_anon_pod10 val_ = val + _cyb_memcpy(&(self._ptr[0].tileExtent), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod10) * 1) + + @property + def miptail_first_level(self): + """int: """ + return self._ptr[0].miptailFirstLevel + + @miptail_first_level.setter + def miptail_first_level(self, val): + if self._readonly: + raise ValueError("This ArraySparseProperties_v1 instance is read-only") + self._ptr[0].miptailFirstLevel = val + + @property + def miptail_size(self): + """int: """ + return self._ptr[0].miptailSize + + @miptail_size.setter + def miptail_size(self, val): + if self._readonly: + raise ValueError("This ArraySparseProperties_v1 instance is read-only") + self._ptr[0].miptailSize = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ArraySparseProperties_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ArraySparseProperties_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1), ArraySparseProperties_v1) + + @staticmethod + def from_data(data): + """Create an ArraySparseProperties_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `array_sparse_properties_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "array_sparse_properties_v1_dtype", array_sparse_properties_v1_dtype, ArraySparseProperties_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ArraySparseProperties_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ArraySparseProperties_v1 obj = ArraySparseProperties_v1.__new__(ArraySparseProperties_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating ArraySparseProperties_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod30_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod30 pod + return _numpy.dtype({ + 'names': ['sparse_level', 'miptail'], + 'formats': [_py_anon_pod31_dtype, _py_anon_pod32_dtype], + 'offsets': [ + (&(pod.sparseLevel)) - (&pod), + (&(pod.miptail)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod30), + }) + +_py_anon_pod30_dtype = _get__py_anon_pod30_dtype_offsets() + +cdef class _py_anon_pod30: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod30`. + + + .. seealso:: `cuda_bindings_driver__anon_pod30` + """ + cdef: + cuda_bindings_driver__anon_pod30 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod30)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod30") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod30 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod30 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef _py_anon_pod30 other_ + if not isinstance(other, _py_anon_pod30): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod30)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod30), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod30)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod30") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_driver__anon_pod30)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def sparse_level(self): + """_py_anon_pod31: """ + return _py_anon_pod31.from_ptr( + &(self._ptr[0].sparseLevel), + readonly=self._readonly, + owner=self, + ) + + @sparse_level.setter + def sparse_level(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod30 instance is read-only") + cdef _py_anon_pod31 val_ = val + _cyb_memcpy(&(self._ptr[0].sparseLevel), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod31) * 1) + + @property + def miptail(self): + """_py_anon_pod32: """ + return _py_anon_pod32.from_ptr( + &(self._ptr[0].miptail), + readonly=self._readonly, + owner=self, + ) + + @miptail.setter + def miptail(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod30 instance is read-only") + cdef _py_anon_pod32 val_ = val + _cyb_memcpy(&(self._ptr[0].miptail), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod32) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod30 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod30), _py_anon_pod30) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod30 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod30_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod30_dtype", _py_anon_pod30_dtype, _py_anon_pod30) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod30 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef _py_anon_pod30 obj = _py_anon_pod30.__new__(_py_anon_pod30) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod30)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod30") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod30)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_location_v1_dtype_offsets(): + cdef CUmemLocation_v1 pod + return _numpy.dtype({ + 'names': ['type', 'id'], + 'formats': [_numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.id)) - (&pod), + ], + 'itemsize': sizeof(CUmemLocation_v1), + }) + +mem_location_v1_dtype = _get_mem_location_v1_dtype_offsets() + +cdef class MemLocation_v1: + """Empty-initialize an instance of `CUmemLocation_v1`. + + + .. seealso:: `CUmemLocation_v1` + """ + cdef: + CUmemLocation_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemLocation_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemLocation_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemLocation_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemLocation_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemLocation_v1 other_ + if not isinstance(other, MemLocation_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemLocation_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemLocation_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemLocation_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemLocation_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemLocation_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This MemLocation_v1 instance is read-only") + self._ptr[0].type = val + + @property + def id(self): + """int: """ + return self._ptr[0].id + + @id.setter + def id(self, val): + if self._readonly: + raise ValueError("This MemLocation_v1 instance is read-only") + self._ptr[0].id = val + + @staticmethod + def from_buffer(buffer): + """Create an MemLocation_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemLocation_v1), MemLocation_v1) + + @staticmethod + def from_data(data): + """Create an MemLocation_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_location_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_location_v1_dtype", mem_location_v1_dtype, MemLocation_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemLocation_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemLocation_v1 obj = MemLocation_v1.__new__(MemLocation_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemLocation_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemLocation_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemLocation_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_mem_allocation_prop_v1_dtype_offsets(): + cdef CUmemAllocationProp_v1 pod + return _numpy.dtype({ + 'names': ['type', 'requested_handle_types', 'location', 'win32handle_meta_data', 'alloc_flags'], + 'formats': [_numpy.int32, _numpy.int32, _numpy.int32, _numpy.intp, _py_anon_pod35_dtype], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.requestedHandleTypes)) - (&pod), + (&(pod.location)) - (&pod), + (&(pod.win32HandleMetaData)) - (&pod), + (&(pod.allocFlags)) - (&pod), + ], + 'itemsize': sizeof(CUmemAllocationProp_v1), + }) + +mem_allocation_prop_v1_dtype = _get_mem_allocation_prop_v1_dtype_offsets() + +cdef class MemAllocationProp_v1: + """Empty-initialize an instance of `CUmemAllocationProp_v1`. + + + .. seealso:: `CUmemAllocationProp_v1` + """ + cdef: + CUmemAllocationProp_v1 *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUmemAllocationProp_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocationProp_v1") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUmemAllocationProp_v1 *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.MemAllocationProp_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef MemAllocationProp_v1 other_ + if not isinstance(other, MemAllocationProp_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemAllocationProp_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemAllocationProp_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUmemAllocationProp_v1)) + if self._ptr == NULL: + raise MemoryError("Error allocating MemAllocationProp_v1") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUmemAllocationProp_v1)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def location(self): + """MemLocation_v1: """ + return MemLocation_v1.from_ptr( + &(self._ptr[0].location), + readonly=self._readonly, + owner=self, + ) + + @location.setter + def location(self, val): + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + cdef MemLocation_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].location), (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @property + def alloc_flags(self): + """_py_anon_pod35: """ + return _py_anon_pod35.from_ptr( + &(self._ptr[0].allocFlags), + readonly=self._readonly, + owner=self, + ) + + @alloc_flags.setter + def alloc_flags(self, val): + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + cdef _py_anon_pod35 val_ = val + _cyb_memcpy(&(self._ptr[0].allocFlags), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod35) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + self._ptr[0].type = val + + @property + def requested_handle_types(self): + """int: """ + return (self._ptr[0].requestedHandleTypes) + + @requested_handle_types.setter + def requested_handle_types(self, val): + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + self._ptr[0].requestedHandleTypes = val + + @property + def win32handle_meta_data(self): + """int: """ + return (self._ptr[0].win32HandleMetaData) + + @win32handle_meta_data.setter + def win32handle_meta_data(self, val): + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + self._ptr[0].win32HandleMetaData = val + + @staticmethod + def from_buffer(buffer): + """Create an MemAllocationProp_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemAllocationProp_v1), MemAllocationProp_v1) + + @staticmethod + def from_data(data): + """Create an MemAllocationProp_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_allocation_prop_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_allocation_prop_v1_dtype", mem_allocation_prop_v1_dtype, MemAllocationProp_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemAllocationProp_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef MemAllocationProp_v1 obj = MemAllocationProp_v1.__new__(MemAllocationProp_v1) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUmemAllocationProp_v1)) + if obj._ptr == NULL: + raise MemoryError("Error allocating MemAllocationProp_v1") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUmemAllocationProp_v1)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_stream_batch_mem_op_params_v1_dtype_offsets(): + cdef CUstreamBatchMemOpParams_v1 pod + return _numpy.dtype({ + 'names': ['operation', 'wait_value', 'write_value', 'flush_remote_writes', 'memory_barrier', 'atomic_reduction', 'pad'], + 'formats': [_numpy.int32, _numpy.dtype(('V', sizeof(pod.waitValue))), _numpy.dtype(('V', sizeof(pod.writeValue))), _numpy.dtype(('V', sizeof(pod.flushRemoteWrites))), _numpy.dtype(('V', sizeof(pod.memoryBarrier))), _numpy.dtype(('V', sizeof(pod.atomicReduction))), (_numpy.uint64, 6)], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.waitValue)) - (&pod), + (&(pod.writeValue)) - (&pod), + (&(pod.flushRemoteWrites)) - (&pod), + (&(pod.memoryBarrier)) - (&pod), + (&(pod.atomicReduction)) - (&pod), + (&(pod.pad)) - (&pod), + ], + 'itemsize': sizeof(CUstreamBatchMemOpParams_v1), + }) + +stream_batch_mem_op_params_v1_dtype = _get_stream_batch_mem_op_params_v1_dtype_offsets() + +cdef class StreamBatchMemOpParams_v1: + """Empty-initialize an array of `CUstreamBatchMemOpParams_v1`. + The resulting object is of length `size` and of dtype `stream_batch_mem_op_params_v1_dtype`. + If default-constructed, the instance represents a single union. + + Args: + size (int): number of unions, default=1. + + .. seealso:: `CUstreamBatchMemOpParams_v1` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=stream_batch_mem_op_params_v1_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUstreamBatchMemOpParams_v1), \ + f"itemsize {self._data.itemsize} mismatches union size { sizeof(CUstreamBatchMemOpParams_v1) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.StreamBatchMemOpParams_v1_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.StreamBatchMemOpParams_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, StreamBatchMemOpParams_v1)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def operation(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.operation[0]) + return self._data.operation + + @operation.setter + def operation(self, val): + self._data.operation = val + + @property + def wait_value(self): + """~_numpy.dtype(('V', sizeof(pod.waitValue))): """ + return self._data.wait_value + + @wait_value.setter + def wait_value(self, val): + self._data.wait_value = val + + @property + def write_value(self): + """~_numpy.dtype(('V', sizeof(pod.writeValue))): """ + return self._data.write_value + + @write_value.setter + def write_value(self, val): + self._data.write_value = val + + @property + def flush_remote_writes(self): + """~_numpy.dtype(('V', sizeof(pod.flushRemoteWrites))): """ + return self._data.flush_remote_writes + + @flush_remote_writes.setter + def flush_remote_writes(self, val): + self._data.flush_remote_writes = val + + @property + def memory_barrier(self): + """~_numpy.dtype(('V', sizeof(pod.memoryBarrier))): """ + return self._data.memory_barrier + + @memory_barrier.setter + def memory_barrier(self, val): + self._data.memory_barrier = val + + @property + def atomic_reduction(self): + """~_numpy.dtype(('V', sizeof(pod.atomicReduction))): """ + return self._data.atomic_reduction + + @atomic_reduction.setter + def atomic_reduction(self, val): + self._data.atomic_reduction = val + + @property + def pad(self): + """~_numpy.uint64: (array of length 6).""" + return self._data.pad + + @pad.setter + def pad(self, val): + self._data.pad = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return StreamBatchMemOpParams_v1.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == stream_batch_mem_op_params_v1_dtype: + return StreamBatchMemOpParams_v1.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamBatchMemOpParams_v1 instance with the memory from the given buffer.""" + return StreamBatchMemOpParams_v1.from_data(_numpy.frombuffer(buffer, dtype=stream_batch_mem_op_params_v1_dtype)) + + @staticmethod + def from_data(data): + """Create an StreamBatchMemOpParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `stream_batch_mem_op_params_v1_dtype` holding the data. + """ + cdef StreamBatchMemOpParams_v1 obj = StreamBatchMemOpParams_v1.__new__(StreamBatchMemOpParams_v1) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != stream_batch_mem_op_params_v1_dtype: + raise ValueError("data array must be of dtype stream_batch_mem_op_params_v1_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an StreamBatchMemOpParams_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of unions, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef StreamBatchMemOpParams_v1 obj = StreamBatchMemOpParams_v1.__new__(StreamBatchMemOpParams_v1) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUstreamBatchMemOpParams_v1) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=stream_batch_mem_op_params_v1_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_array_map_info_v1_dtype_offsets(): + cdef CUarrayMapInfo_v1 pod + return _numpy.dtype({ + 'names': ['resource_type', 'resource', 'subresource_type', 'subresource', 'mem_operation_type', 'mem_handle_type', 'mem_handle', 'offset', 'device_bit_mask', 'flags_', 'reserved'], + 'formats': [_numpy.int32, _py_anon_pod29_dtype, _numpy.int32, _py_anon_pod30_dtype, _numpy.int32, _numpy.int32, _py_anon_pod33_dtype, _numpy.uint64, _numpy.uint32, _numpy.uint32, (_numpy.uint32, 2)], + 'offsets': [ + (&(pod.resourceType)) - (&pod), + (&(pod.resource)) - (&pod), + (&(pod.subresourceType)) - (&pod), + (&(pod.subresource)) - (&pod), + (&(pod.memOperationType)) - (&pod), + (&(pod.memHandleType)) - (&pod), + (&(pod.memHandle)) - (&pod), + (&(pod.offset)) - (&pod), + (&(pod.deviceBitMask)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUarrayMapInfo_v1), + }) + +array_map_info_v1_dtype = _get_array_map_info_v1_dtype_offsets() + +cdef class ArrayMapInfo_v1: + """Empty-initialize an array of `CUarrayMapInfo_v1`. + The resulting object is of length `size` and of dtype `array_map_info_v1_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUarrayMapInfo_v1` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=array_map_info_v1_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUarrayMapInfo_v1), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUarrayMapInfo_v1) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.ArrayMapInfo_v1_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.ArrayMapInfo_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, ArrayMapInfo_v1)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def resource_type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.resource_type[0]) + return self._data.resource_type + + @resource_type.setter + def resource_type(self, val): + self._data.resource_type = val + + @property + def resource(self): + """_py_anon_pod29_dtype: """ + return self._data.resource + + @resource.setter + def resource(self, val): + self._data.resource = val + + @property + def subresource_type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.subresource_type[0]) + return self._data.subresource_type + + @subresource_type.setter + def subresource_type(self, val): + self._data.subresource_type = val + + @property + def subresource(self): + """_py_anon_pod30_dtype: """ + return self._data.subresource + + @subresource.setter + def subresource(self, val): + self._data.subresource = val + + @property + def mem_operation_type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.mem_operation_type[0]) + return self._data.mem_operation_type + + @mem_operation_type.setter + def mem_operation_type(self, val): + self._data.mem_operation_type = val + + @property + def mem_handle_type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.mem_handle_type[0]) + return self._data.mem_handle_type + + @mem_handle_type.setter + def mem_handle_type(self, val): + self._data.mem_handle_type = val + + @property + def mem_handle(self): + """_py_anon_pod33_dtype: """ + return self._data.mem_handle + + @mem_handle.setter + def mem_handle(self, val): + self._data.mem_handle = val + + @property + def offset(self): + """Union[~_numpy.uint64, int]: """ + if self._data.size == 1: + return int(self._data.offset[0]) + return self._data.offset + + @offset.setter + def offset(self, val): + self._data.offset = val + + @property + def device_bit_mask(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.device_bit_mask[0]) + return self._data.device_bit_mask + + @device_bit_mask.setter + def device_bit_mask(self, val): + self._data.device_bit_mask = val + + @property + def flags_(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.flags_[0]) + return self._data.flags_ + + @flags_.setter + def flags_(self, val): + self._data.flags_ = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return ArrayMapInfo_v1.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == array_map_info_v1_dtype: + return ArrayMapInfo_v1.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an ArrayMapInfo_v1 instance with the memory from the given buffer.""" + return ArrayMapInfo_v1.from_data(_numpy.frombuffer(buffer, dtype=array_map_info_v1_dtype)) + + @staticmethod + def from_data(data): + """Create an ArrayMapInfo_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `array_map_info_v1_dtype` holding the data. + """ + cdef ArrayMapInfo_v1 obj = ArrayMapInfo_v1.__new__(ArrayMapInfo_v1) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != array_map_info_v1_dtype: + raise ValueError("data array must be of dtype array_map_info_v1_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an ArrayMapInfo_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef ArrayMapInfo_v1 obj = ArrayMapInfo_v1.__new__(ArrayMapInfo_v1) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUarrayMapInfo_v1) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=array_map_info_v1_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_graph_node_params_dtype_offsets(): + cdef CUgraphNodeParams pod + return _numpy.dtype({ + 'names': ['type', 'reserved0', 'reserved1', 'kernel', 'memcpy', 'memset', 'host', 'graph', 'event_wait', 'event_record', 'ext_sem_signal', 'ext_sem_wait', 'alloc', 'free', 'mem_op', 'conditional', 'as_bytes', 'reserved2'], + 'formats': [_numpy.int32, (_numpy.int32, 3), (_numpy.int64, 29), kernel_node_params_v3_dtype, memcpy_node_params_dtype, memset_node_params_v2_dtype, host_node_params_v2_dtype, child_graph_node_params_dtype, event_wait_node_params_dtype, event_record_node_params_dtype, ext_sem_signal_node_params_v2_dtype, ext_sem_wait_node_params_v2_dtype, mem_alloc_node_params_v2_dtype, mem_free_node_params_dtype, batch_mem_op_node_params_v2_dtype, conditional_node_params_dtype, (_numpy.int8, 232), _numpy.int64], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.reserved0)) - (&pod), + (&(pod.reserved1)) - (&pod), + (&(pod.kernel)) - (&pod), + (&(pod.memcpy)) - (&pod), + (&(pod.memset)) - (&pod), + (&(pod.host)) - (&pod), + (&(pod.graph)) - (&pod), + (&(pod.eventWait)) - (&pod), + (&(pod.eventRecord)) - (&pod), + (&(pod.extSemSignal)) - (&pod), + (&(pod.extSemWait)) - (&pod), + (&(pod.alloc)) - (&pod), + (&(pod.free)) - (&pod), + (&(pod.memOp)) - (&pod), + (&(pod.conditional)) - (&pod), + (&(pod.asBytes)) - (&pod), + (&(pod.reserved2)) - (&pod), + ], + 'itemsize': sizeof(CUgraphNodeParams), + }) + +graph_node_params_dtype = _get_graph_node_params_dtype_offsets() + +cdef class GraphNodeParams: + """Empty-initialize an instance of `CUgraphNodeParams`. + + + .. seealso:: `CUgraphNodeParams` + """ + cdef: + CUgraphNodeParams *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUgraphNodeParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphNodeParams") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUgraphNodeParams *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.GraphNodeParams object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef GraphNodeParams other_ + if not isinstance(other, GraphNodeParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUgraphNodeParams)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUgraphNodeParams), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUgraphNodeParams)) + if self._ptr == NULL: + raise MemoryError("Error allocating GraphNodeParams") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUgraphNodeParams)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def kernel(self): + """KernelNodeParams_v3: """ + return KernelNodeParams_v3.from_ptr( + &(self._ptr[0].kernel), + readonly=self._readonly, + owner=self, + ) + + @kernel.setter + def kernel(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef KernelNodeParams_v3 val_ = val + _cyb_memcpy(&(self._ptr[0].kernel), (val_._get_ptr()), sizeof(CUDA_KERNEL_NODE_PARAMS_v3) * 1) + + @property + def memcpy(self): + """MemcpyNodeParams: """ + return MemcpyNodeParams.from_ptr( + &(self._ptr[0].memcpy), + readonly=self._readonly, + owner=self, + ) + + @memcpy.setter + def memcpy(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef MemcpyNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].memcpy), (val_._get_ptr()), sizeof(CUDA_MEMCPY_NODE_PARAMS) * 1) + + @property + def memset(self): + """MemsetNodeParams_v2: """ + return MemsetNodeParams_v2.from_ptr( + &(self._ptr[0].memset), + readonly=self._readonly, + owner=self, + ) + + @memset.setter + def memset(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef MemsetNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].memset), (val_._get_ptr()), sizeof(CUDA_MEMSET_NODE_PARAMS_v2) * 1) + + @property + def host(self): + """HostNodeParams_v2: """ + return HostNodeParams_v2.from_ptr( + &(self._ptr[0].host), + readonly=self._readonly, + owner=self, + ) + + @host.setter + def host(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef HostNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].host), (val_._get_ptr()), sizeof(CUDA_HOST_NODE_PARAMS_v2) * 1) + + @property + def graph(self): + """ChildGraphNodeParams: """ + return ChildGraphNodeParams.from_ptr( + &(self._ptr[0].graph), + readonly=self._readonly, + owner=self, + ) + + @graph.setter + def graph(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef ChildGraphNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].graph), (val_._get_ptr()), sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS) * 1) + + @property + def event_wait(self): + """EventWaitNodeParams: """ + return EventWaitNodeParams.from_ptr( + &(self._ptr[0].eventWait), + readonly=self._readonly, + owner=self, + ) + + @event_wait.setter + def event_wait(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef EventWaitNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].eventWait), (val_._get_ptr()), sizeof(CUDA_EVENT_WAIT_NODE_PARAMS) * 1) + + @property + def event_record(self): + """EventRecordNodeParams: """ + return EventRecordNodeParams.from_ptr( + &(self._ptr[0].eventRecord), + readonly=self._readonly, + owner=self, + ) + + @event_record.setter + def event_record(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef EventRecordNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].eventRecord), (val_._get_ptr()), sizeof(CUDA_EVENT_RECORD_NODE_PARAMS) * 1) + + @property + def ext_sem_signal(self): + """ExtSemSignalNodeParams_v2: """ + return ExtSemSignalNodeParams_v2.from_ptr( + &(self._ptr[0].extSemSignal), + readonly=self._readonly, + owner=self, + ) + + @ext_sem_signal.setter + def ext_sem_signal(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef ExtSemSignalNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].extSemSignal), (val_._get_ptr()), sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2) * 1) + + @property + def ext_sem_wait(self): + """ExtSemWaitNodeParams_v2: """ + return ExtSemWaitNodeParams_v2.from_ptr( + &(self._ptr[0].extSemWait), + readonly=self._readonly, + owner=self, + ) + + @ext_sem_wait.setter + def ext_sem_wait(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef ExtSemWaitNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].extSemWait), (val_._get_ptr()), sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2) * 1) + + @property + def alloc(self): + """MemAllocNodeParams_v2: """ + return MemAllocNodeParams_v2.from_ptr( + &(self._ptr[0].alloc), + readonly=self._readonly, + owner=self, + ) + + @alloc.setter + def alloc(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef MemAllocNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].alloc), (val_._get_ptr()), sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2) * 1) + + @property + def free(self): + """MemFreeNodeParams: """ + return MemFreeNodeParams.from_ptr( + &(self._ptr[0].free), + readonly=self._readonly, + owner=self, + ) + + @free.setter + def free(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef MemFreeNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].free), (val_._get_ptr()), sizeof(CUDA_MEM_FREE_NODE_PARAMS) * 1) + + @property + def mem_op(self): + """BatchMemOpNodeParams_v2: """ + return BatchMemOpNodeParams_v2.from_ptr( + &(self._ptr[0].memOp), + readonly=self._readonly, + owner=self, + ) + + @mem_op.setter + def mem_op(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef BatchMemOpNodeParams_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].memOp), (val_._get_ptr()), sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2) * 1) + + @property + def conditional(self): + """ConditionalNodeParams: """ + return ConditionalNodeParams.from_ptr( + &(self._ptr[0].conditional), + readonly=self._readonly, + owner=self, + ) + + @conditional.setter + def conditional(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef ConditionalNodeParams val_ = val + _cyb_memcpy(&(self._ptr[0].conditional), (val_._get_ptr()), sizeof(CUDA_CONDITIONAL_NODE_PARAMS) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + self._ptr[0].type = val + + @property + def as_bytes(self): + """~_numpy.int8: (array of length 232).""" + return _cyb_cpython.PyUnicode_FromString(self._ptr[0].asBytes) + + @as_bytes.setter + def as_bytes(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef bytes buf = val.encode() + if len(buf) >= 232: + raise ValueError("String too long for field as_bytes, max length is 231") + cdef char *ptr = buf + _cyb_memcpy((self._ptr[0].asBytes), ptr, 232) + + @staticmethod + def from_buffer(buffer): + """Create an GraphNodeParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUgraphNodeParams), GraphNodeParams) + + @staticmethod + def from_data(data): + """Create an GraphNodeParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `graph_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "graph_node_params_dtype", graph_node_params_dtype, GraphNodeParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an GraphNodeParams instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef GraphNodeParams obj = GraphNodeParams.__new__(GraphNodeParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUgraphNodeParams)) + if obj._ptr == NULL: + raise MemoryError("Error allocating GraphNodeParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUgraphNodeParams)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +cdef _get_dev_resource_v1_dtype_offsets(): + cdef CUdevResource_v1 pod + return _numpy.dtype({ + 'names': ['type', '_internal_padding', 'sm', 'wq_config', 'wq', '_oversize', 'next_resource'], + 'formats': [_numpy.int32, (_numpy.uint8, 92), dev_sm_resource_dtype, dev_workqueue_config_resource_dtype, dev_workqueue_resource_dtype, (_numpy.uint8, 40), _numpy.intp], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod._internal_padding)) - (&pod), + (&(pod.sm)) - (&pod), + (&(pod.wqConfig)) - (&pod), + (&(pod.wq)) - (&pod), + (&(pod._oversize)) - (&pod), + (&(pod.nextResource)) - (&pod), + ], + 'itemsize': sizeof(CUdevResource_v1), + }) + +dev_resource_v1_dtype = _get_dev_resource_v1_dtype_offsets() + +cdef class DevResource_v1: + """Empty-initialize an array of `CUdevResource_v1`. + The resulting object is of length `size` and of dtype `dev_resource_v1_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUdevResource_v1` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=dev_resource_v1_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUdevResource_v1), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUdevResource_v1) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.DevResource_v1_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.DevResource_v1 object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, DevResource_v1)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def type(self): + """Union[~_numpy.int32, int]: """ + if self._data.size == 1: + return int(self._data.type[0]) + return self._data.type + + @type.setter + def type(self, val): + self._data.type = val + + @property + def _internal_padding(self): + """~_numpy.uint8: (array of length 92).""" + return self._data._internal_padding + + @_internal_padding.setter + def _internal_padding(self, val): + self._data._internal_padding = val + + @property + def sm(self): + """dev_sm_resource_dtype: """ + return self._data.sm + + @sm.setter + def sm(self, val): + self._data.sm = val + + @property + def wq_config(self): + """dev_workqueue_config_resource_dtype: """ + return self._data.wq_config + + @wq_config.setter + def wq_config(self, val): + self._data.wq_config = val + + @property + def wq(self): + """dev_workqueue_resource_dtype: """ + return self._data.wq + + @wq.setter + def wq(self, val): + self._data.wq = val + + @property + def _oversize(self): + """~_numpy.uint8: (array of length 40).""" + return self._data._oversize + + @_oversize.setter + def _oversize(self, val): + self._data._oversize = val + + @property + def next_resource(self): + """Union[~_numpy.intp, int]: """ + if self._data.size == 1: + return int(self._data.next_resource[0]) + return self._data.next_resource + + @next_resource.setter + def next_resource(self, val): + self._data.next_resource = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return DevResource_v1.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == dev_resource_v1_dtype: + return DevResource_v1.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an DevResource_v1 instance with the memory from the given buffer.""" + return DevResource_v1.from_data(_numpy.frombuffer(buffer, dtype=dev_resource_v1_dtype)) + + @staticmethod + def from_data(data): + """Create an DevResource_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `dev_resource_v1_dtype` holding the data. + """ + cdef DevResource_v1 obj = DevResource_v1.__new__(DevResource_v1) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != dev_resource_v1_dtype: + raise ValueError("data array must be of dtype dev_resource_v1_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an DevResource_v1 instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef DevResource_v1 obj = DevResource_v1.__new__(DevResource_v1) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(CUdevResource_v1) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=dev_resource_v1_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + +cdef _get_launch_config_dtype_offsets(): + cdef CUlaunchConfig pod + return _numpy.dtype({ + 'names': ['grid_dim_x', 'grid_dim_y', 'grid_dim_z', 'block_dim_x', 'block_dim_y', 'block_dim_z', 'shared_mem_bytes', 'h_stream', 'attrs', 'num_attrs'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.intp, _numpy.intp, _numpy.uint32], + 'offsets': [ + (&(pod.gridDimX)) - (&pod), + (&(pod.gridDimY)) - (&pod), + (&(pod.gridDimZ)) - (&pod), + (&(pod.blockDimX)) - (&pod), + (&(pod.blockDimY)) - (&pod), + (&(pod.blockDimZ)) - (&pod), + (&(pod.sharedMemBytes)) - (&pod), + (&(pod.hStream)) - (&pod), + (&(pod.attrs)) - (&pod), + (&(pod.numAttrs)) - (&pod), + ], + 'itemsize': sizeof(CUlaunchConfig), + }) + +launch_config_dtype = _get_launch_config_dtype_offsets() + +cdef class LaunchConfig: + """Empty-initialize an instance of `CUlaunchConfig`. + + + .. seealso:: `CUlaunchConfig` + """ + cdef: + CUlaunchConfig *_ptr + object _owner + bint _owned + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlaunchConfig)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchConfig") + self._owner = None + self._owned = True + self._readonly = False + + def __dealloc__(self): + cdef CUlaunchConfig *ptr + if self._owned and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LaunchConfig object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return (self._ptr) + + cdef intptr_t _get_ptr(self): + return (self._ptr) + + def __int__(self): + return (self._ptr) + + def __eq__(self, other): + cdef LaunchConfig other_ + if not isinstance(other, LaunchConfig): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlaunchConfig)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlaunchConfig), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + if key == 0 and isinstance(val, _numpy.ndarray): + self._ptr = _cyb_malloc(sizeof(CUlaunchConfig)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchConfig") + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(CUlaunchConfig)) + self._owner = None + self._owned = True + self._readonly = not val.flags.writeable + else: + setattr(self, key, val) + + @property + def grid_dim_x(self): + """int: """ + return self._ptr[0].gridDimX + + @grid_dim_x.setter + def grid_dim_x(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].gridDimX = val + + @property + def grid_dim_y(self): + """int: """ + return self._ptr[0].gridDimY + + @grid_dim_y.setter + def grid_dim_y(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].gridDimY = val + + @property + def grid_dim_z(self): + """int: """ + return self._ptr[0].gridDimZ + + @grid_dim_z.setter + def grid_dim_z(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].gridDimZ = val + + @property + def block_dim_x(self): + """int: """ + return self._ptr[0].blockDimX + + @block_dim_x.setter + def block_dim_x(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].blockDimX = val + + @property + def block_dim_y(self): + """int: """ + return self._ptr[0].blockDimY + + @block_dim_y.setter + def block_dim_y(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].blockDimY = val + + @property + def block_dim_z(self): + """int: """ + return self._ptr[0].blockDimZ + + @block_dim_z.setter + def block_dim_z(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].blockDimZ = val + + @property + def shared_mem_bytes(self): + """int: """ + return self._ptr[0].sharedMemBytes + + @shared_mem_bytes.setter + def shared_mem_bytes(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].sharedMemBytes = val + + @property + def h_stream(self): + """int: """ + return (self._ptr[0].hStream) + + @h_stream.setter + def h_stream(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].hStream = val + + @property + def attrs(self): + """int: """ + return (self._ptr[0].attrs) + + @attrs.setter + def attrs(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].attrs = val + + @property + def num_attrs(self): + """int: """ + return self._ptr[0].numAttrs + + @num_attrs.setter + def num_attrs(self, val): + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + self._ptr[0].numAttrs = val + + @staticmethod + def from_buffer(buffer): + """Create an LaunchConfig instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlaunchConfig), LaunchConfig) + + @staticmethod + def from_data(data): + """Create an LaunchConfig instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `launch_config_dtype` holding the data. + """ + return _cyb_from_data(data, "launch_config_dtype", launch_config_dtype, LaunchConfig) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LaunchConfig instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + owner (object): The Python object that owns the pointer. If not provided, data will be copied. + readonly (bool): whether the data is read-only (to the user). default is `False`. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef LaunchConfig obj = LaunchConfig.__new__(LaunchConfig) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUlaunchConfig)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LaunchConfig") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUlaunchConfig)) + obj._owner = None + obj._owned = True + else: + obj._ptr = ptr + obj._owner = owner + obj._owned = False + obj._readonly = readonly + return obj + + +############################################################################### +# Wrapper functions +############################################################################### + +cdef void _acquire_buffer(object obj, Py_buffer* view) except *: + """Acquire a buffer view of obj, copying to C-contiguous if not already contiguous.""" + cdef object _cont_ + try: + PyObject_GetBuffer(obj, view, PyBUF_ANY_CONTIGUOUS) + except BufferError: + _cont_ = _numpy.ascontiguousarray(obj) + PyObject_GetBuffer(_cont_, view, PyBUF_ANY_CONTIGUOUS) + + +cpdef str get_error_string(int error): + """Return a string describing the given CUresult code. + + Sets ``*pStr`` to the address of a NULL-terminated string description of the + error code ``error``. If the error code is not recognized, + ``CUDA_ERROR_INVALID_VALUE`` will be returned and ``*pStr`` will be set to + the NULL address. + + Args: + error (int): CUDA error code. + + Returns: + str: String describing the error code, or ``""`` if unknown. + + .. seealso:: `cuGetErrorString` + """ + cdef const char* p_str = NULL + with nogil: + cuGetErrorString(error, &p_str) + if p_str == NULL: + return "" + return p_str.decode() + + +cpdef str get_error_name(int error): + """Return the string representation of a CUresult code name. + + Sets ``*pStr`` to the address of a NULL-terminated string representation of + the name of the enum error code ``error``. If the error code is not + recognized, ``CUDA_ERROR_INVALID_VALUE`` will be returned and ``*pStr`` will + be set to the NULL address. + + Args: + error (int): CUDA error code. + + Returns: + str: String containing the name of the error, or ``""`` if unknown. + + .. seealso:: `cuGetErrorName` + """ + cdef const char* p_name = NULL + with nogil: + cuGetErrorName(error, &p_name) + if p_name == NULL: + return "" + return p_name.decode() + + + +cpdef object device_get_host_atomic_capabilities(object operations, int dev): + """Query atomic operation capabilities between host and device. + + Returns details about the requested atomic ``operations`` over the link + between ``dev`` and the host. For each :class:`CUatomicOperation` in + ``operations``, the corresponding result is a bitmask of + :class:`CUatomicOperationCapability` values indicating which operations the + link supports natively. + + Returns ``CUDA_ERROR_INVALID_DEVICE`` if ``dev`` is not valid. + Returns ``CUDA_ERROR_INVALID_VALUE`` if ``count`` is 0 or any operation + value is invalid. + + Args: + operations: Buffer of :class:`CUatomicOperation` enum values whose + capabilities should be queried (any buffer-exposing object, e.g. + a numpy ``int32`` array; non-contiguous inputs are copied). + dev (int): Device handle. + + Returns: + object: numpy ``uint32`` array of the same length as ``operations`` + containing the capability flags for each requested operation. + + .. seealso:: `cuDeviceGetHostAtomicCapabilities` + """ + cdef unsigned int count = len(operations) + cdef object capabilities = _numpy.empty(count, dtype=_numpy.uint32) + cdef intptr_t caps_ptr = capabilities.ctypes.data + cdef Py_buffer _ops_view_ + _acquire_buffer(operations, &_ops_view_) + try: + with nogil: + __status__ = cuDeviceGetHostAtomicCapabilities( + caps_ptr, + _ops_view_.buf, + count, + dev, + ) + check_status(__status__) + return capabilities + finally: + PyBuffer_Release(&_ops_view_) + + +cpdef egl_stream_producer_present_frame(intptr_t conn, intptr_t eglframe, intptr_t p_stream): + """Present a CUDA eglFrame to the EGL stream. + + When a frame is presented by the producer it gets associated with the + EGLStream; freeing the frame before the producer is disconnected leads to + undefined behavior. If producer and consumer are on different GPUs (iGPU + and dGPU), ``CU_EGL_FRAME_TYPE_ARRAY`` is not supported — + ``CU_EGL_FRAME_TYPE_PITCH`` must be used instead. + + For ``CU_EGL_FRAME_TYPE_PITCH`` frames, the application may present a + sub-region of a memory allocation by setting the pitched pointer to the + start address of the sub-region. + + Args: + conn (intptr_t): Connection handle returned by :func:`egl_stream_producer_connect`. + eglframe (intptr_t): Pointer to a ``CUeglFrame`` struct containing the frame to present. + p_stream (intptr_t): Stream on which to present the frame. + + .. seealso:: `cuEGLStreamProducerPresentFrame` + """ + cdef CUeglStreamConnection _conn_ = conn + cdef CUstream _p_stream_ = p_stream + with nogil: + __status__ = cuEGLStreamProducerPresentFrame(&_conn_, (eglframe)[0], &_p_stream_) + check_status(__status__) + + +cpdef egl_stream_producer_return_frame(intptr_t conn, intptr_t eglframe, intptr_t p_stream): + """Return a CUDA eglFrame to the EGL stream released by the consumer. + + This API can potentially return ``CUDA_ERROR_LAUNCH_TIMEOUT`` if the + consumer has not returned a frame to the EGL stream. If timeout is + returned, the application can retry. + + Args: + conn (intptr_t): Connection handle returned by :func:`egl_stream_producer_connect`. + eglframe (intptr_t): Pointer to a ``CUeglFrame`` that will receive the returned frame. + p_stream (intptr_t): Stream on which to return the frame. + + .. seealso:: `cuEGLStreamProducerReturnFrame` + """ + cdef CUeglStreamConnection _conn_ = conn + cdef CUstream _p_stream_ = p_stream + with nogil: + __status__ = cuEGLStreamProducerReturnFrame(&_conn_, eglframe, &_p_stream_) + check_status(__status__) + + +cpdef graphics_resource_get_mapped_egl_frame(intptr_t egl_frame, intptr_t resource, unsigned int index, unsigned int mip_level): + """Get an EGL frame through which to access a registered EGL resource. + + Returns an eglFrame pointer through which the registered graphics resource + ``resource`` may be accessed. This API can only be called for registered + EGL graphics resources. If ``resource`` is not registered, + ``CUDA_ERROR_NOT_MAPPED`` is returned. + + Args: + egl_frame (intptr_t): Pointer to a ``CUeglFrame`` that will receive the frame data. + resource (intptr_t): Registered graphics resource to access. + index (unsigned int): Index for array textures. + mip_level (unsigned int): Mipmap level for the resource. + + .. seealso:: `cuGraphicsResourceGetMappedEglFrame` + """ + with nogil: + __status__ = cuGraphicsResourceGetMappedEglFrame(egl_frame, resource, index, mip_level) + check_status(__status__) + + +cpdef intptr_t device_get_nv_sci_sync_attributes(intptr_t nv_sci_sync_attr_list, int dev, int flags): + """Fill in NvSciSync attributes for the given CUDA device. + + Returns in ``nv_sci_sync_attr_list`` the properties of NvSciSync that + ``dev`` can support. The list can be used to create an NvSciSync object + that matches this device's capabilities. + + The ``flags`` controls how the application intends to use the NvSciSync: + + - ``CUDA_NVSCISYNC_ATTR_SIGNAL``: the application intends to signal an + NvSciSync on this device. + + - ``CUDA_NVSCISYNC_ATTR_WAIT``: the application intends to wait on an + NvSciSync on this device. + + At least one flag must be set. Both flags are orthogonal and may be + combined. If ``NvSciSyncAttrKey_RequiredPerm`` is already set in + ``nv_sci_sync_attr_list``, this API returns ``CUDA_ERROR_INVALID_VALUE``. + + Args: + nv_sci_sync_attr_list (intptr_t): Allocated NvSciSyncAttrList handle to fill. + dev (int): CUDA device ordinal. + flags (int): Flags controlling which attributes are set. + + Returns: + intptr_t: The same ``nv_sci_sync_attr_list`` handle after being populated. + + .. seealso:: `cuDeviceGetNvSciSyncAttributes` + """ + with nogil: + __status__ = cuDeviceGetNvSciSyncAttributes(nv_sci_sync_attr_list, dev, flags) + check_status(__status__) + return nv_sci_sync_attr_list + + +cpdef object gl_get_devices_v2(int device_list): + """Gets the CUDA devices associated with the current OpenGL context. + + Returns the CUDA-compatible devices for the current OpenGL context. If any + of the GPUs used by the current OpenGL context are not CUDA-capable, + ``CUDA_ERROR_NO_DEVICE`` is returned. + + The ``device_list`` argument may be one of ``CU_GL_DEVICE_LIST_ALL`` (all + devices used by the context), ``CU_GL_DEVICE_LIST_CURRENT_FRAME`` (devices + rendering the current frame), or ``CU_GL_DEVICE_LIST_NEXT_FRAME`` (devices + predicted to render the next frame, SLI only). + + .. note:: + This function is not supported on macOS. + + Uses a fixed 64-element buffer; returns only the devices actually present. + + Args: + device_list (int): The set of devices to return (one of :class:`CUGLDeviceList`). + + Returns: + object: numpy ``int32`` array of the CUDA device ordinals associated with + the current OpenGL context. + + .. seealso:: `cuGLGetDevices` + """ + cdef unsigned int count = 0 + cdef CUdevice buf[64] + with nogil: + __status__ = cuGLGetDevices(&count, buf, 64, device_list) + check_status(__status__) + cdef object result = _numpy.empty(count, dtype=_numpy.int32) + cdef unsigned int i + for i in range(count): + result[i] = buf[i] + return result + + +cpdef tuple graph_get_edges(intptr_t h_graph): + """Returns the edges of a CUDA graph, including edge data. + + Alias for :func:`graph_get_edges_v2`. Available on CUDA 13.0 and later + where ``cuGraphGetEdges`` is an alias for ``cuGraphGetEdges_v2``. + + Args: + h_graph (intptr_t): Graph handle. + + Returns: + tuple: (from_nodes, to_nodes, edge_data) where ``from_nodes`` and + ``to_nodes`` are ``intp`` numpy arrays of node handles and + ``edge_data`` is a :class:`GraphEdgeData` instance. + + .. seealso:: `cuGraphGetEdges` + """ + return graph_get_edges_v2(h_graph) + + +cpdef tuple graph_node_get_dependencies(intptr_t h_node): + """Returns the dependencies of a CUDA graph node, including edge data. + + Alias for :func:`graph_node_get_dependencies_v2`. Available on CUDA 13.0 + and later where ``cuGraphNodeGetDependencies`` is an alias for + ``cuGraphNodeGetDependencies_v2``. + + Args: + h_node (intptr_t): Graph node handle. + + Returns: + tuple: (dependencies, edge_data) where ``dependencies`` is an ``intp`` + numpy array of node handles and ``edge_data`` is a + :class:`GraphEdgeData` instance. + + .. seealso:: `cuGraphNodeGetDependencies` + """ + return graph_node_get_dependencies_v2(h_node) + + +cpdef tuple graph_node_get_dependent_nodes(intptr_t h_node): + """Returns the dependent nodes of a CUDA graph node, including edge data. + + Alias for :func:`graph_node_get_dependent_nodes_v2`. Available on CUDA + 13.0 and later where ``cuGraphNodeGetDependentNodes`` is an alias for + ``cuGraphNodeGetDependentNodes_v2``. + + Args: + h_node (intptr_t): Graph node handle. + + Returns: + tuple: (dependent_nodes, edge_data) where ``dependent_nodes`` is an + ``intp`` numpy array of node handles and ``edge_data`` is a + :class:`GraphEdgeData` instance. + + .. seealso:: `cuGraphNodeGetDependentNodes` + """ + return graph_node_get_dependent_nodes_v2(h_node) + + +cpdef bytes kernel_get_name(intptr_t hfunc): + """Return the name of a CUDA kernel. + + Returns the function name associated with the kernel handle ``hfunc`` as a + null-terminated string. The returned name is only valid while the kernel + handle is valid; if the library is unloaded or reloaded, call this API + again to get the updated name. The name may be mangled if the function is + not declared with C linkage. + + Args: + hfunc (intptr_t): Kernel handle. + + Returns: + bytes: The kernel name, or ``b""`` if not available. + + .. seealso:: `cuKernelGetName` + """ + cdef const char* name = NULL + with nogil: + __status__ = cuKernelGetName(&name, hfunc) + check_status(__status__) + if name == NULL: + return b"" + return name + + +cpdef memcpy_batch_async(object dsts, object srcs, object sizes, + object attrs, object attrs_idxs, intptr_t h_stream): + """Perform a batch of memory copies asynchronously. + + 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 use + ``cuMemcpy3DBatchAsync``. + + Every copy in the batch must be associated with a set of attributes via + ``attrs``. Each entry in ``attrs`` can apply to more than one copy; the + ``attrs_idxs`` array gives the index of the first copy each attribute entry + applies to. The first entry in ``attrs_idxs`` must always be 0, entries + must be strictly increasing, and ``len(attrs)`` must be ≤ ``len(dsts)``. + + ``CUmemcpyAttributes.srcAccessOrder`` controls source access ordering: + + - ``CU_MEMCPY_SRC_ACCESS_ORDER_STREAM``: source is accessed in stream + order. + - ``CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL``: source access is out of + stream order but all accesses complete before the API returns (suited for + ephemeral stack variables; allows the driver to optimize the copy and + removes the need for a stream sync after the call). + - ``CU_MEMCPY_SRC_ACCESS_ORDER_ANY``: source access is out of stream order + and accesses may occur even after the API returns (suited for + non-CUDA-allocated host pointers such as those from ``malloc``). + + Each copy must have a valid ``CUmemcpyAttributes`` with an appropriate + ``srcAccessOrder``; otherwise ``CUDA_ERROR_INVALID_VALUE`` is returned. + + ``dsts``, ``srcs``, and ``sizes`` must all have the same length; ``count`` + is inferred from that length. ``attrs`` and ``attrs_idxs`` must both be + ``None`` or both be provided with the same length; ``numAttrs`` is inferred + from that length. + + Args: + dsts: Buffer of destination device pointers (e.g. numpy ``uint64`` array). + srcs: Buffer of source device pointers (e.g. numpy ``uint64`` array). + sizes: Buffer of copy sizes in bytes (e.g. numpy ``uint64`` array). + attrs: Buffer of :class:`CUmemcpyAttributes` values, or ``None``. + attrs_idxs: Buffer of per-attribute copy indices parallel to ``attrs``, + or ``None`` if ``attrs`` is ``None``. + h_stream (intptr_t): Stream on which to perform the copies. + + .. seealso:: `cuMemcpyBatchAsync` + """ + if len(dsts) != len(srcs) or len(dsts) != len(sizes): + raise ValueError( + f"dsts, srcs, and sizes must have the same length, " + f"got {len(dsts)}, {len(srcs)}, {len(sizes)}" + ) + cdef size_t count = len(dsts) + if (attrs is None) != (attrs_idxs is None): + raise ValueError("attrs and attrs_idxs must both be None or both be provided") + if attrs is not None and len(attrs) != len(attrs_idxs): + raise ValueError( + f"attrs and attrs_idxs must have the same length, " + f"got {len(attrs)}, {len(attrs_idxs)}" + ) + cdef size_t num_attrs = 0 if attrs is None else len(attrs) + cdef Py_buffer _dsts_view_, _srcs_view_, _sizes_view_ + cdef Py_buffer _attrs_view_, _attrs_idxs_view_ + cdef bint _attrs_acq_ = False, _attrs_idxs_acq_ = False + cdef void* _attrs_ptr_ = NULL + cdef void* _attrs_idxs_ptr_ = NULL + PyObject_GetBuffer(dsts, &_dsts_view_, PyBUF_ANY_CONTIGUOUS) + try: + PyObject_GetBuffer(srcs, &_srcs_view_, PyBUF_ANY_CONTIGUOUS) + try: + PyObject_GetBuffer(sizes, &_sizes_view_, PyBUF_ANY_CONTIGUOUS) + try: + if attrs is not None: + PyObject_GetBuffer(attrs, &_attrs_view_, PyBUF_ANY_CONTIGUOUS) + _attrs_acq_ = True + _attrs_ptr_ = _attrs_view_.buf + if attrs_idxs is not None: + PyObject_GetBuffer(attrs_idxs, &_attrs_idxs_view_, PyBUF_ANY_CONTIGUOUS) + _attrs_idxs_acq_ = True + _attrs_idxs_ptr_ = _attrs_idxs_view_.buf + with nogil: + __status__ = cuMemcpyBatchAsync( + _dsts_view_.buf, + _srcs_view_.buf, + _sizes_view_.buf, + count, + _attrs_ptr_, + _attrs_idxs_ptr_, + num_attrs, + h_stream, + ) + check_status(__status__) + finally: + PyBuffer_Release(&_sizes_view_) + if _attrs_acq_: + PyBuffer_Release(&_attrs_view_) + if _attrs_idxs_acq_: + PyBuffer_Release(&_attrs_idxs_view_) + finally: + PyBuffer_Release(&_srcs_view_) + finally: + PyBuffer_Release(&_dsts_view_) + + +cpdef bytes func_get_name(intptr_t hfunc): + """Returns the function name for a CUfunction 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. + + Args: + hfunc (intptr_t): Function handle. + + Returns: + bytes: The function name, or ``b""`` if not available. + + .. seealso:: `cuFuncGetName` + """ + cdef const char* name = NULL + with nogil: + __status__ = cuFuncGetName(&name, hfunc) + check_status(__status__) + if name == NULL: + return b"" + return name + + + +############################################################################### +# Kernel launch functions — kernel_params uses _HelperKernelParams +############################################################################### + +# Helper copied verbatim from cuda.bindings._lib.utils so that _v2.driver does +# not depend on the legacy cuda.bindings.driver module. Kernel_params accepts: +# - int → raw void** address +# - None → NULL +# - buffer object → void** from the buffer's data pointer +# - ((values,), (ctypes,)) → construct void** array from Python ctypes values + +cdef void* _callocWrapper(length, size): + cdef void* out = calloc(length, size) + if out is NULL: + raise MemoryError('Failed to allocated length x size memory: {}x{}'.format(length, size)) + return out + +cdef class _HelperKernelParams: + # cdef attributes (normally in utils.pxd; inlined here so no separate .pxd needed) + cdef Py_buffer _pybuffer + cdef bint _pyobj_acquired + cdef void** _ckernelParams + cdef char* _ckernelParamsData + cdef int _length + cdef bint _malloc_list_created + + supported_types = { # excluding void_p and None, which are handled specially + _ctypes.c_bool, + _ctypes.c_char, + _ctypes.c_wchar, + _ctypes.c_byte, + _ctypes.c_ubyte, + _ctypes.c_short, + _ctypes.c_ushort, + _ctypes.c_int, + _ctypes.c_uint, + _ctypes.c_long, + _ctypes.c_ulong, + _ctypes.c_longlong, + _ctypes.c_ulonglong, + _ctypes.c_size_t, + _ctypes.c_float, + _ctypes.c_double + } + + max_param_size = max(_ctypes.sizeof(max(_HelperKernelParams.supported_types, key=lambda t: _ctypes.sizeof(t))), sizeof(intptr_t)) + + def __cinit__(self, kernelParams): + self._pyobj_acquired = False + self._malloc_list_created = False + if kernelParams is None: + self._ckernelParams = NULL + elif isinstance(kernelParams, (int)): + self._ckernelParams = kernelParams + elif PyObject_CheckBuffer(kernelParams): + err_buffer = PyObject_GetBuffer(kernelParams, &self._pybuffer, PyBUF_SIMPLE | PyBUF_ANY_CONTIGUOUS) + if err_buffer == -1: + raise RuntimeError("Argument 'kernelParams' failed to retrieve buffer through Buffer Protocol") + self._pyobj_acquired = True + self._ckernelParams = self._pybuffer.buf + elif isinstance(kernelParams, (tuple)) and len(kernelParams) == 2 and isinstance(kernelParams[0], (tuple)) and isinstance(kernelParams[1], (tuple)): + if len(kernelParams[0]) != len(kernelParams[1]): + raise TypeError("Argument 'kernelParams' has tuples with different length") + if len(kernelParams[0]) != 0: + self._length = len(kernelParams[0]) + self._ckernelParams = _callocWrapper(len(kernelParams[0]), sizeof(void*)) + self._ckernelParamsData = _callocWrapper(len(kernelParams[0]), _HelperKernelParams.max_param_size) + self._malloc_list_created = True + idx = 0 + data_idx = 0 + for value, ctype in zip(kernelParams[0], kernelParams[1]): + if ctype is None: + if callable(getattr(value, 'getPtr', None)): + self._ckernelParams[idx] = value.getPtr() + elif getattr(value, 'ptr', None) is not None: + # cybind-generated wrapper classes (e.g. AUTO_LOWPP_CLASS + # POD structs) expose their address via a `ptr` property + # rather than a `getPtr()` method. + self._ckernelParams[idx] = value.ptr + elif isinstance(value, (_ctypes.Structure)): + self._ckernelParams[idx] = _ctypes.addressof(value) + elif isinstance(value, (_FastEnum)): + self._ckernelParams[idx] = &(self._ckernelParamsData[data_idx]) + (self._ckernelParams[idx])[0] = value.value + data_idx += sizeof(int) + else: + raise TypeError("Provided argument is of type {} but expected Type {}, {} or CUDA Binding structure with getPtr() attribute".format(type(value), type(_ctypes.Structure), type(_ctypes.c_void_p))) + elif ctype in _HelperKernelParams.supported_types: + self._ckernelParams[idx] = &(self._ckernelParamsData[data_idx]) + if ctype == _ctypes.c_double and isinstance(value, _ctypes.c_float): + value = ctype(value.value) + if not isinstance(value, ctype): + size = _param_packer.feed(self._ckernelParams[idx], value, ctype) + if size == 0: + value = ctype(value) + size = _ctypes.sizeof(ctype) + addr = (_ctypes.addressof(value)) + memcpy(self._ckernelParams[idx], addr, size) + else: + size = _ctypes.sizeof(ctype) + addr = (_ctypes.addressof(value)) + memcpy(self._ckernelParams[idx], addr, size) + data_idx += size + elif ctype == _ctypes.c_void_p: + if isinstance(value, (int, _ctypes.c_void_p)): + self._ckernelParams[idx] = &(self._ckernelParamsData[data_idx]) + (self._ckernelParams[idx])[0] = value.value if isinstance(value, (_ctypes.c_void_p)) else value + data_idx += sizeof(intptr_t) + elif callable(getattr(value, 'getPtr', None)): + self._ckernelParams[idx] = &(self._ckernelParamsData[data_idx]) + (self._ckernelParams[idx])[0] = value.getPtr() + data_idx += sizeof(intptr_t) + elif getattr(value, 'ptr', None) is not None: + # cybind-generated wrapper classes (e.g. AUTO_LOWPP_CLASS + # POD structs) expose their address via a `ptr` property + # rather than a `getPtr()` method. + self._ckernelParams[idx] = &(self._ckernelParamsData[data_idx]) + (self._ckernelParams[idx])[0] = value.ptr + data_idx += sizeof(intptr_t) + else: + raise TypeError("Provided argument is of type {} but expected Type {}, {} or CUDA Binding structure with getPtr() attribute".format(type(value), type(int), type(_ctypes.c_void_p))) + else: + raise TypeError("Unsupported type: " + str(type(ctype))) + idx += 1 + else: + raise TypeError("Argument 'kernelParams' is not a valid type: tuple[tuple[Any, ...], tuple[Any, ...]] or PyObject implimenting Buffer Protocol or Int") + + def __dealloc__(self): + if self._pyobj_acquired is True: + PyBuffer_Release(&self._pybuffer) + if self._malloc_list_created is True: + free(self._ckernelParams) + free(self._ckernelParamsData) + + @property + def ckernelParams(self): + return self._ckernelParams + + +cpdef launch_kernel(intptr_t f, unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, unsigned int block_dim_x, unsigned int block_dim_y, unsigned int block_dim_z, unsigned int shared_mem_bytes, intptr_t h_stream, kernel_params, intptr_t extra): + """Launch a CUDA kernel. + + Invokes the kernel ``f`` on a ``grid_dim_x`` × ``grid_dim_y`` × + ``grid_dim_z`` grid of blocks with ``block_dim_x`` × ``block_dim_y`` × + ``block_dim_z`` threads per block and ``shared_mem_bytes`` bytes of dynamic + shared memory per block. + + Args: + f (intptr_t): Kernel / function handle. + grid_dim_x (unsigned int): Width of grid in blocks. + grid_dim_y (unsigned int): Height of grid in blocks. + grid_dim_z (unsigned int): Depth of grid in blocks. + block_dim_x (unsigned int): X dimension of each thread block. + block_dim_y (unsigned int): Y dimension of each thread block. + block_dim_z (unsigned int): Z dimension of each thread block. + shared_mem_bytes (unsigned int): Dynamic shared-memory size per thread + block in bytes. + h_stream (intptr_t): Stream on which to enqueue the launch. + kernel_params: Kernel parameters. Accepted forms: + + - ``int`` — raw ``void**`` address of a pre-constructed parameter array. + - ``None`` — pass ``NULL`` (use the ``extra`` path instead). + - buffer — any Python buffer-protocol object whose data pointer is + used directly as a ``void**`` array. + - ``((values,), (ctypes,))`` — 2-tuple of equal-length tuples; the + helper constructs the ``void**`` array from the given ctypes values. + + extra (intptr_t): Alternative kernel-parameter buffer (``void**``); pass + ``0`` when using ``kernel_params``. + + .. seealso:: `cuLaunchKernel` + """ + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kp_ptr_ = _kp_.ckernelParams + with nogil: + __status__ = cuLaunchKernel( + f, + grid_dim_x, grid_dim_y, grid_dim_z, + block_dim_x, block_dim_y, block_dim_z, + shared_mem_bytes, h_stream, + _kp_ptr_, extra, + ) + check_status(__status__) + + +cpdef launch_kernel_ex(config, intptr_t f, kernel_params, intptr_t extra): + """Launch a CUDA kernel with launch-time configuration. + + Invokes the kernel ``f`` with the :class:`LaunchConfig` ``config``. + + Args: + config (LaunchConfig): Launch configuration struct. + f (intptr_t): Kernel / function handle. + kernel_params: Kernel parameters — same accepted forms as + :func:`launch_kernel`. + extra (intptr_t): Alternative kernel-parameter buffer; pass ``0`` + when using ``kernel_params``. + + .. seealso:: `cuLaunchKernelEx` + """ + cdef intptr_t _config_ptr_ = (config)._get_ptr() + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kp_ptr_ = _kp_.ckernelParams + with nogil: + __status__ = cuLaunchKernelEx( + _config_ptr_, + f, + _kp_ptr_, extra, + ) + check_status(__status__) + + +cpdef launch_cooperative_kernel(intptr_t f, unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, unsigned int block_dim_x, unsigned int block_dim_y, unsigned int block_dim_z, unsigned int shared_mem_bytes, intptr_t h_stream, kernel_params): + """Launch a CUDA cooperative kernel. + + Like :func:`launch_kernel` but enables threads across blocks to cooperate + via ``cudaGridGroup`` and related primitives. + + Args: + f (intptr_t): Kernel / function handle. + grid_dim_x (unsigned int): Width of grid in blocks. + grid_dim_y (unsigned int): Height of grid in blocks. + grid_dim_z (unsigned int): Depth of grid in blocks. + block_dim_x (unsigned int): X dimension of each thread block. + block_dim_y (unsigned int): Y dimension of each thread block. + block_dim_z (unsigned int): Z dimension of each thread block. + shared_mem_bytes (unsigned int): Dynamic shared-memory size per thread + block in bytes. + h_stream (intptr_t): Stream on which to enqueue the launch. + kernel_params: Kernel parameters — same accepted forms as + :func:`launch_kernel`. + + .. seealso:: `cuLaunchCooperativeKernel` + """ + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kp_ptr_ = _kp_.ckernelParams + with nogil: + __status__ = cuLaunchCooperativeKernel( + f, + grid_dim_x, grid_dim_y, grid_dim_z, + block_dim_x, block_dim_y, block_dim_z, + shared_mem_bytes, h_stream, + _kp_ptr_, + ) + check_status(__status__) + + +cpdef init(unsigned int flags): + """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. Currently, the ``flags`` parameter must be 0. If :func:`init` has not been called, any function from the driver API will return ``CUDA_ERROR_NOT_INITIALIZED``. + + Note: cuInit 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. + + Args: + flags (unsigned int): Initialization flag for CUDA. + + .. seealso:: `cuInit` + """ + with nogil: + __status__ = cuInit(flags) + check_status(__status__) + + +cpdef int driver_get_version() except? -1: + """Returns the latest CUDA version supported by driver. + + Returns in ``*driver_version`` 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 ``CUDA_ERROR_INVALID_VALUE`` if + ``driver_version`` is NULL. + + Returns: + int: Returns the CUDA driver version. + + .. seealso:: `cuDriverGetVersion` + """ + cdef int driver_version + with nogil: + __status__ = cuDriverGetVersion(&driver_version) + check_status(__status__) + return driver_version + + +cpdef int device_get(int ordinal) except? -1: + """Returns a handle to a compute device. + + Returns in ``*device`` a device handle given an ordinal in the range [0, + :func:`device_get_count`-1]. + + Args: + ordinal (int): Device number to get handle for. + + Returns: + int: Returned device handle. + + .. seealso:: `cuDeviceGet` + """ + cdef CUdevice device + with nogil: + __status__ = cuDeviceGet(&device, ordinal) + check_status(__status__) + return device + + +cpdef int device_get_count() except? -1: + """Returns the number of compute-capable devices. + + Returns in ``*count`` 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, :func:`device_get_count` returns 0. + + Returns: + int: Returned number of compute-capable devices. + + .. seealso:: `cuDeviceGetCount` + """ + cdef int count + with nogil: + __status__ = cuDeviceGetCount(&count) + check_status(__status__) + return count + + +cpdef bytes device_get_name(int len, int dev): + """Returns an identifier string for the device. + + Returns an ASCII string identifying the device ``dev`` in the NULL- + terminated string pointed to by ``name``. ``length`` specifies the maximum + length of the string that may be returned. ``name`` is shortened to the + specified ``length``, if ``length`` is less than the device name. + + Args: + len (int): Maximum length of string to store in ``name``. + dev (int): Device to get identifier string for. + + Returns: + char: Returned identifier string for the device. + + .. seealso:: `cuDeviceGetName` + """ + cdef bytes _name_ = bytes(len) + cdef char* name = _name_ + with nogil: + __status__ = cuDeviceGetName(name, len, dev) + check_status(__status__) + return _name_ + + +cpdef object device_get_uuid_v2(int dev): + """Return 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. + + Args: + dev (int): Device to get identifier string for. + + Returns: + CUuuid: Returned UUID. + + .. seealso:: `cuDeviceGetUuid_v2` + """ + cdef Uuid uuid_py = Uuid() + cdef CUuuid *uuid = (uuid_py._get_ptr()) + with nogil: + __status__ = cuDeviceGetUuid(uuid, dev) + check_status(__status__) + return uuid_py + + +cpdef tuple device_get_luid(int dev): + """Return an LUID and device node mask for the device. + + Return identifying information (``luid`` and ``device_node_mask``) to allow + matching device with graphics APIs. + + Args: + dev (int): Device to get identifier string for. + + Returns: + A 2-tuple containing: + + - char: Returned LUID. + - unsigned int: Returned device node mask. + + .. seealso:: `cuDeviceGetLuid` + """ + cdef char[8] luid + cdef unsigned int device_node_mask + with nogil: + __status__ = cuDeviceGetLuid(luid, &device_node_mask, dev) + check_status(__status__) + return (_cyb_cpython.PyBytes_FromStringAndSize(luid, 8), device_node_mask) + + +cpdef size_t device_total_mem_v2(int dev) except? 0: + """Returns the total amount of memory on the device. + + Returns in ``*bytes`` the total amount of memory available on the device + ``dev`` in bytes. + + Args: + dev (int): Device handle. + + Returns: + size_t: Returned memory available on device in bytes. + + .. seealso:: `cuDeviceTotalMem_v2` + """ + cdef size_t bytes + with nogil: + __status__ = cuDeviceTotalMem(&bytes, dev) + check_status(__status__) + return bytes + + +cpdef size_t device_get_texture_1d_linear_max_width(int format, unsigned num_channels, int dev) except? 0: + """Returns the maximum number of elements allocatable in a 1D linear texture for a given texture element size. + + Returns in ``max_width_in_elements`` the maximum number of texture elements + allocatable in a 1D linear texture for given ``pformat`` and + ``num_channels``. + + Args: + format (ArrayFormat): Texture format. + num_channels (unsigned): Number of channels per texture + element. + dev (int): Device handle. + + Returns: + size_t: Returned maximum number of texture elements + allocatable for given ``pformat`` and ``num_channels``. + + .. seealso:: `cuDeviceGetTexture1DLinearMaxWidth` + """ + cdef size_t max_width_in_elements + with nogil: + __status__ = cuDeviceGetTexture1DLinearMaxWidth(&max_width_in_elements, format, num_channels, dev) + check_status(__status__) + return max_width_in_elements + + +cpdef int device_get_attribute(int attrib, int dev) except? -1: + """Returns information about the device. + + Returns in ``*pi`` the integer value of the attribute ``attrib`` on device + ``dev``. + + Args: + attrib (DeviceAttribute): Device attribute to query. + dev (int): Device handle. + + Returns: + int: Returned device attribute value. + + .. seealso:: `cuDeviceGetAttribute` + """ + cdef int pi + with nogil: + __status__ = cuDeviceGetAttribute(&pi, attrib, dev) + check_status(__status__) + return pi + + +cpdef device_set_mem_pool(int dev, intptr_t pool): + """Sets the current memory pool of a device. + + The memory pool must be local to the specified device. ``cuMemAllocAsync`` + allocates from the current mempool of the provided stream's device. By + default, a device's current memory pool is its default memory pool. + + Args: + dev (int): Device to set the current memory pool for. + pool (intptr_t): Memory pool to use as the device's current + memory pool. + + .. note:: + Use ``cuMemAllocFromPoolAsync`` to specify asynchronous allocations + from a device different than the one the stream runs on. + + .. seealso:: `cuDeviceSetMemPool` + """ + with nogil: + __status__ = cuDeviceSetMemPool(dev, pool) + check_status(__status__) + + +cpdef intptr_t device_get_mem_pool(int dev) except? 0: + """Gets the current mempool for a device. + + Returns the last pool provided to ``cuDeviceSetMemPool`` for this device or + the device's default memory pool if ``cuDeviceSetMemPool`` 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 ``cuDeviceSetMemPool``. + + Args: + dev (int): Device for which to query the current memory pool. + + Returns: + intptr_t: Returned current memory pool of the device. + + .. seealso:: `cuDeviceGetMemPool` + """ + cdef CUmemoryPool pool + with nogil: + __status__ = cuDeviceGetMemPool(&pool, dev) + check_status(__status__) + return pool + + +cpdef intptr_t device_get_default_mem_pool(int dev) except? 0: + """Returns the default mempool of a device. + + The default mempool of a device contains device memory from that device. + + Args: + dev (int): Device for which to query the default memory pool. + + Returns: + intptr_t: Returned default memory pool of the device. + + .. seealso:: `cuDeviceGetDefaultMemPool` + """ + cdef CUmemoryPool pool_out + with nogil: + __status__ = cuDeviceGetDefaultMemPool(&pool_out, dev) + check_status(__status__) + return pool_out + + +cpdef int device_get_exec_affinity_support(int type, int dev) except? -1: + """Returns information about the execution affinity support of the device. + + Returns in ``*pi`` whether execution affinity type ``typename`` is + supported by device ``dev``. The supported types are:. + + - ``CU_EXEC_AFFINITY_TYPE_SM_COUNT``: 1 if context with limited SMs is + supported by the device, or 0 if not;. + + Args: + type (ExecAffinityType): Execution affinity type to query. + dev (int): Device handle. + + Returns: + int: 1 if the execution affinity type ``typename`` is + supported by the device, or 0 if not. + + .. seealso:: `cuDeviceGetExecAffinitySupport` + """ + cdef int pi + with nogil: + __status__ = cuDeviceGetExecAffinitySupport(&pi, type, dev) + check_status(__status__) + return pi + + +cpdef flush_gpu_direct_rdma_writes(int target, int scope): + """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 + ``CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING``, 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 ``CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE``), 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``. + + Args: + target (FlushGPUDirectRDMAWritesTarget): The target of the + operation, see ``CUflushGPUDirectRDMAWritesTarget``. + scope (FlushGPUDirectRDMAWritesScope): The scope of the + operation, see ``CUflushGPUDirectRDMAWritesScope``. + + .. seealso:: `cuFlushGPUDirectRDMAWrites` + """ + with nogil: + __status__ = cuFlushGPUDirectRDMAWrites(target, scope) + check_status(__status__) + + +cpdef object device_get_properties(int dev): + """Returns properties for a selected device. + + [Deprecated]. + + This function was deprecated as of CUDA 5.0 and replaced by + :func:`device_get_attribute`. + + Returns in ``*prop`` the properties of device ``dev``. The ``CUdevprop`` + structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``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 ``cuMemAllocPitch()``;. + + - ``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. + + Args: + dev (int): Device to get properties for. + + Returns: + CUdevprop_v1: Returned properties of device. + + .. seealso:: `cuDeviceGetProperties` + """ + cdef Devprop_v1 prop_py = Devprop_v1() + cdef CUdevprop *prop = (prop_py._get_ptr()) + with nogil: + __status__ = cuDeviceGetProperties(prop, dev) + check_status(__status__) + return prop_py + + +cpdef tuple device_compute_capability(int dev): + """Returns the compute capability of the device. + + [Deprecated]. + + This function was deprecated as of CUDA 5.0 and its functionality + superseded by :func:`device_get_attribute`. + + Returns in ``*major`` and ``*minor`` the major and minor revision numbers + that define the compute capability of the device ``dev``. + + Args: + dev (int): Device handle. + + Returns: + A 2-tuple containing: + + - int: Major revision number. + - int: Minor revision number. + + .. seealso:: `cuDeviceComputeCapability` + """ + cdef int major + cdef int minor + with nogil: + __status__ = cuDeviceComputeCapability(&major, &minor, dev) + check_status(__status__) + return (major, minor) + + +cpdef intptr_t device_primary_ctx_retain(int dev) except? 0: + """Retain 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 + ``cuDevicePrimaryCtxRelease()`` or resets it with + ``cuDevicePrimaryCtxReset()``. Unlike ``cuCtxCreate()`` the newly retained + context is not pushed onto the stack. + + Retaining the primary context for the first time will fail with + ``CUDA_ERROR_UNKNOWN`` if the compute mode of the device is + ``CU_COMPUTEMODE_PROHIBITED``. The function :func:`device_get_attribute` + can be used with ``CU_DEVICE_ATTRIBUTE_COMPUTE_MODE`` 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 ``cuDevicePrimaryCtxSetFlags()``. + + Args: + dev (int): Device for which primary context is requested. + + Returns: + intptr_t: Returned context handle of the new context. + + .. seealso:: `cuDevicePrimaryCtxRetain` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuDevicePrimaryCtxRetain(&pctx, dev) + check_status(__status__) + return pctx + + +cpdef device_primary_ctx_release_v2(int dev): + """Release 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 ``CUDA_ERROR_INVALID_CONTEXT``. + + Please note that unlike ``cuCtxDestroy()`` this method does not pop the + context from stack in any circumstances. + + Args: + dev (int): Device which primary context is released. + + .. seealso:: `cuDevicePrimaryCtxRelease_v2` + """ + with nogil: + __status__ = cuDevicePrimaryCtxRelease(dev) + check_status(__status__) + + +cpdef device_primary_ctx_set_flags_v2(int dev, unsigned int flags): + """Set 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. + + - ``CU_CTX_SCHED_SPIN``: 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. + + - ``CU_CTX_SCHED_YIELD``: 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. + + - ``CU_CTX_SCHED_BLOCKING_SYNC``: Instruct CUDA to block the CPU thread on + a synchronization primitive when waiting for the GPU to finish work. + + - ``CU_CTX_BLOCKING_SYNC``: 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 + ``CU_CTX_SCHED_BLOCKING_SYNC``. + + - ``CU_CTX_SCHED_AUTO``: 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 (``CU_CTX_SCHED_YIELD``), otherwise CUDA will not yield while + waiting for results and actively spin on the processor + (``CU_CTX_SCHED_SPIN``). Additionally, on Tegra devices, + ``CU_CTX_SCHED_AUTO`` uses a heuristic based on the power profile of the + platform and may choose ``CU_CTX_SCHED_BLOCKING_SYNC`` for low-powered + devices. + + - ``CU_CTX_LMEM_RESIZE_TO_MAX``: 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. + + - ``CU_CTX_COREDUMP_ENABLE``: If GPU coredumps have not been enabled + globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttribute`` from the created context after it becomes + current. + + - ``CU_CTX_USER_COREDUMP_ENABLE``: If user-triggered GPU coredumps have not + been enabled globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttributeGlobal`` before creating the context if this flag + is used. Setting this flag implies that ``CU_CTX_COREDUMP_ENABLE`` 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 ``cuCoredumpSetAttribute`` from the created context + after it becomes current. + + - ``CU_CTX_SYNC_MEMOPS``: 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. + + Args: + dev (int): Device for which the primary context flags are set. + flags (unsigned int): New flags for the device. + + .. seealso:: `cuDevicePrimaryCtxSetFlags_v2` + """ + with nogil: + __status__ = cuDevicePrimaryCtxSetFlags(dev, flags) + check_status(__status__) + + +cpdef tuple device_primary_ctx_get_state(int dev): + """Get 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 ``cuDevicePrimaryCtxSetFlags`` for + flag values. + + Args: + dev (int): Device to get primary context flags for. + + Returns: + A 2-tuple containing: + + - unsigned int: Pointer to store flags. + - int: Pointer to store context state; 0 = inactive, 1 = active. + + .. seealso:: `cuDevicePrimaryCtxGetState` + """ + cdef unsigned int flags + cdef int active + with nogil: + __status__ = cuDevicePrimaryCtxGetState(dev, &flags, &active) + check_status(__status__) + return (flags, active) + + +cpdef device_primary_ctx_reset_v2(int dev): + """Destroy all allocations and reset 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 ``cuDevicePrimaryCtxRelease()`` in most cases. + However it is safe for other modules to call + ``cuDevicePrimaryCtxRelease()`` 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. + + Args: + dev (int): Device for which primary context is destroyed. + + .. seealso:: `cuDevicePrimaryCtxReset_v2` + """ + with nogil: + __status__ = cuDevicePrimaryCtxReset(dev) + check_status(__status__) + + +cpdef intptr_t ctx_create_v2(unsigned int flags, int dev) except? 0: + """Create 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 ``cuCtxCreate()`` must call ``cuCtxDestroy()`` + 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 ``cuCtxPopCurrent()``. + + 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. + + - ``CU_CTX_SCHED_SPIN``: 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. + + - ``CU_CTX_SCHED_YIELD``: 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. + + - ``CU_CTX_SCHED_BLOCKING_SYNC``: Instruct CUDA to block the CPU thread on + a synchronization primitive when waiting for the GPU to finish work. + + - ``CU_CTX_BLOCKING_SYNC``: 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 + ``CU_CTX_SCHED_BLOCKING_SYNC``. + + - ``CU_CTX_SCHED_AUTO``: 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 (``CU_CTX_SCHED_YIELD``), otherwise CUDA will not yield while + waiting for results and actively spin on the processor + (``CU_CTX_SCHED_SPIN``). Additionally, on Tegra devices, + ``CU_CTX_SCHED_AUTO`` uses a heuristic based on the power profile of the + platform and may choose ``CU_CTX_SCHED_BLOCKING_SYNC`` for low-powered + devices. + + - ``CU_CTX_MAP_HOST``: 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. + + - ``CU_CTX_LMEM_RESIZE_TO_MAX``: 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 :func:`ctx_set_limit`. + + - ``CU_CTX_COREDUMP_ENABLE``: If GPU coredumps have not been enabled + globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttribute`` from the created context after it becomes + current. + + - ``CU_CTX_USER_COREDUMP_ENABLE``: If user-triggered GPU coredumps have not + been enabled globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttributeGlobal`` before creating the context if this flag + is used. Setting this flag implies that ``CU_CTX_COREDUMP_ENABLE`` 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 ``cuCoredumpSetAttribute`` from the created context + after it becomes current. Setting this flag on any context creation is + equivalent to setting the ``CU_COREDUMP_ENABLE_USER_TRIGGER`` attribute to + ``true`` globally. + + - ``CU_CTX_SYNC_MEMOPS``: 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 ``CUDA_ERROR_UNKNOWN`` if the compute mode + of the device is ``CU_COMPUTEMODE_PROHIBITED``. The function + :func:`device_get_attribute` can be used with + ``CU_DEVICE_ATTRIBUTE_COMPUTE_MODE`` 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. + + Args: + flags (unsigned int): Context creation flags. + dev (int): Device to create context on. + + Returns: + intptr_t: Returned context handle of the new context. + + .. note:: + In most cases it is recommended to use ``cuDevicePrimaryCtxRetain``. + + .. seealso:: `cuCtxCreate_v2` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuCtxCreate_v2(&pctx, flags, dev) + check_status(__status__) + return pctx + + +cpdef intptr_t ctx_create_v3(params_array, int num_params, unsigned int flags, int dev) except? 0: + """Create a CUDA context with execution affinity. + + Creates a new CUDA context with execution affinity and associates it with + the calling thread. The ``params_array`` and ``flags`` parameter are + described below. The context is created with a usage count of 1 and the + caller of ``cuCtxCreate()`` must call ``cuCtxDestroy()`` 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 ``cuCtxPopCurrent()``. + + The type and the amount of execution resource the context can use is + limited by ``params_array`` and ``num_params``. The ``params_array`` is an + array of ``CUexecAffinityParam`` and the ``num_params`` describes the size + of the array. If two ``CUexecAffinityParam`` in the array have the same + type, the latter execution affinity parameter overrides the former + execution affinity parameter. The supported execution affinity types are:. + + - ``CU_EXEC_AFFINITY_TYPE_SM_COUNT`` limits the portion of SMs that the + context can use. The portion of SMs is specified as the number of SMs via + ``CUexecAffinitySmCount``. 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 ``cuCtxGetExecAffinity`` after + context creation. Currently, this attribute is only supported under Volta+ + MPS. + + 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. + + - ``CU_CTX_SCHED_SPIN``: 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. + + - ``CU_CTX_SCHED_YIELD``: 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. + + - ``CU_CTX_SCHED_BLOCKING_SYNC``: Instruct CUDA to block the CPU thread on + a synchronization primitive when waiting for the GPU to finish work. + + - ``CU_CTX_BLOCKING_SYNC``: 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 + ``CU_CTX_SCHED_BLOCKING_SYNC``. + + - ``CU_CTX_SCHED_AUTO``: 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 (``CU_CTX_SCHED_YIELD``), otherwise CUDA will not yield while + waiting for results and actively spin on the processor + (``CU_CTX_SCHED_SPIN``). Additionally, on Tegra devices, + ``CU_CTX_SCHED_AUTO`` uses a heuristic based on the power profile of the + platform and may choose ``CU_CTX_SCHED_BLOCKING_SYNC`` for low-powered + devices. + + - ``CU_CTX_MAP_HOST``: 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. + + - ``CU_CTX_LMEM_RESIZE_TO_MAX``: 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 :func:`ctx_set_limit`. + + - ``CU_CTX_COREDUMP_ENABLE``: If GPU coredumps have not been enabled + globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttribute`` from the created context after it becomes + current. + + - ``CU_CTX_USER_COREDUMP_ENABLE``: If user-triggered GPU coredumps have not + been enabled globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttributeGlobal`` before creating the context if this flag + is used. Setting this flag implies that ``CU_CTX_COREDUMP_ENABLE`` 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 ``cuCoredumpSetAttribute`` from the created context + after it becomes current. Setting this flag on any context creation is + equivalent to setting the ``CU_COREDUMP_ENABLE_USER_TRIGGER`` attribute to + ``true`` globally. + + Context creation will fail with ``CUDA_ERROR_UNKNOWN`` if the compute mode + of the device is ``CU_COMPUTEMODE_PROHIBITED``. The function + :func:`device_get_attribute` can be used with + ``CU_DEVICE_ATTRIBUTE_COMPUTE_MODE`` 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. + + Args: + params_array (intptr_t): Execution affinity parameters. + num_params (int): Number of execution affinity parameters. + flags (unsigned int): Context creation flags. + dev (int): Device to create context on. + + Returns: + intptr_t: Returned context handle of the new context. + + .. seealso:: `cuCtxCreate_v3` + """ + cdef intptr_t _params_array_ptr_ = int(params_array) + cdef CUcontext pctx + with nogil: + __status__ = cuCtxCreate_v3(&pctx, _params_array_ptr_, num_params, flags, dev) + check_status(__status__) + return pctx + + +cpdef intptr_t ctx_create_v4(ctx_create_params, unsigned int flags, int dev) except? 0: + """Create 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 ``cuCtxCreate()`` must call ``cuCtxDestroy()`` + 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 ``cuCtxPopCurrent()``. + + A regular CUDA context can be created by setting ``ctx_create_params`` 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 ``CUexecAffinityParam`` and the + ``numExecAffinityParams`` describes the size of the paramsArray. If two + ``CUexecAffinityParam`` in the array have the same type, the latter + execution affinity parameter overrides the former execution affinity + parameter. The supported execution affinity types are:. + + - ``CU_EXEC_AFFINITY_TYPE_SM_COUNT`` limits the portion of SMs that the + context can use. The portion of SMs is specified as the number of SMs via + ``CUexecAffinitySmCount``. 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 ``cuCtxGetExecAffinity`` 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 :func:`device_get_attribute` with + ``CU_DEVICE_ATTRIBUTE_D3D12_CIG_SUPPORTED``. ``sharedData`` is a + ID3D12CommandQueue handle. Support for Vulkan graphics client can be + determined using :func:`device_get_attribute` with + ``CU_DEVICE_ATTRIBUTE_VULKAN_CIG_SUPPORTED``. ``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. + + - ``CU_CTX_SCHED_SPIN``: 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. + + - ``CU_CTX_SCHED_YIELD``: 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. + + - ``CU_CTX_SCHED_BLOCKING_SYNC``: Instruct CUDA to block the CPU thread on + a synchronization primitive when waiting for the GPU to finish work. + + - ``CU_CTX_BLOCKING_SYNC``: 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 + ``CU_CTX_SCHED_BLOCKING_SYNC``. + + - ``CU_CTX_SCHED_AUTO``: 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 (``CU_CTX_SCHED_YIELD``), otherwise CUDA will not yield while + waiting for results and actively spin on the processor + (``CU_CTX_SCHED_SPIN``). Additionally, on Tegra devices, + ``CU_CTX_SCHED_AUTO`` uses a heuristic based on the power profile of the + platform and may choose ``CU_CTX_SCHED_BLOCKING_SYNC`` for low-powered + devices. + + - ``CU_CTX_MAP_HOST``: 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. + + - ``CU_CTX_LMEM_RESIZE_TO_MAX``: 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 :func:`ctx_set_limit`. + + - ``CU_CTX_COREDUMP_ENABLE``: If GPU coredumps have not been enabled + globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttribute`` from the created context after it becomes + current. This flag is not supported when CUDA context is created in + CIG(CUDA in Graphics) mode. + + - ``CU_CTX_USER_COREDUMP_ENABLE``: If user-triggered GPU coredumps have not + been enabled globally with ``cuCoredumpSetAttributeGlobal`` 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 + ``cuCoredumpSetAttributeGlobal`` before creating the context if this flag + is used. Setting this flag implies that ``CU_CTX_COREDUMP_ENABLE`` 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 ``cuCoredumpSetAttribute`` from the created context + after it becomes current. Setting this flag on any context creation is + equivalent to setting the ``CU_COREDUMP_ENABLE_USER_TRIGGER`` attribute to + ``true`` globally. This flag is not supported when CUDA context is created + in CIG(CUDA in Graphics) mode. + + - ``CU_CTX_SYNC_MEMOPS``: 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 ``CUDA_ERROR_UNKNOWN`` if the compute mode + of the device is ``CU_COMPUTEMODE_PROHIBITED``. The function + :func:`device_get_attribute` can be used with + ``CU_DEVICE_ATTRIBUTE_COMPUTE_MODE`` 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 ``CUDA_ERROR_INVALID_VALUE`` if invalid + parameter was passed by client to create the CUDA context. + + Context creation in CIG mode will fail with ``CUDA_ERROR_NOT_SUPPORTED`` if + CIG is not supported by the device or the driver. + + Args: + ctx_create_params (object): Context creation parameters. Can + be NULL to create a regular CUDA context. See + ``CUctx_create_params`` for details. + flags (unsigned int): Context creation flags. + dev (int): Device to create context on. + + Returns: + intptr_t: Returned context handle of the new context. + + .. seealso:: `cuCtxCreate_v4` + """ + cdef intptr_t _ctx_create_params_ = 0 if ctx_create_params is None else (ctx_create_params)._get_ptr() + cdef CUcontext pctx + with nogil: + __status__ = cuCtxCreate(&pctx, _ctx_create_params_, flags, dev) + check_status(__status__) + return pctx + + +cpdef ctx_destroy_v2(intptr_t ctx): + """Destroy 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 ``cuCtxDestroy()`` 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 ``CUmodule``, + ``CUfunction``, ``CUstream``, ``CUevent``, ``CUarray``, + ``CUmipmappedArray``, ``CUtexObject``, ``CUsurfObject``, ``CUtexref``, + ``CUsurfref``, ``CUgraphicsResource``, ``CUlinkState``, + ``CUexternalMemory`` and ``CUexternalSemaphore``. These resources also + include memory allocations by ``cuMemAlloc()``, ``cuMemAllocHost()``, + :func:`mem_alloc_managed` and ``cuMemAllocPitch()``. + + If ``ctx`` is current to the calling thread then ``ctx`` will also be + popped from the current thread's context stack (as though + ``cuCtxPopCurrent()`` 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 + ``CUDA_ERROR_CONTEXT_IS_DESTROYED``. + + Args: + ctx (intptr_t): Context to destroy. + + .. note:: + ``cuCtxDestroy()`` will not destroy memory allocations by + :func:`mem_create`, :func:`mem_alloc_async` and + :func:`mem_alloc_from_pool_async`. These memory allocations are not + associated with any CUDA context and need to be destroyed explicitly. + + .. seealso:: `cuCtxDestroy_v2` + """ + with nogil: + __status__ = cuCtxDestroy(ctx) + check_status(__status__) + + +cpdef ctx_push_current_v2(intptr_t ctx): + """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 + ``cuCtxDestroy()`` or ``cuCtxPopCurrent()``. + + Args: + ctx (intptr_t): Context to push. + + .. seealso:: `cuCtxPushCurrent_v2` + """ + with nogil: + __status__ = cuCtxPushCurrent(ctx) + check_status(__status__) + + +cpdef intptr_t ctx_pop_current_v2() except? 0: + """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 in ``*pctx``. That context may then be made current to a + different CPU thread by calling ``cuCtxPushCurrent()``. + + If a context was current to the CPU thread before ``cuCtxCreate()`` or + ``cuCtxPushCurrent()`` was called, this function makes that context current + to the CPU thread again. + + Returns: + intptr_t: Returned popped context handle. + + .. seealso:: `cuCtxPopCurrent_v2` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuCtxPopCurrent(&pctx) + check_status(__status__) + return pctx + + +cpdef ctx_set_current(intptr_t ctx): + """Binds the specified CUDA context to the calling CPU thread. + + 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 ``CUDA_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). + + Args: + ctx (intptr_t): Context to bind to the calling CPU thread. + + .. seealso:: `cuCtxSetCurrent` + """ + with nogil: + __status__ = cuCtxSetCurrent(ctx) + check_status(__status__) + + +cpdef intptr_t ctx_get_current() except? 0: + """Returns the CUDA context bound to the calling CPU thread. + + Returns in ``*pctx`` the CUDA context bound to the calling CPU thread. If + no context is bound to the calling CPU thread then ``*pctx`` is set to NULL + and ``CUDA_SUCCESS`` is returned. + + Returns: + intptr_t: Returned context handle. + + .. seealso:: `cuCtxGetCurrent` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuCtxGetCurrent(&pctx) + check_status(__status__) + return pctx + + +cpdef int ctx_get_device() except? -1: + """Returns the device handle for the current context. + + Returns in ``*device`` the handle of the current context's device. + + Returns: + int: Returned device handle for the current context. + + .. seealso:: `cuCtxGetDevice` + """ + cdef CUdevice device + with nogil: + __status__ = cuCtxGetDevice(&device) + check_status(__status__) + return device + + +cpdef unsigned int ctx_get_flags() except? 0: + """Returns the flags for the current context. + + Returns in ``*flags`` the flags of the current context. See ``cuCtxCreate`` + for flag values. + + Returns: + unsigned int: Pointer to store flags of current context. + + .. seealso:: `cuCtxGetFlags` + """ + cdef unsigned int flags + with nogil: + __status__ = cuCtxGetFlags(&flags) + check_status(__status__) + return flags + + +cpdef ctx_set_flags(unsigned int flags): + """Sets the flags for the current context. + + Sets the flags for the current context overwriting previously set ones. See + ``cuDevicePrimaryCtxSetFlags`` for flag values. + + Args: + flags (unsigned int): Flags to set on the current context. + + .. seealso:: `cuCtxSetFlags` + """ + with nogil: + __status__ = cuCtxSetFlags(flags) + check_status(__status__) + + +cpdef unsigned long long ctx_get_id(intptr_t ctx) except? 0: + """Returns the unique Id associated with the context supplied. + + Returns in ``ctx_id`` 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. + + Args: + ctx (intptr_t): Context for which to obtain the Id. + + Returns: + unsigned long long: Pointer to store the Id of the context. + + .. seealso:: `cuCtxGetId` + """ + cdef unsigned long long ctx_id + with nogil: + __status__ = cuCtxGetId(ctx, &ctx_id) + check_status(__status__) + return ctx_id + + +cpdef ctx_synchronize(): + """Block 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. :func:`ctx_synchronize` + returns an error if one of the preceding tasks failed. If the context was + created with the ``CU_CTX_SCHED_BLOCKING_SYNC`` flag, the CPU thread will + block until the GPU context has finished its work. + + .. seealso:: `cuCtxSynchronize` + """ + with nogil: + __status__ = cuCtxSynchronize() + check_status(__status__) + + +cpdef ctx_set_limit(int limit, size_t value): + """Set 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 :func:`ctx_get_limit` to find out exactly what the + limit has been set to. + + Setting each ``CUlimit`` has its own specific restrictions, so each is + discussed here. + + - ``CU_LIMIT_STACK_SIZE`` 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. + + - ``CU_LIMIT_PRINTF_FIFO_SIZE`` controls the size in bytes of the FIFO used + by the ``printf()`` device system call. Setting + ``CU_LIMIT_PRINTF_FIFO_SIZE`` must be performed before launching any kernel + that uses the ``printf()`` device system call, otherwise + ``CUDA_ERROR_INVALID_VALUE`` will be returned. + + - ``CU_LIMIT_MALLOC_HEAP_SIZE`` controls the size in bytes of the heap used + by the ``malloc()`` and ``free()`` device system calls. Setting + ``CU_LIMIT_MALLOC_HEAP_SIZE`` must be performed before launching any kernel + that uses the ``malloc()`` or ``free()`` device system calls, otherwise + ``CUDA_ERROR_INVALID_VALUE`` will be returned. + + - ``CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH`` 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, :func:`ctx_set_limit` will return ``CUDA_ERROR_OUT_OF_MEMORY``, 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 + ``CUDA_ERROR_UNSUPPORTED_LIMIT`` being returned. + + - ``CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT`` 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, :func:`ctx_set_limit` will return + ``CUDA_ERROR_OUT_OF_MEMORY``, 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 ``CUDA_ERROR_UNSUPPORTED_LIMIT`` being + returned. + + - ``CU_LIMIT_MAX_L2_FETCH_GRANULARITY`` 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. + + - ``CU_LIMIT_PERSISTING_L2_CACHE_SIZE`` 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. + + Args: + limit (Limit): Limit to set. + value (size_t): Size of limit. + + .. seealso:: `cuCtxSetLimit` + """ + with nogil: + __status__ = cuCtxSetLimit(limit, value) + check_status(__status__) + + +cpdef size_t ctx_get_limit(int limit) except? 0: + """Returns resource limits. + + Returns in ``*pvalue`` the current size of ``limit``. The supported + ``CUlimit`` values are:. + + - ``CU_LIMIT_STACK_SIZE``: stack size in bytes of each GPU thread. + + - ``CU_LIMIT_PRINTF_FIFO_SIZE``: size in bytes of the FIFO used by the + ``printf()`` device system call. + + - ``CU_LIMIT_MALLOC_HEAP_SIZE``: size in bytes of the heap used by the + ``malloc()`` and ``free()`` device system calls. + + - ``CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH``: maximum grid depth at which a thread + can issue the device runtime call ``cudaDeviceSynchronize()`` to wait on + child grid launches to complete. + + - ``CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT``: maximum number of + outstanding device runtime launches that can be made from this context. + + - ``CU_LIMIT_MAX_L2_FETCH_GRANULARITY``: L2 cache fetch granularity. + + - ``CU_LIMIT_PERSISTING_L2_CACHE_SIZE``: Persisting L2 cache size in bytes. + + Args: + limit (Limit): Limit to query. + + Returns: + size_t: Returned size of limit. + + .. seealso:: `cuCtxGetLimit` + """ + cdef size_t pvalue + with nogil: + __status__ = cuCtxGetLimit(&pvalue, limit) + check_status(__status__) + return pvalue + + +cpdef int ctx_get_cache_config() except? -1: + """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 ``CU_FUNC_CACHE_PREFER_NONE`` on devices + where the size of the L1 cache and shared memory are fixed. + + The supported cache configurations are:. + + - ``CU_FUNC_CACHE_PREFER_NONE``: no preference for shared memory or L1 + (default). + + - ``CU_FUNC_CACHE_PREFER_SHARED``: prefer larger shared memory and smaller + L1 cache. + + - ``CU_FUNC_CACHE_PREFER_L1``: prefer larger L1 cache and smaller shared + memory. + + - ``CU_FUNC_CACHE_PREFER_EQUAL``: prefer equal sized L1 cache and shared + memory. + + Returns: + int: Returned cache configuration. + + .. seealso:: `cuCtxGetCacheConfig` + """ + cdef CUfunc_cache pconfig + with nogil: + __status__ = cuCtxGetCacheConfig(&pconfig) + check_status(__status__) + return pconfig + + +cpdef ctx_set_cache_config(int config): + """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 :func:`func_set_cache_config` or :func:`kernel_set_cache_config` + will be preferred over this context-wide setting. Setting the context-wide + cache configuration to ``CU_FUNC_CACHE_PREFER_NONE`` 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:. + + - ``CU_FUNC_CACHE_PREFER_NONE``: no preference for shared memory or L1 + (default). + + - ``CU_FUNC_CACHE_PREFER_SHARED``: prefer larger shared memory and smaller + L1 cache. + + - ``CU_FUNC_CACHE_PREFER_L1``: prefer larger L1 cache and smaller shared + memory. + + - ``CU_FUNC_CACHE_PREFER_EQUAL``: prefer equal sized L1 cache and shared + memory. + + Args: + config (FuncCache): Requested cache configuration. + + .. seealso:: `cuCtxSetCacheConfig` + """ + with nogil: + __status__ = cuCtxSetCacheConfig(config) + check_status(__status__) + + +cpdef unsigned int ctx_get_api_version(intptr_t ctx) except? 0: + """Gets the context's API version. + + Returns a version number in ``version`` 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. + + Args: + ctx (intptr_t): Context to check. + + Returns: + unsigned int: Pointer to version. + + .. seealso:: `cuCtxGetApiVersion` + """ + cdef unsigned int version + with nogil: + __status__ = cuCtxGetApiVersion(ctx, &version) + check_status(__status__) + return version + + +cpdef tuple ctx_get_stream_priority_range(): + """Returns numerical values that correspond to the least and greatest stream priorities. + + Returns in ``*least_priority`` and ``*greatest_priority`` 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 [``*greatest_priority``, ``*least_priority``]. 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 ``*least_priority`` or ``*greatest_priority`` + respectively. See ``cuStreamCreateWithPriority`` for details on creating a + priority stream. A NULL may be passed in for ``*least_priority`` or + ``*greatest_priority`` if the value is not desired. + + This function will return '0' in both ``*least_priority`` and + ``*greatest_priority`` if the current context's device does not support + stream priorities (see ``cuDeviceGetAttribute``). + + Returns: + A 2-tuple containing: + + - int: Pointer to an int in which the numerical value for least + stream priority is returned. + - int: Pointer to an int in which the numerical value for + greatest stream priority is returned. + + .. seealso:: `cuCtxGetStreamPriorityRange` + """ + cdef int least_priority + cdef int greatest_priority + with nogil: + __status__ = cuCtxGetStreamPriorityRange(&least_priority, &greatest_priority) + check_status(__status__) + return (least_priority, greatest_priority) + + +cpdef ctx_reset_persisting_l2cache(): + """Resets all persisting lines in cache to normal status. + + ``cuCtxResetPersistingL2Cache`` Resets all persisting lines in cache to + normal status. Takes effect on function return. + + .. seealso:: `cuCtxResetPersistingL2Cache` + """ + with nogil: + __status__ = cuCtxResetPersistingL2Cache() + check_status(__status__) + + +cpdef object ctx_get_exec_affinity(int type): + """Returns the execution affinity setting for the current context. + + Returns in ``*p_exec_affinity`` the current value of ``typename``. The + supported ``CUexecAffinityType`` values are:. + + - ``CU_EXEC_AFFINITY_TYPE_SM_COUNT``: number of SMs the context is limited + to use. + + Args: + type (ExecAffinityType): Execution affinity type to query. + + Returns: + CUexecAffinityParam_v1: Returned execution affinity. + + .. seealso:: `cuCtxGetExecAffinity` + """ + cdef ExecAffinityParam_v1 p_exec_affinity_py = ExecAffinityParam_v1() + cdef CUexecAffinityParam *p_exec_affinity = (p_exec_affinity_py._get_ptr()) + with nogil: + __status__ = cuCtxGetExecAffinity(p_exec_affinity, type) + check_status(__status__) + return p_exec_affinity_py + + +cpdef ctx_record_event(intptr_t h_ctx, intptr_t h_event): + """Records an event. + + Captures in ``h_event`` all the activities of the context ``h_ctx`` at the + time of this call. ``h_event`` and ``h_ctx`` must be from the same CUDA + context, otherwise ``CUDA_ERROR_INVALID_HANDLE`` will be returned. Calls + such as :func:`event_query` or :func:`ctx_wait_event` will then examine or + wait for completion of the work that was captured. Uses of ``h_ctx`` after + this call do not modify ``h_event``. If the context passed to ``h_ctx`` is + the primary context, ``h_event`` will capture all the activities of the + primary context and its green contexts. If the context passed to ``h_ctx`` + is a context converted from green context via :func:`ctx_from_green_ctx`, + ``h_event`` will capture only the activities of the green context. + + Args: + h_ctx (intptr_t): Context to record event for. + h_event (intptr_t): Event to record. + + .. note:: + The API will return ``CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED`` if the + specified context ``h_ctx`` has a stream in the capture mode. In such a + case, the call will invalidate all the conflicting captures. + + .. seealso:: `cuCtxRecordEvent` + """ + with nogil: + __status__ = cuCtxRecordEvent(h_ctx, h_event) + check_status(__status__) + + +cpdef ctx_wait_event(intptr_t h_ctx, intptr_t h_event): + """Make a context wait on an event. + + Makes all future work submitted to context ``h_ctx`` wait for all work + captured in ``h_event``. The synchronization will be performed on the + device and will not block the calling CPU thread. See + :func:`ctx_record_event` for details on what is captured by an event. If + the context passed to ``h_ctx`` is the primary context, the primary context + and its green contexts will wait for ``h_event``. If the context passed to + ``h_ctx`` is a context converted from green context via + :func:`ctx_from_green_ctx`, the green context will wait for ``h_event``. + + Args: + h_ctx (intptr_t): Context to wait. + h_event (intptr_t): Event to wait on. + + .. note:: + ``h_event`` may be from a different context or device than ``h_ctx``. + + .. note:: + The API will return ``CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED`` and + invalidate the capture if the specified event ``h_event`` is part of an + ongoing capture sequence or if the specified context ``h_ctx`` has a + stream in the capture mode. + + .. seealso:: `cuCtxWaitEvent` + """ + with nogil: + __status__ = cuCtxWaitEvent(h_ctx, h_event) + check_status(__status__) + + +cpdef intptr_t ctx_attach(unsigned int flags) except? 0: + """Increment a context's usage-count. + + [Deprecated]. + + Note that this function is deprecated and should not be used. + + Increments the usage count of the context and passes back a context handle + in ``*pctx`` that must be passed to :func:`ctx_detach` when the application + is done with the context. :func:`ctx_attach` fails if there is no context + current to the thread. + + Currently, the ``flags`` parameter must be 0. + + Args: + flags (unsigned int): Context attach flags (must be 0). + + Returns: + intptr_t: Returned context handle of the current context. + + .. seealso:: `cuCtxAttach` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuCtxAttach(&pctx, flags) + check_status(__status__) + return pctx + + +cpdef ctx_detach(intptr_t ctx): + """Decrement a context's usage-count. + + [Deprecated]. + + Note that this function is deprecated and should not be used. + + 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 ``cuCtxCreate()`` or :func:`ctx_attach`, and must be current to the + calling thread. + + Args: + ctx (intptr_t): Context to destroy. + + .. seealso:: `cuCtxDetach` + """ + with nogil: + __status__ = cuCtxDetach(ctx) + check_status(__status__) + + +cpdef int ctx_get_shared_mem_config() except? -1: + """Returns the current shared memory configuration for the current context. + + [Deprecated]. + + This function will return in ``p_config`` the current size of shared memory + banks in the current context. On devices with configurable shared memory + banks, ``cuCtxSetSharedMemConfig`` can be used to change this setting, so + that all subsequent kernel launches will by default use the new bank size. + When ``cuCtxGetSharedMemConfig`` 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:. + + - ``CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE``: shared memory bank width is + four bytes. + + - ``CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE``: shared memory bank width + will eight bytes. + + Returns: + int: returned shared memory configuration. + + .. seealso:: `cuCtxGetSharedMemConfig` + """ + cdef CUsharedconfig p_config + with nogil: + __status__ = cuCtxGetSharedMemConfig(&p_config) + check_status(__status__) + return p_config + + +cpdef ctx_set_shared_mem_config(int config): + """Sets the shared memory configuration for the current context. + + [Deprecated]. + + 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:. + + - ``CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE``: set bank width to the default + initial setting (currently, four bytes). + + - ``CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE``: set shared memory bank + width to be natively four bytes. + + - ``CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE``: set shared memory bank + width to be natively eight bytes. + + Args: + config (Sharedconfig): requested shared memory configuration. + + .. seealso:: `cuCtxSetSharedMemConfig` + """ + with nogil: + __status__ = cuCtxSetSharedMemConfig(config) + check_status(__status__) + + +cpdef intptr_t module_load(fname) except? 0: + """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, + :func:`module_load` 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. + + Args: + fname (bytes): Filename of module to load. + + Returns: + intptr_t: Returned module. + + .. seealso:: `cuModuleLoad` + """ + cdef void* _fname_ = _cyb_get_buffer_pointer(fname, -1, readonly=True) + cdef CUmodule module + with nogil: + __status__ = cuModuleLoad(&module, _fname_) + check_status(__status__) + return module + + +cpdef intptr_t module_load_data(image) except? 0: + """Load a module's data. + + Takes a pointer ``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 NULL-terminated ``PTX``, either as output by nvcc or + hand-written, or ``Tile`` IR data. + + Args: + image (bytes): Module data to load. + + Returns: + intptr_t: Returned module. + + .. seealso:: `cuModuleLoadData` + """ + cdef void* _image_ = _cyb_get_buffer_pointer(image, -1, readonly=True) + cdef CUmodule module + with nogil: + __status__ = cuModuleLoadData(&module, _image_) + check_status(__status__) + return module + + +cpdef intptr_t module_load_data_ex(image, unsigned int num_options, intptr_t options, intptr_t option_values) except? 0: + """Load a module's data with options. + + Takes a pointer ``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 NULL-terminated ``PTX``, either as output by nvcc or + hand-written, or ``Tile`` IR data. + + Args: + image (bytes): Module data to load. + num_options (unsigned int): Number of options. + options (intptr_t): Options for JIT. + option_values (intptr_t): Option values for JIT. + + Returns: + intptr_t: Returned module. + + .. seealso:: `cuModuleLoadDataEx` + """ + cdef void* _image_ = _cyb_get_buffer_pointer(image, -1, readonly=True) + cdef CUmodule module + with nogil: + __status__ = cuModuleLoadDataEx(&module, _image_, num_options, options, option_values) + check_status(__status__) + return module + + +cpdef intptr_t module_load_fat_binary(fat_cubin) except? 0: + """Load a module's data. + + Takes a pointer ``fat_cubin`` 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. + + Args: + fat_cubin (bytes): Fat binary to load. + + Returns: + intptr_t: Returned module. + + .. seealso:: `cuModuleLoadFatBinary` + """ + cdef void* _fat_cubin_ = _cyb_get_buffer_pointer(fat_cubin, -1, readonly=True) + cdef CUmodule module + with nogil: + __status__ = cuModuleLoadFatBinary(&module, _fat_cubin_) + check_status(__status__) + return module + + +cpdef module_unload(intptr_t hmod): + """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 + ``cuLibraryGetModule`` will return ``CUDA_ERROR_NOT_PERMITTED``. + + Args: + hmod (intptr_t): Module to unload. + + .. seealso:: `cuModuleUnload` + """ + with nogil: + __status__ = cuModuleUnload(hmod) + check_status(__status__) + + +cpdef int module_get_loading_mode() except? -1: + """Query lazy loading mode. + + Returns lazy loading mode Module loading mode is controlled by + CUDA_MODULE_LOADING env variable. + + Returns: + int: Returns the lazy loading mode. + + .. seealso:: `cuModuleGetLoadingMode` + """ + cdef CUmoduleLoadingMode mode + with nogil: + __status__ = cuModuleGetLoadingMode(&mode) + check_status(__status__) + return mode + + +cpdef intptr_t module_get_function(intptr_t hmod, name) except? 0: + """Returns a function handle. + + Returns in ``*hfunc`` the handle of the function of name ``name`` located + in module ``hmod``. If no function of that name exists, + :func:`module_get_function` returns ``CUDA_ERROR_NOT_FOUND``. + + Args: + hmod (intptr_t): Module to retrieve function from. + name (str): Name of function to retrieve. + + Returns: + intptr_t: Returned function handle. + + .. seealso:: `cuModuleGetFunction` + """ + if not isinstance(name, str): + raise TypeError("name must be a Python str") + cdef bytes _temp_name_ = (name).encode() + cdef char* _name_ = _temp_name_ + cdef CUfunction hfunc + with nogil: + __status__ = cuModuleGetFunction(&hfunc, hmod, _name_) + check_status(__status__) + return hfunc + + +cpdef unsigned int module_get_function_count(intptr_t mod) except? 0: + """Returns the number of functions within a module. + + Returns in ``count`` the number of functions in ``mod``. + + Args: + mod (intptr_t): Module to query. + + Returns: + unsigned int: Number of functions found within the module. + + .. seealso:: `cuModuleGetFunctionCount` + """ + cdef unsigned int count + with nogil: + __status__ = cuModuleGetFunctionCount(&count, mod) + check_status(__status__) + return count + + +cpdef object module_enumerate_functions(intptr_t mod): + """Returns the function handles within a module. + + Returns in ``functions`` a maximum number of ``num_functions`` 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. + + Args: + mod (intptr_t): Module to query from. + + Returns: + intptr_t: Buffer where the function handles are returned to. + + .. seealso:: `cuModuleEnumerateFunctions` + """ + cdef unsigned int num_functions + with nogil: + __status__ = cuModuleGetFunctionCount(&num_functions, mod) + check_status(__status__) + cdef object _functions_alloc_ = _numpy.empty(max(num_functions, 1), dtype=_numpy.intp) + cdef intptr_t _functions_data_ = _functions_alloc_.ctypes.data + cdef intptr_t *functions_ptr = _functions_data_ + cdef object functions = _functions_alloc_[:num_functions] + if num_functions != 0: + with nogil: + __status__ = cuModuleEnumerateFunctions(functions_ptr, num_functions, mod) + check_status(__status__) + return functions + + +cpdef tuple module_get_global_v2(intptr_t hmod, name): + """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, ``cuModuleGetGlobal()`` returns ``CUDA_ERROR_NOT_FOUND``. One of + the parameters ``dptr`` or ``numbytes`` (not both) can be NULL in which + case it is ignored. + + Args: + hmod (intptr_t): Module to retrieve global from. + name (bytes): Name of global to retrieve. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned global device pointer. + - size_t: Returned global size in bytes. + + .. seealso:: `cuModuleGetGlobal_v2` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUdeviceptr dptr + cdef size_t bytes + with nogil: + __status__ = cuModuleGetGlobal(&dptr, &bytes, hmod, _name_) + check_status(__status__) + return (dptr, bytes) + + +cpdef intptr_t link_create_v2(unsigned int num_options, intptr_t options, intptr_t option_values) except? 0: + """Creates a pending JIT linker invocation. + + If the call is successful, the caller owns the returned ``CUlinkState``, + which should eventually be destroyed with ``cuLinkDestroy``. 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 ``CU_JIT_WALL_TIME``, ``CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES``, + and ``CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES`` will accumulate data until the + ``CUlinkState`` is destroyed. + + The data passed in via ``cuLinkAddData`` and ``cuLinkAddFile`` will be + treated as relocatable (-rdc=true to nvcc) when linking the final cubin + during ``cuLinkComplete`` and will have similar consequences as offline + relocatable device code linking. + + ``option_values`` must remain valid for the life of the ``CUlinkState`` if + output options are used. No other references to inputs are maintained after + this call returns. + + Args: + num_options (unsigned int): Size of options arrays. + options (intptr_t): Array of linker and compiler options. + option_values (intptr_t): Array of option values, each cast to + void *. + + Returns: + intptr_t: On success, this will contain a ``CUlinkState`` to + specify and complete this action. + + .. note:: + For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 + will be accepted. + + .. seealso:: `cuLinkCreate_v2` + """ + cdef CUlinkState state_out + with nogil: + __status__ = cuLinkCreate(num_options, options, option_values, &state_out) + check_status(__status__) + return state_out + + +cpdef link_add_data_v2(intptr_t state, int type, intptr_t data, size_t size, name, unsigned int num_options, intptr_t options, intptr_t option_values): + """Add 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 ``CU_JIT_WALL_TIME``, + ``CU_JIT_INFO_LOG_BUFFER``, ``CU_JIT_ERROR_LOG_BUFFER``, + ``CU_JIT_TARGET_FROM_CUCONTEXT``, or ``CU_JIT_TARGET``. + + Args: + state (intptr_t): A pending linker action. + type (JitInputType): The type of the input data. + data (intptr_t): The input data. PTX must be NULL-terminated. + size (size_t): The length of the input data. + name (bytes): An optional name for this input in log messages. + num_options (unsigned int): Size of options. + options (intptr_t): Options to be applied only for this input + (overrides options from ``cuLinkCreate``). + option_values (intptr_t): Array of option values, each cast to + void *. + + .. note:: + For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 + will be accepted. + + .. seealso:: `cuLinkAddData_v2` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + with nogil: + __status__ = cuLinkAddData(state, type, data, size, _name_, num_options, options, option_values) + check_status(__status__) + + +cpdef link_add_file_v2(intptr_t state, int type, path, unsigned int num_options, intptr_t options, intptr_t option_values): + """Add 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 ``CU_JIT_WALL_TIME``, + ``CU_JIT_INFO_LOG_BUFFER``, ``CU_JIT_ERROR_LOG_BUFFER``, + ``CU_JIT_TARGET_FROM_CUCONTEXT``, or ``CU_JIT_TARGET``. + + This method is equivalent to invoking ``cuLinkAddData`` on the contents of + the file. + + Args: + state (intptr_t): A pending linker action. + type (JitInputType): The type of the input data. + path (bytes): Path to the input file. + num_options (unsigned int): Size of options. + options (intptr_t): Options to be applied only for this input + (overrides options from ``cuLinkCreate``). + option_values (intptr_t): Array of option values, each cast to + void *. + + .. note:: + For LTO-IR input, only LTO-IR compiled with toolkits prior to CUDA 12.0 + will be accepted. + + .. seealso:: `cuLinkAddFile_v2` + """ + cdef void* _path_ = _cyb_get_buffer_pointer(path, -1, readonly=True) + with nogil: + __status__ = cuLinkAddFile(state, type, _path_, num_options, options, option_values) + check_status(__status__) + + +cpdef bytes link_complete(intptr_t state): + """Complete a pending linker invocation. + + Completes the pending linker action and returns the cubin image for the + linked device code, which can be used with ``cuModuleLoadData``. The cubin + is owned by ``state``, so it should be loaded before ``state`` is destroyed + via ``cuLinkDestroy``. This call does not destroy ``state``. + + Args: + state (intptr_t): A pending linker invocation. + + Returns: + intptr_t: On success, this will point to the output image. + + .. seealso:: `cuLinkComplete` + """ + cdef size_t[1] size_out = [0] + cdef void* cubin_out = NULL + with nogil: + __status__ = cuLinkComplete(state, &cubin_out, size_out) + check_status(__status__) + return bytes(_cyb_PyMemoryView_FromMemory(cubin_out, size_out[0], _cyb_PyBUF_READ)) + + +cpdef link_destroy(intptr_t state): + """Destroys state for a JIT linker invocation. + + Args: + state (intptr_t): State object for the linker invocation. + + .. seealso:: `cuLinkDestroy` + """ + with nogil: + __status__ = cuLinkDestroy(state) + check_status(__status__) + + +cpdef intptr_t module_get_tex_ref(intptr_t hmod, name) except? 0: + """Returns a handle to a texture reference. + + [Deprecated]. + + Returns in ``*p_tex_ref`` the handle of the texture reference of name + ``name`` in the module ``hmod``. If no texture reference of that name + exists, :func:`module_get_tex_ref` returns ``CUDA_ERROR_NOT_FOUND``. This + texture reference handle should not be destroyed, since it will be + destroyed when the module is unloaded. + + Args: + hmod (intptr_t): Module to retrieve texture reference from. + name (bytes): Name of texture reference to retrieve. + + Returns: + intptr_t: Returned texture reference. + + .. seealso:: `cuModuleGetTexRef` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUtexref p_tex_ref + with nogil: + __status__ = cuModuleGetTexRef(&p_tex_ref, hmod, _name_) + check_status(__status__) + return p_tex_ref + + +cpdef intptr_t module_get_surf_ref(intptr_t hmod, name) except? 0: + """Returns a handle to a surface reference. + + [Deprecated]. + + Returns in ``*p_surf_ref`` the handle of the surface reference of name + ``name`` in the module ``hmod``. If no surface reference of that name + exists, :func:`module_get_surf_ref` returns ``CUDA_ERROR_NOT_FOUND``. + + Args: + hmod (intptr_t): Module to retrieve surface reference from. + name (bytes): Name of surface reference to retrieve. + + Returns: + intptr_t: Returned surface reference. + + .. seealso:: `cuModuleGetSurfRef` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUsurfref p_surf_ref + with nogil: + __status__ = cuModuleGetSurfRef(&p_surf_ref, hmod, _name_) + check_status(__status__) + return p_surf_ref + + +cpdef intptr_t library_load_data(code, intptr_t jit_options, intptr_t jit_options_values, unsigned int num_jit_options, intptr_t library_options, intptr_t library_option_values, unsigned int num_library_options) except? 0: + """Load a library with specified code 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 :func:`library_unload`. + + - 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 NULL- + terminated ``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 ``jit_options`` and any corresponding + parameters are passed in ``jit_optionsValues``. The number of total JIT + options is supplied via ``num_jit_options``. Any outputs will be returned + via ``jit_optionsValues``. + + Library load options are passed as an array via ``library_options`` and any + corresponding parameters are passed in ``library_option_values``. The + number of total library load options is supplied via + ``num_library_options``. + + Args: + code (bytes): Code to load. + jit_options (intptr_t): Options for JIT. + jit_options_values (intptr_t): Option values for JIT. + num_jit_options (unsigned int): Number of options. + library_options (intptr_t): Options for loading. + library_option_values (intptr_t): Option values for loading. + num_library_options (unsigned int): Number of options for + loading. + + Returns: + intptr_t: Returned library. + + .. note:: + If the library contains managed variables and no device in the system + supports managed variables this call is expected to return + ``CUDA_ERROR_NOT_SUPPORTED``. + + .. seealso:: `cuLibraryLoadData` + """ + cdef void* _code_ = _cyb_get_buffer_pointer(code, -1, readonly=True) + cdef CUlibrary library + with nogil: + __status__ = cuLibraryLoadData(&library, _code_, jit_options, jit_options_values, num_jit_options, library_options, library_option_values, num_library_options) + check_status(__status__) + return library + + +cpdef intptr_t library_load_from_file(file_name, intptr_t jit_options, intptr_t jit_options_values, unsigned int num_jit_options, intptr_t library_options, intptr_t library_option_values, unsigned int num_library_options) except? 0: + """Load 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 :func:`library_unload`. + + - 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 ``jit_options`` and any corresponding + parameters are passed in ``jit_optionsValues``. The number of total options + is supplied via ``num_jit_options``. Any outputs will be returned via + ``jit_optionsValues``. + + Library load options are passed as an array via ``library_options`` and any + corresponding parameters are passed in ``library_option_values``. The + number of total library load options is supplied via + ``num_library_options``. + + Args: + file_name (bytes): File to load from. + jit_options (intptr_t): Options for JIT. + jit_options_values (intptr_t): Option values for JIT. + num_jit_options (unsigned int): Number of options. + library_options (intptr_t): Options for loading. + library_option_values (intptr_t): Option values for loading. + num_library_options (unsigned int): Number of options for + loading. + + Returns: + intptr_t: Returned library. + + .. note:: + If the library contains managed variables and no device in the system + supports managed variables this call is expected to return + ``CUDA_ERROR_NOT_SUPPORTED``. + + .. seealso:: `cuLibraryLoadFromFile` + """ + cdef void* _file_name_ = _cyb_get_buffer_pointer(file_name, -1, readonly=True) + cdef CUlibrary library + with nogil: + __status__ = cuLibraryLoadFromFile(&library, _file_name_, jit_options, jit_options_values, num_jit_options, library_options, library_option_values, num_library_options) + check_status(__status__) + return library + + +cpdef library_unload(intptr_t library): + """Unloads a library. + + Unloads the library specified with ``library``. + + Args: + library (intptr_t): Library to unload. + + .. seealso:: `cuLibraryUnload` + """ + with nogil: + __status__ = cuLibraryUnload(library) + check_status(__status__) + + +cpdef intptr_t library_get_kernel(intptr_t library, name) except? 0: + """Returns a kernel handle. + + Returns in ``p_kernel`` the handle of the kernel with name ``name`` located + in library ``library``. If kernel handle is not found, the call returns + ``CUDA_ERROR_NOT_FOUND``. + + Args: + library (intptr_t): Library to retrieve kernel from. + name (bytes): Name of kernel to retrieve. + + Returns: + intptr_t: Returned kernel handle. + + .. seealso:: `cuLibraryGetKernel` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUkernel p_kernel + with nogil: + __status__ = cuLibraryGetKernel(&p_kernel, library, _name_) + check_status(__status__) + return p_kernel + + +cpdef unsigned int library_get_kernel_count(intptr_t lib) except? 0: + """Returns the number of kernels within a library. + + Returns in ``count`` the number of kernels in ``lib``. + + Args: + lib (intptr_t): Library to query. + + Returns: + unsigned int: Number of kernels found within the library. + + .. seealso:: `cuLibraryGetKernelCount` + """ + cdef unsigned int count + with nogil: + __status__ = cuLibraryGetKernelCount(&count, lib) + check_status(__status__) + return count + + +cpdef object library_enumerate_kernels(intptr_t lib): + """Retrieve the kernel handles within a library. + + Returns in ``kernels`` a maximum number of ``num_kernels`` kernel handles + within ``lib``. The returned kernel handle becomes invalid when the library + is unloaded. + + Args: + lib (intptr_t): Library to query from. + + Returns: + intptr_t: Buffer where the kernel handles are returned to. + + .. seealso:: `cuLibraryEnumerateKernels` + """ + cdef unsigned int num_kernels + with nogil: + __status__ = cuLibraryGetKernelCount(&num_kernels, lib) + check_status(__status__) + cdef object _kernels_alloc_ = _numpy.empty(max(num_kernels, 1), dtype=_numpy.intp) + cdef intptr_t _kernels_data_ = _kernels_alloc_.ctypes.data + cdef intptr_t *kernels_ptr = _kernels_data_ + cdef object kernels = _kernels_alloc_[:num_kernels] + if num_kernels != 0: + with nogil: + __status__ = cuLibraryEnumerateKernels(kernels_ptr, num_kernels, lib) + check_status(__status__) + return kernels + + +cpdef intptr_t library_get_module(intptr_t library) except? 0: + """Returns a module handle. + + Returns in ``p_mod`` the module handle associated with the current context + located in library ``library``. If module handle is not found, the call + returns ``CUDA_ERROR_NOT_FOUND``. + + Args: + library (intptr_t): Library to retrieve module from. + + Returns: + intptr_t: Returned module handle. + + .. seealso:: `cuLibraryGetModule` + """ + cdef CUmodule p_mod + with nogil: + __status__ = cuLibraryGetModule(&p_mod, library) + check_status(__status__) + return p_mod + + +cpdef intptr_t kernel_get_function(intptr_t kernel) except? 0: + """Returns a function handle. + + Returns in ``p_func`` the handle of the function for the requested kernel + ``kernel`` and the current context. If function handle is not found, the + call returns ``CUDA_ERROR_NOT_FOUND``. + + Args: + kernel (intptr_t): Kernel to retrieve function for the + requested context. + + Returns: + intptr_t: Returned function handle. + + .. seealso:: `cuKernelGetFunction` + """ + cdef CUfunction p_func + with nogil: + __status__ = cuKernelGetFunction(&p_func, kernel) + check_status(__status__) + return p_func + + +cpdef intptr_t kernel_get_library(intptr_t kernel) except? 0: + """Returns a library handle. + + Returns in ``p_lib`` the handle of the library for the requested kernel + ``kernel``. + + Args: + kernel (intptr_t): Kernel to retrieve library handle. + + Returns: + intptr_t: Returned library handle. + + .. seealso:: `cuKernelGetLibrary` + """ + cdef CUlibrary p_lib + with nogil: + __status__ = cuKernelGetLibrary(&p_lib, kernel) + check_status(__status__) + return p_lib + + +cpdef tuple library_get_global(intptr_t library, name): + """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 ``CUDA_ERROR_NOT_FOUND``. One of the parameters ``dptr`` or + ``numbytes`` (not both) can be NULL in which case it is ignored. + + Args: + library (intptr_t): Library to retrieve global from. + name (bytes): Name of global to retrieve. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned global device pointer for the + requested context. + - size_t: Returned global size in bytes. + + .. seealso:: `cuLibraryGetGlobal` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUdeviceptr dptr + cdef size_t bytes + with nogil: + __status__ = cuLibraryGetGlobal(&dptr, &bytes, library, _name_) + check_status(__status__) + return (dptr, bytes) + + +cpdef tuple library_get_managed(intptr_t library, name): + """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 + ``CUDA_ERROR_NOT_FOUND``. One of the parameters ``dptr`` or ``numbytes`` + (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. + + Args: + library (intptr_t): Library to retrieve managed memory from. + name (bytes): Name of managed memory to retrieve. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned pointer to the managed memory. + - size_t: Returned memory size in bytes. + + .. seealso:: `cuLibraryGetManaged` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + cdef CUdeviceptr dptr + cdef size_t bytes + with nogil: + __status__ = cuLibraryGetManaged(&dptr, &bytes, library, _name_) + check_status(__status__) + return (dptr, bytes) + + +cpdef intptr_t library_get_unified_function(intptr_t library, symbol) except? 0: + """Returns a pointer to a unified function. + + Returns in ``*fptr`` the function pointer to a unified function denoted by + ``symbol``. If no unified function with name ``symbol`` exists, the call + returns ``CUDA_ERROR_NOT_FOUND``. If there is no device with attribute + ``CU_DEVICE_ATTRIBUTE_UNIFIED_FUNCTION_POINTERS`` present in the system, + the call may return ``CUDA_ERROR_NOT_FOUND``. + + Args: + library (intptr_t): Library to retrieve function pointer + memory from. + symbol (bytes): Name of function pointer to retrieve. + + Returns: + intptr_t: Returned pointer to a unified function. + + .. seealso:: `cuLibraryGetUnifiedFunction` + """ + cdef void* _symbol_ = _cyb_get_buffer_pointer(symbol, -1, readonly=True) + cdef void* fptr + with nogil: + __status__ = cuLibraryGetUnifiedFunction(&fptr, library, _symbol_) + check_status(__status__) + return fptr + + +cpdef int kernel_get_attribute(int attrib, intptr_t kernel, int dev) except? -1: + """Returns information about a kernel. + + Returns in ``*pi`` the integer value of the attribute ``attrib`` for the + kernel ``kernel`` for the requested device ``dev``. The supported + attributes are:. + + - ``CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK``: 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. + + - ``CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES``: 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. + + - ``CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES``: The size in bytes of user- + allocated constant memory required by this kernel. + + - ``CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES``: The size in bytes of local memory + used by each thread of this kernel. + + - ``CU_FUNC_ATTRIBUTE_NUM_REGS``: The number of registers used by each + thread of this kernel. + + - ``CU_FUNC_ATTRIBUTE_PTX_VERSION``: 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. + + - ``CU_FUNC_ATTRIBUTE_BINARY_VERSION``: 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. + + - ``CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES``: The maximum size in + bytes of dynamically-allocated shared memory. + + - ``CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT``: Preferred shared + memory-L1 cache split ratio in percent of total shared memory. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET``: If this attribute is set, + the kernel must launch with a valid cluster size specified. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH``: The required cluster width + in blocks. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT``: The required cluster + height in blocks. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH``: The required cluster depth + in blocks. + + - ``CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED``: 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. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE``: The block + scheduling policy of a function. The value type is + ``CUclusterSchedulingPolicy``. + + Args: + attrib (FunctionAttribute): Attribute requested. + kernel (intptr_t): Kernel to query attribute of. + dev (int): Device to query attribute of. + + Returns: + int: Returned attribute value. + + .. note:: + If another thread is trying to set the same attribute on the same + device using :func:`kernel_set_attribute` simultaneously, the attribute + query will give the old or new value depending on the interleavings + chosen by the OS scheduler and memory consistency. + + .. seealso:: `cuKernelGetAttribute` + """ + cdef int pi + with nogil: + __status__ = cuKernelGetAttribute(&pi, attrib, kernel, dev) + check_status(__status__) + return pi + + +cpdef kernel_set_attribute(int attrib, int val, intptr_t kernel, int dev): + """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 CUDA_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 + (CUDA_ERROR_INVALID_VALUE). + + Note that attributes set using :func:`func_set_attribute` will override the + attribute set by this API irrespective of whether the call to + :func:`func_set_attribute` is made before or after this API call. However, + :func:`kernel_get_attribute` will always return the attribute value set by + this API. + + Supported attributes are:. + + - ``CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES``: This is the maximum + size in bytes of dynamically-allocated shared memory. The value should + contain the requested maximum size of dynamically-allocated shared memory. + The sum of this value and the function attribute + ``CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES`` cannot exceed the device attribute + ``CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN``. The maximal size + of requestable dynamic shared memory may differ by GPU architecture. + + - ``CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT``: 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. See ``CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR`` + This is only a hint, and the driver can choose a different ratio if + required to execute the function. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH``: The required cluster width + in blocks. The width, height, and depth values must either all be 0 or all + be positive. The validity of the cluster dimensions is checked at launch + time. If the value is set during compile time, it cannot be set at runtime. + Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT``: The required cluster + height in blocks. The width, height, and depth values must either all be 0 + or all be positive. The validity of the cluster dimensions is checked at + launch time. If the value is set during compile time, it cannot be set at + runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH``: The required cluster depth + in blocks. The width, height, and depth values must either all be 0 or all + be positive. The validity of the cluster dimensions is checked at launch + time. If the value is set during compile time, it cannot be set at runtime. + Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED``: Indicates + whether the function can be launched with non-portable cluster size. 1 is + allowed, 0 is disallowed. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE``: The block + scheduling policy of a function. The value type is + ``CUclusterSchedulingPolicy``. + + Args: + attrib (FunctionAttribute): Attribute requested. + val (int): Value to set. + kernel (intptr_t): Kernel to set attribute of. + dev (int): Device to set attribute of. + + .. note:: + The API has stricter locking requirements in comparison to its legacy + counterpart :func:`func_set_attribute` 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. + + .. seealso:: `cuKernelSetAttribute` + """ + with nogil: + __status__ = cuKernelSetAttribute(attrib, val, kernel, dev) + check_status(__status__) + + +cpdef kernel_set_cache_config(intptr_t kernel, int config, int dev): + """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 + :func:`ctx_set_cache_config` will be overridden by this per-kernel setting. + + Note that attributes set using :func:`func_set_cache_config` will override + the attribute set by this API irrespective of whether the call to + :func:`func_set_cache_config` 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:. + + - ``CU_FUNC_CACHE_PREFER_NONE``: no preference for shared memory or L1 + (default). + + - ``CU_FUNC_CACHE_PREFER_SHARED``: prefer larger shared memory and smaller + L1 cache. + + - ``CU_FUNC_CACHE_PREFER_L1``: prefer larger L1 cache and smaller shared + memory. + + - ``CU_FUNC_CACHE_PREFER_EQUAL``: prefer equal sized L1 cache and shared + memory. + + Args: + kernel (intptr_t): Kernel to configure cache for. + config (FuncCache): Requested cache configuration. + dev (int): Device to set attribute of. + + .. note:: + The API has stricter locking requirements in comparison to its legacy + counterpart :func:`func_set_cache_config` 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. + + .. seealso:: `cuKernelSetCacheConfig` + """ + with nogil: + __status__ = cuKernelSetCacheConfig(kernel, config, dev) + check_status(__status__) + + +cpdef tuple kernel_get_param_info(intptr_t kernel, size_t param_index): + """Returns the offset and size of a kernel parameter in the device-side parameter layout. + + Queries the kernel parameter at ``param_index`` into ``kernel's`` list of + parameters, and returns in ``param_offset`` and ``param_size`` 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()``. ``param_index`` must be less than + the number of parameters that ``kernel`` takes. ``param_size`` can be set + to NULL if only the parameter offset is desired. + + Args: + kernel (intptr_t): The kernel to query. + param_index (size_t): The parameter index to query. + + Returns: + A 2-tuple containing: + + - size_t: Returns the offset into the device-side parameter + layout at which the parameter resides. + - size_t: Optionally returns the size of the parameter in the + device-side parameter layout. + + .. seealso:: `cuKernelGetParamInfo` + """ + cdef size_t param_offset + cdef size_t param_size + with nogil: + __status__ = cuKernelGetParamInfo(kernel, param_index, ¶m_offset, ¶m_size) + check_status(__status__) + return (param_offset, param_size) + + +cpdef tuple mem_get_info_v2(): + """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. + + Returns: + A 2-tuple containing: + + - size_t: Returned free memory in bytes. + - size_t: Returned total memory in bytes. + + .. seealso:: `cuMemGetInfo_v2` + """ + cdef size_t free + cdef size_t total + with nogil: + __status__ = cuMemGetInfo(&free, &total) + check_status(__status__) + return (free, total) + + +cpdef unsigned long long mem_alloc_v2(size_t bytesize) except? 0: + """Allocates device memory. + + Allocates ``bytesize`` bytes of linear memory on the device and returns in + ``*dptr`` 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, ``cuMemAlloc()`` returns ``CUDA_ERROR_INVALID_VALUE``. + + Args: + bytesize (size_t): Requested allocation size in bytes. + + Returns: + unsigned long long: Returned device pointer. + + .. seealso:: `cuMemAlloc_v2` + """ + cdef CUdeviceptr dptr + with nogil: + __status__ = cuMemAlloc(&dptr, bytesize) + check_status(__status__) + return dptr + + +cpdef tuple mem_alloc_pitch_v2(size_t width_in_bytes, size_t height, unsigned int element_size_bytes): + """Allocates pitched device memory. + + Allocates at least ``width_in_bytes`` * ``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. + ``element_size_bytes`` specifies the size of the largest reads and writes + that will be performed on the memory range. ``element_size_bytes`` may be + 4, 8 or 16 (since coalesced memory transactions are not possible on other + data sizes). If ``element_size_bytes`` 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 ``*p_pitch`` by ``cuMemAllocPitch()`` + is the width in bytes of the allocation. The intended usage of pitch is as + a separate parameter of the allocation, used to compute addresses within + the 2D array. Given the row and column of an array element of type T, the + address is computed as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + The pitch returned by ``cuMemAllocPitch()`` is guaranteed to work with + ``cuMemcpy2D()`` under all circumstances. For allocations of 2D arrays, it + is recommended that programmers consider performing pitch allocations using + ``cuMemAllocPitch()``. 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 ``cuMemAllocPitch()`` is + guaranteed to match or exceed the alignment requirement for texture binding + with ``cuTexRefSetAddress2D()``. + + Args: + width_in_bytes (size_t): Requested allocation width in bytes. + height (size_t): Requested allocation height in rows. + element_size_bytes (unsigned int): Size of largest + reads/writes for range. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned device pointer. + - size_t: Returned pitch of allocation in bytes. + + .. seealso:: `cuMemAllocPitch_v2` + """ + cdef CUdeviceptr dptr + cdef size_t p_pitch + with nogil: + __status__ = cuMemAllocPitch(&dptr, &p_pitch, width_in_bytes, height, element_size_bytes) + check_status(__status__) + return (dptr, p_pitch) + + +cpdef mem_free_v2(unsigned long long dptr): + """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 + - ``cuMemAlloc()``, ``cuMemAllocPitch()``, :func:`mem_alloc_managed`, + :func:`mem_alloc_async`, :func:`mem_alloc_from_pool_async`. + + Note - This API will not perform any implict synchronization when the + pointer was allocated with ``cuMemAllocAsync`` or + ``cuMemAllocFromPoolAsync``. Callers must ensure that all accesses to these + pointer have completed before invoking ``cuMemFree``. For best performance + and memory reuse, users should use ``cuMemFreeAsync`` to free memory + allocated via the stream ordered memory allocator. For all other pointers, + this API may perform implicit synchronization. + + Args: + dptr (unsigned long long): Pointer to memory to free. + + .. seealso:: `cuMemFree_v2` + """ + with nogil: + __status__ = cuMemFree(dptr) + check_status(__status__) + + +cpdef tuple mem_get_address_range_v2(unsigned long long dptr): + """Get 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. + + Args: + dptr (unsigned long long): Device pointer to query. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned base address. + - size_t: Returned size of device memory allocation. + + .. seealso:: `cuMemGetAddressRange_v2` + """ + cdef CUdeviceptr pbase + cdef size_t psize + with nogil: + __status__ = cuMemGetAddressRange(&pbase, &psize, dptr) + check_status(__status__) + return (pbase, psize) + + +cpdef intptr_t mem_alloc_host_v2(size_t bytesize) except? 0: + """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 :func:`cu_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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES`` is + true, ``cuMemAllocHost`` may not page-lock the allocated memory. + + Page-locking excessive amounts of memory with ``cuMemAllocHost()`` 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 ``cuMemAllocHost()`` will + automatically be immediately accessible to all contexts on all devices + which support unified addressing (as may be queried using + ``CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING``). 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. + + Args: + bytesize (size_t): Requested allocation size in bytes. + + Returns: + intptr_t: Returned pointer to host memory. + + .. seealso:: `cuMemAllocHost_v2` + """ + cdef void* pp + with nogil: + __status__ = cuMemAllocHost(&pp, bytesize) + check_status(__status__) + return pp + + +cpdef mem_free_host(p): + """Frees page-locked host memory. + + Frees the memory space pointed to by ``p``, which must have been returned + by a previous call to ``cuMemAllocHost()``. + + Args: + p (bytes): Pointer to memory to free. + + .. seealso:: `cuMemFreeHost` + """ + cdef void* _p_ = _cyb_get_buffer_pointer(p, -1, readonly=False) + with nogil: + __status__ = cuMemFreeHost(_p_) + check_status(__status__) + + +cpdef intptr_t mem_host_alloc(size_t bytesize, unsigned int flags) except? 0: + """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 ``cuMemcpyHtoD()``. 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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES`` is + true, ``cuMemHostAlloc`` 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 + ``cuMemHostGetDevicePointer()``. + + - ``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 ``cuMemHostGetDevicePointer()`` 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 + :func:`mem_free_host`. + + Note all host memory allocated using :func:`mem_host_alloc` will + automatically be immediately accessible to all contexts on all devices + which support unified addressing (as may be queried using + ``CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING``). 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 + ``cuMemHostGetDevicePointer()`` must be used to query the device pointer, + even if the context supports unified addressing. See ``Unified Addressing`` + for additional details. + + Args: + bytesize (size_t): Requested allocation size in bytes. + flags (unsigned int): flags for allocation request. + + Returns: + intptr_t: Returned pointer to host memory. + + .. seealso:: `cuMemHostAlloc` + """ + cdef void* pp + with nogil: + __status__ = cuMemHostAlloc(&pp, bytesize, flags) + check_status(__status__) + return pp + + +cpdef unsigned long long mem_host_get_device_pointer_v2(intptr_t p, unsigned int flags) except? 0: + """Passes back device pointer of mapped pinned memory. + + Passes back the device pointer ``pdptr`` corresponding to the mapped, + pinned host buffer ``p`` allocated by ``cuMemHostAlloc``. + + ``cuMemHostGetDevicePointer()`` 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 + ``CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM``, the memory + can also be accessed from the device using the host pointer ``p``. The + device pointer returned by ``cuMemHostGetDevicePointer()`` 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 + ``cuMemHostGetDevicePointer()`` 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 ``cuMemHostGetDevicePointer()`` + 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. + + Args: + p (intptr_t): Host pointer. + flags (unsigned int): Options (must be 0). + + Returns: + unsigned long long: Returned device pointer. + + .. seealso:: `cuMemHostGetDevicePointer_v2` + """ + cdef CUdeviceptr pdptr + with nogil: + __status__ = cuMemHostGetDevicePointer(&pdptr, p, flags) + check_status(__status__) + return pdptr + + +cpdef unsigned int mem_host_get_flags(intptr_t p) except? 0: + """Passes back flags that were used for a pinned allocation. + + Passes back the flags ``p_flags`` that were specified when allocating the + pinned host buffer ``p`` allocated by ``cuMemHostAlloc``. + + :func:`mem_host_get_flags` will fail if the pointer does not reside in an + allocation performed by ``cuMemAllocHost()`` or :func:`mem_host_alloc`. + + Args: + p (intptr_t): Host pointer. + + Returns: + unsigned int: Returned flags word. + + .. seealso:: `cuMemHostGetFlags` + """ + cdef unsigned int p_flags + with nogil: + __status__ = cuMemHostGetFlags(&p_flags, p) + check_status(__status__) + return p_flags + + +cpdef unsigned long long mem_alloc_managed(size_t bytesize, unsigned int flags) except? 0: + """Allocates memory that will be automatically managed by the Unified Memory system. + + Allocates ``bytesize`` bytes of managed memory on the device and returns in + ``*dptr`` a pointer to the allocated memory. If the device doesn't support + allocating managed memory, ``CUDA_ERROR_NOT_SUPPORTED`` is returned. + Support for managed memory can be queried using the device attribute + ``CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY``. The allocated memory is suitably + aligned for any kind of variable. The memory is not cleared. If + ``bytesize`` is 0, ``cuMemAllocManaged`` returns + ``CUDA_ERROR_INVALID_VALUE``. 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 ``CU_MEM_ATTACH_GLOBAL`` or + ``CU_MEM_ATTACH_HOST``. If ``CU_MEM_ATTACH_GLOBAL`` is specified, then this + memory is accessible from any stream on any device. If + ``CU_MEM_ATTACH_HOST`` is specified, then the allocation should not be + accessed from devices that have a zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``; an explicit call to + ``cuStreamAttachMemAsync`` will be required to enable access on such + devices. + + If the association is later changed via ``cuStreamAttachMemAsync`` to a + single stream, the default association as specified during + ``cuMemAllocManaged`` is restored when that stream is destroyed. For + managed variables, the default association is always + ``CU_MEM_ATTACH_GLOBAL``. 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 ``cuMemAllocManaged`` should be released with + ``cuMemFree``. + + Device memory oversubscription is possible for GPUs that have a non-zero + value for the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. 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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``, 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 + ``cuMemAdvise``. The application can also explicitly migrate memory to a + desired processor's memory via ``cuMemPrefetchAsync``. + + In a multi-GPU system where all of the GPUs have a zero value for the + device attribute ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` 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 + ``cuMemAllocManaged`` 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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` 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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. 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. + + Args: + bytesize (size_t): Requested allocation size in bytes. + flags (unsigned int): Must be one of ``CU_MEM_ATTACH_GLOBAL`` + or ``CU_MEM_ATTACH_HOST``. + + Returns: + unsigned long long: Returned device pointer. + + .. seealso:: `cuMemAllocManaged` + """ + cdef CUdeviceptr dptr + with nogil: + __status__ = cuMemAllocManaged(&dptr, bytesize, flags) + check_status(__status__) + return dptr + + +cpdef intptr_t device_register_async_notification(int device, intptr_t callback_func, intptr_t user_data) except? 0: + """Registers a callback function to receive async notifications. + + Registers ``callback_func`` to receive async notifications. + + The ``user_data`` 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 cuDeviceRegisterAsyncNotification or + cuDeviceUnregisterAsyncNotification. Doing so will result in + ``CUDA_ERROR_NOT_PERMITTED``. Async notification callbacks execute in an + undefined order and may be serialized. + + Returns in ``*callback`` a handle representing the registered callback + instance. + + Args: + device (int): The device on which to register the callback. + callback_func (intptr_t): The function to register as a + callback. + user_data (intptr_t): A generic pointer to user data. This is + passed into the callback function. + + Returns: + intptr_t: A handle representing the registered callback + instance. + + .. seealso:: `cuDeviceRegisterAsyncNotification` + """ + cdef CUasyncCallbackHandle callback + with nogil: + __status__ = cuDeviceRegisterAsyncNotification(device, callback_func, user_data, &callback) + check_status(__status__) + return callback + + +cpdef device_unregister_async_notification(int device, intptr_t callback): + """Unregisters an async notification callback. + + Unregisters ``callback`` so that the corresponding callback function will + stop receiving async notifications. + + Args: + device (int): The device from which to remove ``callback``. + callback (intptr_t): The callback instance to unregister from + receiving async notifications. + + .. seealso:: `cuDeviceUnregisterAsyncNotification` + """ + with nogil: + __status__ = cuDeviceUnregisterAsyncNotification(device, callback) + check_status(__status__) + + +cpdef int device_get_by_pci_bus_id(pci_bus_id) except? -1: + """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. + + Args: + pci_bus_id (bytes): String in one of the following forms:. + + Returns: + int: Returned device handle. + + .. seealso:: `cuDeviceGetByPCIBusId` + """ + cdef void* _pci_bus_id_ = _cyb_get_buffer_pointer(pci_bus_id, -1, readonly=True) + cdef CUdevice dev + with nogil: + __status__ = cuDeviceGetByPCIBusId(&dev, _pci_bus_id_) + check_status(__status__) + return dev + + +cpdef bytes device_get_pci_bus_id(int len, int dev): + """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 ``pci_bus_id``. ``length`` specifies the + maximum length of the string that may be returned. + + where ``domain``, ``bus``, ``device``, and ``function`` are all hexadecimal + values. pci_bus_id should be large enough to store 13 characters including + the NULL-terminator. + + Args: + len (int): Maximum length of string to store in ``name``. + dev (int): Device to get identifier string for. + + Returns: + char: Returned identifier string for the device in the + following format. + + .. seealso:: `cuDeviceGetPCIBusId` + """ + cdef bytes _pci_bus_id_ = bytes(len) + cdef char* pci_bus_id = _pci_bus_id_ + with nogil: + __status__ = cuDeviceGetPCIBusId(pci_bus_id, len, dev) + check_status(__status__) + return _pci_bus_id_ + + +cpdef object ipc_get_event_handle(intptr_t event): + """Gets an interprocess handle for a previously allocated event. + + Takes as input a previously allocated event. This event must have been + created with the ``CU_EVENT_INTERPROCESS`` and ``CU_EVENT_DISABLE_TIMING`` + flags set. This opaque handle may be copied into other processes and opened + with ``cuIpcOpenEventHandle`` to allow efficient hardware synchronization + between GPU work in different processes. + + After the event has been opened in the importing process, + ``cuEventRecord``, ``cuEventSynchronize``, ``cuStreamWaitEvent`` and + ``cuEventQuery`` may be used in either process. Performing operations on + the imported event after the exported event has been freed with + ``cuEventDestroy`` 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 ``cuDeviceGetAttribute`` with + ``CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED``. + + Args: + event (intptr_t): Event allocated with + ``CU_EVENT_INTERPROCESS`` and ``CU_EVENT_DISABLE_TIMING`` + flags. + + Returns: + CUipcEventHandle_v1: Pointer to a user allocated + ``CUipcEventHandle`` in which to return the opaque event + handle. + + .. seealso:: `cuIpcGetEventHandle` + """ + cdef IpcEventHandle_v1 p_handle_py = IpcEventHandle_v1() + cdef CUipcEventHandle *p_handle = (p_handle_py._get_ptr()) + with nogil: + __status__ = cuIpcGetEventHandle(p_handle, event) + check_status(__status__) + return p_handle_py + + +cpdef intptr_t ipc_open_event_handle(handle) except? 0: + """Opens an interprocess event handle for use in the current process. + + Opens an interprocess event handle exported from another process with + ``cuIpcGetEventHandle``. This function returns a ``CUevent`` that behaves + like a locally created event with the ``CU_EVENT_DISABLE_TIMING`` flag + specified. This event must be freed with ``cuEventDestroy``. + + Performing operations on the imported event after the exported event has + been freed with ``cuEventDestroy`` 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 + ``CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED``. + + Args: + handle (CUipcEventHandle_v1): Interprocess handle to open. + + Returns: + intptr_t: Returns the imported event. + + .. seealso:: `cuIpcOpenEventHandle` + """ + cdef intptr_t _handle_ptr_ = (handle)._get_ptr() + cdef CUevent ph_event + with nogil: + __status__ = cuIpcOpenEventHandle(&ph_event, (_handle_ptr_)[0]) + check_status(__status__) + return ph_event + + +cpdef object ipc_get_mem_handle(unsigned long long dptr): + """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 ``cuMemAlloc`` 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 ``cuMemFree`` and a subsequent call to + ``cuMemAlloc`` returns memory with the same device address, + ``cuIpcGetMemHandle`` 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 + ``CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED``. + + Args: + dptr (unsigned long long): Base pointer to previously + allocated device memory. + + Returns: + CUipcMemHandle_v1: Pointer to user allocated + ``CUipcMemHandle`` to return the handle in. + + .. seealso:: `cuIpcGetMemHandle` + """ + cdef IpcMemHandle_v1 p_handle_py = IpcMemHandle_v1() + cdef CUipcMemHandle *p_handle = (p_handle_py._get_ptr()) + with nogil: + __status__ = cuIpcGetMemHandle(p_handle, dptr) + check_status(__status__) + return p_handle_py + + +cpdef unsigned long long ipc_open_mem_handle_v2(handle, unsigned int flags) except? 0: + """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 ``cuIpcGetMemHandle`` into + the current device address space. For contexts on different devices + ``cuIpcOpenMemHandle`` can attempt to enable peer access between the + devices as if the user called ``cuCtxEnablePeerAccess``. This behavior is + controlled by the ``CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS`` flag. + ``cuDeviceCanAccessPeer`` can determine if a mapping is possible. + + Contexts that may open ``CUipcMemHandles`` are restricted in the following + way. ``CUipcMemHandles`` from each ``CUdevice`` in a given process may only + be opened by one ``CUcontext`` per ``CUdevice`` 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 ``cuIpcOpenMemHandle`` must be freed with + ``cuIpcCloseMemHandle``. + + Calling ``cuMemFree`` on an exported memory region before calling + ``cuIpcCloseMemHandle`` 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 + ``CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED``. + + Args: + handle (CUipcMemHandle_v1): ``CUipcMemHandle`` to open. + flags (unsigned int): flags for this operation. Must be + specified as ``CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS``. + + Returns: + unsigned long long: Returned device pointer. + + .. note:: + No guarantees are made about the address returned in ``*pdptr``. In + particular, multiple processes may not receive the same address for the + same ``handle``. + + .. seealso:: `cuIpcOpenMemHandle_v2` + """ + cdef intptr_t _handle_ptr_ = (handle)._get_ptr() + cdef CUdeviceptr pdptr + with nogil: + __status__ = cuIpcOpenMemHandle(&pdptr, (_handle_ptr_)[0], flags) + check_status(__status__) + return pdptr + + +cpdef ipc_close_mem_handle(unsigned long long dptr): + """Attempts to close memory mapped with ``cuIpcOpenMemHandle``. + + Decrements the reference count of the memory returned by + ``cuIpcOpenMemHandle`` 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 + ``CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED``. + + Args: + dptr (unsigned long long): Device pointer returned by + ``cuIpcOpenMemHandle``. + + .. seealso:: `cuIpcCloseMemHandle` + """ + with nogil: + __status__ = cuIpcCloseMemHandle(dptr) + check_status(__status__) + + +cpdef mem_host_register_v2(p, size_t bytesize, unsigned int flags): + """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 ``cuMemHostAlloc`` to automatically + accelerate calls to functions such as ``cuMemcpyHtoD()``. 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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES`` is + true, ``cuMemHostRegister`` 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 + ``cuMemHostGetDevicePointer()``. + + - ``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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES``, 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 ``CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED``. Using + this flag with a current context associated with a device that does not + have this attribute set will cause ``cuMemHostRegister`` to error with + CUDA_ERROR_NOT_SUPPORTED. + + 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 ``cuMemHostGetDevicePointer()`` 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 + ``CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM``, the memory + can also be accessed from the device using the host pointer ``p``. The + device pointer returned by ``cuMemHostGetDevicePointer()`` 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 + ``cuMemHostGetDevicePointer()`` 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 ``cuMemHostGetDevicePointer()`` + 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 + :func:`mem_host_unregister`. + + Args: + p (bytes): Host pointer to memory to page-lock. + bytesize (size_t): Size in bytes of the address range to page- + lock. + flags (unsigned int): flags for allocation request. + + .. seealso:: `cuMemHostRegister_v2` + """ + cdef void* _p_ = _cyb_get_buffer_pointer(p, -1, readonly=False) + with nogil: + __status__ = cuMemHostRegister(_p_, bytesize, flags) + check_status(__status__) + + +cpdef mem_host_unregister(p): + """Unregisters a memory range that was registered with cuMemHostRegister. + + 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 ``cuMemHostRegister()``. + + Args: + p (bytes): Host pointer to memory to unregister. + + .. seealso:: `cuMemHostUnregister` + """ + cdef void* _p_ = _cyb_get_buffer_pointer(p, -1, readonly=False) + with nogil: + __status__ = cuMemHostUnregister(_p_) + check_status(__status__) + + +cpdef cu_memcpy(unsigned long long dst, unsigned long long src, size_t byte_count): + """Copies memory. + + Copies data between two pointers. ``dst`` and ``src`` are base pointers of + the destination and source, respectively. ``byte_count`` 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. + + Args: + dst (unsigned long long): Destination unified virtual address + space pointer. + src (unsigned long long): Source unified virtual address space + pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpy` + """ + with nogil: + __status__ = cuMemcpy(dst, src, byte_count) + check_status(__status__) + + +cpdef memcpy_peer(unsigned long long dst_device, intptr_t dst_context, unsigned long long src_device, intptr_t src_context, size_t byte_count): + """Copies device memory between two contexts. + + Copies from device memory in one context to device memory in another + context. ``dst_device`` is the base device pointer of the destination + memory and ``dst_context`` is the destination context. ``src_device`` is + the base device pointer of the source memory and ``src_context`` is the + source pointer. ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_context (intptr_t): Destination context. + src_device (unsigned long long): Source device pointer. + src_context (intptr_t): Source context. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyPeer` + """ + with nogil: + __status__ = cuMemcpyPeer(dst_device, dst_context, src_device, src_context, byte_count) + check_status(__status__) + + +cpdef memcpy_htod_v2(unsigned long long dst_device, src_host, size_t byte_count): + """Copies memory from Host to Device. + + Copies from host memory to device memory. ``dst_device`` and ``src_host`` + are the base addresses of the destination and source, respectively. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + src_host (bytes): Source host pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyHtoD_v2` + """ + cdef void* _src_host_ = _cyb_get_buffer_pointer(src_host, -1, readonly=True) + with nogil: + __status__ = cuMemcpyHtoD(dst_device, _src_host_, byte_count) + check_status(__status__) + + +cpdef memcpy_dtoh_v2(dst_host, unsigned long long src_device, size_t byte_count): + """Copies memory from Device to Host. + + Copies from device to host memory. ``dst_host`` and ``src_device`` specify + the base pointers of the destination and source, respectively. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_host (bytes): Destination host pointer. + src_device (unsigned long long): Source device pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyDtoH_v2` + """ + cdef void* _dst_host_ = _cyb_get_buffer_pointer(dst_host, -1, readonly=False) + with nogil: + __status__ = cuMemcpyDtoH(_dst_host_, src_device, byte_count) + check_status(__status__) + + +cpdef memcpy_dtod_v2(unsigned long long dst_device, unsigned long long src_device, size_t byte_count): + """Copies memory from Device to Device. + + Copies from device memory to device memory. ``dst_device`` and + ``src_device`` are the base pointers of the destination and source, + respectively. ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + src_device (unsigned long long): Source device pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyDtoD_v2` + """ + with nogil: + __status__ = cuMemcpyDtoD(dst_device, src_device, byte_count) + check_status(__status__) + + +cpdef memcpy_dtoa_v2(intptr_t dst_array, size_t dst_offset, unsigned long long src_device, size_t byte_count): + """Copies memory from Device to Array. + + Copies from device memory to a 1D CUDA array. ``dst_array`` and + ``dst_offset`` specify the CUDA array handle and starting index of the + destination data. ``src_device`` specifies the base pointer of the source. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_array (intptr_t): Destination array. + dst_offset (size_t): Offset in bytes of destination array. + src_device (unsigned long long): Source device pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyDtoA_v2` + """ + with nogil: + __status__ = cuMemcpyDtoA(dst_array, dst_offset, src_device, byte_count) + check_status(__status__) + + +cpdef memcpy_atod_v2(unsigned long long dst_device, intptr_t src_array, size_t src_offset, size_t byte_count): + """Copies memory from Array to Device. + + Copies from one 1D CUDA array to device memory. ``dst_device`` specifies + the base pointer of the destination and must be naturally aligned with the + CUDA array elements. ``src_array`` and ``src_offset`` specify the CUDA + array handle and the offset in bytes into the array where the copy is to + begin. ``byte_count`` specifies the number of bytes to copy and must be + evenly divisible by the array element size. + + Args: + dst_device (unsigned long long): Destination device pointer. + src_array (intptr_t): Source array. + src_offset (size_t): Offset in bytes of source array. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyAtoD_v2` + """ + with nogil: + __status__ = cuMemcpyAtoD(dst_device, src_array, src_offset, byte_count) + check_status(__status__) + + +cpdef memcpy_htoa_v2(intptr_t dst_array, size_t dst_offset, src_host, size_t byte_count): + """Copies memory from Host to Array. + + Copies from host memory to a 1D CUDA array. ``dst_array`` and + ``dst_offset`` specify the CUDA array handle and starting offset in bytes + of the destination data. ``pSrc`` specifies the base address of the source. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_array (intptr_t): Destination array. + dst_offset (size_t): Offset in bytes of destination array. + src_host (bytes): Source host pointer. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyHtoA_v2` + """ + cdef void* _src_host_ = _cyb_get_buffer_pointer(src_host, -1, readonly=True) + with nogil: + __status__ = cuMemcpyHtoA(dst_array, dst_offset, _src_host_, byte_count) + check_status(__status__) + + +cpdef memcpy_atoh_v2(dst_host, intptr_t src_array, size_t src_offset, size_t byte_count): + """Copies memory from Array to Host. + + Copies from one 1D CUDA array to host memory. ``dst_host`` specifies the + base pointer of the destination. ``src_array`` and ``src_offset`` specify + the CUDA array handle and starting offset in bytes of the source data. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_host (bytes): Destination device pointer. + src_array (intptr_t): Source array. + src_offset (size_t): Offset in bytes of source array. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyAtoH_v2` + """ + cdef void* _dst_host_ = _cyb_get_buffer_pointer(dst_host, -1, readonly=False) + with nogil: + __status__ = cuMemcpyAtoH(_dst_host_, src_array, src_offset, byte_count) + check_status(__status__) + + +cpdef memcpy_atoa_v2(intptr_t dst_array, size_t dst_offset, intptr_t src_array, size_t src_offset, size_t byte_count): + """Copies memory from Array to Array. + + Copies from one 1D CUDA array to another. ``dst_array`` and ``src_array`` + specify the handles of the destination and source CUDA arrays for the copy, + respectively. ``dst_offset`` and ``src_offset`` specify the destination and + source offsets in bytes into the CUDA arrays. ``byte_count`` 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. + + Args: + dst_array (intptr_t): Destination array. + dst_offset (size_t): Offset in bytes of destination array. + src_array (intptr_t): Source array. + src_offset (size_t): Offset in bytes of source array. + byte_count (size_t): Size of memory copy in bytes. + + .. seealso:: `cuMemcpyAtoA_v2` + """ + with nogil: + __status__ = cuMemcpyAtoA(dst_array, dst_offset, src_array, src_offset, byte_count) + check_status(__status__) + + +cpdef memcpy_2d_v2(p_copy): + """Copies memory for 2D arrays. + + Perform a 2D memory copy according to the parameters specified in + ``p_copy``. The ``CUDA_MEMCPY2D`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``srcMemoryType`` and ``dstMemoryType`` specify the type of memory of the + source and destination, respectively; ``CUmemorytype_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``srcMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``srcArray`` specifies the + handle of the source data. ``srcHost``, ``srcDevice`` and ``srcPitch`` are + ignored. + + If ``dstMemoryType`` is ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``dstArray`` specifies the + handle of the destination data. ``dstHost``, ``dstDevice`` and ``dstPitch`` + are ignored. + + - ``srcXInBytes`` and ``srcY`` specify the base address of the source data + for the copy. + + For host pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``srcXInBytes`` must be evenly divisible by the array + element size. + + - ``dstXInBytes`` and ``dstY`` specify the base address of the destination + data for the copy. + + For host pointers, the base address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``dstXInBytes`` 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. + + ``cuMemcpy2D()`` returns an error if any pitch is greater than the maximum + allowed (``CU_DEVICE_ATTRIBUTE_MAX_PITCH``). ``cuMemAllocPitch()`` passes + back pitches that always work with ``cuMemcpy2D()``. On intra-device memory + copies (device to device, CUDA array to device, CUDA array to CUDA array), + ``cuMemcpy2D()`` may fail for pitches not computed by + ``cuMemAllocPitch()``. ``cuMemcpy2DUnaligned()`` does not have this + restriction, but may run significantly slower in the cases where + ``cuMemcpy2D()`` would have returned an error code. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + + .. seealso:: `cuMemcpy2D_v2` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy2D(_p_copy_ptr_) + check_status(__status__) + + +cpdef memcpy_2d_unaligned_v2(p_copy): + """Copies memory for 2D arrays. + + Perform a 2D memory copy according to the parameters specified in + ``p_copy``. The ``CUDA_MEMCPY2D`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``srcMemoryType`` and ``dstMemoryType`` specify the type of memory of the + source and destination, respectively; ``CUmemorytype_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``srcMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``srcArray`` specifies the + handle of the source data. ``srcHost``, ``srcDevice`` and ``srcPitch`` are + ignored. + + If ``dstMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``dstArray`` specifies the + handle of the destination data. ``dstHost``, ``dstDevice`` and ``dstPitch`` + are ignored. + + - ``srcXInBytes`` and ``srcY`` specify the base address of the source data + for the copy. + + For host pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``srcXInBytes`` must be evenly divisible by the array + element size. + + - ``dstXInBytes`` and ``dstY`` specify the base address of the destination + data for the copy. + + For host pointers, the base address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``dstXInBytes`` 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. + + ``cuMemcpy2D()`` returns an error if any pitch is greater than the maximum + allowed (``CU_DEVICE_ATTRIBUTE_MAX_PITCH``). ``cuMemAllocPitch()`` passes + back pitches that always work with ``cuMemcpy2D()``. On intra-device memory + copies (device to device, CUDA array to device, CUDA array to CUDA array), + ``cuMemcpy2D()`` may fail for pitches not computed by + ``cuMemAllocPitch()``. ``cuMemcpy2DUnaligned()`` does not have this + restriction, but may run significantly slower in the cases where + ``cuMemcpy2D()`` would have returned an error code. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + + .. seealso:: `cuMemcpy2DUnaligned_v2` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy2DUnaligned(_p_copy_ptr_) + check_status(__status__) + + +cpdef memcpy_3d_v2(p_copy): + """Copies memory for 3D arrays. + + Perform a 3D memory copy according to the parameters specified in + ``p_copy``. The ``CUDA_MEMCPY3D`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``srcMemoryType`` and ``dstMemoryType`` specify the type of memory of the + source and destination, respectively; ``CUmemorytype_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``srcMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``srcArray`` specifies the + handle of the source data. ``srcHost``, ``srcDevice``, ``srcPitch`` and + ``srcHeight`` are ignored. + + If ``dstMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``dstArray`` specifies the + handle of the destination data. ``dstHost``, ``dstDevice``, ``dstPitch`` + and ``dstHeight`` are ignored. + + - ``srcXInBytes``, ``srcY`` and ``srcZ`` specify the base address of the + source data for the copy. + + For host pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``srcXInBytes`` must be evenly divisible by the array + element size. + + - dstXInBytes, ``dstY`` and ``dstZ`` specify the base address of the + destination data for the copy. + + For host pointers, the base address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``dstXInBytes`` 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``. + + ``cuMemcpy3D()`` returns an error if any pitch is greater than the maximum + allowed (``CU_DEVICE_ATTRIBUTE_MAX_PITCH``). + + The ``srcLOD`` and ``dstLOD`` members of the ``CUDA_MEMCPY3D`` structure + must be set to 0. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + + .. seealso:: `cuMemcpy3D_v2` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy3D(_p_copy_ptr_) + check_status(__status__) + + +cpdef memcpy_3d_peer(p_copy): + """Copies memory between contexts. + + Perform a 3D memory copy according to the parameters specified in + ``p_copy``. See the definition of the ``CUDA_MEMCPY3D_PEER`` structure for + documentation of its parameters. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + + .. seealso:: `cuMemcpy3DPeer` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy3DPeer(_p_copy_ptr_) + check_status(__status__) + + +cpdef memcpy_async(unsigned long long dst, unsigned long long src, size_t byte_count, intptr_t h_stream): + """Copies memory asynchronously. + + Copies data between two pointers. ``dst`` and ``src`` are base pointers of + the destination and source, respectively. ``byte_count`` 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. + + Args: + dst (unsigned long long): Destination unified virtual address + space pointer. + src (unsigned long long): Source unified virtual address space + pointer. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyAsync` + """ + with nogil: + __status__ = cuMemcpyAsync(dst, src, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_peer_async(unsigned long long dst_device, intptr_t dst_context, unsigned long long src_device, intptr_t src_context, size_t byte_count, intptr_t h_stream): + """Copies device memory between two contexts asynchronously. + + Copies from device memory in one context to device memory in another + context. ``dst_device`` is the base device pointer of the destination + memory and ``dst_context`` is the destination context. ``src_device`` is + the base device pointer of the source memory and ``src_context`` is the + source pointer. ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_context (intptr_t): Destination context. + src_device (unsigned long long): Source device pointer. + src_context (intptr_t): Source context. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyPeerAsync` + """ + with nogil: + __status__ = cuMemcpyPeerAsync(dst_device, dst_context, src_device, src_context, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_htod_async_v2(unsigned long long dst_device, src_host, size_t byte_count, intptr_t h_stream): + """Copies memory from Host to Device. + + Copies from host memory to device memory. ``dst_device`` and ``src_host`` + are the base addresses of the destination and source, respectively. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + src_host (bytes): Source host pointer. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyHtoDAsync_v2` + """ + cdef void* _src_host_ = _cyb_get_buffer_pointer(src_host, -1, readonly=True) + with nogil: + __status__ = cuMemcpyHtoDAsync(dst_device, _src_host_, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_dtoh_async_v2(dst_host, unsigned long long src_device, size_t byte_count, intptr_t h_stream): + """Copies memory from Device to Host. + + Copies from device to host memory. ``dst_host`` and ``src_device`` specify + the base pointers of the destination and source, respectively. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_host (bytes): Destination host pointer. + src_device (unsigned long long): Source device pointer. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyDtoHAsync_v2` + """ + cdef void* _dst_host_ = _cyb_get_buffer_pointer(dst_host, -1, readonly=False) + with nogil: + __status__ = cuMemcpyDtoHAsync(_dst_host_, src_device, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_dtod_async_v2(unsigned long long dst_device, unsigned long long src_device, size_t byte_count, intptr_t h_stream): + """Copies memory from Device to Device. + + Copies from device memory to device memory. ``dst_device`` and + ``src_device`` are the base pointers of the destination and source, + respectively. ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_device (unsigned long long): Destination device pointer. + src_device (unsigned long long): Source device pointer. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyDtoDAsync_v2` + """ + with nogil: + __status__ = cuMemcpyDtoDAsync(dst_device, src_device, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_htoa_async_v2(intptr_t dst_array, size_t dst_offset, src_host, size_t byte_count, intptr_t h_stream): + """Copies memory from Host to Array. + + Copies from host memory to a 1D CUDA array. ``dst_array`` and + ``dst_offset`` specify the CUDA array handle and starting offset in bytes + of the destination data. ``src_host`` specifies the base address of the + source. ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_array (intptr_t): Destination array. + dst_offset (size_t): Offset in bytes of destination array. + src_host (bytes): Source host pointer. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyHtoAAsync_v2` + """ + cdef void* _src_host_ = _cyb_get_buffer_pointer(src_host, -1, readonly=True) + with nogil: + __status__ = cuMemcpyHtoAAsync(dst_array, dst_offset, _src_host_, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_atoh_async_v2(dst_host, intptr_t src_array, size_t src_offset, size_t byte_count, intptr_t h_stream): + """Copies memory from Array to Host. + + Copies from one 1D CUDA array to host memory. ``dst_host`` specifies the + base pointer of the destination. ``src_array`` and ``src_offset`` specify + the CUDA array handle and starting offset in bytes of the source data. + ``byte_count`` specifies the number of bytes to copy. + + Args: + dst_host (bytes): Destination pointer. + src_array (intptr_t): Source array. + src_offset (size_t): Offset in bytes of source array. + byte_count (size_t): Size of memory copy in bytes. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpyAtoHAsync_v2` + """ + cdef void* _dst_host_ = _cyb_get_buffer_pointer(dst_host, -1, readonly=False) + with nogil: + __status__ = cuMemcpyAtoHAsync(_dst_host_, src_array, src_offset, byte_count, h_stream) + check_status(__status__) + + +cpdef memcpy_2d_async_v2(p_copy, intptr_t h_stream): + """Copies memory for 2D arrays. + + Perform a 2D memory copy according to the parameters specified in + ``p_copy``. The ``CUDA_MEMCPY2D`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``srcMemoryType`` and ``dstMemoryType`` specify the type of memory of the + source and destination, respectively; ``CUmemorytype_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``srcMemoryType`` is ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``srcArray`` specifies the + handle of the source data. ``srcHost``, ``srcDevice`` and ``srcPitch`` are + ignored. + + If ``dstMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``dstArray`` specifies the + handle of the destination data. ``dstHost``, ``dstDevice`` and ``dstPitch`` + are ignored. + + - ``srcXInBytes`` and ``srcY`` specify the base address of the source data + for the copy. + + For host pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``srcXInBytes`` must be evenly divisible by the array + element size. + + - ``dstXInBytes`` and ``dstY`` specify the base address of the destination + data for the copy. + + For host pointers, the base address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``dstXInBytes`` 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``. + + ``cuMemcpy2DAsync()`` returns an error if any pitch is greater than the + maximum allowed (``CU_DEVICE_ATTRIBUTE_MAX_PITCH``). ``cuMemAllocPitch()`` + passes back pitches that always work with ``cuMemcpy2D()``. On intra-device + memory copies (device to device, CUDA array to device, CUDA array to CUDA + array), ``cuMemcpy2DAsync()`` may fail for pitches not computed by + ``cuMemAllocPitch()``. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpy2DAsync_v2` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy2DAsync(_p_copy_ptr_, h_stream) + check_status(__status__) + + +cpdef memcpy_3d_async_v2(p_copy, intptr_t h_stream): + """Copies memory for 3D arrays. + + Perform a 3D memory copy according to the parameters specified in + ``p_copy``. The ``CUDA_MEMCPY3D`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``srcMemoryType`` and ``dstMemoryType`` specify the type of memory of the + source and destination, respectively; ``CUmemorytype_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``srcMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``srcArray`` specifies the + handle of the source data. ``srcHost``, ``srcDevice``, ``srcPitch`` and + ``srcHeight`` are ignored. + + If ``dstMemoryType`` is ``CU_MEMORYTYPE_UNIFIED``, ``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 ``CU_MEMORYTYPE_HOST``, ``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 ``CU_MEMORYTYPE_DEVICE``, ``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 ``CU_MEMORYTYPE_ARRAY``, ``dstArray`` specifies the + handle of the destination data. ``dstHost``, ``dstDevice``, ``dstPitch`` + and ``dstHeight`` are ignored. + + - ``srcXInBytes``, ``srcY`` and ``srcZ`` specify the base address of the + source data for the copy. + + For host pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``srcXInBytes`` must be evenly divisible by the array + element size. + + - dstXInBytes, ``dstY`` and ``dstZ`` specify the base address of the + destination data for the copy. + + For host pointers, the base address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For device pointers, the starting address is. + + **View CUDA Toolkit Documentation for a C++ code example**. + + For CUDA arrays, ``dstXInBytes`` 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``. + + ``cuMemcpy3DAsync()`` returns an error if any pitch is greater than the + maximum allowed (``CU_DEVICE_ATTRIBUTE_MAX_PITCH``). + + The ``srcLOD`` and ``dstLOD`` members of the ``CUDA_MEMCPY3D`` structure + must be set to 0. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpy3DAsync_v2` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy3DAsync(_p_copy_ptr_, h_stream) + check_status(__status__) + + +cpdef memcpy_3d_peer_async(p_copy, intptr_t h_stream): + """Copies memory between contexts asynchronously. + + Perform a 3D memory copy according to the parameters specified in + ``p_copy``. See the definition of the ``CUDA_MEMCPY3D_PEER`` structure for + documentation of its parameters. + + Args: + p_copy (intptr_t): Parameters for the memory copy. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemcpy3DPeerAsync` + """ + cdef intptr_t _p_copy_ptr_ = int(p_copy) + with nogil: + __status__ = cuMemcpy3DPeerAsync(_p_copy_ptr_, h_stream) + check_status(__status__) + + +cpdef memset_d8_v2(unsigned long long dst_device, unsigned char uc, size_t n): + """Initializes device memory. + + Sets the memory range of ``n`` 8-bit values to the specified value ``uc``. + + Args: + dst_device (unsigned long long): Destination device pointer. + uc (unsigned char): Value to set. + n (size_t): number of elements. + + .. seealso:: `cuMemsetD8_v2` + """ + with nogil: + __status__ = cuMemsetD8(dst_device, uc, n) + check_status(__status__) + + +cpdef memset_d16_v2(unsigned long long dst_device, unsigned short us, size_t n): + """Initializes device memory. + + Sets the memory range of ``n`` 16-bit values to the specified value ``us``. + The ``dst_device`` pointer must be two byte aligned. + + Args: + dst_device (unsigned long long): Destination device pointer. + us (unsigned short): Value to set. + n (size_t): number of elements. + + .. seealso:: `cuMemsetD16_v2` + """ + with nogil: + __status__ = cuMemsetD16(dst_device, us, n) + check_status(__status__) + + +cpdef memset_d32_v2(unsigned long long dst_device, unsigned int ui, size_t n): + """Initializes device memory. + + Sets the memory range of ``n`` 32-bit values to the specified value ``ui``. + The ``dst_device`` pointer must be four byte aligned. + + Args: + dst_device (unsigned long long): Destination device pointer. + ui (unsigned int): Value to set. + n (size_t): number of elements. + + .. seealso:: `cuMemsetD32_v2` + """ + with nogil: + __status__ = cuMemsetD32(dst_device, ui, n) + check_status(__status__) + + +cpdef memset_d2d8_v2(unsigned long long dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height): + """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 ``dst_pitch`` + specifies the number of bytes between each row. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + uc (unsigned char): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + + .. seealso:: `cuMemsetD2D8_v2` + """ + with nogil: + __status__ = cuMemsetD2D8(dst_device, dst_pitch, uc, width, height) + check_status(__status__) + + +cpdef memset_d2d16_v2(unsigned long long dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height): + """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 ``dst_pitch`` + specifies the number of bytes between each row. The ``dst_device`` pointer + and ``dst_pitch`` offset must be two byte aligned. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + us (unsigned short): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + + .. seealso:: `cuMemsetD2D16_v2` + """ + with nogil: + __status__ = cuMemsetD2D16(dst_device, dst_pitch, us, width, height) + check_status(__status__) + + +cpdef memset_d2d32_v2(unsigned long long dst_device, size_t dst_pitch, unsigned int ui, size_t width, size_t height): + """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 ``dst_pitch`` + specifies the number of bytes between each row. The ``dst_device`` pointer + and ``dst_pitch`` offset must be four byte aligned. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + ui (unsigned int): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + + .. seealso:: `cuMemsetD2D32_v2` + """ + with nogil: + __status__ = cuMemsetD2D32(dst_device, dst_pitch, ui, width, height) + check_status(__status__) + + +cpdef memset_d8_async(unsigned long long dst_device, unsigned char uc, size_t n, intptr_t h_stream): + """Sets device memory. + + Sets the memory range of ``n`` 8-bit values to the specified value ``uc``. + + Args: + dst_device (unsigned long long): Destination device pointer. + uc (unsigned char): Value to set. + n (size_t): number of elements. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD8Async` + """ + with nogil: + __status__ = cuMemsetD8Async(dst_device, uc, n, h_stream) + check_status(__status__) + + +cpdef memset_d16_async(unsigned long long dst_device, unsigned short us, size_t n, intptr_t h_stream): + """Sets device memory. + + Sets the memory range of ``n`` 16-bit values to the specified value ``us``. + The ``dst_device`` pointer must be two byte aligned. + + Args: + dst_device (unsigned long long): Destination device pointer. + us (unsigned short): Value to set. + n (size_t): number of elements. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD16Async` + """ + with nogil: + __status__ = cuMemsetD16Async(dst_device, us, n, h_stream) + check_status(__status__) + + +cpdef memset_d32_async(unsigned long long dst_device, unsigned int ui, size_t n, intptr_t h_stream): + """Sets device memory. + + Sets the memory range of ``n`` 32-bit values to the specified value ``ui``. + The ``dst_device`` pointer must be four byte aligned. + + Args: + dst_device (unsigned long long): Destination device pointer. + ui (unsigned int): Value to set. + n (size_t): number of elements. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD32Async` + """ + with nogil: + __status__ = cuMemsetD32Async(dst_device, ui, n, h_stream) + check_status(__status__) + + +cpdef memset_d2d8_async(unsigned long long dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height, intptr_t h_stream): + """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 ``dst_pitch`` + specifies the number of bytes between each row. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + uc (unsigned char): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD2D8Async` + """ + with nogil: + __status__ = cuMemsetD2D8Async(dst_device, dst_pitch, uc, width, height, h_stream) + check_status(__status__) + + +cpdef memset_d2d16_async(unsigned long long dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height, intptr_t h_stream): + """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 ``dst_pitch`` + specifies the number of bytes between each row. The ``dst_device`` pointer + and ``dst_pitch`` offset must be two byte aligned. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + us (unsigned short): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD2D16Async` + """ + with nogil: + __status__ = cuMemsetD2D16Async(dst_device, dst_pitch, us, width, height, h_stream) + check_status(__status__) + + +cpdef memset_d2d32_async(unsigned long long dst_device, size_t dst_pitch, unsigned int ui, size_t width, size_t height, intptr_t h_stream): + """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 ``dst_pitch`` + specifies the number of bytes between each row. The ``dst_device`` pointer + and ``dst_pitch`` offset must be four byte aligned. This function performs + fastest when the pitch is one that has been passed back by + ``cuMemAllocPitch()``. + + Args: + dst_device (unsigned long long): Destination device pointer. + dst_pitch (size_t): Pitch of destination device pointer(Unused + if ``height`` is 1). + ui (unsigned int): Value to set. + width (size_t): width of row. + height (size_t): Number of rows. + h_stream (intptr_t): Stream identifier. + + .. seealso:: `cuMemsetD2D32Async` + """ + with nogil: + __status__ = cuMemsetD2D32Async(dst_device, dst_pitch, ui, width, height, h_stream) + check_status(__status__) + + +cpdef intptr_t array_create_v2(p_allocate_array) except? 0: + """Creates a 1D or 2D CUDA array. + + Creates a CUDA array according to the ``CUDA_ARRAY_DESCRIPTOR`` structure + ``p_allocate_array`` and returns a handle to the new CUDA array in + ``*p_handle``. The ``CUDA_ARRAY_DESCRIPTOR`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``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; ``CUarray_format`` is + defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``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:. + + Description for a CUDA array of 2048 floats:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Description for a 64 x 64 CUDA array of floats:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Description for a ``width`` x ``height`` CUDA array of 64-bit, 4x16-bit + float16's:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Description for a ``width`` x ``height`` CUDA array of 16-bit elements, + each of which is two 8-bit unsigned chars:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Args: + p_allocate_array (intptr_t): Array descriptor. + + Returns: + intptr_t: Returned array. + + .. seealso:: `cuArrayCreate_v2` + """ + cdef intptr_t _p_allocate_array_ptr_ = int(p_allocate_array) + cdef CUarray p_handle + with nogil: + __status__ = cuArrayCreate(&p_handle, _p_allocate_array_ptr_) + check_status(__status__) + return p_handle + + +cpdef object array_get_descriptor_v2(intptr_t h_array): + """Get a 1D or 2D CUDA array descriptor. + + Returns in ``*p_array_descriptor`` a descriptor containing information on + the format and dimensions of the CUDA array ``h_array``. 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. + + Args: + h_array (intptr_t): Array to get descriptor of. + + Returns: + CUDA_ARRAY_DESCRIPTOR_v2: Returned array descriptor. + + .. seealso:: `cuArrayGetDescriptor_v2` + """ + cdef ArrayDescriptor_v2 p_array_descriptor_py = ArrayDescriptor_v2() + cdef CUDA_ARRAY_DESCRIPTOR *p_array_descriptor = (p_array_descriptor_py._get_ptr()) + with nogil: + __status__ = cuArrayGetDescriptor(p_array_descriptor, h_array) + check_status(__status__) + return p_array_descriptor_py + + +cpdef object array_get_sparse_properties(intptr_t array): + """Returns the layout properties of a sparse CUDA array. + + Returns the layout properties of a sparse CUDA array in + ``sparse_properties`` If the CUDA array is not allocated with flag + ``CUDA_ARRAY3D_SPARSE`` ``CUDA_ERROR_INVALID_VALUE`` will be returned. + + If the returned value in ``CUDA_ARRAY_SPARSE_PROPERTIES.flags`` contains + ``CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL``, then + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailSize`` represents the total size of + the array. Otherwise, it will be zero. Also, the returned value in + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailFirstLevel`` is always zero. Note + that the ``array`` must have been allocated using ``cuArrayCreate`` or + ``cuArray3DCreate``. For CUDA arrays obtained using + ``cuMipmappedArrayGetLevel``, ``CUDA_ERROR_INVALID_VALUE`` will be + returned. Instead, ``cuMipmappedArrayGetSparseProperties`` must be used to + obtain the sparse properties of the entire CUDA mipmapped array to which + ``array`` belongs to. + + Args: + array (intptr_t): CUDA array to get the sparse properties of. + + Returns: + CUDA_ARRAY_SPARSE_PROPERTIES_v1: Pointer to + ``CUDA_ARRAY_SPARSE_PROPERTIES``. + + .. seealso:: `cuArrayGetSparseProperties` + """ + cdef ArraySparseProperties_v1 sparse_properties_py = ArraySparseProperties_v1() + cdef CUDA_ARRAY_SPARSE_PROPERTIES *sparse_properties = (sparse_properties_py._get_ptr()) + with nogil: + __status__ = cuArrayGetSparseProperties(sparse_properties, array) + check_status(__status__) + return sparse_properties_py + + +cpdef object mipmapped_array_get_sparse_properties(intptr_t mipmap): + """Returns the layout properties of a sparse CUDA mipmapped array. + + Returns the sparse array layout properties in ``sparse_properties`` If the + CUDA mipmapped array is not allocated with flag ``CUDA_ARRAY3D_SPARSE`` + ``CUDA_ERROR_INVALID_VALUE`` will be returned. + + For non-layered CUDA mipmapped arrays, + ``CUDA_ARRAY_SPARSE_PROPERTIES.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 ``CUDA_ARRAY_SPARSE_PROPERTIES.flags`` contains + ``CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL``, then + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailSize`` specifies the size of the mip + tail of all layers combined. Otherwise, + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailSize`` specifies mip tail size per + layer. The returned value of + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailFirstLevel`` is valid only if + ``CUDA_ARRAY_SPARSE_PROPERTIES.miptailSize`` is non-zero. + + Args: + mipmap (intptr_t): CUDA mipmapped array to get the sparse + properties of. + + Returns: + CUDA_ARRAY_SPARSE_PROPERTIES_v1: Pointer to + ``CUDA_ARRAY_SPARSE_PROPERTIES``. + + .. seealso:: `cuMipmappedArrayGetSparseProperties` + """ + cdef ArraySparseProperties_v1 sparse_properties_py = ArraySparseProperties_v1() + cdef CUDA_ARRAY_SPARSE_PROPERTIES *sparse_properties = (sparse_properties_py._get_ptr()) + with nogil: + __status__ = cuMipmappedArrayGetSparseProperties(sparse_properties, mipmap) + check_status(__status__) + return sparse_properties_py + + +cpdef object array_get_memory_requirements(intptr_t array, int device): + """Returns the memory requirements of a CUDA array. + + Returns the memory requirements of a CUDA array in ``memory_requirements`` + If the CUDA array is not allocated with flag + ``CUDA_ARRAY3D_DEFERRED_MAPPING`` ``CUDA_ERROR_INVALID_VALUE`` will be + returned. + + The returned value in ``CUDA_ARRAY_MEMORY_REQUIREMENTS.size`` represents + the total size of the CUDA array. The returned value in + ``CUDA_ARRAY_MEMORY_REQUIREMENTS.alignment`` represents the alignment + necessary for mapping the CUDA array. + + Args: + array (intptr_t): CUDA array to get the memory requirements + of. + device (int): Device to get the memory requirements for. + + Returns: + CUDA_ARRAY_MEMORY_REQUIREMENTS_v1: Pointer to + ``CUDA_ARRAY_MEMORY_REQUIREMENTS``. + + .. seealso:: `cuArrayGetMemoryRequirements` + """ + cdef ArrayMemoryRequirements_v1 memory_requirements_py = ArrayMemoryRequirements_v1() + cdef CUDA_ARRAY_MEMORY_REQUIREMENTS *memory_requirements = (memory_requirements_py._get_ptr()) + with nogil: + __status__ = cuArrayGetMemoryRequirements(memory_requirements, array, device) + check_status(__status__) + return memory_requirements_py + + +cpdef object mipmapped_array_get_memory_requirements(intptr_t mipmap, int device): + """Returns the memory requirements of a CUDA mipmapped array. + + Returns the memory requirements of a CUDA mipmapped array in + ``memory_requirements`` If the CUDA mipmapped array is not allocated with + flag ``CUDA_ARRAY3D_DEFERRED_MAPPING`` ``CUDA_ERROR_INVALID_VALUE`` will be + returned. + + The returned value in ``CUDA_ARRAY_MEMORY_REQUIREMENTS.size`` represents + the total size of the CUDA mipmapped array. The returned value in + ``CUDA_ARRAY_MEMORY_REQUIREMENTS.alignment`` represents the alignment + necessary for mapping the CUDA mipmapped array. + + Args: + mipmap (intptr_t): CUDA mipmapped array to get the memory + requirements of. + device (int): Device to get the memory requirements for. + + Returns: + CUDA_ARRAY_MEMORY_REQUIREMENTS_v1: Pointer to + ``CUDA_ARRAY_MEMORY_REQUIREMENTS``. + + .. seealso:: `cuMipmappedArrayGetMemoryRequirements` + """ + cdef ArrayMemoryRequirements_v1 memory_requirements_py = ArrayMemoryRequirements_v1() + cdef CUDA_ARRAY_MEMORY_REQUIREMENTS *memory_requirements = (memory_requirements_py._get_ptr()) + with nogil: + __status__ = cuMipmappedArrayGetMemoryRequirements(memory_requirements, mipmap, device) + check_status(__status__) + return memory_requirements_py + + +cpdef intptr_t array_get_plane(intptr_t h_array, unsigned int plane_idx) except? 0: + """Gets a CUDA array plane from a CUDA array. + + Returns in ``p_plane_array`` a CUDA array that represents a single format + plane of the CUDA array ``h_array``. + + If ``plane_idx`` is greater than the maximum number of planes in this array + or if the array does not have a multi-planar format e.g: + ``CU_AD_FORMAT_NV12``, then ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Note that if the ``h_array`` has format ``CU_AD_FORMAT_NV12``, then passing + in 0 for ``plane_idx`` returns a CUDA array of the same size as ``h_array`` + but with one channel and ``CU_AD_FORMAT_UNSIGNED_INT8`` as its format. If 1 + is passed for ``plane_idx``, then the returned CUDA array has half the + height and width of ``h_array`` with two channels and + ``CU_AD_FORMAT_UNSIGNED_INT8`` as its format. + + Args: + h_array (intptr_t): Multiplanar CUDA array. + plane_idx (unsigned int): Plane index. + + Returns: + intptr_t: Returned CUDA array referenced by the ``plane_idx``. + + .. seealso:: `cuArrayGetPlane` + """ + cdef CUarray p_plane_array + with nogil: + __status__ = cuArrayGetPlane(&p_plane_array, h_array, plane_idx) + check_status(__status__) + return p_plane_array + + +cpdef array_destroy(intptr_t h_array): + """Destroys a CUDA array. + + Destroys the CUDA array ``h_array``. + + Args: + h_array (intptr_t): Array to destroy. + + .. seealso:: `cuArrayDestroy` + """ + with nogil: + __status__ = cuArrayDestroy(h_array) + check_status(__status__) + + +cpdef intptr_t array_3d_create_v2(p_allocate_array) except? 0: + """Creates a 3D CUDA array. + + Creates a CUDA array according to the ``CUDA_ARRAY3D_DESCRIPTOR`` structure + ``p_allocate_array`` and returns a handle to the new CUDA array in + ``*p_handle``. The ``CUDA_ARRAY3D_DESCRIPTOR`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``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 + ``CUarray_cubemap_face``. + + - 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; ``CUarray_format`` is + defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``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, ``cuSurfRefSetArray`` 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 + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH``. + + 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 ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH`` + and ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT`` respectively, + in that case. + + **View CUDA Toolkit Documentation for a table example**. + + Here are examples of CUDA array descriptions:. + + Description for a CUDA array of 2048 floats:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Description for a 64 x 64 CUDA array of floats:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Description for a ``width`` x ``height`` x ``depth`` CUDA array of 64-bit, + 4x16-bit float16's:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Args: + p_allocate_array (intptr_t): 3D array descriptor. + + Returns: + intptr_t: Returned array. + + .. seealso:: `cuArray3DCreate_v2` + """ + cdef intptr_t _p_allocate_array_ptr_ = int(p_allocate_array) + cdef CUarray p_handle + with nogil: + __status__ = cuArray3DCreate(&p_handle, _p_allocate_array_ptr_) + check_status(__status__) + return p_handle + + +cpdef object array_3d_get_descriptor_v2(intptr_t h_array): + """Get a 3D CUDA array descriptor. + + Returns in ``*p_array_descriptor`` a descriptor containing information on + the format and dimensions of the CUDA array ``h_array``. 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. + + Args: + h_array (intptr_t): 3D array to get descriptor of. + + Returns: + CUDA_ARRAY3D_DESCRIPTOR_v2: Returned 3D array descriptor. + + .. seealso:: `cuArray3DGetDescriptor_v2` + """ + cdef Array3dDescriptor_v2 p_array_descriptor_py = Array3dDescriptor_v2() + cdef CUDA_ARRAY3D_DESCRIPTOR *p_array_descriptor = (p_array_descriptor_py._get_ptr()) + with nogil: + __status__ = cuArray3DGetDescriptor(p_array_descriptor, h_array) + check_status(__status__) + return p_array_descriptor_py + + +cpdef intptr_t mipmapped_array_create(p_mipmapped_array_desc, unsigned int num_mipmap_levels) except? 0: + """Creates a CUDA mipmapped array. + + Creates a CUDA mipmapped array according to the ``CUDA_ARRAY3D_DESCRIPTOR`` + structure ``p_mipmapped_array_desc`` and returns a handle to the new CUDA + mipmapped array in ``*p_handle``. ``num_mipmap_levels`` specifies the + number of mipmap levels to be allocated. This value is clamped to the range + [1, 1 + floor(log2(max(width, height, depth)))]. + + The ``CUDA_ARRAY3D_DESCRIPTOR`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``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 + ``CUarray_cubemap_face``. + + - 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; ``CUarray_format`` is + defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``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, ``cuSurfRefSetArray`` 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 ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH``. + + **View CUDA Toolkit Documentation for a table example**. + + Args: + p_mipmapped_array_desc (intptr_t): mipmapped array descriptor. + num_mipmap_levels (unsigned int): Number of mipmap levels. + + Returns: + intptr_t: Returned mipmapped array. + + .. seealso:: `cuMipmappedArrayCreate` + """ + cdef intptr_t _p_mipmapped_array_desc_ptr_ = int(p_mipmapped_array_desc) + cdef CUmipmappedArray p_handle + with nogil: + __status__ = cuMipmappedArrayCreate(&p_handle, _p_mipmapped_array_desc_ptr_, num_mipmap_levels) + check_status(__status__) + return p_handle + + +cpdef intptr_t mipmapped_array_get_level(intptr_t h_mipmapped_array, unsigned int level) except? 0: + """Gets a mipmap level of a CUDA mipmapped array. + + Returns in ``*p_level_array`` a CUDA array that represents a single mipmap + level of the CUDA mipmapped array ``h_mipmapped_array``. + + If ``level`` is greater than the maximum number of levels in this mipmapped + array, ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Args: + h_mipmapped_array (intptr_t): CUDA mipmapped array. + level (unsigned int): Mipmap level. + + Returns: + intptr_t: Returned mipmap level CUDA array. + + .. seealso:: `cuMipmappedArrayGetLevel` + """ + cdef CUarray p_level_array + with nogil: + __status__ = cuMipmappedArrayGetLevel(&p_level_array, h_mipmapped_array, level) + check_status(__status__) + return p_level_array + + +cpdef mipmapped_array_destroy(intptr_t h_mipmapped_array): + """Destroys a CUDA mipmapped array. + + Destroys the CUDA mipmapped array ``h_mipmapped_array``. + + Args: + h_mipmapped_array (intptr_t): Mipmapped array to destroy. + + .. seealso:: `cuMipmappedArrayDestroy` + """ + with nogil: + __status__ = cuMipmappedArrayDestroy(h_mipmapped_array) + check_status(__status__) + + +cpdef mem_get_handle_for_address_range(intptr_t handle, unsigned long long dptr, size_t size, int handle_type, unsigned long long flags): + """Retrieve handle for an address range. + + Get a handle of the specified type to an address range. When requesting + CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD, address range + obtained by a prior call to either ``cuMemAlloc`` or + ``cuMemAddressReserve`` is supported if the + ``CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED`` device attribute returns true. If + the address range was obtained via ``cuMemAddressReserve``, it must also be + fully mapped via ``cuMemMap``. Address range obtained by a prior call to + either ``cuMemAllocHost`` or ``cuMemHostAlloc`` is supported if the + ``CU_DEVICE_ATTRIBUTE_HOST_ALLOC_DMA_BUF_SUPPORTED`` device attribute + returns true. + + As of CUDA 13.0, querying support for address range obtained by calling + ``cuMemAllocHost`` or ``cuMemHostAlloc`` using the + ``CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED`` 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 + ``cuMemAddressReserve``. 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 CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD, users may + set flags to ``CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE``. 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 ``CU_DEVICE_ATTRIBUTE_DMA_BUF_MMAP_SUPPORTED`` is + set and a CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD 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. + + Args: + handle (intptr_t): Pointer to the location where the returned + handle will be stored. + dptr (unsigned long long): Pointer to a valid CUDA device + allocation. Must be aligned to host page size. + size (size_t): Length of the address range. Must be aligned to + host page size. + handle_type (MemRangeHandleType): Type of handle requested + (defines type and size of the ``handle`` output + parameter). + flags (unsigned long long): When requesting + CUmemRangeHandleType::CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD + the value could be + ``CU_MEM_RANGE_FLAG_DMA_BUF_MAPPING_TYPE_PCIE``, otherwise + 0. + + .. seealso:: `cuMemGetHandleForAddressRange` + """ + with nogil: + __status__ = cuMemGetHandleForAddressRange(handle, dptr, size, handle_type, flags) + check_status(__status__) + + +cpdef mem_batch_decompress_async(params_array, size_t count, unsigned int flags, intptr_t error_index, intptr_t stream): + """Submit a batch of ``count`` independent decompression operations. + + Each of the ``count`` decompression operations is described by a single + entry in the ``params_array`` 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 ``CUmemDecompressParams.src``, + ``CUmemDecompressParams.dst``, and ``CUmemDecompressParams.dstActBytes``, + must be capable of usage with the hardware decompress feature. That is, for + each of said pointers, the pointer attribute + ``CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE`` 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:. + + - ``cuMemAlloc()``. + + - :func:`mem_create` with the usage flag + ``CU_MEM_CREATE_USAGE_HW_DECOMPRESS``. + + - :func:`mem_alloc_from_pool_async` from a pool that was created with the + usage flag ``CU_MEM_POOL_CREATE_USAGE_HW_DECOMPRESS`` Additionally, + ``CUmemDecompressParams.src``, ``CUmemDecompressParams.dst``, and + ``CUmemDecompressParams.dstActBytes``, must all be accessible from the + device associated with the context where ``stream`` was created. For + information on how to ensure this, see the documentation for the allocator + of interest. + + Args: + params_array (intptr_t): The array of structures describing + the independent decompression operations. + count (size_t): The number of entries in ``params_array`` + array. + flags (unsigned int): Must be 0. + error_index (intptr_t): The index into ``params_array`` of the + decompression operation for which the error returned by + this function pertains to. If ``index`` is SIZE_MAX and + the value returned is not ``CUDA_SUCCESS``, then the error + returned by this function should be considered a general + error that does not pertain to a particular decompression + operation. May be ``NULL``, in which case, no index will + be recorded in the event of error. + stream (intptr_t): The stream where the work will be enqueued. + + .. seealso:: `cuMemBatchDecompressAsync` + """ + cdef intptr_t _params_array_ptr_ = int(params_array) + with nogil: + __status__ = cuMemBatchDecompressAsync(_params_array_ptr_, count, flags, error_index, stream) + check_status(__status__) + + +cpdef unsigned long long mem_address_reserve(size_t size, size_t alignment, unsigned long long addr, unsigned long long flags) except? 0: + """Allocate 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. + + Args: + size (size_t): Size of the reserved virtual address range + requested. + alignment (size_t): Alignment of the reserved virtual address + range requested. + addr (unsigned long long): Hint address for the start of the + address range. + flags (unsigned long long): Currently unused, must be zero. + + Returns: + unsigned long long: Resulting pointer to start of virtual + address range allocated. + + .. seealso:: `cuMemAddressReserve` + """ + cdef CUdeviceptr ptr + with nogil: + __status__ = cuMemAddressReserve(&ptr, size, alignment, addr, flags) + check_status(__status__) + return ptr + + +cpdef mem_address_free(unsigned long long ptr, size_t size): + """Free an address range reservation. + + Frees a virtual address range reserved by cuMemAddressReserve. The size + must match what was given to memAddressReserve and the ptr given must match + what was returned from memAddressReserve. + + Args: + ptr (unsigned long long): Starting address of the virtual + address range to free. + size (size_t): Size of the virtual address region to free. + + .. seealso:: `cuMemAddressFree` + """ + with nogil: + __status__ = cuMemAddressFree(ptr, size) + check_status(__status__) + + +cpdef unsigned long long mem_create(size_t size, prop, unsigned long long flags) except? 0: + """Create 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 ``cuMemMap``. This handle cannot + be transmitted directly to other processes (see + ``cuMemExportToShareableHandle``). 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 + ``CUmemAllocationProp.win32HandleMetaData`` for more). The ``size`` of this + allocation must be a multiple of the the value given via + ``cuMemGetAllocationGranularity`` with the + ``CU_MEM_ALLOC_GRANULARITY_MINIMUM`` flag. To create a CPU allocation that + doesn't target any specific NUMA nodes, applications must set + ``CUmemAllocationProp.CUmemLocation.type`` to + ``CU_MEM_LOCATION_TYPE_HOST``. ``CUmemAllocationProp``::CUmemLocation::id + is ignored for HOST allocations. HOST allocations are not IPC capable and + ``CUmemAllocationProp.requestedHandleTypes`` must be 0, any other value + will result in ``CUDA_ERROR_INVALID_VALUE``. To create a CPU allocation + targeting a specific host NUMA node, applications must set + ``CUmemAllocationProp.CUmemLocation.type`` to + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` and + ``CUmemAllocationProp``::CUmemLocation::id must specify the NUMA ID of the + CPU. On systems where NUMA is not available + ``CUmemAllocationProp``::CUmemLocation::id must be set to 0. Specifying + ``CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT`` as the ``CUmemLocation.type`` + will result in ``CUDA_ERROR_INVALID_VALUE``. + + Applications that intend to use ``CU_MEM_HANDLE_TYPE_FABRIC`` 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 0``. + + If ``CUmemAllocationProp.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 ``cuMemMapArrayAsync``). + + Args: + size (size_t): Size of the allocation requested. + prop (intptr_t): Properties of the allocation to create. + flags (unsigned long long): flags for future use, must be zero + now. + + Returns: + unsigned long long: Value of handle returned. All operations + on this allocation are to be performed using this handle. + + .. seealso:: `cuMemCreate` + """ + cdef intptr_t _prop_ptr_ = int(prop) + cdef CUmemGenericAllocationHandle handle + with nogil: + __status__ = cuMemCreate(&handle, size, _prop_ptr_, flags) + check_status(__status__) + return handle + + +cpdef mem_release(unsigned long long handle): + """Release a memory handle representing a memory allocation which was previously allocated through cuMemCreate. + + Frees the memory that was allocated on a device through cuMemCreate. + + 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 ``cuMemRelease`` for the handle to be freed. If + ``handle`` is not a valid handle the behavior is undefined. + + Args: + handle (unsigned long long): Value of handle which was + returned previously by cuMemCreate. + + .. seealso:: `cuMemRelease` + """ + with nogil: + __status__ = cuMemRelease(handle) + check_status(__status__) + + +cpdef mem_map(unsigned long long ptr, size_t size, size_t offset, unsigned long long handle, unsigned long long flags): + """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 + ``cuMemAddressReserve``, 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 ``cuMemGetAllocationGranularity`` with + the ``CU_MEM_ALLOC_GRANULARITY_MINIMUM`` flag. If ``handle`` represents a + multicast object, ``ptr``, ``size`` and ``offset`` must be aligned to the + value returned by ``cuMulticastGetGranularity`` 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 ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_RECOMMENDED_GRANULARITY``. + + When ``handle`` represents a multicast object, this call may return + CUDA_ERROR_ILLEGAL_STATE 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 ``cuMemMap`` does not make the address accessible, the + caller needs to update accessibility of a contiguous mapped VA range by + calling ``cuMemSetAccess``. + + Once a recipient process obtains a shareable memory handle from + ``cuMemImportFromShareableHandle``, the process must use ``cuMemMap`` to + map the memory into its address ranges before setting accessibility with + ``cuMemSetAccess``. + + ``cuMemMap`` can only create mappings on VA range reservations that are not + currently mapped. + + Args: + ptr (unsigned long long): Address where memory will be mapped. + size (size_t): Size of the memory mapping. + offset (size_t): Offset into the memory represented by. + handle (unsigned long long): Handle to a shareable memory. + flags (unsigned long long): flags for future use, must be zero + now. + + .. seealso:: `cuMemMap` + """ + with nogil: + __status__ = cuMemMap(ptr, size, offset, handle, flags) + check_status(__status__) + + +cpdef mem_map_array_async(map_info_list, unsigned int count, intptr_t h_stream): + """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 + ``CUarrayMapInfo`` entry in the ``map_info_list`` array of size ``count``. + The structure ``CUarrayMapInfo`` is defined as follow:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUarrayMapInfo.resourceType`` specifies the type of resource to be + operated on. If ``CUarrayMapInfo.resourceType`` is set to + ``CUresourcetype``::CU_RESOURCE_TYPE_ARRAY then + ``CUarrayMapInfo.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 ``cuArrayCreate`` or ``cuArray3DCreate`` + with the flag ``CUDA_ARRAY3D_SPARSE`` or ``CUDA_ARRAY3D_DEFERRED_MAPPING``. + For CUDA arrays obtained using ``cuMipmappedArrayGetLevel``, + ``CUDA_ERROR_INVALID_VALUE`` will be returned. If + ``CUarrayMapInfo.resourceType`` is set to + ``CUresourcetype``::CU_RESOURCE_TYPE_MIPMAPPED_ARRAY then + ``CUarrayMapInfo.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 + ``cuMipmappedArrayCreate`` with the flag ``CUDA_ARRAY3D_SPARSE`` or + ``CUDA_ARRAY3D_DEFERRED_MAPPING``. + + ``CUarrayMapInfo.subresourceType`` specifies the type of subresource within + the resource. ``CUarraySparseSubresourceType_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUarraySparseSubresourceType``::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SP + ARSE_LEVEL 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 + ``CUarraySparseSubresourceType``::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL + subresource type. + + If ``CUarrayMapInfo.subresourceType`` is set to ``CUarraySparseSubresourceT + ype``::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL then + ``CUarrayMapInfo.subresource.sparseLevel`` struct must contain valid array + subregion offsets and extents. The + ``CUarrayMapInfo.subresource.sparseLevel.offsetX``, + ``CUarrayMapInfo.subresource.sparseLevel.offsetY`` and + ``CUarrayMapInfo.subresource.sparseLevel.offsetZ`` must specify valid X, Y + and Z offsets respectively. The + ``CUarrayMapInfo.subresource.sparseLevel.extentWidth``, + ``CUarrayMapInfo.subresource.sparseLevel.extentHeight`` and + ``CUarrayMapInfo.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 ``CUarrayMapInfo.subresource.sparseLevel.level`` must specify a + valid mip level index. Otherwise, must be zero. For layered CUDA arrays and + layered CUDA mipmapped arrays + ``CUarrayMapInfo.subresource.sparseLevel.layer`` must specify a valid layer + index. Otherwise, must be zero. + ``CUarrayMapInfo.subresource.sparseLevel.offsetZ`` must be zero and + ``CUarrayMapInfo.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 ``cuArrayGetSparseProperties`` and + ``cuMipmappedArrayGetSparseProperties``. + + If ``CUarrayMapInfo.subresourceType`` is set to + ``CUarraySparseSubresourceType``::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL + then ``CUarrayMapInfo.subresource.miptail`` struct must contain valid mip + tail offset in ``CUarrayMapInfo.subresource.miptail.offset`` and size in + ``CUarrayMapInfo.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 + ``CUDA_ARRAY_SPARSE_PROPERTIES.flags`` as returned by + ``cuMipmappedArrayGetSparseProperties``, + ``CUarrayMapInfo.subresource.miptail.layer`` must specify a valid layer + index. Otherwise, must be zero. + + If ``CUarrayMapInfo.resource.array`` or ``CUarrayMapInfo.resource.mipmap`` + was created with ``CUDA_ARRAY3D_DEFERRED_MAPPING`` flag set the + ``CUarrayMapInfo.subresourceType`` and the contents of + ``CUarrayMapInfo.subresource`` will be ignored. + + ``CUarrayMapInfo.memOperationType`` specifies the type of operation. + ``CUmemOperationType`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``CUarrayMapInfo.memOperationType`` is set to + ``CUmemOperationType``::CU_MEM_OPERATION_TYPE_MAP then the subresource will + be mapped onto the tile pool memory specified by + ``CUarrayMapInfo.memHandle`` at offset ``CUarrayMapInfo.offset``. The tile + pool allocation has to be created by specifying the + ``CU_MEM_CREATE_USAGE_TILE_POOL`` flag when calling ``cuMemCreate``. Also, + ``CUarrayMapInfo.memHandleType`` must be set to + ``CUmemHandleType``::CU_MEM_HANDLE_TYPE_GENERIC. + + If ``CUarrayMapInfo.memOperationType`` is set to + ``CUmemOperationType``::CU_MEM_OPERATION_TYPE_UNMAP then an unmapping + operation is performed. ``CUarrayMapInfo.memHandle`` must be NULL. + + ``CUarrayMapInfo.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 ``CUarrayMapInfo.memOperationType`` is set to + ``CUmemOperationType``::CU_MEM_OPERATION_TYPE_MAP, the device must also + match the device associated with the tile pool memory allocation as + specified by ``CUarrayMapInfo.memHandle``. + + ``CUarrayMapInfo.flags`` and ``CUarrayMapInfo.reserved``[] are unused and + must be set to zero. + + Args: + map_info_list (intptr_t): List of ``CUarrayMapInfo``. + count (unsigned int): Count of ``CUarrayMapInfo`` in + ``map_info_list``. + h_stream (intptr_t): Stream identifier for the stream to use + for map or unmap operations. + + .. seealso:: `cuMemMapArrayAsync` + """ + cdef intptr_t _map_info_list_ptr_ = int(map_info_list) + with nogil: + __status__ = cuMemMapArrayAsync(_map_info_list_ptr_, count, h_stream) + check_status(__status__) + + +cpdef mem_unmap(unsigned long long ptr, size_t size): + """Unmap the backing memory of a given address range. + + The range must be the entire contiguous address range that was mapped to. + In other words, ``cuMemUnmap`` cannot unmap a sub-range of an address range + mapped by ``cuMemCreate`` / ``cuMemMap``. Any backing memory allocations + will be freed if there are no existing mappings and there are no unreleased + memory handles. + + When ``cuMemUnmap`` returns successfully the address range is converted to + an address reservation and can be used for a future calls to ``cuMemMap``. + Any new mapping to this virtual address will need to have access granted + through ``cuMemSetAccess``, as all mappings start with no accessibility + setup. + + Args: + ptr (unsigned long long): Starting address for the virtual + address range to unmap. + size (size_t): Size of the virtual address range to unmap. + + .. seealso:: `cuMemUnmap` + """ + with nogil: + __status__ = cuMemUnmap(ptr, size) + check_status(__status__) + + +cpdef mem_set_access(unsigned long long ptr, size_t size, desc, size_t count): + """Set 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 ``cuMemMap`` / ``cuMemCreate``. Users cannot + specify ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` accessibility for allocations + created on with other location types. Note: When + ``CUmemAccessDesc``::CUmemLocation::type is + ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, ``CUmemAccessDesc``::CUmemLocation::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 ``cuMulticastGetGranularity`` 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 + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_RECOMMENDED_GRANULARITY``. + + Args: + ptr (unsigned long long): Starting address for the virtual + address range. + size (size_t): Length of the virtual address range. + desc (intptr_t): Array of ``CUmemAccessDesc`` that describe + how to change the. + count (size_t): Number of ``CUmemAccessDesc`` in ``desc``. + + .. seealso:: `cuMemSetAccess` + """ + cdef intptr_t _desc_ptr_ = int(desc) + with nogil: + __status__ = cuMemSetAccess(ptr, size, _desc_ptr_, count) + check_status(__status__) + + +cpdef unsigned long long mem_get_access(location, unsigned long long ptr) except? 0: + """Get the access ``flags`` set for the given ``location`` and ``ptr``. + + Args: + location (intptr_t): Location in which to check the flags for. + ptr (unsigned long long): Address in which to check the access + flags for. + + Returns: + unsigned long long: Flags set for this location. + + .. seealso:: `cuMemGetAccess` + """ + cdef intptr_t _location_ptr_ = int(location) + cdef unsigned long long flags + with nogil: + __status__ = cuMemGetAccess(&flags, _location_ptr_, ptr) + check_status(__status__) + return flags + + +cpdef mem_export_to_shareable_handle(intptr_t shareable_handle, unsigned long long handle, int handle_type, unsigned long long flags): + """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 ``cuMemImportFromShareableHandle`` and map it with ``cuMemMap``. The + implementation of what this handle is and how it can be transferred is + defined by the requested handle type in ``handle_type``. + + 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. + + Args: + shareable_handle (intptr_t): Pointer to the location in which + to store the requested handle type. + handle (unsigned long long): CUDA handle for the memory + allocation. + handle_type (MemAllocationHandleType): Type of shareable + handle requested (defines type and size of the + ``shareable_handle`` output parameter). + flags (unsigned long long): Reserved, must be zero. + + .. seealso:: `cuMemExportToShareableHandle` + """ + with nogil: + __status__ = cuMemExportToShareableHandle(shareable_handle, handle, handle_type, flags) + check_status(__status__) + + +cpdef unsigned long long mem_import_from_shareable_handle(intptr_t os_handle, int sh_handle_type) except? 0: + """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 ``CUDA_ERROR_NOT_SUPPORTED``. + + If ``sh_handle_type`` is ``CU_MEM_HANDLE_TYPE_FABRIC`` and the importer + process has not been granted access to the same IMEX channel as the + exporter process, this API will error as ``CUDA_ERROR_NOT_PERMITTED``. + + Args: + os_handle (intptr_t): Shareable Handle representing the memory + allocation that is to be imported. + sh_handle_type (MemAllocationHandleType): handle type of the + exported handle ``CUmemAllocationHandleType``. + + Returns: + unsigned long long: CUDA Memory handle for the memory + allocation. + + .. 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 CUDA_ERROR_NOT_SUPPORTED. + 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. + + .. seealso:: `cuMemImportFromShareableHandle` + """ + cdef CUmemGenericAllocationHandle handle + with nogil: + __status__ = cuMemImportFromShareableHandle(&handle, os_handle, sh_handle_type) + check_status(__status__) + return handle + + +cpdef size_t mem_get_allocation_granularity(prop, int option) except? 0: + """Calculates either the minimal or recommended granularity. + + Calculates either the minimal or recommended granularity for a given + allocation specification and returns it in granularity. This granularity + can be used as a multiple for alignment, size, or address mapping. + + Args: + prop (intptr_t): Property for which to determine the + granularity for. + option (MemAllocationGranularityFlags): Determines which + granularity to return. + + Returns: + size_t: Returned granularity. + + .. seealso:: `cuMemGetAllocationGranularity` + """ + cdef intptr_t _prop_ptr_ = int(prop) + cdef size_t granularity + with nogil: + __status__ = cuMemGetAllocationGranularity(&granularity, _prop_ptr_, option) + check_status(__status__) + return granularity + + +cpdef mem_get_allocation_properties_from_handle(prop, unsigned long long handle): + """Retrieve the contents of the property structure defining properties for this handle. + + Args: + prop (intptr_t): Pointer to a properties structure which will + hold the information about this handle. + handle (unsigned long long): Handle which to perform the query + on. + + .. seealso:: `cuMemGetAllocationPropertiesFromHandle` + """ + cdef intptr_t _prop_ptr_ = int(prop) + with nogil: + __status__ = cuMemGetAllocationPropertiesFromHandle(_prop_ptr_, handle) + check_status(__status__) + + +cpdef unsigned long long mem_retain_allocation_handle(intptr_t addr) except? 0: + """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 + ``cuMemRelease``. + + Args: + addr (intptr_t): Memory address to query, that has been mapped + previously. + + Returns: + unsigned long long: CUDA Memory handle for the backing memory + allocation. + + .. note:: + The address ``addr``, can be any address in a range previously mapped + by ``cuMemMap``, and not necessarily the start address. + + .. seealso:: `cuMemRetainAllocationHandle` + """ + cdef CUmemGenericAllocationHandle handle + with nogil: + __status__ = cuMemRetainAllocationHandle(&handle, addr) + check_status(__status__) + return handle + + +cpdef mem_free_async(unsigned long long dptr, intptr_t h_stream): + """Frees memory with stream ordered semantics. + + Inserts a free operation into ``h_stream``. 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. + + Args: + dptr (unsigned long long): memory to free. + h_stream (intptr_t): The stream establishing the stream + ordering contract. + + .. 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. + + .. seealso:: `cuMemFreeAsync` + """ + with nogil: + __status__ = cuMemFreeAsync(dptr, h_stream) + check_status(__status__) + + +cpdef unsigned long long mem_alloc_async(size_t bytesize, intptr_t h_stream) except? 0: + """Allocates memory with stream ordered semantics. + + Inserts an allocation operation into ``h_stream``. A pointer to the + allocated memory is returned immediately in *dptr. The allocation must not + be accessed until the the allocation operation completes. The allocation + comes from the memory pool current to the stream's device. + + Args: + bytesize (size_t): Number of bytes to allocate. + h_stream (intptr_t): The stream establishing the stream + ordering contract and the memory pool to allocate from. + + Returns: + unsigned long long: Returned device pointer. + + .. 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. + + .. seealso:: `cuMemAllocAsync` + """ + cdef CUdeviceptr dptr + with nogil: + __status__ = cuMemAllocAsync(&dptr, bytesize, h_stream) + check_status(__status__) + return dptr + + +cpdef mem_pool_trim_to(intptr_t pool, size_t min_bytes_to_keep): + """Tries to release memory back to the OS. + + Releases memory back to the OS until the pool contains fewer than + min_bytes_to_keep 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. + + Args: + pool (intptr_t): The memory pool to trim. + min_bytes_to_keep (size_t): If the pool has less than + min_bytes_to_keep reserved, the TrimTo operation is a no- + op. Otherwise the pool will be guaranteed to have at least + min_bytes_to_keep bytes reserved after the operation. + + .. 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. + + .. seealso:: `cuMemPoolTrimTo` + """ + with nogil: + __status__ = cuMemPoolTrimTo(pool, min_bytes_to_keep) + check_status(__status__) + + +cpdef mem_pool_set_attribute(intptr_t pool, int attr, intptr_t value): + """Sets attributes of a memory pool. + + Supported attributes are:. + + - ``CU_MEMPOOL_ATTR_RELEASE_THRESHOLD``: (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). + + - ``CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES``: (value type = int) + Allow ``cuMemAllocAsync`` 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). + + - ``CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC``: (value type = int) Allow + reuse of already completed frees when there is no dependency between the + free and allocation. (default enabled). + + - ``CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES``: (value type = int) + Allow ``cuMemAllocAsync`` to insert new stream dependencies in order to + establish the stream ordering required to reuse a piece of memory released + by ``cuMemFreeAsync`` (default enabled). + + - ``CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH``: (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. + + - ``CU_MEMPOOL_ATTR_USED_MEM_HIGH``: (value type = ``cuuint64_t``) Reset + the high watermark that tracks the amount of used memory that was allocated + for the memory pool. + + Args: + pool (intptr_t): The memory pool to modify. + attr (MemPoolAttribute): The attribute to modify. + value (intptr_t): Pointer to the value to assign. + + .. seealso:: `cuMemPoolSetAttribute` + """ + with nogil: + __status__ = cuMemPoolSetAttribute(pool, attr, value) + check_status(__status__) + + +cpdef mem_pool_get_attribute(intptr_t pool, int attr, intptr_t value): + """Gets attributes of a memory pool. + + Supported attributes are:. + + - ``CU_MEMPOOL_ATTR_RELEASE_THRESHOLD``: (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). + + - ``CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES``: (value type = int) + Allow ``cuMemAllocAsync`` 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). + + - ``CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC``: (value type = int) Allow + reuse of already completed frees when there is no dependency between the + free and allocation. (default enabled). + + - ``CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES``: (value type = int) + Allow ``cuMemAllocAsync`` to insert new stream dependencies in order to + establish the stream ordering required to reuse a piece of memory released + by ``cuMemFreeAsync`` (default enabled). + + - ``CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT``: (value type = ``cuuint64_t``) + Amount of backing memory currently allocated for the mempool. + + - ``CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH``: (value type = ``cuuint64_t``) High + watermark of backing memory allocated for the mempool since the last time + it was reset. + + - ``CU_MEMPOOL_ATTR_USED_MEM_CURRENT``: (value type = ``cuuint64_t``) + Amount of memory from the pool that is currently in use by the application. + + - ``CU_MEMPOOL_ATTR_USED_MEM_HIGH``: (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:. + + - ``CU_MEMPOOL_ATTR_ALLOCATION_TYPE``: (value type = + ``CUmemAllocationType``) The allocation type of the mempool. + + - ``CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES``: (value type = + ``CUmemAllocationHandleType``) Available export handle types for the + mempool. For imported pools this value is always CU_MEM_HANDLE_TYPE_NONE as + an imported pool cannot be re-exported. + + - ``CU_MEMPOOL_ATTR_LOCATION_ID``: (value type = int) The location id for + the mempool. If the location type for this pool is + CU_MEM_LOCATION_TYPE_INVISIBLE then ID will be CU_DEVICE_INVALID. + + - ``CU_MEMPOOL_ATTR_LOCATION_TYPE``: (value type = ``CUmemLocationType``) + The location type for the mempool. For imported memory pools where the + device is not directly visible to the importing process or pools imported + via fabric handles across nodes this will be + CU_MEM_LOCATION_TYPE_INVISIBLE. + + - ``CU_MEMPOOL_ATTR_MAX_POOL_SIZE``: (value type = ``cuuint64_t``) Maximum + size of the pool in bytes, this value may be higher than what was initially + passed to cuMemPoolCreate due to alignment requirements. A value of 0 + indicates no maximum size. For CU__MEM_ALLOCATION_TYPE_MANAGED and IPC + imported pools this value will be system dependent. + + - ``CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED``: (value type = int) Indicates + whether the pool has hardware compresssion enabled. + + Args: + pool (intptr_t): The memory pool to get attributes of. + attr (MemPoolAttribute): The attribute to get. + value (intptr_t): Retrieved value. + + .. seealso:: `cuMemPoolGetAttribute` + """ + with nogil: + __status__ = cuMemPoolGetAttribute(pool, attr, value) + check_status(__status__) + + +cpdef mem_pool_set_access(intptr_t pool, map, size_t count): + """Controls visibility of pools between devices. + + Args: + pool (intptr_t): The pool being modified. + map (intptr_t): Array of access descriptors. Each descriptor + instructs the access to enable for a single gpu. + count (size_t): Number of descriptors in the map array. + + .. seealso:: `cuMemPoolSetAccess` + """ + cdef intptr_t _map_ptr_ = int(map) + with nogil: + __status__ = cuMemPoolSetAccess(pool, _map_ptr_, count) + check_status(__status__) + + +cpdef int mem_pool_get_access(intptr_t mem_pool, location) except? 0: + """Returns the accessibility of a pool from a device. + + Returns the accessibility of the pool's memory from the specified location. + + Args: + mem_pool (intptr_t): the pool being queried. + location (intptr_t): the location accessing the pool. + + Returns: + int: the accessibility of the pool from the specified + location. + + .. seealso:: `cuMemPoolGetAccess` + """ + cdef intptr_t _location_ptr_ = int(location) + cdef CUmemAccess_flags flags + with nogil: + __status__ = cuMemPoolGetAccess(&flags, mem_pool, _location_ptr_) + check_status(__status__) + return flags + + +cpdef intptr_t mem_pool_create(pool_props) except? 0: + """Creates a memory pool. + + Creates a CUDA memory pool and returns the handle in ``pool``. The + ``pool_props`` 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 ``CUmemPoolProps``::CUmemLocation::type to + ``CU_MEM_LOCATION_TYPE_HOST``. ``CUmemPoolProps``::CUmemLocation::id is + ignored for such pools. Pools created with the type + ``CU_MEM_LOCATION_TYPE_HOST`` are not IPC capable and + ``CUmemPoolProps.handleTypes`` must be 0, any other values will result in + ``CUDA_ERROR_INVALID_VALUE``. To create a memory pool targeting a specific + host NUMA node, applications must set + ``CUmemPoolProps``::CUmemLocation::type to + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` and + ``CUmemPoolProps``::CUmemLocation::id must specify the NUMA ID of the host + memory node. Specifying ``CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT`` as the + ``CUmemPoolProps``::CUmemLocation::type will result in + ``CUDA_ERROR_INVALID_VALUE``. + + By default, the pool's memory will be accessible from the device it is + allocated on. In the case of pools created with + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` or ``CU_MEM_LOCATION_TYPE_HOST``, 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 + ``CUmemPoolProps.maxSize``. If set to 0, the maximum size of the pool will + default to a system dependent value. + + Applications that intend to use ``CU_MEM_HANDLE_TYPE_FABRIC`` 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 0``. + + To create a managed memory pool, applications must set + ``CUmemPoolProps``::CUmemAllocationType to CU_MEM_ALLOCATION_TYPE_MANAGED. + ``CUmemPoolProps``::CUmemAllocationHandleType must also be set to + CU_MEM_HANDLE_TYPE_NONE since IPC is not supported. For managed memory + pools, ``CUmemPoolProps``::CUmemLocation will be treated as the preferred + location for all allocations created from the pool. An application can also + set CU_MEM_LOCATION_TYPE_NONE to indicate no preferred location. + ``CUmemPoolProps.maxSize`` must be set to zero for managed memory pools. + ``CUmemPoolProps.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 + CUDA_ERROR_NOT_SUPPORTED. + + Args: + pool_props (intptr_t): Memory pool properties. + + Returns: + intptr_t: Returned memory pool. + + .. note:: + Specifying CU_MEM_HANDLE_TYPE_NONE creates a memory pool that will not + support IPC. + + .. seealso:: `cuMemPoolCreate` + """ + cdef intptr_t _pool_props_ptr_ = int(pool_props) + cdef CUmemoryPool pool + with nogil: + __status__ = cuMemPoolCreate(&pool, _pool_props_ptr_) + check_status(__status__) + return pool + + +cpdef mem_pool_destroy(intptr_t pool): + """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 ``cuMemPoolDestroy`` 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. + + Args: + pool (intptr_t): Memory pool to destroy. + + .. note:: + A device's default memory pool cannot be destroyed. + + .. seealso:: `cuMemPoolDestroy` + """ + with nogil: + __status__ = cuMemPoolDestroy(pool) + check_status(__status__) + + +cpdef unsigned long long mem_alloc_from_pool_async(size_t bytesize, intptr_t pool, intptr_t h_stream) except? 0: + """Allocates memory from a specified pool with stream ordered semantics. + + Inserts an allocation operation into ``h_stream``. A pointer to the + allocated memory is returned immediately in *dptr. The allocation must not + be accessed until the the allocation operation completes. The allocation + comes from the specified memory pool. + + Args: + bytesize (size_t): Number of bytes to allocate. + pool (intptr_t): The pool to allocate from. + h_stream (intptr_t): The stream establishing the stream + ordering semantic. + + Returns: + unsigned long long: Returned device pointer. + + .. 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. + + .. seealso:: `cuMemAllocFromPoolAsync` + """ + cdef CUdeviceptr dptr + with nogil: + __status__ = cuMemAllocFromPoolAsync(&dptr, bytesize, pool, h_stream) + check_status(__status__) + return dptr + + +cpdef mem_pool_export_to_shareable_handle(intptr_t handle_out, intptr_t pool, int handle_type, unsigned long long flags): + """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 ``cuMemPoolImportFromShareableHandle``. Individual pointers + can then be shared with the ``cuMemPoolExportPointer`` and + ``cuMemPoolImportPointer`` APIs. The implementation of what the shareable + handle is and how it can be transferred is defined by the requested handle + type. + + Args: + handle_out (intptr_t): Returned OS handle. + pool (intptr_t): pool to export. + handle_type (MemAllocationHandleType): the type of handle to + create. + flags (unsigned long long): must be 0. + + .. note:: + : To create an IPC capable mempool, create a mempool with a + ``CUmemAllocationHandleType`` other than CU_MEM_HANDLE_TYPE_NONE. + + .. seealso:: `cuMemPoolExportToShareableHandle` + """ + with nogil: + __status__ = cuMemPoolExportToShareableHandle(handle_out, pool, handle_type, flags) + check_status(__status__) + + +cpdef intptr_t mem_pool_import_from_shareable_handle(intptr_t handle, int handle_type, unsigned long long flags) except? 0: + """imports a memory pool from a shared handle. + + Specific allocations can be imported from the imported pool with + cuMemPoolImportPointer. + + If ``handle_type`` is ``CU_MEM_HANDLE_TYPE_FABRIC`` and the importer + process has not been granted access to the same IMEX channel as the + exporter process, this API will error as ``CUDA_ERROR_NOT_PERMITTED``. + + Args: + handle (intptr_t): OS handle of the pool to open. + handle_type (MemAllocationHandleType): The type of handle + being imported. + flags (unsigned long long): must be 0. + + Returns: + intptr_t: Returned memory pool. + + .. note:: + Imported memory pools do not support creating new allocations. As such + imported memory pools may not be used in cuDeviceSetMemPool or + ``cuMemAllocFromPoolAsync`` calls. + + .. seealso:: `cuMemPoolImportFromShareableHandle` + """ + cdef CUmemoryPool pool_out + with nogil: + __status__ = cuMemPoolImportFromShareableHandle(&pool_out, handle, handle_type, flags) + check_status(__status__) + return pool_out + + +cpdef object mem_pool_export_pointer(unsigned long long ptr): + """Export data to share a memory pool allocation between processes. + + Constructs ``share_data_out`` for sharing a specific allocation from an + already shared memory pool. The recipient process can import the allocation + with the ``cuMemPoolImportPointer`` api. The data is not a handle and may + be shared through any IPC mechanism. + + Args: + ptr (unsigned long long): pointer to memory being exported. + + Returns: + CUmemPoolPtrExportData_v1: Returned export data. + + .. seealso:: `cuMemPoolExportPointer` + """ + cdef MemPoolPtrExportData_v1 share_data_out_py = MemPoolPtrExportData_v1() + cdef CUmemPoolPtrExportData *share_data_out = (share_data_out_py._get_ptr()) + with nogil: + __status__ = cuMemPoolExportPointer(share_data_out, ptr) + check_status(__status__) + return share_data_out_py + + +cpdef unsigned long long mem_pool_import_pointer(intptr_t pool, share_data) except? 0: + """Import a memory pool allocation from another process. + + Returns in ``ptr_out`` 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 cuMemFree or cuMemFreeAsync. If cuMemFreeAsync is used, the free + must be completed on the importing process before the free operation on the + exporting process. + + Args: + pool (intptr_t): pool from which to import. + share_data (intptr_t): data specifying the memory to import. + + Returns: + unsigned long long: pointer to imported memory. + + .. note:: + The cuMemFreeAsync api may be used in the exporting process before the + cuMemFreeAsync operation completes in its stream as long as the + cuMemFreeAsync in the exporting process specifies a stream with a + stream dependency on the importing process's cuMemFreeAsync. + + .. seealso:: `cuMemPoolImportPointer` + """ + cdef intptr_t _share_data_ptr_ = int(share_data) + cdef CUdeviceptr ptr_out + with nogil: + __status__ = cuMemPoolImportPointer(&ptr_out, pool, _share_data_ptr_) + check_status(__status__) + return ptr_out + + +cpdef unsigned long long multicast_create(prop) except? 0: + """Create 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 ``CUmulticastObjectProp.numDevices``. + Devices can be added to the multicast object via ``cuMulticastAddDevice``. + 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 + ``cuMulticastBindMem``, ``cuMulticastBindMem_v2``, ``cuMulticastBindAddr``, + or ``cuMulticastBindAddr_v2``. and can be unbound via + ``cuMulticastUnbind``. The total amount of memory that can be bound per + device is specified by ``CUmulticastObjectProp.size``. This size must be a + multiple of the value returned by ``cuMulticastGetGranularity`` with the + flag ``CU_MULTICAST_GRANULARITY_MINIMUM``. For best performance however, + the size should be aligned to the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. + + 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 ``cuMemMap`` and ``cuMemSetAccess``). Multicast + objects can also be shared with other processes by requesting a shareable + handle via ``cuMemExportToShareableHandle``. Note that the desired types of + shareable handles must be specified in the bitmask + ``CUmulticastObjectProp.handleTypes``. Multicast objects can be released + using the virtual memory management API ``cuMemRelease``. + + Args: + prop (intptr_t): Properties of the multicast object to create. + + Returns: + unsigned long long: Value of handle returned. + + .. seealso:: `cuMulticastCreate` + """ + cdef intptr_t _prop_ptr_ = int(prop) + cdef CUmemGenericAllocationHandle mc_handle + with nogil: + __status__ = cuMulticastCreate(&mc_handle, _prop_ptr_) + check_status(__status__) + return mc_handle + + +cpdef multicast_add_device(unsigned long long mc_handle, int dev): + """Associate 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 + ``CUmulticastObjectProp.numDevices`` during ``cuMulticastCreate``. 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 ``cuMulticastBindMem``, ``cuMulticastBindMem_v2``, + ``cuMulticastBindAddr``, or ``cuMulticastBindAddr_v2`` 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 ``cuMemMap`` will block until all devices have + been added. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + dev (int): Device that will be associated to the multicast + object. + + .. seealso:: `cuMulticastAddDevice` + """ + with nogil: + __status__ = cuMulticastAddDevice(mc_handle, dev) + check_status(__status__) + + +cpdef multicast_bind_mem(unsigned long long mc_handle, size_t mc_offset, unsigned long long mem_handle, size_t mem_offset, size_t size, unsigned long long flags): + """Bind a memory allocation represented by a handle to a multicast object. + + Binds a memory allocation specified by ``mem_handle`` and created via + ``cuMemCreate`` to a multicast object represented by ``mc_handle`` and + created via ``cuMulticastCreate``. The intended ``size`` of the bind, the + offset in the multicast range ``mc_offset`` as well as the offset in the + memory ``mem_offset`` must be a multiple of the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. For best performance however, + ``size``, ``mc_offset`` and ``mem_offset`` should be aligned to the + granularity of the memory allocation(see ``cuMemGetAllocationGranularity``) + or to the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. + + The ``size`` + ``mem_offset`` cannot be larger than the size of the + allocated memory. Similarly the ``size`` + ``mc_offset`` cannot be larger + than the size of the multicast object. + + The memory allocation must have beeen created on one of the devices that + was added to the multicast team via ``cuMulticastAddDevice``. Externally + shareable as well as imported multicast objects can be bound only to + externally shareable memory. Note that this call will return + CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to + perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if + the necessary system software is not initialized or running. + + This call may return CUDA_ERROR_ILLEGAL_STATE 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. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + mc_offset (size_t): Offset into the multicast object for + attachment. + mem_handle (unsigned long long): Handle representing a memory + allocation. + mem_offset (size_t): Offset into the memory for attachment. + size (size_t): Size of the memory that will be bound to the + multicast object. + flags (unsigned long long): Flags for future use, must be zero + for now. + + .. seealso:: `cuMulticastBindMem` + """ + with nogil: + __status__ = cuMulticastBindMem(mc_handle, mc_offset, mem_handle, mem_offset, size, flags) + check_status(__status__) + + +cpdef multicast_bind_addr(unsigned long long mc_handle, size_t mc_offset, unsigned long long memptr, size_t size, unsigned long long flags): + """Bind 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 ``mc_handle``. The memory must have been + allocated via ``cuMemCreate`` or ``cudaMallocAsync``. The intended ``size`` + of the bind, the offset in the multicast range ``mc_offset`` and ``memptr`` + must be a multiple of the value returned by ``cuMulticastGetGranularity`` + with the flag ``CU_MULTICAST_GRANULARITY_MINIMUM``. For best performance + however, ``size``, ``mc_offset`` and ``memptr`` should be aligned to the + value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. + + The ``size`` cannot be larger than the size of the allocated memory. + Similarly the ``size`` + ``mc_offset`` cannot be larger than the total size + of the multicast object. + + The memory allocation must have beeen created on one of the devices that + was added to the multicast team via ``cuMulticastAddDevice``. Externally + shareable as well as imported multicast objects can be bound only to + externally shareable memory. Note that this call will return + CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to + perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if + the necessary system software is not initialized or running. + + This call may return CUDA_ERROR_ILLEGAL_STATE 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. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + mc_offset (size_t): Offset into multicast va range for + attachment. + memptr (unsigned long long): Virtual address of the memory + allocation. + size (size_t): Size of memory that will be bound to the + multicast object. + flags (unsigned long long): Flags for future use, must be zero + now. + + .. seealso:: `cuMulticastBindAddr` + """ + with nogil: + __status__ = cuMulticastBindAddr(mc_handle, mc_offset, memptr, size, flags) + check_status(__status__) + + +cpdef multicast_unbind(unsigned long long mc_handle, int dev, size_t mc_offset, size_t size): + """Unbind 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 ``mc_offset`` and upto a given ``size``. The intended ``size`` of + the unbind and the offset in the multicast range ( ``mc_offset`` ) must be + a multiple of the value returned by ``cuMulticastGetGranularity`` flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. The ``size`` + ``mc_offset`` cannot + be larger than the total size of the multicast object. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + dev (int): Device that hosts the memory allocation. + mc_offset (size_t): Offset into the multicast object. + size (size_t): Desired size to unbind. + + .. note:: + Warning: The ``mc_offset`` and the ``size`` must match the + corresponding values specified during the bind call. Any other values + may result in undefined behavior. + + .. seealso:: `cuMulticastUnbind` + """ + with nogil: + __status__ = cuMulticastUnbind(mc_handle, dev, mc_offset, size) + check_status(__status__) + + +cpdef size_t multicast_get_granularity(prop, int option) except? 0: + """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 in granularity. This granularity + can be used as a multiple for size, bind offsets and address mappings of + the multicast object. + + Args: + prop (intptr_t): Properties of the multicast object. + option (MulticastGranularityFlags): Determines which + granularity to return. + + Returns: + size_t: Returned granularity. + + .. seealso:: `cuMulticastGetGranularity` + """ + cdef intptr_t _prop_ptr_ = int(prop) + cdef size_t granularity + with nogil: + __status__ = cuMulticastGetGranularity(&granularity, _prop_ptr_, option) + check_status(__status__) + return granularity + + +cpdef pointer_get_attribute(intptr_t data, int attribute, unsigned long long ptr): + """Returns information about a pointer. + + The supported attributes are:. + + - ``CU_POINTER_ATTRIBUTE_CONTEXT``:. + + - Returns in ``*data`` the ``CUcontext`` in which ``ptr`` was allocated or + registered. The type of ``data`` must be ``CUcontext`` *. + + - If ``ptr`` was not allocated by, mapped by, or registered with a + ``CUcontext`` which uses unified virtual addressing then + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + - ``CU_POINTER_ATTRIBUTE_MEMORY_TYPE``:. + + - Returns in ``*data`` the physical memory type of the memory that ``ptr`` + addresses as a ``CUmemorytype`` enumerated value. The type of ``data`` must + be unsigned int. + + - If ``ptr`` addresses device memory then ``*data`` is set to + ``CU_MEMORYTYPE_DEVICE``. The particular ``CUdevice`` on which the memory + resides is the ``CUdevice`` of the ``CUcontext`` returned by the + ``CU_POINTER_ATTRIBUTE_CONTEXT`` attribute of ``ptr``. + + - If ``ptr`` addresses host memory then ``*data`` is set to + ``CU_MEMORYTYPE_HOST``. + + - If ``ptr`` was not allocated by, mapped by, or registered with a + ``CUcontext`` which uses unified virtual addressing then + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + - If the current ``CUcontext`` does not support unified virtual addressing + then ``CUDA_ERROR_INVALID_CONTEXT`` is returned. + + - ``CU_POINTER_ATTRIBUTE_DEVICE_POINTER``:. + + - Returns in ``*data`` the device pointer value through which ``ptr`` may + be accessed by kernels running in the current ``CUcontext``. The type of + ``data`` must be ``CUdeviceptr`` *. + + - If there exists no device pointer value through which kernels running in + the current ``CUcontext`` may access ``ptr`` then + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + - If there is no current ``CUcontext`` then ``CUDA_ERROR_INVALID_CONTEXT`` + is returned. + + - Except in the exceptional disjoint addressing cases discussed below, the + value returned in ``*data`` will equal the input value ``ptr``. + + - ``CU_POINTER_ATTRIBUTE_HOST_POINTER``:. + + - 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 ``CUDA_ERROR_INVALID_VALUE`` is returned. + + - Except in the exceptional disjoint addressing cases discussed below, the + value returned in ``*data`` will equal the input value ``ptr``. + + - ``CU_POINTER_ATTRIBUTE_P2P_TOKENS``:. + + - Returns in ``*data`` two tokens for use with the nv-p2p.h Linux kernel + interface. ``data`` must be a struct of type + ``CUDA_POINTER_ATTRIBUTE_P2P_TOKENS``. + + - ``ptr`` must be a pointer to memory obtained from ``cuMemAlloc()``. 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 ``CU_POINTER_ATTRIBUTE_SYNC_MEMOPS`` for the region + of memory that ``ptr`` points to. + + - ``CU_POINTER_ATTRIBUTE_SYNC_MEMOPS``:. + + - 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. + + - ``CU_POINTER_ATTRIBUTE_BUFFER_ID``:. + + - 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. + + - ``CU_POINTER_ATTRIBUTE_IS_MANAGED``:. + + - 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 ``CUDA_ERROR_INVALID_VALUE`` + is returned. + + - ``CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL``:. + + - Returns in ``*data`` an integer representing a device ordinal of a device + against which the memory was allocated or registered. + + - ``CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE``:. + + - Returns in ``*data`` a boolean that indicates if this pointer maps to an + allocation that is suitable for ``cudaIpcGetMemHandle``. + + - ``CU_POINTER_ATTRIBUTE_RANGE_START_ADDR``:. + + - 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 ``cuMemAddressReserve``). + + - ``CU_POINTER_ATTRIBUTE_RANGE_SIZE``:. + + - 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 ``cuMemAddressReserve``). To retrieve the size of the mapped region, + see ``cuMemGetAddressRange``. + + - ``CU_POINTER_ATTRIBUTE_MAPPED``:. + + - Returns in ``*data`` a boolean that indicates if this pointer is in a + valid address range that is mapped to a backing allocation. + + - ``CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES``:. + + - Returns a bitmask of the allowed handle types for an allocation that may + be passed to ``cuMemExportToShareableHandle``. + + - ``CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE``:. + + - Returns in ``*data`` the handle to the mempool that the allocation was + obtained from. + + - ``CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE``:. + + - Returns in ``*data`` a boolean that indicates whether the pointer points + to memory that is capable to be used for hardware accelerated + decompression. + + 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 ``cuMemHostRegister``. + + - host memory allocated using ``cuMemHostAlloc`` 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 ``CU_POINTER_ATTRIBUTE_HOST_POINTER`` and + ``CU_POINTER_ATTRIBUTE_DEVICE_POINTER`` may be used to retrieve the host + and device addresses from either address. + + Args: + data (intptr_t): Returned pointer attribute value. + attribute (PointerAttribute): Pointer attribute to query. + ptr (unsigned long long): Pointer. + + .. seealso:: `cuPointerGetAttribute` + """ + with nogil: + __status__ = cuPointerGetAttribute(data, attribute, ptr) + check_status(__status__) + + +cpdef mem_prefetch_async_v2(unsigned long long dev_ptr, size_t count, location, unsigned int flags, intptr_t h_stream): + """Prefetches memory to the specified destination location. + + Prefetches memory to the specified destination location. ``dev_ptr`` 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. ``h_stream`` is the stream in which the operation is enqueued. The + memory range must refer to managed memory allocated via + ``cuMemAllocManaged``, via ``cuMemAllocFromPool`` from a managed memory + pool or declared via managed variables. + + Specifying ``CU_MEM_LOCATION_TYPE_DEVICE`` for ``CUmemLocation.type`` will + prefetch memory to GPU specified by device ordinal ``CUmemLocation.id`` + which must have non-zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. Additionally, + ``h_stream`` must be associated with a device that has a non-zero value for + the device attribute ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. + Specifying ``CU_MEM_LOCATION_TYPE_HOST`` as ``CUmemLocation.type`` will + prefetch data to host memory. Applications can request prefetching memory + to a specific host NUMA node by specifying + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` for ``CUmemLocation.type`` and a valid + host NUMA node id in ``CUmemLocation.id`` Users can also request + prefetching memory to the host NUMA node closest to the current thread's + CPU by specifying ``CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT`` for + ``CUmemLocation.type``. Note when ``CUmemLocation.type`` is etiher + ``CU_MEM_LOCATION_TYPE_HOST`` OR + ``CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT``, ``CUmemLocation.id`` will be + ignored. + + 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 ``cuMemAllocManaged`` allocations to host + memory in order to make room. Device memory allocated using ``cuMemAlloc`` + or ``cuArrayCreate`` 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 ``cuMemAdvise`` as described below:. + + If ``CU_MEM_ADVISE_SET_READ_MOSTLY`` 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 ``CU_MEM_ADVISE_SET_PREFERRED_LOCATION`` 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 ``CU_MEM_ADVISE_SET_ACCESSED_BY`` 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. + + Args: + dev_ptr (unsigned long long): Pointer to be prefetched. + count (size_t): Size in bytes. + location (int): Location to prefetch to. + flags (unsigned int): flags for future use, must be zero now. + h_stream (intptr_t): Stream to enqueue prefetch operation. + + .. seealso:: `cuMemPrefetchAsync_v2` + """ + cdef intptr_t _location_ptr_ = (location)._get_ptr() + with nogil: + __status__ = cuMemPrefetchAsync(dev_ptr, count, (_location_ptr_)[0], flags, h_stream) + check_status(__status__) + + +cpdef mem_advise_v2(unsigned long long dev_ptr, size_t count, int advice, location): + """Advise about the usage of a given memory range. + + Advise the Unified Memory subsystem about the usage pattern for the memory + range starting at ``dev_ptr`` 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 + ``cuMemAllocManaged`` 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:. + + - ``CU_MEM_ADVISE_SET_READ_MOSTLY``: 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 + ``cuMemPrefetchAsync`` is called on this region, it will create a read-only + copy of the data on the destination processor. If the target location for + ``cuMemPrefetchAsync`` 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 ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. Also, + if a context is created on a device that does not have the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` 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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS`` 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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES``, then + setting this advice will not create a read-only copy when that device + accesses this memory region. + + - ``CU_MEM_ADVISE_UNSET_READ_MOSTLY``: Undoes the effect of + ``CU_MEM_ADVISE_SET_READ_MOSTLY`` 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. + + - ``CU_MEM_ADVISE_SET_PREFERRED_LOCATION``: This advice sets the preferred + location for the data to be the memory belonging to ``location``. When + ``CUmemLocation.type`` is ``CU_MEM_LOCATION_TYPE_HOST``, + ``CUmemLocation.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 ``CUmemLocation.type`` to + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` and ``CUmemLocation.id`` must specify + the NUMA ID of the host NUMA node. If ``CUmemLocation.type`` is set to + ``CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT``, ``CUmemLocation.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 ``CUmemLocation.type`` is a + ``CU_MEM_LOCATION_TYPE_DEVICE``, then ``CUmemLocation.id`` must be a valid + device ordinal and the device must have a non-zero value for the device + attribute ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. 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 ``cuMemPrefetchAsync``. 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 ``CU_MEM_ADVISE_SET_READ_MOSTLY`` 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 + ``CU_MEM_ADVISE_SET_READ_MOSTLY``. If the memory region refers to valid + system-allocated pageable memory, and ``CUmemLocation.type`` is + CU_MEM_LOCATION_TYPE_DEVICE then ``CUmemLocation.id`` must be a valid + device that has a non-zero alue for the device attribute + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. + + - ``CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION``: Undoes the effect of + ``CU_MEM_ADVISE_SET_PREFERRED_LOCATION`` and changes the preferred location + to none. The ``location`` argument is ignored for this advice. + + - ``CU_MEM_ADVISE_SET_ACCESSED_BY``: This advice implies that the data will + be accessed by processor ``location``. The ``CUmemLocation.type`` must be + either ``CU_MEM_LOCATION_TYPE_DEVICE`` with ``CUmemLocation.id`` + representing a valid device ordinal or ``CU_MEM_LOCATION_TYPE_HOST`` and + ``CUmemLocation.id`` will be ignored. All other location types are invalid. + If ``CUmemLocation.id`` is a GPU, then the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` 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 ``CU_MEM_ADVISE_SET_ACCESSED_BY`` flag set for this data will now have + its mapping updated to point to the page in host memory. If + ``CU_MEM_ADVISE_SET_READ_MOSTLY`` 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 ``CU_MEM_ADVISE_SET_PREFERRED_LOCATION`` will + override the policies of this advice. If the memory region refers to valid + system-allocated pageable memory, and ``CUmemLocation.type`` is + ``CU_MEM_LOCATION_TYPE_DEVICE`` then device in ``CUmemLocation.id`` must + have a non-zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. Additionally, if + ``CUmemLocation.id`` has a non-zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES``, then + this call has no effect. + + - ``CU_MEM_ADVISE_UNSET_ACCESSED_BY``: Undoes the effect of + ``CU_MEM_ADVISE_SET_ACCESSED_BY``. 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 ``CUmemLocation.type`` is + ``CU_MEM_LOCATION_TYPE_DEVICE`` then device in ``CUmemLocation.id`` must + have a non-zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. Additionally, if + ``CUmemLocation.id`` has a non-zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES``, then + this call has no effect. + + Args: + dev_ptr (unsigned long long): Pointer to memory to set the + advice for. + count (size_t): Size in bytes of the memory range. + advice (MemAdvise): Advice to be applied for the specified + memory range. + location (int): location to apply the advice for. + + .. seealso:: `cuMemAdvise_v2` + """ + cdef intptr_t _location_ptr_ = (location)._get_ptr() + with nogil: + __status__ = cuMemAdvise(dev_ptr, count, advice, (_location_ptr_)[0]) + check_status(__status__) + + +cpdef mem_range_get_attribute(intptr_t data, size_t data_size, int attribute, unsigned long long dev_ptr, size_t count): + """Query an attribute of a given memory range. + + Query an attribute about the memory range starting at ``dev_ptr`` with a + size of ``count`` bytes. The memory range must refer to managed memory + allocated via ``cuMemAllocManaged`` or declared via managed variables. + + The ``attribute`` parameter can take the following values:. + + - ``CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY``: If this attribute is specified, + ``data`` will be interpreted as a 32-bit integer, and ``data_size`` must be + 4. The result returned will be 1 if all pages in the given memory range + have read-duplication enabled, or 0 otherwise. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION``: If this attribute is + specified, ``data`` will be interpreted as a 32-bit integer, and + ``data_size`` 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. + + - ``CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY``: If this attribute is specified, + ``data`` will be interpreted as an array of 32-bit integers, and + ``data_size`` must be a non-zero multiple of 4. The result returned will be + a list of device ids that had ``CU_MEM_ADVISE_SET_ACCESSED_BY`` 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 ``data_size`` 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. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION``: If this attribute is + specified, ``data`` will be interpreted as a 32-bit integer, and + ``data_size`` must be 4. The result returned will be the last location to + which all pages in the memory range were prefetched explicitly via + ``cuMemPrefetchAsync``. 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. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE``: If this attribute is + specified, ``data`` will be interpreted as a ``CUmemLocationType``, and + ``data_size`` must be sizeof(CUmemLocationType). The ``CUmemLocationType`` + returned will be ``CU_MEM_LOCATION_TYPE_DEVICE`` if all pages in the memory + range have the same GPU as their preferred location, or + ``CUmemLocationType`` will be ``CU_MEM_LOCATION_TYPE_HOST`` if all pages in + the memory range have the CPU as their preferred location, or it will be + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` if all the pages in the memory range + have the same host NUMA node ID as their preferred location or it will be + ``CU_MEM_LOCATION_TYPE_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 type of the pages in the + memory range at the time of the query may be different from the preferred + location type. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID``: If this attribute is + specified, ``data`` will be interpreted as a 32-bit integer, and + ``data_size`` must be 4. If the + ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE`` query for the same + address range returns ``CU_MEM_LOCATION_TYPE_DEVICE``, it will be a valid + device ordinal or if it returns ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, it will + be a valid host NUMA node ID or if it returns any other location type, the + id should be ignored. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE``: If this attribute + is specified, ``data`` will be interpreted as a ``CUmemLocationType``, and + ``data_size`` must be sizeof(CUmemLocationType). The result returned will + be the last location to which all pages in the memory range were prefetched + explicitly via ``cuMemPrefetchAsync``. The ``CUmemLocationType`` returned + will be ``CU_MEM_LOCATION_TYPE_DEVICE`` if the last prefetch location was a + GPU or ``CU_MEM_LOCATION_TYPE_HOST`` if it was the CPU or + ``CU_MEM_LOCATION_TYPE_HOST_NUMA`` 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, ``CUmemLocationType`` will be ``CU_MEM_LOCATION_TYPE_INVALID``. + 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. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID``: If this attribute + is specified, ``data`` will be interpreted as a 32-bit integer, and + ``data_size`` must be 4. If the + ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE`` query for the same + address range returns ``CU_MEM_LOCATION_TYPE_DEVICE``, it will be a valid + device ordinal or if it returns ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, it will + be a valid host NUMA node ID or if it returns any other location type, the + id should be ignored. + + Args: + data (intptr_t): A pointers to a memory location where the + result of each attribute query will be written to. + data_size (size_t): Array containing the size of data. + attribute (MemRangeAttribute): The attribute to query. + dev_ptr (unsigned long long): Start of the range to query. + count (size_t): Size of the range to query. + + .. seealso:: `cuMemRangeGetAttribute` + """ + with nogil: + __status__ = cuMemRangeGetAttribute(data, data_size, attribute, dev_ptr, count) + check_status(__status__) + + +cpdef mem_range_get_attributes(intptr_t data, intptr_t data_sizes, intptr_t attributes, size_t num_attributes, unsigned long long dev_ptr, size_t count): + """Query attributes of a given memory range. + + Query attributes of the memory range starting at ``dev_ptr`` with a size of + ``count`` bytes. The memory range must refer to managed memory allocated + via ``cuMemAllocManaged`` or declared via managed variables. The + ``attributes`` array will be interpreted to have ``num_attributes`` + entries. The ``data_sizes`` array will also be interpreted to have + ``num_attributes`` entries. The results of the query will be stored in + ``data``. + + The list of supported attributes are given below. Please refer to + ``cuMemRangeGetAttribute`` for attribute descriptions and restrictions. + + - ``CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY``. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION``. + + - ``CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY``. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION``. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE``. + + - ``CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID``. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE``. + + - ``CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID``. + + Args: + data (intptr_t): A two-dimensional array containing pointers + to memory locations where the result of each attribute + query will be written to. + data_sizes (intptr_t): Array containing the sizes of each + result. + attributes (intptr_t): An array of attributes to query + (num_attributes and the number of attributes in this array + should match). + num_attributes (size_t): Number of attributes to query. + dev_ptr (unsigned long long): Start of the range to query. + count (size_t): Size of the range to query. + + .. seealso:: `cuMemRangeGetAttributes` + """ + with nogil: + __status__ = cuMemRangeGetAttributes(data, data_sizes, attributes, num_attributes, dev_ptr, count) + check_status(__status__) + + +cpdef pointer_set_attribute(value, int attribute, unsigned long long ptr): + """Set attributes on a previously allocated memory region. + + The supported attributes are:. + + - ``CU_POINTER_ATTRIBUTE_SYNC_MEMOPS``:. + + - 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. + + Args: + value (bytes): Pointer to memory containing the value to be + set. + attribute (PointerAttribute): Pointer attribute to set. + ptr (unsigned long long): Pointer to a memory region allocated + using CUDA memory allocation APIs. + + .. seealso:: `cuPointerSetAttribute` + """ + cdef void* _value_ = _cyb_get_buffer_pointer(value, -1, readonly=True) + with nogil: + __status__ = cuPointerSetAttribute(_value_, attribute, ptr) + check_status(__status__) + + +cpdef pointer_get_attributes(unsigned int num_attributes, intptr_t attributes, intptr_t data, unsigned long long ptr): + """Returns information about a pointer. + + The supported attributes are (refer to ``cuPointerGetAttribute`` for + attribute descriptions and restrictions):. + + - ``CU_POINTER_ATTRIBUTE_CONTEXT``. + + - ``CU_POINTER_ATTRIBUTE_MEMORY_TYPE``. + + - ``CU_POINTER_ATTRIBUTE_DEVICE_POINTER``. + + - ``CU_POINTER_ATTRIBUTE_HOST_POINTER``. + + - ``CU_POINTER_ATTRIBUTE_SYNC_MEMOPS``. + + - ``CU_POINTER_ATTRIBUTE_BUFFER_ID``. + + - ``CU_POINTER_ATTRIBUTE_IS_MANAGED``. + + - ``CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL``. + + - ``CU_POINTER_ATTRIBUTE_RANGE_START_ADDR``. + + - ``CU_POINTER_ATTRIBUTE_RANGE_SIZE``. + + - ``CU_POINTER_ATTRIBUTE_MAPPED``. + + - ``CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE``. + + - ``CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES``. + + - ``CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE``. + + - ``CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE``. + + Unlike ``cuPointerGetAttribute``, 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 CUDA_SUCCESS is returned. + + If ``ptr`` was not allocated by, mapped by, or registered with a + ``CUcontext`` which uses UVA (Unified Virtual Addressing), + ``CUDA_ERROR_INVALID_CONTEXT`` is returned. + + Args: + num_attributes (unsigned int): Number of attributes to query. + attributes (intptr_t): An array of attributes to query + (num_attributes and the number of attributes in this array + should match). + data (intptr_t): A two-dimensional array containing pointers + to memory locations where the result of each attribute + query will be written to. + ptr (unsigned long long): Pointer to query. + + .. seealso:: `cuPointerGetAttributes` + """ + with nogil: + __status__ = cuPointerGetAttributes(num_attributes, attributes, data, ptr) + check_status(__status__) + + +cpdef intptr_t stream_create(unsigned int flags) except? 0: + """Create a stream. + + Creates a stream and returns a handle in ``ph_stream``. The ``flags`` + argument determines behaviors of the stream. + + Valid values for ``flags`` are:. + + - ``CU_STREAM_DEFAULT``: Default stream creation flag. + + - ``CU_STREAM_NON_BLOCKING``: 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. + + Args: + flags (unsigned int): Parameters for stream creation. + + Returns: + intptr_t: Returned newly created stream. + + .. seealso:: `cuStreamCreate` + """ + cdef CUstream ph_stream + with nogil: + __status__ = cuStreamCreate(&ph_stream, flags) + check_status(__status__) + return ph_stream + + +cpdef intptr_t stream_create_with_priority(unsigned int flags, int priority) except? 0: + """Create a stream with the given priority. + + Creates a stream with the specified priority and returns a handle in + ``ph_stream``. 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 ``cuCtxGetStreamPriorityRange``. + If the specified priority is outside the numerical range returned by + ``cuCtxGetStreamPriorityRange``, it will automatically be clamped to the + lowest or the highest number in the range. + + Args: + flags (unsigned int): Flags for stream creation. See + ``cuStreamCreate`` for a list of valid flags. + priority (int): Stream priority. Lower numbers represent + higher priorities. See ``cuCtxGetStreamPriorityRange`` for + more information about meaningful stream priorities that + can be passed. + + Returns: + intptr_t: Returned newly created stream. + + .. 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. + + .. seealso:: `cuStreamCreateWithPriority` + """ + cdef CUstream ph_stream + with nogil: + __status__ = cuStreamCreateWithPriority(&ph_stream, flags, priority) + check_status(__status__) + return ph_stream + + +cpdef int stream_get_priority(intptr_t h_stream) except? -1: + """Query the priority of a given stream. + + Query the priority of a stream created using ``cuStreamCreate``, + ``cuStreamCreateWithPriority`` or ``cuGreenCtxStreamCreate`` and return the + priority in ``priority``. Note that if the stream was created with a + priority outside the numerical range returned by + ``cuCtxGetStreamPriorityRange``, this function returns the clamped + priority. See ``cuStreamCreateWithPriority`` for details about priority + clamping. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + int: Pointer to a signed integer in which the stream's + priority is returned. + + .. seealso:: `cuStreamGetPriority` + """ + cdef int priority + with nogil: + __status__ = cuStreamGetPriority(h_stream, &priority) + check_status(__status__) + return priority + + +cpdef int stream_get_device(intptr_t h_stream) except? -1: + """Returns the device handle of the stream. + + Returns in ``*device`` the device handle of the stream. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + int: Returns the device to which a stream belongs. + + .. seealso:: `cuStreamGetDevice` + """ + cdef CUdevice device + with nogil: + __status__ = cuStreamGetDevice(h_stream, &device) + check_status(__status__) + return device + + +cpdef unsigned int stream_get_flags(intptr_t h_stream) except? 0: + """Query the flags of a given stream. + + Query the flags of a stream created using ``cuStreamCreate``, + ``cuStreamCreateWithPriority`` or ``cuGreenCtxStreamCreate`` and return the + flags in ``flags``. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + unsigned int: Pointer to an unsigned integer in which the + stream's flags are returned The value returned in + ``flags`` is a logical 'OR' of all flags that were used + while creating this stream. See ``cuStreamCreate`` for the + list of valid flags. + + .. seealso:: `cuStreamGetFlags` + """ + cdef unsigned int flags + with nogil: + __status__ = cuStreamGetFlags(h_stream, &flags) + check_status(__status__) + return flags + + +cpdef unsigned long long stream_get_id(intptr_t h_stream) except? 0: + """Returns the unique Id associated with the stream handle supplied. + + Returns in ``stream_id`` the unique Id which is associated with the given + stream handle. The Id is unique for the life of the program. + + The stream handle ``h_stream`` can refer to any of the following:. + + - a stream created via any of the CUDA driver APIs such as + ``cuStreamCreate`` and ``cuStreamCreateWithPriority``, 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. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + unsigned long long: Pointer to store the Id of the stream. + + .. seealso:: `cuStreamGetId` + """ + cdef unsigned long long stream_id + with nogil: + __status__ = cuStreamGetId(h_stream, &stream_id) + check_status(__status__) + return stream_id + + +cpdef intptr_t stream_get_ctx(intptr_t h_stream) except? 0: + """Query the context associated with a stream. + + Returns the CUDA context that the stream is associated with. + + If the stream was created via the API ``cuGreenCtxStreamCreate``, the + returned context is equivalent to the one returned by + :func:`ctx_from_green_ctx` on the green context associated with the stream + at creation time. + + The stream handle ``h_stream`` can refer to any of the following:. + + - a stream created via any of the CUDA driver APIs such as + ``cuStreamCreate`` and ``cuStreamCreateWithPriority``, 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, ``CUDA_ERROR_INVALID_CONTEXT`` is returned. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + intptr_t: Returned context associated with the stream. + + .. seealso:: `cuStreamGetCtx` + """ + cdef CUcontext pctx + with nogil: + __status__ = cuStreamGetCtx(h_stream, &pctx) + check_status(__status__) + return pctx + + +cpdef tuple stream_get_ctx_v2(intptr_t h_stream): + """Query 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 ``p_green_ctx`` and the primary context of the associated device + in ``p_ctx``. + + If the stream is associated with a regular context, the API returns the + regular context in ``p_ctx`` and NULL in ``p_green_ctx``. + + The stream handle ``h_stream`` can refer to any of the following:. + + - a stream created via any of the CUDA driver APIs such as + ``cuStreamCreate``, ``cuStreamCreateWithPriority`` and + ``cuGreenCtxStreamCreate``, 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 :func:`ctx_from_green_ctx` before setting it + current) is current to the calling thread, the API will return the green + context in ``p_green_ctx`` and the primary context of the associated device + in ``p_ctx``. If a regular context is current, the API returns the regular + context in ``p_ctx`` and NULL in ``p_green_ctx``. Note that specifying + ``CU_STREAM_PER_THREAD`` or ``cudaStreamPerThread`` will return + ``CUDA_ERROR_INVALID_HANDLE`` if a green context is current to the calling + thread. If no context is current to the calling thread, + ``CUDA_ERROR_INVALID_CONTEXT`` is returned. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + A 2-tuple containing: + + - intptr_t: Returned regular context associated with the stream. + - intptr_t: Returned green context if the stream is associated + with a green context or NULL if not. + + .. seealso:: `cuStreamGetCtx_v2` + """ + cdef CUcontext p_ctx + cdef CUgreenCtx p_green_ctx + with nogil: + __status__ = cuStreamGetCtx_v2(h_stream, &p_ctx, &p_green_ctx) + check_status(__status__) + return (p_ctx, p_green_ctx) + + +cpdef stream_wait_event(intptr_t h_stream, intptr_t h_event, unsigned int flags): + """Make a compute stream wait on an event. + + Makes all future work submitted to ``h_stream`` wait for all work captured + in ``h_event``. See :func:`event_record` for details on what is captured by + an event. The synchronization will be performed efficiently on the device + when applicable. ``h_event`` may be from a different context or device than + ``h_stream``. + + flags include:. + + - ``CU_EVENT_WAIT_DEFAULT``: Default event creation flag. + + - ``CU_EVENT_WAIT_EXTERNAL``: Event is captured in the graph as an external + event node when performing stream capture. This flag is invalid outside of + stream capture. + + Args: + h_stream (intptr_t): Stream to wait. + h_event (intptr_t): Event to wait on (may not be NULL). + flags (unsigned int): See ``CUevent_capture_flags``. + + .. seealso:: `cuStreamWaitEvent` + """ + with nogil: + __status__ = cuStreamWaitEvent(h_stream, h_event, flags) + check_status(__status__) + + +cpdef stream_add_callback(intptr_t h_stream, intptr_t callback, intptr_t user_data, unsigned int flags): + """Add a callback to a compute stream. + + Adds a callback to be called on the host after all currently enqueued items + in the stream have completed. For each cuStreamAddCallback 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 ``CUDA_SUCCESS`` or an error code. In the event + of a device error, all subsequently executed callbacks will receive an + appropriate ``CUresult``. + + Callbacks must not make any CUDA API calls. Attempting to use a CUDA API + will result in ``CUDA_ERROR_NOT_PERMITTED``. 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. + + Args: + h_stream (intptr_t): Stream to add callback to. + callback (intptr_t): The function to call once preceding + stream operations are complete. + user_data (intptr_t): User specified data to be passed to the + callback function. + flags (unsigned int): Reserved for future use, must be 0. + + .. 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 ``cuLaunchHostFunc``. Additionally, this function is not + supported with ``cuStreamBeginCapture`` and ``cuStreamEndCapture``, + unlike ``cuLaunchHostFunc``. + + .. seealso:: `cuStreamAddCallback` + """ + with nogil: + __status__ = cuStreamAddCallback(h_stream, callback, user_data, flags) + check_status(__status__) + + +cpdef stream_begin_capture_v2(intptr_t h_stream, int mode): + """Begins graph capture on a stream. + + Begin graph capture on ``h_stream``. When a stream is in capture mode, all + operations pushed into the stream will not be executed, but will instead be + captured into a graph, which will be returned via ``cuStreamEndCapture``. + 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 ``cuStreamIsCapturing``. A unique id representing the + capture sequence may be queried via ``cuStreamGetCaptureInfo``. + + If ``mode`` is not ``CU_STREAM_CAPTURE_MODE_RELAXED``, + ``cuStreamEndCapture`` must be called on this stream from the same thread. + + Args: + h_stream (intptr_t): Stream in which to initiate capture. + mode (StreamCaptureMode): Controls the interaction of this + capture sequence with other API calls that are potentially + unsafe. For more details see + ``cuThreadExchangeStreamCaptureMode``. + + .. 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. + + .. seealso:: `cuStreamBeginCapture_v2` + """ + with nogil: + __status__ = cuStreamBeginCapture(h_stream, mode) + check_status(__status__) + + +cpdef stream_begin_capture_to_graph(intptr_t h_stream, intptr_t h_graph, intptr_t dependencies, dependency_data, size_t num_dependencies, int mode): + """Begins graph capture on a stream to an existing graph. + + Begin graph capture on ``h_stream``, 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 ``h_graph``. + The graph will not be instantiable until the user calls + ``cuStreamEndCapture``. + + 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 ``cuStreamIsCapturing``. A unique id representing the + capture sequence may be queried via ``cuStreamGetCaptureInfo``. + + If ``mode`` is not ``CU_STREAM_CAPTURE_MODE_RELAXED``, + ``cuStreamEndCapture`` must be called on this stream from the same thread. + + Args: + h_stream (intptr_t): Stream in which to initiate capture. + h_graph (intptr_t): Graph to capture into. + dependencies (intptr_t): Dependencies of the first node + captured in the stream. Can be NULL if num_dependencies is + 0. + dependency_data (intptr_t): Optional array of data associated + with each dependency. + num_dependencies (size_t): Number of dependencies. + mode (StreamCaptureMode): Controls the interaction of this + capture sequence with other API calls that are potentially + unsafe. For more details see + ``cuThreadExchangeStreamCaptureMode``. + + .. 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. + + .. seealso:: `cuStreamBeginCaptureToGraph` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _dependency_data_ptr_ = int(dependency_data) + with nogil: + __status__ = cuStreamBeginCaptureToGraph(h_stream, h_graph, dependencies, _dependency_data_ptr_, num_dependencies, mode) + check_status(__status__) + + +cpdef int thread_exchange_stream_capture_mode() except? -1: + """Swaps the stream capture interaction mode for a thread. + + Sets the calling thread's stream capture interaction mode to the value + contained in ``*mode``, and overwrites ``*mode`` with the previous mode for + the thread. To facilitate deterministic behavior across function or module + boundaries, callers are encouraged to use this API in a push-pop fashion:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + During stream capture (see ``cuStreamBeginCapture``), 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 + ``cuStreamBeginCapture`` 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 ``cuStreamBeginCapture``-``cuStreamEndCapture`` + sequence. This behavior can be controlled via this API and flags to + ``cuStreamBeginCapture``. + + A thread's mode is one of the following:. + + - ``CU_STREAM_CAPTURE_MODE_GLOBAL:`` This is the default mode. If the local + thread has an ongoing capture sequence that was not initiated with + ``CU_STREAM_CAPTURE_MODE_RELAXED`` at ``cuStreamBeginCapture``, or if any + other thread has a concurrent capture sequence initiated with + ``CU_STREAM_CAPTURE_MODE_GLOBAL``, this thread is prohibited from + potentially unsafe API calls. + + - ``CU_STREAM_CAPTURE_MODE_THREAD_LOCAL:`` If the local thread has an + ongoing capture sequence not initiated with + ``CU_STREAM_CAPTURE_MODE_RELAXED``, it is prohibited from potentially + unsafe API calls. Concurrent capture sequences in other threads are + ignored. + + - ``CU_STREAM_CAPTURE_MODE_RELAXED:`` The local thread is not prohibited + from potentially unsafe API calls. Note that the thread is still prohibited + from API calls which necessarily conflict with stream capture, for example, + attempting ``cuEventQuery`` on an event that was last recorded inside a + capture sequence. + + Returns: + int: Pointer to mode value to swap with the current mode. + + .. seealso:: `cuThreadExchangeStreamCaptureMode` + """ + cdef CUstreamCaptureMode mode + with nogil: + __status__ = cuThreadExchangeStreamCaptureMode(&mode) + check_status(__status__) + return mode + + +cpdef intptr_t stream_end_capture(intptr_t h_stream) except? 0: + """Ends capture on a stream, returning the captured graph. + + End capture on ``h_stream``, returning the captured graph via ``ph_graph``. + Capture must have been initiated on ``h_stream`` via a call to + ``cuStreamBeginCapture``. 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 ``cuStreamBeginCapture`` was not + ``CU_STREAM_CAPTURE_MODE_RELAXED``, this call must be from the same thread + as ``cuStreamBeginCapture``. + + Args: + h_stream (intptr_t): Stream to query. + + Returns: + intptr_t: The captured graph. + + .. seealso:: `cuStreamEndCapture` + """ + cdef CUgraph ph_graph + with nogil: + __status__ = cuStreamEndCapture(h_stream, &ph_graph) + check_status(__status__) + return ph_graph + + +cpdef int stream_is_capturing(intptr_t h_stream) except? -1: + """Returns a stream's capture status. + + Return the capture status of ``h_stream`` via ``capture_status``. After a + successful call, ``*capture_status`` will contain one of the following:. + + - ``CU_STREAM_CAPTURE_STATUS_NONE``: The stream is not capturing. + + - ``CU_STREAM_CAPTURE_STATUS_ACTIVE``: The stream is capturing. + + - ``CU_STREAM_CAPTURE_STATUS_INVALIDATED``: The stream was capturing but an + error has invalidated the capture sequence. The capture sequence must be + terminated with ``cuStreamEndCapture`` on the stream where it was initiated + in order to continue using ``h_stream``. + + 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 + ``CUDA_ERROR_STREAM_CAPTURE_IMPLICIT`` and ``*capture_status`` 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). + + Args: + h_stream (intptr_t): Stream to query. + + Returns: + int: Returns the stream's capture status. + + .. seealso:: `cuStreamIsCapturing` + """ + cdef CUstreamCaptureStatus capture_status + with nogil: + __status__ = cuStreamIsCapturing(h_stream, &capture_status) + check_status(__status__) + return capture_status + + +cpdef tuple stream_get_capture_info_v2(intptr_t h_stream): + """Query 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 ``CU_STREAM_NON_BLOCKING`` is capturing, returns + ``CUDA_ERROR_STREAM_CAPTURE_IMPLICIT``. + + Valid data (other than capture status) is returned only if both of the + following are true:. + + - the call returns CUDA_SUCCESS. + + - the returned capture status is ``CU_STREAM_CAPTURE_STATUS_ACTIVE``. + + Args: + h_stream (intptr_t): The stream to query. + + Returns: + A 4-tuple containing: + + - int: Location to return the capture status of the stream; + required. + - uint64_t: Optional location to return an id for the capture + sequence, which is unique over the lifetime of the + process. + - intptr_t: Optional location to return the graph being captured + into. All operations other than destroy and node removal + are permitted on the graph while the capture sequence is + in progress. This API does not transfer ownership of the + graph, which is transferred or destroyed at + ``cuStreamEndCapture``. 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 ``cuStreamEndCapture`` due to direct actions on + the graph do not trigger + ``CUDA_ERROR_STREAM_CAPTURE_UNJOINED``. + - intptr_t: Optional location to store a pointer to an array of + nodes. The next node to be captured in the stream will + depend on this set of nodes, absent operations such as + event wait which modify this set. The array pointer is + valid until the next API call which operates on the stream + or until 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. + + .. seealso:: `cuStreamGetCaptureInfo_v2` + """ + cdef CUstreamCaptureStatus capture_status_out + cdef cuuint64_t id_out + cdef CUgraph graph_out + cdef size_t[1] num_dependencies_out = [0] + cdef const CUgraphNode* dependencies_out = NULL + with nogil: + __status__ = cuStreamGetCaptureInfo_v2(h_stream, &capture_status_out, &id_out, &graph_out, &dependencies_out, num_dependencies_out) + check_status(__status__) + return (capture_status_out, id_out, graph_out, (_numpy.empty(0, dtype=_numpy.intp) if num_dependencies_out[0] == 0 or dependencies_out == NULL else _numpy.frombuffer(_cyb_PyMemoryView_FromMemory(dependencies_out, (num_dependencies_out[0] * sizeof(CUgraphNode)), _cyb_PyBUF_READ), dtype=_numpy.intp))) + + +cpdef tuple stream_get_capture_info_v3(intptr_t h_stream): + """Query 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 ``CU_STREAM_NON_BLOCKING`` is capturing, returns + ``CUDA_ERROR_STREAM_CAPTURE_IMPLICIT``. + + Valid data (other than capture status) is returned only if both of the + following are true:. + + - the call returns CUDA_SUCCESS. + + - the returned capture status is ``CU_STREAM_CAPTURE_STATUS_ACTIVE``. + + If ``edge_data_out`` is non-NULL then ``dependencies_out`` must be as well. + If ``dependencies_out`` is non-NULL and ``edge_data_out`` is NULL, but + there is non-zero edge data for one or more of the current stream + dependencies, the call will return ``CUDA_ERROR_LOSSY_QUERY``. + + Args: + h_stream (intptr_t): The stream to query. + + Returns: + A 5-tuple containing: + + - int: Location to return the capture status of the stream; + required. + - uint64_t: Optional location to return an id for the capture + sequence, which is unique over the lifetime of the + process. + - intptr_t: Optional location to return the graph being captured + into. All operations other than destroy and node removal + are permitted on the graph while the capture sequence is + in progress. This API does not transfer ownership of the + graph, which is transferred or destroyed at + ``cuStreamEndCapture``. 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 ``cuStreamEndCapture`` due to direct actions on + the graph do not trigger + ``CUDA_ERROR_STREAM_CAPTURE_UNJOINED``. + - intptr_t: Optional location to store a pointer to an array of + nodes. The next node to be captured in the stream will + depend on this set of nodes, absent operations such as + event wait which modify this set. The array pointer is + valid until the next API call which operates on the stream + or until 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. + - CUgraphEdgeData: Optional location to store a pointer to an + array of graph edge data. This array parallels + ``dependencies_out``; the next node to be added has an + edge to ``dependencies_out``[i] with annotation + ``edge_data_out``[i] for each ``i``. The array pointer is + valid until the next API call which operates on the stream + or until the capture is terminated. + + .. seealso:: `cuStreamGetCaptureInfo_v3` + """ + cdef CUstreamCaptureStatus capture_status_out + cdef cuuint64_t id_out + cdef CUgraph graph_out + cdef size_t[1] num_dependencies_out = [0] + cdef const CUgraphNode* dependencies_out = NULL + cdef const CUgraphEdgeData* edge_data_out = NULL + with nogil: + __status__ = cuStreamGetCaptureInfo(h_stream, &capture_status_out, &id_out, &graph_out, &dependencies_out, &edge_data_out, num_dependencies_out) + check_status(__status__) + return (capture_status_out, id_out, graph_out, (_numpy.empty(0, dtype=_numpy.intp) if num_dependencies_out[0] == 0 or dependencies_out == NULL else _numpy.frombuffer(_cyb_PyMemoryView_FromMemory(dependencies_out, (num_dependencies_out[0] * sizeof(CUgraphNode)), _cyb_PyBUF_READ), dtype=_numpy.intp)), (_numpy.empty(0, dtype=graph_edge_data_dtype) if num_dependencies_out[0] == 0 or edge_data_out == NULL else _numpy.frombuffer(_cyb_PyMemoryView_FromMemory(edge_data_out, (num_dependencies_out[0] * sizeof(CUgraphEdgeData)), _cyb_PyBUF_READ), dtype=graph_edge_data_dtype))) + + +cpdef stream_update_capture_dependencies_v2(intptr_t h_stream, intptr_t dependencies, dependency_data, size_t num_dependencies, unsigned int flags): + """Update 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 ``CU_STREAM_ADD_CAPTURE_DEPENDENCIES`` and + ``CU_STREAM_SET_CAPTURE_DEPENDENCIES``. 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 ``CU_STREAM_ADD_CAPTURE_DEPENDENCIES``. + + Nodes that are removed from the dependency set via this API do not result + in ``CUDA_ERROR_STREAM_CAPTURE_UNJOINED`` if they are unreachable from the + stream at ``cuStreamEndCapture``. + + Returns ``CUDA_ERROR_ILLEGAL_STATE`` if the stream is not capturing. + + Args: + h_stream (intptr_t): The stream to update. + dependencies (intptr_t): The set of dependencies to add. + dependency_data (intptr_t): Optional array of data associated + with each dependency. + num_dependencies (size_t): The size of the dependencies array. + flags (unsigned int): See above. + + .. seealso:: `cuStreamUpdateCaptureDependencies_v2` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _dependency_data_ptr_ = int(dependency_data) + with nogil: + __status__ = cuStreamUpdateCaptureDependencies(h_stream, dependencies, _dependency_data_ptr_, num_dependencies, flags) + check_status(__status__) + + +cpdef stream_attach_mem_async(intptr_t h_stream, unsigned long long dptr, size_t length, unsigned int flags): + """Attach memory to a stream asynchronously. + + Enqueues an operation in ``h_stream`` 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 + ``cuMemAllocManaged``. + + - 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 + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. + + 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 + ``CUmemAttach_flags``. If the ``CU_MEM_ATTACH_GLOBAL`` flag is specified, + the memory can be accessed by any stream on any device. If the + ``CU_MEM_ATTACH_HOST`` 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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. If the + ``CU_MEM_ATTACH_SINGLE`` flag is specified and ``h_stream`` is associated + with a device that has a zero value for the device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``, the program makes a + guarantee that it will only access the memory on the device from + ``h_stream``. It is illegal to attach singly to the NULL stream, because + the NULL stream is a virtual global stream and not a specific stream. An + error will be returned in this case. + + When memory is associated with a single stream, the Unified Memory system + will allow CPU access to this memory region so long as all operations in + ``h_stream`` have completed, regardless of whether other streams are + active. In effect, this constrains exclusive ownership of the managed + memory region by an active GPU to per-stream activity instead of whole-GPU + activity. + + Accessing memory on the device from streams that are not associated with it + will produce undefined results. No error checking is performed by the + Unified Memory system to ensure that kernels launched into other streams do + not access this region. + + It is a program's responsibility to order calls to + ``cuStreamAttachMemAsync`` 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 ``h_stream`` is destroyed while data is associated with it, the + association is removed and the association reverts to the default + visibility of the allocation as specified at ``cuMemAllocManaged``. For + managed variables, the default association is always + ``CU_MEM_ATTACH_GLOBAL``. 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. + + Args: + h_stream (intptr_t): Stream in which to enqueue the attach + operation. + dptr (unsigned long long): Pointer to memory (must be a + pointer to managed memory or to a valid host-accessible + region of system-allocated pageable memory). + length (size_t): Length of memory. + flags (unsigned int): Must be one of ``CUmemAttach_flags``. + + .. seealso:: `cuStreamAttachMemAsync` + """ + with nogil: + __status__ = cuStreamAttachMemAsync(h_stream, dptr, length, flags) + check_status(__status__) + + +cpdef stream_query(intptr_t h_stream): + """Determine status of a compute stream. + + Returns ``CUDA_SUCCESS`` if all operations in the stream specified by + ``h_stream`` have completed, or ``CUDA_ERROR_NOT_READY`` if not. + + For the purposes of Unified Memory, a return value of ``CUDA_SUCCESS`` is + equivalent to having called :func:`stream_synchronize`. + + Args: + h_stream (intptr_t): Stream to query status of. + + .. seealso:: `cuStreamQuery` + """ + with nogil: + __status__ = cuStreamQuery(h_stream) + check_status(__status__) + + +cpdef stream_synchronize(intptr_t h_stream): + """Wait until a stream's tasks are completed. + + Waits until the device has completed all operations in the stream specified + by ``h_stream``. If the context was created with the + ``CU_CTX_SCHED_BLOCKING_SYNC`` flag, the CPU thread will block until the + stream is finished with all of its tasks. + + \note_null_stream. + + Args: + h_stream (intptr_t): Stream to wait for. + + .. seealso:: `cuStreamSynchronize` + """ + with nogil: + __status__ = cuStreamSynchronize(h_stream) + check_status(__status__) + + +cpdef stream_destroy_v2(intptr_t h_stream): + """Destroys a stream. + + Destroys the stream specified by ``h_stream``. + + In case the device is still doing work in the stream ``h_stream`` when + ``cuStreamDestroy()`` is called, the function will return immediately and + the resources associated with ``h_stream`` will be released automatically + once the device has completed all work in ``h_stream``. + + Args: + h_stream (intptr_t): Stream to destroy. + + .. seealso:: `cuStreamDestroy_v2` + """ + with nogil: + __status__ = cuStreamDestroy(h_stream) + check_status(__status__) + + +cpdef stream_copy_attributes(intptr_t dst, intptr_t src): + """Copies attributes from source stream to destination stream. + + Copies attributes from source stream ``src`` to destination stream ``dst``. + Both streams must have the same context. + + Args: + dst (intptr_t): Destination stream. + src (intptr_t): Source stream For list of attributes see + ``CUstreamAttrID``. + + .. seealso:: `cuStreamCopyAttributes` + """ + with nogil: + __status__ = cuStreamCopyAttributes(dst, src) + check_status(__status__) + + +cpdef stream_get_attribute(intptr_t h_stream, int attr, intptr_t value_out): + """Queries stream attribute. + + Queries attribute ``attr`` from ``h_stream`` and stores it in corresponding + member of ``value_out``. + + Args: + h_stream (intptr_t): . + attr (int): . + value_out (intptr_t): . + + .. seealso:: `cuStreamGetAttribute` + """ + with nogil: + __status__ = cuStreamGetAttribute(h_stream, attr, value_out) + check_status(__status__) + + +cpdef stream_set_attribute(intptr_t h_stream, int attr, intptr_t value): + """Sets stream attribute. + + Sets attribute ``attr`` on ``h_stream`` 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. + + Args: + h_stream (intptr_t): . + attr (int): . + value (intptr_t): . + + .. seealso:: `cuStreamSetAttribute` + """ + with nogil: + __status__ = cuStreamSetAttribute(h_stream, attr, value) + check_status(__status__) + + +cpdef intptr_t event_create(unsigned int flags) except? 0: + """Creates an event. + + Creates an event *ph_event for the current context with the flags specified + via ``flags``. Valid flags include:. + + - ``CU_EVENT_DEFAULT``: Default event creation flag. + + - ``CU_EVENT_BLOCKING_SYNC``: Specifies that the created event should use + blocking synchronization. A CPU thread that uses :func:`event_synchronize` + to wait on an event created with this flag will block until the event has + actually been recorded. + + - ``CU_EVENT_DISABLE_TIMING``: Specifies that the created event does not + need to record timing data. Events created with this flag specified and the + ``CU_EVENT_BLOCKING_SYNC`` flag not specified will provide the best + performance when used with :func:`stream_wait_event` and + :func:`event_query`. + + - ``CU_EVENT_INTERPROCESS``: Specifies that the created event may be used + as an interprocess event by :func:`ipc_get_event_handle`. + ``CU_EVENT_INTERPROCESS`` must be specified along with + ``CU_EVENT_DISABLE_TIMING``. + + Args: + flags (unsigned int): Event creation flags. + + Returns: + intptr_t: Returns newly created event. + + .. seealso:: `cuEventCreate` + """ + cdef CUevent ph_event + with nogil: + __status__ = cuEventCreate(&ph_event, flags) + check_status(__status__) + return ph_event + + +cpdef event_record(intptr_t h_event, intptr_t h_stream): + """Records an event. + + Captures in ``h_event`` the contents of ``h_stream`` at the time of this + call. ``h_event`` and ``h_stream`` must be from the same context otherwise + ``CUDA_ERROR_INVALID_HANDLE`` is returned. Calls such as + :func:`event_query` or :func:`stream_wait_event` will then examine or wait + for completion of the work that was captured. Uses of ``h_stream`` after + this call do not modify ``h_event``. See note on default stream behavior + for what is captured in the default case. + + :func:`event_record` can be called multiple times on the same event and + will overwrite the previously captured state. Other APIs such as + :func:`stream_wait_event` use the most recently captured state at the time + of the API call, and are not affected by later calls to + :func:`event_record`. Before the first call to :func:`event_record`, an + event represents an empty set of work, so for example :func:`event_query` + would return ``CUDA_SUCCESS``. + + Args: + h_event (intptr_t): Event to record. + h_stream (intptr_t): Stream to record event for. + + .. seealso:: `cuEventRecord` + """ + with nogil: + __status__ = cuEventRecord(h_event, h_stream) + check_status(__status__) + + +cpdef event_record_with_flags(intptr_t h_event, intptr_t h_stream, unsigned int flags): + """Records an event. + + Captures in ``h_event`` the contents of ``h_stream`` at the time of this + call. ``h_event`` and ``h_stream`` must be from the same context otherwise + ``CUDA_ERROR_INVALID_HANDLE`` is returned. Calls such as + :func:`event_query` or :func:`stream_wait_event` will then examine or wait + for completion of the work that was captured. Uses of ``h_stream`` after + this call do not modify ``h_event``. See note on default stream behavior + for what is captured in the default case. + + :func:`event_record_with_flags` can be called multiple times on the same + event and will overwrite the previously captured state. Other APIs such as + :func:`stream_wait_event` use the most recently captured state at the time + of the API call, and are not affected by later calls to + :func:`event_record_with_flags`. Before the first call to + :func:`event_record_with_flags`, an event represents an empty set of work, + so for example :func:`event_query` would return ``CUDA_SUCCESS``. + + flags include:. + + - ``CU_EVENT_RECORD_DEFAULT``: Default event creation flag. + + - ``CU_EVENT_RECORD_EXTERNAL``: Event is captured in the graph as an + external event node when performing stream capture. This flag is invalid + outside of stream capture. + + Args: + h_event (intptr_t): Event to record. + h_stream (intptr_t): Stream to record event for. + flags (unsigned int): See ``CUevent_capture_flags``. + + .. seealso:: `cuEventRecordWithFlags` + """ + with nogil: + __status__ = cuEventRecordWithFlags(h_event, h_stream, flags) + check_status(__status__) + + +cpdef event_query(intptr_t h_event): + """Queries an event's status. + + Queries the status of all work currently captured by ``h_event``. See + :func:`event_record` for details on what is captured by an event. + + Returns ``CUDA_SUCCESS`` if all captured work has been completed, or + ``CUDA_ERROR_NOT_READY`` if any captured work is incomplete. + + For the purposes of Unified Memory, a return value of ``CUDA_SUCCESS`` is + equivalent to having called :func:`event_synchronize`. + + Args: + h_event (intptr_t): Event to query. + + .. seealso:: `cuEventQuery` + """ + with nogil: + __status__ = cuEventQuery(h_event) + check_status(__status__) + + +cpdef event_synchronize(intptr_t h_event): + """Waits for an event to complete. + + Waits until the completion of all work currently captured in ``h_event``. + See :func:`event_record` for details on what is captured by an event. + + Waiting for an event that was created with the ``CU_EVENT_BLOCKING_SYNC`` + flag will cause the calling CPU thread to block until the event has been + completed by the device. If the ``CU_EVENT_BLOCKING_SYNC`` flag has not + been set, then the CPU thread will busy-wait until the event has been + completed by the device. + + Args: + h_event (intptr_t): Event to wait for. + + .. seealso:: `cuEventSynchronize` + """ + with nogil: + __status__ = cuEventSynchronize(h_event) + check_status(__status__) + + +cpdef event_destroy_v2(intptr_t h_event): + """Destroys an event. + + Destroys the event specified by ``h_event``. + + An event may be destroyed before it is complete (i.e., while + :func:`event_query` would return ``CUDA_ERROR_NOT_READY``). In this case, + the call does not block on completion of the event, and any associated + resources will automatically be released asynchronously at completion. + + Args: + h_event (intptr_t): Event to destroy. + + .. seealso:: `cuEventDestroy_v2` + """ + with nogil: + __status__ = cuEventDestroy(h_event) + check_status(__status__) + + +cpdef float event_elapsed_time_v2(intptr_t h_start, intptr_t h_end) except? -1.0: + """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 ``cuEventQuery`` 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 :func:`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 :func:`event_record` has not been called on either event then + ``CUDA_ERROR_INVALID_HANDLE`` is returned. If :func:`event_record` has been + called on both events but one or both of them has not yet been completed + (that is, :func:`event_query` would return ``CUDA_ERROR_NOT_READY`` on at + least one of the events), ``CUDA_ERROR_NOT_READY`` is returned. If either + event was created with the ``CU_EVENT_DISABLE_TIMING`` flag, then this + function will return ``CUDA_ERROR_INVALID_HANDLE``. + + Args: + h_start (intptr_t): Starting event. + h_end (intptr_t): Ending event. + + Returns: + float: Time between ``h_start`` and ``h_end`` in ms. + + .. seealso:: `cuEventElapsedTime_v2` + """ + cdef float p_milliseconds + with nogil: + __status__ = cuEventElapsedTime(&p_milliseconds, h_start, h_end) + check_status(__status__) + return p_milliseconds + + +cpdef intptr_t import_external_memory(intptr_t mem_handle_desc) except? 0: + """Imports an external memory object. + + Imports an externally allocated memory object and returns a handle to that + in ``ext_mem_out``. + + The properties of the handle being imported must be described in + ``mem_handle_desc``. The ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC`` structure is + defined as follows:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` specifies the type of + handle being imported. ``CUexternalMemoryHandleType`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32``, then exactly one of + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` and + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.name`` must not be NULL. If + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` must be non-NULL + and ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP``, then exactly one of + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` and + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.name`` must not be NULL. If + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE``, then exactly one of + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` and + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.name`` must not be NULL. If + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` must represent a + valid shared NT handle that is returned by + IDXGIResource1::CreateSharedHandle when referring to a ID3D11Resource + object. If ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.handle`` must represent a + valid shared KMT handle that is returned by IDXGIResource::GetSharedHandle + when referring to a ID3D11Resource object and + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.win32.name`` must be NULL. + + If ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 + ``cuWaitExternalSemaphoresAsync`` or ``cuSignalExternalSemaphoresAsync`` 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 ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD``, then + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.handle.fd`` must be a valid file + descriptor referencing a dma_buf object and + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.flags`` must be zero. Importing a + dma_buf object is supported only on Tegra Jetson platform starting with + Thor series. Mapping an imported dma_buf object as CUDA mipmapped array + using ``cuExternalMemoryGetMappedMipmappedArray`` is not supported. + + The size of the memory object must be specified in + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.size``. + + Specifying the flag ``CUDA_EXTERNAL_MEMORY_DEDICATED`` in + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.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 + ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC.type`` is one of the following: + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE`` + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE`` + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT``. + + Args: + mem_handle_desc (intptr_t): Memory import handle descriptor. + + Returns: + intptr_t: Returned handle to an external memory object. + + .. 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. + + .. seealso:: `cuImportExternalMemory` + """ + cdef CUexternalMemory ext_mem_out + with nogil: + __status__ = cuImportExternalMemory(&ext_mem_out, mem_handle_desc) + check_status(__status__) + return ext_mem_out + + +cpdef unsigned long long external_memory_get_mapped_buffer(intptr_t ext_mem, buffer_desc) except? 0: + """Maps a buffer onto an imported memory object. + + Maps a buffer onto an imported memory object and returns a device pointer + in ``dev_ptr``. + + The properties of the buffer being mapped must be described in + ``buffer_desc``. The ``CUDA_EXTERNAL_MEMORY_BUFFER_DESC`` structure is + defined as follows:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUDA_EXTERNAL_MEMORY_BUFFER_DESC.offset`` is the offset in the + memory object where the buffer's base address is. + ``CUDA_EXTERNAL_MEMORY_BUFFER_DESC.size`` is the size of the buffer. + ``CUDA_EXTERNAL_MEMORY_BUFFER_DESC.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 ``dev_ptr`` must be freed using ``cuMemFree``. + + Args: + ext_mem (intptr_t): Handle to external memory object. + buffer_desc (intptr_t): Buffer descriptor. + + Returns: + unsigned long long: Returned device pointer to buffer. + + .. seealso:: `cuExternalMemoryGetMappedBuffer` + """ + cdef intptr_t _buffer_desc_ptr_ = int(buffer_desc) + cdef CUdeviceptr dev_ptr + with nogil: + __status__ = cuExternalMemoryGetMappedBuffer(&dev_ptr, ext_mem, _buffer_desc_ptr_) + check_status(__status__) + return dev_ptr + + +cpdef intptr_t external_memory_get_mapped_mipmapped_array(intptr_t ext_mem, intptr_t mipmap_desc) except? 0: + """Maps a CUDA mipmapped array onto an external memory object. + + Maps a CUDA mipmapped array onto an external object and returns a handle to + it in ``mipmap``. + + The properties of the CUDA mipmapped array being mapped must be described + in ``mipmap_desc``. The structure + ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC`` is defined as follows:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC.offset`` is the offset in + the memory object where the base level of the mipmap chain is. + ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC.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 + ``cuMipmappedArrayCreate``. 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 + ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC``::arrayDesc::Flags. + ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC.numLevels`` specifies the total + number of levels in the mipmap chain. + + If ``ext_mem`` was imported from a handle of type + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF``, then + ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC.numLevels`` must be equal to 1. + + Mapping ``ext_mem`` imported from a handle of type + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD``, is not supported. + + The returned CUDA mipmapped array must be freed using + ``cuMipmappedArrayDestroy``. + + Args: + ext_mem (intptr_t): Handle to external memory object. + mipmap_desc (intptr_t): CUDA array descriptor. + + Returns: + intptr_t: Returned CUDA mipmapped array. + + .. seealso:: `cuExternalMemoryGetMappedMipmappedArray` + """ + cdef CUmipmappedArray mipmap + with nogil: + __status__ = cuExternalMemoryGetMappedMipmappedArray(&mipmap, ext_mem, mipmap_desc) + check_status(__status__) + return mipmap + + +cpdef destroy_external_memory(intptr_t ext_mem): + """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 ``cuMemFree`` and + ``cuMipmappedArrayDestroy`` respectively. + + Args: + ext_mem (intptr_t): External memory object to be destroyed. + + .. seealso:: `cuDestroyExternalMemory` + """ + with nogil: + __status__ = cuDestroyExternalMemory(ext_mem) + check_status(__status__) + + +cpdef intptr_t import_external_semaphore(intptr_t sem_handle_desc) except? 0: + """Imports an external semaphore. + + Imports an externally allocated synchronization object and returns a handle + to that in ``ext_sem_out``. + + The properties of the handle being imported must be described in + ``sem_handle_desc``. The ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC`` is defined + as follows:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` specifies the type of + handle being imported. ``CUexternalSemaphoreHandleType`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32``, then exactly one of + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` and + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` must not be NULL. + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` is not NULL, then + it must name a valid synchronization object. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` must be non- + NULL and ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE``, then exactly one of + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` and + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` must not be NULL. + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` is not NULL, then + it must name a valid synchronization object that refers to a valid + ID3D12Fence object. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` represents a + valid shared NT handle that is returned by ID3D11Fence::CreateSharedHandle. + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` is not NULL, + then it must name a valid synchronization object that refers to a valid + ID3D11Fence object. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.nvSciSyncObj`` represents a + valid NvSciSyncObj. + + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` represents a + valid shared NT handle that is returned by + IDXGIResource1::CreateSharedHandle when referring to a IDXGIKeyedMutex + object. If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` is not + NULL, then it must name a valid synchronization object that refers to a + valid IDXGIKeyedMutex object. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` represents a + valid shared KMT handle that is returned by IDXGIResource::GetSharedHandle + when referring to a IDXGIKeyedMutex object and + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` must be NULL. + + If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD``, then + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.type`` is + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32``, then + exactly one of ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.handle`` + and ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` must not be + NULL. If ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.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 + ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC.handle.win32.name`` is not NULL, then + it must name a valid synchronization object. + + Args: + sem_handle_desc (intptr_t): Semaphore import handle + descriptor. + + Returns: + intptr_t: Returned handle to an external semaphore. + + .. seealso:: `cuImportExternalSemaphore` + """ + cdef CUexternalSemaphore ext_sem_out + with nogil: + __status__ = cuImportExternalSemaphore(&ext_sem_out, sem_handle_desc) + check_status(__status__) + return ext_sem_out + + +cpdef signal_external_semaphores_async(intptr_t ext_sem_array, intptr_t params_array, unsigned int num_ext_sems, intptr_t stream): + """Signals a set of external semaphore objects. + + Enqueues a signal operation on a set of externally allocated semaphore + object in the specified stream. The operations will be executed when all + prior operations in the stream complete. + + The exact semantics of signaling a semaphore depends on the type of the + object. + + If the semaphore object is any one of the following types: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT`` then signaling the + semaphore will set it to the signaled state. + + If the semaphore object is any one of the following types: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32`` then the + semaphore will be set to the value specified in + ``CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS.params.fence.value``. + + If the semaphore object is of the type + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC`` this API sets + ``CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS.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 + ``CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS.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 ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF``. + 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 + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC``, if the NvSciSyncAttrList + used to create the NvSciSyncObj had not set the flags in + ``cuDeviceGetNvSciSyncAttributes`` to CUDA_NVSCISYNC_ATTR_SIGNAL, this API + will return CUDA_ERROR_NOT_SUPPORTED. NvSciSyncFence associated with + semaphore object of the type + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC`` 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 + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC`` 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: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT`` then the keyed + mutex will be released with the key specified in + ``CUDA_EXTERNAL_SEMAPHORE_PARAMS``::params::keyedmutex::key. + + Args: + ext_sem_array (intptr_t): Set of external semaphores to be + signaled. + params_array (intptr_t): Array of semaphore parameters. + num_ext_sems (unsigned int): Number of semaphores to signal. + stream (intptr_t): Stream to enqueue the signal operations in. + + .. seealso:: `cuSignalExternalSemaphoresAsync` + """ + cdef CUexternalSemaphore _ext_sem_array_ = ext_sem_array + with nogil: + __status__ = cuSignalExternalSemaphoresAsync(ext_sem_array, params_array, num_ext_sems, stream) + check_status(__status__) + + +cpdef wait_external_semaphores_async(intptr_t ext_sem_array, intptr_t params_array, unsigned int num_ext_sems, intptr_t stream): + """Waits on a set of external semaphore objects. + + Enqueues a wait operation on a set of externally allocated semaphore object + in the specified stream. The operations will be executed when all prior + operations in the stream complete. + + The exact semantics of waiting on a semaphore depends on the type of the + object. + + If the semaphore object is any one of the following types: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT`` 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: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32`` then waiting + on the semaphore will wait until the value of the semaphore is greater than + or equal to ``CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS.params.fence.value``. + + If the semaphore object is of the type + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC`` then, waiting on the + semaphore will wait until the + ``CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS.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 + ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF``. 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 ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC``, if the + NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in + ``cuDeviceGetNvSciSyncAttributes`` to CUDA_NVSCISYNC_ATTR_WAIT, this API + will return CUDA_ERROR_NOT_SUPPORTED. + + If the semaphore object is any one of the following types: + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX``, + ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT`` then the keyed + mutex will be acquired when it is released with the key specified in + ``CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS.params.keyedmutex.key`` or until the + timeout specified by + ``CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS.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. + + Args: + ext_sem_array (intptr_t): External semaphores to be waited on. + params_array (intptr_t): Array of semaphore parameters. + num_ext_sems (unsigned int): Number of semaphores to wait on. + stream (intptr_t): Stream to enqueue the wait operations in. + + .. seealso:: `cuWaitExternalSemaphoresAsync` + """ + cdef CUexternalSemaphore _ext_sem_array_ = ext_sem_array + with nogil: + __status__ = cuWaitExternalSemaphoresAsync(ext_sem_array, params_array, num_ext_sems, stream) + check_status(__status__) + + +cpdef destroy_external_semaphore(intptr_t ext_sem): + """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. + + Args: + ext_sem (intptr_t): External semaphore to be destroyed. + + .. seealso:: `cuDestroyExternalSemaphore` + """ + with nogil: + __status__ = cuDestroyExternalSemaphore(ext_sem) + check_status(__status__) + + +cpdef stream_wait_value32_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags): + """Wait 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 ``cuMemHostRegister()``, the device + pointer should be obtained with ``cuMemHostGetDevicePointer()``. This + function cannot be used with managed memory (``cuMemAllocManaged``). + + Support for CU_STREAM_WAIT_VALUE_NOR can be queried with + :func:`device_get_attribute` and + ``CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V2``. + + Args: + stream (intptr_t): The stream to synchronize on the memory + location. + addr (unsigned long long): The memory location to wait on. + value (uint64_t): The value to compare with the memory + location. + flags (unsigned int): See ``CUstreamWaitValue_flags``. + + .. note:: + 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. + + .. seealso:: `cuStreamWaitValue32_v2` + """ + with nogil: + __status__ = cuStreamWaitValue32(stream, addr, value, flags) + check_status(__status__) + + +cpdef stream_wait_value64_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags): + """Wait 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 ``cuMemHostRegister()``, the device + pointer should be obtained with ``cuMemHostGetDevicePointer()``. + + Support for this can be queried with :func:`device_get_attribute` and + ``CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS``. + + Args: + stream (intptr_t): The stream to synchronize on the memory + location. + addr (unsigned long long): The memory location to wait on. + value (uint64_t): The value to compare with the memory + location. + flags (unsigned int): See ``CUstreamWaitValue_flags``. + + .. note:: + 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. + + .. seealso:: `cuStreamWaitValue64_v2` + """ + with nogil: + __status__ = cuStreamWaitValue64(stream, addr, value, flags) + check_status(__status__) + + +cpdef stream_write_value32_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags): + """Write a value to memory. + + Write a value to memory. + + If the memory was registered via ``cuMemHostRegister()``, the device + pointer should be obtained with ``cuMemHostGetDevicePointer()``. This + function cannot be used with managed memory (``cuMemAllocManaged``). + + Args: + stream (intptr_t): The stream to do the write in. + addr (unsigned long long): The device address to write to. + value (uint64_t): The value to write. + flags (unsigned int): See ``CUstreamWriteValue_flags``. + + .. seealso:: `cuStreamWriteValue32_v2` + """ + with nogil: + __status__ = cuStreamWriteValue32(stream, addr, value, flags) + check_status(__status__) + + +cpdef stream_write_value64_v2(intptr_t stream, unsigned long long addr, uint64_t value, unsigned int flags): + """Write a value to memory. + + Write a value to memory. + + If the memory was registered via ``cuMemHostRegister()``, the device + pointer should be obtained with ``cuMemHostGetDevicePointer()``. + + Support for this can be queried with :func:`device_get_attribute` and + ``CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS``. + + Args: + stream (intptr_t): The stream to do the write in. + addr (unsigned long long): The device address to write to. + value (uint64_t): The value to write. + flags (unsigned int): See ``CUstreamWriteValue_flags``. + + .. seealso:: `cuStreamWriteValue64_v2` + """ + with nogil: + __status__ = cuStreamWriteValue64(stream, addr, value, flags) + check_status(__status__) + + +cpdef stream_batch_mem_op_v2(intptr_t stream, unsigned int count, param_array, unsigned int flags): + """Batch operations to synchronize the stream via memory operations. + + This is a batch version of ``cuStreamWaitValue32()`` and + ``cuStreamWriteValue32()``. 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 ``CUstreamBatchMemOpType`` for the full set of supported operations, + and ``cuStreamWaitValue32()``, ``cuStreamWaitValue64()``, + ``cuStreamWriteValue32()``, and ``cuStreamWriteValue64()`` for details of + specific operations. + + See related APIs for details on querying support for specific operations. + + Args: + stream (intptr_t): The stream to enqueue the operations in. + count (unsigned int): The number of operations in the array. + Must be less than 256. + param_array (intptr_t): The types and parameters of the + individual operations. + flags (unsigned int): Reserved for future expansion; must be + 0. + + .. note:: + 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. + + .. seealso:: `cuStreamBatchMemOp_v2` + """ + cdef intptr_t _param_array_ptr_ = int(param_array) + with nogil: + __status__ = cuStreamBatchMemOp(stream, count, _param_array_ptr_, flags) + check_status(__status__) + + +cpdef int func_get_attribute(int attrib, intptr_t hfunc) except? -1: + """Returns information about a function. + + Returns in ``*pi`` the integer value of the attribute ``attrib`` on the + kernel given by ``hfunc``. The supported attributes are:. + + - ``CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK``: 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. + + - ``CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES``: 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. + + - ``CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES``: The size in bytes of user- + allocated constant memory required by this function. + + - ``CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES``: The size in bytes of local memory + used by each thread of this function. + + - ``CU_FUNC_ATTRIBUTE_NUM_REGS``: The number of registers used by each + thread of this function. + + - ``CU_FUNC_ATTRIBUTE_PTX_VERSION``: 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. + + - ``CU_FUNC_ATTRIBUTE_BINARY_VERSION``: 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 . + + - ``CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES``: The maximum size in + bytes of dynamically-allocated shared memory. + + - ``CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT``: Preferred shared + memory-L1 cache split ratio in percent of total shared memory. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET``: If this attribute is set, + the kernel must launch with a valid cluster size specified. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH``: The required cluster width + in blocks. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT``: The required cluster + height in blocks. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH``: The required cluster depth + in blocks. + + - ``CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED``: 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. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE``: The block + scheduling policy of a function. The value type is + ``CUclusterSchedulingPolicy``. + + With a few execeptions, function attributes may also be queried on unloaded + function handles returned from ``cuModuleEnumerateFunctions``. + ``CUDA_ERROR_FUNCTION_NOT_LOADED`` 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``. ``cuFuncLoad`` may be + called to explicitly load a function before querying the following + attributes that require the function to be loaded:. + + - ``CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK``. + + - ``CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES``. + + - ``CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES``. + + Args: + attrib (FunctionAttribute): Attribute requested. + hfunc (intptr_t): Function to query attribute of. + + Returns: + int: Returned attribute value. + + .. seealso:: `cuFuncGetAttribute` + """ + cdef int pi + with nogil: + __status__ = cuFuncGetAttribute(&pi, attrib, hfunc) + check_status(__status__) + return pi + + +cpdef func_set_attribute(intptr_t hfunc, int attrib, int value): + """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 CUDA_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 (CUDA_ERROR_INVALID_VALUE). + + Supported attributes for the cuFuncSetAttribute call are:. + + - ``CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES``: This maximum size in + bytes of dynamically-allocated shared memory. The value should contain the + requested maximum size of dynamically-allocated shared memory. The sum of + this value and the function attribute + ``CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES`` cannot exceed the device attribute + ``CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN``. The maximal size + of requestable dynamic shared memory may differ by GPU architecture. + + - ``CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT``: 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. See ``CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR`` + This is only a hint, and the driver can choose a different ratio if + required to execute the function. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH``: The required cluster width + in blocks. The width, height, and depth values must either all be 0 or all + be positive. The validity of the cluster dimensions is checked at launch + time. If the value is set during compile time, it cannot be set at runtime. + Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT``: The required cluster + height in blocks. The width, height, and depth values must either all be 0 + or all be positive. The validity of the cluster dimensions is checked at + launch time. If the value is set during compile time, it cannot be set at + runtime. Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH``: The required cluster depth + in blocks. The width, height, and depth values must either all be 0 or all + be positive. The validity of the cluster dimensions is checked at launch + time. If the value is set during compile time, it cannot be set at runtime. + Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED. + + - ``CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED``: Indicates + whether the function can be launched with non-portable cluster size. 1 is + allowed, 0 is disallowed. + + - ``CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE``: The block + scheduling policy of a function. The value type is + ``CUclusterSchedulingPolicy``. + + Args: + hfunc (intptr_t): Function to query attribute of. + attrib (FunctionAttribute): Attribute requested. + value (int): The value to set. + + .. seealso:: `cuFuncSetAttribute` + """ + with nogil: + __status__ = cuFuncSetAttribute(hfunc, attrib, value) + check_status(__status__) + + +cpdef func_set_cache_config(intptr_t hfunc, int config): + """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 :func:`ctx_set_cache_config` will be overridden by + this per-function setting unless the per-function setting is + ``CU_FUNC_CACHE_PREFER_NONE``. 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:. + + - ``CU_FUNC_CACHE_PREFER_NONE``: no preference for shared memory or L1 + (default). + + - ``CU_FUNC_CACHE_PREFER_SHARED``: prefer larger shared memory and smaller + L1 cache. + + - ``CU_FUNC_CACHE_PREFER_L1``: prefer larger L1 cache and smaller shared + memory. + + - ``CU_FUNC_CACHE_PREFER_EQUAL``: prefer equal sized L1 cache and shared + memory. + + Args: + hfunc (intptr_t): Kernel to configure cache for. + config (FuncCache): Requested cache configuration. + + .. seealso:: `cuFuncSetCacheConfig` + """ + with nogil: + __status__ = cuFuncSetCacheConfig(hfunc, config) + check_status(__status__) + + +cpdef intptr_t func_get_module(intptr_t hfunc) except? 0: + """Returns a module handle. + + Returns in ``*hmod`` 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 :func:`module_unload` on that module will result in + undefined behavior. + + Args: + hfunc (intptr_t): Function to retrieve module for. + + Returns: + intptr_t: Returned module handle. + + .. seealso:: `cuFuncGetModule` + """ + cdef CUmodule hmod + with nogil: + __status__ = cuFuncGetModule(&hmod, hfunc) + check_status(__status__) + return hmod + + +cpdef tuple func_get_param_info(intptr_t func, size_t param_index): + """Returns the offset and size of a kernel parameter in the device-side parameter layout. + + Queries the kernel parameter at ``param_index`` into ``func's`` list of + parameters, and returns in ``param_offset`` and ``param_size`` 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()``. ``param_index`` must be less than + the number of parameters that ``func`` takes. ``param_size`` can be set to + NULL if only the parameter offset is desired. + + Args: + func (intptr_t): The function to query. + param_index (size_t): The parameter index to query. + + Returns: + A 2-tuple containing: + + - size_t: Returns the offset into the device-side parameter + layout at which the parameter resides. + - size_t: Optionally returns the size of the parameter in the + device-side parameter layout. + + .. seealso:: `cuFuncGetParamInfo` + """ + cdef size_t param_offset + cdef size_t param_size + with nogil: + __status__ = cuFuncGetParamInfo(func, param_index, ¶m_offset, ¶m_size) + check_status(__status__) + return (param_offset, param_size) + + +cpdef int func_is_loaded(intptr_t function) except? -1: + """Returns if the function is loaded. + + Returns in ``state`` the loading state of ``function``. + + Args: + function (intptr_t): the function to check. + + Returns: + int: returned loading state. + + .. seealso:: `cuFuncIsLoaded` + """ + cdef CUfunctionLoadingState state + with nogil: + __status__ = cuFuncIsLoaded(&state, function) + check_status(__status__) + return state + + +cpdef func_load(intptr_t function): + """Loads a function. + + Finalizes function loading for ``function``. Calling this API with a fully + loaded function has no effect. + + Args: + function (intptr_t): the function to load. + + .. seealso:: `cuFuncLoad` + """ + with nogil: + __status__ = cuFuncLoad(function) + check_status(__status__) + + +cpdef launch_cooperative_kernel_multi_device(launch_params_list, unsigned int num_devices, unsigned int flags): + """Launches CUDA functions on multiple devices where thread blocks can cooperate and synchronize as they execute. + + [Deprecated]. + + Invokes kernels as specified in the ``launch_params_list`` 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 ``num_devices``. + + 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 + ``CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH``. + + 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 + ``cuStreamCreate`` or ``cuStreamCreateWithPriority``. 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 + ``cuOccupancyMaxActiveBlocksPerMultiprocessor`` (or + ``cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags``) times the number + of multiprocessors as specified by the device attribute + ``CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT``. 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. + + The ``CUDA_LAUNCH_PARAMS`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``CUDA_LAUNCH_PARAMS.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 ``CUkernel`` by querying the + handle using :func:`library_get_kernel` and then casting to ``CUfunction``. + In this case, the context to launch the kernel on be taken from the + specified stream ``CUDA_LAUNCH_PARAMS.hStream``. + + - ``CUDA_LAUNCH_PARAMS.gridDimX`` is the width of the grid in blocks. This + must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.gridDimY`` is the height of the grid in blocks. This + must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.gridDimZ`` is the depth of the grid in blocks. This + must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.blockDimX`` is the X dimension of each thread block. + This must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.blockDimX`` is the Y dimension of each thread block. + This must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.blockDimZ`` is the Z dimension of each thread block. + This must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.sharedMemBytes`` is the dynamic shared-memory size + per thread block in bytes. This must match across all kernels launched. + + - ``CUDA_LAUNCH_PARAMS.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 ``CUDA_LAUNCH_PARAMS.function``. + + - ``CUDA_LAUNCH_PARAMS.kernelParams`` is an array of pointers to kernel + parameters. If ``CUDA_LAUNCH_PARAMS.function`` has N parameters, then + ``CUDA_LAUNCH_PARAMS.kernelParams`` needs to be an array of N pointers. + Each of ``CUDA_LAUNCH_PARAMS.kernelParams``[0] through + ``CUDA_LAUNCH_PARAMS.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 :func:`launch_cooperative_kernel_multi_device` sets persistent + function state that is the same as function state set through + ``cuLaunchKernel`` API when called individually for each element in + ``launch_params_list``. + + When kernels are launched via + :func:`launch_cooperative_kernel_multi_device`, the previous block shape, + shared size and parameter info associated with each + ``CUDA_LAUNCH_PARAMS.function`` in ``launch_params_list`` is overwritten. + + Note that to use :func:`launch_cooperative_kernel_multi_device`, 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 + :func:`launch_cooperative_kernel_multi_device` will return + ``CUDA_ERROR_INVALID_IMAGE``. + + Args: + launch_params_list (intptr_t): List of launch parameters, one + per device. + num_devices (unsigned int): Size of the ``launch_params_list`` + array. + flags (unsigned int): Flags to control launch behavior. + + .. seealso:: `cuLaunchCooperativeKernelMultiDevice` + """ + cdef intptr_t _launch_params_list_ptr_ = int(launch_params_list) + with nogil: + __status__ = cuLaunchCooperativeKernelMultiDevice(_launch_params_list_ptr_, num_devices, flags) + check_status(__status__) + + +cpdef launch_host_func(intptr_t h_stream, intptr_t fn, intptr_t user_data): + """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 ``CUDA_ERROR_NOT_PERMITTED``, 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 ``cuStreamAddCallback``, the function will not be + called in the event of an error in the CUDA context. + + Args: + h_stream (intptr_t): Stream to enqueue function call in. + fn (intptr_t): The function to call once preceding stream + operations are complete. + user_data (intptr_t): User-specified data to be passed to the + function. + + .. seealso:: `cuLaunchHostFunc` + """ + with nogil: + __status__ = cuLaunchHostFunc(h_stream, fn, user_data) + check_status(__status__) + + +cpdef func_set_block_shape(intptr_t hfunc, int x, int y, int z): + """Sets the block-dimensions for the function. + + [Deprecated]. + + Specifies the ``x``, ``y``, and ``z`` dimensions of the thread blocks that + are created when the kernel given by ``hfunc`` is launched. + + Args: + hfunc (intptr_t): Kernel to specify dimensions of. + x (int): X dimension. + y (int): Y dimension. + z (int): Z dimension. + + .. seealso:: `cuFuncSetBlockShape` + """ + with nogil: + __status__ = cuFuncSetBlockShape(hfunc, x, y, z) + check_status(__status__) + + +cpdef func_set_shared_size(intptr_t hfunc, unsigned int bytes): + """Sets the dynamic shared-memory size for the function. + + [Deprecated]. + + Sets through ``numbytes`` the amount of dynamic shared memory that will be + available to each thread block when the kernel given by ``hfunc`` is + launched. + + Args: + hfunc (intptr_t): Kernel to specify dynamic shared-memory size + for. + bytes (unsigned int): Dynamic shared-memory size per thread in + bytes. + + .. seealso:: `cuFuncSetSharedSize` + """ + with nogil: + __status__ = cuFuncSetSharedSize(hfunc, bytes) + check_status(__status__) + + +cpdef param_set_size(intptr_t hfunc, unsigned int numbytes): + """Sets the parameter size for the function. + + [Deprecated]. + + Sets through ``numbytes`` the total size in bytes needed by the function + parameters of the kernel corresponding to ``hfunc``. + + Args: + hfunc (intptr_t): Kernel to set parameter size for. + numbytes (unsigned int): Size of parameter list in bytes. + + .. seealso:: `cuParamSetSize` + """ + with nogil: + __status__ = cuParamSetSize(hfunc, numbytes) + check_status(__status__) + + +cpdef param_seti(intptr_t hfunc, int offset, unsigned int value): + """Adds an integer parameter to the function's argument list. + + [Deprecated]. + + Sets an integer parameter that will be specified the next time the kernel + corresponding to ``hfunc`` will be invoked. ``offset`` is a byte offset. + + Args: + hfunc (intptr_t): Kernel to add parameter to. + offset (int): Offset to add parameter to argument list. + value (unsigned int): Value of parameter. + + .. seealso:: `cuParamSeti` + """ + with nogil: + __status__ = cuParamSeti(hfunc, offset, value) + check_status(__status__) + + +cpdef param_setf(intptr_t hfunc, int offset, float value): + """Adds a floating-point parameter to the function's argument list. + + [Deprecated]. + + 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. + + Args: + hfunc (intptr_t): Kernel to add parameter to. + offset (int): Offset to add parameter to argument list. + value (float): Value of parameter. + + .. seealso:: `cuParamSetf` + """ + with nogil: + __status__ = cuParamSetf(hfunc, offset, value) + check_status(__status__) + + +cpdef param_setv(intptr_t hfunc, int offset, intptr_t ptr, unsigned int numbytes): + """Adds arbitrary data to the function's argument list. + + [Deprecated]. + + 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. + + Args: + hfunc (intptr_t): Kernel to add data to. + offset (int): Offset to add data to argument list. + ptr (intptr_t): Pointer to arbitrary data. + numbytes (unsigned int): Size of data to copy in bytes. + + .. seealso:: `cuParamSetv` + """ + with nogil: + __status__ = cuParamSetv(hfunc, offset, ptr, numbytes) + check_status(__status__) + + +cpdef launch(intptr_t f): + """Launches a CUDA function. + + [Deprecated]. + + 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 + :func:`func_set_block_shape`. + + The block shape, dynamic shared memory size, and parameter information must + be set using :func:`func_set_block_shape`, :func:`func_set_shared_size`, + :func:`param_set_size`, :func:`param_seti`, :func:`param_setf`, and + :func:`param_setv` prior to calling this function. + + Launching a function via :func:`launch_kernel` invalidates the function's + block shape, dynamic shared memory size, and parameter information. After + launching via cuLaunchKernel, this state must be re-initialized prior to + calling this function. Failure to do so results in undefined behavior. + + Args: + f (intptr_t): Kernel to launch. + + .. seealso:: `cuLaunch` + """ + with nogil: + __status__ = cuLaunch(f) + check_status(__status__) + + +cpdef launch_grid(intptr_t f, int grid_width, int grid_height): + """Launches a CUDA function. + + [Deprecated]. + + Invokes the kernel ``f`` on a ``grid_width`` x ``grid_height`` grid of + blocks. Each block contains the number of threads specified by a previous + call to :func:`func_set_block_shape`. + + The block shape, dynamic shared memory size, and parameter information must + be set using :func:`func_set_block_shape`, :func:`func_set_shared_size`, + :func:`param_set_size`, :func:`param_seti`, :func:`param_setf`, and + :func:`param_setv` prior to calling this function. + + Launching a function via :func:`launch_kernel` invalidates the function's + block shape, dynamic shared memory size, and parameter information. After + launching via cuLaunchKernel, this state must be re-initialized prior to + calling this function. Failure to do so results in undefined behavior. + + Args: + f (intptr_t): Kernel to launch. + grid_width (int): Width of grid in blocks. + grid_height (int): Height of grid in blocks. + + .. seealso:: `cuLaunchGrid` + """ + with nogil: + __status__ = cuLaunchGrid(f, grid_width, grid_height) + check_status(__status__) + + +cpdef launch_grid_async(intptr_t f, int grid_width, int grid_height, intptr_t h_stream): + """Launches a CUDA function. + + [Deprecated]. + + Invokes the kernel ``f`` on a ``grid_width`` x ``grid_height`` grid of + blocks. Each block contains the number of threads specified by a previous + call to :func:`func_set_block_shape`. + + The block shape, dynamic shared memory size, and parameter information must + be set using :func:`func_set_block_shape`, :func:`func_set_shared_size`, + :func:`param_set_size`, :func:`param_seti`, :func:`param_setf`, and + :func:`param_setv` prior to calling this function. + + Launching a function via :func:`launch_kernel` invalidates the function's + block shape, dynamic shared memory size, and parameter information. After + launching via cuLaunchKernel, this state must be re-initialized prior to + calling this function. Failure to do so results in undefined behavior. + + \note_null_stream. + + Args: + f (intptr_t): Kernel to launch. + grid_width (int): Width of grid in blocks. + grid_height (int): Height of grid in blocks. + h_stream (intptr_t): Stream identifier. + + .. 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. + + .. seealso:: `cuLaunchGridAsync` + """ + with nogil: + __status__ = cuLaunchGridAsync(f, grid_width, grid_height, h_stream) + check_status(__status__) + + +cpdef param_set_tex_ref(intptr_t hfunc, int texunit, intptr_t h_tex_ref): + """Adds a texture-reference to the function's argument list. + + [Deprecated]. + + Makes the CUDA array or linear memory bound to the texture reference + ``h_tex_ref`` available to a device program as a texture. In this version + of CUDA, the texture-reference must be obtained via + :func:`module_get_tex_ref` and the ``texunit`` parameter must be set to + ``CU_PARAM_TR_DEFAULT``. + + Args: + hfunc (intptr_t): Kernel to add texture-reference to. + texunit (int): Texture unit (must be ``CU_PARAM_TR_DEFAULT``). + h_tex_ref (intptr_t): Texture-reference to add to argument + list. + + .. seealso:: `cuParamSetTexRef` + """ + with nogil: + __status__ = cuParamSetTexRef(hfunc, texunit, h_tex_ref) + check_status(__status__) + + +cpdef func_set_shared_mem_config(intptr_t hfunc, int config): + """Sets the shared memory configuration for a device function. + + [Deprecated]. + + 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 + ``cuFuncSetSharedMemConfig`` will override the context wide setting set + with ``cuCtxSetSharedMemConfig``. + + 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:. + + - ``CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE``: use the context's shared + memory configuration when launching this function. + + - ``CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE``: set shared memory bank + width to be natively four bytes when launching this function. + + - ``CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE``: set shared memory bank + width to be natively eight bytes when launching this function. + + Args: + hfunc (intptr_t): kernel to be given a shared memory config. + config (Sharedconfig): requested shared memory configuration. + + .. seealso:: `cuFuncSetSharedMemConfig` + """ + with nogil: + __status__ = cuFuncSetSharedMemConfig(hfunc, config) + check_status(__status__) + + +cpdef intptr_t graph_create(unsigned int flags) except? 0: + """Creates a graph. + + Creates an empty graph, which is returned via ``ph_graph``. + + Args: + flags (unsigned int): Graph creation flags, must be 0. + + Returns: + intptr_t: Returns newly created graph. + + .. seealso:: `cuGraphCreate` + """ + cdef CUgraph ph_graph + with nogil: + __status__ = cuGraphCreate(&ph_graph, flags) + check_status(__status__) + return ph_graph + + +cpdef intptr_t graph_add_kernel_node_v2(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates a kernel execution node and adds it to a graph. + + Creates a new kernel execution node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + The ``CUDA_KERNEL_NODE_PARAMS`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + 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:. + + 1) 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. + + 2) 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 ``CUDA_ERROR_INVALID_VALUE`` will be returned if kernel + parameters are specified with both ``kernelParams`` and ``extra`` (i.e. + both ``kernelParams`` and ``extra`` are non-NULL). + ``CUDA_ERROR_INVALID_VALUE`` 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the GPU execution node. + + Returns: + intptr_t: Returns newly created node. + + .. 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. + + .. seealso:: `cuGraphAddKernelNode_v2` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddKernelNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_kernel_node_get_params_v2(intptr_t h_node, node_params): + """Returns a kernel node's parameters. + + Returns the parameters of kernel node ``h_node`` in ``node_params``. The + ``kernelParams`` or ``extra`` array returned in ``node_params``, 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 ``cuGraphKernelNodeSetParams`` 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. + + Args: + h_node (intptr_t): Node to get the parameters for. + node_params (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphKernelNodeGetParams_v2` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphKernelNodeGetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_kernel_node_set_params_v2(intptr_t h_node, node_params): + """Sets a kernel node's parameters. + + Sets the parameters of kernel node ``h_node`` to ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphKernelNodeSetParams_v2` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphKernelNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_memcpy_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, copy_params, intptr_t ctx) except? 0: + """Creates a memcpy node and adds it to a graph. + + Creates a new memcpy node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies``. It is + possible for ``num_dependencies`` 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 in + ``ph_graph_node``. + + When the graph is launched, the node will perform the memcpy described by + ``copy_params``. See ``cuMemcpy3D()`` 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 ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. + If one or more of the operands refer to managed memory, then using the + memory type ``CU_MEMORYTYPE_UNIFIED`` 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + copy_params (intptr_t): Parameters for the memory copy. + ctx (intptr_t): Context on which to run the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddMemcpyNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _copy_params_ptr_ = int(copy_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemcpyNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _copy_params_ptr_, ctx) + check_status(__status__) + return ph_graph_node + + +cpdef graph_memcpy_node_get_params(intptr_t h_node, node_params): + """Returns a memcpy node's parameters. + + Returns the parameters of memcpy node ``h_node`` in ``node_params``. + + Args: + h_node (intptr_t): Node to get the parameters for. + node_params (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphMemcpyNodeGetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphMemcpyNodeGetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_memcpy_node_set_params(intptr_t h_node, node_params): + """Sets a memcpy node's parameters. + + Sets the parameters of memcpy node ``h_node`` to ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphMemcpyNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphMemcpyNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_memset_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, memset_params, intptr_t ctx) except? 0: + """Creates a memset node and adds it to a graph. + + Creates a new memset node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies``. It is + possible for ``num_dependencies`` 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 in + ``ph_graph_node``. + + The element size must be 1, 2, or 4 bytes. When the graph is launched, the + node will perform the memset described by ``memset_params``. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + memset_params (intptr_t): Parameters for the memory set. + ctx (intptr_t): Context on which to run the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddMemsetNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _memset_params_ptr_ = int(memset_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemsetNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _memset_params_ptr_, ctx) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_memset_node_get_params(intptr_t h_node): + """Returns a memset node's parameters. + + Returns the parameters of memset node ``h_node`` in ``node_params``. + + Args: + h_node (intptr_t): Node to get the parameters for. + + Returns: + CUDA_MEMSET_NODE_PARAMS_v1: Pointer to return the parameters. + + .. seealso:: `cuGraphMemsetNodeGetParams` + """ + cdef MemsetNodeParams_v1 node_params_py = MemsetNodeParams_v1() + cdef CUDA_MEMSET_NODE_PARAMS *node_params = (node_params_py._get_ptr()) + with nogil: + __status__ = cuGraphMemsetNodeGetParams(h_node, node_params) + check_status(__status__) + return node_params_py + + +cpdef graph_memset_node_set_params(intptr_t h_node, node_params): + """Sets a memset node's parameters. + + Sets the parameters of memset node ``h_node`` to ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphMemsetNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphMemsetNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_host_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates a host execution node and adds it to a graph. + + Creates a new CPU execution node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + When the graph is launched, the node will invoke the specified CPU + function. Host nodes are not supported under MPS with pre-Volta GPUs. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the host node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddHostNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddHostNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_host_node_get_params(intptr_t h_node, node_params): + """Returns a host node's parameters. + + Returns the parameters of host node ``h_node`` in ``node_params``. + + Args: + h_node (intptr_t): Node to get the parameters for. + node_params (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphHostNodeGetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphHostNodeGetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_host_node_set_params(intptr_t h_node, node_params): + """Sets a host node's parameters. + + Sets the parameters of host node ``h_node`` to ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphHostNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphHostNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_child_graph_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t child_graph) except? 0: + """Creates a child graph node and adds it to a graph. + + Creates a new node which executes an embedded graph, and adds it to + ``h_graph`` with ``num_dependencies`` dependencies specified via + ``dependencies``. It is possible for ``num_dependencies`` 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 + in ``ph_graph_node``. + + If ``child_graph`` 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + child_graph (intptr_t): The graph to clone into this node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddChildGraphNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddChildGraphNode(&ph_graph_node, h_graph, dependencies, num_dependencies, child_graph) + check_status(__status__) + return ph_graph_node + + +cpdef intptr_t graph_child_graph_node_get_graph(intptr_t h_node) except? 0: + """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. + + Args: + h_node (intptr_t): Node to get the embedded graph for. + + Returns: + intptr_t: Location to store a handle to the graph. + + .. seealso:: `cuGraphChildGraphNodeGetGraph` + """ + cdef CUgraph ph_graph + with nogil: + __status__ = cuGraphChildGraphNodeGetGraph(h_node, &ph_graph) + check_status(__status__) + return ph_graph + + +cpdef intptr_t graph_add_empty_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies) except? 0: + """Creates an empty node and adds it to a graph. + + Creates a new node which performs no operation, and adds it to ``h_graph`` + with ``num_dependencies`` dependencies specified via ``dependencies``. It + is possible for ``num_dependencies`` 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 in + ``ph_graph_node``. + + 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEmptyNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEmptyNode(&ph_graph_node, h_graph, dependencies, num_dependencies) + check_status(__status__) + return ph_graph_node + + +cpdef intptr_t graph_add_event_record_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t event) except? 0: + """Creates an event record node and adds it to a graph. + + Creates a new event record node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and event + specified in ``event``. It is possible for ``num_dependencies`` 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 in ``ph_graph_node``. + + Each launch of the graph will record ``event`` to capture execution of the + node's dependencies. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + event (intptr_t): Event for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEventRecordNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEventRecordNode(&ph_graph_node, h_graph, dependencies, num_dependencies, event) + check_status(__status__) + return ph_graph_node + + +cpdef intptr_t graph_event_record_node_get_event(intptr_t h_node) except? 0: + """Returns the event associated with an event record node. + + Returns the event of event record node ``h_node`` in ``event_out``. + + Args: + h_node (intptr_t): Node to get the event for. + + Returns: + intptr_t: Pointer to return the event. + + .. seealso:: `cuGraphEventRecordNodeGetEvent` + """ + cdef CUevent event_out + with nogil: + __status__ = cuGraphEventRecordNodeGetEvent(h_node, &event_out) + check_status(__status__) + return event_out + + +cpdef graph_event_record_node_set_event(intptr_t h_node, intptr_t event): + """Sets an event record node's event. + + Sets the event of event record node ``h_node`` to ``event``. + + Args: + h_node (intptr_t): Node to set the event for. + event (intptr_t): Event to use. + + .. seealso:: `cuGraphEventRecordNodeSetEvent` + """ + with nogil: + __status__ = cuGraphEventRecordNodeSetEvent(h_node, event) + check_status(__status__) + + +cpdef intptr_t graph_add_event_wait_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, intptr_t event) except? 0: + """Creates an event wait node and adds it to a graph. + + Creates a new event wait node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and event + specified in ``event``. It is possible for ``num_dependencies`` 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 in ``ph_graph_node``. + + The graph node will wait for all work captured in ``event``. See + :func:`event_record` for details on what is captured by an event. ``event`` + may be from a different context or device than the launch stream. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + event (intptr_t): Event for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEventWaitNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEventWaitNode(&ph_graph_node, h_graph, dependencies, num_dependencies, event) + check_status(__status__) + return ph_graph_node + + +cpdef intptr_t graph_event_wait_node_get_event(intptr_t h_node) except? 0: + """Returns the event associated with an event wait node. + + Returns the event of event wait node ``h_node`` in ``event_out``. + + Args: + h_node (intptr_t): Node to get the event for. + + Returns: + intptr_t: Pointer to return the event. + + .. seealso:: `cuGraphEventWaitNodeGetEvent` + """ + cdef CUevent event_out + with nogil: + __status__ = cuGraphEventWaitNodeGetEvent(h_node, &event_out) + check_status(__status__) + return event_out + + +cpdef graph_event_wait_node_set_event(intptr_t h_node, intptr_t event): + """Sets an event wait node's event. + + Sets the event of event wait node ``h_node`` to ``event``. + + Args: + h_node (intptr_t): Node to set the event for. + event (intptr_t): Event to use. + + .. seealso:: `cuGraphEventWaitNodeSetEvent` + """ + with nogil: + __status__ = cuGraphEventWaitNodeSetEvent(h_node, event) + check_status(__status__) + + +cpdef intptr_t graph_add_external_semaphores_signal_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates an external semaphore signal node and adds it to a graph. + + Creates a new external semaphore signal node and adds it to ``h_graph`` + with ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddExternalSemaphoresSignalNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddExternalSemaphoresSignalNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_external_semaphores_signal_node_get_params(intptr_t h_node, params_out): + """Returns an external semaphore signal node's parameters. + + Returns the parameters of an external semaphore signal node ``h_node`` in + ``params_out``. The ``extSemArray`` and ``paramsArray`` returned in + ``params_out``, 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 ``cuGraphExternalSemaphoresSignalNodeSetParams`` to + update the parameters of this node. + + Args: + h_node (intptr_t): Node to get the parameters for. + params_out (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphExternalSemaphoresSignalNodeGetParams` + """ + cdef intptr_t _params_out_ptr_ = int(params_out) + with nogil: + __status__ = cuGraphExternalSemaphoresSignalNodeGetParams(h_node, _params_out_ptr_) + check_status(__status__) + + +cpdef graph_external_semaphores_signal_node_set_params(intptr_t h_node, node_params): + """Sets an external semaphore signal node's parameters. + + Sets the parameters of an external semaphore signal node ``h_node`` to + ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphExternalSemaphoresSignalNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExternalSemaphoresSignalNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_external_semaphores_wait_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates an external semaphore wait node and adds it to a graph. + + Creates a new external semaphore wait node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddExternalSemaphoresWaitNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddExternalSemaphoresWaitNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_external_semaphores_wait_node_get_params(intptr_t h_node, params_out): + """Returns an external semaphore wait node's parameters. + + Returns the parameters of an external semaphore wait node ``h_node`` in + ``params_out``. The ``extSemArray`` and ``paramsArray`` returned in + ``params_out``, 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 ``cuGraphExternalSemaphoresSignalNodeSetParams`` to + update the parameters of this node. + + Args: + h_node (intptr_t): Node to get the parameters for. + params_out (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphExternalSemaphoresWaitNodeGetParams` + """ + cdef intptr_t _params_out_ptr_ = int(params_out) + with nogil: + __status__ = cuGraphExternalSemaphoresWaitNodeGetParams(h_node, _params_out_ptr_) + check_status(__status__) + + +cpdef graph_external_semaphores_wait_node_set_params(intptr_t h_node, node_params): + """Sets an external semaphore wait node's parameters. + + Sets the parameters of an external semaphore wait node ``h_node`` to + ``node_params``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphExternalSemaphoresWaitNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExternalSemaphoresWaitNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_batch_mem_op_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates a batch memory operation node and adds it to a graph. + + Creates a new batch memory operation node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + When the node is added, the paramArray inside ``node_params`` is copied and + therefore it can be freed after the call returns. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the node. + + Returns: + intptr_t: Returns newly created node. + + .. note:: + 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. + + .. seealso:: `cuGraphAddBatchMemOpNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddBatchMemOpNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_batch_mem_op_node_get_params(intptr_t h_node, node_params_out): + """Returns a batch mem op node's parameters. + + Returns the parameters of batch mem op node ``h_node`` in + ``node_params_out``. The ``paramArray`` returned in ``node_params_out`` 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 + ``cuGraphBatchMemOpNodeSetParams`` to update the parameters of this node. + + Args: + h_node (intptr_t): Node to get the parameters for. + node_params_out (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphBatchMemOpNodeGetParams` + """ + cdef intptr_t _node_params_out_ptr_ = int(node_params_out) + with nogil: + __status__ = cuGraphBatchMemOpNodeGetParams(h_node, _node_params_out_ptr_) + check_status(__status__) + + +cpdef graph_batch_mem_op_node_set_params(intptr_t h_node, node_params): + """Sets a batch mem op node's parameters. + + Sets the parameters of batch mem op node ``h_node`` to ``node_params``. + + The paramArray inside ``node_params`` is copied and therefore it can be + freed after the call returns. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphBatchMemOpNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphBatchMemOpNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_exec_batch_mem_op_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params): + """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 + ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` 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. CU_STREAM_WAIT_VALUE_FLUSH 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. + + ``h_node`` must not have been removed from the original graph. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + The paramArray inside ``node_params`` is copied and therefore it can be + freed after the call returns. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Batch mem op node from the graph from which + graphExec was instantiated. + node_params (intptr_t): Updated Parameters to set. + + .. seealso:: `cuGraphExecBatchMemOpNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecBatchMemOpNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_mem_alloc_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, node_params) except? 0: + """Creates an allocation node and adds it to a graph. + + Creates a new allocation node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``node_params``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + When ``cuGraphAddMemAllocNode`` creates an allocation node, it returns the + address of the allocation in ``node_params.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 + ``cuGraphAddMemFreeNode``, 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:. + + - passing the allocation to ``cuMemFreeAsync`` or ``cuMemFree``;. + + - launching a graph with a free node for that allocation; or. + + - specifying ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH`` during + instantiation, which makes each launch behave as though it called + ``cuMemFreeAsync`` for every unfreed allocation. + + 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Parameters for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddMemAllocNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemAllocNode(&ph_graph_node, h_graph, dependencies, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_mem_alloc_node_get_params(intptr_t h_node, params_out): + """Returns a memory alloc node's parameters. + + Returns the parameters of a memory alloc node ``h_node`` in ``params_out``. + The ``poolProps`` and ``accessDescs`` returned in ``params_out``, are owned + by the node. This memory remains valid until the node is destroyed. The + returned parameters must not be modified. + + Args: + h_node (intptr_t): Node to get the parameters for. + params_out (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphMemAllocNodeGetParams` + """ + cdef intptr_t _params_out_ptr_ = int(params_out) + with nogil: + __status__ = cuGraphMemAllocNodeGetParams(h_node, _params_out_ptr_) + check_status(__status__) + + +cpdef intptr_t graph_add_mem_free_node(intptr_t h_graph, intptr_t dependencies, size_t num_dependencies, unsigned long long dptr) except? 0: + """Creates a memory free node and adds it to a graph. + + Creates a new memory free node and adds it to ``h_graph`` with + ``num_dependencies`` dependencies specified via ``dependencies`` and + arguments specified in ``nodeParams``. It is possible for + ``num_dependencies`` 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 in ``ph_graph_node``. + + ``cuGraphAddMemFreeNode`` will return ``CUDA_ERROR_INVALID_VALUE`` 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. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + num_dependencies (size_t): Number of dependencies. + dptr (unsigned long long): Address of memory to free. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddMemFreeNode` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemFreeNode(&ph_graph_node, h_graph, dependencies, num_dependencies, dptr) + check_status(__status__) + return ph_graph_node + + +cpdef unsigned long long graph_mem_free_node_get_params(intptr_t h_node) except? 0: + """Returns a memory free node's parameters. + + Returns the address of a memory free node ``h_node`` in ``dptr_out``. + + Args: + h_node (intptr_t): Node to get the parameters for. + + Returns: + unsigned long long: Pointer to return the device address. + + .. seealso:: `cuGraphMemFreeNodeGetParams` + """ + cdef CUdeviceptr dptr_out + with nogil: + __status__ = cuGraphMemFreeNodeGetParams(h_node, &dptr_out) + check_status(__status__) + return dptr_out + + +cpdef device_graph_mem_trim(int device): + """Free 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. + + Args: + device (int): The device for which cached memory should be + freed. + + .. seealso:: `cuDeviceGraphMemTrim` + """ + with nogil: + __status__ = cuDeviceGraphMemTrim(device) + check_status(__status__) + + +cpdef device_get_graph_mem_attribute(int device, int attr, intptr_t value): + """Query asynchronous allocation attributes related to graphs. + + Valid attributes are:. + + - ``CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT``: Amount of memory, in bytes, + currently associated with graphs. + + - ``CU_GRAPH_MEM_ATTR_USED_MEM_HIGH``: High watermark of memory, in bytes, + associated with graphs since the last time it was reset. High watermark can + only be reset to zero. + + - ``CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT``: Amount of memory, in bytes, + currently allocated for use by the CUDA graphs asynchronous allocator. + + - ``CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH``: High watermark of memory, in + bytes, currently allocated for use by the CUDA graphs asynchronous + allocator. + + Args: + device (int): Specifies the scope of the query. + attr (GraphMemAttribute): attribute to get. + value (intptr_t): retrieved value. + + .. seealso:: `cuDeviceGetGraphMemAttribute` + """ + with nogil: + __status__ = cuDeviceGetGraphMemAttribute(device, attr, value) + check_status(__status__) + + +cpdef device_set_graph_mem_attribute(int device, int attr, intptr_t value): + """Set asynchronous allocation attributes related to graphs. + + Valid attributes are:. + + - ``CU_GRAPH_MEM_ATTR_USED_MEM_HIGH``: High watermark of memory, in bytes, + associated with graphs since the last time it was reset. High watermark can + only be reset to zero. + + - ``CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH``: High watermark of memory, in + bytes, currently allocated for use by the CUDA graphs asynchronous + allocator. + + Args: + device (int): Specifies the scope of the query. + attr (GraphMemAttribute): attribute to get. + value (intptr_t): pointer to value to set. + + .. seealso:: `cuDeviceSetGraphMemAttribute` + """ + with nogil: + __status__ = cuDeviceSetGraphMemAttribute(device, attr, value) + check_status(__status__) + + +cpdef intptr_t graph_clone(intptr_t original_graph) except? 0: + """Clones a graph. + + This function creates a copy of ``original_graph`` and returns it in + ``ph_graph_clone``. 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. + + Args: + original_graph (intptr_t): Graph to clone. + + Returns: + intptr_t: Returns newly created cloned graph. + + .. note:: + : Cloning is not supported for graphs which contain memory allocation + nodes, memory free nodes, or conditional nodes. + + .. seealso:: `cuGraphClone` + """ + cdef CUgraph ph_graph_clone + with nogil: + __status__ = cuGraphClone(&ph_graph_clone, original_graph) + check_status(__status__) + return ph_graph_clone + + +cpdef intptr_t graph_node_find_in_clone(intptr_t h_original_node, intptr_t h_cloned_graph) except? 0: + """Finds a cloned version of a node. + + This function returns the node in ``h_cloned_graph`` corresponding to + ``h_original_node`` in the original graph. + + ``h_cloned_graph`` must have been cloned from ``hOriginalGraph`` via + ``cuGraphClone``. ``h_original_node`` must have been in ``hOriginalGraph`` + at the time of the call to ``cuGraphClone``, and the corresponding cloned + node in ``h_cloned_graph`` must not have been removed. The cloned node is + then returned via ``phClonedNode``. + + Args: + h_original_node (intptr_t): Handle to the original node. + h_cloned_graph (intptr_t): Cloned graph to query. + + Returns: + intptr_t: Returns handle to the cloned node. + + .. seealso:: `cuGraphNodeFindInClone` + """ + cdef CUgraphNode ph_node + with nogil: + __status__ = cuGraphNodeFindInClone(&ph_node, h_original_node, h_cloned_graph) + check_status(__status__) + return ph_node + + +cpdef int graph_node_get_type(intptr_t h_node) except? -1: + """Returns a node's type. + + Returns the node type of ``h_node`` in ``typename``. + + Args: + h_node (intptr_t): Node to query. + + Returns: + int: Pointer to return the node type. + + .. seealso:: `cuGraphNodeGetType` + """ + cdef CUgraphNodeType type + with nogil: + __status__ = cuGraphNodeGetType(h_node, &type) + check_status(__status__) + return type + + +cpdef object graph_get_nodes(intptr_t h_graph): + """Returns a graph's nodes. + + Returns a list of ``h_graph's`` nodes. ``nodes`` may be NULL, in which case + this function will return the number of nodes in ``num_nodes``. Otherwise, + ``num_nodes`` entries will be filled in. If ``num_nodes`` 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 + ``num_nodes``. + + Args: + h_graph (intptr_t): Graph to query. + + Returns: + intptr_t: Pointer to return the nodes. + + .. seealso:: `cuGraphGetNodes` + """ + cdef size_t[1] num_nodes = [0] + with nogil: + __status__ = cuGraphGetNodes(h_graph, NULL, num_nodes) + check_status_size(__status__) + cdef object _nodes_alloc_ = _numpy.empty(max(num_nodes[0], 1), dtype=_numpy.intp) + cdef intptr_t _nodes_data_ = _nodes_alloc_.ctypes.data + cdef intptr_t *nodes_ptr = _nodes_data_ + cdef object nodes = _nodes_alloc_[:num_nodes[0]] + if num_nodes[0] != 0: + with nogil: + __status__ = cuGraphGetNodes(h_graph, nodes_ptr, num_nodes) + check_status(__status__) + return nodes + + +cpdef object graph_get_root_nodes(intptr_t h_graph): + """Returns a graph's root nodes. + + Returns a list of ``h_graph's`` root nodes. ``root_nodes`` may be NULL, in + which case this function will return the number of root nodes in + ``num_root_nodes``. Otherwise, ``num_root_nodes`` entries will be filled + in. If ``num_root_nodes`` is higher than the actual number of root nodes, + the remaining entries in ``root_nodes`` will be set to NULL, and the number + of nodes actually obtained will be returned in ``num_root_nodes``. + + Args: + h_graph (intptr_t): Graph to query. + + Returns: + intptr_t: Pointer to return the root nodes. + + .. seealso:: `cuGraphGetRootNodes` + """ + cdef size_t[1] num_root_nodes = [0] + with nogil: + __status__ = cuGraphGetRootNodes(h_graph, NULL, num_root_nodes) + check_status_size(__status__) + cdef object _root_nodes_alloc_ = _numpy.empty(max(num_root_nodes[0], 1), dtype=_numpy.intp) + cdef intptr_t _root_nodes_data_ = _root_nodes_alloc_.ctypes.data + cdef intptr_t *root_nodes_ptr = _root_nodes_data_ + cdef object root_nodes = _root_nodes_alloc_[:num_root_nodes[0]] + if num_root_nodes[0] != 0: + with nogil: + __status__ = cuGraphGetRootNodes(h_graph, root_nodes_ptr, num_root_nodes) + check_status(__status__) + return root_nodes + + +cpdef tuple graph_get_edges_v2(intptr_t h_graph): + """Returns a graph's dependency edges. + + Returns a list of ``h_graph's`` dependency edges. Edges are returned via + corresponding indices in ``from``, ``to`` and ``edge_data``; that is, the + node in ``to``[i] has a dependency on the node in ``from``[i] with data + ``edge_data``[i]. ``from`` and ``to`` may both be NULL, in which case this + function only returns the number of edges in ``num_edges``. Otherwise, + ``num_edges`` entries will be filled in. If ``num_edges`` 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 ``num_edges``. ``edge_data`` may alone be NULL, in which case + the edges must all have default (zeroed) edge data. Attempting a lossy + query via NULL ``edge_data`` will result in ``CUDA_ERROR_LOSSY_QUERY``. If + ``edge_data`` is non-NULL then ``from`` and ``to`` must be as well. + + Args: + h_graph (intptr_t): Graph to get the edges from. + + Returns: + A 3-tuple containing: + + - intptr_t: Location to return edge endpoints. + - intptr_t: Location to return edge endpoints. + - CUgraphEdgeData: Optional location to return edge data. + + .. seealso:: `cuGraphGetEdges_v2` + """ + cdef size_t[1] num_edges = [0] + with nogil: + __status__ = cuGraphGetEdges(h_graph, NULL, NULL, NULL, num_edges) + check_status_size(__status__) + cdef object _from__alloc_ = _numpy.empty(max(num_edges[0], 1), dtype=_numpy.intp) + cdef intptr_t _from__data_ = _from__alloc_.ctypes.data + cdef intptr_t *from__ptr = _from__data_ + cdef object from_ = _from__alloc_[:num_edges[0]] + cdef object _to_alloc_ = _numpy.empty(max(num_edges[0], 1), dtype=_numpy.intp) + cdef intptr_t _to_data_ = _to_alloc_.ctypes.data + cdef intptr_t *to_ptr = _to_data_ + cdef object to = _to_alloc_[:num_edges[0]] + cdef GraphEdgeData edge_data = GraphEdgeData(num_edges[0]) + cdef CUgraphEdgeData *edge_data_ptr = (edge_data._get_ptr()) + if not (num_edges[0] == 0): + with nogil: + __status__ = cuGraphGetEdges(h_graph, from__ptr, to_ptr, edge_data_ptr, num_edges) + check_status(__status__) + return (from_, to, edge_data) + + +cpdef tuple graph_node_get_dependencies_v2(intptr_t h_node): + """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 + ``num_dependencies``. Otherwise, ``num_dependencies`` entries will be + filled in. If ``num_dependencies`` 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 + ``num_dependencies``. + + Note that if an edge has non-zero (non-default) edge data and ``edge_data`` + is NULL, this API will return ``CUDA_ERROR_LOSSY_QUERY``. If ``edge_data`` + is non-NULL, then ``dependencies`` must be as well. + + Args: + h_node (intptr_t): Node to query. + + Returns: + A 2-tuple containing: + + - intptr_t: Pointer to return the dependencies. + - CUgraphEdgeData: Optional array to return edge data for each + dependency. + + .. seealso:: `cuGraphNodeGetDependencies_v2` + """ + cdef size_t[1] num_dependencies = [0] + with nogil: + __status__ = cuGraphNodeGetDependencies(h_node, NULL, NULL, num_dependencies) + check_status_size(__status__) + cdef object _dependencies_alloc_ = _numpy.empty(max(num_dependencies[0], 1), dtype=_numpy.intp) + cdef intptr_t _dependencies_data_ = _dependencies_alloc_.ctypes.data + cdef intptr_t *dependencies_ptr = _dependencies_data_ + cdef object dependencies = _dependencies_alloc_[:num_dependencies[0]] + cdef GraphEdgeData edge_data = GraphEdgeData(num_dependencies[0]) + cdef CUgraphEdgeData *edge_data_ptr = (edge_data._get_ptr()) + if not (num_dependencies[0] == 0): + with nogil: + __status__ = cuGraphNodeGetDependencies(h_node, dependencies_ptr, edge_data_ptr, num_dependencies) + check_status(__status__) + return (dependencies, edge_data) + + +cpdef tuple graph_node_get_dependent_nodes_v2(intptr_t h_node): + """Returns a node's dependent nodes. + + Returns a list of ``node's`` dependent nodes. ``dependent_nodes`` may be + NULL, in which case this function will return the number of dependent nodes + in ``num_dependent_nodes``. Otherwise, ``num_dependent_nodes`` entries will + be filled in. If ``num_dependent_nodes`` is higher than the actual number + of dependent nodes, the remaining entries in ``dependent_nodes`` will be + set to NULL, and the number of nodes actually obtained will be returned in + ``num_dependent_nodes``. + + Note that if an edge has non-zero (non-default) edge data and ``edge_data`` + is NULL, this API will return ``CUDA_ERROR_LOSSY_QUERY``. If ``edge_data`` + is non-NULL, then ``dependent_nodes`` must be as well. + + Args: + h_node (intptr_t): Node to query. + + Returns: + A 2-tuple containing: + + - intptr_t: Pointer to return the dependent nodes. + - CUgraphEdgeData: Optional pointer to return edge data for + dependent nodes. + + .. seealso:: `cuGraphNodeGetDependentNodes_v2` + """ + cdef size_t[1] num_dependent_nodes = [0] + with nogil: + __status__ = cuGraphNodeGetDependentNodes(h_node, NULL, NULL, num_dependent_nodes) + check_status_size(__status__) + cdef object _dependent_nodes_alloc_ = _numpy.empty(max(num_dependent_nodes[0], 1), dtype=_numpy.intp) + cdef intptr_t _dependent_nodes_data_ = _dependent_nodes_alloc_.ctypes.data + cdef intptr_t *dependent_nodes_ptr = _dependent_nodes_data_ + cdef object dependent_nodes = _dependent_nodes_alloc_[:num_dependent_nodes[0]] + cdef GraphEdgeData edge_data = GraphEdgeData(num_dependent_nodes[0]) + cdef CUgraphEdgeData *edge_data_ptr = (edge_data._get_ptr()) + if not (num_dependent_nodes[0] == 0): + with nogil: + __status__ = cuGraphNodeGetDependentNodes(h_node, dependent_nodes_ptr, edge_data_ptr, num_dependent_nodes) + check_status(__status__) + return (dependent_nodes, edge_data) + + +cpdef graph_add_dependencies_v2(intptr_t h_graph, intptr_t from_, intptr_t to, edge_data, size_t num_dependencies): + """Adds dependency edges to a graph. + + The number of dependencies to be added is defined by ``num_dependencies`` + Elements in ``from`` and ``to`` at corresponding indices define a + dependency. Each node in ``from`` and ``to`` must belong to ``h_graph``. + + If ``num_dependencies`` is 0, elements in ``from`` and ``to`` will be + ignored. Specifying an existing dependency will return an error. + + Args: + h_graph (intptr_t): Graph to which dependencies are added. + from_ (intptr_t): Array of nodes that provide the + dependencies. + to (intptr_t): Array of dependent nodes. + edge_data (intptr_t): Optional array of edge data. If NULL, + default (zeroed) edge data is assumed. + num_dependencies (size_t): Number of dependencies to be added. + + .. seealso:: `cuGraphAddDependencies_v2` + """ + cdef CUgraphNode _from__ = from_ + cdef CUgraphNode _to_ = to + cdef intptr_t _edge_data_ptr_ = int(edge_data) + with nogil: + __status__ = cuGraphAddDependencies(h_graph, from_, to, _edge_data_ptr_, num_dependencies) + check_status(__status__) + + +cpdef graph_remove_dependencies_v2(intptr_t h_graph, intptr_t from_, intptr_t to, edge_data, size_t num_dependencies): + """Removes dependency edges from a graph. + + The number of ``dependencies`` to be removed is defined by + ``num_dependencies``. Elements in ``from`` and ``to`` at corresponding + indices define a dependency. Each node in ``from`` and ``to`` must belong + to ``h_graph``. + + If ``num_dependencies`` is 0, elements in ``from`` and ``to`` will be + ignored. Specifying an edge that does not exist in the graph, with data + matching ``edge_data``, results in an error. ``edge_data`` 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. + + Args: + h_graph (intptr_t): Graph from which to remove dependencies. + from_ (intptr_t): Array of nodes that provide the + dependencies. + to (intptr_t): Array of dependent nodes. + edge_data (intptr_t): Optional array of edge data. If NULL, + edge data is assumed to be default (zeroed). + num_dependencies (size_t): Number of dependencies to be + removed. + + .. seealso:: `cuGraphRemoveDependencies_v2` + """ + cdef CUgraphNode _from__ = from_ + cdef CUgraphNode _to_ = to + cdef intptr_t _edge_data_ptr_ = int(edge_data) + with nogil: + __status__ = cuGraphRemoveDependencies(h_graph, from_, to, _edge_data_ptr_, num_dependencies) + check_status(__status__) + + +cpdef graph_destroy_node(intptr_t h_node): + """Remove a node from the graph. + + Removes ``h_node`` from its graph. This operation also severs any + dependencies of other nodes on ``h_node`` 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. + + Args: + h_node (intptr_t): Node to remove. + + .. seealso:: `cuGraphDestroyNode` + """ + with nogil: + __status__ = cuGraphDestroyNode(h_node) + check_status(__status__) + + +cpdef intptr_t graph_instantiate_with_flags(intptr_t h_graph, unsigned long long flags) except? 0: + """Creates an executable graph from a graph. + + Instantiates ``h_graph`` 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 in ``ph_graph_exec``. + + The ``flags`` parameter controls the behavior of instantiation and + subsequent graph launches. Valid flags are:. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH``, which configures a + graph containing memory allocation nodes to automatically free any unfreed + memory allocations before the graph is relaunched. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH``, 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 + ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH``. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY``, 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 ``h_graph`` 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 + ``cuGraphExecDestroy`` will result in an error. The same also applies if + ``h_graph`` contains any device-updatable kernel nodes. + + If ``h_graph`` 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. + + Args: + h_graph (intptr_t): Graph to instantiate. + flags (unsigned long long): Flags to control instantiation. + See ``CUgraphInstantiate_flags``. + + Returns: + intptr_t: Returns instantiated graph. + + .. seealso:: `cuGraphInstantiateWithFlags` + """ + cdef CUgraphExec ph_graph_exec + with nogil: + __status__ = cuGraphInstantiate(&ph_graph_exec, h_graph, flags) + check_status(__status__) + return ph_graph_exec + + +cpdef intptr_t graph_instantiate_with_params(intptr_t h_graph, instantiate_params) except? 0: + """Creates an executable graph from a graph. + + Instantiates ``h_graph`` as an executable graph according to the + ``instantiate_params`` 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 in ``ph_graph_exec``. + + ``instantiate_params`` controls the behavior of instantiation and + subsequent graph launches, as well as returning more detailed information + in the event of an error. ``CUDA_GRAPH_INSTANTIATE_PARAMS`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + The ``flags`` field controls the behavior of instantiation and subsequent + graph launches. Valid flags are:. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH``, which configures a + graph containing memory allocation nodes to automatically free any unfreed + memory allocations before the graph is relaunched. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD``, which will perform an upload of + the graph into ``hUploadStream`` once the graph has been instantiated. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_DEVICE_LAUNCH``, 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 + ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH``. + + - ``CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY``, 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 ``h_graph`` 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 + ``cuGraphExecDestroy`` will result in an error. The same also applies if + ``h_graph`` contains any device-updatable kernel nodes. + + If ``h_graph`` 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:. + + - ``CUDA_GRAPH_INSTANTIATE_ERROR``, 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. + + - ``CUDA_GRAPH_INSTANTIATE_INVALID_STRUCTURE``, if the graph structure is + invalid. ``hErrNode_out`` will be set to one of the offending nodes. + + - ``CUDA_GRAPH_INSTANTIATE_NODE_OPERATION_NOT_SUPPORTED``, 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. + + - ``CUDA_GRAPH_INSTANTIATE_MULTIPLE_CTXS_NOT_SUPPORTED``, 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 + ``CUDA_GRAPH_INSTANTIATE_SUCCESS``, and ``hErrNode_out`` will be set to + NULL. + + Args: + h_graph (intptr_t): Graph to instantiate. + instantiate_params (intptr_t): Instantiation parameters. + + Returns: + intptr_t: Returns instantiated graph. + + .. seealso:: `cuGraphInstantiateWithParams` + """ + cdef intptr_t _instantiate_params_ptr_ = int(instantiate_params) + cdef CUgraphExec ph_graph_exec + with nogil: + __status__ = cuGraphInstantiateWithParams(&ph_graph_exec, h_graph, _instantiate_params_ptr_) + check_status(__status__) + return ph_graph_exec + + +cpdef uint64_t graph_exec_get_flags(intptr_t h_graph_exec) except? 0: + """Query the instantiation flags of an executable graph. + + Returns the flags that were passed to instantiation for the given + executable graph. ``CUDA_GRAPH_INSTANTIATE_FLAG_UPLOAD`` will not be + returned by this API as it does not affect the resulting executable graph. + + Args: + h_graph_exec (intptr_t): The executable graph to query. + + Returns: + uint64_t: Returns the instantiation flags. + + .. seealso:: `cuGraphExecGetFlags` + """ + cdef cuuint64_t flags + with nogil: + __status__ = cuGraphExecGetFlags(h_graph_exec, &flags) + check_status(__status__) + return flags + + +cpdef graph_exec_kernel_node_set_params_v2(intptr_t h_graph_exec, intptr_t h_node, node_params): + """Sets the parameters for a kernel node in the given graphExec. + + Sets the parameters of a kernel node in an executable graph + ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` in the non-executable graph, from which the executable graph was + instantiated. + + ``h_node`` must not have been removed from the original graph. All + ``node_params`` 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 ``h_graph_exec`` 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 ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + If ``h_node`` is a device-updatable kernel node, the next upload/launch of + ``h_graph_exec`` 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. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): kernel node from the graph from which + graphExec was instantiated. + node_params (intptr_t): Updated Parameters to set. + + .. seealso:: `cuGraphExecKernelNodeSetParams_v2` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecKernelNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_exec_memcpy_node_set_params(intptr_t h_graph_exec, intptr_t h_node, copy_params, intptr_t ctx): + """Sets the parameters for a memcpy node in the given graphExec. + + Updates the work represented by ``h_node`` in ``h_graph_exec`` as though + ``h_node`` had contained ``copy_params`` at instantiation. h_node must + remain in the graph which was used to instantiate ``h_graph_exec``. Changed + edges to and from h_node are ignored. + + The source and destination memory in ``copy_params`` 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 + ``copy_params`` must be 1-dimensional. Zero-length operations are not + supported. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. h_node is also not modified by this call. + + Returns CUDA_ERROR_INVALID_VALUE if the memory operands' mappings changed + or either the original or new memory operands are multidimensional. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Memcpy node from the graph which was used + to instantiate graphExec. + copy_params (intptr_t): The updated parameters to set. + ctx (intptr_t): Context on which to run the node. + + .. seealso:: `cuGraphExecMemcpyNodeSetParams` + """ + cdef intptr_t _copy_params_ptr_ = int(copy_params) + with nogil: + __status__ = cuGraphExecMemcpyNodeSetParams(h_graph_exec, h_node, _copy_params_ptr_, ctx) + check_status(__status__) + + +cpdef graph_exec_memset_node_set_params(intptr_t h_graph_exec, intptr_t h_node, memset_params, intptr_t ctx): + """Sets the parameters for a memset node in the given graphExec. + + Updates the work represented by ``h_node`` in ``h_graph_exec`` as though + ``h_node`` had contained ``memset_params`` at instantiation. h_node must + remain in the graph which was used to instantiate ``h_graph_exec``. Changed + edges to and from h_node are ignored. + + Zero sized operations are not supported. + + The new destination pointer in memset_params 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 ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. h_node is also not modified by this call. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Memset node from the graph which was used + to instantiate graphExec. + memset_params (intptr_t): The updated parameters to set. + ctx (intptr_t): Context on which to run the node. + + .. seealso:: `cuGraphExecMemsetNodeSetParams` + """ + cdef intptr_t _memset_params_ptr_ = int(memset_params) + with nogil: + __status__ = cuGraphExecMemsetNodeSetParams(h_graph_exec, h_node, _memset_params_ptr_, ctx) + check_status(__status__) + + +cpdef graph_exec_host_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params): + """Sets the parameters for a host node in the given graphExec. + + Updates the work represented by ``h_node`` in ``h_graph_exec`` as though + ``h_node`` had contained ``node_params`` at instantiation. h_node must + remain in the graph which was used to instantiate ``h_graph_exec``. Changed + edges to and from h_node are ignored. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. h_node is also not modified by this call. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Host node from the graph which was used to + instantiate graphExec. + node_params (intptr_t): The updated parameters to set. + + .. seealso:: `cuGraphExecHostNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecHostNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_exec_child_graph_node_set_params(intptr_t h_graph_exec, intptr_t h_node, intptr_t child_graph): + """Updates node parameters in the child graph node in the given graphExec. + + Updates the work represented by ``h_node`` in ``h_graph_exec`` as though + the nodes contained in ``h_node's`` graph had the parameters contained in + ``child_graph's`` nodes at instantiation. ``h_node`` must remain in the + graph which was used to instantiate ``h_graph_exec``. Changed edges to and + from ``h_node`` are ignored. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + The topology of ``child_graph``, as well as the node insertion order, must + match that of the graph contained in ``h_node``. See + ``cuGraphExecUpdate()`` 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. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Host node from the graph which was used to + instantiate graphExec. + child_graph (intptr_t): The graph supplying the updated + parameters. + + .. seealso:: `cuGraphExecChildGraphNodeSetParams` + """ + with nogil: + __status__ = cuGraphExecChildGraphNodeSetParams(h_graph_exec, h_node, child_graph) + check_status(__status__) + + +cpdef graph_exec_event_record_node_set_event(intptr_t h_graph_exec, intptr_t h_node, intptr_t event): + """Sets the event for an event record node in the given graphExec. + + Sets the event of an event record node in an executable graph + ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` in the non-executable graph, from which the executable graph was + instantiated. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): event record node from the graph from which + graphExec was instantiated. + event (intptr_t): Updated event to use. + + .. seealso:: `cuGraphExecEventRecordNodeSetEvent` + """ + with nogil: + __status__ = cuGraphExecEventRecordNodeSetEvent(h_graph_exec, h_node, event) + check_status(__status__) + + +cpdef graph_exec_event_wait_node_set_event(intptr_t h_graph_exec, intptr_t h_node, intptr_t event): + """Sets the event for an event wait node in the given graphExec. + + Sets the event of an event wait node in an executable graph + ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` in the non-executable graph, from which the executable graph was + instantiated. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): event wait node from the graph from which + graphExec was instantiated. + event (intptr_t): Updated event to use. + + .. seealso:: `cuGraphExecEventWaitNodeSetEvent` + """ + with nogil: + __status__ = cuGraphExecEventWaitNodeSetEvent(h_graph_exec, h_node, event) + check_status(__status__) + + +cpdef graph_exec_external_semaphores_signal_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params): + """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 ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` in the non-executable graph, from which the executable graph was + instantiated. + + ``h_node`` must not have been removed from the original graph. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + Changing ``node_params->numExtSems`` is not supported. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): semaphore signal node from the graph from + which graphExec was instantiated. + node_params (intptr_t): Updated Parameters to set. + + .. seealso:: `cuGraphExecExternalSemaphoresSignalNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecExternalSemaphoresSignalNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_exec_external_semaphores_wait_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params): + """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 ``h_graph_exec``. The node is identified by the corresponding node + ``h_node`` in the non-executable graph, from which the executable graph was + instantiated. + + ``h_node`` must not have been removed from the original graph. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + Changing ``node_params->numExtSems`` is not supported. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): semaphore wait node from the graph from + which graphExec was instantiated. + node_params (intptr_t): Updated Parameters to set. + + .. seealso:: `cuGraphExecExternalSemaphoresWaitNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecExternalSemaphoresWaitNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_node_set_enabled(intptr_t h_graph_exec, intptr_t h_node, unsigned int is_enabled): + """Enables or disables the specified node in the given graphExec. + + Sets ``h_node`` 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 ``h_node`` in the non- + executable graph, from which the executable graph was instantiated. + + ``h_node`` must not have been removed from the original graph. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + If ``h_node`` is a device-updatable kernel node, the next upload/launch of + ``h_graph_exec`` 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. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Node from the graph from which graphExec + was instantiated. + is_enabled (unsigned int): Node is enabled if != 0, otherwise + the node is disabled. + + .. note:: + Currently only kernel, memset and memcpy nodes are supported. + + .. seealso:: `cuGraphNodeSetEnabled` + """ + with nogil: + __status__ = cuGraphNodeSetEnabled(h_graph_exec, h_node, is_enabled) + check_status(__status__) + + +cpdef unsigned int graph_node_get_enabled(intptr_t h_graph_exec, intptr_t h_node) except? 0: + """Query whether a node in the given graphExec is enabled. + + Sets is_enabled to 1 if ``h_node`` is enabled, or 0 if ``h_node`` is + disabled. + + The node is identified by the corresponding node ``h_node`` in the non- + executable graph, from which the executable graph was instantiated. + + ``h_node`` must not have been removed from the original graph. + + Args: + h_graph_exec (intptr_t): The executable graph in which to set + the specified node. + h_node (intptr_t): Node from the graph from which graphExec + was instantiated. + + Returns: + unsigned int: Location to return the enabled status of the + node. + + .. note:: + Currently only kernel, memset and memcpy nodes are supported. + + .. note:: + This function will not reflect device-side updates for device-updatable + kernel nodes. + + .. seealso:: `cuGraphNodeGetEnabled` + """ + cdef unsigned int is_enabled + with nogil: + __status__ = cuGraphNodeGetEnabled(h_graph_exec, h_node, &is_enabled) + check_status(__status__) + return is_enabled + + +cpdef graph_upload(intptr_t h_graph_exec, intptr_t h_stream): + """Uploads an executable graph in a stream. + + Uploads ``h_graph_exec`` to the device in ``h_stream`` without executing + it. Uploads of the same ``h_graph_exec`` will be serialized. Each upload is + ordered behind both any previous work in ``h_stream`` and any previous + launches of ``h_graph_exec``. Uses memory cached by ``stream`` to back the + allocations owned by ``h_graph_exec``. + + Args: + h_graph_exec (intptr_t): Executable graph to upload. + h_stream (intptr_t): Stream in which to upload the graph. + + .. seealso:: `cuGraphUpload` + """ + with nogil: + __status__ = cuGraphUpload(h_graph_exec, h_stream) + check_status(__status__) + + +cpdef graph_launch(intptr_t h_graph_exec, intptr_t h_stream): + """Launches an executable graph in a stream. + + Executes ``h_graph_exec`` in ``h_stream``. Only one instance of + ``h_graph_exec`` may be executing at a time. Each launch is ordered behind + both any previous work in ``h_stream`` and any previous launches of + ``h_graph_exec``. To execute a graph concurrently, it must be instantiated + multiple times into multiple executable graphs. + + If any allocations created by ``h_graph_exec`` remain unfreed (from a + previous launch) and ``h_graph_exec`` was not instantiated with + ``CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH``, the launch will fail + with ``CUDA_ERROR_INVALID_VALUE``. + + Args: + h_graph_exec (intptr_t): Executable graph to launch. + h_stream (intptr_t): Stream in which to launch the graph. + + .. seealso:: `cuGraphLaunch` + """ + with nogil: + __status__ = cuGraphLaunch(h_graph_exec, h_stream) + check_status(__status__) + + +cpdef graph_exec_destroy(intptr_t h_graph_exec): + """Destroys an executable graph. + + Destroys the executable graph specified by ``h_graph_exec``, 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. + + Args: + h_graph_exec (intptr_t): Executable graph to destroy. + + .. seealso:: `cuGraphExecDestroy` + """ + with nogil: + __status__ = cuGraphExecDestroy(h_graph_exec) + check_status(__status__) + + +cpdef graph_destroy(intptr_t h_graph): + """Destroys a graph. + + Destroys the graph specified by ``h_graph``, as well as all of its nodes. + + Args: + h_graph (intptr_t): Graph to destroy. + + .. seealso:: `cuGraphDestroy` + """ + with nogil: + __status__ = cuGraphDestroy(h_graph) + check_status(__status__) + + +cpdef graph_exec_update_v2(intptr_t h_graph_exec, intptr_t h_graph, result_info): + """Check whether an executable graph can be updated with a graph and perform the update if possible. + + Updates the node parameters in the instantiated graph specified by + ``h_graph_exec`` with the node parameters in a topologically identical + graph specified by ``h_graph``. + + 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 + CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY, 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 ``h_graph_exec`` 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 ``h_graph`` nor ``h_graph_exec`` 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. + CU_MEMORYTYPE_DEVICE, CU_MEMORYTYPE_ARRAY, 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. + + cuGraphExecUpdate sets the result member of ``result_info`` to + CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED under the following + conditions:. + + - The count of nodes directly in ``h_graph_exec`` and ``h_graph`` differ, + in which case result_info->errorNode is set to NULL. + + - ``h_graph`` has more exit nodes than ``h_graph``, in which case + result_info->errorNode is set to one of the exit nodes in h_graph. + + - A node in ``h_graph`` has a different number of dependencies than the + node from ``h_graph_exec`` it is paired with, in which case + result_info->errorNode is set to the node from ``h_graph``. + + - A node in ``h_graph`` has a dependency that does not match with the + corresponding dependency of the paired node from ``h_graph_exec``. + result_info->errorNode will be set to the node from ``h_graph``. + result_info->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. + + cuGraphExecUpdate sets the result member of ``result_info`` to:. + + - CU_GRAPH_EXEC_UPDATE_ERROR if passed an invalid value. + + - CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED if the graph topology + changed. + + - CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED if the type of a node + changed, in which case ``hErrorNode_out`` is set to the node from + ``h_graph``. + + - CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE if the function + changed in an unsupported way(see note above), in which case + ``hErrorNode_out`` is set to the node from ``h_graph``. + + - CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED if any parameters to a node + changed in a way that is not supported, in which case ``hErrorNode_out`` is + set to the node from ``h_graph``. + + - CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED if any attributes of a node + changed in a way that is not supported, in which case ``hErrorNode_out`` is + set to the node from ``h_graph``. + + - CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED if something about a node is + unsupported, like the node's type or configuration, in which case + ``hErrorNode_out`` is set to the node from ``h_graph``. + + If the update fails for a reason not listed above, the result member of + ``result_info`` will be set to CU_GRAPH_EXEC_UPDATE_ERROR. If the update + succeeds, the result member will be set to CU_GRAPH_EXEC_UPDATE_SUCCESS. + + cuGraphExecUpdate returns CUDA_SUCCESS when the updated was performed + successfully. It returns CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE if the graph + update was not performed because it included changes which violated + constraints specific to instantiated graph update. + + Args: + h_graph_exec (intptr_t): The instantiated graph to be updated. + h_graph (intptr_t): The graph containing the updated + parameters. + result_info (intptr_t): the error info structure. + + .. seealso:: `cuGraphExecUpdate_v2` + """ + cdef intptr_t _result_info_ptr_ = int(result_info) + with nogil: + __status__ = cuGraphExecUpdate(h_graph_exec, h_graph, _result_info_ptr_) + check_status(__status__) + + +cpdef graph_kernel_node_copy_attributes(intptr_t dst, intptr_t src): + """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. + + Args: + dst (intptr_t): Destination node. + src (intptr_t): Source node For list of attributes see + ``CUkernelNodeAttrID``. + + .. seealso:: `cuGraphKernelNodeCopyAttributes` + """ + with nogil: + __status__ = cuGraphKernelNodeCopyAttributes(dst, src) + check_status(__status__) + + +cpdef graph_kernel_node_get_attribute(intptr_t h_node, int attr, intptr_t value_out): + """Queries node attribute. + + Queries attribute ``attr`` from node ``h_node`` and stores it in + corresponding member of ``value_out``. + + Args: + h_node (intptr_t): . + attr (int): . + value_out (intptr_t): . + + .. seealso:: `cuGraphKernelNodeGetAttribute` + """ + with nogil: + __status__ = cuGraphKernelNodeGetAttribute(h_node, attr, value_out) + check_status(__status__) + + +cpdef graph_kernel_node_set_attribute(intptr_t h_node, int attr, intptr_t value): + """Sets node attribute. + + Sets attribute ``attr`` on node ``h_node`` from corresponding attribute of + ``value``. + + Args: + h_node (intptr_t): . + attr (int): . + value (intptr_t): . + + .. seealso:: `cuGraphKernelNodeSetAttribute` + """ + with nogil: + __status__ = cuGraphKernelNodeSetAttribute(h_node, attr, value) + check_status(__status__) + + +cpdef graph_debug_dot_print(intptr_t h_graph, path, unsigned int flags): + """Write a DOT file describing graph structure. + + Using the provided ``h_graph``, 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. + + Args: + h_graph (intptr_t): The graph to create a DOT file from. + path (bytes): The path to write the DOT file to. + flags (unsigned int): Flags from ``CUgraphDebugDot_flags`` for + specifying which additional node information to write. + + .. seealso:: `cuGraphDebugDotPrint` + """ + cdef void* _path_ = _cyb_get_buffer_pointer(path, -1, readonly=True) + with nogil: + __status__ = cuGraphDebugDotPrint(h_graph, _path_, flags) + check_status(__status__) + + +cpdef intptr_t user_object_create(ptr, intptr_t destroy, unsigned int initial_refcount, unsigned int flags) except? 0: + """Create 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. + + Args: + ptr (bytes): The pointer to pass to the destroy function. + destroy (intptr_t): Callback to free the user object when it + is no longer in use. + initial_refcount (unsigned int): The initial refcount to + create the object with, typically 1. The initial + references are owned by the calling thread. + flags (unsigned int): Currently it is required to pass + ``CU_USER_OBJECT_NO_DESTRUCTOR_SYNC``, 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. + + Returns: + intptr_t: Location to return the user object handle. + + .. seealso:: `cuUserObjectCreate` + """ + cdef void* _ptr_ = _cyb_get_buffer_pointer(ptr, -1, readonly=False) + cdef CUuserObject object_out + with nogil: + __status__ = cuUserObjectCreate(&object_out, _ptr_, destroy, initial_refcount, flags) + check_status(__status__) + return object_out + + +cpdef user_object_retain(intptr_t object, unsigned int count): + """Retain 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. + + Args: + object (intptr_t): The object to retain. + count (unsigned int): The number of references to retain, + typically 1. Must be nonzero and not larger than INT_MAX. + + .. seealso:: `cuUserObjectRetain` + """ + with nogil: + __status__ = cuUserObjectRetain(object, count) + check_status(__status__) + + +cpdef user_object_release(intptr_t object, unsigned int count): + """Release 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. + + Args: + object (intptr_t): The object to release. + count (unsigned int): The number of references to release, + typically 1. Must be nonzero and not larger than INT_MAX. + + .. seealso:: `cuUserObjectRelease` + """ + with nogil: + __status__ = cuUserObjectRelease(object, count) + check_status(__status__) + + +cpdef graph_retain_user_object(intptr_t graph, intptr_t object, unsigned int count, unsigned int flags): + """Retain 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. + + Args: + graph (intptr_t): The graph to associate the reference with. + object (intptr_t): The user object to retain a reference for. + count (unsigned int): The number of references to add to the + graph, typically 1. Must be nonzero and not larger than + INT_MAX. + flags (unsigned int): The optional flag + ``CU_GRAPH_USER_OBJECT_MOVE`` transfers references from + the calling thread, rather than create new references. + Pass 0 to create new references. + + .. seealso:: `cuGraphRetainUserObject` + """ + with nogil: + __status__ = cuGraphRetainUserObject(graph, object, count, flags) + check_status(__status__) + + +cpdef graph_release_user_object(intptr_t graph, intptr_t object, unsigned int count): + """Release 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. + + Args: + graph (intptr_t): The graph that will release the reference. + object (intptr_t): The user object to release a reference for. + count (unsigned int): The number of references to release, + typically 1. Must be nonzero and not larger than INT_MAX. + + .. seealso:: `cuGraphReleaseUserObject` + """ + with nogil: + __status__ = cuGraphReleaseUserObject(graph, object, count) + check_status(__status__) + + +cpdef intptr_t graph_add_node_v2(intptr_t h_graph, intptr_t dependencies, dependency_data, size_t num_dependencies, node_params) except? 0: + """Adds a node of arbitrary type to a graph. + + Creates a new node in ``h_graph`` described by ``node_params`` with + ``num_dependencies`` dependencies specified via ``dependencies``. + ``num_dependencies`` may be 0. ``dependencies`` may be null if + ``num_dependencies`` is 0. ``dependencies`` may not have any duplicate + entries. + + ``node_params`` is a tagged union. The node type should be specified in the + ``typename`` 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, ``node_params`` may contain "out parameters" + which are modified during the call, such as ``node_params->alloc.dptr``. + + A handle to the new node will be returned in ``ph_graph_node``. + + Args: + h_graph (intptr_t): Graph to which to add the node. + dependencies (intptr_t): Dependencies of the node. + dependency_data (intptr_t): Optional edge data for the + dependencies. If NULL, the data is assumed to be default + (zeroed) for all dependencies. + num_dependencies (size_t): Number of dependencies. + node_params (intptr_t): Specification of the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddNode_v2` + """ + cdef CUgraphNode _dependencies_ = dependencies + cdef intptr_t _dependency_data_ptr_ = int(dependency_data) + cdef intptr_t _node_params_ptr_ = int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddNode(&ph_graph_node, h_graph, dependencies, _dependency_data_ptr_, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_node_set_params(intptr_t h_node, node_params): + """Update a graph node's parameters. + + Sets the parameters of graph node ``h_node`` to ``node_params``. The node + type specified by ``node_params->type`` must match the type of ``h_node``. + ``node_params`` must be fully initialized and all unused bytes (reserved, + padding) zeroed. + + Modifying parameters is not supported for node types + CU_GRAPH_NODE_TYPE_MEM_ALLOC and CU_GRAPH_NODE_TYPE_MEM_FREE. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphNodeSetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef graph_exec_node_set_params(intptr_t h_graph_exec, intptr_t h_node, node_params): + """Update a graph node's parameters in an instantiated graph. + + Sets the parameters of a node in an executable graph ``h_graph_exec``. The + node is identified by the corresponding node ``h_node`` in the non- + executable graph from which the executable graph was instantiated. + ``h_node`` must not have been removed from the original graph. + + The modifications only affect future launches of ``h_graph_exec``. Already + enqueued or running launches of ``h_graph_exec`` are not affected by this + call. ``h_node`` is also not modified by this call. + + Allowed changes to parameters on executable graphs are as follows:. + + **View CUDA Toolkit Documentation for a table example**. + + Args: + h_graph_exec (intptr_t): The executable graph in which to + update the specified node. + h_node (intptr_t): Corresponding node from the graph from + which graphExec was instantiated. + node_params (intptr_t): Updated Parameters to set. + + .. seealso:: `cuGraphExecNodeSetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphExecNodeSetParams(h_graph_exec, h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef uint64_t graph_conditional_handle_create(intptr_t h_graph, intptr_t ctx, unsigned int default_launch_value, unsigned int flags) except? 0: + """Create a conditional handle. + + Creates a conditional handle associated with ``h_graph``. + + 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. + + Args: + h_graph (intptr_t): Graph which will contain the conditional + node using this handle. + ctx (intptr_t): Context for the handle and associated + conditional node. + default_launch_value (unsigned int): 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 (unsigned int): Currently must be + CU_GRAPH_COND_ASSIGN_DEFAULT or 0. + + Returns: + uint64_t: Pointer used to return the handle to the caller. + + .. seealso:: `cuGraphConditionalHandleCreate` + """ + cdef CUgraphConditionalHandle p_handle_out + with nogil: + __status__ = cuGraphConditionalHandleCreate(&p_handle_out, h_graph, ctx, default_launch_value, flags) + check_status(__status__) + return p_handle_out + + +cpdef int occupancy_max_active_blocks_per_multiprocessor(intptr_t func, int block_size, size_t dynamic_s_mem_size) except? -1: + """Returns occupancy of a function. + + Returns in ``*num_blocks`` the number of the maximum active blocks per + streaming multiprocessor. + + Note that the API can also be used with context-less kernel ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. Here, the context to use for + calculations will be the current context. + + Args: + func (intptr_t): Kernel for which occupancy is calculated. + block_size (int): Block size the kernel is intended to be + launched with. + dynamic_s_mem_size (size_t): Per-block dynamic shared memory + usage intended, in bytes. + + Returns: + int: Returned occupancy. + + .. seealso:: `cuOccupancyMaxActiveBlocksPerMultiprocessor` + """ + cdef int num_blocks + with nogil: + __status__ = cuOccupancyMaxActiveBlocksPerMultiprocessor(&num_blocks, func, block_size, dynamic_s_mem_size) + check_status(__status__) + return num_blocks + + +cpdef int occupancy_max_active_blocks_per_multiprocessor_with_flags(intptr_t func, int block_size, size_t dynamic_s_mem_size, unsigned int flags) except? -1: + """Returns occupancy of a function. + + Returns in ``*num_blocks`` the number of the maximum active blocks per + streaming multiprocessor. + + The ``Flags`` parameter controls how special cases are handled. The valid + flags are:. + + - ``CU_OCCUPANCY_DEFAULT``, which maintains the default behavior as + ``cuOccupancyMaxActiveBlocksPerMultiprocessor``;. + + - ``CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE``, 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 + ``CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE`` 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 ``CUkernel`` + by querying the handle using :func:`library_get_kernel` and then passing it + to the API by casting to ``CUfunction``. Here, the context to use for + calculations will be the current context. + + Args: + func (intptr_t): Kernel for which occupancy is calculated. + block_size (int): Block size the kernel is intended to be + launched with. + dynamic_s_mem_size (size_t): Per-block dynamic shared memory + usage intended, in bytes. + flags (unsigned int): Requested behavior for the occupancy + calculator. + + Returns: + int: Returned occupancy. + + .. seealso:: `cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags` + """ + cdef int num_blocks + with nogil: + __status__ = cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(&num_blocks, func, block_size, dynamic_s_mem_size, flags) + check_status(__status__) + return num_blocks + + +cpdef tuple occupancy_max_potential_block_size(intptr_t func, intptr_t block_size_to_dynamic_s_mem_size, size_t dynamic_s_mem_size, int block_size_limit): + """Suggest a launch configuration with reasonable occupancy. + + Returns in ``*block_size`` 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 ``*min_grid_size`` the minimum grid size + to achieve the maximum occupancy. + + If ``block_sizeLimit`` 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 ``block_sizeToDynamicSMemSize`` and + ``dynamic_s_mem_size`` 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 ``dynamic_s_mem_size``, and + ``block_sizeToDynamicSMemSize`` 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 + ``block_sizeToDynamicSMemSize`` that computes the dynamic shared memory + needed by ``func`` for any given block size. ``dynamic_s_mem_size`` is + ignored. An example signature is:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Note that the API can also be used with context-less kernel ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. Here, the context to use for + calculations will be the current context. + + Args: + func (intptr_t): Kernel for which launch configuration is + calculated. + block_size_to_dynamic_s_mem_size (intptr_t): A function that + calculates how much per-block dynamic shared memory + ``func`` uses based on the block size. + dynamic_s_mem_size (size_t): Dynamic shared memory usage + intended, in bytes. + block_size_limit (int): The maximum block size ``func`` is + designed to handle. + + Returns: + A 2-tuple containing: + + - int: Returned minimum grid size needed to achieve the maximum + occupancy. + - int: Returned maximum block size that can achieve the maximum + occupancy. + + .. seealso:: `cuOccupancyMaxPotentialBlockSize` + """ + cdef int min_grid_size + cdef int block_size + with nogil: + __status__ = cuOccupancyMaxPotentialBlockSize(&min_grid_size, &block_size, func, block_size_to_dynamic_s_mem_size, dynamic_s_mem_size, block_size_limit) + check_status(__status__) + return (min_grid_size, block_size) + + +cpdef tuple occupancy_max_potential_block_size_with_flags(intptr_t func, intptr_t block_size_to_dynamic_s_mem_size, size_t dynamic_s_mem_size, int block_size_limit, unsigned int flags): + """Suggest a launch configuration with reasonable occupancy. + + An extended version of ``cuOccupancyMaxPotentialBlockSize``. In addition to + arguments passed to ``cuOccupancyMaxPotentialBlockSize``, + ``cuOccupancyMaxPotentialBlockSizeWithFlags`` also takes a ``Flags`` + parameter. + + The ``Flags`` parameter controls how special cases are handled. The valid + flags are:. + + - ``CU_OCCUPANCY_DEFAULT``, which maintains the default behavior as + ``cuOccupancyMaxPotentialBlockSize``;. + + - ``CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE``, 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 + ``CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE`` 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 ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. Here, the context to use for + calculations will be the current context. + + Args: + func (intptr_t): Kernel for which launch configuration is + calculated. + block_size_to_dynamic_s_mem_size (intptr_t): A function that + calculates how much per-block dynamic shared memory + ``func`` uses based on the block size. + dynamic_s_mem_size (size_t): Dynamic shared memory usage + intended, in bytes. + block_size_limit (int): The maximum block size ``func`` is + designed to handle. + flags (unsigned int): Options. + + Returns: + A 2-tuple containing: + + - int: Returned minimum grid size needed to achieve the maximum + occupancy. + - int: Returned maximum block size that can achieve the maximum + occupancy. + + .. seealso:: `cuOccupancyMaxPotentialBlockSizeWithFlags` + """ + cdef int min_grid_size + cdef int block_size + with nogil: + __status__ = cuOccupancyMaxPotentialBlockSizeWithFlags(&min_grid_size, &block_size, func, block_size_to_dynamic_s_mem_size, dynamic_s_mem_size, block_size_limit, flags) + check_status(__status__) + return (min_grid_size, block_size) + + +cpdef size_t occupancy_available_dynamic_smem_per_block(intptr_t func, int num_blocks, int block_size) except? 0: + """Returns dynamic shared memory available per block when launching ``num_blocks`` blocks on SM. + + Returns in ``*dynamic_smem_size`` the maximum size of dynamic shared memory + to allow ``num_blocks`` blocks per SM. + + Note that the API can also be used with context-less kernel ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. Here, the context to use for + calculations will be the current context. + + Args: + func (intptr_t): Kernel function for which occupancy is + calculated. + num_blocks (int): Number of blocks to fit on SM. + block_size (int): Size of the blocks. + + Returns: + size_t: Returned maximum dynamic shared memory. + + .. seealso:: `cuOccupancyAvailableDynamicSMemPerBlock` + """ + cdef size_t dynamic_smem_size + with nogil: + __status__ = cuOccupancyAvailableDynamicSMemPerBlock(&dynamic_smem_size, func, num_blocks, block_size) + check_status(__status__) + return dynamic_smem_size + + +cpdef int occupancy_max_potential_cluster_size(intptr_t func, config) except? -1: + """Given the kernel function (``func``) and launch configuration (``config``), return the maximum cluster size in ``*cluster_size``. + + The cluster dimensions in ``config`` are ignored. If func has a required + cluster size set (see ``cudaFuncGetAttributes`` / + ``cuFuncGetAttribute``),``*cluster_size`` 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 ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. 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. + + Args: + func (intptr_t): Kernel function for which maximum cluster + size is calculated. + config (intptr_t): Launch configuration for the given kernel + function. + + Returns: + int: Returned maximum cluster size that can be launched for + the given kernel function and launch configuration. + + .. seealso:: `cuOccupancyMaxPotentialClusterSize` + """ + cdef intptr_t _config_ptr_ = int(config) + cdef int cluster_size + with nogil: + __status__ = cuOccupancyMaxPotentialClusterSize(&cluster_size, func, _config_ptr_) + check_status(__status__) + return cluster_size + + +cpdef int occupancy_max_active_clusters(intptr_t func, config) except? -1: + """Given the kernel function (``func``) and launch configuration (``config``), return the maximum number of clusters that could co-exist on the target device in ``*num_clusters``. + + If the function has required cluster size already set (see + ``cudaFuncGetAttributes`` / ``cuFuncGetAttribute``), 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 ``CUkernel`` by + querying the handle using :func:`library_get_kernel` and then passing it to + the API by casting to ``CUfunction``. 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. + + Args: + func (intptr_t): Kernel function for which maximum number of + clusters are calculated. + config (intptr_t): Launch configuration for the given kernel + function. + + Returns: + int: Returned maximum number of clusters that could co-exist + on the target device. + + .. seealso:: `cuOccupancyMaxActiveClusters` + """ + cdef intptr_t _config_ptr_ = int(config) + cdef int num_clusters + with nogil: + __status__ = cuOccupancyMaxActiveClusters(&num_clusters, func, _config_ptr_) + check_status(__status__) + return num_clusters + + +cpdef tex_ref_set_array(intptr_t h_tex_ref, intptr_t h_array, unsigned int flags): + """Binds an array as a texture reference. + + [Deprecated]. + + Binds the CUDA array ``h_array`` to the texture reference ``h_tex_ref``. + 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 + ``h_tex_ref`` is unbound. + + Args: + h_tex_ref (intptr_t): Texture reference to bind. + h_array (intptr_t): Array to bind. + flags (unsigned int): Options (must be + ``CU_TRSA_OVERRIDE_FORMAT``). + + .. seealso:: `cuTexRefSetArray` + """ + with nogil: + __status__ = cuTexRefSetArray(h_tex_ref, h_array, flags) + check_status(__status__) + + +cpdef tex_ref_set_mipmapped_array(intptr_t h_tex_ref, intptr_t h_mipmapped_array, unsigned int flags): + """Binds a mipmapped array to a texture reference. + + [Deprecated]. + + Binds the CUDA mipmapped array ``h_mipmapped_array`` to the texture + reference ``h_tex_ref``. 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 ``h_tex_ref`` is unbound. + + Args: + h_tex_ref (intptr_t): Texture reference to bind. + h_mipmapped_array (intptr_t): Mipmapped array to bind. + flags (unsigned int): Options (must be + ``CU_TRSA_OVERRIDE_FORMAT``). + + .. seealso:: `cuTexRefSetMipmappedArray` + """ + with nogil: + __status__ = cuTexRefSetMipmappedArray(h_tex_ref, h_mipmapped_array, flags) + check_status(__status__) + + +cpdef size_t tex_ref_set_address_v2(intptr_t h_tex_ref, unsigned long long dptr, size_t bytes) except? 0: + """Binds an address as a texture reference. + + [Deprecated]. + + Binds a linear address range to the texture reference ``h_tex_ref``. Any + previous address or CUDA array state associated with the texture reference + is superseded by this function. Any memory previously bound to + ``h_tex_ref`` is unbound. + + Since the hardware enforces an alignment requirement on texture base + addresses, ``cuTexRefSetAddress()`` passes back a byte offset in + ``*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 ``cuMemAlloc()``, the offset + is guaranteed to be 0 and NULL may be passed as the ``byte_offset`` + parameter. + + The total number of elements (or texels) in the linear address range cannot + exceed ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH``. The number + of elements is computed as (``numbytes`` / bytesPerElement), where + bytesPerElement is determined from the data format and number of components + set using :func:`tex_ref_set_format`. + + Args: + h_tex_ref (intptr_t): Texture reference to bind. + dptr (unsigned long long): Device pointer to bind. + bytes (size_t): Size of memory to bind in bytes. + + Returns: + size_t: Returned byte offset. + + .. seealso:: `cuTexRefSetAddress_v2` + """ + cdef size_t byte_offset + with nogil: + __status__ = cuTexRefSetAddress(&byte_offset, h_tex_ref, dptr, bytes) + check_status(__status__) + return byte_offset + + +cpdef tex_ref_set_address2d_v3(intptr_t h_tex_ref, desc, unsigned long long dptr, size_t pitch): + """Binds an address as a 2D texture reference. + + [Deprecated]. + + Binds a linear address range to the texture reference ``h_tex_ref``. Any + previous address or CUDA array state associated with the texture reference + is superseded by this function. Any memory previously bound to + ``h_tex_ref`` is unbound. + + Using a ``tex2D()`` function inside a kernel requires a call to either + :func:`tex_ref_set_array` to bind the corresponding texture reference to an + array, or ``cuTexRefSetAddress2D()`` to bind the texture reference to + linear memory. + + Function calls to :func:`tex_ref_set_format` cannot follow calls to + ``cuTexRefSetAddress2D()`` 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 ``CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT``. If an unaligned + ``dptr`` is supplied, ``CUDA_ERROR_INVALID_VALUE`` is returned. + + ``pitch`` has to be aligned to the hardware-specific texture pitch + alignment. This value can be queried using the device attribute + ``CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT``. If an unaligned ``pitch`` + is supplied, ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Width and Height, which are specified in elements (or texels), cannot + exceed ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH`` and + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT`` respectively. + ``pitch``, which is specified in bytes, cannot exceed + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH``. + + Args: + h_tex_ref (intptr_t): Texture reference to bind. + desc (intptr_t): Descriptor of CUDA array. + dptr (unsigned long long): Device pointer to bind. + pitch (size_t): Line pitch in bytes. + + .. seealso:: `cuTexRefSetAddress2D_v3` + """ + cdef intptr_t _desc_ptr_ = int(desc) + with nogil: + __status__ = cuTexRefSetAddress2D(h_tex_ref, _desc_ptr_, dptr, pitch) + check_status(__status__) + + +cpdef tex_ref_set_format(intptr_t h_tex_ref, int fmt, int num_packed_components): + """Sets the format for a texture reference. + + [Deprecated]. + + Specifies the format of the data to be read by the texture reference + ``h_tex_ref``. ``fmt`` and ``num_packed_components`` are exactly analogous + to the ``Format`` and ``NumChannels`` members of the + ``CUDA_ARRAY_DESCRIPTOR`` structure: They specify the format of each + component and the number of components per array element. + + Args: + h_tex_ref (intptr_t): Texture reference. + fmt (ArrayFormat): Format to set. + num_packed_components (int): Number of components per array + element. + + .. seealso:: `cuTexRefSetFormat` + """ + with nogil: + __status__ = cuTexRefSetFormat(h_tex_ref, fmt, num_packed_components) + check_status(__status__) + + +cpdef tex_ref_set_address_mode(intptr_t h_tex_ref, int dim, int am): + """Sets the addressing mode for a texture reference. + + [Deprecated]. + + Specifies the addressing mode ``am`` for the given dimension ``dim`` of the + texture reference ``h_tex_ref``. 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. ``CUaddress_mode`` is + defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Note that this call has no effect if ``h_tex_ref`` is bound to linear + memory. Also, if the flag, ``CU_TRSF_NORMALIZED_COORDINATES``, is not set, + the only supported address mode is ``CU_TR_ADDRESS_MODE_CLAMP``. + + Args: + h_tex_ref (intptr_t): Texture reference. + dim (int): Dimension. + am (AddressMode): Addressing mode to set. + + .. seealso:: `cuTexRefSetAddressMode` + """ + with nogil: + __status__ = cuTexRefSetAddressMode(h_tex_ref, dim, am) + check_status(__status__) + + +cpdef tex_ref_set_filter_mode(intptr_t h_tex_ref, int fm): + """Sets the filtering mode for a texture reference. + + [Deprecated]. + + Specifies the filtering mode ``fm`` to be used when reading memory through + the texture reference ``h_tex_ref``. ``CUfilter_mode_enum`` is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Note that this call has no effect if ``h_tex_ref`` is bound to linear + memory. + + Args: + h_tex_ref (intptr_t): Texture reference. + fm (FilterMode): Filtering mode to set. + + .. seealso:: `cuTexRefSetFilterMode` + """ + with nogil: + __status__ = cuTexRefSetFilterMode(h_tex_ref, fm) + check_status(__status__) + + +cpdef tex_ref_set_mipmap_filter_mode(intptr_t h_tex_ref, int fm): + """Sets the mipmap filtering mode for a texture reference. + + [Deprecated]. + + Specifies the mipmap filtering mode ``fm`` to be used when reading memory + through the texture reference ``h_tex_ref``. ``CUfilter_mode_enum`` is + defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + Note that this call has no effect if ``h_tex_ref`` is not bound to a + mipmapped array. + + Args: + h_tex_ref (intptr_t): Texture reference. + fm (FilterMode): Filtering mode to set. + + .. seealso:: `cuTexRefSetMipmapFilterMode` + """ + with nogil: + __status__ = cuTexRefSetMipmapFilterMode(h_tex_ref, fm) + check_status(__status__) + + +cpdef tex_ref_set_mipmap_level_bias(intptr_t h_tex_ref, float bias): + """Sets the mipmap level bias for a texture reference. + + [Deprecated]. + + Specifies the mipmap level bias ``bias`` to be added to the specified + mipmap level when reading memory through the texture reference + ``h_tex_ref``. + + Note that this call has no effect if ``h_tex_ref`` is not bound to a + mipmapped array. + + Args: + h_tex_ref (intptr_t): Texture reference. + bias (float): Mipmap level bias. + + .. seealso:: `cuTexRefSetMipmapLevelBias` + """ + with nogil: + __status__ = cuTexRefSetMipmapLevelBias(h_tex_ref, bias) + check_status(__status__) + + +cpdef tex_ref_set_mipmap_level_clamp(intptr_t h_tex_ref, float min_mipmap_level_clamp, float max_mipmap_level_clamp): + """Sets the mipmap min/max mipmap level clamps for a texture reference. + + [Deprecated]. + + Specifies the min/max mipmap level clamps, ``min_mipmap_level_clamp`` and + ``max_mipmap_level_clamp`` respectively, to be used when reading memory + through the texture reference ``h_tex_ref``. + + Note that this call has no effect if ``h_tex_ref`` is not bound to a + mipmapped array. + + Args: + h_tex_ref (intptr_t): Texture reference. + min_mipmap_level_clamp (float): Mipmap min level clamp. + max_mipmap_level_clamp (float): Mipmap max level clamp. + + .. seealso:: `cuTexRefSetMipmapLevelClamp` + """ + with nogil: + __status__ = cuTexRefSetMipmapLevelClamp(h_tex_ref, min_mipmap_level_clamp, max_mipmap_level_clamp) + check_status(__status__) + + +cpdef tex_ref_set_max_anisotropy(intptr_t h_tex_ref, unsigned int max_aniso): + """Sets the maximum anisotropy for a texture reference. + + [Deprecated]. + + Specifies the maximum anisotropy ``max_aniso`` to be used when reading + memory through the texture reference ``h_tex_ref``. + + Note that this call has no effect if ``h_tex_ref`` is bound to linear + memory. + + Args: + h_tex_ref (intptr_t): Texture reference. + max_aniso (unsigned int): Maximum anisotropy. + + .. seealso:: `cuTexRefSetMaxAnisotropy` + """ + with nogil: + __status__ = cuTexRefSetMaxAnisotropy(h_tex_ref, max_aniso) + check_status(__status__) + + +cpdef tex_ref_set_border_color(intptr_t h_tex_ref, intptr_t p_border_color): + """Sets the border color for a texture reference. + + [Deprecated]. + + Specifies the value of the RGBA color via the ``p_border_color`` to the + texture reference ``h_tex_ref``. The color value supports only float type + and holds color components in the following sequence: p_border_color[0] + holds 'R' component p_border_color[1] holds 'G' component p_border_color[2] + holds 'B' component p_border_color[3] holds 'A' component. + + Note that the color values can be set only when the Address mode is set to + CU_TR_ADDRESS_MODE_BORDER using ``cuTexRefSetAddressMode``. Applications + using integer border color values have to "reinterpret_cast" their values + to float. + + Args: + h_tex_ref (intptr_t): Texture reference. + p_border_color (intptr_t): RGBA color. + + .. seealso:: `cuTexRefSetBorderColor` + """ + with nogil: + __status__ = cuTexRefSetBorderColor(h_tex_ref, p_border_color) + check_status(__status__) + + +cpdef tex_ref_set_flags(intptr_t h_tex_ref, unsigned int flags): + """Sets the flags for a texture reference. + + [Deprecated]. + + Specifies optional flags via ``flags`` to specify the behavior of data + returned through the texture reference ``h_tex_ref``. 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. + + Args: + h_tex_ref (intptr_t): Texture reference. + flags (unsigned int): Optional flags to set. + + .. seealso:: `cuTexRefSetFlags` + """ + with nogil: + __status__ = cuTexRefSetFlags(h_tex_ref, flags) + check_status(__status__) + + +cpdef unsigned long long tex_ref_get_address_v2(intptr_t h_tex_ref) except? 0: + """Gets the address associated with a texture reference. + + [Deprecated]. + + Returns in ``*pdptr`` the base address bound to the texture reference + ``h_tex_ref``, or returns ``CUDA_ERROR_INVALID_VALUE`` if the texture + reference is not bound to any device memory range. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + unsigned long long: Returned device address. + + .. seealso:: `cuTexRefGetAddress_v2` + """ + cdef CUdeviceptr pdptr + with nogil: + __status__ = cuTexRefGetAddress(&pdptr, h_tex_ref) + check_status(__status__) + return pdptr + + +cpdef intptr_t tex_ref_get_array(intptr_t h_tex_ref) except? 0: + """Gets the array bound to a texture reference. + + [Deprecated]. + + Returns in ``*ph_array`` the CUDA array bound to the texture reference + ``h_tex_ref``, or returns ``CUDA_ERROR_INVALID_VALUE`` if the texture + reference is not bound to any CUDA array. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + intptr_t: Returned array. + + .. seealso:: `cuTexRefGetArray` + """ + cdef CUarray ph_array + with nogil: + __status__ = cuTexRefGetArray(&ph_array, h_tex_ref) + check_status(__status__) + return ph_array + + +cpdef intptr_t tex_ref_get_mipmapped_array(intptr_t h_tex_ref) except? 0: + """Gets the mipmapped array bound to a texture reference. + + [Deprecated]. + + Returns in ``*ph_mipmapped_array`` the CUDA mipmapped array bound to the + texture reference ``h_tex_ref``, or returns ``CUDA_ERROR_INVALID_VALUE`` if + the texture reference is not bound to any CUDA mipmapped array. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + intptr_t: Returned mipmapped array. + + .. seealso:: `cuTexRefGetMipmappedArray` + """ + cdef CUmipmappedArray ph_mipmapped_array + with nogil: + __status__ = cuTexRefGetMipmappedArray(&ph_mipmapped_array, h_tex_ref) + check_status(__status__) + return ph_mipmapped_array + + +cpdef int tex_ref_get_address_mode(intptr_t h_tex_ref, int dim) except? -1: + """Gets the addressing mode used by a texture reference. + + [Deprecated]. + + Returns in ``*pam`` the addressing mode corresponding to the dimension + ``dim`` of the texture reference ``h_tex_ref``. Currently, the only valid + value for ``dim`` are 0 and 1. + + Args: + h_tex_ref (intptr_t): Texture reference. + dim (int): Dimension. + + Returns: + int: Returned addressing mode. + + .. seealso:: `cuTexRefGetAddressMode` + """ + cdef CUaddress_mode pam + with nogil: + __status__ = cuTexRefGetAddressMode(&pam, h_tex_ref, dim) + check_status(__status__) + return pam + + +cpdef int tex_ref_get_filter_mode(intptr_t h_tex_ref) except? -1: + """Gets the filter-mode used by a texture reference. + + [Deprecated]. + + Returns in ``*pfm`` the filtering mode of the texture reference + ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + int: Returned filtering mode. + + .. seealso:: `cuTexRefGetFilterMode` + """ + cdef CUfilter_mode pfm + with nogil: + __status__ = cuTexRefGetFilterMode(&pfm, h_tex_ref) + check_status(__status__) + return pfm + + +cpdef tuple tex_ref_get_format(intptr_t h_tex_ref): + """Gets the format used by a texture reference. + + [Deprecated]. + + Returns in ``*p_format`` and ``*p_num_channels`` the format and number of + components of the CUDA array bound to the texture reference ``h_tex_ref``. + If ``p_format`` or ``p_num_channels`` is NULL, it will be ignored. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + A 2-tuple containing: + + - int: Returned format. + - int: Returned number of components. + + .. seealso:: `cuTexRefGetFormat` + """ + cdef CUarray_format p_format + cdef int p_num_channels + with nogil: + __status__ = cuTexRefGetFormat(&p_format, &p_num_channels, h_tex_ref) + check_status(__status__) + return (p_format, p_num_channels) + + +cpdef int tex_ref_get_mipmap_filter_mode(intptr_t h_tex_ref) except? -1: + """Gets the mipmap filtering mode for a texture reference. + + [Deprecated]. + + Returns the mipmap filtering mode in ``pfm`` that's used when reading + memory through the texture reference ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + int: Returned mipmap filtering mode. + + .. seealso:: `cuTexRefGetMipmapFilterMode` + """ + cdef CUfilter_mode pfm + with nogil: + __status__ = cuTexRefGetMipmapFilterMode(&pfm, h_tex_ref) + check_status(__status__) + return pfm + + +cpdef float tex_ref_get_mipmap_level_bias(intptr_t h_tex_ref) except? -1.0: + """Gets the mipmap level bias for a texture reference. + + [Deprecated]. + + Returns the mipmap level bias in ``pBias`` that's added to the specified + mipmap level when reading memory through the texture reference + ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + float: Returned mipmap level bias. + + .. seealso:: `cuTexRefGetMipmapLevelBias` + """ + cdef float pbias + with nogil: + __status__ = cuTexRefGetMipmapLevelBias(&pbias, h_tex_ref) + check_status(__status__) + return pbias + + +cpdef tuple tex_ref_get_mipmap_level_clamp(intptr_t h_tex_ref): + """Gets the min/max mipmap level clamps for a texture reference. + + [Deprecated]. + + Returns the min/max mipmap level clamps in ``pmin_mipmap_level_clamp`` and + ``pmax_mipmap_level_clamp`` that's used when reading memory through the + texture reference ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + A 2-tuple containing: + + - float: Returned mipmap min level clamp. + - float: Returned mipmap max level clamp. + + .. seealso:: `cuTexRefGetMipmapLevelClamp` + """ + cdef float pmin_mipmap_level_clamp + cdef float pmax_mipmap_level_clamp + with nogil: + __status__ = cuTexRefGetMipmapLevelClamp(&pmin_mipmap_level_clamp, &pmax_mipmap_level_clamp, h_tex_ref) + check_status(__status__) + return (pmin_mipmap_level_clamp, pmax_mipmap_level_clamp) + + +cpdef int tex_ref_get_max_anisotropy(intptr_t h_tex_ref) except? -1: + """Gets the maximum anisotropy for a texture reference. + + [Deprecated]. + + Returns the maximum anisotropy in ``pmax_aniso`` that's used when reading + memory through the texture reference ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + int: Returned maximum anisotropy. + + .. seealso:: `cuTexRefGetMaxAnisotropy` + """ + cdef int pmax_aniso + with nogil: + __status__ = cuTexRefGetMaxAnisotropy(&pmax_aniso, h_tex_ref) + check_status(__status__) + return pmax_aniso + + +cpdef tex_ref_get_border_color(intptr_t p_border_color, intptr_t h_tex_ref): + """Gets the border color used by a texture reference. + + [Deprecated]. + + Returns in ``p_border_color``, values of the RGBA color used by the texture + reference ``h_tex_ref``. The color value is of type float and holds color + components in the following sequence: p_border_color[0] holds 'R' component + p_border_color[1] holds 'G' component p_border_color[2] holds 'B' component + p_border_color[3] holds 'A' component. + + Args: + p_border_color (intptr_t): Returned Type and Value of RGBA + color. + h_tex_ref (intptr_t): Texture reference. + + .. seealso:: `cuTexRefGetBorderColor` + """ + with nogil: + __status__ = cuTexRefGetBorderColor(p_border_color, h_tex_ref) + check_status(__status__) + + +cpdef unsigned int tex_ref_get_flags(intptr_t h_tex_ref) except? 0: + """Gets the flags used by a texture reference. + + [Deprecated]. + + Returns in ``*p_flags`` the flags of the texture reference ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + unsigned int: Returned flags. + + .. seealso:: `cuTexRefGetFlags` + """ + cdef unsigned int p_flags + with nogil: + __status__ = cuTexRefGetFlags(&p_flags, h_tex_ref) + check_status(__status__) + return p_flags + + +cpdef intptr_t tex_ref_create() except? 0: + """Creates a texture reference. + + [Deprecated]. + + Creates a texture reference and returns its handle in ``*p_tex_ref``. Once + created, the application must call :func:`tex_ref_set_array` or + ``cuTexRefSetAddress()`` 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. + + Returns: + intptr_t: Returned texture reference. + + .. seealso:: `cuTexRefCreate` + """ + cdef CUtexref p_tex_ref + with nogil: + __status__ = cuTexRefCreate(&p_tex_ref) + check_status(__status__) + return p_tex_ref + + +cpdef tex_ref_destroy(intptr_t h_tex_ref): + """Destroys a texture reference. + + [Deprecated]. + + Destroys the texture reference specified by ``h_tex_ref``. + + Args: + h_tex_ref (intptr_t): Texture reference to destroy. + + .. seealso:: `cuTexRefDestroy` + """ + with nogil: + __status__ = cuTexRefDestroy(h_tex_ref) + check_status(__status__) + + +cpdef surf_ref_set_array(intptr_t h_surf_ref, intptr_t h_array, unsigned int flags): + """Sets the CUDA array for a surface reference. + + [Deprecated]. + + Sets the CUDA array ``h_array`` to be read and written by the surface + reference ``h_surf_ref``. 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 ``h_surf_ref`` is unbound. + + Args: + h_surf_ref (intptr_t): Surface reference handle. + h_array (intptr_t): CUDA array handle. + flags (unsigned int): set to 0. + + .. seealso:: `cuSurfRefSetArray` + """ + with nogil: + __status__ = cuSurfRefSetArray(h_surf_ref, h_array, flags) + check_status(__status__) + + +cpdef intptr_t surf_ref_get_array(intptr_t h_surf_ref) except? 0: + """Passes back the CUDA array bound to a surface reference. + + [Deprecated]. + + Returns in ``*ph_array`` the CUDA array bound to the surface reference + ``h_surf_ref``, or returns ``CUDA_ERROR_INVALID_VALUE`` if the surface + reference is not bound to any CUDA array. + + Args: + h_surf_ref (intptr_t): Surface reference handle. + + Returns: + intptr_t: Surface reference handle. + + .. seealso:: `cuSurfRefGetArray` + """ + cdef CUarray ph_array + with nogil: + __status__ = cuSurfRefGetArray(&ph_array, h_surf_ref) + check_status(__status__) + return ph_array + + +cpdef unsigned long long tex_object_create(intptr_t p_res_desc, p_tex_desc, p_res_view_desc) except? 0: + """Creates a texture object. + + Creates a texture object and returns it in ``p_tex_object``. ``p_res_desc`` + describes the data to texture from. ``p_tex_desc`` describes how the data + should be sampled. ``p_res_view_desc`` is an optional argument that + specifies an alternate format for the data described by ``p_res_desc``, and + also describes the subresource region to restrict access to when texturing. + ``p_res_view_desc`` 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. + + The ``CUDA_RESOURCE_DESC`` structure is defined as:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``CUDA_RESOURCE_DESC.resType`` specifies the type of resource to texture + from. CUresourceType is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + If ``CUDA_RESOURCE_DESC.resType`` is set to ``CU_RESOURCE_TYPE_ARRAY``, + ``CUDA_RESOURCE_DESC.res.array.hArray`` must be set to a valid CUDA array + handle. + + If ``CUDA_RESOURCE_DESC.resType`` is set to + ``CU_RESOURCE_TYPE_MIPMAPPED_ARRAY``, + ``CUDA_RESOURCE_DESC.res.mipmap.hMipmappedArray`` must be set to a valid + CUDA mipmapped array handle. + + If ``CUDA_RESOURCE_DESC.resType`` is set to ``CU_RESOURCE_TYPE_LINEAR``, + ``CUDA_RESOURCE_DESC.res.linear.devPtr`` must be set to a valid device + pointer, that is aligned to ``CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT``. + ``CUDA_RESOURCE_DESC.res.linear.format`` and + ``CUDA_RESOURCE_DESC.res.linear.numChannels`` describe the format of each + component and the number of components per array element. + ``CUDA_RESOURCE_DESC.res.linear.sizeInBytes`` specifies the size of the + array in bytes. The total number of elements in the linear address range + cannot exceed ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH``. The + number of elements is computed as (sizeInBytes / (sizeof(format) * + numChannels)). + + If ``CUDA_RESOURCE_DESC.resType`` is set to ``CU_RESOURCE_TYPE_PITCH2D``, + ``CUDA_RESOURCE_DESC.res.pitch2D.devPtr`` must be set to a valid device + pointer, that is aligned to ``CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT``. + ``CUDA_RESOURCE_DESC.res.pitch2D.format`` and + ``CUDA_RESOURCE_DESC.res.pitch2D.numChannels`` describe the format of each + component and the number of components per array element. + ``CUDA_RESOURCE_DESC.res.pitch2D.width`` and + ``CUDA_RESOURCE_DESC.res.pitch2D.height`` specify the width and height of + the array in elements, and cannot exceed + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH`` and + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT`` respectively. + ``CUDA_RESOURCE_DESC.res.pitch2D.pitchInBytes`` specifies the pitch between + two rows in bytes and has to be aligned to + ``CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT``. Pitch cannot exceed + ``CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH``. + + - ``flags`` must be set to zero. + + The ``CUDA_TEXTURE_DESC`` struct is defined as. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where. + + - ``CUDA_TEXTURE_DESC.addressMode`` specifies the addressing mode for each + dimension of the texture data. ``CUaddress_mode`` is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - This is ignored if ``CUDA_RESOURCE_DESC.resType`` is + ``CU_RESOURCE_TYPE_LINEAR``. Also, if the flag, + ``CU_TRSF_NORMALIZED_COORDINATES`` is not set, the only supported address + mode is ``CU_TR_ADDRESS_MODE_CLAMP``. + + - ``CUDA_TEXTURE_DESC.filterMode`` specifies the filtering mode to be used + when fetching from the texture. ``CUfilter_mode`` is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - This is ignored if ``CUDA_RESOURCE_DESC.resType`` is + ``CU_RESOURCE_TYPE_LINEAR``. + + - ``CUDA_TEXTURE_DESC.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 ``CUDA_TEXTURE_DESC.addressMode`` are + ignored. Instead, if the ``CUDA_TEXTURE_DESC.filterMode`` is set to + ``CU_TR_FILTER_MODE_POINT`` the address mode ``CU_TR_ADDRESS_MODE_CLAMP`` + will be applied for all dimensions. If the ``CUDA_TEXTURE_DESC.filterMode`` + is set to ``CU_TR_FILTER_MODE_LINEAR`` seamless cube map filtering will be + performed when sampling along the cube face borders. + + - ``CUDA_TEXTURE_DESC.maxAnisotropy`` specifies the maximum anisotropy + ratio to be used when doing anisotropic filtering. This value will be + clamped to the range [1,16]. + + - ``CUDA_TEXTURE_DESC.mipmapFilterMode`` specifies the filter mode when the + calculated mipmap level lies between two defined mipmap levels. + + - ``CUDA_TEXTURE_DESC.mipmapLevelBias`` specifies the offset to be applied + to the calculated mipmap level. + + - ``CUDA_TEXTURE_DESC.minMipmapLevelClamp`` specifies the lower end of the + mipmap level range to clamp access to. + + - ``CUDA_TEXTURE_DESC.maxMipmapLevelClamp`` specifies the upper end of the + mipmap level range to clamp access to. + + The ``CUDA_RESOURCE_VIEW_DESC`` struct is defined as. + + **View CUDA Toolkit Documentation for a C++ code example**. + + where:. + + - ``CUDA_RESOURCE_VIEW_DESC.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 + ``CU_AD_FORMAT_UNSIGNED_INT32``. 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 ``CU_AD_FORMAT_UNSIGNED_INT32`` with 2 channels. + The other BC formats require the underlying resource to have the same base + format but with 4 channels. + + - ``CUDA_RESOURCE_VIEW_DESC.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. + + - ``CUDA_RESOURCE_VIEW_DESC.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. + + - ``CUDA_RESOURCE_VIEW_DESC.depth`` specifies the new depth of the texture + data. This value has to be equal to that of the original resource. + + - ``CUDA_RESOURCE_VIEW_DESC.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.``CUDA_TEXTURE_DESC.minMipmapLevelClamp`` and + ``CUDA_TEXTURE_DESC.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. + + - ``CUDA_RESOURCE_VIEW_DESC.lastMipmapLevel`` specifies the least detailed + mipmap level. For non-mipmapped resources, this value has to be zero. + + - ``CUDA_RESOURCE_VIEW_DESC.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. + + - ``CUDA_RESOURCE_VIEW_DESC.lastLayer`` specifies the last layer index for + layered textures. For non-layered resources, this value has to be zero. + + Args: + p_res_desc (intptr_t): Resource descriptor. + p_tex_desc (intptr_t): Texture descriptor. + p_res_view_desc (intptr_t): Resource view descriptor. + + Returns: + unsigned long long: Texture object to create. + + .. seealso:: `cuTexObjectCreate` + """ + cdef intptr_t _p_tex_desc_ptr_ = int(p_tex_desc) + cdef intptr_t _p_res_view_desc_ptr_ = int(p_res_view_desc) + cdef CUtexObject p_tex_object + with nogil: + __status__ = cuTexObjectCreate(&p_tex_object, p_res_desc, _p_tex_desc_ptr_, _p_res_view_desc_ptr_) + check_status(__status__) + return p_tex_object + + +cpdef tex_object_destroy(unsigned long long tex_object): + """Destroys a texture object. + + Destroys the texture object specified by ``tex_object``. + + Args: + tex_object (unsigned long long): Texture object to destroy. + + .. seealso:: `cuTexObjectDestroy` + """ + with nogil: + __status__ = cuTexObjectDestroy(tex_object) + check_status(__status__) + + +cpdef tex_object_get_resource_desc(intptr_t p_res_desc, unsigned long long tex_object): + """Returns a texture object's resource descriptor. + + Returns the resource descriptor for the texture object specified by + ``tex_object``. + + Args: + p_res_desc (intptr_t): Resource descriptor. + tex_object (unsigned long long): Texture object. + + .. seealso:: `cuTexObjectGetResourceDesc` + """ + with nogil: + __status__ = cuTexObjectGetResourceDesc(p_res_desc, tex_object) + check_status(__status__) + + +cpdef tex_object_get_texture_desc(p_tex_desc, unsigned long long tex_object): + """Returns a texture object's texture descriptor. + + Returns the texture descriptor for the texture object specified by + ``tex_object``. + + Args: + p_tex_desc (intptr_t): Texture descriptor. + tex_object (unsigned long long): Texture object. + + .. seealso:: `cuTexObjectGetTextureDesc` + """ + cdef intptr_t _p_tex_desc_ptr_ = int(p_tex_desc) + with nogil: + __status__ = cuTexObjectGetTextureDesc(_p_tex_desc_ptr_, tex_object) + check_status(__status__) + + +cpdef object tex_object_get_resource_view_desc(unsigned long long tex_object): + """Returns a texture object's resource view descriptor. + + Returns the resource view descriptor for the texture object specified by + ``tex_object``. If no resource view was set for ``tex_object``, the + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Args: + tex_object (unsigned long long): Texture object. + + Returns: + CUDA_RESOURCE_VIEW_DESC_v1: Resource view descriptor. + + .. seealso:: `cuTexObjectGetResourceViewDesc` + """ + cdef ResourceViewDesc_v1 p_res_view_desc_py = ResourceViewDesc_v1() + cdef CUDA_RESOURCE_VIEW_DESC *p_res_view_desc = (p_res_view_desc_py._get_ptr()) + with nogil: + __status__ = cuTexObjectGetResourceViewDesc(p_res_view_desc, tex_object) + check_status(__status__) + return p_res_view_desc_py + + +cpdef unsigned long long surf_object_create(intptr_t p_res_desc) except? 0: + """Creates a surface object. + + Creates a surface object and returns it in ``p_surf_object``. + ``p_res_desc`` describes the data to perform surface load/stores on. + ``CUDA_RESOURCE_DESC.resType`` must be ``CU_RESOURCE_TYPE_ARRAY`` and + ``CUDA_RESOURCE_DESC.res.array.hArray`` must be set to a valid CUDA array + handle. ``CUDA_RESOURCE_DESC.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. + + Args: + p_res_desc (intptr_t): Resource descriptor. + + Returns: + unsigned long long: Surface object to create. + + .. seealso:: `cuSurfObjectCreate` + """ + cdef CUsurfObject p_surf_object + with nogil: + __status__ = cuSurfObjectCreate(&p_surf_object, p_res_desc) + check_status(__status__) + return p_surf_object + + +cpdef surf_object_destroy(unsigned long long surf_object): + """Destroys a surface object. + + Destroys the surface object specified by ``surf_object``. + + Args: + surf_object (unsigned long long): Surface object to destroy. + + .. seealso:: `cuSurfObjectDestroy` + """ + with nogil: + __status__ = cuSurfObjectDestroy(surf_object) + check_status(__status__) + + +cpdef surf_object_get_resource_desc(intptr_t p_res_desc, unsigned long long surf_object): + """Returns a surface object's resource descriptor. + + Returns the resource descriptor for the surface object specified by + ``surf_object``. + + Args: + p_res_desc (intptr_t): Resource descriptor. + surf_object (unsigned long long): Surface object. + + .. seealso:: `cuSurfObjectGetResourceDesc` + """ + with nogil: + __status__ = cuSurfObjectGetResourceDesc(p_res_desc, surf_object) + check_status(__status__) + + +cpdef tensor_map_encode_tiled(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, intptr_t box_dim, intptr_t element_strides, int interleave, int swizzle, int l2promotion, int oob_fill): + """Create 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 ``tensor_map``. + + 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:. + + - ``tensor_map`` address must be aligned to 64 bytes. + + - ``tensor_data_type`` has to be an enum from ``CUtensor_mapDataType`` + which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B`` copies '16 x U4' packed values + to memory aligned as 8 bytes. There are no gaps between packed values. + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B`` 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. ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` 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. + + - ``tensor_rank`` must be non-zero and less than or equal to the maximum + supported dimensionality of 5. If ``interleave`` is not + ``CU_TENSOR_MAP_INTERLEAVE_NONE``, then ``tensor_rank`` must additionally + be greater than or equal to 3. + + - ``global_address``, 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, + ``global_address`` must be 32 byte aligned. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` + or ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, ``global_address`` must be 32 + byte aligned. + + ``global_dim`` array, which specifies tensor size of each of the + ``tensor_rank`` 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 ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, global_dim[0] must be a multiple + of 128. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``global_dim``[0] must be a multiple of 2. + + - Dimension for the packed data types must reflect the number of individual + U# values. + + ``global_strides`` array, which specifies tensor stride of each of the + lower ``tensor_rank`` - 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, the strides must + be a multiple of 32. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, the strides must be a multiple + of 32. Each following dimension specified includes previous dimension + stride:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + ``box_dim`` array, which specifies number of elements to be traversed along + each of the ``tensor_rank`` dimensions, must be non-zero and less than or + equal to 256. Additionally, the following requirements need to be met:. + + - When ``interleave`` is ``CU_TENSOR_MAP_INTERLEAVE_NONE``, { + ``box_dim``[0] * elementSizeInBytes( ``tensor_data_type`` ) } must be a + multiple of 16 bytes. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, box_dim[0] must be 128. + + ``element_strides`` array, which specifies the iteration step along each of + the ``tensor_rank`` dimensions, must be non-zero and less than or equal to + 8. Note that when ``interleave`` is ``CU_TENSOR_MAP_INTERLEAVE_NONE``, the + first element of this array is ignored since TMA doesn’t support the stride + for dimension zero. When all elements of ``element_strides`` array is one, + ``box_dim`` specifies the number of elements to load. However, if the + ``element_strides``[i] is not equal to one, then TMA loads ceil( + ``box_dim``[i] / ``element_strides``[i]) number of elements along i-th + dimension. To load N elements along i-th dimension, ``box_dim``[i] must be + set to N * ``element_strides``[i]. + + - ``interleave`` specifies the interleaved layout of type + ``CUtensor_mapInterleave``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 ``CU_TENSOR_MAP_INTERLEAVE_NONE`` and + ``swizzle`` is not ``CU_TENSOR_MAP_SWIZZLE_NONE``, the bounding box inner + dimension (computed as ``box_dim``[0] multiplied by element size derived + from ``tensor_data_type``) must be less than or equal to the swizzle size. + + - CU_TENSOR_MAP_SWIZZLE_32B requires the bounding box inner dimension to + be <= 32. + + - CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to + be <= 64. + + - CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to + be <= 128. Additionally, ``tensor_data_type`` of + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` requires ``interleave`` to be + ``CU_TENSOR_MAP_INTERLEAVE_NONE``. + + - ``swizzle``, which specifies the shared memory bank swizzling pattern, + has to be of type ``CUtensor_mapSwizzle`` which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, ``swizzle`` must be + ``CU_TENSOR_MAP_SWIZZLE_32B``. Other interleave modes can have any + swizzling pattern. When the ``tensor_data_type`` is + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``, only the following swizzle modes + are supported:. + + - CU_TENSOR_MAP_SWIZZLE_NONE (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B (Store only) When the + ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, only the + following swizzle modes are supported:. + + - CU_TENSOR_MAP_SWIZZLE_NONE (Load only). + + - CU_TENSOR_MAP_SWIZZLE_128B (Load only). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only). + + - ``l2promotion`` specifies L2 fetch size which indicates the byte + granurality at which L2 requests is filled from DRAM. It must be of type + ``CUtensor_mapL2promotion``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``oob_fill``, which indicates whether zero or a special NaN constant + should be used to fill out-of-bound elements, must be of type + ``CUtensor_mapFloatOOBfill`` which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - Note that ``CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA`` can only + be used when ``tensor_data_type`` represents a floating-point data type, + and when ``tensor_data_type`` is not + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, and + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``. + + Args: + tensor_map (intptr_t): Tensor map object to create. + tensor_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint64_t): Dimensionality of tensor. + global_address (intptr_t): Starting address of memory region + described by tensor. + global_dim (intptr_t): Array containing tensor size (number of + elements) along each of the ``tensor_rank`` dimensions. + global_strides (intptr_t): Array containing stride size (in + bytes) along each of the ``tensor_rank`` - 1 dimensions. + box_dim (intptr_t): Array containing traversal box size + (number of elments) along each of the ``tensor_rank`` + dimensions. Specifies how many elements to be traversed + along each tensor dimension. + element_strides (intptr_t): Array containing traversal stride + in each of the ``tensor_rank`` dimensions. + interleave (TensorMapInterleave): Type of interleaved layout + the tensor addresses. + swizzle (TensorMapSwizzle): Bank swizzling pattern inside + shared memory. + l2promotion (TensorMapL2promotion): L2 promotion size. + oob_fill (TensorMapFloatOOBfill): Indicate whether zero or + special NaN constant must be used to fill out-of-bound + elements. + + .. seealso:: `cuTensorMapEncodeTiled` + """ + cdef intptr_t _tensor_map_ptr_ = int(tensor_map) + with nogil: + __status__ = cuTensorMapEncodeTiled(_tensor_map_ptr_, tensor_data_type, tensor_rank, global_address, global_dim, global_strides, box_dim, element_strides, interleave, swizzle, l2promotion, oob_fill) + check_status(__status__) + + +cpdef tensor_map_encode_im2col(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, intptr_t pixel_box_lower_corner, intptr_t pixel_box_upper_corner, uint64_t channels_per_pixel, uint64_t pixels_per_column, intptr_t element_strides, int interleave, int swizzle, int l2promotion, int oob_fill): + """Create 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 + ``tensor_map``. + + 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:. + + - ``tensor_map`` address must be aligned to 64 bytes. + + - ``tensor_data_type`` has to be an enum from ``CUtensor_mapDataType`` + which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B`` copies '16 x U4' packed values + to memory aligned as 8 bytes. There are no gaps between packed values. + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B`` 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. ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` 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. + + - ``tensor_rank``, which specifies the number of tensor dimensions, must be + 3, 4, or 5. + + - ``global_address``, 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, + ``global_address`` must be 32 byte aligned. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` + or ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, ``global_address`` must be 32 + byte aligned. + + - ``global_dim`` array, which specifies tensor size of each of the + ``tensor_rank`` 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 ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` + or ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, global_dim[0] must be a + multiple of 128. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``global_dim``[0] must be a multiple of 2. + + - Dimension for the packed data types must reflect the number of + individual U# values. + + - ``global_strides`` array, which specifies tensor stride of each of the + lower ``tensor_rank`` - 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, the strides + must be a multiple of 32. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` + or ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, the strides must be a + multiple of 32. Each following dimension specified includes previous + dimension stride:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``pixel_box_lower_corner`` 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 ``tensor_rank`` is 3, one signed offset within range [-32768, + 32767] is supported. + + - When ``tensor_rank`` is 4, two signed offsets each within range [-128, + 127] are supported. + + - When ``tensor_rank`` is 5, three offsets each within range [-16, 15] + are supported. + + - ``pixel_box_upper_corner`` 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 ``tensor_rank`` is 3, one signed offset within range [-32768, + 32767] is supported. + + - When ``tensor_rank`` is 4, two signed offsets each within range [-128, + 127] are supported. + + - When ``tensor_rank`` is 5, three offsets each within range [-16, 15] + are supported. The bounding box specified by ``pixel_box_lower_corner`` and + ``pixel_box_upper_corner`` must have non-zero area. + + - ``channels_per_pixel``, which specifies the number of elements which must + be accessed along C dimension, must be less than or equal to 256. + Additionally, when ``tensor_data_type`` is + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, ``channels_per_pixel`` must be + 128. + + - ``pixels_per_column``, 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. + + - ``element_strides`` array, which specifies the iteration step along each + of the ``tensor_rank`` dimensions, must be non-zero and less than or equal + to 8. Note that when ``interleave`` is ``CU_TENSOR_MAP_INTERLEAVE_NONE``, + the first element of this array is ignored since TMA doesn’t support the + stride for dimension zero. When all elements of the ``element_strides`` + array are one, ``boxDim`` specifies the number of elements to load. + However, if ``element_strides``[i] is not equal to one for some ``i``, then + TMA loads ceil( ``boxDim``[i] / ``element_strides``[i]) number of elements + along i-th dimension. To load N elements along i-th dimension, + ``boxDim``[i] must be set to N * ``element_strides``[i]. + + - ``interleave`` specifies the interleaved layout of type + ``CUtensor_mapInterleave``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 ``CU_TENSOR_MAP_INTERLEAVE_NONE`` and + ``swizzle`` is not ``CU_TENSOR_MAP_SWIZZLE_NONE``, the bounding box inner + dimension (computed as ``channels_per_pixel`` multiplied by element size in + bytes derived from ``tensor_data_type``) must be less than or equal to the + swizzle size. + + - CU_TENSOR_MAP_SWIZZLE_32B requires the bounding box inner dimension to + be <= 32. + + - CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to + be <= 64. + + - CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to + be <= 128. Additionally, ``tensor_data_type`` of + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` requires ``interleave`` to be + ``CU_TENSOR_MAP_INTERLEAVE_NONE``. + + - ``swizzle``, which specifies the shared memory bank swizzling pattern, + has to be of type ``CUtensor_mapSwizzle`` which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, ``swizzle`` must be + ``CU_TENSOR_MAP_SWIZZLE_32B``. Other interleave modes can have any + swizzling pattern. When the ``tensor_data_type`` is + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``, only the following swizzle modes + are supported:. + + - CU_TENSOR_MAP_SWIZZLE_NONE (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B (Store only) When the + ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, only the + following swizzle modes are supported:. + + - CU_TENSOR_MAP_SWIZZLE_NONE (Load only). + + - CU_TENSOR_MAP_SWIZZLE_128B (Load only). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only). + + - ``l2promotion`` specifies L2 fetch size which indicates the byte + granularity at which L2 requests are filled from DRAM. It must be of type + ``CUtensor_mapL2promotion``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``oob_fill``, which indicates whether zero or a special NaN constant + should be used to fill out-of-bound elements, must be of type + ``CUtensor_mapFloatOOBfill`` which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - Note that ``CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA`` can only + be used when ``tensor_data_type`` represents a floating-point data type, + and when ``tensor_data_type`` is not + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, and + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``. + + Args: + tensor_map (intptr_t): Tensor map object to create. + tensor_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint64_t): Dimensionality of tensor; must be at + least 3. + global_address (intptr_t): Starting address of memory region + described by tensor. + global_dim (intptr_t): Array containing tensor size (number of + elements) along each of the ``tensor_rank`` dimensions. + global_strides (intptr_t): Array containing stride size (in + bytes) along each of the ``tensor_rank`` - 1 dimensions. + pixel_box_lower_corner (intptr_t): Array containing DHW + dimensions of lower box corner. + pixel_box_upper_corner (intptr_t): Array containing DHW + dimensions of upper box corner. + channels_per_pixel (uint64_t): Number of channels per pixel. + pixels_per_column (uint64_t): Number of pixels per column. + element_strides (intptr_t): Array containing traversal stride + in each of the ``tensor_rank`` dimensions. + interleave (TensorMapInterleave): Type of interleaved layout + the tensor addresses. + swizzle (TensorMapSwizzle): Bank swizzling pattern inside + shared memory. + l2promotion (TensorMapL2promotion): L2 promotion size. + oob_fill (TensorMapFloatOOBfill): Indicate whether zero or + special NaN constant will be used to fill out-of-bound + elements. + + .. seealso:: `cuTensorMapEncodeIm2col` + """ + cdef intptr_t _tensor_map_ptr_ = int(tensor_map) + with nogil: + __status__ = cuTensorMapEncodeIm2col(_tensor_map_ptr_, tensor_data_type, tensor_rank, global_address, global_dim, global_strides, pixel_box_lower_corner, pixel_box_upper_corner, channels_per_pixel, pixels_per_column, element_strides, interleave, swizzle, l2promotion, oob_fill) + check_status(__status__) + + +cpdef tensor_map_encode_im2col_wide(tensor_map, int tensor_data_type, uint64_t tensor_rank, intptr_t global_address, intptr_t global_dim, intptr_t global_strides, int pixel_box_lower_corner_width, int pixel_box_upper_corner_width, uint64_t channels_per_pixel, uint64_t pixels_per_column, intptr_t element_strides, int interleave, int mode, int swizzle, int l2promotion, int oob_fill): + """Create 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 ``tensor_map``. 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:. + + - ``tensor_map`` address must be aligned to 64 bytes. + + - ``tensor_data_type`` has to be an enum from ``CUtensor_mapDataType`` + which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B`` copies '16 x U4' packed values + to memory aligned as 8 bytes. There are no gaps between packed values. + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B`` 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. ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` 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. + + - ``tensor_rank``, which specifies the number of tensor dimensions, must be + 3, 4, or 5. + + - ``global_address``, 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, + ``global_address`` must be 32 byte aligned. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` + or ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, ``global_address`` must be 32 + byte aligned. + + ``global_dim`` array, which specifies tensor size of each of the + ``tensor_rank`` 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 ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, global_dim[0] must be a multiple + of 128. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``global_dim``[0] must be a multiple of 2. + + - Dimension for the packed data types must reflect the number of individual + U# values. + + ``global_strides`` array, which specifies tensor stride of each of the + lower ``tensor_rank`` - 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 ``CU_TENSOR_MAP_INTERLEAVE_32B``, the strides must + be a multiple of 32. + + - When ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, the strides must be a multiple + of 32. Each following dimension specified includes previous dimension + stride:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + ``pixel_box_lower_corner_width`` specifies the coordinate offset W of the + bounding box from left corner. The offset must be within range [-32768, + 32767]. + + - ``pixel_box_upper_corner_width`` 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 ``pixel_box_lower_corner_width`` and + ``pixel_box_upper_corner_width`` must have non-zero area. Note that the + size of the box along D and H dimensions is always equal to one. + + - ``channels_per_pixel``, which specifies the number of elements which must + be accessed along C dimension, must be less than or equal to 256. + Additionally, when ``tensor_data_type`` is + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` or + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, ``channels_per_pixel`` must be + 128. + + - ``pixels_per_column``, 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 ``CU_TENSOR_MAP_IM2COL_WIDE_MODE_W128``. + + - ``element_strides`` array, which specifies the iteration step along each + of the ``tensor_rank`` dimensions, must be non-zero and less than or equal + to 8. Note that when ``interleave`` is ``CU_TENSOR_MAP_INTERLEAVE_NONE``, + the first element of this array is ignored since TMA doesn’t support the + stride for dimension zero. When all elements of the ``element_strides`` + array are one, ``boxDim`` specifies the number of elements to load. + However, if ``element_strides``[i] is not equal to one for some ``i``, then + TMA loads ceil( ``boxDim``[i] / ``element_strides``[i]) number of elements + along i-th dimension. To load N elements along i-th dimension, + ``boxDim``[i] must be set to N * ``element_strides``[i]. + + - ``interleave`` specifies the interleaved layout of type + ``CUtensor_mapInterleave``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 ``CU_TENSOR_MAP_INTERLEAVE_NONE``, the + bounding box inner dimension (computed as ``channels_per_pixel`` multiplied + by element size in bytes derived from ``tensor_data_type``) must be less + than or equal to the swizzle size. + + - CU_TENSOR_MAP_SWIZZLE_64B requires the bounding box inner dimension to + be <= 64. + + - CU_TENSOR_MAP_SWIZZLE_128B* require the bounding box inner dimension to + be <= 128. Additionally, ``tensor_data_type`` of + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B`` requires ``interleave`` to be + ``CU_TENSOR_MAP_INTERLEAVE_NONE``. + + - ``mode``, which describes loading of elements loaded along the W + dimension, has to be one of the following ``CUtensor_mapIm2ColWideMode`` + types:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``CU_TENSOR_MAP_IM2COL_WIDE_MODE_W`` allows the number of elements loaded + along the W dimension to be specified via the ``pixels_per_column`` field. + + - ``swizzle``, which specifies the shared memory bank swizzling pattern, + must be one of the following ``CUtensor_mapSwizzle`` modes (other swizzle + modes are not supported):. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - 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 + ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``, only the + following swizzle modes are supported:. + + - CU_TENSOR_MAP_SWIZZLE_64B (Store only). + + - CU_TENSOR_MAP_SWIZZLE_128B (Load & Store). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load & Store) When the + ``tensor_data_type`` is ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, only the + following swizzle modes are supported:. + + - CU_TENSOR_MAP_SWIZZLE_128B (Load only). + + - CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B (Load only). + + Additionally, ``CU_TENSOR_MAP_SWIZZLE_96B`` is supported only when ``mode`` + is ``CU_TENSOR_MAP_IM2COL_WIDE_MODE_W``. + + - ``l2promotion`` specifies L2 fetch size which indicates the byte + granularity at which L2 requests are filled from DRAM. It must be of type + ``CUtensor_mapL2promotion``, which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - ``oob_fill``, which indicates whether zero or a special NaN constant + should be used to fill out-of-bound elements, must be of type + ``CUtensor_mapFloatOOBfill`` which is defined as:. + + - **View CUDA Toolkit Documentation for a C++ code example**. + + - Note that ``CU_TENSOR_MAP_FLOAT_OOB_FILL_NAN_REQUEST_ZERO_FMA`` can only + be used when ``tensor_data_type`` represents a floating-point data type, + and when ``tensor_data_type`` is not + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B``, + ``CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B``, and + ``CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B``. + + Args: + tensor_map (intptr_t): Tensor map object to create. + tensor_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint64_t): Dimensionality of tensor; must be at + least 3. + global_address (intptr_t): Starting address of memory region + described by tensor. + global_dim (intptr_t): Array containing tensor size (number of + elements) along each of the ``tensor_rank`` dimensions. + global_strides (intptr_t): Array containing stride size (in + bytes) along each of the ``tensor_rank`` - 1 dimensions. + pixel_box_lower_corner_width (int): Width offset of left box + corner. + pixel_box_upper_corner_width (int): Width offset of right box + corner. + channels_per_pixel (uint64_t): Number of channels per pixel. + pixels_per_column (uint64_t): Number of pixels per column. + element_strides (intptr_t): Array containing traversal stride + in each of the ``tensor_rank`` dimensions. + interleave (TensorMapInterleave): Type of interleaved layout + the tensor addresses. + mode (TensorMapIm2ColWideMode): W or W128 mode. + swizzle (TensorMapSwizzle): Bank swizzling pattern inside + shared memory. + l2promotion (TensorMapL2promotion): L2 promotion size. + oob_fill (TensorMapFloatOOBfill): Indicate whether zero or + special NaN constant will be used to fill out-of-bound + elements. + + .. seealso:: `cuTensorMapEncodeIm2colWide` + """ + cdef intptr_t _tensor_map_ptr_ = int(tensor_map) + with nogil: + __status__ = cuTensorMapEncodeIm2colWide(_tensor_map_ptr_, tensor_data_type, tensor_rank, global_address, global_dim, global_strides, pixel_box_lower_corner_width, pixel_box_upper_corner_width, channels_per_pixel, pixels_per_column, element_strides, interleave, mode, swizzle, l2promotion, oob_fill) + check_status(__status__) + + +cpdef tensor_map_replace_address(tensor_map, intptr_t global_address): + """Modify an existing tensor map descriptor with an updated global address. + + Modifies the descriptor for Tensor Memory Access (TMA) object passed in + ``tensor_map`` with an updated ``global_address``. + + 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. + + Args: + tensor_map (intptr_t): Tensor map object to modify. + global_address (intptr_t): Starting address of memory region + described by tensor, must follow previous alignment + requirements. + + .. seealso:: `cuTensorMapReplaceAddress` + """ + cdef intptr_t _tensor_map_ptr_ = int(tensor_map) + with nogil: + __status__ = cuTensorMapReplaceAddress(_tensor_map_ptr_, global_address) + check_status(__status__) + + +cpdef int device_can_access_peer(int dev, int peer_dev) except? -1: + """Queries if a device may directly access a peer device's memory. + + Returns in ``*can_access_peer`` a value of 1 if contexts on ``dev`` are + capable of directly accessing memory from contexts on ``peer_dev`` and 0 + otherwise. If direct access of ``peer_dev`` from ``dev`` is possible, then + access may be enabled on two specific contexts by calling + :func:`ctx_enable_peer_access`. + + Args: + dev (int): Device from which allocations on ``peer_dev`` are + to be directly accessed. + peer_dev (int): Device on which the allocations to be directly + accessed by ``dev`` reside. + + Returns: + int: Returned access capability. + + .. seealso:: `cuDeviceCanAccessPeer` + """ + cdef int can_access_peer + with nogil: + __status__ = cuDeviceCanAccessPeer(&can_access_peer, dev, peer_dev) + check_status(__status__) + return can_access_peer + + +cpdef ctx_enable_peer_access(intptr_t peer_context, unsigned int flags): + """Enables direct access to memory allocations in a peer context. + + If both the current context and ``peer_context`` are on devices which + support unified addressing (as may be queried using + ``CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING``) and same major compute + capability, then on success all allocations from ``peer_context`` 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 ``peer_context``, a separate + symmetric call to :func:`ctx_enable_peer_access` 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 ``CUDA_ERROR_PEER_ACCESS_UNSUPPORTED`` if + :func:`device_can_access_peer` indicates that the ``CUdevice`` of the + current context cannot directly access memory from the ``CUdevice`` of + ``peer_context``. + + Returns ``CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED`` if direct access of + ``peer_context`` from the current context has already been enabled. + + Returns ``CUDA_ERROR_TOO_MANY_PEERS`` if direct peer access is not possible + because hardware resources required for peer access have been exhausted. + + Returns ``CUDA_ERROR_INVALID_CONTEXT`` if there is no current context, + ``peer_context`` is not a valid context, or if the current context is + ``peer_context``. + + Returns ``CUDA_ERROR_INVALID_VALUE`` if ``flags`` is not 0. + + Args: + peer_context (intptr_t): Peer context to enable direct access + to from the current context. + flags (unsigned int): Reserved for future use and must be set + to 0. + + .. seealso:: `cuCtxEnablePeerAccess` + """ + with nogil: + __status__ = cuCtxEnablePeerAccess(peer_context, flags) + check_status(__status__) + + +cpdef ctx_disable_peer_access(intptr_t peer_context): + """Disables direct access to memory allocations in a peer context and unregisters any registered allocations. + + Returns ``CUDA_ERROR_PEER_ACCESS_NOT_ENABLED`` if direct peer access has + not yet been enabled from ``peer_context`` to the current context. + + Returns ``CUDA_ERROR_INVALID_CONTEXT`` if there is no current context, or + if ``peer_context`` is not a valid context. + + Args: + peer_context (intptr_t): Peer context to disable direct access + to. + + .. seealso:: `cuCtxDisablePeerAccess` + """ + with nogil: + __status__ = cuCtxDisablePeerAccess(peer_context) + check_status(__status__) + + +cpdef int device_get_p2p_attribute(int attrib, int src_device, int dst_device) except? -1: + """Queries attributes of the link between two devices. + + Returns in ``*value`` the value of the requested attribute ``attrib`` of + the link between ``src_device`` and ``dst_device``. The supported + attributes are:. + + - ``CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK``: A relative value indicating + the performance of the link between two devices. + + - ``CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED`` P2P: 1 if P2P Access is + enable. + + - ``CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED``: 1 if all CUDA-valid + atomic operations over the link are supported. + + - ``CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED``: 1 if cudaArray + can be accessed over the link. + + - ``CU_DEVICE_P2P_ATTRIBUTE_ONLY_PARTIAL_NATIVE_ATOMIC_SUPPORTED``: 1 if + some CUDA-valid atomic operations over the link are supported. Information + about specific operations can be retrieved with + ``cuDeviceGetP2PAtomicCapabilities``. + + Returns ``CUDA_ERROR_INVALID_DEVICE`` if ``src_device`` or ``dst_device`` + are not valid or if they represent the same device. + + Returns ``CUDA_ERROR_INVALID_VALUE`` if ``attrib`` is not valid or if + ``value`` is a null pointer. + + Args: + attrib (DeviceP2PAttribute): The requested attribute of the + link between ``src_device`` and ``dst_device``. + src_device (int): The source device of the target link. + dst_device (int): The destination device of the target link. + + Returns: + int: Returned value of the requested attribute. + + .. seealso:: `cuDeviceGetP2PAttribute` + """ + cdef int value + with nogil: + __status__ = cuDeviceGetP2PAttribute(&value, attrib, src_device, dst_device) + check_status(__status__) + return value + + +cpdef graphics_unregister_resource(intptr_t resource): + """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 ``CUDA_ERROR_INVALID_HANDLE`` is returned. + + Args: + resource (intptr_t): Resource to unregister. + + .. seealso:: `cuGraphicsUnregisterResource` + """ + with nogil: + __status__ = cuGraphicsUnregisterResource(resource) + check_status(__status__) + + +cpdef intptr_t graphics_sub_resource_get_mapped_array(intptr_t resource, unsigned int array_index, unsigned int mip_level) except? 0: + """Get an array through which to access a subresource of a mapped graphics resource. + + Returns in ``*p_array`` an array through which the subresource of the + mapped graphics resource ``resource`` which corresponds to array index + ``array_index`` and mipmap level ``mip_level`` may be accessed. The value + set in ``*p_array`` may change every time that ``resource`` is mapped. + + If ``resource`` is not a texture then it cannot be accessed via an array + and ``CUDA_ERROR_NOT_MAPPED_AS_ARRAY`` is returned. If ``array_index`` is + not a valid array index for ``resource`` then ``CUDA_ERROR_INVALID_VALUE`` + is returned. If ``mip_level`` is not a valid mipmap level for ``resource`` + then ``CUDA_ERROR_INVALID_VALUE`` is returned. If ``resource`` is not + mapped then ``CUDA_ERROR_NOT_MAPPED`` is returned. + + Args: + resource (intptr_t): Mapped resource to access. + array_index (unsigned int): Array index for array textures or + cubemap face index as defined by ``CUarray_cubemap_face`` + for cubemap textures for the subresource to access. + mip_level (unsigned int): Mipmap level for the subresource to + access. + + Returns: + intptr_t: Returned array through which a subresource of + ``resource`` may be accessed. + + .. seealso:: `cuGraphicsSubResourceGetMappedArray` + """ + cdef CUarray p_array + with nogil: + __status__ = cuGraphicsSubResourceGetMappedArray(&p_array, resource, array_index, mip_level) + check_status(__status__) + return p_array + + +cpdef intptr_t graphics_resource_get_mapped_mipmapped_array(intptr_t resource) except? 0: + """Get a mipmapped array through which to access a mapped graphics resource. + + Returns in ``*p_mipmapped_array`` a mipmapped array through which the + mapped graphics resource ``resource``. The value set in + ``*p_mipmapped_array`` may change every time that ``resource`` is mapped. + + If ``resource`` is not a texture then it cannot be accessed via a mipmapped + array and ``CUDA_ERROR_NOT_MAPPED_AS_ARRAY`` is returned. If ``resource`` + is not mapped then ``CUDA_ERROR_NOT_MAPPED`` is returned. + + Args: + resource (intptr_t): Mapped resource to access. + + Returns: + intptr_t: Returned mipmapped array through which ``resource`` + may be accessed. + + .. seealso:: `cuGraphicsResourceGetMappedMipmappedArray` + """ + cdef CUmipmappedArray p_mipmapped_array + with nogil: + __status__ = cuGraphicsResourceGetMappedMipmappedArray(&p_mipmapped_array, resource) + check_status(__status__) + return p_mipmapped_array + + +cpdef tuple graphics_resource_get_mapped_pointer_v2(intptr_t resource): + """Get a device pointer through which to access a mapped graphics resource. + + Returns in ``*p_dev_ptr`` a pointer through which the mapped graphics + resource ``resource`` may be accessed. Returns in ``p_size`` 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 ``CUDA_ERROR_NOT_MAPPED_AS_POINTER`` is returned. If ``resource`` is + not mapped then ``CUDA_ERROR_NOT_MAPPED`` is returned. + + Args: + resource (intptr_t): Mapped resource to access. + + Returns: + A 2-tuple containing: + + - unsigned long long: Returned pointer through which + ``resource`` may be accessed. + - size_t: Returned size of the buffer accessible starting at + ``*pPointer``. + + .. seealso:: `cuGraphicsResourceGetMappedPointer_v2` + """ + cdef CUdeviceptr p_dev_ptr + cdef size_t p_size + with nogil: + __status__ = cuGraphicsResourceGetMappedPointer(&p_dev_ptr, &p_size, resource) + check_status(__status__) + return (p_dev_ptr, p_size) + + +cpdef graphics_resource_set_map_flags_v2(intptr_t resource, unsigned int flags): + """Set 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:. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE``: 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 + ``CUDA_ERROR_ALREADY_MAPPED`` is returned. If ``flags`` is not one of the + above values then ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Args: + resource (intptr_t): Registered resource to set flags for. + flags (unsigned int): Parameters for resource mapping. + + .. seealso:: `cuGraphicsResourceSetMapFlags_v2` + """ + with nogil: + __status__ = cuGraphicsResourceSetMapFlags(resource, flags) + check_status(__status__) + + +cpdef graphics_map_resources(unsigned int count, intptr_t resources, intptr_t h_stream): + """Map 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 :func:`graphics_map_resources` will complete before any + subsequent CUDA work issued in ``stream`` begins. + + If ``resources`` includes any duplicate entries then + ``CUDA_ERROR_INVALID_HANDLE`` is returned. If any of ``resources`` are + presently mapped for access by CUDA then ``CUDA_ERROR_ALREADY_MAPPED`` is + returned. + + Args: + count (unsigned int): Number of resources to map. + resources (intptr_t): Resources to map for CUDA usage. + h_stream (intptr_t): Stream with which to synchronize. + + .. seealso:: `cuGraphicsMapResources` + """ + cdef CUgraphicsResource _resources_ = resources + with nogil: + __status__ = cuGraphicsMapResources(count, resources, h_stream) + check_status(__status__) + + +cpdef graphics_unmap_resources(unsigned int count, intptr_t resources, intptr_t h_stream): + """Unmap 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 :func:`graphics_unmap_resources` will complete + before any subsequently issued graphics work begins. + + If ``resources`` includes any duplicate entries then + ``CUDA_ERROR_INVALID_HANDLE`` is returned. If any of ``resources`` are not + presently mapped for access by CUDA then ``CUDA_ERROR_NOT_MAPPED`` is + returned. + + Args: + count (unsigned int): Number of resources to unmap. + resources (intptr_t): Resources to unmap. + h_stream (intptr_t): Stream with which to synchronize. + + .. seealso:: `cuGraphicsUnmapResources` + """ + cdef CUgraphicsResource _resources_ = resources + with nogil: + __status__ = cuGraphicsUnmapResources(count, resources, h_stream) + check_status(__status__) + + +cpdef get_proc_address_v2(symbol, intptr_t pfn, int cuda_version, uint64_t flags, intptr_t symbol_status): + """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 + ``CUDA_ERROR_INVALID_VALUE``. + + 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 ``CUDA_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 ``cuda_version`` or if + the driver symbol is invalid. + + It will also set the optional ``symbol_status`` to one of the values in + ``CUdriverProcAddressQueryResult`` with the following meanings:. + + - ``CU_GET_PROC_ADDRESS_SUCCESS`` - The requested symbol was succesfully + found based on input arguments and ``pfn`` is valid. + + - ``CU_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND`` - The requested symbol was not + found. + + - ``CU_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT`` - The requested symbol was + found but is not supported by cuda_version specified. + + The requested flags can be:. + + - ``CU_GET_PROC_ADDRESS_DEFAULT``: This is the default mode. This is + equivalent to ``CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM`` if the code + is compiled with --default-stream per-thread compilation flag or the macro + CUDA_API_PER_THREAD_DEFAULT_STREAM is defined; + ``CU_GET_PROC_ADDRESS_LEGACY_STREAM`` otherwise. + + - ``CU_GET_PROC_ADDRESS_LEGACY_STREAM``: This will enable the search for + all driver symbols that match the requested driver symbol name except the + corresponding per-thread versions. + + - ``CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM``: This will enable the + search for all driver symbols that match the requested driver symbol name + including the per-thread versions. If a per-thread version is not found, + the API will return the legacy version of the driver function. + + Args: + symbol (bytes): The base name of the driver API function to + look for. As an example, for the driver API + ``cuMemAlloc_v2``, ``symbol`` would be cuMemAlloc and + ``cuda_version`` would be the ABI compatible CUDA version + for the _v2 variant. + pfn (intptr_t): Location to return the function pointer to the + requested driver function. + cuda_version (int): The CUDA version to look for the requested + driver symbol. + flags (uint64_t): Flags to specify search options. + symbol_status (intptr_t): Optional location to store the + status of the search for ``symbol`` based on + ``cuda_version``. See ``CUdriverProcAddressQueryResult`` + for possible values. + + .. seealso:: `cuGetProcAddress_v2` + """ + cdef void* _symbol_ = _cyb_get_buffer_pointer(symbol, -1, readonly=True) + with nogil: + __status__ = cuGetProcAddress(_symbol_, pfn, cuda_version, flags, symbol_status) + check_status(__status__) + + +cpdef coredump_get_attribute(int attrib, intptr_t value, intptr_t size): + """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:. + + - ``CU_COREDUMP_ENABLE_ON_EXCEPTION``: Bool where ``true`` means that GPU + exceptions from this context will create a coredump at the location + specified by ``CU_COREDUMP_FILE``. The default value is ``false`` unless + set to ``true`` globally or locally, or the CU_CTX_USER_COREDUMP_ENABLE + flag was set during context creation. + + - ``CU_COREDUMP_TRIGGER_HOST``: 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 ``CU_COREDUMP_SKIP_ABORT`` flag to disable host device abort() + if needed. + + - ``CU_COREDUMP_LIGHTWEIGHT``: 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 + ``CU_COREDUMP_GENERATION_FLAGS`` instead. + + - ``CU_COREDUMP_ENABLE_USER_TRIGGER``: Bool where ``true`` means that a + coredump can be created by writing to the system pipe specified by + ``CU_COREDUMP_PIPE``. The default value is ``false`` unless set to ``true`` + globally or locally. + + - ``CU_COREDUMP_FILE``: 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. + + - ``CU_COREDUMP_PIPE``: 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. + + - ``CU_COREDUMP_GENERATION_FLAGS``: An integer with values to allow + granular control the data contained in a coredump specified as a bitwise OR + combination of the following values:. + + - ``CU_COREDUMP_DEFAULT_FLAGS`` - if set by itself, coredump generation + returns to its default settings of including all memory regions that it is + able to access. + + - ``CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES`` - Coredump will not + include the data from CUDA source modules that are not relocated at + runtime. + + - ``CU_COREDUMP_SKIP_GLOBAL_MEMORY`` - Coredump will not include device- + side global data that does not belong to any context. + + - ``CU_COREDUMP_SKIP_SHARED_MEMORY`` - Coredump will not include grid- + scale shared memory for the warp that the dumped kernel belonged to. + + - ``CU_COREDUMP_SKIP_LOCAL_MEMORY`` - Coredump will not include local + memory from the kernel. + + - ``CU_COREDUMP_LIGHTWEIGHT_FLAGS`` - Enables all of the above options. + Equiavlent to setting the ``CU_COREDUMP_LIGHTWEIGHT`` attribute to + ``true``. + + - ``CU_COREDUMP_SKIP_ABORT`` - If set, GPU exceptions will not raise an + abort() in the host CPU process. Same functional goal as + ``CU_COREDUMP_TRIGGER_HOST`` but better reflects the default behavior. + + - ``CU_COREDUMP_SKIP_CONSTBANK_MEMORY`` - Coredump will not include + constbank memory. + + - ``CU_COREDUMP_GZIP_COMPRESS`` - 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. + + - ``CU_COREDUMP_FAULTED_CONTEXTS_ONLY`` - The coredump will only include + contexts that have encountered an exception or a trap. + + - ``CU_COREDUMP_NO_ERRBAR_AT_EXIT`` - 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. + + - ``CU_COREDUMP_LOG_ONLY`` - Setting this flag will disable actual + generation of the coredump file, but exception details will still be + logged. + + Args: + attrib (CoredumpSettings): The enum defining which value to + fetch. + value (intptr_t): void* containing the requested data. + size (intptr_t): The size of the memory region ``value`` + points to. + + .. seealso:: `cuCoredumpGetAttribute` + """ + with nogil: + __status__ = cuCoredumpGetAttribute(attrib, value, size) + check_status(__status__) + + +cpdef coredump_get_attribute_global(int attrib, intptr_t value, intptr_t size): + """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:. + + - ``CU_COREDUMP_ENABLE_ON_EXCEPTION``: Bool where ``true`` means that GPU + exceptions from this context will create a coredump at the location + specified by ``CU_COREDUMP_FILE``. The default value is ``false``. + + - ``CU_COREDUMP_TRIGGER_HOST``: 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 ``CU_COREDUMP_SKIP_ABORT`` flag to disable host device abort() + if needed. + + - ``CU_COREDUMP_LIGHTWEIGHT``: 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 ``CU_COREDUMP_GENERATION_FLAGS`` instead. + + - ``CU_COREDUMP_ENABLE_USER_TRIGGER``: Bool where ``true`` means that a + coredump can be created by writing to the system pipe specified by + ``CU_COREDUMP_PIPE``. The default value is ``false``. + + - ``CU_COREDUMP_FILE``: 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. + + - ``CU_COREDUMP_PIPE``: 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. + + - ``CU_COREDUMP_GENERATION_FLAGS``: An integer with values to allow + granular control the data contained in a coredump specified as a bitwise OR + combination of the following values:. + + - ``CU_COREDUMP_DEFAULT_FLAGS`` - if set by itself, coredump generation + returns to its default settings of including all memory regions that it is + able to access. + + - ``CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES`` - Coredump will not + include the data from CUDA source modules that are not relocated at + runtime. + + - ``CU_COREDUMP_SKIP_GLOBAL_MEMORY`` - Coredump will not include device- + side global data that does not belong to any context. + + - ``CU_COREDUMP_SKIP_SHARED_MEMORY`` - Coredump will not include grid- + scale shared memory for the warp that the dumped kernel belonged to. + + - ``CU_COREDUMP_SKIP_LOCAL_MEMORY`` - Coredump will not include local + memory from the kernel. + + - ``CU_COREDUMP_LIGHTWEIGHT_FLAGS`` - Enables all of the above options. + Equiavlent to setting the ``CU_COREDUMP_LIGHTWEIGHT`` attribute to + ``true``. + + - ``CU_COREDUMP_SKIP_ABORT`` - If set, GPU exceptions will not raise an + abort() in the host CPU process. Same functional goal as + ``CU_COREDUMP_TRIGGER_HOST`` but better reflects the default behavior. + + - ``CU_COREDUMP_SKIP_CONSTBANK_MEMORY`` - Coredump will not include + constbank memory. + + - ``CU_COREDUMP_GZIP_COMPRESS`` - 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. + + - ``CU_COREDUMP_FAULTED_CONTEXTS_ONLY`` - The coredump will only include + contexts that have encountered an exception or a trap. + + - ``CU_COREDUMP_NO_ERRBAR_AT_EXIT`` - 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. + + - ``CU_COREDUMP_LOG_ONLY`` - Setting this flag will disable actual + generation of the coredump file, but exception details will still be + logged. + + Args: + attrib (CoredumpSettings): The enum defining which value to + fetch. + value (intptr_t): void* containing the requested data. + size (intptr_t): The size of the memory region ``value`` + points to. + + .. seealso:: `cuCoredumpGetAttributeGlobal` + """ + with nogil: + __status__ = cuCoredumpGetAttributeGlobal(attrib, value, size) + check_status(__status__) + + +cpdef coredump_set_attribute(int attrib, intptr_t value, intptr_t size): + """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 ``CUDA_ERROR_NOT_SUPPORTED`` if the caller + attempts to set ``CU_COREDUMP_ENABLE_ON_EXCEPTION`` on a GPU of with + Compute Capability < 6.0. ``cuCoredumpSetAttributeGlobal`` works on those + platforms as an alternative. + + /note ``CU_COREDUMP_ENABLE_USER_TRIGGER`` and ``CU_COREDUMP_PIPE`` cannot + be set on a per-context basis. + + The supported attributes are:. + + - ``CU_COREDUMP_ENABLE_ON_EXCEPTION``: Bool where ``true`` means that GPU + exceptions from this context will create a coredump at the location + specified by ``CU_COREDUMP_FILE``. The default value is ``false``. + + - ``CU_COREDUMP_TRIGGER_HOST``: 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 ``CU_COREDUMP_SKIP_ABORT`` flag to disable host device abort() + if needed. + + - ``CU_COREDUMP_LIGHTWEIGHT``: 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 ``CU_COREDUMP_GENERATION_FLAGS`` instead. + + - ``CU_COREDUMP_FILE``: 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. + + - ``CU_COREDUMP_GENERATION_FLAGS``: An integer with values to allow + granular control the data contained in a coredump specified as a bitwise OR + combination of the following values:. + + - ``CU_COREDUMP_DEFAULT_FLAGS`` - if set by itself, coredump generation + returns to its default settings of including all memory regions that it is + able to access. + + - ``CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES`` - Coredump will not + include the data from CUDA source modules that are not relocated at + runtime. + + - ``CU_COREDUMP_SKIP_GLOBAL_MEMORY`` - Coredump will not include device- + side global data that does not belong to any context. + + - ``CU_COREDUMP_SKIP_SHARED_MEMORY`` - Coredump will not include grid- + scale shared memory for the warp that the dumped kernel belonged to. + + - ``CU_COREDUMP_SKIP_LOCAL_MEMORY`` - Coredump will not include local + memory from the kernel. + + - ``CU_COREDUMP_LIGHTWEIGHT_FLAGS`` - Enables all of the above options. + Equiavlent to setting the ``CU_COREDUMP_LIGHTWEIGHT`` attribute to + ``true``. + + - ``CU_COREDUMP_SKIP_ABORT`` - If set, GPU exceptions will not raise an + abort() in the host CPU process. Same functional goal as + ``CU_COREDUMP_TRIGGER_HOST`` but better reflects the default behavior. + + - ``CU_COREDUMP_SKIP_CONSTBANK_MEMORY`` - Coredump will not include + constbank memory. + + - ``CU_COREDUMP_GZIP_COMPRESS`` - 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. + + - ``CU_COREDUMP_FAULTED_CONTEXTS_ONLY`` - The coredump will only include + contexts that have encountered an exception or a trap. + + - ``CU_COREDUMP_NO_ERRBAR_AT_EXIT`` - 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. + + - ``CU_COREDUMP_LOG_ONLY`` - Setting this flag will disable actual + generation of the coredump file, but exception details will still be + logged. + + Args: + attrib (CoredumpSettings): The enum defining which value to + set. + value (intptr_t): void* containing the requested data. + size (intptr_t): The size of the memory region ``value`` + points to. + + .. note:: + ``CU_COREDUMP_GENERATION_FLAGS`` replaces all previously set coredump + flags. Mixing ``CU_COREDUMP_GENERATION_FLAGS`` with the deprecated + boolean attributes (``CU_COREDUMP_TRIGGER_HOST``, + ``CU_COREDUMP_LIGHTWEIGHT``) can result in undefined behavior. To avoid + issues, either use only ``CU_COREDUMP_GENERATION_FLAGS`` or combine all + desired flag bits (including ``CU_COREDUMP_SKIP_ABORT``) in a single + call. + + .. seealso:: `cuCoredumpSetAttribute` + """ + with nogil: + __status__ = cuCoredumpSetAttribute(attrib, value, size) + check_status(__status__) + + +cpdef coredump_set_attribute_global(int attrib, intptr_t value, intptr_t size): + """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:. + + - ``CU_COREDUMP_ENABLE_ON_EXCEPTION``: Bool where ``true`` means that GPU + exceptions from this context will create a coredump at the location + specified by ``CU_COREDUMP_FILE``. The default value is ``false``. + + - ``CU_COREDUMP_TRIGGER_HOST``: 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 ``CU_COREDUMP_SKIP_ABORT`` flag to disable host device abort() + if needed. + + - ``CU_COREDUMP_LIGHTWEIGHT``: 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 ``CU_COREDUMP_GENERATION_FLAGS`` instead. + + - ``CU_COREDUMP_ENABLE_USER_TRIGGER``: Bool where ``true`` means that a + coredump can be created by writing to the system pipe specified by + ``CU_COREDUMP_PIPE``. The default value is ``false``. + + - ``CU_COREDUMP_FILE``: 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. + + - ``CU_COREDUMP_PIPE``: 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 + ``CU_COREDUMP_ENABLE_USER_TRIGGER`` 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. + + - ``CU_COREDUMP_GENERATION_FLAGS``: An integer with values to allow + granular control the data contained in a coredump specified as a bitwise OR + combination of the following values:. + + - ``CU_COREDUMP_DEFAULT_FLAGS`` - if set by itself, coredump generation + returns to its default settings of including all memory regions that it is + able to access. + + - ``CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES`` - Coredump will not + include the data from CUDA source modules that are not relocated at + runtime. + + - ``CU_COREDUMP_SKIP_GLOBAL_MEMORY`` - Coredump will not include device- + side global data that does not belong to any context. + + - ``CU_COREDUMP_SKIP_SHARED_MEMORY`` - Coredump will not include grid- + scale shared memory for the warp that the dumped kernel belonged to. + + - ``CU_COREDUMP_SKIP_LOCAL_MEMORY`` - Coredump will not include local + memory from the kernel. + + - ``CU_COREDUMP_LIGHTWEIGHT_FLAGS`` - Enables all of the above options. + Equiavlent to setting the ``CU_COREDUMP_LIGHTWEIGHT`` attribute to + ``true``. + + - ``CU_COREDUMP_SKIP_ABORT`` - If set, GPU exceptions will not raise an + abort() in the host CPU process. Same functional goal as + ``CU_COREDUMP_TRIGGER_HOST`` but better reflects the default behavior. + + - ``CU_COREDUMP_SKIP_CONSTBANK_MEMORY`` - Coredump will not include + constbank memory. + + - ``CU_COREDUMP_GZIP_COMPRESS`` - 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. + + - ``CU_COREDUMP_FAULTED_CONTEXTS_ONLY`` - The coredump will only include + contexts that have encountered an exception or a trap. + + - ``CU_COREDUMP_NO_ERRBAR_AT_EXIT`` - 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. + + - ``CU_COREDUMP_LOG_ONLY`` - Setting this flag will disable actual + generation of the coredump file, but exception details will still be + logged. + + Args: + attrib (CoredumpSettings): The enum defining which value to + set. + value (intptr_t): void* containing the requested data. + size (intptr_t): The size of the memory region ``value`` + points to. + + .. note:: + ``CU_COREDUMP_GENERATION_FLAGS`` replaces all previously set coredump + flags. Mixing ``CU_COREDUMP_GENERATION_FLAGS`` with the deprecated + boolean attributes (``CU_COREDUMP_TRIGGER_HOST``, + ``CU_COREDUMP_LIGHTWEIGHT``) can result in undefined behavior. To avoid + issues, either use only ``CU_COREDUMP_GENERATION_FLAGS`` or combine all + desired flag bits (including ``CU_COREDUMP_SKIP_ABORT``) in a single + call. + + .. seealso:: `cuCoredumpSetAttributeGlobal` + """ + with nogil: + __status__ = cuCoredumpSetAttributeGlobal(attrib, value, size) + check_status(__status__) + + +cpdef intptr_t get_export_table(p_export_table_id) except? 0: + cdef intptr_t _p_export_table_id_ptr_ = int(p_export_table_id) + cdef const void* pp_export_table + with nogil: + __status__ = cuGetExportTable(&pp_export_table, _p_export_table_id_ptr_) + check_status(__status__) + return pp_export_table + + +cpdef intptr_t green_ctx_create(intptr_t desc, int dev, unsigned int flags) except? 0: + """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 ``ph_ctx``. + 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 ``CUcontext`` using ``cuCtxFromGreenCtx`` and subsequently calling + ``cuCtxSetCurrent`` / ``cuCtxPushCurrent``. 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:. + + - ``CU_GREEN_CTX_NONE`` : Default behavior. + + - ``CU_GREEN_CTX_DEFAULT_STREAM`` : Creates a default stream to use inside + the green context. + + Args: + desc (intptr_t): Descriptor generated via + ``cuDevResourceGenerateDesc`` which contains the set of + resources to be used. + dev (int): Device on which to create the green context. + flags (unsigned int): One of the supported green context + creation flags. + + Returns: + intptr_t: Pointer for the output handle to the green context. + + .. seealso:: `cuGreenCtxCreate` + """ + cdef CUgreenCtx ph_ctx + with nogil: + __status__ = cuGreenCtxCreate(&ph_ctx, desc, dev, flags) + check_status(__status__) + return ph_ctx + + +cpdef green_ctx_destroy(intptr_t h_ctx): + """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 + ``cuGreenCtxStreamCreate``, ``cuStreamCreate``, or + ``cuStreamCreateWithPriority``. Users are expected to destroy these streams + explicitly using ``cuStreamDestroy`` to avoid resource leaks. Once the + green context is destroyed, any subsequent API calls involving these + streams will return ``CUDA_ERROR_STREAM_DETACHED`` with the exception of + the following APIs:. + + - ``cuStreamDestroy``. + + Additionally, the API will invalidate all active captures on these streams. + + Args: + h_ctx (intptr_t): Green context to be destroyed. + + .. seealso:: `cuGreenCtxDestroy` + """ + with nogil: + __status__ = cuGreenCtxDestroy(h_ctx) + check_status(__status__) + + +cpdef intptr_t ctx_from_green_ctx(intptr_t h_ctx) except? 0: + """Returns a ``CUcontext`` handle for a green context. + + This API returns in ``p_context`` a ``CUcontext`` handle that represents + the specified green context ``h_ctx``. The returned handle can be passed to + CUDA APIs that accept a ``CUcontext`` and will be treated as if it were a + primary context, while still honoring the resources and configuration + associated with ``h_ctx`` as applicable. + + Applications that wish to use a green context with CUDA APIs that require a + ``CUcontext`` must use this API to obtain a handle to a ``CUcontext`` + representing the green context. Otherwise, passing a green context to such + APIs will fail with ``CUDA_ERROR_INVALID_CONTEXT``. + + The ``CUcontext`` returned by ``cuCtxFromGreenCtx`` may be passed to CUDA + Driver APIs that accept a ``CUcontext``. + + - 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 ``h_ctx``. + + This call does not create a new independent context and does not change the + underlying context lifetime. The validity of the returned ``p_context`` is + tied to ``h_ctx``, and no additional destruction or release is required + beyond correctly managing ``h_ctx`` with the green context APIs. Destroying + ``p_context`` via ``cuCtxDestroy`` is undefined behavior. + + Args: + h_ctx (intptr_t): Green context to convert. + + Returns: + intptr_t: Returned ``CUcontext`` with green context resources. + + .. seealso:: `cuCtxFromGreenCtx` + """ + cdef CUcontext p_context + with nogil: + __status__ = cuCtxFromGreenCtx(&p_context, h_ctx) + check_status(__status__) + return p_context + + +cpdef device_get_dev_resource(int device, resource, int type): + """Get device resources. + + Get the ``typename`` 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. + + Args: + device (int): Device to get resource for. + resource (intptr_t): Output pointer to a ``CUdevResource`` + structure. + type (DevResourceType): Type of resource to retrieve. + + .. seealso:: `cuDeviceGetDevResource` + """ + cdef intptr_t _resource_ptr_ = int(resource) + with nogil: + __status__ = cuDeviceGetDevResource(device, _resource_ptr_, type) + check_status(__status__) + + +cpdef ctx_get_dev_resource(intptr_t h_ctx, resource, int type): + """Get context resources. + + Get the ``typename`` resources available to the context represented by + ``h_ctx`` Note: The API is not supported on 32-bit platforms. + + Args: + h_ctx (intptr_t): Context to get resource for. + resource (intptr_t): Output pointer to a ``CUdevResource`` + structure. + type (DevResourceType): Type of resource to retrieve. + + .. seealso:: `cuCtxGetDevResource` + """ + cdef intptr_t _resource_ptr_ = int(resource) + with nogil: + __status__ = cuCtxGetDevResource(h_ctx, _resource_ptr_, type) + check_status(__status__) + + +cpdef green_ctx_get_dev_resource(intptr_t h_ctx, resource, int type): + """Get green context resources. + + Get the ``typename`` resources available to the green context represented + by ``h_ctx``. + + Args: + h_ctx (intptr_t): Green context to get resource for. + resource (intptr_t): Output pointer to a ``CUdevResource`` + structure. + type (DevResourceType): Type of resource to retrieve. + + .. seealso:: `cuGreenCtxGetDevResource` + """ + cdef intptr_t _resource_ptr_ = int(resource) + with nogil: + __status__ = cuGreenCtxGetDevResource(h_ctx, _resource_ptr_, type) + check_status(__status__) + + +cpdef dev_sm_resource_split_by_count(result, intptr_t nb_groups, input, remainder, unsigned int flags, unsigned int min_count): + """Splits ``CU_DEV_RESOURCE_TYPE_SM`` resources. + + Splits ``CU_DEV_RESOURCE_TYPE_SM`` resources into ``nb_groups``, adhering + to the minimum SM count specified in ``min_count`` 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 ``nb_groups``. Otherwise, + ``nb_groups`` must point to the amount of elements in ``result`` and on + return, the API will overwrite ``nb_groups`` with the amount actually + created. The groups are written to the array in ``result``. ``nb_groups`` + 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 ``cuDeviceGetDevResource``, + ``cuCtxGetDevResource``, or ``cuGreenCtxGetDevResource``. 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 + ``min_count`` due to cluster requirements or alignment and granularity + requirements for the min_count. These requirements can be queried with + ``cuDeviceGetDevResource``, ``cuCtxGetDevResource``, and + ``cuGreenCtxGetDevResource`` for ``CU_DEV_RESOURCE_TYPE_SM``, 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:. + + - ``CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING`` : Lower the minimum + SM count and alignment, and treat each SM independent of its hierarchy. + This allows more fine grained partitions but at the cost of advanced + features (such as large clusters on compute capability 9.0+). + + - ``CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE`` : Compute + Capability 9.0+ only. Attempt to create groups that may allow for maximally + sized thread clusters. This can be queried post green context creation + using ``cuOccupancyMaxPotentialClusterSize``. + + A successful API call must either have:. + + - A valid array of ``result`` pointers of size passed in ``nb_groups``, + with ``input`` of type ``CU_DEV_RESOURCE_TYPE_SM``. Value of ``min_count`` + 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 + ``nb_groups`` and ``input`` of type ``CU_DEV_RESOURCE_TYPE_SM``. Value of + ``min_count`` 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. + + Args: + result (intptr_t): Output array of ``CUdevResource`` + resources. Can be NULL to query the number of groups. + nb_groups (intptr_t): This is a pointer, specifying the number + of groups that would be or should be created as described + below. + input (intptr_t): Input SM resource to be split. Must be a + valid ``CU_DEV_RESOURCE_TYPE_SM`` resource. + remainder (intptr_t): If the input resource cannot be cleanly + split among ``nb_groups``, the remainder is placed in + here. Can be ommitted (NULL) if the user does not need the + remaining set. + flags (unsigned int): Flags specifying how these partitions + are used or which constraints to abide by when splitting + the input. Zero is valid for default behavior. + min_count (unsigned int): Minimum number of SMs required. + + .. seealso:: `cuDevSmResourceSplitByCount` + """ + cdef intptr_t _result_ptr_ = int(result) + cdef intptr_t _input_ptr_ = int(input) + cdef intptr_t _remainder_ptr_ = int(remainder) + with nogil: + __status__ = cuDevSmResourceSplitByCount(_result_ptr_, nb_groups, _input_ptr_, _remainder_ptr_, flags, min_count) + check_status(__status__) + + +cpdef intptr_t dev_resource_generate_desc(resources, unsigned int nb_resources) except? 0: + """Generate 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 ``cuGreenCtxCreate`` 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 ``ph_desc`` descriptor as well as a valid + array of ``resources`` pointers, with the array size passed in + ``nb_resources``. If multiple resources are provided in ``resources``, the + device they came from must be the same, otherwise + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. If multiple + resources are provided in ``resources`` and they are of type + ``CU_DEV_RESOURCE_TYPE_SM``, they must be outputs (whether ``result`` or + ``remaining``) from the same split API instance and have the same + smCoscheduledAlignment values, otherwise + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. + + Note: The API is not supported on 32-bit platforms. + + Args: + resources (intptr_t): Array of resources to be included in the + descriptor. + nb_resources (unsigned int): Number of resources passed in + ``resources``. + + Returns: + intptr_t: Output descriptor. + + .. seealso:: `cuDevResourceGenerateDesc` + """ + cdef intptr_t _resources_ptr_ = int(resources) + cdef CUdevResourceDesc ph_desc + with nogil: + __status__ = cuDevResourceGenerateDesc(&ph_desc, _resources_ptr_, nb_resources) + check_status(__status__) + return ph_desc + + +cpdef green_ctx_record_event(intptr_t h_ctx, intptr_t h_event): + """Records an event. + + Captures in ``h_event`` all the activities of the green context of + ``h_ctx`` at the time of this call. ``h_event`` and ``h_ctx`` must be from + the same primary context otherwise ``CUDA_ERROR_INVALID_HANDLE`` is + returned. Calls such as :func:`event_query` or :func:`green_ctx_wait_event` + will then examine or wait for completion of the work that was captured. + Uses of ``h_ctx`` after this call do not modify ``h_event``. + + Args: + h_ctx (intptr_t): Green context to record event for. + h_event (intptr_t): Event to record. + + .. note:: + The API will return ``CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED`` if the + specified green context ``h_ctx`` has a stream in the capture mode. In + such a case, the call will invalidate all the conflicting captures. + + .. seealso:: `cuGreenCtxRecordEvent` + """ + with nogil: + __status__ = cuGreenCtxRecordEvent(h_ctx, h_event) + check_status(__status__) + + +cpdef green_ctx_wait_event(intptr_t h_ctx, intptr_t h_event): + """Make a green context wait on an event. + + Makes all future work submitted to green context ``h_ctx`` wait for all + work captured in ``h_event``. The synchronization will be performed on the + device and will not block the calling CPU thread. See + :func:`green_ctx_record_event` or :func:`event_record`, for details on what + is captured by an event. + + Args: + h_ctx (intptr_t): Green context to wait. + h_event (intptr_t): Event to wait on. + + .. note:: + ``h_event`` may be from a different context or device than ``h_ctx``. + + .. note:: + The API will return ``CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED`` and + invalidate the capture if the specified event ``h_event`` is part of an + ongoing capture sequence or if the specified green context ``h_ctx`` + has a stream in the capture mode. + + .. seealso:: `cuGreenCtxWaitEvent` + """ + with nogil: + __status__ = cuGreenCtxWaitEvent(h_ctx, h_event) + check_status(__status__) + + +cpdef intptr_t stream_get_green_ctx(intptr_t h_stream) except? 0: + """Query 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 ``h_stream`` can refer to any of the following:. + + - a stream created via any of the CUDA driver APIs such as + ``cuStreamCreate``, ``cuStreamCreateWithPriority`` and + ``cuGreenCtxStreamCreate``, 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 cuCtxFromGreenCtx, + that green context is returned in ``ph_ctx``. Otherwise, ``*ph_ctx`` is set + to 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 + cuCtxFromGreenCtx, that green context is returned. Otherwise, ``*ph_ctx`` + is set to NULL instead. + + Passing an invalid handle will result in undefined behavior. + + Args: + h_stream (intptr_t): Handle to the stream to be queried. + + Returns: + intptr_t: Returned green context associated with the stream. + + .. seealso:: `cuStreamGetGreenCtx` + """ + cdef CUgreenCtx ph_ctx + with nogil: + __status__ = cuStreamGetGreenCtx(h_stream, &ph_ctx) + check_status(__status__) + return ph_ctx + + +cpdef intptr_t green_ctx_stream_create(intptr_t green_ctx, unsigned int flags, int priority) except? 0: + """Create a stream for use in the green context. + + Creates a stream for use in the specified green context ``green_ctx`` and + returns a handle in ``ph_stream``. The stream can be destroyed by calling + ``cuStreamDestroy()``. Note that the API ignores the context that is + current to the calling thread and creates a stream in the specified green + context ``green_ctx``. + + The supported values for ``flags`` are:. + + - ``CU_STREAM_NON_BLOCKING``: 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 ``cuCtxGetStreamPriorityRange``. If the specified priority is + outside the numerical range returned by ``cuCtxGetStreamPriorityRange``, it + will automatically be clamped to the lowest or the highest number in the + range. + + Args: + green_ctx (intptr_t): Green context for which to create the + stream for. + flags (unsigned int): Flags for stream creation. + ``CU_STREAM_NON_BLOCKING`` must be specified. + priority (int): Stream priority. Lower numbers represent + higher priorities. See ``cuCtxGetStreamPriorityRange`` for + more information about meaningful stream priorities that + can be passed. + + Returns: + intptr_t: Returned newly created stream. + + .. 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. + + .. seealso:: `cuGreenCtxStreamCreate` + """ + cdef CUstream ph_stream + with nogil: + __status__ = cuGreenCtxStreamCreate(&ph_stream, green_ctx, flags, priority) + check_status(__status__) + return ph_stream + + +cpdef intptr_t logs_register_callback(intptr_t callback_func, intptr_t user_data) except? 0: + """Register a callback function to receive error log messages. + + Args: + callback_func (intptr_t): The function to register as a + callback. + user_data (intptr_t): A generic pointer to user data. This is + passed into the callback function. + + Returns: + intptr_t: Optional location to store the callback handle after + it is registered. + + .. seealso:: `cuLogsRegisterCallback` + """ + cdef CUlogsCallbackHandle callback_out + with nogil: + __status__ = cuLogsRegisterCallback(callback_func, user_data, &callback_out) + check_status(__status__) + return callback_out + + +cpdef logs_unregister_callback(intptr_t callback): + """Unregister a log message callback. + + Args: + callback (intptr_t): The callback instance to unregister from + receiving log messages. + + .. seealso:: `cuLogsUnregisterCallback` + """ + with nogil: + __status__ = cuLogsUnregisterCallback(callback) + check_status(__status__) + + +cpdef unsigned int logs_current(unsigned int flags) except? 0: + """Sets log iterator to point to the end of log buffer, where the next message would be written. + + Args: + flags (unsigned int): Reserved for future use, must be 0. + + Returns: + unsigned int: Location to store an iterator to the current + tail of the logs. + + .. seealso:: `cuLogsCurrent` + """ + cdef CUlogIterator iterator_out + with nogil: + __status__ = cuLogsCurrent(&iterator_out, flags) + check_status(__status__) + return iterator_out + + +cpdef logs_dump_to_file(intptr_t iterator, path_to_file, unsigned int flags): + """Dump 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 ``path_to_file`` provided. + + Args: + iterator (intptr_t): Optional auto-advancing iterator + specifying the starting log to read. NULL value dumps all + logs. + path_to_file (bytes): Path to output file for dumping logs. + flags (unsigned int): Reserved for future use, must be 0. + + .. 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. + + .. seealso:: `cuLogsDumpToFile` + """ + cdef void* _path_to_file_ = _cyb_get_buffer_pointer(path_to_file, -1, readonly=True) + with nogil: + __status__ = cuLogsDumpToFile(iterator, _path_to_file_, flags) + check_status(__status__) + + +cpdef logs_dump_to_memory(intptr_t iterator, intptr_t buffer, intptr_t size, unsigned int flags): + """Dump 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 ``CUDA_SUCCESS``. If the provided ``buffer`` is not + large enough to hold any messages, ``*size`` will be set to 0 and the + function will return ``CUDA_ERROR_INVALID_VALUE``. + + Args: + iterator (intptr_t): Optional auto-advancing iterator + specifying the starting log to read. NULL value dumps all + logs. + buffer (intptr_t): Pointer to dump logs. + size (intptr_t): See description. + flags (unsigned int): Reserved for future use, must be 0. + + .. 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. + + .. seealso:: `cuLogsDumpToMemory` + """ + with nogil: + __status__ = cuLogsDumpToMemory(iterator, buffer, size, flags) + check_status(__status__) + + +cpdef int checkpoint_process_get_restore_thread_id(int pid) except? -1: + """Returns the restore thread ID for a CUDA process. + + Returns in ``*tid`` the thread ID of the CUDA restore thread for the + process specified by ``pid``. + + Args: + pid (int): The process ID of the CUDA process. + + Returns: + int: Returned restore thread ID. + + .. seealso:: `cuCheckpointProcessGetRestoreThreadId` + """ + cdef int tid + with nogil: + __status__ = cuCheckpointProcessGetRestoreThreadId(pid, &tid) + check_status(__status__) + return tid + + +cpdef int checkpoint_process_get_state(int pid) except? -1: + """Returns the process state of a CUDA process. + + Returns in ``*state`` the current state of the CUDA process specified by + ``pid``. + + Args: + pid (int): The process ID of the CUDA process. + + Returns: + int: Returned CUDA process state. + + .. seealso:: `cuCheckpointProcessGetState` + """ + cdef CUprocessState state + with nogil: + __status__ = cuCheckpointProcessGetState(pid, &state) + check_status(__status__) + return state + + +cpdef checkpoint_process_lock(int pid, args): + """Lock 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. + + Args: + pid (int): The process ID of the CUDA process. + args (intptr_t): Optional lock operation arguments. + + .. seealso:: `cuCheckpointProcessLock` + """ + cdef intptr_t _args_ptr_ = int(args) + with nogil: + __status__ = cuCheckpointProcessLock(pid, _args_ptr_) + check_status(__status__) + + +cpdef checkpoint_process_checkpoint(int pid, args): + """Checkpoint a CUDA process's GPU memory contents. + + Checkpoints a CUDA process specified by ``pid`` that is in the LOCKED + state. The GPU memory contents will be brought into host memory and all + underlying references will be released. Process must be in the LOCKED state + to checkpoint. + + Upon successful return the process will be in the CHECKPOINTED state. + + Args: + pid (int): The process ID of the CUDA process. + args (intptr_t): Optional checkpoint operation arguments. + + .. seealso:: `cuCheckpointProcessCheckpoint` + """ + cdef intptr_t _args_ptr_ = int(args) + with nogil: + __status__ = cuCheckpointProcessCheckpoint(pid, _args_ptr_) + check_status(__status__) + + +cpdef checkpoint_process_restore(int pid, intptr_t args): + """Restore 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 CHECKPOINTED 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. + + Upon successful return the process will be in the LOCKED state. + + CUDA process restore requires persistence mode to be enabled or ``cuInit`` + to have been called before execution. + + Args: + pid (int): The process ID of the CUDA process. + args (intptr_t): Optional restore operation arguments. + + .. seealso:: `cuCheckpointProcessRestore` + """ + with nogil: + __status__ = cuCheckpointProcessRestore(pid, args) + check_status(__status__) + + +cpdef checkpoint_process_unlock(int pid, args): + """Unlock 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. + + Args: + pid (int): The process ID of the CUDA process. + args (intptr_t): Optional unlock operation arguments. + + .. seealso:: `cuCheckpointProcessUnlock` + """ + cdef intptr_t _args_ptr_ = int(args) + with nogil: + __status__ = cuCheckpointProcessUnlock(pid, _args_ptr_) + check_status(__status__) + + +cpdef graphics_egl_register_image(intptr_t p_cuda_resource, intptr_t image, unsigned int flags): + """Registers an EGL image. + + Registers the ``EGLImageKHR`` specified by ``image`` for access by CUDA. A + handle to the registered object is returned as ``p_cuda_resource``. + Additional Mapping/Unmapping is not required for the registered resource + and ``cuGraphicsResourceGetMappedEglFrame`` can be directly called on the + ``p_cuda_resource``. + + The application will be responsible for synchronizing access to shared + objects. The application must ensure that any pending operation which + access the objects have completed before passing control to CUDA. This may + be accomplished by issuing and waiting for glFinish command on all + GLcontexts (for OpenGL and likewise for other APIs). The application will + be also responsible for ensuring that any pending operation on the + registered CUDA resource has completed prior to executing subsequent + commands in other APIs accesing the same memory objects. This can be + accomplished by calling cuCtxSynchronize or cuEventSynchronize + (preferably). + + The surface's intended usage is specified using ``flags``, as follows:. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE``: 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. This is the default value. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY``: Specifies that CUDA will + not write to this resource. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD``: Specifies that CUDA + 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. + + The ``EGLImageKHR`` is an object which can be used to create EGLImage + target resource. It is defined as a void pointer. typedef void* + ``EGLImageKHR``. + + Args: + p_cuda_resource (intptr_t): Pointer to the returned object + handle. + image (intptr_t): An ``EGLImageKHR`` image which can be used + to create target resource. + flags (unsigned int): Map flags. + + .. seealso:: `cuGraphicsEGLRegisterImage` + """ + cdef CUgraphicsResource _p_cuda_resource_ = p_cuda_resource + with nogil: + __status__ = cuGraphicsEGLRegisterImage(p_cuda_resource, image, flags) + check_status(__status__) + + +cpdef intptr_t egl_stream_consumer_connect(intptr_t stream) except? 0: + """Connect CUDA to EGLStream as a consumer. + + Connect CUDA as a consumer to ``EGLStreamKHR`` specified by ``stream``. + + The ``EGLStreamKHR`` is an EGL object that transfers a sequence of image + frames from one API to another. + + Args: + stream (intptr_t): ``EGLStreamKHR`` handle. + + Returns: + intptr_t: Pointer to the returned connection handle. + + .. seealso:: `cuEGLStreamConsumerConnect` + """ + cdef CUeglStreamConnection conn + with nogil: + __status__ = cuEGLStreamConsumerConnect(&conn, stream) + check_status(__status__) + return conn + + +cpdef intptr_t egl_stream_consumer_connect_with_flags(intptr_t stream, unsigned int flags) except? 0: + """Connect CUDA to EGLStream as a consumer with given flags. + + Connect CUDA as a consumer to ``EGLStreamKHR`` specified by ``stream`` with + specified ``flags`` defined by ``CUeglResourceLocationFlags``. + + The flags specify whether the consumer wants to access frames from system + memory or video memory. Default is ``CU_EGL_RESOURCE_LOCATION_VIDMEM``. + + Args: + stream (intptr_t): ``EGLStreamKHR`` handle. + flags (unsigned int): Flags denote intended location - system + or video. + + Returns: + intptr_t: Pointer to the returned connection handle. + + .. seealso:: `cuEGLStreamConsumerConnectWithFlags` + """ + cdef CUeglStreamConnection conn + with nogil: + __status__ = cuEGLStreamConsumerConnectWithFlags(&conn, stream, flags) + check_status(__status__) + return conn + + +cpdef egl_stream_consumer_disconnect(intptr_t conn): + """Disconnect CUDA as a consumer to EGLStream . + + Disconnect CUDA as a consumer to ``EGLStreamKHR``. + + Args: + conn (intptr_t): Conection to disconnect. + + .. seealso:: `cuEGLStreamConsumerDisconnect` + """ + cdef CUeglStreamConnection _conn_ = conn + with nogil: + __status__ = cuEGLStreamConsumerDisconnect(conn) + check_status(__status__) + + +cpdef intptr_t egl_stream_consumer_acquire_frame(intptr_t conn, intptr_t p_stream, unsigned int timeout) except? 0: + """Acquire an image frame from the EGLStream with CUDA as a consumer. + + Acquire an image frame from ``EGLStreamKHR``. This API can also acquire an + old frame presented by the producer unless explicitly disabled by setting + EGL_SUPPORT_REUSE_NV flag to EGL_FALSE during stream initialization. By + default, EGLStream is created with this flag set to EGL_TRUE. + ``cuGraphicsResourceGetMappedEglFrame`` can be called on + ``p_cuda_resource`` to get ``CUeglFrame``. + + Args: + conn (intptr_t): Connection on which to acquire. + p_stream (intptr_t): CUDA stream for synchronization and any + data migrations implied by ``CUeglResourceLocationFlags``. + timeout (unsigned int): Desired timeout in usec for a new + frame to be acquired. If set as + ``CUDA_EGL_INFINITE_TIMEOUT``, acquire waits infinitely. + After timeout occurs CUDA consumer tries to acquire an old + frame if available and EGL_SUPPORT_REUSE_NV flag is set. + + Returns: + intptr_t: CUDA resource on which the stream frame will be + mapped for use. + + .. seealso:: `cuEGLStreamConsumerAcquireFrame` + """ + cdef CUeglStreamConnection _conn_ = conn + cdef CUstream _p_stream_ = p_stream + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuEGLStreamConsumerAcquireFrame(conn, &p_cuda_resource, &_p_stream_, timeout) + check_status(__status__) + return p_cuda_resource + + +cpdef egl_stream_consumer_release_frame(intptr_t conn, intptr_t p_cuda_resource, intptr_t p_stream): + """Releases the last frame acquired from the EGLStream. + + Release the acquired image frame specified by ``p_cuda_resource`` to + ``EGLStreamKHR``. If EGL_SUPPORT_REUSE_NV flag is set to EGL_TRUE, at the + time of EGL creation this API doesn't release the last frame acquired on + the EGLStream. By default, EGLStream is created with this flag set to + EGL_TRUE. + + Args: + conn (intptr_t): Connection on which to release. + p_cuda_resource (intptr_t): CUDA resource whose corresponding + frame is to be released. + p_stream (intptr_t): CUDA stream on which release will be + done. + + .. seealso:: `cuEGLStreamConsumerReleaseFrame` + """ + cdef CUeglStreamConnection _conn_ = conn + cdef CUstream _p_stream_ = p_stream + with nogil: + __status__ = cuEGLStreamConsumerReleaseFrame(conn, p_cuda_resource, &_p_stream_) + check_status(__status__) + + +cpdef intptr_t egl_stream_producer_connect(intptr_t stream, unsigned int width, unsigned int height) except? 0: + """Connect CUDA to EGLStream as a producer. + + Connect CUDA as a producer to ``EGLStreamKHR`` specified by ``stream``. + + The ``EGLStreamKHR`` is an EGL object that transfers a sequence of image + frames from one API to another. + + Args: + stream (intptr_t): ``EGLStreamKHR`` handle. + width (unsigned int): width of the image to be submitted to + the stream. + height (unsigned int): height of the image to be submitted to + the stream. + + Returns: + intptr_t: Pointer to the returned connection handle. + + .. seealso:: `cuEGLStreamProducerConnect` + """ + cdef CUeglStreamConnection conn + with nogil: + __status__ = cuEGLStreamProducerConnect(&conn, stream, width, height) + check_status(__status__) + return conn + + +cpdef egl_stream_producer_disconnect(intptr_t conn): + """Disconnect CUDA as a producer to EGLStream . + + Disconnect CUDA as a producer to ``EGLStreamKHR``. + + Args: + conn (intptr_t): Conection to disconnect. + + .. seealso:: `cuEGLStreamProducerDisconnect` + """ + cdef CUeglStreamConnection _conn_ = conn + with nogil: + __status__ = cuEGLStreamProducerDisconnect(conn) + check_status(__status__) + + +cpdef intptr_t event_create_from_egl_sync(intptr_t egl_sync, unsigned int flags) except? 0: + """Creates an event from EGLSync object. + + Creates an event *ph_event from an ``EGLSyncKHR`` egl_sync with the flags + specified via ``flags``. Valid flags include:. + + - ``CU_EVENT_DEFAULT``: Default event creation flag. + + - ``CU_EVENT_BLOCKING_SYNC``: Specifies that the created event should use + blocking synchronization. A CPU thread that uses :func:`event_synchronize` + to wait on an event created with this flag will block until the event has + actually been completed. + + Once the ``egl_sync`` gets destroyed, ``cuEventDestroy`` is the only API + that can be invoked on the event. + + ``cuEventRecord`` and TimingData are not supported for events created from + EGLSync. + + The ``EGLSyncKHR`` is an opaque handle to an EGL sync object. typedef void* + ``EGLSyncKHR``. + + Args: + egl_sync (intptr_t): Opaque handle to EGLSync object. + flags (unsigned int): Event creation flags. + + Returns: + intptr_t: Returns newly created event. + + .. seealso:: `cuEventCreateFromEGLSync` + """ + cdef CUevent ph_event + with nogil: + __status__ = cuEventCreateFromEGLSync(&ph_event, egl_sync, flags) + check_status(__status__) + return ph_event + + +cpdef intptr_t graphics_gl_register_buffer(GLuint buffer, unsigned int flags) except? 0: + """Registers an OpenGL buffer object. + + Registers the buffer object specified by ``buffer`` for access by CUDA. A + handle to the registered object is returned as ``p_cuda_resource``. The + register flags ``flags`` specify the intended usage, as follows:. + + - ``CU_GRAPHICS_REGISTER_FLAGS_NONE``: 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. This is the default value. + + - ``CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY``: Specifies that CUDA will not + write to this resource. + + - ``CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD``: Specifies that CUDA 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. + + Args: + buffer (GLuint): name of buffer object to be registered. + flags (unsigned int): Register flags. + + Returns: + intptr_t: Pointer to the returned object handle. + + .. seealso:: `cuGraphicsGLRegisterBuffer` + """ + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuGraphicsGLRegisterBuffer(&p_cuda_resource, buffer, flags) + check_status(__status__) + return p_cuda_resource + + +cpdef intptr_t graphics_gl_register_image(GLuint image, GLenum target, unsigned int flags) except? 0: + """Register an OpenGL texture or renderbuffer object. + + Registers the texture or renderbuffer object specified by ``image`` for + access by CUDA. A handle to the registered object is returned as + ``p_cuda_resource``. + + ``target`` must match the type of the object, and must be one of + ``GL_TEXTURE_2D``, ``GL_TEXTURE_RECTANGLE``, ``GL_TEXTURE_CUBE_MAP``, + ``GL_TEXTURE_3D``, ``GL_TEXTURE_2D_ARRAY``, or ``GL_RENDERBUFFER``. + + The register flags ``flags`` specify the intended usage, as follows:. + + - ``CU_GRAPHICS_REGISTER_FLAGS_NONE``: 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. This is the default value. + + - ``CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY``: Specifies that CUDA will not + write to this resource. + + - ``CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD``: Specifies that CUDA 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. + + - ``CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST``: Specifies that CUDA will + bind this resource to a surface reference. + + - ``CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER``: Specifies that CUDA will + perform texture gather operations on this resource. + + The following image formats are supported. For brevity's sake, the list is + abbreviated. For ex., {GL_R, GL_RG} X {8, 16} would expand to the following + 4 formats {GL_R8, GL_R16, GL_RG8, GL_RG16} :. + + - GL_RED, GL_RG, GL_RGBA, GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, + GL_INTENSITY. + + - {GL_R, GL_RG, GL_RGBA} X {8, 16, 16F, 32F, 8UI, 16UI, 32UI, 8I, 16I, + 32I}. + + - {GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, GL_INTENSITY} X {8, 16, + 16F_ARB, 32F_ARB, 8UI_EXT, 16UI_EXT, 32UI_EXT, 8I_EXT, 16I_EXT, 32I_EXT}. + + The following image classes are currently disallowed:. + + - Textures with borders. + + - Multisampled renderbuffers. + + Args: + image (GLuint): name of texture or renderbuffer object to be + registered. + target (GLenum): Identifies the type of object specified by + ``image``. + flags (unsigned int): Register flags. + + Returns: + intptr_t: Pointer to the returned object handle. + + .. seealso:: `cuGraphicsGLRegisterImage` + """ + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuGraphicsGLRegisterImage(&p_cuda_resource, image, target, flags) + check_status(__status__) + return p_cuda_resource + + +cpdef profiler_start(): + """Enable profiling. + + Enables profile collection by the active profiling tool for the current + context. If profiling is already enabled, then :func:`profiler_start` has + no effect. + + cuProfilerStart and cuProfilerStop APIs are used to programmatically + control the profiling granularity by allowing profiling to be done only on + selective pieces of code. + + .. seealso:: `cuProfilerStart` + """ + with nogil: + __status__ = cuProfilerStart() + check_status(__status__) + + +cpdef profiler_stop(): + """Disable profiling. + + Disables profile collection by the active profiling tool for the current + context. If profiling is already disabled, then :func:`profiler_stop` has + no effect. + + cuProfilerStart and cuProfilerStop APIs are used to programmatically + control the profiling granularity by allowing profiling to be done only on + selective pieces of code. + + .. seealso:: `cuProfilerStop` + """ + with nogil: + __status__ = cuProfilerStop() + check_status(__status__) + + +cpdef int vdpau_get_device(VdpDevice vdp_device, intptr_t vdp_get_proc_address) except? -1: + """Gets the CUDA device associated with a VDPAU device. + + Returns in ``*p_device`` the CUDA device associated with a ``vdp_device``, + if applicable. + + Args: + vdp_device (VdpDevice): A ``Vdp_device`` handle. + vdp_get_proc_address (intptr_t): VDPAU's ``VdpGetProcAddress`` + function pointer. + + Returns: + int: Device associated with vdp_device. + + .. seealso:: `cuVDPAUGetDevice` + """ + cdef CUdevice p_device + with nogil: + __status__ = cuVDPAUGetDevice(&p_device, vdp_device, vdp_get_proc_address) + check_status(__status__) + return p_device + + +cpdef intptr_t vdpau_ctx_create_v2(unsigned int flags, int device, VdpDevice vdp_device, intptr_t vdp_get_proc_address) except? 0: + """Create a CUDA context for interoperability with VDPAU. + + Creates a new CUDA context, initializes VDPAU interoperability, and + associates the CUDA context with the calling thread. It must be called + before performing any other VDPAU interoperability operations. It may fail + if the needed VDPAU driver facilities are not available. For usage of the + ``flags`` parameter, see ``cuCtxCreate()``. + + Args: + flags (unsigned int): Options for CUDA context creation. + device (int): Device on which to create the context. + vdp_device (VdpDevice): The ``VdpDevice`` to interop with. + vdp_get_proc_address (intptr_t): VDPAU's ``VdpGetProcAddress`` + function pointer. + + Returns: + intptr_t: Returned CUDA context. + + .. seealso:: `cuVDPAUCtxCreate_v2` + """ + cdef CUcontext p_ctx + with nogil: + __status__ = cuVDPAUCtxCreate(&p_ctx, flags, device, vdp_device, vdp_get_proc_address) + check_status(__status__) + return p_ctx + + +cpdef intptr_t graphics_vdpau_register_video_surface(VdpVideoSurface vdp_surface, unsigned int flags) except? 0: + """Registers a VDPAU ``VdpVideoSurface`` object. + + Registers the ``VdpVideoSurface`` specified by ``vdp_surface`` for access + by CUDA. A handle to the registered object is returned as + ``p_cuda_resource``. The surface's intended usage is specified using + ``flags``, as follows:. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE``: 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. This is the default value. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY``: Specifies that CUDA will + not write to this resource. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD``: Specifies that CUDA + 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. + + The ``VdpVideoSurface`` is presented as an array of subresources that may + be accessed using pointers returned by + ``cuGraphicsSubResourceGetMappedArray``. The exact number of valid + ``arrayIndex`` values depends on the VDPAU surface format. The mapping is + shown in the table below. ``mipLevel`` must be 0. + + Args: + vdp_surface (VdpVideoSurface): The ``VdpVideoSurface`` to be + registered. + flags (unsigned int): Map flags. + + Returns: + intptr_t: Pointer to the returned object handle. + + .. seealso:: `cuGraphicsVDPAURegisterVideoSurface` + """ + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuGraphicsVDPAURegisterVideoSurface(&p_cuda_resource, vdp_surface, flags) + check_status(__status__) + return p_cuda_resource + + +cpdef intptr_t graphics_vdpau_register_output_surface(VdpOutputSurface vdp_surface, unsigned int flags) except? 0: + """Registers a VDPAU ``VdpOutputSurface`` object. + + Registers the ``VdpOutputSurface`` specified by ``vdp_surface`` for access + by CUDA. A handle to the registered object is returned as + ``p_cuda_resource``. The surface's intended usage is specified using + ``flags``, as follows:. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE``: 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. This is the default value. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY``: Specifies that CUDA will + not write to this resource. + + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD``: Specifies that CUDA + 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. + + The ``VdpOutputSurface`` is presented as an array of subresources that may + be accessed using pointers returned by + ``cuGraphicsSubResourceGetMappedArray``. The exact number of valid + ``arrayIndex`` values depends on the VDPAU surface format. The mapping is + shown in the table below. ``mipLevel`` must be 0. + + Args: + vdp_surface (VdpOutputSurface): The ``VdpOutputSurface`` to be + registered. + flags (unsigned int): Map flags. + + Returns: + intptr_t: Pointer to the returned object handle. + + .. seealso:: `cuGraphicsVDPAURegisterOutputSurface` + """ + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuGraphicsVDPAURegisterOutputSurface(&p_cuda_resource, vdp_surface, flags) + check_status(__status__) + return p_cuda_resource + + +cpdef int ctx_get_device_v2(intptr_t ctx) except? -1: + """Returns the device handle for the specified context. + + Returns in ``*device`` the handle of the specified context's device. If the + specified context is NULL, the API will return the current context's + device. + + Args: + ctx (intptr_t): Context for which to obtain the device. + + Returns: + int: Returned device handle for the specified context. + + .. seealso:: `cuCtxGetDevice_v2` + """ + cdef CUdevice device + with nogil: + __status__ = cuCtxGetDevice_v2(&device, ctx) + check_status(__status__) + return device + + +cpdef ctx_synchronize_v2(intptr_t ctx): + """Block 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 ``CU_CTX_SCHED_BLOCKING_SYNC`` 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. + + Args: + ctx (intptr_t): Context to synchronize. + + .. seealso:: `cuCtxSynchronize_v2` + """ + with nogil: + __status__ = cuCtxSynchronize_v2(ctx) + check_status(__status__) + + +cpdef memcpy_batch_async_v2(intptr_t dsts, intptr_t srcs, intptr_t sizes, size_t count, attrs, intptr_t attrs_idxs, size_t num_attrs, intptr_t h_stream): + """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 ``cuMemcpy3DBatchAsync``. + + 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 ``attrs_idxs`` + array, the index of the first copy that the corresponding entry in the + ``attrs`` array applies to. Both ``attrs`` and ``attrs_idxs`` must be of + the same length as specified by ``num_attrs``. 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 ``num_attrs`` will be 2, + ``attrs_idxs`` will be {0, 6} and ``attrs`` will contains the two sets of + attributes. Note that the first entry in ``attrs_idxs`` must always be 0. + Also, each entry must be greater than the previous entry and the last entry + should be less than ``count``. Furthermore, ``num_attrs`` must be lesser + than or equal to ``count``. + + The ``CUmemcpyAttributes.srcAccessOrder`` indicates the source access + ordering to be observed for copies associated with the attribute. If the + source access order is set to ``CU_MEMCPY_SRC_ACCESS_ORDER_STREAM``, then + the source will be accessed in stream order. If the source access order is + set to ``CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL`` 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 + ``CU_MEMCPY_SRC_ACCESS_ORDER_ANY`` 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 ``CUmemcpyAttributes`` corresponding to it + including the appropriate srcAccessOrder setting, otherwise the API will + return ``CUDA_ERROR_INVALID_VALUE``. + + The ``CUmemcpyAttributes.srcLocHint`` and ``CUmemcpyAttributes.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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` is true or system- + allocated pageable memory on devices where + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS`` is true. For other cases, + these hints are ignored. + + The ``CUmemcpyAttributes.flags`` field can be used to specify certain flags + for copies. Setting the ``CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE`` 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. + + Args: + dsts (intptr_t): Array of destination pointers. + srcs (intptr_t): Array of memcpy source pointers. + sizes (intptr_t): Array of sizes for memcpy operations. + count (size_t): Size of ``dsts``, ``srcs`` and ``sizes`` + arrays. + attrs (intptr_t): Array of memcpy attributes. + attrs_idxs (intptr_t): Array of indices to specify which + copies each entry in the ``attrs`` array applies to. The + attributes specified in attrs[k] will be applied to copies + starting from attrs_idxs[k] through attrs_idxs[k+1] - 1. + Also attrs[num_attrs-1] will apply to copies starting from + attrs_idxs[num_attrs-1] through count - 1. + num_attrs (size_t): Size of ``attrs`` and ``attrs_idxs`` + arrays. + h_stream (intptr_t): The stream to enqueue the operations in. + Must not be legacy NULL stream. + + .. seealso:: `cuMemcpyBatchAsync_v2` + """ + cdef intptr_t _attrs_ptr_ = int(attrs) + with nogil: + __status__ = cuMemcpyBatchAsync(dsts, srcs, sizes, count, _attrs_ptr_, attrs_idxs, num_attrs, h_stream) + check_status(__status__) + + +cpdef memcpy_3d_batch_async_v2(size_t num_ops, intptr_t op_list, unsigned long long flags, intptr_t h_stream): + """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 ``op_list`` array. The length of + this array is specified in ``num_ops``. 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 + ``CUDA_MEMCPY3D_BATCH_OP.src`` and ``CUDA_MEMCPY3D_BATCH_OP.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 ``CUDA_MEMCPY3D_BATCH_OP.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 ``CUmemcpy3DOperand.type`` is specified as + ``CU_MEMCPY_OPERAND_TYPE_POINTER``, then ``CUmemcpy3DOperand.op.ptr`` will + be used. The ``CUmemcpy3DOperand.op.ptr.ptr`` field must contain the + pointer where the copy should begin. The + ``CUmemcpy3DOperand.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 ``CUDA_MEMCPY3D_BATCH_OP``::extent::width. + The ``CUmemcpy3DOperand.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 ``CUDA_MEMCPY3D_BATCH_OP``::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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` is true or system- + allocated pageable memory on devices where + ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS`` is true, the + ``CUmemcpy3DOperand.op.ptr.locHint`` field can be used to hint the location + of the operand. + + If an operand's type is specified as ``CU_MEMCPY_OPERAND_TYPE_ARRAY``, then + ``CUmemcpy3DOperand.op.array`` will be used. The + ``CUmemcpy3DOperand.op.array.array`` field specifies the CUDA array and + ``CUmemcpy3DOperand.op.array.offset`` specifies the 3D offset into that + array where the copy begins. + + The ``CUmemcpyAttributes.srcAccessOrder`` indicates the source access + ordering to be observed for copies associated with the attribute. If the + source access order is set to ``CU_MEMCPY_SRC_ACCESS_ORDER_STREAM``, then + the source will be accessed in stream order. If the source access order is + set to ``CU_MEMCPY_SRC_ACCESS_ORDER_DURING_API_CALL`` 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 + ``CU_MEMCPY_SRC_ACCESS_ORDER_ANY`` 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 + ``op_list`` must have a valid srcAccessOrder setting, otherwise this API + will return ``CUDA_ERROR_INVALID_VALUE``. + + The ``CUmemcpyAttributes.flags`` field can be used to specify certain flags + for copies. Setting the ``CU_MEMCPY_FLAG_PREFER_OVERLAP_WITH_COMPUTE`` 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. + + Args: + num_ops (size_t): Total number of memcpy operations. + op_list (intptr_t): Array of size ``num_ops`` containing the + actual memcpy operations. + flags (unsigned long long): Flags for future use, must be zero + now. + h_stream (intptr_t): The stream to enqueue the operations in. + Must not be default NULL stream. + + .. seealso:: `cuMemcpy3DBatchAsync_v2` + """ + with nogil: + __status__ = cuMemcpy3DBatchAsync(num_ops, op_list, flags, h_stream) + check_status(__status__) + + +cpdef intptr_t mem_get_default_mem_pool(location, int type) except? 0: + """Returns the default memory pool for a given location and allocation type. + + The memory location can be of one of ``CU_MEM_LOCATION_TYPE_DEVICE``, + ``CU_MEM_LOCATION_TYPE_HOST``, or ``CU_MEM_LOCATION_TYPE_HOST_NUMA``. The + allocation type can be one of ``CU_MEM_ALLOCATION_TYPE_PINNED`` or + ``CU_MEM_ALLOCATION_TYPE_MANAGED``. When the allocation type is + ``CU_MEM_ALLOCATION_TYPE_MANAGED``, the location type can also be + ``CU_MEM_LOCATION_TYPE_NONE`` to indicate no preferred location for the + managed memory pool. + + Args: + location (intptr_t): Memory location for which to query the + default memory pool. + type (MemAllocationType): Allocation type for which to query + the default memory pool. + + Returns: + intptr_t: Returned default memory pool for the given location + and allocation type. + + .. seealso:: `cuMemGetDefaultMemPool` + """ + cdef intptr_t _location_ptr_ = int(location) + cdef CUmemoryPool pool_out + with nogil: + __status__ = cuMemGetDefaultMemPool(&pool_out, _location_ptr_, type) + check_status(__status__) + return pool_out + + +cpdef intptr_t mem_get_mem_pool(location, int type) except? 0: + """Gets the current memory pool for a memory location and of a particular allocation type. + + The memory location can be of one of ``CU_MEM_LOCATION_TYPE_DEVICE``, + ``CU_MEM_LOCATION_TYPE_HOST`` or ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, or + ``CU_MEM_LOCATION_TYPE_HOST_NUMA``. The allocation type can be one of + ``CU_MEM_ALLOCATION_TYPE_PINNED`` or ``CU_MEM_ALLOCATION_TYPE_MANAGED``. + When the allocation type is ``CU_MEM_ALLOCATION_TYPE_MANAGED``, the + location type can also be ``CU_MEM_LOCATION_TYPE_NONE`` to indicate no + preferred location for the managed memory pool. In all other cases, the + call returns ``CUDA_ERROR_INVALID_VALUE``. + + Returns the last pool provided to ``cuMemSetMemPool`` or + ``cuDeviceSetMemPool`` for this location and allocation type or the + location's default memory pool if ``cuMemSetMemPool`` or + ``cuDeviceSetMemPool`` 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 + ``cuDeviceSetMemPool``. + + Args: + location (intptr_t): Memory location for which to query the + current memory pool. + type (MemAllocationType): Allocation type for which to query + the current memory pool. + + Returns: + intptr_t: Returned current memory pool for the given location + and allocation type. + + .. seealso:: `cuMemGetMemPool` + """ + cdef intptr_t _location_ptr_ = int(location) + cdef CUmemoryPool pool + with nogil: + __status__ = cuMemGetMemPool(&pool, _location_ptr_, type) + check_status(__status__) + return pool + + +cpdef mem_set_mem_pool(location, int type, intptr_t pool): + """Sets the current memory pool for a memory location and allocation type. + + The memory location can be of one of ``CU_MEM_LOCATION_TYPE_DEVICE``, + ``CU_MEM_LOCATION_TYPE_HOST`` or or ``CU_MEM_LOCATION_TYPE_HOST_NUMA``. The + allocation type can be one of ``CU_MEM_ALLOCATION_TYPE_PINNED`` or + ``CU_MEM_ALLOCATION_TYPE_MANAGED``. When the allocation type is + ``CU_MEM_ALLOCATION_TYPE_MANAGED``, the location type can also be + ``CU_MEM_LOCATION_TYPE_NONE`` to indicate no preferred location for the + managed memory pool. ``CU_MEM_ALLOCATION_TYPE_MANAGED`` can not be used + with ``CU_MEM_LOCATION_TYPE_DEVICE_MEMORY_NODE``. In all other cases, the + call returns ``CUDA_ERROR_INVALID_VALUE``. + + 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 + ``CUDA_ERROR_INVALID_VALUE`` is returned. By default, a memory location's + current memory pool is its default memory pool that can be obtained via + ``cuMemGetDefaultMemPool``. If the location type is + ``CU_MEM_LOCATION_TYPE_DEVICE`` and the allocation type is + ``CU_MEM_ALLOCATION_TYPE_PINNED``, then this API is the equivalent of + calling ``cuDeviceSetMemPool`` with the location id as the device. For + further details on the implications, please refer to the documentation for + ``cuDeviceSetMemPool``. + + Args: + location (intptr_t): Memory location for which to set the + current memory pool. + type (MemAllocationType): Allocation type for which to set the + current memory pool. + pool (intptr_t): Memory pool to use as the current memory pool + for the given location and allocation type. + + .. note:: + Use ``cuMemAllocFromPoolAsync`` to specify asynchronous allocations + from a device different than the one the stream runs on. + + .. seealso:: `cuMemSetMemPool` + """ + cdef intptr_t _location_ptr_ = int(location) + with nogil: + __status__ = cuMemSetMemPool(_location_ptr_, type, pool) + check_status(__status__) + + +cpdef mem_prefetch_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, prefetch_locs, intptr_t prefetch_loc_idxs, size_t num_prefetch_locs, unsigned long long flags, intptr_t h_stream): + """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 ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` + otherwise the API will return an error. + + The semantics of the individual prefetch operations are as described in + ``cuMemPrefetchAsync``. + + 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 ``cuMemAllocManaged`` or declared via managed variables or it + may also refer to system-allocated memory when all devices have a non-zero + value for ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. The prefetch + location for every operation in the batch is specified in the + ``prefetch_locs`` array. Each entry in this array can apply to more than + one operation. This can be done by specifying in the ``prefetch_loc_idxs`` + array, the index of the first prefetch operation that the corresponding + entry in the ``prefetch_locs`` array applies to. Both ``prefetch_locs`` and + ``prefetch_loc_idxs`` must be of the same length as specified by + ``num_prefetch_locs``. 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 ``num_prefetch_locs`` + will be 2, ``prefetch_loc_idxs`` will be {0, 4} and ``prefetch_locs`` will + contain the two locations. Note the first entry in ``prefetch_loc_idxs`` + must always be 0. Also, each entry must be greater than the previous entry + and the last entry should be less than ``count``. Furthermore, + ``num_prefetch_locs`` must be lesser than or equal to ``count``. + + Args: + dptrs (intptr_t): Array of pointers to be prefetched. + sizes (intptr_t): Array of sizes for memory prefetch + operations. + count (size_t): Size of ``dptrs`` and ``sizes`` arrays. + prefetch_locs (intptr_t): Array of locations to prefetch to. + prefetch_loc_idxs (intptr_t): Array of indices to specify + which operands each entry in the ``prefetch_locs`` array + applies to. The locations specified in prefetch_locs[k] + will be applied to copies starting from + prefetch_loc_idxs[k] through prefetch_loc_idxs[k+1] - 1. + Also prefetch_locs[num_prefetch_locs - 1] will apply to + prefetches starting from + prefetch_loc_idxs[num_prefetch_locs - 1] through count - + 1. + num_prefetch_locs (size_t): Size of ``prefetch_locs`` and + ``prefetch_loc_idxs`` arrays. + flags (unsigned long long): Flags reserved for future use. + Must be zero. + h_stream (intptr_t): The stream to enqueue the operations in. + Must not be legacy NULL stream. + + .. seealso:: `cuMemPrefetchBatchAsync` + """ + cdef intptr_t _prefetch_locs_ptr_ = int(prefetch_locs) + with nogil: + __status__ = cuMemPrefetchBatchAsync(dptrs, sizes, count, _prefetch_locs_ptr_, prefetch_loc_idxs, num_prefetch_locs, flags, h_stream) + check_status(__status__) + + +cpdef mem_discard_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, unsigned long long flags, intptr_t h_stream): + """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 ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` + 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 ``cuMemPrefetchAsync`` or + ``cuMemPrefetchBatchAsync``. 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 ``cuMemAllocManaged`` or declared via managed variables or it + may also refer to system-allocated memory when all devices have a non-zero + value for ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. + + Args: + dptrs (intptr_t): Array of pointers to be discarded. + sizes (intptr_t): Array of sizes for memory discard + operations. + count (size_t): Size of ``dptrs`` and ``sizes`` arrays. + flags (unsigned long long): Flags reserved for future use. + Must be zero. + h_stream (intptr_t): The stream to enqueue the operations in. + Must not be legacy NULL stream. + + .. seealso:: `cuMemDiscardBatchAsync` + """ + with nogil: + __status__ = cuMemDiscardBatchAsync(dptrs, sizes, count, flags, h_stream) + check_status(__status__) + + +cpdef mem_discard_and_prefetch_batch_async(intptr_t dptrs, intptr_t sizes, size_t count, prefetch_locs, intptr_t prefetch_loc_idxs, size_t num_prefetch_locs, unsigned long long flags, intptr_t h_stream): + """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 + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS`` otherwise the API will + return an error. + + Calling ``cuMemDiscardAndPrefetchBatchAsync`` is semantically equivalent to + calling ``cuMemDiscardBatchAsync`` followed by ``cuMemPrefetchBatchAsync``, + but is more optimal. For more details on what discarding and prefetching + imply, please refer to ``cuMemDiscardBatchAsync`` and + ``cuMemPrefetchBatchAsync`` 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 ``cuMemAllocManaged`` or declared via managed + variables or it may also refer to system-allocated memory when all devices + have a non-zero value for ``CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS``. + Every operation in the batch has to be associated with a valid location to + prefetch the address range to and specified in the ``prefetch_locs`` array. + Each entry in this array can apply to more than one operation. This can be + done by specifying in the ``prefetch_loc_idxs`` array, the index of the + first operation that the corresponding entry in the ``prefetch_locs`` array + applies to. Both ``prefetch_locs`` and ``prefetch_loc_idxs`` must be of the + same length as specified by ``num_prefetch_locs``. 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 ``num_prefetch_locs`` will be 2, ``prefetch_loc_idxs`` will + be {0, 6} and ``prefetch_locs`` will contain the two set of locations. Note + the first entry in ``prefetch_loc_idxs`` must always be 0. Also, each entry + must be greater than the previous entry and the last entry should be less + than ``count``. Furthermore, ``num_prefetch_locs`` must be lesser than or + equal to ``count``. + + Args: + dptrs (intptr_t): Array of pointers to be discarded. + sizes (intptr_t): Array of sizes for memory discard + operations. + count (size_t): Size of ``dptrs`` and ``sizes`` arrays. + prefetch_locs (intptr_t): Array of locations to prefetch to. + prefetch_loc_idxs (intptr_t): Array of indices to specify + which operands each entry in the ``prefetch_locs`` array + applies to. The locations specified in prefetch_locs[k] + will be applied to operations starting from + prefetch_loc_idxs[k] through prefetch_loc_idxs[k+1] - 1. + Also prefetch_locs[num_prefetch_locs - 1] will apply to + copies starting from prefetch_loc_idxs[num_prefetch_locs - + 1] through count - 1. + num_prefetch_locs (size_t): Size of ``prefetch_locs`` and + ``prefetch_loc_idxs`` arrays. + flags (unsigned long long): Flags reserved for future use. + Must be zero. + h_stream (intptr_t): The stream to enqueue the operations in. + Must not be legacy NULL stream. + + .. seealso:: `cuMemDiscardAndPrefetchBatchAsync` + """ + cdef intptr_t _prefetch_locs_ptr_ = int(prefetch_locs) + with nogil: + __status__ = cuMemDiscardAndPrefetchBatchAsync(dptrs, sizes, count, _prefetch_locs_ptr_, prefetch_loc_idxs, num_prefetch_locs, flags, h_stream) + check_status(__status__) + + +cpdef unsigned int device_get_p2p_atomic_capabilities(intptr_t operations, unsigned int count, int src_device, int dst_device) except? 0: + """Queries details about atomic operations supported between two devices. + + Returns in ``*capabilities`` the details about requested atomic + ``*operations`` over the the link between ``src_device`` and + ``dst_device``. The allocated size of ``*operations`` and ``*capabilities`` + must be ``count``. + + For each ``CUatomicOperation`` in ``*operations``, the corresponding result + in ``*capabilities`` will be a bitmask indicating which of + ``CUatomicOperationCapability`` the link supports natively. + + Returns ``CUDA_ERROR_INVALID_DEVICE`` if ``src_device`` or ``dst_device`` + are not valid or if they represent the same device. + + Returns ``CUDA_ERROR_INVALID_VALUE`` if ``*capabilities`` or + ``*operations`` is NULL, if ``count`` is 0, or if any of ``*operations`` is + not valid. + + Args: + operations (intptr_t): Requested operations. + count (unsigned int): Count of requested operations and size + of capabilities. + src_device (int): The source device of the target link. + dst_device (int): The destination device of the target link. + + Returns: + unsigned int: Returned capability details of each requested + operation. + + .. seealso:: `cuDeviceGetP2PAtomicCapabilities` + """ + cdef unsigned int capabilities + with nogil: + __status__ = cuDeviceGetP2PAtomicCapabilities(&capabilities, operations, count, src_device, dst_device) + check_status(__status__) + return capabilities + + +cpdef unsigned long long green_ctx_get_id(intptr_t green_ctx) except? 0: + """Returns the unique Id associated with the green context supplied. + + Returns in ``green_ctxId`` 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. + + Args: + green_ctx (intptr_t): Green context for which to obtain the + Id. + + Returns: + unsigned long long: Pointer to store the Id of the green + context. + + .. seealso:: `cuGreenCtxGetId` + """ + cdef unsigned long long green_ctx_id + with nogil: + __status__ = cuGreenCtxGetId(green_ctx, &green_ctx_id) + check_status(__status__) + return green_ctx_id + + +cpdef multicast_bind_mem_v2(unsigned long long mc_handle, int dev, size_t mc_offset, unsigned long long mem_handle, size_t mem_offset, size_t size, unsigned long long flags): + """Bind a memory allocation represented by a handle to a multicast object. + + Binds a memory allocation specified by ``mem_handle`` and created via + ``cuMemCreate`` to a multicast object represented by ``mc_handle`` and + created via ``cuMulticastCreate``. The binding will be applicable for the + device ``dev``. The intended ``size`` of the bind, the offset in the + multicast range ``mc_offset`` as well as the offset in the memory + ``mem_offset`` must be a multiple of the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. For best performance however, + ``size``, ``mc_offset`` and ``mem_offset`` should be aligned to the + granularity of the memory allocation(see ``cuMemGetAllocationGranularity``) + or to the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. + + The ``size`` + ``mem_offset`` cannot be larger than the size of the + allocated memory. Similarly the ``size`` + ``mc_offset`` cannot be larger + than the size of the multicast object. + + The memory allocation must have beeen created on one of the devices that + was added to the multicast team via ``cuMulticastAddDevice``. For device + memory, i.e., type ``CU_MEM_LOCATION_TYPE_DEVICE``, the memory allocation + must have been created on the device specified by ``dev``. For host NUMA + memory, i.e., type ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, the memory + allocation must have been created on the CPU NUMA node closest to ``dev``. + That is, the value returned when querying + ``CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID`` 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 ``cuMulticastAddDevice``. + Externally shareable as well as imported multicast objects can be bound + only to externally shareable memory. Note that this call will return + CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to + perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if + the necessary system software is not initialized or running. + + This call may return CUDA_ERROR_ILLEGAL_STATE 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. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + dev (int): The device that for which the multicast memory + binding will be applicable. + mc_offset (size_t): Offset into the multicast object for + attachment. + mem_handle (unsigned long long): Handle representing a memory + allocation. + mem_offset (size_t): Offset into the memory for attachment. + size (size_t): Size of the memory that will be bound to the + multicast object. + flags (unsigned long long): Flags for future use, must be zero + for now. + + .. seealso:: `cuMulticastBindMem_v2` + """ + with nogil: + __status__ = cuMulticastBindMem_v2(mc_handle, dev, mc_offset, mem_handle, mem_offset, size, flags) + check_status(__status__) + + +cpdef multicast_bind_addr_v2(unsigned long long mc_handle, int dev, size_t mc_offset, unsigned long long memptr, size_t size, unsigned long long flags): + """Bind 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 ``mc_handle``. The binding will be + applicable for the device ``dev``. The memory must have been allocated via + ``cuMemCreate`` or ``cudaMallocAsync``. The intended ``size`` of the bind, + the offset in the multicast range ``mc_offset`` and ``memptr`` must be a + multiple of the value returned by ``cuMulticastGetGranularity`` with the + flag ``CU_MULTICAST_GRANULARITY_MINIMUM``. For best performance however, + ``size``, ``mc_offset`` and ``memptr`` should be aligned to the value + returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. + + The ``size`` cannot be larger than the size of the allocated memory. + Similarly the ``size`` + ``mc_offset`` cannot be larger than the total size + of the multicast object. + + For device memory, i.e., type ``CU_MEM_LOCATION_TYPE_DEVICE``, the memory + allocation must have been created on the device specified by ``dev``. For + host NUMA memory, i.e., type ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, the memory + allocation must have been created on the CPU NUMA node closest to ``dev``. + That is, the value returned when querying + ``CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID`` 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 ``cuMulticastAddDevice``. + Externally shareable as well as imported multicast objects can be bound + only to externally shareable memory. Note that this call will return + CUDA_ERROR_OUT_OF_MEMORY if there are insufficient resources required to + perform the bind. This call may also return CUDA_ERROR_SYSTEM_NOT_READY if + the necessary system software is not initialized or running. + + This call may return CUDA_ERROR_ILLEGAL_STATE 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. + + Args: + mc_handle (unsigned long long): Handle representing a + multicast object. + dev (int): The device that for which the multicast memory + binding will be applicable. + mc_offset (size_t): Offset into multicast va range for + attachment. + memptr (unsigned long long): Virtual address of the memory + allocation. + size (size_t): Size of memory that will be bound to the + multicast object. + flags (unsigned long long): Flags for future use, must be zero + now. + + .. seealso:: `cuMulticastBindAddr_v2` + """ + with nogil: + __status__ = cuMulticastBindAddr_v2(mc_handle, dev, mc_offset, memptr, size, flags) + check_status(__status__) + + +cpdef intptr_t graph_node_get_containing_graph(intptr_t h_node) except? 0: + """Returns the graph that contains a given graph node. + + Returns the graph that contains ``h_node`` in ``*ph_graph``. If ``h_node`` + is in a child graph, the child graph it is in is returned. + + Args: + h_node (intptr_t): Node to query. + + Returns: + intptr_t: Pointer to return the containing graph. + + .. seealso:: `cuGraphNodeGetContainingGraph` + """ + cdef CUgraph ph_graph + with nogil: + __status__ = cuGraphNodeGetContainingGraph(h_node, &ph_graph) + check_status(__status__) + return ph_graph + + +cpdef unsigned int graph_node_get_local_id(intptr_t h_node) except? 0: + """Returns the local node id of a given graph node. + + Returns the node id of ``h_node`` in ``*node_id``. The node_id matches that + referenced by ``cuGraphDebugDotPrint``. The local node_id and graphId + together can uniquely identify the node. + + Args: + h_node (intptr_t): Node to query. + + Returns: + unsigned int: Pointer to return the node_id. + + .. seealso:: `cuGraphNodeGetLocalId` + """ + cdef unsigned int node_id + with nogil: + __status__ = cuGraphNodeGetLocalId(h_node, &node_id) + check_status(__status__) + return node_id + + +cpdef unsigned long long graph_node_get_tools_id(intptr_t h_node) except? 0: + """Returns an id used by tools to identify a given node. + + Args: + h_node (intptr_t): Node to query. + + Returns: + unsigned long long: Pointer to return the id used by tools. + + .. seealso:: `cuGraphNodeGetToolsId` + """ + cdef unsigned long long tools_node_id + with nogil: + __status__ = cuGraphNodeGetToolsId(h_node, &tools_node_id) + check_status(__status__) + return tools_node_id + + +cpdef unsigned int graph_get_id(intptr_t h_graph) except? 0: + """Returns the id of a given graph. + + Returns the id of ``h_graph`` in ``*graph_id``. The value in ``*graph_id`` + will match that referenced by ``cuGraphDebugDotPrint``. + + Args: + h_graph (intptr_t): Graph to query. + + Returns: + unsigned int: Pointer to return the graph_id. + + .. seealso:: `cuGraphGetId` + """ + cdef unsigned int graph_id + with nogil: + __status__ = cuGraphGetId(h_graph, &graph_id) + check_status(__status__) + return graph_id + + +cpdef unsigned int graph_exec_get_id(intptr_t h_graph_exec) except? 0: + """Returns the id of a given graph exec. + + Returns the id of ``h_graph_exec`` in ``*graph_id``. The value in + ``*graph_id`` will match that referenced by ``cuGraphDebugDotPrint``. + + Args: + h_graph_exec (intptr_t): Graph to query. + + Returns: + unsigned int: Pointer to return the graph_id. + + .. seealso:: `cuGraphExecGetId` + """ + cdef unsigned int graph_id + with nogil: + __status__ = cuGraphExecGetId(h_graph_exec, &graph_id) + check_status(__status__) + return graph_id + + +cpdef dev_sm_resource_split(result, unsigned int nb_groups, input, remainder, unsigned int flags, group_params): + """Splits a ``CU_DEV_RESOURCE_TYPE_SM`` resource into structured groups. + + This API will split a resource of ``CU_DEV_RESOURCE_TYPE_SM`` into + ``nb_groups`` structured device resource groups (the ``result`` array), as + well as an optional ``remainder``, according to a set of requirements + specified in the ``group_params`` 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 + ``group_params`` 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 ``group_params`` array entry is set to 0 - the + smCount will be filled in by the API with the derived SM count according to + the provided ``group_params`` 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 ``group_params`` array is evaluated from index 0 to ``nb_groups`` - 1. + For each index in the ``group_params`` 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 ``CUdevResource`` array of size + ``nb_groups``, or alternatively, may be NULL, if the developer wishes for + only the group_params entries to be updated. + + - ``input`` should be a valid ``CU_DEV_RESOURCE_TYPE_SM`` 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 ``CU_DEV_SM_RESOURCE_GROUP_PARAMS`` array of size ``nb_groups``. 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``. + 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 + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION 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 ``CU_DEV_RESOURCE_TYPE_SM`` resource (8 on + Compute Architecture 9.0+ and 2 otherwise). The maximum is 32 on Compute + Architecture 9.0+ and 2 otherwise. + + - ``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:``. + + - ``CU_DEV_SM_RESOURCE_GROUP_BACKFILL:`` 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. + + Example params and their effect:. + + A group_params array element is defined in the following order:. + + **View CUDA Toolkit Documentation for a C++ code example**. + + **View CUDA Toolkit Documentation for a C++ code example**. + + **View CUDA Toolkit Documentation for a C++ code example**. + + **View CUDA Toolkit Documentation for a C++ code example**. + + 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 ``CU_DEV_SM_RESOURCE_GROUP_BACKFILL`` 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. + + Args: + result (intptr_t): Output array of ``CUdevResource`` + resources. Can be NULL, alongside an smCount of 0, for + discovery purpose. + nb_groups (unsigned int): Specifies the number of groups in + ``result`` and ``group_params``. + input (intptr_t): Input SM resource to be split. Must be a + valid ``CU_DEV_RESOURCE_TYPE_SM`` resource. + remainder (intptr_t): If splitting the input resource leaves + any SMs, the remainder is placed in here. + flags (unsigned int): Flags specifying how the API should + behave. The value should be 0 for now. + group_params (intptr_t): Description of how the SMs should be + split and assigned to the corresponding result entry. + + .. seealso:: `cuDevSmResourceSplit` + """ + cdef intptr_t _result_ptr_ = int(result) + cdef intptr_t _input_ptr_ = int(input) + cdef intptr_t _remainder_ptr_ = int(remainder) + cdef intptr_t _group_params_ptr_ = int(group_params) + with nogil: + __status__ = cuDevSmResourceSplit(_result_ptr_, nb_groups, _input_ptr_, _remainder_ptr_, flags, _group_params_ptr_) + check_status(__status__) + + +cpdef stream_get_dev_resource(intptr_t h_stream, resource, int type): + """Get stream resources. + + Get the ``typename`` resources available to the ``h_stream`` and store them + in ``resource``. + + Note: The API will return ``CUDA_ERROR_INVALID_RESOURCE_TYPE`` is + ``typename`` is ``CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG`` or + ``CU_DEV_RESOURCE_TYPE_WORKQUEUE``. + + Args: + h_stream (intptr_t): Stream to get resource for. + resource (intptr_t): Output pointer to a ``CUdevResource`` + structure. + type (DevResourceType): Type of resource to retrieve. + + .. seealso:: `cuStreamGetDevResource` + """ + cdef intptr_t _resource_ptr_ = int(resource) + with nogil: + __status__ = cuStreamGetDevResource(h_stream, _resource_ptr_, type) + check_status(__status__) + + +cpdef size_t kernel_get_param_count(intptr_t kernel) except? 0: + """Returns the number of parameters used by the kernel. + + Queries the number of kernel parameters used by ``kernel`` and returns it + in ``param_count``. + + Args: + kernel (intptr_t): The kernel to query. + + Returns: + size_t: Returns the number of parameters used by the function. + + .. seealso:: `cuKernelGetParamCount` + """ + cdef size_t param_count + with nogil: + __status__ = cuKernelGetParamCount(kernel, ¶m_count) + check_status(__status__) + return param_count + + +cpdef memcpy_with_attributes_async(unsigned long long dst, unsigned long long src, size_t size, attr, intptr_t h_stream): + """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 + ``h_stream`` specifies the stream to enqueue the operation in. + + For more information regarding the attributes, please refer to + ``CUmemcpyAttributes`` and it's usage desciption in::cuMemcpyBatchAsync. + + Args: + dst (unsigned long long): Destination device pointer. + src (unsigned long long): Source device pointer. + size (size_t): Number of bytes to copy. + attr (intptr_t): Attributes for the copy. + h_stream (intptr_t): Stream to enqueue the operation in. + + .. seealso:: `cuMemcpyWithAttributesAsync` + """ + cdef intptr_t _attr_ptr_ = int(attr) + with nogil: + __status__ = cuMemcpyWithAttributesAsync(dst, src, size, _attr_ptr_, h_stream) + check_status(__status__) + + +cpdef memcpy_3d_with_attributes_async(intptr_t op, unsigned long long flags, intptr_t h_stream): + """Performs 3D memory copy with attributes asynchronously. + + Performs the copy operation specified in ``op``. ``flags`` specifies the + flags for the copy and ``h_stream`` specifies the stream to enqueue the + operation in. + + For more information regarding the operation, please refer to + ``CUDA_MEMCPY3D_BATCH_OP`` and it's usage desciption + in::cuMemcpy3DBatchAsync. + + Args: + op (intptr_t): Operation to perform. + flags (unsigned long long): Flags for the copy, must be zero + now. + h_stream (intptr_t): Stream to enqueue the operation in. + + .. seealso:: `cuMemcpy3DWithAttributesAsync` + """ + with nogil: + __status__ = cuMemcpy3DWithAttributesAsync(op, flags, h_stream) + check_status(__status__) + + +cpdef stream_begin_capture_to_cig(intptr_t h_stream, intptr_t stream_cig_capture_params): + """Begins capture to CIG on a stream. + + Support for CIG streams with D3D12 can be determined using + :func:`device_get_attribute` with + ``CU_DEVICE_ATTRIBUTE_D3D12_CIG_STREAMS_SUPPORTED``. + + Begin CIG (CUDA in Graphics) capture on ``h_stream`` for the graphics API + as provided in ``stream_cig_capture_params``. 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 ``CUDA_ERROR_INVALID_CONTEXT`` will be returned. + + Data from the graphics client can be shared with CUDA via the + ``streamSharedData`` in ``stream_cig_capture_params``. 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 + ``cuStreamEndCaptureToCig`` 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 ``cuStreamBeginCapture`` with the + ``CU_STREAM_CAPTURE_MODE_RELAXED`` 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: + ``cuLaunchHostFunc`` ``cuStreamAddCallback`` ``cuStreamSynchronize`` + ``cuStreamWaitValue32`` ``cuStreamWaitValue64`` ``cuStreamBatchMemOp`` + ``cuStreamBeginCapture`` ``cuStreamBeginCaptureToGraph`` + ``cuMemAllocAsync`` ``cuMemFreeAsync``. + + Args: + h_stream (intptr_t): Stream in which to initiate capture to + CIG. + stream_cig_capture_params (intptr_t): CIG capture parameters. + + .. seealso:: `cuStreamBeginCaptureToCig` + """ + with nogil: + __status__ = cuStreamBeginCaptureToCig(h_stream, stream_cig_capture_params) + check_status(__status__) + + +cpdef stream_end_capture_to_cig(intptr_t h_stream): + """Ends CIG capture on a stream. + + End CIG capture on ``h_stream``. Capture must have been initiated on + ``h_stream`` via a call to ``cuStreamBeginCaptureToCig``. Once this + function is called, ``h_stream`` 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 ``h_stream`` in the + previous call to ``cuStreamBeginCaptureToCig`` 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). + + Args: + h_stream (intptr_t): Stream to end CIG capture. + + .. seealso:: `cuStreamEndCaptureToCig` + """ + with nogil: + __status__ = cuStreamEndCaptureToCig(h_stream) + check_status(__status__) + + +cpdef size_t func_get_param_count(intptr_t func) except? 0: + """Returns the number of parameters used by the function. + + Queries the number of kernel parameters used by ``func`` and returns it in + ``param_count``. + + Args: + func (intptr_t): The function to query. + + Returns: + size_t: Returns the number of parameters used by the function. + + .. seealso:: `cuFuncGetParamCount` + """ + cdef size_t param_count + with nogil: + __status__ = cuFuncGetParamCount(func, ¶m_count) + check_status(__status__) + return param_count + + +cpdef launch_host_func_v2(intptr_t h_stream, intptr_t fn, intptr_t user_data, unsigned int sync_mode): + """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 ``CUDA_ERROR_NOT_PERMITTED``, 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 ``cuStreamAddCallback``, the function will not be + called in the event of an error in the CUDA context. + + Args: + h_stream (intptr_t): Stream to enqueue function call in. + fn (intptr_t): The function to call once preceding stream + operations are complete. + user_data (intptr_t): User-specified data to be passed to the + function. + sync_mode (unsigned int): Synchronization mode for the host + function. + + .. seealso:: `cuLaunchHostFunc_v2` + """ + with nogil: + __status__ = cuLaunchHostFunc_v2(h_stream, fn, user_data, sync_mode) + check_status(__status__) + + +cpdef graph_node_get_params(intptr_t h_node, node_params): + """Return a graph node's parameters. + + Returns the parameters of graph node ``h_node`` in ``*node_params``. + + Any pointers returned in ``*node_params`` point to driver-owned memory + associated with the node. This memory remains valid until the node is + destroyed. Any memory pointed to from ``*node_params`` 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. + + Args: + h_node (intptr_t): Node to get the parameters for. + node_params (intptr_t): Pointer to return the parameters. + + .. seealso:: `cuGraphNodeGetParams` + """ + cdef intptr_t _node_params_ptr_ = int(node_params) + with nogil: + __status__ = cuGraphNodeGetParams(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef intptr_t coredump_register_start_callback(intptr_t callback, intptr_t user_data) except? 0: + """Register 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 user_data, and each registration + will receive a unique handle. + + Args: + callback (intptr_t): The callback function to register. + user_data (intptr_t): User data pointer to pass to the + callback. + + Returns: + intptr_t: Location to store the callback handle (optional, may + be NULL). + + .. note:: + Callbacks execute synchronously during the coredump process and will + block coredump progress while running. + + .. seealso:: `cuCoredumpRegisterStartCallback` + """ + cdef CUcoredumpCallbackHandle callback_out + with nogil: + __status__ = cuCoredumpRegisterStartCallback(callback, user_data, &callback_out) + check_status(__status__) + return callback_out + + +cpdef intptr_t coredump_register_complete_callback(intptr_t callback, intptr_t user_data) except? 0: + """Register 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 user_data, and each registration will receive + a unique handle. + + Args: + callback (intptr_t): The callback function to register. + user_data (intptr_t): User data pointer to pass to the + callback. + + Returns: + intptr_t: Location to store the callback handle (optional, may + be NULL). + + .. note:: + Callbacks execute synchronously during the coredump process and will + block coredump progress while running. + + .. seealso:: `cuCoredumpRegisterCompleteCallback` + """ + cdef CUcoredumpCallbackHandle callback_out + with nogil: + __status__ = cuCoredumpRegisterCompleteCallback(callback, user_data, &callback_out) + check_status(__status__) + return callback_out + + +cpdef coredump_deregister_start_callback(intptr_t callback): + """Deregister a previously registered coredump start callback. + + This function removes a callback that was registered with + ``cuCoredumpRegisterStartCallback``. The callback handle becomes invalid + after this call. + + Args: + callback (intptr_t): The callback handle to deregister. + + .. note:: + It is the caller's responsibility to deregister callbacks before they + go out of scope. + + .. seealso:: `cuCoredumpDeregisterStartCallback` + """ + with nogil: + __status__ = cuCoredumpDeregisterStartCallback(callback) + check_status(__status__) + + +cpdef coredump_deregister_complete_callback(intptr_t callback): + """Deregister a previously registered coredump complete callback. + + This function removes a callback that was registered with + ``cuCoredumpRegisterCompleteCallback``. The callback handle becomes invalid + after this call. + + Args: + callback (intptr_t): The callback handle to deregister. + + .. note:: + It is the caller's responsibility to deregister callbacks before they + go out of scope. + + .. seealso:: `cuCoredumpDeregisterCompleteCallback` + """ + with nogil: + __status__ = cuCoredumpDeregisterCompleteCallback(callback) + check_status(__status__) + + +cpdef uint32_t logical_endpoint_id_reserve(uint64_t count) except? 0: + """Reserves a range of logical endpoint ids. + + Reserves a range of logical endpoint ids starting at ``*base_le_id`` and + extending for ``count``. The reserved ids can be used to create or import + logical endpoints via ``cuLogicalEndpointCreate`` or + ``cuLogicalEndpointImport`` respectively. + + Args: + count (uint64_t): The number of logical endpoint ids to + reserve. + + Returns: + uint32_t: If ``cuLogicalEndpointIdReserve`` returns + CUDA_SUCCESS, *base_le_id contains the base logical + endpoint id of the reserved logical endpoint id range. + + .. seealso:: `cuLogicalEndpointIdReserve` + """ + cdef CUlogicalEndpointId base_le_id + with nogil: + __status__ = cuLogicalEndpointIdReserve(&base_le_id, count) + check_status(__status__) + return base_le_id + + +cpdef logical_endpoint_id_release(uint32_t base_le_id, uint64_t count): + """Releases a range of logical endpoint ids. + + Releases up to ``count`` logical endpoint ids starting at ``base_le_id``. + The range of ids represented by [``base_le_id``, ``base_le_id`` + + ``count``) must all be previously reserved. All logical endpoints in the + range must be destroyed before they can be released. + + Args: + base_le_id (uint32_t): First logical endpoint id to be + released back to the system. + count (uint64_t): Number of logical endpoint ids to release + back to the system. + + .. seealso:: `cuLogicalEndpointIdRelease` + """ + with nogil: + __status__ = cuLogicalEndpointIdRelease(base_le_id, count) + check_status(__status__) + + +cpdef logical_endpoint_create(uint32_t le_id, intptr_t prop): + """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 ``CUlogicalEndpointProp.type``. + If the type is ``CU_LOGICAL_ENDPOINT_TYPE_UNICAST`` then + ``CUlogicalEndpointProp.unicast.device`` specifies the owner device of the + unicast logical endpoint. If the type is + ``CU_LOGICAL_ENDPOINT_TYPE_MULTICAST`` then + ``CUlogicalEndpointProp.multicast.numDevices`` specifies the number of + devices in the multicast logical endpoint team. + + Devices can be added to a multicast logical endpoint via + ``cuLogicalEndpointAddDevice``. After all the participating devices have + been added, a call to ``cuLogicalEndpointQuery`` 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 + ``cuLogicalEndpointAddDevice``. However, a call to + ``cuLogicalEndpointQuery`` 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 + ``cuLogicalEndpointBindAddr`` or ``cuLogicalEndpointBindMem``, and can be + unbound via ``cuLogicalEndpointUnbind``. The total amount of memory that + can be bound per device is specified by ``CUlogicalEndpointProp.size``. + This size must be a multiple of the value for ``bindAlignment`` as returned + by ``cuLogicalEndpointGetLimits``. The maximum size for the logical + endpoint cannot exceed the value for ``maxSize`` as returned by + ``cuLogicalEndpointGetLimits``. The bind alignment and maximum size depend + on the properties of the logical endpoint. + + Args: + le_id (uint32_t): Logical endpoint id that will be associated + with the newly created logical endpoint. + prop (intptr_t): Properties of the logical endpoint to create. + + .. seealso:: `cuLogicalEndpointCreate` + """ + with nogil: + __status__ = cuLogicalEndpointCreate(le_id, prop) + check_status(__status__) + + +cpdef logical_endpoint_add_device(uint32_t le_id, int dev): + """Associates a device to a multicast logical endpoint. + + Associates a device to a logical endpoint. The type of the logical endpoint + must be ``CU_LOGICAL_ENDPOINT_TYPE_MULTICAST``. The added device will be a + part of the multicast team of size specified by + ``CUlogicalEndpointProp.multicast.numDevices`` during + ``cuLogicalEndpointCreate``. 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 + ``cuLogicalEndpointQuery``. + + Args: + le_id (uint32_t): Logical endpoint id representing a multicast + logical endpoint. + dev (int): Device that will be associated with the multicast + logical endpoint. + + .. seealso:: `cuLogicalEndpointAddDevice` + """ + with nogil: + __status__ = cuLogicalEndpointAddDevice(le_id, dev) + check_status(__status__) + + +cpdef logical_endpoint_destroy(uint32_t le_id): + """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. + + Args: + le_id (uint32_t): Logical endpoint id of the logical endpoint + to be destroyed. + + .. seealso:: `cuLogicalEndpointDestroy` + """ + with nogil: + __status__ = cuLogicalEndpointDestroy(le_id) + check_status(__status__) + + +cpdef logical_endpoint_bind_addr(uint32_t le_id, int dev, uint64_t offset, intptr_t ptr, uint64_t size, unsigned long long flags): + """Bind 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 ``le_id`` at the offset ``offset``. The + memory must have been allocated via ``cuMemCreate`` 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 ``cuLogicalEndpointGetLimits``. + + 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 ``CU_MEM_LOCATION_TYPE_DEVICE``, the memory + allocation must have been created on the device specified by ``dev``. For + host NUMA memory, i.e., type ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, the memory + allocation must have been created on the CPU NUMA node closest to ``dev``. + That is, the value returned when querying + ``CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID`` 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 ``cuLogicalEndpointAddDevice``. + + For unicast endpoints the device named by ``dev`` must be the owner device + specified during ``cuLogicalEndpointCreate`` via + ``CUlogicalEndpointProp.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 ``CUDA_ERROR_INVALID_VALUE`` if + ``cuLogicalEndpointQuery`` has not been called for the logical endpoint to + ensure that the endpoint is ready for memory binding. + + Note that this call will return ``CUDA_ERROR_OUT_OF_MEMORY`` if there are + insufficient resources required to perform the bind. This call may also + return ``CUDA_ERROR_SYSTEM_NOT_READY`` if the necessary system software is + not initialized or running. This call may return + ``CUDA_ERROR_ILLEGAL_STATE`` 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. + + Args: + le_id (uint32_t): Logical endpoint to which memory will be + associated. + dev (int): Device on which the memory will be bound to the + logical endpoint. + offset (uint64_t): Offset into the logical endpoint space. + ptr (intptr_t): Virtual address of the memory allocation. + size (uint64_t): Size of memory that will be bound to the + logical endpoint. + flags (unsigned long long): Flags for future use, must be zero + for now. + + .. seealso:: `cuLogicalEndpointBindAddr` + """ + with nogil: + __status__ = cuLogicalEndpointBindAddr(le_id, dev, offset, ptr, size, flags) + check_status(__status__) + + +cpdef logical_endpoint_bind_mem(uint32_t le_id, int dev, uint64_t offset, unsigned long long mem_handle, uint64_t mem_offset, uint64_t size, unsigned long long flags): + """Binds memory object represented by a handle to the logical endpoint. + + Binds the memory allocation specified by ``mem_handle`` to a logical + endpoint represented by ``le_id`` at the offset ``offset``. The memory must + have been allocated via ``cuMemCreate``. The intended ``size`` of the bind, + the offset in the logical endpoint range ``offset`` and the offset in the + memory handle ``mem_offset`` must be multiples of the value for + ``bindAlignment`` as returned by ``cuLogicalEndpointGetLimits``. + + The ``size`` + ``mem_offset`` 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 ``CU_MEM_LOCATION_TYPE_DEVICE``, the memory + allocation must have been created on the device specified by ``dev``. For + host NUMA memory, i.e., type ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, the memory + allocation must have been created on the CPU NUMA node closest to ``dev``. + That is, the value returned when querying + ``CU_DEVICE_ATTRIBUTE_HOST_NUMA_ID`` 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 ``cuLogicalEndpointAddDevice``. + + For unicast endpoints the device named by ``dev`` must be the owner device + specified during ``cuLogicalEndpointCreate`` via + ``CUlogicalEndpointProp.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 ``CUDA_ERROR_INVALID_VALUE`` if + ``cuLogicalEndpointQuery`` has not been called for the logical endpoint to + ensure that the endpoint is ready for memory binding. + + Note that this call will return ``CUDA_ERROR_OUT_OF_MEMORY`` if there are + insufficient resources required to perform the bind. This call may also + return ``CUDA_ERROR_SYSTEM_NOT_READY`` if the necessary system software is + not initialized or running. This call may return + ``CUDA_ERROR_ILLEGAL_STATE`` 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. + + Args: + le_id (uint32_t): Logical endpoint to which memory will be + associated. + dev (int): Device on which the memory will be bound to the + logical endpoint. + offset (uint64_t): Offset into the logical endpoint space. + mem_handle (unsigned long long): Handle representing a memory + allocation. + mem_offset (uint64_t): Offset into the memory for the + attachment. + size (uint64_t): Size of memory that will be bound to the + logical endpoint. + flags (unsigned long long): Flags for future use, must be zero + for now. + + .. seealso:: `cuLogicalEndpointBindMem` + """ + with nogil: + __status__ = cuLogicalEndpointBindMem(le_id, dev, offset, mem_handle, mem_offset, size, flags) + check_status(__status__) + + +cpdef logical_endpoint_unbind(uint32_t le_id, int dev, uint64_t offset, uint64_t size): + """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 + ``cuLogicalEndpointGetLimits``. + + Args: + le_id (uint32_t): Logical endpoint id representing a logical + endpoint. + dev (int): Device on which the memory is bound to the logical + endpoint. + offset (uint64_t): Offset into the logical endpoint. + size (uint64_t): Desired size to unbind. + + .. 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. + + .. seealso:: `cuLogicalEndpointUnbind` + """ + with nogil: + __status__ = cuLogicalEndpointUnbind(le_id, dev, offset, size) + check_status(__status__) + + +cpdef logical_endpoint_export(intptr_t handle, uint32_t le_id, int handle_type): + """Exports a logical endpoint associated with le_id to an IPC handle. + + Given a logical endpoint id ``le_id``, 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 ``cuLogicalEndpointImport``. The implementation of what + this ``handle`` is and how it can be transfered is defined by the requested + handle type in ``handletype``. + + Args: + handle (intptr_t): Pointer to the location in which to store + the requested handle type. + le_id (uint32_t): Logical endpoint id of logical endpoint. + handle_type (LogicalEndpointIpcHandleType): Type of shareable + handle requested. Defines type and size of the handle + output parameter. + + .. seealso:: `cuLogicalEndpointExport` + """ + with nogil: + __status__ = cuLogicalEndpointExport(handle, le_id, handle_type) + check_status(__status__) + + +cpdef logical_endpoint_import(uint32_t le_id, handle, int handle_type): + """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 ``le_id``. + + If the current process cannot support the logical endpoint described by the + shareable handle, this API will error as ``CUDA_ERROR_NOT_SUPPORTED``. If + ``handle`` is of type ``CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_FABRIC`` and + the importer process does not have access permissions, then + ``CUDA_ERROR_NOT_PERMITTED`` will be returned. + + Args: + le_id (uint32_t): Logical endpoint id that will be used to + access the exported logical endpoint. + handle (bytes): Shareable handle representing the logical + endpoint that is to be imported. + handle_type (LogicalEndpointIpcHandleType): Handle type of the + exported handle. + + .. seealso:: `cuLogicalEndpointImport` + """ + cdef void* _handle_ = _cyb_get_buffer_pointer(handle, -1, readonly=True) + with nogil: + __status__ = cuLogicalEndpointImport(le_id, _handle_, handle_type) + check_status(__status__) + + +cpdef tuple logical_endpoint_get_limits(intptr_t prop): + """Calculates the minimum alignment and the maximum size for the given logical endpoint properties. + + The ``bind_alignment`` can be used as a multiple for size and bind offset + values. The ``max_size`` is the maximum size of the logical endpoint. If + ``max_size`` is less than ``CUlogicalEndpointProp``:size the user must + adjust the request to the smaller value. + + Args: + prop (intptr_t): Properties of the logical endpoint. + + Returns: + A 2-tuple containing: + + - uint64_t: Minimum alignment granularity of the proposed + logical endpoint. + - uint64_t: Maximum size of the logical endpoint. + + .. seealso:: `cuLogicalEndpointGetLimits` + """ + cdef cuuint64_t bind_alignment + cdef cuuint64_t max_size + with nogil: + __status__ = cuLogicalEndpointGetLimits(&bind_alignment, &max_size, prop) + check_status(__status__) + return (bind_alignment, max_size) + + +cpdef logical_endpoint_query(uint32_t le_id, uint64_t count, intptr_t query_status): + """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 ``le_id`` 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 ``query_status`` + of 0 if any logical endpoint ID in the given range is not fully + constructed, and a non-zero value otherwise. + + Args: + le_id (uint32_t): First logical endpoint ID to be queried. + count (uint64_t): Number of logical endpoints IDs to be + queried. + query_status (intptr_t): Status of the logical endpoints. + Returns 0 if any logical endpoint in the given range is + not fully constructed, and non-zero if all logical + endpoints in the given range are fully constructed. + + .. seealso:: `cuLogicalEndpointQuery` + """ + with nogil: + __status__ = cuLogicalEndpointQuery(le_id, count, query_status) + check_status(__status__) + + +cpdef stream_begin_recapture_to_graph(intptr_t h_stream, int mode, intptr_t h_graph, intptr_t callback_func, intptr_t user_data): + """Begin graph capture on a stream to an existing graph. + + Begin graph capture on ``h_stream`` to the existing ``h_graph``. 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 ``callback_func``. The recapture will fail + immediately if the callback returns anything other than CUDA_SUCCESS. + + If the recapture fails for any reason, the ``graph`` will be in an + undefined state and should be destroyed. + + See cuStreamBeginCapture for additional detail on beginning the capture. + + Args: + h_stream (intptr_t): Stream in which to initiate capture. + mode (StreamCaptureMode): Controls the interaction of this + capture sequence with other API calls that are potentially + unsafe. For more details see + ``cuThreadExchangeStreamCaptureMode``. + h_graph (intptr_t): Existing CUDA graph to be captured into. + callback_func (intptr_t): Function that will be called for all + parameter mismatches from the original graph. + user_data (intptr_t): A generic pointer to user data that is + passed into the callback function. + + .. note:: + Any user objects associated with ``graph`` will be released prior to + the recapture. + + .. seealso:: `cuStreamBeginRecaptureToGraph` + """ + with nogil: + __status__ = cuStreamBeginRecaptureToGraph(h_stream, mode, h_graph, callback_func, user_data) + check_status(__status__) + +# Alias +graph_instantiate = graph_instantiate_with_flags +del _cyb_FastEnum diff --git a/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx b/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx index ffa3973e950..3da64834a01 100644 --- a/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx +++ b/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx @@ -3,14 +3,13 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.0 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=a36c7e54cf29166832dd9aebc1fa71cc3649498794a2846e707396419caebe10 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=f9b340180d3296dbf8b6145df99c5475fb6fabd158d985d1c5f6e080a1852886 # <<<< PREAMBLE CONTENT >>>> cimport cpython as _cyb_cpython cimport cpython.buffer as _cyb_cpython_buffer -from cython cimport view as _cyb_view from libc.stdint cimport intptr_t from libc.stdlib cimport ( calloc as _cyb_calloc, @@ -630,7 +629,7 @@ cpdef str get_error_string(int result): cdef const char *_output_cstr_ cdef bytes _output_ with nogil: - _output_cstr_ = nvrtcGetErrorString(<_Result>result) + _output_cstr_ = nvrtcGetErrorString(result) _output_ = _output_cstr_ return _output_.decode() @@ -657,6 +656,8 @@ cpdef tuple version(): cpdef int get_num_supported_archs() except? -1: """nvrtcGetNumSupportedArchs sets the output parameter ``num_archs`` with the number of architectures supported by NVRTC. This can then be used to pass an array to ``nvrtcGetSupportedArchs`` to get the supported architectures. + see ``nvrtcGetSupportedArchs``. + Returns: int: number of supported architectures. @@ -672,6 +673,8 @@ cpdef int get_num_supported_archs() except? -1: cpdef object get_supported_archs(): """nvrtcGetSupportedArchs populates the array passed via the output parameter ``supported_archs`` with the architectures supported by NVRTC. The array is sorted in the ascending order. The size of the array to be passed can be determined using ``nvrtcGetNumSupportedArchs``. + see ``nvrtcGetNumSupportedArchs``. + Returns: int: sorted array of supported architectures. @@ -681,13 +684,14 @@ cpdef object get_supported_archs(): with nogil: __status__ = nvrtcGetNumSupportedArchs(&numArchs) check_status(__status__) - if numArchs == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(int), format="i", mode="c")[:0] - cdef _cyb_view.array supported_archs = _cyb_view.array(shape=(numArchs,), itemsize=sizeof(int), format="i", mode="c") - cdef int *supported_archs_ptr = (supported_archs.data) - with nogil: - __status__ = nvrtcGetSupportedArchs(supported_archs_ptr) - check_status(__status__) + cdef object _supported_archs_alloc_ = _numpy.empty(max(numArchs, 1), dtype=_numpy.int32) + cdef intptr_t _supported_archs_data_ = _supported_archs_alloc_.ctypes.data + cdef int *supported_archs_ptr = _supported_archs_data_ + cdef object supported_archs = _supported_archs_alloc_[:numArchs] + if numArchs != 0: + with nogil: + __status__ = nvrtcGetSupportedArchs(supported_archs_ptr) + check_status(__status__) return supported_archs @@ -699,9 +703,9 @@ cpdef destroy_program(intptr_t prog): .. seealso:: `nvrtcDestroyProgram` """ - cdef Program _prog_ = prog + cdef nvrtcProgram _prog_ = prog with nogil: - __status__ = nvrtcDestroyProgram(&_prog_) + __status__ = nvrtcDestroyProgram(prog) check_status(__status__) @@ -719,7 +723,7 @@ cpdef size_t get_ptx_size(intptr_t prog) except? 0: """ cdef size_t ptx_size_ret with nogil: - __status__ = nvrtcGetPTXSize(prog, &ptx_size_ret) + __status__ = nvrtcGetPTXSize(prog, &ptx_size_ret) check_status(__status__) return ptx_size_ret @@ -737,15 +741,14 @@ cpdef bytes get_ptx(intptr_t prog): """ cdef size_t ptxSizeRet with nogil: - __status__ = nvrtcGetPTXSize(prog, &ptxSizeRet) + __status__ = nvrtcGetPTXSize(prog, &ptxSizeRet) check_status(__status__) - if ptxSizeRet == 0: - return b"" cdef bytes _ptx_ = bytes(ptxSizeRet) cdef char* ptx = _ptx_ - with nogil: - __status__ = nvrtcGetPTX(prog, ptx) - check_status(__status__) + if ptxSizeRet != 0: + with nogil: + __status__ = nvrtcGetPTX(prog, ptx) + check_status(__status__) return _ptx_ @@ -762,7 +765,7 @@ cpdef size_t get_cubin_size(intptr_t prog) except? 0: """ cdef size_t cubin_size_ret with nogil: - __status__ = nvrtcGetCUBINSize(prog, &cubin_size_ret) + __status__ = nvrtcGetCUBINSize(prog, &cubin_size_ret) check_status(__status__) return cubin_size_ret @@ -780,15 +783,14 @@ cpdef bytes get_cubin(intptr_t prog): """ cdef size_t cubinSizeRet with nogil: - __status__ = nvrtcGetCUBINSize(prog, &cubinSizeRet) + __status__ = nvrtcGetCUBINSize(prog, &cubinSizeRet) check_status(__status__) - if cubinSizeRet == 0: - return b"" cdef bytes _cubin_ = bytes(cubinSizeRet) cdef char* cubin = _cubin_ - with nogil: - __status__ = nvrtcGetCUBIN(prog, cubin) - check_status(__status__) + if cubinSizeRet != 0: + with nogil: + __status__ = nvrtcGetCUBIN(prog, cubin) + check_status(__status__) return _cubin_ @@ -805,7 +807,7 @@ cpdef size_t get_ltoir_size(intptr_t prog) except? 0: """ cdef size_t ltoir_size_ret with nogil: - __status__ = nvrtcGetLTOIRSize(prog, <oir_size_ret) + __status__ = nvrtcGetLTOIRSize(prog, <oir_size_ret) check_status(__status__) return ltoir_size_ret @@ -823,15 +825,14 @@ cpdef bytes get_ltoir(intptr_t prog): """ cdef size_t LTOIRSizeRet with nogil: - __status__ = nvrtcGetLTOIRSize(prog, <OIRSizeRet) + __status__ = nvrtcGetLTOIRSize(prog, <OIRSizeRet) check_status(__status__) - if LTOIRSizeRet == 0: - return b"" cdef bytes _ltoir_ = bytes(LTOIRSizeRet) cdef char* ltoir = _ltoir_ - with nogil: - __status__ = nvrtcGetLTOIR(prog, ltoir) - check_status(__status__) + if LTOIRSizeRet != 0: + with nogil: + __status__ = nvrtcGetLTOIR(prog, ltoir) + check_status(__status__) return _ltoir_ @@ -848,7 +849,7 @@ cpdef size_t get_optix_ir_size(intptr_t prog) except? 0: """ cdef size_t optixir_size_ret with nogil: - __status__ = nvrtcGetOptiXIRSize(prog, &optixir_size_ret) + __status__ = nvrtcGetOptiXIRSize(prog, &optixir_size_ret) check_status(__status__) return optixir_size_ret @@ -866,21 +867,23 @@ cpdef bytes get_optix_ir(intptr_t prog): """ cdef size_t optixirSizeRet with nogil: - __status__ = nvrtcGetOptiXIRSize(prog, &optixirSizeRet) + __status__ = nvrtcGetOptiXIRSize(prog, &optixirSizeRet) check_status(__status__) - if optixirSizeRet == 0: - return b"" cdef bytes _optixir_ = bytes(optixirSizeRet) cdef char* optixir = _optixir_ - with nogil: - __status__ = nvrtcGetOptiXIR(prog, optixir) - check_status(__status__) + if optixirSizeRet != 0: + with nogil: + __status__ = nvrtcGetOptiXIR(prog, optixir) + check_status(__status__) return _optixir_ cpdef size_t get_program_log_size(intptr_t prog) except? 0: """nvrtcGetProgramLogSize sets ``log_size_ret`` with the size of the log generated by the previous compilation of ``prog`` (including the trailing ``NULL``). + Note that compilation log may be generated with warnings and informative + messages, even when the compilation of ``prog`` succeeds. + Args: prog (intptr_t): CUDA Runtime Compilation program. @@ -892,7 +895,7 @@ cpdef size_t get_program_log_size(intptr_t prog) except? 0: """ cdef size_t log_size_ret with nogil: - __status__ = nvrtcGetProgramLogSize(prog, &log_size_ret) + __status__ = nvrtcGetProgramLogSize(prog, &log_size_ret) check_status(__status__) return log_size_ret @@ -910,21 +913,23 @@ cpdef bytes get_program_log(intptr_t prog): """ cdef size_t logSizeRet with nogil: - __status__ = nvrtcGetProgramLogSize(prog, &logSizeRet) + __status__ = nvrtcGetProgramLogSize(prog, &logSizeRet) check_status(__status__) - if logSizeRet == 0: - return b"" cdef bytes _log_ = bytes(logSizeRet) cdef char* log = _log_ - with nogil: - __status__ = nvrtcGetProgramLog(prog, log) - check_status(__status__) + if logSizeRet != 0: + with nogil: + __status__ = nvrtcGetProgramLog(prog, log) + check_status(__status__) return _log_ cpdef add_name_expression(intptr_t prog, name_expression): """nvrtcAddNameExpression notes the given name expression denoting the address of a global function or device/__constant__ variable. + The identical name expression string must be provided on a subsequent call + to nvrtcGetLoweredName to extract the lowered name. + Args: prog (intptr_t): CUDA Runtime Compilation program. name_expression (str): constant expression denoting the @@ -938,7 +943,7 @@ cpdef add_name_expression(intptr_t prog, name_expression): cdef bytes _temp_name_expression_ = (name_expression).encode() cdef char* _name_expression_ = _temp_name_expression_ with nogil: - __status__ = nvrtcAddNameExpression(prog, _name_expression_) + __status__ = nvrtcAddNameExpression(prog, _name_expression_) check_status(__status__) @@ -961,6 +966,10 @@ cpdef size_t get_pch_heap_size() except? 0: cpdef set_pch_heap_size(size_t size): """set the size of the PCH Heap. + The requested size may be rounded up to a platform dependent alignment + (e.g. page size). If the PCH Heap has already been allocated, the heap + memory will be freed and a new PCH Heap will be allocated. + Args: size (size_t): requested size of the PCH Heap, in bytes. @@ -974,6 +983,20 @@ cpdef set_pch_heap_size(size_t size): cpdef int get_pch_create_status(intptr_t prog) except? -1: """returns the PCH creation status. + NVRTC_SUCCESS indicates that the PCH was successfully created. + NVRTC_ERROR_NO_PCH_CREATE_ATTEMPTED indicates that no PCH creation was + attempted, either because PCH functionality was not requested during the + preceding nvrtcCompileProgram call, or automatic PCH processing was + requested, and compiler chose not to create a PCH file. + NVRTC_ERROR_PCH_CREATE_HEAP_EXHAUSTED indicates that a PCH file could + potentially have been created, but the compiler ran out space in the PCH + heap. In this scenario, the :func:`get_pch_heap_size_required` can be used + to query the required heap size, the heap can be reallocated for this size + with :func:`set_pch_heap_size` and PCH creation may be reattempted again + invoking :func:`compile_program` with a new NVRTC program instance. + NVRTC_ERROR_PCH_CREATE indicates that an error condition prevented the PCH + file from being created. + Args: prog (intptr_t): CUDA Runtime Compilation program. @@ -981,7 +1004,7 @@ cpdef int get_pch_create_status(intptr_t prog) except? -1: """ cdef int ret with nogil: - ret = nvrtcGetPCHCreateStatus(prog) + ret = nvrtcGetPCHCreateStatus(prog) return ret @@ -999,7 +1022,7 @@ cpdef size_t get_pch_heap_size_required(intptr_t prog) except? 0: """ cdef size_t size with nogil: - __status__ = nvrtcGetPCHHeapSizeRequired(prog, &size) + __status__ = nvrtcGetPCHHeapSizeRequired(prog, &size) check_status(__status__) return size @@ -1017,7 +1040,7 @@ cpdef size_t get_tile_ir_size(intptr_t prog) except? 0: """ cdef size_t tile_ir_size_ret with nogil: - __status__ = nvrtcGetTileIRSize(prog, &tile_ir_size_ret) + __status__ = nvrtcGetTileIRSize(prog, &tile_ir_size_ret) check_status(__status__) return tile_ir_size_ret @@ -1035,15 +1058,14 @@ cpdef bytes get_tile_ir(intptr_t prog): """ cdef size_t TileIRSizeRet with nogil: - __status__ = nvrtcGetTileIRSize(prog, &TileIRSizeRet) + __status__ = nvrtcGetTileIRSize(prog, &TileIRSizeRet) check_status(__status__) - if TileIRSizeRet == 0: - return b"" cdef bytes _tile_ir_ = bytes(TileIRSizeRet) cdef char* tile_ir = _tile_ir_ - with nogil: - __status__ = nvrtcGetTileIR(prog, tile_ir) - check_status(__status__) + if TileIRSizeRet != 0: + with nogil: + __status__ = nvrtcGetTileIR(prog, tile_ir) + check_status(__status__) return _tile_ir_ diff --git a/cuda_bindings/cuda/bindings/cudla.pxd b/cuda_bindings/cuda/bindings/cudla.pxd index bb11235cbb6..e33867b912f 100644 --- a/cuda_bindings/cuda/bindings/cudla.pxd +++ b/cuda_bindings/cuda/bindings/cudla.pxd @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # This code was automatically generated across versions from 1.5.0 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=b82680ec867e23638b173760105c35030e0cba5c9a8b3bb536ce5bb3381ec1fb +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=3b52467aafbb78d33c99d8be6d3acdd552c8aa0851758d01932080aebaec5213 # <<<< PREAMBLE CONTENT >>>> @@ -55,7 +55,7 @@ cpdef intptr_t create_device(uint64_t device, uint32_t flags) except * cpdef intptr_t mem_register(intptr_t dev_handle, intptr_t ptr, size_t size, uint32_t flags) except * cpdef intptr_t module_load_from_memory(intptr_t dev_handle, p_module, size_t module_size, uint32_t flags) except * cpdef module_unload(intptr_t h_module, uint32_t flags) -cpdef submit_task(intptr_t dev_handle, intptr_t ptr_to_tasks, uint32_t num_tasks, intptr_t stream, uint32_t flags) +cpdef submit_task(intptr_t dev_handle, ptr_to_tasks, uint32_t num_tasks, intptr_t stream, uint32_t flags) cpdef object device_get_attribute(intptr_t dev_handle, int attrib) cpdef mem_unregister(intptr_t dev_handle, intptr_t dev_ptr) cpdef int get_last_error(intptr_t dev_handle) except? 0 diff --git a/cuda_bindings/cuda/bindings/cudla.pyx b/cuda_bindings/cuda/bindings/cudla.pyx index 75b1f05f2ca..342693aa305 100644 --- a/cuda_bindings/cuda/bindings/cudla.pyx +++ b/cuda_bindings/cuda/bindings/cudla.pyx @@ -2,14 +2,14 @@ # SPDX-License-Identifier: Apache-2.0 # This code was automatically generated across versions from 1.5.0 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=3c177b7a0328c0f6f16067c8c9f4e5a002bd019e8c17c017ba9f77af21da8d75 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=df4b59eb430f91fb901b5696e5518c656054618e8ac208a2b803b8ecf6db4235 # <<<< PREAMBLE CONTENT >>>> cimport cpython as _cyb_cpython cimport cpython.buffer as _cyb_cpython_buffer -from cython cimport view as _cyb_view +from cpython.memoryview cimport PyMemoryView_FromMemory as _cyb_PyMemoryView_FromMemory from libc.stdint cimport ( intptr_t, uint32_t, @@ -75,7 +75,9 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep flags |= _cyb_cpython.PyBUF_WRITABLE cdef int status = -1 cdef _cyb_cpython.Py_buffer view - if isinstance(buf, int): + if buf is None: + ptr = 0 + elif isinstance(buf, int): ptr = buf else: try: @@ -86,7 +88,7 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep except Exception as e: adj = "writable " if not readonly else "" raise ValueError( - "buf must be either a Python int representing the pointer " + "buf must be None, a Python int representing the pointer " f"address to a valid buffer, or a 1D contiguous {adj}" f"buffer, of size {size}" ) from e @@ -604,9 +606,12 @@ cdef class ModuleTensorDescriptor: @property def stride(self): """~_numpy.uint32: (array of length 8).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(8,), itemsize=sizeof(uint32_t), format="I", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].stride)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].stride)), + (sizeof(uint32_t) * (8)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @stride.setter def stride(self, val): @@ -614,9 +619,8 @@ cdef class ModuleTensorDescriptor: raise ValueError("This ModuleTensorDescriptor instance is read-only") if len(val) != 8: raise ValueError(f"Expected length { 8 } for field stride, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(8,), itemsize=sizeof(uint32_t), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - _cyb_memcpy((&(self._ptr[0].stride)), (arr.data), sizeof(uint32_t) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + _cyb_memcpy((&(self._ptr[0].stride)), (_val_.ctypes.data), sizeof(uint32_t) * (8)) @staticmethod def from_buffer(buffer): @@ -1344,10 +1348,13 @@ cdef class SignalEvents: def dev_ptrs(self): """int: """ if self._ptr[0].devPtrs == NULL or self._ptr[0].numEvents == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(intptr_t), format="q", mode="c")[:0] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].numEvents,), itemsize=sizeof(intptr_t), format="q", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].devPtrs) - return arr + return _numpy.empty(0, dtype=_numpy.intp) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].devPtrs), + (self._ptr[0].numEvents * sizeof(intptr_t)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.intp) @dev_ptrs.setter def dev_ptrs(self, val): @@ -1357,13 +1364,9 @@ cdef class SignalEvents: self._ptr[0].numEvents = _n if _n == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(_n,), itemsize=sizeof(intptr_t), format="q", mode="c") - cdef intptr_t[:] mv = arr - cdef Py_ssize_t i - for i in range(_n): - mv[i] = val[i] - self._ptr[0].devPtrs = (arr.data) - self._refs["dev_ptrs"] = arr + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.intp)) + self._ptr[0].devPtrs = _arr_.ctypes.data + self._refs["dev_ptrs"] = _arr_ @property def eof_fences(self): @@ -1530,10 +1533,13 @@ cdef class Task: def output_tensor(self): """int: """ if self._ptr[0].outputTensor == NULL or self._ptr[0].numOutputTensors == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(intptr_t), format="q", mode="c")[:0] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].numOutputTensors,), itemsize=sizeof(intptr_t), format="q", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].outputTensor) - return arr + return _numpy.empty(0, dtype=_numpy.intp) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].outputTensor), + (self._ptr[0].numOutputTensors * sizeof(intptr_t)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.intp) @output_tensor.setter def output_tensor(self, val): @@ -1543,22 +1549,21 @@ cdef class Task: self._ptr[0].numOutputTensors = _n if _n == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(_n,), itemsize=sizeof(intptr_t), format="q", mode="c") - cdef intptr_t[:] mv = arr - cdef Py_ssize_t i - for i in range(_n): - mv[i] = val[i] - self._ptr[0].outputTensor = (arr.data) - self._refs["output_tensor"] = arr + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.intp)) + self._ptr[0].outputTensor = _arr_.ctypes.data + self._refs["output_tensor"] = _arr_ @property def input_tensor(self): """int: """ if self._ptr[0].inputTensor == NULL or self._ptr[0].numInputTensors == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(intptr_t), format="q", mode="c")[:0] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].numInputTensors,), itemsize=sizeof(intptr_t), format="q", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].inputTensor) - return arr + return _numpy.empty(0, dtype=_numpy.intp) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].inputTensor), + (self._ptr[0].numInputTensors * sizeof(intptr_t)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.intp) @input_tensor.setter def input_tensor(self, val): @@ -1568,13 +1573,9 @@ cdef class Task: self._ptr[0].numInputTensors = _n if _n == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(_n,), itemsize=sizeof(intptr_t), format="q", mode="c") - cdef intptr_t[:] mv = arr - cdef Py_ssize_t i - for i in range(_n): - mv[i] = val[i] - self._ptr[0].inputTensor = (arr.data) - self._refs["input_tensor"] = arr + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.intp)) + self._ptr[0].inputTensor = _arr_.ctypes.data + self._refs["input_tensor"] = _arr_ @property def wait_events(self): @@ -1804,9 +1805,10 @@ cpdef module_unload(intptr_t h_module, uint32_t flags): check_status(__status__) -cpdef submit_task(intptr_t dev_handle, intptr_t ptr_to_tasks, uint32_t num_tasks, intptr_t stream, uint32_t flags): +cpdef submit_task(intptr_t dev_handle, ptr_to_tasks, uint32_t num_tasks, intptr_t stream, uint32_t flags): + cdef intptr_t _ptr_to_tasks_ptr_ = int(ptr_to_tasks) with nogil: - __status__ = cudlaSubmitTask(dev_handle, ptr_to_tasks, num_tasks, stream, flags) + __status__ = cudlaSubmitTask(dev_handle, _ptr_to_tasks_ptr_, num_tasks, stream, flags) check_status(__status__) diff --git a/cuda_bindings/cuda/bindings/cufile.pxd b/cuda_bindings/cuda/bindings/cufile.pxd index 74633880658..2d212e02ca0 100644 --- a/cuda_bindings/cuda/bindings/cufile.pxd +++ b/cuda_bindings/cuda/bindings/cufile.pxd @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=b10e4f1751ee5423db23c6fc953cb0ae37bff7e8937bf1d39ac5fd6eeb0e4e87 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=232c1336341a3bd41bdcac568f24b320c839206e07a249bb4425ab726c1838be @@ -53,7 +53,7 @@ ctypedef CUfileP2PFlags_t _P2PFlags # Functions ############################################################################### -cpdef intptr_t handle_register(intptr_t descr) except? 0 +cpdef intptr_t handle_register(descr) except? 0 cpdef void handle_deregister(intptr_t fh) except* cpdef buf_register(intptr_t buf_ptr_base, size_t length, int flags) cpdef buf_deregister(intptr_t buf_ptr_base) @@ -65,8 +65,8 @@ cpdef driver_set_max_direct_io_size(size_t max_direct_io_size) cpdef driver_set_max_cache_size(size_t max_cache_size) cpdef driver_set_max_pinned_mem_size(size_t max_pinned_size) cpdef intptr_t batch_io_set_up(unsigned nr) except? 0 -cpdef batch_io_submit(intptr_t batch_idp, unsigned nr, intptr_t iocbp, unsigned int flags) -cpdef batch_io_get_status(intptr_t batch_idp, unsigned min_nr, intptr_t nr, intptr_t iocbp, intptr_t timeout) +cpdef batch_io_submit(intptr_t batch_idp, unsigned nr, iocbp, unsigned int flags) +cpdef batch_io_get_status(intptr_t batch_idp, unsigned min_nr, intptr_t nr, iocbp, intptr_t timeout) cpdef batch_io_cancel(intptr_t batch_idp) cpdef void batch_io_destroy(intptr_t batch_idp) except* cpdef read_async(intptr_t fh, intptr_t buf_ptr_base, intptr_t size_p, intptr_t file_offset_p, intptr_t buf_ptr_offset_p, intptr_t bytes_read_p, intptr_t stream) @@ -86,9 +86,9 @@ cpdef int get_stats_level() except? 0 cpdef stats_start() cpdef stats_stop() cpdef stats_reset() -cpdef get_stats_l1(intptr_t stats) -cpdef get_stats_l2(intptr_t stats) -cpdef get_stats_l3(intptr_t stats) +cpdef get_stats_l1(stats) +cpdef get_stats_l2(stats) +cpdef get_stats_l3(stats) cpdef size_t get_bar_size_in_kb(int gpu_index) except? 0 cpdef set_parameter_posix_pool_slab_array(intptr_t size_values, intptr_t count_values, int len) cpdef get_parameter_posix_pool_slab_array(intptr_t size_values, intptr_t count_values, int len) diff --git a/cuda_bindings/cuda/bindings/cufile.pyx b/cuda_bindings/cuda/bindings/cufile.pyx index e8127feb6c3..7d9679173c6 100644 --- a/cuda_bindings/cuda/bindings/cufile.pyx +++ b/cuda_bindings/cuda/bindings/cufile.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=df46a6921d93f83249134c7705b2809f57145b6fb72f6f40c4657ecd1b443b81 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=332e17ca38b2effd5cf0b6790bde71801592da31498d7f27030b826ea0d5fba7 # <<<< PREAMBLE CONTENT >>>> @@ -11,7 +11,7 @@ cimport cpython as _cyb_cpython cimport cpython.buffer as _cyb_cpython_buffer cimport cpython.memoryview as _cyb_cpython_memoryview -from cython cimport view as _cyb_view +from cpython.memoryview cimport PyMemoryView_FromMemory as _cyb_PyMemoryView_FromMemory from libc.stdint cimport ( intptr_t, uint64_t, @@ -94,7 +94,7 @@ cdef _get__py_anon_pod1_dtype_offsets(): (&(pod.fd)) - (&pod), (&(pod.handle)) - (&pod), ], - 'itemsize': sizeof((NULL).handle), + 'itemsize': sizeof(cuda_bindings_cufile__anon_pod1), }) _py_anon_pod1_dtype = _get__py_anon_pod1_dtype_offsets() @@ -112,7 +112,7 @@ cdef class _py_anon_pod1: bint _readonly def __init__(self): - self._ptr = _cyb_calloc(1, sizeof((NULL).handle)) + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_cufile__anon_pod1)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod1") self._owner = None @@ -145,20 +145,20 @@ cdef class _py_anon_pod1: if not isinstance(other, _py_anon_pod1): return False other_ = other - return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof((NULL).handle)) == 0) + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_cufile__anon_pod1)) == 0) def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): - _cyb___getbuffer(self, buffer, self._ptr, sizeof((NULL).handle), self._readonly) + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_cufile__anon_pod1), self._readonly) def __releasebuffer__(self, Py_buffer *buffer): pass def __setitem__(self, key, val): if key == 0 and isinstance(val, _numpy.ndarray): - self._ptr = _cyb_malloc(sizeof((NULL).handle)) + self._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod1)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod1") - _cyb_memcpy(self._ptr, val.ctypes.data, sizeof((NULL).handle)) + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_cufile__anon_pod1)) self._owner = None self._owned = True self._readonly = not val.flags.writeable @@ -190,7 +190,7 @@ cdef class _py_anon_pod1: @staticmethod def from_buffer(buffer): """Create an _py_anon_pod1 instance with the memory from the given buffer.""" - return _cyb_from_buffer(buffer, sizeof((NULL).handle), _py_anon_pod1) + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_cufile__anon_pod1), _py_anon_pod1) @staticmethod def from_data(data): @@ -214,10 +214,10 @@ cdef class _py_anon_pod1: raise ValueError("ptr must not be null (0)") cdef _py_anon_pod1 obj = _py_anon_pod1.__new__(_py_anon_pod1) if owner is None: - obj._ptr = _cyb_malloc(sizeof((NULL).handle)) + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod1)) if obj._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod1") - _cyb_memcpy((obj._ptr), ptr, sizeof((NULL).handle)) + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_cufile__anon_pod1)) obj._owner = None obj._owned = True else: @@ -239,7 +239,7 @@ cdef _get__py_anon_pod3_dtype_offsets(): (&(pod.devPtr_offset)) - (&pod), (&(pod.size)) - (&pod), ], - 'itemsize': sizeof((NULL).u.batch), + 'itemsize': sizeof(cuda_bindings_cufile__anon_pod3), }) _py_anon_pod3_dtype = _get__py_anon_pod3_dtype_offsets() @@ -257,7 +257,7 @@ cdef class _py_anon_pod3: bint _readonly def __init__(self): - self._ptr = _cyb_calloc(1, sizeof((NULL).u.batch)) + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_cufile__anon_pod3)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod3") self._owner = None @@ -290,20 +290,20 @@ cdef class _py_anon_pod3: if not isinstance(other, _py_anon_pod3): return False other_ = other - return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof((NULL).u.batch)) == 0) + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_cufile__anon_pod3)) == 0) def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): - _cyb___getbuffer(self, buffer, self._ptr, sizeof((NULL).u.batch), self._readonly) + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_cufile__anon_pod3), self._readonly) def __releasebuffer__(self, Py_buffer *buffer): pass def __setitem__(self, key, val): if key == 0 and isinstance(val, _numpy.ndarray): - self._ptr = _cyb_malloc(sizeof((NULL).u.batch)) + self._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod3)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod3") - _cyb_memcpy(self._ptr, val.ctypes.data, sizeof((NULL).u.batch)) + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_cufile__anon_pod3)) self._owner = None self._owned = True self._readonly = not val.flags.writeable @@ -357,7 +357,7 @@ cdef class _py_anon_pod3: @staticmethod def from_buffer(buffer): """Create an _py_anon_pod3 instance with the memory from the given buffer.""" - return _cyb_from_buffer(buffer, sizeof((NULL).u.batch), _py_anon_pod3) + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_cufile__anon_pod3), _py_anon_pod3) @staticmethod def from_data(data): @@ -381,10 +381,10 @@ cdef class _py_anon_pod3: raise ValueError("ptr must not be null (0)") cdef _py_anon_pod3 obj = _py_anon_pod3.__new__(_py_anon_pod3) if owner is None: - obj._ptr = _cyb_malloc(sizeof((NULL).u.batch)) + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod3)) if obj._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod3") - _cyb_memcpy((obj._ptr), ptr, sizeof((NULL).u.batch)) + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_cufile__anon_pod3)) obj._owner = None obj._owned = True else: @@ -425,7 +425,10 @@ cdef class IOEvents: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=io_events_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=io_events_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(CUfileIOEvents_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUfileIOEvents_t) }" @@ -445,9 +448,10 @@ cdef class IOEvents: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -764,7 +768,10 @@ cdef class PerGpuStats: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=per_gpu_stats_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=per_gpu_stats_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(CUfilePerGpuStats_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUfilePerGpuStats_t) }" @@ -784,9 +791,10 @@ cdef class PerGpuStats: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -1228,7 +1236,10 @@ cdef class Descr: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=descr_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=descr_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(CUfileDescr_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUfileDescr_t) }" @@ -1248,9 +1259,10 @@ cdef class Descr: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -1373,7 +1385,7 @@ cdef _get__py_anon_pod2_dtype_offsets(): 'offsets': [ (&(pod.batch)) - (&pod), ], - 'itemsize': sizeof((NULL).u), + 'itemsize': sizeof(cuda_bindings_cufile__anon_pod2), }) _py_anon_pod2_dtype = _get__py_anon_pod2_dtype_offsets() @@ -1391,7 +1403,7 @@ cdef class _py_anon_pod2: bint _readonly def __init__(self): - self._ptr = _cyb_calloc(1, sizeof((NULL).u)) + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_cufile__anon_pod2)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod2") self._owner = None @@ -1424,20 +1436,20 @@ cdef class _py_anon_pod2: if not isinstance(other, _py_anon_pod2): return False other_ = other - return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof((NULL).u)) == 0) + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_cufile__anon_pod2)) == 0) def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): - _cyb___getbuffer(self, buffer, self._ptr, sizeof((NULL).u), self._readonly) + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_cufile__anon_pod2), self._readonly) def __releasebuffer__(self, Py_buffer *buffer): pass def __setitem__(self, key, val): if key == 0 and isinstance(val, _numpy.ndarray): - self._ptr = _cyb_malloc(sizeof((NULL).u)) + self._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod2)) if self._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod2") - _cyb_memcpy(self._ptr, val.ctypes.data, sizeof((NULL).u)) + _cyb_memcpy(self._ptr, val.ctypes.data, sizeof(cuda_bindings_cufile__anon_pod2)) self._owner = None self._owned = True self._readonly = not val.flags.writeable @@ -1463,7 +1475,7 @@ cdef class _py_anon_pod2: @staticmethod def from_buffer(buffer): """Create an _py_anon_pod2 instance with the memory from the given buffer.""" - return _cyb_from_buffer(buffer, sizeof((NULL).u), _py_anon_pod2) + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_cufile__anon_pod2), _py_anon_pod2) @staticmethod def from_data(data): @@ -1487,10 +1499,10 @@ cdef class _py_anon_pod2: raise ValueError("ptr must not be null (0)") cdef _py_anon_pod2 obj = _py_anon_pod2.__new__(_py_anon_pod2) if owner is None: - obj._ptr = _cyb_malloc(sizeof((NULL).u)) + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_cufile__anon_pod2)) if obj._ptr == NULL: raise MemoryError("Error allocating _py_anon_pod2") - _cyb_memcpy((obj._ptr), ptr, sizeof((NULL).u)) + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_cufile__anon_pod2)) obj._owner = None obj._owned = True else: @@ -2273,7 +2285,10 @@ cdef class IOParams: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=io_params_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=io_params_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(CUfileIOParams_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUfileIOParams_t) }" @@ -2293,9 +2308,10 @@ cdef class IOParams: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -2532,9 +2548,12 @@ cdef class StatsLevel2: @property def read_size_kb_hist(self): """~_numpy.uint64: (array of length 32).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(uint64_t), format="Q", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].read_size_kb_hist)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].read_size_kb_hist)), + (sizeof(uint64_t) * (32)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint64) @read_size_kb_hist.setter def read_size_kb_hist(self, val): @@ -2542,16 +2561,18 @@ cdef class StatsLevel2: raise ValueError("This StatsLevel2 instance is read-only") if len(val) != 32: raise ValueError(f"Expected length { 32 } for field read_size_kb_hist, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(uint64_t), format="Q", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint64) - _cyb_memcpy((&(self._ptr[0].read_size_kb_hist)), (arr.data), sizeof(uint64_t) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint64)) + _cyb_memcpy((&(self._ptr[0].read_size_kb_hist)), (_val_.ctypes.data), sizeof(uint64_t) * (32)) @property def write_size_kb_hist(self): """~_numpy.uint64: (array of length 32).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(uint64_t), format="Q", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].write_size_kb_hist)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].write_size_kb_hist)), + (sizeof(uint64_t) * (32)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint64) @write_size_kb_hist.setter def write_size_kb_hist(self, val): @@ -2559,9 +2580,8 @@ cdef class StatsLevel2: raise ValueError("This StatsLevel2 instance is read-only") if len(val) != 32: raise ValueError(f"Expected length { 32 } for field write_size_kb_hist, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(uint64_t), format="Q", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint64) - _cyb_memcpy((&(self._ptr[0].write_size_kb_hist)), (arr.data), sizeof(uint64_t) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint64)) + _cyb_memcpy((&(self._ptr[0].write_size_kb_hist)), (_val_.ctypes.data), sizeof(uint64_t) * (32)) @staticmethod def from_buffer(buffer): @@ -3009,7 +3029,7 @@ cdef int check_status(ReturnT status) except 1 nogil: # Wrapper functions ############################################################################### -cpdef intptr_t handle_register(intptr_t descr) except? 0: +cpdef intptr_t handle_register(descr) except? 0: """cuFileHandleRegister is required, and performs extra checking that is memoized to provide increased performance on later cuFile operations. Args: @@ -3022,9 +3042,10 @@ cpdef intptr_t handle_register(intptr_t descr) except? 0: .. seealso:: `cuFileHandleRegister` """ + cdef intptr_t _descr_ptr_ = int(descr) cdef Handle fh with nogil: - __status__ = cuFileHandleRegister(&fh, descr) + __status__ = cuFileHandleRegister(&fh, _descr_ptr_) check_status(__status__) return fh @@ -3169,15 +3190,17 @@ cpdef intptr_t batch_io_set_up(unsigned nr) except? 0: return batch_idp -cpdef batch_io_submit(intptr_t batch_idp, unsigned nr, intptr_t iocbp, unsigned int flags): +cpdef batch_io_submit(intptr_t batch_idp, unsigned nr, iocbp, unsigned int flags): + cdef intptr_t _iocbp_ptr_ = int(iocbp) with nogil: - __status__ = cuFileBatchIOSubmit(batch_idp, nr, iocbp, flags) + __status__ = cuFileBatchIOSubmit(batch_idp, nr, _iocbp_ptr_, flags) check_status(__status__) -cpdef batch_io_get_status(intptr_t batch_idp, unsigned min_nr, intptr_t nr, intptr_t iocbp, intptr_t timeout): +cpdef batch_io_get_status(intptr_t batch_idp, unsigned min_nr, intptr_t nr, iocbp, intptr_t timeout): + cdef intptr_t _iocbp_ptr_ = int(iocbp) with nogil: - __status__ = cuFileBatchIOGetStatus(batch_idp, min_nr, nr, iocbp, timeout) + __status__ = cuFileBatchIOGetStatus(batch_idp, min_nr, nr, _iocbp_ptr_, timeout) check_status(__status__) @@ -3356,7 +3379,7 @@ cpdef stats_reset(): check_status(__status__) -cpdef get_stats_l1(intptr_t stats): +cpdef get_stats_l1(stats): """Get Level 1 cuFile statistics. Args: @@ -3365,12 +3388,13 @@ cpdef get_stats_l1(intptr_t stats): .. seealso:: `cuFileGetStatsL1` """ + cdef intptr_t _stats_ptr_ = int(stats) with nogil: - __status__ = cuFileGetStatsL1(stats) + __status__ = cuFileGetStatsL1(_stats_ptr_) check_status(__status__) -cpdef get_stats_l2(intptr_t stats): +cpdef get_stats_l2(stats): """Get Level 2 cuFile statistics. Args: @@ -3379,12 +3403,13 @@ cpdef get_stats_l2(intptr_t stats): .. seealso:: `cuFileGetStatsL2` """ + cdef intptr_t _stats_ptr_ = int(stats) with nogil: - __status__ = cuFileGetStatsL2(stats) + __status__ = cuFileGetStatsL2(_stats_ptr_) check_status(__status__) -cpdef get_stats_l3(intptr_t stats): +cpdef get_stats_l3(stats): """Get Level 3 cuFile statistics. Args: @@ -3393,8 +3418,9 @@ cpdef get_stats_l3(intptr_t stats): .. seealso:: `cuFileGetStatsL3` """ + cdef intptr_t _stats_ptr_ = int(stats) with nogil: - __status__ = cuFileGetStatsL3(stats) + __status__ = cuFileGetStatsL3(_stats_ptr_) check_status(__status__) diff --git a/cuda_bindings/cuda/bindings/cynvml.pxd b/cuda_bindings/cuda/bindings/cynvml.pxd index 9b2cd749775..60fd1825712 100644 --- a/cuda_bindings/cuda/bindings/cynvml.pxd +++ b/cuda_bindings/cuda/bindings/cynvml.pxd @@ -11,7 +11,7 @@ ############################################################################### # enums -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=54d380973e59fbf316058a81b2026313f3564008841e322dd7dc3c7915e4ee87 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=f30665f85b06f57b6b81c0fd72d072b39d4f39d2d841ef632ec6854e8338a4cf ctypedef enum nvmlBridgeChipType_t "nvmlBridgeChipType_t": NVML_BRIDGE_CHIP_PLX "NVML_BRIDGE_CHIP_PLX" = 0 NVML_BRIDGE_CHIP_BRO4 "NVML_BRIDGE_CHIP_BRO4" = 1 @@ -1854,7 +1854,8 @@ ctypedef struct nvmlNvlinkFirmwareInfo_t 'nvmlNvlinkFirmwareInfo_t': ctypedef struct nvmlPRMTLV_v1_t 'nvmlPRMTLV_v1_t': unsigned dataSize unsigned status - cuda_bindings_nvml__anon_pod7 _anon_pod_member0 + unsigned char inData[496] + unsigned char outData[496] ctypedef struct nvmlVgpuSchedulerLogInfo_v2_t 'nvmlVgpuSchedulerLogInfo_v2_t': unsigned int engineId diff --git a/cuda_bindings/cuda/bindings/driver.pyx b/cuda_bindings/cuda/bindings/driver.pyx index 71c9d0d2f92..1497ae8e914 100644 --- a/cuda_bindings/cuda/bindings/driver.pyx +++ b/cuda_bindings/cuda/bindings/driver.pyx @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # This code was automatically generated with version 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=f62fe4f88ff8394acc48a14d465c00898f1f24f13fbd339862226a544cc8111a +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=0faac9f382211204c57212b06d9b0f1400afec346c1a2c803f85ba98e4616748 from typing import Any, Optional import cython import ctypes @@ -25780,9 +25780,9 @@ def cuDeviceSetMemPool(dev, pool): Parameters ---------- dev : :py:obj:`~.CUdevice` - None + Device to set the current memory pool for pool : :py:obj:`~.CUmemoryPool` or :py:obj:`~.cudaMemPool_t` - None + Memory pool to use as the device's current memory pool Returns ------- @@ -25830,14 +25830,14 @@ def cuDeviceGetMemPool(dev): Parameters ---------- dev : :py:obj:`~.CUdevice` - None + Device for which to query the current memory pool Returns ------- CUresult :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE` pool : :py:obj:`~.CUmemoryPool` - None + Returned current memory pool of the device See Also -------- @@ -25868,14 +25868,14 @@ def cuDeviceGetDefaultMemPool(dev): Parameters ---------- dev : :py:obj:`~.CUdevice` - None + Device for which to query the default memory pool Returns ------- CUresult :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_DEINITIALIZED` :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_INVALID_DEVICE`, :py:obj:`~.CUDA_ERROR_NOT_SUPPORTED` pool_out : :py:obj:`~.CUmemoryPool` - None + Returned default memory pool of the device See Also -------- @@ -27144,14 +27144,18 @@ def cuCtxGetLimit(limit not None : CUlimit): Parameters ---------- limit : :py:obj:`~.CUlimit` - None + Limit to query Returns ------- CUresult - + :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_UNSUPPORTED_LIMIT` pvalue : int - None + Returned size of limit + + See Also + -------- + :py:obj:`~.cuCtxCreate`, :py:obj:`~.cuCtxDestroy`, :py:obj:`~.cuCtxGetApiVersion`, :py:obj:`~.cuCtxGetCacheConfig`, :py:obj:`~.cuCtxGetDevice`, :py:obj:`~.cuCtxGetFlags`, :py:obj:`~.cuCtxPopCurrent`, :py:obj:`~.cuCtxPushCurrent`, :py:obj:`~.cuCtxSetCacheConfig`, :py:obj:`~.cuCtxSetLimit`, :py:obj:`~.cuCtxSynchronize`, :py:obj:`~.cudaDeviceGetLimit` """ cdef size_t pvalue = 0 cdef cydriver.CUlimit cylimit = int(limit) @@ -35414,16 +35418,20 @@ def cuMemPoolGetAttribute(pool, attr not None : CUmemPool_attribute): Parameters ---------- pool : :py:obj:`~.CUmemoryPool` or :py:obj:`~.cudaMemPool_t` - None + The memory pool to get attributes of attr : :py:obj:`~.CUmemPool_attribute` - None + The attribute to get Returns ------- CUresult - + :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE` value : Any - None + Retrieved value + + See Also + -------- + :py:obj:`~.cuMemAllocAsync`, :py:obj:`~.cuMemFreeAsync`, :py:obj:`~.cuDeviceGetDefaultMemPool`, :py:obj:`~.cuDeviceGetMemPool`, :py:obj:`~.cuMemPoolCreate` """ cdef cydriver.CUmemoryPool cypool if pool is None: @@ -35605,14 +35613,14 @@ def cuMemPoolCreate(poolProps : Optional[CUmemPoolProps]): Parameters ---------- poolProps : :py:obj:`~.CUmemPoolProps` - None + Memory pool properties Returns ------- CUresult :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_OUT_OF_MEMORY`, :py:obj:`~.CUDA_ERROR_NOT_PERMITTED`, :py:obj:`~.CUDA_ERROR_NOT_SUPPORTED` pool : :py:obj:`~.CUmemoryPool` - None + Returned memory pool See Also -------- @@ -35646,7 +35654,7 @@ def cuMemPoolDestroy(pool): Parameters ---------- pool : :py:obj:`~.CUmemoryPool` or :py:obj:`~.cudaMemPool_t` - None + Memory pool to destroy Returns ------- @@ -35690,16 +35698,17 @@ def cuMemGetDefaultMemPool(location : Optional[CUmemLocation], typename not None Parameters ---------- location : :py:obj:`~.CUmemLocation` - None + Memory location for which to query the default memory pool typename : :py:obj:`~.CUmemAllocationType` - None + Allocation type for which to query the default memory pool Returns ------- CUresult :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_DEINITIALIZED` :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_INVALID_DEVICE`, :py:obj:`~.CUDA_ERROR_NOT_SUPPORTED` pool_out : :py:obj:`~.CUmemoryPool` - None + Returned default memory pool for the given location and allocation + type See Also -------- @@ -35741,16 +35750,17 @@ def cuMemGetMemPool(location : Optional[CUmemLocation], typename not None : CUme Parameters ---------- location : :py:obj:`~.CUmemLocation` - None + Memory location for which to query the current memory pool typename : :py:obj:`~.CUmemAllocationType` - None + Allocation type for which to query the current memory pool Returns ------- CUresult :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE` pool : :py:obj:`~.CUmemoryPool` - None + Returned current memory pool for the given location and allocation + type See Also -------- @@ -35797,11 +35807,12 @@ def cuMemSetMemPool(location : Optional[CUmemLocation], typename not None : CUme Parameters ---------- location : :py:obj:`~.CUmemLocation` - None + Memory location for which to set the current memory pool typename : :py:obj:`~.CUmemAllocationType` - None + Allocation type for which to set the current memory pool pool : :py:obj:`~.CUmemoryPool` or :py:obj:`~.cudaMemPool_t` - None + Memory pool to use as the current memory pool for the given + location and allocation type Returns ------- @@ -52424,16 +52435,20 @@ def cuGraphicsResourceGetMappedPointer(resource): Parameters ---------- resource : :py:obj:`~.CUgraphicsResource` - None + Mapped resource to access Returns ------- CUresult - + :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_DEINITIALIZED`, :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_CONTEXT`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_INVALID_HANDLE`, :py:obj:`~.CUDA_ERROR_NOT_MAPPED`, :py:obj:`~.CUDA_ERROR_NOT_MAPPED_AS_POINTER` pDevPtr : :py:obj:`~.CUdeviceptr` - None + Returned pointer through which `resource` may be accessed pSize : int - None + Returned size of the buffer accessible starting at `*pPointer` + + See Also + -------- + :py:obj:`~.cuGraphicsMapResources`, :py:obj:`~.cuGraphicsSubResourceGetMappedArray`, :py:obj:`~.cudaGraphicsResourceGetMappedPointer` """ cdef cydriver.CUgraphicsResource cyresource if resource is None: @@ -55471,18 +55486,22 @@ def cuGraphicsResourceGetMappedEglFrame(resource, unsigned int index, unsigned i Parameters ---------- resource : :py:obj:`~.CUgraphicsResource` - None + Registered resource to access. index : unsigned int - None + Index for cubemap surfaces. mipLevel : unsigned int - None + Mipmap level for the subresource to access. Returns ------- CUresult - + :py:obj:`~.CUDA_SUCCESS`, :py:obj:`~.CUDA_ERROR_DEINITIALIZED`, :py:obj:`~.CUDA_ERROR_NOT_INITIALIZED`, :py:obj:`~.CUDA_ERROR_INVALID_CONTEXT`, :py:obj:`~.CUDA_ERROR_INVALID_VALUE`, :py:obj:`~.CUDA_ERROR_INVALID_HANDLE`, :py:obj:`~.CUDA_ERROR_NOT_MAPPED` eglFrame : :py:obj:`~.CUeglFrame` - None + Returned eglFrame. + + See Also + -------- + :py:obj:`~.cuGraphicsMapResources`, :py:obj:`~.cuGraphicsSubResourceGetMappedArray`, :py:obj:`~.cuGraphicsResourceGetMappedPointer`, :py:obj:`~.cudaGraphicsResourceGetMappedEglFrame` """ cdef cydriver.CUgraphicsResource cyresource if resource is None: diff --git a/cuda_bindings/cuda/bindings/nvfatbin.pyx b/cuda_bindings/cuda/bindings/nvfatbin.pyx index 0e485dd80dc..d94512b56af 100644 --- a/cuda_bindings/cuda/bindings/nvfatbin.pyx +++ b/cuda_bindings/cuda/bindings/nvfatbin.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.4.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=464151e9be344b663eb001d24b780328f477470afca263a03384394a057b74bd +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=183bfbae252b3647deef334f131c6e98f300c401f6a6b13c5c4f5e10b442917c # <<<< PREAMBLE CONTENT >>>> @@ -20,7 +20,9 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep flags |= _cyb_cpython.PyBUF_WRITABLE cdef int status = -1 cdef _cyb_cpython.Py_buffer view - if isinstance(buf, int): + if buf is None: + ptr = 0 + elif isinstance(buf, int): ptr = buf else: try: @@ -31,7 +33,7 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep except Exception as e: adj = "writable " if not readonly else "" raise ValueError( - "buf must be either a Python int representing the pointer " + "buf must be None, a Python int representing the pointer " f"address to a valid buffer, or a 1D contiguous {adj}" f"buffer, of size {size}" ) from e @@ -320,6 +322,17 @@ cpdef tuple version(): cpdef add_index(intptr_t handle, code, size_t size, identifier): + """nvFatbinAddIndex adds an index file to the fatbinary. + + Args: + handle (intptr_t): nvFatbin handle. + code (bytes): The index. + size (size_t): The size of the index. + identifier (str): Name of the index, useful when extracting + the fatbin with tools like cuobjdump. + + .. seealso:: `nvFatbinAddIndex` + """ cdef void* _code_ = _cyb_get_buffer_pointer(code, size, readonly=True) if not isinstance(identifier, str): raise TypeError("identifier must be a Python str") diff --git a/cuda_bindings/cuda/bindings/nvjitlink.pyx b/cuda_bindings/cuda/bindings/nvjitlink.pyx index 89076249cf9..ae04649ee0d 100644 --- a/cuda_bindings/cuda/bindings/nvjitlink.pyx +++ b/cuda_bindings/cuda/bindings/nvjitlink.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.0.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=4f142d6dd069dd459052ff17e4e585b764e7a8b4298051df3c6c0d39e1c67ded +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=435af9c33982479f9bef02504387f8f8498c5e8e0507284ecf0c0a60294f4944 # <<<< PREAMBLE CONTENT >>>> @@ -23,7 +23,9 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep flags |= _cyb_cpython.PyBUF_WRITABLE cdef int status = -1 cdef _cyb_cpython.Py_buffer view - if isinstance(buf, int): + if buf is None: + ptr = 0 + elif isinstance(buf, int): ptr = buf else: try: @@ -34,7 +36,7 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep except Exception as e: adj = "writable " if not readonly else "" raise ValueError( - "buf must be either a Python int representing the pointer " + "buf must be None, a Python int representing the pointer " f"address to a valid buffer, or a 1D contiguous {adj}" f"buffer, of size {size}" ) from e diff --git a/cuda_bindings/cuda/bindings/nvml.pxd b/cuda_bindings/cuda/bindings/nvml.pxd index ce3c1db4852..c9e6152f248 100644 --- a/cuda_bindings/cuda/bindings/nvml.pxd +++ b/cuda_bindings/cuda/bindings/nvml.pxd @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=b6fe9a4efd0077f8c09ef4f826880ad0a54100455d4465953c4127d3de8c4d91 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=1def942240cd7ac4772723263496d54496c2ef3ed0ec4147fe3884f8489bc19a @@ -62,7 +62,6 @@ ctypedef nvmlUnrepairableMemoryStatus_v1_t UnrepairableMemoryStatus_v1 ctypedef nvmlRusdSettings_v1_t RusdSettings_v1 ctypedef nvmlPowerValue_v2_t PowerValue_v2 ctypedef nvmlVgpuTypeMaxInstance_v1_t VgpuTypeMaxInstance_v1 -ctypedef nvmlVgpuProcessUtilizationSample_t VgpuProcessUtilizationSample ctypedef nvmlGpuFabricInfo_t GpuFabricInfo ctypedef nvmlSystemEventSetCreateRequest_v1_t SystemEventSetCreateRequest_v1 ctypedef nvmlSystemEventSetFreeRequest_v1_t SystemEventSetFreeRequest_v1 @@ -163,6 +162,7 @@ cpdef int system_get_cuda_driver_version() except * cpdef int system_get_cuda_driver_version_v2() except 0 cpdef str system_get_process_name(unsigned int pid) cpdef object system_get_hic_version() +cpdef object system_get_topology_gpu_set(unsigned int cpu_number) cpdef unsigned int unit_get_count() except? 0 cpdef intptr_t unit_get_handle_by_index(unsigned int index) except? 0 cpdef object unit_get_unit_info(intptr_t unit) @@ -170,6 +170,7 @@ cpdef object unit_get_led_state(intptr_t unit) cpdef object unit_get_psu_info(intptr_t unit) cpdef unsigned int unit_get_temperature(intptr_t unit, unsigned int type) except? 0 cpdef object unit_get_fan_speed_info(intptr_t unit) +cpdef object unit_get_devices(intptr_t unit) cpdef unsigned int device_get_count_v2() except? 0 cpdef object device_get_attributes_v2(intptr_t device) cpdef intptr_t device_get_handle_by_index_v2(unsigned int index) except? 0 @@ -189,6 +190,7 @@ cpdef device_set_cpu_affinity(intptr_t device) cpdef device_clear_cpu_affinity(intptr_t device) cpdef unsigned int device_get_numa_node_id(intptr_t device) except? 0 cpdef int device_get_topology_common_ancestor(intptr_t device1, intptr_t device2) except? -1 +cpdef object device_get_topology_nearest_gpus(intptr_t device, int level) cpdef int device_get_p2p_status(intptr_t device1, intptr_t device2, int p2p_index) except? -1 cpdef str device_get_uuid(intptr_t device) cpdef unsigned int device_get_minor_number(intptr_t device) except? 0 @@ -236,7 +238,7 @@ cpdef int device_get_mem_clk_vf_offset(intptr_t device) except? 0 cpdef tuple device_get_min_max_clock_of_p_state(intptr_t device, int type, int pstate) cpdef tuple device_get_gpc_clk_min_max_vf_offset(intptr_t device) cpdef tuple device_get_mem_clk_min_max_vf_offset(intptr_t device) -cpdef device_set_clock_offsets(intptr_t device, intptr_t info) +cpdef device_set_clock_offsets(intptr_t device, info) cpdef unsigned int device_get_power_management_limit(intptr_t device) except? 0 cpdef tuple device_get_power_management_limit_constraints(intptr_t device) cpdef unsigned int device_get_power_management_default_limit(intptr_t device) except? 0 @@ -271,6 +273,7 @@ cpdef object device_get_graphics_running_processes_v3(intptr_t device) cpdef object device_get_mps_compute_running_processes_v3(intptr_t device) cpdef int device_on_same_board(intptr_t device1, intptr_t device2) except? 0 cpdef int device_get_api_restriction(intptr_t device, int api_type) except? -1 +cpdef tuple device_get_samples(intptr_t device, int type, unsigned long long last_seen_time_stamp) cpdef object device_get_bar1_memory_info(intptr_t device) cpdef unsigned int device_get_irq_num(intptr_t device) except? 0 cpdef unsigned int device_get_num_gpu_cores(intptr_t device) except? 0 @@ -297,6 +300,7 @@ cpdef object device_get_accounting_stats(intptr_t device, unsigned int pid) cpdef object device_get_accounting_pids(intptr_t device) cpdef unsigned int device_get_accounting_buffer_size(intptr_t device) except? 0 cpdef object device_get_retired_pages(intptr_t device, int cause) +cpdef tuple device_get_retired_pages_v2(intptr_t device, int cause) cpdef int device_get_retired_pages_pending_status(intptr_t device) except? -1 cpdef tuple device_get_remapped_rows(intptr_t device) cpdef object device_get_row_remapper_histogram(intptr_t device) @@ -333,16 +337,16 @@ cpdef system_set_nvlink_bw_mode(unsigned int nvlink_bw_mode) cpdef unsigned int system_get_nvlink_bw_mode() except? 0 cpdef object device_get_nvlink_supported_bw_modes(intptr_t device) cpdef object device_get_nvlink_bw_mode(intptr_t device) -cpdef device_set_nvlink_bw_mode(intptr_t device, intptr_t set_bw_mode) +cpdef device_set_nvlink_bw_mode(intptr_t device, set_bw_mode) cpdef intptr_t event_set_create() except? 0 cpdef device_register_events(intptr_t device, unsigned long long event_types, intptr_t set) cpdef unsigned long long device_get_supported_event_types(intptr_t device) except? 0 cpdef object event_set_wait_v2(intptr_t set, unsigned int timeoutms) cpdef event_set_free(intptr_t set) -cpdef device_modify_drain_state(intptr_t pci_info, int new_state) -cpdef int device_query_drain_state(intptr_t pci_info) except? -1 -cpdef device_remove_gpu_v2(intptr_t pci_info, int gpu_state, int link_state) -cpdef device_discover_gpus(intptr_t pci_info) +cpdef device_modify_drain_state(pci_info, int new_state) +cpdef int device_query_drain_state(pci_info) except? -1 +cpdef device_remove_gpu_v2(pci_info, int gpu_state, int link_state) +cpdef device_discover_gpus(pci_info) cpdef int device_get_virtualization_mode(intptr_t device) except? -1 cpdef int device_get_host_vgpu_mode(intptr_t device) except? -1 cpdef device_set_virtualization_mode(intptr_t device, int virtual_mode) @@ -352,6 +356,8 @@ cpdef device_set_vgpu_capabilities(intptr_t device, int capability, int state) cpdef object device_get_grid_licensable_features_v4(intptr_t device) cpdef unsigned int get_vgpu_driver_capabilities(int capability) except? 0 cpdef unsigned int device_get_vgpu_capabilities(intptr_t device, int capability) except? 0 +cpdef object device_get_supported_vgpus(intptr_t device) +cpdef object device_get_creatable_vgpus(intptr_t device) cpdef str vgpu_type_get_class(unsigned int vgpu_type_id) cpdef unsigned int vgpu_type_get_gpu_instance_profile_id(unsigned int vgpu_type_id) except? 0 cpdef tuple vgpu_type_get_device_id(unsigned int vgpu_type_id) @@ -363,6 +369,8 @@ cpdef unsigned int vgpu_type_get_frame_rate_limit(unsigned int vgpu_type_id) exc cpdef unsigned int vgpu_type_get_max_instances(intptr_t device, unsigned int vgpu_type_id) except? 0 cpdef unsigned int vgpu_type_get_max_instances_per_vm(unsigned int vgpu_type_id) except? 0 cpdef object vgpu_type_get_bar1_info(unsigned int vgpu_type_id) +cpdef object device_get_active_vgpus(intptr_t device) +cpdef tuple vgpu_instance_get_vm_id(unsigned int vgpu_instance) cpdef str vgpu_instance_get_uuid(unsigned int vgpu_instance) cpdef str vgpu_instance_get_vm_driver_version(unsigned int vgpu_instance) cpdef unsigned long long vgpu_instance_get_fb_usage(unsigned int vgpu_instance) except? 0 @@ -380,7 +388,7 @@ cpdef unsigned int vgpu_instance_get_gpu_instance_id(unsigned int vgpu_instance) cpdef str vgpu_instance_get_gpu_pci_id(unsigned int vgpu_instance) cpdef unsigned int vgpu_type_get_capabilities(unsigned int vgpu_type_id, int capability) except? 0 cpdef str vgpu_instance_get_mdev_uuid(unsigned int vgpu_instance) -cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, intptr_t p_scheduler) +cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, p_scheduler) cpdef object gpu_instance_get_vgpu_scheduler_state(intptr_t gpu_instance) cpdef object gpu_instance_get_vgpu_scheduler_log(intptr_t gpu_instance) cpdef str device_get_pgpu_metadata_string(intptr_t device) @@ -388,8 +396,10 @@ cpdef object device_get_vgpu_scheduler_log(intptr_t device) cpdef object device_get_vgpu_scheduler_state(intptr_t device) cpdef object device_get_vgpu_scheduler_capabilities(intptr_t device) cpdef device_set_vgpu_scheduler_state(intptr_t device, intptr_t p_scheduler_state) -cpdef set_vgpu_version(intptr_t vgpu_version) -cpdef tuple device_get_vgpu_process_utilization(intptr_t device, unsigned long long last_seen_time_stamp) +cpdef tuple get_vgpu_version() +cpdef set_vgpu_version(vgpu_version) +cpdef tuple device_get_vgpu_utilization(intptr_t device, unsigned long long last_seen_time_stamp) +cpdef object device_get_vgpu_process_utilization(intptr_t device, unsigned long long last_seen_time_stamp) cpdef int vgpu_instance_get_accounting_mode(unsigned int vgpu_instance) except? -1 cpdef object vgpu_instance_get_accounting_pids(unsigned int vgpu_instance) cpdef object vgpu_instance_get_accounting_stats(unsigned int vgpu_instance, unsigned int pid) @@ -402,16 +412,18 @@ cpdef tuple device_get_mig_mode(intptr_t device) cpdef object device_get_gpu_instance_possible_placements_v2(intptr_t device, unsigned int profile_id) cpdef unsigned int device_get_gpu_instance_remaining_capacity(intptr_t device, unsigned int profile_id) except? 0 cpdef intptr_t device_create_gpu_instance(intptr_t device, unsigned int profile_id) except? 0 -cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsigned int profile_id, intptr_t placement) except? 0 +cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsigned int profile_id, placement) except? 0 cpdef gpu_instance_destroy(intptr_t gpu_instance) +cpdef object device_get_gpu_instances(intptr_t device, unsigned int profile_id) cpdef intptr_t device_get_gpu_instance_by_id(intptr_t device, unsigned int id) except? 0 cpdef object gpu_instance_get_info(intptr_t gpu_instance) cpdef object gpu_instance_get_compute_instance_profile_info_v(intptr_t gpu_instance, unsigned int profile, unsigned int eng_profile) cpdef unsigned int gpu_instance_get_compute_instance_remaining_capacity(intptr_t gpu_instance, unsigned int profile_id) except? 0 cpdef object gpu_instance_get_compute_instance_possible_placements(intptr_t gpu_instance, unsigned int profile_id) cpdef intptr_t gpu_instance_create_compute_instance(intptr_t gpu_instance, unsigned int profile_id) except? 0 -cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_instance, unsigned int profile_id, intptr_t placement) except? 0 +cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_instance, unsigned int profile_id, placement) except? 0 cpdef compute_instance_destroy(intptr_t compute_instance) +cpdef object gpu_instance_get_compute_instances(intptr_t gpu_instance, unsigned int profile_id) cpdef intptr_t gpu_instance_get_compute_instance_by_id(intptr_t gpu_instance, unsigned int id) except? 0 cpdef object compute_instance_get_info_v2(intptr_t compute_instance) cpdef unsigned int device_is_mig_device_handle(intptr_t device) except? 0 @@ -426,14 +438,14 @@ cpdef device_power_smoothing_set_state(intptr_t device, intptr_t state) cpdef object device_get_addressing_mode(intptr_t device) cpdef object device_get_repair_status(intptr_t device) cpdef object device_get_power_mizer_mode_v1(intptr_t device) -cpdef device_set_power_mizer_mode_v1(intptr_t device, intptr_t power_mizer_mode) +cpdef device_set_power_mizer_mode_v1(intptr_t device, power_mizer_mode) cpdef device_vgpu_force_gsp_unload(intptr_t device) cpdef object device_get_vgpu_scheduler_state_v2(intptr_t device) cpdef object gpu_instance_get_vgpu_scheduler_state_v2(intptr_t gpu_instance) cpdef object device_get_vgpu_scheduler_log_v2(intptr_t device) cpdef object gpu_instance_get_vgpu_scheduler_log_v2(intptr_t gpu_instance) -cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, intptr_t p_scheduler_state) -cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, intptr_t p_scheduler_state) +cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, p_scheduler_state) +cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, p_scheduler_state) cpdef object system_get_cper_v1() cpdef object device_get_bbx_time_data_v1(intptr_t device) cpdef object device_get_accounting_stats_v2(intptr_t device) diff --git a/cuda_bindings/cuda/bindings/nvml.pyx b/cuda_bindings/cuda/bindings/nvml.pyx index 4378e667d06..fcdd6479c37 100644 --- a/cuda_bindings/cuda/bindings/nvml.pyx +++ b/cuda_bindings/cuda/bindings/nvml.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=9167da2a3d3194c67c44a0fe8d4d34b3dbd3c0f43061c50b7d238d2044c75509 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=0b1daff691b8b90c968f51286ae212829d9f7b34c97e0db2b859994173f7f2da # <<<< PREAMBLE CONTENT >>>> @@ -11,7 +11,7 @@ cimport cpython as _cyb_cpython cimport cpython.buffer as _cyb_cpython_buffer cimport cpython.memoryview as _cyb_cpython_memoryview -from cython cimport view as _cyb_view +from cpython.memoryview cimport PyMemoryView_FromMemory as _cyb_PyMemoryView_FromMemory from libc.stdint cimport intptr_t from libc.stdlib cimport ( calloc as _cyb_calloc, @@ -3267,7 +3267,10 @@ cdef class ProcessInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=process_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlProcessInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlProcessInfo_t) }" @@ -3287,9 +3290,10 @@ cdef class ProcessInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -3449,7 +3453,10 @@ cdef class ProcessDetail_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_detail_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=process_detail_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlProcessDetail_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlProcessDetail_v1_t) }" @@ -3469,9 +3476,10 @@ cdef class ProcessDetail_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -4176,7 +4184,10 @@ cdef class BridgeChipInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=bridge_chip_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=bridge_chip_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlBridgeChipInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlBridgeChipInfo_t) }" @@ -4196,9 +4207,10 @@ cdef class BridgeChipInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -4539,7 +4551,10 @@ cdef class _py_anon_pod0: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=_py_anon_pod0_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=_py_anon_pod0_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(cuda_bindings_nvml__anon_pod0), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(cuda_bindings_nvml__anon_pod0) }" @@ -4559,9 +4574,10 @@ cdef class _py_anon_pod0: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -4896,7 +4912,10 @@ cdef class ClkMonFaultInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=clk_mon_fault_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=clk_mon_fault_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlClkMonFaultInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlClkMonFaultInfo_t) }" @@ -4916,9 +4935,10 @@ cdef class ClkMonFaultInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -5248,7 +5268,10 @@ cdef class ProcessUtilizationSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_utilization_sample_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=process_utilization_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlProcessUtilizationSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlProcessUtilizationSample_t) }" @@ -5268,9 +5291,10 @@ cdef class ProcessUtilizationSample: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -5455,7 +5479,10 @@ cdef class ProcessUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_utilization_info_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=process_utilization_info_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlProcessUtilizationInfo_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlProcessUtilizationInfo_v1_t) }" @@ -5475,9 +5502,10 @@ cdef class ProcessUtilizationInfo_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -6024,9 +6052,12 @@ cdef class PlatformInfo_v1: @property def ib_guid(self): """~_numpy.uint8: (array of length 16).Infiniband GUID reported by platform (for Blackwell, ibGuid is 8 bytes so indices 8-15 are zero).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].ibGuid)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].ibGuid)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @ib_guid.setter def ib_guid(self, val): @@ -6034,16 +6065,18 @@ cdef class PlatformInfo_v1: raise ValueError("This PlatformInfo_v1 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field ib_guid, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].ibGuid)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].ibGuid)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def rack_guid(self): """~_numpy.uint8: (array of length 16).GUID of the rack containing this GPU (for Blackwell rackGuid is 13 bytes so indices 13-15 are zero).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].rackGuid)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].rackGuid)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @rack_guid.setter def rack_guid(self, val): @@ -6051,9 +6084,8 @@ cdef class PlatformInfo_v1: raise ValueError("This PlatformInfo_v1 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field rack_guid, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].rackGuid)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].rackGuid)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def chassis_physical_slot_number(self): @@ -6251,9 +6283,12 @@ cdef class PlatformInfo_v2: @property def ib_guid(self): """~_numpy.uint8: (array of length 16).Infiniband GUID reported by platform (for Blackwell, ibGuid is 8 bytes so indices 8-15 are zero).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].ibGuid)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].ibGuid)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @ib_guid.setter def ib_guid(self, val): @@ -6261,16 +6296,18 @@ cdef class PlatformInfo_v2: raise ValueError("This PlatformInfo_v2 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field ib_guid, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].ibGuid)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].ibGuid)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def chassis_serial_number(self): """~_numpy.uint8: (array of length 16).Serial number of the chassis containing this GPU (for Blackwell it is 13 bytes so indices 13-15 are zero).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].chassisSerialNumber)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].chassisSerialNumber)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @chassis_serial_number.setter def chassis_serial_number(self, val): @@ -6278,9 +6315,8 @@ cdef class PlatformInfo_v2: raise ValueError("This PlatformInfo_v2 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field chassis_serial_number, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].chassisSerialNumber)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].chassisSerialNumber)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def slot_number(self): @@ -6409,7 +6445,10 @@ cdef class _py_anon_pod1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=_py_anon_pod1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=_py_anon_pod1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(cuda_bindings_nvml__anon_pod1), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(cuda_bindings_nvml__anon_pod1) }" @@ -6429,9 +6468,10 @@ cdef class _py_anon_pod1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -6671,19 +6711,21 @@ cdef class VgpuPlacementList_v2: """int: IN/OUT: Placement IDs for the vGPU type.""" if self._ptr[0].placementIds == NULL: return [] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].count,), itemsize=sizeof(unsigned int), format="I", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].placementIds) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].placementIds), + (self._ptr[0].count * sizeof(unsigned int)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @placement_ids.setter def placement_ids(self, val): if self._readonly: raise ValueError("This VgpuPlacementList_v2 instance is read-only") - cdef _cyb_view.array arr = _cyb_view.array(shape=(len(val),), itemsize=sizeof(unsigned int), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - self._ptr[0].placementIds = (arr.data) + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + self._ptr[0].placementIds = _arr_.ctypes.data self._ptr[0].count = len(val) - self._refs["placement_ids"] = arr + self._refs["placement_ids"] = _arr_ @property def mode(self): @@ -6881,6 +6923,237 @@ cdef class VgpuTypeBar1Info_v1: return obj +cdef _get_vgpu_process_utilization_sample_dtype_offsets(): + cdef nvmlVgpuProcessUtilizationSample_t pod + return _numpy.dtype({ + 'names': ['vgpu_instance', 'pid', 'process_name', 'time_stamp', 'sm_util', 'mem_util', 'enc_util', 'dec_util'], + 'formats': [_numpy.uint32, _numpy.uint32, (_numpy.int8, 64), _numpy.uint64, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.vgpuInstance)) - (&pod), + (&(pod.pid)) - (&pod), + (&(pod.processName)) - (&pod), + (&(pod.timeStamp)) - (&pod), + (&(pod.smUtil)) - (&pod), + (&(pod.memUtil)) - (&pod), + (&(pod.encUtil)) - (&pod), + (&(pod.decUtil)) - (&pod), + ], + 'itemsize': sizeof(nvmlVgpuProcessUtilizationSample_t), + }) + +vgpu_process_utilization_sample_dtype = _get_vgpu_process_utilization_sample_dtype_offsets() + +cdef class VgpuProcessUtilizationSample: + """Empty-initialize an array of `nvmlVgpuProcessUtilizationSample_t`. + The resulting object is of length `size` and of dtype `vgpu_process_utilization_sample_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `nvmlVgpuProcessUtilizationSample_t` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_process_utilization_sample_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(nvmlVgpuProcessUtilizationSample_t), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuProcessUtilizationSample_t) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.VgpuProcessUtilizationSample_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.VgpuProcessUtilizationSample object at {hex(id(self))}>" + + @property + def ptr(self): + """Get the pointer address to the data as Python :class:`int`.""" + return self._data.ctypes.data + + cdef intptr_t _get_ptr(self): + return self._data.ctypes.data + + def __int__(self): + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") + return self._data.ctypes.data + + def __len__(self): + return self._data.size + + def __eq__(self, other): + cdef object self_data = self._data + if (not isinstance(other, VgpuProcessUtilizationSample)) or self_data.size != other._data.size or self_data.dtype != other._data.dtype: + return False + return bool((self_data == other._data).all()) + + def __getbuffer__(self, Py_buffer *buffer, int flags): + _cyb_cpython.PyObject_GetBuffer(self._data, buffer, flags) + + def __releasebuffer__(self, Py_buffer *buffer): + _cyb_cpython.PyBuffer_Release(buffer) + + @property + def vgpu_instance(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.vgpu_instance[0]) + return self._data.vgpu_instance + + @vgpu_instance.setter + def vgpu_instance(self, val): + self._data.vgpu_instance = val + + @property + def pid(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.pid[0]) + return self._data.pid + + @pid.setter + def pid(self, val): + self._data.pid = val + + @property + def process_name(self): + """~_numpy.int8: (array of length 64).""" + return self._data.process_name + + @process_name.setter + def process_name(self, val): + self._data.process_name = val + + @property + def time_stamp(self): + """Union[~_numpy.uint64, int]: """ + if self._data.size == 1: + return int(self._data.time_stamp[0]) + return self._data.time_stamp + + @time_stamp.setter + def time_stamp(self, val): + self._data.time_stamp = val + + @property + def sm_util(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.sm_util[0]) + return self._data.sm_util + + @sm_util.setter + def sm_util(self, val): + self._data.sm_util = val + + @property + def mem_util(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.mem_util[0]) + return self._data.mem_util + + @mem_util.setter + def mem_util(self, val): + self._data.mem_util = val + + @property + def enc_util(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.enc_util[0]) + return self._data.enc_util + + @enc_util.setter + def enc_util(self, val): + self._data.enc_util = val + + @property + def dec_util(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.dec_util[0]) + return self._data.dec_util + + @dec_util.setter + def dec_util(self, val): + self._data.dec_util = val + + def __getitem__(self, key): + cdef ssize_t key_ + cdef ssize_t size + if isinstance(key, int): + key_ = key + size = self._data.size + if key_ >= size or key_ <= -(size+1): + raise IndexError("index is out of bounds") + if key_ < 0: + key_ += size + return VgpuProcessUtilizationSample.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == vgpu_process_utilization_sample_dtype: + return VgpuProcessUtilizationSample.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an VgpuProcessUtilizationSample instance with the memory from the given buffer.""" + return VgpuProcessUtilizationSample.from_data(_numpy.frombuffer(buffer, dtype=vgpu_process_utilization_sample_dtype)) + + @staticmethod + def from_data(data): + """Create an VgpuProcessUtilizationSample instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `vgpu_process_utilization_sample_dtype` holding the data. + """ + cdef VgpuProcessUtilizationSample obj = VgpuProcessUtilizationSample.__new__(VgpuProcessUtilizationSample) + if not isinstance(data, _numpy.ndarray): + raise TypeError("data argument must be a NumPy ndarray") + if data.ndim != 1: + raise ValueError("data array must be 1D") + if data.dtype != vgpu_process_utilization_sample_dtype: + raise ValueError("data array must be of dtype vgpu_process_utilization_sample_dtype") + obj._data = data.view(_numpy.recarray) + + return obj + + @staticmethod + def from_ptr(intptr_t ptr, size_t size=1, bint readonly=False, object owner=None): + """Create an VgpuProcessUtilizationSample instance wrapping the given pointer. + + Args: + ptr (intptr_t): pointer address as Python :class:`int` to the data. + size (int): number of structs, default=1. + readonly (bool): whether the data is read-only (to the user). default is `False`. + owner (object): object that owns the memory at *ptr*. A strong reference is + kept so the backing storage outlives this wrapper. + """ + if ptr == 0: + raise ValueError("ptr must not be null (0)") + cdef VgpuProcessUtilizationSample obj = VgpuProcessUtilizationSample.__new__(VgpuProcessUtilizationSample) + cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE + cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory( + ptr, sizeof(nvmlVgpuProcessUtilizationSample_t) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=vgpu_process_utilization_sample_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + return obj + + cdef _get_vgpu_process_utilization_info_v1_dtype_offsets(): cdef nvmlVgpuProcessUtilizationInfo_v1_t pod return _numpy.dtype({ @@ -6918,7 +7191,10 @@ cdef class VgpuProcessUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_process_utilization_info_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_process_utilization_info_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlVgpuProcessUtilizationInfo_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuProcessUtilizationInfo_v1_t) }" @@ -6938,9 +7214,10 @@ cdef class VgpuProcessUtilizationInfo_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -7439,7 +7716,10 @@ cdef class VgpuSchedulerLogEntry: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_scheduler_log_entry_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_scheduler_log_entry_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlVgpuSchedulerLogEntry_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuSchedulerLogEntry_t) }" @@ -7459,9 +7739,10 @@ cdef class VgpuSchedulerLogEntry: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -7974,9 +8255,12 @@ cdef class VgpuSchedulerCapabilities: @property def supported_schedulers(self): """~_numpy.uint32: (array of length 3).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(unsigned int), format="I", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].supportedSchedulers)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].supportedSchedulers)), + (sizeof(unsigned int) * (3)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @supported_schedulers.setter def supported_schedulers(self, val): @@ -7984,9 +8268,8 @@ cdef class VgpuSchedulerCapabilities: raise ValueError("This VgpuSchedulerCapabilities instance is read-only") if len(val) != 3: raise ValueError(f"Expected length { 3 } for field supported_schedulers, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(unsigned int), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - _cyb_memcpy((&(self._ptr[0].supportedSchedulers)), (arr.data), sizeof(unsigned int) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + _cyb_memcpy((&(self._ptr[0].supportedSchedulers)), (_val_.ctypes.data), sizeof(unsigned int) * (3)) @property def max_timeslice(self): @@ -8611,19 +8894,21 @@ cdef class VgpuTypeIdInfo_v1: """int: OUT: List of vGPU type IDs.""" if self._ptr[0].vgpuTypeIds == NULL: return [] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].vgpuCount,), itemsize=sizeof(unsigned int), format="I", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].vgpuTypeIds) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].vgpuTypeIds), + (self._ptr[0].vgpuCount * sizeof(unsigned int)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @vgpu_type_ids.setter def vgpu_type_ids(self, val): if self._readonly: raise ValueError("This VgpuTypeIdInfo_v1 instance is read-only") - cdef _cyb_view.array arr = _cyb_view.array(shape=(len(val),), itemsize=sizeof(unsigned int), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - self._ptr[0].vgpuTypeIds = (arr.data) + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + self._ptr[0].vgpuTypeIds = _arr_.ctypes.data self._ptr[0].vgpuCount = len(val) - self._refs["vgpu_type_ids"] = arr + self._refs["vgpu_type_ids"] = _arr_ @staticmethod def from_buffer(buffer): @@ -8766,19 +9051,21 @@ cdef class ActiveVgpuInstanceInfo_v1: """int: IN/OUT: list of active vGPU instances.""" if self._ptr[0].vgpuInstances == NULL: return [] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].vgpuCount,), itemsize=sizeof(unsigned int), format="I", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].vgpuInstances) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].vgpuInstances), + (self._ptr[0].vgpuCount * sizeof(unsigned int)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @vgpu_instances.setter def vgpu_instances(self, val): if self._readonly: raise ValueError("This ActiveVgpuInstanceInfo_v1 instance is read-only") - cdef _cyb_view.array arr = _cyb_view.array(shape=(len(val),), itemsize=sizeof(unsigned int), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - self._ptr[0].vgpuInstances = (arr.data) + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + self._ptr[0].vgpuInstances = _arr_.ctypes.data self._ptr[0].vgpuCount = len(val) - self._refs["vgpu_instances"] = arr + self._refs["vgpu_instances"] = _arr_ @staticmethod def from_buffer(buffer): @@ -8945,19 +9232,21 @@ cdef class VgpuCreatablePlacementInfo_v1: """int: IN/OUT: Placement IDs for the vGPU type.""" if self._ptr[0].placementIds == NULL: return [] - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].placementSize,), itemsize=sizeof(unsigned int), format="I", mode="c", allocate_buffer=False) - arr.data = (self._ptr[0].placementIds) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (self._ptr[0].placementIds), + (self._ptr[0].placementSize * sizeof(unsigned int)), + _cyb_cpython_buffer.PyBUF_WRITE, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint32) @placement_ids.setter def placement_ids(self, val): if self._readonly: raise ValueError("This VgpuCreatablePlacementInfo_v1 instance is read-only") - cdef _cyb_view.array arr = _cyb_view.array(shape=(len(val),), itemsize=sizeof(unsigned int), format="I", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint32) - self._ptr[0].placementIds = (arr.data) + _arr_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint32)) + self._ptr[0].placementIds = _arr_.ctypes.data self._ptr[0].placementSize = len(val) - self._refs["placement_ids"] = arr + self._refs["placement_ids"] = _arr_ @staticmethod def from_buffer(buffer): @@ -9030,7 +9319,10 @@ cdef class HwbcEntry: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=hwbc_entry_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=hwbc_entry_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlHwbcEntry_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlHwbcEntry_t) }" @@ -9050,9 +9342,10 @@ cdef class HwbcEntry: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -9686,7 +9979,10 @@ cdef class UnitFanInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=unit_fan_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=unit_fan_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlUnitFanInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlUnitFanInfo_t) }" @@ -9706,9 +10002,10 @@ cdef class UnitFanInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -10022,7 +10319,10 @@ cdef class SystemEventData_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=system_event_data_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=system_event_data_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlSystemEventData_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlSystemEventData_v1_t) }" @@ -10042,9 +10342,10 @@ cdef class SystemEventData_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -10377,7 +10678,10 @@ cdef class EncoderSessionInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=encoder_session_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=encoder_session_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlEncoderSessionInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlEncoderSessionInfo_t) }" @@ -10397,9 +10701,10 @@ cdef class EncoderSessionInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -10765,7 +11070,10 @@ cdef class FBCSessionInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=fbc_session_info_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=fbc_session_info_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlFBCSessionInfo_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlFBCSessionInfo_t) }" @@ -10785,9 +11093,10 @@ cdef class FBCSessionInfo: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -11710,9 +12019,12 @@ cdef class ConfComputeGpuCertificate: """~_numpy.uint8: (array of length 4096).""" if self._ptr[0].certChainSize == 0: return _numpy.array([]) - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].certChainSize,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].certChain)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].certChain)), + (sizeof(unsigned char) * (self._ptr[0].certChainSize)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @cert_chain.setter def cert_chain(self, val): @@ -11723,18 +12035,20 @@ cdef class ConfComputeGpuCertificate: self._ptr[0].certChainSize = len(val) if len(val) == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].certChainSize,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].certChain)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].certChain)), (_val_.ctypes.data), sizeof(unsigned char) * (self._ptr[0].certChainSize)) @property def attestation_cert_chain(self): """~_numpy.uint8: (array of length 5120).""" if self._ptr[0].attestationCertChainSize == 0: return _numpy.array([]) - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].attestationCertChainSize,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].attestationCertChain)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].attestationCertChain)), + (sizeof(unsigned char) * (self._ptr[0].attestationCertChainSize)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @attestation_cert_chain.setter def attestation_cert_chain(self, val): @@ -11745,9 +12059,8 @@ cdef class ConfComputeGpuCertificate: self._ptr[0].attestationCertChainSize = len(val) if len(val) == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].attestationCertChainSize,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].attestationCertChain)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].attestationCertChain)), (_val_.ctypes.data), sizeof(unsigned char) * (self._ptr[0].attestationCertChainSize)) @staticmethod def from_buffer(buffer): @@ -11888,9 +12201,12 @@ cdef class ConfComputeGpuAttestationReport: @property def nonce(self): """~_numpy.uint8: (array of length 32).""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].nonce)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].nonce)), + (sizeof(unsigned char) * (32)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @nonce.setter def nonce(self, val): @@ -11898,18 +12214,20 @@ cdef class ConfComputeGpuAttestationReport: raise ValueError("This ConfComputeGpuAttestationReport instance is read-only") if len(val) != 32: raise ValueError(f"Expected length { 32 } for field nonce, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(32,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].nonce)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].nonce)), (_val_.ctypes.data), sizeof(unsigned char) * (32)) @property def attestation_report(self): """~_numpy.uint8: (array of length 8192).""" if self._ptr[0].attestationReportSize == 0: return _numpy.array([]) - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].attestationReportSize,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].attestationReport)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].attestationReport)), + (sizeof(unsigned char) * (self._ptr[0].attestationReportSize)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @attestation_report.setter def attestation_report(self, val): @@ -11920,18 +12238,20 @@ cdef class ConfComputeGpuAttestationReport: self._ptr[0].attestationReportSize = len(val) if len(val) == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].attestationReportSize,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].attestationReport)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].attestationReport)), (_val_.ctypes.data), sizeof(unsigned char) * (self._ptr[0].attestationReportSize)) @property def cec_attestation_report(self): """~_numpy.uint8: (array of length 4096).""" if self._ptr[0].cecAttestationReportSize == 0: return _numpy.array([]) - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].cecAttestationReportSize,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].cecAttestationReport)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].cecAttestationReport)), + (sizeof(unsigned char) * (self._ptr[0].cecAttestationReportSize)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @cec_attestation_report.setter def cec_attestation_report(self, val): @@ -11942,9 +12262,8 @@ cdef class ConfComputeGpuAttestationReport: self._ptr[0].cecAttestationReportSize = len(val) if len(val) == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].cecAttestationReportSize,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].cecAttestationReport)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].cecAttestationReport)), (_val_.ctypes.data), sizeof(unsigned char) * (self._ptr[0].cecAttestationReportSize)) @staticmethod def from_buffer(buffer): @@ -12085,9 +12404,12 @@ cdef class GpuFabricInfo_v2: @property def cluster_uuid(self): """~_numpy.uint8: (array of length 16).Uuid of the cluster to which this GPU belongs.""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].clusterUuid)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].clusterUuid)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @cluster_uuid.setter def cluster_uuid(self, val): @@ -12095,9 +12417,8 @@ cdef class GpuFabricInfo_v2: raise ValueError("This GpuFabricInfo_v2 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field cluster_uuid, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].clusterUuid)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].clusterUuid)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def status(self): @@ -12281,9 +12602,12 @@ cdef class NvlinkSupportedBwModes_v1: """~_numpy.uint8: (array of length 23).""" if self._ptr[0].totalBwModes == 0: return _numpy.array([]) - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].totalBwModes,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].bwModes)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].bwModes)), + (sizeof(unsigned char) * (self._ptr[0].totalBwModes)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @bw_modes.setter def bw_modes(self, val): @@ -12294,9 +12618,8 @@ cdef class NvlinkSupportedBwModes_v1: self._ptr[0].totalBwModes = len(val) if len(val) == 0: return - cdef _cyb_view.array arr = _cyb_view.array(shape=(self._ptr[0].totalBwModes,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].bwModes)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].bwModes)), (_val_.ctypes.data), sizeof(unsigned char) * (self._ptr[0].totalBwModes)) @staticmethod def from_buffer(buffer): @@ -13204,7 +13527,10 @@ cdef class GpuInstancePlacement: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=gpu_instance_placement_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=gpu_instance_placement_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlGpuInstancePlacement_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlGpuInstancePlacement_t) }" @@ -13224,9 +13550,10 @@ cdef class GpuInstancePlacement: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -13640,7 +13967,10 @@ cdef class ComputeInstancePlacement: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=compute_instance_placement_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=compute_instance_placement_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlComputeInstancePlacement_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlComputeInstancePlacement_t) }" @@ -13660,9 +13990,10 @@ cdef class ComputeInstancePlacement: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -14777,7 +15108,10 @@ cdef class EccSramUniqueUncorrectedErrorEntry_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=ecc_sram_unique_uncorrected_error_entry_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=ecc_sram_unique_uncorrected_error_entry_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlEccSramUniqueUncorrectedErrorEntry_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlEccSramUniqueUncorrectedErrorEntry_v1_t) }" @@ -14797,9 +15131,10 @@ cdef class EccSramUniqueUncorrectedErrorEntry_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -15059,9 +15394,12 @@ cdef class GpuFabricInfo_v3: @property def cluster_uuid(self): """~_numpy.uint8: (array of length 16).Uuid of the cluster to which this GPU belongs.""" - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) - arr.data = (&(self._ptr[0].clusterUuid)) - return _numpy.asarray(arr) + cdef object _mv_ = _cyb_PyMemoryView_FromMemory( + (&(self._ptr[0].clusterUuid)), + (sizeof(unsigned char) * (16)), + _cyb_cpython_buffer.PyBUF_WRITE if not self._readonly else _cyb_cpython_buffer.PyBUF_READ, + ) + return _numpy.frombuffer(_mv_, dtype=_numpy.uint8) @cluster_uuid.setter def cluster_uuid(self, val): @@ -15069,9 +15407,8 @@ cdef class GpuFabricInfo_v3: raise ValueError("This GpuFabricInfo_v3 instance is read-only") if len(val) != 16: raise ValueError(f"Expected length { 16 } for field cluster_uuid, got {len(val)}") - cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(unsigned char), format="B", mode="c") - arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) - _cyb_memcpy((&(self._ptr[0].clusterUuid)), (arr.data), sizeof(unsigned char) * len(val)) + _val_ = _numpy.ascontiguousarray(_numpy.asarray(val, dtype=_numpy.uint8)) + _cyb_memcpy((&(self._ptr[0].clusterUuid)), (_val_.ctypes.data), sizeof(unsigned char) * (16)) @property def status(self): @@ -15343,7 +15680,10 @@ cdef class NvlinkFirmwareVersion: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=nvlink_firmware_version_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=nvlink_firmware_version_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlNvlinkFirmwareVersion_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlNvlinkFirmwareVersion_t) }" @@ -15363,9 +15703,10 @@ cdef class NvlinkFirmwareVersion: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -15825,7 +16166,10 @@ cdef class VgpuSchedulerLogEntry_v2: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_scheduler_log_entry_v2_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_scheduler_log_entry_v2_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlVgpuSchedulerLogEntry_v2_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuSchedulerLogEntry_v2_t) }" @@ -15845,9 +16189,10 @@ cdef class VgpuSchedulerLogEntry_v2: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -17388,7 +17733,10 @@ cdef class Sample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=sample_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlSample_t) }" @@ -17408,9 +17756,10 @@ cdef class Sample: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -17547,7 +17896,10 @@ cdef class VgpuInstanceUtilizationSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_instance_utilization_sample_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_instance_utilization_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlVgpuInstanceUtilizationSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuInstanceUtilizationSample_t) }" @@ -17567,9 +17919,10 @@ cdef class VgpuInstanceUtilizationSample: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -17746,7 +18099,10 @@ cdef class VgpuInstanceUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_instance_utilization_info_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=vgpu_instance_utilization_info_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlVgpuInstanceUtilizationInfo_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlVgpuInstanceUtilizationInfo_v1_t) }" @@ -17766,9 +18122,10 @@ cdef class VgpuInstanceUtilizationInfo_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -17962,7 +18319,10 @@ cdef class FieldValue: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=field_value_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=field_value_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlFieldValue_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlFieldValue_t) }" @@ -17982,9 +18342,10 @@ cdef class FieldValue: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -19597,7 +19958,10 @@ cdef class GridLicensableFeature: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=grid_licensable_feature_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=grid_licensable_feature_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlGridLicensableFeature_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlGridLicensableFeature_t) }" @@ -19617,9 +19981,10 @@ cdef class GridLicensableFeature: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -21367,7 +21732,10 @@ cdef class PRMCounter_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=prm_counter_v1_dtype) + # Zero-initialized (not _numpy.empty): the caller may not set every + # field (e.g. reserved/padding members the wrapper doesn't expose), + # and many C APIs require unset bytes to be zero rather than garbage. + arr = _numpy.zeros(size, dtype=prm_counter_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPRMCounter_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPRMCounter_v1_t) }" @@ -21387,9 +21755,10 @@ cdef class PRMCounter_v1: return self._data.ctypes.data def __int__(self): - if self._data.size > 1: - raise TypeError("int() argument must be a bytes-like object of size 1. " - "To get the pointer address of an array, use .ptr") + if self._data.size > 1 and not self._data.flags["C_CONTIGUOUS"]: + raise TypeError("int() argument must be a bytes-like object of size 1, or a " + "C-contiguous array. To get the pointer address of a " + "non-contiguous array, use .ptr") return self._data.ctypes.data def __len__(self): @@ -22909,14 +23278,40 @@ cpdef object system_get_hic_version(): check_status_size(__status__) cdef HwbcEntry hwbc_entries = HwbcEntry(hwbc_count[0]) cdef nvmlHwbcEntry_t *hwbc_entries_ptr = (hwbc_entries._get_ptr()) - if hwbc_count[0] == 0: - return hwbc_entries - with nogil: - __status__ = nvmlSystemGetHicVersion(hwbc_count, hwbc_entries_ptr) - check_status(__status__) + if hwbc_count[0] != 0: + with nogil: + __status__ = nvmlSystemGetHicVersion(hwbc_count, hwbc_entries_ptr) + check_status(__status__) return hwbc_entries +cpdef object system_get_topology_gpu_set(unsigned int cpu_number): + """Retrieve the set of GPUs that have a CPU affinity with the given CPU number For all products. Supported on Linux only. + + Args: + cpu_number (unsigned int): The CPU number. + + Returns: + intptr_t: An array of device handles for GPUs found with + affinity to ``cpu_number``. + + .. seealso:: `nvmlSystemGetTopologyGpuSet` + """ + cdef unsigned int[1] count = [0] + with nogil: + __status__ = nvmlSystemGetTopologyGpuSet(cpu_number, count, NULL) + check_status_size(__status__) + cdef object _device_array_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.intp) + cdef intptr_t _device_array_data_ = _device_array_alloc_.ctypes.data + cdef intptr_t *device_array_ptr = _device_array_data_ + cdef object device_array = _device_array_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlSystemGetTopologyGpuSet(cpu_number, count, device_array_ptr) + check_status(__status__) + return device_array + + cpdef unsigned int unit_get_count() except? 0: """Retrieves the number of units in the system. @@ -23052,9 +23447,36 @@ cpdef object unit_get_fan_speed_info(intptr_t unit): return fan_speeds_py -cpdef unsigned int device_get_count_v2() except? 0: - """Retrieves the number of compute devices in the system. A compute device is a single GPU. - +cpdef object unit_get_devices(intptr_t unit): + """Retrieves the set of GPU devices that are attached to the specified unit. + + Args: + unit (intptr_t): The identifier of the target unit. + + Returns: + intptr_t: Reference in which to return the references to the + attached GPU devices. + + .. seealso:: `nvmlUnitGetDevices` + """ + cdef unsigned int[1] device_count = [0] + with nogil: + __status__ = nvmlUnitGetDevices(unit, device_count, NULL) + check_status_size(__status__) + cdef object _devices_alloc_ = _numpy.empty(max(device_count[0], 1), dtype=_numpy.intp) + cdef intptr_t _devices_data_ = _devices_alloc_.ctypes.data + cdef intptr_t *devices_ptr = _devices_data_ + cdef object devices = _devices_alloc_[:device_count[0]] + if device_count[0] != 0: + with nogil: + __status__ = nvmlUnitGetDevices(unit, device_count, devices_ptr) + check_status(__status__) + return devices + + +cpdef unsigned int device_get_count_v2() except? 0: + """Retrieves the number of compute devices in the system. A compute device is a single GPU. + Returns: unsigned int: Reference in which to return the number of accessible devices. @@ -23307,10 +23729,10 @@ cpdef object device_get_memory_affinity(intptr_t device, unsigned int node_set_s .. seealso:: `nvmlDeviceGetMemoryAffinity` """ - if node_set_size == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned long), format="L", mode="c")[:0] - cdef _cyb_view.array node_set = _cyb_view.array(shape=(node_set_size,), itemsize=sizeof(unsigned long), format="L", mode="c") - cdef unsigned long *node_set_ptr = (node_set.data) + cdef object _node_set_alloc_ = _numpy.empty(max(node_set_size, 1), dtype=_numpy.uint32) + cdef intptr_t _node_set_data_ = _node_set_alloc_.ctypes.data + cdef unsigned long *node_set_ptr = _node_set_data_ + cdef object node_set = _node_set_alloc_[:node_set_size] with nogil: __status__ = nvmlDeviceGetMemoryAffinity(device, node_set_size, node_set_ptr, scope) check_status(__status__) @@ -23333,10 +23755,10 @@ cpdef object device_get_cpu_affinity_within_scope(intptr_t device, unsigned int .. seealso:: `nvmlDeviceGetCpuAffinityWithinScope` """ - if cpu_set_size == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned long), format="L", mode="c")[:0] - cdef _cyb_view.array cpu_set = _cyb_view.array(shape=(cpu_set_size,), itemsize=sizeof(unsigned long), format="L", mode="c") - cdef unsigned long *cpu_set_ptr = (cpu_set.data) + cdef object _cpu_set_alloc_ = _numpy.empty(max(cpu_set_size, 1), dtype=_numpy.uint32) + cdef intptr_t _cpu_set_data_ = _cpu_set_alloc_.ctypes.data + cdef unsigned long *cpu_set_ptr = _cpu_set_data_ + cdef object cpu_set = _cpu_set_alloc_[:cpu_set_size] with nogil: __status__ = nvmlDeviceGetCpuAffinityWithinScope(device, cpu_set_size, cpu_set_ptr, scope) check_status(__status__) @@ -23358,10 +23780,10 @@ cpdef object device_get_cpu_affinity(intptr_t device, unsigned int cpu_set_size) .. seealso:: `nvmlDeviceGetCpuAffinity` """ - if cpu_set_size == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned long), format="L", mode="c")[:0] - cdef _cyb_view.array cpu_set = _cyb_view.array(shape=(cpu_set_size,), itemsize=sizeof(unsigned long), format="L", mode="c") - cdef unsigned long *cpu_set_ptr = (cpu_set.data) + cdef object _cpu_set_alloc_ = _numpy.empty(max(cpu_set_size, 1), dtype=_numpy.uint32) + cdef intptr_t _cpu_set_data_ = _cpu_set_alloc_.ctypes.data + cdef unsigned long *cpu_set_ptr = _cpu_set_data_ + cdef object cpu_set = _cpu_set_alloc_[:cpu_set_size] with nogil: __status__ = nvmlDeviceGetCpuAffinity(device, cpu_set_size, cpu_set_ptr) check_status(__status__) @@ -23431,6 +23853,35 @@ cpdef int device_get_topology_common_ancestor(intptr_t device1, intptr_t device2 return path_info +cpdef object device_get_topology_nearest_gpus(intptr_t device, int level): + """Retrieve the set of GPUs that are nearest to a given device at a specific interconnectivity level For all products. Supported on Linux only. + + Args: + device (intptr_t): The identifier of the first device. + level (GpuTopologyLevel): The ``nvmlGpuTopologyLevel_t`` level + to search for other GPUs. + + Returns: + intptr_t: An array of device handles for GPUs found at + ``level``. + + .. seealso:: `nvmlDeviceGetTopologyNearestGpus` + """ + cdef unsigned int[1] count = [0] + with nogil: + __status__ = nvmlDeviceGetTopologyNearestGpus(device, <_GpuTopologyLevel>level, count, NULL) + check_status_size(__status__) + cdef object _device_array_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.intp) + cdef intptr_t _device_array_data_ = _device_array_alloc_.ctypes.data + cdef intptr_t *device_array_ptr = _device_array_data_ + cdef object device_array = _device_array_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetTopologyNearestGpus(device, <_GpuTopologyLevel>level, count, device_array_ptr) + check_status(__status__) + return device_array + + cpdef int device_get_p2p_status(intptr_t device1, intptr_t device2, int p2p_index) except? -1: """Retrieve the status for a given p2p capability index between a given pair of GPU. @@ -23945,13 +24396,14 @@ cpdef object device_get_supported_memory_clocks(intptr_t device): with nogil: __status__ = nvmlDeviceGetSupportedMemoryClocks(device, count, NULL) check_status_size(__status__) - if count[0] == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef _cyb_view.array clocks_m_hz = _cyb_view.array(shape=(count[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - cdef unsigned int *clocks_m_hz_ptr = (clocks_m_hz.data) - with nogil: - __status__ = nvmlDeviceGetSupportedMemoryClocks(device, count, clocks_m_hz_ptr) - check_status(__status__) + cdef object _clocks_m_hz_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _clocks_m_hz_data_ = _clocks_m_hz_alloc_.ctypes.data + cdef unsigned int *clocks_m_hz_ptr = _clocks_m_hz_data_ + cdef object clocks_m_hz = _clocks_m_hz_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetSupportedMemoryClocks(device, count, clocks_m_hz_ptr) + check_status(__status__) return clocks_m_hz @@ -23972,13 +24424,14 @@ cpdef object device_get_supported_graphics_clocks(intptr_t device, unsigned int with nogil: __status__ = nvmlDeviceGetSupportedGraphicsClocks(device, memory_clock_m_hz, count, NULL) check_status_size(__status__) - if count[0] == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef _cyb_view.array clocks_m_hz = _cyb_view.array(shape=(count[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - cdef unsigned int *clocks_m_hz_ptr = (clocks_m_hz.data) - with nogil: - __status__ = nvmlDeviceGetSupportedGraphicsClocks(device, memory_clock_m_hz, count, clocks_m_hz_ptr) - check_status(__status__) + cdef object _clocks_m_hz_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _clocks_m_hz_data_ = _clocks_m_hz_alloc_.ctypes.data + cdef unsigned int *clocks_m_hz_ptr = _clocks_m_hz_data_ + cdef object clocks_m_hz = _clocks_m_hz_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetSupportedGraphicsClocks(device, memory_clock_m_hz, count, clocks_m_hz_ptr) + check_status(__status__) return clocks_m_hz @@ -24373,7 +24826,7 @@ cpdef tuple device_get_mem_clk_min_max_vf_offset(intptr_t device): return (min_offset, max_offset) -cpdef device_set_clock_offsets(intptr_t device, intptr_t info): +cpdef device_set_clock_offsets(intptr_t device, info): """Control current clock offset of some clock domain for a given PState. Args: @@ -24383,8 +24836,9 @@ cpdef device_set_clock_offsets(intptr_t device, intptr_t info): .. seealso:: `nvmlDeviceSetClockOffsets` """ + cdef intptr_t _info_ptr_ = int(info) with nogil: - __status__ = nvmlDeviceSetClockOffsets(device, info) + __status__ = nvmlDeviceSetClockOffsets(device, _info_ptr_) check_status(__status__) @@ -24829,11 +25283,10 @@ cpdef object device_get_encoder_sessions(intptr_t device): check_status_size(__status__) cdef EncoderSessionInfo session_infos = EncoderSessionInfo(session_count[0]) cdef nvmlEncoderSessionInfo_t *session_infos_ptr = (session_infos._get_ptr()) - if session_count[0] == 0: - return session_infos - with nogil: - __status__ = nvmlDeviceGetEncoderSessions(device, session_count, session_infos_ptr) - check_status(__status__) + if session_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetEncoderSessions(device, session_count, session_infos_ptr) + check_status(__status__) return session_infos @@ -24947,11 +25400,10 @@ cpdef object device_get_fbc_sessions(intptr_t device): check_status_size(__status__) cdef FBCSessionInfo session_info = FBCSessionInfo(session_count[0]) cdef nvmlFBCSessionInfo_t *session_info_ptr = (session_info._get_ptr()) - if session_count[0] == 0: - return session_info - with nogil: - __status__ = nvmlDeviceGetFBCSessions(device, session_count, session_info_ptr) - check_status(__status__) + if session_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetFBCSessions(device, session_count, session_info_ptr) + check_status(__status__) return session_info @@ -25034,11 +25486,10 @@ cpdef object device_get_compute_running_processes_v3(intptr_t device): check_status_size(__status__) cdef ProcessInfo infos = ProcessInfo(info_count[0]) cdef nvmlProcessInfo_t *infos_ptr = (infos._get_ptr()) - if info_count[0] == 0: - return infos - with nogil: - __status__ = nvmlDeviceGetComputeRunningProcesses_v3(device, info_count, infos_ptr) - check_status(__status__) + if info_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetComputeRunningProcesses_v3(device, info_count, infos_ptr) + check_status(__status__) return infos @@ -25060,11 +25511,10 @@ cpdef object device_get_graphics_running_processes_v3(intptr_t device): check_status_size(__status__) cdef ProcessInfo infos = ProcessInfo(info_count[0]) cdef nvmlProcessInfo_t *infos_ptr = (infos._get_ptr()) - if info_count[0] == 0: - return infos - with nogil: - __status__ = nvmlDeviceGetGraphicsRunningProcesses_v3(device, info_count, infos_ptr) - check_status(__status__) + if info_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetGraphicsRunningProcesses_v3(device, info_count, infos_ptr) + check_status(__status__) return infos @@ -25086,11 +25536,10 @@ cpdef object device_get_mps_compute_running_processes_v3(intptr_t device): check_status_size(__status__) cdef ProcessInfo infos = ProcessInfo(info_count[0]) cdef nvmlProcessInfo_t *infos_ptr = (infos._get_ptr()) - if info_count[0] == 0: - return infos - with nogil: - __status__ = nvmlDeviceGetMPSComputeRunningProcesses_v3(device, info_count, infos_ptr) - check_status(__status__) + if info_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetMPSComputeRunningProcesses_v3(device, info_count, infos_ptr) + check_status(__status__) return infos @@ -25136,6 +25585,38 @@ cpdef int device_get_api_restriction(intptr_t device, int api_type) except? -1: return is_restricted +cpdef tuple device_get_samples(intptr_t device, int type, unsigned long long last_seen_time_stamp): + """Gets recent samples for the GPU. + + Args: + device (intptr_t): The identifier for the target device. + type (SamplingType): Type of sampling event. + last_seen_time_stamp (unsigned long long): Return only samples + with timestamp greater than last_seen_time_stamp. + + Returns: + A 2-tuple containing: + + - int: Output parameter to represent the type of sample value as + described in nvmlSampleVal_t. + - nvmlSample_t: Reference in which samples are returned. + + .. seealso:: `nvmlDeviceGetSamples` + """ + cdef _ValueType sample_val_type + cdef unsigned int[1] sample_count = [0] + with nogil: + __status__ = nvmlDeviceGetSamples(device, <_SamplingType>type, last_seen_time_stamp, &sample_val_type, sample_count, NULL) + check_status_size(__status__) + cdef Sample samples = Sample(sample_count[0]) + cdef nvmlSample_t *samples_ptr = (samples._get_ptr()) + if not (sample_count[0] == 0): + with nogil: + __status__ = nvmlDeviceGetSamples(device, <_SamplingType>type, last_seen_time_stamp, &sample_val_type, sample_count, samples_ptr) + check_status(__status__) + return (sample_val_type, samples) + + cpdef object device_get_bar1_memory_info(intptr_t device): """Gets Total, Available and Used size of BAR1 memory. @@ -25576,13 +26057,14 @@ cpdef object device_get_accounting_pids(intptr_t device): with nogil: __status__ = nvmlDeviceGetAccountingPids(device, count, NULL) check_status_size(__status__) - if count[0] == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef _cyb_view.array pids = _cyb_view.array(shape=(count[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - cdef unsigned int *pids_ptr = (pids.data) - with nogil: - __status__ = nvmlDeviceGetAccountingPids(device, count, pids_ptr) - check_status(__status__) + cdef object _pids_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _pids_data_ = _pids_alloc_.ctypes.data + cdef unsigned int *pids_ptr = _pids_data_ + cdef object pids = _pids_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetAccountingPids(device, count, pids_ptr) + check_status(__status__) return pids @@ -25623,16 +26105,53 @@ cpdef object device_get_retired_pages(intptr_t device, int cause): with nogil: __status__ = nvmlDeviceGetRetiredPages(device, <_PageRetirementCause>cause, page_count, NULL) check_status_size(__status__) - if page_count[0] == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned long long), format="Q", mode="c")[:0] - cdef _cyb_view.array addresses = _cyb_view.array(shape=(page_count[0],), itemsize=sizeof(unsigned long long), format="Q", mode="c") - cdef unsigned long long *addresses_ptr = (addresses.data) - with nogil: - __status__ = nvmlDeviceGetRetiredPages(device, <_PageRetirementCause>cause, page_count, addresses_ptr) - check_status(__status__) + cdef object _addresses_alloc_ = _numpy.empty(max(page_count[0], 1), dtype=_numpy.uint64) + cdef intptr_t _addresses_data_ = _addresses_alloc_.ctypes.data + cdef unsigned long long *addresses_ptr = _addresses_data_ + cdef object addresses = _addresses_alloc_[:page_count[0]] + if page_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetRetiredPages(device, <_PageRetirementCause>cause, page_count, addresses_ptr) + check_status(__status__) return addresses +cpdef tuple device_get_retired_pages_v2(intptr_t device, int cause): + """Returns the list of retired pages by source, including pages that are pending retirement The address information provided from this API is the hardware address of the page that was retired. Note that this does not match the virtual address used in CUDA, but will match the address information in Xid 63. + + Args: + device (intptr_t): The identifier of the target device. + cause (PageRetirementCause): Filter page addresses by cause of + retirement. + + Returns: + A 2-tuple containing: + + - unsigned long long: Buffer to write the page addresses into. + - unsigned long long: Buffer to write the timestamps of page + retirement, additional for _v2. + + .. seealso:: `nvmlDeviceGetRetiredPages_v2` + """ + cdef unsigned int[1] page_count = [0] + with nogil: + __status__ = nvmlDeviceGetRetiredPages_v2(device, <_PageRetirementCause>cause, page_count, NULL, NULL) + check_status_size(__status__) + cdef object _addresses_alloc_ = _numpy.empty(max(page_count[0], 1), dtype=_numpy.uint64) + cdef intptr_t _addresses_data_ = _addresses_alloc_.ctypes.data + cdef unsigned long long *addresses_ptr = _addresses_data_ + cdef object addresses = _addresses_alloc_[:page_count[0]] + cdef object _timestamps_alloc_ = _numpy.empty(max(page_count[0], 1), dtype=_numpy.uint64) + cdef intptr_t _timestamps_data_ = _timestamps_alloc_.ctypes.data + cdef unsigned long long *timestamps_ptr = _timestamps_data_ + cdef object timestamps = _timestamps_alloc_[:page_count[0]] + if not (page_count[0] == 0): + with nogil: + __status__ = nvmlDeviceGetRetiredPages_v2(device, <_PageRetirementCause>cause, page_count, addresses_ptr, timestamps_ptr) + check_status(__status__) + return (addresses, timestamps) + + cpdef int device_get_retired_pages_pending_status(intptr_t device) except? -1: """Check if any pages are pending retirement and need a reboot to fully retire. @@ -25760,11 +26279,10 @@ cpdef object device_get_process_utilization(intptr_t device, unsigned long long check_status_size(__status__) cdef ProcessUtilizationSample utilization = ProcessUtilizationSample(process_samples_count[0]) cdef nvmlProcessUtilizationSample_t *utilization_ptr = (utilization._get_ptr()) - if process_samples_count[0] == 0: - return utilization - with nogil: - __status__ = nvmlDeviceGetProcessUtilization(device, utilization_ptr, process_samples_count, last_seen_time_stamp) - check_status(__status__) + if process_samples_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetProcessUtilization(device, utilization_ptr, process_samples_count, last_seen_time_stamp) + check_status(__status__) return utilization @@ -26257,7 +26775,7 @@ cpdef object device_get_nvlink_bw_mode(intptr_t device): return get_bw_mode_py -cpdef device_set_nvlink_bw_mode(intptr_t device, intptr_t set_bw_mode): +cpdef device_set_nvlink_bw_mode(intptr_t device, set_bw_mode): """Set the NvLink Reduced Bandwidth Mode for the device. Args: @@ -26267,9 +26785,10 @@ cpdef device_set_nvlink_bw_mode(intptr_t device, intptr_t set_bw_mode): .. seealso:: `nvmlDeviceSetNvlinkBwMode` """ + cdef intptr_t _set_bw_mode_ptr_ = int(set_bw_mode) set_bw_mode.version = NVML_VERSION_STRUCT(sizeof(nvmlNvlinkSetBwMode_v1_t), 1) with nogil: - __status__ = nvmlDeviceSetNvlinkBwMode(device, set_bw_mode) + __status__ = nvmlDeviceSetNvlinkBwMode(device, _set_bw_mode_ptr_) check_status(__status__) @@ -26357,7 +26876,7 @@ cpdef event_set_free(intptr_t set): check_status(__status__) -cpdef device_modify_drain_state(intptr_t pci_info, int new_state): +cpdef device_modify_drain_state(pci_info, int new_state): """Modify the drain state of a GPU. This method forces a GPU to no longer accept new incoming requests. Any new NVML process will no longer see this GPU. Persistence mode for this GPU must be turned off before this call is made. Must be called as administrator. For Linux only. Args: @@ -26368,12 +26887,13 @@ cpdef device_modify_drain_state(intptr_t pci_info, int new_state): .. seealso:: `nvmlDeviceModifyDrainState` """ + cdef intptr_t _pci_info_ptr_ = int(pci_info) with nogil: - __status__ = nvmlDeviceModifyDrainState(pci_info, <_EnableState>new_state) + __status__ = nvmlDeviceModifyDrainState(_pci_info_ptr_, <_EnableState>new_state) check_status(__status__) -cpdef int device_query_drain_state(intptr_t pci_info) except? -1: +cpdef int device_query_drain_state(pci_info) except? -1: """Query the drain state of a GPU. This method is used to check if a GPU is in a currently draining state. For Linux only. Args: @@ -26386,14 +26906,15 @@ cpdef int device_query_drain_state(intptr_t pci_info) except? -1: .. seealso:: `nvmlDeviceQueryDrainState` """ + cdef intptr_t _pci_info_ptr_ = int(pci_info) cdef _EnableState current_state with nogil: - __status__ = nvmlDeviceQueryDrainState(pci_info, ¤t_state) + __status__ = nvmlDeviceQueryDrainState(_pci_info_ptr_, ¤t_state) check_status(__status__) return current_state -cpdef device_remove_gpu_v2(intptr_t pci_info, int gpu_state, int link_state): +cpdef device_remove_gpu_v2(pci_info, int gpu_state, int link_state): """This method will remove the specified GPU from the view of both NVML and the NVIDIA kernel driver as long as no other processes are attached. If other processes are attached, this call will return NVML_ERROR_IN_USE and the GPU will be returned to its original "draining" state. Note: the only situation where a process can still be attached after :func:`device_modify_drain_state` is called to initiate the draining state is if that process was using, and is still using, a GPU before the call was made. Also note, persistence mode counts as an attachment to the GPU thus it must be disabled prior to this call. Args: @@ -26405,12 +26926,13 @@ cpdef device_remove_gpu_v2(intptr_t pci_info, int gpu_state, int link_state): .. seealso:: `nvmlDeviceRemoveGpu_v2` """ + cdef intptr_t _pci_info_ptr_ = int(pci_info) with nogil: - __status__ = nvmlDeviceRemoveGpu_v2(pci_info, <_DetachGpuState>gpu_state, <_PcieLinkState>link_state) + __status__ = nvmlDeviceRemoveGpu_v2(_pci_info_ptr_, <_DetachGpuState>gpu_state, <_PcieLinkState>link_state) check_status(__status__) -cpdef device_discover_gpus(intptr_t pci_info): +cpdef device_discover_gpus(pci_info): """Request the OS and the NVIDIA kernel driver to rediscover a portion of the PCI subsystem looking for GPUs that were previously removed. The portion of the PCI tree can be narrowed by specifying a domain, bus, and device. If all are zeroes then the entire PCI tree will be searched. Please note that for long-running NVML processes the enumeration will change based on how many GPUs are discovered and where they are inserted in bus order. Args: @@ -26419,8 +26941,9 @@ cpdef device_discover_gpus(intptr_t pci_info): .. seealso:: `nvmlDeviceDiscoverGpus` """ + cdef intptr_t _pci_info_ptr_ = int(pci_info) with nogil: - __status__ = nvmlDeviceDiscoverGpus(pci_info) + __status__ = nvmlDeviceDiscoverGpus(_pci_info_ptr_) check_status(__status__) @@ -26591,6 +27114,60 @@ cpdef unsigned int device_get_vgpu_capabilities(intptr_t device, int capability) return cap_result +cpdef object device_get_supported_vgpus(intptr_t device): + """Retrieve the supported vGPU types on a physical GPU (device). + + Args: + device (intptr_t): The identifier of the target device. + + Returns: + unsigned int: Pointer to caller-supplied array in which to + return list of vGPU types. + + .. seealso:: `nvmlDeviceGetSupportedVgpus` + """ + cdef unsigned int[1] vgpu_count = [0] + with nogil: + __status__ = nvmlDeviceGetSupportedVgpus(device, vgpu_count, NULL) + check_status_size(__status__) + cdef object _vgpu_type_ids_alloc_ = _numpy.empty(max(vgpu_count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _vgpu_type_ids_data_ = _vgpu_type_ids_alloc_.ctypes.data + cdef nvmlVgpuTypeId_t *vgpu_type_ids_ptr = _vgpu_type_ids_data_ + cdef object vgpu_type_ids = _vgpu_type_ids_alloc_[:vgpu_count[0]] + if vgpu_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetSupportedVgpus(device, vgpu_count, vgpu_type_ids_ptr) + check_status(__status__) + return vgpu_type_ids + + +cpdef object device_get_creatable_vgpus(intptr_t device): + """Retrieve the currently creatable vGPU types on a physical GPU (device). + + Args: + device (intptr_t): The identifier of the target device. + + Returns: + unsigned int: Pointer to caller-supplied array in which to + return list of vGPU types. + + .. seealso:: `nvmlDeviceGetCreatableVgpus` + """ + cdef unsigned int[1] vgpu_count = [0] + with nogil: + __status__ = nvmlDeviceGetCreatableVgpus(device, vgpu_count, NULL) + check_status_size(__status__) + cdef object _vgpu_type_ids_alloc_ = _numpy.empty(max(vgpu_count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _vgpu_type_ids_data_ = _vgpu_type_ids_alloc_.ctypes.data + cdef nvmlVgpuTypeId_t *vgpu_type_ids_ptr = _vgpu_type_ids_data_ + cdef object vgpu_type_ids = _vgpu_type_ids_alloc_[:vgpu_count[0]] + if vgpu_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetCreatableVgpus(device, vgpu_count, vgpu_type_ids_ptr) + check_status(__status__) + return vgpu_type_ids + + cpdef str vgpu_type_get_class(unsigned int vgpu_type_id): """Retrieve the class of a vGPU type. It will not exceed 64 characters in length (including the NUL terminator). See nvmlConstants::NVML_DEVICE_NAME_BUFFER_SIZE. @@ -26606,13 +27183,12 @@ cpdef str vgpu_type_get_class(unsigned int vgpu_type_id): with nogil: __status__ = nvmlVgpuTypeGetClass(vgpu_type_id, NULL, size) check_status_size(__status__) - if size[0] == 0: - return "" cdef bytes _vgpu_type_class_ = bytes(size[0]) cdef char* vgpu_type_class = _vgpu_type_class_ - with nogil: - __status__ = nvmlVgpuTypeGetClass(vgpu_type_id, vgpu_type_class, size) - check_status(__status__) + if size[0] != 0: + with nogil: + __status__ = nvmlVgpuTypeGetClass(vgpu_type_id, vgpu_type_class, size) + check_status(__status__) return _cyb_cpython.PyUnicode_FromString(vgpu_type_class) @@ -26817,6 +27393,57 @@ cpdef object vgpu_type_get_bar1_info(unsigned int vgpu_type_id): return bar1info_py +cpdef object device_get_active_vgpus(intptr_t device): + """Retrieve the active vGPU instances on a device. + + Args: + device (intptr_t): The identifier of the target device. + + Returns: + unsigned int: Pointer to array in which to return list of vGPU + instances. + + .. seealso:: `nvmlDeviceGetActiveVgpus` + """ + cdef unsigned int[1] vgpu_count = [0] + with nogil: + __status__ = nvmlDeviceGetActiveVgpus(device, vgpu_count, NULL) + check_status_size(__status__) + cdef object _vgpu_instances_alloc_ = _numpy.empty(max(vgpu_count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _vgpu_instances_data_ = _vgpu_instances_alloc_.ctypes.data + cdef nvmlVgpuInstance_t *vgpu_instances_ptr = _vgpu_instances_data_ + cdef object vgpu_instances = _vgpu_instances_alloc_[:vgpu_count[0]] + if vgpu_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetActiveVgpus(device, vgpu_count, vgpu_instances_ptr) + check_status(__status__) + return vgpu_instances + + +cpdef tuple vgpu_instance_get_vm_id(unsigned int vgpu_instance): + """Retrieve the VM ID associated with a vGPU instance. + + Args: + vgpu_instance (unsigned int): Identifier of the target vGPU + instance. + + Returns: + A 2-tuple containing: + + - char: Pointer to caller-supplied buffer to hold VM ID. + - int: Pointer to hold VM ID type. + + .. seealso:: `nvmlVgpuInstanceGetVmID` + """ + cdef unsigned int size = 80 + cdef char[80] vm_id + cdef _VgpuVmIdType vm_id_type + with nogil: + __status__ = nvmlVgpuInstanceGetVmID(vgpu_instance, vm_id, size, &vm_id_type) + check_status(__status__) + return (_cyb_cpython.PyUnicode_FromString(vm_id), vm_id_type) + + cpdef str vgpu_instance_get_uuid(unsigned int vgpu_instance): """Retrieve the UUID of a vGPU instance. @@ -27035,11 +27662,10 @@ cpdef object vgpu_instance_get_encoder_sessions(unsigned int vgpu_instance): check_status_size(__status__) cdef EncoderSessionInfo session_info = EncoderSessionInfo(session_count[0]) cdef nvmlEncoderSessionInfo_t *session_info_ptr = (session_info._get_ptr()) - if session_count[0] == 0: - return session_info - with nogil: - __status__ = nvmlVgpuInstanceGetEncoderSessions(vgpu_instance, session_count, session_info_ptr) - check_status(__status__) + if session_count[0] != 0: + with nogil: + __status__ = nvmlVgpuInstanceGetEncoderSessions(vgpu_instance, session_count, session_info_ptr) + check_status(__status__) return session_info @@ -27083,11 +27709,10 @@ cpdef object vgpu_instance_get_fbc_sessions(unsigned int vgpu_instance): check_status_size(__status__) cdef FBCSessionInfo session_info = FBCSessionInfo(session_count[0]) cdef nvmlFBCSessionInfo_t *session_info_ptr = (session_info._get_ptr()) - if session_count[0] == 0: - return session_info - with nogil: - __status__ = nvmlVgpuInstanceGetFBCSessions(vgpu_instance, session_count, session_info_ptr) - check_status(__status__) + if session_count[0] != 0: + with nogil: + __status__ = nvmlVgpuInstanceGetFBCSessions(vgpu_instance, session_count, session_info_ptr) + check_status(__status__) return session_info @@ -27126,13 +27751,12 @@ cpdef str vgpu_instance_get_gpu_pci_id(unsigned int vgpu_instance): with nogil: __status__ = nvmlVgpuInstanceGetGpuPciId(vgpu_instance, NULL, length) check_status_size(__status__) - if length[0] == 0: - return "" cdef bytes _vgpu_pci_id_ = bytes(length[0]) cdef char* vgpu_pci_id = _vgpu_pci_id_ - with nogil: - __status__ = nvmlVgpuInstanceGetGpuPciId(vgpu_instance, vgpu_pci_id, length) - check_status(__status__) + if length[0] != 0: + with nogil: + __status__ = nvmlVgpuInstanceGetGpuPciId(vgpu_instance, vgpu_pci_id, length) + check_status(__status__) return _cyb_cpython.PyUnicode_FromString(vgpu_pci_id) @@ -27177,7 +27801,7 @@ cpdef str vgpu_instance_get_mdev_uuid(unsigned int vgpu_instance): return _cyb_cpython.PyUnicode_FromString(mdev_uuid) -cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, intptr_t p_scheduler): +cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, p_scheduler): """Set vGPU scheduler state for the given GPU instance. Args: @@ -27187,9 +27811,10 @@ cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, intptr_t p_sc .. seealso:: `nvmlGpuInstanceSetVgpuSchedulerState` """ + cdef intptr_t _p_scheduler_ptr_ = int(p_scheduler) (p_scheduler).version = NVML_VERSION_STRUCT(sizeof(nvmlVgpuSchedulerState_v1_t), 1) with nogil: - __status__ = nvmlGpuInstanceSetVgpuSchedulerState(gpu_instance, p_scheduler) + __status__ = nvmlGpuInstanceSetVgpuSchedulerState(gpu_instance, _p_scheduler_ptr_) check_status(__status__) @@ -27251,13 +27876,12 @@ cpdef str device_get_pgpu_metadata_string(intptr_t device): with nogil: __status__ = nvmlDeviceGetPgpuMetadataString(device, NULL, buffer_size) check_status_size(__status__) - if buffer_size[0] == 0: - return "" cdef bytes _pgpu_metadata_ = bytes(buffer_size[0]) cdef char* pgpu_metadata = _pgpu_metadata_ - with nogil: - __status__ = nvmlDeviceGetPgpuMetadataString(device, pgpu_metadata, buffer_size) - check_status(__status__) + if buffer_size[0] != 0: + with nogil: + __status__ = nvmlDeviceGetPgpuMetadataString(device, pgpu_metadata, buffer_size) + check_status(__status__) return _cyb_cpython.PyUnicode_FromString(pgpu_metadata) @@ -27336,7 +27960,32 @@ cpdef device_set_vgpu_scheduler_state(intptr_t device, intptr_t p_scheduler_stat check_status(__status__) -cpdef set_vgpu_version(intptr_t vgpu_version): +cpdef tuple get_vgpu_version(): + """Query the ranges of supported vGPU versions. + + Returns: + A 2-tuple containing: + + - nvmlVgpuVersion_t: Pointer to the structure in which the + preset range of vGPU versions supported by the NVIDIA vGPU + Manager is written. + - nvmlVgpuVersion_t: Pointer to the structure in which the range + of supported vGPU versions set by an administrator is + written. + + .. seealso:: `nvmlGetVgpuVersion` + """ + cdef VgpuVersion supported_py = VgpuVersion() + cdef nvmlVgpuVersion_t *supported = (supported_py._get_ptr()) + cdef VgpuVersion current_py = VgpuVersion() + cdef nvmlVgpuVersion_t *current = (current_py._get_ptr()) + with nogil: + __status__ = nvmlGetVgpuVersion(supported, current) + check_status(__status__) + return (supported_py, current_py) + + +cpdef set_vgpu_version(vgpu_version): """Override the preset range of vGPU versions supported by the NVIDIA vGPU Manager with a range set by an administrator. Args: @@ -27345,13 +27994,14 @@ cpdef set_vgpu_version(intptr_t vgpu_version): .. seealso:: `nvmlSetVgpuVersion` """ + cdef intptr_t _vgpu_version_ptr_ = int(vgpu_version) with nogil: - __status__ = nvmlSetVgpuVersion(vgpu_version) + __status__ = nvmlSetVgpuVersion(_vgpu_version_ptr_) check_status(__status__) -cpdef tuple device_get_vgpu_process_utilization(intptr_t device, unsigned long long last_seen_time_stamp): - """Retrieves current utilization for processes running on vGPUs on a physical GPU (device). +cpdef tuple device_get_vgpu_utilization(intptr_t device, unsigned long long last_seen_time_stamp): + """Retrieves current utilization for vGPUs on a physical GPU (device). Args: device (intptr_t): The identifier for the target device. @@ -27361,20 +28011,54 @@ cpdef tuple device_get_vgpu_process_utilization(intptr_t device, unsigned long l Returns: A 2-tuple containing: - - unsigned int: Pointer to caller-supplied array size, and - returns number of processes running on vGPU instances. - - nvmlVgpuProcessUtilizationSample_t: Pointer to caller-supplied + - int: Pointer to caller-supplied buffer to hold the type of + returned sample values. + - nvmlVgpuInstanceUtilizationSample_t: Pointer to caller- + supplied buffer in which vGPU utilization samples are + returned. + + .. seealso:: `nvmlDeviceGetVgpuUtilization` + """ + cdef _ValueType sample_val_type + cdef unsigned int[1] vgpu_instance_samples_count = [0] + with nogil: + __status__ = nvmlDeviceGetVgpuUtilization(device, last_seen_time_stamp, &sample_val_type, vgpu_instance_samples_count, NULL) + check_status_size(__status__) + cdef VgpuInstanceUtilizationSample utilization_samples = VgpuInstanceUtilizationSample(vgpu_instance_samples_count[0]) + cdef nvmlVgpuInstanceUtilizationSample_t *utilization_samples_ptr = (utilization_samples._get_ptr()) + if not (vgpu_instance_samples_count[0] == 0): + with nogil: + __status__ = nvmlDeviceGetVgpuUtilization(device, last_seen_time_stamp, &sample_val_type, vgpu_instance_samples_count, utilization_samples_ptr) + check_status(__status__) + return (sample_val_type, utilization_samples) + + +cpdef object device_get_vgpu_process_utilization(intptr_t device, unsigned long long last_seen_time_stamp): + """Retrieves current utilization for processes running on vGPUs on a physical GPU (device). + + Args: + device (intptr_t): The identifier for the target device. + last_seen_time_stamp (unsigned long long): Return only samples + with timestamp greater than last_seen_time_stamp. + + Returns: + nvmlVgpuProcessUtilizationSample_t: Pointer to caller-supplied buffer in which vGPU sub process utilization samples are returned. .. seealso:: `nvmlDeviceGetVgpuProcessUtilization` """ - cdef unsigned int vgpu_process_samples_count - cdef nvmlVgpuProcessUtilizationSample_t utilization_samples + cdef unsigned int[1] vgpu_process_samples_count = [0] with nogil: - __status__ = nvmlDeviceGetVgpuProcessUtilization(device, last_seen_time_stamp, &vgpu_process_samples_count, &utilization_samples) - check_status(__status__) - return (vgpu_process_samples_count, utilization_samples) + __status__ = nvmlDeviceGetVgpuProcessUtilization(device, last_seen_time_stamp, vgpu_process_samples_count, NULL) + check_status_size(__status__) + cdef VgpuProcessUtilizationSample utilization_samples = VgpuProcessUtilizationSample(vgpu_process_samples_count[0]) + cdef nvmlVgpuProcessUtilizationSample_t *utilization_samples_ptr = (utilization_samples._get_ptr()) + if vgpu_process_samples_count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetVgpuProcessUtilization(device, last_seen_time_stamp, vgpu_process_samples_count, utilization_samples_ptr) + check_status(__status__) + return utilization_samples cpdef int vgpu_instance_get_accounting_mode(unsigned int vgpu_instance) except? -1: @@ -27413,13 +28097,14 @@ cpdef object vgpu_instance_get_accounting_pids(unsigned int vgpu_instance): with nogil: __status__ = nvmlVgpuInstanceGetAccountingPids(vgpu_instance, count, NULL) check_status_size(__status__) - if count[0] == 0: - return _cyb_view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef _cyb_view.array pids = _cyb_view.array(shape=(count[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - cdef unsigned int *pids_ptr = (pids.data) - with nogil: - __status__ = nvmlVgpuInstanceGetAccountingPids(vgpu_instance, count, pids_ptr) - check_status(__status__) + cdef object _pids_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.uint32) + cdef intptr_t _pids_data_ = _pids_alloc_.ctypes.data + cdef unsigned int *pids_ptr = _pids_data_ + cdef object pids = _pids_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlVgpuInstanceGetAccountingPids(vgpu_instance, count, pids_ptr) + check_status(__status__) return pids @@ -27585,11 +28270,10 @@ cpdef object device_get_gpu_instance_possible_placements_v2(intptr_t device, uns check_status_size(__status__) cdef GpuInstancePlacement placements = GpuInstancePlacement(count[0]) cdef nvmlGpuInstancePlacement_t *placements_ptr = (placements._get_ptr()) - if count[0] == 0: - return placements - with nogil: - __status__ = nvmlDeviceGetGpuInstancePossiblePlacements_v2(device, profile_id, placements_ptr, count) - check_status(__status__) + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetGpuInstancePossiblePlacements_v2(device, profile_id, placements_ptr, count) + check_status(__status__) return placements @@ -27634,7 +28318,7 @@ cpdef intptr_t device_create_gpu_instance(intptr_t device, unsigned int profile_ return gpu_instance -cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsigned int profile_id, intptr_t placement) except? 0: +cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsigned int profile_id, placement) except? 0: """Create GPU instance with the specified placement. Args: @@ -27649,9 +28333,10 @@ cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsign .. seealso:: `nvmlDeviceCreateGpuInstanceWithPlacement` """ + cdef intptr_t _placement_ptr_ = int(placement) cdef GpuInstance gpu_instance with nogil: - __status__ = nvmlDeviceCreateGpuInstanceWithPlacement(device, profile_id, placement, &gpu_instance) + __status__ = nvmlDeviceCreateGpuInstanceWithPlacement(device, profile_id, _placement_ptr_, &gpu_instance) check_status(__status__) return gpu_instance @@ -27669,6 +28354,36 @@ cpdef gpu_instance_destroy(intptr_t gpu_instance): check_status(__status__) +cpdef object device_get_gpu_instances(intptr_t device, unsigned int profile_id): + """Get GPU instances for given profile ID. + + Args: + device (intptr_t): The identifier of the target device. + profile_id (unsigned int): The GPU instance profile ID. See + ``nvmlDeviceGetGpuInstanceProfileInfo``. + + Returns: + intptr_t: Returns pre-exiting GPU instances, the buffer must + be large enough to accommodate the instances supported by + the profile. See ``nvmlDeviceGetGpuInstanceProfileInfo``. + + .. seealso:: `nvmlDeviceGetGpuInstances` + """ + cdef unsigned int[1] count = [0] + with nogil: + __status__ = nvmlDeviceGetGpuInstances(device, profile_id, NULL, count) + check_status_size(__status__) + cdef object _gpu_instances_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.intp) + cdef intptr_t _gpu_instances_data_ = _gpu_instances_alloc_.ctypes.data + cdef intptr_t *gpu_instances_ptr = _gpu_instances_data_ + cdef object gpu_instances = _gpu_instances_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlDeviceGetGpuInstances(device, profile_id, gpu_instances_ptr, count) + check_status(__status__) + return gpu_instances + + cpdef intptr_t device_get_gpu_instance_by_id(intptr_t device, unsigned int id) except? 0: """Get GPU instances for given instance ID. @@ -27779,11 +28494,10 @@ cpdef object gpu_instance_get_compute_instance_possible_placements(intptr_t gpu_ check_status_size(__status__) cdef ComputeInstancePlacement placements = ComputeInstancePlacement(count[0]) cdef nvmlComputeInstancePlacement_t *placements_ptr = (placements._get_ptr()) - if count[0] == 0: - return placements - with nogil: - __status__ = nvmlGpuInstanceGetComputeInstancePossiblePlacements(gpu_instance, profile_id, placements_ptr, count) - check_status(__status__) + if count[0] != 0: + with nogil: + __status__ = nvmlGpuInstanceGetComputeInstancePossiblePlacements(gpu_instance, profile_id, placements_ptr, count) + check_status(__status__) return placements @@ -27808,7 +28522,7 @@ cpdef intptr_t gpu_instance_create_compute_instance(intptr_t gpu_instance, unsig return compute_instance -cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_instance, unsigned int profile_id, intptr_t placement) except? 0: +cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_instance, unsigned int profile_id, placement) except? 0: """Create compute instance with the specified placement. Args: @@ -27824,9 +28538,10 @@ cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_ .. seealso:: `nvmlGpuInstanceCreateComputeInstanceWithPlacement` """ + cdef intptr_t _placement_ptr_ = int(placement) cdef ComputeInstance compute_instance with nogil: - __status__ = nvmlGpuInstanceCreateComputeInstanceWithPlacement(gpu_instance, profile_id, placement, &compute_instance) + __status__ = nvmlGpuInstanceCreateComputeInstanceWithPlacement(gpu_instance, profile_id, _placement_ptr_, &compute_instance) check_status(__status__) return compute_instance @@ -27844,6 +28559,38 @@ cpdef compute_instance_destroy(intptr_t compute_instance): check_status(__status__) +cpdef object gpu_instance_get_compute_instances(intptr_t gpu_instance, unsigned int profile_id): + """Get compute instances for given profile ID. + + Args: + gpu_instance (intptr_t): The identifier of the target GPU + instance. + profile_id (unsigned int): The compute instance profile ID. + See ``nvmlGpuInstanceGetComputeInstanceProfileInfo``. + + Returns: + intptr_t: Returns pre-exiting compute instances, the buffer + must be large enough to accommodate the instances + supported by the profile. See + ``nvmlGpuInstanceGetComputeInstanceProfileInfo``. + + .. seealso:: `nvmlGpuInstanceGetComputeInstances` + """ + cdef unsigned int[1] count = [0] + with nogil: + __status__ = nvmlGpuInstanceGetComputeInstances(gpu_instance, profile_id, NULL, count) + check_status_size(__status__) + cdef object _compute_instances_alloc_ = _numpy.empty(max(count[0], 1), dtype=_numpy.intp) + cdef intptr_t _compute_instances_data_ = _compute_instances_alloc_.ctypes.data + cdef intptr_t *compute_instances_ptr = _compute_instances_data_ + cdef object compute_instances = _compute_instances_alloc_[:count[0]] + if count[0] != 0: + with nogil: + __status__ = nvmlGpuInstanceGetComputeInstances(gpu_instance, profile_id, compute_instances_ptr, count) + check_status(__status__) + return compute_instances + + cpdef intptr_t gpu_instance_get_compute_instance_by_id(intptr_t gpu_instance, unsigned int id) except? 0: """Get compute instance for given instance ID. @@ -28101,7 +28848,7 @@ cpdef object device_get_power_mizer_mode_v1(intptr_t device): return power_mizer_mode_py -cpdef device_set_power_mizer_mode_v1(intptr_t device, intptr_t power_mizer_mode): +cpdef device_set_power_mizer_mode_v1(intptr_t device, power_mizer_mode): """Sets the new power mizer mode. Args: @@ -28111,8 +28858,9 @@ cpdef device_set_power_mizer_mode_v1(intptr_t device, intptr_t power_mizer_mode) .. seealso:: `nvmlDeviceSetPowerMizerMode_v1` """ + cdef intptr_t _power_mizer_mode_ptr_ = int(power_mizer_mode) with nogil: - __status__ = nvmlDeviceSetPowerMizerMode_v1(device, power_mizer_mode) + __status__ = nvmlDeviceSetPowerMizerMode_v1(device, _power_mizer_mode_ptr_) check_status(__status__) @@ -28209,7 +28957,7 @@ cpdef object gpu_instance_get_vgpu_scheduler_log_v2(intptr_t gpu_instance): return p_scheduler_log_info_py -cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, intptr_t p_scheduler_state): +cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, p_scheduler_state): """Sets the vGPU scheduler state. Args: @@ -28219,12 +28967,13 @@ cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, intptr_t p_scheduler_s .. seealso:: `nvmlDeviceSetVgpuSchedulerState_v2` """ + cdef intptr_t _p_scheduler_state_ptr_ = int(p_scheduler_state) with nogil: - __status__ = nvmlDeviceSetVgpuSchedulerState_v2(device, p_scheduler_state) + __status__ = nvmlDeviceSetVgpuSchedulerState_v2(device, _p_scheduler_state_ptr_) check_status(__status__) -cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, intptr_t p_scheduler_state): +cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, p_scheduler_state): """Set vGPU scheduler state for the given GPU instance. Args: @@ -28234,8 +28983,9 @@ cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, intptr_t p .. seealso:: `nvmlGpuInstanceSetVgpuSchedulerState_v2` """ + cdef intptr_t _p_scheduler_state_ptr_ = int(p_scheduler_state) with nogil: - __status__ = nvmlGpuInstanceSetVgpuSchedulerState_v2(gpu_instance, p_scheduler_state) + __status__ = nvmlGpuInstanceSetVgpuSchedulerState_v2(gpu_instance, _p_scheduler_state_ptr_) check_status(__status__) @@ -28321,28 +29071,6 @@ cpdef object device_get_remapped_rows_v2(intptr_t device): return info_py -cpdef object system_get_topology_gpu_set(unsigned int cpuNumber): - """Retrieve the set of GPUs that have a CPU affinity with the given CPU number - - Args: - cpuNumber (unsigned int): The CPU number - - Returns: - array: An array of device handles for GPUs found with affinity to cpuNumber - """ - cdef unsigned int[1] count = [0] - with nogil: - __status__ = nvmlSystemGetTopologyGpuSet(cpuNumber, count, NULL) - check_status_size(__status__) - if count[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(intptr_t), format="P", mode="c")[:0] - cdef view.array deviceArray = view.array(shape=(count[0],), itemsize=sizeof(intptr_t), format="P", mode="c") - with nogil: - __status__ = nvmlSystemGetTopologyGpuSet(cpuNumber, count, deviceArray.data) - check_status(__status__) - return deviceArray - - cpdef str system_get_driver_branch(): """Retrieves the driver branch of the NVIDIA driver installed on the system. @@ -28361,61 +29089,6 @@ cpdef str system_get_driver_branch(): return cpython.PyUnicode_FromString(info.branch) -cpdef object unit_get_devices(intptr_t unit): - """Retrieves the set of GPU devices that are attached to the specified unit. - - Args: - unit (Unit): The identifier of the target unit. - - Returns: - array: An array of device handles for GPUs attached to the unit. - """ - cdef unsigned int[1] deviceCount = [0] - with nogil: - __status__ = nvmlUnitGetDevices(unit, deviceCount, NULL) - check_status_size(__status__) - if deviceCount[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(intptr_t), format="P", mode="c")[:0] - cdef view.array deviceArray = view.array(shape=(deviceCount[0],), itemsize=sizeof(intptr_t), format="P", mode="c") - with nogil: - __status__ = nvmlUnitGetDevices(unit, deviceCount, deviceArray.data) - check_status(__status__) - return deviceArray - - -cpdef object device_get_topology_nearest_gpus(intptr_t device, unsigned int level): - """Retrieve the set of GPUs that are nearest to a given device at a specific interconnectivity level - - Args: - device (Device): The identifier of the first device - level (GpuTopologyLevel): The level to search for other GPUs - - Returns: - array: An array of device handles for GPUs found at level - """ - cdef unsigned int[1] count = [0] - with nogil: - __status__ = nvmlDeviceGetTopologyNearestGpus( - device, - level, - count, - NULL - ) - check_status_size(__status__) - if count[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(intptr_t), format="P", mode="c")[:0] - cdef view.array deviceArray = view.array(shape=(count[0],), itemsize=sizeof(intptr_t), format="P", mode="c") - with nogil: - __status__ = nvmlDeviceGetTopologyNearestGpus( - device, - level, - count, - deviceArray.data - ) - check_status(__status__) - return deviceArray - - cpdef int device_get_temperature_v(intptr_t device, nvmlTemperatureSensors_t sensorType): """Retrieves the current temperature readings (in degrees C) for the given device. @@ -28490,58 +29163,6 @@ cpdef object device_get_running_process_detail_list(intptr_t device, unsigned in return plist -cpdef tuple device_get_samples(intptr_t device, int type, unsigned long long last_seen_time_stamp): - """Gets recent samples for the GPU. - - Args: - device (intptr_t): The identifier for the target device. - type (SamplingType): Type of sampling event. - last_seen_time_stamp (unsigned long long): Return only samples with timestamp greater than last_seen_time_stamp. - - .. seealso:: `nvmlDeviceGetSamples` - """ - cdef unsigned int[1] sample_count = [0] - cdef unsigned int[1] sample_val_type = [0] - with nogil: - __status__ = nvmlDeviceGetSamples(device, <_SamplingType>type, last_seen_time_stamp, <_ValueType*>sample_val_type, sample_count, NULL) - check_status_size(__status__) - cdef Sample samples = Sample(sample_count[0]) - cdef nvmlSample_t *samples_ptr = samples._get_ptr() - if sample_count[0] == 0: - return samples - with nogil: - __status__ = nvmlDeviceGetSamples(device, <_SamplingType>type, last_seen_time_stamp, <_ValueType*>sample_val_type, sample_count, samples_ptr) - check_status(__status__) - return (sample_val_type[0], samples) - - -cpdef tuple device_get_retired_pages_v2(intptr_t device, int cause): - """Returns the list of retired pages by source, including pages that are pending retirement - - Args: - device (Device): The identifier of the target device. - cause (PageRetirementCause): Filter page addresses by cause of retirement. - - Returns: - tuple: A tuple of two arrays (addresses, timestamps). - """ - cdef unsigned int[1] page_count = [0] - with nogil: - __status__ = nvmlDeviceGetRetiredPages_v2(device, <_PageRetirementCause>cause, page_count, NULL, NULL) - check_status_size(__status__) - if page_count[0] == 0: - return ( - view.array(shape=(1,), itemsize=sizeof(unsigned long long), format="Q", mode="c")[:0], - view.array(shape=(1,), itemsize=sizeof(unsigned long long), format="Q", mode="c")[:0] - ) - cdef view.array addresses = view.array(shape=(page_count[0],), itemsize=sizeof(unsigned long long), format="Q", mode="c") - cdef view.array timestamps = view.array(shape=(page_count[0],), itemsize=sizeof(unsigned long long), format="Q", mode="c") - with nogil: - __status__ = nvmlDeviceGetRetiredPages_v2(device, <_PageRetirementCause>cause, page_count, addresses.data, timestamps.data) - check_status(__status__) - return (addresses, timestamps) - - cpdef object device_get_processes_utilization_info(intptr_t device, unsigned long long last_seen_time_stamp): """Retrieves the recent utilization and process ID for all running processes @@ -28685,90 +29306,6 @@ cpdef device_clear_field_values(intptr_t device, values): check_status(__status__) -cpdef object device_get_supported_vgpus(intptr_t device): - """Retrieve the supported vGPU types on a physical GPU (device). - - Args: - device (Device): The identifier of the target device. - - Returns: - array: An array of supported vGPU type IDs. - """ - cdef unsigned int[1] vgpuCount = [0] - with nogil: - __status__ = nvmlDeviceGetSupportedVgpus(device, vgpuCount, NULL) - check_status_size(__status__) - if vgpuCount[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef view.array vgpuTypeIds = view.array(shape=(deviceCount[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - with nogil: - __status__ = nvmlDeviceGetSupportedVgpus(device, vgpuCount, vgpuTypeIds.data) - check_status(__status__) - return vgpuTypeIds - - -cpdef object device_get_creatable_vgpus(intptr_t device): - """Retrieve the currently creatable vGPU types on a physical GPU (device). - - Args: - device (Device): The identifier of the target device. - - Returns: - array: An array of createable vGPU type IDs. - """ - cdef unsigned int[1] vgpuCount = [0] - with nogil: - __status__ = nvmlDeviceGetCreatableVgpus(device, vgpuCount, NULL) - check_status_size(__status__) - if vgpuCount[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef view.array vgpuTypeIds = view.array(shape=(deviceCount[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - with nogil: - __status__ = nvmlDeviceGetCreatableVgpus(device, vgpuCount, vgpuTypeIds.data) - check_status(__status__) - return vgpuTypeIds - - -cpdef object device_get_active_vgpus(intptr_t device): - """Retrieve the active vGPU instances on a device. - - Args: - device (Device): The identifier of the target device. - - Returns: - array: An array of active vGPU instance IDs. - """ - cdef unsigned int[1] vgpuCount = [0] - with nogil: - __status__ = nvmlDeviceGetActiveVgpus(device, vgpuCount, NULL) - check_status_size(__status__) - if vgpuCount[0] == 0: - return view.array(shape=(1,), itemsize=sizeof(unsigned int), format="I", mode="c")[:0] - cdef view.array vgpuInstances = view.array(shape=(deviceCount[0],), itemsize=sizeof(unsigned int), format="I", mode="c") - with nogil: - __status__ = nvmlDeviceGetActiveVgpus(device, vgpuCount, vgpuInstances.data) - check_status(__status__) - return vgpuInstances - - -cpdef tuple vgpu_instance_get_vm_id(unsigned int vgpu_instance): - """Retrieve the VM ID associated with a vGPU instance. - - Args: - vgpu_instance (unsigned int): The identifier of the target vGPU instance. - - Returns: - tuple[str, VgpuVmIdType]: A tuple of (id, id_type). - """ - cdef unsigned int size = 80 - cdef char[80] vmId - cdef nvmlVgpuVmIdType_t[1] vmIdType - with nogil: - __status__ = nvmlVgpuInstanceGetVmID(vgpu_instance, vmId, size, vmIdType) - check_status(__status__) - return (cpython.PyUnicode_FromString(vmId), vmIdType[0]) - - cpdef object gpu_instance_get_creatable_vgpus(intptr_t gpu_instance): """Query the currently creatable vGPU types on a specific GPU Instance. @@ -28976,24 +29513,6 @@ cpdef object get_vgpu_compatibility(VgpuMetadata vgpu_metadata, VgpuPgpuMetadata return compatibilityInfo -cpdef tuple get_vgpu_version(): - """Query the ranges of supported vGPU versions. - - Returns: - tuple: A tuple of (VgpuVersion supported, VgpuVersion current). - """ - cdef VgpuVersion supported = VgpuVersion() - cdef nvmlVgpuVersion_t *supported_ptr = supported._get_ptr() - cdef VgpuVersion current = VgpuVersion() - cdef nvmlVgpuVersion_t *current_ptr = current._get_ptr() - - with nogil: - __status__ = nvmlGetVgpuVersion(supported_ptr, current_ptr) - - check_status(__status__) - return (supported, current) - - cpdef object device_get_vgpu_instances_utilization_info(intptr_t device): """ Retrieves recent utilization for vGPU instances running on a physical GPU (device). @@ -29061,58 +29580,6 @@ cpdef object device_get_vgpu_processes_utilization_info(intptr_t device, unsigne return vgpuProcUtilInfo -cpdef object device_get_gpu_instances(intptr_t device, unsigned int profile_id): - """Get GPU instances for given profile ID. - - Args: - device (Device): The identifier of the target device. - profile_id (unsigned int): The GPU instance profile ID. See device_get_gpu_instance_profile_info(). - - Returns: - array: An array of GPU instance handles. - """ - cdef unsigned int[1] count = [0] - with nogil: - __status__ = nvmlDeviceGetGpuInstances(device, profile_id, NULL, count) - check_status_size(__status__) - - if count[0] == 0: - view.array(shape=(1,), itemsize=sizeof(intptr_t), format="P", mode="c")[:0] - - cdef view.array gpuInstances = view.array(shape=(count[0],), itemsize=sizeof(intptr_t), format="P", mode="c") - with nogil: - __status__ = nvmlDeviceGetGpuInstances(device, profile_id, gpuInstances.data, count) - check_status(__status__) - - return gpuInstances - - -cpdef object gpu_instance_get_compute_instances(intptr_t gpu_instance, unsigned int profile_id): - """Get Compute instances for given profile ID. - - Args: - gpu_instance (GpuInstance): The identifier of the target GPU Instance. - profile_id (unsigned int): The Compute instance profile ID. - - Returns: - array: An array of Compute instance handles. - """ - cdef unsigned int[1] count = [0] - with nogil: - __status__ = nvmlGpuInstanceGetComputeInstances(gpu_instance, profile_id, NULL, count) - check_status_size(__status__) - - if count[0] == 0: - view.array(shape=(1,), itemsize=sizeof(intptr_t), format="P", mode="c")[:0] - - cdef view.array computeInstances = view.array(shape=(count[0],), itemsize=sizeof(intptr_t), format="P", mode="c") - with nogil: - __status__ = nvmlGpuInstanceGetComputeInstances(gpu_instance, profile_id, computeInstances.data, count) - check_status(__status__) - - return computeInstances - - cpdef object device_get_sram_unique_uncorrected_ecc_error_counts(intptr_t device): """Retrieves the counts of SRAM unique uncorrected ECC errors @@ -29710,55 +30177,6 @@ cpdef gpu_instance_set_vgpu_heterogeneous_mode(intptr_t gpu_instance, unsigned i check_status(__status__) -cpdef tuple device_get_vgpu_utilization(intptr_t device, unsigned long long last_seen_time_stamp): - """Retrieves current utilization for vGPUs on a physical GPU (device). - - Args: - device (intptr_t): The identifier for the target device. - last_seen_time_stamp (unsigned long long): Return only samples with timestamp greater than last_seen_time_stamp. - - Returns: - A 2-tuple containing: - - - samples: Returned sample values. - - utilizationSamples: Utilization samples. - - .. seealso:: `nvmlDeviceGetVgpuUtilization` - """ - cdef unsigned int vgpu_instance_samples_count - with nogil: - __status__ = nvmlDeviceGetVgpuUtilization( - device, - last_seen_time_stamp, - NULL, - &vgpu_instance_samples_count, - NULL - ) - check_status_size(__status__) - - if vgpu_instance_samples_count == 0: - return ( - view.array(shape=(1,), itemsize=sizeof(int), format="I", mode="c")[:0], - VgpuInstanceUtilizationSample(0) - ) - - cdef view.array arr = view.array(shape=(vgpu_instance_samples_count,), itemsize=sizeof(int), format="I", mode="c") - cdef VgpuInstanceUtilizationSample utilization_samples_py = VgpuInstanceUtilizationSample(vgpu_instance_samples_count) - cdef nvmlVgpuInstanceUtilizationSample_t *ptr = utilization_samples_py._get_ptr() - - with nogil: - __status__ = nvmlDeviceGetVgpuUtilization( - device, - last_seen_time_stamp, - arr.data, - &vgpu_instance_samples_count, - ptr - ) - check_status(__status__) - - return (arr, utilization_samples_py) - - cpdef object device_read_prm_counters_v1(intptr_t device, PRMCounter_v1 counters): """Read a list of GPU PRM Counters. diff --git a/cuda_bindings/cuda/bindings/nvvm.pyx b/cuda_bindings/cuda/bindings/nvvm.pyx index b6e8a13f1cb..f4fd3a93d2a 100644 --- a/cuda_bindings/cuda/bindings/nvvm.pyx +++ b/cuda_bindings/cuda/bindings/nvvm.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.0.1 to 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=a82258bb2654bea18f6bce657324bdbbee8b8b0b30d2a0021e792ba5f95fa9a4 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=6fc70275a97b87cfcb879950f4db012bc84a57d5493f097308c0f5c2473d0e0b # <<<< PREAMBLE CONTENT >>>> @@ -20,7 +20,9 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep flags |= _cyb_cpython.PyBUF_WRITABLE cdef int status = -1 cdef _cyb_cpython.Py_buffer view - if isinstance(buf, int): + if buf is None: + ptr = 0 + elif isinstance(buf, int): ptr = buf else: try: @@ -31,7 +33,7 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep except Exception as e: adj = "writable " if not readonly else "" raise ValueError( - "buf must be either a Python int representing the pointer " + "buf must be None, a Python int representing the pointer " f"address to a valid buffer, or a 1D contiguous {adj}" f"buffer, of size {size}" ) from e diff --git a/cuda_bindings/cuda/bindings/runtime.pyx b/cuda_bindings/cuda/bindings/runtime.pyx index a2292efad7a..03ea689bd61 100644 --- a/cuda_bindings/cuda/bindings/runtime.pyx +++ b/cuda_bindings/cuda/bindings/runtime.pyx @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # This code was automatically generated with version 13.3.0. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=979e766bb067947f8d255ab5e8d2439b946aed85f2d19a209eb4136a1ceda20b +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=33679c061c9c6e01df2f8cf014d769cd3f3565085f4e7d1b5b50adff7bb9db05 from typing import Any, Optional import cython import ctypes @@ -30868,16 +30868,20 @@ def cudaGraphicsResourceGetMappedPointer(resource): Parameters ---------- resource : :py:obj:`~.cudaGraphicsResource_t` - None + Mapped resource to access Returns ------- cudaError_t - + :py:obj:`~.cudaSuccess`, :py:obj:`~.cudaErrorInvalidValue`, :py:obj:`~.cudaErrorInvalidResourceHandle`, :py:obj:`~.cudaErrorUnknown` devPtr : Any - None + Returned pointer through which `resource` may be accessed size : int - None + Returned size of the buffer accessible starting at `*devPtr` + + See Also + -------- + :py:obj:`~.cudaGraphicsMapResources`, :py:obj:`~.cudaGraphicsSubResourceGetMappedArray`, :py:obj:`~.cuGraphicsResourceGetMappedPointer` """ cdef cyruntime.cudaGraphicsResource_t cyresource if resource is None: diff --git a/cuda_bindings/cuda/bindings/utils/_version_check.py b/cuda_bindings/cuda/bindings/utils/_version_check.py index 5c68b50152e..84ceac63505 100644 --- a/cuda_bindings/cuda/bindings/utils/_version_check.py +++ b/cuda_bindings/cuda/bindings/utils/_version_check.py @@ -36,16 +36,17 @@ def warn_if_cuda_major_version_mismatch(): return # Import here to avoid circular imports and allow lazy loading - from cuda.bindings import driver + from cuda.bindings._v2 import driver # Get compile-time CUDA version from cuda-bindings compile_version = driver.CUDA_VERSION # e.g., 13010 compile_major = compile_version // 1000 # Get runtime driver version - err, runtime_version = driver.cuDriverGetVersion() - if err != driver.CUresult.CUDA_SUCCESS: - raise RuntimeError(f"Failed to query CUDA driver version: {err}") + try: + runtime_version = driver.driver_get_version() + except driver.DriverError as e: + raise RuntimeError(f"Failed to query CUDA driver version: {e}") from e runtime_major = runtime_version // 1000 diff --git a/cuda_bindings/tests/conftest.py b/cuda_bindings/tests/conftest.py index fada7d95601..ed1dde0a96c 100644 --- a/cuda_bindings/tests/conftest.py +++ b/cuda_bindings/tests/conftest.py @@ -10,7 +10,7 @@ import pytest -import cuda.bindings.driver as cuda +import cuda.bindings._v2.driver as cuda # Keep in sync with cuda_core/tests/conftest.py. try: @@ -41,15 +41,12 @@ def pytest_configure(config): def _thread_context(): # Context setting up `device` and `ctx` for individual threads on # pytest-run-parallel - err, device = cuda.cuDeviceGet(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, ctx = cuda.cuCtxCreate(None, 0, device) - assert err == cuda.CUresult.CUDA_SUCCESS + device = cuda.device_get(0) + ctx = cuda.ctx_create_v4(None, 0, device) try: yield device, ctx finally: - (err,) = cuda.cuCtxDestroy(ctx) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.ctx_destroy_v2(ctx) def _wrap_worker_cuda_test(func): @@ -106,22 +103,17 @@ def pytest_collection_modifyitems(self, config, items): @pytest.fixture(scope="module") def cuda_driver(): - (err,) = cuda.cuInit(0) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.init(0) @pytest.fixture(scope="module") def device(cuda_driver): - err, device = cuda.cuDeviceGet(0) - assert err == cuda.CUresult.CUDA_SUCCESS - return device + return cuda.device_get(0) @pytest.fixture(scope="module", autouse=True) def ctx(device): # Construct context - err, ctx = cuda.cuCtxCreate(None, 0, device) - assert err == cuda.CUresult.CUDA_SUCCESS + ctx = cuda.ctx_create_v4(None, 0, device) yield ctx - (err,) = cuda.cuCtxDestroy(ctx) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.ctx_destroy_v2(ctx) diff --git a/cuda_bindings/tests/legacy_api/__init__.py b/cuda_bindings/tests/legacy_api/__init__.py new file mode 100644 index 00000000000..e5725ea5a48 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/cuda_bindings/tests/legacy_api/conftest.py b/cuda_bindings/tests/legacy_api/conftest.py new file mode 100644 index 00000000000..c6901b715a3 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/conftest.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Overrides the root conftest's `cuda_driver`/`device`/`ctx` fixtures with +versions backed by the legacy (non-v2) driver API. + +The root conftest.py was ported to `cuda.bindings._v2.driver`, whose handles +are plain Python ints. Some legacy_api tests (e.g. test_legacy_cuda.py's repr +tests) assert on the repr of the old wrapped handle types (CUcontext, +CUdevice), so this directory needs its own copies of these fixtures using the +old API to stay frozen, per legacy_api/README.md. +""" + +import pytest + +import cuda.bindings.driver as cuda + + +@pytest.fixture(scope="module") +def cuda_driver(): + (err,) = cuda.cuInit(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.fixture(scope="module") +def device(cuda_driver): + err, device = cuda.cuDeviceGet(0) + assert err == cuda.CUresult.CUDA_SUCCESS + return device + + +@pytest.fixture(scope="module", autouse=True) +def ctx(device): + # Construct context + err, ctx = cuda.cuCtxCreate(None, 0, device) + assert err == cuda.CUresult.CUDA_SUCCESS + yield ctx + (err,) = cuda.cuCtxDestroy(ctx) + assert err == cuda.CUresult.CUDA_SUCCESS diff --git a/cuda_bindings/tests/legacy_api/cufile.json b/cuda_bindings/tests/legacy_api/cufile.json new file mode 100644 index 00000000000..21ab1f3b6bb --- /dev/null +++ b/cuda_bindings/tests/legacy_api/cufile.json @@ -0,0 +1,22 @@ +{ + // NOTE : Application can override custom configuration via export CUFILE_ENV_PATH_JSON= + // e.g : export CUFILE_ENV_PATH_JSON="/home//cufile.json" + + + "properties" : { + "allow_compat_mode" : true + }, + + "execution" : { + // max number of workitems in the queue; + "max_io_queue_depth": 128, + // max number of host threads per gpu to spawn for parallel IO + "max_io_threads" : 4, + // enable support for parallel IO + "parallel_io" : true, + // minimum IO threshold before splitting the IO + "min_io_threshold_size_kb" : 8192, + // maximum parallelism for a single request + "max_request_parallelism" : 4 + } +} diff --git a/cuda_bindings/tests/legacy_api/nvml/__init__.py b/cuda_bindings/tests/legacy_api/nvml/__init__.py new file mode 100644 index 00000000000..e5725ea5a48 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/nvml/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/cuda_bindings/tests/legacy_api/nvml/test_legacy_nvml_cuda.py b/cuda_bindings/tests/legacy_api/nvml/test_legacy_nvml_cuda.py new file mode 100644 index 00000000000..38df854dd5a --- /dev/null +++ b/cuda_bindings/tests/legacy_api/nvml/test_legacy_nvml_cuda.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import os + +import pytest + +import cuda.bindings.driver as cuda +from cuda.bindings import nvml + + +# Inlined from tests/nvml/conftest.py: legacy_api snapshots must not depend +# on files outside this directory. +class NVMLInitializer: + def __init__(self): + pass + + def __enter__(self): + nvml.init_v2() + + def __exit__(self, exception_type, exception, trace): + nvml.shutdown() + + +def get_nvml_device_names(): + result = [] + with NVMLInitializer(): + # uses NVML Library to get the device count, device id and device pci id + num_devices = nvml.device_get_count_v2() + for idx in range(num_devices): + handle = nvml.device_get_handle_by_index_v2(idx) + name = nvml.device_get_name(handle) + info = nvml.device_get_pci_info_v3(handle) + assert isinstance(info.bus, int) + assert isinstance(name, str) + result.append({"name": name, "id": info.bus}) + + return result + + +def get_cuda_device_names(sort_by_bus_id=True): + result = [] + + (err,) = cuda.cuInit(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, device_count = cuda.cuDeviceGetCount() + assert err == cuda.CUresult.CUDA_SUCCESS + + for dev in range(device_count): + size = 256 + err, name = cuda.cuDeviceGetName(size, dev) + name = name.split(b"\x00")[0].decode() + assert err == cuda.CUresult.CUDA_SUCCESS + + err, pci_bus_id = cuda.cuDeviceGetAttribute(cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_PCI_BUS_ID, dev) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(pci_bus_id, int) + + result.append({"name": name, "id": pci_bus_id}) + + if sort_by_bus_id: + result = sorted(result, key=lambda k: k["id"]) + + return result + + +def test_cuda_device_order(): + cuda_devices = get_cuda_device_names() + nvml_devices = get_nvml_device_names() + + if any("Thor" in device["name"] for device in nvml_devices): + pytest.skip("Skipping test on Thor, which has non-standard device naming") + return + + if "CUDA_VISIBLE_DEVICES" not in os.environ: + # If that environment variable isn't set, the device lists should match exactly + assert cuda_devices == nvml_devices, "CUDA and NVML device lists do not match" + else: + # If the environment variable is set, there may possibly be fewer CUDA devices, + # and each of them should still be found in NVML devices. + assert len(cuda_devices) <= len(nvml_devices) + for cuda_device in cuda_devices: + assert cuda_device in nvml_devices, f"CUDA device {cuda_device} not found in NVML device list" diff --git a/cuda_bindings/tests/legacy_api/test_legacy_cuda.py b/cuda_bindings/tests/legacy_api/test_legacy_cuda.py new file mode 100644 index 00000000000..7bef2b844aa --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_cuda.py @@ -0,0 +1,1337 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import ctypes +import os.path +import shutil +import subprocess +import sys +import textwrap + +import numpy as np +import pytest +from cuda_python_test_helpers.mempool import xfail_if_mempool_oom + +import cuda.bindings.driver as cuda +import cuda.bindings.runtime as cudart +from cuda.bindings import driver +from cuda_python_test_helpers import driver_version_less_than + + +def supportsMemoryPool(): + err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrMemoryPoolsSupported, 0) + return err == cudart.cudaError_t.cudaSuccess and isSupported + + +def supportsManagedMemory(): + err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrManagedMemory, 0) + return err == cudart.cudaError_t.cudaSuccess and isSupported + + +def supportsCudaAPI(name): + return name in dir(cuda) + + +def callableBinary(name): + return shutil.which(name) is not None + + +@pytest.mark.skipif(True, reason="Always skip!") +def test_always_skip(): + pass + + +def test_cuda_memcpy(): + # Get device + + # Allocate dev memory + size = int(1024 * np.uint8().itemsize) + err, dptr = cuda.cuMemAlloc(size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Set h1 and h2 memory to be different + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # h1 to D + (err,) = cuda.cuMemcpyHtoD(dptr, h1, size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # D to h2 + (err,) = cuda.cuMemcpyDtoH(h2, dptr, size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Validate h1 == h2 + assert np.array_equal(h1, h2) + + # Cleanup + (err,) = cuda.cuMemFree(dptr) + assert err == cuda.CUresult.CUDA_SUCCESS + + +def test_cuda_array(): + # No context created + desc = cuda.CUDA_ARRAY_DESCRIPTOR() + err, arr = cuda.cuArrayCreate(desc) + assert err == cuda.CUresult.CUDA_ERROR_INVALID_CONTEXT or err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + + # Desciption not filled + err, arr = cuda.cuArrayCreate(desc) + assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + + # Pass + desc.Format = cuda.CUarray_format.CU_AD_FORMAT_SIGNED_INT8 + desc.NumChannels = 1 + desc.Width = 1 + err, arr = cuda.cuArrayCreate(desc) + assert err == cuda.CUresult.CUDA_SUCCESS + + (err,) = cuda.cuArrayDestroy(arr) + assert err == cuda.CUresult.CUDA_SUCCESS + + +def test_cuda_repr_primitive(device, ctx): + assert str(device) == "" + assert int(device) == 0 + + assert str(ctx).startswith(" 0 + assert hex(ctx) == hex(int(ctx)) + + # CUdeviceptr + err, dptr = cuda.cuMemAlloc(1024 * np.uint8().itemsize) + assert err == cuda.CUresult.CUDA_SUCCESS + assert str(dptr).startswith(" 0 + (err,) = cuda.cuMemFree(dptr) + size = 7 + dptr = cuda.CUdeviceptr(size) + assert str(dptr) == f"" + assert int(dptr) == size + size = 4294967295 + dptr = cuda.CUdeviceptr(size) + assert str(dptr) == f"" + assert int(dptr) == size + size = 18446744073709551615 + dptr = cuda.CUdeviceptr(size) + assert str(dptr) == f"" + assert int(dptr) == size + + # cuuint32_t + size = 7 + int32 = cuda.cuuint32_t(size) + assert str(int32) == f"" + assert int(int32) == size + size = 4294967295 + int32 = cuda.cuuint32_t(size) + assert str(int32) == f"" + assert int(int32) == size + size = 18446744073709551615 + try: + int32 = cuda.cuuint32_t(size) + raise RuntimeError("int32 = cuda.cuuint32_t(18446744073709551615) did not fail") + except OverflowError as err: + pass + + # cuuint64_t + size = 7 + int64 = cuda.cuuint64_t(size) + assert str(int64) == f"" + assert int(int64) == size + size = 4294967295 + int64 = cuda.cuuint64_t(size) + assert str(int64) == f"" + assert int(int64) == size + size = 18446744073709551615 + int64 = cuda.cuuint64_t(size) + assert str(int64) == f"" + assert int(int64) == size + + +def test_cuda_repr_pointer(ctx): + # Test 1: Classes representing pointers + assert str(ctx).startswith(" 0 + assert hex(ctx) == hex(int(ctx)) + randomCtxPointer = 12345 + randomCtx = cuda.CUcontext(randomCtxPointer) + assert str(randomCtx) == f"" + assert int(randomCtx) == randomCtxPointer + assert hex(randomCtx) == hex(randomCtxPointer) + + # Test 2: Function pointers + func = 12345 + b2d_cb = cuda.CUoccupancyB2DSize(func) + assert str(b2d_cb) == f"" + assert int(b2d_cb) == func + assert hex(b2d_cb) == hex(func) + + +def test_cuda_uuid_list_access(device): + err, uuid = cuda.cuDeviceGetUuid(device) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(uuid.bytes) <= 16 + + jit_option = cuda.CUjit_option + options = { + jit_option.CU_JIT_INFO_LOG_BUFFER: 1, + jit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: 2, + jit_option.CU_JIT_ERROR_LOG_BUFFER: 3, + jit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: 4, + jit_option.CU_JIT_LOG_VERBOSE: 5, + } + + +def test_cuda_cuModuleLoadDataEx(): + option_keys = [ + cuda.CUjit_option.CU_JIT_INFO_LOG_BUFFER, + cuda.CUjit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, + cuda.CUjit_option.CU_JIT_ERROR_LOG_BUFFER, + cuda.CUjit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, + cuda.CUjit_option.CU_JIT_LOG_VERBOSE, + ] + # FIXME: This function call raises CUDA_ERROR_INVALID_VALUE + err, mod = cuda.cuModuleLoadDataEx(0, 0, option_keys, []) + + +def test_cuda_repr(): + actual = cuda.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS() + assert isinstance(actual, cuda.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS) + + actual_repr = actual.__repr__() + expected_repr = textwrap.dedent(""" + params : + fence : + value : 0 + nvSciSync : + fence : 0x0 + keyedMutex : + key : 0 +flags : 0 +""") + assert actual_repr.split() == expected_repr.split() + + actual_repr = cuda.CUDA_KERNEL_NODE_PARAMS_st().__repr__() + expected_repr = textwrap.dedent(""" + func : +gridDimX : 0 +gridDimY : 0 +gridDimZ : 0 +blockDimX : 0 +blockDimY : 0 +blockDimZ : 0 +sharedMemBytes : 0 +kernelParams : 0 +extra : 0 +""") + assert actual_repr.split() == expected_repr.split() + + +def test_cuda_struct_list_of_enums(): + desc = cuda.CUDA_TEXTURE_DESC_st() + desc.addressMode = [ + cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, + cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP, + cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_MIRROR, + ] + + # # Too many args + # desc.addressMode = [cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, + # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP, + # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_MIRROR, + # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_BORDER] + + # # Too little args + # desc.addressMode = [cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, + # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP] + + +def test_cuda_CUstreamBatchMemOpParams(): + params = cuda.CUstreamBatchMemOpParams() + params.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 + params.waitValue.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 + params.writeValue.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 + params.flushRemoteWrites.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 + params.waitValue.value64 = 666 + assert int(params.waitValue.value64) == 666 + + +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsMemoryPool(), reason="When new attributes were introduced" +) +def test_cuda_memPool_attr(): + poolProps = cuda.CUmemPoolProps() + poolProps.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED + poolProps.location.id = 0 + poolProps.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + + attr_list = [None] * 8 + err, pool = cuda.cuMemPoolCreate(poolProps) + xfail_if_mempool_oom(err, "cuMemPoolCreate", poolProps.location.id) + assert err == cuda.CUresult.CUDA_SUCCESS + + for idx, attr in enumerate( + [ + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_USED_MEM_CURRENT, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_USED_MEM_HIGH, + ] + ): + err, attr_tmp = cuda.cuMemPoolGetAttribute(pool, attr) + assert err == cuda.CUresult.CUDA_SUCCESS + attr_list[idx] = attr_tmp + + for idxA, attr in enumerate( + [ + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, + ] + ): + (err,) = cuda.cuMemPoolSetAttribute(pool, attr, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + for idx, attr in enumerate([cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD]): + (err,) = cuda.cuMemPoolSetAttribute(pool, attr, cuda.cuuint64_t(9)) + assert err == cuda.CUresult.CUDA_SUCCESS + + for idx, attr in enumerate( + [ + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, + ] + ): + err, attr_tmp = cuda.cuMemPoolGetAttribute(pool, attr) + assert err == cuda.CUresult.CUDA_SUCCESS + attr_list[idx] = attr_tmp + assert attr_list[0] == 0 + assert attr_list[1] == 0 + assert attr_list[2] == 0 + assert int(attr_list[3]) == 9 + + (err,) = cuda.cuMemPoolDestroy(pool) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsManagedMemory(), reason="When new attributes were introduced" +) +def test_cuda_pointer_attr(): + err, ptr = cuda.cuMemAllocManaged(0x1000, cuda.CUmemAttach_flags.CU_MEM_ATTACH_GLOBAL.value) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Individual version + attr_type_list = [ + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_CONTEXT, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMORY_TYPE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_POINTER, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_HOST_POINTER, + # cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_P2P_TOKENS, # TODO: Can I somehow test this? + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_BUFFER_ID, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_MANAGED, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_RANGE_START_ADDR, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_RANGE_SIZE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPED, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ACCESS_FLAGS, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE, + ] + attr_value_list = [None] * len(attr_type_list) + for idx, attr in enumerate(attr_type_list): + err, attr_tmp = cuda.cuPointerGetAttribute(attr, ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + attr_value_list[idx] = attr_tmp + + # List version + err, attr_value_list_v2 = cuda.cuPointerGetAttributes(len(attr_type_list), attr_type_list, ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): + assert str(attr1) == str(attr2) + + # Test setting values + for val in (True, False): + (err,) = cuda.cuPointerSetAttribute(val, cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + err, attr_tmp = cuda.cuPointerGetAttribute(cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + assert attr_tmp == val + + (err,) = cuda.cuMemFree(ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsManagedMemory(), reason="When new attributes were introduced" +) +def test_pointer_get_attributes_device_ordinal(): + attributes = [ + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, + ] + + attrs = cuda.cuPointerGetAttributes(len(attributes), attributes, 0) + + # device ordinals are always small numbers. A large number would indicate + # an overflow error. + + assert abs(attrs[1][0]) < 256 + + +@pytest.mark.skipif(not supportsManagedMemory(), reason="When new attributes were introduced") +def test_cuda_mem_range_attr(device): + size = 0x1000 + location_device = cuda.CUmemLocation() + location_device.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + location_device.id = int(device) + location_cpu = cuda.CUmemLocation() + location_cpu.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST + location_cpu.id = int(cuda.CU_DEVICE_CPU) + + err, ptr = cuda.cuMemAllocManaged(size, cuda.CUmemAttach_flags.CU_MEM_ATTACH_GLOBAL.value) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_READ_MOSTLY, location_device) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_PREFERRED_LOCATION, location_cpu) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_ACCESSED_BY, location_cpu) + assert err == cuda.CUresult.CUDA_SUCCESS + err, concurrentSupported = cuda.cuDeviceGetAttribute( + cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, device + ) + assert err == cuda.CUresult.CUDA_SUCCESS + if concurrentSupported: + (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_ACCESSED_BY, location_device) + assert err == cuda.CUresult.CUDA_SUCCESS + expected_values_list = ([1, -1, [0, -1, -2], -2],) + else: + expected_values_list = ([1, -1, [-1, -2, -2], -2], [0, -2, [-2, -2, -2], -2]) + + # Individual version + attr_type_list = [ + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION, + ] + attr_type_size_list = [4, 4, 12, 4] + attr_value_list = [None] * len(attr_type_list) + for idx in range(len(attr_type_list)): + err, attr_tmp = cuda.cuMemRangeGetAttribute(attr_type_size_list[idx], attr_type_list[idx], ptr, size) + assert err == cuda.CUresult.CUDA_SUCCESS + attr_value_list[idx] = attr_tmp + + matched = False + for expected_values in expected_values_list: + if expected_values == attr_value_list: + matched = True + break + if not matched: + raise RuntimeError(f"attr_value_list {attr_value_list} did not match any {expected_values_list}") + + # List version + err, attr_value_list_v2 = cuda.cuMemRangeGetAttributes( + attr_type_size_list, attr_type_list, len(attr_type_list), ptr, size + ) + assert err == cuda.CUresult.CUDA_SUCCESS + for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): + assert str(attr1) == str(attr2) + + (err,) = cuda.cuMemFree(ptr) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(11040) or not supportsMemoryPool(), reason="Mempool for graphs not supported" +) +@pytest.mark.thread_unsafe(reason="used high memory can be higher if threaded.") +def test_cuda_graphMem_attr(device): + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + allocSize = 1 + + params = cuda.CUDA_MEM_ALLOC_NODE_PARAMS() + params.poolProps.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + params.poolProps.location.id = device + params.poolProps.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED + params.bytesize = allocSize + + err, allocNode = cuda.cuGraphAddMemAllocNode(graph, None, 0, params) + if err == cuda.CUresult.CUDA_ERROR_OUT_OF_MEMORY: + (destroy_err,) = cuda.cuGraphDestroy(graph) + assert destroy_err == cuda.CUresult.CUDA_SUCCESS + (destroy_err,) = cuda.cuStreamDestroy(stream) + assert destroy_err == cuda.CUresult.CUDA_SUCCESS + xfail_if_mempool_oom(err, "cuGraphAddMemAllocNode", device) + assert err == cuda.CUresult.CUDA_SUCCESS + err, freeNode = cuda.cuGraphAddMemFreeNode(graph, [allocNode], 1, params.dptr) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graphExec = cuda.cuGraphInstantiate(graph, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + (err,) = cuda.cuGraphLaunch(graphExec, stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, used = cuda.cuDeviceGetGraphMemAttribute(device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT) + assert err == cuda.CUresult.CUDA_SUCCESS + err, usedHigh = cuda.cuDeviceGetGraphMemAttribute(device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_USED_MEM_HIGH) + assert err == cuda.CUresult.CUDA_SUCCESS + err, reserved = cuda.cuDeviceGetGraphMemAttribute( + device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT + ) + assert err == cuda.CUresult.CUDA_SUCCESS + err, reservedHigh = cuda.cuDeviceGetGraphMemAttribute( + device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH + ) + assert err == cuda.CUresult.CUDA_SUCCESS + + assert int(used) >= allocSize + assert int(usedHigh) == int(used) + assert int(reserved) == int(usedHigh) + assert int(reservedHigh) == int(reserved) + + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamDestroy(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(12010) + or not supportsCudaAPI("cuCoredumpSetAttributeGlobal") + or not supportsCudaAPI("cuCoredumpGetAttributeGlobal"), + reason="Coredump API not present", +) +def test_cuda_coredump_attr(): + attr_list = [None] * 6 + + (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, False) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_FILE, b"corefile") + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_PIPE, b"corepipe") + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_LIGHTWEIGHT, True) + assert err == cuda.CUresult.CUDA_SUCCESS + + for idx, attr in enumerate( + [ + cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, + cuda.CUcoredumpSettings.CU_COREDUMP_FILE, + cuda.CUcoredumpSettings.CU_COREDUMP_PIPE, + cuda.CUcoredumpSettings.CU_COREDUMP_LIGHTWEIGHT, + ] + ): + err, attr_tmp = cuda.cuCoredumpGetAttributeGlobal(attr) + assert err == cuda.CUresult.CUDA_SUCCESS + attr_list[idx] = attr_tmp + + assert attr_list[0] is False + assert attr_list[1] == b"corefile" + assert attr_list[2] == b"corepipe" + assert attr_list[3] is True + + +def test_get_error_name_and_string(): + err, device = cuda.cuDeviceGet(0) + _, s = cuda.cuGetErrorString(err) + assert s == b"no error" + _, s = cuda.cuGetErrorName(err) + assert s == b"CUDA_SUCCESS" + + err, device = cuda.cuDeviceGet(-1) + _, s = cuda.cuGetErrorString(err) + assert s == b"invalid device ordinal" + _, s = cuda.cuGetErrorName(err) + assert s == b"CUDA_ERROR_INVALID_DEVICE" + + +# TODO: cuStreamGetCaptureInfo_v2 +@pytest.mark.skipif(driver_version_less_than(11030), reason="Driver too old for cuStreamGetCaptureInfo_v2") +def test_stream_capture(): + pass + + +def test_profiler(): + (err,) = cuda.cuProfilerStart() + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuProfilerStop() + assert err == cuda.CUresult.CUDA_SUCCESS + + +def test_eglFrame(): + val = cuda.CUeglFrame() + # [, , ] + assert int(val.frame.pArray[0]) == 0 + assert int(val.frame.pArray[1]) == 0 + assert int(val.frame.pArray[2]) == 0 + val.frame.pArray = [1, 2, 3] + # [, , ] + assert int(val.frame.pArray[0]) == 1 + assert int(val.frame.pArray[1]) == 2 + assert int(val.frame.pArray[2]) == 3 + val.frame.pArray = [cuda.CUarray(4), 2, 3] + # [, , ] + assert int(val.frame.pArray[0]) == 4 + assert int(val.frame.pArray[1]) == 2 + assert int(val.frame.pArray[2]) == 3 + val.frame.pPitch = [4, 2, 3] + # [4, 2, 3] + assert int(val.frame.pPitch[0]) == 4 + assert int(val.frame.pPitch[1]) == 2 + assert int(val.frame.pPitch[2]) == 3 + val.frame.pPitch = [1, 2, 3] + assert int(val.frame.pPitch[0]) == 1 + assert int(val.frame.pPitch[1]) == 2 + assert int(val.frame.pPitch[2]) == 3 + + +def test_anon_assign(): + val1 = cuda.CUexecAffinityParam_st() + val2 = cuda.CUexecAffinityParam_st() + + assert val1.param.smCount.val == 0 + val1.param.smCount.val = 5 + assert val1.param.smCount.val == 5 + val2.param.smCount.val = 11 + assert val2.param.smCount.val == 11 + + val1.param = val2.param + assert val1.param.smCount.val == 11 + + +def test_union_assign(): + val = cuda.CUlaunchAttributeValue() + val.clusterDim.x, val.clusterDim.y, val.clusterDim.z = 9, 9, 9 + attr = cuda.CUlaunchAttribute() + attr.value = val + + assert val.clusterDim.x == 9 + assert val.clusterDim.y == 9 + assert val.clusterDim.z == 9 + + +def test_invalid_repr_attribute(): + val = cuda.CUlaunchAttributeValue() + string = str(val) + + +@pytest.mark.skipif( + driver_version_less_than(12020) + or not supportsCudaAPI("cuGraphAddNode") + or not supportsCudaAPI("cuGraphNodeSetParams") + or not supportsCudaAPI("cuGraphExecNodeSetParams"), + reason="Polymorphic graph APIs required", +) +def test_graph_poly(): + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # cuGraphAddNode + + # Create 2 buffers + size = int(1024 * np.uint8().itemsize) + buffers = [] + for _ in range(2): + err, dptr = cuda.cuMemAlloc(size) + assert err == cuda.CUresult.CUDA_SUCCESS + buffers += [(np.full(size, 2).astype(np.uint8), dptr)] + + # Update dev buffers + for host, device in buffers: + (err,) = cuda.cuMemcpyHtoD(device, host, size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Create graph + nodes = [] + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Memset + host, device = buffers[0] + memsetParams = cuda.CUgraphNodeParams() + memsetParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_MEMSET + memsetParams.memset.elementSize = np.uint8().itemsize + memsetParams.memset.width = size + memsetParams.memset.height = 1 + memsetParams.memset.dst = device + memsetParams.memset.value = 1 + err, node = cuda.cuGraphAddNode(graph, None, None, 0, memsetParams) + assert err == cuda.CUresult.CUDA_SUCCESS + nodes += [node] + + # Memcpy + host, device = buffers[1] + memcpyParams = cuda.CUgraphNodeParams() + memcpyParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_MEMCPY + memcpyParams.memcpy.copyParams.srcMemoryType = cuda.CUmemorytype.CU_MEMORYTYPE_DEVICE + memcpyParams.memcpy.copyParams.srcDevice = device + memcpyParams.memcpy.copyParams.dstMemoryType = cuda.CUmemorytype.CU_MEMORYTYPE_HOST + memcpyParams.memcpy.copyParams.dstHost = host + memcpyParams.memcpy.copyParams.WidthInBytes = size + memcpyParams.memcpy.copyParams.Height = 1 + memcpyParams.memcpy.copyParams.Depth = 1 + err, node = cuda.cuGraphAddNode(graph, None, None, 0, memcpyParams) + assert err == cuda.CUresult.CUDA_SUCCESS + nodes += [node] + + # Instantiate, execute, validate + err, graphExec = cuda.cuGraphInstantiate(graph, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphLaunch(graphExec, stream) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamSynchronize(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Validate + for host, device in buffers: + (err,) = cuda.cuMemcpyDtoH(host, device, size) + assert err == cuda.CUresult.CUDA_SUCCESS + assert np.array_equal(buffers[0][0], np.full(size, 1).astype(np.uint8)) + assert np.array_equal(buffers[1][0], np.full(size, 2).astype(np.uint8)) + + # cuGraphNodeSetParams + host, device = buffers[1] + err, memcpyParamsCopy = cuda.cuGraphMemcpyNodeGetParams(nodes[1]) + assert err == cuda.CUresult.CUDA_SUCCESS + assert int(memcpyParamsCopy.srcDevice) == int(device) + host, device = buffers[0] + memcpyParams.memcpy.copyParams.srcDevice = device + (err,) = cuda.cuGraphNodeSetParams(nodes[1], memcpyParams) + assert err == cuda.CUresult.CUDA_SUCCESS + err, memcpyParamsCopy = cuda.cuGraphMemcpyNodeGetParams(nodes[1]) + assert err == cuda.CUresult.CUDA_SUCCESS + assert int(memcpyParamsCopy.srcDevice) == int(device) + + # cuGraphExecNodeSetParams + memsetParams.memset.value = 11 + (err,) = cuda.cuGraphExecNodeSetParams(graphExec, nodes[0], memsetParams) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphLaunch(graphExec, stream) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamSynchronize(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuMemcpyDtoH(buffers[0][0], buffers[0][1], size) + assert err == cuda.CUresult.CUDA_SUCCESS + assert np.array_equal(buffers[0][0], np.full(size, 11).astype(np.uint8)) + + # Cleanup + (err,) = cuda.cuMemFree(buffers[0][1]) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuMemFree(buffers[1][1]) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphExecDestroy(graphExec) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamDestroy(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(12040) or not supportsCudaAPI("cuDeviceGetDevResource"), + reason="Polymorphic graph APIs required", +) +def test_cuDeviceGetDevResource(device): + err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) + + err, res, count, rem = cuda.cuDevSmResourceSplitByCount(0, resource_in, 0, 2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert count != 0 + assert len(res) == 0 + err, res, count_same, rem = cuda.cuDevSmResourceSplitByCount(count, resource_in, 0, 2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert count == count_same + assert len(res) == count + err, res, count, rem = cuda.cuDevSmResourceSplitByCount(3, resource_in, 0, 2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(res) == 3 + + +@pytest.mark.skipif( + driver_version_less_than(12030) or not supportsCudaAPI("cuGraphConditionalHandleCreate"), + reason="Conditional graph APIs required", +) +def test_conditional(ctx): + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, handle = cuda.cuGraphConditionalHandleCreate(graph, ctx, 0, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + params = cuda.CUgraphNodeParams() + params.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_CONDITIONAL + params.conditional.handle = handle + params.conditional.type = cuda.CUgraphConditionalNodeType.CU_GRAPH_COND_TYPE_IF + params.conditional.size = 1 + params.conditional.ctx = ctx + + assert len(params.conditional.phGraph_out) == 1 + assert int(params.conditional.phGraph_out[0]) == 0 + err, node = cuda.cuGraphAddNode(graph, None, None, 0, params) + assert err == cuda.CUresult.CUDA_SUCCESS + + assert len(params.conditional.phGraph_out) == 1 + assert int(params.conditional.phGraph_out[0]) != 0 + + +def test_CUmemDecompressParams_st(): + desc = cuda.CUmemDecompressParams_st() + assert int(desc.dstActBytes) == 0 + + +def test_all_CUresult_codes(): + max_code = int(max(cuda.CUresult)) + # Smoke test. CUDA_ERROR_UNKNOWN = 999, but intentionally using literal value. + assert max_code >= 999 + num_good = 0 + for code in range(max_code + 2): # One past max_code + try: + error = cuda.CUresult(code) + except ValueError: + pass # cython-generated enum does not exist for this code + else: + err_name, name = cuda.cuGetErrorName(error) + if err_name == cuda.CUresult.CUDA_SUCCESS: + assert name + err_desc, desc = cuda.cuGetErrorString(error) + assert err_desc == cuda.CUresult.CUDA_SUCCESS + assert desc + num_good += 1 + else: + # cython-generated enum exists but is not known to an older driver + # (example: cuda-bindings built with CTK 12.8, driver from CTK 12.0) + assert name is None + assert err_name == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + err_desc, desc = cuda.cuGetErrorString(error) + assert err_desc == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + assert desc is None + # Smoke test: Do we have at least some "good" codes? + # The number will increase over time as new enums are added and support for + # old CTKs is dropped, but it is not critical that this number is updated. + assert num_good >= 76 # CTK 11.0.3_450.51.06 + + +@pytest.mark.skipif(driver_version_less_than(12030), reason="Driver too old for cuKernelGetName") +def test_cuKernelGetName_failure(): + err, name = cuda.cuKernelGetName(0) + assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + assert name is None + + +@pytest.mark.skipif(driver_version_less_than(12030), reason="Driver too old for cuFuncGetName") +def test_cuFuncGetName_failure(): + err, name = cuda.cuFuncGetName(0) + assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + assert name is None + + +@pytest.mark.skipif( + driver_version_less_than(12080) or not supportsCudaAPI("cuCheckpointProcessGetState"), + reason="When API was introduced", +) +def test_cuCheckpointProcessGetState_failure(): + err, state = cuda.cuCheckpointProcessGetState(123434) + assert err != cuda.CUresult.CUDA_SUCCESS + assert state is None + + +def test_private_function_pointer_inspector(): + from cuda.bindings._internal.driver import _inspect_function_pointer + + assert _inspect_function_pointer("__cuGetErrorString") != 0 + + +@pytest.mark.parametrize( + "target", + ( + driver.CUcontext, + driver.CUstream, + driver.CUevent, + driver.CUmodule, + driver.CUlibrary, + driver.CUfunction, + driver.CUkernel, + driver.CUgraph, + driver.CUgraphNode, + driver.CUgraphExec, + driver.CUmemoryPool, + ), +) +def test_struct_pointer_comparison(target): + a = target(123) + b = target(123) + assert a == b + assert hash(a) == hash(b) + c = target(456) + assert a != c + assert hash(a) != hash(c) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuGraphGetId"), + reason="Requires CUDA 13.1+", +) +def test_cuGraphGetId(device, ctx): + """Test cuGraphGetId - get graph ID.""" + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graph_id = cuda.cuGraphGetId(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(graph_id, int) + assert graph_id > 0 + + # Create another graph and verify it has a different ID + err, graph2 = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, graph_id2 = cuda.cuGraphGetId(graph2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert graph_id2 != graph_id + + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphDestroy(graph2) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuGraphExecGetId"), + reason="Requires CUDA 13.1+", +) +def test_cuGraphExecGetId(device, ctx): + """Test cuGraphExecGetId - get graph exec ID.""" + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Add an empty node to make the graph valid + err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graphExec = cuda.cuGraphInstantiate(graph, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, graph_exec_id = cuda.cuGraphExecGetId(graphExec) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(graph_exec_id, int) + assert graph_exec_id > 0 + + # Create another graph exec and verify it has a different ID + err, graph2 = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, node2 = cuda.cuGraphAddEmptyNode(graph2, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, graphExec2 = cuda.cuGraphInstantiate(graph2, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, graph_exec_id2 = cuda.cuGraphExecGetId(graphExec2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert graph_exec_id2 != graph_exec_id + + (err,) = cuda.cuGraphExecDestroy(graphExec) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphExecDestroy(graphExec2) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphDestroy(graph2) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamDestroy(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + +def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): + # Regression test for https://github.com/NVIDIA/cuda-python/issues/1804 + # cuGraphGetEdges previously returned CUgraphEdgeData wrappers backed by + # a scratch buffer that was freed before the call returned, leaving the + # wrappers pointing at freed memory. Ensure the returned objects remain + # readable after the call and after subsequent allocations. + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + err, n0 = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, n1 = cuda.cuGraphAddEmptyNode(graph, [n0], 1) + assert err == cuda.CUresult.CUDA_SUCCESS + err, n2 = cuda.cuGraphAddEmptyNode(graph, [n0, n1], 2) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, _, _, _, num_edges = cuda.cuGraphGetEdges(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + assert num_edges == 3 + err, from_nodes, to_nodes, edge_data, num_edges = cuda.cuGraphGetEdges(graph, num_edges) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(edge_data) == num_edges == 3 + + # Stir the heap to make a use-after-free more likely to surface. + for _ in range(64): + err, _, _, _, _ = cuda.cuGraphGetEdges(graph, num_edges) + assert err == cuda.CUresult.CUDA_SUCCESS + err, _, _, _ = cuda.cuGraphNodeGetDependencies(n1, 1) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Each wrapper must still own its data. + for ed in edge_data: + assert ed.from_port == 0 + assert ed.to_port == 0 + assert int(ed.type) == 0 + finally: + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + + +def test_cuGraphNodeGetDependencies_edgeData_outlives_call(device, ctx): + # Companion regression test for #1804 covering the dependency-query path. + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + err, n0 = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, n1 = cuda.cuGraphAddEmptyNode(graph, [n0], 1) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, _, _, num_deps = cuda.cuGraphNodeGetDependencies(n1) + assert err == cuda.CUresult.CUDA_SUCCESS + assert num_deps == 1 + err, deps, edge_data, num_deps = cuda.cuGraphNodeGetDependencies(n1, num_deps) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(edge_data) == num_deps == 1 + + err, _, _, num_dependents = cuda.cuGraphNodeGetDependentNodes(n0) + assert err == cuda.CUresult.CUDA_SUCCESS + assert num_dependents == 1 + err, dependents, dep_edge_data, num_dependents = cuda.cuGraphNodeGetDependentNodes(n0, num_dependents) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(dep_edge_data) == num_dependents == 1 + + for _ in range(64): + err, _, _, _ = cuda.cuGraphNodeGetDependencies(n1, num_deps) + assert err == cuda.CUresult.CUDA_SUCCESS + err, _, _, _ = cuda.cuGraphNodeGetDependentNodes(n0, num_dependents) + assert err == cuda.CUresult.CUDA_SUCCESS + + for ed in edge_data + dep_edge_data: + assert ed.from_port == 0 + assert ed.to_port == 0 + assert int(ed.type) == 0 + finally: + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetLocalId"), + reason="Requires CUDA 13.1+", +) +def test_cuGraphNodeGetLocalId(device, ctx): + """Test cuGraphNodeGetLocalId - get node local ID.""" + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Add multiple nodes + err, node1 = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, node2 = cuda.cuGraphAddEmptyNode(graph, [node1], 1) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, node3 = cuda.cuGraphAddEmptyNode(graph, [node1, node2], 2) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Get local IDs for each node + err, node_id1 = cuda.cuGraphNodeGetLocalId(node1) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(node_id1, int) + assert node_id1 >= 0 + + err, node_id2 = cuda.cuGraphNodeGetLocalId(node2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(node_id2, int) + assert node_id2 >= 0 + assert node_id2 != node_id1 + + err, node_id3 = cuda.cuGraphNodeGetLocalId(node3) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(node_id3, int) + assert node_id3 >= 0 + assert node_id3 != node_id1 + assert node_id3 != node_id2 + + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetToolsId"), + reason="Requires CUDA 13.1+", +) +def test_cuGraphNodeGetToolsId(device, ctx): + """Test cuGraphNodeGetToolsId - get node tools ID.""" + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, tools_node_id = cuda.cuGraphNodeGetToolsId(node) + assert err == cuda.CUresult.CUDA_SUCCESS + assert isinstance(tools_node_id, int) + # toolsNodeId is unsigned long long, so it can be any non-negative value + assert tools_node_id >= 0 + + # Add another node and verify it has a different tools ID + err, node2 = cuda.cuGraphAddEmptyNode(graph, [node], 1) + assert err == cuda.CUresult.CUDA_SUCCESS + err, tools_node_id2 = cuda.cuGraphNodeGetToolsId(node2) + assert err == cuda.CUresult.CUDA_SUCCESS + assert tools_node_id2 != tools_node_id + + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetContainingGraph"), + reason="Requires CUDA 13.1+", +) +def test_cuGraphNodeGetContainingGraph(device, ctx): + """Test cuGraphNodeGetContainingGraph - get graph containing a node.""" + err, graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Get the containing graph + err, containing_graph = cuda.cuGraphNodeGetContainingGraph(node) + assert err == cuda.CUresult.CUDA_SUCCESS + # Verify it's the same graph + assert int(containing_graph) == int(graph) + + # Test with a child graph node (if supported) + # Create a child graph node + err, child_graph = cuda.cuGraphCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, child_node = cuda.cuGraphAddEmptyNode(child_graph, None, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Add child graph node to parent graph + childGraphNodeParams = cuda.CUgraphNodeParams() + childGraphNodeParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_GRAPH + childGraphNodeParams.graph.graph = child_graph + err, child_graph_node = cuda.cuGraphAddNode(graph, None, None, 0, childGraphNodeParams) + if err == cuda.CUresult.CUDA_SUCCESS: + # Get containing graph for the child graph node + err, containing_graph_for_child = cuda.cuGraphNodeGetContainingGraph(child_graph_node) + assert err == cuda.CUresult.CUDA_SUCCESS + assert int(containing_graph_for_child) == int(graph) + + # Get containing graph for node inside child graph + err, containing_graph_for_nested = cuda.cuGraphNodeGetContainingGraph(child_node) + assert err == cuda.CUresult.CUDA_SUCCESS + assert int(containing_graph_for_nested) == int(child_graph) + + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuGraphDestroy(child_graph) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuStreamGetDevResource"), + reason="Requires CUDA 13.1+", +) +def test_cuStreamGetDevResource(device, ctx): + """Test cuStreamGetDevResource - get device resource from stream.""" + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Get SM resource from stream + err, resource = cuda.cuStreamGetDevResource(stream, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) + assert err == cuda.CUresult.CUDA_SUCCESS + # Verify resource is valid (non-None) + assert resource is not None + + (err,) = cuda.cuStreamDestroy(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cuDevSmResourceSplit"), + reason="Requires CUDA 13.1+", +) +def test_cuDevSmResourceSplit(device, ctx): + """Test cuDevSmResourceSplit - split SM resource into structured groups.""" + err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Test case 1: Split into 1 group + nb_groups = 1 + group_params = [cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS()] + # Set up group: request 4 SMs with coscheduled count of 2 + group_params[0].smCount = 4 + group_params[0].coscheduledSmCount = 2 + + err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + assert err == cuda.CUresult.CUDA_SUCCESS + assert len(res) == nb_groups + assert rem is not None or len(res) > 0 + + # Test case 2: Split into 2 groups (if device has enough SMs) + # First, get the device resource again for a fresh split + err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) + assert err == cuda.CUresult.CUDA_SUCCESS + + nb_groups = 2 + group_params = [ + cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), + cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), + ] + # First group: request 4 SMs with coscheduled count of 2 + group_params[0].smCount = 4 + group_params[0].coscheduledSmCount = 2 + # Second group: request 4 SMs with coscheduled count of 2 + group_params[1].smCount = 4 + group_params[1].coscheduledSmCount = 2 + + err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + # This may succeed or fail depending on device SM count, but should handle gracefully + if err == cuda.CUresult.CUDA_SUCCESS: + assert len(res) == nb_groups + assert rem is not None or len(res) > 0 + else: + # If it fails, it should be due to insufficient resources, not a binding error + assert err in ( + cuda.CUresult.CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION, + cuda.CUresult.CUDA_ERROR_INVALID_VALUE, + ) + + # Test case 3: Empty list (0 groups) - should handle gracefully + # Note: According to CUDA docs, nbGroups specifies number of groups, so 0 might not be valid + # But we test that the binding accepts an empty list without crashing + nb_groups = 0 + group_params = [] + + err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + # With 0 groups, result should be empty + if err == cuda.CUresult.CUDA_SUCCESS: + assert len(res) == 0 + else: + # If it fails, it should be a valid CUDA error, not a Python binding error + assert err in ( + cuda.CUresult.CUDA_ERROR_INVALID_VALUE, + cuda.CUresult.CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION, + ) + + +def test_buffer_reference(): + # Create a host buffer + size = int(1024 * np.uint8().itemsize) + host = np.full(size, 2).astype(np.uint8) + + # Set the buffer to a struct member + memcpyParams = cuda.CUgraphNodeParams() + memcpyParams.memcpy.copyParams.dstHost = host + + # Delete the local reference to the host buffer. The reference in the + # struct should keep it alive. + del host + + # Create a new numpy array from the pointer and make sure the memory is + # intact and hasn't been freed. If the reference counting in + # copyParams.dstHost is incorrect, we will either see over-written memory or + # a segmentation fault here. + ptr = ctypes.cast(memcpyParams.memcpy.copyParams.dstHost, ctypes.POINTER(ctypes.c_uint8)) + x = np.ctypeslib.as_array(ptr, shape=(size,)) + assert np.all(x == 2) + + +def test_array_setter_no_double_free_after_clearing_with_empty_list(): + # Regression test for a double-free in the generated setters for + # list-valued struct members (e.g. CUlaunchConfig.attrs, + # CUDA_MEM_ALLOC_NODE_PARAMS.accessDescs, ...). Assigning an empty list + # used to free the internal buffer but leave the cached pointer non-NULL; + # the next assignment (or __dealloc__) would call free() on that dangling + # pointer, causing a double-free that glibc aborts via SIGABRT. + # + # CUlaunchConfig.attrs is exercised here as one representative instance; + # the same pattern was applied across many setters in driver.pyx.in and + # runtime.pyx.in. + # + # The reproducer runs in a subprocess so that a glibc abort surfaces as + # a non-zero return code instead of tearing down the pytest process. + code = textwrap.dedent( + """ + import cuda.bindings.driver as cuda + + params = cuda.CUlaunchConfig() + # Allocate the internal buffer. + params.attrs = [cuda.CUlaunchAttribute() for _ in range(4)] + # Free it. Pre-fix, self._attrs is left pointing at freed memory. + params.attrs = [] + # Length mismatch (0 vs 8) takes the else branch and calls free() + # again on the dangling pointer. + params.attrs = [cuda.CUlaunchAttribute() for _ in range(8)] + """ + ) + proc = subprocess.run([sys.executable, "-c", code], capture_output=True, cwd=os.path.dirname(__file__)) # noqa: S603 + assert proc.returncode == 0, ( + f"reproducer subprocess exited with code {proc.returncode}; stderr: {proc.stderr.decode(errors='replace')}" + ) + + +def test_dealloc_clears_array_field_in_external_struct(): + # Regression test for the externally-owned-memory case of the same bug. + # + # When a wrapper aliases an externally-owned struct (constructed with + # `_ptr=...`), `__dealloc__` used to free its internal buffer but leave + # `self._pvt_ptr[0].` pointing at the freed memory. Anyone still + # holding the external struct (the owning wrapper, a parent struct, or + # the CUDA driver itself) would see a dangling pointer. + # + # CUlaunchConfig.attrs is exercised here as one representative instance; + # the same pattern was applied across the `__dealloc__` methods in + # driver.pyx.in and runtime.pyx.in. + outer = cuda.CUlaunchConfig() + # `inner` aliases the same underlying struct as `outer`. + inner = cuda.CUlaunchConfig(_ptr=outer.getPtr()) + # Allocates a buffer and writes its pointer into the shared struct's + # `attrs` field. + inner.attrs = [cuda.CUlaunchAttribute() for _ in range(4)] + + # Locate `attrs` in the C struct by scanning for the just-written + # pointer. The struct is small and only `attrs` is non-NULL. + struct_addr = outer.getPtr() + word_size = ctypes.sizeof(ctypes.c_void_p) + scan_words = 128 // word_size + words = (ctypes.c_void_p * scan_words).from_address(struct_addr) + attrs_offset = next( + (i * word_size for i, p in enumerate(words) if p), + None, + ) + assert attrs_offset is not None, "attrs pointer was not written into the C struct" + + # Destroy the wrapper. With the fix, __dealloc__ also clears the field + # in the externally-owned struct; without it, the field remains dangling. + del inner + + attrs_after = ctypes.c_void_p.from_address(struct_addr + attrs_offset).value + assert attrs_after is None, ( + f"external struct still holds a dangling pointer ({attrs_after:#x}) " + "where attrs was, after the aliasing wrapper was destroyed" + ) diff --git a/cuda_bindings/tests/legacy_api/test_legacy_cudart.py b/cuda_bindings/tests/legacy_api/test_legacy_cudart.py new file mode 100644 index 00000000000..3dc4fba7461 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_cudart.py @@ -0,0 +1,1981 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import ctypes +import math + +import numpy as np +import pytest +from cuda_python_test_helpers.mempool import xfail_if_mempool_oom + +import cuda.bindings.driver as cuda +import cuda.bindings.runtime as cudart +from cuda import pathfinder +from cuda.bindings import runtime +from cuda_python_test_helpers import driver_version_less_than + + +def isSuccess(err): + return err == cudart.cudaError_t.cudaSuccess + + +def assertSuccess(err): + assert isSuccess(err) + + +def supportsMemoryPool(): + err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrMemoryPoolsSupported, 0) + return isSuccess(err) and isSupported + + +def supportsSparseTexturesDeviceFilter(): + err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrSparseCudaArraySupported, 0) + return isSuccess(err) and isSupported + + +def supportsCudaAPI(name): + return name in dir(cuda) or name in dir(cudart) + + +@pytest.mark.agent_authored(model="claude-opus-5") +def test_supportsCudaAPI(): + # Guards the operator precedence: `name in dir(cuda) or dir(cudart)` parses + # as `(name in dir(cuda)) or dir(cudart)`, which is truthy for every name. + assert supportsCudaAPI("cudaMalloc") is True # runtime module + assert supportsCudaAPI("cuInit") is True # driver module + assert supportsCudaAPI("this_is_not_a_cuda_api") is False + + +def test_cudart_memcpy(): + # Allocate dev memory + size = 1024 * np.uint8().itemsize + err, dptr = cudart.cudaMalloc(size) + assertSuccess(err) + + # Set h1 and h2 memory to be different + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # h1 to D + (err,) = cudart.cudaMemcpy(dptr, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # D to h2 + (err,) = cudart.cudaMemcpy(h2, dptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # Validate h1 == h2 + assert np.array_equal(h1, h2) + + # Cleanup + (err,) = cudart.cudaFree(dptr) + assertSuccess(err) + + +def test_cudart_hostRegister(): + # Use hostRegister API to check for correct enum return values + page_size = 80 + addr_host = np.full(page_size * 3, 1).astype(np.uint8) + addr = addr_host.ctypes.data + + size_0 = (16 * page_size) / 8 + addr_0 = addr + int((0 * page_size) / 8) + size_1 = (16 * page_size) / 8 + addr_1 = addr + int((8 * page_size) / 8) + + (err,) = cudart.cudaHostRegister(addr_0, size_0, 3) + assertSuccess(err) + (err,) = cudart.cudaHostRegister(addr_1, size_1, 3) + assert err == cudart.cudaError_t.cudaErrorHostMemoryAlreadyRegistered + + (err,) = cudart.cudaHostUnregister(addr_1) + assert err == cudart.cudaError_t.cudaErrorInvalidValue + (err,) = cudart.cudaHostUnregister(addr_0) + assertSuccess(err) + + +def test_cudart_class_reference(): + offset = 1 + width = 4 + height = 5 + depth = 6 + flags = 0 + numMipLevels = 1 + + extent = cudart.cudaExtent() + formatDesc = cudart.cudaChannelFormatDesc() + externalMemoryMipmappedArrayDesc = cudart.cudaExternalMemoryMipmappedArrayDesc() + + # Get/set class attributes + extent.width = width + extent.height = height + extent.depth = depth + + formatDesc.x = 8 + formatDesc.y = 0 + formatDesc.z = 0 + formatDesc.w = 0 + formatDesc.f = cudart.cudaChannelFormatKind.cudaChannelFormatKindSigned + + externalMemoryMipmappedArrayDesc.offset = offset + externalMemoryMipmappedArrayDesc.formatDesc = formatDesc + externalMemoryMipmappedArrayDesc.extent = extent + externalMemoryMipmappedArrayDesc.flags = flags + externalMemoryMipmappedArrayDesc.numLevels = numMipLevels + + # Can manipulate child structure values directly + externalMemoryMipmappedArrayDesc.extent.width = width + 1 + externalMemoryMipmappedArrayDesc.extent.height = height + 1 + externalMemoryMipmappedArrayDesc.extent.depth = depth + 1 + assert externalMemoryMipmappedArrayDesc.extent.width == width + 1 + assert externalMemoryMipmappedArrayDesc.extent.height == height + 1 + assert externalMemoryMipmappedArrayDesc.extent.depth == depth + 1 + + externalMemoryMipmappedArrayDesc.formatDesc.x = 20 + externalMemoryMipmappedArrayDesc.formatDesc.y = 21 + externalMemoryMipmappedArrayDesc.formatDesc.z = 22 + externalMemoryMipmappedArrayDesc.formatDesc.w = 23 + externalMemoryMipmappedArrayDesc.formatDesc.f = cudart.cudaChannelFormatKind.cudaChannelFormatKindFloat + assert externalMemoryMipmappedArrayDesc.formatDesc.x == 20 + assert externalMemoryMipmappedArrayDesc.formatDesc.y == 21 + assert externalMemoryMipmappedArrayDesc.formatDesc.z == 22 + assert externalMemoryMipmappedArrayDesc.formatDesc.w == 23 + assert externalMemoryMipmappedArrayDesc.formatDesc.f == cudart.cudaChannelFormatKind.cudaChannelFormatKindFloat + + # Can copy classes over + externalMemoryMipmappedArrayDesc.extent = extent + assert externalMemoryMipmappedArrayDesc.extent.width == width + assert externalMemoryMipmappedArrayDesc.extent.height == height + assert externalMemoryMipmappedArrayDesc.extent.depth == depth + + externalMemoryMipmappedArrayDesc.formatDesc = formatDesc + assert externalMemoryMipmappedArrayDesc.formatDesc.x == 8 + assert externalMemoryMipmappedArrayDesc.formatDesc.y == 0 + assert externalMemoryMipmappedArrayDesc.formatDesc.z == 0 + assert externalMemoryMipmappedArrayDesc.formatDesc.w == 0 + assert externalMemoryMipmappedArrayDesc.formatDesc.f == cudart.cudaChannelFormatKind.cudaChannelFormatKindSigned + + +@pytest.mark.skipif(not supportsSparseTexturesDeviceFilter(), reason="Sparse Texture Device Filter") +def test_cudart_class_inline(): + extent = cudart.cudaExtent() + extent.width = 1000 + extent.height = 500 + extent.depth = 0 + + desc = cudart.cudaChannelFormatDesc() + desc.x = 32 + desc.y = 32 + desc.z = 32 + desc.w = 32 + desc.f = cudart.cudaChannelFormatKind.cudaChannelFormatKindFloat + + numChannels = 4 + numBytesPerChannel = desc.x / 8 + numBytesPerTexel = numChannels * numBytesPerChannel + + flags = cudart.cudaArraySparse + maxDim = max(extent.width, extent.height) + numLevels = int(1.0 + math.log(maxDim, 2)) + + err, mipmap = cudart.cudaMallocMipmappedArray(desc, extent, numLevels, flags) + assertSuccess(err) + + err, sparseProp = cudart.cudaMipmappedArrayGetSparseProperties(mipmap) + assertSuccess(err) + + # tileExtent + # TODO: Will these values always be this same? Maybe need a more stable test? + # TODO: Are these values even correct? Need to research the function some more.. Maybe need an easier API test + assert sparseProp.tileExtent.width == 64 + assert sparseProp.tileExtent.height == 64 + assert sparseProp.tileExtent.depth == 1 + + sparsePropNew = cudart.cudaArraySparseProperties() + sparsePropNew.tileExtent.width = 15 + sparsePropNew.tileExtent.height = 16 + sparsePropNew.tileExtent.depth = 17 + + # Check that we can copy inner structs + sparseProp.tileExtent = sparsePropNew.tileExtent + assert sparseProp.tileExtent.width == 15 + assert sparseProp.tileExtent.height == 16 + assert sparseProp.tileExtent.depth == 17 + + assert sparseProp.miptailFirstLevel == 3 + assert sparseProp.miptailSize == 196608 + assert sparseProp.flags == 0 + + (err,) = cudart.cudaFreeMipmappedArray(mipmap) + assertSuccess(err) + + # TODO + example = cudart.cudaExternalSemaphoreSignalNodeParams() + example.extSemArray = [ + cudart.cudaExternalSemaphore_t(0), + cudart.cudaExternalSemaphore_t(123), + cudart.cudaExternalSemaphore_t(999), + ] + a1 = cudart.cudaExternalSemaphoreSignalParams() + a1.params.fence.value = 7 + a1.params.nvSciSync.fence = 999 + a1.params.keyedMutex.key = 9 + a1.flags = 1 + a2 = cudart.cudaExternalSemaphoreSignalParams() + a2.params.fence.value = 7 + a2.params.nvSciSync.fence = 999 + a2.params.keyedMutex.key = 9 + a2.flags = 2 + a3 = cudart.cudaExternalSemaphoreSignalParams() + a3.params.fence.value = 7 + a3.params.nvSciSync.fence = 999 + a3.params.keyedMutex.key = 9 + a3.flags = 3 + example.paramsArray = [a1] + # Note: Setting is a pass by value. Changing the object does not reflect internal value + a3.params.fence.value = 4 + a3.params.nvSciSync.fence = 4 + a3.params.keyedMutex.key = 4 + a3.flags = 4 + example.numExtSems = 3 + + +def test_cudart_graphs(): + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + err, pGraphNode0 = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + err, pGraphNode1 = cudart.cudaGraphAddEmptyNode(graph, [pGraphNode0], 1) + assertSuccess(err) + err, pGraphNode2 = cudart.cudaGraphAddEmptyNode(graph, [pGraphNode0, pGraphNode1], 2) + assertSuccess(err) + + err, nodes, numNodes = cudart.cudaGraphGetNodes(graph) + err, nodes, numNodes = cudart.cudaGraphGetNodes(graph, numNodes) + + stream_legacy = cudart.cudaStream_t(cudart.cudaStreamLegacy) + stream_per_thread = cudart.cudaStream_t(cudart.cudaStreamPerThread) + err, stream_with_flags = cudart.cudaStreamCreateWithFlags(cudart.cudaStreamNonBlocking) + assertSuccess(err) + + +def test_cudart_cudaGraphGetEdges_edgeData_outlives_call(): + # Regression test for https://github.com/NVIDIA/cuda-python/issues/1804 + # cudaGraphGetEdges previously returned cudaGraphEdgeData wrappers backed + # by a scratch buffer that was freed before the call returned, leaving + # the wrappers pointing at freed memory. Ensure the returned objects + # remain readable after the call and after subsequent allocations. + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + try: + err, n0 = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + err, n1 = cudart.cudaGraphAddEmptyNode(graph, [n0], 1) + assertSuccess(err) + err, n2 = cudart.cudaGraphAddEmptyNode(graph, [n0, n1], 2) + assertSuccess(err) + + err, _, _, _, num_edges = cudart.cudaGraphGetEdges(graph) + assertSuccess(err) + assert num_edges == 3 + err, from_nodes, to_nodes, edge_data, num_edges = cudart.cudaGraphGetEdges(graph, num_edges) + assertSuccess(err) + assert len(edge_data) == num_edges == 3 + + # Stir the heap to make a use-after-free more likely to surface + # by reallocating the same-sized scratch buffer many times. + for _ in range(64): + err, _, _, _, _ = cudart.cudaGraphGetEdges(graph, num_edges) + assertSuccess(err) + + # Each wrapper must still own its data. Default-edge values are zero; + # if the wrapper were holding a dangling pointer, attribute access + # would be undefined behavior. We at minimum require it to not crash + # and to report the documented defaults. + for ed in edge_data: + assert ed.from_port == 0 + assert ed.to_port == 0 + assert int(ed.type) == 0 + finally: + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + + +def test_cudart_cudaGraphNodeGetDependencies_edgeData_outlives_call(): + # Companion regression test for #1804 covering the dependency-query path. + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + try: + err, n0 = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + err, n1 = cudart.cudaGraphAddEmptyNode(graph, [n0], 1) + assertSuccess(err) + + err, _, _, num_deps = cudart.cudaGraphNodeGetDependencies(n1) + assertSuccess(err) + assert num_deps == 1 + err, deps, edge_data, num_deps = cudart.cudaGraphNodeGetDependencies(n1, num_deps) + assertSuccess(err) + assert len(edge_data) == num_deps == 1 + + err, _, _, num_dependents = cudart.cudaGraphNodeGetDependentNodes(n0) + assertSuccess(err) + assert num_dependents == 1 + err, dependents, dep_edge_data, num_dependents = cudart.cudaGraphNodeGetDependentNodes(n0, num_dependents) + assertSuccess(err) + assert len(dep_edge_data) == num_dependents == 1 + + for _ in range(64): + err, _, _, _ = cudart.cudaGraphNodeGetDependencies(n1, num_deps) + assertSuccess(err) + err, _, _, _ = cudart.cudaGraphNodeGetDependentNodes(n0, num_dependents) + assertSuccess(err) + + for ed in edge_data + dep_edge_data: + assert ed.from_port == 0 + assert ed.to_port == 0 + assert int(ed.type) == 0 + finally: + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + + +def test_cudart_list_access(): + err, prop = cudart.cudaGetDeviceProperties(0) + prop.name = prop.name + b" " * (256 - len(prop.name)) + + +def test_cudart_class_setters(): + dim = cudart.dim3() + + dim.x = 1 + dim.y = 2 + dim.z = 3 + + assert dim.x == 1 + assert dim.y == 2 + assert dim.z == 3 + + +def test_cudart_both_type(): + err, mode = cudart.cudaThreadExchangeStreamCaptureMode(cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) + assertSuccess(err) + err, mode = cudart.cudaThreadExchangeStreamCaptureMode(cudart.cudaStreamCaptureMode.cudaStreamCaptureModeRelaxed) + assertSuccess(err) + assert mode == cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal + err, mode = cudart.cudaThreadExchangeStreamCaptureMode( + cudart.cudaStreamCaptureMode.cudaStreamCaptureModeThreadLocal + ) + assertSuccess(err) + assert mode == cudart.cudaStreamCaptureMode.cudaStreamCaptureModeRelaxed + err, mode = cudart.cudaThreadExchangeStreamCaptureMode(cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) + assertSuccess(err) + assert mode == cudart.cudaStreamCaptureMode.cudaStreamCaptureModeThreadLocal + + +def test_cudart_cudaGetDeviceProperties(): + err, prop = cudart.cudaGetDeviceProperties(0) + assertSuccess(err) + attrs = [ + "name", + "uuid", + "luid", + "luidDeviceNodeMask", + "totalGlobalMem", + "sharedMemPerBlock", + "regsPerBlock", + "warpSize", + "memPitch", + "maxThreadsPerBlock", + "maxThreadsDim", + "maxGridSize", + "totalConstMem", + "major", + "minor", + "textureAlignment", + "texturePitchAlignment", + "multiProcessorCount", + "integrated", + "canMapHostMemory", + "maxTexture1D", + "maxTexture1DMipmap", + "maxTexture2D", + "maxTexture2DMipmap", + "maxTexture2DLinear", + "maxTexture2DGather", + "maxTexture3D", + "maxTexture3DAlt", + "maxTextureCubemap", + "maxTexture1DLayered", + "maxTexture2DLayered", + "maxTextureCubemapLayered", + "maxSurface1D", + "maxSurface2D", + "maxSurface3D", + "maxSurface1DLayered", + "maxSurface2DLayered", + "maxSurfaceCubemap", + "maxSurfaceCubemapLayered", + "surfaceAlignment", + "concurrentKernels", + "ECCEnabled", + "pciBusID", + "pciDeviceID", + "pciDomainID", + "tccDriver", + "asyncEngineCount", + "unifiedAddressing", + "memoryBusWidth", + "l2CacheSize", + "persistingL2CacheMaxSize", + "maxThreadsPerMultiProcessor", + "streamPrioritiesSupported", + "globalL1CacheSupported", + "localL1CacheSupported", + "sharedMemPerMultiprocessor", + "regsPerMultiprocessor", + "managedMemory", + "isMultiGpuBoard", + "multiGpuBoardGroupID", + "hostNativeAtomicSupported", + "pageableMemoryAccess", + "concurrentManagedAccess", + "computePreemptionSupported", + "canUseHostPointerForRegisteredMem", + "cooperativeLaunch", + "sharedMemPerBlockOptin", + "pageableMemoryAccessUsesHostPageTables", + "directManagedMemAccessFromHost", + "maxBlocksPerMultiProcessor", + "accessPolicyMaxWindowSize", + "reservedSharedMemPerBlock", + "hostRegisterSupported", + "sparseCudaArraySupported", + "hostRegisterReadOnlySupported", + "timelineSemaphoreInteropSupported", + "memoryPoolsSupported", + "gpuDirectRDMASupported", + "gpuDirectRDMAFlushWritesOptions", + "gpuDirectRDMAWritesOrdering", + "memoryPoolSupportedHandleTypes", + "deferredMappingCudaArraySupported", + "ipcEventSupported", + "clusterLaunch", + "unifiedFunctionPointers", + "deviceNumaConfig", + "deviceNumaId", + "mpsEnabled", + "hostNumaId", + "gpuPciDeviceID", + "gpuPciSubsystemID", + "hostNumaMultinodeIpcSupported", + ] + for attr in attrs: + assert hasattr(prop, attr) + assert len(prop.name.decode("utf-8")) != 0 + assert len(prop.uuid.bytes.hex()) != 0 + + example = cudart.cudaExternalSemaphoreSignalNodeParams() + example.extSemArray = [ + cudart.cudaExternalSemaphore_t(0), + cudart.cudaExternalSemaphore_t(123), + cudart.cudaExternalSemaphore_t(999), + ] + a1 = cudart.cudaExternalSemaphoreSignalParams() + a1.params.fence.value = 7 + a1.params.nvSciSync.fence = 999 + a1.params.keyedMutex.key = 9 + a1.flags = 1 + a2 = cudart.cudaExternalSemaphoreSignalParams() + a2.params.fence.value = 7 + a2.params.nvSciSync.fence = 999 + a2.params.keyedMutex.key = 9 + a2.flags = 2 + a3 = cudart.cudaExternalSemaphoreSignalParams() + a3.params.fence.value = 7 + a3.params.nvSciSync.fence = 999 + a3.params.keyedMutex.key = 9 + a3.flags = 3 + example.paramsArray = [a1] + # Note: Setting is a pass by value. Changing the object does not reflect internal value + a3.params.fence.value = 4 + a3.params.nvSciSync.fence = 4 + a3.params.keyedMutex.key = 4 + a3.flags = 4 + example.numExtSems = 3 + + +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsMemoryPool(), reason="When new attributes were introduced" +) +def test_cudart_MemPool_attr(): + poolProps = cudart.cudaMemPoolProps() + poolProps.allocType = cudart.cudaMemAllocationType.cudaMemAllocationTypePinned + poolProps.location.id = 0 + poolProps.location.type = cudart.cudaMemLocationType.cudaMemLocationTypeDevice + + attr_list = [None] * 8 + err, pool = cudart.cudaMemPoolCreate(poolProps) + xfail_if_mempool_oom(err, "cudaMemPoolCreate", poolProps.location.id) + assertSuccess(err) + + for idx, attr in enumerate( + [ + cudart.cudaMemPoolAttr.cudaMemPoolReuseFollowEventDependencies, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowOpportunistic, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowInternalDependencies, + cudart.cudaMemPoolAttr.cudaMemPoolAttrReleaseThreshold, + cudart.cudaMemPoolAttr.cudaMemPoolAttrReservedMemCurrent, + cudart.cudaMemPoolAttr.cudaMemPoolAttrReservedMemHigh, + cudart.cudaMemPoolAttr.cudaMemPoolAttrUsedMemCurrent, + cudart.cudaMemPoolAttr.cudaMemPoolAttrUsedMemHigh, + ] + ): + err, attr_tmp = cudart.cudaMemPoolGetAttribute(pool, attr) + assertSuccess(err) + attr_list[idx] = attr_tmp + + for idxA, attr in enumerate( + [ + cudart.cudaMemPoolAttr.cudaMemPoolReuseFollowEventDependencies, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowOpportunistic, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowInternalDependencies, + ] + ): + (err,) = cudart.cudaMemPoolSetAttribute(pool, attr, 0) + assertSuccess(err) + for idx, attr in enumerate([cudart.cudaMemPoolAttr.cudaMemPoolAttrReleaseThreshold]): + (err,) = cudart.cudaMemPoolSetAttribute(pool, attr, cuda.cuuint64_t(9)) + assertSuccess(err) + + for idx, attr in enumerate( + [ + cudart.cudaMemPoolAttr.cudaMemPoolReuseFollowEventDependencies, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowOpportunistic, + cudart.cudaMemPoolAttr.cudaMemPoolReuseAllowInternalDependencies, + cudart.cudaMemPoolAttr.cudaMemPoolAttrReleaseThreshold, + ] + ): + err, attr_tmp = cudart.cudaMemPoolGetAttribute(pool, attr) + assertSuccess(err) + attr_list[idx] = attr_tmp + assert attr_list[0] == 0 + assert attr_list[1] == 0 + assert attr_list[2] == 0 + assert int(attr_list[3]) == 9 + + (err,) = cudart.cudaMemPoolDestroy(pool) + assertSuccess(err) + + +def test_cudart_make_api(): + err, channelDesc = cudart.cudaCreateChannelDesc( + 32, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindFloat + ) + assertSuccess(err) + assert channelDesc.x == 32 + assert channelDesc.y == 0 + assert channelDesc.z == 0 + assert channelDesc.w == 0 + assert channelDesc.f == cudart.cudaChannelFormatKind.cudaChannelFormatKindFloat + + # make_cudaPitchedPtr + cudaPitchedPtr = cudart.make_cudaPitchedPtr(1, 2, 3, 4) + assert cudaPitchedPtr.ptr == 1 + assert cudaPitchedPtr.pitch == 2 + assert cudaPitchedPtr.xsize == 3 + assert cudaPitchedPtr.ysize == 4 + + # make_cudaPos + cudaPos = cudart.make_cudaPos(1, 2, 3) + assert cudaPos.x == 1 + assert cudaPos.y == 2 + assert cudaPos.z == 3 + + # make_cudaExtent + cudaExtent = cudart.make_cudaExtent(1, 2, 3) + assert cudaExtent.width == 1 + assert cudaExtent.height == 2 + assert cudaExtent.depth == 3 + + +def test_cudart_cudaStreamGetCaptureInfo(): + # create stream + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # validate that stream is not capturing + err, status, *info = cudart.cudaStreamGetCaptureInfo(stream) + assertSuccess(err) + assert status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusNone + + # start capture + (err,) = cudart.cudaStreamBeginCapture(stream, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) + assertSuccess(err) + + # validate that stream is capturing now + err, status, *info = cudart.cudaStreamGetCaptureInfo(stream) + assertSuccess(err) + assert status == cudart.cudaStreamCaptureStatus.cudaStreamCaptureStatusActive + + # clean up + err, pgraph = cudart.cudaStreamEndCapture(stream) + assertSuccess(err) + + +def test_cudart_cudaArrayGetInfo(): + # create channel descriptor + x, y, z, w = 8, 0, 0, 0 + f = cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned + err, desc = cudart.cudaCreateChannelDesc(x, y, z, w, f) + assertSuccess(err) + + # allocate device array + width = 10 + height = 0 + inFlags = 0 + err, arr = cudart.cudaMallocArray(desc, width, height, inFlags) + assertSuccess(err) + + # get device array info + err, desc, extent, outFlags = cudart.cudaArrayGetInfo(arr) + assertSuccess(err) + + # validate descriptor, extent, flags + assert desc.x == x + assert desc.y == y + assert desc.z == z + assert desc.w == w + assert desc.f == f + assert extent.width == width + assert extent.height == height + assert inFlags == outFlags + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + + +def test_cudart_cudaMemcpy2DToArray(): + # create host arrays + size = int(1024 * np.uint8().itemsize) + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to arr + (err,) = cudart.cudaMemcpy2DToArray(arr, 0, 0, h1, size, size, 1, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # arr to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, arr, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + + +def test_cudart_cudaMemcpy2DToArray_DtoD(): + # allocate device memory + size = 1024 * np.uint8().itemsize + err, d1 = cudart.cudaMalloc(size) + assertSuccess(err) + err, d2 = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to d1 + (err,) = cudart.cudaMemcpy(d1, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # d1 to arr + (err,) = cudart.cudaMemcpy2DToArray(arr, 0, 0, d1, size, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice) + assertSuccess(err) + + # arr to d2 + (err,) = cudart.cudaMemcpy2DFromArray(d2, size, arr, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice) + assertSuccess(err) + + # d2 to h2 + (err,) = cudart.cudaMemcpy(h2, d2, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + (err,) = cudart.cudaFree(d2) + assertSuccess(err) + (err,) = cudart.cudaFree(d1) + assertSuccess(err) + + +def test_cudart_cudaMemcpy2DArrayToArray(): + # create host arrays + size = 1024 * np.uint8().itemsize + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device arrays + err, a1 = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + err, a2 = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to a1 + (err,) = cudart.cudaMemcpy2DToArray(a1, 0, 0, h1, size, size, 1, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # a1 to a2 + (err,) = cudart.cudaMemcpy2DArrayToArray( + a2, 0, 0, a1, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice + ) + assertSuccess(err) + + # a2 to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, a2, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(a2) + assertSuccess(err) + (err,) = cudart.cudaFreeArray(a1) + assertSuccess(err) + + +def test_cudart_cudaMemcpyArrayToArray(): + # create host arrays + size = 1024 * np.uint8().itemsize + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device arrays + err, a1 = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + err, a2 = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to a1 + (err,) = cudart.cudaMemcpy2DToArray(a1, 0, 0, h1, size, size, 1, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # a1 to a2 + (err,) = cudart.cudaMemcpyArrayToArray(a2, 0, 0, a1, 0, 0, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice) + assertSuccess(err) + + # a2 to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, a2, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(a2) + assertSuccess(err) + (err,) = cudart.cudaFreeArray(a1) + assertSuccess(err) + + +def test_cudart_cudaGetChannelDesc(): + # create channel descriptor + x, y, z, w = 8, 0, 0, 0 + f = cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned + err, desc = cudart.cudaCreateChannelDesc(x, y, z, w, f) + assertSuccess(err) + + # allocate device array + width = 10 + height = 0 + flags = 0 + err, arr = cudart.cudaMallocArray(desc, width, height, flags) + assertSuccess(err) + + # get channel descriptor from array + err, desc = cudart.cudaGetChannelDesc(arr) + assertSuccess(err) + + # validate array channel descriptor + assert desc.x == x + assert desc.y == y + assert desc.z == z + assert desc.w == w + assert desc.f == f + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + + +def test_cudart_cudaGetTextureObjectTextureDesc(): + # create channel descriptor + err, channelDesc = cudart.cudaCreateChannelDesc( + 8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned + ) + assertSuccess(err) + + # allocate device arrays + err, arr = cudart.cudaMallocArray(channelDesc, 1024, 0, 0) + assertSuccess(err) + + # create descriptors for texture object + resDesc = cudart.cudaResourceDesc() + resDesc.res.array.array = arr + inTexDesc = cudart.cudaTextureDesc() + + # create texture object + err, texObject = cudart.cudaCreateTextureObject(resDesc, inTexDesc, None) + assertSuccess(err) + + # get texture descriptor + err, outTexDesc = cudart.cudaGetTextureObjectTextureDesc(texObject) + assertSuccess(err) + + # validate texture descriptor + for attr in dir(outTexDesc): + if attr in ["borderColor", "getPtr"]: + continue + if not attr.startswith("_"): + assert getattr(outTexDesc, attr) == getattr(inTexDesc, attr) + + # clean up + (err,) = cudart.cudaDestroyTextureObject(texObject) + assertSuccess(err) + + +def test_cudart_cudaMemset3D(): + # create host arrays + size = 1024 * np.uint8().itemsize + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # allocate device memory + devExtent = cudart.make_cudaExtent(32, 32, 1) + err, devPitchedPtr = cudart.cudaMalloc3D(devExtent) + assertSuccess(err) + + # set memory + memExtent = cudart.make_cudaExtent(devPitchedPtr.pitch, devPitchedPtr.ysize, 1) + (err,) = cudart.cudaMemset3D(devPitchedPtr, 1, memExtent) + assertSuccess(err) + + # D to h2 + (err,) = cudart.cudaMemcpy(h2, devPitchedPtr.ptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFree(devPitchedPtr.ptr) + assertSuccess(err) + + +def test_cudart_cudaMemset3D_2D(): + # create host arrays + size = 512 * np.uint8().itemsize + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # allocate device memory + devExtent = cudart.make_cudaExtent(1024, 1, 1) + err, devPitchedPtr = cudart.cudaMalloc3D(devExtent) + assertSuccess(err) + + # set memory + memExtent = cudart.make_cudaExtent(size, devPitchedPtr.ysize, 1) + (err,) = cudart.cudaMemset3D(devPitchedPtr, 1, memExtent) + assertSuccess(err) + + # D to h2 + (err,) = cudart.cudaMemcpy(h2, devPitchedPtr.ptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFree(devPitchedPtr.ptr) + assertSuccess(err) + + +def test_cudart_cudaMemcpyToArray(): + # create host arrays + size = 1024 * np.uint8().itemsize + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to arr + (err,) = cudart.cudaMemcpyToArray(arr, 0, 0, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # arr to h2 + (err,) = cudart.cudaMemcpyFromArray(h2, arr, 0, 0, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + + +def test_cudart_cudaMemcpyToArray_DtoD(): + # allocate device memory + size = int(1024 * np.uint8().itemsize) + err, d1 = cudart.cudaMalloc(size) + assertSuccess(err) + err, d2 = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # h1 to d1 + (err,) = cudart.cudaMemcpy(d1, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # d1 to arr + (err,) = cudart.cudaMemcpyToArray(arr, 0, 0, d1, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice) + assertSuccess(err) + + # arr to d2 + (err,) = cudart.cudaMemcpyFromArray(d2, arr, 0, 0, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice) + assertSuccess(err) + + # d2 to h2 + (err,) = cudart.cudaMemcpy(h2, d2, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + (err,) = cudart.cudaFree(d2) + assertSuccess(err) + (err,) = cudart.cudaFree(d1) + assertSuccess(err) + + +def test_cudart_cudaMemcpy3DAsync(): + # create host arrays + size = int(1024 * np.uint8().itemsize) + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # create stream + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # create memcpy params + params = cudart.cudaMemcpy3DParms() + params.srcPtr = cudart.make_cudaPitchedPtr(h1, size, 1, 1) + params.dstArray = arr + params.extent = cudart.make_cudaExtent(size, 1, 1) + params.kind = cudart.cudaMemcpyKind.cudaMemcpyHostToDevice + + # h1 to arr + (err,) = cudart.cudaMemcpy3DAsync(params, stream) + assertSuccess(err) + + # await results + (err,) = cudart.cudaStreamSynchronize(stream) + assertSuccess(err) + + # arr to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, arr, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + + +def test_cudart_cudaGraphAddMemcpyNode1D(): + # allocate device memory + size = 1024 * np.uint8().itemsize + err, dptr = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # build graph + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + # add nodes + err, hToDNode = cudart.cudaGraphAddMemcpyNode1D( + graph, [], 0, dptr, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice + ) + assertSuccess(err) + err, dToHNode = cudart.cudaGraphAddMemcpyNode1D( + graph, [hToDNode], 1, h2, dptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost + ) + assertSuccess(err) + + # create stream + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # execute graph + err, execGraph = cudart.cudaGraphInstantiate(graph, 0) + assertSuccess(err) + (err,) = cudart.cudaGraphLaunch(execGraph, stream) + + # await results + (err,) = cudart.cudaStreamSynchronize(stream) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFree(dptr) + assertSuccess(err) + + +def test_cudart_cudaGraphAddMemsetNode(): + # allocate device memory + size = 1024 * np.uint8().itemsize + err, dptr = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # build graph + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + # set memset params + params = cudart.cudaMemsetParams() + params.dst = dptr + params.pitch = size + params.value = 1 + params.elementSize = 1 + params.width = size + params.height = 1 + + # add nodes + err, setNode = cudart.cudaGraphAddMemsetNode(graph, [], 0, params) + assertSuccess(err) + err, cpyNode = cudart.cudaGraphAddMemcpyNode1D( + graph, [setNode], 1, h2, dptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost + ) + assertSuccess(err) + + # create stream + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # execute graph + err, execGraph = cudart.cudaGraphInstantiate(graph, 0) + assertSuccess(err) + (err,) = cudart.cudaGraphLaunch(execGraph, stream) + assertSuccess(err) + + # await results + (err,) = cudart.cudaStreamSynchronize(stream) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFree(dptr) + assertSuccess(err) + + +def test_cudart_cudaMemcpy3DPeer(): + # allocate device memory + size = int(1024 * np.uint8().itemsize) + err, dptr = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # create memcpy params + params = cudart.cudaMemcpy3DPeerParms() + params.srcPtr = cudart.make_cudaPitchedPtr(dptr, size, 1, 1) + params.dstArray = arr + params.extent = cudart.make_cudaExtent(size, 1, 1) + + # h1 to D + (err,) = cudart.cudaMemcpy(dptr, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # D to arr + (err,) = cudart.cudaMemcpy3DPeer(params) + assertSuccess(err) + + # arr to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, arr, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + (err,) = cudart.cudaFree(dptr) + assertSuccess(err) + + +def test_cudart_cudaMemcpy3DPeerAsync(): + # allocate device memory + size = 1024 * np.uint8().itemsize + err, dptr = cudart.cudaMalloc(size) + assertSuccess(err) + + # create host arrays + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # create channel descriptor + err, desc = cudart.cudaCreateChannelDesc(8, 0, 0, 0, cudart.cudaChannelFormatKind.cudaChannelFormatKindUnsigned) + assertSuccess(err) + + # allocate device array + err, arr = cudart.cudaMallocArray(desc, size, 0, 0) + assertSuccess(err) + + # create stream + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # create memcpy params + params = cudart.cudaMemcpy3DPeerParms() + params.srcPtr = cudart.make_cudaPitchedPtr(dptr, size, 1, 1) + params.dstArray = arr + params.extent = cudart.make_cudaExtent(size, 1, 1) + + # h1 to D + (err,) = cudart.cudaMemcpy(dptr, h1, size, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice) + assertSuccess(err) + + # ensure the DMA to device memory has completed + (err,) = cudart.cudaStreamSynchronize(0) + assertSuccess(err) + + # D to arr + (err,) = cudart.cudaMemcpy3DPeerAsync(params, stream) + assertSuccess(err) + + # await results + (err,) = cudart.cudaStreamSynchronize(stream) + assertSuccess(err) + + # arr to h2 + (err,) = cudart.cudaMemcpy2DFromArray(h2, size, arr, 0, 0, size, 1, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assertSuccess(err) + + # validate h1 == h2 + assert np.array_equal(h1, h2) + + # clean up + (err,) = cudart.cudaFreeArray(arr) + assertSuccess(err) + (err,) = cudart.cudaFree(dptr) + assertSuccess(err) + + +def test_profiler(): + (err,) = cudart.cudaProfilerStart() + assertSuccess(err) + (err,) = cudart.cudaProfilerStop() + assertSuccess(err) + + +def test_cudart_eglFrame(): + frame = cudart.cudaEglFrame() + # [, , ] + assert int(frame.frame.pArray[0]) == 0 + assert int(frame.frame.pArray[1]) == 0 + assert int(frame.frame.pArray[2]) == 0 + frame.frame.pArray = [1, 2, 3] + # [, , ] + assert int(frame.frame.pArray[0]) == 1 + assert int(frame.frame.pArray[1]) == 2 + assert int(frame.frame.pArray[2]) == 3 + frame.frame.pArray = [1, 2, cudart.cudaArray_t(4)] + # [, , ] + assert int(frame.frame.pArray[0]) == 1 + assert int(frame.frame.pArray[1]) == 2 + assert int(frame.frame.pArray[2]) == 4 + # frame.frame.pPitch + # [ptr : 0x1 + # pitch : 2 + # xsize : 4 + # ysize : 0, ptr : 0x0 + # pitch : 0 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 0 + # xsize : 0 + # ysize : 0] + assert int(frame.frame.pPitch[0].ptr) == 1 + assert int(frame.frame.pPitch[0].pitch) == 2 + assert int(frame.frame.pPitch[0].xsize) == 4 + assert int(frame.frame.pPitch[0].ysize) == 0 + assert int(frame.frame.pPitch[1].ptr) == 0 + assert int(frame.frame.pPitch[1].pitch) == 0 + assert int(frame.frame.pPitch[1].xsize) == 0 + assert int(frame.frame.pPitch[1].ysize) == 0 + assert int(frame.frame.pPitch[2].ptr) == 0 + assert int(frame.frame.pPitch[2].pitch) == 0 + assert int(frame.frame.pPitch[2].xsize) == 0 + assert int(frame.frame.pPitch[2].ysize) == 0 + frame.frame.pPitch = [cudart.cudaPitchedPtr(), cudart.cudaPitchedPtr(), cudart.cudaPitchedPtr()] + # [ptr : 0x0 + # pitch : 0 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 0 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 0 + # xsize : 0 + # ysize : 0] + assert int(frame.frame.pPitch[0].ptr) == 0 + assert int(frame.frame.pPitch[0].pitch) == 0 + assert int(frame.frame.pPitch[0].xsize) == 0 + assert int(frame.frame.pPitch[0].ysize) == 0 + assert int(frame.frame.pPitch[1].ptr) == 0 + assert int(frame.frame.pPitch[1].pitch) == 0 + assert int(frame.frame.pPitch[1].xsize) == 0 + assert int(frame.frame.pPitch[1].ysize) == 0 + assert int(frame.frame.pPitch[2].ptr) == 0 + assert int(frame.frame.pPitch[2].pitch) == 0 + assert int(frame.frame.pPitch[2].xsize) == 0 + assert int(frame.frame.pPitch[2].ysize) == 0 + x = frame.frame.pPitch[0] + x.pitch = 123 + frame.frame.pPitch = [x, x, x] + # [ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0] + assert int(frame.frame.pPitch[0].ptr) == 0 + assert int(frame.frame.pPitch[0].pitch) == 123 + assert int(frame.frame.pPitch[0].xsize) == 0 + assert int(frame.frame.pPitch[0].ysize) == 0 + assert int(frame.frame.pPitch[1].ptr) == 0 + assert int(frame.frame.pPitch[1].pitch) == 123 + assert int(frame.frame.pPitch[1].xsize) == 0 + assert int(frame.frame.pPitch[1].ysize) == 0 + assert int(frame.frame.pPitch[2].ptr) == 0 + assert int(frame.frame.pPitch[2].pitch) == 123 + assert int(frame.frame.pPitch[2].xsize) == 0 + assert int(frame.frame.pPitch[2].ysize) == 0 + x.pitch = 1234 + # [ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0, ptr : 0x0 + # pitch : 123 + # xsize : 0 + # ysize : 0] + assert int(frame.frame.pPitch[0].ptr) == 0 + assert int(frame.frame.pPitch[0].pitch) == 123 + assert int(frame.frame.pPitch[0].xsize) == 0 + assert int(frame.frame.pPitch[0].ysize) == 0 + assert int(frame.frame.pPitch[1].ptr) == 0 + assert int(frame.frame.pPitch[1].pitch) == 123 + assert int(frame.frame.pPitch[1].xsize) == 0 + assert int(frame.frame.pPitch[1].ysize) == 0 + assert int(frame.frame.pPitch[2].ptr) == 0 + assert int(frame.frame.pPitch[2].pitch) == 123 + assert int(frame.frame.pPitch[2].xsize) == 0 + assert int(frame.frame.pPitch[2].ysize) == 0 + + +def cudart_func_stream_callback(use_host_api): + class testStruct(ctypes.Structure): + _fields_ = [ + ("a", ctypes.c_int), + ("b", ctypes.c_int), + ("c", ctypes.c_int), + ] + + def task_callback_host(userData): + data = testStruct.from_address(userData) + assert data.a == 1 + assert data.b == 2 + assert data.c == 3 + return 0 + + def task_callback_stream(stream, status, userData): + data = testStruct.from_address(userData) + assert data.a == 1 + assert data.b == 2 + assert data.c == 3 + return 0 + + if use_host_api: + callback_type = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_void_p) + target_task = task_callback_host + else: + callback_type = ctypes.PYFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p) + target_task = task_callback_stream + + # Construct ctype data + c_callback = callback_type(target_task) + c_data = testStruct(1, 2, 3) + + # ctypes is managing the pointer value for us + if use_host_api: + callback = cudart.cudaHostFn_t(_ptr=ctypes.addressof(c_callback)) + else: + callback = cudart.cudaStreamCallback_t(_ptr=ctypes.addressof(c_callback)) + + # Run + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + if use_host_api: + (err,) = cudart.cudaLaunchHostFunc(stream, callback, ctypes.addressof(c_data)) + assertSuccess(err) + else: + (err,) = cudart.cudaStreamAddCallback(stream, callback, ctypes.addressof(c_data), 0) + assertSuccess(err) + (err,) = cudart.cudaDeviceSynchronize() + assertSuccess(err) + + +def test_cudart_func_callback(): + cudart_func_stream_callback(use_host_api=False) + cudart_func_stream_callback(use_host_api=True) + + +@pytest.mark.skipif( + driver_version_less_than(12030) or not supportsCudaAPI("cudaGraphConditionalHandleCreate"), + reason="Conditional graph APIs required", +) +def test_cudart_conditional(): + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + err, handle = cudart.cudaGraphConditionalHandleCreate(graph, 0, 0) + assertSuccess(err) + + params = cudart.cudaGraphNodeParams() + params.type = cudart.cudaGraphNodeType.cudaGraphNodeTypeConditional + params.conditional.handle = handle + params.conditional.type = cudart.cudaGraphConditionalNodeType.cudaGraphCondTypeIf + params.conditional.size = 1 + + assert len(params.conditional.phGraph_out) == 1 + assert int(params.conditional.phGraph_out[0]) == 0 + err, node = cudart.cudaGraphAddNode(graph, None, None, 0, params) + assertSuccess(err) + + assert len(params.conditional.phGraph_out) == 1 + assert int(params.conditional.phGraph_out[0]) != 0 + + +@pytest.mark.parametrize( + "target", + ( + runtime.cudaStream_t, + runtime.cudaEvent_t, + runtime.cudaGraph_t, + runtime.cudaGraphNode_t, + runtime.cudaGraphExec_t, + runtime.cudaMemPool_t, + ), +) +def test_struct_pointer_comparison(target): + a = target(123) + b = target(123) + assert a == b + assert hash(a) == hash(b) + c = target(456) + assert a != c + assert hash(a) != hash(c) + + +def test_getLocalRuntimeVersion(): + # verify that successive calls do not segfault the interpreter + for _ in range(10): + try: + err, version = cudart.getLocalRuntimeVersion() + except pathfinder.DynamicLibNotFoundError: + pytest.skip("cudart dynamic lib not available") + else: + assertSuccess(err) + assert version >= 12000 # CUDA 12.0 + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphGetId"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphGetId(): + """Test cudaGraphGetId - get graph ID.""" + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + err, graph_id = cudart.cudaGraphGetId(graph) + assertSuccess(err) + assert isinstance(graph_id, int) + assert graph_id > 0 + + # Create another graph and verify it has a different ID + err, graph2 = cudart.cudaGraphCreate(0) + assertSuccess(err) + err, graph_id2 = cudart.cudaGraphGetId(graph2) + assertSuccess(err) + assert graph_id2 != graph_id + + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + (err,) = cudart.cudaGraphDestroy(graph2) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphExecGetId"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphExecGetId(): + """Test cudaGraphExecGetId - get graph exec ID.""" + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + # Add an empty node to make the graph valid + err, node = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + + err, graphExec = cudart.cudaGraphInstantiate(graph, 0) + assertSuccess(err) + + err, graph_exec_id = cudart.cudaGraphExecGetId(graphExec) + assertSuccess(err) + assert isinstance(graph_exec_id, int) + assert graph_exec_id > 0 + + # Create another graph exec and verify it has a different ID + err, graph2 = cudart.cudaGraphCreate(0) + assertSuccess(err) + err, node2 = cudart.cudaGraphAddEmptyNode(graph2, None, 0) + assertSuccess(err) + err, graphExec2 = cudart.cudaGraphInstantiate(graph2, 0) + assertSuccess(err) + err, graph_exec_id2 = cudart.cudaGraphExecGetId(graphExec2) + assertSuccess(err) + assert graph_exec_id2 != graph_exec_id + + (err,) = cudart.cudaGraphExecDestroy(graphExec) + assertSuccess(err) + (err,) = cudart.cudaGraphExecDestroy(graphExec2) + assertSuccess(err) + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + (err,) = cudart.cudaGraphDestroy(graph2) + assertSuccess(err) + (err,) = cudart.cudaStreamDestroy(stream) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphNodeGetLocalId"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphNodeGetLocalId(): + """Test cudaGraphNodeGetLocalId - get node local ID.""" + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + # Add multiple nodes + err, node1 = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + + err, node2 = cudart.cudaGraphAddEmptyNode(graph, [node1], 1) + assertSuccess(err) + + err, node3 = cudart.cudaGraphAddEmptyNode(graph, [node1, node2], 2) + assertSuccess(err) + + # Get local IDs for each node + err, node_id1 = cudart.cudaGraphNodeGetLocalId(node1) + assertSuccess(err) + assert isinstance(node_id1, int) + assert node_id1 >= 0 + + err, node_id2 = cudart.cudaGraphNodeGetLocalId(node2) + assertSuccess(err) + assert isinstance(node_id2, int) + assert node_id2 >= 0 + assert node_id2 != node_id1 + + err, node_id3 = cudart.cudaGraphNodeGetLocalId(node3) + assertSuccess(err) + assert isinstance(node_id3, int) + assert node_id3 >= 0 + assert node_id3 != node_id1 + assert node_id3 != node_id2 + + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphNodeGetToolsId"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphNodeGetToolsId(): + """Test cudaGraphNodeGetToolsId - get node tools ID.""" + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + err, node = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + + err, tools_node_id = cudart.cudaGraphNodeGetToolsId(node) + assertSuccess(err) + assert isinstance(tools_node_id, int) + # toolsNodeId is unsigned long long, so it can be any non-negative value + assert tools_node_id >= 0 + + # Add another node and verify it has a different tools ID + err, node2 = cudart.cudaGraphAddEmptyNode(graph, [node], 1) + assertSuccess(err) + err, tools_node_id2 = cudart.cudaGraphNodeGetToolsId(node2) + assertSuccess(err) + assert tools_node_id2 != tools_node_id + + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphNodeGetContainingGraph"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphNodeGetContainingGraph(): + """Test cudaGraphNodeGetContainingGraph - get graph containing a node.""" + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + err, node = cudart.cudaGraphAddEmptyNode(graph, None, 0) + assertSuccess(err) + + # Get the containing graph + err, containing_graph = cudart.cudaGraphNodeGetContainingGraph(node) + assertSuccess(err) + # Verify it's the same graph + assert int(containing_graph) == int(graph) + + # Test with a child graph node (if supported) + # Create a child graph + err, child_graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + err, child_node = cudart.cudaGraphAddEmptyNode(child_graph, None, 0) + assertSuccess(err) + + # Add child graph node to parent graph + childGraphNodeParams = cudart.cudaGraphNodeParams() + childGraphNodeParams.type = cudart.cudaGraphNodeType.cudaGraphNodeTypeGraph + childGraphNodeParams.graph.graph = child_graph + err, child_graph_node = cudart.cudaGraphAddNode(graph, None, None, 0, childGraphNodeParams) + if isSuccess(err): + # Get containing graph for the child graph node + err, containing_graph_for_child = cudart.cudaGraphNodeGetContainingGraph(child_graph_node) + assertSuccess(err) + assert int(containing_graph_for_child) == int(graph) + + # Get containing graph for node inside child graph + err, containing_graph_for_nested = cudart.cudaGraphNodeGetContainingGraph(child_node) + assertSuccess(err) + assert int(containing_graph_for_nested) == int(child_graph) + + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) + (err,) = cudart.cudaGraphDestroy(child_graph) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaStreamGetDevResource"), + reason="Requires CUDA 13.1+", +) +def test_cudaStreamGetDevResource(): + """Test cudaStreamGetDevResource - get device resource from stream.""" + err, stream = cudart.cudaStreamCreate() + assertSuccess(err) + + # Get SM resource from stream + err, resource = cudart.cudaStreamGetDevResource(stream, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + # Verify resource is valid (non-None) + assert resource is not None + + (err,) = cudart.cudaStreamDestroy(stream) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDeviceGetDevResource"), + reason="Requires CUDA 13.1+", +) +def test_cudaDeviceGetDevResource(): + """Test cudaDeviceGetDevResource - get device resource.""" + device = 0 + + # Get SM resource from device + err, resource = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + # Verify resource is valid (non-None) + assert resource is not None + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDeviceGetExecutionCtx"), + reason="Requires CUDA 13.1+", +) +def test_cudaExecutionCtxGetDevResource(): + """Test cudaExecutionCtxGetDevResource - get device resource from execution context.""" + # Get execution context for device 0 (primary context) + err, exec_ctx = cudart.cudaDeviceGetExecutionCtx(0) + assertSuccess(err) + assert exec_ctx is not None + + # Get SM resource from execution context + err, resource = cudart.cudaExecutionCtxGetDevResource(exec_ctx, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + # Verify resource is valid (non-None) + assert resource is not None + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDeviceGetExecutionCtx"), + reason="Requires CUDA 13.1+", +) +def test_cudaExecutionCtxGetDevice(): + """Test cudaExecutionCtxGetDevice - get device from execution context.""" + device = 0 + + # Get execution context for device + err, exec_ctx = cudart.cudaDeviceGetExecutionCtx(device) + assertSuccess(err) + assert exec_ctx is not None + + # Get device from execution context + err, device_from_ctx = cudart.cudaExecutionCtxGetDevice(exec_ctx) + assertSuccess(err) + # Verify it returns the same device + assert device_from_ctx == device + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDeviceGetExecutionCtx"), + reason="Requires CUDA 13.1+", +) +def test_cudaExecutionCtxGetId(): + """Test cudaExecutionCtxGetId - get unique ID from execution context.""" + # Get execution context for device 0 (primary context) + err, exec_ctx = cudart.cudaDeviceGetExecutionCtx(0) + assertSuccess(err) + assert exec_ctx is not None + + # Get unique ID from execution context + err, ctx_id = cudart.cudaExecutionCtxGetId(exec_ctx) + assertSuccess(err) + assert isinstance(ctx_id, int) + assert ctx_id > 0 + + # Get another execution context and verify it has a different ID + err, exec_ctx2 = cudart.cudaDeviceGetExecutionCtx(0) + assertSuccess(err) + # Should return the same context for the same device + assert int(exec_ctx2) == int(exec_ctx) + err, ctx_id2 = cudart.cudaExecutionCtxGetId(exec_ctx2) + assertSuccess(err) + # Should have the same ID since it's the same context + assert ctx_id2 == ctx_id + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDevSmResourceSplit"), + reason="Requires CUDA 13.1+", +) +def test_cudaDevSmResourceSplit(): + """Test cudaDevSmResourceSplit - split SM resource into structured groups.""" + device = 0 + err, resource_in = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + + # Test case 1: Split into 1 group + nb_groups = 1 + group_params = [cudart.cudaDevSmResourceGroupParams()] + # Set up group: request 4 SMs with coscheduled count of 2 + group_params[0].smCount = 4 + group_params[0].coscheduledSmCount = 2 + + err, res, rem = cudart.cudaDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + assertSuccess(err) + assert len(res) == nb_groups + assert rem is not None or len(res) > 0 + + # Test case 2: Split into 2 groups (if device has enough SMs) + # First, get the device resource again for a fresh split + err, resource_in = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + + nb_groups = 2 + group_params = [ + cudart.cudaDevSmResourceGroupParams(), + cudart.cudaDevSmResourceGroupParams(), + ] + # First group: request 4 SMs with coscheduled count of 2 + group_params[0].smCount = 4 + group_params[0].coscheduledSmCount = 2 + # Second group: request 4 SMs with coscheduled count of 2 + group_params[1].smCount = 4 + group_params[1].coscheduledSmCount = 2 + + err, res, rem = cudart.cudaDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + # This may succeed or fail depending on device SM count, but should handle gracefully + if err == cudart.cudaError_t.cudaSuccess: + assert len(res) == nb_groups + assert rem is not None or len(res) > 0 + else: + # If it fails, it should be due to insufficient resources, not a binding error + assert err in ( + cudart.cudaError_t.cudaErrorInvalidResourceConfiguration, + cudart.cudaError_t.cudaErrorInvalidValue, + ) + + # Test case 3: Empty list (0 groups) - should handle gracefully + # Note: According to CUDA docs, nbGroups specifies number of groups, so 0 might not be valid + # But we test that the binding accepts an empty list without crashing + nb_groups = 0 + group_params = [] + + err, res, rem = cudart.cudaDevSmResourceSplit(nb_groups, resource_in, 0, group_params) + # With 0 groups, result should be empty + if err == cudart.cudaError_t.cudaSuccess: + assert len(res) == 0 + else: + # If it fails, it should be a valid CUDA error, not a Python binding error + assert err in ( + cudart.cudaError_t.cudaErrorInvalidValue, + cudart.cudaError_t.cudaErrorInvalidResourceConfiguration, + ) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDevSmResourceSplitByCount"), + reason="Requires CUDA 13.1+", +) +def test_cudaDevSmResourceSplitByCount(): + """Test cudaDevSmResourceSplitByCount - split SM resource by count.""" + device = 0 + err, resource_in = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + + # First call: discovery mode (nbGroups = 0) to get count + err, res, count, rem = cudart.cudaDevSmResourceSplitByCount(0, resource_in, 0, 2) + assertSuccess(err) + assert count > 0 + assert len(res) == 0 # No results in discovery mode + + # Second call: actual split with the discovered count + err, res, count_same, rem = cudart.cudaDevSmResourceSplitByCount(count, resource_in, 0, 2) + assertSuccess(err) + assert count == count_same + assert len(res) == count + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaDevResourceGenerateDesc"), + reason="Requires CUDA 13.1+", +) +def test_cudaDevResourceGenerateDesc(): + """Test cudaDevResourceGenerateDesc - generate resource descriptor.""" + device = 0 + err, resource = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + + # Generate descriptor from a single resource + resources = [resource] + err, desc = cudart.cudaDevResourceGenerateDesc(resources, len(resources)) + assertSuccess(err) + assert desc is not None + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGreenCtxCreate"), + reason="Requires CUDA 13.1+", +) +def test_cudaGreenCtxCreate(): + """Test cudaGreenCtxCreate - create green context with resources.""" + device = 0 + + # Set device to ensure primary context is ready + (err,) = cudart.cudaSetDevice(device) + assertSuccess(err) + + # Get device resource + err, resource = cudart.cudaDeviceGetDevResource(device, cudart.cudaDevResourceType.cudaDevResourceTypeSm) + assertSuccess(err) + + # Generate descriptor + resources = [resource] + err, desc = cudart.cudaDevResourceGenerateDesc(resources, len(resources)) + assertSuccess(err) + + # Create green context + err, green_ctx = cudart.cudaGreenCtxCreate(desc, device, 0) + assertSuccess(err) + assert green_ctx is not None + + # Cleanup: destroy the green context + (err,) = cudart.cudaExecutionCtxDestroy(green_ctx) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaExecutionCtxStreamCreate"), + reason="Requires CUDA 13.1+", +) +def test_cudaExecutionCtxStreamCreate(): + """Test cudaExecutionCtxStreamCreate - create stream for execution context.""" + # Get execution context for device 0 (primary context) + err, exec_ctx = cudart.cudaDeviceGetExecutionCtx(0) + assertSuccess(err) + assert exec_ctx is not None + + # Create stream for the execution context + err, stream = cudart.cudaExecutionCtxStreamCreate(exec_ctx, 0, 0) + assertSuccess(err) + assert stream is not None + + # Cleanup: destroy the stream + (err,) = cudart.cudaStreamDestroy(stream) + assertSuccess(err) + + +@pytest.mark.skipif( + driver_version_less_than(13010) or not supportsCudaAPI("cudaGraphConditionalHandleCreate_v2"), + reason="Requires CUDA 13.1+", +) +def test_cudaGraphConditionalHandleCreate_v2(): + """Test cudaGraphConditionalHandleCreate_v2 - create conditional handle with execution context.""" + err, graph = cudart.cudaGraphCreate(0) + assertSuccess(err) + + # Get execution context (can be None for v2) + err, exec_ctx = cudart.cudaDeviceGetExecutionCtx(0) + assertSuccess(err) + + # Create conditional handle with execution context + err, handle = cudart.cudaGraphConditionalHandleCreate_v2(graph, exec_ctx, 0, 0) + assertSuccess(err) + assert handle is not None + + (err,) = cudart.cudaGraphDestroy(graph) + assertSuccess(err) diff --git a/cuda_bindings/tests/legacy_api/test_legacy_cufile.py b/cuda_bindings/tests/legacy_api/test_legacy_cufile.py new file mode 100644 index 00000000000..b695e254f2b --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_cufile.py @@ -0,0 +1,1915 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import ctypes +import logging +import os +import pathlib +import platform +import subprocess +import tempfile +from contextlib import contextmanager, suppress +from functools import cache + +import pytest + +import cuda.bindings.driver as cuda + +cufile = pytest.importorskip("cuda.bindings.cufile") + +# Configure logging to show INFO level and above +logging.basicConfig( + level=logging.INFO, + format="%(levelname)s: %(message)s", + force=True, # Override any existing logging configuration +) + +cufile = pytest.importorskip("cuda.bindings.cufile", reason="skipping tests on Windows") + + +@contextmanager +def _cufile_driver_session(): + """Open the cuFile driver for a block; always close in a finally (mirrors try/finally).""" + cufile.driver_open() + try: + yield + finally: + cufile.driver_close() + + +@pytest.fixture +def cufile_env_json(monkeypatch): + """Set CUFILE_ENV_PATH_JSON environment variable for async tests.""" + # Get absolute path to cufile.json in the same directory as this test file + test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + config_path = os.path.join(test_dir, "cufile.json") + assert os.path.isfile(config_path) + monkeypatch.setenv("CUFILE_ENV_PATH_JSON", config_path) + logging.info(f"Using cuFile config: {config_path}") + + +@cache +def cufileLibraryAvailable(): + """Check if cuFile library is available on the system.""" + try: + # Try to get cuFile library version - this will fail if library is not available + version = cufile.get_version() + logging.info(f"cuFile library available, version: {version}") + return True + except Exception as e: + logging.warning(f"cuFile library not available: {e}") + return False + + +@cache +def cufileVersionLessThan(target): + """Check if cuFile library version is less than target version.""" + try: + # Get cuFile library version + version = cufile.get_version() + logging.info(f"cuFile library version: {version}") + # Check if version is less than target + if version < target: + logging.warning(f"cuFile library version {version} is less than required {target}") + return True + return False + except Exception as e: + logging.error(f"Error checking cuFile version: {e}") + return True # Assume old version if any error occurs + + +@cache +def isSupportedFilesystem(): + """Check if the current filesystem is supported (ext4 or xfs). + + This uses `findmnt` so the kernel's mount table logic owns the decoding of the filesystem type. + """ + fs_type = subprocess.check_output(["findmnt", "-no", "FSTYPE", "-T", os.getcwd()], text=True).strip() # noqa: S603, S607 + logging.info(f"Current filesystem type (findmnt): {fs_type}") + return fs_type in ("ext4", "xfs") + + +@cache +def get_tegra_kind(): + """Detect Tegra device kind (Orin/Thor) via nvidia-smi, or None if not Tegra.""" + if not pathlib.Path("/etc/nv_tegra_release").exists(): + return None + out = subprocess.check_output(["nvidia-smi"], text=True, stderr=subprocess.STDOUT) # noqa: S607 + tegra_kinds_found = [] + for kind in ("Orin", "Thor"): + if f" {kind} " in out: + tegra_kinds_found.append(kind) + assert len(tegra_kinds_found) == 1, f"UNEXPECTED nvidia-smi output:\n{out}" + return tegra_kinds_found[0] + + +# Global skip condition for all tests if cuFile library is not available +pytestmark = [ + pytest.mark.skipif(not cufileLibraryAvailable(), reason="cuFile library not available on this system"), + pytest.mark.skipif( + platform.system() == "Linux" and "microsoft" in pathlib.Path("/proc/version").read_text().lower(), + reason="skipping cuFile tests on WSL", + ), + pytest.mark.skipif(get_tegra_kind() == "Orin", reason="skipping cuFile tests on Orin (Tegra Linux)"), + pytest.mark.skipif( + get_tegra_kind() == "Thor" and cufileVersionLessThan(1160), + reason="skipping cuFile tests on Thor (Tegra Linux) with CTK < 13.1", + ), +] + + +def test_cufile_success_defined(): + """Check if CUFILE_SUCCESS is defined in OpError enum.""" + assert hasattr(cufile.OpError, "SUCCESS") + + +@pytest.fixture +def ctx(): + # Initialize CUDA + (err,) = cuda.cuInit(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, device = cuda.cuDeviceGet(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, ctx = cuda.cuDevicePrimaryCtxRetain(device) + assert err == cuda.CUresult.CUDA_SUCCESS + + (err,) = cuda.cuCtxSetCurrent(ctx) + assert err == cuda.CUresult.CUDA_SUCCESS + + yield + + cuda.cuDevicePrimaryCtxRelease(device) + + +@pytest.fixture(scope="module", autouse=True) +def _cufile_driver_prewarm(): + """Prime libcufile with one driver_open/close cycle before any test runs. + + The cuFile test module mixes two incompatible regimes: + + - Driver-open tests (buf_register_*, cufile_read_write, batch_io, stats, + etc.) need cuFileDriverOpen; they use the function-scope `driver` + fixture to open/close per test. + - Driver-closed tests (test_set_get_parameter_*, test_set_parameter_posix_*) + must run with the driver CLOSED — libcufile rejects parameter-set calls + when the driver is open (DRIVER_ALREADY_OPEN, 5026). + + Workaround for NVIDIA libcufile 1.17.1 bug: calling cuFileSetParameterSizeT + (or similar pre-open configuration APIs) BEFORE the first cuFileDriverOpen + leaves an internal version list uninitialized such that a later + cuFileDriverOpen SIGFPEs in CUFileDrv::ReadVersionInfo (div-by-zero). + Under random ordering, a driver-closed test can run before any + driver-open test, poisoning libcufile and tearing down pytest with a fatal + signal on the next driver_open. + + One open/close cycle up front primes libcufile's version list. After that, + both regimes work: the per-test `driver` fixture can open/close freely, + and parameter-set tests run against the (now properly initialized) closed + driver. + + Note: per-test driver_open/close is not ideal on throughput grounds, but + it is forced by the libcufile API — parameter-set tests cannot coexist + with a session-wide open driver. + """ + (err,) = cuda.cuInit(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, device = cuda.cuDeviceGet(0) + assert err == cuda.CUresult.CUDA_SUCCESS + err, dctx = cuda.cuDevicePrimaryCtxRetain(device) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuCtxSetCurrent(dctx) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + cufile.driver_open() + cufile.driver_close() + finally: + cuda.cuDevicePrimaryCtxRelease(device) + + +@pytest.fixture +def driver(ctx): + cufile.driver_open() + yield + cufile.driver_close() + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_handle_register(tmpdir): + """Test file handle registration with cuFile.""" + # Create test file + file_path = tmpdir / "test_handle_register.bin" + + # Create file with POSIX operations + fd = os.open(file_path, os.O_CREAT | os.O_RDWR, 0o600) + + # Write test data using POSIX write + test_data = b"Test data for cuFile - POSIX write" + bytes_written = os.write(fd, test_data) + + # Sync to ensure data is on disk + os.fsync(fd) + + # Close and reopen with O_DIRECT for cuFile operations + os.close(fd) + + # Reopen with O_DIRECT + flags = os.O_RDWR | os.O_DIRECT + fd = os.open(file_path, flags) + + try: + # Create and initialize the descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register the handle + handle = cufile.handle_register(descr.ptr) + + # Deregister the handle + cufile.handle_deregister(handle) + + finally: + os.close(fd) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_simple(): + """Simple test for buffer registration with cuFile.""" + # Allocate CUDA memory + buffer_size = 4096 # 4KB, aligned to 4096 bytes + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Register the buffer with cuFile + flags = 0 + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, flags) + + # Deregister the buffer + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free CUDA memory + cuda.cuMemFree(buf_ptr) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_host_memory(): + """Test buffer registration with host memory.""" + # Allocate host memory + buffer_size = 4096 # 4KB, aligned to 4096 bytes + err, buf_ptr = cuda.cuMemHostAlloc(buffer_size, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Register the host buffer with cuFile + flags = 0 + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, flags) + + # Deregister the buffer + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free host memory + cuda.cuMemFreeHost(buf_ptr) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_multiple_buffers(): + """Test registering multiple buffers.""" + # Allocate multiple CUDA buffers + buffer_sizes = [4096, 16384, 65536] # All aligned to 4096 bytes + buffers = [] + + for size in buffer_sizes: + err, buf_ptr = cuda.cuMemAlloc(size) + assert err == cuda.CUresult.CUDA_SUCCESS + buffers.append(buf_ptr) + + try: + # Register all buffers + flags = 0 + for buf_ptr, size in zip(buffers, buffer_sizes): + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, size, flags) + + # Deregister all buffers + for buf_ptr in buffers: + buf_ptr_int = int(buf_ptr) + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free all buffers + for buf_ptr in buffers: + cuda.cuMemFree(buf_ptr) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_invalid_flags(): + """Test buffer registration with invalid flags.""" + # Allocate CUDA memory + buffer_size = 65536 + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Try to register with invalid flags + invalid_flags = 999 + buf_ptr_int = int(buf_ptr) + + with suppress(Exception): + cufile.buf_register(buf_ptr_int, buffer_size, invalid_flags) + # If we get here, deregister to clean up + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free CUDA memory + cuda.cuMemFree(buf_ptr) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_large_buffer(): + """Test buffer registration with a large buffer.""" + # Allocate large CUDA memory (1MB, aligned to 4096 bytes) + buffer_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0) + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Register the large buffer with cuFile + flags = 0 + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, flags) + + # Deregister the buffer + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free CUDA memory + cuda.cuMemFree(buf_ptr) + + +@pytest.mark.usefixtures("driver") +def test_buf_register_already_registered(): + """Test that registering an already registered buffer fails.""" + # Allocate CUDA memory + buffer_size = 4096 # 4KB, aligned to 4096 bytes + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Register the buffer first time + flags = 0 + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, flags) + + # Try to register the same buffer again + try: + cufile.buf_register(buf_ptr_int, buffer_size, flags) + # If we get here, deregister both times + cufile.buf_deregister(buf_ptr_int) + cufile.buf_deregister(buf_ptr_int) + except Exception: + # Expected error when registering buffer twice + # Deregister the first registration + cufile.buf_deregister(buf_ptr_int) + + finally: + # Free CUDA memory + cuda.cuMemFree(buf_ptr) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_cufile_read_write(tmpdir): + """Test cuFile read and write operations.""" + # Create test file + file_path = tmpdir / "test_cufile_rw.bin" + + # Allocate CUDA memory for write and read + write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) + err, write_buf = cuda.cuMemAlloc(write_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, read_buf = cuda.cuMemAlloc(write_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Allocate host memory for data verification + host_buf = ctypes.create_string_buffer(write_size) + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register buffers with cuFile + write_buf_int = int(write_buf) + read_buf_int = int(read_buf) + + cufile.buf_register(write_buf_int, write_size, 0) + cufile.buf_register(read_buf_int, write_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Prepare test data + test_string = b"Hello cuFile! This is test data for read/write operations. " + test_string_len = len(test_string) + repetitions = write_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:write_size] # Ensure it fits exactly in buffer + host_buf = ctypes.create_string_buffer(test_data, write_size) + + # Copy test data to CUDA write buffer + cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0) + cuda.cuStreamSynchronize(0) + + # Write data using cuFile + bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0) + + # Read data back using cuFile + bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0) + + # Verify bytes written equals bytes read + assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}" + assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}" + assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})" + + # Copy read data back to host + cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0) + cuda.cuStreamSynchronize(0) + + # Verify the data + read_data = host_buf.value + assert read_data == test_data, "Read data doesn't match written data" + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + cufile.buf_deregister(write_buf_int) + cufile.buf_deregister(read_buf_int) + + finally: + # Close file + os.close(fd) + # Free CUDA memory + cuda.cuMemFree(write_buf) + cuda.cuMemFree(read_buf) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_cufile_read_write_host_memory(tmpdir): + """Test cuFile read and write operations using host memory.""" + # Create test file + file_path = tmpdir / "test_cufile_rw_host.bin" + + # Allocate host memory for write and read + write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) + err, write_buf = cuda.cuMemHostAlloc(write_size, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, read_buf = cuda.cuMemHostAlloc(write_size, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register host buffers with cuFile + write_buf_int = int(write_buf) + read_buf_int = int(read_buf) + + cufile.buf_register(write_buf_int, write_size, 0) + cufile.buf_register(read_buf_int, write_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Prepare test data + test_string = b"Host memory test data for cuFile operations! " + test_string_len = len(test_string) + repetitions = write_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:write_size] # Ensure it fits exactly in buffer + + # Copy test data to host write buffer + host_buf = ctypes.create_string_buffer(test_data, write_size) + write_buf_content = ctypes.string_at(write_buf, write_size) + + # Write data using cuFile + bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0) + + # Sync to ensure data is on disk + os.fsync(fd) + + # Read data back using cuFile + bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0) + + # Verify bytes written equals bytes read + assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}" + assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}" + assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})" + + # Verify the data + read_data = ctypes.string_at(read_buf, write_size) + expected_data = write_buf_content + assert read_data == expected_data, "Read data doesn't match written data" + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + cufile.buf_deregister(write_buf_int) + cufile.buf_deregister(read_buf_int) + + finally: + # Close file + os.close(fd) + # Free host memory + cuda.cuMemFreeHost(write_buf) + cuda.cuMemFreeHost(read_buf) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_cufile_read_write_large(tmpdir): + """Test cuFile read and write operations with large data.""" + # Create test file + file_path = tmpdir / "test_cufile_rw_large.bin" + + # Allocate large CUDA memory (1MB, aligned to 4096 bytes) + write_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0) + err, write_buf = cuda.cuMemAlloc(write_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, read_buf = cuda.cuMemAlloc(write_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Allocate host memory for data verification + host_buf = ctypes.create_string_buffer(write_size) + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register buffers with cuFile + write_buf_int = int(write_buf) + read_buf_int = int(read_buf) + + cufile.buf_register(write_buf_int, write_size, 0) + cufile.buf_register(read_buf_int, write_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Generate large test data + import random + + test_data = bytes(random.getrandbits(8) for _ in range(write_size)) + host_buf = ctypes.create_string_buffer(test_data, write_size) + + # Copy test data to CUDA write buffer + cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0) + cuda.cuStreamSynchronize(0) + + # Get the actual data that was written to CUDA buffer + cuda.cuMemcpyDtoHAsync(host_buf, write_buf, write_size, 0) + cuda.cuStreamSynchronize(0) + expected_data = host_buf.value + + # Write data using cuFile + bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0) + + # Read data back using cuFile + bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0) + + # Verify bytes written equals bytes read + assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}" + assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}" + assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})" + + # Copy read data back to host + cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0) + cuda.cuStreamSynchronize(0) + + # Verify the data + read_data = host_buf.value + assert read_data == expected_data, "Large read data doesn't match written data" + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + cufile.buf_deregister(write_buf_int) + cufile.buf_deregister(read_buf_int) + + finally: + # Close file + os.close(fd) + # Free CUDA memory + cuda.cuMemFree(write_buf) + cuda.cuMemFree(read_buf) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver") +def test_cufile_write_async(tmpdir): + """Test cuFile asynchronous write operations.""" + # Create test file + file_path = tmpdir / "test_cufile_write_async.bin" + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + try: + # Register file handle + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + handle = cufile.handle_register(descr.ptr) + + # Allocate and register device buffer + buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) + err, buf_ptr = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + cufile.buf_register(int(buf_ptr), buf_size, 0) + + # Create CUDA stream + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register stream with cuFile + cufile.stream_register(int(stream), 0) + + # Prepare test data in device buffer + test_string = b"Async write test data for cuFile!" + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:buf_size] # Ensure it fits exactly in buffer + host_buf = ctypes.create_string_buffer(test_data, buf_size) + cuda.cuMemcpyHtoDAsync(buf_ptr, host_buf, buf_size, 0) + cuda.cuStreamSynchronize(0) + + # Create parameter arrays for async write + size_p = ctypes.c_size_t(buf_size) + file_offset_p = ctypes.c_int64(0) + buf_ptr_offset_p = ctypes.c_int64(0) + bytes_written_p = ctypes.c_ssize_t(0) + + # Perform async write + cufile.write_async( + int(handle), + int(buf_ptr), + ctypes.addressof(size_p), + ctypes.addressof(file_offset_p), + ctypes.addressof(buf_ptr_offset_p), + ctypes.addressof(bytes_written_p), + int(stream), + ) + + # Synchronize stream to wait for completion + cuda.cuStreamSynchronize(stream) + + # Verify bytes written + assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}" + + # Deregister stream + cufile.stream_deregister(int(stream)) + + # Deregister and cleanup + cufile.buf_deregister(int(buf_ptr)) + cufile.handle_deregister(handle) + cuda.cuStreamDestroy(stream) + cuda.cuMemFree(buf_ptr) + + finally: + os.close(fd) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver") +def test_cufile_read_async(tmpdir): + """Test cuFile asynchronous read operations.""" + # Create test file + file_path = tmpdir / "test_cufile_read_async.bin" + + # First create and write test data without O_DIRECT + fd_temp = os.open(file_path, os.O_CREAT | os.O_RDWR, 0o600) + # Create test data that's aligned to 4096 bytes + test_string = b"Async read test data for cuFile!" + test_string_len = len(test_string) + buf_size = 65536 # 64KB, aligned to 4096 bytes + repetitions = buf_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:buf_size] # Ensure exact 64KB + os.write(fd_temp, test_data) + os.fsync(fd_temp) + os.close(fd_temp) + + # Now open with O_DIRECT for cuFile operations + fd = os.open(file_path, os.O_RDWR | os.O_DIRECT) + + try: + # Register file handle + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + handle = cufile.handle_register(descr.ptr) + + # Allocate and register device buffer + buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) + err, buf_ptr = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + cufile.buf_register(int(buf_ptr), buf_size, 0) + + # Create CUDA stream + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register stream with cuFile + cufile.stream_register(int(stream), 0) + + # Create parameter arrays for async read + size_p = ctypes.c_size_t(buf_size) + file_offset_p = ctypes.c_int64(0) + buf_ptr_offset_p = ctypes.c_int64(0) + bytes_read_p = ctypes.c_ssize_t(0) + + # Perform async read + cufile.read_async( + int(handle), + int(buf_ptr), + ctypes.addressof(size_p), + ctypes.addressof(file_offset_p), + ctypes.addressof(buf_ptr_offset_p), + ctypes.addressof(bytes_read_p), + int(stream), + ) + + # Synchronize stream to wait for completion + cuda.cuStreamSynchronize(stream) + + # Verify bytes read + assert bytes_read_p.value > 0, f"Expected bytes read, got {bytes_read_p.value}" + + # Copy read data back to host and verify + host_buf = ctypes.create_string_buffer(buf_size) + cuda.cuMemcpyDtoHAsync(host_buf, buf_ptr, buf_size, 0) + cuda.cuStreamSynchronize(0) + read_data = host_buf.value[: bytes_read_p.value] + expected_data = test_data[: bytes_read_p.value] + assert read_data == expected_data, "Read data doesn't match written data" + + # Deregister stream + cufile.stream_deregister(int(stream)) + + # Deregister and cleanup + cufile.buf_deregister(int(buf_ptr)) + cufile.handle_deregister(handle) + cuda.cuStreamDestroy(stream) + cuda.cuMemFree(buf_ptr) + + finally: + os.close(fd) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver") +def test_cufile_async_read_write(tmpdir): + """Test cuFile asynchronous read and write operations in sequence.""" + # Create test file + file_path = tmpdir / "test_cufile_async_rw.bin" + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + try: + # Register file handle + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + handle = cufile.handle_register(descr.ptr) + + # Allocate and register device buffers + buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) + err, write_buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + cufile.buf_register(int(write_buf), buf_size, 0) + + err, read_buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + cufile.buf_register(int(read_buf), buf_size, 0) + + # Create CUDA stream + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register stream with cuFile + cufile.stream_register(int(stream), 0) + + # Prepare test data in write buffer + test_string = b"Async RW test data for cuFile!" + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:buf_size] # Ensure it fits exactly in buffer + host_buf = ctypes.create_string_buffer(test_data, buf_size) + cuda.cuMemcpyHtoDAsync(write_buf, host_buf, buf_size, 0) + cuda.cuStreamSynchronize(0) + + # Create parameter arrays for async write + write_size_p = ctypes.c_size_t(buf_size) + write_file_offset_p = ctypes.c_int64(0) + write_buf_ptr_offset_p = ctypes.c_int64(0) + bytes_written_p = ctypes.c_ssize_t(0) + + # Perform async write + cufile.write_async( + int(handle), + int(write_buf), + ctypes.addressof(write_size_p), + ctypes.addressof(write_file_offset_p), + ctypes.addressof(write_buf_ptr_offset_p), + ctypes.addressof(bytes_written_p), + int(stream), + ) + + # Synchronize stream to wait for write completion + cuda.cuStreamSynchronize(stream) + + # Verify bytes written + assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}" + + # Create parameter arrays for async read + read_size_p = ctypes.c_size_t(buf_size) + read_file_offset_p = ctypes.c_int64(0) + read_buf_ptr_offset_p = ctypes.c_int64(0) + bytes_read_p = ctypes.c_ssize_t(0) + + # Perform async read + cufile.read_async( + int(handle), + int(read_buf), + ctypes.addressof(read_size_p), + ctypes.addressof(read_file_offset_p), + ctypes.addressof(read_buf_ptr_offset_p), + ctypes.addressof(bytes_read_p), + int(stream), + ) + + # Synchronize stream to wait for read completion + cuda.cuStreamSynchronize(stream) + + # Verify bytes read + assert bytes_read_p.value == buf_size, f"Expected {buf_size} bytes read, got {bytes_read_p.value}" + + # Copy read data back to host and verify + host_buf = ctypes.create_string_buffer(buf_size) + cuda.cuMemcpyDtoHAsync(host_buf, read_buf, buf_size, 0) + cuda.cuStreamSynchronize(0) + read_data = host_buf.value + assert read_data == test_data, "Read data doesn't match written data" + + # Deregister stream + cufile.stream_deregister(int(stream)) + + # Deregister and cleanup + cufile.buf_deregister(int(write_buf)) + cufile.buf_deregister(int(read_buf)) + cufile.handle_deregister(handle) + cuda.cuStreamDestroy(stream) + cuda.cuMemFree(write_buf) + cuda.cuMemFree(read_buf) + + finally: + os.close(fd) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_batch_io_basic(tmpdir): + """Test basic batch IO operations with multiple read/write operations.""" + # Create test file + file_path = tmpdir / "test_batch_io.bin" + + # Allocate CUDA memory for multiple operations + buf_size = 65536 # 64KB + num_operations = 4 + + buffers = [] + read_buffers = [] # Initialize read_buffers to avoid UnboundLocalError + + for i in range(num_operations): + err, buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + buffers.append(buf) + + # Allocate host memory for data verification + host_buf = ctypes.create_string_buffer(buf_size) + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register buffers with cuFile + for buf in buffers: + buf_int = int(buf) + cufile.buf_register(buf_int, buf_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Set up batch IO + batch_handle = cufile.batch_io_set_up(num_operations) + + # Create IOParams array for batch operations + io_params = cufile.IOParams(num_operations) + io_events = cufile.IOEvents(num_operations) + + # Prepare test data for each operation + test_strings = [ + b"Batch operation 1 data for testing cuFile! ", + b"Batch operation 2 data for testing cuFile! ", + b"Batch operation 3 data for testing cuFile! ", + b"Batch operation 4 data for testing cuFile! ", + ] + + # Set up write operations + for i in range(num_operations): + # Prepare test data + test_string = test_strings[i] + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:buf_size] # Ensure it fits exactly in buffer + host_buf = ctypes.create_string_buffer(test_data, buf_size) + + # Copy test data to CUDA buffer + cuda.cuMemcpyHtoDAsync(buffers[i], host_buf, buf_size, 0) + cuda.cuStreamSynchronize(0) + + # Set up IOParams for this operation + io_params[i].mode = cufile.BatchMode.BATCH # Batch mode + io_params[i].fh = handle + io_params[i].opcode = cufile.Opcode.WRITE # Write opcode + io_params[i].cookie = i # Use index as cookie for identification + io_params[i].u.batch.dev_ptr_base = int(buffers[i]) + io_params[i].u.batch.file_offset = i * buf_size # Sequential file offsets + io_params[i].u.batch.dev_ptr_offset = 0 + io_params[i].u.batch.size_ = buf_size + + # Submit batch write operations + cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + + # Get batch status + min_nr = num_operations # Wait for all operations to complete + nr_completed = ctypes.c_uint(num_operations) # Initialize to max operations posted + timeout = ctypes.c_int(5000) # 5 second timeout + + cufile.batch_io_get_status( + batch_handle, min_nr, ctypes.addressof(nr_completed), io_events.ptr, ctypes.addressof(timeout) + ) + + # Verify all operations completed successfully + assert nr_completed.value == num_operations, f"Expected {num_operations} operations, got {nr_completed.value}" + + # Collect all returned cookies + returned_cookies = set() + for i in range(num_operations): + assert io_events[i].status == cufile.Status.COMPLETE, ( + f"Operation {i} failed with status {io_events[i].status}" + ) + assert io_events[i].ret == buf_size, f"Expected {buf_size} bytes, got {io_events[i].ret} for operation {i}" + returned_cookies.add(io_events[i].cookie) + + # Verify all expected cookies are present + expected_cookies = set(range(num_operations)) # cookies 0, 1, 2, 3 + assert returned_cookies == expected_cookies, ( + f"Cookie mismatch. Expected {expected_cookies}, got {returned_cookies}" + ) + + # Now test batch read operations + read_buffers = [] + for i in range(num_operations): + err, buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + read_buffers.append(buf) + buf_int = int(buf) + cufile.buf_register(buf_int, buf_size, 0) + + # Create fresh io_events array for read operations + io_events_read = cufile.IOEvents(num_operations) + + # Set up read operations + for i in range(num_operations): + io_params[i].mode = cufile.BatchMode.BATCH # Batch mode + io_params[i].fh = handle + io_params[i].opcode = cufile.Opcode.READ # Read opcode + io_params[i].cookie = i + 100 # Different cookie for reads + io_params[i].u.batch.dev_ptr_base = int(read_buffers[i]) + io_params[i].u.batch.file_offset = i * buf_size + io_params[i].u.batch.dev_ptr_offset = 0 + io_params[i].u.batch.size_ = buf_size + + # Submit batch read operations + cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + + # Get batch status for reads + cufile.batch_io_get_status( + batch_handle, min_nr, ctypes.addressof(nr_completed), io_events_read.ptr, ctypes.addressof(timeout) + ) + + # Verify read operations completed successfully + assert nr_completed.value == num_operations, ( + f"Expected {num_operations} read operations, got {nr_completed.value}" + ) + + # Collect all returned cookies for read operations + returned_cookies_read = set() + for i in range(num_operations): + assert io_events_read[i].status == cufile.Status.COMPLETE, ( + f"Operation {i} failed with status {io_events_read[i].status}" + ) + assert io_events_read[i].ret == buf_size, ( + f"Expected {buf_size} bytes read, got {io_events_read[i].ret} for operation {i}" + ) + returned_cookies_read.add(io_events_read[i].cookie) + + # Verify all expected cookies are present + expected_cookies_read = set(range(100, 100 + num_operations)) # cookies 100, 101, 102, 103 + assert returned_cookies_read == expected_cookies_read, ( + f"Cookie mismatch. Expected {expected_cookies_read}, got {returned_cookies_read}" + ) + + # Verify the read data matches the written data + for i in range(num_operations): + # Copy read data back to host + cuda.cuMemcpyDtoHAsync(host_buf, read_buffers[i], buf_size, 0) + cuda.cuStreamSynchronize(0) + read_data = host_buf.value + + # Prepare expected data + test_string = test_strings[i] + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + expected_data = (test_string * repetitions)[:buf_size] + + assert read_data == expected_data, f"Read data doesn't match written data for operation {i}" + + # Clean up batch IO + cufile.batch_io_destroy(batch_handle) + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + for buf in buffers + read_buffers: + buf_int = int(buf) + cufile.buf_deregister(buf_int) + + finally: + # Close file + os.close(fd) + # Free CUDA memory + for buf in buffers + read_buffers: + cuda.cuMemFree(buf) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_batch_io_cancel(tmpdir): + """Test batch IO cancellation.""" + # Create test file + file_path = tmpdir / "test_batch_cancel.bin" + + # Allocate CUDA memory + buf_size = 4096 # 4KB, aligned to 4096 bytes + num_operations = 2 + + buffers = [] + for i in range(num_operations): + err, buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + buffers.append(buf) + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register buffers with cuFile + for buf in buffers: + buf_int = int(buf) + cufile.buf_register(buf_int, buf_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Set up batch IO + batch_handle = cufile.batch_io_set_up(num_operations) + + # Create IOParams array for batch operations + io_params = cufile.IOParams(num_operations) + + # Set up write operations + for i in range(num_operations): + io_params[i].mode = cufile.BatchMode.BATCH # Batch mode + io_params[i].fh = handle + io_params[i].opcode = cufile.Opcode.WRITE # Write opcode + io_params[i].cookie = i + io_params[i].u.batch.dev_ptr_base = int(buffers[i]) + io_params[i].u.batch.file_offset = i * buf_size + io_params[i].u.batch.dev_ptr_offset = 0 + io_params[i].u.batch.size_ = buf_size + + # Submit batch operations + cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + + # Cancel the batch operations + cufile.batch_io_cancel(batch_handle) + + # Clean up batch IO + cufile.batch_io_destroy(batch_handle) + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + for buf in buffers: + buf_int = int(buf) + cufile.buf_deregister(buf_int) + + finally: + # Close file + os.close(fd) + # Free CUDA memory + for buf in buffers: + cuda.cuMemFree(buf) + + +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("driver") +def test_batch_io_large_operations(tmpdir): + """Test batch IO with large buffer operations.""" + # Create test file + file_path = tmpdir / "test_batch_large.bin" + + # Allocate large CUDA memory (1MB, aligned to 4096 bytes) + buf_size = 1024 * 1024 # 1MB, aligned to 4096 bytes + num_operations = 2 + + write_buffers = [] + read_buffers = [] + all_buffers = [] # Initialize all_buffers to avoid UnboundLocalError + + for i in range(num_operations): + err, buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + write_buffers.append(buf) + + err, buf = cuda.cuMemAlloc(buf_size) + assert err == cuda.CUresult.CUDA_SUCCESS + read_buffers.append(buf) + + # Allocate host memory for data verification + host_buf = ctypes.create_string_buffer(buf_size) + + try: + # Create file with O_DIRECT + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + # Register all buffers with cuFile + all_buffers = write_buffers + read_buffers + for buf in all_buffers: + buf_int = int(buf) + cufile.buf_register(buf_int, buf_size, 0) + + # Create file descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register file handle + handle = cufile.handle_register(descr.ptr) + + # Set up batch IO + batch_handle = cufile.batch_io_set_up(num_operations) # Only for writes + + # Create IOParams array for batch operations + io_params = cufile.IOParams(num_operations) + io_events = cufile.IOEvents(num_operations) + + # Prepare test data + test_strings = [ + b"Large batch operation 1 data for testing cuFile with 1MB buffers! ", + b"Large batch operation 2 data for testing cuFile with 1MB buffers! ", + ] + + # Prepare write data + for i in range(num_operations): + test_string = test_strings[i] + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + test_data = test_string * repetitions + test_data = test_data[:buf_size] + host_buf = ctypes.create_string_buffer(test_data, buf_size) + cuda.cuMemcpyHtoDAsync(write_buffers[i], host_buf, buf_size, 0) + cuda.cuStreamSynchronize(0) + + # Set up write operations + for i in range(num_operations): + io_params[i].mode = cufile.BatchMode.BATCH # Batch mode + io_params[i].fh = handle + io_params[i].opcode = cufile.Opcode.WRITE # Write opcode + io_params[i].cookie = i + io_params[i].u.batch.dev_ptr_base = int(write_buffers[i]) + io_params[i].u.batch.file_offset = i * buf_size + io_params[i].u.batch.dev_ptr_offset = 0 + io_params[i].u.batch.size_ = buf_size + + # Submit writes + cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + + # Wait for writes to complete + nr_completed_writes = ctypes.c_uint(num_operations) + timeout = ctypes.c_int(10000) + cufile.batch_io_get_status( + batch_handle, + num_operations, + ctypes.addressof(nr_completed_writes), + io_events.ptr, + ctypes.addressof(timeout), + ) + + # Clean up write batch + cufile.batch_io_destroy(batch_handle) + + # Now submit reads separately + read_batch_handle = cufile.batch_io_set_up(num_operations) + read_io_params = cufile.IOParams(num_operations) + read_io_events = cufile.IOEvents(num_operations) + + # Set up read operations + for i in range(num_operations): + read_io_params[i].mode = cufile.BatchMode.BATCH + read_io_params[i].fh = handle + read_io_params[i].opcode = cufile.Opcode.READ + read_io_params[i].cookie = i + 100 + read_io_params[i].u.batch.dev_ptr_base = int(read_buffers[i]) + read_io_params[i].u.batch.file_offset = i * buf_size + read_io_params[i].u.batch.dev_ptr_offset = 0 + read_io_params[i].u.batch.size_ = buf_size + + # Submit reads + cufile.batch_io_submit(read_batch_handle, num_operations, read_io_params.ptr, 0) + + # Wait for reads + nr_completed = ctypes.c_uint(num_operations) + cufile.batch_io_get_status( + read_batch_handle, + num_operations, + ctypes.addressof(nr_completed), + read_io_events.ptr, + ctypes.addressof(timeout), + ) + + # Verify all operations completed successfully + assert nr_completed.value == num_operations, f"Expected {num_operations} operations, got {nr_completed.value}" + + # Collect all returned cookies + returned_cookies = set() + for i in range(num_operations): + assert read_io_events[i].status == cufile.Status.COMPLETE, ( + f"Operation {i} failed with status {read_io_events[i].status}" + ) + returned_cookies.add(read_io_events[i].cookie) + + # Verify all expected cookies are present + expected_cookies = set(range(100, 100 + num_operations)) + assert returned_cookies == expected_cookies, ( + f"Cookie mismatch. Expected {expected_cookies}, got {returned_cookies}" + ) + + # Verify the read data matches the written data + for i in range(num_operations): + # Copy read data back to host + cuda.cuMemcpyDtoHAsync(host_buf, read_buffers[i], buf_size, 0) + cuda.cuStreamSynchronize(0) + read_data = host_buf.value + + # Prepare expected data + test_string = test_strings[i] + test_string_len = len(test_string) + repetitions = buf_size // test_string_len + expected_data = (test_string * repetitions)[:buf_size] + + if read_data != expected_data: + n = 100 # Show first n bytes + raise RuntimeError( + f"Read data doesn't match written data for operation {i}: " + f"{len(read_data)=}, {len(expected_data)=}, " + f"first {n} bytes: read {read_data[:n]!r}, " + f"expected {expected_data[:n]!r}" + ) + + # Clean up batch IO + cufile.batch_io_destroy(read_batch_handle) + + # Deregister file handle + cufile.handle_deregister(handle) + + # Deregister buffers + for buf in all_buffers: + buf_int = int(buf) + cufile.buf_deregister(buf_int) + + finally: + # Close file + os.close(fd) + # Free CUDA memory + for buf in all_buffers: + cuda.cuMemFree(buf) + + +@pytest.mark.skipif( + cufileVersionLessThan(1140), reason="cuFile parameter APIs require cuFile library version 1.14.0 or later" +) +@pytest.mark.usefixtures("ctx", "cufile_env_json") +def test_set_get_parameter_size_t(): + """Test setting and getting size_t parameters with cuFile validation.""" + param_val_pairs = ( + (cufile.SizeTConfigParameter.POLLTHRESHOLD_SIZE_KB, 64), # 64KB threshold + (cufile.SizeTConfigParameter.PROPERTIES_MAX_DIRECT_IO_SIZE_KB, 1024), # 1MB max direct IO size + (cufile.SizeTConfigParameter.PROPERTIES_MAX_DEVICE_CACHE_SIZE_KB, 512), # 512KB max cache size + (cufile.SizeTConfigParameter.PROPERTIES_PER_BUFFER_CACHE_SIZE_KB, 128), # 128KB per buffer cache + (cufile.SizeTConfigParameter.PROPERTIES_MAX_DEVICE_PINNED_MEM_SIZE_KB, 2048), # 2MB max pinned memory + (cufile.SizeTConfigParameter.PROPERTIES_IO_BATCHSIZE, 16), # 16 operations per batch + (cufile.SizeTConfigParameter.PROPERTIES_BATCH_IO_TIMEOUT_MS, 5000), # 5 second timeout + (cufile.SizeTConfigParameter.EXECUTION_MAX_IO_QUEUE_DEPTH, 32), # Max 32 operations in queue + (cufile.SizeTConfigParameter.EXECUTION_MAX_IO_THREADS, 8), # Max 8 IO threads + (cufile.SizeTConfigParameter.EXECUTION_MIN_IO_THRESHOLD_SIZE_KB, 4), # 4KB minimum IO threshold + (cufile.SizeTConfigParameter.EXECUTION_MAX_REQUEST_PARALLELISM, 4), # Max 4 parallel requests + ) + + # Snapshot baselines after driver_open so getters reflect merged config (defaults + JSON), + # not pre-open pending state that could restore invalid values (e.g. 0 for per-buffer cache). + with _cufile_driver_session(): + originals = {param: cufile.get_parameter_size_t(param) for param, _ in param_val_pairs} + + def test_param(param, val): + orig_val = originals[param] + cufile.set_parameter_size_t(param, val) + retrieved_val = cufile.get_parameter_size_t(param) + assert retrieved_val == val + cufile.set_parameter_size_t(param, orig_val) + + # Test setting and getting various size_t parameters + for param, val in param_val_pairs: + test_param(param, val) + + +@pytest.mark.skipif( + cufileVersionLessThan(1140), reason="cuFile parameter APIs require cuFile library version 1.14.0 or later" +) +@pytest.mark.usefixtures("ctx", "cufile_env_json") +def test_set_get_parameter_bool(): + """Test setting and getting boolean parameters with cuFile validation.""" + # Load the compat-enabled test config before the first driver_open so the compat + # bool params can still be round-tripped on systems without nvidia-fs. + param_val_pairs = ( + (cufile.BoolConfigParameter.PROPERTIES_USE_POLL_MODE, True), + (cufile.BoolConfigParameter.PROPERTIES_ALLOW_COMPAT_MODE, False), + (cufile.BoolConfigParameter.FORCE_COMPAT_MODE, False), + (cufile.BoolConfigParameter.FS_MISC_API_CHECK_AGGRESSIVE, True), + (cufile.BoolConfigParameter.EXECUTION_PARALLEL_IO, True), + (cufile.BoolConfigParameter.PROFILE_NVTX, False), + (cufile.BoolConfigParameter.PROPERTIES_ALLOW_SYSTEM_MEMORY, True), + (cufile.BoolConfigParameter.USE_PCIP2PDMA, True), + (cufile.BoolConfigParameter.PREFER_IO_URING, False), + (cufile.BoolConfigParameter.FORCE_ODIRECT_MODE, True), + (cufile.BoolConfigParameter.SKIP_TOPOLOGY_DETECTION, False), + (cufile.BoolConfigParameter.STREAM_MEMOPS_BYPASS, True), + ) + # PROFILE_NVTX is deprecated (CTK 13.1.0+); cuFile >= 1.16 rejects bool getters for it. + if cufile.get_version() >= 1160: + param_val_pairs = tuple((p, v) for p, v in param_val_pairs if p is not cufile.BoolConfigParameter.PROFILE_NVTX) + + with _cufile_driver_session(): + originals = {param: cufile.get_parameter_bool(param) for param, _ in param_val_pairs} + + def test_param(param, val): + orig_val = originals[param] + cufile.set_parameter_bool(param, val) + retrieved_val = cufile.get_parameter_bool(param) + assert retrieved_val is val + cufile.set_parameter_bool(param, orig_val) + + # Test setting and getting various boolean parameters + for param, val in param_val_pairs: + test_param(param, val) + + +@pytest.mark.skipif( + cufileVersionLessThan(1140), reason="cuFile parameter APIs require cuFile library version 1.14.0 or later" +) +@pytest.mark.usefixtures("ctx", "cufile_env_json") +def test_set_get_parameter_string(tmp_path): + """Test setting and getting string parameters with cuFile validation.""" + temp_dir = tempfile.gettempdir() + # must be set to avoid getter error when testing ENV_LOGFILE_PATH... + os.environ["CUFILE_LOGFILE_PATH"] = "" + + param_val_pairs = ( + (cufile.StringConfigParameter.LOGGING_LEVEL, "INFO", "DEBUG"), # Test logging level + ( + cufile.StringConfigParameter.ENV_LOGFILE_PATH, + os.path.join(temp_dir, "cufile.log"), + str(tmp_path / "cufile.log"), + ), # Test environment log file path + ( + cufile.StringConfigParameter.LOG_DIR, + os.path.join(temp_dir, "cufile_logs"), + str(tmp_path), + ), # Test log directory + ) + + with _cufile_driver_session(): + originals = {param: cufile.get_parameter_string(param, 256) for param, _, _ in param_val_pairs} + + def test_param(param, val, default_val): + orig_val = originals[param] + + val_b = val.encode("utf-8") + val_buf = ctypes.create_string_buffer(val_b) + default_val_b = default_val.encode("utf-8") + defualt_val_buf = ctypes.create_string_buffer(default_val_b) + orig_val_b = orig_val.encode("utf-8") + orig_val_buf = ctypes.create_string_buffer(orig_val_b) + + # Round-trip test + cufile.set_parameter_string(param, int(ctypes.addressof(val_buf))) + retrieved_val = cufile.get_parameter_string(param, 256) + assert retrieved_val == val + + # Restore + try: + # Currently this line will raise, see below. + cufile.set_parameter_string(param, int(ctypes.addressof(orig_val_buf))) + except cufile.cuFileError: + # This block will always be reached because cuFILE could start with garbage default (empty string) + # that cannot be restored. In other words, cuFILE does honor the common sense that getter/setter + # should be round-tripable. + cufile.set_parameter_string(param, int(ctypes.addressof(defualt_val_buf))) + + try: + # Test setting and getting various string parameters + # Note: String parameter tests may have issues with the current implementation + for param, val, default_val in param_val_pairs: + test_param(param, val, default_val) + finally: + del os.environ["CUFILE_LOGFILE_PATH"] + + +@pytest.fixture +def stats(driver): + old_level = cufile.get_stats_level() + yield + # Reset cuFile statistics to clear all counters + cufile.stats_reset() + cufile.set_stats_level(old_level) + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.usefixtures("stats") +def test_set_stats_level(): + """Test cuFile statistics level configuration.""" + # Test setting different statistics levels + valid_levels = [0, 1, 2, 3] # 0=disabled, 1=basic, 2=detailed, 3=verbose + + for level in valid_levels: + cufile.set_stats_level(level) + + # Verify the level was set correctly + current_level = cufile.get_stats_level() + assert current_level == level, f"Expected stats level {level}, but got {current_level}" + + logging.info(f"Successfully set and verified stats level {level}") + + # Test invalid level (should raise an error) + try: + assert cufile.set_stats_level(-1) # Invalid negative level + except Exception as e: + logging.info(f"Correctly caught error for invalid stats level: {e}") + + try: + assert cufile.set_stats_level(4) # Invalid level > 3 + except Exception as e: + logging.info(f"Correctly caught error for invalid stats level: {e}") + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.usefixtures("driver") +def test_get_parameter_min_max_value(): + """Test getting minimum and maximum values for size_t parameters.""" + # Test with poll threshold parameter + param = cufile.SizeTConfigParameter.POLLTHRESHOLD_SIZE_KB + + # Get min/max values + min_value, max_value = cufile.get_parameter_min_max_value(param) + + # Verify that min <= max and both are reasonable values + assert min_value >= 0, f"Invalid min value: {min_value}" + assert max_value >= min_value, f"Max value {max_value} < min value {min_value}" + assert max_value > 0, f"Invalid max value: {max_value}" + + logging.info(f"POLLTHRESHOLD_SIZE_KB: min={min_value}, max={max_value}") + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.usefixtures("stats") +@pytest.mark.thread_unsafe(reason="not safe to stats_start() from multiple threads") +def test_stats_start_stop(): + """Test cuFile statistics collection stop.""" + # Set statistics level first (required before starting stats) + cufile.set_stats_level(1) # Level 1 = basic statistics + # Start collecting cuFile statistics first + cufile.stats_start() + + # Stop collecting cuFile statistics + cufile.stats_stop() + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("stats") +@pytest.mark.thread_unsafe(reason="cuFile stats counters and collection state are process-global") +def test_get_stats_l1(tmpdir): + """Test cuFile L1 statistics retrieval with file operations.""" + # Create test file directly with O_DIRECT + file_path = tmpdir / "test_stats_l1.bin" + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + try: + cufile.set_stats_level(1) # L1 = basic operation counts + # Start collecting cuFile statistics + cufile.stats_start() + + # Create and initialize the descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register the handle + handle = cufile.handle_register(descr.ptr) + + # Allocate CUDA memory + buffer_size = 4096 # 4KB, aligned to 4096 bytes + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register the buffer with cuFile + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, 0) + + # Prepare test data and copy to GPU buffer + test_data = b"cuFile L1 stats test data" * 100 # Fill buffer + test_data = test_data[:buffer_size] + host_buf = ctypes.create_string_buffer(test_data, buffer_size) + cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + + # Perform cuFile operations to generate L1 statistics + cufile.write(handle, buf_ptr_int, buffer_size, 0, 0) + cufile.read(handle, buf_ptr_int, buffer_size, 0, 0) + + # Use the exposed StatsLevel1 class from cufile module + stats = cufile.StatsLevel1() + + # Get L1 statistics (basic operation counts) + cufile.get_stats_l1(stats.ptr) + + # Verify actual field values using OpCounter class for cleaner access + read_ops = cufile.OpCounter.from_data(stats.read_ops) + write_ops = cufile.OpCounter.from_data(stats.write_ops) + read_bytes = int(stats.read_bytes) + write_bytes = int(stats.write_bytes) + + assert read_ops.ok > 0, f"Expected read operations, got {read_ops.ok}" + assert write_ops.ok > 0, f"Expected write operations, got {write_ops.ok}" + assert read_bytes > 0, f"Expected read bytes, got {read_bytes}" + assert write_bytes > 0, f"Expected write bytes, got {write_bytes}" + + logging.info( + f"Stats: reads={read_ops.ok}, writes={write_ops.ok}, read_bytes={read_bytes}, write_bytes={write_bytes}" + ) + + # Stop statistics collection + cufile.stats_stop() + + # Clean up cuFile resources + cufile.buf_deregister(buf_ptr_int) + cufile.handle_deregister(handle) + cuda.cuMemFree(buf_ptr) + + finally: + os.close(fd) + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("stats") +@pytest.mark.thread_unsafe(reason="cuFile stats counters and collection state are process-global") +def test_get_stats_l2(tmpdir): + """Test cuFile L2 statistics retrieval with file operations.""" + # Create test file directly with O_DIRECT + file_path = tmpdir / "test_stats_l2.bin" + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + try: + cufile.set_stats_level(2) # L2 = detailed performance metrics + + # Start collecting cuFile statistics + cufile.stats_start() + + # Create and initialize the descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register the handle + handle = cufile.handle_register(descr.ptr) + + # Allocate CUDA memory + buffer_size = 8192 # 8KB for more detailed stats + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register the buffer with cuFile + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, 0) + + # Prepare test data and copy to GPU buffer + test_data = b"cuFile L2 detailed stats test data" * 150 # Fill buffer + test_data = test_data[:buffer_size] + host_buf = ctypes.create_string_buffer(test_data, buffer_size) + cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + + # Perform multiple cuFile operations to generate detailed L2 statistics + cufile.write(handle, buf_ptr_int, buffer_size, 0, 0) + cufile.read(handle, buf_ptr_int, buffer_size, 0, 0) + cufile.write(handle, buf_ptr_int, buffer_size, buffer_size, 0) # Different offset + cufile.read(handle, buf_ptr_int, buffer_size, buffer_size, 0) + + # Use the exposed StatsLevel2 class from cufile module + stats = cufile.StatsLevel2() + + # Get L2 statistics (detailed performance metrics) + cufile.get_stats_l2(stats.ptr) + + # Verify L2 histogram fields contain data + # Access numpy array fields: histograms are numpy arrays + read_hist_total = int(stats.read_size_kb_hist.sum()) + write_hist_total = int(stats.write_size_kb_hist.sum()) + assert read_hist_total > 0 or write_hist_total > 0, "Expected L2 histogram data" + + # L2 also contains L1 basic stats - verify using OpCounter class + basic_stats = cufile.StatsLevel1.from_data(stats.basic) + read_ops = cufile.OpCounter.from_data(basic_stats.read_ops) + write_ops = cufile.OpCounter.from_data(basic_stats.write_ops) + + logging.info( + f"L2 Stats: read_hist_total={read_hist_total}, write_hist_total={write_hist_total}, " + f"basic_reads={read_ops.ok}, basic_writes={write_ops.ok}" + ) + + # Stop statistics collection + cufile.stats_stop() + + # Clean up cuFile resources + cufile.buf_deregister(buf_ptr_int) + cufile.handle_deregister(handle) + cuda.cuMemFree(buf_ptr) + + finally: + os.close(fd) + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") +@pytest.mark.usefixtures("stats") +@pytest.mark.thread_unsafe(reason="cuFile stats counters and collection state are process-global") +def test_get_stats_l3(tmpdir): + """Test cuFile L3 statistics retrieval with file operations.""" + # Create test file directly with O_DIRECT + file_path = tmpdir / "test_stats_l3.bin" + fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600) + + try: + cufile.set_stats_level(3) # L3 = comprehensive diagnostic data + + # Start collecting cuFile statistics + cufile.stats_start() + + # Create and initialize the descriptor + descr = cufile.Descr() + descr.type = cufile.FileHandleType.OPAQUE_FD + descr.handle.fd = fd + descr.fs_ops = 0 + + # Register the handle + handle = cufile.handle_register(descr.ptr) + + # Allocate CUDA memory + buffer_size = 16384 # 16KB for comprehensive stats testing + err, buf_ptr = cuda.cuMemAlloc(buffer_size) + assert err == cuda.CUresult.CUDA_SUCCESS + + # Register the buffer with cuFile + buf_ptr_int = int(buf_ptr) + cufile.buf_register(buf_ptr_int, buffer_size, 0) + + # Prepare test data and copy to GPU buffer + test_data = b"cuFile L3 comprehensive stats test data" * 200 # Fill buffer + test_data = test_data[:buffer_size] + host_buf = ctypes.create_string_buffer(test_data, buffer_size) + cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + + # Perform comprehensive cuFile operations to generate L3 statistics + # Multiple writes and reads at different offsets to generate rich stats + cufile.write(handle, buf_ptr_int, buffer_size, 0, 0) + cufile.read(handle, buf_ptr_int, buffer_size, 0, 0) + cufile.write(handle, buf_ptr_int, buffer_size, buffer_size, 0) # Different offset + cufile.read(handle, buf_ptr_int, buffer_size, buffer_size, 0) + cufile.write(handle, buf_ptr_int, buffer_size // 2, buffer_size * 2, 0) # Partial write + cufile.read(handle, buf_ptr_int, buffer_size // 2, buffer_size * 2, 0) # Partial read + + # Use the exposed StatsLevel3 class from cufile module + stats = cufile.StatsLevel3() + + # Get L3 statistics (comprehensive diagnostic data) + cufile.get_stats_l3(stats.ptr) + + # Verify L3-specific fields + num_gpus = int(stats.num_gpus) + assert num_gpus >= 0, f"Expected valid GPU count, got {num_gpus}" + + # Check if we have at least one GPU with stats using PerGpuStats class + gpu_with_data = False + for i in range(min(num_gpus, 16)): + # Access per-GPU stats using PerGpuStats class + # stats.per_gpu_stats has shape (1, 16), we need to get [0] first to get the (16,) array + # then slice [i:i+1] to get a 1-d array view (required by from_data) + gpu_stats = stats.per_gpu_stats[i] # Get the (16,) array + if gpu_stats.n_total_reads > 0 or gpu_stats.read_bytes > 0: + gpu_with_data = True + break + + # L3 also contains L2 detailed stats (which includes L1 basic stats) + detailed_stats = cufile.StatsLevel2.from_data(stats.detailed) + read_hist_total = int(detailed_stats.read_size_kb_hist.sum()) + + logging.info( + f"L3 Stats: num_gpus={num_gpus}, gpu_with_data={gpu_with_data}, detailed_read_hist={read_hist_total}" + ) + + # Stop statistics collection + cufile.stats_stop() + + # Clean up cuFile resources + cufile.buf_deregister(buf_ptr_int) + cufile.handle_deregister(handle) + cuda.cuMemFree(buf_ptr) + + finally: + os.close(fd) + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +@pytest.mark.usefixtures("driver") +def test_get_bar_size_in_kb(): + """Test cuFile BAR (Base Address Register) size retrieval.""" + # Get BAR size in kilobytes + try: + bar_size_kb = cufile.get_bar_size_in_kb(0) + except cufile.cuFileError as e: + if get_tegra_kind() != "Thor": + raise + pytest.xfail(f"TODO(#9999): Resolve Thor: cuFileError: {e!s}") + + # Verify BAR size is a reasonable value + assert isinstance(bar_size_kb, int), "BAR size should be an integer" + # Tegra devices may report 0 BAR size, which is acceptable + min_bar_size = 0 if get_tegra_kind() else 1 + assert bar_size_kb >= min_bar_size, f"BAR size should be >= {min_bar_size}" + + logging.info(f"GPU BAR size: {bar_size_kb} KB ({bar_size_kb / 1024 / 1024:.2f} GB)") + + +@pytest.fixture(scope="module") +def slab_sizes(): + """Define slab sizes for POSIX I/O pool (common I/O buffer sizes) - BEFORE driver open""" + return [ + 4096, # 4KB - small files + 65536, # 64KB - medium files + 1048576, # 1MB - large files + 16777216, # 16MB - very large files + ] + + +@pytest.fixture(scope="module") +def slab_counts(): + """Define counts for each slab size (number of buffers)""" + return [ + 10, # 10 buffers of 4KB + 5, # 5 buffers of 64KB + 3, # 3 buffers of 1MB + 2, # 2 buffers of 16MB + ] + + +@pytest.fixture +def driver_config(slab_sizes, slab_counts): + # Convert to ctypes arrays + size_array_type = ctypes.c_size_t * len(slab_sizes) + count_array_type = ctypes.c_size_t * len(slab_counts) + size_array = size_array_type(*slab_sizes) + count_array = count_array_type(*slab_counts) + + # Set POSIX pool slab array configuration BEFORE opening driver + cufile.set_parameter_posix_pool_slab_array( + ctypes.addressof(size_array), ctypes.addressof(count_array), len(slab_sizes) + ) + + +@pytest.mark.skipif( + cufileVersionLessThan(1150), reason="cuFile parameter APIs require cuFile library version 13.0 or later" +) +def test_set_parameter_posix_pool_slab_array(slab_sizes, slab_counts, driver_config, driver): + """Test cuFile POSIX pool slab array configuration.""" + # After setting parameters, retrieve them back to verify + n_slab_sizes = len(slab_sizes) + retrieved_sizes = (ctypes.c_size_t * n_slab_sizes)() + retrieved_counts = (ctypes.c_size_t * len(slab_counts))() + + retrieved_sizes_addr = ctypes.addressof(retrieved_sizes) + retrieved_counts_addr = ctypes.addressof(retrieved_counts) + + # Open cuFile driver AFTER setting parameters + with _cufile_driver_session(): + cufile.get_parameter_posix_pool_slab_array(retrieved_sizes_addr, retrieved_counts_addr, n_slab_sizes) + + # Verify they match what we set + assert list(retrieved_sizes) == slab_sizes + assert list(retrieved_counts) == slab_counts diff --git a/cuda_bindings/tests/legacy_api/test_legacy_interoperability.py b/cuda_bindings/tests/legacy_api/test_legacy_interoperability.py new file mode 100644 index 00000000000..08bac311a2d --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_interoperability.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import pytest +from cuda_python_test_helpers.mempool import xfail_if_mempool_oom + +import cuda.bindings.driver as cuda +import cuda.bindings.runtime as cudart + + +def supportsMemoryPool(): + err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrMemoryPoolsSupported, 0) + return err == cudart.cudaError_t.cudaSuccess and isSupported + + +def test_interop_stream(): + # DRV to RT + err_dr, stream = cuda.cuStreamCreate(0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaStreamDestroy(stream) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, stream = cudart.cudaStreamCreate() + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuStreamDestroy(stream) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + +def test_interop_event(): + # DRV to RT + err_dr, event = cuda.cuEventCreate(0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaEventDestroy(event) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, event = cudart.cudaEventCreate() + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuEventDestroy(event) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + +def test_interop_graph(): + # DRV to RT + err_dr, graph = cuda.cuGraphCreate(0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaGraphDestroy(graph) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, graph = cudart.cudaGraphCreate(0) + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuGraphDestroy(graph) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + +def test_interop_graphNode(): + err_dr, graph = cuda.cuGraphCreate(0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + # DRV to RT + err_dr, node = cuda.cuGraphAddEmptyNode(graph, [], 0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaGraphDestroyNode(node) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, node = cudart.cudaGraphAddEmptyNode(graph, [], 0) + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuGraphDestroyNode(node) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + (err_rt,) = cudart.cudaGraphDestroy(graph) + assert err_rt == cudart.cudaError_t.cudaSuccess + + +# cudaUserObject_t +# TODO + + +# cudaFunction_t +# TODO + + +@pytest.mark.skipif(not supportsMemoryPool(), reason="Requires mempool operations") +def test_interop_memPool(): + # DRV to RT + err_dr, pool = cuda.cuDeviceGetDefaultMemPool(0) + xfail_if_mempool_oom(err_dr, "cuDeviceGetDefaultMemPool", 0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaDeviceSetMemPool(0, pool) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, pool = cudart.cudaDeviceGetDefaultMemPool(0) + xfail_if_mempool_oom(err_rt, "cudaDeviceGetDefaultMemPool", 0) + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuDeviceSetMemPool(0, pool) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + +def test_interop_graphExec(): + err_dr, graph = cuda.cuGraphCreate(0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + err_dr, node = cuda.cuGraphAddEmptyNode(graph, [], 0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + # DRV to RT + err_dr, graphExec = cuda.cuGraphInstantiate(graph, 0) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + (err_rt,) = cudart.cudaGraphExecDestroy(graphExec) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, graphExec = cudart.cudaGraphInstantiate(graph, 0) + assert err_rt == cudart.cudaError_t.cudaSuccess + (err_dr,) = cuda.cuGraphExecDestroy(graphExec) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + (err_rt,) = cudart.cudaGraphDestroy(graph) + assert err_rt == cudart.cudaError_t.cudaSuccess + + +def test_interop_deviceptr(): + # Allocate dev memory + size = 1024 * np.uint8().itemsize + err_dr, dptr = cuda.cuMemAlloc(size) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + # Allocate host memory + h1 = np.full(size, 1).astype(np.uint8) + h2 = np.full(size, 2).astype(np.uint8) + assert np.array_equal(h1, h2) is False + + # Initialize device memory + (err_rt,) = cudart.cudaMemset(dptr, 1, size) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # D to h2 + (err_rt,) = cudart.cudaMemcpy(h2, dptr, size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # Validate h1 == h2 + assert np.array_equal(h1, h2) + + # Cleanup + (err_dr,) = cuda.cuMemFree(dptr) + assert err_dr == cuda.CUresult.CUDA_SUCCESS diff --git a/cuda_bindings/tests/nvml/test_cuda.py b/cuda_bindings/tests/nvml/test_cuda.py index 7a782e7403c..8ec7c8bcc68 100644 --- a/cuda_bindings/tests/nvml/test_cuda.py +++ b/cuda_bindings/tests/nvml/test_cuda.py @@ -5,7 +5,7 @@ import pytest -import cuda.bindings.driver as cuda +import cuda.bindings._v2.driver as cuda from cuda.bindings import nvml from .conftest import NVMLInitializer @@ -30,20 +30,16 @@ def get_nvml_device_names(): def get_cuda_device_names(sort_by_bus_id=True): result = [] - (err,) = cuda.cuInit(0) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.init(0) - err, device_count = cuda.cuDeviceGetCount() - assert err == cuda.CUresult.CUDA_SUCCESS + device_count = cuda.device_get_count() for dev in range(device_count): size = 256 - err, name = cuda.cuDeviceGetName(size, dev) + name = cuda.device_get_name(size, dev) name = name.split(b"\x00")[0].decode() - assert err == cuda.CUresult.CUDA_SUCCESS - err, pci_bus_id = cuda.cuDeviceGetAttribute(cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_PCI_BUS_ID, dev) - assert err == cuda.CUresult.CUDA_SUCCESS + pci_bus_id = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_PCI_BUS_ID, dev) assert isinstance(pci_bus_id, int) result.append({"name": name, "id": pci_bus_id}) diff --git a/cuda_bindings/tests/nvml/test_pci.py b/cuda_bindings/tests/nvml/test_pci.py index 877f9d2998a..7c671e6b7ff 100644 --- a/cuda_bindings/tests/nvml/test_pci.py +++ b/cuda_bindings/tests/nvml/test_pci.py @@ -15,7 +15,7 @@ def test_discover_gpus(all_devices, subtests): pci_info = nvml.device_get_pci_info_v3(device) # Docs say this should be supported on PASCAL and later with unsupported_before(device, None), contextlib.suppress(nvml.OperatingSystemError): - nvml.device_discover_gpus(pci_info.ptr) + nvml.device_discover_gpus(pci_info) def test_bridge_chip_hierarchy_t(): diff --git a/cuda_bindings/tests/test_cuda.py b/cuda_bindings/tests/test_cuda.py index 7bef2b844aa..753ce6a77ef 100644 --- a/cuda_bindings/tests/test_cuda.py +++ b/cuda_bindings/tests/test_cuda.py @@ -1,20 +1,17 @@ # SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import contextlib import ctypes -import os.path import shutil -import subprocess -import sys -import textwrap import numpy as np import pytest from cuda_python_test_helpers.mempool import xfail_if_mempool_oom -import cuda.bindings.driver as cuda +import cuda.bindings._v2.driver as cuda import cuda.bindings.runtime as cudart -from cuda.bindings import driver +from cuda.bindings._v2 import driver from cuda_python_test_helpers import driver_version_less_than @@ -36,6 +33,15 @@ def callableBinary(name): return shutil.which(name) is not None +# The _v2 bindings expose handles as plain ints and most structs as thin +# wrapper classes (e.g. driver.MemPoolProps_v1, driver.GraphNodeParams, +# driver.DevResource_v1, driver._DevSmResourceGroupParams) backed by the real +# cuda.h layout. Array-typed wrapper classes (AUTO_LOWPP_ARRAY) default to a +# single struct (`size=1`) but also support `Class(n)` for a caller-allocated +# array of n contiguous structs, backed by a numpy recarray -- used below for +# the SM-split APIs' bulk input/output arrays. + + @pytest.mark.skipif(True, reason="Always skip!") def test_always_skip(): pass @@ -46,8 +52,7 @@ def test_cuda_memcpy(): # Allocate dev memory size = int(1024 * np.uint8().itemsize) - err, dptr = cuda.cuMemAlloc(size) - assert err == cuda.CUresult.CUDA_SUCCESS + dptr = cuda.mem_alloc_v2(size) # Set h1 and h2 memory to be different h1 = np.full(size, 1).astype(np.uint8) @@ -55,125 +60,53 @@ def test_cuda_memcpy(): assert np.array_equal(h1, h2) is False # h1 to D - (err,) = cuda.cuMemcpyHtoD(dptr, h1, size) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.memcpy_htod_v2(dptr, h1, size) # D to h2 - (err,) = cuda.cuMemcpyDtoH(h2, dptr, size) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.memcpy_dtoh_v2(h2, dptr, size) # Validate h1 == h2 assert np.array_equal(h1, h2) # Cleanup - (err,) = cuda.cuMemFree(dptr) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_free_v2(dptr) def test_cuda_array(): # No context created - desc = cuda.CUDA_ARRAY_DESCRIPTOR() - err, arr = cuda.cuArrayCreate(desc) - assert err == cuda.CUresult.CUDA_ERROR_INVALID_CONTEXT or err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + desc = driver.ArrayDescriptor_v2() + with pytest.raises(driver.DriverError): + cuda.array_create_v2(desc) - # Desciption not filled - err, arr = cuda.cuArrayCreate(desc) - assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + # Description not filled + with pytest.raises(driver.DriverError) as excinfo: + cuda.array_create_v2(desc) + assert excinfo.value.status == driver.Result.CUDA_ERROR_INVALID_VALUE # Pass - desc.Format = cuda.CUarray_format.CU_AD_FORMAT_SIGNED_INT8 - desc.NumChannels = 1 - desc.Width = 1 - err, arr = cuda.cuArrayCreate(desc) - assert err == cuda.CUresult.CUDA_SUCCESS - - (err,) = cuda.cuArrayDestroy(arr) - assert err == cuda.CUresult.CUDA_SUCCESS - - -def test_cuda_repr_primitive(device, ctx): - assert str(device) == "" - assert int(device) == 0 - - assert str(ctx).startswith(" 0 - assert hex(ctx) == hex(int(ctx)) - - # CUdeviceptr - err, dptr = cuda.cuMemAlloc(1024 * np.uint8().itemsize) - assert err == cuda.CUresult.CUDA_SUCCESS - assert str(dptr).startswith(" 0 - (err,) = cuda.cuMemFree(dptr) - size = 7 - dptr = cuda.CUdeviceptr(size) - assert str(dptr) == f"" - assert int(dptr) == size - size = 4294967295 - dptr = cuda.CUdeviceptr(size) - assert str(dptr) == f"" - assert int(dptr) == size - size = 18446744073709551615 - dptr = cuda.CUdeviceptr(size) - assert str(dptr) == f"" - assert int(dptr) == size - - # cuuint32_t - size = 7 - int32 = cuda.cuuint32_t(size) - assert str(int32) == f"" - assert int(int32) == size - size = 4294967295 - int32 = cuda.cuuint32_t(size) - assert str(int32) == f"" - assert int(int32) == size - size = 18446744073709551615 - try: - int32 = cuda.cuuint32_t(size) - raise RuntimeError("int32 = cuda.cuuint32_t(18446744073709551615) did not fail") - except OverflowError as err: - pass - - # cuuint64_t - size = 7 - int64 = cuda.cuuint64_t(size) - assert str(int64) == f"" - assert int(int64) == size - size = 4294967295 - int64 = cuda.cuuint64_t(size) - assert str(int64) == f"" - assert int(int64) == size - size = 18446744073709551615 - int64 = cuda.cuuint64_t(size) - assert str(int64) == f"" - assert int(int64) == size - - -def test_cuda_repr_pointer(ctx): - # Test 1: Classes representing pointers - assert str(ctx).startswith(" 0 - assert hex(ctx) == hex(int(ctx)) - randomCtxPointer = 12345 - randomCtx = cuda.CUcontext(randomCtxPointer) - assert str(randomCtx) == f"" - assert int(randomCtx) == randomCtxPointer - assert hex(randomCtx) == hex(randomCtxPointer) - - # Test 2: Function pointers - func = 12345 - b2d_cb = cuda.CUoccupancyB2DSize(func) - assert str(b2d_cb) == f"" - assert int(b2d_cb) == func - assert hex(b2d_cb) == hex(func) + desc.format = driver.ArrayFormat.CU_AD_FORMAT_SIGNED_INT8 + desc.num_channels = 1 + desc.width = 1 + arr = cuda.array_create_v2(desc) + + cuda.array_destroy(arr) + + +# NOTE: test_cuda_repr_primitive and test_cuda_repr_pointer are intentionally +# not ported. They tested the repr/overflow/construction behavior of legacy +# wrapper classes (CUdeviceptr, cuuint32_t, cuuint64_t, CUcontext, +# CUoccupancyB2DSize) that have no equivalent in _v2.driver, where handles and +# device pointers are plain Python ints. That behavior remains permanently +# covered by tests/legacy_api/test_legacy_cuda.py. def test_cuda_uuid_list_access(device): - err, uuid = cuda.cuDeviceGetUuid(device) - assert err == cuda.CUresult.CUDA_SUCCESS - assert len(uuid.bytes) <= 16 + uuid = cuda.device_get_uuid_v2(device) + # Uuid.bytes decodes the raw 16-byte field as a UTF-8 C-string, which + # fails on arbitrary binary UUID bytes; read the raw bytes directly. + assert len(ctypes.string_at(uuid.ptr, 16)) == 16 - jit_option = cuda.CUjit_option + jit_option = driver.JitOption options = { jit_option.CU_JIT_INFO_LOG_BUFFER: 1, jit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: 2, @@ -181,254 +114,226 @@ def test_cuda_uuid_list_access(device): jit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: 4, jit_option.CU_JIT_LOG_VERBOSE: 5, } + assert len(options) == 5 def test_cuda_cuModuleLoadDataEx(): option_keys = [ - cuda.CUjit_option.CU_JIT_INFO_LOG_BUFFER, - cuda.CUjit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, - cuda.CUjit_option.CU_JIT_ERROR_LOG_BUFFER, - cuda.CUjit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, - cuda.CUjit_option.CU_JIT_LOG_VERBOSE, + driver.JitOption.CU_JIT_INFO_LOG_BUFFER, + driver.JitOption.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, + driver.JitOption.CU_JIT_ERROR_LOG_BUFFER, + driver.JitOption.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, + driver.JitOption.CU_JIT_LOG_VERBOSE, ] + options = (ctypes.c_int * len(option_keys))(*[int(k) for k in option_keys]) + option_values = (ctypes.c_void_p * len(option_keys))() # FIXME: This function call raises CUDA_ERROR_INVALID_VALUE - err, mod = cuda.cuModuleLoadDataEx(0, 0, option_keys, []) - - -def test_cuda_repr(): - actual = cuda.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS() - assert isinstance(actual, cuda.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS) - - actual_repr = actual.__repr__() - expected_repr = textwrap.dedent(""" - params : - fence : - value : 0 - nvSciSync : - fence : 0x0 - keyedMutex : - key : 0 -flags : 0 -""") - assert actual_repr.split() == expected_repr.split() - - actual_repr = cuda.CUDA_KERNEL_NODE_PARAMS_st().__repr__() - expected_repr = textwrap.dedent(""" - func : -gridDimX : 0 -gridDimY : 0 -gridDimZ : 0 -blockDimX : 0 -blockDimY : 0 -blockDimZ : 0 -sharedMemBytes : 0 -kernelParams : 0 -extra : 0 -""") - assert actual_repr.split() == expected_repr.split() + with pytest.raises(driver.DriverError): + cuda.module_load_data_ex(b"", len(option_keys), ctypes.addressof(options), ctypes.addressof(option_values)) -def test_cuda_struct_list_of_enums(): - desc = cuda.CUDA_TEXTURE_DESC_st() - desc.addressMode = [ - cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, - cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP, - cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_MIRROR, - ] +# NOTE: test_cuda_repr is intentionally not ported. It asserted a detailed, +# field-dump-style __repr__ for CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS and +# CUDA_KERNEL_NODE_PARAMS_st that is specific to the legacy driver.pyx.in +# codegen. _v2.driver's wrapper classes (e.g. KernelNodeParams_v2) use a +# generic `` __repr__ instead, so there is nothing +# equivalent to port. - # # Too many args - # desc.addressMode = [cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, - # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP, - # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_MIRROR, - # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_BORDER] - # # Too little args - # desc.addressMode = [cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, - # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP] +def test_cuda_struct_list_of_enums(): + desc = driver.TextureDesc_v1() + desc.address_mode = [ + driver.AddressMode.CU_TR_WRAP, + driver.AddressMode.CU_TR_CLAMP, + driver.AddressMode.CU_TR_MIRROR, + ] def test_cuda_CUstreamBatchMemOpParams(): - params = cuda.CUstreamBatchMemOpParams() - params.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 - params.waitValue.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 - params.writeValue.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 - params.flushRemoteWrites.operation = cuda.CUstreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32 - params.waitValue.value64 = 666 - assert int(params.waitValue.value64) == 666 + # StreamBatchMemOpParams_v1 exposes its per-operation members (wait_value, + # write_value, ...) as raw numpy "void" bytes (they alias the same union + # storage), so field-by-field access goes through ctypes at the + # underlying pointer rather than through nested wrapper objects. + params = driver.StreamBatchMemOpParams_v1() + ptr = params.ptr + ctypes.c_int.from_address(ptr).value = int(driver.StreamBatchMemOpType.CU_STREAM_MEM_OP_WAIT_VALUE_32) + # waitValue.value64 is CUstreamBatchMemOpType operation (4, padded to 8) + + # CUdeviceptr address (8) + value64 (8) -> offset 16 within the union. + ctypes.c_uint64.from_address(ptr + 16).value = 666 + assert ctypes.c_uint64.from_address(ptr + 16).value == 666 @pytest.mark.skipif( driver_version_less_than(11030) or not supportsMemoryPool(), reason="When new attributes were introduced" ) def test_cuda_memPool_attr(): - poolProps = cuda.CUmemPoolProps() - poolProps.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED - poolProps.location.id = 0 - poolProps.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + pool_props = driver.MemPoolProps_v1() + pool_props.alloc_type = driver.MemAllocationType.CU_PINNED + pool_props.location.id = 0 + pool_props.location.type = driver.MemLocationType.CU_DEVICE attr_list = [None] * 8 - err, pool = cuda.cuMemPoolCreate(poolProps) - xfail_if_mempool_oom(err, "cuMemPoolCreate", poolProps.location.id) - assert err == cuda.CUresult.CUDA_SUCCESS + try: + pool = cuda.mem_pool_create(pool_props) + except driver.DriverError as e: + xfail_if_mempool_oom(e, "mem_pool_create", pool_props.location.id) + raise + + def get_attr(attr): + buf = ctypes.c_uint64() + cuda.mem_pool_get_attribute(pool, attr, ctypes.addressof(buf)) + return buf.value + + def set_attr(attr, value, ctype=ctypes.c_int): + buf = ctype(value) + cuda.mem_pool_set_attribute(pool, attr, ctypes.addressof(buf)) for idx, attr in enumerate( [ - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_USED_MEM_CURRENT, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_USED_MEM_HIGH, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_USED_MEM_CURRENT, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_USED_MEM_HIGH, ] ): - err, attr_tmp = cuda.cuMemPoolGetAttribute(pool, attr) - assert err == cuda.CUresult.CUDA_SUCCESS - attr_list[idx] = attr_tmp + attr_list[idx] = get_attr(attr) - for idxA, attr in enumerate( - [ - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, - ] + for attr in ( + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, ): - (err,) = cuda.cuMemPoolSetAttribute(pool, attr, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - for idx, attr in enumerate([cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD]): - (err,) = cuda.cuMemPoolSetAttribute(pool, attr, cuda.cuuint64_t(9)) - assert err == cuda.CUresult.CUDA_SUCCESS + set_attr(attr, 0, ctypes.c_int) + set_attr(driver.MemPoolAttribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, 9, ctypes.c_uint64) for idx, attr in enumerate( [ - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, + driver.MemPoolAttribute.CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, ] ): - err, attr_tmp = cuda.cuMemPoolGetAttribute(pool, attr) - assert err == cuda.CUresult.CUDA_SUCCESS - attr_list[idx] = attr_tmp + attr_list[idx] = get_attr(attr) assert attr_list[0] == 0 assert attr_list[1] == 0 assert attr_list[2] == 0 - assert int(attr_list[3]) == 9 + assert attr_list[3] == 9 - (err,) = cuda.cuMemPoolDestroy(pool) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_pool_destroy(pool) @pytest.mark.skipif( driver_version_less_than(11030) or not supportsManagedMemory(), reason="When new attributes were introduced" ) def test_cuda_pointer_attr(): - err, ptr = cuda.cuMemAllocManaged(0x1000, cuda.CUmemAttach_flags.CU_MEM_ATTACH_GLOBAL.value) - assert err == cuda.CUresult.CUDA_SUCCESS + ptr = cuda.mem_alloc_managed(0x1000, int(driver.MemAttachFlags.CU_MEM_ATTACH_GLOBAL)) # Individual version attr_type_list = [ - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_CONTEXT, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMORY_TYPE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_POINTER, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_HOST_POINTER, - # cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_P2P_TOKENS, # TODO: Can I somehow test this? - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_BUFFER_ID, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_MANAGED, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_RANGE_START_ADDR, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_RANGE_SIZE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPED, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ACCESS_FLAGS, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE, + driver.PointerAttribute.CU_ATTRIBUTE_CONTEXT, + driver.PointerAttribute.CU_ATTRIBUTE_MEMORY_TYPE, + driver.PointerAttribute.CU_ATTRIBUTE_DEVICE_POINTER, + driver.PointerAttribute.CU_ATTRIBUTE_HOST_POINTER, + # driver.PointerAttribute.CU_ATTRIBUTE_P2P_TOKENS, # TODO: Can I somehow test this? + driver.PointerAttribute.CU_ATTRIBUTE_SYNC_MEMOPS, + driver.PointerAttribute.CU_ATTRIBUTE_BUFFER_ID, + driver.PointerAttribute.CU_ATTRIBUTE_IS_MANAGED, + driver.PointerAttribute.CU_ATTRIBUTE_DEVICE_ORDINAL, + driver.PointerAttribute.CU_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE, + driver.PointerAttribute.CU_ATTRIBUTE_RANGE_START_ADDR, + driver.PointerAttribute.CU_ATTRIBUTE_RANGE_SIZE, + driver.PointerAttribute.CU_ATTRIBUTE_MAPPED, + driver.PointerAttribute.CU_ATTRIBUTE_ALLOWED_HANDLE_TYPES, + driver.PointerAttribute.CU_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE, + driver.PointerAttribute.CU_ATTRIBUTE_ACCESS_FLAGS, + driver.PointerAttribute.CU_ATTRIBUTE_MEMPOOL_HANDLE, ] attr_value_list = [None] * len(attr_type_list) for idx, attr in enumerate(attr_type_list): - err, attr_tmp = cuda.cuPointerGetAttribute(attr, ptr) - assert err == cuda.CUresult.CUDA_SUCCESS - attr_value_list[idx] = attr_tmp - - # List version - err, attr_value_list_v2 = cuda.cuPointerGetAttributes(len(attr_type_list), attr_type_list, ptr) - assert err == cuda.CUresult.CUDA_SUCCESS - for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): - assert str(attr1) == str(attr2) + buf = ctypes.c_uint64() + cuda.pointer_get_attribute(ctypes.addressof(buf), attr, ptr) + attr_value_list[idx] = buf.value + + # List version. `data` is a `void**`: an array of pointers to + # per-attribute result buffers, not a flat array of values. + attributes = (ctypes.c_int * len(attr_type_list))(*[int(a) for a in attr_type_list]) + value_bufs = [ctypes.c_uint64() for _ in attr_type_list] + data = (ctypes.c_void_p * len(attr_type_list))(*[ctypes.addressof(b) for b in value_bufs]) + cuda.pointer_get_attributes(len(attr_type_list), ctypes.addressof(attributes), ctypes.addressof(data), ptr) + for attr1, buf in zip(attr_value_list, value_bufs): + assert attr1 == buf.value # Test setting values for val in (True, False): - (err,) = cuda.cuPointerSetAttribute(val, cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr) - assert err == cuda.CUresult.CUDA_SUCCESS - err, attr_tmp = cuda.cuPointerGetAttribute(cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, ptr) - assert err == cuda.CUresult.CUDA_SUCCESS - assert attr_tmp == val + flag = ctypes.c_int(int(val)) + cuda.pointer_set_attribute(ctypes.addressof(flag), driver.PointerAttribute.CU_ATTRIBUTE_SYNC_MEMOPS, ptr) + buf = ctypes.c_uint64() + cuda.pointer_get_attribute(ctypes.addressof(buf), driver.PointerAttribute.CU_ATTRIBUTE_SYNC_MEMOPS, ptr) + assert bool(buf.value) == val - (err,) = cuda.cuMemFree(ptr) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_free_v2(ptr) @pytest.mark.skipif( driver_version_less_than(11030) or not supportsManagedMemory(), reason="When new attributes were introduced" ) def test_pointer_get_attributes_device_ordinal(): - attributes = [ - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, - ] + attributes = [driver.PointerAttribute.CU_ATTRIBUTE_DEVICE_ORDINAL] + attributes_buf = (ctypes.c_int * len(attributes))(*[int(a) for a in attributes]) + value_buf = ctypes.c_int32() + data = (ctypes.c_void_p * len(attributes))(ctypes.addressof(value_buf)) - attrs = cuda.cuPointerGetAttributes(len(attributes), attributes, 0) + cuda.pointer_get_attributes(len(attributes), ctypes.addressof(attributes_buf), ctypes.addressof(data), 0) # device ordinals are always small numbers. A large number would indicate # an overflow error. - - assert abs(attrs[1][0]) < 256 + assert abs(value_buf.value) < 256 @pytest.mark.skipif(not supportsManagedMemory(), reason="When new attributes were introduced") def test_cuda_mem_range_attr(device): size = 0x1000 - location_device = cuda.CUmemLocation() - location_device.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + location_device = driver.MemLocation_v1() + location_device.type = driver.MemLocationType.CU_DEVICE location_device.id = int(device) - location_cpu = cuda.CUmemLocation() - location_cpu.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST - location_cpu.id = int(cuda.CU_DEVICE_CPU) - - err, ptr = cuda.cuMemAllocManaged(size, cuda.CUmemAttach_flags.CU_MEM_ATTACH_GLOBAL.value) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_READ_MOSTLY, location_device) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_PREFERRED_LOCATION, location_cpu) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_ACCESSED_BY, location_cpu) - assert err == cuda.CUresult.CUDA_SUCCESS - err, concurrentSupported = cuda.cuDeviceGetAttribute( - cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, device + location_cpu = driver.MemLocation_v1() + location_cpu.type = driver.MemLocationType.CU_HOST + location_cpu.id = -1 # CU_DEVICE_CPU + + ptr = cuda.mem_alloc_managed(size, int(driver.MemAttachFlags.CU_MEM_ATTACH_GLOBAL)) + cuda.mem_advise_v2(ptr, size, driver.MemAdvise.CU_SET_READ_MOSTLY, location_device) + cuda.mem_advise_v2(ptr, size, driver.MemAdvise.CU_SET_PREFERRED_LOCATION, location_cpu) + cuda.mem_advise_v2(ptr, size, driver.MemAdvise.CU_SET_ACCESSED_BY, location_cpu) + concurrentSupported = cuda.device_get_attribute( + driver.DeviceAttribute.CU_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, device ) - assert err == cuda.CUresult.CUDA_SUCCESS if concurrentSupported: - (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_ACCESSED_BY, location_device) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_advise_v2(ptr, size, driver.MemAdvise.CU_SET_ACCESSED_BY, location_device) expected_values_list = ([1, -1, [0, -1, -2], -2],) else: expected_values_list = ([1, -1, [-1, -2, -2], -2], [0, -2, [-2, -2, -2], -2]) # Individual version attr_type_list = [ - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION, + driver.MemRangeAttribute.CU_ATTRIBUTE_READ_MOSTLY, + driver.MemRangeAttribute.CU_ATTRIBUTE_PREFERRED_LOCATION, + driver.MemRangeAttribute.CU_ATTRIBUTE_ACCESSED_BY, + driver.MemRangeAttribute.CU_ATTRIBUTE_LAST_PREFETCH_LOCATION, ] attr_type_size_list = [4, 4, 12, 4] attr_value_list = [None] * len(attr_type_list) for idx in range(len(attr_type_list)): - err, attr_tmp = cuda.cuMemRangeGetAttribute(attr_type_size_list[idx], attr_type_list[idx], ptr, size) - assert err == cuda.CUresult.CUDA_SUCCESS - attr_value_list[idx] = attr_tmp + buf = ctypes.create_string_buffer(attr_type_size_list[idx]) + cuda.mem_range_get_attribute(ctypes.addressof(buf), attr_type_size_list[idx], attr_type_list[idx], ptr, size) + if attr_type_size_list[idx] == 4: + attr_value_list[idx] = ctypes.c_int32.from_buffer(buf, 0).value + else: + attr_value_list[idx] = [ctypes.c_int32.from_buffer(buf, i * 4).value for i in range(3)] matched = False for expected_values in expected_values_list: @@ -438,16 +343,28 @@ def test_cuda_mem_range_attr(device): if not matched: raise RuntimeError(f"attr_value_list {attr_value_list} did not match any {expected_values_list}") - # List version - err, attr_value_list_v2 = cuda.cuMemRangeGetAttributes( - attr_type_size_list, attr_type_list, len(attr_type_list), ptr, size + # List version. `data` is a `void**`: an array of pointers to + # per-attribute result buffers, not a flat array of values. + data_sizes = (ctypes.c_size_t * len(attr_type_list))(*attr_type_size_list) + attributes = (ctypes.c_int * len(attr_type_list))(*[int(a) for a in attr_type_list]) + value_bufs = [ctypes.create_string_buffer(sz) for sz in attr_type_size_list] + data = (ctypes.c_void_p * len(attr_type_list))(*[ctypes.addressof(b) for b in value_bufs]) + cuda.mem_range_get_attributes( + ctypes.addressof(data), + ctypes.addressof(data_sizes), + ctypes.addressof(attributes), + len(attr_type_list), + ptr, + size, ) - assert err == cuda.CUresult.CUDA_SUCCESS - for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): - assert str(attr1) == str(attr2) + for idx, (buf, sz) in enumerate(zip(value_bufs, attr_type_size_list)): + if sz == 4: + value = ctypes.c_int32.from_buffer(buf, 0).value + else: + value = [ctypes.c_int32.from_buffer(buf, i * 4).value for i in range(3)] + assert value == attr_value_list[idx] - (err,) = cuda.cuMemFree(ptr) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_free_v2(ptr) @pytest.mark.skipif( @@ -455,109 +372,116 @@ def test_cuda_mem_range_attr(device): ) @pytest.mark.thread_unsafe(reason="used high memory can be higher if threaded.") def test_cuda_graphMem_attr(device): - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + stream = cuda.stream_create(0) + graph = cuda.graph_create(0) allocSize = 1 - params = cuda.CUDA_MEM_ALLOC_NODE_PARAMS() - params.poolProps.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE - params.poolProps.location.id = device - params.poolProps.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED + params = driver.MemAllocNodeParams_v2() + params.pool_props.location.type = driver.MemLocationType.CU_DEVICE + params.pool_props.location.id = device + params.pool_props.alloc_type = driver.MemAllocationType.CU_PINNED params.bytesize = allocSize - err, allocNode = cuda.cuGraphAddMemAllocNode(graph, None, 0, params) - if err == cuda.CUresult.CUDA_ERROR_OUT_OF_MEMORY: - (destroy_err,) = cuda.cuGraphDestroy(graph) - assert destroy_err == cuda.CUresult.CUDA_SUCCESS - (destroy_err,) = cuda.cuStreamDestroy(stream) - assert destroy_err == cuda.CUresult.CUDA_SUCCESS - xfail_if_mempool_oom(err, "cuGraphAddMemAllocNode", device) - assert err == cuda.CUresult.CUDA_SUCCESS - err, freeNode = cuda.cuGraphAddMemFreeNode(graph, [allocNode], 1, params.dptr) - assert err == cuda.CUresult.CUDA_SUCCESS - - err, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - - (err,) = cuda.cuGraphLaunch(graphExec, stream) - assert err == cuda.CUresult.CUDA_SUCCESS - - err, used = cuda.cuDeviceGetGraphMemAttribute(device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT) - assert err == cuda.CUresult.CUDA_SUCCESS - err, usedHigh = cuda.cuDeviceGetGraphMemAttribute(device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_USED_MEM_HIGH) - assert err == cuda.CUresult.CUDA_SUCCESS - err, reserved = cuda.cuDeviceGetGraphMemAttribute( - device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT + try: + allocNode = cuda.graph_add_mem_alloc_node(graph, 0, 0, params) + except driver.DriverError as e: + if e.status == driver.Result.CUDA_ERROR_OUT_OF_MEMORY: + cuda.graph_destroy(graph) + cuda.stream_destroy_v2(stream) + xfail_if_mempool_oom(e, "graph_add_mem_alloc_node", device) + raise + deps = (ctypes.c_void_p * 1)(allocNode) + cuda.graph_add_mem_free_node(graph, ctypes.addressof(deps), 1, params.dptr) + + graphExec = cuda.graph_instantiate_with_flags(graph, 0) + + cuda.graph_launch(graphExec, stream) + + used = ctypes.c_uint64() + cuda.device_get_graph_mem_attribute( + device, driver.GraphMemAttribute.CU_ATTR_USED_MEM_CURRENT, ctypes.addressof(used) + ) + usedHigh = ctypes.c_uint64() + cuda.device_get_graph_mem_attribute( + device, driver.GraphMemAttribute.CU_ATTR_USED_MEM_HIGH, ctypes.addressof(usedHigh) ) - assert err == cuda.CUresult.CUDA_SUCCESS - err, reservedHigh = cuda.cuDeviceGetGraphMemAttribute( - device, cuda.CUgraphMem_attribute.CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH + reserved = ctypes.c_uint64() + cuda.device_get_graph_mem_attribute( + device, driver.GraphMemAttribute.CU_ATTR_RESERVED_MEM_CURRENT, ctypes.addressof(reserved) + ) + reservedHigh = ctypes.c_uint64() + cuda.device_get_graph_mem_attribute( + device, driver.GraphMemAttribute.CU_ATTR_RESERVED_MEM_HIGH, ctypes.addressof(reservedHigh) ) - assert err == cuda.CUresult.CUDA_SUCCESS - assert int(used) >= allocSize - assert int(usedHigh) == int(used) - assert int(reserved) == int(usedHigh) - assert int(reservedHigh) == int(reserved) + assert used.value >= allocSize + assert usedHigh.value == used.value + assert reserved.value == usedHigh.value + assert reservedHigh.value == reserved.value - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_exec_destroy(graphExec) + cuda.graph_destroy(graph) + cuda.stream_destroy_v2(stream) @pytest.mark.skipif( driver_version_less_than(12010) - or not supportsCudaAPI("cuCoredumpSetAttributeGlobal") - or not supportsCudaAPI("cuCoredumpGetAttributeGlobal"), + or not supportsCudaAPI("coredump_set_attribute_global") + or not supportsCudaAPI("coredump_get_attribute_global"), reason="Coredump API not present", ) def test_cuda_coredump_attr(): - attr_list = [None] * 6 - - (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, False) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_FILE, b"corefile") - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_PIPE, b"corepipe") - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuCoredumpSetAttributeGlobal(cuda.CUcoredumpSettings.CU_COREDUMP_LIGHTWEIGHT, True) - assert err == cuda.CUresult.CUDA_SUCCESS - - for idx, attr in enumerate( - [ - cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, - cuda.CUcoredumpSettings.CU_COREDUMP_FILE, - cuda.CUcoredumpSettings.CU_COREDUMP_PIPE, - cuda.CUcoredumpSettings.CU_COREDUMP_LIGHTWEIGHT, - ] - ): - err, attr_tmp = cuda.cuCoredumpGetAttributeGlobal(attr) - assert err == cuda.CUresult.CUDA_SUCCESS - attr_list[idx] = attr_tmp - - assert attr_list[0] is False - assert attr_list[1] == b"corefile" - assert attr_list[2] == b"corepipe" - assert attr_list[3] is True + def set_bool(attr, value): + buf = ctypes.c_bool(value) + size = ctypes.c_size_t(ctypes.sizeof(buf)) + cuda.coredump_set_attribute_global(attr, ctypes.addressof(buf), ctypes.addressof(size)) + + def set_bytes(attr, value): + buf = ctypes.create_string_buffer(value) + size = ctypes.c_size_t(len(value)) + cuda.coredump_set_attribute_global(attr, ctypes.addressof(buf), ctypes.addressof(size)) + + def get_bool(attr): + buf = ctypes.c_bool() + size = ctypes.c_size_t(ctypes.sizeof(buf)) + cuda.coredump_get_attribute_global(attr, ctypes.addressof(buf), ctypes.addressof(size)) + return buf.value + + def get_bytes(attr, maxlen=1024): + buf = ctypes.create_string_buffer(maxlen) + size = ctypes.c_size_t(maxlen) + cuda.coredump_get_attribute_global(attr, ctypes.addressof(buf), ctypes.addressof(size)) + return buf.raw[: size.value] + + set_bool(driver.CoredumpSettings.CU_COREDUMP_TRIGGER_HOST, False) + set_bytes(driver.CoredumpSettings.CU_COREDUMP_FILE, b"corefile") + set_bytes(driver.CoredumpSettings.CU_COREDUMP_PIPE, b"corepipe") + set_bool(driver.CoredumpSettings.CU_COREDUMP_LIGHTWEIGHT, True) + + assert get_bool(driver.CoredumpSettings.CU_COREDUMP_TRIGGER_HOST) is False + assert get_bytes(driver.CoredumpSettings.CU_COREDUMP_FILE).rstrip(b"\x00") == b"corefile" + assert get_bytes(driver.CoredumpSettings.CU_COREDUMP_PIPE).rstrip(b"\x00") == b"corepipe" + assert get_bool(driver.CoredumpSettings.CU_COREDUMP_LIGHTWEIGHT) is True def test_get_error_name_and_string(): - err, device = cuda.cuDeviceGet(0) - _, s = cuda.cuGetErrorString(err) - assert s == b"no error" - _, s = cuda.cuGetErrorName(err) - assert s == b"CUDA_SUCCESS" - - err, device = cuda.cuDeviceGet(-1) - _, s = cuda.cuGetErrorString(err) - assert s == b"invalid device ordinal" - _, s = cuda.cuGetErrorName(err) - assert s == b"CUDA_ERROR_INVALID_DEVICE" + device = cuda.device_get(0) + assert isinstance(device, int) + # get_error_string / get_error_name return str in _v2.driver (the legacy + # API returned bytes). + s = cuda.get_error_string(driver.Result.CUDA_SUCCESS) + assert s == "no error" + s = cuda.get_error_name(driver.Result.CUDA_SUCCESS) + assert s == "CUDA_SUCCESS" + + with pytest.raises(driver.DriverError) as excinfo: + cuda.device_get(-1) + assert excinfo.value.status == driver.Result.CUDA_ERROR_INVALID_DEVICE + s = cuda.get_error_string(driver.Result.CUDA_ERROR_INVALID_DEVICE) + assert s == "invalid device ordinal" + s = cuda.get_error_name(driver.Result.CUDA_ERROR_INVALID_DEVICE) + assert s == "CUDA_ERROR_INVALID_DEVICE" # TODO: cuStreamGetCaptureInfo_v2 @@ -567,258 +491,195 @@ def test_stream_capture(): def test_profiler(): - (err,) = cuda.cuProfilerStart() - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuProfilerStop() - assert err == cuda.CUresult.CUDA_SUCCESS - - -def test_eglFrame(): - val = cuda.CUeglFrame() - # [, , ] - assert int(val.frame.pArray[0]) == 0 - assert int(val.frame.pArray[1]) == 0 - assert int(val.frame.pArray[2]) == 0 - val.frame.pArray = [1, 2, 3] - # [, , ] - assert int(val.frame.pArray[0]) == 1 - assert int(val.frame.pArray[1]) == 2 - assert int(val.frame.pArray[2]) == 3 - val.frame.pArray = [cuda.CUarray(4), 2, 3] - # [, , ] - assert int(val.frame.pArray[0]) == 4 - assert int(val.frame.pArray[1]) == 2 - assert int(val.frame.pArray[2]) == 3 - val.frame.pPitch = [4, 2, 3] - # [4, 2, 3] - assert int(val.frame.pPitch[0]) == 4 - assert int(val.frame.pPitch[1]) == 2 - assert int(val.frame.pPitch[2]) == 3 - val.frame.pPitch = [1, 2, 3] - assert int(val.frame.pPitch[0]) == 1 - assert int(val.frame.pPitch[1]) == 2 - assert int(val.frame.pPitch[2]) == 3 - - -def test_anon_assign(): - val1 = cuda.CUexecAffinityParam_st() - val2 = cuda.CUexecAffinityParam_st() - - assert val1.param.smCount.val == 0 - val1.param.smCount.val = 5 - assert val1.param.smCount.val == 5 - val2.param.smCount.val = 11 - assert val2.param.smCount.val == 11 - - val1.param = val2.param - assert val1.param.smCount.val == 11 - - -def test_union_assign(): - val = cuda.CUlaunchAttributeValue() - val.clusterDim.x, val.clusterDim.y, val.clusterDim.z = 9, 9, 9 - attr = cuda.CUlaunchAttribute() - attr.value = val - - assert val.clusterDim.x == 9 - assert val.clusterDim.y == 9 - assert val.clusterDim.z == 9 - - -def test_invalid_repr_attribute(): - val = cuda.CUlaunchAttributeValue() - string = str(val) + cuda.profiler_start() + cuda.profiler_stop() + + +# NOTE: test_eglFrame is intentionally not ported. It only exercised +# construction/field-assignment of a bare CUeglFrame struct (no driver call), +# and _v2.driver does not expose a Python wrapper class for CUeglFrame. + + +# NOTE: test_anon_assign, test_union_assign, and test_invalid_repr_attribute +# are intentionally not ported. They tested legacy-codegen-specific behavior +# of the anonymous-union wrapper classes for CUexecAffinityParam_st and +# CUlaunchAttributeValue. _v2.driver has no CUlaunchAttributeValue wrapper at +# all, and its ExecAffinityParam_v1 is a numpy-recarray-backed batch wrapper +# with fundamentally different assignment semantics, so there is no +# meaningful equivalent to port. @pytest.mark.skipif( driver_version_less_than(12020) - or not supportsCudaAPI("cuGraphAddNode") - or not supportsCudaAPI("cuGraphNodeSetParams") - or not supportsCudaAPI("cuGraphExecNodeSetParams"), - reason="Polymorphic graph APIs required", + or not supportsCudaAPI("graph_add_memset_node") + or not supportsCudaAPI("graph_exec_memset_node_set_params"), + reason="Typed graph node APIs required", ) -def test_graph_poly(): - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - - # cuGraphAddNode +def test_graph_poly(ctx): + stream = cuda.stream_create(0) # Create 2 buffers size = int(1024 * np.uint8().itemsize) buffers = [] for _ in range(2): - err, dptr = cuda.cuMemAlloc(size) - assert err == cuda.CUresult.CUDA_SUCCESS + dptr = cuda.mem_alloc_v2(size) buffers += [(np.full(size, 2).astype(np.uint8), dptr)] # Update dev buffers for host, device in buffers: - (err,) = cuda.cuMemcpyHtoD(device, host, size) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.memcpy_htod_v2(device, host, size) # Create graph nodes = [] - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) # Memset host, device = buffers[0] - memsetParams = cuda.CUgraphNodeParams() - memsetParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_MEMSET - memsetParams.memset.elementSize = np.uint8().itemsize - memsetParams.memset.width = size - memsetParams.memset.height = 1 - memsetParams.memset.dst = device - memsetParams.memset.value = 1 - err, node = cuda.cuGraphAddNode(graph, None, None, 0, memsetParams) - assert err == cuda.CUresult.CUDA_SUCCESS + memsetParams = driver.MemsetNodeParams_v1() + memsetParams.dst = device + memsetParams.element_size = np.uint8().itemsize + memsetParams.width = size + memsetParams.height = 1 + memsetParams.value = 1 + node = cuda.graph_add_memset_node(graph, 0, 0, memsetParams, ctx) nodes += [node] # Memcpy host, device = buffers[1] - memcpyParams = cuda.CUgraphNodeParams() - memcpyParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_MEMCPY - memcpyParams.memcpy.copyParams.srcMemoryType = cuda.CUmemorytype.CU_MEMORYTYPE_DEVICE - memcpyParams.memcpy.copyParams.srcDevice = device - memcpyParams.memcpy.copyParams.dstMemoryType = cuda.CUmemorytype.CU_MEMORYTYPE_HOST - memcpyParams.memcpy.copyParams.dstHost = host - memcpyParams.memcpy.copyParams.WidthInBytes = size - memcpyParams.memcpy.copyParams.Height = 1 - memcpyParams.memcpy.copyParams.Depth = 1 - err, node = cuda.cuGraphAddNode(graph, None, None, 0, memcpyParams) - assert err == cuda.CUresult.CUDA_SUCCESS + memcpyParams = driver.Memcpy3d_v2() + memcpyParams.src_memory_type = driver.Memorytype.CU_DEVICE + memcpyParams.src_device = device + memcpyParams.dst_memory_type = driver.Memorytype.CU_HOST + # dst_host takes a raw address (unlike the legacy API's setter, it does + # not hold a reference to keep the buffer alive itself); `host` is kept + # alive by the `buffers` list for the duration of this test. + memcpyParams.dst_host = host.ctypes.data + memcpyParams.width_in_bytes = size + memcpyParams.height = 1 + memcpyParams.depth = 1 + node = cuda.graph_add_memcpy_node(graph, 0, 0, memcpyParams, ctx) nodes += [node] # Instantiate, execute, validate - err, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphLaunch(graphExec, stream) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamSynchronize(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + graphExec = cuda.graph_instantiate_with_flags(graph, 0) + cuda.graph_launch(graphExec, stream) + cuda.stream_synchronize(stream) # Validate for host, device in buffers: - (err,) = cuda.cuMemcpyDtoH(host, device, size) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.memcpy_dtoh_v2(host, device, size) assert np.array_equal(buffers[0][0], np.full(size, 1).astype(np.uint8)) assert np.array_equal(buffers[1][0], np.full(size, 2).astype(np.uint8)) - # cuGraphNodeSetParams + # graph_memcpy_node_get_params / graph_memcpy_node_set_params host, device = buffers[1] - err, memcpyParamsCopy = cuda.cuGraphMemcpyNodeGetParams(nodes[1]) - assert err == cuda.CUresult.CUDA_SUCCESS - assert int(memcpyParamsCopy.srcDevice) == int(device) + memcpyParamsCopy = driver.Memcpy3d_v2() + cuda.graph_memcpy_node_get_params(nodes[1], memcpyParamsCopy) + assert int(memcpyParamsCopy.src_device) == int(device) host, device = buffers[0] - memcpyParams.memcpy.copyParams.srcDevice = device - (err,) = cuda.cuGraphNodeSetParams(nodes[1], memcpyParams) - assert err == cuda.CUresult.CUDA_SUCCESS - err, memcpyParamsCopy = cuda.cuGraphMemcpyNodeGetParams(nodes[1]) - assert err == cuda.CUresult.CUDA_SUCCESS - assert int(memcpyParamsCopy.srcDevice) == int(device) - - # cuGraphExecNodeSetParams - memsetParams.memset.value = 11 - (err,) = cuda.cuGraphExecNodeSetParams(graphExec, nodes[0], memsetParams) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphLaunch(graphExec, stream) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamSynchronize(stream) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuMemcpyDtoH(buffers[0][0], buffers[0][1], size) - assert err == cuda.CUresult.CUDA_SUCCESS + memcpyParams.src_device = device + cuda.graph_memcpy_node_set_params(nodes[1], memcpyParams) + memcpyParamsCopy = driver.Memcpy3d_v2() + cuda.graph_memcpy_node_get_params(nodes[1], memcpyParamsCopy) + assert int(memcpyParamsCopy.src_device) == int(device) + + # graph_exec_memset_node_set_params + memsetParams.value = 11 + cuda.graph_exec_memset_node_set_params(graphExec, nodes[0], memsetParams, ctx) + cuda.graph_launch(graphExec, stream) + cuda.stream_synchronize(stream) + cuda.memcpy_dtoh_v2(buffers[0][0], buffers[0][1], size) assert np.array_equal(buffers[0][0], np.full(size, 11).astype(np.uint8)) # Cleanup - (err,) = cuda.cuMemFree(buffers[0][1]) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuMemFree(buffers[1][1]) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphExecDestroy(graphExec) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.mem_free_v2(buffers[0][1]) + cuda.mem_free_v2(buffers[1][1]) + cuda.graph_exec_destroy(graphExec) + cuda.graph_destroy(graph) + cuda.stream_destroy_v2(stream) @pytest.mark.skipif( - driver_version_less_than(12040) or not supportsCudaAPI("cuDeviceGetDevResource"), + driver_version_less_than(12040) or not supportsCudaAPI("device_get_dev_resource"), reason="Polymorphic graph APIs required", ) def test_cuDeviceGetDevResource(device): - err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) + resource_in = driver.DevResource_v1() + cuda.device_get_dev_resource(device, resource_in, driver.DevResourceType.CU_SM) + + def split(nb_groups, min_count): + result = driver.DevResource_v1(nb_groups) if nb_groups else None + nb_groups_buf = ctypes.c_uint(nb_groups) + remainder = driver.DevResource_v1() + cuda.dev_sm_resource_split_by_count( + result if result is not None else 0, + ctypes.addressof(nb_groups_buf), + resource_in, + remainder, + 0, + min_count, + ) + return result, nb_groups_buf.value - err, res, count, rem = cuda.cuDevSmResourceSplitByCount(0, resource_in, 0, 2) - assert err == cuda.CUresult.CUDA_SUCCESS + # Query the number of groups that would be created. + _, count = split(0, 2) assert count != 0 - assert len(res) == 0 - err, res, count_same, rem = cuda.cuDevSmResourceSplitByCount(count, resource_in, 0, 2) - assert err == cuda.CUresult.CUDA_SUCCESS + res, count_same = split(count, 2) assert count == count_same - assert len(res) == count - err, res, count, rem = cuda.cuDevSmResourceSplitByCount(3, resource_in, 0, 2) - assert err == cuda.CUresult.CUDA_SUCCESS - assert len(res) == 3 + res, count = split(3, 2) + assert count <= 3 @pytest.mark.skipif( - driver_version_less_than(12030) or not supportsCudaAPI("cuGraphConditionalHandleCreate"), + driver_version_less_than(12030) or not supportsCudaAPI("graph_conditional_handle_create"), reason="Conditional graph APIs required", ) -def test_conditional(ctx): - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, handle = cuda.cuGraphConditionalHandleCreate(graph, ctx, 0, 0) - assert err == cuda.CUresult.CUDA_SUCCESS +def test_conditional(ctx, device): + graph = cuda.graph_create(0) + handle = cuda.graph_conditional_handle_create(graph, ctx, 0, 0) - params = cuda.CUgraphNodeParams() - params.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_CONDITIONAL - params.conditional.handle = handle - params.conditional.type = cuda.CUgraphConditionalNodeType.CU_GRAPH_COND_TYPE_IF - params.conditional.size = 1 - params.conditional.ctx = ctx + # `phGraph_out` is a CUDA-owned output array (see the field docstring in + # cuda.h): the driver allocates it and writes its own pointer into + # node_params.conditional.ph_graph_out during node creation -- it must be + # left unset (zero) on input, not pre-allocated by the caller. + node_params = driver.GraphNodeParams() + node_params.type = driver.GraphNodeType.CU_CONDITIONAL + node_params.conditional.handle = handle + node_params.conditional.type = int(driver.GraphConditionalNodeType.CU_GRAPH_COND_TYPE_IF) + node_params.conditional.size_ = 1 + node_params.conditional.ctx = ctx - assert len(params.conditional.phGraph_out) == 1 - assert int(params.conditional.phGraph_out[0]) == 0 - err, node = cuda.cuGraphAddNode(graph, None, None, 0, params) - assert err == cuda.CUresult.CUDA_SUCCESS + assert node_params.conditional.ph_graph_out == 0 + cuda.graph_add_node_v2(graph, 0, 0, 0, node_params) - assert len(params.conditional.phGraph_out) == 1 - assert int(params.conditional.phGraph_out[0]) != 0 + phGraph_out_ptr = node_params.conditional.ph_graph_out + assert phGraph_out_ptr not in (None, 0) + branch_graph = ctypes.cast(phGraph_out_ptr, ctypes.POINTER(ctypes.c_void_p))[0] + assert branch_graph is not None - -def test_CUmemDecompressParams_st(): - desc = cuda.CUmemDecompressParams_st() - assert int(desc.dstActBytes) == 0 + cuda.graph_destroy(graph) def test_all_CUresult_codes(): - max_code = int(max(cuda.CUresult)) + max_code = int(max(driver.Result)) # Smoke test. CUDA_ERROR_UNKNOWN = 999, but intentionally using literal value. assert max_code >= 999 num_good = 0 for code in range(max_code + 2): # One past max_code try: - error = cuda.CUresult(code) + error = driver.Result(code) except ValueError: pass # cython-generated enum does not exist for this code else: - err_name, name = cuda.cuGetErrorName(error) - if err_name == cuda.CUresult.CUDA_SUCCESS: - assert name - err_desc, desc = cuda.cuGetErrorString(error) - assert err_desc == cuda.CUresult.CUDA_SUCCESS - assert desc + # get_error_name/get_error_string return "" (rather than raising) + # when the driver does not recognize the code (e.g. cuda-bindings + # built against a newer CTK than the installed driver supports). + name = cuda.get_error_name(error) + if name: + assert cuda.get_error_string(error) num_good += 1 else: - # cython-generated enum exists but is not known to an older driver - # (example: cuda-bindings built with CTK 12.8, driver from CTK 12.0) - assert name is None - assert err_name == cuda.CUresult.CUDA_ERROR_INVALID_VALUE - err_desc, desc = cuda.cuGetErrorString(error) - assert err_desc == cuda.CUresult.CUDA_ERROR_INVALID_VALUE - assert desc is None + assert cuda.get_error_string(error) == "" # Smoke test: Do we have at least some "good" codes? # The number will increase over time as new enums are added and support for # old CTKs is dropped, but it is not critical that this number is updated. @@ -827,26 +688,25 @@ def test_all_CUresult_codes(): @pytest.mark.skipif(driver_version_less_than(12030), reason="Driver too old for cuKernelGetName") def test_cuKernelGetName_failure(): - err, name = cuda.cuKernelGetName(0) - assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE - assert name is None + with pytest.raises(driver.DriverError) as excinfo: + cuda.kernel_get_name(0) + assert excinfo.value.status == driver.Result.CUDA_ERROR_INVALID_VALUE @pytest.mark.skipif(driver_version_less_than(12030), reason="Driver too old for cuFuncGetName") def test_cuFuncGetName_failure(): - err, name = cuda.cuFuncGetName(0) - assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE - assert name is None + with pytest.raises(driver.DriverError) as excinfo: + cuda.func_get_name(0) + assert excinfo.value.status == driver.Result.CUDA_ERROR_INVALID_VALUE @pytest.mark.skipif( - driver_version_less_than(12080) or not supportsCudaAPI("cuCheckpointProcessGetState"), + driver_version_less_than(12080) or not supportsCudaAPI("checkpoint_process_get_state"), reason="When API was introduced", ) def test_cuCheckpointProcessGetState_failure(): - err, state = cuda.cuCheckpointProcessGetState(123434) - assert err != cuda.CUresult.CUDA_SUCCESS - assert state is None + with pytest.raises(driver.DriverError): + cuda.checkpoint_process_get_state(123434) def test_private_function_pointer_inspector(): @@ -855,104 +715,64 @@ def test_private_function_pointer_inspector(): assert _inspect_function_pointer("__cuGetErrorString") != 0 -@pytest.mark.parametrize( - "target", - ( - driver.CUcontext, - driver.CUstream, - driver.CUevent, - driver.CUmodule, - driver.CUlibrary, - driver.CUfunction, - driver.CUkernel, - driver.CUgraph, - driver.CUgraphNode, - driver.CUgraphExec, - driver.CUmemoryPool, - ), -) -def test_struct_pointer_comparison(target): - a = target(123) - b = target(123) - assert a == b - assert hash(a) == hash(b) - c = target(456) - assert a != c - assert hash(a) != hash(c) +# NOTE: test_struct_pointer_comparison is intentionally not ported. It tested +# equality/hash behavior of legacy pointer-wrapper classes (CUcontext, +# CUstream, ...) that have no equivalent in _v2.driver, where handles are +# plain Python ints (which already support equality/hash trivially). @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuGraphGetId"), + driver_version_less_than(13010) or not supportsCudaAPI("graph_get_id"), reason="Requires CUDA 13.1+", ) def test_cuGraphGetId(device, ctx): - """Test cuGraphGetId - get graph ID.""" - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test graph_get_id - get graph ID.""" + graph = cuda.graph_create(0) - err, graph_id = cuda.cuGraphGetId(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + graph_id = cuda.graph_get_id(graph) assert isinstance(graph_id, int) assert graph_id > 0 # Create another graph and verify it has a different ID - err, graph2 = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, graph_id2 = cuda.cuGraphGetId(graph2) - assert err == cuda.CUresult.CUDA_SUCCESS + graph2 = cuda.graph_create(0) + graph_id2 = cuda.graph_get_id(graph2) assert graph_id2 != graph_id - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphDestroy(graph2) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) + cuda.graph_destroy(graph2) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuGraphExecGetId"), + driver_version_less_than(13010) or not supportsCudaAPI("graph_exec_get_id"), reason="Requires CUDA 13.1+", ) def test_cuGraphExecGetId(device, ctx): - """Test cuGraphExecGetId - get graph exec ID.""" - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test graph_exec_get_id - get graph exec ID.""" + stream = cuda.stream_create(0) - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) # Add an empty node to make the graph valid - err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_add_empty_node(graph, 0, 0) - err, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + graphExec = cuda.graph_instantiate_with_flags(graph, 0) - err, graph_exec_id = cuda.cuGraphExecGetId(graphExec) - assert err == cuda.CUresult.CUDA_SUCCESS + graph_exec_id = cuda.graph_exec_get_id(graphExec) assert isinstance(graph_exec_id, int) assert graph_exec_id > 0 # Create another graph exec and verify it has a different ID - err, graph2 = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, node2 = cuda.cuGraphAddEmptyNode(graph2, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, graphExec2 = cuda.cuGraphInstantiate(graph2, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, graph_exec_id2 = cuda.cuGraphExecGetId(graphExec2) - assert err == cuda.CUresult.CUDA_SUCCESS + graph2 = cuda.graph_create(0) + cuda.graph_add_empty_node(graph2, 0, 0) + graphExec2 = cuda.graph_instantiate_with_flags(graph2, 0) + graph_exec_id2 = cuda.graph_exec_get_id(graphExec2) assert graph_exec_id2 != graph_exec_id - (err,) = cuda.cuGraphExecDestroy(graphExec) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphExecDestroy(graphExec2) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphDestroy(graph2) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_exec_destroy(graphExec) + cuda.graph_exec_destroy(graphExec2) + cuda.graph_destroy(graph) + cuda.graph_destroy(graph2) + cuda.stream_destroy_v2(stream) def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): @@ -961,29 +781,24 @@ def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): # a scratch buffer that was freed before the call returned, leaving the # wrappers pointing at freed memory. Ensure the returned objects remain # readable after the call and after subsequent allocations. - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) try: - err, n0 = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, n1 = cuda.cuGraphAddEmptyNode(graph, [n0], 1) - assert err == cuda.CUresult.CUDA_SUCCESS - err, n2 = cuda.cuGraphAddEmptyNode(graph, [n0, n1], 2) - assert err == cuda.CUresult.CUDA_SUCCESS - - err, _, _, _, num_edges = cuda.cuGraphGetEdges(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + n0 = cuda.graph_add_empty_node(graph, 0, 0) + deps1 = (ctypes.c_void_p * 1)(n0) + n1 = cuda.graph_add_empty_node(graph, ctypes.addressof(deps1), 1) + deps2 = (ctypes.c_void_p * 2)(n0, n1) + cuda.graph_add_empty_node(graph, ctypes.addressof(deps2), 2) + + from_nodes, to_nodes, edge_data = cuda.graph_get_edges(graph) + num_edges = len(from_nodes) assert num_edges == 3 - err, from_nodes, to_nodes, edge_data, num_edges = cuda.cuGraphGetEdges(graph, num_edges) - assert err == cuda.CUresult.CUDA_SUCCESS + from_nodes, to_nodes, edge_data = cuda.graph_get_edges(graph) assert len(edge_data) == num_edges == 3 # Stir the heap to make a use-after-free more likely to surface. for _ in range(64): - err, _, _, _, _ = cuda.cuGraphGetEdges(graph, num_edges) - assert err == cuda.CUresult.CUDA_SUCCESS - err, _, _, _ = cuda.cuGraphNodeGetDependencies(n1, 1) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_get_edges(graph) + cuda.graph_node_get_dependencies(n1) # Each wrapper must still own its data. for ed in edge_data: @@ -991,347 +806,239 @@ def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): assert ed.to_port == 0 assert int(ed.type) == 0 finally: - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) def test_cuGraphNodeGetDependencies_edgeData_outlives_call(device, ctx): # Companion regression test for #1804 covering the dependency-query path. - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) try: - err, n0 = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, n1 = cuda.cuGraphAddEmptyNode(graph, [n0], 1) - assert err == cuda.CUresult.CUDA_SUCCESS + n0 = cuda.graph_add_empty_node(graph, 0, 0) + deps1 = (ctypes.c_void_p * 1)(n0) + n1 = cuda.graph_add_empty_node(graph, ctypes.addressof(deps1), 1) - err, _, _, num_deps = cuda.cuGraphNodeGetDependencies(n1) - assert err == cuda.CUresult.CUDA_SUCCESS + deps, edge_data = cuda.graph_node_get_dependencies(n1) + num_deps = len(deps) assert num_deps == 1 - err, deps, edge_data, num_deps = cuda.cuGraphNodeGetDependencies(n1, num_deps) - assert err == cuda.CUresult.CUDA_SUCCESS + deps, edge_data = cuda.graph_node_get_dependencies(n1) assert len(edge_data) == num_deps == 1 - err, _, _, num_dependents = cuda.cuGraphNodeGetDependentNodes(n0) - assert err == cuda.CUresult.CUDA_SUCCESS + dependents, dep_edge_data = cuda.graph_node_get_dependent_nodes(n0) + num_dependents = len(dependents) assert num_dependents == 1 - err, dependents, dep_edge_data, num_dependents = cuda.cuGraphNodeGetDependentNodes(n0, num_dependents) - assert err == cuda.CUresult.CUDA_SUCCESS + dependents, dep_edge_data = cuda.graph_node_get_dependent_nodes(n0) assert len(dep_edge_data) == num_dependents == 1 for _ in range(64): - err, _, _, _ = cuda.cuGraphNodeGetDependencies(n1, num_deps) - assert err == cuda.CUresult.CUDA_SUCCESS - err, _, _, _ = cuda.cuGraphNodeGetDependentNodes(n0, num_dependents) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_node_get_dependencies(n1) + cuda.graph_node_get_dependent_nodes(n0) - for ed in edge_data + dep_edge_data: + for ed in list(edge_data) + list(dep_edge_data): assert ed.from_port == 0 assert ed.to_port == 0 assert int(ed.type) == 0 finally: - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetLocalId"), + driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_local_id"), reason="Requires CUDA 13.1+", ) def test_cuGraphNodeGetLocalId(device, ctx): - """Test cuGraphNodeGetLocalId - get node local ID.""" - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test graph_node_get_local_id - get node local ID.""" + graph = cuda.graph_create(0) # Add multiple nodes - err, node1 = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node1 = cuda.graph_add_empty_node(graph, 0, 0) - err, node2 = cuda.cuGraphAddEmptyNode(graph, [node1], 1) - assert err == cuda.CUresult.CUDA_SUCCESS + deps2 = (ctypes.c_void_p * 1)(node1) + node2 = cuda.graph_add_empty_node(graph, ctypes.addressof(deps2), 1) - err, node3 = cuda.cuGraphAddEmptyNode(graph, [node1, node2], 2) - assert err == cuda.CUresult.CUDA_SUCCESS + deps3 = (ctypes.c_void_p * 2)(node1, node2) + node3 = cuda.graph_add_empty_node(graph, ctypes.addressof(deps3), 2) # Get local IDs for each node - err, node_id1 = cuda.cuGraphNodeGetLocalId(node1) - assert err == cuda.CUresult.CUDA_SUCCESS + node_id1 = cuda.graph_node_get_local_id(node1) assert isinstance(node_id1, int) assert node_id1 >= 0 - err, node_id2 = cuda.cuGraphNodeGetLocalId(node2) - assert err == cuda.CUresult.CUDA_SUCCESS + node_id2 = cuda.graph_node_get_local_id(node2) assert isinstance(node_id2, int) assert node_id2 >= 0 assert node_id2 != node_id1 - err, node_id3 = cuda.cuGraphNodeGetLocalId(node3) - assert err == cuda.CUresult.CUDA_SUCCESS + node_id3 = cuda.graph_node_get_local_id(node3) assert isinstance(node_id3, int) assert node_id3 >= 0 assert node_id3 != node_id1 assert node_id3 != node_id2 - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetToolsId"), + driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_tools_id"), reason="Requires CUDA 13.1+", ) def test_cuGraphNodeGetToolsId(device, ctx): - """Test cuGraphNodeGetToolsId - get node tools ID.""" - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test graph_node_get_tools_id - get node tools ID.""" + graph = cuda.graph_create(0) - err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node = cuda.graph_add_empty_node(graph, 0, 0) - err, tools_node_id = cuda.cuGraphNodeGetToolsId(node) - assert err == cuda.CUresult.CUDA_SUCCESS + tools_node_id = cuda.graph_node_get_tools_id(node) assert isinstance(tools_node_id, int) # toolsNodeId is unsigned long long, so it can be any non-negative value assert tools_node_id >= 0 # Add another node and verify it has a different tools ID - err, node2 = cuda.cuGraphAddEmptyNode(graph, [node], 1) - assert err == cuda.CUresult.CUDA_SUCCESS - err, tools_node_id2 = cuda.cuGraphNodeGetToolsId(node2) - assert err == cuda.CUresult.CUDA_SUCCESS + deps = (ctypes.c_void_p * 1)(node) + node2 = cuda.graph_add_empty_node(graph, ctypes.addressof(deps), 1) + tools_node_id2 = cuda.graph_node_get_tools_id(node2) assert tools_node_id2 != tools_node_id - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuGraphNodeGetContainingGraph"), + driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_containing_graph"), reason="Requires CUDA 13.1+", ) def test_cuGraphNodeGetContainingGraph(device, ctx): - """Test cuGraphNodeGetContainingGraph - get graph containing a node.""" - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test graph_node_get_containing_graph - get graph containing a node.""" + graph = cuda.graph_create(0) - err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node = cuda.graph_add_empty_node(graph, 0, 0) # Get the containing graph - err, containing_graph = cuda.cuGraphNodeGetContainingGraph(node) - assert err == cuda.CUresult.CUDA_SUCCESS + containing_graph = cuda.graph_node_get_containing_graph(node) # Verify it's the same graph assert int(containing_graph) == int(graph) # Test with a child graph node (if supported) # Create a child graph node - err, child_graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, child_node = cuda.cuGraphAddEmptyNode(child_graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + child_graph = cuda.graph_create(0) + child_node = cuda.graph_add_empty_node(child_graph, 0, 0) # Add child graph node to parent graph - childGraphNodeParams = cuda.CUgraphNodeParams() - childGraphNodeParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_GRAPH - childGraphNodeParams.graph.graph = child_graph - err, child_graph_node = cuda.cuGraphAddNode(graph, None, None, 0, childGraphNodeParams) - if err == cuda.CUresult.CUDA_SUCCESS: + node_params = driver.GraphNodeParams() + node_params.type = driver.GraphNodeType.CU_GRAPH + node_params.graph.graph = child_graph + node_params.graph.ownership = int(driver.GraphChildGraphNodeOwnership.CU_GRAPH_CHILD_GRAPH_OWNERSHIP_CLONE) + try: + child_graph_node = cuda.graph_add_node_v2(graph, 0, 0, 0, node_params) + except driver.DriverError: + child_graph_node = None + + if child_graph_node is not None: # Get containing graph for the child graph node - err, containing_graph_for_child = cuda.cuGraphNodeGetContainingGraph(child_graph_node) - assert err == cuda.CUresult.CUDA_SUCCESS + containing_graph_for_child = cuda.graph_node_get_containing_graph(child_graph_node) assert int(containing_graph_for_child) == int(graph) # Get containing graph for node inside child graph - err, containing_graph_for_nested = cuda.cuGraphNodeGetContainingGraph(child_node) - assert err == cuda.CUresult.CUDA_SUCCESS + containing_graph_for_nested = cuda.graph_node_get_containing_graph(child_node) assert int(containing_graph_for_nested) == int(child_graph) - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuGraphDestroy(child_graph) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(graph) + cuda.graph_destroy(child_graph) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuStreamGetDevResource"), + driver_version_less_than(13010) or not supportsCudaAPI("stream_get_dev_resource"), reason="Requires CUDA 13.1+", ) def test_cuStreamGetDevResource(device, ctx): - """Test cuStreamGetDevResource - get device resource from stream.""" - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test stream_get_dev_resource - get device resource from stream.""" + stream = cuda.stream_create(0) # Get SM resource from stream - err, resource = cuda.cuStreamGetDevResource(stream, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) - assert err == cuda.CUresult.CUDA_SUCCESS - # Verify resource is valid (non-None) - assert resource is not None + resource = driver.DevResource_v1() + cuda.stream_get_dev_resource(stream, resource, driver.DevResourceType.CU_SM) + # Verify resource is valid (non-empty) + assert resource.type == int(driver.DevResourceType.CU_SM) - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.stream_destroy_v2(stream) @pytest.mark.skipif( - driver_version_less_than(13010) or not supportsCudaAPI("cuDevSmResourceSplit"), + driver_version_less_than(13010) or not supportsCudaAPI("dev_sm_resource_split"), reason="Requires CUDA 13.1+", ) def test_cuDevSmResourceSplit(device, ctx): - """Test cuDevSmResourceSplit - split SM resource into structured groups.""" - err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) - assert err == cuda.CUresult.CUDA_SUCCESS + """Test dev_sm_resource_split - split SM resource into structured groups.""" + resource_in = driver.DevResource_v1() + cuda.device_get_dev_resource(device, resource_in, driver.DevResourceType.CU_SM) # Test case 1: Split into 1 group nb_groups = 1 - group_params = [cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS()] + group_params = driver._DevSmResourceGroupParams(nb_groups) # Set up group: request 4 SMs with coscheduled count of 2 - group_params[0].smCount = 4 - group_params[0].coscheduledSmCount = 2 - - err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) - assert err == cuda.CUresult.CUDA_SUCCESS - assert len(res) == nb_groups - assert rem is not None or len(res) > 0 + group_params.sm_count = 4 + group_params.coscheduled_sm_count = 2 + + result = driver.DevResource_v1(nb_groups) + remainder = driver.DevResource_v1() + cuda.dev_sm_resource_split( + result, + nb_groups, + resource_in, + remainder, + 0, + group_params, + ) # Test case 2: Split into 2 groups (if device has enough SMs) # First, get the device resource again for a fresh split - err, resource_in = cuda.cuDeviceGetDevResource(device, cuda.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM) - assert err == cuda.CUresult.CUDA_SUCCESS + resource_in = driver.DevResource_v1() + cuda.device_get_dev_resource(device, resource_in, driver.DevResourceType.CU_SM) nb_groups = 2 - group_params = [ - cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), - cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), - ] - # First group: request 4 SMs with coscheduled count of 2 - group_params[0].smCount = 4 - group_params[0].coscheduledSmCount = 2 - # Second group: request 4 SMs with coscheduled count of 2 - group_params[1].smCount = 4 - group_params[1].coscheduledSmCount = 2 - - err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) - # This may succeed or fail depending on device SM count, but should handle gracefully - if err == cuda.CUresult.CUDA_SUCCESS: - assert len(res) == nb_groups - assert rem is not None or len(res) > 0 - else: - # If it fails, it should be due to insufficient resources, not a binding error - assert err in ( - cuda.CUresult.CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION, - cuda.CUresult.CUDA_ERROR_INVALID_VALUE, + group_params = driver._DevSmResourceGroupParams(nb_groups) + group_params.sm_count = [4, 4] + group_params.coscheduled_sm_count = [2, 2] + + result = driver.DevResource_v1(nb_groups) + remainder = driver.DevResource_v1() + with contextlib.suppress(driver.InvalidResourceConfigurationError, driver.InvalidValueError): + cuda.dev_sm_resource_split( + result, + nb_groups, + resource_in, + remainder, + 0, + group_params, ) # Test case 3: Empty list (0 groups) - should handle gracefully - # Note: According to CUDA docs, nbGroups specifies number of groups, so 0 might not be valid - # But we test that the binding accepts an empty list without crashing nb_groups = 0 - group_params = [] - - err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) - # With 0 groups, result should be empty - if err == cuda.CUresult.CUDA_SUCCESS: - assert len(res) == 0 - else: - # If it fails, it should be a valid CUDA error, not a Python binding error - assert err in ( - cuda.CUresult.CUDA_ERROR_INVALID_VALUE, - cuda.CUresult.CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION, + group_params_empty = driver._DevSmResourceGroupParams(1) # unused, but keep a valid pointer + remainder = driver.DevResource_v1() + with contextlib.suppress(driver.InvalidResourceConfigurationError, driver.InvalidValueError): + cuda.dev_sm_resource_split( + 0, + nb_groups, + resource_in, + remainder, + 0, + group_params_empty, ) -def test_buffer_reference(): - # Create a host buffer - size = int(1024 * np.uint8().itemsize) - host = np.full(size, 2).astype(np.uint8) - - # Set the buffer to a struct member - memcpyParams = cuda.CUgraphNodeParams() - memcpyParams.memcpy.copyParams.dstHost = host - - # Delete the local reference to the host buffer. The reference in the - # struct should keep it alive. - del host - - # Create a new numpy array from the pointer and make sure the memory is - # intact and hasn't been freed. If the reference counting in - # copyParams.dstHost is incorrect, we will either see over-written memory or - # a segmentation fault here. - ptr = ctypes.cast(memcpyParams.memcpy.copyParams.dstHost, ctypes.POINTER(ctypes.c_uint8)) - x = np.ctypeslib.as_array(ptr, shape=(size,)) - assert np.all(x == 2) - - -def test_array_setter_no_double_free_after_clearing_with_empty_list(): - # Regression test for a double-free in the generated setters for - # list-valued struct members (e.g. CUlaunchConfig.attrs, - # CUDA_MEM_ALLOC_NODE_PARAMS.accessDescs, ...). Assigning an empty list - # used to free the internal buffer but leave the cached pointer non-NULL; - # the next assignment (or __dealloc__) would call free() on that dangling - # pointer, causing a double-free that glibc aborts via SIGABRT. - # - # CUlaunchConfig.attrs is exercised here as one representative instance; - # the same pattern was applied across many setters in driver.pyx.in and - # runtime.pyx.in. - # - # The reproducer runs in a subprocess so that a glibc abort surfaces as - # a non-zero return code instead of tearing down the pytest process. - code = textwrap.dedent( - """ - import cuda.bindings.driver as cuda - - params = cuda.CUlaunchConfig() - # Allocate the internal buffer. - params.attrs = [cuda.CUlaunchAttribute() for _ in range(4)] - # Free it. Pre-fix, self._attrs is left pointing at freed memory. - params.attrs = [] - # Length mismatch (0 vs 8) takes the else branch and calls free() - # again on the dangling pointer. - params.attrs = [cuda.CUlaunchAttribute() for _ in range(8)] - """ - ) - proc = subprocess.run([sys.executable, "-c", code], capture_output=True, cwd=os.path.dirname(__file__)) # noqa: S603 - assert proc.returncode == 0, ( - f"reproducer subprocess exited with code {proc.returncode}; stderr: {proc.stderr.decode(errors='replace')}" - ) +# NOTE: test_buffer_reference is intentionally not ported. It verified that +# assigning a numpy array to a struct's host-pointer field kept that array +# alive via reference counting internal to the legacy driver.pyx.in generated +# setter. _v2.driver's Memcpy3d_v2.dst_host setter takes a raw integer +# address instead (see the `dst_host = host.ctypes.data` pattern used in +# test_graph_poly) and keeps no reference at all, so the premise of this test +# (that the wrapper keeps the buffer alive) does not hold for the new API. -def test_dealloc_clears_array_field_in_external_struct(): - # Regression test for the externally-owned-memory case of the same bug. - # - # When a wrapper aliases an externally-owned struct (constructed with - # `_ptr=...`), `__dealloc__` used to free its internal buffer but leave - # `self._pvt_ptr[0].` pointing at the freed memory. Anyone still - # holding the external struct (the owning wrapper, a parent struct, or - # the CUDA driver itself) would see a dangling pointer. - # - # CUlaunchConfig.attrs is exercised here as one representative instance; - # the same pattern was applied across the `__dealloc__` methods in - # driver.pyx.in and runtime.pyx.in. - outer = cuda.CUlaunchConfig() - # `inner` aliases the same underlying struct as `outer`. - inner = cuda.CUlaunchConfig(_ptr=outer.getPtr()) - # Allocates a buffer and writes its pointer into the shared struct's - # `attrs` field. - inner.attrs = [cuda.CUlaunchAttribute() for _ in range(4)] - - # Locate `attrs` in the C struct by scanning for the just-written - # pointer. The struct is small and only `attrs` is non-NULL. - struct_addr = outer.getPtr() - word_size = ctypes.sizeof(ctypes.c_void_p) - scan_words = 128 // word_size - words = (ctypes.c_void_p * scan_words).from_address(struct_addr) - attrs_offset = next( - (i * word_size for i, p in enumerate(words) if p), - None, - ) - assert attrs_offset is not None, "attrs pointer was not written into the C struct" - - # Destroy the wrapper. With the fix, __dealloc__ also clears the field - # in the externally-owned struct; without it, the field remains dangling. - del inner - - attrs_after = ctypes.c_void_p.from_address(struct_addr + attrs_offset).value - assert attrs_after is None, ( - f"external struct still holds a dangling pointer ({attrs_after:#x}) " - "where attrs was, after the aliasing wrapper was destroyed" - ) +# NOTE: test_array_setter_no_double_free_after_clearing_with_empty_list and +# test_dealloc_clears_array_field_in_external_struct are intentionally not +# ported. They were regression tests for a double-free bug in the legacy +# driver.pyx.in / runtime.pyx.in generated setters for list-valued struct +# members (which allocated and freed a backing buffer on assignment). +# _v2.driver's LaunchConfig.attrs is a plain raw-pointer property (no +# allocation/ownership machinery at all), so that class of bug cannot occur +# and there is nothing equivalent to regression-test. diff --git a/cuda_bindings/tests/test_cudart.py b/cuda_bindings/tests/test_cudart.py index 3dc4fba7461..8b8a991786b 100644 --- a/cuda_bindings/tests/test_cudart.py +++ b/cuda_bindings/tests/test_cudart.py @@ -8,6 +8,9 @@ import pytest from cuda_python_test_helpers.mempool import xfail_if_mempool_oom +# Kept on the legacy driver API: its only use is constructing a +# cuuint64_t POD value for cudaMemPoolSetAttribute, and cuda.bindings._v2.driver +# does not expose an equivalent wrapper type. import cuda.bindings.driver as cuda import cuda.bindings.runtime as cudart from cuda import pathfinder diff --git a/cuda_bindings/tests/test_cufile.py b/cuda_bindings/tests/test_cufile.py index 46bd8429a62..2b5f24ec6fd 100644 --- a/cuda_bindings/tests/test_cufile.py +++ b/cuda_bindings/tests/test_cufile.py @@ -13,7 +13,7 @@ import pytest -import cuda.bindings.driver as cuda +import cuda.bindings._v2.driver as cuda cufile = pytest.importorskip("cuda.bindings.cufile") @@ -126,21 +126,17 @@ def test_cufile_success_defined(): @pytest.fixture def ctx(): # Initialize CUDA - (err,) = cuda.cuInit(0) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.init(0) - err, device = cuda.cuDeviceGet(0) - assert err == cuda.CUresult.CUDA_SUCCESS + device = cuda.device_get(0) - err, ctx = cuda.cuDevicePrimaryCtxRetain(device) - assert err == cuda.CUresult.CUDA_SUCCESS + ctx = cuda.device_primary_ctx_retain(device) - (err,) = cuda.cuCtxSetCurrent(ctx) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.ctx_set_current(ctx) yield - cuda.cuDevicePrimaryCtxRelease(device) + cuda.device_primary_ctx_release_v2(device) @pytest.fixture(scope="module", autouse=True) @@ -173,19 +169,15 @@ def _cufile_driver_prewarm(): it is forced by the libcufile API — parameter-set tests cannot coexist with a session-wide open driver. """ - (err,) = cuda.cuInit(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, device = cuda.cuDeviceGet(0) - assert err == cuda.CUresult.CUDA_SUCCESS - err, dctx = cuda.cuDevicePrimaryCtxRetain(device) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuCtxSetCurrent(dctx) - assert err == cuda.CUresult.CUDA_SUCCESS + cuda.init(0) + device = cuda.device_get(0) + dctx = cuda.device_primary_ctx_retain(device) + cuda.ctx_set_current(dctx) try: cufile.driver_open() cufile.driver_close() finally: - cuda.cuDevicePrimaryCtxRelease(device) + cuda.device_primary_ctx_release_v2(device) @pytest.fixture @@ -227,7 +219,7 @@ def test_handle_register(tmpdir): descr.fs_ops = 0 # Register the handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Deregister the handle cufile.handle_deregister(handle) @@ -241,8 +233,7 @@ def test_buf_register_simple(): """Simple test for buffer registration with cuFile.""" # Allocate CUDA memory buffer_size = 4096 # 4KB, aligned to 4096 bytes - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) try: # Register the buffer with cuFile @@ -255,7 +246,7 @@ def test_buf_register_simple(): finally: # Free CUDA memory - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) @pytest.mark.usefixtures("driver") @@ -263,8 +254,7 @@ def test_buf_register_host_memory(): """Test buffer registration with host memory.""" # Allocate host memory buffer_size = 4096 # 4KB, aligned to 4096 bytes - err, buf_ptr = cuda.cuMemHostAlloc(buffer_size, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_host_alloc(buffer_size, 0) try: # Register the host buffer with cuFile @@ -277,7 +267,7 @@ def test_buf_register_host_memory(): finally: # Free host memory - cuda.cuMemFreeHost(buf_ptr) + cuda.mem_free_host(buf_ptr) @pytest.mark.usefixtures("driver") @@ -288,8 +278,7 @@ def test_buf_register_multiple_buffers(): buffers = [] for size in buffer_sizes: - err, buf_ptr = cuda.cuMemAlloc(size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(size) buffers.append(buf_ptr) try: @@ -307,7 +296,7 @@ def test_buf_register_multiple_buffers(): finally: # Free all buffers for buf_ptr in buffers: - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) @pytest.mark.usefixtures("driver") @@ -315,8 +304,7 @@ def test_buf_register_invalid_flags(): """Test buffer registration with invalid flags.""" # Allocate CUDA memory buffer_size = 65536 - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) try: # Try to register with invalid flags @@ -330,7 +318,7 @@ def test_buf_register_invalid_flags(): finally: # Free CUDA memory - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) @pytest.mark.usefixtures("driver") @@ -338,8 +326,7 @@ def test_buf_register_large_buffer(): """Test buffer registration with a large buffer.""" # Allocate large CUDA memory (1MB, aligned to 4096 bytes) buffer_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0) - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) try: # Register the large buffer with cuFile @@ -352,7 +339,7 @@ def test_buf_register_large_buffer(): finally: # Free CUDA memory - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) @pytest.mark.usefixtures("driver") @@ -360,8 +347,7 @@ def test_buf_register_already_registered(): """Test that registering an already registered buffer fails.""" # Allocate CUDA memory buffer_size = 4096 # 4KB, aligned to 4096 bytes - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) try: # Register the buffer first time @@ -382,7 +368,7 @@ def test_buf_register_already_registered(): finally: # Free CUDA memory - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -394,11 +380,9 @@ def test_cufile_read_write(tmpdir): # Allocate CUDA memory for write and read write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) - err, write_buf = cuda.cuMemAlloc(write_size) - assert err == cuda.CUresult.CUDA_SUCCESS + write_buf = cuda.mem_alloc_v2(write_size) - err, read_buf = cuda.cuMemAlloc(write_size) - assert err == cuda.CUresult.CUDA_SUCCESS + read_buf = cuda.mem_alloc_v2(write_size) # Allocate host memory for data verification host_buf = ctypes.create_string_buffer(write_size) @@ -421,7 +405,7 @@ def test_cufile_read_write(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Prepare test data test_string = b"Hello cuFile! This is test data for read/write operations. " @@ -432,8 +416,8 @@ def test_cufile_read_write(tmpdir): host_buf = ctypes.create_string_buffer(test_data, write_size) # Copy test data to CUDA write buffer - cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(write_buf, host_buf, write_size, 0) + cuda.stream_synchronize(0) # Write data using cuFile bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0) @@ -447,8 +431,8 @@ def test_cufile_read_write(tmpdir): assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})" # Copy read data back to host - cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, read_buf, write_size, 0) + cuda.stream_synchronize(0) # Verify the data read_data = host_buf.value @@ -465,8 +449,8 @@ def test_cufile_read_write(tmpdir): # Close file os.close(fd) # Free CUDA memory - cuda.cuMemFree(write_buf) - cuda.cuMemFree(read_buf) + cuda.mem_free_v2(write_buf) + cuda.mem_free_v2(read_buf) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -478,11 +462,9 @@ def test_cufile_read_write_host_memory(tmpdir): # Allocate host memory for write and read write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) - err, write_buf = cuda.cuMemHostAlloc(write_size, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + write_buf = cuda.mem_host_alloc(write_size, 0) - err, read_buf = cuda.cuMemHostAlloc(write_size, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + read_buf = cuda.mem_host_alloc(write_size, 0) try: # Create file with O_DIRECT @@ -502,7 +484,7 @@ def test_cufile_read_write_host_memory(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Prepare test data test_string = b"Host memory test data for cuFile operations! " @@ -545,8 +527,8 @@ def test_cufile_read_write_host_memory(tmpdir): # Close file os.close(fd) # Free host memory - cuda.cuMemFreeHost(write_buf) - cuda.cuMemFreeHost(read_buf) + cuda.mem_free_host(write_buf) + cuda.mem_free_host(read_buf) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -558,11 +540,9 @@ def test_cufile_read_write_large(tmpdir): # Allocate large CUDA memory (1MB, aligned to 4096 bytes) write_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0) - err, write_buf = cuda.cuMemAlloc(write_size) - assert err == cuda.CUresult.CUDA_SUCCESS + write_buf = cuda.mem_alloc_v2(write_size) - err, read_buf = cuda.cuMemAlloc(write_size) - assert err == cuda.CUresult.CUDA_SUCCESS + read_buf = cuda.mem_alloc_v2(write_size) # Allocate host memory for data verification host_buf = ctypes.create_string_buffer(write_size) @@ -585,7 +565,7 @@ def test_cufile_read_write_large(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Generate large test data import random @@ -594,12 +574,12 @@ def test_cufile_read_write_large(tmpdir): host_buf = ctypes.create_string_buffer(test_data, write_size) # Copy test data to CUDA write buffer - cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(write_buf, host_buf, write_size, 0) + cuda.stream_synchronize(0) # Get the actual data that was written to CUDA buffer - cuda.cuMemcpyDtoHAsync(host_buf, write_buf, write_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, write_buf, write_size, 0) + cuda.stream_synchronize(0) expected_data = host_buf.value # Write data using cuFile @@ -614,8 +594,8 @@ def test_cufile_read_write_large(tmpdir): assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})" # Copy read data back to host - cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, read_buf, write_size, 0) + cuda.stream_synchronize(0) # Verify the data read_data = host_buf.value @@ -632,8 +612,8 @@ def test_cufile_read_write_large(tmpdir): # Close file os.close(fd) # Free CUDA memory - cuda.cuMemFree(write_buf) - cuda.cuMemFree(read_buf) + cuda.mem_free_v2(write_buf) + cuda.mem_free_v2(read_buf) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -650,17 +630,15 @@ def test_cufile_write_async(tmpdir): descr.type = cufile.FileHandleType.OPAQUE_FD descr.handle.fd = fd descr.fs_ops = 0 - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate and register device buffer buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) - err, buf_ptr = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buf_size) cufile.buf_register(int(buf_ptr), buf_size, 0) # Create CUDA stream - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + stream = cuda.stream_create(0) # Register stream with cuFile cufile.stream_register(int(stream), 0) @@ -672,8 +650,8 @@ def test_cufile_write_async(tmpdir): test_data = test_string * repetitions test_data = test_data[:buf_size] # Ensure it fits exactly in buffer host_buf = ctypes.create_string_buffer(test_data, buf_size) - cuda.cuMemcpyHtoDAsync(buf_ptr, host_buf, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(buf_ptr, host_buf, buf_size, 0) + cuda.stream_synchronize(0) # Create parameter arrays for async write size_p = ctypes.c_size_t(buf_size) @@ -693,7 +671,7 @@ def test_cufile_write_async(tmpdir): ) # Synchronize stream to wait for completion - cuda.cuStreamSynchronize(stream) + cuda.stream_synchronize(stream) # Verify bytes written assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}" @@ -704,8 +682,8 @@ def test_cufile_write_async(tmpdir): # Deregister and cleanup cufile.buf_deregister(int(buf_ptr)) cufile.handle_deregister(handle) - cuda.cuStreamDestroy(stream) - cuda.cuMemFree(buf_ptr) + cuda.stream_destroy_v2(stream) + cuda.mem_free_v2(buf_ptr) finally: os.close(fd) @@ -740,17 +718,15 @@ def test_cufile_read_async(tmpdir): descr.type = cufile.FileHandleType.OPAQUE_FD descr.handle.fd = fd descr.fs_ops = 0 - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate and register device buffer buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) - err, buf_ptr = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buf_size) cufile.buf_register(int(buf_ptr), buf_size, 0) # Create CUDA stream - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + stream = cuda.stream_create(0) # Register stream with cuFile cufile.stream_register(int(stream), 0) @@ -773,15 +749,15 @@ def test_cufile_read_async(tmpdir): ) # Synchronize stream to wait for completion - cuda.cuStreamSynchronize(stream) + cuda.stream_synchronize(stream) # Verify bytes read assert bytes_read_p.value > 0, f"Expected bytes read, got {bytes_read_p.value}" # Copy read data back to host and verify host_buf = ctypes.create_string_buffer(buf_size) - cuda.cuMemcpyDtoHAsync(host_buf, buf_ptr, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, buf_ptr, buf_size, 0) + cuda.stream_synchronize(0) read_data = host_buf.value[: bytes_read_p.value] expected_data = test_data[: bytes_read_p.value] assert read_data == expected_data, "Read data doesn't match written data" @@ -792,8 +768,8 @@ def test_cufile_read_async(tmpdir): # Deregister and cleanup cufile.buf_deregister(int(buf_ptr)) cufile.handle_deregister(handle) - cuda.cuStreamDestroy(stream) - cuda.cuMemFree(buf_ptr) + cuda.stream_destroy_v2(stream) + cuda.mem_free_v2(buf_ptr) finally: os.close(fd) @@ -813,21 +789,18 @@ def test_cufile_async_read_write(tmpdir): descr.type = cufile.FileHandleType.OPAQUE_FD descr.handle.fd = fd descr.fs_ops = 0 - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate and register device buffers buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0) - err, write_buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + write_buf = cuda.mem_alloc_v2(buf_size) cufile.buf_register(int(write_buf), buf_size, 0) - err, read_buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + read_buf = cuda.mem_alloc_v2(buf_size) cufile.buf_register(int(read_buf), buf_size, 0) # Create CUDA stream - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + stream = cuda.stream_create(0) # Register stream with cuFile cufile.stream_register(int(stream), 0) @@ -839,8 +812,8 @@ def test_cufile_async_read_write(tmpdir): test_data = test_string * repetitions test_data = test_data[:buf_size] # Ensure it fits exactly in buffer host_buf = ctypes.create_string_buffer(test_data, buf_size) - cuda.cuMemcpyHtoDAsync(write_buf, host_buf, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(write_buf, host_buf, buf_size, 0) + cuda.stream_synchronize(0) # Create parameter arrays for async write write_size_p = ctypes.c_size_t(buf_size) @@ -860,7 +833,7 @@ def test_cufile_async_read_write(tmpdir): ) # Synchronize stream to wait for write completion - cuda.cuStreamSynchronize(stream) + cuda.stream_synchronize(stream) # Verify bytes written assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}" @@ -883,15 +856,15 @@ def test_cufile_async_read_write(tmpdir): ) # Synchronize stream to wait for read completion - cuda.cuStreamSynchronize(stream) + cuda.stream_synchronize(stream) # Verify bytes read assert bytes_read_p.value == buf_size, f"Expected {buf_size} bytes read, got {bytes_read_p.value}" # Copy read data back to host and verify host_buf = ctypes.create_string_buffer(buf_size) - cuda.cuMemcpyDtoHAsync(host_buf, read_buf, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, read_buf, buf_size, 0) + cuda.stream_synchronize(0) read_data = host_buf.value assert read_data == test_data, "Read data doesn't match written data" @@ -902,9 +875,9 @@ def test_cufile_async_read_write(tmpdir): cufile.buf_deregister(int(write_buf)) cufile.buf_deregister(int(read_buf)) cufile.handle_deregister(handle) - cuda.cuStreamDestroy(stream) - cuda.cuMemFree(write_buf) - cuda.cuMemFree(read_buf) + cuda.stream_destroy_v2(stream) + cuda.mem_free_v2(write_buf) + cuda.mem_free_v2(read_buf) finally: os.close(fd) @@ -925,8 +898,7 @@ def test_batch_io_basic(tmpdir): read_buffers = [] # Initialize read_buffers to avoid UnboundLocalError for i in range(num_operations): - err, buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = cuda.mem_alloc_v2(buf_size) buffers.append(buf) # Allocate host memory for data verification @@ -948,7 +920,7 @@ def test_batch_io_basic(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Set up batch IO batch_handle = cufile.batch_io_set_up(num_operations) @@ -976,8 +948,8 @@ def test_batch_io_basic(tmpdir): host_buf = ctypes.create_string_buffer(test_data, buf_size) # Copy test data to CUDA buffer - cuda.cuMemcpyHtoDAsync(buffers[i], host_buf, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(buffers[i], host_buf, buf_size, 0) + cuda.stream_synchronize(0) # Set up IOParams for this operation io_params[i].mode = cufile.BatchMode.BATCH # Batch mode @@ -990,7 +962,7 @@ def test_batch_io_basic(tmpdir): io_params[i].u.batch.size_ = buf_size # Submit batch write operations - cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + cufile.batch_io_submit(batch_handle, num_operations, io_params, 0) # Get batch status min_nr = num_operations # Wait for all operations to complete @@ -998,7 +970,7 @@ def test_batch_io_basic(tmpdir): timeout = ctypes.c_int(5000) # 5 second timeout cufile.batch_io_get_status( - batch_handle, min_nr, ctypes.addressof(nr_completed), io_events.ptr, ctypes.addressof(timeout) + batch_handle, min_nr, ctypes.addressof(nr_completed), io_events, ctypes.addressof(timeout) ) # Verify all operations completed successfully @@ -1022,8 +994,7 @@ def test_batch_io_basic(tmpdir): # Now test batch read operations read_buffers = [] for i in range(num_operations): - err, buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = cuda.mem_alloc_v2(buf_size) read_buffers.append(buf) buf_int = int(buf) cufile.buf_register(buf_int, buf_size, 0) @@ -1043,11 +1014,11 @@ def test_batch_io_basic(tmpdir): io_params[i].u.batch.size_ = buf_size # Submit batch read operations - cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + cufile.batch_io_submit(batch_handle, num_operations, io_params, 0) # Get batch status for reads cufile.batch_io_get_status( - batch_handle, min_nr, ctypes.addressof(nr_completed), io_events_read.ptr, ctypes.addressof(timeout) + batch_handle, min_nr, ctypes.addressof(nr_completed), io_events_read, ctypes.addressof(timeout) ) # Verify read operations completed successfully @@ -1075,8 +1046,8 @@ def test_batch_io_basic(tmpdir): # Verify the read data matches the written data for i in range(num_operations): # Copy read data back to host - cuda.cuMemcpyDtoHAsync(host_buf, read_buffers[i], buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, read_buffers[i], buf_size, 0) + cuda.stream_synchronize(0) read_data = host_buf.value # Prepare expected data @@ -1103,7 +1074,7 @@ def test_batch_io_basic(tmpdir): os.close(fd) # Free CUDA memory for buf in buffers + read_buffers: - cuda.cuMemFree(buf) + cuda.mem_free_v2(buf) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -1119,8 +1090,7 @@ def test_batch_io_cancel(tmpdir): buffers = [] for i in range(num_operations): - err, buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = cuda.mem_alloc_v2(buf_size) buffers.append(buf) try: @@ -1139,7 +1109,7 @@ def test_batch_io_cancel(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Set up batch IO batch_handle = cufile.batch_io_set_up(num_operations) @@ -1159,7 +1129,7 @@ def test_batch_io_cancel(tmpdir): io_params[i].u.batch.size_ = buf_size # Submit batch operations - cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + cufile.batch_io_submit(batch_handle, num_operations, io_params, 0) # Cancel the batch operations cufile.batch_io_cancel(batch_handle) @@ -1180,7 +1150,7 @@ def test_batch_io_cancel(tmpdir): os.close(fd) # Free CUDA memory for buf in buffers: - cuda.cuMemFree(buf) + cuda.mem_free_v2(buf) @pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem") @@ -1199,12 +1169,10 @@ def test_batch_io_large_operations(tmpdir): all_buffers = [] # Initialize all_buffers to avoid UnboundLocalError for i in range(num_operations): - err, buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = cuda.mem_alloc_v2(buf_size) write_buffers.append(buf) - err, buf = cuda.cuMemAlloc(buf_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = cuda.mem_alloc_v2(buf_size) read_buffers.append(buf) # Allocate host memory for data verification @@ -1227,7 +1195,7 @@ def test_batch_io_large_operations(tmpdir): descr.fs_ops = 0 # Register file handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Set up batch IO batch_handle = cufile.batch_io_set_up(num_operations) # Only for writes @@ -1250,8 +1218,8 @@ def test_batch_io_large_operations(tmpdir): test_data = test_string * repetitions test_data = test_data[:buf_size] host_buf = ctypes.create_string_buffer(test_data, buf_size) - cuda.cuMemcpyHtoDAsync(write_buffers[i], host_buf, buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_htod_async_v2(write_buffers[i], host_buf, buf_size, 0) + cuda.stream_synchronize(0) # Set up write operations for i in range(num_operations): @@ -1265,7 +1233,7 @@ def test_batch_io_large_operations(tmpdir): io_params[i].u.batch.size_ = buf_size # Submit writes - cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0) + cufile.batch_io_submit(batch_handle, num_operations, io_params, 0) # Wait for writes to complete nr_completed_writes = ctypes.c_uint(num_operations) @@ -1274,7 +1242,7 @@ def test_batch_io_large_operations(tmpdir): batch_handle, num_operations, ctypes.addressof(nr_completed_writes), - io_events.ptr, + io_events, ctypes.addressof(timeout), ) @@ -1298,7 +1266,7 @@ def test_batch_io_large_operations(tmpdir): read_io_params[i].u.batch.size_ = buf_size # Submit reads - cufile.batch_io_submit(read_batch_handle, num_operations, read_io_params.ptr, 0) + cufile.batch_io_submit(read_batch_handle, num_operations, read_io_params, 0) # Wait for reads nr_completed = ctypes.c_uint(num_operations) @@ -1306,7 +1274,7 @@ def test_batch_io_large_operations(tmpdir): read_batch_handle, num_operations, ctypes.addressof(nr_completed), - read_io_events.ptr, + read_io_events, ctypes.addressof(timeout), ) @@ -1330,8 +1298,8 @@ def test_batch_io_large_operations(tmpdir): # Verify the read data matches the written data for i in range(num_operations): # Copy read data back to host - cuda.cuMemcpyDtoHAsync(host_buf, read_buffers[i], buf_size, 0) - cuda.cuStreamSynchronize(0) + cuda.memcpy_dtoh_async_v2(host_buf, read_buffers[i], buf_size, 0) + cuda.stream_synchronize(0) read_data = host_buf.value # Prepare expected data @@ -1365,7 +1333,7 @@ def test_batch_io_large_operations(tmpdir): os.close(fd) # Free CUDA memory for buf in all_buffers: - cuda.cuMemFree(buf) + cuda.mem_free_v2(buf) @pytest.mark.skipif( @@ -1606,12 +1574,11 @@ def test_get_stats_l1(tmpdir): descr.fs_ops = 0 # Register the handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate CUDA memory buffer_size = 4096 # 4KB, aligned to 4096 bytes - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) # Register the buffer with cuFile buf_ptr_int = int(buf_ptr) @@ -1621,7 +1588,7 @@ def test_get_stats_l1(tmpdir): test_data = b"cuFile L1 stats test data" * 100 # Fill buffer test_data = test_data[:buffer_size] host_buf = ctypes.create_string_buffer(test_data, buffer_size) - cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + cuda.memcpy_htod_v2(buf_ptr, host_buf, len(test_data)) # Perform cuFile operations to generate L1 statistics cufile.write(handle, buf_ptr_int, buffer_size, 0, 0) @@ -1631,7 +1598,7 @@ def test_get_stats_l1(tmpdir): stats = cufile.StatsLevel1() # Get L1 statistics (basic operation counts) - cufile.get_stats_l1(stats.ptr) + cufile.get_stats_l1(stats) # Verify actual field values using OpCounter class for cleaner access read_ops = cufile.OpCounter.from_data(stats.read_ops) @@ -1654,7 +1621,7 @@ def test_get_stats_l1(tmpdir): # Clean up cuFile resources cufile.buf_deregister(buf_ptr_int) cufile.handle_deregister(handle) - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) finally: os.close(fd) @@ -1685,12 +1652,11 @@ def test_get_stats_l2(tmpdir): descr.fs_ops = 0 # Register the handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate CUDA memory buffer_size = 8192 # 8KB for more detailed stats - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) # Register the buffer with cuFile buf_ptr_int = int(buf_ptr) @@ -1700,7 +1666,7 @@ def test_get_stats_l2(tmpdir): test_data = b"cuFile L2 detailed stats test data" * 150 # Fill buffer test_data = test_data[:buffer_size] host_buf = ctypes.create_string_buffer(test_data, buffer_size) - cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + cuda.memcpy_htod_v2(buf_ptr, host_buf, len(test_data)) # Perform multiple cuFile operations to generate detailed L2 statistics cufile.write(handle, buf_ptr_int, buffer_size, 0, 0) @@ -1712,7 +1678,7 @@ def test_get_stats_l2(tmpdir): stats = cufile.StatsLevel2() # Get L2 statistics (detailed performance metrics) - cufile.get_stats_l2(stats.ptr) + cufile.get_stats_l2(stats) # Verify L2 histogram fields contain data # Access numpy array fields: histograms are numpy arrays @@ -1736,7 +1702,7 @@ def test_get_stats_l2(tmpdir): # Clean up cuFile resources cufile.buf_deregister(buf_ptr_int) cufile.handle_deregister(handle) - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) finally: os.close(fd) @@ -1767,12 +1733,11 @@ def test_get_stats_l3(tmpdir): descr.fs_ops = 0 # Register the handle - handle = cufile.handle_register(descr.ptr) + handle = cufile.handle_register(descr) # Allocate CUDA memory buffer_size = 16384 # 16KB for comprehensive stats testing - err, buf_ptr = cuda.cuMemAlloc(buffer_size) - assert err == cuda.CUresult.CUDA_SUCCESS + buf_ptr = cuda.mem_alloc_v2(buffer_size) # Register the buffer with cuFile buf_ptr_int = int(buf_ptr) @@ -1782,7 +1747,7 @@ def test_get_stats_l3(tmpdir): test_data = b"cuFile L3 comprehensive stats test data" * 200 # Fill buffer test_data = test_data[:buffer_size] host_buf = ctypes.create_string_buffer(test_data, buffer_size) - cuda.cuMemcpyHtoD(buf_ptr, host_buf, len(test_data)) + cuda.memcpy_htod_v2(buf_ptr, host_buf, len(test_data)) # Perform comprehensive cuFile operations to generate L3 statistics # Multiple writes and reads at different offsets to generate rich stats @@ -1797,7 +1762,7 @@ def test_get_stats_l3(tmpdir): stats = cufile.StatsLevel3() # Get L3 statistics (comprehensive diagnostic data) - cufile.get_stats_l3(stats.ptr) + cufile.get_stats_l3(stats) # Verify L3-specific fields num_gpus = int(stats.num_gpus) @@ -1828,7 +1793,7 @@ def test_get_stats_l3(tmpdir): # Clean up cuFile resources cufile.buf_deregister(buf_ptr_int) cufile.handle_deregister(handle) - cuda.cuMemFree(buf_ptr) + cuda.mem_free_v2(buf_ptr) finally: os.close(fd) diff --git a/cuda_bindings/tests/test_interoperability.py b/cuda_bindings/tests/test_interoperability.py index 08bac311a2d..24265c55ca9 100644 --- a/cuda_bindings/tests/test_interoperability.py +++ b/cuda_bindings/tests/test_interoperability.py @@ -5,7 +5,7 @@ import pytest from cuda_python_test_helpers.mempool import xfail_if_mempool_oom -import cuda.bindings.driver as cuda +import cuda.bindings._v2.driver as cuda import cuda.bindings.runtime as cudart @@ -16,61 +16,52 @@ def supportsMemoryPool(): def test_interop_stream(): # DRV to RT - err_dr, stream = cuda.cuStreamCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + stream = cuda.stream_create(0) (err_rt,) = cudart.cudaStreamDestroy(stream) assert err_rt == cudart.cudaError_t.cudaSuccess # RT to DRV err_rt, stream = cudart.cudaStreamCreate() assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuStreamDestroy(stream) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.stream_destroy_v2(int(stream)) def test_interop_event(): # DRV to RT - err_dr, event = cuda.cuEventCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + event = cuda.event_create(0) (err_rt,) = cudart.cudaEventDestroy(event) assert err_rt == cudart.cudaError_t.cudaSuccess # RT to DRV err_rt, event = cudart.cudaEventCreate() assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuEventDestroy(event) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.event_destroy_v2(int(event)) def test_interop_graph(): # DRV to RT - err_dr, graph = cuda.cuGraphCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) (err_rt,) = cudart.cudaGraphDestroy(graph) assert err_rt == cudart.cudaError_t.cudaSuccess # RT to DRV err_rt, graph = cudart.cudaGraphCreate(0) assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuGraphDestroy(graph) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy(int(graph)) def test_interop_graphNode(): - err_dr, graph = cuda.cuGraphCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) # DRV to RT - err_dr, node = cuda.cuGraphAddEmptyNode(graph, [], 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + node = cuda.graph_add_empty_node(graph, 0, 0) (err_rt,) = cudart.cudaGraphDestroyNode(node) assert err_rt == cudart.cudaError_t.cudaSuccess # RT to DRV err_rt, node = cudart.cudaGraphAddEmptyNode(graph, [], 0) assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuGraphDestroyNode(node) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.graph_destroy_node(int(node)) (err_rt,) = cudart.cudaGraphDestroy(graph) assert err_rt == cudart.cudaError_t.cudaSuccess @@ -87,9 +78,11 @@ def test_interop_graphNode(): @pytest.mark.skipif(not supportsMemoryPool(), reason="Requires mempool operations") def test_interop_memPool(): # DRV to RT - err_dr, pool = cuda.cuDeviceGetDefaultMemPool(0) - xfail_if_mempool_oom(err_dr, "cuDeviceGetDefaultMemPool", 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + try: + pool = cuda.device_get_default_mem_pool(0) + except cuda.DriverError as e: + xfail_if_mempool_oom(e, "device_get_default_mem_pool", 0) + raise (err_rt,) = cudart.cudaDeviceSetMemPool(0, pool) assert err_rt == cudart.cudaError_t.cudaSuccess @@ -97,27 +90,22 @@ def test_interop_memPool(): err_rt, pool = cudart.cudaDeviceGetDefaultMemPool(0) xfail_if_mempool_oom(err_rt, "cudaDeviceGetDefaultMemPool", 0) assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuDeviceSetMemPool(0, pool) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.device_set_mem_pool(0, int(pool)) def test_interop_graphExec(): - err_dr, graph = cuda.cuGraphCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS - err_dr, node = cuda.cuGraphAddEmptyNode(graph, [], 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graph = cuda.graph_create(0) + cuda.graph_add_empty_node(graph, 0, 0) # DRV to RT - err_dr, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graphExec = cuda.graph_instantiate_with_flags(graph, 0) (err_rt,) = cudart.cudaGraphExecDestroy(graphExec) assert err_rt == cudart.cudaError_t.cudaSuccess # RT to DRV err_rt, graphExec = cudart.cudaGraphInstantiate(graph, 0) assert err_rt == cudart.cudaError_t.cudaSuccess - (err_dr,) = cuda.cuGraphExecDestroy(graphExec) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.graph_exec_destroy(int(graphExec)) (err_rt,) = cudart.cudaGraphDestroy(graph) assert err_rt == cudart.cudaError_t.cudaSuccess @@ -126,8 +114,7 @@ def test_interop_graphExec(): def test_interop_deviceptr(): # Allocate dev memory size = 1024 * np.uint8().itemsize - err_dr, dptr = cuda.cuMemAlloc(size) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + dptr = cuda.mem_alloc_v2(size) # Allocate host memory h1 = np.full(size, 1).astype(np.uint8) @@ -146,5 +133,4 @@ def test_interop_deviceptr(): assert np.array_equal(h1, h2) # Cleanup - (err_dr,) = cuda.cuMemFree(dptr) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + cuda.mem_free_v2(dptr) diff --git a/cuda_bindings/tests/test_kernelParams.py b/cuda_bindings/tests/test_kernelParams.py index 3457965086e..0d45a4b89b8 100644 --- a/cuda_bindings/tests/test_kernelParams.py +++ b/cuda_bindings/tests/test_kernelParams.py @@ -6,16 +6,13 @@ import numpy as np import pytest +import cuda.bindings._v2.driver as cuda import cuda.bindings._v2.nvrtc as nvrtc -import cuda.bindings.driver as cuda import cuda.bindings.runtime as cudart def ASSERT_DRV(err): - if isinstance(err, cuda.CUresult): - if err != cuda.CUresult.CUDA_SUCCESS: - raise RuntimeError(f"Cuda Error: {err}") - elif isinstance(err, cudart.cudaError_t): + if isinstance(err, cudart.cudaError_t): if err != cudart.cudaError_t.cudaSuccess: raise RuntimeError(f"Cudart Error: {err}") else: @@ -23,10 +20,8 @@ def ASSERT_DRV(err): def common_nvrtc(allKernelStrings, dev): - err, major = cuda.cuDeviceGetAttribute(cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev) - ASSERT_DRV(err) - err, minor = cuda.cuDeviceGetAttribute(cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev) - ASSERT_DRV(err) + major = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev) + minor = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev) _, nvrtc_minor = nvrtc.version() use_cubin = nvrtc_minor >= 1 prefix = "sm" if use_cubin else "compute" @@ -46,10 +41,7 @@ def common_nvrtc(allKernelStrings, dev): else: data = nvrtc.get_ptx(prog) - err, module = cuda.cuModuleLoadData(np.char.array(data)) - ASSERT_DRV(err) - - return module + return cuda.module_load_data(np.char.array(data)) def test_kernelParams_empty(device): @@ -66,13 +58,11 @@ def test_kernelParams_empty(device): module = common_nvrtc(kernelString, device) # cudaStructs kernel - err, kernel = cuda.cuModuleGetFunction(module, b"empty_kernel") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "empty_kernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -85,8 +75,7 @@ def test_kernelParams_empty(device): ((), ()), 0, ) # arguments - ASSERT_DRV(err) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -99,23 +88,19 @@ def test_kernelParams_empty(device): None, 0, ) # arguments - ASSERT_DRV(err) # Retrieve global and validate isDone_host = ctypes.c_bool() - err, isDonePtr_device, isDonePtr_device_size = cuda.cuModuleGetGlobal(module, b"isDone") - ASSERT_DRV(err) + isDonePtr_device, isDonePtr_device_size = cuda.module_get_global_v2(module, b"isDone") assert isDonePtr_device_size == ctypes.sizeof(ctypes.c_bool) - (err,) = cuda.cuMemcpyDtoHAsync(isDone_host, isDonePtr_device, ctypes.sizeof(ctypes.c_bool), stream) - ASSERT_DRV(err) - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + # memcpy_dtoh_async_v2 requires a 1D buffer or a raw address; a scalar + # ctypes object's buffer has ndim 0, so pass its address instead. + cuda.memcpy_dtoh_async_v2(ctypes.addressof(isDone_host), isDonePtr_device, ctypes.sizeof(ctypes.c_bool), stream) + cuda.stream_synchronize(stream) assert isDone_host.value is True - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) @pytest.mark.parametrize("use_ctypes_as_values", [False, True], ids=["no-ctypes", "ctypes"]) @@ -254,69 +239,37 @@ def test_kernelParams(use_ctypes_as_values, device): module = common_nvrtc(basicKernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"basic") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "basic") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) # Prepare kernel - err, pb = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_bool)) - ASSERT_DRV(err) - err, pc = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_char)) - ASSERT_DRV(err) - err, pwc = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_wchar)) - ASSERT_DRV(err) - err, pbyte = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_byte)) - ASSERT_DRV(err) - err, pubyte = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_ubyte)) - ASSERT_DRV(err) - err, ps = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_short)) - ASSERT_DRV(err) - err, pus = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_ushort)) - ASSERT_DRV(err) - err, pi = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_int)) - ASSERT_DRV(err) - err, pui = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_uint)) - ASSERT_DRV(err) - err, pl = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_long)) - ASSERT_DRV(err) - err, pul = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_ulong)) - ASSERT_DRV(err) - err, pll = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_longlong)) - ASSERT_DRV(err) - err, pull = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_ulonglong)) - ASSERT_DRV(err) - err, psize = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_size_t)) - ASSERT_DRV(err) - err, pf = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_float)) - ASSERT_DRV(err) - err, pd = cuda.cuMemAlloc(ctypes.sizeof(ctypes.c_double)) - ASSERT_DRV(err) + pb = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_bool)) + pc = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_char)) + pwc = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_wchar)) + pbyte = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_byte)) + pubyte = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_ubyte)) + ps = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_short)) + pus = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_ushort)) + pi = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_int)) + pui = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_uint)) + pl = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_long)) + pul = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_ulong)) + pll = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_longlong)) + pull = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_ulonglong)) + psize = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_size_t)) + pf = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_float)) + pd = cuda.mem_alloc_v2(ctypes.sizeof(ctypes.c_double)) assertValues_device = (pb, pc, pwc, pbyte, pubyte, ps, pus, pi, pui, pl, pul, pll, pull, psize, pf, pd) - assertTypes_device = ( - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - ) + # mem_alloc_v2 returns a plain int device pointer. Pairing it with the + # ctypes.c_void_p type marker is enough for _HelperKernelParams to marshal + # it by pointer -- no need to box the value itself. + assertTypes_device = (ctypes.c_void_p,) * len(assertValues_device) basicKernelValues = assertValues_host + assertValues_device basicKernelTypes = assertTypes_host + assertTypes_device - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -329,19 +282,16 @@ def test_kernelParams(use_ctypes_as_values, device): (basicKernelValues, basicKernelTypes), 0, ) # arguments - ASSERT_DRV(err) # Retrieve each dptr host_params = tuple([valueType() for valueType in assertTypes_host[:-1]]) for i in range(len(host_params)): - (err,) = cuda.cuMemcpyDtoHAsync( - host_params[i], assertValues_device[i], ctypes.sizeof(assertTypes_host[i]), stream + cuda.memcpy_dtoh_async_v2( + ctypes.addressof(host_params[i]), assertValues_device[i], ctypes.sizeof(assertTypes_host[i]), stream ) - ASSERT_DRV(err) # Validate retrieved values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) for i in range(len(host_params)): val = basicKernelValues[i].value if use_ctypes_as_values else basicKernelValues[i] if basicKernelTypes[i] == ctypes.c_float: @@ -352,49 +302,28 @@ def test_kernelParams(use_ctypes_as_values, device): else: assert val == host_params[i].value - (err,) = cuda.cuMemFree(pb) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pc) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pwc) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pbyte) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pubyte) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(ps) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pus) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pi) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pui) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pl) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pul) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pll) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pull) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(psize) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pf) - ASSERT_DRV(err) - (err,) = cuda.cuMemFree(pd) - ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.mem_free_v2(pb) + cuda.mem_free_v2(pc) + cuda.mem_free_v2(pwc) + cuda.mem_free_v2(pbyte) + cuda.mem_free_v2(pubyte) + cuda.mem_free_v2(ps) + cuda.mem_free_v2(pus) + cuda.mem_free_v2(pi) + cuda.mem_free_v2(pui) + cuda.mem_free_v2(pl) + cuda.mem_free_v2(pul) + cuda.mem_free_v2(pll) + cuda.mem_free_v2(pull) + cuda.mem_free_v2(psize) + cuda.mem_free_v2(pf) + cuda.mem_free_v2(pd) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) def test_kernelParams_types_cuda(device): - err, uvaSupported = cuda.cuDeviceGetAttribute( - cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, device - ) - ASSERT_DRV(err) + uvaSupported = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_UNIFIED_ADDRESSING, device) err, perr = cudart.cudaMalloc(ctypes.sizeof(ctypes.c_int)) ASSERT_DRV(err) @@ -448,13 +377,11 @@ def test_kernelParams_types_cuda(device): module = common_nvrtc(kernelString, device) # cudaStructs kernel - err, kernel = cuda.cuModuleGetFunction(module, b"structsCuda") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "structsCuda") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -467,7 +394,6 @@ def test_kernelParams_types_cuda(device): (kernelValues, kernelTypes), 0, ) # arguments - ASSERT_DRV(err) # Retrieve each dptr host_err = ctypes.c_int() @@ -481,8 +407,7 @@ def test_kernelParams_types_cuda(device): ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) cuda_err = cudart.cudaError_t(host_err.value) if uvaSupported: @@ -506,17 +431,12 @@ def test_kernelParams_types_cuda(device): ASSERT_DRV(err) (err,) = cudart.cudaFreeHost(pDim3_host) ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) def test_kernelParams_struct_custom(device): - err, uvaSupported = cuda.cuDeviceGetAttribute( - cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, device - ) - ASSERT_DRV(err) + uvaSupported = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -532,11 +452,9 @@ def test_kernelParams_struct_custom(device): module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"structCustom") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "structCustom") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) # structCustom kernel class testStruct(ctypes.Structure): @@ -554,7 +472,7 @@ class testStruct(ctypes.Structure): kernelValues = (testStruct(5), pStruct_device) kernelTypes = (None, ctypes.c_void_p) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -567,28 +485,21 @@ class testStruct(ctypes.Structure): (kernelValues, kernelTypes), 0, ) # arguments - ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) struct_shared = testStruct.from_address(pStruct_host) assert kernelValues[0].value == struct_shared.value (err,) = cudart.cudaFreeHost(pStruct_host) ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) @pytest.mark.parametrize("pass_by_address", [False, True], ids=["by-address", "not-by-address"]) def test_kernelParams_buffer_protocol(pass_by_address, device): - err, uvaSupported = cuda.cuDeviceGetAttribute( - cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, device - ) - ASSERT_DRV(err) + uvaSupported = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -607,11 +518,9 @@ def test_kernelParams_buffer_protocol(pass_by_address, device): module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"testkernel") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "testkernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) # testkernel kernel class testStruct(ctypes.Structure): @@ -653,7 +562,7 @@ class testStruct(ctypes.Structure): packagedParams = (ctypes.c_void_p * len(kernelValues))() for idx in range(len(packagedParams)): packagedParams[idx] = ctypes.addressof(kernelValues[idx]) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -666,28 +575,21 @@ class testStruct(ctypes.Structure): ctypes.addressof(packagedParams) if pass_by_address else packagedParams, 0, ) # arguments - ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) assert kernelValues[0].value == ctypes.c_int.from_address(pInt_host).value assert kernelValues[2].value == ctypes.c_float.from_address(pFloat_host).value assert kernelValues[4].value == testStruct.from_address(pStruct_host).value (err,) = cudart.cudaFreeHost(pStruct_host) ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) def test_kernelParams_buffer_protocol_numpy(device): - err, uvaSupported = cuda.cuDeviceGetAttribute( - cuda.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, device - ) - ASSERT_DRV(err) + uvaSupported = cuda.device_get_attribute(cuda.DeviceAttribute.CU_ATTRIBUTE_UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -706,11 +608,9 @@ def test_kernelParams_buffer_protocol_numpy(device): module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"testkernel") - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "testkernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = cuda.stream_create(0) # testkernel kernel testStruct = np.dtype([("value", np.int32)]) @@ -749,7 +649,7 @@ def test_kernelParams_buffer_protocol_numpy(device): ) packagedParams = np.array([arg.ctypes.data for arg in kernelValues], dtype=np.uint64) - (err,) = cuda.cuLaunchKernel( + cuda.launch_kernel( kernel, 1, 1, @@ -762,11 +662,9 @@ def test_kernelParams_buffer_protocol_numpy(device): packagedParams, 0, ) # arguments - ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) class numpy_address_wrapper: def __init__(self, address, typestr): @@ -778,10 +676,8 @@ def __init__(self, address, typestr): (err,) = cudart.cudaFreeHost(pStruct_host) ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) def test_kernelParams_c_int_out_of_range_raises(device): @@ -791,25 +687,19 @@ def test_kernelParams_c_int_out_of_range_raises(device): extern "C" __global__ void take_int(int i) {} """ module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"take_int") - ASSERT_DRV(err) - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + kernel = cuda.module_get_function(module, "take_int") + stream = cuda.stream_create(0) # An in-range value still packs and launches fine. - (err,) = cuda.cuLaunchKernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((5,), (ctypes.c_int,)), 0) - ASSERT_DRV(err) + cuda.launch_kernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((5,), (ctypes.c_int,)), 0) # Out-of-range values now raise OverflowError during packing (previously the # high bits were silently dropped, so the kernel saw a different value). with pytest.raises(OverflowError): - cuda.cuLaunchKernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((2**32 + 5,), (ctypes.c_int,)), 0) + cuda.launch_kernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((2**32 + 5,), (ctypes.c_int,)), 0) with pytest.raises(OverflowError): - cuda.cuLaunchKernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((200,), (ctypes.c_byte,)), 0) + cuda.launch_kernel(kernel, 1, 1, 1, 1, 1, 1, 0, stream, ((200,), (ctypes.c_byte,)), 0) - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + cuda.stream_synchronize(stream) + cuda.stream_destroy_v2(stream) + cuda.module_unload(module) diff --git a/cuda_bindings/tests/test_nvvm.py b/cuda_bindings/tests/test_nvvm.py index 91b7d705d34..08231ba182a 100644 --- a/cuda_bindings/tests/test_nvvm.py +++ b/cuda_bindings/tests/test_nvvm.py @@ -80,10 +80,8 @@ def test_create_and_destroy(): @pytest.mark.parametrize("add_fn", [nvvm.add_module_to_program, nvvm.lazy_add_module_to_program]) def test_add_module_to_program_fail(add_fn): - with nvvm_program() as prog, pytest.raises(ValueError): - # Passing a C NULL pointer generates "ERROR_INVALID_INPUT (4)", - # but that is not possible through our Python bindings. - # The ValueError originates from the cython bindings code. + with nvvm_program() as prog, pytest.raises(nvvm.nvvmError, match=match_exact("ERROR_INVALID_INPUT (4)")): + # None is passed through as a C NULL pointer, which nvvm rejects. add_fn(prog, None, 0, "FileNameHere.ll") diff --git a/cuda_bindings/tests/test_version_check.py b/cuda_bindings/tests/test_version_check.py index 03c3d7d3c2c..d91df411722 100644 --- a/cuda_bindings/tests/test_version_check.py +++ b/cuda_bindings/tests/test_version_check.py @@ -7,7 +7,7 @@ import pytest -from cuda.bindings import driver +from cuda.bindings._v2 import driver from cuda.bindings.utils import _version_check, warn_if_cuda_major_version_mismatch @@ -24,7 +24,7 @@ def test_no_warning_when_driver_newer(self): # Mock compile version 12.9 and driver version 13.0 with ( mock.patch.object(driver, "CUDA_VERSION", 12090), - mock.patch.object(driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_SUCCESS, 13000)), + mock.patch.object(driver, "driver_get_version", return_value=13000), warnings.catch_warnings(record=True) as w, ): warnings.simplefilter("always") @@ -36,7 +36,7 @@ def test_no_warning_when_same_major_version(self): # Mock compile version 12.9 and driver version 12.8 with ( mock.patch.object(driver, "CUDA_VERSION", 12090), - mock.patch.object(driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_SUCCESS, 12080)), + mock.patch.object(driver, "driver_get_version", return_value=12080), warnings.catch_warnings(record=True) as w, ): warnings.simplefilter("always") @@ -48,7 +48,7 @@ def test_warning_when_compile_major_newer(self): # Mock compile version 13.0 and driver version 12.8 with ( mock.patch.object(driver, "CUDA_VERSION", 13000), - mock.patch.object(driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_SUCCESS, 12080)), + mock.patch.object(driver, "driver_get_version", return_value=12080), warnings.catch_warnings(record=True) as w, ): warnings.simplefilter("always") @@ -62,7 +62,7 @@ def test_warning_only_issued_once(self): """Warning should only be issued once per process.""" with ( mock.patch.object(driver, "CUDA_VERSION", 13000), - mock.patch.object(driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_SUCCESS, 12080)), + mock.patch.object(driver, "driver_get_version", return_value=12080), warnings.catch_warnings(record=True) as w, ): warnings.simplefilter("always") @@ -76,7 +76,7 @@ def test_warning_suppressed_by_env_var(self): """Warning should be suppressed when CUDA_PYTHON_DISABLE_MAJOR_VERSION_WARNING is set.""" with ( mock.patch.object(driver, "CUDA_VERSION", 13000), - mock.patch.object(driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_SUCCESS, 12080)), + mock.patch.object(driver, "driver_get_version", return_value=12080), mock.patch.dict(os.environ, {"CUDA_PYTHON_DISABLE_MAJOR_VERSION_WARNING": "1"}), warnings.catch_warnings(record=True) as w, ): @@ -85,11 +85,13 @@ def test_warning_suppressed_by_env_var(self): assert len(w) == 0 def test_error_when_driver_version_fails(self): - """Should raise RuntimeError if cuDriverGetVersion fails.""" + """Should raise RuntimeError if driver_get_version fails.""" with ( mock.patch.object(driver, "CUDA_VERSION", 13000), mock.patch.object( - driver, "cuDriverGetVersion", return_value=(driver.CUresult.CUDA_ERROR_NOT_INITIALIZED, 0) + driver, + "driver_get_version", + side_effect=driver.DriverError(driver.Result.CUDA_ERROR_NOT_INITIALIZED), ), pytest.raises(RuntimeError, match="Failed to query CUDA driver version"), ):