diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e141937748a..650bd62f51e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -127,7 +127,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|_v2/driver)\.pyx$ - id: check-case-conflict - id: check-docstring-first - id: check-merge-conflict diff --git a/cuda_bindings/AGENTS.md b/cuda_bindings/AGENTS.md index 389246be5a9..20370170218 100644 --- a/cuda_bindings/AGENTS.md +++ b/cuda_bindings/AGENTS.md @@ -46,10 +46,10 @@ subpackage in the `cuda-python` monorepo. - **Samples**: sample coverage is pytest-based under `../samples/cuda_bindings/`. - **Benchmarks**: run with `pytest --benchmark-only benchmarks/` when needed. -The `legacy_tests` subdirectory tests the old pre-v2 APIs of `driver`, `runtime` +The `legacy_api` subdirectory tests the old pre-v2 APIs of `driver`, `runtime` and `nvrtc`. These test files should not be added to, only updated when necessary to fix test failures. The canonical set of tests are those outside of -the `legacy_tests` subdirectory. +the `legacy_api` subdirectory. ## Build and environment notes diff --git a/cuda_bindings/cuda/bindings/_v2/driver.pxd b/cuda_bindings/cuda/bindings/_v2/driver.pxd new file mode 100644 index 00000000000..634c4121d2b --- /dev/null +++ b/cuda_bindings/cuda/bindings/_v2/driver.pxd @@ -0,0 +1,721 @@ +# 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.4.1. Do not modify it directly. +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=f9f2c83efd71c87778422f6fa62fa737eb43ec0c437102501f821a8426d1b78b + + +# <<<< PREAMBLE CONTENT >>>> + +from libc.stdint cimport ( + intptr_t, + uint32_t, + uint64_t, +) + + +# <<<< END OF PREAMBLE CONTENT >>>> + +from libc.stdint cimport intptr_t, uint32_t, uint64_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 CUcheckpointOperationHandle CheckpointOperationHandle +ctypedef CUhostFn hostFn +ctypedef CUoccupancyB2DSize occupancyB2DSize +ctypedef CUlogsCallback logsCallback +ctypedef CUDA_KERNEL_NODE_PARAMS_v1 KernelNodeParams_v1 +ctypedef CUstreamCallback streamCallback +ctypedef CUcheckpointCustomStoragePerDeviceData CheckpointCustomStoragePerDeviceData +ctypedef CUcoredumpStatusCallback coredumpStatusCallback +ctypedef CUcheckpointCustomStorageInfo CheckpointCustomStorageInfo +ctypedef CUasyncCallback asyncCallback +ctypedef CUgraphRecaptureCallback graphRecaptureCallback + + +############################################################################### +# Enum +############################################################################### + +ctypedef CUipcMem_flags _IpcMemFlags +ctypedef CUmemAttach_flags _MemAttachFlags +ctypedef CUctx_flags _CtxFlags +ctypedef CUevent_sched_flags _EventSchedFlags +ctypedef cl_event_flags _NvclEventFlags +ctypedef cl_context_flags _ContextFlags +ctypedef CUstream_flags _StreamFlags +ctypedef CUevent_flags _EventFlags +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 +ctypedef CUcliqueType _CliqueType + + +############################################################################### +# Functions +############################################################################### + +cpdef object mem_export_to_shareable_handle(uint64_t handle, int handle_type, unsigned long long flags) +cpdef object mem_pool_export_to_shareable_handle(intptr_t pool, int handle_type, unsigned long long flags) +cpdef object logical_endpoint_export(uint32_t le_id, int handle_type) +cpdef memcpy_batch_async(object dsts, object srcs, object sizes, object attrs, object attrs_idxs, intptr_t h_stream) +cpdef int mem_get_handle_for_address_range(uint64_t dptr, size_t size, int handle_type, unsigned long long flags) except? -1 +cpdef int thread_exchange_stream_capture_mode(int mode) except? -1 +cpdef list tex_ref_get_border_color(intptr_t h_tex_ref) +cpdef unsigned int logs_dump_to_file(iterator, bytes path_to_file, unsigned int flags) except? 0 +cpdef object pointer_get_attribute(int attribute, uint64_t ptr) +cpdef list pointer_get_attributes(attributes, uint64_t ptr) +cpdef object mem_pool_get_attribute(intptr_t pool, int attr) +cpdef unsigned long long device_get_graph_mem_attribute(int device, int attr) except? 0 +cpdef object mem_range_get_attribute(size_t data_size, int attribute, uint64_t dev_ptr, size_t count) +cpdef list mem_range_get_attributes(data_sizes, attributes, uint64_t dev_ptr, size_t count) +cpdef object coredump_get_attribute(int attrib) +cpdef object coredump_get_attribute_global(int attrib) +cpdef coredump_set_attribute(int attrib, value) +cpdef coredump_set_attribute_global(int attrib, value) +cpdef object device_get_host_atomic_capabilities(object operations, int dev) +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 str get_error_string(int error) +cpdef str get_error_name(int error) +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_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 bytes kernel_get_name(intptr_t hfunc) +cpdef tuple kernel_get_param_info(intptr_t kernel, size_t param_index) +cpdef tuple mem_get_info_v2() +cpdef uint64_t 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(uint64_t dptr) +cpdef tuple mem_get_address_range_v2(uint64_t 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 uint64_t 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 uint64_t 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(uint64_t dptr) +cpdef uint64_t ipc_open_mem_handle_v2(handle, unsigned int flags) except? 0 +cpdef ipc_close_mem_handle(uint64_t dptr) +cpdef mem_host_register_v2(p, size_t bytesize, unsigned int flags) +cpdef mem_host_unregister(p) +cpdef cu_memcpy(uint64_t dst, uint64_t src, size_t byte_count) +cpdef memcpy_peer(uint64_t dst_device, intptr_t dst_context, uint64_t src_device, intptr_t src_context, size_t byte_count) +cpdef memcpy_htod_v2(uint64_t dst_device, src_host, size_t byte_count) +cpdef memcpy_dtoh_v2(dst_host, uint64_t src_device, size_t byte_count) +cpdef memcpy_dtod_v2(uint64_t dst_device, uint64_t src_device, size_t byte_count) +cpdef memcpy_dtoa_v2(intptr_t dst_array, size_t dst_offset, uint64_t src_device, size_t byte_count) +cpdef memcpy_atod_v2(uint64_t 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(uint64_t dst, uint64_t src, size_t byte_count, intptr_t h_stream) +cpdef memcpy_peer_async(uint64_t dst_device, intptr_t dst_context, uint64_t src_device, intptr_t src_context, size_t byte_count, intptr_t h_stream) +cpdef memcpy_htod_async_v2(uint64_t dst_device, src_host, size_t byte_count, intptr_t h_stream) +cpdef memcpy_dtoh_async_v2(dst_host, uint64_t src_device, size_t byte_count, intptr_t h_stream) +cpdef memcpy_dtod_async_v2(uint64_t dst_device, uint64_t 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(uint64_t dst_device, unsigned char uc, size_t n) +cpdef memset_d16_v2(uint64_t dst_device, unsigned short us, size_t n) +cpdef memset_d32_v2(uint64_t dst_device, unsigned int ui, size_t n) +cpdef memset_d2d8_v2(uint64_t dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height) +cpdef memset_d2d16_v2(uint64_t dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height) +cpdef memset_d2d32_v2(uint64_t dst_device, size_t dst_pitch, unsigned int ui, size_t width, size_t height) +cpdef memset_d8_async(uint64_t dst_device, unsigned char uc, size_t n, intptr_t h_stream) +cpdef memset_d16_async(uint64_t dst_device, unsigned short us, size_t n, intptr_t h_stream) +cpdef memset_d32_async(uint64_t dst_device, unsigned int ui, size_t n, intptr_t h_stream) +cpdef memset_d2d8_async(uint64_t dst_device, size_t dst_pitch, unsigned char uc, size_t width, size_t height, intptr_t h_stream) +cpdef memset_d2d16_async(uint64_t dst_device, size_t dst_pitch, unsigned short us, size_t width, size_t height, intptr_t h_stream) +cpdef memset_d2d32_async(uint64_t 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 size_t mem_batch_decompress_async(params_array, size_t count, unsigned int flags, intptr_t stream) except? 0 +cpdef uint64_t mem_address_reserve(size_t size, size_t alignment, uint64_t addr, unsigned long long flags) except? 0 +cpdef mem_address_free(uint64_t ptr, size_t size) +cpdef uint64_t mem_create(size_t size, prop, unsigned long long flags) except? 0 +cpdef mem_release(uint64_t handle) +cpdef mem_map(uint64_t ptr, size_t size, size_t offset, uint64_t handle, unsigned long long flags) +cpdef mem_map_array_async(map_info_list, unsigned int count, intptr_t h_stream) +cpdef mem_unmap(uint64_t ptr, size_t size) +cpdef mem_set_access(uint64_t ptr, size_t size, desc, size_t count) +cpdef unsigned long long mem_get_access(location, uint64_t ptr) except? 0 +cpdef uint64_t 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 object mem_get_allocation_properties_from_handle(uint64_t handle) +cpdef uint64_t mem_retain_allocation_handle(intptr_t addr) except? 0 +cpdef mem_free_async(uint64_t dptr, intptr_t h_stream) +cpdef uint64_t 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_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 uint64_t mem_alloc_from_pool_async(size_t bytesize, intptr_t pool, intptr_t h_stream) except? 0 +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(uint64_t ptr) +cpdef uint64_t mem_pool_import_pointer(intptr_t pool, share_data) except? 0 +cpdef uint64_t multicast_create(prop) except? 0 +cpdef multicast_add_device(uint64_t mc_handle, int dev) +cpdef multicast_bind_mem(uint64_t mc_handle, size_t mc_offset, uint64_t mem_handle, size_t mem_offset, size_t size, unsigned long long flags) +cpdef multicast_bind_addr(uint64_t mc_handle, size_t mc_offset, uint64_t memptr, size_t size, unsigned long long flags) +cpdef multicast_unbind(uint64_t mc_handle, int dev, size_t mc_offset, size_t size) +cpdef size_t multicast_get_granularity(prop, int option) except? 0 +cpdef mem_prefetch_async_v2(uint64_t dev_ptr, size_t count, location, unsigned int flags, intptr_t h_stream) +cpdef mem_advise_v2(uint64_t dev_ptr, size_t count, int advice, location) +cpdef pointer_set_attribute(value, int attribute, uint64_t 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, dependencies, dependency_data, size_t num_dependencies, int mode) +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, dependencies, dependency_data, size_t num_dependencies, unsigned int flags) +cpdef stream_attach_mem_async(intptr_t h_stream, uint64_t 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 object stream_get_attribute(intptr_t h_stream, int attr) +cpdef stream_set_attribute(intptr_t h_stream, int attr, 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(mem_handle_desc) except? 0 +cpdef uint64_t 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, mipmap_desc) except? 0 +cpdef destroy_external_memory(intptr_t ext_mem) +cpdef intptr_t import_external_semaphore(sem_handle_desc) except? 0 +cpdef signal_external_semaphores_async(ext_sem_array, params_array, unsigned int num_ext_sems, intptr_t stream) +cpdef wait_external_semaphores_async(ext_sem_array, 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, uint64_t addr, uint32_t value, unsigned int flags) +cpdef stream_wait_value64_v2(intptr_t stream, uint64_t addr, uint64_t value, unsigned int flags) +cpdef stream_write_value32_v2(intptr_t stream, uint64_t addr, uint32_t value, unsigned int flags) +cpdef stream_write_value64_v2(intptr_t stream, uint64_t 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 bytes func_get_name(intptr_t hfunc) +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_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 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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_kernel_node_get_params_v2(intptr_t h_node) +cpdef graph_kernel_node_set_params_v2(intptr_t h_node, node_params) +cpdef intptr_t graph_add_memcpy_node(intptr_t h_graph, dependencies, size_t num_dependencies, copy_params, intptr_t ctx) except? 0 +cpdef object graph_memcpy_node_get_params(intptr_t h_node) +cpdef graph_memcpy_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_memset_node(intptr_t h_graph, 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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_host_node_get_params(intptr_t h_node) +cpdef graph_host_node_set_params(intptr_t h_node, node_params) +cpdef intptr_t graph_add_child_graph_node(intptr_t h_graph, 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, dependencies, size_t num_dependencies) except? 0 +cpdef intptr_t graph_add_event_record_node(intptr_t h_graph, 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, 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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_external_semaphores_signal_node_get_params(intptr_t h_node) +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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_external_semaphores_wait_node_get_params(intptr_t h_node) +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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_batch_mem_op_node_get_params(intptr_t h_node) +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, dependencies, size_t num_dependencies, node_params) except? 0 +cpdef object graph_mem_alloc_node_get_params(intptr_t h_node) +cpdef intptr_t graph_add_mem_free_node(intptr_t h_graph, dependencies, size_t num_dependencies, uint64_t dptr) except? 0 +cpdef uint64_t graph_mem_free_node_get_params(intptr_t h_node) except? 0 +cpdef device_graph_mem_trim(int device) +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, from_, to, edge_data, size_t num_dependencies) +cpdef graph_remove_dependencies_v2(intptr_t h_graph, from_, 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 object graph_exec_update_v2(intptr_t h_graph_exec, intptr_t h_graph) +cpdef graph_kernel_node_copy_attributes(intptr_t dst, intptr_t src) +cpdef object graph_kernel_node_get_attribute(intptr_t h_node, int attr) +cpdef graph_kernel_node_set_attribute(intptr_t h_node, int attr, 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, 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, uint64_t dptr, size_t bytes) except? 0 +cpdef tex_ref_set_address2d_v3(intptr_t h_tex_ref, desc, uint64_t 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 uint64_t 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 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 uint64_t tex_object_create(p_res_desc, p_tex_desc, p_res_view_desc) except? 0 +cpdef tex_object_destroy(uint64_t tex_object) +cpdef object tex_object_get_resource_desc(uint64_t tex_object) +cpdef object tex_object_get_texture_desc(uint64_t tex_object) +cpdef object tex_object_get_resource_view_desc(uint64_t tex_object) +cpdef uint64_t surf_object_create(p_res_desc) except? 0 +cpdef surf_object_destroy(uint64_t surf_object) +cpdef object surf_object_get_resource_desc(uint64_t surf_object) +cpdef object tensor_map_encode_tiled(int tensor_data_type, uint32_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 object tensor_map_encode_im2col(int tensor_data_type, uint32_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, uint32_t channels_per_pixel, uint32_t pixels_per_column, intptr_t element_strides, int interleave, int swizzle, int l2promotion, int oob_fill) +cpdef object tensor_map_encode_im2col_wide(int tensor_data_type, uint32_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, uint32_t channels_per_pixel, uint32_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, resources, intptr_t h_stream) +cpdef graphics_unmap_resources(unsigned int count, resources, intptr_t h_stream) +cpdef tuple get_proc_address_v2(symbol, int cuda_version, uint64_t flags) +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 object device_get_dev_resource(int device, int type) +cpdef object ctx_get_dev_resource(intptr_t h_ctx, int type) +cpdef object green_ctx_get_dev_resource(intptr_t h_ctx, int type) +cpdef tuple dev_sm_resource_split_by_count(input, 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_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, args) +cpdef checkpoint_process_unlock(int pid, args) +cpdef intptr_t graphics_egl_register_image(intptr_t image, unsigned int flags) except? 0 +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, 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(uint64_t mc_handle, int dev, size_t mc_offset, uint64_t mem_handle, size_t mem_offset, size_t size, unsigned long long flags) +cpdef multicast_bind_addr_v2(uint64_t mc_handle, int dev, size_t mc_offset, uint64_t 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 tuple dev_sm_resource_split(unsigned int nb_groups, input, unsigned int flags, group_params) +cpdef object stream_get_dev_resource(intptr_t h_stream, int type) +cpdef size_t kernel_get_param_count(intptr_t kernel) except? 0 +cpdef memcpy_with_attributes_async(uint64_t dst, uint64_t src, size_t size, attr, intptr_t h_stream) +cpdef memcpy_3d_with_attributes_async(op, unsigned long long flags, intptr_t h_stream) +cpdef stream_begin_capture_to_cig(intptr_t h_stream, 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 object graph_node_get_params(intptr_t h_node) +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(uint32_t count) except? 0 +cpdef logical_endpoint_id_release(uint32_t base_le_id, uint32_t count) +cpdef logical_endpoint_create(uint32_t le_id, 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, uint64_t 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_import(uint32_t le_id, handle, int handle_type) +cpdef tuple logical_endpoint_get_limits(prop) +cpdef int logical_endpoint_query(uint32_t le_id, uint32_t count) except? -1 +cpdef stream_begin_recapture_to_graph(intptr_t h_stream, int mode, intptr_t h_graph, intptr_t callback_func, intptr_t user_data) +cpdef object device_get_fabric_cluster_uuid(int dev) +cpdef size_t device_get_clique_count(int dev) except? 0 +cpdef object device_get_clique_info(int dev) +cpdef object mem_get_location_info(uint64_t ptr, size_t size, size_t summary_granularity, size_t sampling_granularity) +cpdef intptr_t graph_add_node_v3(intptr_t h_graph, dependencies, dependency_data, size_t num_dependencies, node_params) except? 0 +cpdef graph_node_set_params_v2(intptr_t h_node, node_params) +cpdef checkpoint_operation_complete(intptr_t handle) diff --git a/cuda_bindings/cuda/bindings/_v2/driver.pyx b/cuda_bindings/cuda/bindings/_v2/driver.pyx new file mode 100644 index 00000000000..f7f1c73b02e --- /dev/null +++ b/cuda_bindings/cuda/bindings/_v2/driver.pyx @@ -0,0 +1,43748 @@ +# 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.4.1. Do not modify it directly. +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=669fccd9c90beac89a312832e43ef932007842229300c7a881d8bb6c960f9b6a + + +# <<<< PREAMBLE CONTENT >>>> + +cimport cpython as _cyb_cpython +cimport cpython.buffer as _cyb_cpython_buffer +from cpython.buffer cimport ( + PyBUF_READ as _cyb_PyBUF_READ, + PyBUF_SIMPLE as _cyb_PyBUF_SIMPLE, + PyBuffer_Release as _cyb_PyBuffer_Release, + PyObject_GetBuffer as _cyb_PyObject_GetBuffer, + Py_buffer as _cyb_Py_buffer, +) +cimport cpython.memoryview as _cyb_cpython_memoryview +from cpython.memoryview cimport PyMemoryView_FromMemory as _cyb_PyMemoryView_FromMemory +from cuda.bindings._internal.utils cimport ( + get_resource_ptrs as _cyb_get_resource_ptrs, + nullable_unique_ptr as _cyb_nullable_unique_ptr, +) +from cython cimport view as _cyb_view +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, + memmove as _cyb_memmove, +) +from libcpp.vector cimport vector as _cyb_vector + +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, view.readonly != 0, 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 + 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 contiguous {adj}" + f"buffer (a ctypes object, NumPy array, bytes, ...), 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.string cimport memcpy, memset + +from cpython.mem cimport PyMem_Calloc, PyMem_Free + +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`. + """ + 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`. + """ + GLOBAL = (cydriver.CUmemAttach_flags_enum.CU_MEM_ATTACH_GLOBAL, 'Memory can be accessed by any stream on any device') + HOST = (cydriver.CUmemAttach_flags_enum.CU_MEM_ATTACH_HOST, 'Memory cannot be accessed by any stream on any device') + 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`. + """ + SCHED_AUTO = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_AUTO, 'Automatic scheduling') + SCHED_SPIN = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_SPIN, 'Set spin as default scheduling') + SCHED_YIELD = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_YIELD, 'Set yield as default scheduling') + SCHED_BLOCKING_SYNC = (cydriver.CUctx_flags_enum.CU_CTX_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + BLOCKING_SYNC = (cydriver.CUctx_flags_enum.CU_CTX_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling [Deprecated]') + SCHED_MASK = cydriver.CUctx_flags_enum.CU_CTX_SCHED_MASK + MAP_HOST = (cydriver.CUctx_flags_enum.CU_CTX_MAP_HOST, '[Deprecated]') + LMEM_RESIZE_TO_MAX = (cydriver.CUctx_flags_enum.CU_CTX_LMEM_RESIZE_TO_MAX, 'Keep local memory allocation after launch') + COREDUMP_ENABLE = (cydriver.CUctx_flags_enum.CU_CTX_COREDUMP_ENABLE, 'Trigger coredumps from exceptions in this context') + USER_COREDUMP_ENABLE = (cydriver.CUctx_flags_enum.CU_CTX_USER_COREDUMP_ENABLE, 'Enable user pipe to trigger coredumps in this context') + SYNC_MEMOPS = (cydriver.CUctx_flags_enum.CU_CTX_SYNC_MEMOPS, 'Ensure synchronous memory operations on this context will synchronize') + FLAGS_MASK = cydriver.CUctx_flags_enum.CU_CTX_FLAGS_MASK + +class EventSchedFlags(_cyb_FastEnum): + """ + Event sched flags + + See `CUevent_sched_flags`. + """ + AUTO = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_AUTO, 'Automatic scheduling') + SPIN = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_SPIN, 'Set spin as default scheduling') + YIELD = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_YIELD, 'Set yield as default scheduling') + BLOCKING_SYNC = (cydriver.CUevent_sched_flags_enum.CU_EVENT_SCHED_BLOCKING_SYNC, 'Set blocking synchronization as default scheduling') + +class NvclEventFlags(_cyb_FastEnum): + """ + NVCL event scheduling flags + + See `cl_event_flags`. + """ + AUTO = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_AUTO, 'Automatic scheduling') + SPIN = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_SPIN, 'Set spin as default scheduling') + YIELD = (cydriver.cl_event_flags_enum.NVCL_EVENT_SCHED_YIELD, 'Set yield as default scheduling') + 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`. + """ + AUTO = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_AUTO, 'Automatic scheduling') + SPIN = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_SPIN, 'Set spin as default scheduling') + YIELD = (cydriver.cl_context_flags_enum.NVCL_CTX_SCHED_YIELD, 'Set yield as default scheduling') + 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`. + """ + DEFAULT = (cydriver.CUstream_flags_enum.CU_STREAM_DEFAULT, 'Default stream flag') + 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`. + """ + DEFAULT = (cydriver.CUevent_flags_enum.CU_EVENT_DEFAULT, 'Default event flag') + BLOCKING_SYNC = (cydriver.CUevent_flags_enum.CU_EVENT_BLOCKING_SYNC, 'Event uses blocking synchronization') + DISABLE_TIMING = (cydriver.CUevent_flags_enum.CU_EVENT_DISABLE_TIMING, 'Event will not record timing data') + 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`. + """ + DEFAULT = (cydriver.CUevent_record_flags_enum.CU_EVENT_RECORD_DEFAULT, 'Default event record flag') + 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`. + """ + DEFAULT = (cydriver.CUevent_wait_flags_enum.CU_EVENT_WAIT_DEFAULT, 'Default event wait flag') + 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`. + """ + 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.)') + EQ = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_EQ, 'Wait until \\*addr == value.') + AND = (cydriver.CUstreamWaitValue_flags_enum.CU_STREAM_WAIT_VALUE_AND, 'Wait until (\\*addr & value) != 0.') + 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`.') + 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`. + """ + DEFAULT = (cydriver.CUstreamWriteValue_flags_enum.CU_STREAM_WRITE_VALUE_DEFAULT, 'Default behavior') + 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`. + """ + WAIT_VALUE_32 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WAIT_VALUE_32, 'Represents a `cuStreamWaitValue32` operation') + WRITE_VALUE_32 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WRITE_VALUE_32, 'Represents a `cuStreamWriteValue32` operation') + WAIT_VALUE_64 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WAIT_VALUE_64, 'Represents a `cuStreamWaitValue64` operation') + WRITE_VALUE_64 = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_WRITE_VALUE_64, 'Represents a `cuStreamWriteValue64` operation') + BARRIER = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_BARRIER, 'Insert a memory barrier of the specified type') + ATOMIC_REDUCTION = (cydriver.CUstreamBatchMemOpType_enum.CU_STREAM_MEM_OP_ATOMIC_REDUCTION, 'Perform a atomic reduction. See `CUstreamBatchMemOpParams.atomicReduction`') + 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`. + """ + SYS = (cydriver.CUstreamMemoryBarrier_flags_enum.CU_STREAM_MEMORY_BARRIER_TYPE_SYS, 'System-wide memory barrier.') + 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`. + """ + DEFAULT = (cydriver.CUoccupancy_flags_enum.CU_OCCUPANCY_DEFAULT, 'Default behavior') + 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`. + """ + ADD_CAPTURE_DEPENDENCIES = (cydriver.CUstreamUpdateCaptureDependencies_flags_enum.CU_STREAM_ADD_CAPTURE_DEPENDENCIES, 'Add new nodes to the dependency set') + 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`. + """ + 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`. + """ + UNSIGNED_INT8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT8, 'Unsigned 8-bit integers') + UNSIGNED_INT16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT16, 'Unsigned 16-bit integers') + UNSIGNED_INT32 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNSIGNED_INT32, 'Unsigned 32-bit integers') + SIGNED_INT8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT8, 'Signed 8-bit integers') + SIGNED_INT16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT16, 'Signed 16-bit integers') + SIGNED_INT32 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SIGNED_INT32, 'Signed 32-bit integers') + HALF = (cydriver.CUarray_format_enum.CU_AD_FORMAT_HALF, '16-bit floating point') + FLOAT = (cydriver.CUarray_format_enum.CU_AD_FORMAT_FLOAT, '32-bit floating point') + NV12 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_NV12, '8-bit YUV planar format, with 4:2:0 sampling') + UNORM_INT8X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X1, '1 channel unsigned 8-bit normalized integer') + UNORM_INT8X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X2, '2 channel unsigned 8-bit normalized integer') + UNORM_INT8X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT8X4, '4 channel unsigned 8-bit normalized integer') + UNORM_INT16X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X1, '1 channel unsigned 16-bit normalized integer') + UNORM_INT16X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X2, '2 channel unsigned 16-bit normalized integer') + UNORM_INT16X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT16X4, '4 channel unsigned 16-bit normalized integer') + SNORM_INT8X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X1, '1 channel signed 8-bit normalized integer') + SNORM_INT8X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X2, '2 channel signed 8-bit normalized integer') + SNORM_INT8X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT8X4, '4 channel signed 8-bit normalized integer') + SNORM_INT16X1 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X1, '1 channel signed 16-bit normalized integer') + SNORM_INT16X2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X2, '2 channel signed 16-bit normalized integer') + SNORM_INT16X4 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_SNORM_INT16X4, '4 channel signed 16-bit normalized integer') + BC1_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC1_UNORM, '4 channel unsigned normalized block-compressed (BC1 compression) 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') + BC2_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC2_UNORM, '4 channel unsigned normalized block-compressed (BC2 compression) 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') + BC3_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC3_UNORM, '4 channel unsigned normalized block-compressed (BC3 compression) 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') + BC4_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC4_UNORM, '1 channel unsigned normalized block-compressed (BC4 compression) format') + BC4_SNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC4_SNORM, '1 channel signed normalized block-compressed (BC4 compression) format') + BC5_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC5_UNORM, '2 channel unsigned normalized block-compressed (BC5 compression) format') + BC5_SNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC5_SNORM, '2 channel signed normalized block-compressed (BC5 compression) format') + BC6H_UF16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC6H_UF16, '3 channel unsigned half-float block-compressed (BC6H compression) format') + BC6H_SF16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC6H_SF16, '3 channel signed half-float block-compressed (BC6H compression) format') + BC7_UNORM = (cydriver.CUarray_format_enum.CU_AD_FORMAT_BC7_UNORM, '4 channel unsigned normalized block-compressed (BC7 compression) 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') + P010 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P010, '10-bit YUV planar format, with 4:2:0 sampling') + P016 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P016, '16-bit YUV planar format, with 4:2:0 sampling') + NV16 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_NV16, '8-bit YUV planar format, with 4:2:2 sampling') + P210 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P210, '10-bit YUV planar format, with 4:2:2 sampling') + P216 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_P216, '16-bit YUV planar format, with 4:2:2 sampling') + YUY2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_YUY2, '2 channel, 8-bit YUV packed planar format, with 4:2:2 sampling') + Y210 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y210, '2 channel, 10-bit YUV packed planar format, with 4:2:2 sampling') + Y216 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y216, '2 channel, 16-bit YUV packed planar format, with 4:2:2 sampling') + AYUV = (cydriver.CUarray_format_enum.CU_AD_FORMAT_AYUV, '4 channel, 8-bit YUV packed planar format, with 4:4:4 sampling') + Y410 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y410, '10-bit YUV packed planar format, with 4:4:4 sampling') + Y416 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y416, '4 channel, 12-bit YUV packed planar format, with 4:4:4 sampling') + Y444_PLANAR8 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y444_PLANAR8, '3 channel 8-bit YUV planar format, with 4:4:4 sampling') + Y444_PLANAR10 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_Y444_PLANAR10, '3 channel 10-bit YUV planar format, with 4:4:4 sampling') + 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') + 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') + UNORM_INT_101010_2 = (cydriver.CUarray_format_enum.CU_AD_FORMAT_UNORM_INT_101010_2, '4 channel unorm R10G10B10A2 RGB 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + MAX = cydriver.CUarray_format_enum.CU_AD_FORMAT_MAX + +class AddressMode(_cyb_FastEnum): + """ + Texture reference addressing modes + + See `CUaddress_mode`. + """ + WRAP = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_WRAP, 'Wrapping address mode') + CLAMP = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_CLAMP, 'Clamp to edge address mode') + MIRROR = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_MIRROR, 'Mirror address mode') + BORDER = (cydriver.CUaddress_mode_enum.CU_TR_ADDRESS_MODE_BORDER, 'Border address mode') + +class FilterMode(_cyb_FastEnum): + """ + Texture reference filtering modes + + See `CUfilter_mode`. + """ + POINT = (cydriver.CUfilter_mode_enum.CU_TR_FILTER_MODE_POINT, 'Point filter mode') + LINEAR = (cydriver.CUfilter_mode_enum.CU_TR_FILTER_MODE_LINEAR, 'Linear filter mode') + +class DeviceAttribute(_cyb_FastEnum): + """ + Device properties + + See `CUdevice_attribute`. + """ + MAX_THREADS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, 'Maximum number of threads per block') + MAX_BLOCK_DIM_X = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, 'Maximum block dimension X') + MAX_BLOCK_DIM_Y = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, 'Maximum block dimension Y') + MAX_BLOCK_DIM_Z = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, 'Maximum block dimension Z') + MAX_GRID_DIM_X = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, 'Maximum grid dimension X') + MAX_GRID_DIM_Y = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, 'Maximum grid dimension Y') + MAX_GRID_DIM_Z = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, 'Maximum grid dimension Z') + 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') + 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') + 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') + WARP_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_WARP_SIZE, 'Warp size in threads') + MAX_PITCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_PITCH, 'Maximum pitch in bytes allowed by memory copies') + MAX_REGISTERS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, 'Maximum number of 32-bit registers available per block') + REGISTERS_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK') + CLOCK_RATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CLOCK_RATE, 'Typical clock frequency in kilohertz') + TEXTURE_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, 'Alignment requirement for textures') + 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.') + MULTIPROCESSOR_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, 'Number of multiprocessors on device') + KERNEL_EXEC_TIMEOUT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, 'Specifies whether there is a run time limit on kernels') + INTEGRATED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_INTEGRATED, 'Device is integrated with host memory') + CAN_MAP_HOST_MEMORY = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, 'Device can map host memory into CUDA address space') + COMPUTE_MODE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, 'Compute mode (See `CUcomputemode` for details)') + MAXIMUM_TEXTURE1D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH, 'Maximum 1D texture width') + MAXIMUM_TEXTURE2D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH, 'Maximum 2D texture width') + MAXIMUM_TEXTURE2D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT, 'Maximum 2D texture height') + MAXIMUM_TEXTURE3D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH, 'Maximum 3D texture width') + MAXIMUM_TEXTURE3D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT, 'Maximum 3D texture height') + MAXIMUM_TEXTURE3D_DEPTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH, 'Maximum 3D texture depth') + MAXIMUM_TEXTURE2D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH, 'Maximum 2D layered texture width') + MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT, 'Maximum 2D layered texture height') + MAXIMUM_TEXTURE2D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS, 'Maximum layers in a 2D layered texture') + MAXIMUM_TEXTURE2D_ARRAY_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH') + MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT') + MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES, 'Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS') + SURFACE_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT, 'Alignment requirement for surfaces') + CONCURRENT_KERNELS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, 'Device can possibly execute multiple kernels concurrently') + ECC_ENABLED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ECC_ENABLED, 'Device has ECC support enabled') + PCI_BUS_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_BUS_ID, 'PCI bus ID of the device') + PCI_DEVICE_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID, 'PCI device ID of the device') + TCC_DRIVER = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TCC_DRIVER, 'Device is using TCC driver model') + MEMORY_CLOCK_RATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, 'Peak memory clock frequency in kilohertz') + GLOBAL_MEMORY_BUS_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, 'Global memory bus width in bits') + L2_CACHE_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, 'Size of L2 cache in bytes') + MAX_THREADS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, 'Maximum resident threads per multiprocessor') + ASYNC_ENGINE_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, 'Number of asynchronous engines') + UNIFIED_ADDRESSING = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, 'Device shares a unified address space with the host') + MAXIMUM_TEXTURE1D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH, 'Maximum 1D layered texture width') + MAXIMUM_TEXTURE1D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS, 'Maximum layers in a 1D layered texture') + CAN_TEX2D_GATHER = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER, 'Deprecated, do not use.') + 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') + 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') + MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE, 'Alternate maximum 3D texture width') + MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE, 'Alternate maximum 3D texture height') + MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE, 'Alternate maximum 3D texture depth') + PCI_DOMAIN_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID, 'PCI domain ID of the device') + TEXTURE_PITCH_ALIGNMENT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT, 'Pitch alignment requirement for textures') + MAXIMUM_TEXTURECUBEMAP_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH, 'Maximum cubemap texture width/height') + MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH, 'Maximum cubemap layered texture width/height') + MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS, 'Maximum layers in a cubemap layered texture') + MAXIMUM_SURFACE1D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH, 'Maximum 1D surface width') + MAXIMUM_SURFACE2D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH, 'Maximum 2D surface width') + MAXIMUM_SURFACE2D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT, 'Maximum 2D surface height') + MAXIMUM_SURFACE3D_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH, 'Maximum 3D surface width') + MAXIMUM_SURFACE3D_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT, 'Maximum 3D surface height') + MAXIMUM_SURFACE3D_DEPTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH, 'Maximum 3D surface depth') + MAXIMUM_SURFACE1D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH, 'Maximum 1D layered surface width') + MAXIMUM_SURFACE1D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS, 'Maximum layers in a 1D layered surface') + MAXIMUM_SURFACE2D_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH, 'Maximum 2D layered surface width') + MAXIMUM_SURFACE2D_LAYERED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT, 'Maximum 2D layered surface height') + MAXIMUM_SURFACE2D_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS, 'Maximum layers in a 2D layered surface') + MAXIMUM_SURFACECUBEMAP_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH, 'Maximum cubemap surface width') + MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH, 'Maximum cubemap layered surface width') + MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS, 'Maximum layers in a cubemap layered surface') + MAXIMUM_TEXTURE1D_LINEAR_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH, 'Deprecated, do not use. Use cudaDeviceGetTexture1DLinearMaxWidth() or `cuDeviceGetTexture1DLinearMaxWidth()` instead.') + MAXIMUM_TEXTURE2D_LINEAR_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH, 'Maximum 2D linear texture width') + MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT, 'Maximum 2D linear texture height') + MAXIMUM_TEXTURE2D_LINEAR_PITCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH, 'Maximum 2D linear texture pitch in bytes') + MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH, 'Maximum mipmapped 2D texture width') + MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT, 'Maximum mipmapped 2D texture height') + COMPUTE_CAPABILITY_MAJOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, 'Major compute capability version number') + COMPUTE_CAPABILITY_MINOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, 'Minor compute capability version number') + MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH, 'Maximum mipmapped 1D texture width') + STREAM_PRIORITIES_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED, 'Device supports stream priorities') + GLOBAL_L1_CACHE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED, 'Device supports caching globals in L1') + LOCAL_L1_CACHE_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED, 'Device supports caching locals in L1') + 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') + MAX_REGISTERS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR, 'Maximum number of 32-bit registers available per multiprocessor') + MANAGED_MEMORY = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, 'Device can allocate managed memory on this system') + MULTI_GPU_BOARD = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, 'Device is on a multi-GPU board') + 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') + 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') + 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') + PAGEABLE_MEMORY_ACCESS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS, 'Device supports coherently accessing pageable memory without calling cudaHostRegister on it') + CONCURRENT_MANAGED_ACCESS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, 'Device can coherently access managed memory concurrently with the CPU') + COMPUTE_PREEMPTION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, 'Device supports compute preemption.') + 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') + 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.') + 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.') + 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.') + COOPERATIVE_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, 'Device supports launching cooperative kernels via `cuLaunchCooperativeKernel`') + COOPERATIVE_MULTI_DEVICE_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH, 'Deprecated, `cuLaunchCooperativeKernelMultiDevice` is deprecated.') + 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.') + 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.') + HOST_REGISTER_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED, 'Device supports host memory registration via `cudaHostRegister`.') + 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.") + 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.') + VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED, 'Deprecated, Use CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED') + 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') + 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`') + 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`') + 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`') + MAX_BLOCKS_PER_MULTIPROCESSOR = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_BLOCKS_PER_MULTIPROCESSOR, 'Maximum number of blocks per multiprocessor') + GENERIC_COMPRESSION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED, 'Device supports compression of memory') + 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.') + MAX_ACCESS_POLICY_WINDOW_SIZE = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE, 'Maximum value of `CUaccessPolicyWindow.num_bytes`.') + 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`') + 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') + 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') + 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') + TIMELINE_SEMAPHORE_INTEROP_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TIMELINE_SEMAPHORE_INTEROP_SUPPORTED, 'External timeline semaphore interop is supported on the device') + MEMORY_POOLS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED, 'Device supports using the `cuMemAllocAsync` and `cuMemPool` family of APIs') + 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)') + 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') + 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.') + MEMPOOL_SUPPORTED_HANDLE_TYPES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES, 'Handle types supported with mempool based IPC') + CLUSTER_LAUNCH = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_CLUSTER_LAUNCH, 'Indicates device supports cluster launch') + 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') + 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.') + 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.') + DMA_BUF_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED, 'Device supports buffer sharing with dma_buf mechanism.') + IPC_EVENT_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_IPC_EVENT_SUPPORTED, 'Device supports IPC Events.') + MEM_SYNC_DOMAIN_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MEM_SYNC_DOMAIN_COUNT, 'Number of memory domains the device supports.') + TENSOR_MAP_ACCESS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_TENSOR_MAP_ACCESS_SUPPORTED, 'Device supports accessing memory using Tensor Map.') + 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()`') + UNIFIED_FUNCTION_POINTERS = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_UNIFIED_FUNCTION_POINTERS, 'Device supports unified function pointers.') + NUMA_CONFIG = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_NUMA_CONFIG, 'NUMA configuration of a device: value is of type `CUdeviceNumaConfig` enum') + NUMA_ID = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_NUMA_ID, 'NUMA node ID of the GPU memory') + MULTICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MULTICAST_SUPPORTED, 'Device supports switch multicast and reduction operations.') + MPS_ENABLED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MPS_ENABLED, 'Indicates if contexts created on this device will be shared via MPS') + 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.') + D3D12_CIG_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_D3D12_CIG_SUPPORTED, 'Device supports CIG with D3D12.') + 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.') + 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.') + VULKAN_CIG_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_VULKAN_CIG_SUPPORTED, 'Device supports CIG with Vulkan.') + GPU_PCI_DEVICE_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.') + 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.') + 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') + 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') + 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.') + 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') + 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') + 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.') + 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') + ATOMIC_REDUCTION_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_ATOMIC_REDUCTION_SUPPORTED, 'Device supports atomic reduction operations in stream batch memory operations') + LOCALITY_DOMAIN_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOCALITY_DOMAIN_COUNT, 'Number of locality domains') + MAX_OVERSIZED_SHARED_MEMORY_PER_BLOCK = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX_OVERSIZED_SHARED_MEMORY_PER_BLOCK, 'Maximum oversized shared memory per block') + D3D12_CIG_STREAMS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_D3D12_CIG_STREAMS_SUPPORTED, 'Device supports CIG streams with D3D12') + 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') + LOGICAL_ENDPOINT_UNICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_UNICAST_SUPPORTED, 'Device supports unicast logical endpoints') + LOGICAL_ENDPOINT_MULTICAST_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_MULTICAST_SUPPORTED, 'Device supports multicast logical endpoints') + LOGICAL_ENDPOINT_COUNTED_OPS_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_COUNTED_OPS_SUPPORTED, 'Device supports counted operations via logical endpoints') + LOGICAL_ENDPOINT_UNICAST_ACCESS_ON_OWNER_DEVICE_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') + LOCALITY_DOMAIN_MULTIPROCESSOR_COUNT = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOCALITY_DOMAIN_MULTIPROCESSOR_COUNT, 'Number of multiprocessors on each locality domain') + LOGICAL_ENDPOINT_SUPPORTED_HANDLE_TYPES = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_LOGICAL_ENDPOINT_SUPPORTED_HANDLE_TYPES, 'Handle types supported with logical endpoint IPC') + GPU_DIRECT_RDMA_WITH_LOCALIZED_MEMORY_SUPPORTED = (cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_LOCALIZED_MEMORY_SUPPORTED, 'Device supports GPUDirect RDMA with localized memory using the default RDMA mapping link') + MAX = cydriver.CUdevice_attribute_enum.CU_DEVICE_ATTRIBUTE_MAX + +class PointerAttribute(_cyb_FastEnum): + """ + Pointer information + + See `CUpointer_attribute`. + """ + CONTEXT = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_CONTEXT, 'The `CUcontext` on which a pointer was allocated or registered') + MEMORY_TYPE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MEMORY_TYPE, 'The `CUmemorytype` describing the physical location of a pointer') + 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") + 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") + 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') + SYNC_MEMOPS = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, 'Synchronize every synchronous memory operation initiated on this region') + BUFFER_ID = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_BUFFER_ID, 'A process-wide unique ID for an allocated memory region') + IS_MANAGED = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_IS_MANAGED, 'Indicates if the pointer points to managed memory') + 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') + 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') + RANGE_START_ADDR = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_RANGE_START_ADDR, 'Starting address for this requested pointer') + RANGE_SIZE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_RANGE_SIZE, 'Size of the address range for this requested pointer') + 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') + ALLOWED_HANDLE_TYPES = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, 'Bitmask of allowed `CUmemAllocationHandleType` for this allocation') + 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') + 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') + 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.') + MAPPING_SIZE = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MAPPING_SIZE, 'Size of the actual underlying mapping that the pointer belongs to') + MAPPING_BASE_ADDR = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR, 'The start address of the mapping that the pointer belongs to') + 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') + 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.') + LOCALITY_DOMAIN_ORDINAL = (cydriver.CUpointer_attribute_enum.CU_POINTER_ATTRIBUTE_LOCALITY_DOMAIN_ORDINAL, 'Returns in `*data` an integer representing the locality domain ordinal of the memory allocation, or -1 if the allocation is not localized to a locality domain.') + +class FunctionAttribute(_cyb_FastEnum): + """ + Function properties + + See `CUfunction_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.') + 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.') + 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.') + 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.') + NUM_REGS = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_NUM_REGS, 'The number of registers used by each thread of this function.') + 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.') + 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.') + 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 .') + 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`. This attribute is ignored if `CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE` or `CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE` is set. This attribute cannot be used to access oversized shared memory. Oversized shared memory can only be accessed by setting `CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE` or `CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE`. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + 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`') + 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`') + 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`') + 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`') + 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`') + 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`') + 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`') + 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`.') + SHARED_MEMORY_MODE = (cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE, 'The shared memory mode of a function. The value type is `CUsharedMemoryMode` / cudaSharedMemoryMode. See `cuFuncSetAttribute`, `cuKernelSetAttribute`') + MAX = cydriver.CUfunction_attribute_enum.CU_FUNC_ATTRIBUTE_MAX + +class FuncCache(_cyb_FastEnum): + """ + Function cache configurations + + See `CUfunc_cache`. + """ + NONE = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_NONE, 'no preference for shared memory or L1 (default)') + SHARED = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_SHARED, 'prefer larger shared memory and smaller L1 cache') + L1 = (cydriver.CUfunc_cache_enum.CU_FUNC_CACHE_PREFER_L1, 'prefer larger L1 cache and smaller shared memory') + 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`. + """ + DEFAULT_BANK_SIZE = (cydriver.CUsharedconfig_enum.CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE, 'set default shared memory bank size') + FOUR_BYTE_BANK_SIZE = (cydriver.CUsharedconfig_enum.CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE, 'set shared memory bank width to four bytes') + 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`. + """ + DEFAULT = (cydriver.CUshared_carveout_enum.CU_SHAREDMEM_CARVEOUT_DEFAULT, 'No preference for shared memory or L1 (default)') + MAX_SHARED = (cydriver.CUshared_carveout_enum.CU_SHAREDMEM_CARVEOUT_MAX_SHARED, 'Prefer maximum available shared memory, minimum L1 cache') + 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`. + """ + HOST = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_HOST, 'Host memory') + DEVICE = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_DEVICE, 'Device memory') + ARRAY = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_ARRAY, 'Array memory') + UNIFIED = (cydriver.CUmemorytype_enum.CU_MEMORYTYPE_UNIFIED, 'Unified device or host memory') + +class ComputeMode(_cyb_FastEnum): + """ + Compute Modes + + See `CUcomputemode`. + """ + DEFAULT = (cydriver.CUcomputemode_enum.CU_COMPUTEMODE_DEFAULT, 'Default compute mode (Multiple contexts allowed per device)') + PROHIBITED = (cydriver.CUcomputemode_enum.CU_COMPUTEMODE_PROHIBITED, 'Compute-prohibited mode (No contexts can be created on this device at this time)') + 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`. + """ + SET_READ_MOSTLY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_SET_READ_MOSTLY, 'Data will mostly be read and only occasionally be written to') + UNSET_READ_MOSTLY = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_UNSET_READ_MOSTLY, 'Undo the effect of `CU_MEM_ADVISE_SET_READ_MOSTLY`') + SET_PREFERRED_LOCATION = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_SET_PREFERRED_LOCATION, 'Set the preferred location for the data as the specified device') + UNSET_PREFERRED_LOCATION = (cydriver.CUmem_advise_enum.CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION, 'Clear the preferred location for the data') + 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') + 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`. + """ + 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') + PREFERRED_LOCATION = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION, 'The preferred location of the range') + 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') + LAST_PREFETCH_LOCATION = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION, 'The last location to which the range was prefetched') + PREFERRED_LOCATION_TYPE = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE, 'The preferred location type of the range') + PREFERRED_LOCATION_ID = (cydriver.CUmem_range_attribute_enum.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID, 'The preferred location id of the range') + 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') + 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`. + """ + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + NEW_SM3X_OPT = (cydriver.CUjit_option_enum.CU_JIT_NEW_SM3X_OPT, '[Deprecated]') + FAST_COMPILE = (cydriver.CUjit_option_enum.CU_JIT_FAST_COMPILE, 'This jit option is used for internal purpose only.') + 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') + 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') + 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') + LTO = (cydriver.CUjit_option_enum.CU_JIT_LTO, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + FTZ = (cydriver.CUjit_option_enum.CU_JIT_FTZ, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + PREC_DIV = (cydriver.CUjit_option_enum.CU_JIT_PREC_DIV, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + PREC_SQRT = (cydriver.CUjit_option_enum.CU_JIT_PREC_SQRT, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + FMA = (cydriver.CUjit_option_enum.CU_JIT_FMA, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + NUM_OPTIONS = cydriver.CUjit_option_enum.CU_JIT_NUM_OPTIONS + +class JitTarget(_cyb_FastEnum): + """ + Online compilation targets + + See `CUjit_target`. + """ + TARGET_COMPUTE_30 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_30, 'Compute device class 3.0') + TARGET_COMPUTE_32 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_32, 'Compute device class 3.2') + TARGET_COMPUTE_35 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_35, 'Compute device class 3.5') + TARGET_COMPUTE_37 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_37, 'Compute device class 3.7') + TARGET_COMPUTE_50 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_50, 'Compute device class 5.0') + TARGET_COMPUTE_52 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_52, 'Compute device class 5.2') + TARGET_COMPUTE_53 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_53, 'Compute device class 5.3') + TARGET_COMPUTE_60 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_60, 'Compute device class 6.0.') + TARGET_COMPUTE_61 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_61, 'Compute device class 6.1.') + TARGET_COMPUTE_62 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_62, 'Compute device class 6.2.') + TARGET_COMPUTE_70 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_70, 'Compute device class 7.0.') + TARGET_COMPUTE_72 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_72, 'Compute device class 7.2.') + TARGET_COMPUTE_75 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_75, 'Compute device class 7.5.') + TARGET_COMPUTE_80 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_80, 'Compute device class 8.0.') + TARGET_COMPUTE_86 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_86, 'Compute device class 8.6.') + TARGET_COMPUTE_87 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_87, 'Compute device class 8.7.') + TARGET_COMPUTE_89 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_89, 'Compute device class 8.9.') + TARGET_COMPUTE_90 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_90, 'Compute device class 9.0.') + TARGET_COMPUTE_100 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100, 'Compute device class 10.0.') + TARGET_COMPUTE_110 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110, 'Compute device class 11.0.') + TARGET_COMPUTE_103 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103, 'Compute device class 10.3.') + TARGET_COMPUTE_107 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_107, 'Compute device class 10.7.') + TARGET_COMPUTE_120 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120, 'Compute device class 12.0.') + TARGET_COMPUTE_121 = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121, 'Compute device class 12.1. Compute device class 9.0. with accelerated features.') + TARGET_COMPUTE_90A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_90A, 'Compute device class 10.0. with accelerated features.') + TARGET_COMPUTE_100A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100A, 'Compute device class 11.0 with accelerated features.') + TARGET_COMPUTE_110A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110A, 'Compute device class 10.3. with accelerated features.') + TARGET_COMPUTE_103A = cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103A + TARGET_COMPUTE_107A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_107A, 'Compute device class 12.0. with accelerated features.') + TARGET_COMPUTE_120A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120A, 'Compute device class 12.1. with accelerated features.') + TARGET_COMPUTE_121A = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121A, 'Compute device class 10.x with family features.') + TARGET_COMPUTE_100F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_100F, 'Compute device class 11.0 with family features.') + TARGET_COMPUTE_110F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_110F, 'Compute device class 10.3. with family features.') + TARGET_COMPUTE_103F = cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_103F + TARGET_COMPUTE_107F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_107F, 'Compute device class 12.0. with family features.') + TARGET_COMPUTE_120F = (cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_120F, 'Compute device class 12.1. with family features.') + TARGET_COMPUTE_121F = cydriver.CUjit_target_enum.CU_TARGET_COMPUTE_121F + +class JitFallback(_cyb_FastEnum): + """ + Cubin matching fallback strategies + + See `CUjit_fallback`. + """ + PTX = (cydriver.CUjit_fallback_enum.CU_PREFER_PTX, 'Prefer to compile ptx if exact binary match not found') + 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`. + """ + NONE = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_NONE, 'Compile with no -dlcm flag specified') + CG = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_CG, 'Compile with L1 cache disabled') + CA = (cydriver.CUjit_cacheMode_enum.CU_JIT_CACHE_OPTION_CA, 'Compile with L1 cache enabled') + +class JitInputType(_cyb_FastEnum): + """ + Device code formats + + See `CUjitInputType`. + """ + INPUT_CUBIN = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_CUBIN, 'Compiled device-class-specific device code Applicable options: none') + INPUT_PTX = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_PTX, 'PTX source code Applicable options: PTX compiler options') + 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`') + INPUT_OBJECT = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_OBJECT, 'Host object with embedded device code Applicable options: PTX compiler options, `CU_JIT_FALLBACK_STRATEGY`') + 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`') + INPUT_NVVM = (cydriver.CUjitInputType_enum.CU_JIT_INPUT_NVVM, '[Deprecated] Only valid with LTO-IR compiled with toolkits prior to CUDA 12.0') + NUM_INPUT_TYPES = cydriver.CUjitInputType_enum.CU_JIT_NUM_INPUT_TYPES + +class GraphicsRegisterFlags(_cyb_FastEnum): + """ + Flags to register a graphics resource + + See `CUgraphicsRegisterFlags`. + """ + NONE = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_NONE + READ_ONLY = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY + WRITE_DISCARD = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD + SURFACE_LDST = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST + TEXTURE_GATHER = cydriver.CUgraphicsRegisterFlags_enum.CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER + +class GraphicsMapResourceFlags(_cyb_FastEnum): + """ + Flags for mapping and unmapping interop resources + + See `CUgraphicsMapResourceFlags`. + """ + NONE = cydriver.CUgraphicsMapResourceFlags_enum.CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE + READ_ONLY = cydriver.CUgraphicsMapResourceFlags_enum.CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY + 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`. + """ + POSITIVE_X = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_X, 'Positive X face of cubemap') + NEGATIVE_X = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_X, 'Negative X face of cubemap') + POSITIVE_Y = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_Y, 'Positive Y face of cubemap') + NEGATIVE_Y = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_Y, 'Negative Y face of cubemap') + POSITIVE_Z = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_POSITIVE_Z, 'Positive Z face of cubemap') + NEGATIVE_Z = (cydriver.CUarray_cubemap_face_enum.CU_CUBEMAP_FACE_NEGATIVE_Z, 'Negative Z face of cubemap') + +class Limit(_cyb_FastEnum): + """ + Limits + + See `CUlimit`. + """ + STACK_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_STACK_SIZE, 'GPU thread stack size') + PRINTF_FIFO_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_PRINTF_FIFO_SIZE, 'GPU printf FIFO size') + MALLOC_HEAP_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_MALLOC_HEAP_SIZE, 'GPU malloc heap size') + DEV_RUNTIME_SYNC_DEPTH = (cydriver.CUlimit_enum.CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH, 'GPU device runtime launch synchronize depth') + DEV_RUNTIME_PENDING_LAUNCH_COUNT = (cydriver.CUlimit_enum.CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT, 'GPU device runtime pending launch count') + 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') + PERSISTING_L2_CACHE_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_PERSISTING_L2_CACHE_SIZE, 'A size in bytes for L2 persisting lines cache size') + 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') + 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') + 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') + PER_BLOCK_MEMORY_SIZE = (cydriver.CUlimit_enum.CU_LIMIT_PER_BLOCK_MEMORY_SIZE, 'Per-block memory size') + MAX = cydriver.CUlimit_enum.CU_LIMIT_MAX + +class ResourceType(_cyb_FastEnum): + """ + Resource types + + See `CUresourcetype`. + """ + ARRAY = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_ARRAY, 'Array resource') + MIPMAPPED_ARRAY = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_MIPMAPPED_ARRAY, 'Mipmapped array resource') + LINEAR = (cydriver.CUresourcetype_enum.CU_RESOURCE_TYPE_LINEAR, 'Linear resource') + 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`. + """ + NORMAL = (cydriver.CUaccessProperty_enum.CU_ACCESS_PROPERTY_NORMAL, 'Normal cache persistence.') + STREAMING = (cydriver.CUaccessProperty_enum.CU_ACCESS_PROPERTY_STREAMING, 'Streaming access is less likely to persit from cache.') + 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`. + """ + 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.") + WHILE = (cydriver.CUgraphConditionalNodeType_enum.CU_GRAPH_COND_TYPE_WHILE, "Conditional 'while' Node. Body executed repeatedly while condition value is non-zero.") + 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`. + """ + KERNEL = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_KERNEL, 'GPU kernel node') + MEMCPY = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEMCPY, 'Memcpy node') + MEMSET = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEMSET, 'Memset node') + HOST = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_HOST, 'Host (executable) node') + GRAPH = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_GRAPH, 'Node which executes an embedded graph') + EMPTY = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EMPTY, 'Empty (no-op) node') + WAIT_EVENT = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_WAIT_EVENT, 'External event wait node') + EVENT_RECORD = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EVENT_RECORD, 'External event record node') + EXT_SEMAS_SIGNAL = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL, 'External semaphore signal node') + EXT_SEMAS_WAIT = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT, 'External semaphore wait node') + MEM_ALLOC = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEM_ALLOC, 'Memory Allocation Node') + MEM_FREE = (cydriver.CUgraphNodeType_enum.CU_GRAPH_NODE_TYPE_MEM_FREE, 'Memory Free Node') + 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.') + 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.') + 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`. + """ + DEFAULT = (cydriver.CUgraphDependencyType_enum.CU_GRAPH_DEPENDENCY_TYPE_DEFAULT, 'This is an ordinary dependency.') + 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`. + """ + SUCCESS = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_SUCCESS, 'Instantiation succeeded') + ERROR = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_ERROR, 'Instantiation failed for an unexpected reason which is described in the return value of the function') + INVALID_STRUCTURE = (cydriver.CUgraphInstantiateResult_enum.CUDA_GRAPH_INSTANTIATE_INVALID_STRUCTURE, 'Instantiation failed due to invalid structure, such as cycles') + 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') + 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') + 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`. + """ + AUTO = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_AUTO + SPIN = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_SPIN + YIELD = cydriver.CUsynchronizationPolicy_enum.CU_SYNC_POLICY_YIELD + 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`. + """ + DEFAULT = (cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_DEFAULT, 'the default policy') + SPREAD = (cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_SPREAD, 'spread the blocks within a cluster to the SMs') + 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') + RUBIN_DSMEM_LOCALITY = cydriver.CUclusterSchedulingPolicy_enum.CU_CLUSTER_SCHEDULING_POLICY_RUBIN_DSMEM_LOCALITY + +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`. + """ + DEFAULT = (cydriver.CUlaunchMemSyncDomain_enum.CU_LAUNCH_MEM_SYNC_DOMAIN_DEFAULT, 'Launch kernels in the default domain') + 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`. + """ + IGNORE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_IGNORE, 'Ignored entry, for convenient composition') + ACCESS_POLICY_WINDOW = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.accessPolicyWindow`.') + COOPERATIVE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_COOPERATIVE, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.cooperative`.') + SYNCHRONIZATION_POLICY = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY, 'Valid for streams. See `CUlaunchAttributeValue.syncPolicy`.') + CLUSTER_DIMENSION = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.clusterDim`.') + CLUSTER_SCHEDULING_POLICY_PREFERENCE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE, 'Valid for graph nodes, launches. See `CUlaunchAttributeValue.clusterSchedulingPolicyPreference`.') + 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).") + 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).") + PRIORITY = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_PRIORITY, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.priority`.') + MEM_SYNC_DOMAIN_MAP = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN_MAP, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.memSyncDomainMap`.') + MEM_SYNC_DOMAIN = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_MEM_SYNC_DOMAIN, 'Valid for streams, graph nodes, launches. See `CUlaunchAttributeValue.memSyncDomain`.') + 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.') + 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).') + 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.") + 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.') + 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).") + 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`') + SHARED_MEMORY_MODE = (cydriver.CUlaunchAttributeID_enum.CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE, "Valid for graph nodes, launches. This controls a kernel's use of non-portable or oversized shared memory configurations.") + +class StreamCaptureStatus(_cyb_FastEnum): + """ + Possible stream capture statuses returned by `cuStreamIsCapturing` + + See `CUstreamCaptureStatus`. + """ + NONE = (cydriver.CUstreamCaptureStatus_enum.CU_STREAM_CAPTURE_STATUS_NONE, 'Stream is not capturing') + ACTIVE = (cydriver.CUstreamCaptureStatus_enum.CU_STREAM_CAPTURE_STATUS_ACTIVE, 'Stream is actively capturing') + 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`. + """ + GLOBAL = cydriver.CUstreamCaptureMode_enum.CU_STREAM_CAPTURE_MODE_GLOBAL + THREAD_LOCAL = cydriver.CUstreamCaptureMode_enum.CU_STREAM_CAPTURE_MODE_THREAD_LOCAL + 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`. + """ + DEFAULT = (cydriver.CUdriverProcAddress_flags_enum.CU_GET_PROC_ADDRESS_DEFAULT, 'Default search mode for driver symbols.') + LEGACY_STREAM = (cydriver.CUdriverProcAddress_flags_enum.CU_GET_PROC_ADDRESS_LEGACY_STREAM, 'Search for legacy versions of driver symbols.') + 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`. + """ + SUCCESS = (cydriver.CUdriverProcAddressQueryResult_enum.CU_GET_PROC_ADDRESS_SUCCESS, 'Symbol was succesfully found') + SYMBOL_NOT_FOUND = (cydriver.CUdriverProcAddressQueryResult_enum.CU_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND, 'Symbol was not found in search') + 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`. + """ + SM_COUNT = (cydriver.CUexecAffinityType_enum.CU_EXEC_AFFINITY_TYPE_SM_COUNT, 'Create a context with limited SMs.') + 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`. + """ + HOST_UNIVERSAL_FUNCTION_AND_DATA_TABLE = cydriver.CUlibraryOption_enum.CU_LIBRARY_HOST_UNIVERSAL_FUNCTION_AND_DATA_TABLE + 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`.') + NUM_OPTIONS = cydriver.CUlibraryOption_enum.CU_LIBRARY_NUM_OPTIONS + +class Result(_cyb_FastEnum): + """ + Error codes + + See `CUresult`. + """ + 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()`).') + 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.') + 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.') + 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.') + ERROR_DEINITIALIZED = (cydriver.cudaError_enum.CUDA_ERROR_DEINITIALIZED, 'This indicates that the CUDA driver is in the process of shutting down.') + 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.') + ERROR_PROFILER_NOT_INITIALIZED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_NOT_INITIALIZED, '[Deprecated]') + ERROR_PROFILER_ALREADY_STARTED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_ALREADY_STARTED, '[Deprecated]') + ERROR_PROFILER_ALREADY_STOPPED = (cydriver.cudaError_enum.CUDA_ERROR_PROFILER_ALREADY_STOPPED, '[Deprecated]') + 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.') + 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.') + 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`.') + ERROR_MULTICAST_RESOURCE_FULL = (cydriver.cudaError_enum.CUDA_ERROR_MULTICAST_RESOURCE_FULL, 'The API call failed because of a hardware resource required to bind memory to a multicast object is unavailable.') + ERROR_NO_DEVICE = (cydriver.cudaError_enum.CUDA_ERROR_NO_DEVICE, 'This indicates that no CUDA-capable devices were detected by the installed CUDA driver.') + 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.') + ERROR_DEVICE_NOT_LICENSED = (cydriver.cudaError_enum.CUDA_ERROR_DEVICE_NOT_LICENSED, 'This error indicates that the Grid license is not applied.') + 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.') + 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.') + 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]') + ERROR_MAP_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_MAP_FAILED, 'This indicates that a map or register operation has failed.') + ERROR_UNMAP_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_UNMAP_FAILED, 'This indicates that an unmap or unregister operation has failed.') + 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.') + ERROR_ALREADY_MAPPED = (cydriver.cudaError_enum.CUDA_ERROR_ALREADY_MAPPED, 'This indicates that the resource is already mapped.') + 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.') + ERROR_ALREADY_ACQUIRED = (cydriver.cudaError_enum.CUDA_ERROR_ALREADY_ACQUIRED, 'This indicates that a resource has already been acquired.') + ERROR_NOT_MAPPED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_MAPPED, 'This indicates that a resource is not mapped.') + 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.') + 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.') + ERROR_ECC_UNCORRECTABLE = (cydriver.cudaError_enum.CUDA_ERROR_ECC_UNCORRECTABLE, 'This indicates that an uncorrectable ECC error was detected during execution.') + 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.') + 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.') + ERROR_PEER_ACCESS_UNSUPPORTED = (cydriver.cudaError_enum.CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, 'This indicates that peer access is not supported across the given devices.') + ERROR_INVALID_PTX = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_PTX, 'This indicates that a PTX JIT compilation failed.') + ERROR_INVALID_GRAPHICS_CONTEXT = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT, 'This indicates an error with OpenGL or DirectX context.') + ERROR_NVLINK_UNCORRECTABLE = (cydriver.cudaError_enum.CUDA_ERROR_NVLINK_UNCORRECTABLE, 'This indicates that an uncorrectable NVLink error was detected during the execution.') + 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.') + ERROR_UNSUPPORTED_PTX_VERSION = (cydriver.cudaError_enum.CUDA_ERROR_UNSUPPORTED_PTX_VERSION, 'This indicates that the provided PTX was compiled with an unsupported toolchain.') + ERROR_JIT_COMPILATION_DISABLED = (cydriver.cudaError_enum.CUDA_ERROR_JIT_COMPILATION_DISABLED, 'This indicates that the PTX JIT compilation was disabled.') + 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.') + 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.') + 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.") + ERROR_INSUFFICIENT_LOADER_VERSION = (cydriver.cudaError_enum.CUDA_ERROR_INSUFFICIENT_LOADER_VERSION, 'This indicates that the Loader version is insufficient for fatbin') + 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.') + ERROR_FILE_NOT_FOUND = (cydriver.cudaError_enum.CUDA_ERROR_FILE_NOT_FOUND, 'This indicates that the file specified was not found.') + 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.') + ERROR_SHARED_OBJECT_INIT_FAILED = (cydriver.cudaError_enum.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, 'This indicates that initialization of a shared object failed.') + ERROR_OPERATING_SYSTEM = (cydriver.cudaError_enum.CUDA_ERROR_OPERATING_SYSTEM, 'This indicates that an OS call failed.') + 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`.') + 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.') + 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.') + 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.') + 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()`.') + 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.') + 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.") + 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.') + ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = (cydriver.cudaError_enum.CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, 'This error indicates a kernel launch that uses an incompatible texturing mode.') + 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.') + 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()`.') + 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.') + 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.') + 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.') + 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()`.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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`.') + 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.') + ERROR_NOT_PERMITTED = (cydriver.cudaError_enum.CUDA_ERROR_NOT_PERMITTED, 'This error indicates that the attempted operation is not permitted.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + ERROR_STREAM_CAPTURE_UNMATCHED = (cydriver.cudaError_enum.CUDA_ERROR_STREAM_CAPTURE_UNMATCHED, 'This error indicates that the capture was not initiated in this stream.') + 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.') + 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.') + 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.') + 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.') + 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.') + ERROR_TIMEOUT = (cydriver.cudaError_enum.CUDA_ERROR_TIMEOUT, 'This error indicates that the timeout specified for the wait operation has lapsed.') + 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.') + 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.") + ERROR_INVALID_CLUSTER_SIZE = (cydriver.cudaError_enum.CUDA_ERROR_INVALID_CLUSTER_SIZE, 'Indicates a kernel launch error due to cluster misconfiguration.') + 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.') + 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.') + 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.') + ERROR_KEY_ROTATION = (cydriver.cudaError_enum.CUDA_ERROR_KEY_ROTATION, 'This error indicates that an error happened during the key rotation sequence.') + 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.") + 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.') + ERROR_FABRIC_NOT_READY = (cydriver.cudaError_enum.CUDA_ERROR_FABRIC_NOT_READY, 'The GPU fabric is not ready within the bounded wait while the fabric manager probe is still in progress (or not converging in time). Applications may retry after a delay; for the initialization wait budget, see environment variables such as CUDA_FABRIC_INIT_TIMEOUT_MS. The CUDA Runtime uses the same value as `cudaErrorFabricNotReady`.') + 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`. + """ + PERFORMANCE_RANK = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK, 'A relative value indicating the performance of the link between two devices') + ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED, 'P2P Access is enable') + NATIVE_ATOMIC_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED, 'All CUDA-valid atomic operation over the link are supported') + ACCESS_ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED, '[Deprecated]') + CUDA_ARRAY_ACCESS_SUPPORTED = (cydriver.CUdevice_P2PAttribute_enum.CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED, 'Accessing CUDA arrays over the link supported') + 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`. + """ + NONE = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_NONE, 'No resource view format (use underlying resource format)') + UINT_1X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X8, '1 channel unsigned 8-bit integers') + UINT_2X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X8, '2 channel unsigned 8-bit integers') + UINT_4X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X8, '4 channel unsigned 8-bit integers') + SINT_1X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X8, '1 channel signed 8-bit integers') + SINT_2X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X8, '2 channel signed 8-bit integers') + SINT_4X8 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X8, '4 channel signed 8-bit integers') + UINT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X16, '1 channel unsigned 16-bit integers') + UINT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X16, '2 channel unsigned 16-bit integers') + UINT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X16, '4 channel unsigned 16-bit integers') + SINT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X16, '1 channel signed 16-bit integers') + SINT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X16, '2 channel signed 16-bit integers') + SINT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X16, '4 channel signed 16-bit integers') + UINT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_1X32, '1 channel unsigned 32-bit integers') + UINT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_2X32, '2 channel unsigned 32-bit integers') + UINT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UINT_4X32, '4 channel unsigned 32-bit integers') + SINT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_1X32, '1 channel signed 32-bit integers') + SINT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_2X32, '2 channel signed 32-bit integers') + SINT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SINT_4X32, '4 channel signed 32-bit integers') + FLOAT_1X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_1X16, '1 channel 16-bit floating point') + FLOAT_2X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_2X16, '2 channel 16-bit floating point') + FLOAT_4X16 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_4X16, '4 channel 16-bit floating point') + FLOAT_1X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_1X32, '1 channel 32-bit floating point') + FLOAT_2X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_2X32, '2 channel 32-bit floating point') + FLOAT_4X32 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_FLOAT_4X32, '4 channel 32-bit floating point') + UNSIGNED_BC1 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC1, 'Block compressed 1') + UNSIGNED_BC2 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC2, 'Block compressed 2') + UNSIGNED_BC3 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC3, 'Block compressed 3') + UNSIGNED_BC4 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC4, 'Block compressed 4 unsigned') + SIGNED_BC4 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC4, 'Block compressed 4 signed') + UNSIGNED_BC5 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC5, 'Block compressed 5 unsigned') + SIGNED_BC5 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC5, 'Block compressed 5 signed') + UNSIGNED_BC6H = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC6H, 'Block compressed 6 unsigned half-float') + SIGNED_BC6H = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_SIGNED_BC6H, 'Block compressed 6 signed half-float') + UNSIGNED_BC7 = (cydriver.CUresourceViewFormat_enum.CU_RES_VIEW_FORMAT_UNSIGNED_BC7, 'Block compressed 7') + +class TensorMapDataType(_cyb_FastEnum): + """ + Tensor map data type + + See `CUtensorMapDataType`. + """ + TENSOR_MAP_DATA_TYPE_UINT8 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT8 + TENSOR_MAP_DATA_TYPE_UINT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT16 + TENSOR_MAP_DATA_TYPE_UINT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT32 + TENSOR_MAP_DATA_TYPE_INT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_INT32 + TENSOR_MAP_DATA_TYPE_UINT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_UINT64 + TENSOR_MAP_DATA_TYPE_INT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_INT64 + TENSOR_MAP_DATA_TYPE_FLOAT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT16 + TENSOR_MAP_DATA_TYPE_FLOAT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT32 + TENSOR_MAP_DATA_TYPE_FLOAT64 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT64 + TENSOR_MAP_DATA_TYPE_BFLOAT16 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_BFLOAT16 + TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_FLOAT32_FTZ + TENSOR_MAP_DATA_TYPE_TFLOAT32 = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_TFLOAT32 + TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_TFLOAT32_FTZ + TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN8B + TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U4_ALIGN16B + TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B = cydriver.CUtensorMapDataType_enum.CU_TENSOR_MAP_DATA_TYPE_16U6_ALIGN16B + +class TensorMapInterleave(_cyb_FastEnum): + """ + Tensor map interleave layout type + + See `CUtensorMapInterleave`. + """ + TENSOR_MAP_INTERLEAVE_NONE = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_NONE + TENSOR_MAP_INTERLEAVE_16B = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_16B + TENSOR_MAP_INTERLEAVE_32B = cydriver.CUtensorMapInterleave_enum.CU_TENSOR_MAP_INTERLEAVE_32B + +class TensorMapSwizzle(_cyb_FastEnum): + """ + Tensor map swizzling mode of shared memory banks + + See `CUtensorMapSwizzle`. + """ + TENSOR_MAP_SWIZZLE_NONE = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_NONE + TENSOR_MAP_SWIZZLE_32B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_32B + TENSOR_MAP_SWIZZLE_64B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_64B + TENSOR_MAP_SWIZZLE_128B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B + TENSOR_MAP_SWIZZLE_128B_ATOM_32B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B + TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_32B_FLIP_8B + TENSOR_MAP_SWIZZLE_128B_ATOM_64B = cydriver.CUtensorMapSwizzle_enum.CU_TENSOR_MAP_SWIZZLE_128B_ATOM_64B + +class TensorMapL2Promotion(_cyb_FastEnum): + """ + Tensor map L2 promotion type + + See `CUtensorMapL2promotion`. + """ + NONE = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_NONE + L2_64B = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_L2_64B + L2_128B = cydriver.CUtensorMapL2promotion_enum.CU_TENSOR_MAP_L2_PROMOTION_L2_128B + 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`. + """ + NONE = cydriver.CUtensorMapFloatOOBfill_enum.CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE + 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`. + """ + W = cydriver.CUtensorMapIm2ColWideMode_enum.CU_TENSOR_MAP_IM2COL_WIDE_MODE_W + 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`. + """ + 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') + 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.') + 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`. + """ + OPAQUE_FD = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD, 'Handle is an opaque file descriptor') + OPAQUE_WIN32 = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32, 'Handle is an opaque shared NT handle') + OPAQUE_WIN32_KMT = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT, 'Handle is an opaque, globally shared handle') + D3D12_HEAP = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP, 'Handle is a D3D12 heap object') + D3D12_RESOURCE = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE, 'Handle is a D3D12 committed resource') + D3D11_RESOURCE = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE, 'Handle is a shared NT handle to a D3D11 resource') + D3D11_RESOURCE_KMT = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT, 'Handle is a globally shared handle to a D3D11 resource') + NVSCIBUF = (cydriver.CUexternalMemoryHandleType_enum.CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, 'Handle is an NvSciBuf object') + 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`. + """ + OPAQUE_FD = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, 'Handle is an opaque file descriptor') + OPAQUE_WIN32 = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, 'Handle is an opaque shared NT handle') + OPAQUE_WIN32_KMT = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT, 'Handle is an opaque, globally shared handle') + D3D12_FENCE = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, 'Handle is a shared NT handle referencing a D3D12 fence object') + D3D11_FENCE = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, 'Handle is a shared NT handle referencing a D3D11 fence object') + NVSCISYNC = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, 'Opaque handle to NvSciSync Object') + 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') + 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') + TIMELINE_SEMAPHORE_FD = (cydriver.CUexternalSemaphoreHandleType_enum.CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, 'Handle is an opaque file descriptor referencing a timeline semaphore') + 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`. + """ + NONE = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_NONE, 'Does not allow any export mechanism. >') + 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)') + WIN32 = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_WIN32, 'Allows a Win32 NT handle to be used for exporting. (HANDLE)') + WIN32_KMT = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_WIN32_KMT, 'Allows a Win32 KMT handle to be used for exporting. (D3DKMT_HANDLE)') + FABRIC = (cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_FABRIC, 'Allows a fabric handle to be used for exporting. (`CUmemFabricHandle`)') + MAX = cydriver.CUmemAllocationHandleType_enum.CU_MEM_HANDLE_TYPE_MAX + +class MemAccessFlags(_cyb_FastEnum): + """ + Specifies the memory protection flags for mapping. + + See `CUmemAccess_flags`. + """ + NONE = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_NONE, 'Default, make the address range not accessible') + READ = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_READ, 'Make the address range read accessible') + READWRITE = (cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_READWRITE, 'Make the address range read-write accessible') + MAX = cydriver.CUmemAccess_flags_enum.CU_MEM_ACCESS_FLAGS_PROT_MAX + +class MemLocationType(_cyb_FastEnum): + """ + Specifies the type of location + + See `CUmemLocationType`. + """ + INVALID = cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_INVALID + 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') + DEVICE = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_DEVICE, 'Location is a device location, thus id is a device ordinal') + HOST = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_HOST, 'Location is host, id is ignored') + 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') + 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') + INVISIBLE = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_INVISIBLE, 'Location is not visible but device is accessible, id is always CU_DEVICE_INVALID') + DEVICE_LOCALITY_DOMAIN = (cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN, 'Location is a portion of device memory, specified by the locality domain ID.') + MAX = cydriver.CUmemLocationType_enum.CU_MEM_LOCATION_TYPE_MAX + +class MemAllocationType(_cyb_FastEnum): + """ + Defines the allocation types available + + See `CUmemAllocationType`. + """ + INVALID = cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_INVALID + 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") + MANAGED = (cydriver.CUmemAllocationType_enum.CU_MEM_ALLOCATION_TYPE_MANAGED, 'This allocation type is managed memory') + 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`. + """ + MINIMUM = (cydriver.CUmemAllocationGranularity_flags_enum.CU_MEM_ALLOC_GRANULARITY_MINIMUM, 'Minimum required granularity for allocation') + 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`. + """ + DMA_BUF_FD = cydriver.CUmemRangeHandleType_enum.CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD + MAX = cydriver.CUmemRangeHandleType_enum.CU_MEM_RANGE_HANDLE_TYPE_MAX + +class MemRangeFlags(_cyb_FastEnum): + """ + Flag for requesting handle type for address range. + + See `CUmemRangeFlags`. + """ + 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`. + """ + SPARSE_LEVEL = cydriver.CUarraySparseSubresourceType_enum.CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL + MIPTAIL = cydriver.CUarraySparseSubresourceType_enum.CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL + +class MemOperationType(_cyb_FastEnum): + """ + Memory operation types + + See `CUmemOperationType`. + """ + MAP = cydriver.CUmemOperationType_enum.CU_MEM_OPERATION_TYPE_MAP + UNMAP = cydriver.CUmemOperationType_enum.CU_MEM_OPERATION_TYPE_UNMAP + +class MemHandleType(_cyb_FastEnum): + """ + Memory handle types + + See `CUmemHandleType`. + """ + GENERIC = cydriver.CUmemHandleType_enum.CU_MEM_HANDLE_TYPE_GENERIC + +class MemAllocationCompType(_cyb_FastEnum): + """ + Specifies compression attribute for an allocation. + + See `CUmemAllocationCompType`. + """ + NONE = (cydriver.CUmemAllocationCompType_enum.CU_MEM_ALLOCATION_COMP_NONE, 'Allocating non-compressible memory') + 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`. + """ + MINIMUM = (cydriver.CUmulticastGranularity_flags_enum.CU_MULTICAST_GRANULARITY_MINIMUM, 'Minimum required 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`. + """ + SUCCESS = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_SUCCESS, 'The update succeeded') + 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') + ERROR_TOPOLOGY_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED, 'The update failed because the topology changed') + ERROR_NODE_TYPE_CHANGED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED, 'The update failed because a node type changed') + 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)') + 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') + ERROR_NOT_SUPPORTED = (cydriver.CUgraphExecUpdateResult_enum.CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED, 'The update failed because something about the node is not supported') + 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') + 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`. + """ + 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)') + 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)') + 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).') + 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)') + 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.') + 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.') + 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.') + 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.') + ALLOCATION_TYPE = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_ALLOCATION_TYPE, '(value type = `CUmemAllocationType`) The allocation type of the mempool') + 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') + 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.') + 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.') + 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.') + HW_DECOMPRESS_ENABLED = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED, '(value type = int) Indicates whether the pool has hardware compresssion enabled') + LOCALITY_DOMAIN_ID = (cydriver.CUmemPool_attribute_enum.CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID, '(value type = int) The locality domain ID for the mempool, if the mempool is localized to a locality domain. A value of -1 indicates that the mempool is not localized. Note: On devices with a single locality domain, mempools created with `CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN` and localityDomainId 0 are equivalent to full-device mempools created with `CU_MEM_LOCATION_TYPE_DEVICE`. The value of this attribute will be -1 for such mempools.') + +class MemCpyFlags(_cyb_FastEnum): + """ + Flags to specify for copies within a batch. For more details see + `cuMemcpyBatchAsync`. + + See `CUmemcpyFlags`. + """ + DEFAULT = cydriver.CUmemcpyFlags_enum.CU_MEMCPY_FLAG_DEFAULT + 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`. + """ + INVALID = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_INVALID, 'Default invalid.') + STREAM = (cydriver.CUmemcpySrcAccessOrder_enum.CU_MEMCPY_SRC_ACCESS_ORDER_STREAM, 'Indicates that access to the source pointer must be in stream order.') + 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.") + 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.") + 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`. + """ + POINTER = (cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_POINTER, 'Memcpy operand is a valid pointer.') + ARRAY = (cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_ARRAY, 'Memcpy operand is a `CUarray`.') + MAX = cydriver.CUmemcpy3DOperandType_enum.CU_MEMCPY_OPERAND_TYPE_MAX + +class GraphMemAttribute(_cyb_FastEnum): + """ + See `CUgraphMem_attribute`. + """ + 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') + 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.') + 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.') + 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`. + """ + 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.") + 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.') + 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`. + """ + HOST = (cydriver.CUflushGPUDirectRDMAWritesOptions_enum.CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_HOST, '`cuFlushGPUDirectRDMAWrites()` and its CUDA Runtime API counterpart are supported on the device.') + 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`. + """ + 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.') + 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.') + 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`. + """ + 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.') + 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`. + """ + 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`. + """ + VERBOSE = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE, 'Output all debug data as if every debug flag is enabled') + RUNTIME_TYPES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES, 'Use CUDA Runtime structures for output') + KERNEL_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS, 'Adds `CUDA_KERNEL_NODE_PARAMS` values to output') + MEMCPY_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS, 'Adds `CUDA_MEMCPY3D` values to output') + MEMSET_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS, 'Adds `CUDA_MEMSET_NODE_PARAMS` values to output') + HOST_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS, 'Adds `CUDA_HOST_NODE_PARAMS` values to output') + 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') + 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') + 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') + KERNEL_NODE_ATTRIBUTES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES, 'Adds `CUkernelNodeAttrValue` values to output') + HANDLES = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES, 'Adds node handles and every kernel function handle to output') + MEM_ALLOC_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS, 'Adds memory alloc node parameters to output') + MEM_FREE_NODE_PARAMS = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS, 'Adds memory free node parameters to output') + 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') + EXTRA_TOPO_INFO = (cydriver.CUgraphDebugDot_flags_enum.CU_GRAPH_DEBUG_DOT_FLAGS_EXTRA_TOPO_INFO, 'Adds edge numbering information') + 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`. + """ + 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`. + """ + 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`. + """ + 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.') + 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`.') + 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.') + 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`. + """ + NONE = (cydriver.CUdeviceNumaConfig_enum.CU_DEVICE_NUMA_CONFIG_NONE, 'The GPU is not a NUMA node') + 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`. + """ + RUNNING = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_RUNNING, 'Default process state') + LOCKED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_LOCKED, 'CUDA API locks are taken so further CUDA API calls will block') + CHECKPOINTED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_CHECKPOINTED, 'Application memory contents have been checkpointed and underlying allocations and device handles have been released') + FAILED = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_FAILED, 'Application entered an uncorrectable error during the checkpoint/restore process') + CHECKPOINTING = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_CHECKPOINTING, 'Application memory contents are being checkpointed') + RESTORING = (cydriver.CUprocessState_enum.CU_PROCESS_STATE_RESTORING, 'Application memory contents are being restored') + +class ModuleLoadingMode(_cyb_FastEnum): + """ + CUDA Lazy Loading status + + See `CUmoduleLoadingMode`. + """ + EAGER_LOADING = (cydriver.CUmoduleLoadingMode_enum.CU_MODULE_EAGER_LOADING, 'Lazy Kernel Loading is not enabled') + 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`. + """ + UNSUPPORTED = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_UNSUPPORTED, 'Decompression is unsupported.') + ALGORITHM_DEFLATE = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_DEFLATE, 'Deflate is supported.') + ALGORITHM_SNAPPY = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_SNAPPY, 'Snappy is supported.') + ALGORITHM_LZ4 = (cydriver.CUmemDecompressAlgorithm_enum.CU_MEM_DECOMPRESS_ALGORITHM_LZ4, 'LZ4 is supported.') + +class FunctionLoadingState(_cyb_FastEnum): + """ + See `CUfunctionLoadingState`. + """ + UNLOADED = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_UNLOADED + LOADED = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_LOADED + MAX = cydriver.CUfunctionLoadingState_enum.CU_FUNCTION_LOADING_STATE_MAX + +class CoredumpSettings(_cyb_FastEnum): + """ + Flags for choosing a coredump attribute to get/set + + See `CUcoredumpSettings`. + """ + ENABLE_ON_EXCEPTION = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_ENABLE_ON_EXCEPTION + TRIGGER_HOST = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_TRIGGER_HOST + LIGHTWEIGHT = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_LIGHTWEIGHT + ENABLE_USER_TRIGGER = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_ENABLE_USER_TRIGGER + FILE = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_FILE + PIPE = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_PIPE + GENERATION_FLAGS = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_GENERATION_FLAGS + MAX = cydriver.CUcoredumpSettings_enum.CU_COREDUMP_MAX + +class CoredumpGenerationFlags(_cyb_FastEnum): + """ + Flags for controlling coredump contents + + See `CUCoredumpGenerationFlags`. + """ + DEFAULT_FLAGS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_DEFAULT_FLAGS + SKIP_NONRELOCATED_ELF_IMAGES = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_NONRELOCATED_ELF_IMAGES + SKIP_GLOBAL_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_GLOBAL_MEMORY + SKIP_SHARED_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_SHARED_MEMORY + SKIP_LOCAL_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_LOCAL_MEMORY + SKIP_ABORT = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_ABORT + SKIP_CONSTBANK_MEMORY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_SKIP_CONSTBANK_MEMORY + GZIP_COMPRESS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_GZIP_COMPRESS + FAULTED_CONTEXTS_ONLY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_FAULTED_CONTEXTS_ONLY + NO_ERRBAR_AT_EXIT = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_NO_ERRBAR_AT_EXIT + LOG_ONLY = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_LOG_ONLY + LIGHTWEIGHT_FLAGS = cydriver.CUCoredumpGenerationFlags.CU_COREDUMP_LIGHTWEIGHT_FLAGS + +class GreenCtxCreateFlags(_cyb_FastEnum): + """ + Flags for green context creation + + See `CUgreenCtxCreate_flags`. + """ + NONE = cydriver.CUgreenCtxCreate_flags.CU_GREEN_CTX_NONE + 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`. + """ + INVALID = cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_INVALID + SM = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM, 'Streaming multiprocessors related information') + WORKQUEUE_CONFIG = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG, 'Workqueue configuration related information') + WORKQUEUE = (cydriver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_WORKQUEUE, 'Pre-existing workqueue related information') + +class LogLevel(_cyb_FastEnum): + """ + See `CUlogLevel`. + """ + ERROR = cydriver.CUlogLevel_enum.CU_LOG_LEVEL_ERROR + WARNING = cydriver.CUlogLevel_enum.CU_LOG_LEVEL_WARNING + +class EglFrameType(_cyb_FastEnum): + """ + CUDA EglFrame type - array or pointer + + See `CUeglFrameType`. + """ + ARRAY = (cydriver.CUeglFrameType_enum.CU_EGL_FRAME_TYPE_ARRAY, 'Frame type CUDA array') + 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`. + """ + SYSMEM = (cydriver.CUeglResourceLocationFlags_enum.CU_EGL_RESOURCE_LOCATION_SYSMEM, 'Resource location sysmem') + 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`. + """ + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + ARGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_ARGB, 'R/G/B/A four channels in one surface with BGRA byte ordering.') + RGBA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_RGBA, 'R/G/B/A four channels in one surface with ABGR byte ordering.') + L = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_L, 'single luminance channel in one surface.') + R = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_R, 'single color channel in one surface.') + 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.') + 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.') + YUYV_422 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUYV_422, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + UYVY_422 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_422, 'Y, U, V in one surface, interleaved as YUYV in one channel.') + ABGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_ABGR, 'R/G/B/A four channels in one surface with RGBA byte ordering.') + BGRA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BGRA, 'R/G/B/A four channels in one surface with ARGB byte ordering.') + A = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_A, 'Alpha color format - one channel in one surface.') + RG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_RG, 'R/G color format - two channels in one surface with GR byte ordering') + AYUV = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_AYUV, 'Y, U, V, A four channels in one surface, interleaved as VUYA.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + BAYER_RGGB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_RGGB, 'Bayer format - one channel in one surface with interleaved RGGB ordering.') + BAYER_BGGR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_BGGR, 'Bayer format - one channel in one surface with interleaved BGGR ordering.') + BAYER_GRBG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_GRBG, 'Bayer format - one channel in one surface with interleaved GRBG ordering.') + BAYER_GBRG = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_GBRG, 'Bayer format - one channel in one surface with interleaved GBRG ordering.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + BAYER_BCCR = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_BCCR, 'Bayer format - one channel in one surface with interleaved BCCR ordering.') + BAYER_RCCB = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_RCCB, 'Bayer format - one channel in one surface with interleaved RCCB ordering.') + BAYER_CRBC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_CRBC, 'Bayer format - one channel in one surface with interleaved CRBC ordering.') + BAYER_CBRC = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_BAYER_CBRC, 'Bayer format - one channel in one surface with interleaved CBRC ordering.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + Y = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y, 'Color format for single Y plane.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + Y_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y_ER, 'Extended Range Color format for single Y plane.') + Y_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y_709_ER, 'Extended Range Color format for single Y plane.') + Y10_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10_ER, 'Extended Range Color format for single Y10 plane.') + Y10_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y10_709_ER, 'Extended Range Color format for single Y10 plane.') + Y12_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12_ER, 'Extended Range Color format for single Y12 plane.') + Y12_709_ER = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_Y12_709_ER, 'Extended Range Color format for single Y12 plane.') + YUVA = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YUVA, 'Y, U, V, A four channels in one surface, interleaved as AVUY.') + 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.') + YVYU = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_YVYU, 'Y, U, V in one surface, interleaved as YVYU in one channel.') + VYUY = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_VYUY, 'Y, U, V in one surface, interleaved as VYUY in one channel.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + 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.') + UYVY_709 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_709, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + 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.') + UYVY_2020 = (cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_UYVY_2020, 'Y, U, V in one surface, interleaved as UYVY in one channel.') + MAX = cydriver.CUeglColorFormat_enum.CU_EGL_COLOR_FORMAT_MAX + +class GLMapFlags(_cyb_FastEnum): + """ + Flags to map or unmap a resource + + See `CUGLmap_flags`. + """ + NONE = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_NONE + READ_ONLY = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY + WRITE_DISCARD = cydriver.CUGLmap_flags_enum.CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD + +class OutputMode(_cyb_FastEnum): + """ + Profiler Output Modes + + See `CUoutput_mode`. + """ + KEY_VALUE_PAIR = (cydriver.CUoutput_mode_enum.CU_OUT_KEY_VALUE_PAIR, 'Output mode Key-Value pair format.') + CSV = (cydriver.CUoutput_mode_enum.CU_OUT_CSV, 'Output mode Comma separated values format.') + +class AtomicOperation(_cyb_FastEnum): + """ + CUDA-valid Atomic Operations + + See `CUatomicOperation`. + """ + INTEGER_ADD = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_ADD + INTEGER_MIN = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_MIN + INTEGER_MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_MAX + INTEGER_INCREMENT = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_INCREMENT + INTEGER_DECREMENT = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_INTEGER_DECREMENT + AND = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_AND + OR = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_OR + XOR = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_XOR + EXCHANGE = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_EXCHANGE + CAS = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_CAS + FLOAT_ADD = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_ADD + FLOAT_MIN = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_MIN + FLOAT_MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_FLOAT_MAX + MAX = cydriver.CUatomicOperation_enum.CU_ATOMIC_OPERATION_MAX + +class AtomicOperationCapability(_cyb_FastEnum): + """ + CUDA-valid Atomic Operation capabilities + + See `CUatomicOperationCapability`. + """ + SIGNED = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SIGNED + UNSIGNED = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_UNSIGNED + REDUCTION = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_REDUCTION + SCALAR_32 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_32 + SCALAR_64 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_64 + SCALAR_128 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_SCALAR_128 + VECTOR_32x4 = cydriver.CUatomicOperationCapability_enum.CU_ATOMIC_CAPABILITY_VECTOR_32x4 + +class StreamAtomicReductionOpType(_cyb_FastEnum): + """ + Atomic reduction operation types for + `CUstreamBatchMemOpParams`::atomicReduction::reductionOp + + See `CUstreamAtomicReductionOpType`. + """ + OR = (cydriver.CUstreamAtomicReductionOpType_enum.CU_STREAM_ATOMIC_REDUCTION_OP_OR, 'Performs an atomic OR: \\*(address) = \\*(address) | value') + AND = (cydriver.CUstreamAtomicReductionOpType_enum.CU_STREAM_ATOMIC_REDUCTION_OP_AND, 'Performs an atomic AND: \\*(address) = \\*(address) & value') + 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`. + """ + STREAM_ATOMIC_REDUCTION_UNSIGNED_32 = cydriver.CUstreamAtomicReductionDataType_enum.CU_STREAM_ATOMIC_REDUCTION_UNSIGNED_32 + 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`. + """ + DEFAULT = cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_DEFAULT + BACKFILL = cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_BACKFILL + LOCALITY_DOMAIN_ID = (cydriver.CUdevSmResourceGroup_flags.CU_DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID, 'The SMs must be located on a specific locality domain, specified by localityDomainId') + +class DevSmResourceSplitByCountFlags(_cyb_FastEnum): + """ + See `CUdevSmResourceSplitByCount_flags`. + """ + IGNORE_SM_COSCHEDULING = cydriver.CUdevSmResourceSplitByCount_flags.CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING + 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`. + """ + DEVICE_CTX = (cydriver.CUdevWorkqueueConfigScope.CU_WORKQUEUE_SCOPE_DEVICE_CTX, 'Use all shared workqueue resources across all contexts. Default driver behaviour.') + 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`. + """ + BLOCKING = (cydriver.CUhostTaskSyncMode_enum.CU_HOST_TASK_BLOCKING, 'The execution thread will block until new host tasks are ready to run') + 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`. + """ + 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`') + REQUIRE_PORTABLE = (cydriver.CUlaunchAttributePortableClusterMode_enum.CU_LAUNCH_PORTABLE_CLUSTER_MODE_REQUIRE_PORTABLE, 'Specifies that the cluster size requested must be a portable size') + 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`. + """ + 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`') + 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`') + 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`') + ALLOW_OVERSIZED_SHARED_MEMORY = (cydriver.CUsharedMemoryMode_enum.CU_SHARED_MEMORY_MODE_ALLOW_OVERSIZED_SHARED_MEMORY, 'Specifies that oversized shared memory configurations may be used (with the limitation of only 8kB L1 cache)') + PREFER_OVERSIZED_SHARED_MEMORY = (cydriver.CUsharedMemoryMode_enum.CU_SHARED_MEMORY_MODE_PREFER_OVERSIZED_SHARED_MEMORY, 'Specifies that oversized shared memory configurations may be used (with the limitation of only 8kB L1 cache), and prefer an oversized shared memory configuration') + +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`. + """ + NONE = cydriver.CUlogicalEndpointIpcHandleType_enum.CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_NONE + FABRIC = cydriver.CUlogicalEndpointIpcHandleType_enum.CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_FABRIC + +class LogicalEndpointType(_cyb_FastEnum): + """ + Logical endpoint type + + See `CUlogicalEndpointType`. + """ + INVALID = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_INVALID + UNICAST = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_UNICAST + MULTICAST = cydriver.CUlogicalEndpointType_enum.CU_LOGICAL_ENDPOINT_TYPE_MULTICAST + +class LogicalEndpointFlag(_cyb_FastEnum): + """ + Flags for `CUlogicalEndpointProp` + + See `CUlogicalEndpointFlag`. + """ + NONE = (cydriver.CUlogicalEndpointFlag_enum.CU_LOGICAL_ENDPOINT_FLAG_NONE, 'Default flag for logical endpoint construction') + 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`. + """ + ELIGIBLE_FOR_UPDATE = (cydriver.CUgraphRecaptureStatus_enum.CU_GRAPH_RECAPTURE_ELIGIBLE_FOR_UPDATE, 'Node is eligible for update in an instantiated graph.') + INELIGIBLE_FOR_UPDATE = (cydriver.CUgraphRecaptureStatus_enum.CU_GRAPH_RECAPTURE_INELIGIBLE_FOR_UPDATE, 'Parameter changes in the node cannot be applied to an instantiated graph.') + 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.') + +class CliqueType(_cyb_FastEnum): + """ + Fabric clique types + + See `CUcliqueType`. + """ + UNICAST_POINTER = (cydriver.CUcliqueType_enum.CU_CLIQUE_TYPE_UNICAST_POINTER, 'Unicast pointer clique') + MULTICAST_POINTER = (cydriver.CUcliqueType_enum.CU_CLIQUE_TYPE_MULTICAST_POINTER, 'Multicast pointer clique') + UNICAST_LOGICAL_ENDPOINT = (cydriver.CUcliqueType_enum.CU_CLIQUE_TYPE_UNICAST_LOGICAL_ENDPOINT, 'Unicast logical endpoint clique') + MULTICAST_LOGICAL_ENDPOINT = (cydriver.CUcliqueType_enum.CU_CLIQUE_TYPE_MULTICAST_LOGICAL_ENDPOINT, 'Multicast logical endpoint clique') + +############################################################################### +# Enums for C preprocessor constants (`#define`), grouped by what they are used for. +# The values are taken from the C constants, so they track the CTK header. +############################################################################### + +class Array3dFlags(_FastEnum): + """Flags for `Array3dDescriptor_v2.flags_` (`CUDA_ARRAY3D_*`).""" + LAYERED = (cydriver.CUDA_ARRAY3D_LAYERED, 'If set, the CUDA array is a collection of layers, where each layer is either a 1D or a 2D array and the Depth member of CUDA_ARRAY3D_DESCRIPTOR specifies the number of layers, not the depth of a 3D array.') + ARRAY_2D = (cydriver.CUDA_ARRAY3D_2DARRAY, 'Deprecated, use CUDA_ARRAY3D_LAYERED') + SURFACE_LDST = (cydriver.CUDA_ARRAY3D_SURFACE_LDST, 'This flag must be set in order to bind a surface reference to the CUDA array') + CUBEMAP = (cydriver.CUDA_ARRAY3D_CUBEMAP, 'If set, the CUDA array is a collection of six 2D arrays, representing faces of a cube. The width of such a CUDA array must be equal to its height, and Depth must be six. If CUDA_ARRAY3D_LAYERED flag is also set, then the CUDA array is a collection of cubemaps and Depth must be a multiple of six.') + TEXTURE_GATHER = (cydriver.CUDA_ARRAY3D_TEXTURE_GATHER, 'This flag must be set in order to perform texture gather operations on a CUDA array.') + DEPTH_TEXTURE = (cydriver.CUDA_ARRAY3D_DEPTH_TEXTURE, 'This flag if set indicates that the CUDA array is a DEPTH_TEXTURE.') + COLOR_ATTACHMENT = (cydriver.CUDA_ARRAY3D_COLOR_ATTACHMENT, 'This flag indicates that the CUDA array may be bound as a color target in an external graphics API') + SPARSE = (cydriver.CUDA_ARRAY3D_SPARSE, 'This flag if set indicates that the CUDA array or CUDA mipmapped array is a sparse CUDA array or CUDA mipmapped array respectively') + DEFERRED_MAPPING = (cydriver.CUDA_ARRAY3D_DEFERRED_MAPPING, 'This flag if set indicates that the CUDA array or CUDA mipmapped array will allow deferred memory mapping') + VIDEO_ENCODE_DECODE = (cydriver.CUDA_ARRAY3D_VIDEO_ENCODE_DECODE, 'This flag indicates that the CUDA array will be used for hardware accelerated video encode/decode operations.') + +class ArraySparsePropertiesFlags(_FastEnum): + """Flags in `ArraySparseProperties_v1.flags_` (`CU_ARRAY_SPARSE_PROPERTIES_*`).""" + SINGLE_MIPTAIL = (cydriver.CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, 'Indicates that the layered sparse CUDA array or CUDA mipmapped array has a single mip tail region for all layers') + +class TexRefArrayFlags(_FastEnum): + """Flags for `tex_ref_set_array` (`CU_TRSA_*`).""" + OVERRIDE_FORMAT = (cydriver.CU_TRSA_OVERRIDE_FORMAT, 'Override the texref format with a format inferred from the array. Flag for cuTexRefSetArray()') + +class TexRefFlags(_FastEnum): + """Flags for `tex_ref_set_flags` (`CU_TRSF_*`).""" + READ_AS_INTEGER = (cydriver.CU_TRSF_READ_AS_INTEGER, 'Read the texture as integers rather than promoting the values to floats in the range [0,1]. Flag for cuTexRefSetFlags() and cuTexObjectCreate()') + NORMALIZED_COORDINATES = (cydriver.CU_TRSF_NORMALIZED_COORDINATES, 'Use normalized texture coordinates in the range [0,1) instead of [0,dim). Flag for cuTexRefSetFlags() and cuTexObjectCreate()') + SRGB = (cydriver.CU_TRSF_SRGB, 'Perform sRGB->linear conversion during texture read. Flag for cuTexRefSetFlags() and cuTexObjectCreate()') + DISABLE_TRILINEAR_OPTIMIZATION = (cydriver.CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, 'Disable any trilinear filtering optimizations. Flag for cuTexRefSetFlags() and cuTexObjectCreate()') + SEAMLESS_CUBEMAP = (cydriver.CU_TRSF_SEAMLESS_CUBEMAP, 'Enable seamless cube map filtering. Flag for cuTexObjectCreate()') + +class MemHostAllocFlags(_FastEnum): + """Flags for `mem_host_alloc` (`CU_MEMHOSTALLOC_*`).""" + PORTABLE = (cydriver.CU_MEMHOSTALLOC_PORTABLE, 'If set, host memory is portable between CUDA contexts. Flag for cuMemHostAlloc()') + DEVICEMAP = (cydriver.CU_MEMHOSTALLOC_DEVICEMAP, 'If set, host memory is mapped into CUDA address space and cuMemHostGetDevicePointer() may be called on the host pointer. Flag for cuMemHostAlloc()') + WRITECOMBINED = (cydriver.CU_MEMHOSTALLOC_WRITECOMBINED, 'If set, host memory is allocated as write-combined - fast to write, faster to DMA, slow to read except via SSE4 streaming load instruction (MOVNTDQA). Flag for cuMemHostAlloc()') + +class MemHostRegisterFlags(_FastEnum): + """Flags for `mem_host_register_v2` (`CU_MEMHOSTREGISTER_*`).""" + PORTABLE = (cydriver.CU_MEMHOSTREGISTER_PORTABLE, 'If set, host memory is portable between CUDA contexts. Flag for cuMemHostRegister()') + DEVICEMAP = (cydriver.CU_MEMHOSTREGISTER_DEVICEMAP, 'If set, host memory is mapped into CUDA address space and cuMemHostGetDevicePointer() may be called on the host pointer. Flag for cuMemHostRegister()') + IOMEMORY = (cydriver.CU_MEMHOSTREGISTER_IOMEMORY, 'If set, the passed memory pointer is treated as pointing to some memory-mapped I/O space, e.g. belonging to a third-party PCIe device. On Windows the flag is a no-op. On Linux that memory is marked as non cache-coherent for the GPU and is expected to be physically contiguous. It may return CUDA_ERROR_NOT_PERMITTED if run as an unprivileged user, CUDA_ERROR_NOT_SUPPORTED on older Linux kernel versions. On all other platforms, it is not supported and CUDA_ERROR_NOT_SUPPORTED is returned. Flag for cuMemHostRegister()') + READ_ONLY = (cydriver.CU_MEMHOSTREGISTER_READ_ONLY, 'If set, the passed memory 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.') + +class MemCreateUsage(_FastEnum): + """Usage hints for `MemAllocationProp_v1.alloc_flags` (`CU_MEM_CREATE_USAGE_*`).""" + TILE_POOL = (cydriver.CU_MEM_CREATE_USAGE_TILE_POOL, 'This flag if set indicates that the memory will be used as a tile pool.') + HW_DECOMPRESS = (cydriver.CU_MEM_CREATE_USAGE_HW_DECOMPRESS, 'This flag, if set, indicates that the memory will be used as a buffer for hardware accelerated decompression.') + GPU_DIRECT_RDMA_OVER_PCIE = (cydriver.CU_MEM_CREATE_USAGE_GPU_DIRECT_RDMA_OVER_PCIE, 'Setting this flag forces GPUDirect RDMA on a locality-domain-localized allocation to use the PCIe (BAR1) path, allowing the allocation to remain locality-domain localized on platforms where the platform-coherent RDMA path does not support localized allocations. Because on some platforms the PCIe bandwidth is limited, using this flag may result in lower RDMA bandwidth than the default RDMA mapping link. Note that this flag does not itself force PCIe to be used, and that this must be done when creating the RDMA export. CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_LOCALIZED_MEMORY_SUPPORTED indicates whether this flag is needed to create GPUDirect RDMA capable localized memory allocations. This flag is only valid if gpuDirectRDMACapable is set.') + +class MemPoolCreateUsage(_FastEnum): + """Usage hints for `MemPoolProps_v1.usage` (`CU_MEM_POOL_CREATE_USAGE_*`).""" + HW_DECOMPRESS = (cydriver.CU_MEM_POOL_CREATE_USAGE_HW_DECOMPRESS, 'This flag, if set, indicates that the memory will be used as a buffer for hardware accelerated decompression.') + +class CooperativeLaunchMultiDeviceFlags(_FastEnum): + """Flags for `launch_cooperative_kernel_multi_device` (`CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_*`).""" + NO_PRE_LAUNCH_SYNC = (cydriver.CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC, 'If set, each kernel launched as part of cuLaunchCooperativeKernelMultiDevice only waits for prior work in the stream corresponding to that GPU to complete before the kernel begins execution.') + NO_POST_LAUNCH_SYNC = (cydriver.CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC, 'If set, any subsequent work pushed in a stream that participated in a call to cuLaunchCooperativeKernelMultiDevice will only wait for the kernel launched on the GPU corresponding to that stream to complete before it begins execution.') + +class ExternalMemoryFlags(_FastEnum): + """Flags for `ExternalMemoryHandleDesc_v1.flags_` (`CUDA_EXTERNAL_MEMORY_*`).""" + DEDICATED = (cydriver.CUDA_EXTERNAL_MEMORY_DEDICATED, 'Indicates that the external memory object is a dedicated resource') + +class ExternalSemaphoreSignalFlags(_FastEnum): + """Flags for `ExternalSemaphoreSignalParams_v1.flags_` (`CUDA_EXTERNAL_SEMAPHORE_SIGNAL_*`).""" + SKIP_NVSCIBUF_MEMSYNC = (cydriver.CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC, 'When the flags parameter of CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS contains this flag, it indicates that signaling an external semaphore object should skip performing appropriate memory synchronization operations over all the external memory objects that are imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, which otherwise are performed by default to ensure data coherency with other importers of the same NvSciBuf memory objects.') + +class ExternalSemaphoreWaitFlags(_FastEnum): + """Flags for `ExternalSemaphoreWaitParams_v1.flags_` (`CUDA_EXTERNAL_SEMAPHORE_WAIT_*`).""" + SKIP_NVSCIBUF_MEMSYNC = (cydriver.CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC, 'When the flags parameter of CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS contains this flag, it indicates that waiting on an external semaphore object should skip performing appropriate memory synchronization operations over all the external memory objects that are imported as CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, which otherwise are performed by default to ensure data coherency with other importers of the same NvSciBuf memory objects.') + +class NvSciSyncAttr(_FastEnum): + """NvSciSync attribute directions (`CUDA_NVSCISYNC_ATTR_*`).""" + SIGNAL = (cydriver.CUDA_NVSCISYNC_ATTR_SIGNAL, 'When flags of cuDeviceGetNvSciSyncAttributes is set to this, it indicates that application needs signaler specific NvSciSyncAttr to be filled by cuDeviceGetNvSciSyncAttributes.') + WAIT = (cydriver.CUDA_NVSCISYNC_ATTR_WAIT, 'When flags of cuDeviceGetNvSciSyncAttributes is set to this, it indicates that application needs waiter specific NvSciSyncAttr to be filled by cuDeviceGetNvSciSyncAttributes.') + +class GraphKernelNodePort(_FastEnum): + """Outgoing ports of a kernel node, for `GraphEdgeData.from_port` (`CU_GRAPH_KERNEL_NODE_PORT_*`).""" + DEFAULT = (cydriver.CU_GRAPH_KERNEL_NODE_PORT_DEFAULT, 'This port activates when the kernel has finished executing.') + PROGRAMMATIC = (cydriver.CU_GRAPH_KERNEL_NODE_PORT_PROGRAMMATIC, 'This port activates when all blocks of the kernel have performed cudaTriggerProgrammaticLaunchCompletion() or have terminated. It must be used with edge type CU_GRAPH_DEPENDENCY_TYPE_PROGRAMMATIC. See also CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT.') + LAUNCH_ORDER = (cydriver.CU_GRAPH_KERNEL_NODE_PORT_LAUNCH_ORDER, 'This port activates when all blocks of the kernel have begun execution. See also CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT.') + +class GraphConditionalHandleFlags(_FastEnum): + """Flags for `graph_conditional_handle_create` (`CU_GRAPH_COND_*`).""" + ASSIGN_DEFAULT = (cydriver.CU_GRAPH_COND_ASSIGN_DEFAULT, 'Default value is applied when graph is launched.') + +class ComputeTargetBase(_FastEnum): + """Offsets added to a compute capability to form a `JitTarget` with accelerated or family features (`CU_COMPUTE_*_TARGET_BASE`).""" + ACCELERATED = (cydriver.CU_COMPUTE_ACCELERATED_TARGET_BASE, 'Indicates that compute device class supports accelerated features.') + FAMILY = (cydriver.CU_COMPUTE_FAMILY_TARGET_BASE, 'Indicates that compute device class supports family features.') + +class LaunchParam(_FastEnum): + """Markers in the `extra` array of `launch_kernel` (`CU_LAUNCH_PARAM_*`).""" + END = (cydriver.CU_LAUNCH_PARAM_END_AS_INT, 'End of array terminator for the extra parameter to cuLaunchKernel') + BUFFER_POINTER = (cydriver.CU_LAUNCH_PARAM_BUFFER_POINTER_AS_INT, 'Indicator that the next value in the extra parameter to cuLaunchKernel will be a pointer to a buffer containing all kernel parameters used for launching kernel f. This buffer needs to honor all alignment/padding requirements of the individual parameters. If CU_LAUNCH_PARAM_BUFFER_SIZE is not also specified in the extra array, then CU_LAUNCH_PARAM_BUFFER_POINTER will have no effect.') + BUFFER_SIZE = (cydriver.CU_LAUNCH_PARAM_BUFFER_SIZE_AS_INT, 'Indicator that the next value in the extra parameter to cuLaunchKernel will be a pointer to a size_t which contains the size of the buffer specified with CU_LAUNCH_PARAM_BUFFER_POINTER. It is required that CU_LAUNCH_PARAM_BUFFER_POINTER also be specified in the extra array if the value associated with CU_LAUNCH_PARAM_BUFFER_SIZE is not zero.') + +class SpecialDevice(_FastEnum): + """Special `int` device ordinals (`CU_DEVICE_*`).""" + CPU = (cydriver.CU_DEVICE_CPU, 'Device that represents the CPU') + INVALID = (cydriver.CU_DEVICE_INVALID, 'Device that represents an invalid device') + +class SpecialStream(_FastEnum): + """Special stream handles, as `int` (`CU_STREAM_*`).""" + LEGACY = (cydriver.CU_STREAM_LEGACY, 'Legacy stream handle. Stream handle that can be passed as a CUstream to use an implicit stream with legacy synchronization behavior.') + PER_THREAD = (cydriver.CU_STREAM_PER_THREAD, 'Per-thread stream handle. Stream handle that can be passed as a CUstream to use an implicit stream with per-thread synchronization behavior.') + +class ParamTexRef(_FastEnum): + """Special texture reference index for `param_set_tex_ref` (`CU_PARAM_TR_*`).""" + DEFAULT = (cydriver.CU_PARAM_TR_DEFAULT, 'For texture references loaded into the module, use default texunit from texture reference.') + +# Constants that do not belong to a natural group. +globals()['CU_IPC_HANDLE_SIZE'] = cydriver.CU_IPC_HANDLE_SIZE +globals()['CU_TENSOR_MAP_NUM_QWORDS'] = cydriver.CU_TENSOR_MAP_NUM_QWORDS +globals()['CU_LAUNCH_KERNEL_REQUIRED_BLOCK_DIM'] = cydriver.CU_LAUNCH_KERNEL_REQUIRED_BLOCK_DIM +globals()['CUDA_EGL_INFINITE_TIMEOUT'] = cydriver.CUDA_EGL_INFINITE_TIMEOUT +globals()['MAX_PLANES'] = cydriver.MAX_PLANES + + + +############################################################################### +# Error handling +############################################################################### + + +class DriverError(Exception): + def __init__(self, status): + self.status = status + cdef str err + try: + s = Result(status) + err = f"{s.name} ({s.value})" + except ValueError: + err = f"Unknown error ({status})" + 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 MulticastResourceFullError(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 InsufficientLoaderVersionError(DriverError): + pass +class InvalidSourceError(DriverError): + pass +class DriverFileNotFoundError(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 HardwareStackError(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 DriverTimeoutError(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 FabricNotReadyError(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 == 47: + return MulticastResourceFullError(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 == 227: + return InsufficientLoaderVersionError(pystatus) + elif status == 300: + return InvalidSourceError(pystatus) + elif status == 301: + return DriverFileNotFoundError(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 HardwareStackError(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 DriverTimeoutError(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 == 919: + return FabricNotReadyError(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 _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUuuid)) + if self._ptr == NULL: + raise MemoryError("Error allocating Uuid") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUuuid *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This Uuid instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUuuid): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUuuid), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUuuid)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def bytes(self): + """bytes: The 16 raw bytes of the UUID.""" + return self._ptr[0].bytes[:16] + + @bytes.setter + def bytes(self, val): + if self._readonly: + raise ValueError("This Uuid instance is read-only") + cdef bytes buf = bytes(val) + if len(buf) != 16: + raise ValueError(f"A UUID is 16 bytes, got {len(buf)}") + cdef const char* src = buf + cdef int i + for i in range(16): + self._ptr[0].bytes[i] = src[i] + + @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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUmemFabricHandle_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemFabricHandle_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemFabricHandle_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemFabricHandle_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemFabricHandle_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def data_(self): + """~_numpy.uint8: (array of length 64).""" + cdef _cyb_view.array arr = _cyb_view.array(shape=(64,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].data)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(64,), itemsize=sizeof(unsigned char), format="B", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) + _cyb_memcpy((&(self._ptr[0].data)), (arr.data), sizeof(unsigned char) * len(val)) + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemFabricHandle_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUipcEventHandle_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This IpcEventHandle_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUipcEventHandle_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUipcEventHandle_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUipcEventHandle_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUipcEventHandle_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUipcMemHandle_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This IpcMemHandle_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUipcMemHandle_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUipcMemHandle_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUipcMemHandle_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUipcMemHandle_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_mem_op_flush_remote_writes_params_dtype_offsets(): + cdef CUstreamMemOpFlushRemoteWritesParams_st pod + return _numpy.dtype({ + 'names': ['operation', 'flags_'], + 'formats': [_numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUstreamMemOpFlushRemoteWritesParams_st), + }) + +stream_mem_op_flush_remote_writes_params_dtype = _get_stream_mem_op_flush_remote_writes_params_dtype_offsets() + +cdef class StreamMemOpFlushRemoteWritesParams: + """Empty-initialize an instance of `CUstreamMemOpFlushRemoteWritesParams_st`. + + + .. seealso:: `CUstreamMemOpFlushRemoteWritesParams_st` + """ + cdef: + CUstreamMemOpFlushRemoteWritesParams_st *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamMemOpFlushRemoteWritesParams_st)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpFlushRemoteWritesParams") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUstreamMemOpFlushRemoteWritesParams_st *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamMemOpFlushRemoteWritesParams 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 StreamMemOpFlushRemoteWritesParams other_ + if not isinstance(other, StreamMemOpFlushRemoteWritesParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamMemOpFlushRemoteWritesParams_st)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamMemOpFlushRemoteWritesParams_st), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamMemOpFlushRemoteWritesParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamMemOpFlushRemoteWritesParams_st): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamMemOpFlushRemoteWritesParams_st), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUstreamMemOpFlushRemoteWritesParams_st)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def operation(self): + """int: """ + return (self._ptr[0].operation) + + @operation.setter + def operation(self, val): + if self._readonly: + raise ValueError("This StreamMemOpFlushRemoteWritesParams instance is read-only") + self._ptr[0].operation = val + + @property + def flags_(self): + """int: Must be 0.""" + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This StreamMemOpFlushRemoteWritesParams instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamMemOpFlushRemoteWritesParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamMemOpFlushRemoteWritesParams_st), StreamMemOpFlushRemoteWritesParams) + + @staticmethod + def from_data(data): + """Create an StreamMemOpFlushRemoteWritesParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_mem_op_flush_remote_writes_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_mem_op_flush_remote_writes_params_dtype", stream_mem_op_flush_remote_writes_params_dtype, StreamMemOpFlushRemoteWritesParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamMemOpFlushRemoteWritesParams 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 StreamMemOpFlushRemoteWritesParams obj = StreamMemOpFlushRemoteWritesParams.__new__(StreamMemOpFlushRemoteWritesParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamMemOpFlushRemoteWritesParams_st)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpFlushRemoteWritesParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamMemOpFlushRemoteWritesParams_st)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_mem_op_memory_barrier_params_dtype_offsets(): + cdef CUstreamMemOpMemoryBarrierParams_st pod + return _numpy.dtype({ + 'names': ['operation', 'flags_'], + 'formats': [_numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUstreamMemOpMemoryBarrierParams_st), + }) + +stream_mem_op_memory_barrier_params_dtype = _get_stream_mem_op_memory_barrier_params_dtype_offsets() + +cdef class StreamMemOpMemoryBarrierParams: + """Empty-initialize an instance of `CUstreamMemOpMemoryBarrierParams_st`. + + + .. seealso:: `CUstreamMemOpMemoryBarrierParams_st` + """ + cdef: + CUstreamMemOpMemoryBarrierParams_st *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamMemOpMemoryBarrierParams_st)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpMemoryBarrierParams") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUstreamMemOpMemoryBarrierParams_st *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamMemOpMemoryBarrierParams 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 StreamMemOpMemoryBarrierParams other_ + if not isinstance(other, StreamMemOpMemoryBarrierParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamMemOpMemoryBarrierParams_st)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamMemOpMemoryBarrierParams_st), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamMemOpMemoryBarrierParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamMemOpMemoryBarrierParams_st): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamMemOpMemoryBarrierParams_st), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUstreamMemOpMemoryBarrierParams_st)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def operation(self): + """int: < Only supported in the _v2 API""" + return (self._ptr[0].operation) + + @operation.setter + def operation(self, val): + if self._readonly: + raise ValueError("This StreamMemOpMemoryBarrierParams instance is read-only") + self._ptr[0].operation = val + + @property + def flags_(self): + """int: See CUstreamMemoryBarrier_flags""" + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This StreamMemOpMemoryBarrierParams instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamMemOpMemoryBarrierParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamMemOpMemoryBarrierParams_st), StreamMemOpMemoryBarrierParams) + + @staticmethod + def from_data(data): + """Create an StreamMemOpMemoryBarrierParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_mem_op_memory_barrier_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_mem_op_memory_barrier_params_dtype", stream_mem_op_memory_barrier_params_dtype, StreamMemOpMemoryBarrierParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamMemOpMemoryBarrierParams 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 StreamMemOpMemoryBarrierParams obj = StreamMemOpMemoryBarrierParams.__new__(StreamMemOpMemoryBarrierParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamMemOpMemoryBarrierParams_st)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpMemoryBarrierParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamMemOpMemoryBarrierParams_st)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_mem_op_atomic_reduction_params_dtype_offsets(): + cdef CUstreamMemOpAtomicReductionParams_st pod + return _numpy.dtype({ + 'names': ['operation', 'flags_', 'reduction_op', 'data_type', 'address', 'value', 'alias'], + 'formats': [_numpy.int32, _numpy.uint32, _numpy.int32, _numpy.int32, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reductionOp)) - (&pod), + (&(pod.dataType)) - (&pod), + (&(pod.address)) - (&pod), + (&(pod.value)) - (&pod), + (&(pod.alias)) - (&pod), + ], + 'itemsize': sizeof(CUstreamMemOpAtomicReductionParams_st), + }) + +stream_mem_op_atomic_reduction_params_dtype = _get_stream_mem_op_atomic_reduction_params_dtype_offsets() + +cdef class StreamMemOpAtomicReductionParams: + """Empty-initialize an instance of `CUstreamMemOpAtomicReductionParams_st`. + + + .. seealso:: `CUstreamMemOpAtomicReductionParams_st` + """ + cdef: + CUstreamMemOpAtomicReductionParams_st *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamMemOpAtomicReductionParams_st)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpAtomicReductionParams") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUstreamMemOpAtomicReductionParams_st *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamMemOpAtomicReductionParams 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 StreamMemOpAtomicReductionParams other_ + if not isinstance(other, StreamMemOpAtomicReductionParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamMemOpAtomicReductionParams_st)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamMemOpAtomicReductionParams_st), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamMemOpAtomicReductionParams_st): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamMemOpAtomicReductionParams_st), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUstreamMemOpAtomicReductionParams_st)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def operation(self): + """int: """ + return (self._ptr[0].operation) + + @operation.setter + def operation(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].operation = val + + @property + def flags_(self): + """int: Must be 0""" + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].flags = val + + @property + def reduction_op(self): + """int: See CUstreamAtomicReductionOpType""" + return (self._ptr[0].reductionOp) + + @reduction_op.setter + def reduction_op(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].reductionOp = val + + @property + def data_type(self): + """int: See CUstreamAtomicReductionDataType""" + return (self._ptr[0].dataType) + + @data_type.setter + def data_type(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].dataType = val + + @property + def address(self): + """int: The address the atomic operation will be operated on""" + return (self._ptr[0].address) + + @address.setter + def address(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].address = val + + @property + def value(self): + """int: The operand value the atomic operation will operate with""" + return (self._ptr[0].value) + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].value = val + + @property + def alias(self): + """int: For driver internal use. Initial value is unimportant.""" + return (self._ptr[0].alias) + + @alias.setter + def alias(self, val): + if self._readonly: + raise ValueError("This StreamMemOpAtomicReductionParams instance is read-only") + self._ptr[0].alias = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamMemOpAtomicReductionParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamMemOpAtomicReductionParams_st), StreamMemOpAtomicReductionParams) + + @staticmethod + def from_data(data): + """Create an StreamMemOpAtomicReductionParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_mem_op_atomic_reduction_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_mem_op_atomic_reduction_params_dtype", stream_mem_op_atomic_reduction_params_dtype, StreamMemOpAtomicReductionParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamMemOpAtomicReductionParams 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 StreamMemOpAtomicReductionParams obj = StreamMemOpAtomicReductionParams.__new__(StreamMemOpAtomicReductionParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamMemOpAtomicReductionParams_st)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpAtomicReductionParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamMemOpAtomicReductionParams_st)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod3_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod3 pod + return _numpy.dtype({ + 'names': ['bytes_over_budget'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.bytesOverBudget)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod3), + }) + +_py_anon_pod3_dtype = _get__py_anon_pod3_dtype_offsets() + +cdef class _py_anon_pod3: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod3`. + + + .. seealso:: `cuda_bindings_driver__anon_pod3` + """ + cdef: + cuda_bindings_driver__anon_pod3 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod3)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod3") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod3 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod3 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_pod3 other_ + if not isinstance(other, _py_anon_pod3): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod3)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod3), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod3 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod3): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod3), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod3)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def bytes_over_budget(self): + """int: """ + return self._ptr[0].bytesOverBudget + + @bytes_over_budget.setter + def bytes_over_budget(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod3 instance is read-only") + self._ptr[0].bytesOverBudget = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod3 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod3), _py_anon_pod3) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod3 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod3_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod3_dtype", _py_anon_pod3_dtype, _py_anon_pod3) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod3 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_pod3 obj = _py_anon_pod3.__new__(_py_anon_pod3) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod3)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod3") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod3)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_dev_prop_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), + }) + +dev_prop_v1_dtype = _get_dev_prop_v1_dtype_offsets() + +cdef class DevProp_v1: + """Empty-initialize an instance of `CUdevprop_v1`. + + + .. seealso:: `CUdevprop_v1` + """ + cdef: + CUdevprop_v1 _data + CUdevprop_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This DevProp_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUdevprop_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUdevprop_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUdevprop_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(int), format="i", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].maxThreadsDim)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(int), format="i", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.int32) + _cyb_memcpy((&(self._ptr[0].maxThreadsDim)), (arr.data), sizeof(int) * len(val)) + + @property + def max_grid_size(self): + """~_numpy.int32: (array of length 3).""" + cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(int), format="i", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].maxGridSize)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(int), format="i", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.int32) + _cyb_memcpy((&(self._ptr[0].maxGridSize)), (arr.data), sizeof(int) * len(val)) + + @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 `dev_prop_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "dev_prop_v1_dtype", dev_prop_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUdevprop_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUaccessPolicyWindow_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This AccessPolicyWindow_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUaccessPolicyWindow_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUaccessPolicyWindow_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUaccessPolicyWindow_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUaccessPolicyWindow_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_KERNEL_NODE_PARAMS_v2 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This KernelNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_KERNEL_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_KERNEL_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_KERNEL_NODE_PARAMS_v2)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_KERNEL_NODE_PARAMS_v3 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This KernelNodeParams_v3 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_KERNEL_NODE_PARAMS_v3): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_KERNEL_NODE_PARAMS_v3), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_KERNEL_NODE_PARAMS_v3)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_set_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), + }) + +mem_set_node_params_v1_dtype = _get_mem_set_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 _data + CUDA_MEMSET_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemSetNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMSET_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMSET_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_set_node_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_set_node_params_v1_dtype", mem_set_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEMSET_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_set_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), + }) + +mem_set_node_params_v2_dtype = _get_mem_set_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMSET_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemSetNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMSET_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMSET_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_MEMSET_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_set_node_params_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_set_node_params_v2_dtype", mem_set_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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_HOST_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This HostNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_HOST_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_HOST_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_HOST_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_HOST_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_CONDITIONAL_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ConditionalNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_CONDITIONAL_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_CONDITIONAL_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_CONDITIONAL_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 device 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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): + 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 _data + CUDA_GRAPH_INSTANTIATE_PARAMS *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This GraphInstantiateParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_GRAPH_INSTANTIATE_PARAMS)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlaunchMemSyncDomainMap)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchMemSyncDomainMap") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUlaunchMemSyncDomainMap *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LaunchMemSyncDomainMap instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlaunchMemSyncDomainMap): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlaunchMemSyncDomainMap), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUlaunchMemSyncDomainMap)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod5_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod5 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod5 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod5 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod5): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod5), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod5)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod5 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_pod5 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_pod5 instance is read-only") + self._ptr[0].z = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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_', '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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod6 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod6 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod6): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod6), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod6)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @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_pod6 instance is read-only") + self._ptr[0].triggerAtBlockStart = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod7_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod7 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod7 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod7 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod7): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod7), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod7)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod7 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_pod7 instance is read-only") + self._ptr[0].flags = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod8_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod8 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod8 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod8 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod8): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod8), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod8)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod8 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_pod8 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_pod8 instance is read-only") + self._ptr[0].z = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod9_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod9 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod9 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod9 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod9): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod9), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod9)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod9 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_pod9 instance is read-only") + self._ptr[0].devNode = val + + @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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUexecAffinitySmCount_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExecAffinitySmCount_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUexecAffinitySmCount_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUexecAffinitySmCount_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUexecAffinitySmCount_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUexecAffinitySmCount_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUctxCigParam *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CtxCigParam instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUctxCigParam): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUctxCigParam), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUctxCigParam)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUctxCigParam)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUlibraryHostUniversalFunctionAndDataTable *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LibraryHostUniversalFunctionAndDataTable instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlibraryHostUniversalFunctionAndDataTable): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlibraryHostUniversalFunctionAndDataTable), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUlibraryHostUniversalFunctionAndDataTable)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy2d_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), + }) + +mem_cpy2d_v2_dtype = _get_mem_cpy2d_v2_dtype_offsets() + +cdef class MemCpy2d_v2: + """Empty-initialize an instance of `CUDA_MEMCPY2D_v2`. + + + .. seealso:: `CUDA_MEMCPY2D_v2` + """ + cdef: + CUDA_MEMCPY2D_v2 _data + CUDA_MEMCPY2D_v2 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpy2d_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMCPY2D_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMCPY2D_v2), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEMCPY2D_v2)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_cpy2d_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy2d_v2_dtype", mem_cpy2d_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEMCPY2D_v2)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy3d_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), + }) + +mem_cpy3d_v2_dtype = _get_mem_cpy3d_v2_dtype_offsets() + +cdef class MemCpy3d_v2: + """Empty-initialize an instance of `CUDA_MEMCPY3D_v2`. + + + .. seealso:: `CUDA_MEMCPY3D_v2` + """ + cdef: + CUDA_MEMCPY3D_v2 _data + CUDA_MEMCPY3D_v2 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpy3d_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMCPY3D_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMCPY3D_v2), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEMCPY3D_v2)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_cpy3d_v2_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy3d_v2_dtype", mem_cpy3d_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEMCPY3D_v2)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy3d_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), + }) + +mem_cpy3d_peer_v1_dtype = _get_mem_cpy3d_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 _data + CUDA_MEMCPY3D_PEER_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpy3dPeer_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMCPY3D_PEER_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMCPY3D_PEER_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEMCPY3D_PEER_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_cpy3d_peer_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy3d_peer_v1_dtype", mem_cpy3d_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEMCPY3D_PEER_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_ARRAY_DESCRIPTOR_v2 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ArrayDescriptor_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_ARRAY_DESCRIPTOR_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_ARRAY_DESCRIPTOR_v2), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_ARRAY_DESCRIPTOR_v2)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_ARRAY3D_DESCRIPTOR_v2 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This Array3dDescriptor_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_ARRAY3D_DESCRIPTOR_v2)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod11_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod11 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_pod11), + }) + +_py_anon_pod11_dtype = _get__py_anon_pod11_dtype_offsets() + +cdef class _py_anon_pod11: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod11`. + + + .. seealso:: `cuda_bindings_driver__anon_pod11` + """ + cdef: + cuda_bindings_driver__anon_pod11 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod11)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod11") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod11 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod11 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_pod11 other_ + if not isinstance(other, _py_anon_pod11): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod11)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod11), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod11 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod11): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod11), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod11)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod11 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_pod11 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_pod11 instance is read-only") + self._ptr[0].depth = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod11 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod11), _py_anon_pod11) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod11 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod11_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod11_dtype", _py_anon_pod11_dtype, _py_anon_pod11) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod11 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_pod11 obj = _py_anon_pod11.__new__(_py_anon_pod11) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod11)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod11") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod11)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ArrayMemoryRequirements_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_ARRAY_MEMORY_REQUIREMENTS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod13_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod13 pod + return _numpy.dtype({ + 'names': ['h_array'], + 'formats': [_numpy.intp], + 'offsets': [ + (&(pod.hArray)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod13), + }) + +_py_anon_pod13_dtype = _get__py_anon_pod13_dtype_offsets() + +cdef class _py_anon_pod13: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod13`. + + + .. seealso:: `cuda_bindings_driver__anon_pod13` + """ + cdef: + cuda_bindings_driver__anon_pod13 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod13)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod13") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod13 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod13 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_pod13 other_ + if not isinstance(other, _py_anon_pod13): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod13)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod13), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod13 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod13): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod13), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod13)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def h_array(self): + """int: """ + return (self._ptr[0].hArray) + + @h_array.setter + def h_array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod13 instance is read-only") + self._ptr[0].hArray = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod13 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod13), _py_anon_pod13) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod13 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod13_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod13_dtype", _py_anon_pod13_dtype, _py_anon_pod13) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod13 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_pod13 obj = _py_anon_pod13.__new__(_py_anon_pod13) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod13)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod13") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod13)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod14_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod14 pod + return _numpy.dtype({ + 'names': ['h_mipmapped_array'], + 'formats': [_numpy.intp], + 'offsets': [ + (&(pod.hMipmappedArray)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod14), + }) + +_py_anon_pod14_dtype = _get__py_anon_pod14_dtype_offsets() + +cdef class _py_anon_pod14: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod14`. + + + .. seealso:: `cuda_bindings_driver__anon_pod14` + """ + cdef: + cuda_bindings_driver__anon_pod14 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod14)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod14") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod14 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod14 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_pod14 other_ + if not isinstance(other, _py_anon_pod14): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod14)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod14), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod14 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod14): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod14), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod14)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def h_mipmapped_array(self): + """int: """ + return (self._ptr[0].hMipmappedArray) + + @h_mipmapped_array.setter + def h_mipmapped_array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod14 instance is read-only") + self._ptr[0].hMipmappedArray = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod14 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod14), _py_anon_pod14) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod14 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod14_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod14_dtype", _py_anon_pod14_dtype, _py_anon_pod14) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod14 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_pod14 obj = _py_anon_pod14.__new__(_py_anon_pod14) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod14)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod14") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod14)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod15_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod15 pod + return _numpy.dtype({ + 'names': ['dev_ptr', 'format', 'num_channels', 'size_in_bytes'], + 'formats': [_numpy.uint64, _numpy.int32, _numpy.uint32, _numpy.uint64], + 'offsets': [ + (&(pod.devPtr)) - (&pod), + (&(pod.format)) - (&pod), + (&(pod.numChannels)) - (&pod), + (&(pod.sizeInBytes)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod15), + }) + +_py_anon_pod15_dtype = _get__py_anon_pod15_dtype_offsets() + +cdef class _py_anon_pod15: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod15`. + + + .. seealso:: `cuda_bindings_driver__anon_pod15` + """ + cdef: + cuda_bindings_driver__anon_pod15 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod15)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod15") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod15 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod15 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_pod15 other_ + if not isinstance(other, _py_anon_pod15): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod15)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod15), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod15 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod15): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod15), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod15)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def dev_ptr(self): + """int: """ + return (self._ptr[0].devPtr) + + @dev_ptr.setter + def dev_ptr(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod15 instance is read-only") + self._ptr[0].devPtr = val + + @property + def format(self): + """int: """ + return (self._ptr[0].format) + + @format.setter + def format(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod15 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 _py_anon_pod15 instance is read-only") + self._ptr[0].numChannels = val + + @property + def size_in_bytes(self): + """int: """ + return self._ptr[0].sizeInBytes + + @size_in_bytes.setter + def size_in_bytes(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod15 instance is read-only") + self._ptr[0].sizeInBytes = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod15 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod15), _py_anon_pod15) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod15 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod15_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod15_dtype", _py_anon_pod15_dtype, _py_anon_pod15) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod15 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_pod15 obj = _py_anon_pod15.__new__(_py_anon_pod15) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod15)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod15") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod15)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod16_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod16 pod + return _numpy.dtype({ + 'names': ['dev_ptr', 'format', 'num_channels', 'width', 'height', 'pitch_in_bytes'], + 'formats': [_numpy.uint64, _numpy.int32, _numpy.uint32, _numpy.uint64, _numpy.uint64, _numpy.uint64], + 'offsets': [ + (&(pod.devPtr)) - (&pod), + (&(pod.format)) - (&pod), + (&(pod.numChannels)) - (&pod), + (&(pod.width)) - (&pod), + (&(pod.height)) - (&pod), + (&(pod.pitchInBytes)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod16), + }) + +_py_anon_pod16_dtype = _get__py_anon_pod16_dtype_offsets() + +cdef class _py_anon_pod16: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod16`. + + + .. seealso:: `cuda_bindings_driver__anon_pod16` + """ + cdef: + cuda_bindings_driver__anon_pod16 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod16)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod16") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod16 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod16 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_pod16 other_ + if not isinstance(other, _py_anon_pod16): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod16)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod16), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod16 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod16): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod16), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod16)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def dev_ptr(self): + """int: """ + return (self._ptr[0].devPtr) + + @dev_ptr.setter + def dev_ptr(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod16 instance is read-only") + self._ptr[0].devPtr = val + + @property + def format(self): + """int: """ + return (self._ptr[0].format) + + @format.setter + def format(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod16 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 _py_anon_pod16 instance is read-only") + self._ptr[0].numChannels = 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_pod16 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_pod16 instance is read-only") + self._ptr[0].height = val + + @property + def pitch_in_bytes(self): + """int: """ + return self._ptr[0].pitchInBytes + + @pitch_in_bytes.setter + def pitch_in_bytes(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod16 instance is read-only") + self._ptr[0].pitchInBytes = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod16 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod16), _py_anon_pod16) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod16 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod16_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod16_dtype", _py_anon_pod16_dtype, _py_anon_pod16) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod16 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_pod16 obj = _py_anon_pod16.__new__(_py_anon_pod16) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod16)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod16") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod16)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod17_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod17 pod + return _numpy.dtype({ + 'names': ['reserved'], + 'formats': [(_numpy.int32, 32)], + 'offsets': [ + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod17), + }) + +_py_anon_pod17_dtype = _get__py_anon_pod17_dtype_offsets() + +cdef class _py_anon_pod17: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod17`. + + + .. seealso:: `cuda_bindings_driver__anon_pod17` + """ + cdef: + cuda_bindings_driver__anon_pod17 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod17)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod17") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod17 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod17 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_pod17 other_ + if not isinstance(other, _py_anon_pod17): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod17)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod17), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod17 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod17): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod17), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod17)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod17 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod17), _py_anon_pod17) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod17 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod17_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod17_dtype", _py_anon_pod17_dtype, _py_anon_pod17) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod17 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_pod17 obj = _py_anon_pod17.__new__(_py_anon_pod17) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod17)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod17") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod17)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_TEXTURE_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This TextureDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_TEXTURE_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_TEXTURE_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_TEXTURE_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def address_mode(self): + """~_numpy.int32: (array of length 3).""" + cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(intptr_t), format="q", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].addressMode)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(3,), itemsize=sizeof(intptr_t), format="q", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.intp) + _cyb_memcpy((&(self._ptr[0].addressMode)), (arr.data), sizeof(intptr_t) * len(val)) + + @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 _cyb_view.array arr = _cyb_view.array(shape=(4,), itemsize=sizeof(float), format="f", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].borderColor)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(4,), itemsize=sizeof(float), format="f", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.float32) + _cyb_memcpy((&(self._ptr[0].borderColor)), (arr.data), sizeof(float) * len(val)) + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_TEXTURE_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_RESOURCE_VIEW_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ResourceViewDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_RESOURCE_VIEW_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_RESOURCE_VIEW_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_RESOURCE_VIEW_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUtensorMap *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This TensorMap instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUtensorMap): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUtensorMap), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUtensorMap)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def opaque(self): + """~_numpy.uint64: (array of length 16).""" + cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(intptr_t), format="q", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].opaque)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(16,), itemsize=sizeof(intptr_t), format="q", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.intp) + _cyb_memcpy((&(self._ptr[0].opaque)), (arr.data), sizeof(intptr_t) * len(val)) + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUtensorMap)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This PointerAttributeP2PTokens_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_LAUNCH_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LaunchParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_LAUNCH_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_LAUNCH_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_LAUNCH_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_LAUNCH_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod19_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod19 pod + return _numpy.dtype({ + 'names': ['handle', 'name'], + 'formats': [_numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.handle)) - (&pod), + (&(pod.name)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod19), + }) + +_py_anon_pod19_dtype = _get__py_anon_pod19_dtype_offsets() + +cdef class _py_anon_pod19: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod19`. + + + .. seealso:: `cuda_bindings_driver__anon_pod19` + """ + cdef: + cuda_bindings_driver__anon_pod19 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod19)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod19") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod19 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod19 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_pod19 other_ + if not isinstance(other, _py_anon_pod19): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod19)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod19), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod19 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod19): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod19), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod19)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def handle(self): + """int: """ + return (self._ptr[0].handle) + + @handle.setter + def handle(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod19 instance is read-only") + self._ptr[0].handle = val + + @property + def name(self): + """int: """ + return (self._ptr[0].name) + + @name.setter + def name(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod19 instance is read-only") + self._ptr[0].name = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod19 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod19), _py_anon_pod19) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod19 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod19_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod19_dtype", _py_anon_pod19_dtype, _py_anon_pod19) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod19 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_pod19 obj = _py_anon_pod19.__new__(_py_anon_pod19) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod19)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod19") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod19)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalMemoryBufferDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod21_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod21 pod + return _numpy.dtype({ + 'names': ['handle', 'name'], + 'formats': [_numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.handle)) - (&pod), + (&(pod.name)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod21), + }) + +_py_anon_pod21_dtype = _get__py_anon_pod21_dtype_offsets() + +cdef class _py_anon_pod21: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod21`. + + + .. seealso:: `cuda_bindings_driver__anon_pod21` + """ + cdef: + cuda_bindings_driver__anon_pod21 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod21)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod21") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod21 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod21 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_pod21 other_ + if not isinstance(other, _py_anon_pod21): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod21)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod21), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod21 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod21): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod21), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod21)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def handle(self): + """int: """ + return (self._ptr[0].handle) + + @handle.setter + def handle(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod21 instance is read-only") + self._ptr[0].handle = val + + @property + def name(self): + """int: """ + return (self._ptr[0].name) + + @name.setter + def name(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod21 instance is read-only") + self._ptr[0].name = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod21 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod21), _py_anon_pod21) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod21 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod21_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod21_dtype", _py_anon_pod21_dtype, _py_anon_pod21) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod21 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_pod21 obj = _py_anon_pod21.__new__(_py_anon_pod21) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod21)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod21") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod21)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod23_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod23 pod + return _numpy.dtype({ + 'names': ['value'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.value)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod23), + }) + +_py_anon_pod23_dtype = _get__py_anon_pod23_dtype_offsets() + +cdef class _py_anon_pod23: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod23`. + + + .. seealso:: `cuda_bindings_driver__anon_pod23` + """ + cdef: + cuda_bindings_driver__anon_pod23 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod23)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod23") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod23 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod23 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_pod23 other_ + if not isinstance(other, _py_anon_pod23): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod23)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod23), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod23 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod23): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod23), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod23)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def value(self): + """int: """ + return self._ptr[0].value + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod23 instance is read-only") + self._ptr[0].value = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod23 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod23), _py_anon_pod23) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod23 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod23_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod23_dtype", _py_anon_pod23_dtype, _py_anon_pod23) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod23 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_pod23 obj = _py_anon_pod23.__new__(_py_anon_pod23) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod23)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod23") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod23)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod24_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod24 pod + return _numpy.dtype({ + 'names': ['fence', 'reserved'], + 'formats': [_numpy.intp, _numpy.uint64], + 'offsets': [ + (&(pod.fence)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod24), + }) + +_py_anon_pod24_dtype = _get__py_anon_pod24_dtype_offsets() + +cdef class _py_anon_pod24: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod24`. + + + .. seealso:: `cuda_bindings_driver__anon_pod24` + """ + cdef: + cuda_bindings_driver__anon_pod24 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod24)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod24") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod24 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod24 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_pod24 other_ + if not isinstance(other, _py_anon_pod24): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod24)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod24), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod24 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod24): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod24), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod24)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def fence(self): + """int: """ + return (self._ptr[0].fence) + + @fence.setter + def fence(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod24 instance is read-only") + self._ptr[0].fence = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod24 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod24), _py_anon_pod24) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod24 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod24_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod24_dtype", _py_anon_pod24_dtype, _py_anon_pod24) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod24 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_pod24 obj = _py_anon_pod24.__new__(_py_anon_pod24) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod24)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod24") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod24)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod25_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod25 pod + return _numpy.dtype({ + 'names': ['key'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.key)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod25), + }) + +_py_anon_pod25_dtype = _get__py_anon_pod25_dtype_offsets() + +cdef class _py_anon_pod25: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod25`. + + + .. seealso:: `cuda_bindings_driver__anon_pod25` + """ + cdef: + cuda_bindings_driver__anon_pod25 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod25)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod25") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod25 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod25 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_pod25 other_ + if not isinstance(other, _py_anon_pod25): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod25)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod25), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod25 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod25): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod25), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod25)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def key(self): + """int: """ + return self._ptr[0].key + + @key.setter + def key(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod25 instance is read-only") + self._ptr[0].key = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod25 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod25), _py_anon_pod25) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod25 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod25_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod25_dtype", _py_anon_pod25_dtype, _py_anon_pod25) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod25 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_pod25 obj = _py_anon_pod25.__new__(_py_anon_pod25) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod25)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod25") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod25)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod27_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod27 pod + return _numpy.dtype({ + 'names': ['value'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.value)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod27), + }) + +_py_anon_pod27_dtype = _get__py_anon_pod27_dtype_offsets() + +cdef class _py_anon_pod27: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod27`. + + + .. seealso:: `cuda_bindings_driver__anon_pod27` + """ + cdef: + cuda_bindings_driver__anon_pod27 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod27)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod27") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod27 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod27 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_pod27 other_ + if not isinstance(other, _py_anon_pod27): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod27)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod27), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod27 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod27): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod27), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod27)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def value(self): + """int: """ + return self._ptr[0].value + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod27 instance is read-only") + self._ptr[0].value = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod27 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod27), _py_anon_pod27) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod27 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod27_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod27_dtype", _py_anon_pod27_dtype, _py_anon_pod27) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod27 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_pod27 obj = _py_anon_pod27.__new__(_py_anon_pod27) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod27)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod27") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod27)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod28_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod28 pod + return _numpy.dtype({ + 'names': ['fence', 'reserved'], + 'formats': [_numpy.intp, _numpy.uint64], + 'offsets': [ + (&(pod.fence)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod28), + }) + +_py_anon_pod28_dtype = _get__py_anon_pod28_dtype_offsets() + +cdef class _py_anon_pod28: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod28`. + + + .. seealso:: `cuda_bindings_driver__anon_pod28` + """ + cdef: + cuda_bindings_driver__anon_pod28 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod28)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod28") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod28 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod28 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_pod28 other_ + if not isinstance(other, _py_anon_pod28): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod28)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod28), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod28 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod28): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod28), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod28)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def fence(self): + """int: """ + return (self._ptr[0].fence) + + @fence.setter + def fence(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod28 instance is read-only") + self._ptr[0].fence = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod28 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod28), _py_anon_pod28) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod28 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod28_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod28_dtype", _py_anon_pod28_dtype, _py_anon_pod28) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod28 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_pod28 obj = _py_anon_pod28.__new__(_py_anon_pod28) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod28)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod28") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod28)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod29_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod29 pod + return _numpy.dtype({ + 'names': ['key', 'timeout_ms'], + 'formats': [_numpy.uint64, _numpy.uint32], + 'offsets': [ + (&(pod.key)) - (&pod), + (&(pod.timeoutMs)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod29 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod29 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod29): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod29), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod29)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def key(self): + """int: """ + return self._ptr[0].key + + @key.setter + def key(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod29 instance is read-only") + self._ptr[0].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 _py_anon_pod29 instance is read-only") + self._ptr[0].timeoutMs = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod32_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod32 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod32 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod32 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod32): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod32), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod32)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod32 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_pod32 instance is read-only") + self._ptr[0].array = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod34_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod34 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_pod34), + }) + +_py_anon_pod34_dtype = _get__py_anon_pod34_dtype_offsets() + +cdef class _py_anon_pod34: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod34`. + + + .. seealso:: `cuda_bindings_driver__anon_pod34` + """ + cdef: + cuda_bindings_driver__anon_pod34 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod34)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod34") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod34 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod34 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_pod34 other_ + if not isinstance(other, _py_anon_pod34): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod34)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod34), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod34 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod34): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod34), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod34)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod34 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_pod34 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_pod34 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_pod34 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_pod34 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_pod34 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_pod34 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_pod34 instance is read-only") + self._ptr[0].extentDepth = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod34 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod34), _py_anon_pod34) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod34 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod34_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod34_dtype", _py_anon_pod34_dtype, _py_anon_pod34) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod34 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_pod34 obj = _py_anon_pod34.__new__(_py_anon_pod34) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod34)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod34") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod34)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod35_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod35 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_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod35 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod35 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod35): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod35), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod35)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod35 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_pod35 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_pod35 instance is read-only") + self._ptr[0].size = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod36_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod36 pod + return _numpy.dtype({ + 'names': ['mem_handle'], + 'formats': [_numpy.uint64], + 'offsets': [ + (&(pod.memHandle)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod36), + }) + +_py_anon_pod36_dtype = _get__py_anon_pod36_dtype_offsets() + +cdef class _py_anon_pod36: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod36`. + + + .. seealso:: `cuda_bindings_driver__anon_pod36` + """ + cdef: + cuda_bindings_driver__anon_pod36 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod36)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod36") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod36 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod36 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_pod36 other_ + if not isinstance(other, _py_anon_pod36): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod36)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod36), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod36 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod36): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod36), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod36)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod36 instance is read-only") + self._ptr[0].memHandle = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod36 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod36), _py_anon_pod36) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod36 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod36_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod36_dtype", _py_anon_pod36_dtype, _py_anon_pod36) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod36 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_pod36 obj = _py_anon_pod36.__new__(_py_anon_pod36) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod36)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod36") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod36)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod38_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod38 pod + return _numpy.dtype({ + 'names': ['device_id', 'locality_domain_id'], + 'formats': [_numpy.uint8, _numpy.uint8], + 'offsets': [ + (&(pod.deviceId)) - (&pod), + (&(pod.localityDomainId)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod38), + }) + +_py_anon_pod38_dtype = _get__py_anon_pod38_dtype_offsets() + +cdef class _py_anon_pod38: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod38`. + + + .. seealso:: `cuda_bindings_driver__anon_pod38` + """ + cdef: + cuda_bindings_driver__anon_pod38 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod38)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod38") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod38 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod38 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_pod38 other_ + if not isinstance(other, _py_anon_pod38): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod38)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod38), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod38 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod38): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod38), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod38)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def device_id(self): + """int: """ + return self._ptr[0].deviceId + + @device_id.setter + def device_id(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod38 instance is read-only") + self._ptr[0].deviceId = val + + @property + def locality_domain_id(self): + """int: """ + return self._ptr[0].localityDomainId + + @locality_domain_id.setter + def locality_domain_id(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod38 instance is read-only") + self._ptr[0].localityDomainId = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod38 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod38), _py_anon_pod38) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod38 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod38_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod38_dtype", _py_anon_pod38_dtype, _py_anon_pod38) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod38 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_pod38 obj = _py_anon_pod38.__new__(_py_anon_pod38) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod38)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod38") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod38)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod39_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod39 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_pod39), + }) + +_py_anon_pod39_dtype = _get__py_anon_pod39_dtype_offsets() + +cdef class _py_anon_pod39: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod39`. + + + .. seealso:: `cuda_bindings_driver__anon_pod39` + """ + cdef: + cuda_bindings_driver__anon_pod39 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod39)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod39") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod39 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod39 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_pod39 other_ + if not isinstance(other, _py_anon_pod39): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod39)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod39), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod39 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod39): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod39), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod39)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod39 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_pod39 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_pod39 instance is read-only") + self._ptr[0].usage = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod39 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod39), _py_anon_pod39) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod39 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod39_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod39_dtype", _py_anon_pod39_dtype, _py_anon_pod39) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod39 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_pod39 obj = _py_anon_pod39.__new__(_py_anon_pod39) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod39)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod39") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod39)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUmulticastObjectProp_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MulticastObjectProp_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmulticastObjectProp_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmulticastObjectProp_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmulticastObjectProp_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmulticastObjectProp_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + 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 _data + CUgraphExecUpdateResultInfo_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This GraphExecUpdateResultInfo_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUgraphExecUpdateResultInfo_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUgraphExecUpdateResultInfo_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUgraphExecUpdateResultInfo_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUgraphExecUpdateResultInfo_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUmemPoolPtrExportData_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemPoolPtrExportData_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemPoolPtrExportData_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemPoolPtrExportData_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemPoolPtrExportData_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemPoolPtrExportData_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUoffset3D_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This Offset3D_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUoffset3D_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUoffset3D_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUoffset3D_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUoffset3D_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUextent3D_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This Extent3D_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUextent3D_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUextent3D_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUextent3D_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUextent3D_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEM_FREE_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemFreeNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEM_FREE_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEM_FREE_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_MEM_FREE_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_CHILD_GRAPH_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ChildGraphNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_CHILD_GRAPH_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EVENT_WAIT_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This EventWaitNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EVENT_WAIT_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EVENT_WAIT_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_EVENT_WAIT_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUcheckpointLockArgs *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CheckpointLockArgs instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUcheckpointLockArgs): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUcheckpointLockArgs), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUcheckpointLockArgs)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUcheckpointLockArgs)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUcheckpointUnlockArgs *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CheckpointUnlockArgs instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUcheckpointUnlockArgs): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUcheckpointUnlockArgs), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUcheckpointUnlockArgs)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUcheckpointUnlockArgs)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUmemDecompressParams *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemDecompressParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemDecompressParams): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemDecompressParams), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemDecompressParams)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemDecompressParams)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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_', 'locality_domain_id'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.smCount)) - (&pod), + (&(pod.minSmPartitionSize)) - (&pod), + (&(pod.smCoscheduledAlignment)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.localityDomainId)) - (&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 _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevSmResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevSmResource") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUdevSmResource *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUdevSmResource): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUdevSmResource), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUdevSmResource)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @property + def locality_domain_id(self): + """int: """ + return self._ptr[0].localityDomainId + + @locality_domain_id.setter + def locality_domain_id(self, val): + if self._readonly: + raise ValueError("This DevSmResource instance is read-only") + self._ptr[0].localityDomainId = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevWorkqueueConfigResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueConfigResource") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUdevWorkqueueConfigResource *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This DevWorkqueueConfigResource instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUdevWorkqueueConfigResource): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUdevWorkqueueConfigResource), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUdevWorkqueueConfigResource)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUdevWorkqueueResource)) + if self._ptr == NULL: + raise MemoryError("Error allocating DevWorkqueueResource") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUdevWorkqueueResource *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This DevWorkqueueResource instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUdevWorkqueueResource): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUdevWorkqueueResource), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUdevWorkqueueResource)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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_', 'locality_domain_id', 'reserved'], + 'formats': [_numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, _numpy.uint32, (_numpy.uint32, 11)], + 'offsets': [ + (&(pod.smCount)) - (&pod), + (&(pod.coscheduledSmCount)) - (&pod), + (&(pod.preferredCoscheduledSmCount)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.localityDomainId)) - (&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): + 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 + + @property + def locality_domain_id(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.locality_domain_id[0]) + return self._data.locality_domain_id + + @locality_domain_id.setter + def locality_domain_id(self, val): + self._data.locality_domain_id = 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 _data + CUstreamCigParam *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamCigParam instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamCigParam): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamCigParam), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUstreamCigParam)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUstreamCigParam)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUlogicalEndpointFabricHandle *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LogicalEndpointFabricHandle instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlogicalEndpointFabricHandle): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlogicalEndpointFabricHandle), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUlogicalEndpointFabricHandle)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def data_(self): + """~_numpy.uint8: (array of length 64).""" + cdef _cyb_view.array arr = _cyb_view.array(shape=(64,), itemsize=sizeof(unsigned char), format="B", mode="c", allocate_buffer=False) + arr.data = (&(self._ptr[0].data)) + return _numpy.asarray(arr) + + @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)}") + cdef _cyb_view.array arr = _cyb_view.array(shape=(64,), itemsize=sizeof(unsigned char), format="B", mode="c") + arr[:] = _numpy.asarray(val, dtype=_numpy.uint8) + _cyb_memcpy((&(self._ptr[0].data)), (arr.data), sizeof(unsigned char) * len(val)) + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUlogicalEndpointFabricHandle)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod47_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod47 pod + return _numpy.dtype({ + 'names': ['device_'], + 'formats': [_numpy.int32], + 'offsets': [ + (&(pod.device)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod47), + }) + +_py_anon_pod47_dtype = _get__py_anon_pod47_dtype_offsets() + +cdef class _py_anon_pod47: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod47`. + + + .. seealso:: `cuda_bindings_driver__anon_pod47` + """ + cdef: + cuda_bindings_driver__anon_pod47 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod47)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod47") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod47 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod47 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_pod47 other_ + if not isinstance(other, _py_anon_pod47): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod47)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod47), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod47 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod47): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod47), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod47)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 _py_anon_pod47 instance is read-only") + self._ptr[0].device = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod47 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod47), _py_anon_pod47) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod47 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod47_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod47_dtype", _py_anon_pod47_dtype, _py_anon_pod47) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod47 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_pod47 obj = _py_anon_pod47.__new__(_py_anon_pod47) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod47)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod47") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod47)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod48_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod48 pod + return _numpy.dtype({ + 'names': ['num_devices'], + 'formats': [_numpy.uint32], + 'offsets': [ + (&(pod.numDevices)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod48), + }) + +_py_anon_pod48_dtype = _get__py_anon_pod48_dtype_offsets() + +cdef class _py_anon_pod48: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod48`. + + + .. seealso:: `cuda_bindings_driver__anon_pod48` + """ + cdef: + cuda_bindings_driver__anon_pod48 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod48)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod48") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod48 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod48 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_pod48 other_ + if not isinstance(other, _py_anon_pod48): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod48)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod48), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod48 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod48): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod48), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod48)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 _py_anon_pod48 instance is read-only") + self._ptr[0].numDevices = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod48 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod48), _py_anon_pod48) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod48 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod48_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod48_dtype", _py_anon_pod48_dtype, _py_anon_pod48) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod48 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_pod48 obj = _py_anon_pod48.__new__(_py_anon_pod48) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod48)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod48") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod48)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_clique_info_dtype_offsets(): + cdef CUcliqueInfo pod + return _numpy.dtype({ + 'names': ['type', 'id'], + 'formats': [_numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.id)) - (&pod), + ], + 'itemsize': sizeof(CUcliqueInfo), + }) + +clique_info_dtype = _get_clique_info_dtype_offsets() + +cdef class CliqueInfo: + """Empty-initialize an array of `CUcliqueInfo`. + The resulting object is of length `size` and of dtype `clique_info_dtype`. + If default-constructed, the instance represents a single struct. + + Args: + size (int): number of structs, default=1. + + .. seealso:: `CUcliqueInfo` + """ + cdef: + readonly object _data + object _owner + + def __init__(self, size=1): + arr = _numpy.zeros(size, dtype=clique_info_dtype) + self._data = arr.view(_numpy.recarray) + assert self._data.itemsize == sizeof(CUcliqueInfo), \ + f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUcliqueInfo) }" + + def __repr__(self): + if self._data.size > 1: + return f"<{__name__}.CliqueInfo_Array_{self._data.size} object at {hex(id(self))}>" + else: + return f"<{__name__}.CliqueInfo 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, CliqueInfo)) 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 id(self): + """Union[~_numpy.uint32, int]: """ + if self._data.size == 1: + return int(self._data.id[0]) + return self._data.id + + @id.setter + def id(self, val): + self._data.id = 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 CliqueInfo.from_data(self._data[key_:key_+1]) + out = self._data[key] + if isinstance(out, _numpy.recarray) and out.dtype == clique_info_dtype: + return CliqueInfo.from_data(out) + return out + + def __setitem__(self, key, val): + self._data[key] = val + + @staticmethod + def from_buffer(buffer): + """Create an CliqueInfo instance with the memory from the given buffer.""" + return CliqueInfo.from_data(_numpy.frombuffer(buffer, dtype=clique_info_dtype)) + + @staticmethod + def from_data(data): + """Create an CliqueInfo instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a 1D array of dtype `clique_info_dtype` holding the data. + """ + cdef CliqueInfo obj = CliqueInfo.__new__(CliqueInfo) + 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 != clique_info_dtype: + raise ValueError("data array must be of dtype clique_info_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 CliqueInfo 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 CliqueInfo obj = CliqueInfo.__new__(CliqueInfo) + 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(CUcliqueInfo) * size, flag) + data = _numpy.ndarray(size, buffer=buf, dtype=clique_info_dtype) + obj._data = data.view(_numpy.recarray) + obj._owner = owner + + 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 _data + CUcheckpointGpuPair *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CheckpointGpuPair instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUcheckpointGpuPair): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUcheckpointGpuPair), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUcheckpointGpuPair)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUcheckpointGpuPair)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_mem_op_wait_value_params_dtype_offsets(): + cdef CUstreamMemOpWaitValueParams_st pod + return _numpy.dtype({ + 'names': ['operation', 'address', 'value', 'value64', 'flags_', 'alias'], + 'formats': [_numpy.int32, _numpy.uint64, _numpy.uint32, _numpy.uint64, _numpy.uint32, _numpy.uint64], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.address)) - (&pod), + (&(pod.value)) - (&pod), + (&(pod.value64)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.alias)) - (&pod), + ], + 'itemsize': sizeof(CUstreamMemOpWaitValueParams_st), + }) + +stream_mem_op_wait_value_params_dtype = _get_stream_mem_op_wait_value_params_dtype_offsets() + +cdef class StreamMemOpWaitValueParams: + """Empty-initialize an instance of `CUstreamMemOpWaitValueParams_st`. + + + .. seealso:: `CUstreamMemOpWaitValueParams_st` + """ + cdef: + CUstreamMemOpWaitValueParams_st *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamMemOpWaitValueParams_st)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpWaitValueParams") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUstreamMemOpWaitValueParams_st *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamMemOpWaitValueParams 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 StreamMemOpWaitValueParams other_ + if not isinstance(other, StreamMemOpWaitValueParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamMemOpWaitValueParams_st)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamMemOpWaitValueParams_st), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamMemOpWaitValueParams_st): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamMemOpWaitValueParams_st), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUstreamMemOpWaitValueParams_st)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def operation(self): + """int: """ + return (self._ptr[0].operation) + + @operation.setter + def operation(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].operation = val + + @property + def address(self): + """int: """ + return (self._ptr[0].address) + + @address.setter + def address(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].address = val + + @property + def value(self): + """int: """ + return (self._ptr[0].value) + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].value = val + + @property + def value64(self): + """int: """ + return (self._ptr[0].value64) + + @value64.setter + def value64(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].value64 = val + + @property + def flags_(self): + """int: See CUstreamWaitValue_flags.""" + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].flags = val + + @property + def alias(self): + """int: For driver internal use. Initial value is unimportant.""" + return (self._ptr[0].alias) + + @alias.setter + def alias(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWaitValueParams instance is read-only") + self._ptr[0].alias = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamMemOpWaitValueParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamMemOpWaitValueParams_st), StreamMemOpWaitValueParams) + + @staticmethod + def from_data(data): + """Create an StreamMemOpWaitValueParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_mem_op_wait_value_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_mem_op_wait_value_params_dtype", stream_mem_op_wait_value_params_dtype, StreamMemOpWaitValueParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamMemOpWaitValueParams 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 StreamMemOpWaitValueParams obj = StreamMemOpWaitValueParams.__new__(StreamMemOpWaitValueParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamMemOpWaitValueParams_st)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpWaitValueParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamMemOpWaitValueParams_st)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_mem_op_write_value_params_dtype_offsets(): + cdef CUstreamMemOpWriteValueParams_st pod + return _numpy.dtype({ + 'names': ['operation', 'address', 'value', 'value64', 'flags_', 'alias'], + 'formats': [_numpy.int32, _numpy.uint64, _numpy.uint32, _numpy.uint64, _numpy.uint32, _numpy.uint64], + 'offsets': [ + (&(pod.operation)) - (&pod), + (&(pod.address)) - (&pod), + (&(pod.value)) - (&pod), + (&(pod.value64)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.alias)) - (&pod), + ], + 'itemsize': sizeof(CUstreamMemOpWriteValueParams_st), + }) + +stream_mem_op_write_value_params_dtype = _get_stream_mem_op_write_value_params_dtype_offsets() + +cdef class StreamMemOpWriteValueParams: + """Empty-initialize an instance of `CUstreamMemOpWriteValueParams_st`. + + + .. seealso:: `CUstreamMemOpWriteValueParams_st` + """ + cdef: + CUstreamMemOpWriteValueParams_st *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUstreamMemOpWriteValueParams_st)) + if self._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpWriteValueParams") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUstreamMemOpWriteValueParams_st *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.StreamMemOpWriteValueParams 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 StreamMemOpWriteValueParams other_ + if not isinstance(other, StreamMemOpWriteValueParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamMemOpWriteValueParams_st)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamMemOpWriteValueParams_st), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamMemOpWriteValueParams_st): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamMemOpWriteValueParams_st), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUstreamMemOpWriteValueParams_st)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def operation(self): + """int: """ + return (self._ptr[0].operation) + + @operation.setter + def operation(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].operation = val + + @property + def address(self): + """int: """ + return (self._ptr[0].address) + + @address.setter + def address(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].address = val + + @property + def value(self): + """int: """ + return (self._ptr[0].value) + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].value = val + + @property + def value64(self): + """int: """ + return (self._ptr[0].value64) + + @value64.setter + def value64(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].value64 = val + + @property + def flags_(self): + """int: See CUstreamWriteValue_flags.""" + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].flags = val + + @property + def alias(self): + """int: For driver internal use. Initial value is unimportant.""" + return (self._ptr[0].alias) + + @alias.setter + def alias(self, val): + if self._readonly: + raise ValueError("This StreamMemOpWriteValueParams instance is read-only") + self._ptr[0].alias = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamMemOpWriteValueParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamMemOpWriteValueParams_st), StreamMemOpWriteValueParams) + + @staticmethod + def from_data(data): + """Create an StreamMemOpWriteValueParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_mem_op_write_value_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_mem_op_write_value_params_dtype", stream_mem_op_write_value_params_dtype, StreamMemOpWriteValueParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamMemOpWriteValueParams 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 StreamMemOpWriteValueParams obj = StreamMemOpWriteValueParams.__new__(StreamMemOpWriteValueParams) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUstreamMemOpWriteValueParams_st)) + if obj._ptr == NULL: + raise MemoryError("Error allocating StreamMemOpWriteValueParams") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUstreamMemOpWriteValueParams_st)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod2_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod2 pod + return _numpy.dtype({ + 'names': ['over_budget'], + 'formats': [_py_anon_pod3_dtype], + 'offsets': [ + (&(pod.overBudget)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod2), + }) + +_py_anon_pod2_dtype = _get__py_anon_pod2_dtype_offsets() + +cdef class _py_anon_pod2: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod2`. + + + .. seealso:: `cuda_bindings_driver__anon_pod2` + """ + cdef: + cuda_bindings_driver__anon_pod2 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod2)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod2") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod2 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod2 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_pod2 other_ + if not isinstance(other, _py_anon_pod2): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod2)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod2), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def over_budget(self): + """_py_anon_pod3: """ + return _py_anon_pod3.from_ptr( + &(self._ptr[0].overBudget), + readonly=self._readonly, + owner=self, + ) + + @over_budget.setter + def over_budget(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod2 instance is read-only") + cdef _py_anon_pod3 val_ = val + _cyb_memcpy(&(self._ptr[0].overBudget), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod3) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod2 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod2), _py_anon_pod2) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod2 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod2_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod2_dtype", _py_anon_pod2_dtype, _py_anon_pod2) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod2 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_pod2 obj = _py_anon_pod2.__new__(_py_anon_pod2) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod2)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod2") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod2)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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', 'ctx', 'g_ctx'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.fn)) - (&pod), + (&(pod.userData)) - (&pod), + (&(pod.syncMode)) - (&pod), + (&(pod.ctx)) - (&pod), + (&(pod.gCtx)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_HOST_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_HOST_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_HOST_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_HOST_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @property + def g_ctx(self): + """int: """ + return (self._ptr[0].gCtx) + + @g_ctx.setter + def g_ctx(self, val): + if self._readonly: + raise ValueError("This HostNodeParams_v2 instance is read-only") + self._ptr[0].gCtx = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_launch_attribute_value_dtype_offsets(): + cdef CUlaunchAttributeValue pod + return _numpy.dtype({ + 'names': ['pad', 'access_policy_window', 'cooperative', 'sync_policy', 'cluster_dim', 'cluster_scheduling_policy_preference', 'programmatic_stream_serialization_allowed', 'programmatic_event', 'launch_completion_event', 'priority', 'mem_sync_domain_map', 'mem_sync_domain', 'preferred_cluster_dim', 'device_updatable_kernel_node', 'shared_mem_carveout', 'nvlink_util_centric_scheduling', 'portable_cluster_size_mode', 'shared_memory_mode'], + 'formats': [(_numpy.int8, 64), access_policy_window_v1_dtype, _numpy.int32, _numpy.int32, _py_anon_pod5_dtype, _numpy.int32, _numpy.int32, _py_anon_pod6_dtype, _py_anon_pod7_dtype, _numpy.int32, launch_mem_sync_domain_map_dtype, _numpy.int32, _py_anon_pod8_dtype, _py_anon_pod9_dtype, _numpy.uint32, _numpy.uint32, _numpy.int32, _numpy.int32], + 'offsets': [ + (&(pod.pad)) - (&pod), + (&(pod.accessPolicyWindow)) - (&pod), + (&(pod.cooperative)) - (&pod), + (&(pod.syncPolicy)) - (&pod), + (&(pod.clusterDim)) - (&pod), + (&(pod.clusterSchedulingPolicyPreference)) - (&pod), + (&(pod.programmaticStreamSerializationAllowed)) - (&pod), + (&(pod.programmaticEvent)) - (&pod), + (&(pod.launchCompletionEvent)) - (&pod), + (&(pod.priority)) - (&pod), + (&(pod.memSyncDomainMap)) - (&pod), + (&(pod.memSyncDomain)) - (&pod), + (&(pod.preferredClusterDim)) - (&pod), + (&(pod.deviceUpdatableKernelNode)) - (&pod), + (&(pod.sharedMemCarveout)) - (&pod), + (&(pod.nvlinkUtilCentricScheduling)) - (&pod), + (&(pod.portableClusterSizeMode)) - (&pod), + (&(pod.sharedMemoryMode)) - (&pod), + ], + 'itemsize': sizeof(CUlaunchAttributeValue), + }) + +launch_attribute_value_dtype = _get_launch_attribute_value_dtype_offsets() + +cdef class LaunchAttributeValue: + """Empty-initialize an instance of `CUlaunchAttributeValue`. + + + .. seealso:: `CUlaunchAttributeValue` + """ + cdef: + CUlaunchAttributeValue *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(CUlaunchAttributeValue)) + if self._ptr == NULL: + raise MemoryError("Error allocating LaunchAttributeValue") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUlaunchAttributeValue *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}.LaunchAttributeValue 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 LaunchAttributeValue other_ + if not isinstance(other, LaunchAttributeValue): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlaunchAttributeValue)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlaunchAttributeValue), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlaunchAttributeValue): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlaunchAttributeValue), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUlaunchAttributeValue)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def access_policy_window(self): + """AccessPolicyWindow_v1: """ + return AccessPolicyWindow_v1.from_ptr( + &(self._ptr[0].accessPolicyWindow), + readonly=self._readonly, + owner=self, + ) + + @access_policy_window.setter + def access_policy_window(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef AccessPolicyWindow_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].accessPolicyWindow), (val_._get_ptr()), sizeof(CUaccessPolicyWindow) * 1) + + @property + def cluster_dim(self): + """_py_anon_pod5: """ + return _py_anon_pod5.from_ptr( + &(self._ptr[0].clusterDim), + readonly=self._readonly, + owner=self, + ) + + @cluster_dim.setter + def cluster_dim(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef _py_anon_pod5 val_ = val + _cyb_memcpy(&(self._ptr[0].clusterDim), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod5) * 1) + + @property + def programmatic_event(self): + """_py_anon_pod6: """ + return _py_anon_pod6.from_ptr( + &(self._ptr[0].programmaticEvent), + readonly=self._readonly, + owner=self, + ) + + @programmatic_event.setter + def programmatic_event(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef _py_anon_pod6 val_ = val + _cyb_memcpy(&(self._ptr[0].programmaticEvent), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod6) * 1) + + @property + def launch_completion_event(self): + """_py_anon_pod7: """ + return _py_anon_pod7.from_ptr( + &(self._ptr[0].launchCompletionEvent), + readonly=self._readonly, + owner=self, + ) + + @launch_completion_event.setter + def launch_completion_event(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef _py_anon_pod7 val_ = val + _cyb_memcpy(&(self._ptr[0].launchCompletionEvent), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod7) * 1) + + @property + def mem_sync_domain_map(self): + """LaunchMemSyncDomainMap: """ + return LaunchMemSyncDomainMap.from_ptr( + &(self._ptr[0].memSyncDomainMap), + readonly=self._readonly, + owner=self, + ) + + @mem_sync_domain_map.setter + def mem_sync_domain_map(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef LaunchMemSyncDomainMap val_ = val + _cyb_memcpy(&(self._ptr[0].memSyncDomainMap), (val_._get_ptr()), sizeof(CUlaunchMemSyncDomainMap) * 1) + + @property + def preferred_cluster_dim(self): + """_py_anon_pod8: """ + return _py_anon_pod8.from_ptr( + &(self._ptr[0].preferredClusterDim), + readonly=self._readonly, + owner=self, + ) + + @preferred_cluster_dim.setter + def preferred_cluster_dim(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef _py_anon_pod8 val_ = val + _cyb_memcpy(&(self._ptr[0].preferredClusterDim), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod8) * 1) + + @property + def device_updatable_kernel_node(self): + """_py_anon_pod9: """ + return _py_anon_pod9.from_ptr( + &(self._ptr[0].deviceUpdatableKernelNode), + readonly=self._readonly, + owner=self, + ) + + @device_updatable_kernel_node.setter + def device_updatable_kernel_node(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + cdef _py_anon_pod9 val_ = val + _cyb_memcpy(&(self._ptr[0].deviceUpdatableKernelNode), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod9) * 1) + + @property + def cooperative(self): + """int: """ + return self._ptr[0].cooperative + + @cooperative.setter + def cooperative(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].cooperative = val + + @property + def sync_policy(self): + """int: """ + return (self._ptr[0].syncPolicy) + + @sync_policy.setter + def sync_policy(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].syncPolicy = val + + @property + def cluster_scheduling_policy_preference(self): + """int: """ + return (self._ptr[0].clusterSchedulingPolicyPreference) + + @cluster_scheduling_policy_preference.setter + def cluster_scheduling_policy_preference(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].clusterSchedulingPolicyPreference = val + + @property + def programmatic_stream_serialization_allowed(self): + """int: """ + return self._ptr[0].programmaticStreamSerializationAllowed + + @programmatic_stream_serialization_allowed.setter + def programmatic_stream_serialization_allowed(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].programmaticStreamSerializationAllowed = val + + @property + def priority(self): + """int: """ + return self._ptr[0].priority + + @priority.setter + def priority(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].priority = val + + @property + def mem_sync_domain(self): + """int: """ + return (self._ptr[0].memSyncDomain) + + @mem_sync_domain.setter + def mem_sync_domain(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].memSyncDomain = val + + @property + def shared_mem_carveout(self): + """int: """ + return self._ptr[0].sharedMemCarveout + + @shared_mem_carveout.setter + def shared_mem_carveout(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].sharedMemCarveout = val + + @property + def nvlink_util_centric_scheduling(self): + """int: """ + return self._ptr[0].nvlinkUtilCentricScheduling + + @nvlink_util_centric_scheduling.setter + def nvlink_util_centric_scheduling(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].nvlinkUtilCentricScheduling = val + + @property + def portable_cluster_size_mode(self): + """int: """ + return (self._ptr[0].portableClusterSizeMode) + + @portable_cluster_size_mode.setter + def portable_cluster_size_mode(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].portableClusterSizeMode = val + + @property + def shared_memory_mode(self): + """int: """ + return (self._ptr[0].sharedMemoryMode) + + @shared_memory_mode.setter + def shared_memory_mode(self, val): + if self._readonly: + raise ValueError("This LaunchAttributeValue instance is read-only") + self._ptr[0].sharedMemoryMode = val + + @staticmethod + def from_buffer(buffer): + """Create an LaunchAttributeValue instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlaunchAttributeValue), LaunchAttributeValue) + + @staticmethod + def from_data(data): + """Create an LaunchAttributeValue instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `launch_attribute_value_dtype` holding the data. + """ + return _cyb_from_data(data, "launch_attribute_value_dtype", launch_attribute_value_dtype, LaunchAttributeValue) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LaunchAttributeValue 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 LaunchAttributeValue obj = LaunchAttributeValue.__new__(LaunchAttributeValue) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(CUlaunchAttributeValue)) + if obj._ptr == NULL: + raise MemoryError("Error allocating LaunchAttributeValue") + _cyb_memcpy((obj._ptr), ptr, sizeof(CUlaunchAttributeValue)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod10_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod10 pod + return _numpy.dtype({ + 'names': ['sm_count'], + 'formats': [exec_affinity_sm_count_v1_dtype], + 'offsets': [ + (&(pod.smCount)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod10 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod10 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod10): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod10), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod10)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod10 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_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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy_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, mem_cpy3d_v2_dtype], + 'offsets': [ + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + (&(pod.copyCtx)) - (&pod), + (&(pod.copyParams)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY_NODE_PARAMS), + }) + +mem_cpy_node_params_dtype = _get_mem_cpy_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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEMCPY_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpyNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMCPY_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMCPY_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_MEMCPY_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_cpy_node_params_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy_node_params_dtype", mem_cpy_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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_external_memory_mipmapped_array_desc_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 pod + return _numpy.dtype({ + 'names': ['offset', 'array_desc', 'num_levels', 'reserved'], + 'formats': [_numpy.uint64, array3d_descriptor_v2_dtype, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.offset)) - (&pod), + (&(pod.arrayDesc)) - (&pod), + (&(pod.numLevels)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1), + }) + +external_memory_mipmapped_array_desc_v1_dtype = _get_external_memory_mipmapped_array_desc_v1_dtype_offsets() + +cdef class ExternalMemoryMipmappedArrayDesc_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1`. + + + .. seealso:: `CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1` + """ + cdef: + CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 _data + CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ExternalMemoryMipmappedArrayDesc_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 ExternalMemoryMipmappedArrayDesc_v1 other_ + if not isinstance(other, ExternalMemoryMipmappedArrayDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalMemoryMipmappedArrayDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def array_desc(self): + """Array3dDescriptor_v2: """ + return Array3dDescriptor_v2.from_ptr( + &(self._ptr[0].arrayDesc), + readonly=self._readonly, + owner=self, + ) + + @array_desc.setter + def array_desc(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryMipmappedArrayDesc_v1 instance is read-only") + cdef Array3dDescriptor_v2 val_ = val + _cyb_memcpy(&(self._ptr[0].arrayDesc), (val_._get_ptr()), sizeof(CUDA_ARRAY3D_DESCRIPTOR) * 1) + + @property + def offset(self): + """int: """ + return self._ptr[0].offset + + @offset.setter + def offset(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryMipmappedArrayDesc_v1 instance is read-only") + self._ptr[0].offset = val + + @property + def num_levels(self): + """int: """ + return self._ptr[0].numLevels + + @num_levels.setter + def num_levels(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryMipmappedArrayDesc_v1 instance is read-only") + self._ptr[0].numLevels = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalMemoryMipmappedArrayDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1), ExternalMemoryMipmappedArrayDesc_v1) + + @staticmethod + def from_data(data): + """Create an ExternalMemoryMipmappedArrayDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_memory_mipmapped_array_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_memory_mipmapped_array_desc_v1_dtype", external_memory_mipmapped_array_desc_v1_dtype, ExternalMemoryMipmappedArrayDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalMemoryMipmappedArrayDesc_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 ExternalMemoryMipmappedArrayDesc_v1 obj = ExternalMemoryMipmappedArrayDesc_v1.__new__(ExternalMemoryMipmappedArrayDesc_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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_pod11_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 _data + CUDA_ARRAY_SPARSE_PROPERTIES_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ArraySparseProperties_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def tile_extent(self): + """_py_anon_pod11: """ + return _py_anon_pod11.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_pod11 val_ = val + _cyb_memcpy(&(self._ptr[0].tileExtent), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod11) * 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_ARRAY_SPARSE_PROPERTIES_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod12_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod12 pod + return _numpy.dtype({ + 'names': ['array', 'mipmap', 'linear', 'pitch2d', 'reserved'], + 'formats': [_py_anon_pod13_dtype, _py_anon_pod14_dtype, _py_anon_pod15_dtype, _py_anon_pod16_dtype, _py_anon_pod17_dtype], + 'offsets': [ + (&(pod.array)) - (&pod), + (&(pod.mipmap)) - (&pod), + (&(pod.linear)) - (&pod), + (&(pod.pitch2D)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod12), + }) + +_py_anon_pod12_dtype = _get__py_anon_pod12_dtype_offsets() + +cdef class _py_anon_pod12: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod12`. + + + .. seealso:: `cuda_bindings_driver__anon_pod12` + """ + cdef: + cuda_bindings_driver__anon_pod12 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod12)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod12") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod12 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod12 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_pod12 other_ + if not isinstance(other, _py_anon_pod12): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod12)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod12), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod12 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod12): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod12), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod12)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def array(self): + """_py_anon_pod13: """ + return _py_anon_pod13.from_ptr( + &(self._ptr[0].array), + readonly=self._readonly, + owner=self, + ) + + @array.setter + def array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod12 instance is read-only") + cdef _py_anon_pod13 val_ = val + _cyb_memcpy(&(self._ptr[0].array), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod13) * 1) + + @property + def mipmap(self): + """_py_anon_pod14: """ + return _py_anon_pod14.from_ptr( + &(self._ptr[0].mipmap), + readonly=self._readonly, + owner=self, + ) + + @mipmap.setter + def mipmap(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod12 instance is read-only") + cdef _py_anon_pod14 val_ = val + _cyb_memcpy(&(self._ptr[0].mipmap), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod14) * 1) + + @property + def linear(self): + """_py_anon_pod15: """ + return _py_anon_pod15.from_ptr( + &(self._ptr[0].linear), + readonly=self._readonly, + owner=self, + ) + + @linear.setter + def linear(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod12 instance is read-only") + cdef _py_anon_pod15 val_ = val + _cyb_memcpy(&(self._ptr[0].linear), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod15) * 1) + + @property + def pitch2d(self): + """_py_anon_pod16: """ + return _py_anon_pod16.from_ptr( + &(self._ptr[0].pitch2D), + readonly=self._readonly, + owner=self, + ) + + @pitch2d.setter + def pitch2d(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod12 instance is read-only") + cdef _py_anon_pod16 val_ = val + _cyb_memcpy(&(self._ptr[0].pitch2D), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod16) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod12 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod12), _py_anon_pod12) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod12 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod12_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod12_dtype", _py_anon_pod12_dtype, _py_anon_pod12) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod12 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_pod12 obj = _py_anon_pod12.__new__(_py_anon_pod12) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod12)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod12") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod12)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod18_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod18 pod + return _numpy.dtype({ + 'names': ['fd', 'win32', 'nv_sci_buf_object'], + 'formats': [_numpy.int32, _py_anon_pod19_dtype, _numpy.intp], + 'offsets': [ + (&(pod.fd)) - (&pod), + (&(pod.win32)) - (&pod), + (&(pod.nvSciBufObject)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod18), + }) + +_py_anon_pod18_dtype = _get__py_anon_pod18_dtype_offsets() + +cdef class _py_anon_pod18: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod18`. + + + .. seealso:: `cuda_bindings_driver__anon_pod18` + """ + cdef: + cuda_bindings_driver__anon_pod18 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod18)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod18") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod18 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod18 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_pod18 other_ + if not isinstance(other, _py_anon_pod18): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod18)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod18), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod18 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod18): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod18), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod18)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def win32(self): + """_py_anon_pod19: """ + return _py_anon_pod19.from_ptr( + &(self._ptr[0].win32), + readonly=self._readonly, + owner=self, + ) + + @win32.setter + def win32(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod18 instance is read-only") + cdef _py_anon_pod19 val_ = val + _cyb_memcpy(&(self._ptr[0].win32), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod19) * 1) + + @property + def fd(self): + """int: """ + return self._ptr[0].fd + + @fd.setter + def fd(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod18 instance is read-only") + self._ptr[0].fd = val + + @property + def nv_sci_buf_object(self): + """int: """ + return (self._ptr[0].nvSciBufObject) + + @nv_sci_buf_object.setter + def nv_sci_buf_object(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod18 instance is read-only") + self._ptr[0].nvSciBufObject = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod18 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod18), _py_anon_pod18) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod18 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod18_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod18_dtype", _py_anon_pod18_dtype, _py_anon_pod18) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod18 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_pod18 obj = _py_anon_pod18.__new__(_py_anon_pod18) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod18)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod18") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod18)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod20_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod20 pod + return _numpy.dtype({ + 'names': ['fd', 'win32', 'nv_sci_sync_obj'], + 'formats': [_numpy.int32, _py_anon_pod21_dtype, _numpy.intp], + 'offsets': [ + (&(pod.fd)) - (&pod), + (&(pod.win32)) - (&pod), + (&(pod.nvSciSyncObj)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod20), + }) + +_py_anon_pod20_dtype = _get__py_anon_pod20_dtype_offsets() + +cdef class _py_anon_pod20: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod20`. + + + .. seealso:: `cuda_bindings_driver__anon_pod20` + """ + cdef: + cuda_bindings_driver__anon_pod20 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod20)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod20") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod20 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod20 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_pod20 other_ + if not isinstance(other, _py_anon_pod20): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod20)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod20), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod20 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod20): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod20), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod20)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def win32(self): + """_py_anon_pod21: """ + return _py_anon_pod21.from_ptr( + &(self._ptr[0].win32), + readonly=self._readonly, + owner=self, + ) + + @win32.setter + def win32(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod20 instance is read-only") + cdef _py_anon_pod21 val_ = val + _cyb_memcpy(&(self._ptr[0].win32), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod21) * 1) + + @property + def fd(self): + """int: """ + return self._ptr[0].fd + + @fd.setter + def fd(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod20 instance is read-only") + self._ptr[0].fd = val + + @property + def nv_sci_sync_obj(self): + """int: """ + return (self._ptr[0].nvSciSyncObj) + + @nv_sci_sync_obj.setter + def nv_sci_sync_obj(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod20 instance is read-only") + self._ptr[0].nvSciSyncObj = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod20 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod20), _py_anon_pod20) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod20 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod20_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod20_dtype", _py_anon_pod20_dtype, _py_anon_pod20) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod20 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_pod20 obj = _py_anon_pod20.__new__(_py_anon_pod20) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod20)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod20") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod20)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod22_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod22 pod + return _numpy.dtype({ + 'names': ['fence', 'nv_sci_sync', 'keyed_mutex', 'reserved'], + 'formats': [_py_anon_pod23_dtype, _py_anon_pod24_dtype, _py_anon_pod25_dtype, (_numpy.uint32, 12)], + 'offsets': [ + (&(pod.fence)) - (&pod), + (&(pod.nvSciSync)) - (&pod), + (&(pod.keyedMutex)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod22), + }) + +_py_anon_pod22_dtype = _get__py_anon_pod22_dtype_offsets() + +cdef class _py_anon_pod22: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod22`. + + + .. seealso:: `cuda_bindings_driver__anon_pod22` + """ + cdef: + cuda_bindings_driver__anon_pod22 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod22)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod22") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod22 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod22 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_pod22 other_ + if not isinstance(other, _py_anon_pod22): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod22)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod22), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod22 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod22): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod22), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod22)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def fence(self): + """_py_anon_pod23: """ + return _py_anon_pod23.from_ptr( + &(self._ptr[0].fence), + readonly=self._readonly, + owner=self, + ) + + @fence.setter + def fence(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod22 instance is read-only") + cdef _py_anon_pod23 val_ = val + _cyb_memcpy(&(self._ptr[0].fence), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod23) * 1) + + @property + def nv_sci_sync(self): + """_py_anon_pod24: """ + return _py_anon_pod24.from_ptr( + &(self._ptr[0].nvSciSync), + readonly=self._readonly, + owner=self, + ) + + @nv_sci_sync.setter + def nv_sci_sync(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod22 instance is read-only") + cdef _py_anon_pod24 val_ = val + _cyb_memcpy(&(self._ptr[0].nvSciSync), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod24) * 1) + + @property + def keyed_mutex(self): + """_py_anon_pod25: """ + return _py_anon_pod25.from_ptr( + &(self._ptr[0].keyedMutex), + readonly=self._readonly, + owner=self, + ) + + @keyed_mutex.setter + def keyed_mutex(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod22 instance is read-only") + cdef _py_anon_pod25 val_ = val + _cyb_memcpy(&(self._ptr[0].keyedMutex), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod25) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod22 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod22), _py_anon_pod22) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod22 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod22_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod22_dtype", _py_anon_pod22_dtype, _py_anon_pod22) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod22 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_pod22 obj = _py_anon_pod22.__new__(_py_anon_pod22) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod22)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod22") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod22)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod26_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod26 pod + return _numpy.dtype({ + 'names': ['fence', 'nv_sci_sync', 'keyed_mutex', 'reserved'], + 'formats': [_py_anon_pod27_dtype, _py_anon_pod28_dtype, _py_anon_pod29_dtype, (_numpy.uint32, 10)], + 'offsets': [ + (&(pod.fence)) - (&pod), + (&(pod.nvSciSync)) - (&pod), + (&(pod.keyedMutex)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod26), + }) + +_py_anon_pod26_dtype = _get__py_anon_pod26_dtype_offsets() + +cdef class _py_anon_pod26: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod26`. + + + .. seealso:: `cuda_bindings_driver__anon_pod26` + """ + cdef: + cuda_bindings_driver__anon_pod26 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod26)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod26") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod26 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod26 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_pod26 other_ + if not isinstance(other, _py_anon_pod26): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod26)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod26), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod26 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod26): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod26), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod26)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def fence(self): + """_py_anon_pod27: """ + return _py_anon_pod27.from_ptr( + &(self._ptr[0].fence), + readonly=self._readonly, + owner=self, + ) + + @fence.setter + def fence(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod26 instance is read-only") + cdef _py_anon_pod27 val_ = val + _cyb_memcpy(&(self._ptr[0].fence), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod27) * 1) + + @property + def nv_sci_sync(self): + """_py_anon_pod28: """ + return _py_anon_pod28.from_ptr( + &(self._ptr[0].nvSciSync), + readonly=self._readonly, + owner=self, + ) + + @nv_sci_sync.setter + def nv_sci_sync(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod26 instance is read-only") + cdef _py_anon_pod28 val_ = val + _cyb_memcpy(&(self._ptr[0].nvSciSync), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod28) * 1) + + @property + def keyed_mutex(self): + """_py_anon_pod29: """ + return _py_anon_pod29.from_ptr( + &(self._ptr[0].keyedMutex), + readonly=self._readonly, + owner=self, + ) + + @keyed_mutex.setter + def keyed_mutex(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod26 instance is read-only") + cdef _py_anon_pod29 val_ = val + _cyb_memcpy(&(self._ptr[0].keyedMutex), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod29) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod26 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod26), _py_anon_pod26) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod26 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod26_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod26_dtype", _py_anon_pod26_dtype, _py_anon_pod26) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod26 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_pod26 obj = _py_anon_pod26.__new__(_py_anon_pod26) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod26)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod26") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod26)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod33_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod33 pod + return _numpy.dtype({ + 'names': ['sparse_level', 'miptail'], + 'formats': [_py_anon_pod34_dtype, _py_anon_pod35_dtype], + 'offsets': [ + (&(pod.sparseLevel)) - (&pod), + (&(pod.miptail)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod33 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod33 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod33): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod33), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod33)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def sparse_level(self): + """_py_anon_pod34: """ + return _py_anon_pod34.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_pod33 instance is read-only") + cdef _py_anon_pod34 val_ = val + _cyb_memcpy(&(self._ptr[0].sparseLevel), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod34) * 1) + + @property + def miptail(self): + """_py_anon_pod35: """ + return _py_anon_pod35.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_pod33 instance is read-only") + cdef _py_anon_pod35 val_ = val + _cyb_memcpy(&(self._ptr[0].miptail), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod35) * 1) + + @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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod42_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod42 pod + return _numpy.dtype({ + 'names': ['array', 'offset'], + 'formats': [_numpy.intp, offset3d_v1_dtype], + 'offsets': [ + (&(pod.array)) - (&pod), + (&(pod.offset)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod42), + }) + +_py_anon_pod42_dtype = _get__py_anon_pod42_dtype_offsets() + +cdef class _py_anon_pod42: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod42`. + + + .. seealso:: `cuda_bindings_driver__anon_pod42` + """ + cdef: + cuda_bindings_driver__anon_pod42 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod42)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod42") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod42 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod42 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_pod42 other_ + if not isinstance(other, _py_anon_pod42): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod42)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod42), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod42 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod42): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod42), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod42)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def offset(self): + """Offset3D_v1: """ + return Offset3D_v1.from_ptr( + &(self._ptr[0].offset), + readonly=self._readonly, + owner=self, + ) + + @offset.setter + def offset(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod42 instance is read-only") + cdef Offset3D_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].offset), (val_._get_ptr()), sizeof(CUoffset3D) * 1) + + @property + def array(self): + """int: """ + return (self._ptr[0].array) + + @array.setter + def array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod42 instance is read-only") + self._ptr[0].array = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod42 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod42), _py_anon_pod42) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod42 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod42_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod42_dtype", _py_anon_pod42_dtype, _py_anon_pod42) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod42 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_pod42 obj = _py_anon_pod42.__new__(_py_anon_pod42) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod42)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod42") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod42)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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', 'ctx', 'g_ctx'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.event)) - (&pod), + (&(pod.ctx)) - (&pod), + (&(pod.gCtx)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EVENT_RECORD_NODE_PARAMS *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This EventRecordNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EVENT_RECORD_NODE_PARAMS): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EVENT_RECORD_NODE_PARAMS), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_EVENT_RECORD_NODE_PARAMS)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This EventRecordNodeParams instance is read-only") + self._ptr[0].ctx = val + + @property + def g_ctx(self): + """int: """ + return (self._ptr[0].gCtx) + + @g_ctx.setter + def g_ctx(self, val): + if self._readonly: + raise ValueError("This EventRecordNodeParams instance is read-only") + self._ptr[0].gCtx = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_stream_cig_capture_params_dtype_offsets(): + cdef CUstreamCigCaptureParams pod + return _numpy.dtype({ + 'names': ['stream_cig_params'], + 'formats': [_numpy.intp], + 'offsets': [ + (&(pod.streamCigParams)) - (&pod), + ], + 'itemsize': sizeof(CUstreamCigCaptureParams), + }) + +stream_cig_capture_params_dtype = _get_stream_cig_capture_params_dtype_offsets() + +cdef class StreamCigCaptureParams: + """Empty-initialize an instance of `CUstreamCigCaptureParams`. + + + .. seealso:: `CUstreamCigCaptureParams` + """ + cdef: + CUstreamCigCaptureParams _data + CUstreamCigCaptureParams *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.StreamCigCaptureParams 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 StreamCigCaptureParams other_ + if not isinstance(other, StreamCigCaptureParams): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUstreamCigCaptureParams)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUstreamCigCaptureParams), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This StreamCigCaptureParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUstreamCigCaptureParams): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUstreamCigCaptureParams), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUstreamCigCaptureParams)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def stream_cig_params(self): + """int: """ + return (self._ptr[0].streamCigParams) + + @stream_cig_params.setter + def stream_cig_params(self, val): + if self._readonly: + raise ValueError("This StreamCigCaptureParams instance is read-only") + self._ptr[0].streamCigParams = val + + @staticmethod + def from_buffer(buffer): + """Create an StreamCigCaptureParams instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUstreamCigCaptureParams), StreamCigCaptureParams) + + @staticmethod + def from_data(data): + """Create an StreamCigCaptureParams instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `stream_cig_capture_params_dtype` holding the data. + """ + return _cyb_from_data(data, "stream_cig_capture_params_dtype", stream_cig_capture_params_dtype, StreamCigCaptureParams) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an StreamCigCaptureParams 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 StreamCigCaptureParams obj = StreamCigCaptureParams.__new__(StreamCigCaptureParams) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUstreamCigCaptureParams)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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, stream_mem_op_wait_value_params_dtype, stream_mem_op_write_value_params_dtype, stream_mem_op_flush_remote_writes_params_dtype, stream_mem_op_memory_barrier_params_dtype, stream_mem_op_atomic_reduction_params_dtype, (_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 + readonly tuple _wait_value + readonly tuple _write_value + readonly tuple _flush_remote_writes + readonly tuple _memory_barrier + readonly tuple _atomic_reduction + + def __init__(self, size=1): + 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) }" + obj = self + wait_value_list = list() + for i in range(obj._data.size): + addr = obj._data.wait_value[i].__array_interface__['data'][0] + wait_value_obj = StreamMemOpWaitValueParams.from_ptr(addr, owner=obj, readonly=False) + wait_value_list.append(wait_value_obj) + obj._wait_value = tuple(wait_value_list) + write_value_list = list() + for i in range(obj._data.size): + addr = obj._data.write_value[i].__array_interface__['data'][0] + write_value_obj = StreamMemOpWriteValueParams.from_ptr(addr, owner=obj, readonly=False) + write_value_list.append(write_value_obj) + obj._write_value = tuple(write_value_list) + flush_remote_writes_list = list() + for i in range(obj._data.size): + addr = obj._data.flush_remote_writes[i].__array_interface__['data'][0] + flush_remote_writes_obj = StreamMemOpFlushRemoteWritesParams.from_ptr(addr, owner=obj, readonly=False) + flush_remote_writes_list.append(flush_remote_writes_obj) + obj._flush_remote_writes = tuple(flush_remote_writes_list) + memory_barrier_list = list() + for i in range(obj._data.size): + addr = obj._data.memory_barrier[i].__array_interface__['data'][0] + memory_barrier_obj = StreamMemOpMemoryBarrierParams.from_ptr(addr, owner=obj, readonly=False) + memory_barrier_list.append(memory_barrier_obj) + obj._memory_barrier = tuple(memory_barrier_list) + atomic_reduction_list = list() + for i in range(obj._data.size): + addr = obj._data.atomic_reduction[i].__array_interface__['data'][0] + atomic_reduction_obj = StreamMemOpAtomicReductionParams.from_ptr(addr, owner=obj, readonly=False) + atomic_reduction_list.append(atomic_reduction_obj) + obj._atomic_reduction = tuple(atomic_reduction_list) + + 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 wait_value(self): + """StreamMemOpWaitValueParams: """ + if self._data.size == 1: + return self._wait_value[0] + return self._wait_value + + @wait_value.setter + def wait_value(self, val): + cdef StreamMemOpWaitValueParams val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].wait_value = value") + cdef intptr_t addr = self._data.wait_value[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUstreamMemOpWaitValueParams_st) * 1) + + @property + def write_value(self): + """StreamMemOpWriteValueParams: """ + if self._data.size == 1: + return self._write_value[0] + return self._write_value + + @write_value.setter + def write_value(self, val): + cdef StreamMemOpWriteValueParams val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].write_value = value") + cdef intptr_t addr = self._data.write_value[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUstreamMemOpWriteValueParams_st) * 1) + + @property + def flush_remote_writes(self): + """StreamMemOpFlushRemoteWritesParams: """ + if self._data.size == 1: + return self._flush_remote_writes[0] + return self._flush_remote_writes + + @flush_remote_writes.setter + def flush_remote_writes(self, val): + cdef StreamMemOpFlushRemoteWritesParams val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].flush_remote_writes = value") + cdef intptr_t addr = self._data.flush_remote_writes[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUstreamMemOpFlushRemoteWritesParams_st) * 1) + + @property + def memory_barrier(self): + """StreamMemOpMemoryBarrierParams: """ + if self._data.size == 1: + return self._memory_barrier[0] + return self._memory_barrier + + @memory_barrier.setter + def memory_barrier(self, val): + cdef StreamMemOpMemoryBarrierParams val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].memory_barrier = value") + cdef intptr_t addr = self._data.memory_barrier[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUstreamMemOpMemoryBarrierParams_st) * 1) + + @property + def atomic_reduction(self): + """StreamMemOpAtomicReductionParams: """ + if self._data.size == 1: + return self._atomic_reduction[0] + return self._atomic_reduction + + @atomic_reduction.setter + def atomic_reduction(self, val): + cdef StreamMemOpAtomicReductionParams val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].atomic_reduction = value") + cdef intptr_t addr = self._data.atomic_reduction[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUstreamMemOpAtomicReductionParams_st) * 1) + + @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 + + 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) + + wait_value_list = list() + for i in range(obj._data.size): + addr = obj._data.wait_value[i].__array_interface__['data'][0] + wait_value_obj = StreamMemOpWaitValueParams.from_ptr(addr, owner=obj, readonly=False) + wait_value_list.append(wait_value_obj) + obj._wait_value = tuple(wait_value_list) + write_value_list = list() + for i in range(obj._data.size): + addr = obj._data.write_value[i].__array_interface__['data'][0] + write_value_obj = StreamMemOpWriteValueParams.from_ptr(addr, owner=obj, readonly=False) + write_value_list.append(write_value_obj) + obj._write_value = tuple(write_value_list) + flush_remote_writes_list = list() + for i in range(obj._data.size): + addr = obj._data.flush_remote_writes[i].__array_interface__['data'][0] + flush_remote_writes_obj = StreamMemOpFlushRemoteWritesParams.from_ptr(addr, owner=obj, readonly=False) + flush_remote_writes_list.append(flush_remote_writes_obj) + obj._flush_remote_writes = tuple(flush_remote_writes_list) + memory_barrier_list = list() + for i in range(obj._data.size): + addr = obj._data.memory_barrier[i].__array_interface__['data'][0] + memory_barrier_obj = StreamMemOpMemoryBarrierParams.from_ptr(addr, owner=obj, readonly=False) + memory_barrier_list.append(memory_barrier_obj) + obj._memory_barrier = tuple(memory_barrier_list) + atomic_reduction_list = list() + for i in range(obj._data.size): + addr = obj._data.atomic_reduction[i].__array_interface__['data'][0] + atomic_reduction_obj = StreamMemOpAtomicReductionParams.from_ptr(addr, owner=obj, readonly=False) + atomic_reduction_list.append(atomic_reduction_obj) + obj._atomic_reduction = tuple(atomic_reduction_list) + 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 + + wait_value_list = list() + for i in range(obj._data.size): + addr = obj._data.wait_value[i].__array_interface__['data'][0] + wait_value_obj = StreamMemOpWaitValueParams.from_ptr(addr, owner=obj, readonly=readonly) + wait_value_list.append(wait_value_obj) + obj._wait_value = tuple(wait_value_list) + write_value_list = list() + for i in range(obj._data.size): + addr = obj._data.write_value[i].__array_interface__['data'][0] + write_value_obj = StreamMemOpWriteValueParams.from_ptr(addr, owner=obj, readonly=readonly) + write_value_list.append(write_value_obj) + obj._write_value = tuple(write_value_list) + flush_remote_writes_list = list() + for i in range(obj._data.size): + addr = obj._data.flush_remote_writes[i].__array_interface__['data'][0] + flush_remote_writes_obj = StreamMemOpFlushRemoteWritesParams.from_ptr(addr, owner=obj, readonly=readonly) + flush_remote_writes_list.append(flush_remote_writes_obj) + obj._flush_remote_writes = tuple(flush_remote_writes_list) + memory_barrier_list = list() + for i in range(obj._data.size): + addr = obj._data.memory_barrier[i].__array_interface__['data'][0] + memory_barrier_obj = StreamMemOpMemoryBarrierParams.from_ptr(addr, owner=obj, readonly=readonly) + memory_barrier_list.append(memory_barrier_obj) + obj._memory_barrier = tuple(memory_barrier_list) + atomic_reduction_list = list() + for i in range(obj._data.size): + addr = obj._data.atomic_reduction[i].__array_interface__['data'][0] + atomic_reduction_obj = StreamMemOpAtomicReductionParams.from_ptr(addr, owner=obj, readonly=readonly) + atomic_reduction_list.append(atomic_reduction_obj) + obj._atomic_reduction = tuple(atomic_reduction_list) + return obj + + +cdef _get_async_notification_info_dtype_offsets(): + cdef CUasyncNotificationInfo pod + return _numpy.dtype({ + 'names': ['type', 'info'], + 'formats': [_numpy.int32, _py_anon_pod2_dtype], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.info)) - (&pod), + ], + 'itemsize': sizeof(CUasyncNotificationInfo), + }) + +async_notification_info_dtype = _get_async_notification_info_dtype_offsets() + +cdef class AsyncNotificationInfo: + """Empty-initialize an instance of `CUasyncNotificationInfo`. + + + .. seealso:: `CUasyncNotificationInfo` + """ + cdef: + CUasyncNotificationInfo _data + CUasyncNotificationInfo *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.AsyncNotificationInfo 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 AsyncNotificationInfo other_ + if not isinstance(other, AsyncNotificationInfo): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUasyncNotificationInfo)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUasyncNotificationInfo), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This AsyncNotificationInfo instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUasyncNotificationInfo): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUasyncNotificationInfo), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUasyncNotificationInfo)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def info(self): + """_py_anon_pod2: """ + return _py_anon_pod2.from_ptr( + &(self._ptr[0].info), + readonly=self._readonly, + owner=self, + ) + + @info.setter + def info(self, val): + if self._readonly: + raise ValueError("This AsyncNotificationInfo instance is read-only") + cdef _py_anon_pod2 val_ = val + _cyb_memcpy(&(self._ptr[0].info), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod2) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This AsyncNotificationInfo instance is read-only") + self._ptr[0].type = val + + @staticmethod + def from_buffer(buffer): + """Create an AsyncNotificationInfo instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUasyncNotificationInfo), AsyncNotificationInfo) + + @staticmethod + def from_data(data): + """Create an AsyncNotificationInfo instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `async_notification_info_dtype` holding the data. + """ + return _cyb_from_data(data, "async_notification_info_dtype", async_notification_info_dtype, AsyncNotificationInfo) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an AsyncNotificationInfo 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 AsyncNotificationInfo obj = AsyncNotificationInfo.__new__(AsyncNotificationInfo) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUasyncNotificationInfo)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_launch_attribute_dtype_offsets(): + cdef CUlaunchAttribute pod + return _numpy.dtype({ + 'names': ['id', 'value'], + 'formats': [_numpy.int32, launch_attribute_value_dtype], + 'offsets': [ + (&(pod.id)) - (&pod), + (&(pod.value)) - (&pod), + ], + 'itemsize': sizeof(CUlaunchAttribute), + }) + +launch_attribute_dtype = _get_launch_attribute_dtype_offsets() + +cdef class LaunchAttribute: + """Empty-initialize an instance of `CUlaunchAttribute`. + + + .. seealso:: `CUlaunchAttribute` + """ + cdef: + CUlaunchAttribute _data + CUlaunchAttribute *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.LaunchAttribute 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 LaunchAttribute other_ + if not isinstance(other, LaunchAttribute): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlaunchAttribute)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlaunchAttribute), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LaunchAttribute instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlaunchAttribute): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlaunchAttribute), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUlaunchAttribute)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def value(self): + """LaunchAttributeValue: """ + return LaunchAttributeValue.from_ptr( + &(self._ptr[0].value), + readonly=self._readonly, + owner=self, + ) + + @value.setter + def value(self, val): + if self._readonly: + raise ValueError("This LaunchAttribute instance is read-only") + cdef LaunchAttributeValue val_ = val + _cyb_memcpy(&(self._ptr[0].value), (val_._get_ptr()), sizeof(CUlaunchAttributeValue) * 1) + + @property + def id(self): + """int: """ + return (self._ptr[0].id) + + @id.setter + def id(self, val): + if self._readonly: + raise ValueError("This LaunchAttribute instance is read-only") + self._ptr[0].id = val + + @staticmethod + def from_buffer(buffer): + """Create an LaunchAttribute instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlaunchAttribute), LaunchAttribute) + + @staticmethod + def from_data(data): + """Create an LaunchAttribute instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `launch_attribute_dtype` holding the data. + """ + return _cyb_from_data(data, "launch_attribute_dtype", launch_attribute_dtype, LaunchAttribute) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LaunchAttribute 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 LaunchAttribute obj = LaunchAttribute.__new__(LaunchAttribute) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUlaunchAttribute)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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_pod10_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 + readonly tuple _param + + def __init__(self, size=1): + 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) }" + obj = self + param_list = list() + for i in range(obj._data.size): + addr = obj._data.param[i].__array_interface__['data'][0] + param_obj = _py_anon_pod10.from_ptr(addr, owner=obj, readonly=False) + param_list.append(param_obj) + obj._param = tuple(param_list) + + 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 param(self): + """_py_anon_pod10: """ + if self._data.size == 1: + return self._param[0] + return self._param + + @param.setter + def param(self, val): + cdef _py_anon_pod10 val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].param = value") + cdef intptr_t addr = self._data.param[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod10) * 1) + + @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 + + 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) + + param_list = list() + for i in range(obj._data.size): + addr = obj._data.param[i].__array_interface__['data'][0] + param_obj = _py_anon_pod10.from_ptr(addr, owner=obj, readonly=False) + param_list.append(param_obj) + obj._param = tuple(param_list) + 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 + + param_list = list() + for i in range(obj._data.size): + addr = obj._data.param[i].__array_interface__['data'][0] + param_obj = _py_anon_pod10.from_ptr(addr, owner=obj, readonly=readonly) + param_list.append(param_obj) + obj._param = tuple(param_list) + return obj + + +cdef _get_resource_desc_v1_dtype_offsets(): + cdef CUDA_RESOURCE_DESC_v1 pod + return _numpy.dtype({ + 'names': ['res_type', 'res', 'flags_'], + 'formats': [_numpy.int32, _py_anon_pod12_dtype, _numpy.uint32], + 'offsets': [ + (&(pod.resType)) - (&pod), + (&(pod.res)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUDA_RESOURCE_DESC_v1), + }) + +resource_desc_v1_dtype = _get_resource_desc_v1_dtype_offsets() + +cdef class ResourceDesc_v1: + """Empty-initialize an instance of `CUDA_RESOURCE_DESC_v1`. + + + .. seealso:: `CUDA_RESOURCE_DESC_v1` + """ + cdef: + CUDA_RESOURCE_DESC_v1 _data + CUDA_RESOURCE_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ResourceDesc_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 ResourceDesc_v1 other_ + if not isinstance(other, ResourceDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_RESOURCE_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_RESOURCE_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ResourceDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_RESOURCE_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_RESOURCE_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_RESOURCE_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def res(self): + """_py_anon_pod12: """ + return _py_anon_pod12.from_ptr( + &(self._ptr[0].res), + readonly=self._readonly, + owner=self, + ) + + @res.setter + def res(self, val): + if self._readonly: + raise ValueError("This ResourceDesc_v1 instance is read-only") + cdef _py_anon_pod12 val_ = val + _cyb_memcpy(&(self._ptr[0].res), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod12) * 1) + + @property + def res_type(self): + """int: """ + return (self._ptr[0].resType) + + @res_type.setter + def res_type(self, val): + if self._readonly: + raise ValueError("This ResourceDesc_v1 instance is read-only") + self._ptr[0].resType = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ResourceDesc_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ResourceDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_RESOURCE_DESC_v1), ResourceDesc_v1) + + @staticmethod + def from_data(data): + """Create an ResourceDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `resource_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "resource_desc_v1_dtype", resource_desc_v1_dtype, ResourceDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ResourceDesc_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 ResourceDesc_v1 obj = ResourceDesc_v1.__new__(ResourceDesc_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_RESOURCE_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_external_memory_handle_desc_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 pod + return _numpy.dtype({ + 'names': ['type', 'handle', 'size_', 'flags_', 'reserved'], + 'formats': [_numpy.int32, _py_anon_pod18_dtype, _numpy.uint64, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.handle)) - (&pod), + (&(pod.size)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1), + }) + +external_memory_handle_desc_v1_dtype = _get_external_memory_handle_desc_v1_dtype_offsets() + +cdef class ExternalMemoryHandleDesc_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1`. + + + .. seealso:: `CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1` + """ + cdef: + CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 _data + CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ExternalMemoryHandleDesc_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 ExternalMemoryHandleDesc_v1 other_ + if not isinstance(other, ExternalMemoryHandleDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalMemoryHandleDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def handle(self): + """_py_anon_pod18: """ + return _py_anon_pod18.from_ptr( + &(self._ptr[0].handle), + readonly=self._readonly, + owner=self, + ) + + @handle.setter + def handle(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryHandleDesc_v1 instance is read-only") + cdef _py_anon_pod18 val_ = val + _cyb_memcpy(&(self._ptr[0].handle), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod18) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryHandleDesc_v1 instance is read-only") + self._ptr[0].type = val + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This ExternalMemoryHandleDesc_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 ExternalMemoryHandleDesc_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalMemoryHandleDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1), ExternalMemoryHandleDesc_v1) + + @staticmethod + def from_data(data): + """Create an ExternalMemoryHandleDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_memory_handle_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_memory_handle_desc_v1_dtype", external_memory_handle_desc_v1_dtype, ExternalMemoryHandleDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalMemoryHandleDesc_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 ExternalMemoryHandleDesc_v1 obj = ExternalMemoryHandleDesc_v1.__new__(ExternalMemoryHandleDesc_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_external_semaphore_handle_desc_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 pod + return _numpy.dtype({ + 'names': ['type', 'handle', 'flags_', 'reserved'], + 'formats': [_numpy.int32, _py_anon_pod20_dtype, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.handle)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1), + }) + +external_semaphore_handle_desc_v1_dtype = _get_external_semaphore_handle_desc_v1_dtype_offsets() + +cdef class ExternalSemaphoreHandleDesc_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1`. + + + .. seealso:: `CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1` + """ + cdef: + CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 _data + CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ExternalSemaphoreHandleDesc_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 ExternalSemaphoreHandleDesc_v1 other_ + if not isinstance(other, ExternalSemaphoreHandleDesc_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalSemaphoreHandleDesc_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def handle(self): + """_py_anon_pod20: """ + return _py_anon_pod20.from_ptr( + &(self._ptr[0].handle), + readonly=self._readonly, + owner=self, + ) + + @handle.setter + def handle(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreHandleDesc_v1 instance is read-only") + cdef _py_anon_pod20 val_ = val + _cyb_memcpy(&(self._ptr[0].handle), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod20) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreHandleDesc_v1 instance is read-only") + self._ptr[0].type = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreHandleDesc_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalSemaphoreHandleDesc_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1), ExternalSemaphoreHandleDesc_v1) + + @staticmethod + def from_data(data): + """Create an ExternalSemaphoreHandleDesc_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_semaphore_handle_desc_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_semaphore_handle_desc_v1_dtype", external_semaphore_handle_desc_v1_dtype, ExternalSemaphoreHandleDesc_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalSemaphoreHandleDesc_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 ExternalSemaphoreHandleDesc_v1 obj = ExternalSemaphoreHandleDesc_v1.__new__(ExternalSemaphoreHandleDesc_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_external_semaphore_signal_params_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['params', 'flags_', 'reserved'], + 'formats': [_py_anon_pod22_dtype, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.params)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1), + }) + +external_semaphore_signal_params_v1_dtype = _get_external_semaphore_signal_params_v1_dtype_offsets() + +cdef class ExternalSemaphoreSignalParams_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1`. + + + .. seealso:: `CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1` + """ + cdef: + CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 _data + CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ExternalSemaphoreSignalParams_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 ExternalSemaphoreSignalParams_v1 other_ + if not isinstance(other, ExternalSemaphoreSignalParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalSemaphoreSignalParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def params(self): + """_py_anon_pod22: """ + return _py_anon_pod22.from_ptr( + &(self._ptr[0].params), + readonly=self._readonly, + owner=self, + ) + + @params.setter + def params(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreSignalParams_v1 instance is read-only") + cdef _py_anon_pod22 val_ = val + _cyb_memcpy(&(self._ptr[0].params), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod22) * 1) + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreSignalParams_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalSemaphoreSignalParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1), ExternalSemaphoreSignalParams_v1) + + @staticmethod + def from_data(data): + """Create an ExternalSemaphoreSignalParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_semaphore_signal_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_semaphore_signal_params_v1_dtype", external_semaphore_signal_params_v1_dtype, ExternalSemaphoreSignalParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalSemaphoreSignalParams_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 ExternalSemaphoreSignalParams_v1 obj = ExternalSemaphoreSignalParams_v1.__new__(ExternalSemaphoreSignalParams_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_external_semaphore_wait_params_v1_dtype_offsets(): + cdef CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 pod + return _numpy.dtype({ + 'names': ['params', 'flags_', 'reserved'], + 'formats': [_py_anon_pod26_dtype, _numpy.uint32, (_numpy.uint32, 16)], + 'offsets': [ + (&(pod.params)) - (&pod), + (&(pod.flags)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1), + }) + +external_semaphore_wait_params_v1_dtype = _get_external_semaphore_wait_params_v1_dtype_offsets() + +cdef class ExternalSemaphoreWaitParams_v1: + """Empty-initialize an instance of `CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1`. + + + .. seealso:: `CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1` + """ + cdef: + CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 _data + CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.ExternalSemaphoreWaitParams_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 ExternalSemaphoreWaitParams_v1 other_ + if not isinstance(other, ExternalSemaphoreWaitParams_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExternalSemaphoreWaitParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def params(self): + """_py_anon_pod26: """ + return _py_anon_pod26.from_ptr( + &(self._ptr[0].params), + readonly=self._readonly, + owner=self, + ) + + @params.setter + def params(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreWaitParams_v1 instance is read-only") + cdef _py_anon_pod26 val_ = val + _cyb_memcpy(&(self._ptr[0].params), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod26) * 1) + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This ExternalSemaphoreWaitParams_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an ExternalSemaphoreWaitParams_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1), ExternalSemaphoreWaitParams_v1) + + @staticmethod + def from_data(data): + """Create an ExternalSemaphoreWaitParams_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `external_semaphore_wait_params_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "external_semaphore_wait_params_v1_dtype", external_semaphore_wait_params_v1_dtype, ExternalSemaphoreWaitParams_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an ExternalSemaphoreWaitParams_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 ExternalSemaphoreWaitParams_v1 obj = ExternalSemaphoreWaitParams_v1.__new__(ExternalSemaphoreWaitParams_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + 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_pod32_dtype, _numpy.int32, _py_anon_pod33_dtype, _numpy.int32, _numpy.int32, _py_anon_pod36_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 + readonly tuple _resource + readonly tuple _subresource + readonly tuple _mem_handle + + def __init__(self, size=1): + 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) }" + obj = self + resource_list = list() + for i in range(obj._data.size): + addr = obj._data.resource[i].__array_interface__['data'][0] + resource_obj = _py_anon_pod32.from_ptr(addr, owner=obj, readonly=False) + resource_list.append(resource_obj) + obj._resource = tuple(resource_list) + subresource_list = list() + for i in range(obj._data.size): + addr = obj._data.subresource[i].__array_interface__['data'][0] + subresource_obj = _py_anon_pod33.from_ptr(addr, owner=obj, readonly=False) + subresource_list.append(subresource_obj) + obj._subresource = tuple(subresource_list) + mem_handle_list = list() + for i in range(obj._data.size): + addr = obj._data.mem_handle[i].__array_interface__['data'][0] + mem_handle_obj = _py_anon_pod36.from_ptr(addr, owner=obj, readonly=False) + mem_handle_list.append(mem_handle_obj) + obj._mem_handle = tuple(mem_handle_list) + + 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(self): + """_py_anon_pod32: """ + if self._data.size == 1: + return self._resource[0] + return self._resource + + @resource.setter + def resource(self, val): + cdef _py_anon_pod32 val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].resource = value") + cdef intptr_t addr = self._data.resource[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod32) * 1) + + @property + def subresource(self): + """_py_anon_pod33: """ + if self._data.size == 1: + return self._subresource[0] + return self._subresource + + @subresource.setter + def subresource(self, val): + cdef _py_anon_pod33 val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].subresource = value") + cdef intptr_t addr = self._data.subresource[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod33) * 1) + + @property + def mem_handle(self): + """_py_anon_pod36: """ + if self._data.size == 1: + return self._mem_handle[0] + return self._mem_handle + + @mem_handle.setter + def mem_handle(self, val): + cdef _py_anon_pod36 val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].mem_handle = value") + cdef intptr_t addr = self._data.mem_handle[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod36) * 1) + + @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 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 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 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) + + resource_list = list() + for i in range(obj._data.size): + addr = obj._data.resource[i].__array_interface__['data'][0] + resource_obj = _py_anon_pod32.from_ptr(addr, owner=obj, readonly=False) + resource_list.append(resource_obj) + obj._resource = tuple(resource_list) + subresource_list = list() + for i in range(obj._data.size): + addr = obj._data.subresource[i].__array_interface__['data'][0] + subresource_obj = _py_anon_pod33.from_ptr(addr, owner=obj, readonly=False) + subresource_list.append(subresource_obj) + obj._subresource = tuple(subresource_list) + mem_handle_list = list() + for i in range(obj._data.size): + addr = obj._data.mem_handle[i].__array_interface__['data'][0] + mem_handle_obj = _py_anon_pod36.from_ptr(addr, owner=obj, readonly=False) + mem_handle_list.append(mem_handle_obj) + obj._mem_handle = tuple(mem_handle_list) + 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 + + resource_list = list() + for i in range(obj._data.size): + addr = obj._data.resource[i].__array_interface__['data'][0] + resource_obj = _py_anon_pod32.from_ptr(addr, owner=obj, readonly=readonly) + resource_list.append(resource_obj) + obj._resource = tuple(resource_list) + subresource_list = list() + for i in range(obj._data.size): + addr = obj._data.subresource[i].__array_interface__['data'][0] + subresource_obj = _py_anon_pod33.from_ptr(addr, owner=obj, readonly=readonly) + subresource_list.append(subresource_obj) + obj._subresource = tuple(subresource_list) + mem_handle_list = list() + for i in range(obj._data.size): + addr = obj._data.mem_handle[i].__array_interface__['data'][0] + mem_handle_obj = _py_anon_pod36.from_ptr(addr, owner=obj, readonly=readonly) + mem_handle_list.append(mem_handle_obj) + obj._mem_handle = tuple(mem_handle_list) + return obj + + +cdef _get_mem_location_v1_dtype_offsets(): + cdef CUmemLocation_v1 pod + return _numpy.dtype({ + 'names': ['type', 'id', 'localized'], + 'formats': [_numpy.int32, _numpy.int32, _py_anon_pod38_dtype], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.id)) - (&pod), + (&(pod.localized)) - (&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 _data + CUmemLocation_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemLocation_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemLocation_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemLocation_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemLocation_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def localized(self): + """_py_anon_pod38: """ + return _py_anon_pod38.from_ptr( + &(self._ptr[0].localized), + readonly=self._readonly, + owner=self, + ) + + @localized.setter + def localized(self, val): + if self._readonly: + raise ValueError("This MemLocation_v1 instance is read-only") + cdef _py_anon_pod38 val_ = val + _cyb_memcpy(&(self._ptr[0].localized), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod38) * 1) + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemLocation_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_checkpoint_args_dtype_offsets(): + cdef CUcheckpointCheckpointArgs pod + return _numpy.dtype({ + 'names': ['custom_storage_info_out', 'reserved'], + 'formats': [_numpy.intp, (_numpy.int8, 56)], + 'offsets': [ + (&(pod.customStorageInfo_out)) - (&pod), + (&(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 _data + CUcheckpointCheckpointArgs *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CheckpointCheckpointArgs instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUcheckpointCheckpointArgs): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUcheckpointCheckpointArgs), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUcheckpointCheckpointArgs)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def custom_storage_info_out(self): + """int: """ + return (self._ptr[0].customStorageInfo_out) + + @custom_storage_info_out.setter + def custom_storage_info_out(self, val): + if self._readonly: + raise ValueError("This CheckpointCheckpointArgs instance is read-only") + self._ptr[0].customStorageInfo_out = 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUcheckpointCheckpointArgs)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_checkpoint_restore_args_dtype_offsets(): + cdef CUcheckpointRestoreArgs pod + return _numpy.dtype({ + 'names': ['gpu_pairs', 'gpu_pairs_count', 'padding0', 'custom_storage_info_out', 'reserved'], + 'formats': [_numpy.intp, _numpy.uint32, _numpy.uint32, _numpy.intp, (_numpy.int8, 40)], + 'offsets': [ + (&(pod.gpuPairs)) - (&pod), + (&(pod.gpuPairsCount)) - (&pod), + (&(pod.padding0)) - (&pod), + (&(pod.customStorageInfo_out)) - (&pod), + (&(pod.reserved)) - (&pod), + ], + 'itemsize': sizeof(CUcheckpointRestoreArgs), + }) + +checkpoint_restore_args_dtype = _get_checkpoint_restore_args_dtype_offsets() + +cdef class CheckpointRestoreArgs: + """Empty-initialize an instance of `CUcheckpointRestoreArgs`. + + + .. seealso:: `CUcheckpointRestoreArgs` + """ + cdef: + CUcheckpointRestoreArgs _data + CUcheckpointRestoreArgs *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.CheckpointRestoreArgs 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 CheckpointRestoreArgs other_ + if not isinstance(other, CheckpointRestoreArgs): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUcheckpointRestoreArgs)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUcheckpointRestoreArgs), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CheckpointRestoreArgs instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUcheckpointRestoreArgs): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUcheckpointRestoreArgs), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUcheckpointRestoreArgs)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def gpu_pairs(self): + """int: """ + return (self._ptr[0].gpuPairs) + + @gpu_pairs.setter + def gpu_pairs(self, val): + if self._readonly: + raise ValueError("This CheckpointRestoreArgs instance is read-only") + self._ptr[0].gpuPairs = val + + @property + def gpu_pairs_count(self): + """int: """ + return self._ptr[0].gpuPairsCount + + @gpu_pairs_count.setter + def gpu_pairs_count(self, val): + if self._readonly: + raise ValueError("This CheckpointRestoreArgs instance is read-only") + self._ptr[0].gpuPairsCount = val + + @property + def custom_storage_info_out(self): + """int: """ + return (self._ptr[0].customStorageInfo_out) + + @custom_storage_info_out.setter + def custom_storage_info_out(self, val): + if self._readonly: + raise ValueError("This CheckpointRestoreArgs instance is read-only") + self._ptr[0].customStorageInfo_out = val + + @staticmethod + def from_buffer(buffer): + """Create an CheckpointRestoreArgs instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUcheckpointRestoreArgs), CheckpointRestoreArgs) + + @staticmethod + def from_data(data): + """Create an CheckpointRestoreArgs instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `checkpoint_restore_args_dtype` holding the data. + """ + return _cyb_from_data(data, "checkpoint_restore_args_dtype", checkpoint_restore_args_dtype, CheckpointRestoreArgs) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an CheckpointRestoreArgs 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 CheckpointRestoreArgs obj = CheckpointRestoreArgs.__new__(CheckpointRestoreArgs) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUcheckpointRestoreArgs)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 + readonly tuple _sm + readonly tuple _wq_config + readonly tuple _wq + + def __init__(self, size=1): + 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) }" + obj = self + sm_list = list() + for i in range(obj._data.size): + addr = obj._data.sm[i].__array_interface__['data'][0] + sm_obj = DevSmResource.from_ptr(addr, owner=obj, readonly=False) + sm_list.append(sm_obj) + obj._sm = tuple(sm_list) + wq_config_list = list() + for i in range(obj._data.size): + addr = obj._data.wq_config[i].__array_interface__['data'][0] + wq_config_obj = DevWorkqueueConfigResource.from_ptr(addr, owner=obj, readonly=False) + wq_config_list.append(wq_config_obj) + obj._wq_config = tuple(wq_config_list) + wq_list = list() + for i in range(obj._data.size): + addr = obj._data.wq[i].__array_interface__['data'][0] + wq_obj = DevWorkqueueResource.from_ptr(addr, owner=obj, readonly=False) + wq_list.append(wq_obj) + obj._wq = tuple(wq_list) + + 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 sm(self): + """DevSmResource: """ + if self._data.size == 1: + return self._sm[0] + return self._sm + + @sm.setter + def sm(self, val): + cdef DevSmResource val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].sm = value") + cdef intptr_t addr = self._data.sm[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUdevSmResource) * 1) + + @property + def wq_config(self): + """DevWorkqueueConfigResource: """ + if self._data.size == 1: + return self._wq_config[0] + return self._wq_config + + @wq_config.setter + def wq_config(self, val): + cdef DevWorkqueueConfigResource val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].wq_config = value") + cdef intptr_t addr = self._data.wq_config[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUdevWorkqueueConfigResource) * 1) + + @property + def wq(self): + """DevWorkqueueResource: """ + if self._data.size == 1: + return self._wq[0] + return self._wq + + @wq.setter + def wq(self, val): + cdef DevWorkqueueResource val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].wq = value") + cdef intptr_t addr = self._data.wq[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUdevWorkqueueResource) * 1) + + @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 _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) + + sm_list = list() + for i in range(obj._data.size): + addr = obj._data.sm[i].__array_interface__['data'][0] + sm_obj = DevSmResource.from_ptr(addr, owner=obj, readonly=False) + sm_list.append(sm_obj) + obj._sm = tuple(sm_list) + wq_config_list = list() + for i in range(obj._data.size): + addr = obj._data.wq_config[i].__array_interface__['data'][0] + wq_config_obj = DevWorkqueueConfigResource.from_ptr(addr, owner=obj, readonly=False) + wq_config_list.append(wq_config_obj) + obj._wq_config = tuple(wq_config_list) + wq_list = list() + for i in range(obj._data.size): + addr = obj._data.wq[i].__array_interface__['data'][0] + wq_obj = DevWorkqueueResource.from_ptr(addr, owner=obj, readonly=False) + wq_list.append(wq_obj) + obj._wq = tuple(wq_list) + 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 + + sm_list = list() + for i in range(obj._data.size): + addr = obj._data.sm[i].__array_interface__['data'][0] + sm_obj = DevSmResource.from_ptr(addr, owner=obj, readonly=readonly) + sm_list.append(sm_obj) + obj._sm = tuple(sm_list) + wq_config_list = list() + for i in range(obj._data.size): + addr = obj._data.wq_config[i].__array_interface__['data'][0] + wq_config_obj = DevWorkqueueConfigResource.from_ptr(addr, owner=obj, readonly=readonly) + wq_config_list.append(wq_config_obj) + obj._wq_config = tuple(wq_config_list) + wq_list = list() + for i in range(obj._data.size): + addr = obj._data.wq[i].__array_interface__['data'][0] + wq_obj = DevWorkqueueResource.from_ptr(addr, owner=obj, readonly=readonly) + wq_list.append(wq_obj) + obj._wq = tuple(wq_list) + return obj + + +cdef _get_logical_endpoint_prop_dtype_offsets(): + cdef CUlogicalEndpointProp pod + return _numpy.dtype({ + 'names': ['type', 'unicast', 'multicast', 'size_', 'ipc_handle_types', 'flags_'], + 'formats': [_numpy.int32, _py_anon_pod47_dtype, _py_anon_pod48_dtype, _numpy.uint64, _numpy.uint32, _numpy.uint32], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.unicast)) - (&pod), + (&(pod.multicast)) - (&pod), + (&(pod.size)) - (&pod), + (&(pod.ipcHandleTypes)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUlogicalEndpointProp), + }) + +logical_endpoint_prop_dtype = _get_logical_endpoint_prop_dtype_offsets() + +cdef class LogicalEndpointProp: + """Empty-initialize an instance of `CUlogicalEndpointProp`. + + + .. seealso:: `CUlogicalEndpointProp` + """ + cdef: + CUlogicalEndpointProp _data + CUlogicalEndpointProp *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.LogicalEndpointProp 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 LogicalEndpointProp other_ + if not isinstance(other, LogicalEndpointProp): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUlogicalEndpointProp)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUlogicalEndpointProp), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlogicalEndpointProp): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlogicalEndpointProp), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUlogicalEndpointProp)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def unicast(self): + """_py_anon_pod47: """ + return _py_anon_pod47.from_ptr( + &(self._ptr[0].unicast), + readonly=self._readonly, + owner=self, + ) + + @unicast.setter + def unicast(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + cdef _py_anon_pod47 val_ = val + _cyb_memcpy(&(self._ptr[0].unicast), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod47) * 1) + + @property + def multicast(self): + """_py_anon_pod48: """ + return _py_anon_pod48.from_ptr( + &(self._ptr[0].multicast), + readonly=self._readonly, + owner=self, + ) + + @multicast.setter + def multicast(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + cdef _py_anon_pod48 val_ = val + _cyb_memcpy(&(self._ptr[0].multicast), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod48) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + self._ptr[0].type = val + + @property + def size_(self): + """int: """ + return self._ptr[0].size + + @size_.setter + def size_(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + self._ptr[0].size = val + + @property + def ipc_handle_types(self): + """int: """ + return self._ptr[0].ipcHandleTypes + + @ipc_handle_types.setter + def ipc_handle_types(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + self._ptr[0].ipcHandleTypes = val + + @property + def flags_(self): + """int: """ + return self._ptr[0].flags + + @flags_.setter + def flags_(self, val): + if self._readonly: + raise ValueError("This LogicalEndpointProp instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an LogicalEndpointProp instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUlogicalEndpointProp), LogicalEndpointProp) + + @staticmethod + def from_data(data): + """Create an LogicalEndpointProp instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `logical_endpoint_prop_dtype` holding the data. + """ + return _cyb_from_data(data, "logical_endpoint_prop_dtype", logical_endpoint_prop_dtype, LogicalEndpointProp) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an LogicalEndpointProp 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 LogicalEndpointProp obj = LogicalEndpointProp.__new__(LogicalEndpointProp) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUlogicalEndpointProp)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_BATCH_MEM_OP_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This BatchMemOpNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_BATCH_MEM_OP_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + 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 _data + CUlaunchConfig *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This LaunchConfig instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUlaunchConfig): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUlaunchConfig), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUlaunchConfig)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUlaunchConfig)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + 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 _data + CUctxCreateParams *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This CtxCreateParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUctxCreateParams): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUctxCreateParams), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUctxCreateParams)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUctxCreateParams)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _data + CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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', 'ctx', 'g_ctx'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + (&(pod.ctx)) - (&pod), + (&(pod.gCtx)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @property + def g_ctx(self): + """int: """ + return (self._ptr[0].gCtx) + + @g_ctx.setter + def g_ctx(self, val): + if self._readonly: + raise ValueError("This ExtSemSignalNodeParams_v2 instance is read-only") + self._ptr[0].gCtx = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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', 'ctx', 'g_ctx'], + 'formats': [_numpy.intp, _numpy.intp, _numpy.uint32, _numpy.intp, _numpy.intp], + 'offsets': [ + (&(pod.extSemArray)) - (&pod), + (&(pod.paramsArray)) - (&pod), + (&(pod.numExtSems)) - (&pod), + (&(pod.ctx)) - (&pod), + (&(pod.gCtx)) - (&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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @property + def ctx(self): + """int: """ + return (self._ptr[0].ctx) + + @ctx.setter + def ctx(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + self._ptr[0].ctx = val + + @property + def g_ctx(self): + """int: """ + return (self._ptr[0].gCtx) + + @g_ctx.setter + def g_ctx(self, val): + if self._readonly: + raise ValueError("This ExtSemWaitNodeParams_v2 instance is read-only") + self._ptr[0].gCtx = 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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, mem_location_v1_dtype, _numpy.intp, _py_anon_pod39_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 _data + CUmemAllocationProp_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemAllocationProp_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemAllocationProp_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemAllocationProp_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemAllocationProp_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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_pod39: """ + return _py_anon_pod39.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_pod39 val_ = val + _cyb_memcpy(&(self._ptr[0].allocFlags), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod39) * 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemAllocationProp_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_access_desc_v1_dtype_offsets(): + cdef CUmemAccessDesc_v1 pod + return _numpy.dtype({ + 'names': ['location', 'flags_'], + 'formats': [mem_location_v1_dtype, _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 + readonly tuple _location + + def __init__(self, size=1): + 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) }" + obj = self + location_list = list() + for i in range(obj._data.size): + addr = obj._data.location[i].__array_interface__['data'][0] + location_obj = MemLocation_v1.from_ptr(addr, owner=obj, readonly=False) + location_list.append(location_obj) + obj._location = tuple(location_list) + + 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): + """MemLocation_v1: """ + if self._data.size == 1: + return self._location[0] + return self._location + + @location.setter + def location(self, val): + cdef MemLocation_v1 val_ = val + if self._data.size != 1: + raise ValueError("Assign to the member of one element, e.g. array[i].location = value") + cdef intptr_t addr = self._data.location[0].__array_interface__['data'][0] + _cyb_memcpy(addr, (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @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) + + location_list = list() + for i in range(obj._data.size): + addr = obj._data.location[i].__array_interface__['data'][0] + location_obj = MemLocation_v1.from_ptr(addr, owner=obj, readonly=False) + location_list.append(location_obj) + obj._location = tuple(location_list) + 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 + + location_list = list() + for i in range(obj._data.size): + addr = obj._data.location[i].__array_interface__['data'][0] + location_obj = MemLocation_v1.from_ptr(addr, owner=obj, readonly=readonly) + location_list.append(location_obj) + obj._location = tuple(location_list) + 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', 'gpu_direct_rdma_capable', 'reserved'], + 'formats': [_numpy.int32, _numpy.int32, mem_location_v1_dtype, _numpy.intp, _numpy.uint64, _numpy.uint16, _numpy.uint8, (_numpy.uint8, 53)], + 'offsets': [ + (&(pod.allocType)) - (&pod), + (&(pod.handleTypes)) - (&pod), + (&(pod.location)) - (&pod), + (&(pod.win32SecurityAttributes)) - (&pod), + (&(pod.maxSize)) - (&pod), + (&(pod.usage)) - (&pod), + (&(pod.gpuDirectRDMACapable)) - (&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 _data + CUmemPoolProps_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemPoolProps_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemPoolProps_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemPoolProps_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemPoolProps_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 + + @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 MemPoolProps_v1 instance is read-only") + self._ptr[0].gpuDirectRDMACapable = 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemPoolProps_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy_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, mem_location_v1_dtype, mem_location_v1_dtype, _numpy.uint32], + 'offsets': [ + (&(pod.srcAccessOrder)) - (&pod), + (&(pod.srcLocHint)) - (&pod), + (&(pod.dstLocHint)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUmemcpyAttributes_v1), + }) + +mem_cpy_attributes_v1_dtype = _get_mem_cpy_attributes_v1_dtype_offsets() + +cdef class MemCpyAttributes_v1: + """Empty-initialize an instance of `CUmemcpyAttributes_v1`. + + + .. seealso:: `CUmemcpyAttributes_v1` + """ + cdef: + CUmemcpyAttributes_v1 _data + CUmemcpyAttributes_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpyAttributes_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemcpyAttributes_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemcpyAttributes_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemcpyAttributes_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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 `mem_cpy_attributes_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy_attributes_v1_dtype", mem_cpy_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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemcpyAttributes_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod41_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod41 pod + return _numpy.dtype({ + 'names': ['ptr_', 'row_length', 'layer_height', 'loc_hint'], + 'formats': [_numpy.uint64, _numpy.uint64, _numpy.uint64, mem_location_v1_dtype], + 'offsets': [ + (&(pod.ptr)) - (&pod), + (&(pod.rowLength)) - (&pod), + (&(pod.layerHeight)) - (&pod), + (&(pod.locHint)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod41), + }) + +_py_anon_pod41_dtype = _get__py_anon_pod41_dtype_offsets() + +cdef class _py_anon_pod41: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod41`. + + + .. seealso:: `cuda_bindings_driver__anon_pod41` + """ + cdef: + cuda_bindings_driver__anon_pod41 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod41)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod41") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod41 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod41 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_pod41 other_ + if not isinstance(other, _py_anon_pod41): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod41)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod41), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod41 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod41): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod41), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod41)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def loc_hint(self): + """MemLocation_v1: """ + return MemLocation_v1.from_ptr( + &(self._ptr[0].locHint), + readonly=self._readonly, + owner=self, + ) + + @loc_hint.setter + def loc_hint(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod41 instance is read-only") + cdef MemLocation_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].locHint), (val_._get_ptr()), sizeof(CUmemLocation) * 1) + + @property + def ptr_(self): + """int: """ + return (self._ptr[0].ptr) + + @ptr_.setter + def ptr_(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod41 instance is read-only") + self._ptr[0].ptr = val + + @property + def row_length(self): + """int: """ + return self._ptr[0].rowLength + + @row_length.setter + def row_length(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod41 instance is read-only") + self._ptr[0].rowLength = val + + @property + def layer_height(self): + """int: """ + return self._ptr[0].layerHeight + + @layer_height.setter + def layer_height(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod41 instance is read-only") + self._ptr[0].layerHeight = val + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod41 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod41), _py_anon_pod41) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod41 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod41_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod41_dtype", _py_anon_pod41_dtype, _py_anon_pod41) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod41 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_pod41 obj = _py_anon_pod41.__new__(_py_anon_pod41) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod41)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod41") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod41)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + 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 _data + CUDA_MEM_ALLOC_NODE_PARAMS_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemAllocNodeParams_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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 _owns_ptr + 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._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef CUDA_MEM_ALLOC_NODE_PARAMS_v2 *ptr + if self._owns_ptr 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemAllocNodeParams_v2 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(CUDA_MEM_ALLOC_NODE_PARAMS_v2)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get__py_anon_pod40_dtype_offsets(): + cdef cuda_bindings_driver__anon_pod40 pod + return _numpy.dtype({ + 'names': ['ptr_', 'array'], + 'formats': [_py_anon_pod41_dtype, _py_anon_pod42_dtype], + 'offsets': [ + (&(pod.ptr)) - (&pod), + (&(pod.array)) - (&pod), + ], + 'itemsize': sizeof(cuda_bindings_driver__anon_pod40), + }) + +_py_anon_pod40_dtype = _get__py_anon_pod40_dtype_offsets() + +cdef class _py_anon_pod40: + """Empty-initialize an instance of `cuda_bindings_driver__anon_pod40`. + + + .. seealso:: `cuda_bindings_driver__anon_pod40` + """ + cdef: + cuda_bindings_driver__anon_pod40 *_ptr + object _owner + bint _owns_ptr + bint _readonly + + def __init__(self): + self._ptr = _cyb_calloc(1, sizeof(cuda_bindings_driver__anon_pod40)) + if self._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod40") + self._owns_ptr = True + self._owner = None + self._readonly = False + + def __dealloc__(self): + cdef cuda_bindings_driver__anon_pod40 *ptr + if self._owns_ptr and self._ptr != NULL: + ptr = self._ptr + self._ptr = NULL + _cyb_free(ptr) + + def __repr__(self): + return f"<{__name__}._py_anon_pod40 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_pod40 other_ + if not isinstance(other, _py_anon_pod40): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(cuda_bindings_driver__anon_pod40)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(cuda_bindings_driver__anon_pod40), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This _py_anon_pod40 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(cuda_bindings_driver__anon_pod40): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(cuda_bindings_driver__anon_pod40), view.len) + ) + _cyb_memmove(self._ptr, view.buf, sizeof(cuda_bindings_driver__anon_pod40)) + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def ptr_(self): + """_py_anon_pod41: """ + return _py_anon_pod41.from_ptr( + &(self._ptr[0].ptr), + readonly=self._readonly, + owner=self, + ) + + @ptr_.setter + def ptr_(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod40 instance is read-only") + cdef _py_anon_pod41 val_ = val + _cyb_memcpy(&(self._ptr[0].ptr), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod41) * 1) + + @property + def array(self): + """_py_anon_pod42: """ + return _py_anon_pod42.from_ptr( + &(self._ptr[0].array), + readonly=self._readonly, + owner=self, + ) + + @array.setter + def array(self, val): + if self._readonly: + raise ValueError("This _py_anon_pod40 instance is read-only") + cdef _py_anon_pod42 val_ = val + _cyb_memcpy(&(self._ptr[0].array), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod42) * 1) + + @staticmethod + def from_buffer(buffer): + """Create an _py_anon_pod40 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(cuda_bindings_driver__anon_pod40), _py_anon_pod40) + + @staticmethod + def from_data(data): + """Create an _py_anon_pod40 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `_py_anon_pod40_dtype` holding the data. + """ + return _cyb_from_data(data, "_py_anon_pod40_dtype", _py_anon_pod40_dtype, _py_anon_pod40) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an _py_anon_pod40 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_pod40 obj = _py_anon_pod40.__new__(_py_anon_pod40) + if owner is None: + obj._ptr = _cyb_malloc(sizeof(cuda_bindings_driver__anon_pod40)) + if obj._ptr == NULL: + raise MemoryError("Error allocating _py_anon_pod40") + _cyb_memcpy((obj._ptr), ptr, sizeof(cuda_bindings_driver__anon_pod40)) + obj._owns_ptr = True + obj._owner = None + else: + obj._ptr = ptr + obj._owns_ptr = False + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy3d_operand_v1_dtype_offsets(): + cdef CUmemcpy3DOperand_v1 pod + return _numpy.dtype({ + 'names': ['type', 'op'], + 'formats': [_numpy.int32, _py_anon_pod40_dtype], + 'offsets': [ + (&(pod.type)) - (&pod), + (&(pod.op)) - (&pod), + ], + 'itemsize': sizeof(CUmemcpy3DOperand_v1), + }) + +mem_cpy3d_operand_v1_dtype = _get_mem_cpy3d_operand_v1_dtype_offsets() + +cdef class MemCpy3dOperand_v1: + """Empty-initialize an instance of `CUmemcpy3DOperand_v1`. + + + .. seealso:: `CUmemcpy3DOperand_v1` + """ + cdef: + CUmemcpy3DOperand_v1 _data + CUmemcpy3DOperand_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.MemCpy3dOperand_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 MemCpy3dOperand_v1 other_ + if not isinstance(other, MemCpy3dOperand_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUmemcpy3DOperand_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUmemcpy3DOperand_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpy3dOperand_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUmemcpy3DOperand_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUmemcpy3DOperand_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUmemcpy3DOperand_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def op(self): + """_py_anon_pod40: """ + return _py_anon_pod40.from_ptr( + &(self._ptr[0].op), + readonly=self._readonly, + owner=self, + ) + + @op.setter + def op(self, val): + if self._readonly: + raise ValueError("This MemCpy3dOperand_v1 instance is read-only") + cdef _py_anon_pod40 val_ = val + _cyb_memcpy(&(self._ptr[0].op), (val_._get_ptr()), sizeof(cuda_bindings_driver__anon_pod40) * 1) + + @property + def type(self): + """int: """ + return (self._ptr[0].type) + + @type.setter + def type(self, val): + if self._readonly: + raise ValueError("This MemCpy3dOperand_v1 instance is read-only") + self._ptr[0].type = val + + @staticmethod + def from_buffer(buffer): + """Create an MemCpy3dOperand_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUmemcpy3DOperand_v1), MemCpy3dOperand_v1) + + @staticmethod + def from_data(data): + """Create an MemCpy3dOperand_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_cpy3d_operand_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy3d_operand_v1_dtype", mem_cpy3d_operand_v1_dtype, MemCpy3dOperand_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemCpy3dOperand_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 MemCpy3dOperand_v1 obj = MemCpy3dOperand_v1.__new__(MemCpy3dOperand_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUmemcpy3DOperand_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + 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, mem_cpy_node_params_dtype, mem_set_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 _data + CUgraphNodeParams *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + 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): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUgraphNodeParams): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUgraphNodeParams), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUgraphNodeParams)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + 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): + """bytes: The raw 232 bytes of the union.""" + return self._ptr[0].asBytes[:232] + + @as_bytes.setter + def as_bytes(self, val): + if self._readonly: + raise ValueError("This GraphNodeParams instance is read-only") + cdef bytes buf = bytes(val) + if len(buf) != 232: + raise ValueError(f"Expected 232 bytes, got {len(buf)}") + cdef const char* src = buf + cdef int i + for i in range(232): + self._ptr[0].asBytes[i] = src[i] + + @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: + _cyb_memcpy(&obj._data, ptr, sizeof(CUgraphNodeParams)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + obj._readonly = readonly + return obj + + +cdef _get_mem_cpy3d_batch_op_v1_dtype_offsets(): + cdef CUDA_MEMCPY3D_BATCH_OP_v1 pod + return _numpy.dtype({ + 'names': ['src', 'dst', 'extent', 'src_access_order', 'flags_'], + 'formats': [mem_cpy3d_operand_v1_dtype, mem_cpy3d_operand_v1_dtype, extent3d_v1_dtype, _numpy.int32, _numpy.uint32], + 'offsets': [ + (&(pod.src)) - (&pod), + (&(pod.dst)) - (&pod), + (&(pod.extent)) - (&pod), + (&(pod.srcAccessOrder)) - (&pod), + (&(pod.flags)) - (&pod), + ], + 'itemsize': sizeof(CUDA_MEMCPY3D_BATCH_OP_v1), + }) + +mem_cpy3d_batch_op_v1_dtype = _get_mem_cpy3d_batch_op_v1_dtype_offsets() + +cdef class MemCpy3dBatchOp_v1: + """Empty-initialize an instance of `CUDA_MEMCPY3D_BATCH_OP_v1`. + + + .. seealso:: `CUDA_MEMCPY3D_BATCH_OP_v1` + """ + cdef: + CUDA_MEMCPY3D_BATCH_OP_v1 _data + CUDA_MEMCPY3D_BATCH_OP_v1 *_ptr + object _owner + bint _readonly + + def __init__(self): + self._ptr = &self._data + self._owner = None + self._readonly = False + + def __repr__(self): + return f"<{__name__}.MemCpy3dBatchOp_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 MemCpy3dBatchOp_v1 other_ + if not isinstance(other, MemCpy3dBatchOp_v1): + return False + other_ = other + return (_cyb_memcmp((self._ptr), (other_._ptr), sizeof(CUDA_MEMCPY3D_BATCH_OP_v1)) == 0) + + def __getbuffer__(self, _cyb_cpython.Py_buffer *buffer, int flags): + _cyb___getbuffer(self, buffer, self._ptr, sizeof(CUDA_MEMCPY3D_BATCH_OP_v1), self._readonly) + + def __releasebuffer__(self, Py_buffer *buffer): + pass + + def __setitem__(self, key, val): + cdef _cyb_Py_buffer view + if key == 0: + if self._readonly: + raise ValueError("This MemCpy3dBatchOp_v1 instance is read-only") + _cyb_PyObject_GetBuffer(val, &view, _cyb_PyBUF_SIMPLE) + try: + if view.len < sizeof(CUDA_MEMCPY3D_BATCH_OP_v1): + raise ValueError( + "source buffer too small: expected at least %d bytes, got %d" % (sizeof(CUDA_MEMCPY3D_BATCH_OP_v1), view.len) + ) + _cyb_memmove(&self._data, view.buf, sizeof(CUDA_MEMCPY3D_BATCH_OP_v1)) + self._ptr = &self._data + self._owner = None + self._readonly = view.readonly != 0 + finally: + _cyb_PyBuffer_Release(&view) + else: + setattr(self, key, val) + + @property + def src(self): + """MemCpy3dOperand_v1: """ + return MemCpy3dOperand_v1.from_ptr( + &(self._ptr[0].src), + readonly=self._readonly, + owner=self, + ) + + @src.setter + def src(self, val): + if self._readonly: + raise ValueError("This MemCpy3dBatchOp_v1 instance is read-only") + cdef MemCpy3dOperand_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].src), (val_._get_ptr()), sizeof(CUmemcpy3DOperand) * 1) + + @property + def dst(self): + """MemCpy3dOperand_v1: """ + return MemCpy3dOperand_v1.from_ptr( + &(self._ptr[0].dst), + readonly=self._readonly, + owner=self, + ) + + @dst.setter + def dst(self, val): + if self._readonly: + raise ValueError("This MemCpy3dBatchOp_v1 instance is read-only") + cdef MemCpy3dOperand_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].dst), (val_._get_ptr()), sizeof(CUmemcpy3DOperand) * 1) + + @property + def extent(self): + """Extent3D_v1: """ + return Extent3D_v1.from_ptr( + &(self._ptr[0].extent), + readonly=self._readonly, + owner=self, + ) + + @extent.setter + def extent(self, val): + if self._readonly: + raise ValueError("This MemCpy3dBatchOp_v1 instance is read-only") + cdef Extent3D_v1 val_ = val + _cyb_memcpy(&(self._ptr[0].extent), (val_._get_ptr()), sizeof(CUextent3D) * 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 MemCpy3dBatchOp_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 MemCpy3dBatchOp_v1 instance is read-only") + self._ptr[0].flags = val + + @staticmethod + def from_buffer(buffer): + """Create an MemCpy3dBatchOp_v1 instance with the memory from the given buffer.""" + return _cyb_from_buffer(buffer, sizeof(CUDA_MEMCPY3D_BATCH_OP_v1), MemCpy3dBatchOp_v1) + + @staticmethod + def from_data(data): + """Create an MemCpy3dBatchOp_v1 instance wrapping the given NumPy array. + + Args: + data (_numpy.ndarray): a single-element array of dtype `mem_cpy3d_batch_op_v1_dtype` holding the data. + """ + return _cyb_from_data(data, "mem_cpy3d_batch_op_v1_dtype", mem_cpy3d_batch_op_v1_dtype, MemCpy3dBatchOp_v1) + + @staticmethod + def from_ptr(intptr_t ptr, bint readonly=False, object owner=None): + """Create an MemCpy3dBatchOp_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 MemCpy3dBatchOp_v1 obj = MemCpy3dBatchOp_v1.__new__(MemCpy3dBatchOp_v1) + if owner is None: + _cyb_memcpy(&obj._data, ptr, sizeof(CUDA_MEMCPY3D_BATCH_OP_v1)) + obj._ptr = &obj._data + obj._owner = None + else: + obj._ptr = ptr + obj._owner = owner + 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) + + +cdef Py_ssize_t _buffer_item_count(const Py_buffer* view, size_t itemsize, str name, bint allow_raw_bytes=False) except -1: + """Return the number of items in `view`, which must hold items of exactly `itemsize` bytes. + + The buffer is later cast to a C array of that item type, so a buffer with another item size + (for example an ``int64`` array where ``int32`` values are expected) is rejected rather than + being reinterpreted. With `allow_raw_bytes`, a buffer of single bytes is also accepted, as long + as its length is a whole number of items (the cybind struct wrappers export their memory that way). + """ + if view.itemsize == itemsize: + return view.len // view.itemsize + if allow_raw_bytes and view.itemsize == 1 and view.len % itemsize == 0: + return (view.len // itemsize) + raise ValueError(f"{name} must hold items of {itemsize} bytes, got {view.itemsize}-byte items") + + +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:`AtomicOperation` in + ``operations``, the corresponding result is a bitmask of + :class:`AtomicOperationCapability` values indicating which operations the + link supports natively. + + Raises :class:`InvalidDeviceError` if ``dev`` is not valid, and + :class:`InvalidValueError` if ``operations`` is empty or any operation + value is invalid. + + Args: + operations: Buffer of :class:`AtomicOperation` enum values whose + capabilities should be queried (any buffer-exposing object, e.g. + a numpy ``int32`` array; non-contiguous inputs are copied). Each + item must be 4 bytes. + 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 Py_buffer _ops_view_ + cdef unsigned int count + cdef object capabilities + cdef intptr_t caps_ptr + _acquire_buffer(operations, &_ops_view_) + try: + count = _buffer_item_count(&_ops_view_, sizeof(CUatomicOperation), "operations") + capabilities = _numpy.empty(count, dtype=_numpy.uint32) + caps_ptr = capabilities.ctypes.data + 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 ``CU_GL_DEVICE_LIST_ALL``, ``CU_GL_DEVICE_LIST_CURRENT_FRAME`` or ``CU_GL_DEVICE_LIST_NEXT_FRAME``). + + 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 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:`MemCpyAttributes_v1` 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 (attrs is None) != (attrs_idxs is None): + raise ValueError("attrs and attrs_idxs must both be None or both be provided") + cdef size_t count, num_attrs = 0 + 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 + count = _buffer_item_count(&_dsts_view_, sizeof(CUdeviceptr), "dsts") + if ( + _buffer_item_count(&_srcs_view_, sizeof(CUdeviceptr), "srcs") != count + or _buffer_item_count(&_sizes_view_, sizeof(size_t), "sizes") != count + ): + raise ValueError("dsts, srcs, and sizes must hold the same number of items") + if attrs is not None: + num_attrs = _buffer_item_count(&_attrs_view_, sizeof(CUmemcpyAttributes), "attrs", True) + if _buffer_item_count(&_attrs_idxs_view_, sizeof(size_t), "attrs_idxs") != num_attrs: + raise ValueError("attrs and attrs_idxs must hold the same number of items") + 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_) + + +############################################################################### +# Coredump attributes -- the value type depends on the attribute, so these are +# hand-written (they take and return a Python `bytes`, `bool` or `int`, as the legacy +# cuda.bindings.driver functions do). +############################################################################### + +# Value kinds of the coredump attributes. +cdef enum _CoredumpKind: + _COREDUMP_BOOL + _COREDUMP_STRING + _COREDUMP_FLAGS + + +cdef _CoredumpKind _coredump_kind(int attrib) except *: + if attrib == CU_COREDUMP_FILE or attrib == CU_COREDUMP_PIPE: + return _COREDUMP_STRING + if attrib == CU_COREDUMP_GENERATION_FLAGS: + return _COREDUMP_FLAGS + if ( + attrib == CU_COREDUMP_ENABLE_ON_EXCEPTION + or attrib == CU_COREDUMP_TRIGGER_HOST + or attrib == CU_COREDUMP_LIGHTWEIGHT + or attrib == CU_COREDUMP_ENABLE_USER_TRIGGER + ): + return _COREDUMP_BOOL + raise TypeError(f"Unsupported coredump attribute: {attrib}") + + +cdef object _coredump_get(int attrib, bint is_global): + cdef _CoredumpKind kind = _coredump_kind(attrib) + cdef char name[1024] + cdef unsigned char flag = 0 + cdef unsigned int flags = 0 + cdef void* buf + cdef size_t size + cdef CUresult status + name[0] = 0 + if kind == _COREDUMP_STRING: + buf = name + size = 1024 + elif kind == _COREDUMP_FLAGS: + buf = &flags + size = sizeof(flags) + else: + buf = &flag + size = 1 + with nogil: + if is_global: + status = cuCoredumpGetAttributeGlobal(attrib, buf, &size) + else: + status = cuCoredumpGetAttribute(attrib, buf, &size) + check_status(status) + if kind == _COREDUMP_STRING: + return name + if kind == _COREDUMP_FLAGS: + return flags + return bool(flag) + + +cdef _coredump_set(int attrib, value, bint is_global): + cdef _CoredumpKind kind = _coredump_kind(attrib) + cdef bytes data + cdef unsigned char flag = 0 + cdef unsigned int flags = 0 + cdef void* buf + cdef size_t size + cdef CUresult status + if kind == _COREDUMP_STRING: + data = value + buf = data + size = len(data) + elif kind == _COREDUMP_FLAGS: + flags = value + buf = &flags + size = sizeof(flags) + else: + if value: + flag = 1 + buf = &flag + size = 1 + with nogil: + if is_global: + status = cuCoredumpSetAttributeGlobal(attrib, buf, &size) + else: + status = cuCoredumpSetAttribute(attrib, buf, &size) + check_status(status) + + +cpdef object coredump_get_attribute(int attrib): + """Fetch a coredump attribute value for the current context. + + Args: + attrib (int): A :class:`CoredumpSettings` value. + + Returns: + bytes | bool | int: ``bytes`` for ``FILE`` and ``PIPE``, ``int`` (a bitmask of + :class:`CoredumpGenerationFlags`) for ``GENERATION_FLAGS``, and ``bool`` for + ``ENABLE_ON_EXCEPTION``, ``TRIGGER_HOST``, ``LIGHTWEIGHT`` and + ``ENABLE_USER_TRIGGER``. + + .. seealso:: `cuCoredumpGetAttribute` + """ + return _coredump_get(attrib, False) + + +cpdef object coredump_get_attribute_global(int attrib): + """Fetch a coredump attribute value for the entire application. + + Args: + attrib (int): A :class:`CoredumpSettings` value. + + Returns: + bytes | bool | int: As for :func:`coredump_get_attribute`. + + .. seealso:: `cuCoredumpGetAttributeGlobal` + """ + return _coredump_get(attrib, True) + + +cpdef coredump_set_attribute(int attrib, value): + """Set a coredump attribute value for the current context. + + Args: + attrib (int): A :class:`CoredumpSettings` value. + value (bytes | bool | int): ``bytes`` for ``FILE`` and ``PIPE``, an ``int`` + bitmask for ``GENERATION_FLAGS``, ``bool`` for the other supported attributes. + + .. seealso:: `cuCoredumpSetAttribute` + """ + _coredump_set(attrib, value, False) + + +cpdef coredump_set_attribute_global(int attrib, value): + """Set a coredump attribute value globally. + + Args: + attrib (int): A :class:`CoredumpSettings` value. + value (bytes | bool | int): As for :func:`coredump_set_attribute`. + + .. seealso:: `cuCoredumpSetAttributeGlobal` + """ + _coredump_set(attrib, value, True) + + +############################################################################### +# Attribute queries whose value type depends on the attribute +# +# The C functions take a `void*` for the result, so they are hand-written: the +# attribute selects what is read and the value is returned directly. +############################################################################### + +cdef enum _AttrKind: + _ATTR_INT + _ATTR_UINT + _ATTR_ULL + _ATTR_SIZE + _ATTR_BOOL + _ATTR_POINTER + _ATTR_TOKENS + + +cdef union _AttrSlot: + int i + unsigned int u + unsigned long long ull + size_t sz + void* p + CUDA_POINTER_ATTRIBUTE_P2P_TOKENS tokens + + +cdef _AttrKind _pointer_attribute_kind(int attr) except *: + if ( + attr == CU_POINTER_ATTRIBUTE_CONTEXT + or attr == CU_POINTER_ATTRIBUTE_HOST_POINTER + or attr == CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE + ): + return _ATTR_POINTER + if ( + attr == CU_POINTER_ATTRIBUTE_MEMORY_TYPE + or attr == CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE + or attr == CU_POINTER_ATTRIBUTE_ACCESS_FLAGS + ): + return _ATTR_UINT + if attr == CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL: + return _ATTR_INT + if attr == CU_POINTER_ATTRIBUTE_LOCALITY_DOMAIN_ORDINAL: + return _ATTR_INT + if ( + attr == CU_POINTER_ATTRIBUTE_DEVICE_POINTER + or attr == CU_POINTER_ATTRIBUTE_RANGE_START_ADDR + or attr == CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR + or attr == CU_POINTER_ATTRIBUTE_BUFFER_ID + or attr == CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES + or attr == CU_POINTER_ATTRIBUTE_MEMORY_BLOCK_ID + ): + return _ATTR_ULL + if attr == CU_POINTER_ATTRIBUTE_RANGE_SIZE or attr == CU_POINTER_ATTRIBUTE_MAPPING_SIZE: + return _ATTR_SIZE + if attr == CU_POINTER_ATTRIBUTE_P2P_TOKENS: + return _ATTR_TOKENS + if ( + attr == CU_POINTER_ATTRIBUTE_SYNC_MEMOPS + or attr == CU_POINTER_ATTRIBUTE_IS_MANAGED + or attr == CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE + or attr == CU_POINTER_ATTRIBUTE_MAPPED + or attr == CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE + ): + return _ATTR_BOOL + raise TypeError(f"Unsupported pointer attribute: {attr}") + + +cdef _AttrKind _mem_pool_attribute_kind(int attr) except *: + if ( + attr == CU_MEMPOOL_ATTR_RELEASE_THRESHOLD + or attr == CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT + or attr == CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH + or attr == CU_MEMPOOL_ATTR_USED_MEM_CURRENT + or attr == CU_MEMPOOL_ATTR_USED_MEM_HIGH + ): + return _ATTR_ULL + if attr == CU_MEMPOOL_ATTR_MAX_POOL_SIZE: + return _ATTR_ULL + if ( + attr == CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES + or attr == CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC + or attr == CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES + ): + return _ATTR_INT + if ( + attr == CU_MEMPOOL_ATTR_ALLOCATION_TYPE + or attr == CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES + or attr == CU_MEMPOOL_ATTR_LOCATION_ID + or attr == CU_MEMPOOL_ATTR_LOCATION_TYPE + or attr == CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED + ): + return _ATTR_INT + if attr == CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID: + return _ATTR_INT + raise TypeError(f"Unsupported memory pool attribute: {attr}") + + +cdef object _attr_slot_to_python(_AttrKind kind, _AttrSlot* slot): + if kind == _ATTR_INT: + return slot.i + if kind == _ATTR_UINT: + return slot.u + if kind == _ATTR_ULL: + return slot.ull + if kind == _ATTR_SIZE: + return slot.sz + if kind == _ATTR_BOOL: + return bool(slot.i) + if kind == _ATTR_POINTER: + return slot.p + # P2P tokens: a copy owned by the returned wrapper + return PointerAttributeP2PTokens_v1.from_ptr(&slot.tokens) + + +cpdef object pointer_get_attribute(int attribute, uint64_t ptr): + """Return an attribute of a pointer. + + The type of the result depends on ``attribute``: an ``int`` (also for pointers + and device addresses), a ``bool``, or a :class:`PointerAttributeP2PTokens_v1` + for ``P2P_TOKENS``. + + Args: + attribute (int): A :class:`PointerAttribute` value. + ptr (uint64_t): Pointer to query. + + Returns: + int | bool | PointerAttributeP2PTokens_v1: The attribute value. + + .. seealso:: `cuPointerGetAttribute` + """ + cdef _AttrKind kind = _pointer_attribute_kind(attribute) + cdef _AttrSlot slot + cdef CUresult status + memset(&slot, 0, sizeof(slot)) + with nogil: + status = cuPointerGetAttribute(&slot, attribute, ptr) + check_status(status) + return _attr_slot_to_python(kind, &slot) + + +cpdef list pointer_get_attributes(attributes, uint64_t ptr): + """Return several attributes of a pointer, in one call. + + Args: + attributes (sequence of int): :class:`PointerAttribute` values. + ptr (uint64_t): Pointer to query. + + Returns: + list: One value per attribute, as for :func:`pointer_get_attribute`. + + .. seealso:: `cuPointerGetAttributes` + """ + cdef list attrs = [int(a) for a in attributes] + cdef Py_ssize_t n = len(attrs) + cdef Py_ssize_t i + cdef CUpointer_attribute* c_attrs + cdef _AttrSlot* slots + cdef void** data + cdef _AttrKind* kinds + cdef CUresult status + cdef list out + if n == 0: + return [] + for i in range(n): + _pointer_attribute_kind(attrs[i]) # validates the attribute + slots = <_AttrSlot*>PyMem_Calloc(n, sizeof(_AttrSlot)) + data = PyMem_Calloc(n, sizeof(void*)) + c_attrs = PyMem_Calloc(n, sizeof(CUpointer_attribute)) + kinds = <_AttrKind*>PyMem_Calloc(n, sizeof(_AttrKind)) + try: + if slots == NULL or data == NULL or c_attrs == NULL or kinds == NULL: + raise MemoryError("Failed to allocate the attribute buffers") + for i in range(n): + kinds[i] = _pointer_attribute_kind(attrs[i]) + c_attrs[i] = attrs[i] + data[i] = &slots[i] + with nogil: + status = cuPointerGetAttributes(n, c_attrs, data, ptr) + check_status(status) + out = [_attr_slot_to_python(kinds[i], &slots[i]) for i in range(n)] + finally: + PyMem_Free(slots) + PyMem_Free(data) + PyMem_Free(c_attrs) + PyMem_Free(kinds) + return out + + +cpdef object mem_pool_get_attribute(intptr_t pool, int attr): + """Return an attribute of a memory pool (an ``int``). + + Args: + pool (intptr_t): Memory pool handle. + attr (int): A :class:`MemPoolAttribute` value. + + Returns: + int: The attribute value. + + .. seealso:: `cuMemPoolGetAttribute` + """ + cdef _AttrKind kind = _mem_pool_attribute_kind(attr) + cdef _AttrSlot slot + cdef CUresult status + memset(&slot, 0, sizeof(slot)) + with nogil: + status = cuMemPoolGetAttribute(pool, attr, &slot) + check_status(status) + return _attr_slot_to_python(kind, &slot) + + +cpdef unsigned long long device_get_graph_mem_attribute(int device, int attr) except? 0: + """Return a graph memory attribute of a device, in bytes. + + Args: + device (int): Device ordinal. + attr (int): A :class:`GraphMemAttribute` value (``USED_MEM_CURRENT``, ``USED_MEM_HIGH``, + ``RESERVED_MEM_CURRENT`` or ``RESERVED_MEM_HIGH``). + + Returns: + int: The attribute value, in bytes. + + .. seealso:: `cuDeviceGetGraphMemAttribute` + """ + cdef unsigned long long value = 0 + cdef CUresult status + if not ( + attr == CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT + or attr == CU_GRAPH_MEM_ATTR_USED_MEM_HIGH + or attr == CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT + or attr == CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH + ): + raise TypeError(f"Unsupported graph memory attribute: {attr}") + with nogil: + status = cuDeviceGetGraphMemAttribute(device, attr, &value) + check_status(status) + return value + + +cdef bint _mem_range_attribute_is_list(int attribute) except -1: + if attribute == CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY: + return True + if ( + attribute == CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY + or attribute == CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION + or attribute == CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION + or attribute == CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE + or attribute == CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID + or attribute == CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE + or attribute == CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID + ): + return False + raise TypeError(f"Unsupported memory range attribute: {attribute}") + + +cdef object _mem_range_value_to_python(int attribute, void* buf, size_t size): + cdef size_t i + if _mem_range_attribute_is_list(attribute): + return [(buf)[i] for i in range(size // sizeof(int))] + return (buf)[0] + + +cpdef object mem_range_get_attribute(size_t data_size, int attribute, uint64_t dev_ptr, size_t count): + """Return an attribute of a memory range. + + Args: + data_size (size_t): Size in bytes of the result; for ``ACCESSED_BY`` it sets how many + devices (``data_size // 4``) are returned. + attribute (int): A :class:`MemRangeAttribute` value. + dev_ptr (uint64_t): Start of the memory range. + count (size_t): Size of the range in bytes. + + Returns: + int | list[int]: A list of device ordinals for ``ACCESSED_BY``, else an ``int``. + + .. seealso:: `cuMemRangeGetAttribute` + """ + _mem_range_attribute_is_list(attribute) # validates the attribute + cdef size_t size = data_size + if size < sizeof(int): + size = sizeof(int) + cdef void* buf = PyMem_Calloc(1, size) + cdef CUresult status + if buf == NULL: + raise MemoryError("Failed to allocate the attribute buffer") + try: + with nogil: + status = cuMemRangeGetAttribute(buf, data_size, attribute, dev_ptr, count) + check_status(status) + return _mem_range_value_to_python(attribute, buf, data_size) + finally: + PyMem_Free(buf) + + +cpdef list mem_range_get_attributes(data_sizes, attributes, uint64_t dev_ptr, size_t count): + """Return several attributes of a memory range, in one call. + + Args: + data_sizes (sequence of int): Size in bytes of each result. + attributes (sequence of int): :class:`MemRangeAttribute` values. + dev_ptr (uint64_t): Start of the memory range. + count (size_t): Size of the range in bytes. + + Returns: + list: One value per attribute, as for :func:`mem_range_get_attribute`. + + .. seealso:: `cuMemRangeGetAttributes` + """ + cdef list sizes = [int(s) for s in data_sizes] + cdef list attrs = [int(a) for a in attributes] + cdef Py_ssize_t n = len(attrs) + cdef Py_ssize_t i + cdef size_t* c_sizes + cdef CUmem_range_attribute* c_attrs + cdef void** data + cdef CUresult status + cdef list out = [] + if len(sizes) != n: + raise ValueError("data_sizes and attributes must have the same length") + if n == 0: + return [] + for i in range(n): + _mem_range_attribute_is_list(attrs[i]) # validates the attribute + c_sizes = PyMem_Calloc(n, sizeof(size_t)) + c_attrs = PyMem_Calloc(n, sizeof(CUmem_range_attribute)) + data = PyMem_Calloc(n, sizeof(void*)) + try: + if c_sizes == NULL or c_attrs == NULL or data == NULL: + raise MemoryError("Failed to allocate the attribute buffers") + for i in range(n): + c_sizes[i] = sizes[i] + c_attrs[i] = attrs[i] + # Every result needs room for at least one int + data[i] = PyMem_Calloc(1, max(sizes[i], sizeof(int))) + if data[i] == NULL: + raise MemoryError("Failed to allocate the attribute buffer") + with nogil: + status = cuMemRangeGetAttributes(data, c_sizes, c_attrs, n, dev_ptr, count) + check_status(status) + for i in range(n): + out.append(_mem_range_value_to_python(attrs[i], data[i], c_sizes[i])) + finally: + if data != NULL: + for i in range(n): + PyMem_Free(data[i]) + PyMem_Free(c_sizes) + PyMem_Free(c_attrs) + PyMem_Free(data) + return out + + + +############################################################################### +# Other functions with `void*` or in/out results, hand-written so the result is +# returned directly +############################################################################### + +cdef union _HandleSlot: + int i + unsigned int u + void* p + CUmemFabricHandle mem_fabric + CUlogicalEndpointFabricHandle le_fabric + + +cdef object _shareable_handle_to_python(int handle_type, _HandleSlot* slot): + if handle_type == CU_MEM_HANDLE_TYPE_NONE or handle_type == CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR: + return slot.i + if handle_type == CU_MEM_HANDLE_TYPE_WIN32: + return slot.p + if handle_type == CU_MEM_HANDLE_TYPE_WIN32_KMT: + return slot.u + if handle_type == CU_MEM_HANDLE_TYPE_FABRIC: + return MemFabricHandle_v1.from_ptr(&slot.mem_fabric) + raise TypeError(f"Unsupported memory handle type: {handle_type}") + + +cpdef object mem_export_to_shareable_handle(uint64_t handle, int handle_type, unsigned long long flags): + """Export an allocation to an OS-specific shareable handle. + + Args: + handle (uint64_t): Memory allocation handle to export. + handle_type (int): A :class:`MemAllocationHandleType` value. + flags (unsigned long long): Reserved, must be zero. + + Returns: + int | MemFabricHandle_v1: A file descriptor or OS handle as an ``int`` (a + :class:`MemFabricHandle_v1` for ``FABRIC``). + + .. seealso:: `cuMemExportToShareableHandle` + """ + cdef _HandleSlot slot + cdef CUresult status + memset(&slot, 0, sizeof(slot)) + _shareable_handle_to_python(handle_type, &slot) # validates handle_type + with nogil: + status = cuMemExportToShareableHandle(&slot, handle, handle_type, flags) + check_status(status) + return _shareable_handle_to_python(handle_type, &slot) + + +cpdef object mem_pool_export_to_shareable_handle(intptr_t pool, int handle_type, unsigned long long flags): + """Export a memory pool to an OS-specific shareable handle. + + Args: + pool (intptr_t): Memory pool to export. + handle_type (int): A :class:`MemAllocationHandleType` value. + flags (unsigned long long): Reserved, must be zero. + + Returns: + int | MemFabricHandle_v1: As for :func:`mem_export_to_shareable_handle`. + + .. seealso:: `cuMemPoolExportToShareableHandle` + """ + cdef _HandleSlot slot + cdef CUresult status + memset(&slot, 0, sizeof(slot)) + _shareable_handle_to_python(handle_type, &slot) # validates handle_type + with nogil: + status = cuMemPoolExportToShareableHandle(&slot, pool, handle_type, flags) + check_status(status) + return _shareable_handle_to_python(handle_type, &slot) + + +cpdef object logical_endpoint_export(uint32_t le_id, int handle_type): + """Export a logical endpoint to an IPC handle. + + Args: + le_id (uint32_t): Logical endpoint id. + handle_type (int): A :class:`LogicalEndpointIpcHandleType` value. + + Returns: + int | LogicalEndpointFabricHandle: A file descriptor as an ``int``, or a + :class:`LogicalEndpointFabricHandle` for ``FABRIC``. + + .. seealso:: `cuLogicalEndpointExport` + """ + cdef _HandleSlot slot + cdef CUresult status + memset(&slot, 0, sizeof(slot)) + if handle_type != CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_NONE and handle_type != CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_FABRIC: + raise TypeError(f"Unsupported logical endpoint handle type: {handle_type}") + with nogil: + status = cuLogicalEndpointExport(&slot, le_id, handle_type) + check_status(status) + if handle_type == CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_FABRIC: + return LogicalEndpointFabricHandle.from_ptr(&slot.le_fabric) + return slot.i + + +cpdef int mem_get_handle_for_address_range(uint64_t dptr, size_t size, int handle_type, unsigned long long flags) except? -1: + """Return a handle (a dma-buf file descriptor) for an address range. + + Args: + dptr (uint64_t): Start of the address range. + size (size_t): Size of the range in bytes. + handle_type (int): A :class:`MemRangeHandleType` value. + flags (unsigned long long): Flags, see the CUDA documentation. + + Returns: + int: The file descriptor. + + .. seealso:: `cuMemGetHandleForAddressRange` + """ + cdef int handle = -1 + cdef CUresult status + with nogil: + status = cuMemGetHandleForAddressRange(&handle, dptr, size, handle_type, flags) + check_status(status) + return handle + + +cpdef int thread_exchange_stream_capture_mode(int mode) except? -1: + """Swap the stream capture interaction mode of the calling thread. + + Sets the calling thread's stream capture interaction mode to ``mode`` and returns the + mode it had before. Callers are encouraged to use this in a push-pop fashion: set the + mode they need, and restore the returned one afterwards. + + During stream capture, some actions (such as a call to ``cudaMalloc``) may be unsafe. + A thread's mode is one of the :class:`StreamCaptureMode` values: ``GLOBAL`` (the + default), ``THREAD_LOCAL`` or ``RELAXED``. + + Args: + mode (int): The new mode, a :class:`StreamCaptureMode` value. + + Returns: + int: The previous mode of the thread, a :class:`StreamCaptureMode` value. + + .. seealso:: `cuThreadExchangeStreamCaptureMode` + """ + cdef CUstreamCaptureMode c_mode = mode + cdef CUresult status + with nogil: + status = cuThreadExchangeStreamCaptureMode(&c_mode) + check_status(status) + return c_mode + + +cpdef list tex_ref_get_border_color(intptr_t h_tex_ref): + """Return the border color of a texture reference. + + Args: + h_tex_ref (intptr_t): Texture reference. + + Returns: + list[float]: The four color components (R, G, B, A). + + .. seealso:: `cuTexRefGetBorderColor` + """ + cdef float color[4] + cdef CUresult status + color[0] = color[1] = color[2] = color[3] = 0 + with nogil: + status = cuTexRefGetBorderColor(color, h_tex_ref) + check_status(status) + return [color[0], color[1], color[2], color[3]] + + +cpdef unsigned int logs_dump_to_file(iterator, bytes path_to_file, unsigned int flags) except? 0: + """Dump the driver's error log buffer to a file. + + Args: + iterator (int | None): Iterator from a previous call, or ``None`` to dump the whole + buffer. + path_to_file (bytes): Path of the output file. + flags (unsigned int): Reserved, must be zero. + + Returns: + int: The updated iterator, which can be passed to the next call to continue from there. + + .. seealso:: `cuLogsDumpToFile` + """ + cdef CUlogIterator it = 0 + cdef CUlogIterator* it_ptr = NULL + cdef const char* c_path = path_to_file + cdef CUresult status + if iterator is not None: + it = iterator + it_ptr = &it + with nogil: + status = cuLogsDumpToFile(it_ptr, c_path, flags) + check_status(status) + return it + + +############################################################################### +# kernel_params support, used by the generated launch_kernel, launch_kernel_ex and +# launch_cooperative_kernel wrappers (see the `pyargs` of cuLaunchKernel in the config) +############################################################################### + +# Helper adapted 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 object _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, +} +# A slot wide enough for all `supported_types` (and `void_p`) +cdef size_t _MAX_PARAM_SIZE = max(_ctypes.sizeof(t) for t in _supported_types) +# For correct access pointers have to fit (appended) and the size +# must be a multiple of the max alignment (guaranteed if power of 2). +assert _MAX_PARAM_SIZE % sizeof(void*) == 0 +assert ((_MAX_PARAM_SIZE - 1) & _MAX_PARAM_SIZE) == 0 + + +cdef int _try_specific_types(char* slot, object value, object ctype) except -1: + """Fast paths for the common argument types. If this returns 0, the caller + falls back to `ctype(value)`. This converter is stricter than ctypes + (e.g. raises for out of bound integers). + """ + cdef object value_type = type(value) + if ctype is _ctypes.c_int and value_type is int: + (slot)[0] = value + return 1 + if ctype is _ctypes.c_bool and value_type is bool: + (slot)[0] = value + return 1 + if ctype is _ctypes.c_byte and value_type is int: + (slot)[0] = value + return 1 + if ctype is _ctypes.c_double: + if value_type is float: + (slot)[0] = value + return 1 + if isinstance(value, _ctypes.c_float): + # This explicitly allows c_float for double arguments. + (slot)[0] = value.value + return 1 + return 0 + if ctype is _ctypes.c_float and value_type is float: + (slot)[0] = value + return 1 + if ctype is _ctypes.c_longlong and value_type is int: + (slot)[0] = value + return 1 + return 0 + + +cdef int _pack_argument(void** ptr, char* slot, object value, object ctype) except -1: + cdef size_t size + cdef void* addr + cdef object get_ptr + + if ctype is None: + get_ptr = getattr(value, 'getPtr', None) + if callable(get_ptr): + ptr[0] = get_ptr() + 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 `getPtr()`. + ptr[0] = value.ptr + elif isinstance(value, _ctypes.Structure): + ptr[0] = _ctypes.addressof(value) + elif isinstance(value, _FastEnum): + ptr[0] = slot + (slot)[0] = value # _FastEnum is an int + else: + raise TypeError( + f"Provided argument is of type {type(value)} but expected Type {_ctypes.Structure}, " + f"{_ctypes.c_void_p} or CUDA Binding structure with getPtr() attribute" + ) + return 0 + + ptr[0] = slot + if _try_specific_types(slot, value, ctype): + return 0 + if ctype in _supported_types: + if not isinstance(value, ctype): + value = ctype(value) + size = _ctypes.sizeof(ctype) + addr = _ctypes.addressof(value) + memcpy(slot, addr, size) + return 0 + elif ctype is _ctypes.c_void_p: + if isinstance(value, (int, _ctypes.c_void_p)): + if isinstance(value, _ctypes.c_void_p): + (slot)[0] = value.value + else: + (slot)[0] = value + else: + get_ptr = getattr(value, 'getPtr', None) + if callable(get_ptr): + (slot)[0] = get_ptr() + elif getattr(value, 'ptr', None) is not None: + (slot)[0] = value.ptr + else: + raise TypeError( + f"Provided argument is of type {type(value)} but expected Type {int}, " + f"{_ctypes.c_void_p} or CUDA Binding structure with getPtr() attribute" + ) + return 0 + raise TypeError(f"Unsupported type: {ctype!r}") + + +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 + + def __cinit__(self, kernelParams): + cdef tuple values, types + cdef Py_ssize_t i, n + cdef size_t data_bytes, total + cdef char* block + cdef char* slot + cdef int err_buffer + cdef void** ptrs + + self._pyobj_acquired = False + self._ckernelParams = NULL + self._ckernelParamsData = NULL + + if kernelParams is None: + pass + 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) + ): + values = kernelParams[0] + types = kernelParams[1] + n = len(values) + if n != len(types): + raise TypeError("Argument 'kernelParams' has tuples with different length") + if n == 0: + return + # One block: `n` fixed-size value slots followed by the `n` void* pointers. + data_bytes = n * _MAX_PARAM_SIZE + total = data_bytes + n * sizeof(void*) + block = PyMem_Calloc(1, total) + if block == NULL: + raise MemoryError("Failed to allocate memory for kernel parameters") + self._ckernelParamsData = block + ptrs = (block + data_bytes) + self._ckernelParams = ptrs + for i in range(n): + slot = block + i * _MAX_PARAM_SIZE + _pack_argument(ptrs + i, slot, values[i], types[i]) + else: + raise TypeError("Argument 'kernelParams' is not a valid type: tuple[tuple[Any, ...], tuple[Any, ...]] or PyObject implementing Buffer Protocol or Int") + + def __dealloc__(self): + if self._pyobj_acquired: + PyBuffer_Release(&self._pybuffer) + if self._ckernelParamsData: + PyMem_Free(self._ckernelParamsData) + + @property + def ckernelParams(self): + return self._ckernelParams + + +cpdef str get_error_string(int error): + """Gets the string description of an error code. + + Sets ``*p_str`` 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 ``*p_str`` will be set to the + NULL address. + + Args: + error (Result): Error code to convert to string. + + Returns: + str: Address of the string pointer. + + .. seealso:: `cuGetErrorString` + """ + cdef const char* p_str = NULL + with nogil: + __status__ = cuGetErrorString(error, &p_str) + check_status(__status__) + return _cyb_cpython.PyUnicode_FromString(p_str) if p_str != NULL else "" + + +cpdef str get_error_name(int error): + """Gets the string representation of an error code enum name. + + Sets ``*p_str`` 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 ``*p_str`` will be set to the + NULL address. + + Args: + error (Result): Error code to convert to string. + + Returns: + str: Address of the string pointer. + + .. seealso:: `cuGetErrorName` + """ + cdef const char* p_str = NULL + with nogil: + __status__ = cuGetErrorName(error, &p_str) + check_status(__status__) + return _cyb_cpython.PyUnicode_FromString(p_str) if p_str != NULL else "" + + +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: + bytes: 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: + - bytes: 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_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 (intptr_t): 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_ptr_ = 0 if ctx_create_params is None else int(ctx_create_params) + cdef CUcontext pctx + with nogil: + __status__ = cuCtxCreate(&pctx, _ctx_create_params_ptr_, 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. + - ``CU_LIMIT_PER_BLOCK_MEMORY_SIZE`` constrols size in bytes of per-block + memory. + + 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. + - ``CU_LIMIT_PER_BLOCK_MEMORY_SIZE``: Per-block memory 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 (bytes): Name of function to retrieve. + + Returns: + intptr_t: Returned function handle. + + .. seealso:: `cuModuleGetFunction` + """ + cdef void* _name_ = _cyb_get_buffer_pointer(name, -1, readonly=True) + 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 _cyb_view.array _functions_alloc_ = _cyb_view.array(shape=(max(num_functions, 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *functions_ptr = (_functions_alloc_.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: + - uint64_t: 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: + bytes: 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 _cyb_view.array _kernels_alloc_ = _cyb_view.array(shape=(max(num_kernels, 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *kernels_ptr = (_kernels_alloc_.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: + - uint64_t: 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: + - uint64_t: 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``. + - ``CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE``: The shared memory mode of a + function. The value type is ``CUsharedMemoryMode`` / cudaSharedMemoryMode. + + 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``. + - ``CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE``: The shared memory mode of a + function. The value type is ``CUsharedMemoryMode`` / cudaSharedMemoryMode. + + 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 bytes kernel_get_name(intptr_t hfunc): + """Returns the function name for a ``CUkernel`` handle. + + Returns in ``**name`` the function name associated with the kernel handle + ``hfunc`` . The function name is returned as a null-terminated string. The + returned name is only valid when the kernel handle is valid. If the library is + unloaded or reloaded, one must call the API again to get the updated name. This + API may return a mangled name if the function is not declared as having C + linkage. If either ``**name`` or ``hfunc`` is NULL, + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Args: + hfunc (intptr_t): The function handle to retrieve the name for. + + Returns: + bytes: The returned name of the function. + + .. seealso:: `cuKernelGetName` + """ + cdef const char* name = NULL + with nogil: + __status__ = cuKernelGetName(&name, hfunc) + check_status(__status__) + return (name) if name != NULL else b"" + + +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 uint64_t 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: + uint64_t: 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: + - uint64_t: 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(uint64_t 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 (uint64_t): Pointer to memory to free. + + .. seealso:: `cuMemFree_v2` + """ + with nogil: + __status__ = cuMemFree(dptr) + check_status(__status__) + + +cpdef tuple mem_get_address_range_v2(uint64_t 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 (uint64_t): Device pointer to query. + + Returns: + A 2-tuple containing: + - uint64_t: 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 uint64_t 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: + uint64_t: 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 uint64_t 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: + uint64_t: 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: + bytes: 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(uint64_t 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 (uint64_t): 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 uint64_t 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: + uint64_t: 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(uint64_t 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 (uint64_t): 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(uint64_t dst, uint64_t 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 (uint64_t): Destination unified virtual address space pointer. + src (uint64_t): 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(uint64_t dst_device, intptr_t dst_context, uint64_t 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 (uint64_t): Destination device pointer. + dst_context (intptr_t): Destination context. + src_device (uint64_t): 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(uint64_t 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 (uint64_t): 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, uint64_t 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 (uint64_t): 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(uint64_t dst_device, uint64_t 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 (uint64_t): Destination device pointer. + src_device (uint64_t): 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, uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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_ = 0 if p_copy is None else 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_ = 0 if p_copy is None else 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_ = 0 if p_copy is None else 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_ = 0 if p_copy is None else int(p_copy) + with nogil: + __status__ = cuMemcpy3DPeer(_p_copy_ptr_) + check_status(__status__) + + +cpdef memcpy_async(uint64_t dst, uint64_t 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 (uint64_t): Destination unified virtual address space pointer. + src (uint64_t): 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(uint64_t dst_device, intptr_t dst_context, uint64_t 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 (uint64_t): Destination device pointer. + dst_context (intptr_t): Destination context. + src_device (uint64_t): 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(uint64_t 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 (uint64_t): 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, uint64_t 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 (uint64_t): 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(uint64_t dst_device, uint64_t 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 (uint64_t): Destination device pointer. + src_device (uint64_t): 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_ = 0 if p_copy is None else 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_ = 0 if p_copy is None else 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_ = 0 if p_copy is None else int(p_copy) + with nogil: + __status__ = cuMemcpy3DPeerAsync(_p_copy_ptr_, h_stream) + check_status(__status__) + + +cpdef memset_d8_v2(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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_ = 0 if p_allocate_array is None else 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_ = 0 if p_allocate_array is None else 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_ = 0 if p_mipmapped_array_desc is None else 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 size_t mem_batch_decompress_async(params_array, size_t count, unsigned int flags, intptr_t stream) except? 0: + """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. + stream (intptr_t): The stream where the work will be enqueued. + + Returns: + size_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. + + .. seealso:: `cuMemBatchDecompressAsync` + """ + cdef intptr_t _params_array_ptr_ = 0 if params_array is None else int(params_array) + cdef size_t error_index + with nogil: + __status__ = cuMemBatchDecompressAsync(_params_array_ptr_, count, flags, &error_index, stream) + check_status(__status__) + return error_index + + +cpdef uint64_t mem_address_reserve(size_t size, size_t alignment, uint64_t 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 (uint64_t): Hint address for the start of the address range. + flags (unsigned long long): Currently unused, must be zero. + + Returns: + uint64_t: 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(uint64_t 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 (uint64_t): 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 uint64_t 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``. Specifying + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN`` as the ``CUmemLocation.type`` + will localize the allocation to the specified locality domain. + ``CUmemAllocationProp``::CUmemLocation::localized.deviceId must specify the + device ID. ``CUmemAllocationProp``::CUmemLocation::localized.localityDomainId + must specify the locality domain ID. The locality domain ID must be a valid + locality domain ID for the specified device. See also ``cuDeviceGetAttribute`` + with the attribute ``CU_DEVICE_ATTRIBUTE_LOCALITY_DOMAIN_COUNT``. + 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: + uint64_t: Value of handle returned. All operations on this + allocation are to be performed using this handle. + + .. note:: + On devices with a single locality domain, + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN`` and localityDomainId 0 is + equivalent to a full-device allocation created with + ``CU_MEM_LOCATION_TYPE_DEVICE``. The resulting allocation will be of type + ``CU_MEM_LOCATION_TYPE_DEVICE``. + .. seealso:: `cuMemCreate` + """ + cdef intptr_t _prop_ptr_ = 0 if prop is None else int(prop) + cdef CUmemGenericAllocationHandle handle + with nogil: + __status__ = cuMemCreate(&handle, size, _prop_ptr_, flags) + check_status(__status__) + return handle + + +cpdef mem_release(uint64_t 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 (uint64_t): Value of handle which was returned previously + by cuMemCreate. + + .. seealso:: `cuMemRelease` + """ + with nogil: + __status__ = cuMemRelease(handle) + check_status(__status__) + + +cpdef mem_map(uint64_t ptr, size_t size, size_t offset, uint64_t 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 fail if the + devices added via ``cuMulticastAddDevice`` do not belong to the same clique. + 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 (uint64_t): Address where memory will be mapped. + size (size_t): Size of the memory mapping. + offset (size_t): Offset into the memory represented by. + handle (uint64_t): 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_SPARSE_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 + ``CUarraySparseSubresourceType``::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_ = 0 if map_info_list is None else int(map_info_list) + with nogil: + __status__ = cuMemMapArrayAsync(_map_info_list_ptr_, count, h_stream) + check_status(__status__) + + +cpdef mem_unmap(uint64_t 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 (uint64_t): 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(uint64_t 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 (uint64_t): 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_ = 0 if desc is None else int(desc) + with nogil: + __status__ = cuMemSetAccess(ptr, size, _desc_ptr_, count) + check_status(__status__) + + +cpdef unsigned long long mem_get_access(location, uint64_t 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 (uint64_t): 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_ = 0 if location is None else int(location) + cdef unsigned long long flags + with nogil: + __status__ = cuMemGetAccess(&flags, _location_ptr_, ptr) + check_status(__status__) + return flags + + +cpdef uint64_t 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: + uint64_t: 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_ = 0 if prop is None else int(prop) + cdef size_t granularity + with nogil: + __status__ = cuMemGetAllocationGranularity(&granularity, _prop_ptr_, option) + check_status(__status__) + return granularity + + +cpdef object mem_get_allocation_properties_from_handle(uint64_t handle): + """Retrieve the contents of the property structure defining properties for this handle. + + + Args: + handle (uint64_t): Handle which to perform the query on. + + Returns: + CUmemAllocationProp_v1: Pointer to a properties structure which + will hold the information about this handle. + + .. seealso:: `cuMemGetAllocationPropertiesFromHandle` + """ + cdef MemAllocationProp_v1 prop_py = MemAllocationProp_v1() + cdef CUmemAllocationProp *prop = (prop_py._get_ptr()) + with nogil: + __status__ = cuMemGetAllocationPropertiesFromHandle(prop, handle) + check_status(__status__) + return prop_py + + +cpdef uint64_t 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: + uint64_t: 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(uint64_t 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 (uint64_t): 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 uint64_t 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: + uint64_t: 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_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_ = 0 if map is None else 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_ = 0 if location is None else 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``. To create a memory pool targeting a specific + device locality domain, applications must set + ``CUmemPoolProps``::CUmemLocation::type to + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN``, + ``CUmemPoolProps``::CUmemLocation::localized.deviceId must specify the device + ID, and ``CUmemPoolProps``::CUmemLocation::localized.localityDomainId must + specify the locality domain ID. The locality domain ID must be a valid locality + domain ID for the specified device. See also ``cuDeviceGetAttribute`` with the + attribute ``CU_DEVICE_ATTRIBUTE_LOCALITY_DOMAIN_COUNT``. + 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:: + On devices with a single locality domain, a memory pool created with + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN`` and localityDomainId 0 is + equivalent to a full-device memory pool created with + ``CU_MEM_LOCATION_TYPE_DEVICE``. The pool will report + ``CU_MEM_LOCATION_TYPE_DEVICE`` for ``CU_MEMPOOL_ATTR_LOCATION_TYPE`` and -1 + for ``CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID``. + .. note:: + Specifying CU_MEM_HANDLE_TYPE_NONE creates a memory pool that will not support + IPC. + .. seealso:: `cuMemPoolCreate` + """ + cdef intptr_t _pool_props_ptr_ = 0 if pool_props is None else 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 uint64_t 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: + uint64_t: Returned device pointer. + + .. note:: + The specified memory pool may be from a device different than that of the + specified ``h_stream``. + .. 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:: `cuMemAllocFromPoolAsync` + """ + cdef CUdeviceptr dptr + with nogil: + __status__ = cuMemAllocFromPoolAsync(&dptr, bytesize, pool, h_stream) + check_status(__status__) + return dptr + + +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(uint64_t 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 (uint64_t): 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 uint64_t 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: + uint64_t: 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_ = 0 if share_data is None else int(share_data) + cdef CUdeviceptr ptr_out + with nogil: + __status__ = cuMemPoolImportPointer(&ptr_out, pool, _share_data_ptr_) + check_status(__status__) + return ptr_out + + +cpdef uint64_t 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: + uint64_t: Value of handle returned. + + .. seealso:: `cuMulticastCreate` + """ + cdef intptr_t _prop_ptr_ = 0 if prop is None else int(prop) + cdef CUmemGenericAllocationHandle mc_handle + with nogil: + __status__ = cuMulticastCreate(&mc_handle, _prop_ptr_) + check_status(__status__) + return mc_handle + + +cpdef multicast_add_device(uint64_t 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. + This call may fail with ``CUDA_ERROR_INVALID_DEVICE`` if the device specified + by ``dev`` does not belong to the same clique as the other devices previously + added to this multicast object. + + Args: + mc_handle (uint64_t): 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(uint64_t mc_handle, size_t mc_offset, uint64_t 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. + On systems with Rubin+ (SM_107+) GPUs, ``mem_offset`` may be aligned to 256 + instead of the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. In such a case the ``size`` + + ``mem_offset`` cannot be larger than the size of the allocated memory. + Similarly the ``size`` + ``mc_offset`` + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` cannot be larger than the size of the than + the size of the multicast object. The next available mc_offset for the next + bind will be mc_offset + size + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. + Also note that the ability to accept a ``mem_offset`` that is not aligned to + the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED`` is limited by HW resources and may + result in error ``CUDA_ERROR_MULTICAST_RESOURCE_FULL``. + 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 fail if the devices added via ``cuMulticastAddDevice`` do not + belong to the same clique. + 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 (uint64_t): Handle representing a multicast object. + mc_offset (size_t): Offset into the multicast object for + attachment. + mem_handle (uint64_t): 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(uint64_t mc_handle, size_t mc_offset, uint64_t 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. + On systems with Rubin+ (SM_107+) GPUs, ``memptr`` may be aligned to 256 instead + of the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. In such a case the ``size`` + + ``memptr`` cannot be larger than the size of the allocated memory. Similarly + the ``size`` + ``mc_offset`` + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` cannot be larger than the size of the than + the size of the multicast object. The next available mc_offset for the next + bind will be mc_offset + size + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. + Also note that the ability to accept a ``memptr`` that is not aligned to the + value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED`` is limited by HW resources and may + result in error ``CUDA_ERROR_MULTICAST_RESOURCE_FULL``. + 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 fail if the devices added via ``cuMulticastAddDevice`` do not + belong to the same clique. + 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 (uint64_t): Handle representing a multicast object. + mc_offset (size_t): Offset into multicast va range for attachment. + memptr (uint64_t): 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(uint64_t 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 (uint64_t): 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_ = 0 if prop is None else int(prop) + cdef size_t granularity + with nogil: + __status__ = cuMulticastGetGranularity(&granularity, _prop_ptr_, option) + check_status(__status__) + return granularity + + +cpdef mem_prefetch_async_v2(uint64_t 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. Prefetching to + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN`` locations is not supported. + The start address and end address of the memory range will be rounded down and + rounded up respectively to be aligned to CPU page size before the prefetch + operation is enqueued in the stream. + If no physical memory has been allocated for this region, then this memory + region will be populated and mapped on the destination device. If there's + insufficient memory to prefetch the desired region, the Unified Memory driver + may evict pages from other ``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 (uint64_t): Pointer to be prefetched. + count (size_t): Size in bytes. + location (CUmemLocation_v1): 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(uint64_t 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``. A ``CUmemLocation.type`` + of ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN`` is unsupported. Setting + the preferred location does not cause data to migrate to that location + immediately. Instead, it guides the migration policy when a fault occurs on + that memory region. If the data is already in its preferred location and the + faulting processor can establish a mapping without requiring the data to be + migrated, then data migration will be avoided. On the other hand, if the data + is not in its preferred location or if a direct mapping cannot be + established, then it will be migrated to the processor accessing it. It is + important to note that setting the preferred location does not prevent data + prefetching done using ``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 (uint64_t): 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 (CUmemLocation_v1): 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 pointer_set_attribute(value, int attribute, uint64_t 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 (uint64_t): 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 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, 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 (object): Dependencies of the first node captured in + the stream. Can be NULL if num_dependencies is 0. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _dependency_data_ptr_ = 0 if dependency_data is None else int(dependency_data) + with nogil: + __status__ = cuStreamBeginCaptureToGraph(h_stream, h_graph, (_dependencies_.data()), _dependency_data_ptr_, num_dependencies, mode) + check_status(__status__) + + +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, 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 (object): The set of dependencies to add. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _dependency_data_ptr_ = 0 if dependency_data is None else int(dependency_data) + with nogil: + __status__ = cuStreamUpdateCaptureDependencies(h_stream, (_dependencies_.data()), _dependency_data_ptr_, num_dependencies, flags) + check_status(__status__) + + +cpdef stream_attach_mem_async(intptr_t h_stream, uint64_t 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 (uint64_t): 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 object stream_get_attribute(intptr_t h_stream, int attr): + """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): . + + Returns: + CUlaunchAttributeValue: . + + .. seealso:: `cuStreamGetAttribute` + """ + cdef LaunchAttributeValue value_out_py = LaunchAttributeValue() + cdef CUstreamAttrValue *value_out = (value_out_py._get_ptr()) + with nogil: + __status__ = cuStreamGetAttribute(h_stream, attr, value_out) + check_status(__status__) + return value_out_py + + +cpdef stream_set_attribute(intptr_t h_stream, int attr, 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` + """ + cdef intptr_t _value_ptr_ = 0 if value is None else int(value) + with nogil: + __status__ = cuStreamSetAttribute(h_stream, attr, _value_ptr_) + 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(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 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 intptr_t _mem_handle_desc_ptr_ = 0 if mem_handle_desc is None else int(mem_handle_desc) + cdef CUexternalMemory ext_mem_out + with nogil: + __status__ = cuImportExternalMemory(&ext_mem_out, _mem_handle_desc_ptr_) + check_status(__status__) + return ext_mem_out + + +cpdef uint64_t 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: + uint64_t: Returned device pointer to buffer. + + .. seealso:: `cuExternalMemoryGetMappedBuffer` + """ + cdef intptr_t _buffer_desc_ptr_ = 0 if buffer_desc is None else 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, 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 intptr_t _mipmap_desc_ptr_ = 0 if mipmap_desc is None else int(mipmap_desc) + cdef CUmipmappedArray mipmap + with nogil: + __status__ = cuExternalMemoryGetMappedMipmappedArray(&mipmap, ext_mem, _mipmap_desc_ptr_) + 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(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 intptr_t _sem_handle_desc_ptr_ = 0 if sem_handle_desc is None else int(sem_handle_desc) + cdef CUexternalSemaphore ext_sem_out + with nogil: + __status__ = cuImportExternalSemaphore(&ext_sem_out, _sem_handle_desc_ptr_) + check_status(__status__) + return ext_sem_out + + +cpdef signal_external_semaphores_async(ext_sem_array, 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 (object): Set of external semaphores to be signaled. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _ext_sem_array_ + _cyb_get_resource_ptrs[void](_ext_sem_array_, ext_sem_array, NULL) + cdef intptr_t _params_array_ptr_ = 0 if params_array is None else int(params_array) + with nogil: + __status__ = cuSignalExternalSemaphoresAsync((_ext_sem_array_.data()), _params_array_ptr_, num_ext_sems, stream) + check_status(__status__) + + +cpdef wait_external_semaphores_async(ext_sem_array, 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 (object): External semaphores to be waited on. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _ext_sem_array_ + _cyb_get_resource_ptrs[void](_ext_sem_array_, ext_sem_array, NULL) + cdef intptr_t _params_array_ptr_ = 0 if params_array is None else int(params_array) + with nogil: + __status__ = cuWaitExternalSemaphoresAsync((_ext_sem_array_.data()), _params_array_ptr_, 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, uint64_t addr, uint32_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 (uint64_t): The memory location to wait on. + value (uint32_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, uint64_t 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 (uint64_t): 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, uint64_t addr, uint32_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 (uint64_t): The device address to write to. + value (uint32_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, uint64_t 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 (uint64_t): 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_ = 0 if param_array is None else 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``. + - ``CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE``: The shared memory mode of a + function. The value type is ``CUsharedMemoryMode`` / cudaSharedMemoryMode. + + 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``. + - ``CU_FUNC_ATTRIBUTE_SHARED_MEMORY_MODE``: The shared memory mode of a + function. The value type is ``CUsharedMemoryMode`` / cudaSharedMemoryMode. + + 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 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. If either ``**name`` or ``hfunc`` is NULL, + ``CUDA_ERROR_INVALID_VALUE`` is returned. + + Args: + hfunc (intptr_t): The function handle to retrieve the name for. + + Returns: + bytes: The returned name of the function. + + .. seealso:: `cuFuncGetName` + """ + cdef const char* name = NULL + with nogil: + __status__ = cuFuncGetName(&name, hfunc) + check_status(__status__) + return (name) if name != NULL else b"" + + +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_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): + """Launches a CUDA function ``CUfunction`` or a CUDA kernel ``CUkernel``. + + Invokes the function ``CUfunction`` or the kernel ``CUkernel`` ``f`` on a + ``grid_dim_x`` x ``grid_dim_y`` x ``grid_dim_z`` grid of blocks. Each block + contains ``block_dim_x`` x ``block_dim_y`` x ``block_dim_z`` threads. + ``shared_mem_bytes`` sets the amount of dynamic shared memory that will be + available to each thread block. + Kernel parameters to ``f`` can be specified in one of two ways:. + 1) Kernel parameters can be specified via ``kernel_params``. If ``f`` has N + parameters, then ``kernel_params`` needs to be an array of N pointers. Each of + ``kernel_params``\[0] through ``kernel_params``\[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. + 2) Kernel parameters can also be packaged by the application into a single + buffer that is passed in via the ``extra`` parameter. This places the burden on + the application of knowing each kernel parameter's size and alignment/padding + within the buffer. Here is an example of using the ``extra`` parameter in this + manner:. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + The ``extra`` parameter exists to allow ``cuLaunchKernel`` to take additional + less commonly used arguments. ``extra`` specifies a list of names of extra + settings and their corresponding values. Each extra setting name is immediately + followed by the corresponding value. The list must be terminated with either + NULL or ``CU_LAUNCH_PARAM_END``. + + - ``CU_LAUNCH_PARAM_END``, which indicates the end of the ``extra`` array;. + - ``CU_LAUNCH_PARAM_BUFFER_POINTER``, which specifies that the next value in + ``extra`` will be a pointer to a buffer containing all the kernel parameters + for launching kernel ``f``;. + - ``CU_LAUNCH_PARAM_BUFFER_SIZE``, which specifies that the next value in + ``extra`` will be a pointer to a size_t containing the size of the buffer + specified with ``CU_LAUNCH_PARAM_BUFFER_POINTER``;. + + The error ``CUDA_ERROR_INVALID_VALUE`` will be returned if kernel parameters + are specified with both ``kernel_params`` and ``extra`` (i.e. both + ``kernel_params`` and ``extra`` are non-NULL). + Calling :func:`launch_kernel` invalidates the persistent function state set + through the following deprecated APIs: :func:`func_set_block_shape`, + :func:`func_set_shared_size`, :func:`param_set_size`, :func:`param_seti`, + :func:`param_setf`, :func:`param_setv`. + Note that to use :func:`launch_kernel`, the kernel ``f`` must either have been + compiled with toolchain version 3.2 or later so that it will contain kernel + parameter information, or have no kernel parameters. If either of these + conditions is not met, then :func:`launch_kernel` will return + ``CUDA_ERROR_INVALID_IMAGE``. + Note that the API can also be used to 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 launch the kernel on + will either be taken from the specified stream ``h_stream`` or the current + context in case of NULL stream. + + Args: + f (intptr_t): Function ``CUfunction`` or Kernel ``CUkernel`` to + launch. + 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 identifier. + kernel_params (object): Array of pointers to kernel parameters. + extra (intptr_t): Extra options. + + .. seealso:: `cuLaunchKernel` + """ + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kernel_params__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, (_kernel_params__ptr), extra) + check_status(__status__) + + +cpdef launch_kernel_ex(config, intptr_t f, kernel_params, intptr_t extra): + """Launches a CUDA function ``CUfunction`` or a CUDA kernel ``CUkernel`` with launch-time configuration. + + Invokes the function ``CUfunction`` or the kernel ``CUkernel`` ``f`` with the + specified launch-time configuration ``config``. + The ``CUlaunchConfig`` structure is defined as:. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + where:. + + - ``CUlaunchConfig.gridDimX`` is the width of the grid in blocks. + - ``CUlaunchConfig.gridDimY`` is the height of the grid in blocks. + - ``CUlaunchConfig.gridDimZ`` is the depth of the grid in blocks. + - ``CUlaunchConfig.blockDimX`` is the X dimension of each thread block. + - ``CUlaunchConfig.blockDimX`` is the Y dimension of each thread block. + - ``CUlaunchConfig.blockDimZ`` is the Z dimension of each thread block. + - ``CUlaunchConfig.sharedMemBytes`` is the dynamic shared-memory size per + thread block in bytes. + - ``CUlaunchConfig.hStream`` is the handle to the stream to perform the launch + in. The CUDA context associated with this stream must match that associated + with function f. + - ``CUlaunchConfig.attrs`` is an array of ``CUlaunchConfig.numAttrs`` + continguous ``CUlaunchAttribute`` elements. The value of this pointer is not + considered if ``CUlaunchConfig.numAttrs`` is zero. However, in that case, it + is recommended to set the pointer to NULL. + - ``CUlaunchConfig.numAttrs`` is the number of attributes populating the first + ``CUlaunchConfig.numAttrs`` positions of the ``CUlaunchConfig.attrs`` array. + + Launch-time configuration is specified by adding entries to + ``CUlaunchConfig.attrs``. Each entry is an attribute ID and a corresponding + attribute value. + The ``CUlaunchAttribute`` structure is defined as:. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + where:. + + - ``CUlaunchAttribute.id`` is a unique enum identifying the attribute. + - ``CUlaunchAttribute.value`` is a union that hold the attribute value. + + An example of using the ``config`` parameter:. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + The ``CUlaunchAttributeID`` enum is defined as:. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + and the corresponding ``CUlaunchAttributeValue`` union as :. + \*\*View CUDA Toolkit Documentation for a C++ code example*\*. + Setting ``CU_LAUNCH_ATTRIBUTE_COOPERATIVE`` to a non-zero value causes the + kernel launch to be a cooperative launch, with exactly the same usage and + semantics of ``cuLaunchCooperativeKernel``. + Setting ``CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_STREAM_SERIALIZATION`` to a non-zero + values causes the kernel to use programmatic means to resolve its stream + dependency -- enabling the CUDA runtime to opportunistically allow the grid's + execution to overlap with the previous kernel in the stream, if that kernel + requests the overlap. + ``CU_LAUNCH_ATTRIBUTE_PROGRAMMATIC_EVENT`` records an event along with the + kernel launch. Event recorded through this launch attribute is guaranteed to + only trigger after all block in the associated kernel trigger the event. A + block can trigger the event through PTX launchdep.release or CUDA builtin + function cudaTriggerProgrammaticLaunchCompletion(). A trigger can also be + inserted at the beginning of each block's execution if triggerAtBlockStart is + set to non-0. Note that dependents (including the CPU thread calling + :func:`event_synchronize`) are not guaranteed to observe the release precisely + when it is released. For example, :func:`event_synchronize` may only observe + the event trigger long after the associated kernel has completed. This + recording type is primarily meant for establishing programmatic dependency + between device tasks. The event supplied must not be an interprocess or interop + event. The event must disable timing (i.e. created with + ``CU_EVENT_DISABLE_TIMING`` flag set). + ``CU_LAUNCH_ATTRIBUTE_LAUNCH_COMPLETION_EVENT`` records an event along with the + kernel launch. Nominally, the event is triggered once all blocks of the kernel + have begun execution. Currently this is a best effort. If a kernel B has a + launch completion dependency on a kernel A, B may wait until A is complete. + Alternatively, blocks of B may begin before all blocks of A have begun, for + example:. + + - If B can claim execution resources unavailable to A, for example if they run + on different GPUs. + - If B is a higher priority than A. + + Exercise caution if such an ordering inversion could lead to deadlock. The + event supplied must not be an interprocess or interop event. The event must + disable timing (i.e. must be created with the ``CU_EVENT_DISABLE_TIMING`` flag + set). + Setting ``CU_LAUNCH_ATTRIBUTE_DEVICE_UPDATABLE_KERNEL_NODE`` to 1 on a captured + launch causes the resulting kernel node to be device-updatable. This attribute + is specific to graphs, and passing it to a launch in a non-capturing stream + results in an error. Passing a value other than 0 or 1 is not allowed. + On success, a handle will be returned via + ``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``. + Kernel nodes which are device-updatable have additional restrictions compared + to regular kernel nodes. Firstly, device-updatable nodes cannot be removed from + their graph via ``cuGraphDestroyNode``. Additionally, once opted-in to this + functionality, a node cannot opt out, and any attempt to set the attribute to 0 + will result in an error. Graphs containing one or more device-updatable node + also do not allow multiple instantiation. + ``CU_LAUNCH_ATTRIBUTE_PREFERRED_CLUSTER_DIMENSION`` allows the kernel launch to + specify a preferred substitute cluster dimension. Blocks may be grouped + according to either the dimensions specified with this attribute (grouped into + a "preferred substitute cluster"), or the one specified with + ``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 The preferred substitute cluster dimension + must be an integer multiple greater than zero of the regular cluster dimension + and must divide the grid. It must also be no more than ``maxBlocksPerCluster``, + if it is set in the kernel's ``__launch_bounds__``. Otherwise it must be less + than the maximum value the driver can support. Otherwise, setting this + attribute to a value physically unable to fit on any particular device is + permitted. + The effect of other attributes is consistent with their effect when set via + persistent APIs. + See ``cuStreamSetAttribute`` for. + + - ``CU_LAUNCH_ATTRIBUTE_ACCESS_POLICY_WINDOW``. + - ``CU_LAUNCH_ATTRIBUTE_SYNCHRONIZATION_POLICY``. + + See ``cuFuncSetAttribute`` for. + + - ``CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION``. + - ``CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE``. + + Kernel parameters to ``f`` can be specified in the same ways that they can be + using ``cuLaunchKernel``. + Note that the API can also be used to 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 launch the kernel on + will either be taken from the specified stream ``CUlaunchConfig.hStream`` or + the current context in case of NULL stream. + + Args: + config (intptr_t): Config to launch. + f (intptr_t): Function ``CUfunction`` or Kernel ``CUkernel`` to + launch. + kernel_params (object): Array of pointers to kernel parameters. + extra (intptr_t): Extra options. + + .. seealso:: `cuLaunchKernelEx` + """ + cdef intptr_t _config_ptr_ = 0 if config is None else int(config) + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kernel_params__ptr = _kp_.ckernelParams + with nogil: + __status__ = cuLaunchKernelEx(_config_ptr_, f, (_kernel_params__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): + """Launches a CUDA function ``CUfunction`` or a CUDA kernel ``CUkernel`` where thread blocks can cooperate and synchronize as they execute. + + Invokes the function ``CUfunction`` or the kernel ``CUkernel`` ``f`` on a + ``grid_dim_x`` x ``grid_dim_y`` x ``grid_dim_z`` grid of blocks. Each block + contains ``block_dim_x`` x ``block_dim_y`` x ``block_dim_z`` threads. + ``shared_mem_bytes`` sets the amount of dynamic shared memory that will be + available to each thread block. + The device on which this kernel is invoked must have a non-zero value for the + device attribute ``CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH``. + The total number of blocks launched 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``. + The kernel cannot make use of CUDA dynamic parallelism. + Kernel parameters must be specified via ``kernel_params``. If ``f`` has N + parameters, then ``kernel_params`` needs to be an array of N pointers. Each of + ``kernel_params``\[0] through ``kernel_params``\[N-1] must point to a region of + memory from which the actual kernel parameter will be copied. The number of + kernel parameters and their offsets and sizes do not need to be specified as + that information is retrieved directly from the kernel's image. + Calling :func:`launch_cooperative_kernel` sets persistent function state that + is the same as function state set through ``cuLaunchKernel`` API. + When the kernel ``f`` is launched via :func:`launch_cooperative_kernel`, the + previous block shape, shared size and parameter info associated with ``f`` is + overwritten. + Note that to use :func:`launch_cooperative_kernel`, the kernel ``f`` must + either have been compiled with toolchain version 3.2 or later so that it will + contain kernel parameter information, or have no kernel parameters. If either + of these conditions is not met, then :func:`launch_cooperative_kernel` will + return ``CUDA_ERROR_INVALID_IMAGE``. + Note that the API can also be used to 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 launch the kernel on + will either be taken from the specified stream ``h_stream`` or the current + context in case of NULL stream. + + Args: + f (intptr_t): Function ``CUfunction`` or Kernel ``CUkernel`` to + launch. + 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 identifier. + kernel_params (object): Array of pointers to kernel parameters. + + .. seealso:: `cuLaunchCooperativeKernel` + """ + cdef object _kp_ = _HelperKernelParams(kernel_params) + cdef intptr_t _kernel_params__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, (_kernel_params__ptr)) + 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_ = 0 if launch_params_list is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddKernelNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_kernel_node_get_params_v2(intptr_t h_node): + """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. + + Returns: + CUDA_KERNEL_NODE_PARAMS_v2: Pointer to return the parameters. + + .. seealso:: `cuGraphKernelNodeGetParams_v2` + """ + cdef KernelNodeParams_v2 node_params_py = KernelNodeParams_v2() + cdef CUDA_KERNEL_NODE_PARAMS *node_params = (node_params_py._get_ptr()) + with nogil: + __status__ = cuGraphKernelNodeGetParams(h_node, node_params) + check_status(__status__) + return node_params_py + + +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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _copy_params_ptr_ = 0 if copy_params is None else int(copy_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemcpyNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _copy_params_ptr_, ctx) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_memcpy_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_MEMCPY3D_v2: Pointer to return the parameters. + + .. seealso:: `cuGraphMemcpyNodeGetParams` + """ + cdef MemCpy3d_v2 node_params_py = MemCpy3d_v2() + cdef CUDA_MEMCPY3D *node_params = (node_params_py._get_ptr()) + with nogil: + __status__ = cuGraphMemcpyNodeGetParams(h_node, node_params) + check_status(__status__) + return node_params_py + + +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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _memset_params_ptr_ = 0 if memset_params is None else int(memset_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemsetNode(&ph_graph_node, h_graph, (_dependencies_.data()), 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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddHostNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_host_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_HOST_NODE_PARAMS_v1: Pointer to return the parameters. + + .. seealso:: `cuGraphHostNodeGetParams` + """ + cdef HostNodeParams_v1 node_params_py = HostNodeParams_v1() + cdef CUDA_HOST_NODE_PARAMS *node_params = (node_params_py._get_ptr()) + with nogil: + __status__ = cuGraphHostNodeGetParams(h_node, node_params) + check_status(__status__) + return node_params_py + + +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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddChildGraphNode(&ph_graph_node, h_graph, (_dependencies_.data()), 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + num_dependencies (size_t): Number of dependencies. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEmptyNode` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEmptyNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies) + check_status(__status__) + return ph_graph_node + + +cpdef intptr_t graph_add_event_record_node(intptr_t h_graph, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + num_dependencies (size_t): Number of dependencies. + event (intptr_t): Event for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEventRecordNode` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEventRecordNode(&ph_graph_node, h_graph, (_dependencies_.data()), 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. + + .. note:: + This function will reset the node's context to the event's device context. + .. seealso:: `cuGraphEventRecordNodeSetEvent` + """ + with nogil: + __status__ = cuGraphEventRecordNodeSetEvent(h_node, event) + check_status(__status__) + + +cpdef intptr_t graph_add_event_wait_node(intptr_t h_graph, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + num_dependencies (size_t): Number of dependencies. + event (intptr_t): Event for the node. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddEventWaitNode` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddEventWaitNode(&ph_graph_node, h_graph, (_dependencies_.data()), 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddExternalSemaphoresSignalNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_external_semaphores_signal_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1: Pointer to return the + parameters. + + .. seealso:: `cuGraphExternalSemaphoresSignalNodeGetParams` + """ + cdef ExtSemSignalNodeParams_v1 params_out_py = ExtSemSignalNodeParams_v1() + cdef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS *params_out = (params_out_py._get_ptr()) + with nogil: + __status__ = cuGraphExternalSemaphoresSignalNodeGetParams(h_node, params_out) + check_status(__status__) + return params_out_py + + +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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddExternalSemaphoresWaitNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_external_semaphores_wait_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1: Pointer to return the + parameters. + + .. seealso:: `cuGraphExternalSemaphoresWaitNodeGetParams` + """ + cdef ExtSemWaitNodeParams_v1 params_out_py = ExtSemWaitNodeParams_v1() + cdef CUDA_EXT_SEM_WAIT_NODE_PARAMS *params_out = (params_out_py._get_ptr()) + with nogil: + __status__ = cuGraphExternalSemaphoresWaitNodeGetParams(h_node, params_out) + check_status(__status__) + return params_out_py + + +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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddBatchMemOpNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_batch_mem_op_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_BATCH_MEM_OP_NODE_PARAMS_v1: Pointer to return the + parameters. + + .. seealso:: `cuGraphBatchMemOpNodeGetParams` + """ + cdef BatchMemOpNodeParams_v1 node_params_out_py = BatchMemOpNodeParams_v1() + cdef CUDA_BATCH_MEM_OP_NODE_PARAMS *node_params_out = (node_params_out_py._get_ptr()) + with nogil: + __status__ = cuGraphBatchMemOpNodeGetParams(h_node, node_params_out) + check_status(__status__) + return node_params_out_py + + +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_ = 0 if node_params is None else 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_ = 0 if node_params is None else 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemAllocNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef object graph_mem_alloc_node_get_params(intptr_t h_node): + """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. + + Returns: + CUDA_MEM_ALLOC_NODE_PARAMS_v1: Pointer to return the parameters. + + .. seealso:: `cuGraphMemAllocNodeGetParams` + """ + cdef MemAllocNodeParams_v1 params_out_py = MemAllocNodeParams_v1() + cdef CUDA_MEM_ALLOC_NODE_PARAMS *params_out = (params_out_py._get_ptr()) + with nogil: + __status__ = cuGraphMemAllocNodeGetParams(h_node, params_out) + check_status(__status__) + return params_out_py + + +cpdef intptr_t graph_add_mem_free_node(intptr_t h_graph, dependencies, size_t num_dependencies, uint64_t 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + num_dependencies (size_t): Number of dependencies. + dptr (uint64_t): Address of memory to free. + + Returns: + intptr_t: Returns newly created node. + + .. seealso:: `cuGraphAddMemFreeNode` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddMemFreeNode(&ph_graph_node, h_graph, (_dependencies_.data()), num_dependencies, dptr) + check_status(__status__) + return ph_graph_node + + +cpdef uint64_t 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: + uint64_t: 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_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 _cyb_view.array _nodes_alloc_ = _cyb_view.array(shape=(max(num_nodes[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *nodes_ptr = (_nodes_alloc_.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[:num_nodes[0]] + + +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 _cyb_view.array _root_nodes_alloc_ = _cyb_view.array(shape=(max(num_root_nodes[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *root_nodes_ptr = (_root_nodes_alloc_.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[:num_root_nodes[0]] + + +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 _cyb_view.array _from__alloc_ = _cyb_view.array(shape=(max(num_edges[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *from__ptr = (_from__alloc_.data) + cdef object from_ = _from__alloc_[:num_edges[0]] + cdef _cyb_view.array _to_alloc_ = _cyb_view.array(shape=(max(num_edges[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *to_ptr = (_to_alloc_.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_[:num_edges[0]], to[:num_edges[0]], edge_data[:num_edges[0]]) + + +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 _cyb_view.array _dependencies_alloc_ = _cyb_view.array(shape=(max(num_dependencies[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *dependencies_ptr = (_dependencies_alloc_.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[:num_dependencies[0]], edge_data[:num_dependencies[0]]) + + +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 _cyb_view.array _dependent_nodes_alloc_ = _cyb_view.array(shape=(max(num_dependent_nodes[0], 1),), itemsize=sizeof(intptr_t), format="q", mode="c") + cdef intptr_t *dependent_nodes_ptr = (_dependent_nodes_alloc_.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[:num_dependent_nodes[0]], edge_data[:num_dependent_nodes[0]]) + + +cpdef graph_add_dependencies_v2(intptr_t h_graph, from_, 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_ (object): Array of nodes that provide the dependencies. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + to (object): Array of dependent nodes. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _from__ + _cyb_get_resource_ptrs[void](_from__, from_, NULL) + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _to_ + _cyb_get_resource_ptrs[void](_to_, to, NULL) + cdef intptr_t _edge_data_ptr_ = 0 if edge_data is None else int(edge_data) + with nogil: + __status__ = cuGraphAddDependencies(h_graph, (_from__.data()), (_to_.data()), _edge_data_ptr_, num_dependencies) + check_status(__status__) + + +cpdef graph_remove_dependencies_v2(intptr_t h_graph, from_, 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_ (object): Array of nodes that provide the dependencies. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + to (object): Array of dependent nodes. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _from__ + _cyb_get_resource_ptrs[void](_from__, from_, NULL) + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _to_ + _cyb_get_resource_ptrs[void](_to_, to, NULL) + cdef intptr_t _edge_data_ptr_ = 0 if edge_data is None else int(edge_data) + with nogil: + __status__ = cuGraphRemoveDependencies(h_graph, (_from__.data()), (_to_.data()), _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_ = 0 if instantiate_params is None else 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_ = 0 if node_params is None else 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_ = 0 if copy_params is None else 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_ = 0 if memset_params is None else 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_ = 0 if node_params is None else 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_ = 0 if node_params is None else 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_ = 0 if node_params is None else 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 object graph_exec_update_v2(intptr_t h_graph_exec, intptr_t h_graph): + """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. + + Returns: + CUgraphExecUpdateResultInfo_v1: the error info structure. + + .. seealso:: `cuGraphExecUpdate_v2` + """ + cdef GraphExecUpdateResultInfo_v1 result_info_py = GraphExecUpdateResultInfo_v1() + cdef CUgraphExecUpdateResultInfo *result_info = (result_info_py._get_ptr()) + with nogil: + __status__ = cuGraphExecUpdate(h_graph_exec, h_graph, result_info) + check_status(__status__) + return result_info_py + + +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 object graph_kernel_node_get_attribute(intptr_t h_node, int attr): + """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): . + + Returns: + CUlaunchAttributeValue: . + + .. seealso:: `cuGraphKernelNodeGetAttribute` + """ + cdef LaunchAttributeValue value_out_py = LaunchAttributeValue() + cdef CUkernelNodeAttrValue *value_out = (value_out_py._get_ptr()) + with nogil: + __status__ = cuGraphKernelNodeGetAttribute(h_node, attr, value_out) + check_status(__status__) + return value_out_py + + +cpdef graph_kernel_node_set_attribute(intptr_t h_node, int attr, 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` + """ + cdef intptr_t _value_ptr_ = 0 if value is None else int(value) + with nogil: + __status__ = cuGraphKernelNodeSetAttribute(h_node, attr, _value_ptr_) + 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, 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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 _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _dependency_data_ptr_ = 0 if dependency_data is None else int(dependency_data) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddNode(&ph_graph_node, h_graph, (_dependencies_.data()), _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_ = 0 if node_params is None else 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_ = 0 if node_params is None else 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_ = 0 if config is None else 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_ = 0 if config is None else 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, uint64_t 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 (uint64_t): 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, uint64_t 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 (uint64_t): Device pointer to bind. + pitch (size_t): Line pitch in bytes. + + .. seealso:: `cuTexRefSetAddress2D_v3` + """ + cdef intptr_t _desc_ptr_ = 0 if desc is None else 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 uint64_t 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: + uint64_t: 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 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 uint64_t tex_object_create(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: + uint64_t: Texture object to create. + + .. seealso:: `cuTexObjectCreate` + """ + cdef intptr_t _p_res_desc_ptr_ = 0 if p_res_desc is None else int(p_res_desc) + cdef intptr_t _p_tex_desc_ptr_ = 0 if p_tex_desc is None else int(p_tex_desc) + cdef intptr_t _p_res_view_desc_ptr_ = 0 if p_res_view_desc is None else int(p_res_view_desc) + cdef CUtexObject p_tex_object + with nogil: + __status__ = cuTexObjectCreate(&p_tex_object, _p_res_desc_ptr_, _p_tex_desc_ptr_, _p_res_view_desc_ptr_) + check_status(__status__) + return p_tex_object + + +cpdef tex_object_destroy(uint64_t tex_object): + """Destroys a texture object. + + Destroys the texture object specified by ``tex_object``. + + Args: + tex_object (uint64_t): Texture object to destroy. + + .. seealso:: `cuTexObjectDestroy` + """ + with nogil: + __status__ = cuTexObjectDestroy(tex_object) + check_status(__status__) + + +cpdef object tex_object_get_resource_desc(uint64_t tex_object): + """Returns a texture object's resource descriptor. + + Returns the resource descriptor for the texture object specified by + ``tex_object``. + + Args: + tex_object (uint64_t): Texture object. + + Returns: + CUDA_RESOURCE_DESC_v1: Resource descriptor. + + .. seealso:: `cuTexObjectGetResourceDesc` + """ + cdef ResourceDesc_v1 p_res_desc_py = ResourceDesc_v1() + cdef CUDA_RESOURCE_DESC *p_res_desc = (p_res_desc_py._get_ptr()) + with nogil: + __status__ = cuTexObjectGetResourceDesc(p_res_desc, tex_object) + check_status(__status__) + return p_res_desc_py + + +cpdef object tex_object_get_texture_desc(uint64_t tex_object): + """Returns a texture object's texture descriptor. + + Returns the texture descriptor for the texture object specified by + ``tex_object``. + + Args: + tex_object (uint64_t): Texture object. + + Returns: + CUDA_TEXTURE_DESC_v1: Texture descriptor. + + .. seealso:: `cuTexObjectGetTextureDesc` + """ + cdef TextureDesc_v1 p_tex_desc_py = TextureDesc_v1() + cdef CUDA_TEXTURE_DESC *p_tex_desc = (p_tex_desc_py._get_ptr()) + with nogil: + __status__ = cuTexObjectGetTextureDesc(p_tex_desc, tex_object) + check_status(__status__) + return p_tex_desc_py + + +cpdef object tex_object_get_resource_view_desc(uint64_t 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 (uint64_t): 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 uint64_t surf_object_create(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: + uint64_t: Surface object to create. + + .. seealso:: `cuSurfObjectCreate` + """ + cdef intptr_t _p_res_desc_ptr_ = 0 if p_res_desc is None else int(p_res_desc) + cdef CUsurfObject p_surf_object + with nogil: + __status__ = cuSurfObjectCreate(&p_surf_object, _p_res_desc_ptr_) + check_status(__status__) + return p_surf_object + + +cpdef surf_object_destroy(uint64_t surf_object): + """Destroys a surface object. + + Destroys the surface object specified by ``surf_object``. + + Args: + surf_object (uint64_t): Surface object to destroy. + + .. seealso:: `cuSurfObjectDestroy` + """ + with nogil: + __status__ = cuSurfObjectDestroy(surf_object) + check_status(__status__) + + +cpdef object surf_object_get_resource_desc(uint64_t surf_object): + """Returns a surface object's resource descriptor. + + Returns the resource descriptor for the surface object specified by + ``surf_object``. + + Args: + surf_object (uint64_t): Surface object. + + Returns: + CUDA_RESOURCE_DESC_v1: Resource descriptor. + + .. seealso:: `cuSurfObjectGetResourceDesc` + """ + cdef ResourceDesc_v1 p_res_desc_py = ResourceDesc_v1() + cdef CUDA_RESOURCE_DESC *p_res_desc = (p_res_desc_py._get_ptr()) + with nogil: + __status__ = cuSurfObjectGetResourceDesc(p_res_desc, surf_object) + check_status(__status__) + return p_res_desc_py + + +cpdef object tensor_map_encode_tiled(int tensor_data_type, uint32_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_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint32_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. + + Returns: + CUtensorMap: Tensor map object to create. + + .. seealso:: `cuTensorMapEncodeTiled` + """ + cdef TensorMap tensor_map_py = TensorMap() + cdef CUtensorMap *tensor_map = (tensor_map_py._get_ptr()) + with nogil: + __status__ = cuTensorMapEncodeTiled(tensor_map, tensor_data_type, tensor_rank, global_address, global_dim, global_strides, box_dim, element_strides, interleave, swizzle, l2promotion, oob_fill) + check_status(__status__) + return tensor_map_py + + +cpdef object tensor_map_encode_im2col(int tensor_data_type, uint32_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, uint32_t channels_per_pixel, uint32_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_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint32_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 (uint32_t): Number of channels per pixel. + pixels_per_column (uint32_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. + + Returns: + CUtensorMap: Tensor map object to create. + + .. seealso:: `cuTensorMapEncodeIm2col` + """ + cdef TensorMap tensor_map_py = TensorMap() + cdef CUtensorMap *tensor_map = (tensor_map_py._get_ptr()) + with nogil: + __status__ = cuTensorMapEncodeIm2col(tensor_map, 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__) + return tensor_map_py + + +cpdef object tensor_map_encode_im2col_wide(int tensor_data_type, uint32_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, uint32_t channels_per_pixel, uint32_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_data_type (TensorMapDataType): Tensor data type. + tensor_rank (uint32_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 (uint32_t): Number of channels per pixel. + pixels_per_column (uint32_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. + + Returns: + CUtensorMap: Tensor map object to create. + + .. seealso:: `cuTensorMapEncodeIm2colWide` + """ + cdef TensorMap tensor_map_py = TensorMap() + cdef CUtensorMap *tensor_map = (tensor_map_py._get_ptr()) + with nogil: + __status__ = cuTensorMapEncodeIm2colWide(tensor_map, 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__) + return tensor_map_py + + +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_ = 0 if tensor_map is None else 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 ``p_dev_ptr`` + 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: + - uint64_t: Returned pointer through which ``resource`` may be + accessed. + - size_t: Returned size of the buffer accessible starting at + ``*p_dev_ptr``. + + .. 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, 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 (object): Resources to map for CUDA usage. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + h_stream (intptr_t): Stream with which to synchronize. + + .. seealso:: `cuGraphicsMapResources` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _resources_ + _cyb_get_resource_ptrs[void](_resources_, resources, NULL) + with nogil: + __status__ = cuGraphicsMapResources(count, (_resources_.data()), h_stream) + check_status(__status__) + + +cpdef graphics_unmap_resources(unsigned int count, 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 (object): Resources to unmap. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + h_stream (intptr_t): Stream with which to synchronize. + + .. seealso:: `cuGraphicsUnmapResources` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _resources_ + _cyb_get_resource_ptrs[void](_resources_, resources, NULL) + with nogil: + __status__ = cuGraphicsUnmapResources(count, (_resources_.data()), h_stream) + check_status(__status__) + + +cpdef tuple get_proc_address_v2(symbol, int cuda_version, uint64_t flags): + """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. + cuda_version (int): The CUDA version to look for the requested + driver symbol. + flags (uint64_t): Flags to specify search options. + + Returns: + A 2-tuple containing: + - intptr_t: Location to return the function pointer to the requested + driver function. + - int: 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) + cdef void* pfn + cdef CUdriverProcAddressQueryResult symbol_status + with nogil: + __status__ = cuGetProcAddress(_symbol_, &pfn, cuda_version, flags, &symbol_status) + check_status(__status__) + return (pfn, symbol_status) + + +cpdef intptr_t get_export_table(p_export_table_id) except? 0: + cdef intptr_t _p_export_table_id_ptr_ = 0 if p_export_table_id is None else 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 object device_get_dev_resource(int device, 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. + type (DevResourceType): Type of resource to retrieve. + + Returns: + CUdevResource_v1: Output pointer to a ``CUdevResource`` structure. + + .. seealso:: `cuDeviceGetDevResource` + """ + cdef DevResource_v1 resource_py = DevResource_v1() + cdef CUdevResource *resource = (resource_py._get_ptr()) + with nogil: + __status__ = cuDeviceGetDevResource(device, resource, type) + check_status(__status__) + return resource_py + + +cpdef object ctx_get_dev_resource(intptr_t h_ctx, 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. + type (DevResourceType): Type of resource to retrieve. + + Returns: + CUdevResource_v1: Output pointer to a ``CUdevResource`` structure. + + .. seealso:: `cuCtxGetDevResource` + """ + cdef DevResource_v1 resource_py = DevResource_v1() + cdef CUdevResource *resource = (resource_py._get_ptr()) + with nogil: + __status__ = cuCtxGetDevResource(h_ctx, resource, type) + check_status(__status__) + return resource_py + + +cpdef object green_ctx_get_dev_resource(intptr_t h_ctx, 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. + type (DevResourceType): Type of resource to retrieve. + + Returns: + CUdevResource_v1: Output pointer to a ``CUdevResource`` structure. + + .. seealso:: `cuGreenCtxGetDevResource` + """ + cdef DevResource_v1 resource_py = DevResource_v1() + cdef CUdevResource *resource = (resource_py._get_ptr()) + with nogil: + __status__ = cuGreenCtxGetDevResource(h_ctx, resource, type) + check_status(__status__) + return resource_py + + +cpdef tuple dev_sm_resource_split_by_count(input, 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: + input (intptr_t): Input SM resource to be split. Must be a valid + ``CU_DEV_RESOURCE_TYPE_SM`` resource. + 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. + + Returns: + A 2-tuple containing: + - CUdevResource_v1: Output array of ``CUdevResource`` resources. Can + be NULL to query the number of groups. + - CUdevResource_v1: 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. + + .. seealso:: `cuDevSmResourceSplitByCount` + """ + cdef intptr_t _input_ptr_ = 0 if input is None else int(input) + cdef unsigned int[1] nb_groups = [0] + cdef DevResource_v1 remainder_py = DevResource_v1() + cdef CUdevResource *remainder = (remainder_py._get_ptr()) + with nogil: + __status__ = cuDevSmResourceSplitByCount(NULL, nb_groups, _input_ptr_, remainder, flags, min_count) + check_status_size(__status__) + cdef DevResource_v1 result = DevResource_v1(nb_groups[0]) + cdef CUdevResource_v1 *result_ptr = (result._get_ptr()) + if not (nb_groups[0] == 0): + with nogil: + __status__ = cuDevSmResourceSplitByCount(result_ptr, nb_groups, _input_ptr_, remainder, flags, min_count) + check_status(__status__) + return (result[:nb_groups[0]], remainder_py) + + +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 and localityDomainId values, otherwise + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. + + The output descriptor ``ph_desc`` will remain valid for the lifetime of the + process. + 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_ = 0 if resources is None else 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_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_ = 0 if args is None else 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``. The GPU memory contents will + be brought into host memory or mapped onto the calling process's GPUs for user- + defined behavior. Underlying GPU references are released when checkpointing + completes. The process must be in the ``CU_PROCESS_STATE_LOCKED`` state to + checkpoint. + When ``CUcheckpointCheckpointArgs.customStorageInfo_out`` is not NULL, all the + GPU memory allocated by the process with ``pid`` will be mapped onto the + calling process's GPUs so the application can copy the memory to custom + storage. Upon return of this call, the pointer referenced by + ``CUcheckpointCheckpointArgs.customStorageInfo_out`` will point to a + ``CUcheckpointCustomStorageInfo`` struct allocated and populated by the driver. + For each GPU which contains data from the checkpointed process, there is a + corresponding entry in the ``CUcheckpointCustomStoragePerDeviceData`` array. + + - The device pointers and sizes for the contiguously mapped memory on a + particular GPU are set in the + ``CUcheckpointCustomStoragePerDeviceData.devPtr`` and + ``CUcheckpointCustomStoragePerDeviceData.size`` fields respectively. + - A stream belonging to the primary context of a particular GPU is set in + ``CUcheckpointCustomStoragePerDeviceData.stream``. The application can use + the stream to find out which GPU the memory is mapped on and to enqueue the + copies to custom storage. + + The application is responsible for copying the mapped data from the GPU at the + specified device address to custom storage. When checkpointing to custom + storage, the application is expected to call ``cuCheckpointOperationComplete``. + The ``CUcheckpointCustomStorageInfo.handle`` set by this call should be passed + to ``cuCheckpointOperationComplete`` in ``handle``. The driver synchronizes all + the streams in ``cuCheckpointOperationComplete``, at which point the copy to + custom storage is considered complete. + When checkpointing to custom storage, the application is expected to retain + primary contexts of all the devices used by the process to be checkpointed. + Otherwise ``cuCheckpointProcessCheckpoint`` will return + ``CUDA_ERROR_INVALID_CONTEXT``. Unlike other checkpoint operations, + checkpointing to custom storage requires ``cuInit`` to have been called before + execution. Checkpointing the calling process's GPU memory to custom storage is + not supported. Upon successful return, the target process will be in the + ``CU_PROCESS_STATE_CHECKPOINTING`` state. + When ``CUcheckpointCheckpointArgs.customStorageInfo_out`` is NULL, the GPU + memory contents will be brought into host memory by + ``cuCheckpointProcessCheckpoint``. The application is not expected to copy the + GPU memory contents. The application is also not expected to call + ``cuCheckpointOperationComplete``. Upon successful return, the target process + will be in the ``CU_PROCESS_STATE_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_ = 0 if args is None else int(args) + with nogil: + __status__ = cuCheckpointProcessCheckpoint(pid, _args_ptr_) + check_status(__status__) + + +cpdef checkpoint_process_restore(int pid, 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 ``CU_PROCESS_STATE_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. + CUDA process restore requires persistence mode to be enabled or ``cuInit`` to + have been called before execution. + When ``CUcheckpointRestoreArgs.customStorageInfo_out`` is not NULL, all the GPU + memory to be restored for the process with ``pid`` will be mapped onto the + calling process's GPUs so the application can copy the memory back to the GPU. + Upon return of this call, the pointer referenced by + ``CUcheckpointRestoreArgs.customStorageInfo_out`` will point to a + ``CUcheckpointCustomStorageInfo`` struct allocated and populated by the driver. + For each GPU which contains data from the restored process, there is a + corresponding entry in the ``CUcheckpointCustomStoragePerDeviceData`` array. + + - The device pointers and sizes for the contiguously mapped memory on a + particular GPU are set in the + ``CUcheckpointCustomStoragePerDeviceData.devPtr`` and + ``CUcheckpointCustomStoragePerDeviceData.size`` fields respectively. + - A stream belonging to the primary context of the GPU is set in + ``CUcheckpointCustomStoragePerDeviceData.stream``. The application can use + the stream to find out which GPU the memory is mapped on and to enqueue the + copies from custom storage back to the GPU. + + The application is responsible for copying the data from custom storage to the + GPU at the specified device address. When restoring from custom storage, the + application is expected to call ``cuCheckpointOperationComplete``. The + ``CUcheckpointCustomStorageInfo.handle`` set by this call should be passed to + ``cuCheckpointOperationComplete`` in ``handle``. The driver synchronizes all + the streams in ``cuCheckpointOperationComplete``, at which point the copy from + custom storage is considered complete. + When restoring from custom storage, the application is expected to retain + primary contexts of all the devices used by the process to be restored. + Otherwise ``cuCheckpointProcessRestore`` will return + ``CUDA_ERROR_INVALID_CONTEXT``. Restoring the calling process's GPU memory + from custom storage is not supported. Upon successful return, the target + process will be in the ``CU_PROCESS_STATE_RESTORING`` state. + When ``CUcheckpointRestoreArgs.customStorageInfo_out`` is NULL, the GPU memory + contents will be restored from host memory by ``cuCheckpointProcessRestore``. + The application is not expected to copy back the GPU memory contents. The + application is also not expected to call ``cuCheckpointOperationComplete``. + Upon successful return, the target process will be in the + ``CU_PROCESS_STATE_LOCKED`` state. + + Args: + pid (int): The process ID of the CUDA process. + args (intptr_t): Optional restore operation arguments. + + .. seealso:: `cuCheckpointProcessRestore` + """ + cdef intptr_t _args_ptr_ = 0 if args is None else int(args) + with nogil: + __status__ = cuCheckpointProcessRestore(pid, _args_ptr_) + 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_ = 0 if args is None else int(args) + with nogil: + __status__ = cuCheckpointProcessUnlock(pid, _args_ptr_) + check_status(__status__) + + +cpdef intptr_t graphics_egl_register_image(intptr_t image, unsigned int flags) except? 0: + """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: + image (intptr_t): An ``EGLImageKHR`` image which can be used to + create target resource. + flags (unsigned int): Map flags. + + Returns: + intptr_t: Pointer to the returned object handle. + + .. seealso:: `cuGraphicsEGLRegisterImage` + """ + cdef CUgraphicsResource p_cuda_resource + with nogil: + __status__ = cuGraphicsEGLRegisterImage(&p_cuda_resource, image, flags) + check_status(__status__) + return p_cuda_resource + + +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_ = 0 if attrs is None else 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, 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` + """ + cdef intptr_t _op_list_ptr_ = 0 if op_list is None else int(op_list) + with nogil: + __status__ = cuMemcpy3DBatchAsync(num_ops, _op_list_ptr_, 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``, ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, or + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN``. 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_LOCALITY_DOMAIN``. + + 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_ = 0 if location is None else 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``, + ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, or + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN``. 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_LOCALITY_DOMAIN``. 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_ = 0 if location is None else 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 ``CU_MEM_LOCATION_TYPE_HOST_NUMA``, + ``CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN``. 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``. + 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_ = 0 if location is None else 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_ = 0 if prefetch_locs is None else 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_ = 0 if prefetch_locs is None else 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(uint64_t mc_handle, int dev, size_t mc_offset, uint64_t 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. + On systems with Rubin+ (SM_107+) GPUs, ``mem_offset`` may be aligned to 256 + instead of the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. In such a case the ``size`` + + ``mem_offset`` cannot be larger than the size of the allocated memory. + Similarly the ``size`` + ``mc_offset`` + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` cannot be larger than the size of the than + the size of the multicast object. The next available mc_offset for the next + bind will be mc_offset + size + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. + Also note that the ability to accept a ``mem_offset`` that is not aligned to + the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED`` is limited by HW resources and may + result in error ``CUDA_ERROR_MULTICAST_RESOURCE_FULL``. + 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 fail if the devices added via ``cuMulticastAddDevice`` do not + belong to the same clique. + 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 (uint64_t): 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 (uint64_t): 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(uint64_t mc_handle, int dev, size_t mc_offset, uint64_t 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. + On systems with Rubin+ (SM_107+) GPUs, ``memptr`` may be aligned to 256 instead + of the value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED``. In such a case the ``size`` + + ``memptr`` cannot be larger than the size of the allocated memory. Similarly + the ``size`` + ``mc_offset`` + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` cannot be larger than the size of the than + the size of the multicast object. The next available mc_offset for the next + bind will be mc_offset + size + the value returned by + ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM``. + Also note that the ability to accept a ``memptr`` that is not aligned to the + value returned by ``cuMulticastGetGranularity`` with the flag + ``CU_MULTICAST_GRANULARITY_MINIMUM`` or + ``CU_MULTICAST_GRANULARITY_RECOMMENDED`` is limited by HW resources and may + result in error ``CUDA_ERROR_MULTICAST_RESOURCE_FULL``. + 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 fail if the devices added via ``cuMulticastAddDevice`` do not + belong to the same clique. + 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 (uint64_t): 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 (uint64_t): 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 tuple dev_sm_resource_split(unsigned int nb_groups, input, 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`` if + it is nonzero. When assigning SMs to a group (and if results are expected + by having the ``result`` parameter set), ``smCount`` cannot end up with 0 + or a value less than ``coscheduledSmCount`` otherwise + 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. A ``coscheduledSmCount`` of 0 uses the + default value internally while preserving 0 in ``group_params``. Cluster + occupancy will be derived from the resulting SM topology. + - ``preferredCoscheduledSmCount:`` Attempts to merge ``coscheduledSmCount`` + groups into larger groups, in order to make use of + ``preferredClusterDimensions`` on Compute Architecture 10.0+. The default + value is set to ``coscheduledSmCount``. + - ``flags:``. + - ``CU_DEV_SM_RESOURCE_GROUP_BACKFILL:`` Treats constraints as a hint, + ignoring them if necessary to reach the requested ``smCount``. Lets + ``smCount`` be a non-multiple of ``coscheduledSmCount``, filling the + difference between SM count and already assigned co-scheduled groupings + with other SMs. This lets any resulting group behave similar to the + ``remainder`` group for example. When used with + ``CU_DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID``, backfill fills up to the + requested ``smCount`` using the target locality domain first, then SMs + not attributed to any locality domain, then SMs from other locality + domains. If no SMs can be found in the requested locality domain, + CUDA_ERROR_INVALID_RESOURCE_CONFIGURATION is returned. + - ``CU_DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID:`` Specifies that the SM + partition should be localized to the specified ``localityDomainId``. + - ``localityDomainId:`` Specifies the locality domain that the partitioned + SMs must be located on. Only valid when + CU_DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID is set in flags. + + 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: + 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. + 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. + + Returns: + A 2-tuple containing: + - CUdevResource_v1: Output array of ``CUdevResource`` resources. Can + be NULL, alongside an smCount of 0, for discovery purpose. + - CUdevResource_v1: If splitting the input resource leaves any SMs, + the remainder is placed in here. + + .. seealso:: `cuDevSmResourceSplit` + """ + cdef intptr_t _input_ptr_ = 0 if input is None else int(input) + cdef intptr_t _group_params_ptr_ = 0 if group_params is None else int(group_params) + cdef DevResource_v1 result = DevResource_v1(nb_groups) + cdef CUdevResource_v1 *result_ptr = (result._get_ptr()) + cdef DevResource_v1 remainder_py = DevResource_v1() + cdef CUdevResource *remainder = (remainder_py._get_ptr()) + with nogil: + __status__ = cuDevSmResourceSplit(result_ptr, nb_groups, _input_ptr_, remainder, flags, _group_params_ptr_) + check_status(__status__) + return (result, remainder_py) + + +cpdef object stream_get_dev_resource(intptr_t h_stream, 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. + type (DevResourceType): Type of resource to retrieve. + + Returns: + CUdevResource_v1: Output pointer to a ``CUdevResource`` structure. + + .. seealso:: `cuStreamGetDevResource` + """ + cdef DevResource_v1 resource_py = DevResource_v1() + cdef CUdevResource *resource = (resource_py._get_ptr()) + with nogil: + __status__ = cuStreamGetDevResource(h_stream, resource, type) + check_status(__status__) + return resource_py + + +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(uint64_t dst, uint64_t 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 (uint64_t): Destination device pointer. + src (uint64_t): 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_ = 0 if attr is None else int(attr) + with nogil: + __status__ = cuMemcpyWithAttributesAsync(dst, src, size, _attr_ptr_, h_stream) + check_status(__status__) + + +cpdef memcpy_3d_with_attributes_async(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` + """ + cdef intptr_t _op_ptr_ = 0 if op is None else int(op) + with nogil: + __status__ = cuMemcpy3DWithAttributesAsync(_op_ptr_, flags, h_stream) + check_status(__status__) + + +cpdef stream_begin_capture_to_cig(intptr_t h_stream, 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` + """ + cdef intptr_t _stream_cig_capture_params_ptr_ = 0 if stream_cig_capture_params is None else int(stream_cig_capture_params) + with nogil: + __status__ = cuStreamBeginCaptureToCig(h_stream, _stream_cig_capture_params_ptr_) + 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 object graph_node_get_params(intptr_t h_node): + """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. + + Returns: + CUgraphNodeParams: Pointer to return the parameters. + + .. seealso:: `cuGraphNodeGetParams` + """ + cdef GraphNodeParams node_params_py = GraphNodeParams() + cdef CUgraphNodeParams *node_params = (node_params_py._get_ptr()) + with nogil: + __status__ = cuGraphNodeGetParams(h_node, node_params) + check_status(__status__) + return node_params_py + + +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(uint32_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 (uint32_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, uint32_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 (uint32_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, 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` + """ + cdef intptr_t _prop_ptr_ = 0 if prop is None else int(prop) + with nogil: + __status__ = cuLogicalEndpointCreate(le_id, _prop_ptr_) + 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``. + This call may fail with ``CUDA_ERROR_INVALID_DEVICE`` if the device specified + by ``dev`` does not belong to the same clique as the other devices previously + added to this multicast logical endpoint. + + 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, uint64_t 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 (uint64_t): 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_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(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 intptr_t _prop_ptr_ = 0 if prop is None else int(prop) + cdef cuuint64_t bind_alignment + cdef cuuint64_t max_size + with nogil: + __status__ = cuLogicalEndpointGetLimits(&bind_alignment, &max_size, _prop_ptr_) + check_status(__status__) + return (bind_alignment, max_size) + + +cpdef int logical_endpoint_query(uint32_t le_id, uint32_t count) except? -1: + """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. + Construction of a multicast logical endpoint may fail here if the devices added + via ``cuLogicalEndpointAddDevice`` do not belong to the same clique. + This API may return ``CUDA_ERROR_ILLEGAL_STATE`` if no devices are found on + which this logical endpoint can be accessed. + + Args: + le_id (uint32_t): First logical endpoint ID to be queried. + count (uint32_t): Number of logical endpoints IDs to be queried. + + Returns: + int: 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` + """ + cdef int query_status + with nogil: + __status__ = cuLogicalEndpointQuery(le_id, count, &query_status) + check_status(__status__) + return 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): + """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__) + + +cpdef object device_get_fabric_cluster_uuid(int dev): + """Retrieves the fabric cluster UUID. + + Retrieves the fabric cluster UUID for the given device. + + Args: + dev (int): Device for which the fabric cluster UUID is requested. + + Returns: + CUuuid: Fabric cluster UUID. + + .. seealso:: `cuDeviceGetFabricClusterUuid` + """ + cdef Uuid uuid_py = Uuid() + cdef CUuuid *uuid = (uuid_py._get_ptr()) + with nogil: + __status__ = cuDeviceGetFabricClusterUuid(uuid, dev) + check_status(__status__) + return uuid_py + + +cpdef size_t device_get_clique_count(int dev) except? 0: + """Retrieves the number of fabric cliques. + + Retrieves the number of fabric cliques that the device is part of. + + Args: + dev (int): Device for which the number of fabric cliques is + requested. + + Returns: + size_t: Number of fabric cliques that the device is part of. + + .. seealso:: `cuDeviceGetCliqueCount` + """ + cdef size_t count + with nogil: + __status__ = cuDeviceGetCliqueCount(&count, dev) + check_status(__status__) + return count + + +cpdef object device_get_clique_info(int dev): + """Retrieves fabric clique information. + + Returns the fabric clique information for the cliques that the device is a part + of. User must specify the size of the ``clique_info`` array in ``count``. The + same parameter ``count`` will return the actual number of entries updated in + the ``clique_info`` array. + + Args: + dev (int): Device for which the clique information is requested. + + Returns: + CUcliqueInfo: Array to store the fabric clique information. + + .. seealso:: `cuDeviceGetCliqueInfo` + """ + cdef size_t[1] _count_count_ = [64] + cdef CliqueInfo clique_info = CliqueInfo(_count_count_[0]) + cdef CUcliqueInfo *clique_info_ptr = (clique_info._get_ptr()) + with nogil: + __status__ = cuDeviceGetCliqueInfo(clique_info_ptr, _count_count_, dev) + check_status(__status__) + return clique_info[:_count_count_[0]] + + +cpdef object mem_get_location_info(uint64_t ptr, size_t size, size_t summary_granularity, size_t sampling_granularity): + """Gets residency information for a memory address range. + + Retrieves memory location information for the specified address range starting + at ``ptr`` with size ``size``. The API summarizes the location information with + a granularity specified by ``summary_granularity``. For each summary region, + the API determines the most common location by sampling memory at intervals + defined by ``sampling_granularity`` within that region. + The location information is returned in the ``location_out`` array, with one + entry per summary region. The total number of locations returned will be + ceil(size/summary_granularity). The user is expected to allocate the + ``location_out`` array with sufficient memory. + For example, with an address range of 1GB, a ``summary_granularity`` of 128MB, + and a ``sampling_granularity`` of 2MB, the function will:. + + - Divide the 1GB range into 8 summary regions of 128MB each. + - Within each 128MB region, sample every 2MB to determine the most common + location. If there is a tie a random winner is chosen. + - Populate the ``location_out`` array with 8 entries, one for each 128MB region + ``summary_granularity`` should be less than or equal to ``size`` and greater + than 0. ``sampling_granularity`` should be less than or equal to + ``summary_granularity``. If the ``sampling_granularity`` is set to 0, a + system dependent value is used as the granularity. In all other cases, the + call returns ``CUDA_ERROR_INVALID_VALUE``. + + When the memory is not resident on any processor, the call returns + ``CUDA_SUCCESS`` and the returned location type for that interval is + ``CU_MEM_LOCATION_TYPE_NONE``. + The memory range must refer to one of the following:. + + - Managed memory allocated via ``cuMemAllocManaged``, via + ``cuMemAllocFromPool`` from a managed memory pool or declared via managed + variables. + - System-allocated pageable memory that is not registered via + ``cuMemHostRegister``. If the memory range does not refer to one of the + above, the call returns ``CUDA_ERROR_INVALID_VALUE``. + + All devices on the system must have non-zero value of device attribute + ``CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS``. If not, this call returns + ``CUDA_ERROR_NOT_SUPPORTED``. + + Args: + ptr (uint64_t): Starting address of the memory range to query. + size (size_t): Size in bytes of the memory range to query. + summary_granularity (size_t): Granularity in bytes at which to + summarize location information. + sampling_granularity (size_t): Granularity in bytes at which to + sample memory within each summary region. + + Returns: + CUmemLocation_v1: Array to store location information, one entry + per summary region. + + .. seealso:: `cuMemGetLocationInfo` + """ + cdef MemLocation_v1 location_out_py = MemLocation_v1() + cdef CUmemLocation *location_out = (location_out_py._get_ptr()) + with nogil: + __status__ = cuMemGetLocationInfo(ptr, size, summary_granularity, sampling_granularity, location_out) + check_status(__status__) + return location_out_py + + +cpdef intptr_t graph_add_node_v3(intptr_t h_graph, 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``. + For kernel nodes, if both the kernel node's ``CUfunction`` and ctx are non- + NULL, the underlying device context of ctx must match the device context that + the ``CUfunction`` was loaded into; otherwise the call returns + ``CUDA_ERROR_INVALID_CONTEXT``. + 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 (object): Dependencies of the node. It can be: + + - an :class:`int` as the pointer address to the array, or + - a Python sequence of :class:`int`\s (as pointer addresses). + 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_v3` + """ + cdef _cyb_nullable_unique_ptr[ _cyb_vector[void*] ] _dependencies_ + _cyb_get_resource_ptrs[void](_dependencies_, dependencies, NULL) + cdef intptr_t _dependency_data_ptr_ = 0 if dependency_data is None else int(dependency_data) + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + cdef CUgraphNode ph_graph_node + with nogil: + __status__ = cuGraphAddNode_v3(&ph_graph_node, h_graph, (_dependencies_.data()), _dependency_data_ptr_, num_dependencies, _node_params_ptr_) + check_status(__status__) + return ph_graph_node + + +cpdef graph_node_set_params_v2(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. + For kernel nodes, if both the kernel node's ``CUfunction`` and ctx are non- + NULL, the underlying device context of ctx must match the device context that + the ``CUfunction`` was loaded into; otherwise the call returns + ``CUDA_ERROR_INVALID_CONTEXT``. + + Args: + h_node (intptr_t): Node to set the parameters for. + node_params (intptr_t): Parameters to copy. + + .. seealso:: `cuGraphNodeSetParams_v2` + """ + cdef intptr_t _node_params_ptr_ = 0 if node_params is None else int(node_params) + with nogil: + __status__ = cuGraphNodeSetParams_v2(h_node, _node_params_ptr_) + check_status(__status__) + + +cpdef checkpoint_operation_complete(intptr_t handle): + """Complete a custom-storage checkpoint or restore operation. + + After ``cuCheckpointProcessCheckpoint`` or ``cuCheckpointProcessRestore`` with + custom storage, ``cuCheckpointOperationComplete`` should be called when the + application has finished or enqueued (on a stream) the required copies (for + checkpoint, GPU mappings to custom storage and for restore, custom storage into + GPU mappings) so the driver can finish the operation. + ``cuCheckpointOperationComplete`` will first synchronize on the streams + returned by ``cuCheckpointProcessCheckpoint`` or + ``cuCheckpointProcessRestore``. The driver assumes that the application has + completed copying the memory to or from custom storage once synchronization is + done. None of the streams returned by ``cuCheckpointProcessCheckpoint`` or + ``cuCheckpointProcessRestore`` should be in stream capture mode; any attempt to + do so would result in ``CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED``. Once the + synchronization is done, ``cuCheckpointOperationComplete`` will unmap the GPU + memory that was mapped on each GPU in a particular + ``cuCheckpointProcessCheckpoint`` or ``cuCheckpointProcessRestore`` operation. + ``cuCheckpointOperationComplete`` identifies the operation to be completed + using ``handle``. This handle is set by ``cuCheckpointProcessCheckpoint`` or + ``cuCheckpointProcessRestore``. + When the call returns successfully, the target process will be in the + ``CU_PROCESS_STATE_CHECKPOINTED`` state when completing a checkpoint operation + or the ``CU_PROCESS_STATE_LOCKED`` state when completing a restore operation. + + Args: + handle (intptr_t): ``CUcheckpointCustomStorageInfo.handle`` set by + a prior ``cuCheckpointProcessCheckpoint`` or + ``cuCheckpointProcessRestore`` call. + + .. seealso:: `cuCheckpointOperationComplete` + """ + with nogil: + __status__ = cuCheckpointOperationComplete(handle) + check_status(__status__) + +# Aliases +graph_instantiate = graph_instantiate_with_flags +# `cuGraphGetEdges` & co. are the `_v2` functions on CUDA 13.0 and later. +graph_get_edges = graph_get_edges_v2 +graph_node_get_dependencies = graph_node_get_dependencies_v2 +graph_node_get_dependent_nodes = graph_node_get_dependent_nodes_v2 +del _cyb_FastEnum diff --git a/cuda_bindings/cuda/bindings/_v2/nvrtc.pxd b/cuda_bindings/cuda/bindings/_v2/nvrtc.pxd index 9c5978e5474..98c657180e1 100644 --- a/cuda_bindings/cuda/bindings/_v2/nvrtc.pxd +++ b/cuda_bindings/cuda/bindings/_v2/nvrtc.pxd @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.0 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=5c7c24ae0ae5a6032e23f801fe9c3151a434eebd3b3429fbfd799985f87b184c +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=94a2cbbfd690b8a9ff436e4e424f67a8ab35631b4ed8790516952e3afbc94de3 # <<<< PREAMBLE CONTENT >>>> @@ -39,10 +39,6 @@ ctypedef nvrtcResult _Result cpdef intptr_t create_program(bytes src, name, headers=*, include_names=*) except? 0 cpdef compile_program(intptr_t prog, options=*) cpdef set_flow_callback(intptr_t prog, intptr_t callback, intptr_t payload) -cpdef bytes get_lowered_name(intptr_t prog, bytes name_expression) -cpdef install_bundled_headers(bytes install_path, unsigned int flags) -cpdef tuple get_bundled_headers_info() -cpdef remove_bundled_headers(bytes install_path) cpdef str get_error_string(int result) cpdef tuple version() @@ -60,9 +56,13 @@ cpdef bytes get_optix_ir(intptr_t prog) cpdef size_t get_program_log_size(intptr_t prog) except? 0 cpdef bytes get_program_log(intptr_t prog) cpdef add_name_expression(intptr_t prog, name_expression) +cpdef bytes get_lowered_name(intptr_t prog, name_expression) cpdef size_t get_pch_heap_size() except? 0 cpdef set_pch_heap_size(size_t size) cpdef int get_pch_create_status(intptr_t prog) except? -1 cpdef size_t get_pch_heap_size_required(intptr_t prog) except? 0 cpdef size_t get_tile_ir_size(intptr_t prog) except? 0 cpdef bytes get_tile_ir(intptr_t prog) +cpdef bytes install_bundled_headers(install_path, unsigned int flags) +cpdef tuple get_bundled_headers_info() +cpdef bytes remove_bundled_headers(install_path) diff --git a/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx b/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx index 37776341963..5926513718d 100644 --- a/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx +++ b/cuda_bindings/cuda/bindings/_v2/nvrtc.pyx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.9.0 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=343843af0d4fa5698e46b9e9dd9ba41a1abe2f056ba3fe97ad98351bf2261c1b +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=19c58d80d518d7503530eddd3838b601f741b4e53ee1d46aa8ab4f8d62731795 # <<<< PREAMBLE CONTENT >>>> @@ -162,7 +162,7 @@ class NoLoweredNamesBeforeCompilationError(NvrtcError): pass class NameExpressionNotValidError(NvrtcError): pass -class InternalErrorError(NvrtcError): +class InternalError(NvrtcError): pass class TimeFileWriteFailedError(NvrtcError): pass @@ -201,7 +201,7 @@ cdef object _nvrtc_error_factory(int status): elif status == 10: return NameExpressionNotValidError(pystatus) elif status == 11: - return InternalErrorError(pystatus) + return InternalError(pystatus) elif status == 12: return TimeFileWriteFailedError(pystatus) elif status == 13: @@ -218,8 +218,6 @@ cdef object _nvrtc_error_factory(int status): return BusyError(pystatus) return NvrtcError(status) -InternalError = InternalErrorError - @cython.profile(False) cdef int check_status(int status) except 1 nogil: @@ -451,7 +449,11 @@ cpdef intptr_t create_program(bytes src, name, headers=None, include_names=None) cdef int num_headers = len(headers) cdef Program prog cdef const char* c_src = src - cdef bytes _name = b"" if name is None else name + cdef bytes _name + if name is None: + _name = b"" + else: + _name = name cdef const char* c_name = _name cdef vector[const char*] cy_headers = headers cdef vector[const char*] cy_include_names = include_names @@ -514,107 +516,6 @@ cpdef set_flow_callback(intptr_t prog, intptr_t callback, intptr_t payload): check_status(__status__) -cpdef bytes get_lowered_name(intptr_t prog, bytes name_expression): - """nvrtcGetLoweredName extracts the lowered (mangled) name for a ``__global__`` function or ``__device__``/``__constant__`` variable. - - The memory containing the name is released when the program is destroyed by - :func:`destroy_program`. The identical *name_expression* must have been previously - provided to :func:`add_name_expression`. - - Args: - prog (intptr_t): CUDA Runtime Compilation program. - name_expression (bytes): Constant expression denoting the address of a - ``__global__`` function or ``__device__``/``__constant__`` variable. - - Returns: - bytes: C string containing the lowered (mangled) name, or ``None``. - - .. seealso:: `nvrtcGetLoweredName` - """ - cdef const char* c_name_expression = name_expression - cdef const char* lowered_name = NULL - with nogil: - __status__ = nvrtcGetLoweredName(prog, c_name_expression, &lowered_name) - check_status(__status__) - return lowered_name if lowered_name != NULL else None - - -cpdef install_bundled_headers(bytes install_path, unsigned int flags): - """nvrtcInstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory. - - NVRTC bundles a set of CUDA Toolkit headers and CCCL within libnvrtc-builtins. - After extraction, compile kernels by passing ``-I`` and - ``-I/cccl`` to :func:`compile_program`. A version marker file - (``.nvrtc_headers_version``) is created to track the installed version. - The function is thread-safe and process-safe; concurrent calls are serialized - using file locking. - - Args: - install_path (bytes): Path where headers should be extracted (UTF-8 encoded). - The directory is created if it does not exist. - flags (unsigned int): Bitwise OR of :class:`InstallHeadersFlag` values (or 0 - for the default ``SKIP_IF_EXISTS`` behaviour). - - Returns: - bytes | None: Detailed error message on failure, or ``None`` on success. - - .. seealso:: `nvrtcInstallBundledHeaders` - """ - cdef const char* c_install_path = install_path - cdef const char* error_log = NULL - with nogil: - __status__ = nvrtcInstallBundledHeaders(c_install_path, flags, &error_log) - check_status(__status__) - return error_log if error_log != NULL else None - - -cpdef tuple get_bundled_headers_info(): - """nvrtcGetBundledHeadersInfo queries information about the bundled headers without extracting them. - - Allows users to determine if bundled headers are available and get size estimates - before calling :func:`install_bundled_headers`. - - Returns: - tuple[BundledHeadersInfo, bytes | None]: Header information struct and an optional - detailed error message (``None`` on success). - - .. seealso:: `nvrtcGetBundledHeadersInfo` - """ - cdef BundledHeadersInfo info = BundledHeadersInfo() - cdef nvrtcBundledHeadersInfo* c_info = (info._get_ptr()) - cdef const char* error_log = NULL - with nogil: - __status__ = nvrtcGetBundledHeadersInfo(c_info, &error_log) - check_status(__status__) - return info, (error_log if error_log != NULL else None) - - -cpdef remove_bundled_headers(bytes install_path): - """nvrtcRemoveBundledHeaders removes previously installed bundled headers. - - Recursively removes all files and subdirectories within the installation - directory to help manage disk space. - - .. note:: This removes ALL contents of the specified directory, not just files - installed by NVRTC. Use with caution. - - Args: - install_path (bytes): Path where headers were previously installed; must be - the same path used with :func:`install_bundled_headers`. - - Returns: - bytes | None: Detailed error message on failure, or ``None`` on success. - - .. seealso:: `nvrtcRemoveBundledHeaders` - """ - cdef const char* c_install_path = install_path - cdef const char* error_log = NULL - with nogil: - __status__ = nvrtcRemoveBundledHeaders(c_install_path, &error_log) - check_status(__status__) - return error_log if error_log != NULL else None - - cpdef str get_error_string(int result): """nvrtcGetErrorString is a helper function that returns a string describing the given ``nvrtcResult`` code, e.g., NVRTC_SUCCESS to ``"NVRTC_SUCCESS"``. For unrecognized enumeration values, it returns ``"NVRTC_ERROR unknown"``. @@ -627,7 +528,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() @@ -701,7 +602,7 @@ cpdef destroy_program(intptr_t prog): .. seealso:: `nvrtcDestroyProgram` """ - cdef Program _prog_ = prog + cdef nvrtcProgram _prog_ = prog with nogil: __status__ = nvrtcDestroyProgram(&_prog_) check_status(__status__) @@ -722,7 +623,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 @@ -735,19 +636,19 @@ cpdef bytes get_ptx(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Compiled result. + bytes: Compiled result. .. seealso:: `nvrtcGetPTX` """ cdef size_t ptxSizeRet with nogil: - __status__ = nvrtcGetPTXSize(prog, &ptxSizeRet) + __status__ = nvrtcGetPTXSize(prog, &ptxSizeRet) check_status(__status__) cdef bytes _ptx_ = bytes(ptxSizeRet) cdef char* ptx = _ptx_ if ptxSizeRet != 0: with nogil: - __status__ = nvrtcGetPTX(prog, ptx) + __status__ = nvrtcGetPTX(prog, ptx) check_status(__status__) return _ptx_ @@ -766,7 +667,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 @@ -779,19 +680,19 @@ cpdef bytes get_cubin(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Compiled and assembled result. + bytes: Compiled and assembled result. .. seealso:: `nvrtcGetCUBIN` """ cdef size_t cubinSizeRet with nogil: - __status__ = nvrtcGetCUBINSize(prog, &cubinSizeRet) + __status__ = nvrtcGetCUBINSize(prog, &cubinSizeRet) check_status(__status__) cdef bytes _cubin_ = bytes(cubinSizeRet) cdef char* cubin = _cubin_ if cubinSizeRet != 0: with nogil: - __status__ = nvrtcGetCUBIN(prog, cubin) + __status__ = nvrtcGetCUBIN(prog, cubin) check_status(__status__) return _cubin_ @@ -810,7 +711,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,19 +724,19 @@ cpdef bytes get_ltoir(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Compiled result. + bytes: Compiled result. .. seealso:: `nvrtcGetLTOIR` """ cdef size_t LTOIRSizeRet with nogil: - __status__ = nvrtcGetLTOIRSize(prog, <OIRSizeRet) + __status__ = nvrtcGetLTOIRSize(prog, <OIRSizeRet) check_status(__status__) cdef bytes _ltoir_ = bytes(LTOIRSizeRet) cdef char* ltoir = _ltoir_ if LTOIRSizeRet != 0: with nogil: - __status__ = nvrtcGetLTOIR(prog, ltoir) + __status__ = nvrtcGetLTOIR(prog, ltoir) check_status(__status__) return _ltoir_ @@ -854,7 +755,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 @@ -867,19 +768,19 @@ cpdef bytes get_optix_ir(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Optix IR Compiled result. + bytes: Optix IR Compiled result. .. seealso:: `nvrtcGetOptiXIR` """ cdef size_t optixirSizeRet with nogil: - __status__ = nvrtcGetOptiXIRSize(prog, &optixirSizeRet) + __status__ = nvrtcGetOptiXIRSize(prog, &optixirSizeRet) check_status(__status__) cdef bytes _optixir_ = bytes(optixirSizeRet) cdef char* optixir = _optixir_ if optixirSizeRet != 0: with nogil: - __status__ = nvrtcGetOptiXIR(prog, optixir) + __status__ = nvrtcGetOptiXIR(prog, optixir) check_status(__status__) return _optixir_ @@ -901,7 +802,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 @@ -914,19 +815,19 @@ cpdef bytes get_program_log(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Compilation log. + bytes: Compilation log. .. seealso:: `nvrtcGetProgramLog` """ cdef size_t logSizeRet with nogil: - __status__ = nvrtcGetProgramLogSize(prog, &logSizeRet) + __status__ = nvrtcGetProgramLogSize(prog, &logSizeRet) check_status(__status__) cdef bytes _log_ = bytes(logSizeRet) cdef char* log = _log_ if logSizeRet != 0: with nogil: - __status__ = nvrtcGetProgramLog(prog, log) + __status__ = nvrtcGetProgramLog(prog, log) check_status(__status__) return _log_ @@ -949,10 +850,37 @@ 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__) +cpdef bytes get_lowered_name(intptr_t prog, name_expression): + """nvrtcGetLoweredName extracts the lowered (mangled) name for a global function or device/__constant__ variable, and updates \*lowered_name to point to it. The memory containing the name is released when the NVRTC program is destroyed by nvrtcDestroyProgram. The identical name expression must have been previously provided to nvrtcAddNameExpression. + + + Args: + prog (intptr_t): CUDA Runtime Compilation program. + name_expression (str): constant expression denoting the address of + a global function or device/__constant__ variable. + + Returns: + bytes: initialized by the function to point to a C string + containing the lowered (mangled) name corresponding to the + provided name expression. + + .. seealso:: `nvrtcGetLoweredName` + """ + if not isinstance(name_expression, str): + raise TypeError("name_expression must be a Python str") + cdef bytes _temp_name_expression_ = (name_expression).encode() + cdef char* _name_expression_ = _temp_name_expression_ + cdef const char* lowered_name = NULL + with nogil: + __status__ = nvrtcGetLoweredName(prog, _name_expression_, &lowered_name) + check_status(__status__) + return (lowered_name) if lowered_name != NULL else b"" + + cpdef size_t get_pch_heap_size() except? 0: """retrieve the current size of the PCH Heap. @@ -1011,7 +939,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 @@ -1030,7 +958,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 @@ -1049,7 +977,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 @@ -1062,21 +990,127 @@ cpdef bytes get_tile_ir(intptr_t prog): prog (intptr_t): CUDA Runtime Compilation program. Returns: - char: Generated cuda_tile IR. + bytes: Generated cuda_tile IR. .. seealso:: `nvrtcGetTileIR` """ cdef size_t TileIRSizeRet with nogil: - __status__ = nvrtcGetTileIRSize(prog, &TileIRSizeRet) + __status__ = nvrtcGetTileIRSize(prog, &TileIRSizeRet) check_status(__status__) cdef bytes _tile_ir_ = bytes(TileIRSizeRet) cdef char* tile_ir = _tile_ir_ if TileIRSizeRet != 0: with nogil: - __status__ = nvrtcGetTileIR(prog, tile_ir) + __status__ = nvrtcGetTileIR(prog, tile_ir) check_status(__status__) return _tile_ir_ +cpdef bytes install_bundled_headers(install_path, unsigned int flags): + """nvrtcInstallBundledHeaders extracts CUDA headers bundled with NVRTC to a specified directory for use during compilation. + + NVRTC bundles a set of CUDA Toolkit headers and CUDA C++ Core Libraries (CCCL) + within libnvrtc-builtins. This function extracts these headers to the specified + directory, allowing NVRTC programs to compile without requiring a separate CUDA + Toolkit installation. The bundled headers match those available in the CUDA + Toolkit plus CCCL libraries. + After extraction, users can compile kernels by passing appropriate include + paths (such as "-I" and "-I/cccl") to + nvrtcCompileProgram. + A version marker file (.nvrtc_headers_version) is created in the installation + directory to track the installed version. + This function is thread-safe and process-safe. Concurrent calls from multiple + threads or processes will be serialized using file locking. By default, the + function waits for the lock; use NVRTC_INSTALL_HEADERS_NO_WAIT to return + immediately with NVRTC_ERROR_BUSY if another process holds the lock. + + Args: + install_path (str): Path where headers should be extracted (UTF-8 + encoded). The directory will be created if it doesn't exist. + flags (unsigned int): NVRTC_INSTALL_HEADERS_* flags:. + + Returns: + bytes: Optional pointer to receive detailed error message on + failure. If non-NULL, ``*error_log`` will be set to point to a + string describing the error cause. Note: subsequent API calls + from the same thread may overwrite this message. May be NULL + if error details are not needed. + + .. note:: + Use NVRTC_INSTALL_HEADERS_SKIP_IF_EXISTS to avoid reinstalling if headers + already exist. Use NVRTC_INSTALL_HEADERS_FORCE_OVERWRITE to guarantee + consistency by clearing the directory first. + .. seealso:: `nvrtcInstallBundledHeaders` + """ + if not isinstance(install_path, str): + raise TypeError("install_path must be a Python str") + cdef bytes _temp_install_path_ = (install_path).encode() + cdef char* _install_path_ = _temp_install_path_ + cdef const char* error_log = NULL + with nogil: + __status__ = nvrtcInstallBundledHeaders(_install_path_, flags, &error_log) + check_status(__status__) + return (error_log) if error_log != NULL else b"" + + +cpdef tuple get_bundled_headers_info(): + """nvrtcGetBundledHeadersInfo queries information about the bundled headers without extracting them. + + This function allows users to determine if bundled headers are available and + get size estimates before calling nvrtcInstallBundledHeaders. + + Returns: + A 2-tuple containing: + - nvrtcBundledHeadersInfo: Pointer to structure to receive header + information. + - bytes: Optional pointer to receive detailed error message on + failure. If non-NULL, ``*error_log`` will be set to point to a + string describing the error cause. Note: subsequent API calls + from the same thread may overwrite this message. May be NULL + if error details are not needed. + + .. seealso:: `nvrtcGetBundledHeadersInfo` + """ + cdef BundledHeadersInfo info_py = BundledHeadersInfo() + cdef nvrtcBundledHeadersInfo *info = (info_py._get_ptr()) + cdef const char* error_log = NULL + with nogil: + __status__ = nvrtcGetBundledHeadersInfo(info, &error_log) + check_status(__status__) + return (info_py, (error_log) if error_log != NULL else b"") + + +cpdef bytes remove_bundled_headers(install_path): + """nvrtcRemoveBundledHeaders removes previously installed bundled headers. + + This function removes the headers installed by nvrtcInstallBundledHeaders, + helping users manage disk space. It recursively removes all files and + subdirectories within the installation directory. + + Args: + install_path (str): Path where headers were previously installed. + Must be the same path used with nvrtcInstallBundledHeaders. + + Returns: + bytes: Optional pointer to receive detailed error message on + failure. If non-NULL, ``*error_log`` will be set to point to a + string describing the error cause. Note: subsequent API calls + from the same thread may overwrite this message. May be NULL + if error details are not needed. + + .. note:: + This function will remove ALL contents of the specified directory, not just + files installed by NVRTC. Use with caution. + .. seealso:: `nvrtcRemoveBundledHeaders` + """ + if not isinstance(install_path, str): + raise TypeError("install_path must be a Python str") + cdef bytes _temp_install_path_ = (install_path).encode() + cdef char* _install_path_ = _temp_install_path_ + cdef const char* error_log = NULL + with nogil: + __status__ = nvrtcRemoveBundledHeaders(_install_path_, &error_log) + check_status(__status__) + return (error_log) if error_log != NULL else b"" del _cyb_FastEnum diff --git a/cuda_bindings/cuda/bindings/cudla.pyx b/cuda_bindings/cuda/bindings/cudla.pyx index d5a86038549..64fc8d78a25 100644 --- a/cuda_bindings/cuda/bindings/cudla.pyx +++ b/cuda_bindings/cuda/bindings/cudla.pyx @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # This code was automatically generated across versions from 1.5.0 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=7a208273ab596a5fc3e4ce5ca2f4cd474a4d3e649aa06b78bc8e5564fe2cebfd +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=50159aaec5737fc94f227c703c6abe29874cd8022b8f545b46498e9c5862c4e6 # <<<< PREAMBLE CONTENT >>>> @@ -86,13 +86,12 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep 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}" + f"address to a valid buffer, or a contiguous {adj}" + f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}" ) from e else: ptr = view.buf @@ -1773,7 +1772,7 @@ cpdef module_unload(intptr_t h_module, 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) + cdef intptr_t _ptr_to_tasks_ptr_ = 0 if ptr_to_tasks is None else int(ptr_to_tasks) with nogil: __status__ = cudlaSubmitTask(dev_handle, _ptr_to_tasks_ptr_, num_tasks, stream, flags) check_status(__status__) diff --git a/cuda_bindings/cuda/bindings/cufile.pyx b/cuda_bindings/cuda/bindings/cufile.pyx index 14587496690..85280099612 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.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=81d29d3c883454c4864665cd1027a72114cacd123e4bfdd997485faedb5a054a +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=d429cbad8076b96b3deb6eeceb51bbcb55e7b1fe5a189afa88a3ebce9970fa8d # <<<< PREAMBLE CONTENT >>>> @@ -444,7 +444,7 @@ cdef class IOEvents: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=io_events_dtype) + 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) }" @@ -790,7 +790,7 @@ cdef class PerGpuStats: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=per_gpu_stats_dtype) + 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) }" @@ -1254,7 +1254,7 @@ cdef class IOVec: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=io_vec_dtype) + arr = _numpy.zeros(size, dtype=io_vec_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(CUfileIOVec_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(CUfileIOVec_t) }" @@ -1413,7 +1413,7 @@ cdef class Descr: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=descr_dtype) + 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) }" @@ -2625,7 +2625,7 @@ cdef class IOParams: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=io_params_dtype) + 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) }" @@ -3384,7 +3384,7 @@ cpdef intptr_t handle_register(descr) except? 0: the file needs to be opened in O_DIRECT mode to support GPUDirect Storage. .. seealso:: `cuFileHandleRegister` """ - cdef intptr_t _descr_ptr_ = int(descr) + cdef intptr_t _descr_ptr_ = 0 if descr is None else int(descr) cdef Handle fh with nogil: __status__ = cuFileHandleRegister(&fh, _descr_ptr_) @@ -3557,14 +3557,14 @@ cpdef intptr_t batch_io_set_up(unsigned nr) except? 0: cpdef batch_io_submit(intptr_t batch_idp, unsigned nr, iocbp, unsigned int flags): - cdef intptr_t _iocbp_ptr_ = int(iocbp) + cdef intptr_t _iocbp_ptr_ = 0 if iocbp is None else int(iocbp) with nogil: __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, iocbp, intptr_t timeout): - cdef intptr_t _iocbp_ptr_ = int(iocbp) + cdef intptr_t _iocbp_ptr_ = 0 if iocbp is None else int(iocbp) with nogil: __status__ = cuFileBatchIOGetStatus(batch_idp, min_nr, nr, _iocbp_ptr_, timeout) check_status(__status__) @@ -3772,7 +3772,7 @@ cpdef get_stats_l1(stats): .. seealso:: `cuFileGetStatsL1` """ - cdef intptr_t _stats_ptr_ = int(stats) + cdef intptr_t _stats_ptr_ = 0 if stats is None else int(stats) with nogil: __status__ = cuFileGetStatsL1(_stats_ptr_) check_status(__status__) @@ -3788,7 +3788,7 @@ cpdef get_stats_l2(stats): .. seealso:: `cuFileGetStatsL2` """ - cdef intptr_t _stats_ptr_ = int(stats) + cdef intptr_t _stats_ptr_ = 0 if stats is None else int(stats) with nogil: __status__ = cuFileGetStatsL2(_stats_ptr_) check_status(__status__) @@ -3804,7 +3804,7 @@ cpdef get_stats_l3(stats): .. seealso:: `cuFileGetStatsL3` """ - cdef intptr_t _stats_ptr_ = int(stats) + cdef intptr_t _stats_ptr_ = 0 if stats is None else int(stats) with nogil: __status__ = cuFileGetStatsL3(_stats_ptr_) check_status(__status__) diff --git a/cuda_bindings/cuda/bindings/driver.pyx b/cuda_bindings/cuda/bindings/driver.pyx index 0d7268422d9..eb037ffb4ed 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.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=548b03ca3d3021957ab650d666fcd33a16d9af80a5004254c2733f807836679b +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=348b02f0a76a3a271fbb11535f02d660d811d3c21a877e46bfc070bbabf43e76 from typing import Any, Optional import cython import ctypes @@ -26427,9 +26427,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 ------- @@ -26477,14 +26477,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 -------- @@ -26515,14 +26515,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 -------- @@ -36311,14 +36311,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 -------- @@ -36354,7 +36354,7 @@ def cuMemPoolDestroy(pool): Parameters ---------- pool : :py:obj:`~.CUmemoryPool` or :py:obj:`~.cudaMemPool_t` - None + Memory pool to destroy Returns ------- @@ -36401,16 +36401,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 -------- @@ -36455,16 +36456,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`, :py:obj:`~.CUDA_ERROR_NOT_SUPPORTED` pool : :py:obj:`~.CUmemoryPool` - None + Returned current memory pool for the given location and allocation + type See Also -------- @@ -36510,11 +36512,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 ------- diff --git a/cuda_bindings/cuda/bindings/nvfatbin.pyx b/cuda_bindings/cuda/bindings/nvfatbin.pyx index be8b01f3db4..d5c16d7b6e5 100644 --- a/cuda_bindings/cuda/bindings/nvfatbin.pyx +++ b/cuda_bindings/cuda/bindings/nvfatbin.pyx @@ -3,12 +3,16 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.4.1 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=a7028b3fc77724f1ea7c5c49302cfe8524b85554b73eaf754231ac9bfc26c0f7 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=a7b1e6452305b24e9ce950d8adbc14639f922708f50252656f28e0fe2e3cd464 # <<<< PREAMBLE CONTENT >>>> cimport cpython as _cyb_cpython +from cuda.bindings._internal.utils cimport ( + get_nested_resource_ptr as _cyb_get_nested_resource_ptr, + nested_resource as _cyb_nested_resource, +) from libc.stdint cimport intptr_t from cuda.bindings._internal._fast_enum import FastEnum as _cyb_FastEnum @@ -29,13 +33,12 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep 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}" + f"address to a valid buffer, or a contiguous {adj}" + f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}" ) from e else: ptr = view.buf @@ -165,8 +168,8 @@ cpdef intptr_t create(options, size_t options_count) except -1: .. seealso:: `nvFatbinCreate` """ - cdef nested_resource[ char ] _options_ - get_nested_resource_ptr[char](_options_, options, NULL) + cdef _cyb_nested_resource[ char ] _options_ + _cyb_get_nested_resource_ptr[char](_options_, options, NULL) cdef Handle handle_indirect with nogil: __status__ = nvFatbinCreate(&handle_indirect, (_options_.ptrs.data()), options_count) diff --git a/cuda_bindings/cuda/bindings/nvjitlink.pyx b/cuda_bindings/cuda/bindings/nvjitlink.pyx index 475f48dcd98..3294c90b9e8 100644 --- a/cuda_bindings/cuda/bindings/nvjitlink.pyx +++ b/cuda_bindings/cuda/bindings/nvjitlink.pyx @@ -3,12 +3,16 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.0.1 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=d783bc46a513ae0becbc9385c3be40ba64809b0fd834e5ed3189b94bd287436d +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=fa69db9162a1215e162a49f33d17f368a9a3a6ac8bcd89b30f4069ba2919e3f3 # <<<< PREAMBLE CONTENT >>>> cimport cpython as _cyb_cpython +from cuda.bindings._internal.utils cimport ( + get_nested_resource_ptr as _cyb_get_nested_resource_ptr, + nested_resource as _cyb_nested_resource, +) from libc.stdint cimport ( intptr_t, uint32_t, @@ -32,13 +36,12 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep 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}" + f"address to a valid buffer, or a contiguous {adj}" + f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}" ) from e else: ptr = view.buf @@ -168,8 +171,8 @@ cpdef intptr_t create(uint32_t num_options, options) except -1: .. seealso:: `nvJitLinkCreate` """ - cdef nested_resource[ char ] _options_ - get_nested_resource_ptr[char](_options_, options, NULL) + cdef _cyb_nested_resource[ char ] _options_ + _cyb_get_nested_resource_ptr[char](_options_, options, NULL) cdef Handle handle with nogil: __status__ = nvJitLinkCreate(&handle, num_options, (_options_.ptrs.data())) diff --git a/cuda_bindings/cuda/bindings/nvml.pyx b/cuda_bindings/cuda/bindings/nvml.pyx index 4a3c2ca260b..13e5dfc3142 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.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=341606be9fe4e6d759ff42b1ac1e10ac2e68e9412f550de5781e57183e218297 +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=475626c3bcb69e8e6c831c4d204de2fac2c4f31f282ef903901ae0ce444da212 # <<<< PREAMBLE CONTENT >>>> @@ -2960,7 +2960,7 @@ class InsufficientPowerError(NvmlError): pass class DriverNotLoadedError(NvmlError): pass -class TimeoutError(NvmlError): +class NvmlTimeoutError(NvmlError): pass class IrqIssueError(NvmlError): pass @@ -2980,7 +2980,7 @@ class LibRmVersionMismatchError(NvmlError): pass class InUseError(NvmlError): pass -class MemoryError(NvmlError): +class NvmlMemoryError(NvmlError): pass class NoDataError(NvmlError): pass @@ -3025,7 +3025,7 @@ cdef object _nvml_error_factory(int status): elif status == 9: return DriverNotLoadedError(pystatus) elif status == 10: - return TimeoutError(pystatus) + return NvmlTimeoutError(pystatus) elif status == 11: return IrqIssueError(pystatus) elif status == 12: @@ -3045,7 +3045,7 @@ cdef object _nvml_error_factory(int status): elif status == 19: return InUseError(pystatus) elif status == 20: - return MemoryError(pystatus) + return NvmlMemoryError(pystatus) elif status == 21: return NoDataError(pystatus) elif status == 22: @@ -4172,7 +4172,7 @@ cdef class ProcessInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_info_dtype) + 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) }" @@ -4355,7 +4355,7 @@ cdef class ProcessDetail_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_detail_v1_dtype) + 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) }" @@ -5065,7 +5065,7 @@ cdef class BridgeChipInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=bridge_chip_info_dtype) + 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) }" @@ -5435,7 +5435,7 @@ cdef class _py_anon_pod0: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=_py_anon_pod0_dtype) + 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) }" @@ -5787,7 +5787,7 @@ cdef class ClkMonFaultInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=clk_mon_fault_info_dtype) + 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) }" @@ -6134,7 +6134,7 @@ cdef class ProcessUtilizationSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_utilization_sample_dtype) + 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) }" @@ -6342,7 +6342,7 @@ cdef class ProcessUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=process_utilization_info_v1_dtype) + 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) }" @@ -7279,7 +7279,7 @@ cdef class _py_anon_pod1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=_py_anon_pod1_dtype) + 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) }" @@ -7775,7 +7775,7 @@ cdef class VgpuProcessUtilizationSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_process_utilization_sample_dtype) + 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) }" @@ -8005,7 +8005,7 @@ cdef class VgpuProcessUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_process_utilization_info_v1_dtype) + 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) }" @@ -8539,7 +8539,7 @@ cdef class VgpuSchedulerLogEntry: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_scheduler_log_entry_dtype) + 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) }" @@ -10131,7 +10131,7 @@ cdef class HwbcEntry: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=hwbc_entry_dtype) + 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) }" @@ -10770,7 +10770,7 @@ cdef class UnitFanInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=unit_fan_info_dtype) + 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) }" @@ -11101,7 +11101,7 @@ cdef class SystemEventData_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=system_event_data_v1_dtype) + 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) }" @@ -11451,7 +11451,7 @@ cdef class EncoderSessionInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=encoder_session_info_dtype) + 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) }" @@ -11834,7 +11834,7 @@ cdef class FBCSessionInfo: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=fbc_session_info_dtype) + 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) }" @@ -14208,7 +14208,7 @@ cdef class GpuInstancePlacement: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=gpu_instance_placement_dtype) + 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) }" @@ -14639,7 +14639,7 @@ cdef class ComputeInstancePlacement: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=compute_instance_placement_dtype) + 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) }" @@ -15747,7 +15747,7 @@ cdef class EccSramUniqueUncorrectedErrorEntry_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=ecc_sram_unique_uncorrected_error_entry_v1_dtype) + 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) }" @@ -16302,7 +16302,7 @@ cdef class NvlinkFirmwareVersion: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=nvlink_firmware_version_dtype) + 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) }" @@ -16785,7 +16785,7 @@ cdef class VgpuSchedulerLogEntry_v2: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_scheduler_log_entry_v2_dtype) + 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) }" @@ -18194,7 +18194,7 @@ cdef class PmgrPwrTuple: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pmgr_pwr_tuple_dtype) + arr = _numpy.zeros(size, dtype=pmgr_pwr_tuple_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPmgrPwrTuple_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPmgrPwrTuple_t) }" @@ -18341,7 +18341,7 @@ cdef class RailMetrics: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=rail_metrics_dtype) + arr = _numpy.zeros(size, dtype=rail_metrics_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlRailMetrics_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlRailMetrics_t) }" @@ -18498,7 +18498,7 @@ cdef class PwrModelMetricsDlppm1xPerf: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_metrics_dlppm1x_perf_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_metrics_dlppm1x_perf_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelMetricsDlppm1xPerf_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelMetricsDlppm1xPerf_t) }" @@ -18645,7 +18645,7 @@ cdef class PwrModelMetricsSamplePfpp1x: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_metrics_sample_pfpp1x_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_metrics_sample_pfpp1x_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelMetricsSamplePfpp1x_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelMetricsSamplePfpp1x_t) }" @@ -18801,7 +18801,7 @@ cdef class PwrModelOperatingPointPfpp1x: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_operating_point_pfpp1x_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_operating_point_pfpp1x_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelOperatingPointPfpp1x_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelOperatingPointPfpp1x_t) }" @@ -20442,7 +20442,7 @@ cdef class NvlinkTelemetrySample_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=nvlink_telemetry_sample_v1_dtype) + arr = _numpy.zeros(size, dtype=nvlink_telemetry_sample_v1_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlNvlinkTelemetrySample_v1_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlNvlinkTelemetrySample_v1_t) }" @@ -21228,7 +21228,7 @@ cdef class Sample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=sample_dtype) + 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) }" @@ -21388,7 +21388,7 @@ cdef class VgpuInstanceUtilizationSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_instance_utilization_sample_dtype) + 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) }" @@ -21588,7 +21588,7 @@ cdef class VgpuInstanceUtilizationInfo_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=vgpu_instance_utilization_info_v1_dtype) + 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) }" @@ -21805,7 +21805,7 @@ cdef class FieldValue: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=field_value_dtype) + 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) }" @@ -23423,7 +23423,7 @@ cdef class GridLicensableFeature: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=grid_licensable_feature_dtype) + 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) }" @@ -24967,7 +24967,7 @@ cdef class CoreRailMetrics: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=core_rail_metrics_dtype) + arr = _numpy.zeros(size, dtype=core_rail_metrics_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlCoreRailMetrics_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlCoreRailMetrics_t) }" @@ -25117,10 +25117,18 @@ cdef class PwrModelMetricsPfpp1x: readonly tuple _estimated_metrics def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_metrics_pfpp1x_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_metrics_pfpp1x_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelMetricsPfpp1x_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelMetricsPfpp1x_t) }" + obj = self + estimated_metrics_list = list() + for i in range(obj._data.size): + addr = obj._data.estimated_metrics[i].__array_interface__['data'][0] + n = int(obj._data.num_vf_points[i]) + estimated_metrics_obj = PwrModelMetricsSamplePfpp1x.from_ptr(addr, n, owner=obj, readonly=False) + estimated_metrics_list.append(estimated_metrics_obj) + obj._estimated_metrics = tuple(estimated_metrics_list) def __repr__(self): if self._data.size > 1: @@ -26005,7 +26013,7 @@ cdef class PRMCounter_v1: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=prm_counter_v1_dtype) + 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) }" @@ -27394,7 +27402,7 @@ cdef class PwrModelMetricsDlppm1x: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_metrics_dlppm1x_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_metrics_dlppm1x_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelMetricsDlppm1x_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelMetricsDlppm1x_t) }" @@ -27576,7 +27584,7 @@ cdef class PerfMetricsPfpp1xSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=perf_metrics_pfpp1x_sample_dtype) + arr = _numpy.zeros(size, dtype=perf_metrics_pfpp1x_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPerfMetricsPfpp1xSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPerfMetricsPfpp1xSample_t) }" @@ -27722,10 +27730,18 @@ cdef class PwrModelMetricsDlppm1xDramclkEstimates: readonly tuple _estimated_metrics def __init__(self, size=1): - arr = _numpy.empty(size, dtype=pwr_model_metrics_dlppm1x_dramclk_estimates_dtype) + arr = _numpy.zeros(size, dtype=pwr_model_metrics_dlppm1x_dramclk_estimates_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPwrModelMetricsDlppm1xDramclkEstimates_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPwrModelMetricsDlppm1xDramclkEstimates_t) }" + obj = self + estimated_metrics_list = list() + for i in range(obj._data.size): + addr = obj._data.estimated_metrics[i].__array_interface__['data'][0] + n = int(obj._data.num_estimated_metrics[i]) + estimated_metrics_obj = PwrModelMetricsDlppm1x.from_ptr(addr, n, owner=obj, readonly=False) + estimated_metrics_list.append(estimated_metrics_obj) + obj._estimated_metrics = tuple(estimated_metrics_list) def __repr__(self): if self._data.size > 1: @@ -27883,7 +27899,7 @@ cdef class ObservedMetrics: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=observed_metrics_dtype) + arr = _numpy.zeros(size, dtype=observed_metrics_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlObservedMetrics_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlObservedMetrics_t) }" @@ -28074,7 +28090,7 @@ cdef class PerfMetricsDlppc2xSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=perf_metrics_dlppc2x_sample_dtype) + arr = _numpy.zeros(size, dtype=perf_metrics_dlppc2x_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPerfMetricsDlppc2xSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPerfMetricsDlppc2xSample_t) }" @@ -28380,7 +28396,7 @@ cdef class PerfMetricControllerSample: object _owner def __init__(self, size=1): - arr = _numpy.empty(size, dtype=perf_metric_controller_sample_dtype) + arr = _numpy.zeros(size, dtype=perf_metric_controller_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPerfMetricControllerSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPerfMetricControllerSample_t) }" @@ -28537,10 +28553,18 @@ cdef class PerfMetricsSample: readonly tuple _controller_data def __init__(self, size=1): - arr = _numpy.empty(size, dtype=perf_metrics_sample_dtype) + arr = _numpy.zeros(size, dtype=perf_metrics_sample_dtype) self._data = arr.view(_numpy.recarray) assert self._data.itemsize == sizeof(nvmlPerfMetricsSample_t), \ f"itemsize {self._data.itemsize} mismatches struct size { sizeof(nvmlPerfMetricsSample_t) }" + obj = self + controller_data_list = list() + for i in range(obj._data.size): + addr = obj._data.controller_data[i].__array_interface__['data'][0] + n = int(obj._data.num_controller_data[i]) + controller_data_obj = PerfMetricControllerSample.from_ptr(addr, n, owner=obj, readonly=False) + controller_data_list.append(controller_data_obj) + obj._controller_data = tuple(controller_data_list) def __repr__(self): if self._data.size > 1: @@ -28898,7 +28922,7 @@ cpdef str system_get_driver_version(): nvmlConstants::NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE. Returns: - char: Reference in which to return the version identifier. + str: Reference in which to return the version identifier. .. seealso:: `nvmlSystemGetDriverVersion` """ @@ -28919,7 +28943,7 @@ cpdef str system_get_nvml_version(): nvmlConstants::NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE. Returns: - char: Reference in which to return the version identifier. + str: Reference in which to return the version identifier. .. seealso:: `nvmlSystemGetNVMLVersion` """ @@ -28980,7 +29004,7 @@ cpdef str system_get_process_name(unsigned int pid): pid (unsigned int): The identifier of the process. Returns: - char: Reference in which to return the process name. + str: Reference in which to return the process name. .. seealso:: `nvmlSystemGetProcessName` """ @@ -29431,7 +29455,7 @@ cpdef str device_get_name(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Reference in which to return the product name. + str: Reference in which to return the product name. .. seealso:: `nvmlDeviceGetName` """ @@ -29510,7 +29534,7 @@ cpdef str device_get_serial(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Reference in which to return the board/module serial number. + str: Reference in which to return the board/module serial number. .. seealso:: `nvmlDeviceGetSerial` """ @@ -29788,7 +29812,7 @@ cpdef str device_get_uuid(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Reference in which to return the GPU UUID. + str: Reference in which to return the GPU UUID. .. seealso:: `nvmlDeviceGetUUID` """ @@ -29830,7 +29854,7 @@ cpdef str device_get_board_part_number(intptr_t device): device (intptr_t): Identifier of the target device. Returns: - char: Reference to the buffer to return. + str: Reference to the buffer to return. .. seealso:: `nvmlDeviceGetBoardPartNumber` """ @@ -29858,7 +29882,7 @@ cpdef str device_get_inforom_version(intptr_t device, int object): object (InforomObject): The target infoROM object. Returns: - char: Reference in which to return the infoROM version. + str: Reference in which to return the infoROM version. .. seealso:: `nvmlDeviceGetInforomVersion` """ @@ -29884,7 +29908,7 @@ cpdef str device_get_inforom_image_version(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Reference in which to return the infoROM image version. + str: Reference in which to return the infoROM image version. .. seealso:: `nvmlDeviceGetInforomImageVersion` """ @@ -30858,7 +30882,7 @@ cpdef device_set_clock_offsets(intptr_t device, info): .. seealso:: `nvmlDeviceSetClockOffsets` """ - cdef intptr_t _info_ptr_ = int(info) + cdef intptr_t _info_ptr_ = 0 if info is None else int(info) with nogil: __status__ = nvmlDeviceSetClockOffsets(device, _info_ptr_) check_status(__status__) @@ -31624,7 +31648,7 @@ cpdef str device_get_vbios_version(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Reference to which to return the VBIOS version. + str: Reference to which to return the VBIOS version. .. seealso:: `nvmlDeviceGetVbiosVersion` """ @@ -33407,7 +33431,7 @@ cpdef device_set_nvlink_bw_mode(intptr_t device, set_bw_mode): .. seealso:: `nvmlDeviceSetNvlinkBwMode` """ - cdef intptr_t _set_bw_mode_ptr_ = int(set_bw_mode) + cdef intptr_t _set_bw_mode_ptr_ = 0 if set_bw_mode is None else int(set_bw_mode) set_bw_mode.version = NVML_VERSION_STRUCT(sizeof(nvmlNvlinkSetBwMode_v1_t), 1) with nogil: __status__ = nvmlDeviceSetNvlinkBwMode(device, _set_bw_mode_ptr_) @@ -33550,7 +33574,7 @@ cpdef device_modify_drain_state(pci_info, int new_state): .. seealso:: `nvmlDeviceModifyDrainState` """ - cdef intptr_t _pci_info_ptr_ = int(pci_info) + cdef intptr_t _pci_info_ptr_ = 0 if pci_info is None else int(pci_info) with nogil: __status__ = nvmlDeviceModifyDrainState(_pci_info_ptr_, <_EnableState>new_state) check_status(__status__) @@ -33571,7 +33595,7 @@ cpdef int device_query_drain_state(pci_info) except? -1: .. seealso:: `nvmlDeviceQueryDrainState` """ - cdef intptr_t _pci_info_ptr_ = int(pci_info) + cdef intptr_t _pci_info_ptr_ = 0 if pci_info is None else int(pci_info) cdef _EnableState current_state with nogil: __status__ = nvmlDeviceQueryDrainState(_pci_info_ptr_, ¤t_state) @@ -33598,7 +33622,7 @@ cpdef device_remove_gpu_v2(pci_info, int gpu_state, int link_state): .. seealso:: `nvmlDeviceRemoveGpu_v2` """ - cdef intptr_t _pci_info_ptr_ = int(pci_info) + cdef intptr_t _pci_info_ptr_ = 0 if pci_info is None else int(pci_info) with nogil: __status__ = nvmlDeviceRemoveGpu_v2(_pci_info_ptr_, <_DetachGpuState>gpu_state, <_PcieLinkState>link_state) check_status(__status__) @@ -33619,7 +33643,7 @@ cpdef device_discover_gpus(pci_info): .. seealso:: `nvmlDeviceDiscoverGpus` """ - cdef intptr_t _pci_info_ptr_ = int(pci_info) + cdef intptr_t _pci_info_ptr_ = 0 if pci_info is None else int(pci_info) with nogil: __status__ = nvmlDeviceDiscoverGpus(_pci_info_ptr_) check_status(__status__) @@ -33909,7 +33933,7 @@ cpdef str vgpu_type_get_class(unsigned int vgpu_type_id): vgpu_type_id (unsigned int): Handle to vGPU type. Returns: - char: Pointer to string array to return class in. + str: Pointer to string array to return class in. .. seealso:: `nvmlVgpuTypeGetClass` """ @@ -34052,7 +34076,7 @@ cpdef str vgpu_type_get_license(unsigned int vgpu_type_id): vgpu_type_id (unsigned int): Handle to vGPU type. Returns: - char: Pointer to buffer to return license info. + str: Pointer to buffer to return license info. .. seealso:: `nvmlVgpuTypeGetLicense` """ @@ -34204,7 +34228,7 @@ cpdef tuple vgpu_instance_get_vm_id(unsigned int vgpu_instance): Returns: A 2-tuple containing: - - char: Pointer to caller-supplied buffer to hold VM ID. + - str: Pointer to caller-supplied buffer to hold VM ID. - int: Pointer to hold VM ID type. .. seealso:: `nvmlVgpuInstanceGetVmID` @@ -34232,7 +34256,7 @@ cpdef str vgpu_instance_get_uuid(unsigned int vgpu_instance): instance. Returns: - char: Pointer to caller-supplied buffer to hold vGPU UUID. + str: Pointer to caller-supplied buffer to hold vGPU UUID. .. seealso:: `nvmlVgpuInstanceGetUUID` """ @@ -34262,7 +34286,7 @@ cpdef str vgpu_instance_get_vm_driver_version(unsigned int vgpu_instance): instance. Returns: - char: Caller-supplied buffer to return driver version string. + str: Caller-supplied buffer to return driver version string. .. seealso:: `nvmlVgpuInstanceGetVmDriverVersion` """ @@ -34589,7 +34613,7 @@ cpdef str vgpu_instance_get_gpu_pci_id(unsigned int vgpu_instance): instance. Returns: - char: Caller-supplied buffer to return vGPU PCI Id string. + str: Caller-supplied buffer to return vGPU PCI Id string. .. seealso:: `nvmlVgpuInstanceGetGpuPciId` """ @@ -34643,7 +34667,7 @@ cpdef str vgpu_instance_get_mdev_uuid(unsigned int vgpu_instance): instance. Returns: - char: Pointer to caller-supplied buffer to hold MDEV UUID. + str: Pointer to caller-supplied buffer to hold MDEV UUID. .. seealso:: `nvmlVgpuInstanceGetMdevUUID` """ @@ -34673,7 +34697,7 @@ cpdef gpu_instance_set_vgpu_scheduler_state(intptr_t gpu_instance, p_scheduler): .. seealso:: `nvmlGpuInstanceSetVgpuSchedulerState` """ - cdef intptr_t _p_scheduler_ptr_ = int(p_scheduler) + cdef intptr_t _p_scheduler_ptr_ = 0 if p_scheduler is None else int(p_scheduler) (_p_scheduler_ptr_).version = NVML_VERSION_STRUCT(sizeof(nvmlVgpuSchedulerState_v1_t), 1) with nogil: __status__ = nvmlGpuInstanceSetVgpuSchedulerState(gpu_instance, _p_scheduler_ptr_) @@ -34739,7 +34763,7 @@ cpdef str device_get_pgpu_metadata_string(intptr_t device): device (intptr_t): The identifier of the target device. Returns: - char: Pointer to caller-supplied buffer into which + str: Pointer to caller-supplied buffer into which ``pgpu_metadata`` is written. .. seealso:: `nvmlDeviceGetPgpuMetadataString` @@ -34899,7 +34923,7 @@ cpdef set_vgpu_version(vgpu_version): the NVIDIA vGPU Manager supports. Otherwise, an error is returned. .. seealso:: `nvmlSetVgpuVersion` """ - cdef intptr_t _vgpu_version_ptr_ = int(vgpu_version) + cdef intptr_t _vgpu_version_ptr_ = 0 if vgpu_version is None else int(vgpu_version) with nogil: __status__ = nvmlSetVgpuVersion(_vgpu_version_ptr_) check_status(__status__) @@ -35382,7 +35406,7 @@ cpdef intptr_t device_create_gpu_instance_with_placement(intptr_t device, unsign .. seealso:: `nvmlDeviceCreateGpuInstanceWithPlacement` """ - cdef intptr_t _placement_ptr_ = int(placement) + cdef intptr_t _placement_ptr_ = 0 if placement is None else int(placement) cdef GpuInstance gpu_instance with nogil: __status__ = nvmlDeviceCreateGpuInstanceWithPlacement(device, profile_id, _placement_ptr_, &gpu_instance) @@ -35590,7 +35614,7 @@ cpdef intptr_t gpu_instance_create_compute_instance_with_placement(intptr_t gpu_ .. seealso:: `nvmlGpuInstanceCreateComputeInstanceWithPlacement` """ - cdef intptr_t _placement_ptr_ = int(placement) + cdef intptr_t _placement_ptr_ = 0 if placement is None else int(placement) cdef ComputeInstance compute_instance with nogil: __status__ = nvmlGpuInstanceCreateComputeInstanceWithPlacement(gpu_instance, profile_id, _placement_ptr_, &compute_instance) @@ -35931,7 +35955,7 @@ cpdef device_set_power_mizer_mode_v1(intptr_t device, power_mizer_mode): .. seealso:: `nvmlDeviceSetPowerMizerMode_v1` """ - cdef intptr_t _power_mizer_mode_ptr_ = int(power_mizer_mode) + cdef intptr_t _power_mizer_mode_ptr_ = 0 if power_mizer_mode is None else int(power_mizer_mode) with nogil: __status__ = nvmlDeviceSetPowerMizerMode_v1(device, _power_mizer_mode_ptr_) check_status(__status__) @@ -36064,7 +36088,7 @@ cpdef device_set_vgpu_scheduler_state_v2(intptr_t device, p_scheduler_state): .. seealso:: `nvmlDeviceSetVgpuSchedulerState_v2` """ - cdef intptr_t _p_scheduler_state_ptr_ = int(p_scheduler_state) + cdef intptr_t _p_scheduler_state_ptr_ = 0 if p_scheduler_state is None else int(p_scheduler_state) with nogil: __status__ = nvmlDeviceSetVgpuSchedulerState_v2(device, _p_scheduler_state_ptr_) check_status(__status__) @@ -36086,7 +36110,7 @@ cpdef gpu_instance_set_vgpu_scheduler_state_v2(intptr_t gpu_instance, p_schedule .. seealso:: `nvmlGpuInstanceSetVgpuSchedulerState_v2` """ - cdef intptr_t _p_scheduler_state_ptr_ = int(p_scheduler_state) + cdef intptr_t _p_scheduler_state_ptr_ = 0 if p_scheduler_state is None else int(p_scheduler_state) with nogil: __status__ = nvmlGpuInstanceSetVgpuSchedulerState_v2(gpu_instance, _p_scheduler_state_ptr_) check_status(__status__) @@ -36279,7 +36303,7 @@ cpdef device_set_memory_limits_v1(intptr_t device, limits): MIG handles are not supported. .. seealso:: `nvmlDeviceSetMemoryLimits_v1` """ - cdef intptr_t _limits_ptr_ = int(limits) + cdef intptr_t _limits_ptr_ = 0 if limits is None else int(limits) with nogil: __status__ = nvmlDeviceSetMemoryLimits_v1(device, _limits_ptr_) check_status(__status__) @@ -36440,7 +36464,7 @@ cpdef event_set_register_gpu_operational_events_v1(intptr_t event_set, config): .. seealso:: `nvmlEventSetRegisterGpuOperationalEvents_v1` """ - cdef intptr_t _config_ptr_ = int(config) + cdef intptr_t _config_ptr_ = 0 if config is None else int(config) with nogil: __status__ = nvmlEventSetRegisterGpuOperationalEvents_v1(event_set, _config_ptr_) check_status(__status__) @@ -38022,4 +38046,8 @@ cpdef bytes event_set_get_context_data_v1(intptr_t set, unsigned int index): __status__ = nvmlEventSetGetContextData_v1(set, ¶ms) check_status(__status__) return data + + +TimeoutError = NvmlTimeoutError +MemoryError = NvmlMemoryError del _cyb_FastEnum diff --git a/cuda_bindings/cuda/bindings/nvvm.pyx b/cuda_bindings/cuda/bindings/nvvm.pyx index e1d0bb39087..75d6a4723cf 100644 --- a/cuda_bindings/cuda/bindings/nvvm.pyx +++ b/cuda_bindings/cuda/bindings/nvvm.pyx @@ -3,12 +3,16 @@ # SPDX-License-Identifier: Apache-2.0 # # This code was automatically generated across versions from 12.0.1 to 13.4.1. Do not modify it directly. -# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=92a06aa55bccfabc1d5bb1216489bb147dfb71d6e628480128fee207b8f3794f +# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=d8933fb727fe70e6c790346a9c502409553a5f982b92288b6044a85229e6ce48 # <<<< PREAMBLE CONTENT >>>> cimport cpython as _cyb_cpython +from cuda.bindings._internal.utils cimport ( + get_nested_resource_ptr as _cyb_get_nested_resource_ptr, + nested_resource as _cyb_nested_resource, +) from libc.stdint cimport intptr_t from cuda.bindings._internal._fast_enum import FastEnum as _cyb_FastEnum @@ -29,13 +33,12 @@ cdef intptr_t _cyb_get_buffer_pointer(buf, Py_ssize_t size, readonly=True) excep 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}" + f"address to a valid buffer, or a contiguous {adj}" + f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}" ) from e else: ptr = view.buf @@ -333,8 +336,8 @@ cpdef compile_program(intptr_t prog, int num_options, options): .. seealso:: `nvvmCompileProgram` """ - cdef nested_resource[ char ] _options_ - get_nested_resource_ptr[char](_options_, options, NULL) + cdef _cyb_nested_resource[ char ] _options_ + _cyb_get_nested_resource_ptr[char](_options_, options, NULL) with nogil: __status__ = nvvmCompileProgram(prog, num_options, (_options_.ptrs.data())) check_status(__status__) @@ -358,8 +361,8 @@ cpdef verify_program(intptr_t prog, int num_options, options): .. seealso:: `nvvmVerifyProgram` """ - cdef nested_resource[ char ] _options_ - get_nested_resource_ptr[char](_options_, options, NULL) + cdef _cyb_nested_resource[ char ] _options_ + _cyb_get_nested_resource_ptr[char](_options_, options, NULL) with nogil: __status__ = nvvmVerifyProgram(prog, num_options, (_options_.ptrs.data())) check_status(__status__) diff --git a/cuda_bindings/docs/source/api.rst b/cuda_bindings/docs/source/api.rst index c3de98f24d9..d5ea7d7f9a6 100644 --- a/cuda_bindings/docs/source/api.rst +++ b/cuda_bindings/docs/source/api.rst @@ -10,8 +10,10 @@ CUDA Python API Reference :caption: CaptionHolder: module/driver + module/driver_v2 module/runtime module/nvrtc + module/nvrtc_v2 module/nvjitlink module/nvvm module/nvfatbin diff --git a/cuda_bindings/docs/source/module/driver_v2.rst b/cuda_bindings/docs/source/module/driver_v2.rst new file mode 100644 index 00000000000..7dce1e9db2a --- /dev/null +++ b/cuda_bindings/docs/source/module/driver_v2.rst @@ -0,0 +1,1476 @@ +.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +.. SPDX-License-Identifier: Apache-2.0 + +.. currentmodule:: cuda.bindings._v2.driver + +--------- +driver_v2 +--------- + +.. seealso:: + + See the :doc:`migration guide ` for the differences between this module and the legacy :doc:`driver ` module. + +Data types used by CUDA driver +------------------------------ + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + Uuid + MemFabricHandle_v1 + IpcEventHandle_v1 + IpcMemHandle_v1 + StreamBatchMemOpParams_v1 + BatchMemOpNodeParams_v1 + BatchMemOpNodeParams_v2 + AsyncNotificationInfo + AccessPolicyWindow_v1 + KernelNodeParams_v2 + KernelNodeParams_v3 + MemSetNodeParams_v1 + MemSetNodeParams_v2 + HostNodeParams_v1 + HostNodeParams_v2 + ConditionalNodeParams + GraphEdgeData + GraphInstantiateParams + LaunchMemSyncDomainMap + LaunchAttributeValue + LaunchAttribute + LaunchConfig + ExecAffinitySmCount_v1 + ExecAffinityParam_v1 + CtxCigParam + CtxCreateParams + StreamCigParam + StreamCigCaptureParams + LibraryHostUniversalFunctionAndDataTable + MemCpy2d_v2 + MemCpy3d_v2 + MemCpy3dPeer_v1 + MemCpyNodeParams + ArrayDescriptor_v2 + Array3dDescriptor_v2 + ArraySparseProperties_v1 + ArrayMemoryRequirements_v1 + ResourceDesc_v1 + TextureDesc_v1 + ResourceViewDesc_v1 + TensorMap + PointerAttributeP2PTokens_v1 + ExternalMemoryHandleDesc_v1 + ExternalMemoryBufferDesc_v1 + ExternalMemoryMipmappedArrayDesc_v1 + ExternalSemaphoreHandleDesc_v1 + ExternalSemaphoreSignalParams_v1 + ExternalSemaphoreWaitParams_v1 + ExtSemSignalNodeParams_v1 + ExtSemSignalNodeParams_v2 + ExtSemWaitNodeParams_v1 + ExtSemWaitNodeParams_v2 + ArrayMapInfo_v1 + MemLocation_v1 + MemAllocationProp_v1 + MulticastObjectProp_v1 + MemAccessDesc_v1 + GraphExecUpdateResultInfo_v1 + MemPoolProps_v1 + MemPoolPtrExportData_v1 + MemCpyAttributes_v1 + Offset3D_v1 + Extent3D_v1 + MemCpy3dOperand_v1 + MemCpy3dBatchOp_v1 + MemAllocNodeParams_v1 + MemAllocNodeParams_v2 + MemFreeNodeParams + ChildGraphNodeParams + EventRecordNodeParams + EventWaitNodeParams + GraphNodeParams + CheckpointLockArgs + CheckpointCheckpointArgs + CheckpointGpuPair + CheckpointRestoreArgs + CheckpointUnlockArgs + IpcMemFlags + MemAttachFlags + CtxFlags + EventSchedFlags + ContextFlags + HostTaskSyncMode + StreamFlags + EventFlags + EventRecordFlags + EventWaitFlags + AtomicOperation + AtomicOperationCapability + StreamWaitValueFlags + StreamWriteValueFlags + StreamBatchMemOpType + StreamMemoryBarrierFlags + StreamAtomicReductionOpType + StreamAtomicReductionDataType + OccupancyFlags + StreamUpdateCaptureDependenciesFlags + AsyncNotificationType + ArrayFormat + AddressMode + FilterMode + DeviceAttribute + PointerAttribute + FunctionAttribute + FuncCache + SharedCarveout + MemoryType + ComputeMode + MemAdvise + MemRangeAttribute + JitOption + JitTarget + JitFallback + JitCacheMode + JitInputType + GraphicsRegisterFlags + GraphicsMapResourceFlags + ArrayCubemapFace + Limit + ResourceType + AccessProperty + GraphConditionalNodeType + GraphNodeType + GraphDependencyType + GraphInstantiateResult + SynchronizationPolicy + ClusterSchedulingPolicy + LaunchMemSyncDomain + LaunchAttributePortableClusterMode + SharedMemoryMode + LaunchAttributeID + StreamCaptureStatus + StreamCaptureMode + DriverProcAddressFlags + DriverProcAddressQueryResult + ExecAffinityType + CigDataType + StreamCigDataType + LibraryOption + Result + DeviceP2PAttribute + ResourceViewFormat + TensorMapDataType + TensorMapInterleave + TensorMapSwizzle + TensorMapL2Promotion + TensorMapFloatOOBFill + TensorMapIm2ColWideMode + PointerAttributeAccessFlags + ExternalMemoryHandleType + ExternalSemaphoreHandleType + MemAllocationHandleType + MemAccessFlags + MemLocationType + MemAllocationType + MemAllocationGranularityFlags + MemRangeHandleType + MemRangeFlags + ArraySparseSubresourceType + MemOperationType + MemHandleType + MemAllocationCompType + MulticastGranularityFlags + GraphExecUpdateResult + MemPoolAttribute + MemCpyFlags + MemCpySrcAccessOrder + MemCpy3DOperandType + GraphMemAttribute + GraphChildGraphNodeOwnership + FlushGPUDirectRDMAWritesOptions + GPUDirectRDMAWritesOrdering + FlushGPUDirectRDMAWritesScope + FlushGPUDirectRDMAWritesTarget + GraphDebugDotFlags + UserObjectFlags + UserObjectRetainFlags + GraphInstantiateFlags + DeviceNumaConfig + ProcessState + EglFrameType + EglResourceLocationFlags + EglColorFormat + Array3dFlags + ArraySparsePropertiesFlags + ComputeTargetBase + ExternalMemoryFlags + ExternalSemaphoreSignalFlags + ExternalSemaphoreWaitFlags + GLMapFlags + GraphConditionalHandleFlags + GraphKernelNodePort + MemCreateUsage + MemHostAllocFlags + MemHostRegisterFlags + MemPoolCreateUsage + NvSciSyncAttr + OutputMode + SpecialDevice + SpecialStream + DevSmResourceGroupParams + StreamMemOpAtomicReductionParams + StreamMemOpFlushRemoteWritesParams + StreamMemOpMemoryBarrierParams + StreamMemOpWaitValueParams + StreamMemOpWriteValueParams + DevProp_v1 + LaunchParams_v1 + CooperativeLaunchMultiDeviceFlags + LaunchParam + NvclEventFlags + ParamTexRef + SharedConfig + TexRefArrayFlags + TexRefFlags + +Error Handling +-------------- + +This section describes the error handling functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + AlreadyAcquiredError + AlreadyMappedError + ArrayIsMappedError + AssertError + CallRequiresNewerDriverError + CapturedEventError + CdpNotSupportedError + CdpVersionMismatchError + CompatNotSupportedOnDeviceError + ContainedError + ContextAlreadyCurrentError + ContextAlreadyInUseError + ContextIsDestroyedError + CooperativeLaunchTooLargeError + DeinitializedError + DeviceNotLicensedError + DeviceUnavailableError + DriverError + EccUncorrectableError + ExternalDeviceError + FabricNotReadyError + DriverFileNotFoundError + FunctionNotLoadedError + GraphExecUpdateFailureError + GraphRecaptureFailureError + HardwareStackError + HostMemoryAlreadyRegisteredError + HostMemoryNotRegisteredError + IllegalAddressError + IllegalInstructionError + IllegalStateError + InsufficientLoaderVersionError + InvalidAddressSpaceError + InvalidClusterSizeError + InvalidContextError + InvalidDeviceError + InvalidGraphicsContextError + InvalidHandleError + InvalidImageError + InvalidPcError + InvalidPtxError + InvalidResourceConfigurationError + InvalidResourceTypeError + InvalidSourceError + InvalidValueError + JitCompilationDisabledError + JitCompilerNotFoundError + KeyRotationError + LaunchFailedError + LaunchIncompatibleTexturingError + LaunchOutOfResourcesError + LaunchTimeoutError + LossyQueryError + MapFailedError + MisalignedAddressError + MpsClientTerminatedError + MpsConnectionFailedError + MpsMaxClientsReachedError + MpsMaxConnectionsReachedError + MpsRpcFailureError + MpsServerNotReadyError + MulticastResourceFullError + NoBinaryForGpuError + NoDeviceError + NotFoundError + NotInitializedError + NotMappedAsArrayError + NotMappedAsPointerError + NotMappedError + NotPermittedError + NotReadyError + NotSupportedError + NvlinkUncorrectableError + OperatingSystemError + OutOfMemoryError + PeerAccessAlreadyEnabledError + PeerAccessNotEnabledError + PeerAccessUnsupportedError + PrimaryContextActiveError + ProfilerAlreadyStartedError + ProfilerAlreadyStoppedError + ProfilerDisabledError + ProfilerNotInitializedError + SharedObjectInitFailedError + SharedObjectSymbolNotFoundError + StreamCaptureImplicitError + StreamCaptureInvalidatedError + StreamCaptureIsolationError + StreamCaptureMergeError + StreamCaptureUnjoinedError + StreamCaptureUnmatchedError + StreamCaptureUnsupportedError + StreamCaptureWrongThreadError + StreamDetachedError + StubLibraryError + SystemDriverMismatchError + SystemNotReadyError + TensorMemoryLeakError + DriverTimeoutError + TooManyPeersError + UnknownError + UnmapFailedError + UnsupportedDevsideSyncError + UnsupportedExecAffinityError + UnsupportedLimitError + UnsupportedPtxVersionError + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + get_error_string + get_error_name + +Initialization +-------------- + +This section describes the initialization functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + init + +Version Management +------------------ + +This section describes the version management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + driver_get_version + +Device Management +----------------- + +This section describes the device management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + device_get + device_get_count + device_get_name + device_get_uuid_v2 + device_get_luid + device_total_mem_v2 + device_get_texture_1d_linear_max_width + device_get_attribute + device_get_properties + device_compute_capability + device_get_host_atomic_capabilities + device_get_nv_sci_sync_attributes + device_set_mem_pool + device_get_mem_pool + device_get_default_mem_pool + device_get_exec_affinity_support + flush_gpu_direct_rdma_writes + +Primary Context Management +-------------------------- + +This section describes the primary context management functions of the low-level CUDA driver application programming interface. + +The primary context is unique per device and shared with the CUDA runtime API. These functions allow integration with other libraries using CUDA. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + device_primary_ctx_retain + device_primary_ctx_release_v2 + device_primary_ctx_set_flags_v2 + device_primary_ctx_get_state + device_primary_ctx_reset_v2 + +Context Management +------------------ + +This section describes the context management functions of the low-level CUDA driver application programming interface. + +Please note that some functions are described in Primary Context Management section. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + ctx_create_v4 + ctx_destroy_v2 + ctx_push_current_v2 + ctx_pop_current_v2 + ctx_set_current + ctx_get_current + ctx_get_device + ctx_get_device_v2 + ctx_get_flags + ctx_set_flags + ctx_get_id + ctx_synchronize + ctx_synchronize_v2 + ctx_set_limit + ctx_get_limit + ctx_get_cache_config + ctx_set_cache_config + ctx_get_api_version + ctx_get_stream_priority_range + ctx_reset_persisting_l2cache + ctx_get_exec_affinity + ctx_record_event + ctx_wait_event + +Module Management +----------------- + +This section describes the module management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + ModuleLoadingMode + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + module_load + module_load_data + module_load_data_ex + module_load_fat_binary + module_unload + module_get_loading_mode + module_get_function + module_get_function_count + module_enumerate_functions + module_get_global_v2 + link_create_v2 + link_add_data_v2 + link_add_file_v2 + link_complete + link_destroy + +Library Management +------------------ + +This section describes the library management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + library_load_data + library_load_from_file + library_unload + library_get_kernel + library_get_kernel_count + library_enumerate_kernels + library_get_module + kernel_get_function + kernel_get_library + library_get_global + library_get_managed + library_get_unified_function + kernel_get_attribute + kernel_set_attribute + kernel_set_cache_config + kernel_get_name + kernel_get_param_info + kernel_get_param_count + +Memory Management +----------------- + +This section describes the memory management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + MemDecompressParams + MemDecompressAlgorithm + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + mem_get_info_v2 + mem_alloc_v2 + mem_alloc_pitch_v2 + mem_free_v2 + mem_get_address_range_v2 + mem_alloc_host_v2 + mem_free_host + mem_host_alloc + mem_host_get_device_pointer_v2 + mem_host_get_flags + mem_alloc_managed + device_register_async_notification + device_unregister_async_notification + device_get_by_pci_bus_id + device_get_pci_bus_id + ipc_get_event_handle + ipc_open_event_handle + ipc_get_mem_handle + ipc_open_mem_handle_v2 + ipc_close_mem_handle + mem_host_register_v2 + mem_host_unregister + cu_memcpy + memcpy_peer + memcpy_htod_v2 + memcpy_dtoh_v2 + memcpy_dtod_v2 + memcpy_dtoa_v2 + memcpy_atod_v2 + memcpy_htoa_v2 + memcpy_atoh_v2 + memcpy_atoa_v2 + memcpy_2d_v2 + memcpy_2d_unaligned_v2 + memcpy_3d_v2 + memcpy_3d_peer + memcpy_async + memcpy_peer_async + memcpy_htod_async_v2 + memcpy_dtoh_async_v2 + memcpy_dtod_async_v2 + memcpy_htoa_async_v2 + memcpy_atoh_async_v2 + memcpy_2d_async_v2 + memcpy_3d_async_v2 + memcpy_3d_peer_async + memcpy_batch_async + memcpy_batch_async_v2 + memcpy_3d_batch_async_v2 + memcpy_with_attributes_async + memcpy_3d_with_attributes_async + memset_d8_v2 + memset_d16_v2 + memset_d32_v2 + memset_d2d8_v2 + memset_d2d16_v2 + memset_d2d32_v2 + memset_d8_async + memset_d16_async + memset_d32_async + memset_d2d8_async + memset_d2d16_async + memset_d2d32_async + array_create_v2 + array_get_descriptor_v2 + array_get_sparse_properties + mipmapped_array_get_sparse_properties + array_get_memory_requirements + mipmapped_array_get_memory_requirements + array_get_plane + array_destroy + array_3d_create_v2 + array_3d_get_descriptor_v2 + mipmapped_array_create + mipmapped_array_get_level + mipmapped_array_destroy + mem_get_handle_for_address_range + mem_batch_decompress_async + +Virtual Memory Management +------------------------- + +This section describes the virtual memory management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + mem_address_reserve + mem_address_free + mem_create + mem_release + mem_map + mem_map_array_async + mem_unmap + mem_set_access + mem_get_access + mem_export_to_shareable_handle + mem_import_from_shareable_handle + mem_get_allocation_granularity + mem_get_allocation_properties_from_handle + mem_retain_allocation_handle + +Stream Ordered Memory Allocator +------------------------------- + +This section describes the stream ordered memory allocator exposed by the low-level CUDA driver application programming interface. + +**overview** + +The asynchronous allocator allows the user to allocate and free in stream order. All asynchronous accesses of the allocation must happen between the stream executions of the allocation and the free. If the memory is accessed outside of the promised stream order, a use before allocation / use after free error will cause undefined behavior. + +The allocator is free to reallocate the memory as long as it can guarantee that compliant memory accesses will not overlap temporally. The allocator may refer to internal stream ordering as well as inter-stream dependencies (such as CUDA events and null stream dependencies) when establishing the temporal guarantee. The allocator may also insert inter-stream dependencies to establish the temporal guarantee. + +**Supported Platforms** + +Whether or not a device supports the integrated stream ordered memory allocator may be queried by calling cuDeviceGetAttribute() with the device attribute CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + mem_free_async + mem_alloc_async + mem_pool_trim_to + mem_pool_set_attribute + mem_pool_get_attribute + mem_pool_set_access + mem_pool_get_access + mem_pool_create + mem_pool_destroy + mem_get_default_mem_pool + mem_get_mem_pool + mem_set_mem_pool + mem_alloc_from_pool_async + mem_pool_export_to_shareable_handle + mem_pool_import_from_shareable_handle + mem_pool_export_pointer + mem_pool_import_pointer + +Multicast Object Management +--------------------------- + +This section describes the CUDA multicast object operations exposed by the low-level CUDA driver application programming interface. + +**overview** + +A multicast object created via cuMulticastCreate enables certain memory operations to be broadcast to a team of devices. Devices can be added to a multicast object via cuMulticastAddDevice. Memory can be bound on each participating device via cuMulticastBindMem, cuMulticastBindMem_v2, cuMulticastBindAddr, or cuMulticastBindAddr_v2. Multicast objects can be mapped into a device's virtual address space using the virtual memmory management APIs (see cuMemMap and cuMemSetAccess). + +**Supported Platforms** + +Support for multicast on a specific device can be queried using the device attribute CU_DEVICE_ATTRIBUTE_MULTICAST_SUPPORTED + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + multicast_create + multicast_add_device + multicast_bind_mem + multicast_bind_mem_v2 + multicast_bind_addr + multicast_bind_addr_v2 + multicast_unbind + multicast_get_granularity + +Fabric Clique Information +------------------------- + +This section describes functions and data structures to retrieve fabric clique information. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + CliqueInfo + CliqueType + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + device_get_fabric_cluster_uuid + device_get_clique_count + device_get_clique_info + +Logical Endpoint +---------------- + +This section describes the logical endpoint functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + LogicalEndpointFabricHandle + LogicalEndpointProp + LogicalEndpointIpcHandleType + LogicalEndpointType + LogicalEndpointFlag + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + logical_endpoint_id_reserve + logical_endpoint_id_release + logical_endpoint_create + logical_endpoint_add_device + logical_endpoint_destroy + logical_endpoint_bind_addr + logical_endpoint_bind_mem + logical_endpoint_unbind + logical_endpoint_export + logical_endpoint_import + logical_endpoint_get_limits + logical_endpoint_query + +Unified Addressing +------------------ + +This section describes the unified addressing functions of the low-level CUDA driver application programming interface. + +**Overview** + +CUDA devices can share a unified address space with the host. For these devices there is no distinction between a device pointer and a host pointer -- the same pointer value may be used to access memory from the host program and from a kernel running on the device (with exceptions enumerated below). + +**Supported Platforms** + +Whether or not a device supports unified addressing may be queried by calling cuDeviceGetAttribute() with the device attribute CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING. + +Unified addressing is automatically enabled in 64-bit processes + +**Looking Up Information from Pointer Values** + +It is possible to look up information about the memory which backs a pointer value. For instance, one may want to know if a pointer points to host or device memory. As another example, in the case of device memory, one may want to know on which CUDA device the memory resides. These properties may be queried using the function cuPointerGetAttribute() + +Since pointers are unique, it is not necessary to specify information about the pointers specified to the various copy functions in the CUDA API. The function cuMemcpy() may be used to perform a copy between two pointers, ignoring whether they point to host or device memory (making cuMemcpyHtoD(), cuMemcpyDtoD(), and cuMemcpyDtoH() unnecessary for devices supporting unified addressing). For multidimensional copies, the memory type CU_MEMORYTYPE_UNIFIED may be used to specify that the CUDA driver should infer the location of the pointer from its value. + +**Automatic Mapping of Host Allocated Host Memory** + +All host memory allocated in all contexts using cuMemAllocHost() and cuMemHostAlloc() is always directly accessible from all contexts on all devices that support unified addressing. This is the case regardless of whether or not the flags CU_MEMHOSTALLOC_PORTABLE and CU_MEMHOSTALLOC_DEVICEMAP are specified. + +The pointer value through which allocated host memory may be accessed in kernels on all devices that support unified addressing is the same as the pointer value through which that memory is accessed on the host, so it is not necessary to call cuMemHostGetDevicePointer() to get the device pointer for these allocations. + +Note that this is not the case for memory allocated using the flag CU_MEMHOSTALLOC_WRITECOMBINED, as discussed below. + +**Automatic Registration of Peer Memory** + +Upon enabling direct access from a context that supports unified addressing to another peer context that supports unified addressing using cuCtxEnablePeerAccess() all memory allocated in the peer context using cuMemAlloc() and cuMemAllocPitch() will immediately be accessible by the current context. The device pointer value through which any peer memory may be accessed in the current context is the same pointer value through which that memory may be accessed in the peer context. + +**Exceptions, Disjoint Addressing** + +Not all memory may be accessed on devices through the same pointer value through which they are accessed on the host. These exceptions are host memory registered using cuMemHostRegister() and host memory allocated using the flag CU_MEMHOSTALLOC_WRITECOMBINED. For these exceptions, there exists a distinct host and device address for the memory. The device address is guaranteed to not overlap any valid host pointer range and is guaranteed to have the same value across all contexts that support unified addressing. + +This device address may be queried using cuMemHostGetDevicePointer() when a context using unified addressing is current. Either the host or the unified device pointer value may be used to refer to this memory through cuMemcpy() and similar functions using the CU_MEMORYTYPE_UNIFIED memory type. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + pointer_get_attribute + mem_prefetch_async_v2 + mem_advise_v2 + mem_prefetch_batch_async + mem_discard_batch_async + mem_discard_and_prefetch_batch_async + mem_get_location_info + mem_range_get_attribute + mem_range_get_attributes + pointer_set_attribute + pointer_get_attributes + +Stream Management +----------------- + +This section describes the stream management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + GraphRecaptureStatus + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + stream_create + stream_create_with_priority + stream_begin_capture_to_cig + stream_end_capture_to_cig + stream_get_priority + stream_get_device + stream_get_flags + stream_get_id + stream_get_ctx + stream_get_ctx_v2 + stream_wait_event + stream_add_callback + stream_begin_capture_v2 + stream_begin_recapture_to_graph + stream_begin_capture_to_graph + thread_exchange_stream_capture_mode + stream_end_capture + stream_is_capturing + stream_get_capture_info_v2 + stream_get_capture_info_v3 + stream_update_capture_dependencies_v2 + stream_attach_mem_async + stream_query + stream_synchronize + stream_destroy_v2 + stream_copy_attributes + stream_get_attribute + stream_set_attribute + +Event Management +---------------- + +This section describes the event management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + event_create + event_record + event_record_with_flags + event_query + event_synchronize + event_destroy_v2 + event_elapsed_time_v2 + +External Resource Interoperability +---------------------------------- + +This section describes the external resource interoperability functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + import_external_memory + external_memory_get_mapped_buffer + external_memory_get_mapped_mipmapped_array + destroy_external_memory + import_external_semaphore + signal_external_semaphores_async + wait_external_semaphores_async + destroy_external_semaphore + +Stream Memory Operations +------------------------ + +This section describes the stream memory operations of the low-level CUDA driver application programming interface. + +Support for the CU_STREAM_WAIT_VALUE_NOR flag can be queried with ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR_V2. + +Support for the cuStreamWriteValue64() and cuStreamWaitValue64() functions, as well as for the CU_STREAM_MEM_OP_WAIT_VALUE_64 and CU_STREAM_MEM_OP_WRITE_VALUE_64 flags, can be queried with CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. + +Support for both CU_STREAM_WAIT_VALUE_FLUSH and CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES requires dedicated platform hardware features and can be queried with cuDeviceGetAttribute() and CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES. + +Note that all memory pointers passed as parameters to these operations are device pointers. Where necessary a device pointer should be obtained, for example with cuMemHostGetDevicePointer(). + +None of the operations accepts pointers to managed memory buffers (cuMemAllocManaged). + +Warning: Improper use of these APIs may deadlock the application. Synchronization ordering established through these APIs is not visible to CUDA. CUDA tasks that are (even indirectly) ordered by these APIs 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. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + stream_wait_value32_v2 + stream_wait_value64_v2 + stream_write_value32_v2 + stream_write_value64_v2 + stream_batch_mem_op_v2 + +Execution Control +----------------- + +This section describes the execution control functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + FunctionLoadingState + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + func_get_attribute + func_set_attribute + func_set_cache_config + func_get_module + func_get_name + func_get_param_info + func_get_param_count + func_is_loaded + func_load + launch_kernel + launch_kernel_ex + launch_cooperative_kernel + launch_cooperative_kernel_multi_device + launch_host_func + launch_host_func_v2 + +Graph Management +---------------- + +This section describes the graph management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + graph_create + graph_add_kernel_node_v2 + graph_kernel_node_get_params_v2 + graph_kernel_node_set_params_v2 + graph_add_memcpy_node + graph_memcpy_node_get_params + graph_memcpy_node_set_params + graph_add_memset_node + graph_memset_node_get_params + graph_memset_node_set_params + graph_add_host_node + graph_host_node_get_params + graph_host_node_set_params + graph_add_child_graph_node + graph_child_graph_node_get_graph + graph_add_empty_node + graph_add_event_record_node + graph_event_record_node_get_event + graph_event_record_node_set_event + graph_add_event_wait_node + graph_event_wait_node_get_event + graph_event_wait_node_set_event + graph_add_external_semaphores_signal_node + graph_external_semaphores_signal_node_get_params + graph_external_semaphores_signal_node_set_params + graph_add_external_semaphores_wait_node + graph_external_semaphores_wait_node_get_params + graph_external_semaphores_wait_node_set_params + graph_add_batch_mem_op_node + graph_batch_mem_op_node_get_params + graph_batch_mem_op_node_set_params + graph_exec_batch_mem_op_node_set_params + graph_add_mem_alloc_node + graph_mem_alloc_node_get_params + graph_add_mem_free_node + graph_mem_free_node_get_params + device_graph_mem_trim + device_get_graph_mem_attribute + device_set_graph_mem_attribute + graph_clone + graph_node_find_in_clone + graph_node_get_type + graph_node_get_containing_graph + graph_node_get_local_id + graph_node_get_tools_id + graph_get_id + graph_exec_get_id + graph_get_nodes + graph_get_root_nodes + graph_get_edges + graph_get_edges_v2 + graph_node_get_dependencies + graph_node_get_dependencies_v2 + graph_node_get_dependent_nodes + graph_node_get_dependent_nodes_v2 + graph_add_dependencies_v2 + graph_remove_dependencies_v2 + graph_destroy_node + graph_instantiate + graph_instantiate_with_flags + graph_instantiate_with_params + graph_exec_get_flags + graph_exec_kernel_node_set_params_v2 + graph_exec_memcpy_node_set_params + graph_exec_memset_node_set_params + graph_exec_host_node_set_params + graph_exec_child_graph_node_set_params + graph_exec_event_record_node_set_event + graph_exec_event_wait_node_set_event + graph_exec_external_semaphores_signal_node_set_params + graph_exec_external_semaphores_wait_node_set_params + graph_node_set_enabled + graph_node_get_enabled + graph_upload + graph_launch + graph_exec_destroy + graph_destroy + graph_exec_update_v2 + graph_kernel_node_copy_attributes + graph_kernel_node_get_attribute + graph_kernel_node_set_attribute + graph_debug_dot_print + user_object_create + user_object_retain + user_object_release + graph_retain_user_object + graph_release_user_object + graph_add_node_v2 + graph_add_node_v3 + graph_node_set_params + graph_node_set_params_v2 + graph_node_get_params + graph_exec_node_set_params + graph_conditional_handle_create + +Occupancy +--------- + +This section describes the occupancy calculation functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + occupancy_max_active_blocks_per_multiprocessor + occupancy_max_active_blocks_per_multiprocessor_with_flags + occupancy_max_potential_block_size + occupancy_max_potential_block_size_with_flags + occupancy_available_dynamic_smem_per_block + occupancy_max_potential_cluster_size + occupancy_max_active_clusters + +Texture Object Management +------------------------- + +This section describes the texture object management functions of the low-level CUDA driver application programming interface. The texture object API is only supported on devices of compute capability 3.0 or higher. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + tex_object_create + tex_object_destroy + tex_object_get_resource_desc + tex_object_get_texture_desc + tex_object_get_resource_view_desc + +Surface Object Management +------------------------- + +This section describes the surface object management functions of the low-level CUDA driver application programming interface. The surface object API is only supported on devices of compute capability 3.0 or higher. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + surf_object_create + surf_object_destroy + surf_object_get_resource_desc + +Tensor Map Object Managment +--------------------------- + +This section describes the tensor map object management functions of the low-level CUDA driver application programming interface. The tensor core API is only supported on devices of compute capability 9.0 or higher. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + tensor_map_encode_tiled + tensor_map_encode_im2col + tensor_map_encode_im2col_wide + tensor_map_replace_address + +Peer Context Memory Access +-------------------------- + +This section describes the direct peer context memory access functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + device_can_access_peer + ctx_enable_peer_access + ctx_disable_peer_access + device_get_p2p_attribute + device_get_p2p_atomic_capabilities + +Graphics Interoperability +------------------------- + +This section describes the graphics interoperability functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + graphics_unregister_resource + graphics_sub_resource_get_mapped_array + graphics_resource_get_mapped_mipmapped_array + graphics_resource_get_mapped_pointer_v2 + graphics_resource_set_map_flags_v2 + graphics_map_resources + graphics_unmap_resources + +Driver Entry Point Access +------------------------- + +This section describes the driver entry point access functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + get_proc_address_v2 + get_export_table + +Coredump Attributes Control API +------------------------------- + +This section describes the coredump attribute control functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + CoredumpSettings + CoredumpGenerationFlags + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + coredump_get_attribute + coredump_get_attribute_global + coredump_set_attribute + coredump_set_attribute_global + coredump_register_start_callback + coredump_register_complete_callback + coredump_deregister_start_callback + coredump_deregister_complete_callback + +Green Contexts +-------------- + +This section describes the APIs for creation and manipulation of green contexts in the CUDA driver. Green contexts are a lightweight alternative to traditional contexts, that can be used to select a subset of device resources. This allows the developer to, for example, select SMs from distinct spatial partitions of the GPU and target them via CUDA stream operations, kernel launches, etc. + +Here are the broad initial steps to follow to get started: + +- (1) Start with an initial set of resources. For SM resources, they can be fetched via cuDeviceGetDevResource. In case of workqueues, a new configuration can be used or an existing one queried via the cuDeviceGetDevResource API. + +- (2) Modify these resources by either partitioning them (in case of SMs) or changing the configuration (in case of workqueues). To partition SMs, we recommend cuDevSmResourceSplit. Changing the workqueue configuration can be done directly in place. + +- (3) Finalize the specification of resources by creating a descriptor via cuDevResourceGenerateDesc. + +- (4) Create a green context via cuGreenCtxCreate. This provisions the resource, such as workqueues (until this step it was only a configuration specification). + +- (5) Create a stream via cuGreenCtxStreamCreate, and use it throughout your application. + +SMs + +There are two possible partition operations - with cuDevSmResourceSplitByCount the partitions created have to follow default SM count granularity requirements, so it will often be rounded up and aligned to a default value. On the other hand, cuDevSmResourceSplit is explicit and allows for creation of non-equal groups. It will not round up automatically - instead it is the developer’s responsibility to query and set the correct values. These requirements can be queried with cuDeviceGetDevResource to determine the alignment granularity (sm.smCoscheduledAlignment). A general guideline on the default values for each compute architecture: + +- On all architectures, + + - Portable code should set smCount to a multiple of the device's alignment granularity (sm.smCoscheduledAlignment). + +- On Compute Architecture 7.X, 8.X, and all Tegra SoC: + + - The smCount must be a multiple of 2. + + - The alignment (and default value of coscheduledSmCount) is 2. + +- On Compute Architecture 9.0+: + + - The smCount must be a multiple of coscheduledSmCount if provided. + + - The alignment is 8. + +While the maximum value for coscheduled SM count is 32 on all Compute Architecture 9.0+, it's recommended to follow cluster size requirements. The portable cluster size and the max cluster size should be used in order to benefit from this co-scheduling. + +Workqueues + +For ``CU_DEV_RESOURCE_TYPE_WORKQUEUE_CONFIG``, the resource specifies the expected maximum number of concurrent stream-ordered workloads via the ``wqConcurrencyLimit`` field. The ``sharingScope`` field determines how workqueue resources are shared: + +- ``CU_WORKQUEUE_SCOPE_DEVICE_CTX:`` Use all shared workqueue resources across all contexts (default driver behavior). + +- ``CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED:`` When possible, use non-overlapping workqueue resources with other balanced green contexts. + +The maximum concurrency limit depends on ::CUDA_DEVICE_MAX_CONNECTIONS and can be queried from the primary context via cuCtxGetDevResource. Configurations may exceed this concurrency limit, but the driver will not guarantee that work submission remains non-overlapping. + +For ``CU_DEV_RESOURCE_TYPE_WORKQUEUE``, the resource represents a pre-existing workqueue that can be retrieved from existing contexts or green contexts. This allows reusing workqueue resources across different green contexts. + +On Concurrency + +Even if the green contexts have disjoint SM partitions, it is not guaranteed that the kernels launched in them will run concurrently or have forward progress guarantees. This is due to other resources that could cause a dependency. Using a combination of disjoint SMs and CU_WORKQUEUE_SCOPE_GREEN_CTX_BALANCED workqueue configurations can provide the best chance of avoiding interference. More resources will be added in the future to provide stronger guarantees. + +Additionally, there are two known scenarios, where its possible for the workload to run on more SMs than was provisioned (but never less). + +- On Volta+ MPS: When ``CUDA_MPS_ACTIVE_THREAD_PERCENTAGE`` is used, the set of SMs that are used for running kernels can be scaled up to the value of SMs used for the MPS client. + +- On Compute Architecture 9.x: When a module with dynamic parallelism (CDP) is loaded, all future kernels running under green contexts may use and share an additional set of 2 SMs. + +Memory Copy Operations + +Green context restrictions apply to memory copy operations only when the copy is performed using a green context. For cross-device copies, green context restrictions may not be applied. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + DevSmResource + DevWorkqueueConfigResource + DevWorkqueueResource + DevResource_v1 + GreenCtxCreateFlags + DevSmResourceGroupFlags + DevSmResourceSplitByCountFlags + DevResourceType + DevWorkqueueConfigScope + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + green_ctx_create + green_ctx_destroy + ctx_from_green_ctx + device_get_dev_resource + ctx_get_dev_resource + green_ctx_get_dev_resource + dev_sm_resource_split_by_count + dev_sm_resource_split + dev_resource_generate_desc + green_ctx_record_event + green_ctx_wait_event + stream_get_green_ctx + green_ctx_stream_create + green_ctx_get_id + stream_get_dev_resource + +Error Log Management Functions +------------------------------ + +This section describes the error log management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + LogLevel + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + logs_register_callback + logs_unregister_callback + logs_current + logs_dump_to_file + logs_dump_to_memory + +CUDA Checkpointing +------------------ + +CUDA API versioning support + +This sections describes the checkpoint and restore functions of the low-level CUDA driver application programming interface. + +The CUDA checkpoint and restore API's provide a way to save and restore GPU state for full process checkpoints when used with CPU side process checkpointing solutions. They can also be used to pause GPU work and suspend a CUDA process to allow other applications to make use of GPU resources. + +Checkpoint and restore capabilities are currently restricted to Linux. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + checkpoint_process_get_restore_thread_id + checkpoint_process_get_state + checkpoint_process_lock + checkpoint_process_checkpoint + checkpoint_process_restore + checkpoint_operation_complete + checkpoint_process_unlock + +Profiler Control +---------------- + +This section describes the profiler control functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + profiler_start + profiler_stop + +EGL Interoperability +-------------------- + +This section describes the EGL interoperability functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + graphics_egl_register_image + egl_stream_consumer_connect + egl_stream_consumer_connect_with_flags + egl_stream_consumer_disconnect + egl_stream_consumer_acquire_frame + egl_stream_consumer_release_frame + egl_stream_producer_connect + egl_stream_producer_disconnect + egl_stream_producer_present_frame + egl_stream_producer_return_frame + graphics_resource_get_mapped_egl_frame + event_create_from_egl_sync + +OpenGL Interoperability +----------------------- + +This section describes the OpenGL interoperability functions of the low-level CUDA driver application programming interface. Note that mapping of OpenGL resources is performed with the graphics API agnostic, resource mapping interface described in Graphics Interoperability. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + graphics_gl_register_buffer + graphics_gl_register_image + gl_get_devices_v2 + +VDPAU Interoperability +---------------------- + +This section describes the VDPAU interoperability functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + vdpau_get_device + vdpau_ctx_create_v2 + graphics_vdpau_register_video_surface + graphics_vdpau_register_output_surface + +Deprecated Context Management +----------------------------- + +This section describes the deprecated context management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + ctx_attach + ctx_detach + ctx_get_shared_mem_config + ctx_set_shared_mem_config + +Deprecated Module Management +---------------------------- + +This section describes the deprecated module management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + module_get_tex_ref + module_get_surf_ref + +Deprecated Execution Control +---------------------------- + +This section describes the deprecated execution control functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + func_set_block_shape + func_set_shared_size + func_set_shared_mem_config + param_set_size + param_seti + param_setf + param_setv + param_set_tex_ref + launch + launch_grid + launch_grid_async + +Deprecated Texture Reference Management +--------------------------------------- + +This section describes the deprecated texture reference management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + tex_ref_create + tex_ref_destroy + tex_ref_set_array + tex_ref_set_mipmapped_array + tex_ref_set_address_v2 + tex_ref_set_address2d_v3 + tex_ref_set_format + tex_ref_set_address_mode + tex_ref_set_filter_mode + tex_ref_set_mipmap_filter_mode + tex_ref_set_mipmap_level_bias + tex_ref_set_mipmap_level_clamp + tex_ref_set_max_anisotropy + tex_ref_set_border_color + tex_ref_set_flags + tex_ref_get_address_v2 + tex_ref_get_array + tex_ref_get_mipmapped_array + tex_ref_get_address_mode + tex_ref_get_filter_mode + tex_ref_get_format + tex_ref_get_mipmap_filter_mode + tex_ref_get_mipmap_level_bias + tex_ref_get_mipmap_level_clamp + tex_ref_get_max_anisotropy + tex_ref_get_border_color + tex_ref_get_flags + +Deprecated Surface Reference Management +--------------------------------------- + +This section describes the deprecated surface reference management functions of the low-level CUDA driver application programming interface. + +.. autosummary:: + :toctree: generated/driver_v2/ + :nosignatures: + + surf_ref_set_array + surf_ref_get_array diff --git a/cuda_bindings/docs/source/module/nvrtc_v2.rst b/cuda_bindings/docs/source/module/nvrtc_v2.rst new file mode 100644 index 00000000000..f50aebdea1c --- /dev/null +++ b/cuda_bindings/docs/source/module/nvrtc_v2.rst @@ -0,0 +1,440 @@ +.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +.. SPDX-License-Identifier: Apache-2.0 + +.. currentmodule:: cuda.bindings._v2.nvrtc + +-------- +nvrtc_v2 +-------- + +.. seealso:: + + See the :doc:`migration guide ` for the differences between this module and the legacy :doc:`nvrtc ` module. + +Error Handling +-------------- + +NVRTC defines the following enumeration type and function for API call error handling. + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + Result + BuiltinOperationFailureError + BusyError + CancelledError + CompilationError + InternalError + InvalidInputError + InvalidOptionError + InvalidProgramError + NameExpressionNotValidError + NoLoweredNamesBeforeCompilationError + NoNameExpressionsAfterCompilationError + NoPchCreateAttemptedError + NvrtcError + OutOfMemoryError + PchCreateError + PchCreateHeapExhaustedError + ProgramCreationFailureError + TimeFileWriteFailedError + TimeTraceFileWriteFailedError + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + get_error_string + +General Information Query +------------------------- + +NVRTC defines the following function for general information query. + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + version + get_num_supported_archs + get_supported_archs + +Compilation +----------- + +NVRTC defines the following type and functions for actual compilation. + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + create_program + destroy_program + compile_program + get_ptx_size + get_ptx + get_cubin_size + get_cubin + get_ltoir_size + get_ltoir + get_optix_ir_size + get_optix_ir + get_program_log_size + get_program_log + add_name_expression + get_lowered_name + set_flow_callback + get_tile_ir_size + get_tile_ir + +Precompiled header (PCH) (CUDA 12.8+) +------------------------------------- + +NVRTC defines the following function related to PCH. Also see PCH related flags passed to compile_program. + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + get_pch_heap_size + set_pch_heap_size + get_pch_create_status + get_pch_heap_size_required + +Bundled Headers Installation +---------------------------- + +NVRTC defines the following types and functions for bundled headers installation and management. + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + BundledHeadersInfo + InstallHeadersFlag + +.. autosummary:: + :toctree: generated/nvrtc_v2/ + :nosignatures: + + install_bundled_headers + get_bundled_headers_info + remove_bundled_headers + +Supported Compile Options +------------------------- + +NVRTC supports the compile options below. Option names with two preceding dashs (``--``) are long option names and option names with one preceding dash (``-``) are short option names. Short option names can be used instead of long option names. When a compile option takes an argument, an assignment operator (``=``) is used to separate the compile option argument from the compile option name, e.g., ``"--gpu-architecture=compute_100"``. Alternatively, the compile option name and the argument can be specified in separate strings without an assignment operator, .e.g, ``"--gpu-architecture"`` ``"compute_100"``. Single-character short option names, such as ``-D``, ``-U``, and ``-I``, do not require an assignment operator, and the compile option name and the argument can be present in the same string with or without spaces between them. For instance, ``"-D="``, ``"-D"``, and ``"-D "`` are all supported. + +The valid compiler options are: + +- Compilation targets + + - ``--gpu-architecture=`` (``-arch``) + +Specify the name of the class of GPU architectures for which the input must be compiled. + +- Separate compilation / whole-program compilation + + - ``--device-c`` (``-dc``) + +Generate relocatable code that can be linked with other relocatable device code. It is equivalent to ``--relocatable-device-code=true``. + + - ``--device-w`` (``-dw``) + +Generate non-relocatable code. It is equivalent to ``--relocatable-device-code=false``. + + - ``--relocatable-device-code={true|false}`` (``-rdc``) + +Enable (disable) the generation of relocatable device code. + + - ``--extensible-whole-program`` (``-ewp``) + +Do extensible whole program compilation of device code. + +- Tile compilation + + - ``--enable-tile`` (``-enable-tile``) + +Enable support for Tile constructs (e.g. ``__tile__`` ) and define the macro ``__CUDACC_TILE__`` . + + - ``--tile-only`` (``-tile-only``) + +Enable support for parsing Tile constructs and define the macro ``__CUDACC_TILE__``, but omit code generation for non-Tile code (e.g. ``__global__`` function). + + - ``--simt-only`` (``-simt-only``) + +Enable support for parsing Tile constructs and define the macro ``__CUDACC_TILE__``, but omit code generation for Tile code (e.g. ``__tile_global__`` function). + + - ``--default-tile`` (``--default-tile``) + +Consider an unannotated function or static storage duration variable as having an implicit ``__tile__`` annotation. If the static storage duration variable violates Tile restrictions (e.g. cannot be of pointer type), then the implicit annotation is silently omitted by default; use ``-diagnose-implicit-tile-var`` to enable compiler diagnostics for such cases. + +``-default-tile`` can be used in conjunction with ``-default-device``. If both flags are specified, the unannotated function and/or static storage duration variable will be considered to have both ``__tile__`` and ``__device__`` implict annotations. There will be a separate copy of the function/variable in the generated SIMT and cuda_tile programs, at present. + + - ``--diagnose-implicit-tile-var`` (``-diagnose-implicit-tile-var``) + +When combined with ``-default-tile``, diagnose static storage duration variables that could not be implicitly annotated with the ``__tile__`` memory space specifier (e.g., due to pointer type restrictions). + +- Debugging support + + - ``--device-debug`` (``-G``) + +Generate debug information. If ``--dopt`` is not specified, then turns off all optimizations. + + - ``--generate-line-info`` (``-lineinfo``) + +Generate line-number information. + +- Code generation + + - ``--dopt`` ``on`` (``-dopt``) + + - ``--dopt=on`` + +Enable device code optimization. When specified along with ``-G``, enables limited debug information generation for optimized device code (currently, only line number information). When ``-G`` is not specified, ``-dopt=on`` is implicit. + + - ``--Ofast-compile={0|min|mid|max}`` (``-Ofc``) + +Specify the fast-compile level for device code, which controls the tradeoff between compilation speed and runtime performance by disabling certain optimizations at varying levels. + + - ``--ptxas-options`` (``-Xptxas``) + + - ``--ptxas-options=`` + +Specify options directly to ptxas, the PTX optimizing assembler. + + - ``--maxrregcount=`` (``-maxrregcount``) + +Specify the maximum amount of registers that GPU functions can use. Until a function-specific limit, a higher value will generally increase the performance of individual GPU threads that execute this function. However, because thread registers are allocated from a global register pool on each GPU, a higher value of this option will also reduce the maximum thread block size, thereby reducing the amount of thread parallelism. Hence, a good maxrregcount value is the result of a trade-off. If this option is not specified, then no maximum is assumed. Value less than the minimum registers required by ABI will be bumped up by the compiler to ABI minimum limit. + + - ``--ftz={true|false}`` (``-ftz``) + +When performing single-precision floating-point operations, flush denormal values to zero or preserve denormal values. + +``--use_fast_math`` implies ``--ftz=true``. + + - ``--prec-sqrt={true|false}`` (``-prec-sqrt``) + +For single-precision floating-point square root, use IEEE round-to-nearest mode or use a faster approximation. ``--use_fast_math`` implies ``--prec-sqrt=false``. + + - ``--prec-div={true|false}`` (``-prec-div``) For single-precision floating-point division and reciprocals, use IEEE round-to-nearest mode or use a faster approximation. ``--use_fast_math`` implies ``--prec-div=false``. + + - Default: ``true`` + + - ``--fmad={true|false}`` (``-fmad``) + +Enables (disables) the contraction of floating-point multiplies and adds/subtracts into floating-point multiply-add operations (FMAD, FFMA, or DFMA). ``--use_fast_math`` implies ``--fmad=true``. + + - ``--fno-signed-zeros`` (``-fno-signed-zeros``) + +This option instructs the optimizer not to distinguish between +-0. + + - ``--ffinite-math-only`` (``-ffinite-math-only``) + +This option instructs the optimizer to assume that values are not nan or +-inf. + + - ``--use_fast_math`` (``-use_fast_math``) + +Make use of fast math operations. ``--use_fast_math`` implies ``--ftz=true`` ``--prec-div=false`` ``--prec-sqrt=false`` ``--fmad=true``. + + - ``--extra-device-vectorization`` (``-extra-device-vectorization``) + +Enables more aggressive device code vectorization in the NVVM optimizer. + + - ``--modify-stack-limit={true|false}`` (``-modify-stack-limit``) + +On Linux, during compilation, use ``setrlimit()`` to increase stack size to maximum allowed. The limit is reset to the previous value at the end of compilation. Note: ``setrlimit()`` changes the value for the entire process. + + - ``--dlink-time-opt`` (``-dlto``) + +Generate intermediate code for later link-time optimization. It implies ``-rdc=true``. Note: when this option is used the ``get_ltoir`` API should be used, as PTX or Cubin will not be generated. + + - ``--gen-opt-lto`` (``-gen-opt-lto``) + +Run the optimizer passes before generating the LTO IR. + + - ``--optix-ir`` (``-optix-ir``) + +Generate OptiX IR. The Optix IR is only intended for consumption by OptiX through appropriate APIs. This feature is not supported with link-time-optimization (``-dlto``). + +Note: when this option is used the get_optix_ir API should be used, as PTX or Cubin will not be generated. + + - ``--jump-table-density=``\[0-101] (``-jtd``) + +Specify the case density percentage in switch statements, and use it as a minimal threshold to determine whether jump table(brx.idx instruction) will be used to implement a switch statement. Default value is 101. The percentage ranges from 0 to 101 inclusively. + + - ``--device-stack-protector={true|false}`` (``-device-stack-protector``) + +Enable (disable) the generation of stack canaries in device code. + + - ``--no-cache`` (``-no-cache``) + +Disable the use of cache for both ptx and cubin code generation. + + - ``--frandom-seed`` (``-frandom-seed``) + +The user specified random seed will be used to replace random numbers used in generating symbol names and variable names. The option can be used to generate deterministically identical ptx and object files. If the input value is a valid number (decimal, octal, or hex), it will be used directly as the random seed. Otherwise, the CRC value of the passed string will be used instead. + +- Preprocessing + + - ``--define-macro=`` (``-D``) + +```` can be either ```` or ````. + + - ``--undefine-macro=`` (``-U``) + +Cancel any previous definition of ````. + + - ``--include-path=`` (``-I``) + +Add the directory ```` to the list of directories to be searched for headers. These paths are searched after the list of headers given to create_program. + + - ``--use-bundled-headers=`` + +Install bundled CUDA headers to ```` and add include paths. This is a convenience flag that combines calling install_bundled_headers and adding ``-I`` and ``-I/cccl`` to the include search path. Headers are installed only if they don't already exist at the specified location. + + - ``--pre-include=
`` (``-include``) + +Preinclude ``
`` during preprocessing. + + - ``--no-source-include`` (``-no-source-include``) + +The preprocessor by default adds the directory of each input sources to the include path. This option disables this feature and only considers the path specified explicitly. + +- Language Dialect + + - ``--std={c++03|c++11|c++14|c++17|c++20|c++23}`` (``-std``) + +Set language dialect to C++03, C++11, C++14, C++17, C++20, or C++23 + + - ``--builtin-move-forward={true|false}`` (``-builtin-move-forward``) + +Provide builtin definitions of ``std::move`` and ``std::forward``, when C++11 or later language dialect is selected. + + - ``--builtin-initializer-list={true|false}`` (``-builtin-initializer-list``) + +Provide builtin definitions of ``std::initializer_list`` class and member functions when C++11 or later language dialect is selected. + +- Precompiled header support (CUDA 12.8+) + + - ``--pch`` (``-pch``) + +Enable automatic PCH processing. + + - ``--create-pch=`` (``-create-pch``) + +Create a PCH file. + + - ``--use-pch=`` (``-use-pch``) + +Use the specified PCH file. + + - ``--pch-dir=`` (``-pch-dir``) + +When using automatic PCH (``-pch``), look for and create PCH files in the specified directory. When using explicit PCH (``-create-pch`` or ``-use-pch``), the directory name is prefixed before the specified file name, unless the file name is an absolute path name. + + - ``--pch-verbose={true|false}`` (``-pch-verbose``) + +In automatic PCH mode, for each PCH file that could not be used in current compilation, print the reason in the compilation log. + + - ``--pch-messages={true|false}`` (``-pch-messages``) + +Print a message in the compilation log, if a PCH file was created or used in the current compilation. + + - ``--instantiate-templates-in-pch={true|false}`` (``-instantiate-templates-in-pch``) + +Enable or disable instantiatiation of templates before PCH creation. Instantiating templates may increase the size of the PCH file, while reducing the compilation cost when using the PCH file (since some template instantiations can be skipped). + +- Misc. + + - ``--disable-warnings`` (``-w``) + +Inhibit all warning messages. + + - ``--Wreorder`` (``-Wreorder``) + +Generate warnings when member initializers are reordered. + + - ``--Wconversion`` (``-Wconversion``) + +Generate a warning when an implicit numeric conversion may narrow the value in the target type (e.g. ``long`` ``long`` narrowed to ``int``) + + - ``--warning-as-error=`` ,... (``-Werror``) + +Make warnings of the specified kinds into errors. The following is the list of warning kinds accepted by this option: + + - ``--fmax-errors=`` (``-fmax-errors``) + +Specify the maximum number of errors to emit before compilation is aborted; must be greater than 0. + + - ``--restrict`` (``-restrict``) + +Programmer assertion that all kernel pointer parameters are restrict pointers. + + - ``--device-as-default-execution-space`` (``-default-device``) + +Treat entities with no execution space annotation as ``__device__`` entities. + + - ``--device-int128`` (``-device-int128``) + +Allow the ``__int128`` type in device code. Also causes the macro ``__CUDACC_RTC_INT128__`` to be defined. + + - ``--device-float128`` (``-device-float128``) + +Allow the ``__float128`` and ``_Float128`` types in device code. Also causes the macro ``D__CUDACC_RTC_FLOAT128__`` to be defined. + + - ``--optimization-info=`` (``-opt-info``) + +Provide optimization reports for the specified kind of optimization. The following kind tags are supported: + + - ``--display-error-number`` (``-err-no``) + +Display diagnostic number for warning messages. (Default) + + - ``--no-display-error-number`` (``-no-err-no``) + +Disables the display of a diagnostic number for warning messages. + + - ``--diag-error=``,... (``-diag-error``) + +Emit error for specified diagnostic message number(s). Message numbers can be separated by comma. + + - ``--diag-suppress=``,... (``-diag-suppress``) + +Suppress specified diagnostic message number(s). Message numbers can be separated by comma. + + - ``--diag-warn=``,... (``-diag-warn``) + +Emit warning for specified diagnostic message number(s). Message numbers can be separated by comma. + + - ``--brief-diagnostics={true|false}`` (``-brief-diag``) + +This option disables or enables showing source line and column info in a diagnostic. The ``--brief-diagnostics=true`` will not show the source line and column info. + + - ``--time=`` (``-time``) + +Generate a comma separated value table with the time taken by each compilation phase, and append it at the end of the file given as the option argument. If the file does not exist, the column headings are generated in the first row of the table. If the file name is '-', the timing data is written to the compilation log. + + - ``--split-compile=`` (``-split-compile=``) + +Perform compiler optimizations in parallel. Split compilation attempts to reduce compile time by enabling the compiler to run certain optimization passes concurrently. This option accepts a numerical value that specifies the maximum number of threads the compiler can use. One can also allow the compiler to use the maximum threads available on the system by setting ``--split-compile=0``. Setting ``--split-compile=1`` will cause this option to be ignored. + + - ``--fdevice-syntax-only`` (``-fdevice-syntax-only``) + +Ends device compilation after front-end syntax checking. This option does not generate valid device code. + + - ``--minimal`` (``-minimal``) + +Omit certain language features to reduce compile time for small programs. In particular, the following are omitted: + + - ``--device-stack-protector`` (``-device-stack-protector``) + +Enable stack canaries in device code. Stack canaries make it more difficult to exploit certain types of memory safety bugs involving stack-local variables. The compiler uses heuristics to assess the risk of such a bug in each function. Only those functions which are deemed high-risk make use of a stack canary. + + - ``--fdevice-time-trace=`` (``-fdevice-time-trace=``) Enables the time profiler, outputting a JSON file based on given . Results can be analyzed on chrome://tracing for a flamegraph visualization. + + - ``--utf-8`` (``-utf-8``) + +Set the source and execution character set to UTF-8 on platforms where that isn't already the default. diff --git a/cuda_bindings/docs/source/module/v2_migration.rst b/cuda_bindings/docs/source/module/v2_migration.rst new file mode 100644 index 00000000000..c62ff83bc47 --- /dev/null +++ b/cuda_bindings/docs/source/module/v2_migration.rst @@ -0,0 +1,3494 @@ +.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +.. SPDX-License-Identifier: Apache-2.0 + +.. _v2-migration: + +------------------------------------ +Migrating to the ``_v2`` Bindings +------------------------------------ + +The ``cuda.bindings._v2`` package provides new bindings for the CUDA driver API +(:doc:`driver_v2 `) and NVRTC (:doc:`nvrtc_v2 `). They cover the +same C APIs as the existing :doc:`driver ` and :doc:`nvrtc ` +modules but follow a more Pythonic design. This guide lists what changed so that +existing code can be ported. + +Overview of changes +=================== + +Errors are raised as exceptions +------------------------------- + +Legacy functions return a tuple that starts with a result code, such as +``(CUresult.CUDA_SUCCESS, value)``. The new functions never return a result code. +A failing call raises an exception instead. The exceptions derive from ``DriverError`` for the +driver and ``NvrtcError`` for NVRTC, and there is one subclass per error code, for +example ``InvalidDeviceError``. The numeric status is available as ``e.status`` +(a plain ``int``). + +Return values +------------- + +A function with no outputs returns ``None``, a function with one output returns that +value directly, and a function with several outputs returns a ``tuple``. The order of +the outputs is the same as in the legacy API. Functions whose signature or return value changes beyond this are +noted in the tables below. + +Naming +------ + +- Functions use ``snake_case`` with the ``cu``/``nvrtc`` prefix removed + (``cuStreamCreate`` becomes ``stream_create``). Driver functions keep the version suffix of + the C symbol (``mem_alloc_v2``), whereas the legacy module drops it. +- Parameters and struct members use ``snake_case``. Names that would clash with a Python keyword or + builtin, or with a name reserved by the generated classes, get a trailing underscore (``input_``, ``flags_``). +- Enumeration classes and structs use ``CamelCase`` with the ``CU``/``nvrtc`` prefix removed. + Structs keep their C version suffix (``MemLocation_v1``) and there is a single class per + versioned C type instead of several aliases. +- Enumeration members lose their common C prefix (``CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK`` + becomes ``DeviceAttribute.MAX_THREADS_PER_BLOCK``), and the old full names are not kept as aliases. + Enumerations with a single member keep the part of the C name that identifies the member, because there is no + second member to share a prefix with. For example ``CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS`` becomes + ``IpcMemFlags.IPC_MEM_LAZY_ENABLE_PEER_ACCESS`` and ``CU_USER_OBJECT_NO_DESTRUCTOR_SYNC`` becomes + ``UserObjectFlags.USER_OBJECT_NO_DESTRUCTOR_SYNC``. The *Prefix removed* columns below list what was removed in each case. + +Handles are plain integers +-------------------------- + +Handle types such as ``CUcontext``, ``CUstream``, ``CUevent``, ``CUmodule``, ``CUdeviceptr`` and +``nvrtcProgram`` are no longer classes. Functions return them as ``int`` and accept only ``int``. +Legacy functions accepted ``None`` for a null handle. The new functions raise ``TypeError`` for ``None``; +pass ``0`` instead (for example ``stream_synchronize(0)`` for the default stream). +Use ``int(handle)`` to convert a legacy handle object. + +Enumerations +------------ + +Enumeration classes are ``int`` subclasses. Functions accept either the enumeration members or plain integers. +Their members expose a description of the value automatically, so the individual members +are no longer documented one by one. + +Structs +------- + +Struct classes are generated extension types that wrap a C struct. They expose their address through the ``.ptr`` +property (replacing ``getPtr()``), and can be created from existing memory with the +``from_ptr()``, ``from_data()`` (which takes a NumPy array of the matching ``*_dtype``) and ``from_buffer()`` class methods. Where a function takes a struct, the argument +is either a raw address (an ``int``) or the struct object itself. Wrapper objects of the legacy classes cannot be +passed in their place. + +Strings and constants +--------------------- + +- ``get_error_string`` and ``get_error_name`` return ``str``, where the legacy functions returned ``bytes``. +- The ``#define`` constants that the legacy driver module exposed as module attributes (``CU_MEMHOSTALLOC_PORTABLE`` and + so on) are now members of enumerations grouped by purpose, for example ``MemHostAllocFlags.PORTABLE``. Only a + few ungrouped constants remain at module level, keeping their C names: ``CUDA_VERSION``, ``CU_IPC_HANDLE_SIZE``, + ``CU_TENSOR_MAP_NUM_QWORDS``, ``CU_LAUNCH_KERNEL_REQUIRED_BLOCK_DIM``, ``CUDA_EGL_INFINITE_TIMEOUT`` and ``MAX_PLANES``. + +Driver +====== + +The ``cuda.bindings._v2.driver`` module replaces ``cuda.bindings.driver``. The deprecated driver APIs (texture references, surface references, ``cuLaunch*`` and ``cuParam*`` functions, ``cuCtxAttach``, and so on) are also available and follow the same rules. They are listed in the *Deprecated functions* table below. + +Functions +--------- + +Where the C symbol has a version suffix (``cuCtxCreate_v2``), the legacy module exposes only the unsuffixed name, while the new module keeps the suffix, so one legacy function can map to several new ones. Only changes to parameters and return values beyond the general rules above are noted. Renamed parameters are not listed. + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - Legacy + - New + - Notes + * - ``cuArray3DCreate`` + - ``array_3d_create_v2`` + - + * - ``cuArray3DGetDescriptor`` + - ``array_3d_get_descriptor_v2`` + - + * - ``cuArrayCreate`` + - ``array_create_v2`` + - + * - ``cuArrayDestroy`` + - ``array_destroy`` + - + * - ``cuArrayGetDescriptor`` + - ``array_get_descriptor_v2`` + - + * - ``cuArrayGetMemoryRequirements`` + - ``array_get_memory_requirements`` + - + * - ``cuArrayGetPlane`` + - ``array_get_plane`` + - + * - ``cuArrayGetSparseProperties`` + - ``array_get_sparse_properties`` + - + * - ``cuCheckpointOperationComplete`` + - ``checkpoint_operation_complete`` + - + * - ``cuCheckpointProcessCheckpoint`` + - ``checkpoint_process_checkpoint`` + - + * - ``cuCheckpointProcessGetRestoreThreadId`` + - ``checkpoint_process_get_restore_thread_id`` + - + * - ``cuCheckpointProcessGetState`` + - ``checkpoint_process_get_state`` + - + * - ``cuCheckpointProcessLock`` + - ``checkpoint_process_lock`` + - + * - ``cuCheckpointProcessRestore`` + - ``checkpoint_process_restore`` + - + * - ``cuCheckpointProcessUnlock`` + - ``checkpoint_process_unlock`` + - + * - ``cuCoredumpDeregisterCompleteCallback`` + - ``coredump_deregister_complete_callback`` + - + * - ``cuCoredumpDeregisterStartCallback`` + - ``coredump_deregister_start_callback`` + - + * - ``cuCoredumpGetAttribute`` + - ``coredump_get_attribute`` + - Returns only the value (``bytes``, ``bool`` or ``int``, depending on the attribute). The legacy function also returned ``size``. + * - ``cuCoredumpGetAttributeGlobal`` + - ``coredump_get_attribute_global`` + - Returns only the value (``bytes``, ``bool`` or ``int``, depending on the attribute). The legacy function also returned ``size``. + * - ``cuCoredumpRegisterCompleteCallback`` + - ``coredump_register_complete_callback`` + - + * - ``cuCoredumpRegisterStartCallback`` + - ``coredump_register_start_callback`` + - + * - ``cuCoredumpSetAttribute`` + - ``coredump_set_attribute`` + - Returns ``None``. The legacy function also returned ``size``. + * - ``cuCoredumpSetAttributeGlobal`` + - ``coredump_set_attribute_global`` + - Returns ``None``. The legacy function also returned ``size``. + * - ``cuCtxCreate`` + - ``ctx_create_v4`` + - + * - ``cuCtxDestroy`` + - ``ctx_destroy_v2`` + - + * - ``cuCtxDisablePeerAccess`` + - ``ctx_disable_peer_access`` + - + * - ``cuCtxEnablePeerAccess`` + - ``ctx_enable_peer_access`` + - + * - ``cuCtxFromGreenCtx`` + - ``ctx_from_green_ctx`` + - + * - ``cuCtxGetApiVersion`` + - ``ctx_get_api_version`` + - + * - ``cuCtxGetCacheConfig`` + - ``ctx_get_cache_config`` + - + * - ``cuCtxGetCurrent`` + - ``ctx_get_current`` + - + * - ``cuCtxGetDevResource`` + - ``ctx_get_dev_resource`` + - + * - ``cuCtxGetDevice`` + - ``ctx_get_device`` + - + * - ``cuCtxGetDevice`` + - ``ctx_get_device_v2`` + - Parameters added: ``ctx``. + * - ``cuCtxGetExecAffinity`` + - ``ctx_get_exec_affinity`` + - + * - ``cuCtxGetFlags`` + - ``ctx_get_flags`` + - + * - ``cuCtxGetId`` + - ``ctx_get_id`` + - + * - ``cuCtxGetLimit`` + - ``ctx_get_limit`` + - + * - ``cuCtxGetStreamPriorityRange`` + - ``ctx_get_stream_priority_range`` + - + * - ``cuCtxPopCurrent`` + - ``ctx_pop_current_v2`` + - + * - ``cuCtxPushCurrent`` + - ``ctx_push_current_v2`` + - + * - ``cuCtxRecordEvent`` + - ``ctx_record_event`` + - + * - ``cuCtxResetPersistingL2Cache`` + - ``ctx_reset_persisting_l2cache`` + - + * - ``cuCtxSetCacheConfig`` + - ``ctx_set_cache_config`` + - + * - ``cuCtxSetCurrent`` + - ``ctx_set_current`` + - + * - ``cuCtxSetFlags`` + - ``ctx_set_flags`` + - + * - ``cuCtxSetLimit`` + - ``ctx_set_limit`` + - + * - ``cuCtxSynchronize`` + - ``ctx_synchronize`` + - + * - ``cuCtxSynchronize`` + - ``ctx_synchronize_v2`` + - Parameters added: ``ctx``. + * - ``cuCtxWaitEvent`` + - ``ctx_wait_event`` + - + * - ``cuDestroyExternalMemory`` + - ``destroy_external_memory`` + - + * - ``cuDestroyExternalSemaphore`` + - ``destroy_external_semaphore`` + - + * - ``cuDevResourceGenerateDesc`` + - ``dev_resource_generate_desc`` + - + * - ``cuDevSmResourceSplit`` + - ``dev_sm_resource_split`` + - + * - ``cuDevSmResourceSplitByCount`` + - ``dev_sm_resource_split_by_count`` + - Parameters removed: ``nbGroups``. Returns ``(resources, remainder)``. The group count is no longer returned. + * - ``cuDeviceCanAccessPeer`` + - ``device_can_access_peer`` + - + * - ``cuDeviceGet`` + - ``device_get`` + - + * - ``cuDeviceGetAttribute`` + - ``device_get_attribute`` + - + * - ``cuDeviceGetByPCIBusId`` + - ``device_get_by_pci_bus_id`` + - + * - ``cuDeviceGetCliqueCount`` + - ``device_get_clique_count`` + - + * - ``cuDeviceGetCliqueInfo`` + - ``device_get_clique_info`` + - Parameters removed: ``count``. Returns the array of ``CliqueInfo`` directly. The count is no longer returned. + * - ``cuDeviceGetCount`` + - ``device_get_count`` + - + * - ``cuDeviceGetDefaultMemPool`` + - ``device_get_default_mem_pool`` + - + * - ``cuDeviceGetDevResource`` + - ``device_get_dev_resource`` + - + * - ``cuDeviceGetExecAffinitySupport`` + - ``device_get_exec_affinity_support`` + - + * - ``cuDeviceGetFabricClusterUuid`` + - ``device_get_fabric_cluster_uuid`` + - + * - ``cuDeviceGetGraphMemAttribute`` + - ``device_get_graph_mem_attribute`` + - + * - ``cuDeviceGetHostAtomicCapabilities`` + - ``device_get_host_atomic_capabilities`` + - Parameters removed: ``count``. + * - ``cuDeviceGetLuid`` + - ``device_get_luid`` + - + * - ``cuDeviceGetMemPool`` + - ``device_get_mem_pool`` + - + * - ``cuDeviceGetName`` + - ``device_get_name`` + - + * - ``cuDeviceGetNvSciSyncAttributes`` + - ``device_get_nv_sci_sync_attributes`` + - Returns the populated ``nv_sci_sync_attr_list`` handle. + * - ``cuDeviceGetP2PAtomicCapabilities`` + - ``device_get_p2p_atomic_capabilities`` + - + * - ``cuDeviceGetP2PAttribute`` + - ``device_get_p2p_attribute`` + - + * - ``cuDeviceGetPCIBusId`` + - ``device_get_pci_bus_id`` + - + * - ``cuDeviceGetTexture1DLinearMaxWidth`` + - ``device_get_texture_1d_linear_max_width`` + - + * - ``cuDeviceGetUuid`` + - ``device_get_uuid_v2`` + - + * - ``cuDeviceGraphMemTrim`` + - ``device_graph_mem_trim`` + - + * - ``cuDevicePrimaryCtxGetState`` + - ``device_primary_ctx_get_state`` + - + * - ``cuDevicePrimaryCtxRelease`` + - ``device_primary_ctx_release_v2`` + - + * - ``cuDevicePrimaryCtxReset`` + - ``device_primary_ctx_reset_v2`` + - + * - ``cuDevicePrimaryCtxRetain`` + - ``device_primary_ctx_retain`` + - + * - ``cuDevicePrimaryCtxSetFlags`` + - ``device_primary_ctx_set_flags_v2`` + - + * - ``cuDeviceRegisterAsyncNotification`` + - ``device_register_async_notification`` + - + * - ``cuDeviceSetGraphMemAttribute`` + - ``device_set_graph_mem_attribute`` + - + * - ``cuDeviceSetMemPool`` + - ``device_set_mem_pool`` + - + * - ``cuDeviceTotalMem`` + - ``device_total_mem_v2`` + - + * - ``cuDeviceUnregisterAsyncNotification`` + - ``device_unregister_async_notification`` + - + * - ``cuDriverGetVersion`` + - ``driver_get_version`` + - + * - ``cuEGLStreamConsumerAcquireFrame`` + - ``egl_stream_consumer_acquire_frame`` + - Parameters removed: ``pCudaResource``. Returns the CUDA resource handle. + * - ``cuEGLStreamConsumerConnect`` + - ``egl_stream_consumer_connect`` + - + * - ``cuEGLStreamConsumerConnectWithFlags`` + - ``egl_stream_consumer_connect_with_flags`` + - + * - ``cuEGLStreamConsumerDisconnect`` + - ``egl_stream_consumer_disconnect`` + - + * - ``cuEGLStreamConsumerReleaseFrame`` + - ``egl_stream_consumer_release_frame`` + - + * - ``cuEGLStreamProducerConnect`` + - ``egl_stream_producer_connect`` + - + * - ``cuEGLStreamProducerDisconnect`` + - ``egl_stream_producer_disconnect`` + - + * - ``cuEGLStreamProducerPresentFrame`` + - ``egl_stream_producer_present_frame`` + - + * - ``cuEGLStreamProducerReturnFrame`` + - ``egl_stream_producer_return_frame`` + - + * - ``cuEventCreate`` + - ``event_create`` + - + * - ``cuEventCreateFromEGLSync`` + - ``event_create_from_egl_sync`` + - + * - ``cuEventDestroy`` + - ``event_destroy_v2`` + - + * - ``cuEventElapsedTime`` + - ``event_elapsed_time_v2`` + - + * - ``cuEventQuery`` + - ``event_query`` + - + * - ``cuEventRecord`` + - ``event_record`` + - + * - ``cuEventRecordWithFlags`` + - ``event_record_with_flags`` + - + * - ``cuEventSynchronize`` + - ``event_synchronize`` + - + * - ``cuExternalMemoryGetMappedBuffer`` + - ``external_memory_get_mapped_buffer`` + - + * - ``cuExternalMemoryGetMappedMipmappedArray`` + - ``external_memory_get_mapped_mipmapped_array`` + - + * - ``cuFlushGPUDirectRDMAWrites`` + - ``flush_gpu_direct_rdma_writes`` + - + * - ``cuFuncGetAttribute`` + - ``func_get_attribute`` + - + * - ``cuFuncGetModule`` + - ``func_get_module`` + - + * - ``cuFuncGetName`` + - ``func_get_name`` + - + * - ``cuFuncGetParamCount`` + - ``func_get_param_count`` + - + * - ``cuFuncGetParamInfo`` + - ``func_get_param_info`` + - + * - ``cuFuncIsLoaded`` + - ``func_is_loaded`` + - + * - ``cuFuncLoad`` + - ``func_load`` + - + * - ``cuFuncSetAttribute`` + - ``func_set_attribute`` + - + * - ``cuFuncSetCacheConfig`` + - ``func_set_cache_config`` + - + * - ``cuGLGetDevices`` + - ``gl_get_devices_v2`` + - Parameters removed: ``cudaDeviceCount``. Returns a NumPy ``int32`` array of device ordinals. The device count is no longer returned. + * - ``cuGetErrorName`` + - ``get_error_name`` + - + * - ``cuGetErrorString`` + - ``get_error_string`` + - + * - ``cuGetExportTable`` + - ``get_export_table`` + - + * - ``cuGetProcAddress`` + - ``get_proc_address_v2`` + - + * - ``cuGraphAddBatchMemOpNode`` + - ``graph_add_batch_mem_op_node`` + - + * - ``cuGraphAddChildGraphNode`` + - ``graph_add_child_graph_node`` + - + * - ``cuGraphAddDependencies`` + - ``graph_add_dependencies_v2`` + - + * - ``cuGraphAddEmptyNode`` + - ``graph_add_empty_node`` + - + * - ``cuGraphAddEventRecordNode`` + - ``graph_add_event_record_node`` + - + * - ``cuGraphAddEventWaitNode`` + - ``graph_add_event_wait_node`` + - + * - ``cuGraphAddExternalSemaphoresSignalNode`` + - ``graph_add_external_semaphores_signal_node`` + - + * - ``cuGraphAddExternalSemaphoresWaitNode`` + - ``graph_add_external_semaphores_wait_node`` + - + * - ``cuGraphAddHostNode`` + - ``graph_add_host_node`` + - + * - ``cuGraphAddKernelNode`` + - ``graph_add_kernel_node_v2`` + - + * - ``cuGraphAddMemAllocNode`` + - ``graph_add_mem_alloc_node`` + - + * - ``cuGraphAddMemFreeNode`` + - ``graph_add_mem_free_node`` + - + * - ``cuGraphAddMemcpyNode`` + - ``graph_add_memcpy_node`` + - + * - ``cuGraphAddMemsetNode`` + - ``graph_add_memset_node`` + - + * - ``cuGraphAddNode`` + - ``graph_add_node_v2`` + - + * - ``cuGraphAddNode`` + - ``graph_add_node_v3`` + - + * - ``cuGraphBatchMemOpNodeGetParams`` + - ``graph_batch_mem_op_node_get_params`` + - + * - ``cuGraphBatchMemOpNodeSetParams`` + - ``graph_batch_mem_op_node_set_params`` + - + * - ``cuGraphChildGraphNodeGetGraph`` + - ``graph_child_graph_node_get_graph`` + - + * - ``cuGraphClone`` + - ``graph_clone`` + - + * - ``cuGraphConditionalHandleCreate`` + - ``graph_conditional_handle_create`` + - + * - ``cuGraphCreate`` + - ``graph_create`` + - + * - ``cuGraphDebugDotPrint`` + - ``graph_debug_dot_print`` + - + * - ``cuGraphDestroy`` + - ``graph_destroy`` + - + * - ``cuGraphDestroyNode`` + - ``graph_destroy_node`` + - + * - ``cuGraphEventRecordNodeGetEvent`` + - ``graph_event_record_node_get_event`` + - + * - ``cuGraphEventRecordNodeSetEvent`` + - ``graph_event_record_node_set_event`` + - + * - ``cuGraphEventWaitNodeGetEvent`` + - ``graph_event_wait_node_get_event`` + - + * - ``cuGraphEventWaitNodeSetEvent`` + - ``graph_event_wait_node_set_event`` + - + * - ``cuGraphExecBatchMemOpNodeSetParams`` + - ``graph_exec_batch_mem_op_node_set_params`` + - + * - ``cuGraphExecChildGraphNodeSetParams`` + - ``graph_exec_child_graph_node_set_params`` + - + * - ``cuGraphExecDestroy`` + - ``graph_exec_destroy`` + - + * - ``cuGraphExecEventRecordNodeSetEvent`` + - ``graph_exec_event_record_node_set_event`` + - + * - ``cuGraphExecEventWaitNodeSetEvent`` + - ``graph_exec_event_wait_node_set_event`` + - + * - ``cuGraphExecExternalSemaphoresSignalNodeSetParams`` + - ``graph_exec_external_semaphores_signal_node_set_params`` + - + * - ``cuGraphExecExternalSemaphoresWaitNodeSetParams`` + - ``graph_exec_external_semaphores_wait_node_set_params`` + - + * - ``cuGraphExecGetFlags`` + - ``graph_exec_get_flags`` + - + * - ``cuGraphExecGetId`` + - ``graph_exec_get_id`` + - + * - ``cuGraphExecHostNodeSetParams`` + - ``graph_exec_host_node_set_params`` + - + * - ``cuGraphExecKernelNodeSetParams`` + - ``graph_exec_kernel_node_set_params_v2`` + - + * - ``cuGraphExecMemcpyNodeSetParams`` + - ``graph_exec_memcpy_node_set_params`` + - + * - ``cuGraphExecMemsetNodeSetParams`` + - ``graph_exec_memset_node_set_params`` + - + * - ``cuGraphExecNodeSetParams`` + - ``graph_exec_node_set_params`` + - + * - ``cuGraphExecUpdate`` + - ``graph_exec_update_v2`` + - + * - ``cuGraphExternalSemaphoresSignalNodeGetParams`` + - ``graph_external_semaphores_signal_node_get_params`` + - + * - ``cuGraphExternalSemaphoresSignalNodeSetParams`` + - ``graph_external_semaphores_signal_node_set_params`` + - + * - ``cuGraphExternalSemaphoresWaitNodeGetParams`` + - ``graph_external_semaphores_wait_node_get_params`` + - + * - ``cuGraphExternalSemaphoresWaitNodeSetParams`` + - ``graph_external_semaphores_wait_node_set_params`` + - + * - ``cuGraphGetEdges`` + - ``graph_get_edges`` + - Parameters removed: ``numEdges``. Returns ``(from, to, edge_data)``. The edge count is no longer returned. + * - ``cuGraphGetEdges`` + - ``graph_get_edges_v2`` + - Parameters removed: ``numEdges``. Returns ``(from, to, edge_data)``. The edge count is no longer returned. + * - ``cuGraphGetId`` + - ``graph_get_id`` + - + * - ``cuGraphGetNodes`` + - ``graph_get_nodes`` + - Parameters removed: ``numNodes``. Returns an array of node handles. The count is no longer returned. + * - ``cuGraphGetRootNodes`` + - ``graph_get_root_nodes`` + - Parameters removed: ``numRootNodes``. Returns an array of node handles. The count is no longer returned. + * - ``cuGraphHostNodeGetParams`` + - ``graph_host_node_get_params`` + - + * - ``cuGraphHostNodeSetParams`` + - ``graph_host_node_set_params`` + - + * - ``cuGraphInstantiate`` + - ``graph_instantiate`` + - + * - ``cuGraphInstantiateWithParams`` + - ``graph_instantiate_with_params`` + - + * - ``cuGraphKernelNodeCopyAttributes`` + - ``graph_kernel_node_copy_attributes`` + - + * - ``cuGraphKernelNodeGetAttribute`` + - ``graph_kernel_node_get_attribute`` + - + * - ``cuGraphKernelNodeGetParams`` + - ``graph_kernel_node_get_params_v2`` + - + * - ``cuGraphKernelNodeSetAttribute`` + - ``graph_kernel_node_set_attribute`` + - + * - ``cuGraphKernelNodeSetParams`` + - ``graph_kernel_node_set_params_v2`` + - + * - ``cuGraphLaunch`` + - ``graph_launch`` + - + * - ``cuGraphMemAllocNodeGetParams`` + - ``graph_mem_alloc_node_get_params`` + - + * - ``cuGraphMemFreeNodeGetParams`` + - ``graph_mem_free_node_get_params`` + - + * - ``cuGraphMemcpyNodeGetParams`` + - ``graph_memcpy_node_get_params`` + - + * - ``cuGraphMemcpyNodeSetParams`` + - ``graph_memcpy_node_set_params`` + - + * - ``cuGraphMemsetNodeGetParams`` + - ``graph_memset_node_get_params`` + - + * - ``cuGraphMemsetNodeSetParams`` + - ``graph_memset_node_set_params`` + - + * - ``cuGraphNodeFindInClone`` + - ``graph_node_find_in_clone`` + - + * - ``cuGraphNodeGetContainingGraph`` + - ``graph_node_get_containing_graph`` + - + * - ``cuGraphNodeGetDependencies`` + - ``graph_node_get_dependencies`` + - Parameters removed: ``numDependencies``. Returns ``(dependencies, edge_data)``. The count is no longer returned. + * - ``cuGraphNodeGetDependencies`` + - ``graph_node_get_dependencies_v2`` + - Parameters removed: ``numDependencies``. Returns ``(dependencies, edge_data)``. The count is no longer returned. + * - ``cuGraphNodeGetDependentNodes`` + - ``graph_node_get_dependent_nodes`` + - Parameters removed: ``numDependentNodes``. Returns ``(dependent_nodes, edge_data)``. The count is no longer returned. + * - ``cuGraphNodeGetDependentNodes`` + - ``graph_node_get_dependent_nodes_v2`` + - Parameters removed: ``numDependentNodes``. Returns ``(dependent_nodes, edge_data)``. The count is no longer returned. + * - ``cuGraphNodeGetEnabled`` + - ``graph_node_get_enabled`` + - + * - ``cuGraphNodeGetLocalId`` + - ``graph_node_get_local_id`` + - + * - ``cuGraphNodeGetParams`` + - ``graph_node_get_params`` + - + * - ``cuGraphNodeGetToolsId`` + - ``graph_node_get_tools_id`` + - + * - ``cuGraphNodeGetType`` + - ``graph_node_get_type`` + - + * - ``cuGraphNodeSetEnabled`` + - ``graph_node_set_enabled`` + - + * - ``cuGraphNodeSetParams`` + - ``graph_node_set_params`` + - + * - ``cuGraphNodeSetParams`` + - ``graph_node_set_params_v2`` + - + * - ``cuGraphReleaseUserObject`` + - ``graph_release_user_object`` + - + * - ``cuGraphRemoveDependencies`` + - ``graph_remove_dependencies_v2`` + - + * - ``cuGraphRetainUserObject`` + - ``graph_retain_user_object`` + - + * - ``cuGraphUpload`` + - ``graph_upload`` + - + * - ``cuGraphicsEGLRegisterImage`` + - ``graphics_egl_register_image`` + - + * - ``cuGraphicsGLRegisterBuffer`` + - ``graphics_gl_register_buffer`` + - + * - ``cuGraphicsGLRegisterImage`` + - ``graphics_gl_register_image`` + - + * - ``cuGraphicsMapResources`` + - ``graphics_map_resources`` + - + * - ``cuGraphicsResourceGetMappedEglFrame`` + - ``graphics_resource_get_mapped_egl_frame`` + - Output ``eglFrame`` is now an input: the caller supplies the address of a buffer to fill. + * - ``cuGraphicsResourceGetMappedMipmappedArray`` + - ``graphics_resource_get_mapped_mipmapped_array`` + - + * - ``cuGraphicsResourceGetMappedPointer`` + - ``graphics_resource_get_mapped_pointer_v2`` + - + * - ``cuGraphicsResourceSetMapFlags`` + - ``graphics_resource_set_map_flags_v2`` + - + * - ``cuGraphicsSubResourceGetMappedArray`` + - ``graphics_sub_resource_get_mapped_array`` + - + * - ``cuGraphicsUnmapResources`` + - ``graphics_unmap_resources`` + - + * - ``cuGraphicsUnregisterResource`` + - ``graphics_unregister_resource`` + - + * - ``cuGraphicsVDPAURegisterOutputSurface`` + - ``graphics_vdpau_register_output_surface`` + - + * - ``cuGraphicsVDPAURegisterVideoSurface`` + - ``graphics_vdpau_register_video_surface`` + - + * - ``cuGreenCtxCreate`` + - ``green_ctx_create`` + - + * - ``cuGreenCtxDestroy`` + - ``green_ctx_destroy`` + - + * - ``cuGreenCtxGetDevResource`` + - ``green_ctx_get_dev_resource`` + - + * - ``cuGreenCtxGetId`` + - ``green_ctx_get_id`` + - + * - ``cuGreenCtxRecordEvent`` + - ``green_ctx_record_event`` + - + * - ``cuGreenCtxStreamCreate`` + - ``green_ctx_stream_create`` + - + * - ``cuGreenCtxWaitEvent`` + - ``green_ctx_wait_event`` + - + * - ``cuImportExternalMemory`` + - ``import_external_memory`` + - + * - ``cuImportExternalSemaphore`` + - ``import_external_semaphore`` + - + * - ``cuInit`` + - ``init`` + - + * - ``cuIpcCloseMemHandle`` + - ``ipc_close_mem_handle`` + - + * - ``cuIpcGetEventHandle`` + - ``ipc_get_event_handle`` + - + * - ``cuIpcGetMemHandle`` + - ``ipc_get_mem_handle`` + - + * - ``cuIpcOpenEventHandle`` + - ``ipc_open_event_handle`` + - + * - ``cuIpcOpenMemHandle`` + - ``ipc_open_mem_handle_v2`` + - + * - ``cuKernelGetAttribute`` + - ``kernel_get_attribute`` + - + * - ``cuKernelGetFunction`` + - ``kernel_get_function`` + - + * - ``cuKernelGetLibrary`` + - ``kernel_get_library`` + - + * - ``cuKernelGetName`` + - ``kernel_get_name`` + - + * - ``cuKernelGetParamCount`` + - ``kernel_get_param_count`` + - + * - ``cuKernelGetParamInfo`` + - ``kernel_get_param_info`` + - + * - ``cuKernelSetAttribute`` + - ``kernel_set_attribute`` + - + * - ``cuKernelSetCacheConfig`` + - ``kernel_set_cache_config`` + - + * - ``cuLaunchCooperativeKernel`` + - ``launch_cooperative_kernel`` + - + * - ``cuLaunchCooperativeKernelMultiDevice`` + - ``launch_cooperative_kernel_multi_device`` + - + * - ``cuLaunchHostFunc`` + - ``launch_host_func`` + - + * - ``cuLaunchHostFunc`` + - ``launch_host_func_v2`` + - Parameters added: ``sync_mode``. + * - ``cuLaunchKernel`` + - ``launch_kernel`` + - + * - ``cuLaunchKernelEx`` + - ``launch_kernel_ex`` + - + * - ``cuLibraryEnumerateKernels`` + - ``library_enumerate_kernels`` + - Parameters removed: ``numKernels``. Returns an array of kernel handles. + * - ``cuLibraryGetGlobal`` + - ``library_get_global`` + - + * - ``cuLibraryGetKernel`` + - ``library_get_kernel`` + - + * - ``cuLibraryGetKernelCount`` + - ``library_get_kernel_count`` + - + * - ``cuLibraryGetManaged`` + - ``library_get_managed`` + - + * - ``cuLibraryGetModule`` + - ``library_get_module`` + - + * - ``cuLibraryGetUnifiedFunction`` + - ``library_get_unified_function`` + - + * - ``cuLibraryLoadData`` + - ``library_load_data`` + - + * - ``cuLibraryLoadFromFile`` + - ``library_load_from_file`` + - + * - ``cuLibraryUnload`` + - ``library_unload`` + - + * - ``cuLinkAddData`` + - ``link_add_data_v2`` + - + * - ``cuLinkAddFile`` + - ``link_add_file_v2`` + - + * - ``cuLinkComplete`` + - ``link_complete`` + - Returns the linked image as ``bytes``. ``sizeOut`` is no longer returned. + * - ``cuLinkCreate`` + - ``link_create_v2`` + - + * - ``cuLinkDestroy`` + - ``link_destroy`` + - + * - ``cuLogicalEndpointAddDevice`` + - ``logical_endpoint_add_device`` + - + * - ``cuLogicalEndpointBindAddr`` + - ``logical_endpoint_bind_addr`` + - + * - ``cuLogicalEndpointBindMem`` + - ``logical_endpoint_bind_mem`` + - + * - ``cuLogicalEndpointCreate`` + - ``logical_endpoint_create`` + - + * - ``cuLogicalEndpointDestroy`` + - ``logical_endpoint_destroy`` + - + * - ``cuLogicalEndpointExport`` + - ``logical_endpoint_export`` + - + * - ``cuLogicalEndpointGetLimits`` + - ``logical_endpoint_get_limits`` + - + * - ``cuLogicalEndpointIdRelease`` + - ``logical_endpoint_id_release`` + - + * - ``cuLogicalEndpointIdReserve`` + - ``logical_endpoint_id_reserve`` + - + * - ``cuLogicalEndpointImport`` + - ``logical_endpoint_import`` + - + * - ``cuLogicalEndpointQuery`` + - ``logical_endpoint_query`` + - + * - ``cuLogicalEndpointUnbind`` + - ``logical_endpoint_unbind`` + - + * - ``cuLogsCurrent`` + - ``logs_current`` + - + * - ``cuLogsDumpToFile`` + - ``logs_dump_to_file`` + - + * - ``cuLogsDumpToMemory`` + - ``logs_dump_to_memory`` + - + * - ``cuLogsRegisterCallback`` + - ``logs_register_callback`` + - + * - ``cuLogsUnregisterCallback`` + - ``logs_unregister_callback`` + - + * - ``cuMemAddressFree`` + - ``mem_address_free`` + - + * - ``cuMemAddressReserve`` + - ``mem_address_reserve`` + - + * - ``cuMemAdvise`` + - ``mem_advise_v2`` + - + * - ``cuMemAlloc`` + - ``mem_alloc_v2`` + - + * - ``cuMemAllocAsync`` + - ``mem_alloc_async`` + - + * - ``cuMemAllocFromPoolAsync`` + - ``mem_alloc_from_pool_async`` + - + * - ``cuMemAllocHost`` + - ``mem_alloc_host_v2`` + - + * - ``cuMemAllocManaged`` + - ``mem_alloc_managed`` + - + * - ``cuMemAllocPitch`` + - ``mem_alloc_pitch_v2`` + - + * - ``cuMemBatchDecompressAsync`` + - ``mem_batch_decompress_async`` + - + * - ``cuMemCreate`` + - ``mem_create`` + - + * - ``cuMemDiscardAndPrefetchBatchAsync`` + - ``mem_discard_and_prefetch_batch_async`` + - + * - ``cuMemDiscardBatchAsync`` + - ``mem_discard_batch_async`` + - + * - ``cuMemExportToShareableHandle`` + - ``mem_export_to_shareable_handle`` + - + * - ``cuMemFree`` + - ``mem_free_v2`` + - + * - ``cuMemFreeAsync`` + - ``mem_free_async`` + - + * - ``cuMemFreeHost`` + - ``mem_free_host`` + - + * - ``cuMemGetAccess`` + - ``mem_get_access`` + - + * - ``cuMemGetAddressRange`` + - ``mem_get_address_range_v2`` + - + * - ``cuMemGetAllocationGranularity`` + - ``mem_get_allocation_granularity`` + - + * - ``cuMemGetAllocationPropertiesFromHandle`` + - ``mem_get_allocation_properties_from_handle`` + - + * - ``cuMemGetDefaultMemPool`` + - ``mem_get_default_mem_pool`` + - + * - ``cuMemGetHandleForAddressRange`` + - ``mem_get_handle_for_address_range`` + - + * - ``cuMemGetInfo`` + - ``mem_get_info_v2`` + - + * - ``cuMemGetLocationInfo`` + - ``mem_get_location_info`` + - Parameters removed: ``location_out``. Returns the array of ``MemLocation_v1`` entries. + * - ``cuMemGetMemPool`` + - ``mem_get_mem_pool`` + - + * - ``cuMemHostAlloc`` + - ``mem_host_alloc`` + - + * - ``cuMemHostGetDevicePointer`` + - ``mem_host_get_device_pointer_v2`` + - + * - ``cuMemHostGetFlags`` + - ``mem_host_get_flags`` + - + * - ``cuMemHostRegister`` + - ``mem_host_register_v2`` + - + * - ``cuMemHostUnregister`` + - ``mem_host_unregister`` + - + * - ``cuMemImportFromShareableHandle`` + - ``mem_import_from_shareable_handle`` + - + * - ``cuMemMap`` + - ``mem_map`` + - + * - ``cuMemMapArrayAsync`` + - ``mem_map_array_async`` + - + * - ``cuMemPoolCreate`` + - ``mem_pool_create`` + - + * - ``cuMemPoolDestroy`` + - ``mem_pool_destroy`` + - + * - ``cuMemPoolExportPointer`` + - ``mem_pool_export_pointer`` + - + * - ``cuMemPoolExportToShareableHandle`` + - ``mem_pool_export_to_shareable_handle`` + - + * - ``cuMemPoolGetAccess`` + - ``mem_pool_get_access`` + - + * - ``cuMemPoolGetAttribute`` + - ``mem_pool_get_attribute`` + - + * - ``cuMemPoolImportFromShareableHandle`` + - ``mem_pool_import_from_shareable_handle`` + - + * - ``cuMemPoolImportPointer`` + - ``mem_pool_import_pointer`` + - + * - ``cuMemPoolSetAccess`` + - ``mem_pool_set_access`` + - + * - ``cuMemPoolSetAttribute`` + - ``mem_pool_set_attribute`` + - + * - ``cuMemPoolTrimTo`` + - ``mem_pool_trim_to`` + - + * - ``cuMemPrefetchAsync`` + - ``mem_prefetch_async_v2`` + - + * - ``cuMemPrefetchBatchAsync`` + - ``mem_prefetch_batch_async`` + - + * - ``cuMemRangeGetAttribute`` + - ``mem_range_get_attribute`` + - + * - ``cuMemRangeGetAttributes`` + - ``mem_range_get_attributes`` + - Parameters removed: ``numAttributes``. + * - ``cuMemRelease`` + - ``mem_release`` + - + * - ``cuMemRetainAllocationHandle`` + - ``mem_retain_allocation_handle`` + - + * - ``cuMemSetAccess`` + - ``mem_set_access`` + - + * - ``cuMemSetMemPool`` + - ``mem_set_mem_pool`` + - + * - ``cuMemUnmap`` + - ``mem_unmap`` + - + * - ``cuMemcpy`` + - ``cu_memcpy`` + - + * - ``cuMemcpy2D`` + - ``memcpy_2d_v2`` + - + * - ``cuMemcpy2DAsync`` + - ``memcpy_2d_async_v2`` + - + * - ``cuMemcpy2DUnaligned`` + - ``memcpy_2d_unaligned_v2`` + - + * - ``cuMemcpy3D`` + - ``memcpy_3d_v2`` + - + * - ``cuMemcpy3DAsync`` + - ``memcpy_3d_async_v2`` + - + * - ``cuMemcpy3DBatchAsync`` + - ``memcpy_3d_batch_async_v2`` + - + * - ``cuMemcpy3DPeer`` + - ``memcpy_3d_peer`` + - + * - ``cuMemcpy3DPeerAsync`` + - ``memcpy_3d_peer_async`` + - + * - ``cuMemcpy3DWithAttributesAsync`` + - ``memcpy_3d_with_attributes_async`` + - + * - ``cuMemcpyAsync`` + - ``memcpy_async`` + - + * - ``cuMemcpyAtoA`` + - ``memcpy_atoa_v2`` + - + * - ``cuMemcpyAtoD`` + - ``memcpy_atod_v2`` + - + * - ``cuMemcpyAtoH`` + - ``memcpy_atoh_v2`` + - + * - ``cuMemcpyAtoHAsync`` + - ``memcpy_atoh_async_v2`` + - + * - ``cuMemcpyBatchAsync`` + - ``memcpy_batch_async`` + - Parameters removed: ``count``, ``numAttrs``. + * - ``cuMemcpyBatchAsync`` + - ``memcpy_batch_async_v2`` + - + * - ``cuMemcpyDtoA`` + - ``memcpy_dtoa_v2`` + - + * - ``cuMemcpyDtoD`` + - ``memcpy_dtod_v2`` + - + * - ``cuMemcpyDtoDAsync`` + - ``memcpy_dtod_async_v2`` + - + * - ``cuMemcpyDtoH`` + - ``memcpy_dtoh_v2`` + - + * - ``cuMemcpyDtoHAsync`` + - ``memcpy_dtoh_async_v2`` + - + * - ``cuMemcpyHtoA`` + - ``memcpy_htoa_v2`` + - + * - ``cuMemcpyHtoAAsync`` + - ``memcpy_htoa_async_v2`` + - + * - ``cuMemcpyHtoD`` + - ``memcpy_htod_v2`` + - + * - ``cuMemcpyHtoDAsync`` + - ``memcpy_htod_async_v2`` + - + * - ``cuMemcpyPeer`` + - ``memcpy_peer`` + - + * - ``cuMemcpyPeerAsync`` + - ``memcpy_peer_async`` + - + * - ``cuMemcpyWithAttributesAsync`` + - ``memcpy_with_attributes_async`` + - + * - ``cuMemsetD16`` + - ``memset_d16_v2`` + - + * - ``cuMemsetD16Async`` + - ``memset_d16_async`` + - + * - ``cuMemsetD2D16`` + - ``memset_d2d16_v2`` + - + * - ``cuMemsetD2D16Async`` + - ``memset_d2d16_async`` + - + * - ``cuMemsetD2D32`` + - ``memset_d2d32_v2`` + - + * - ``cuMemsetD2D32Async`` + - ``memset_d2d32_async`` + - + * - ``cuMemsetD2D8`` + - ``memset_d2d8_v2`` + - + * - ``cuMemsetD2D8Async`` + - ``memset_d2d8_async`` + - + * - ``cuMemsetD32`` + - ``memset_d32_v2`` + - + * - ``cuMemsetD32Async`` + - ``memset_d32_async`` + - + * - ``cuMemsetD8`` + - ``memset_d8_v2`` + - + * - ``cuMemsetD8Async`` + - ``memset_d8_async`` + - + * - ``cuMipmappedArrayCreate`` + - ``mipmapped_array_create`` + - + * - ``cuMipmappedArrayDestroy`` + - ``mipmapped_array_destroy`` + - + * - ``cuMipmappedArrayGetLevel`` + - ``mipmapped_array_get_level`` + - + * - ``cuMipmappedArrayGetMemoryRequirements`` + - ``mipmapped_array_get_memory_requirements`` + - + * - ``cuMipmappedArrayGetSparseProperties`` + - ``mipmapped_array_get_sparse_properties`` + - + * - ``cuModuleEnumerateFunctions`` + - ``module_enumerate_functions`` + - Parameters removed: ``numFunctions``. Returns an array of function handles. + * - ``cuModuleGetFunction`` + - ``module_get_function`` + - + * - ``cuModuleGetFunctionCount`` + - ``module_get_function_count`` + - + * - ``cuModuleGetGlobal`` + - ``module_get_global_v2`` + - + * - ``cuModuleGetLoadingMode`` + - ``module_get_loading_mode`` + - + * - ``cuModuleLoad`` + - ``module_load`` + - + * - ``cuModuleLoadData`` + - ``module_load_data`` + - + * - ``cuModuleLoadDataEx`` + - ``module_load_data_ex`` + - + * - ``cuModuleLoadFatBinary`` + - ``module_load_fat_binary`` + - + * - ``cuModuleUnload`` + - ``module_unload`` + - + * - ``cuMulticastAddDevice`` + - ``multicast_add_device`` + - + * - ``cuMulticastBindAddr`` + - ``multicast_bind_addr`` + - + * - ``cuMulticastBindAddr`` + - ``multicast_bind_addr_v2`` + - Parameters added: ``dev``. + * - ``cuMulticastBindMem`` + - ``multicast_bind_mem`` + - + * - ``cuMulticastBindMem`` + - ``multicast_bind_mem_v2`` + - Parameters added: ``dev``. + * - ``cuMulticastCreate`` + - ``multicast_create`` + - + * - ``cuMulticastGetGranularity`` + - ``multicast_get_granularity`` + - + * - ``cuMulticastUnbind`` + - ``multicast_unbind`` + - + * - ``cuOccupancyAvailableDynamicSMemPerBlock`` + - ``occupancy_available_dynamic_smem_per_block`` + - + * - ``cuOccupancyMaxActiveBlocksPerMultiprocessor`` + - ``occupancy_max_active_blocks_per_multiprocessor`` + - + * - ``cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags`` + - ``occupancy_max_active_blocks_per_multiprocessor_with_flags`` + - + * - ``cuOccupancyMaxActiveClusters`` + - ``occupancy_max_active_clusters`` + - + * - ``cuOccupancyMaxPotentialBlockSize`` + - ``occupancy_max_potential_block_size`` + - + * - ``cuOccupancyMaxPotentialBlockSizeWithFlags`` + - ``occupancy_max_potential_block_size_with_flags`` + - + * - ``cuOccupancyMaxPotentialClusterSize`` + - ``occupancy_max_potential_cluster_size`` + - + * - ``cuPointerGetAttribute`` + - ``pointer_get_attribute`` + - + * - ``cuPointerGetAttributes`` + - ``pointer_get_attributes`` + - Parameters removed: ``numAttributes``. + * - ``cuPointerSetAttribute`` + - ``pointer_set_attribute`` + - + * - ``cuProfilerStart`` + - ``profiler_start`` + - + * - ``cuProfilerStop`` + - ``profiler_stop`` + - + * - ``cuSignalExternalSemaphoresAsync`` + - ``signal_external_semaphores_async`` + - + * - ``cuStreamAddCallback`` + - ``stream_add_callback`` + - + * - ``cuStreamAttachMemAsync`` + - ``stream_attach_mem_async`` + - + * - ``cuStreamBatchMemOp`` + - ``stream_batch_mem_op_v2`` + - + * - ``cuStreamBeginCapture`` + - ``stream_begin_capture_v2`` + - + * - ``cuStreamBeginCaptureToCig`` + - ``stream_begin_capture_to_cig`` + - + * - ``cuStreamBeginCaptureToGraph`` + - ``stream_begin_capture_to_graph`` + - + * - ``cuStreamBeginRecaptureToGraph`` + - ``stream_begin_recapture_to_graph`` + - + * - ``cuStreamCopyAttributes`` + - ``stream_copy_attributes`` + - + * - ``cuStreamCreate`` + - ``stream_create`` + - + * - ``cuStreamCreateWithPriority`` + - ``stream_create_with_priority`` + - + * - ``cuStreamDestroy`` + - ``stream_destroy_v2`` + - + * - ``cuStreamEndCapture`` + - ``stream_end_capture`` + - + * - ``cuStreamEndCaptureToCig`` + - ``stream_end_capture_to_cig`` + - + * - ``cuStreamGetAttribute`` + - ``stream_get_attribute`` + - + * - ``cuStreamGetCaptureInfo`` + - ``stream_get_capture_info_v2`` + - Returns a 4-tuple. The dependency count is no longer returned and edge data is not included. + * - ``cuStreamGetCaptureInfo`` + - ``stream_get_capture_info_v3`` + - Returns a 5-tuple. The dependency count is no longer returned. + * - ``cuStreamGetCtx`` + - ``stream_get_ctx`` + - + * - ``cuStreamGetCtx`` + - ``stream_get_ctx_v2`` + - Returns a 2-tuple ``(ctx, green_ctx)``. The legacy function returned only the context. + * - ``cuStreamGetDevResource`` + - ``stream_get_dev_resource`` + - + * - ``cuStreamGetDevice`` + - ``stream_get_device`` + - + * - ``cuStreamGetFlags`` + - ``stream_get_flags`` + - + * - ``cuStreamGetGreenCtx`` + - ``stream_get_green_ctx`` + - + * - ``cuStreamGetId`` + - ``stream_get_id`` + - + * - ``cuStreamGetPriority`` + - ``stream_get_priority`` + - + * - ``cuStreamIsCapturing`` + - ``stream_is_capturing`` + - + * - ``cuStreamQuery`` + - ``stream_query`` + - + * - ``cuStreamSetAttribute`` + - ``stream_set_attribute`` + - + * - ``cuStreamSynchronize`` + - ``stream_synchronize`` + - + * - ``cuStreamUpdateCaptureDependencies`` + - ``stream_update_capture_dependencies_v2`` + - + * - ``cuStreamWaitEvent`` + - ``stream_wait_event`` + - + * - ``cuStreamWaitValue32`` + - ``stream_wait_value32_v2`` + - + * - ``cuStreamWaitValue64`` + - ``stream_wait_value64_v2`` + - + * - ``cuStreamWriteValue32`` + - ``stream_write_value32_v2`` + - + * - ``cuStreamWriteValue64`` + - ``stream_write_value64_v2`` + - + * - ``cuSurfObjectCreate`` + - ``surf_object_create`` + - + * - ``cuSurfObjectDestroy`` + - ``surf_object_destroy`` + - + * - ``cuSurfObjectGetResourceDesc`` + - ``surf_object_get_resource_desc`` + - + * - ``cuTensorMapEncodeIm2col`` + - ``tensor_map_encode_im2col`` + - + * - ``cuTensorMapEncodeIm2colWide`` + - ``tensor_map_encode_im2col_wide`` + - + * - ``cuTensorMapEncodeTiled`` + - ``tensor_map_encode_tiled`` + - + * - ``cuTensorMapReplaceAddress`` + - ``tensor_map_replace_address`` + - + * - ``cuTexObjectCreate`` + - ``tex_object_create`` + - + * - ``cuTexObjectDestroy`` + - ``tex_object_destroy`` + - + * - ``cuTexObjectGetResourceDesc`` + - ``tex_object_get_resource_desc`` + - + * - ``cuTexObjectGetResourceViewDesc`` + - ``tex_object_get_resource_view_desc`` + - + * - ``cuTexObjectGetTextureDesc`` + - ``tex_object_get_texture_desc`` + - + * - ``cuTexRefSetAddressMode`` + - ``tex_ref_set_address_mode`` + - + * - ``cuTexRefSetFilterMode`` + - ``tex_ref_set_filter_mode`` + - + * - ``cuTexRefSetMipmapFilterMode`` + - ``tex_ref_set_mipmap_filter_mode`` + - + * - ``cuThreadExchangeStreamCaptureMode`` + - ``thread_exchange_stream_capture_mode`` + - + * - ``cuUserObjectCreate`` + - ``user_object_create`` + - + * - ``cuUserObjectRelease`` + - ``user_object_release`` + - + * - ``cuUserObjectRetain`` + - ``user_object_retain`` + - + * - ``cuVDPAUCtxCreate`` + - ``vdpau_ctx_create_v2`` + - + * - ``cuVDPAUGetDevice`` + - ``vdpau_get_device`` + - + * - ``cuWaitExternalSemaphoresAsync`` + - ``wait_external_semaphores_async`` + - + * - ``cuDeviceComputeCapability`` + - ``device_compute_capability`` + - + * - ``cuDeviceGetProperties`` + - ``device_get_properties`` + - + * - ``cuLaunchCooperativeKernelMultiDevice`` + - ``launch_cooperative_kernel_multi_device`` + - + * - *(none)* + - ``graph_instantiate_with_flags`` + - Legacy exposes this C function as ``cuGraphInstantiate``. + +Deprecated functions +-------------------- + +These functions are deprecated in the CUDA driver API but are still available in the new module. The general rules above apply. Texture and surface references are handles, so they are ``int`` values like the other handle types. + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - Legacy + - New + - Notes + * - ``cuCtxAttach`` + - ``ctx_attach`` + - + * - ``cuCtxDetach`` + - ``ctx_detach`` + - + * - ``cuCtxGetSharedMemConfig`` + - ``ctx_get_shared_mem_config`` + - + * - ``cuCtxSetSharedMemConfig`` + - ``ctx_set_shared_mem_config`` + - + * - ``cuFuncSetBlockShape`` + - ``func_set_block_shape`` + - + * - ``cuFuncSetSharedMemConfig`` + - ``func_set_shared_mem_config`` + - + * - ``cuFuncSetSharedSize`` + - ``func_set_shared_size`` + - + * - ``cuLaunch`` + - ``launch`` + - + * - ``cuLaunchGrid`` + - ``launch_grid`` + - + * - ``cuLaunchGridAsync`` + - ``launch_grid_async`` + - + * - ``cuModuleGetSurfRef`` + - ``module_get_surf_ref`` + - + * - ``cuModuleGetTexRef`` + - ``module_get_tex_ref`` + - + * - ``cuParamSetSize`` + - ``param_set_size`` + - + * - ``cuParamSetTexRef`` + - ``param_set_tex_ref`` + - + * - ``cuParamSetf`` + - ``param_setf`` + - + * - ``cuParamSeti`` + - ``param_seti`` + - + * - ``cuParamSetv`` + - ``param_setv`` + - + * - ``cuSurfRefGetArray`` + - ``surf_ref_get_array`` + - + * - ``cuSurfRefSetArray`` + - ``surf_ref_set_array`` + - + * - ``cuTexRefCreate`` + - ``tex_ref_create`` + - + * - ``cuTexRefDestroy`` + - ``tex_ref_destroy`` + - + * - ``cuTexRefGetAddress`` + - ``tex_ref_get_address_v2`` + - + * - ``cuTexRefGetAddressMode`` + - ``tex_ref_get_address_mode`` + - + * - ``cuTexRefGetArray`` + - ``tex_ref_get_array`` + - + * - ``cuTexRefGetBorderColor`` + - ``tex_ref_get_border_color`` + - + * - ``cuTexRefGetFilterMode`` + - ``tex_ref_get_filter_mode`` + - + * - ``cuTexRefGetFlags`` + - ``tex_ref_get_flags`` + - + * - ``cuTexRefGetFormat`` + - ``tex_ref_get_format`` + - + * - ``cuTexRefGetMaxAnisotropy`` + - ``tex_ref_get_max_anisotropy`` + - + * - ``cuTexRefGetMipmapFilterMode`` + - ``tex_ref_get_mipmap_filter_mode`` + - + * - ``cuTexRefGetMipmapLevelBias`` + - ``tex_ref_get_mipmap_level_bias`` + - + * - ``cuTexRefGetMipmapLevelClamp`` + - ``tex_ref_get_mipmap_level_clamp`` + - + * - ``cuTexRefGetMipmappedArray`` + - ``tex_ref_get_mipmapped_array`` + - + * - ``cuTexRefSetAddress`` + - ``tex_ref_set_address_v2`` + - + * - ``cuTexRefSetAddress2D`` + - ``tex_ref_set_address2d_v3`` + - + * - ``cuTexRefSetAddressMode`` + - ``tex_ref_set_address_mode`` + - + * - ``cuTexRefSetArray`` + - ``tex_ref_set_array`` + - + * - ``cuTexRefSetBorderColor`` + - ``tex_ref_set_border_color`` + - + * - ``cuTexRefSetFilterMode`` + - ``tex_ref_set_filter_mode`` + - + * - ``cuTexRefSetFlags`` + - ``tex_ref_set_flags`` + - + * - ``cuTexRefSetFormat`` + - ``tex_ref_set_format`` + - + * - ``cuTexRefSetMaxAnisotropy`` + - ``tex_ref_set_max_anisotropy`` + - + * - ``cuTexRefSetMipmapFilterMode`` + - ``tex_ref_set_mipmap_filter_mode`` + - + * - ``cuTexRefSetMipmapLevelBias`` + - ``tex_ref_set_mipmap_level_bias`` + - + * - ``cuTexRefSetMipmapLevelClamp`` + - ``tex_ref_set_mipmap_level_clamp`` + - + * - ``cuTexRefSetMipmappedArray`` + - ``tex_ref_set_mipmapped_array`` + - + +Classes +------- + +The legacy module exposes several aliases for the same class (``X``, ``X_st``, ``X_v1``). Only one legacy name per class is shown. Handle types such as ``CUcontext`` and ``CUstream`` have no class in the new module (see above). Each class is followed by its renamed members. Members that are not listed keep their name apart from the general rename to ``snake_case``. + +.. rubric:: ``CUaccessPolicyWindow_v1`` -> ``AccessPolicyWindow_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``hitProp`` + - ``hit_prop`` + * - ``hitRatio`` + - ``hit_ratio`` + * - ``missProp`` + - ``miss_prop`` + +.. rubric:: ``CUarrayMapInfo_v1`` -> ``ArrayMapInfo_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``deviceBitMask`` + - ``device_bit_mask`` + * - ``flags`` + - ``flags_`` + * - ``memHandle`` + - ``mem_handle`` + * - ``memHandleType`` + - ``mem_handle_type`` + * - ``memOperationType`` + - ``mem_operation_type`` + * - ``resourceType`` + - ``resource_type`` + * - ``subresourceType`` + - ``subresource_type`` + +.. rubric:: ``CUasyncNotificationInfo`` -> ``AsyncNotificationInfo`` + +.. rubric:: ``CUcheckpointCheckpointArgs`` -> ``CheckpointCheckpointArgs`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``customStorageInfo_out`` + - ``custom_storage_info_out`` + +.. rubric:: ``CUcheckpointGpuPair`` -> ``CheckpointGpuPair`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``newUuid`` + - ``new_uuid`` + * - ``oldUuid`` + - ``old_uuid`` + +.. rubric:: ``CUcheckpointLockArgs`` -> ``CheckpointLockArgs`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``timeoutMs`` + - ``timeout_ms`` + +.. rubric:: ``CUcheckpointRestoreArgs`` -> ``CheckpointRestoreArgs`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``customStorageInfo_out`` + - ``custom_storage_info_out`` + * - ``gpuPairs`` + - ``gpu_pairs`` + * - ``gpuPairsCount`` + - ``gpu_pairs_count`` + +.. rubric:: ``CUcheckpointUnlockArgs`` -> ``CheckpointUnlockArgs`` + +.. rubric:: ``CUcliqueInfo`` -> ``CliqueInfo`` + +.. rubric:: ``CUctxCigParam`` -> ``CtxCigParam`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``sharedData`` + - ``shared_data`` + * - ``sharedDataType`` + - ``shared_data_type`` + +.. rubric:: ``CUctxCreateParams`` -> ``CtxCreateParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``cigParams`` + - ``cig_params`` + * - ``execAffinityParams`` + - ``exec_affinity_params`` + * - ``numExecAffinityParams`` + - ``num_exec_affinity_params`` + +.. rubric:: ``CUDA_ARRAY3D_DESCRIPTOR_v2`` -> ``Array3dDescriptor_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``Depth`` + - ``depth`` + * - ``Flags`` + - ``flags_`` + * - ``Format`` + - ``format`` + * - ``Height`` + - ``height`` + * - ``NumChannels`` + - ``num_channels`` + * - ``Width`` + - ``width`` + +.. rubric:: ``CUDA_ARRAY_DESCRIPTOR_v2`` -> ``ArrayDescriptor_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``Format`` + - ``format`` + * - ``Height`` + - ``height`` + * - ``NumChannels`` + - ``num_channels`` + * - ``Width`` + - ``width`` + +.. rubric:: ``CUDA_ARRAY_MEMORY_REQUIREMENTS_v1`` -> ``ArrayMemoryRequirements_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``size`` + - ``size_`` + +.. rubric:: ``CUDA_ARRAY_SPARSE_PROPERTIES_v1`` -> ``ArraySparseProperties_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``miptailFirstLevel`` + - ``miptail_first_level`` + * - ``miptailSize`` + - ``miptail_size`` + * - ``tileExtent`` + - ``tile_extent`` + +.. rubric:: ``CUDA_BATCH_MEM_OP_NODE_PARAMS_v1`` -> ``BatchMemOpNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``paramArray`` + - ``param_array`` + +.. rubric:: ``CUDA_BATCH_MEM_OP_NODE_PARAMS_v2`` -> ``BatchMemOpNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``paramArray`` + - ``param_array`` + +.. rubric:: ``CUDA_CHILD_GRAPH_NODE_PARAMS`` -> ``ChildGraphNodeParams`` + +.. rubric:: ``CUDA_CONDITIONAL_NODE_PARAMS`` -> ``ConditionalNodeParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``phGraph_out`` + - ``ph_graph_out`` + * - ``size`` + - ``size_`` + +.. rubric:: ``CUDA_EVENT_RECORD_NODE_PARAMS`` -> ``EventRecordNodeParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``gCtx`` + - ``g_ctx`` + +.. rubric:: ``CUDA_EVENT_WAIT_NODE_PARAMS`` -> ``EventWaitNodeParams`` + +.. rubric:: ``CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1`` -> ``ExtSemSignalNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``extSemArray`` + - ``ext_sem_array`` + * - ``numExtSems`` + - ``num_ext_sems`` + * - ``paramsArray`` + - ``params_array`` + +.. rubric:: ``CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v2`` -> ``ExtSemSignalNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``extSemArray`` + - ``ext_sem_array`` + * - ``gCtx`` + - ``g_ctx`` + * - ``numExtSems`` + - ``num_ext_sems`` + * - ``paramsArray`` + - ``params_array`` + +.. rubric:: ``CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1`` -> ``ExtSemWaitNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``extSemArray`` + - ``ext_sem_array`` + * - ``numExtSems`` + - ``num_ext_sems`` + * - ``paramsArray`` + - ``params_array`` + +.. rubric:: ``CUDA_EXT_SEM_WAIT_NODE_PARAMS_v2`` -> ``ExtSemWaitNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``extSemArray`` + - ``ext_sem_array`` + * - ``gCtx`` + - ``g_ctx`` + * - ``numExtSems`` + - ``num_ext_sems`` + * - ``paramsArray`` + - ``params_array`` + +.. rubric:: ``CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1`` -> ``ExternalMemoryBufferDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``size`` + - ``size_`` + +.. rubric:: ``CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1`` -> ``ExternalMemoryHandleDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``size`` + - ``size_`` + +.. rubric:: ``CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1`` -> ``ExternalMemoryMipmappedArrayDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``arrayDesc`` + - ``array_desc`` + * - ``numLevels`` + - ``num_levels`` + +.. rubric:: ``CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1`` -> ``ExternalSemaphoreHandleDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1`` -> ``ExternalSemaphoreSignalParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1`` -> ``ExternalSemaphoreWaitParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUDA_GRAPH_INSTANTIATE_PARAMS`` -> ``GraphInstantiateParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``hErrNode_out`` + - ``h_err_node_out`` + * - ``hUploadStream`` + - ``h_upload_stream`` + +.. rubric:: ``CUDA_HOST_NODE_PARAMS_v1`` -> ``HostNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``userData`` + - ``user_data`` + +.. rubric:: ``CUDA_HOST_NODE_PARAMS_v2`` -> ``HostNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``gCtx`` + - ``g_ctx`` + * - ``syncMode`` + - ``sync_mode`` + * - ``userData`` + - ``user_data`` + +.. rubric:: ``CUDA_KERNEL_NODE_PARAMS`` -> ``KernelNodeParams_v3`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``blockDimX`` + - ``block_dim_x`` + * - ``blockDimY`` + - ``block_dim_y`` + * - ``blockDimZ`` + - ``block_dim_z`` + * - ``gridDimX`` + - ``grid_dim_x`` + * - ``gridDimY`` + - ``grid_dim_y`` + * - ``gridDimZ`` + - ``grid_dim_z`` + * - ``kernelParams`` + - ``kernel_params`` + * - ``sharedMemBytes`` + - ``shared_mem_bytes`` + +.. rubric:: ``CUDA_KERNEL_NODE_PARAMS_v2`` -> ``KernelNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``blockDimX`` + - ``block_dim_x`` + * - ``blockDimY`` + - ``block_dim_y`` + * - ``blockDimZ`` + - ``block_dim_z`` + * - ``gridDimX`` + - ``grid_dim_x`` + * - ``gridDimY`` + - ``grid_dim_y`` + * - ``gridDimZ`` + - ``grid_dim_z`` + * - ``kernelParams`` + - ``kernel_params`` + * - ``sharedMemBytes`` + - ``shared_mem_bytes`` + +.. rubric:: ``CUDA_MEM_ALLOC_NODE_PARAMS_v1`` -> ``MemAllocNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``accessDescCount`` + - ``access_desc_count`` + * - ``accessDescs`` + - ``access_descs`` + * - ``poolProps`` + - ``pool_props`` + +.. rubric:: ``CUDA_MEM_ALLOC_NODE_PARAMS_v2`` -> ``MemAllocNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``accessDescCount`` + - ``access_desc_count`` + * - ``accessDescs`` + - ``access_descs`` + * - ``poolProps`` + - ``pool_props`` + +.. rubric:: ``CUDA_MEM_FREE_NODE_PARAMS`` -> ``MemFreeNodeParams`` + +.. rubric:: ``CUDA_MEMCPY2D_v2`` -> ``MemCpy2d_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``Height`` + - ``height`` + * - ``WidthInBytes`` + - ``width_in_bytes`` + * - ``dstArray`` + - ``dst_array`` + * - ``dstDevice`` + - ``dst_device`` + * - ``dstHost`` + - ``dst_host`` + * - ``dstMemoryType`` + - ``dst_memory_type`` + * - ``dstPitch`` + - ``dst_pitch`` + * - ``dstXInBytes`` + - ``dst_x_in_bytes`` + * - ``dstY`` + - ``dst_y`` + * - ``srcArray`` + - ``src_array`` + * - ``srcDevice`` + - ``src_device`` + * - ``srcHost`` + - ``src_host`` + * - ``srcMemoryType`` + - ``src_memory_type`` + * - ``srcPitch`` + - ``src_pitch`` + * - ``srcXInBytes`` + - ``src_x_in_bytes`` + * - ``srcY`` + - ``src_y`` + +.. rubric:: ``CUDA_MEMCPY3D_BATCH_OP_v1`` -> ``MemCpy3dBatchOp_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``srcAccessOrder`` + - ``src_access_order`` + +.. rubric:: ``CUDA_MEMCPY3D_PEER_v1`` -> ``MemCpy3dPeer_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``Depth`` + - ``depth`` + * - ``Height`` + - ``height`` + * - ``WidthInBytes`` + - ``width_in_bytes`` + * - ``dstArray`` + - ``dst_array`` + * - ``dstContext`` + - ``dst_context`` + * - ``dstDevice`` + - ``dst_device`` + * - ``dstHeight`` + - ``dst_height`` + * - ``dstHost`` + - ``dst_host`` + * - ``dstLOD`` + - ``dst_lod`` + * - ``dstMemoryType`` + - ``dst_memory_type`` + * - ``dstPitch`` + - ``dst_pitch`` + * - ``dstXInBytes`` + - ``dst_x_in_bytes`` + * - ``dstY`` + - ``dst_y`` + * - ``dstZ`` + - ``dst_z`` + * - ``srcArray`` + - ``src_array`` + * - ``srcContext`` + - ``src_context`` + * - ``srcDevice`` + - ``src_device`` + * - ``srcHeight`` + - ``src_height`` + * - ``srcHost`` + - ``src_host`` + * - ``srcLOD`` + - ``src_lod`` + * - ``srcMemoryType`` + - ``src_memory_type`` + * - ``srcPitch`` + - ``src_pitch`` + * - ``srcXInBytes`` + - ``src_x_in_bytes`` + * - ``srcY`` + - ``src_y`` + * - ``srcZ`` + - ``src_z`` + +.. rubric:: ``CUDA_MEMCPY3D_v2`` -> ``MemCpy3d_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``Depth`` + - ``depth`` + * - ``Height`` + - ``height`` + * - ``WidthInBytes`` + - ``width_in_bytes`` + * - ``dstArray`` + - ``dst_array`` + * - ``dstDevice`` + - ``dst_device`` + * - ``dstHeight`` + - ``dst_height`` + * - ``dstHost`` + - ``dst_host`` + * - ``dstLOD`` + - ``dst_lod`` + * - ``dstMemoryType`` + - ``dst_memory_type`` + * - ``dstPitch`` + - ``dst_pitch`` + * - ``dstXInBytes`` + - ``dst_x_in_bytes`` + * - ``dstY`` + - ``dst_y`` + * - ``dstZ`` + - ``dst_z`` + * - ``srcArray`` + - ``src_array`` + * - ``srcDevice`` + - ``src_device`` + * - ``srcHeight`` + - ``src_height`` + * - ``srcHost`` + - ``src_host`` + * - ``srcLOD`` + - ``src_lod`` + * - ``srcMemoryType`` + - ``src_memory_type`` + * - ``srcPitch`` + - ``src_pitch`` + * - ``srcXInBytes`` + - ``src_x_in_bytes`` + * - ``srcY`` + - ``src_y`` + * - ``srcZ`` + - ``src_z`` + +.. rubric:: ``CUDA_MEMCPY_NODE_PARAMS`` -> ``MemCpyNodeParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``copyCtx`` + - ``copy_ctx`` + * - ``copyParams`` + - ``copy_params`` + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUDA_MEMSET_NODE_PARAMS_v1`` -> ``MemSetNodeParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``elementSize`` + - ``element_size`` + +.. rubric:: ``CUDA_MEMSET_NODE_PARAMS_v2`` -> ``MemSetNodeParams_v2`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``elementSize`` + - ``element_size`` + +.. rubric:: ``CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1`` -> ``PointerAttributeP2PTokens_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``p2pToken`` + - ``p2p_token`` + * - ``vaSpaceToken`` + - ``va_space_token`` + +.. rubric:: ``CUDA_RESOURCE_DESC_v1`` -> ``ResourceDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``resType`` + - ``res_type`` + +.. rubric:: ``CUDA_RESOURCE_VIEW_DESC_v1`` -> ``ResourceViewDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``firstLayer`` + - ``first_layer`` + * - ``firstMipmapLevel`` + - ``first_mipmap_level`` + * - ``lastLayer`` + - ``last_layer`` + * - ``lastMipmapLevel`` + - ``last_mipmap_level`` + +.. rubric:: ``CUDA_TEXTURE_DESC_v1`` -> ``TextureDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``addressMode`` + - ``address_mode`` + * - ``borderColor`` + - ``border_color`` + * - ``filterMode`` + - ``filter_mode`` + * - ``flags`` + - ``flags_`` + * - ``maxAnisotropy`` + - ``max_anisotropy`` + * - ``maxMipmapLevelClamp`` + - ``max_mipmap_level_clamp`` + * - ``minMipmapLevelClamp`` + - ``min_mipmap_level_clamp`` + * - ``mipmapFilterMode`` + - ``mipmap_filter_mode`` + * - ``mipmapLevelBias`` + - ``mipmap_level_bias`` + +.. rubric:: ``CUdevResource_v1`` -> ``DevResource_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``nextResource`` + - ``next_resource`` + * - ``wqConfig`` + - ``wq_config`` + +.. rubric:: ``CUdevSmResource`` -> ``DevSmResource`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``localityDomainId`` + - ``locality_domain_id`` + * - ``minSmPartitionSize`` + - ``min_sm_partition_size`` + * - ``smCoscheduledAlignment`` + - ``sm_coscheduled_alignment`` + * - ``smCount`` + - ``sm_count`` + +.. rubric:: ``CUdevWorkqueueConfigResource`` -> ``DevWorkqueueConfigResource`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``device`` + - ``device_`` + * - ``sharingScope`` + - ``sharing_scope`` + * - ``wqConcurrencyLimit`` + - ``wq_concurrency_limit`` + +.. rubric:: ``CUdevWorkqueueResource`` -> ``DevWorkqueueResource`` + +.. rubric:: ``CUexecAffinityParam_v1`` -> ``ExecAffinityParam_v1`` + +.. rubric:: ``CUexecAffinitySmCount_v1`` -> ``ExecAffinitySmCount_v1`` + +.. rubric:: ``CUextent3D_v1`` -> ``Extent3D_v1`` + +.. rubric:: ``CUgraphEdgeData`` -> ``GraphEdgeData`` + +.. rubric:: ``CUgraphExecUpdateResultInfo_v1`` -> ``GraphExecUpdateResultInfo_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``errorFromNode`` + - ``error_from_node`` + * - ``errorNode`` + - ``error_node`` + +.. rubric:: ``CUgraphNodeParams`` -> ``GraphNodeParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``asBytes`` + - ``as_bytes`` + * - ``eventRecord`` + - ``event_record`` + * - ``eventWait`` + - ``event_wait`` + * - ``extSemSignal`` + - ``ext_sem_signal`` + * - ``extSemWait`` + - ``ext_sem_wait`` + * - ``memOp`` + - ``mem_op`` + +.. rubric:: ``CUipcEventHandle_v1`` -> ``IpcEventHandle_v1`` + +.. rubric:: ``CUipcMemHandle_v1`` -> ``IpcMemHandle_v1`` + +.. rubric:: ``CUlaunchAttribute`` -> ``LaunchAttribute`` + +.. rubric:: ``CUlaunchAttributeValue`` -> ``LaunchAttributeValue`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``accessPolicyWindow`` + - ``access_policy_window`` + * - ``clusterDim`` + - ``cluster_dim`` + * - ``clusterSchedulingPolicyPreference`` + - ``cluster_scheduling_policy_preference`` + * - ``deviceUpdatableKernelNode`` + - ``device_updatable_kernel_node`` + * - ``launchCompletionEvent`` + - ``launch_completion_event`` + * - ``memSyncDomain`` + - ``mem_sync_domain`` + * - ``memSyncDomainMap`` + - ``mem_sync_domain_map`` + * - ``nvlinkUtilCentricScheduling`` + - ``nvlink_util_centric_scheduling`` + * - ``portableClusterSizeMode`` + - ``portable_cluster_size_mode`` + * - ``preferredClusterDim`` + - ``preferred_cluster_dim`` + * - ``programmaticEvent`` + - ``programmatic_event`` + * - ``programmaticStreamSerializationAllowed`` + - ``programmatic_stream_serialization_allowed`` + * - ``sharedMemCarveout`` + - ``shared_mem_carveout`` + * - ``sharedMemoryMode`` + - ``shared_memory_mode`` + * - ``syncPolicy`` + - ``sync_policy`` + +.. rubric:: ``CUlaunchConfig`` -> ``LaunchConfig`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``blockDimX`` + - ``block_dim_x`` + * - ``blockDimY`` + - ``block_dim_y`` + * - ``blockDimZ`` + - ``block_dim_z`` + * - ``gridDimX`` + - ``grid_dim_x`` + * - ``gridDimY`` + - ``grid_dim_y`` + * - ``gridDimZ`` + - ``grid_dim_z`` + * - ``hStream`` + - ``h_stream`` + * - ``numAttrs`` + - ``num_attrs`` + * - ``sharedMemBytes`` + - ``shared_mem_bytes`` + +.. rubric:: ``CUlaunchMemSyncDomainMap`` -> ``LaunchMemSyncDomainMap`` + +.. rubric:: ``CUlibraryHostUniversalFunctionAndDataTable`` -> ``LibraryHostUniversalFunctionAndDataTable`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``dataTable`` + - ``data_table`` + * - ``dataWindowSize`` + - ``data_window_size`` + * - ``functionTable`` + - ``function_table`` + * - ``functionWindowSize`` + - ``function_window_size`` + +.. rubric:: ``CUlogicalEndpointFabricHandle`` -> ``LogicalEndpointFabricHandle`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``data`` + - ``data_`` + +.. rubric:: ``CUlogicalEndpointProp`` -> ``LogicalEndpointProp`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``ipcHandleTypes`` + - ``ipc_handle_types`` + * - ``size`` + - ``size_`` + +.. rubric:: ``CUmemAccessDesc_v1`` -> ``MemAccessDesc_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUmemAllocationProp_v1`` -> ``MemAllocationProp_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``allocFlags`` + - ``alloc_flags`` + * - ``requestedHandleTypes`` + - ``requested_handle_types`` + * - ``win32HandleMetaData`` + - ``win32handle_meta_data`` + +.. rubric:: ``CUmemcpy3DOperand_v1`` -> ``MemCpy3dOperand_v1`` + +.. rubric:: ``CUmemcpyAttributes_v1`` -> ``MemCpyAttributes_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``dstLocHint`` + - ``dst_loc_hint`` + * - ``flags`` + - ``flags_`` + * - ``srcAccessOrder`` + - ``src_access_order`` + * - ``srcLocHint`` + - ``src_loc_hint`` + +.. rubric:: ``CUmemDecompressParams`` -> ``MemDecompressParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``dstActBytes`` + - ``dst_act_bytes`` + * - ``dstNumBytes`` + - ``dst_num_bytes`` + * - ``srcNumBytes`` + - ``src_num_bytes`` + +.. rubric:: ``CUmemFabricHandle_v1`` -> ``MemFabricHandle_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``data`` + - ``data_`` + +.. rubric:: ``CUmemLocation_v1`` -> ``MemLocation_v1`` + +.. rubric:: ``CUmemPoolProps_v1`` -> ``MemPoolProps_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``allocType`` + - ``alloc_type`` + * - ``gpuDirectRDMACapable`` + - ``gpu_direct_rdma_capable`` + * - ``handleTypes`` + - ``handle_types`` + * - ``maxSize`` + - ``max_size`` + * - ``win32SecurityAttributes`` + - ``win32security_attributes`` + +.. rubric:: ``CUmemPoolPtrExportData_v1`` -> ``MemPoolPtrExportData_v1`` + +.. rubric:: ``CUmulticastObjectProp_v1`` -> ``MulticastObjectProp_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + * - ``handleTypes`` + - ``handle_types`` + * - ``numDevices`` + - ``num_devices`` + * - ``size`` + - ``size_`` + +.. rubric:: ``CUoffset3D_v1`` -> ``Offset3D_v1`` + +.. rubric:: ``CUstreamBatchMemOpParams_v1`` -> ``StreamBatchMemOpParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``atomicReduction`` + - ``atomic_reduction`` + * - ``flushRemoteWrites`` + - ``flush_remote_writes`` + * - ``memoryBarrier`` + - ``memory_barrier`` + * - ``waitValue`` + - ``wait_value`` + * - ``writeValue`` + - ``write_value`` + +.. rubric:: ``CUstreamCigCaptureParams`` -> ``StreamCigCaptureParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``streamCigParams`` + - ``stream_cig_params`` + +.. rubric:: ``CUstreamCigParam`` -> ``StreamCigParam`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``streamSharedData`` + - ``stream_shared_data`` + * - ``streamSharedDataType`` + - ``stream_shared_data_type`` + +.. rubric:: ``CUstreamMemOpAtomicReductionParams_st`` -> ``StreamMemOpAtomicReductionParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``dataType`` + - ``data_type`` + * - ``flags`` + - ``flags_`` + * - ``reductionOp`` + - ``reduction_op`` + +.. rubric:: ``CUstreamMemOpFlushRemoteWritesParams_st`` -> ``StreamMemOpFlushRemoteWritesParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUstreamMemOpMemoryBarrierParams_st`` -> ``StreamMemOpMemoryBarrierParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUstreamMemOpWaitValueParams_st`` -> ``StreamMemOpWaitValueParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUstreamMemOpWriteValueParams_st`` -> ``StreamMemOpWriteValueParams`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``flags`` + - ``flags_`` + +.. rubric:: ``CUtensorMap`` -> ``TensorMap`` + +.. rubric:: ``CUuuid`` -> ``Uuid`` + +.. rubric:: ``CUdevprop_v1`` -> ``DevProp_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``SIMDWidth`` + - ``simd_width`` + +.. rubric:: ``CUDA_LAUNCH_PARAMS_v1`` -> ``LaunchParams_v1`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``blockDimX`` + - ``block_dim_x`` + * - ``blockDimY`` + - ``block_dim_y`` + * - ``blockDimZ`` + - ``block_dim_z`` + * - ``gridDimX`` + - ``grid_dim_x`` + * - ``gridDimY`` + - ``grid_dim_y`` + * - ``gridDimZ`` + - ``grid_dim_z`` + * - ``hStream`` + - ``h_stream`` + * - ``kernelParams`` + - ``kernel_params`` + * - ``sharedMemBytes`` + - ``shared_mem_bytes`` + +Enumerations +------------ + +Enumeration members lose the common C prefix shown in the *Prefix removed* column. For example ``CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK`` becomes ``DeviceAttribute.MAX_THREADS_PER_BLOCK``. The old full C names are not kept as aliases. Members that changed in any other way are listed under the enumeration. + +.. list-table:: + :header-rows: 1 + :widths: 38 32 30 + + * - Legacy + - New + - Prefix removed + * - ``cl_context_flags`` + - ``ContextFlags`` + - ``NVCL_CTX_SCHED_`` + * - ``CUaccessProperty`` + - ``AccessProperty`` + - ``CU_ACCESS_PROPERTY_`` + * - ``CUaddress_mode`` + - ``AddressMode`` + - ``CU_TR_ADDRESS_MODE_`` + * - ``CUarray_cubemap_face`` + - ``ArrayCubemapFace`` + - ``CU_CUBEMAP_FACE_`` + * - ``CUarray_format`` + - ``ArrayFormat`` + - ``CU_AD_FORMAT_`` + * - ``CUarraySparseSubresourceType`` + - ``ArraySparseSubresourceType`` + - ``CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_`` + * - ``CUasyncNotificationType`` + - ``AsyncNotificationType`` + - ``CU_ASYNC_NOTIFICATION_TYPE_`` + * - ``CUatomicOperation`` + - ``AtomicOperation`` + - ``CU_ATOMIC_OPERATION_`` + * - ``CUatomicOperationCapability`` + - ``AtomicOperationCapability`` + - ``CU_ATOMIC_CAPABILITY_`` + * - ``CUcigDataType`` + - ``CigDataType`` + - ``CIG_DATA_TYPE_`` + * - ``CUcliqueType`` + - ``CliqueType`` + - ``CU_CLIQUE_TYPE_`` + * - ``CUclusterSchedulingPolicy`` + - ``ClusterSchedulingPolicy`` + - ``CU_CLUSTER_SCHEDULING_POLICY_`` + * - ``CUcomputemode`` + - ``ComputeMode`` + - ``CU_COMPUTEMODE_`` + * - ``CUCoredumpGenerationFlags`` + - ``CoredumpGenerationFlags`` + - ``CU_COREDUMP_`` + * - ``CUcoredumpSettings`` + - ``CoredumpSettings`` + - ``CU_COREDUMP_`` + * - ``CUctx_flags`` + - ``CtxFlags`` + - ``CU_CTX_`` + * - ``CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS`` + - ``PointerAttributeAccessFlags`` + - ``CU_POINTER_ATTRIBUTE_ACCESS_FLAG_`` + * - ``CUdevice_attribute`` + - ``DeviceAttribute`` + - ``CU_DEVICE_ATTRIBUTE_`` + * - ``CUdevice_P2PAttribute`` + - ``DeviceP2PAttribute`` + - ``CU_DEVICE_P2P_ATTRIBUTE_`` + * - ``CUdeviceNumaConfig`` + - ``DeviceNumaConfig`` + - ``CU_DEVICE_NUMA_CONFIG_`` + * - ``CUdevResourceType`` + - ``DevResourceType`` + - ``CU_DEV_RESOURCE_TYPE_`` + * - ``CUdevSmResourceGroup_flags`` + - ``DevSmResourceGroupFlags`` + - ``CU_DEV_SM_RESOURCE_GROUP_`` + * - ``CUdevSmResourceSplitByCount_flags`` + - ``DevSmResourceSplitByCountFlags`` + - ``CU_DEV_SM_RESOURCE_SPLIT_`` + * - ``CUdevWorkqueueConfigScope`` + - ``DevWorkqueueConfigScope`` + - ``CU_WORKQUEUE_SCOPE_`` + * - ``CUdriverProcAddress_flags`` + - ``DriverProcAddressFlags`` + - ``CU_GET_PROC_ADDRESS_`` + * - ``CUdriverProcAddressQueryResult`` + - ``DriverProcAddressQueryResult`` + - ``CU_GET_PROC_ADDRESS_`` + * - ``CUeglColorFormat`` + - ``EglColorFormat`` + - ``CU_EGL_COLOR_FORMAT_`` + * - ``CUeglFrameType`` + - ``EglFrameType`` + - ``CU_EGL_FRAME_TYPE_`` + * - ``CUeglResourceLocationFlags`` + - ``EglResourceLocationFlags`` + - ``CU_EGL_RESOURCE_LOCATION_`` + * - ``CUevent_flags`` + - ``EventFlags`` + - ``CU_EVENT_`` + * - ``CUevent_record_flags`` + - ``EventRecordFlags`` + - ``CU_EVENT_RECORD_`` + * - ``CUevent_sched_flags`` + - ``EventSchedFlags`` + - ``CU_EVENT_SCHED_`` + * - ``CUevent_wait_flags`` + - ``EventWaitFlags`` + - ``CU_EVENT_WAIT_`` + * - ``CUexecAffinityType`` + - ``ExecAffinityType`` + - ``CU_EXEC_AFFINITY_TYPE_`` + * - ``CUexternalMemoryHandleType`` + - ``ExternalMemoryHandleType`` + - ``CU_EXTERNAL_MEMORY_HANDLE_TYPE_`` + * - ``CUexternalSemaphoreHandleType`` + - ``ExternalSemaphoreHandleType`` + - ``CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_`` + * - ``CUfilter_mode`` + - ``FilterMode`` + - ``CU_TR_FILTER_MODE_`` + * - ``CUflushGPUDirectRDMAWritesOptions`` + - ``FlushGPUDirectRDMAWritesOptions`` + - ``CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_`` + * - ``CUflushGPUDirectRDMAWritesScope`` + - ``FlushGPUDirectRDMAWritesScope`` + - ``CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_`` + * - ``CUflushGPUDirectRDMAWritesTarget`` + - ``FlushGPUDirectRDMAWritesTarget`` + - ``CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TARGET_`` + * - ``CUfunc_cache`` + - ``FuncCache`` + - ``CU_FUNC_CACHE_PREFER_`` + * - ``CUfunction_attribute`` + - ``FunctionAttribute`` + - ``CU_FUNC_ATTRIBUTE_`` + * - ``CUfunctionLoadingState`` + - ``FunctionLoadingState`` + - ``CU_FUNCTION_LOADING_STATE_`` + * - ``CUGLmap_flags`` + - ``GLMapFlags`` + - ``CU_GL_MAP_RESOURCE_FLAGS_`` + * - ``CUGPUDirectRDMAWritesOrdering`` + - ``GPUDirectRDMAWritesOrdering`` + - ``CU_GPU_DIRECT_RDMA_WRITES_ORDERING_`` + * - ``CUgraphChildGraphNodeOwnership`` + - ``GraphChildGraphNodeOwnership`` + - ``CU_GRAPH_CHILD_GRAPH_OWNERSHIP_`` + * - ``CUgraphConditionalNodeType`` + - ``GraphConditionalNodeType`` + - ``CU_GRAPH_COND_TYPE_`` + * - ``CUgraphDebugDot_flags`` + - ``GraphDebugDotFlags`` + - ``CU_GRAPH_DEBUG_DOT_FLAGS_`` + * - ``CUgraphDependencyType`` + - ``GraphDependencyType`` + - ``CU_GRAPH_DEPENDENCY_TYPE_`` + * - ``CUgraphExecUpdateResult`` + - ``GraphExecUpdateResult`` + - ``CU_GRAPH_EXEC_UPDATE_`` + * - ``CUgraphicsMapResourceFlags`` + - ``GraphicsMapResourceFlags`` + - ``CU_GRAPHICS_MAP_RESOURCE_FLAGS_`` + * - ``CUgraphicsRegisterFlags`` + - ``GraphicsRegisterFlags`` + - ``CU_GRAPHICS_REGISTER_FLAGS_`` + * - ``CUgraphInstantiate_flags`` + - ``GraphInstantiateFlags`` + - ``CUDA_GRAPH_INSTANTIATE_FLAG_`` + * - ``CUgraphInstantiateResult`` + - ``GraphInstantiateResult`` + - ``CUDA_GRAPH_INSTANTIATE_`` + * - ``CUgraphMem_attribute`` + - ``GraphMemAttribute`` + - ``CU_GRAPH_MEM_ATTR_`` + * - ``CUgraphNodeType`` + - ``GraphNodeType`` + - ``CU_GRAPH_NODE_TYPE_`` + * - ``CUgraphRecaptureStatus`` + - ``GraphRecaptureStatus`` + - ``CU_GRAPH_RECAPTURE_`` + * - ``CUgreenCtxCreate_flags`` + - ``GreenCtxCreateFlags`` + - ``CU_GREEN_CTX_`` + * - ``CUhostTaskSyncMode`` + - ``HostTaskSyncMode`` + - ``CU_HOST_TASK_`` + * - ``CUipcMem_flags`` + - ``IpcMemFlags`` + - ``CU_`` + * - ``CUjit_cacheMode`` + - ``JitCacheMode`` + - ``CU_JIT_CACHE_OPTION_`` + * - ``CUjit_fallback`` + - ``JitFallback`` + - ``CU_PREFER_`` + * - ``CUjit_option`` + - ``JitOption`` + - ``CU_JIT_`` + * - ``CUjit_target`` + - ``JitTarget`` + - ``CU_`` + * - ``CUjitInputType`` + - ``JitInputType`` + - ``CU_JIT_`` + * - ``CUlaunchAttributeID`` + - ``LaunchAttributeID`` + - ``CU_LAUNCH_ATTRIBUTE_`` + * - ``CUlaunchAttributePortableClusterMode`` + - ``LaunchAttributePortableClusterMode`` + - ``CU_LAUNCH_PORTABLE_CLUSTER_MODE_`` + * - ``CUlaunchMemSyncDomain`` + - ``LaunchMemSyncDomain`` + - ``CU_LAUNCH_MEM_SYNC_DOMAIN_`` + * - ``CUlibraryOption`` + - ``LibraryOption`` + - ``CU_LIBRARY_`` + * - ``CUlimit`` + - ``Limit`` + - ``CU_LIMIT_`` + * - ``CUlogicalEndpointFlag`` + - ``LogicalEndpointFlag`` + - ``CU_LOGICAL_ENDPOINT_FLAG_`` + * - ``CUlogicalEndpointIpcHandleType`` + - ``LogicalEndpointIpcHandleType`` + - ``CU_LOGICAL_ENDPOINT_IPC_HANDLE_TYPE_`` + * - ``CUlogicalEndpointType`` + - ``LogicalEndpointType`` + - ``CU_LOGICAL_ENDPOINT_TYPE_`` + * - ``CUlogLevel`` + - ``LogLevel`` + - ``CU_LOG_LEVEL_`` + * - ``CUmem_advise`` + - ``MemAdvise`` + - ``CU_MEM_ADVISE_`` + * - ``CUmem_range_attribute`` + - ``MemRangeAttribute`` + - ``CU_MEM_RANGE_ATTRIBUTE_`` + * - ``CUmemAccess_flags`` + - ``MemAccessFlags`` + - ``CU_MEM_ACCESS_FLAGS_PROT_`` + * - ``CUmemAllocationCompType`` + - ``MemAllocationCompType`` + - ``CU_MEM_ALLOCATION_COMP_`` + * - ``CUmemAllocationGranularity_flags`` + - ``MemAllocationGranularityFlags`` + - ``CU_MEM_ALLOC_GRANULARITY_`` + * - ``CUmemAllocationHandleType`` + - ``MemAllocationHandleType`` + - ``CU_MEM_HANDLE_TYPE_`` + * - ``CUmemAllocationType`` + - ``MemAllocationType`` + - ``CU_MEM_ALLOCATION_TYPE_`` + * - ``CUmemAttach_flags`` + - ``MemAttachFlags`` + - ``CU_MEM_ATTACH_`` + * - ``CUmemcpy3DOperandType`` + - ``MemCpy3DOperandType`` + - ``CU_MEMCPY_OPERAND_TYPE_`` + * - ``CUmemcpyFlags`` + - ``MemCpyFlags`` + - ``CU_MEMCPY_FLAG_`` + * - ``CUmemcpySrcAccessOrder`` + - ``MemCpySrcAccessOrder`` + - ``CU_MEMCPY_SRC_ACCESS_ORDER_`` + * - ``CUmemDecompressAlgorithm`` + - ``MemDecompressAlgorithm`` + - ``CU_MEM_DECOMPRESS_`` + * - ``CUmemHandleType`` + - ``MemHandleType`` + - ``CU_MEM_HANDLE_TYPE_`` + * - ``CUmemLocationType`` + - ``MemLocationType`` + - ``CU_MEM_LOCATION_TYPE_`` + * - ``CUmemOperationType`` + - ``MemOperationType`` + - ``CU_MEM_OPERATION_TYPE_`` + * - ``CUmemorytype`` + - ``MemoryType`` + - ``CU_MEMORYTYPE_`` + * - ``CUmemPool_attribute`` + - ``MemPoolAttribute`` + - ``CU_MEMPOOL_ATTR_`` + * - ``CUmemRangeFlags`` + - ``MemRangeFlags`` + - ``CU_`` + * - ``CUmemRangeHandleType`` + - ``MemRangeHandleType`` + - ``CU_MEM_RANGE_HANDLE_TYPE_`` + * - ``CUmoduleLoadingMode`` + - ``ModuleLoadingMode`` + - ``CU_MODULE_`` + * - ``CUmulticastGranularity_flags`` + - ``MulticastGranularityFlags`` + - ``CU_MULTICAST_GRANULARITY_`` + * - ``CUoccupancy_flags`` + - ``OccupancyFlags`` + - ``CU_OCCUPANCY_`` + * - ``CUoutput_mode`` + - ``OutputMode`` + - ``CU_OUT_`` + * - ``CUpointer_attribute`` + - ``PointerAttribute`` + - ``CU_POINTER_ATTRIBUTE_`` + * - ``CUprocessState`` + - ``ProcessState`` + - ``CU_PROCESS_STATE_`` + * - ``CUresourcetype`` + - ``ResourceType`` + - ``CU_RESOURCE_TYPE_`` + * - ``CUresourceViewFormat`` + - ``ResourceViewFormat`` + - ``CU_RES_VIEW_FORMAT_`` + * - ``CUresult`` + - ``Result`` + - ``CUDA_`` + * - ``CUshared_carveout`` + - ``SharedCarveout`` + - ``CU_SHAREDMEM_CARVEOUT_`` + * - ``CUsharedMemoryMode`` + - ``SharedMemoryMode`` + - ``CU_SHARED_MEMORY_MODE_`` + * - ``CUstream_flags`` + - ``StreamFlags`` + - ``CU_STREAM_`` + * - ``CUstreamAtomicReductionDataType`` + - ``StreamAtomicReductionDataType`` + - ``CU_`` + * - ``CUstreamAtomicReductionOpType`` + - ``StreamAtomicReductionOpType`` + - ``CU_STREAM_ATOMIC_REDUCTION_OP_`` + * - ``CUstreamBatchMemOpType`` + - ``StreamBatchMemOpType`` + - ``CU_STREAM_MEM_OP_`` + * - ``CUstreamCaptureMode`` + - ``StreamCaptureMode`` + - ``CU_STREAM_CAPTURE_MODE_`` + * - ``CUstreamCaptureStatus`` + - ``StreamCaptureStatus`` + - ``CU_STREAM_CAPTURE_STATUS_`` + * - ``CUstreamCigDataType`` + - ``StreamCigDataType`` + - ``STREAM_CIG_DATA_TYPE_`` + * - ``CUstreamMemoryBarrier_flags`` + - ``StreamMemoryBarrierFlags`` + - ``CU_STREAM_MEMORY_BARRIER_TYPE_`` + * - ``CUstreamUpdateCaptureDependencies_flags`` + - ``StreamUpdateCaptureDependenciesFlags`` + - ``CU_STREAM_`` + * - ``CUstreamWaitValue_flags`` + - ``StreamWaitValueFlags`` + - ``CU_STREAM_WAIT_VALUE_`` + * - ``CUstreamWriteValue_flags`` + - ``StreamWriteValueFlags`` + - ``CU_STREAM_WRITE_VALUE_`` + * - ``CUsynchronizationPolicy`` + - ``SynchronizationPolicy`` + - ``CU_SYNC_POLICY_`` + * - ``CUtensorMapDataType`` + - ``TensorMapDataType`` + - ``CU_`` + * - ``CUtensorMapFloatOOBfill`` + - ``TensorMapFloatOOBFill`` + - ``CU_TENSOR_MAP_FLOAT_OOB_FILL_`` + * - ``CUtensorMapIm2ColWideMode`` + - ``TensorMapIm2ColWideMode`` + - ``CU_TENSOR_MAP_IM2COL_WIDE_MODE_`` + * - ``CUtensorMapInterleave`` + - ``TensorMapInterleave`` + - ``CU_`` + * - ``CUtensorMapL2promotion`` + - ``TensorMapL2Promotion`` + - ``CU_TENSOR_MAP_L2_PROMOTION_`` + * - ``CUtensorMapSwizzle`` + - ``TensorMapSwizzle`` + - ``CU_`` + * - ``CUuserObject_flags`` + - ``UserObjectFlags`` + - ``CU_`` + * - ``CUuserObjectRetain_flags`` + - ``UserObjectRetainFlags`` + - ``CU_`` + * - ``cl_event_flags`` + - ``NvclEventFlags`` + - ``NVCL_EVENT_SCHED_`` + * - ``CUsharedconfig`` + - ``SharedConfig`` + - ``CU_SHARED_MEM_CONFIG_`` + * - *(module constants ``CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_*``)* + - ``CooperativeLaunchMultiDeviceFlags`` + - ``CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_`` + * - *(module constants ``CU_LAUNCH_PARAM_*``)* + - ``LaunchParam`` + - ``CU_LAUNCH_PARAM_``, and the ``_AS_INT`` suffix + * - *(module constant ``CU_PARAM_TR_DEFAULT``)* + - ``ParamTexRef`` + - ``CU_PARAM_TR_`` + * - *(module constants ``CU_TRSA_*``)* + - ``TexRefArrayFlags`` + - ``CU_TRSA_`` + * - *(module constants ``CU_TRSF_*``)* + - ``TexRefFlags`` + - ``CU_TRSF_`` + +.. rubric:: ``CUgraphConditionalNodeType`` -> ``GraphConditionalNodeType`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy + - New + * - ``CU_GRAPH_COND_TYPE_IF`` + - ``IF_`` + +NVRTC +===== + +The ``cuda.bindings._v2.nvrtc`` module replaces ``cuda.bindings.nvrtc``. + +Functions +--------- + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + + * - Legacy + - New + - Notes + * - ``nvrtcVersion`` + - ``version`` + - Returns ``(major, minor)`` as a tuple. + * - ``nvrtcGetNumSupportedArchs`` + - ``get_num_supported_archs`` + - + * - ``nvrtcGetSupportedArchs`` + - ``get_supported_archs`` + - Returns the sorted architectures as an integer array (legacy returned a ``list[int]``). + * - ``nvrtcCreateProgram`` + - ``create_program`` + - Parameter ``numHeaders`` removed (the number of headers is taken from ``headers``). ``headers`` and ``include_names`` default to ``None``. Returns the program handle as an ``int``. + * - ``nvrtcDestroyProgram`` + - ``destroy_program`` + - + * - ``nvrtcCompileProgram`` + - ``compile_program`` + - Parameter ``numOptions`` removed (taken from ``options``). ``options`` defaults to ``None``. + * - ``nvrtcGetPTXSize`` + - ``get_ptx_size`` + - + * - ``nvrtcGetPTX`` + - ``get_ptx`` + - Parameter ``ptx`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcGetCUBINSize`` + - ``get_cubin_size`` + - + * - ``nvrtcGetCUBIN`` + - ``get_cubin`` + - Parameter ``cubin`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcGetLTOIRSize`` + - ``get_ltoir_size`` + - + * - ``nvrtcGetLTOIR`` + - ``get_ltoir`` + - Parameter ``LTOIR`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcGetOptiXIRSize`` + - ``get_optix_ir_size`` + - + * - ``nvrtcGetOptiXIR`` + - ``get_optix_ir`` + - Parameter ``optixir`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcGetTileIRSize`` + - ``get_tile_ir_size`` + - + * - ``nvrtcGetTileIR`` + - ``get_tile_ir`` + - Parameter ``TileIR`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcGetProgramLogSize`` + - ``get_program_log_size`` + - + * - ``nvrtcGetProgramLog`` + - ``get_program_log`` + - Parameter ``log`` (a caller-allocated buffer) removed. Returns the result as ``bytes``. + * - ``nvrtcAddNameExpression`` + - ``add_name_expression`` + - + * - ``nvrtcGetLoweredName`` + - ``get_lowered_name`` + - Returns the lowered name as ``bytes``. + * - ``nvrtcSetFlowCallback`` + - ``set_flow_callback`` + - ``callback`` and ``payload`` are plain integers (a C function pointer and an opaque pointer). + * - ``nvrtcGetPCHHeapSize`` + - ``get_pch_heap_size`` + - + * - ``nvrtcSetPCHHeapSize`` + - ``set_pch_heap_size`` + - + * - ``nvrtcGetPCHCreateStatus`` + - ``get_pch_create_status`` + - Returns the status as an ``int`` holding a ``Result`` value (for example ``Result.ERROR_NO_PCH_CREATE_ATTEMPTED``) instead of a result code. + * - ``nvrtcGetPCHHeapSizeRequired`` + - ``get_pch_heap_size_required`` + - + * - ``nvrtcInstallBundledHeaders`` + - ``install_bundled_headers`` + - ``flags`` takes ``InstallHeadersFlag`` values. Returns the optional error message (``bytes`` or ``None``). + * - ``nvrtcGetBundledHeadersInfo`` + - ``get_bundled_headers_info`` + - Returns ``(BundledHeadersInfo, error_log)`` as a tuple, with ``error_log`` set to ``None`` on success. + * - ``nvrtcRemoveBundledHeaders`` + - ``remove_bundled_headers`` + - Returns the optional error message (``bytes`` or ``None``). + * - ``nvrtcGetErrorString`` + - ``get_error_string`` + - Takes the result code as an ``int``. Returns ``str`` (legacy returned ``bytes``). + +Classes +------- + +.. rubric:: ``nvrtcBundledHeadersInfo`` -> ``BundledHeadersInfo`` + +.. list-table:: + :header-rows: 1 + :widths: 50 50 + + * - Legacy member + - New member + * - ``compressedSize`` + - ``compressed_size`` + * - ``cudaVersionMajor`` + - ``cuda_version_major`` + * - ``cudaVersionMinor`` + - ``cuda_version_minor`` + * - ``numFiles`` + - ``num_files`` + * - ``uncompressedSize`` + - ``uncompressed_size`` + * - ``getPtr()`` + - ``.ptr`` + +.. rubric:: ``nvrtcProgram`` (removed) + +Programs are plain ``int`` handles. + +Enumerations +------------ + +Members lose the prefix shown in the *Prefix removed* column. No members changed in any other way. ``NVRTC_SUCCESS`` becomes ``Result.SUCCESS`` and ``NVRTC_ERROR_OUT_OF_MEMORY`` becomes ``Result.ERROR_OUT_OF_MEMORY``. The installation flags were plain module-level constants in the legacy module and are now members of the ``InstallHeadersFlag`` enumeration. + +.. list-table:: + :header-rows: 1 + :widths: 38 32 30 + + * - Legacy + - New + - Prefix removed + * - ``nvrtcResult`` + - ``Result`` + - ``NVRTC_`` + * - ``NVRTC_INSTALL_HEADERS_*`` (module constants) + - ``InstallHeadersFlag`` + - ``NVRTC_INSTALL_HEADERS_`` diff --git a/cuda_bindings/docs/source/release/13.5.0-notes.rst b/cuda_bindings/docs/source/release/13.5.0-notes.rst index a95a520bea2..89a28c46bdb 100644 --- a/cuda_bindings/docs/source/release/13.5.0-notes.rst +++ b/cuda_bindings/docs/source/release/13.5.0-notes.rst @@ -317,6 +317,19 @@ Behavior changes - Passing a ``None`` to ``nvvm.add_module_to_program`` or ``nvvm.lazy_add_module_to_program`` will now raise a ``nvvm.nvvmError`` (``INVALID_INPUT``) rather than a ``ValueError``. +Deprecations +------------ + +- Two ``cuda.bindings.nvml`` exception classes were renamed so that they no longer have the same name as a Python builtin + exception. Code that did ``from cuda.bindings.nvml import *`` (or ``from cuda.bindings.nvml import TimeoutError``) + replaced the builtin ``TimeoutError`` and ``MemoryError`` in its namespace. Update code that refers to the old names: + + - ``nvml.TimeoutError`` is now ``nvml.NvmlTimeoutError``. + - ``nvml.MemoryError`` is now ``nvml.NvmlMemoryError``. + + They are still subclasses of ``nvml.NvmlError``, and the error codes they represent + (``ERROR_TIMEOUT`` and ``ERROR_MEMORY``) are unchanged, so ``except nvml.NvmlError`` is not affected. + Bugfixes -------- diff --git a/cuda_bindings/tests/conftest.py b/cuda_bindings/tests/conftest.py index fada7d95601..c33a357d9bb 100644 --- a/cuda_bindings/tests/conftest.py +++ b/cuda_bindings/tests/conftest.py @@ -10,7 +10,8 @@ import pytest -import cuda.bindings.driver as cuda +import cuda.bindings.driver as legacy_driver +from cuda.bindings._v2 import driver # Keep in sync with cuda_core/tests/conftest.py. try: @@ -41,18 +42,30 @@ 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 = driver.device_get(0) + ctx = driver.ctx_create_v4(None, 0, device) try: yield device, ctx finally: - (err,) = cuda.cuCtxDestroy(ctx) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.ctx_destroy_v2(ctx) -def _wrap_worker_cuda_test(func): +@contextmanager +def _legacy_thread_context(): + # Same as _thread_context, but using the legacy API so that the objects + # passed to tests/legacy_api have the types those tests expect. + err, device = legacy_driver.cuDeviceGet(0) + assert err == legacy_driver.CUresult.CUDA_SUCCESS + err, ctx = legacy_driver.cuCtxCreate(None, 0, device) + assert err == legacy_driver.CUresult.CUDA_SUCCESS + try: + yield device, ctx + finally: + (err,) = legacy_driver.cuCtxDestroy(ctx) + assert err == legacy_driver.CUresult.CUDA_SUCCESS + + +def _wrap_worker_cuda_test(func, thread_context): if getattr(func, "_cuda_bindings_worker_cuda_wrapped", False): return func @@ -63,7 +76,7 @@ def _wrap_worker_cuda_test(func): @functools.wraps(func) def wrapper(*args, **kwargs): kwargs = dict(kwargs) # copy before mutating - with _thread_context() as (device, ctx): + with thread_context() as (device, ctx): # device is None when reusing an existing context (defensive path); # keep whatever the fixture provided in kwargs as-is. if wants_device and device is not None: @@ -101,27 +114,26 @@ class _CudaBindingsParallelPlugin: def pytest_collection_modifyitems(self, config, items): for item in items: if _item_needs_thread_ctx(item): - item.obj = _wrap_worker_cuda_test(item.obj) + if "legacy_api" in item.path.parts: + thread_context = _legacy_thread_context + else: + thread_context = _thread_context + item.obj = _wrap_worker_cuda_test(item.obj, thread_context) @pytest.fixture(scope="module") def cuda_driver(): - (err,) = cuda.cuInit(0) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.init(0) @pytest.fixture(scope="module") def device(cuda_driver): - err, device = cuda.cuDeviceGet(0) - assert err == cuda.CUresult.CUDA_SUCCESS - return device + return driver.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 = driver.ctx_create_v4(None, 0, device) yield ctx - (err,) = cuda.cuCtxDestroy(ctx) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.ctx_destroy_v2(ctx) diff --git a/cuda_bindings/tests/legacy_api/conftest.py b/cuda_bindings/tests/legacy_api/conftest.py new file mode 100644 index 00000000000..3d9b2b6b6a0 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/conftest.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Fixtures for the legacy-API tests. These override the same-named fixtures in +# the parent conftest.py, which use the ``cuda.bindings._v2.driver`` API. + +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/nvml/test_legacy_nvml_cuda.py b/cuda_bindings/tests/legacy_api/nvml/test_legacy_nvml_cuda.py new file mode 100644 index 00000000000..71a23cd69a5 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/nvml/test_legacy_nvml_cuda.py @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from contextlib import contextmanager + +import pytest + +import cuda.bindings.driver as cuda +from cuda.bindings import nvml + + +# Not imported from tests/nvml/conftest.py: that package is only importable when +# tests/ happens to be on sys.path, which this directory cannot rely on. +@contextmanager +def nvml_initialized(): + nvml.init_v2() + try: + yield + finally: + nvml.shutdown() + + +def get_nvml_device_names(): + result = [] + with nvml_initialized(): + # 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) + try: + info = nvml.device_get_pci_info_v3(handle) + except nvml.NotSupportedError: + bus_id = -1 + else: + bus_id = info.bus + assert isinstance(bus_id, int) + assert isinstance(name, str) + result.append({"name": name, "id": bus_id}) + + 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() + + for kind in ("Orin", "Thor"): + if any(kind in device["name"] for device in nvml_devices): + pytest.skip(f"Skipping test on {kind}, which has non-standard device naming") + + def compare(cuda_device, nvml_device): + return cuda_device["name"] == nvml_device["name"] and ( + nvml_device["id"] == -1 or cuda_device["id"] == nvml_device["id"] + ) + + assert len(cuda_devices) <= len(nvml_devices) + for cuda_device in cuda_devices: + assert any(compare(cuda_device, nvml_device) for nvml_device in nvml_devices) 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..369190c6b64 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_cuda.py @@ -0,0 +1,1540 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import ctypes +import os +import shutil +import tempfile +import textwrap + +import numpy as np +import pytest +from cuda_python_test_helpers.subprocess_runner import run_python_snippet + +import cuda.bindings.driver as cuda +import cuda.bindings.runtime as cudart +from cuda.bindings import driver +from cuda.bindings._internal.utils import FunctionNotFoundError +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) + 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, + ] + + err, attrs = cuda.cuPointerGetAttributes(len(attributes), attributes, 0) + + assert err == cuda.CUresult.CUDA_SUCCESS + # Drivers use either negative sentinel for a null pointer. Both ensure the + # signed device ordinal is returned rather than an unsigned value. + assert attrs[0] in (cuda.CU_DEVICE_CPU, cuda.CU_DEVICE_INVALID) + + +@pytest.mark.agent_authored(model="gpt-5.6-sol") +def test_pointer_allowed_handle_types_preserves_64_bits(): + helper = cuda._HelperCUpointer_attribute( + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, 0, is_getter=True + ) + expected = 1 << 40 + ctypes.c_uint64.from_address(helper.cptr).value = expected + + assert helper.pyObj() == expected + + +@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 + 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 + + +@pytest.mark.agent_authored(model="gpt-5.6-sol") +def test_coredump_bool_uses_single_byte_storage(): + helper = cuda._HelperCUcoredumpSettings(cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, 0, is_getter=True) + ctypes.c_uint32.from_address(helper.cptr).value = 0xFFFFFFFF + ctypes.c_uint8.from_address(helper.cptr).value = 0 + + assert helper.size() == ctypes.sizeof(ctypes.c_bool) + assert helper.pyObj() is False + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_new_pointer_attributes(): + """Smoke-test that every newly added CUpointer_attribute branch can be + constructed without raising TypeError.""" + new_attrs = [ + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPING_SIZE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMORY_BLOCK_ID, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE, + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_LOCALITY_DOMAIN_ORDINAL, + ] + for attr in new_attrs: + helper = cuda._HelperCUpointer_attribute(attr, 0, is_getter=True) + assert helper.cptr != 0 + _ = helper.pyObj() + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_mapping_base_addr(): + """CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR uses the CUdeviceptr getter path.""" + helper = cuda._HelperCUpointer_attribute( + cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR, 0, is_getter=True + ) + assert helper.cptr != 0 + _ = helper.pyObj() + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_new_mempool_attributes(): + """Smoke-test all newly added CUmemPool_attribute branches.""" + int_attrs = [ + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_ALLOCATION_TYPE, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCATION_ID, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCATION_TYPE, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED, + cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID, + ] + for attr in int_attrs: + helper = cuda._HelperCUmemPool_attribute(attr, 0, is_getter=True) + assert helper.cptr != 0 + assert helper.pyObj() == 0 + + uint_attr = cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES + helper = cuda._HelperCUmemPool_attribute(uint_attr, 0, is_getter=True) + assert helper.cptr != 0 + assert helper.pyObj() == 0 + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_new_mem_range_attributes(): + """Smoke-test all newly added CUmem_range_attribute branches (scalar int).""" + new_attrs = [ + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE, + cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID, + ] + for attr in new_attrs: + helper = cuda._HelperCUmem_range_attribute(attr, 4) + assert helper.cptr != 0 + assert helper.pyObj() == 0 + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_jit_option_new_int_attrs(): + """Newly added int-type CUjit_option branches should construct without TypeError. + + These options use the value-cast pattern: the int value is encoded directly + in the void* slot (cptr == NULL when value is 0, which is expected). + """ + new_int_attrs = [ + cuda.CUjit_option.CU_JIT_POSITION_INDEPENDENT_CODE, + cuda.CUjit_option.CU_JIT_MAX_THREADS_PER_BLOCK, + cuda.CUjit_option.CU_JIT_OVERRIDE_DIRECTIVE_VALUES, + ] + for attr in new_int_attrs: + helper = cuda._HelperCUjit_option(attr, 1) + assert helper.cptr == 1 # value is encoded as pointer + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_jit_option_binary_loader_thread_count(): + """CU_JIT_BINARY_LOADER_THREAD_COUNT is unsigned int, value-cast like other uint options.""" + helper = cuda._HelperCUjit_option(cuda.CUjit_option.CU_JIT_BINARY_LOADER_THREAD_COUNT, 4) + assert helper.cptr != 0 + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_jit_wall_time_pointer_is_valid(): + """CU_JIT_WALL_TIME must give CUDA a valid writable float address, not a garbage pointer.""" + helper = cuda._HelperCUjit_option(cuda.CUjit_option.CU_JIT_WALL_TIME, 0.0) + # Guard against NULL so a regression fails instead of segfaulting. + assert helper.cptr != 0 + # Write a sentinel float via ctypes to confirm the pointer is addressable. + ctypes.c_float.from_address(helper.cptr).value = 3.14 + assert ctypes.c_float.from_address(helper.cptr).value == pytest.approx(3.14, rel=1e-5) + + +@pytest.mark.agent_authored(model="claude-sonnet-4-6") +def test_ffi_coverage_coredump_generation_flags(): + """CU_COREDUMP_GENERATION_FLAGS is an unsigned int bitmask.""" + helper = cuda._HelperCUcoredumpSettings(cuda.CUcoredumpSettings.CU_COREDUMP_GENERATION_FLAGS, 0, is_getter=True) + assert helper.size() == ctypes.sizeof(ctypes.c_uint) + ctypes.c_uint.from_address(helper.cptr).value = 0xDEAD + assert helper.pyObj() == 0xDEAD + + +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 + + +@pytest.mark.agent_authored(model="claude-fable-5-1") +def test_cuda_launch_host_func_graph_replay(): + # A host function captured into a graph runs once per graph launch. The + # bindings must hand the function pointer and the user data to CUDA + # unchanged so that every launch reaches the same function (issue #790). + counter = ctypes.c_int(0) + + @ctypes.CFUNCTYPE(None, ctypes.c_void_p) + def host_fn(userData): + ctypes.c_int.from_address(userData).value += 1 + + callback = cuda.CUhostFn(_ptr=ctypes.addressof(host_fn)) + err, stream = cuda.cuStreamCreate(0) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + (err,) = cuda.cuStreamBeginCapture(stream, cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_GLOBAL) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuLaunchHostFunc(stream, callback, ctypes.addressof(counter)) + assert err == cuda.CUresult.CUDA_SUCCESS + err, graph = cuda.cuStreamEndCapture(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + err, graphExec = cuda.cuGraphInstantiate(graph, 0) + assert err == cuda.CUresult.CUDA_SUCCESS + try: + for launch in range(1, 6): + (err,) = cuda.cuGraphLaunch(graphExec, stream) + assert err == cuda.CUresult.CUDA_SUCCESS + (err,) = cuda.cuStreamSynchronize(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + assert counter.value == launch + finally: + (err,) = cuda.cuGraphExecDestroy(graphExec) + assert err == cuda.CUresult.CUDA_SUCCESS + finally: + (err,) = cuda.cuGraphDestroy(graph) + assert err == cuda.CUresult.CUDA_SUCCESS + finally: + (err,) = cuda.cuStreamDestroy(stream) + assert err == cuda.CUresult.CUDA_SUCCESS + + +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 + + +@pytest.mark.skipif( + driver_version_less_than(12090), + reason="cuLogs* functions were introduced in CUDA 12.9", +) +def test_culogs_functions(): + try: + err, callback_handle = cuda.cuLogsRegisterCallback(0, None) + assert err == cuda.CUresult.CUDA_SUCCESS + + err, _ = cuda.cuLogsCurrent(0) + assert err == cuda.CUresult.CUDA_SUCCESS + + with tempfile.NamedTemporaryFile(delete=False) as f: + log_path = f.name + try: + err, _ = cuda.cuLogsDumpToFile(None, log_path.encode(), 0) + assert err == cuda.CUresult.CUDA_SUCCESS + finally: + os.remove(log_path) + + # cuLogsDumpToMemory's own docstring states the driver's internal log + # buffer is capped at 25600 bytes, so a buffer of that size is always + # large enough to hold the dump without risking a buffer overrun. + buf = bytearray(25600) + err, _, _ = cuda.cuLogsDumpToMemory(None, buf, len(buf), 0) + assert err == cuda.CUresult.CUDA_SUCCESS + + (err,) = cuda.cuLogsUnregisterCallback(callback_handle) + assert err == cuda.CUresult.CUDA_SUCCESS + except FunctionNotFoundError as e: + pytest.fail(f"cuLogs* function unexpectedly not found on the driver: {e}") + + +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 + # CUgraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] + raw = (ctypes.c_uint8 * 8).from_address(ed.getPtr()) + assert bytes(raw[3:]) == b"\x00" * 5 + 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 + # CUgraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] + raw = (ctypes.c_uint8 * 8).from_address(ed.getPtr()) + assert bytes(raw[3:]) == b"\x00" * 5 + 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)] + """ + ) + run_python_snippet(code) + + +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_cufile.py b/cuda_bindings/tests/legacy_api/test_legacy_cufile.py new file mode 100644 index 00000000000..75f51dc0e15 --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_cufile.py @@ -0,0 +1,1916 @@ +# 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 parent tests directory + 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 ctx + + 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") +@pytest.mark.thread_unsafe(reason="cuFile stats level is process-global") +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..b8774af13fe --- /dev/null +++ b/cuda_bindings/tests/legacy_api/test_legacy_interoperability.py @@ -0,0 +1,171 @@ +# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import pytest + +import cuda.bindings.driver as cuda +import cuda.bindings.runtime as cudart + +# Cap for the memory pool created by test_interop_memPool. Touching the device's +# default pool (e.g. via cuDeviceGetDefaultMemPool, cudaDeviceGetDefaultMemPool, +# or cuDeviceGetMemPool / cudaDeviceGetMemPool before a pool has been set) +# reserves virtual address space of about twice the device memory, which +# cannot be satisfied in a 39-bit address space. +POOL_SIZE = 2 * 1024 * 1024 # 2 MiB + + +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.thread_unsafe(reason="changes the device's current memory pool") +@pytest.mark.agent_authored(model="claude-sonnet-5.5") +@pytest.mark.skipif(not supportsMemoryPool(), reason="Requires mempool operations") +def test_interop_memPool(): + # Use a small, capped pool instead of the device's default pool. The pool + # must be set before it is queried below because the getters create (and + # reserve address space for) the default pool if none has been set. + props = cuda.CUmemPoolProps() + props.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED + props.handleTypes = cuda.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_NONE + props.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + props.location.id = 0 + props.maxSize = POOL_SIZE + err_dr, pool = cuda.cuMemPoolCreate(props) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + + try: + # DRV to RT + (err_rt,) = cudart.cudaDeviceSetMemPool(0, pool) + assert err_rt == cudart.cudaError_t.cudaSuccess + + # RT to DRV + err_rt, rt_pool = cudart.cudaDeviceGetMemPool(0) + assert err_rt == cudart.cudaError_t.cudaSuccess + assert int(rt_pool) == int(pool) + (err_dr,) = cuda.cuDeviceSetMemPool(0, rt_pool) + assert err_dr == cuda.CUresult.CUDA_SUCCESS + finally: + (err_dr,) = cuda.cuMemPoolDestroy(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 4b4dcfb823a..f3d3e2fd072 100644 --- a/cuda_bindings/tests/nvml/test_cuda.py +++ b/cuda_bindings/tests/nvml/test_cuda.py @@ -4,8 +4,8 @@ import pytest -import cuda.bindings.driver as cuda from cuda.bindings import nvml +from cuda.bindings._v2 import driver from .conftest import NVMLInitializer @@ -34,20 +34,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 + driver.init(0) - err, device_count = cuda.cuDeviceGetCount() - assert err == cuda.CUresult.CUDA_SUCCESS + device_count = driver.device_get_count() for dev in range(device_count): size = 256 - err, name = cuda.cuDeviceGetName(size, dev) + name = driver.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 = driver.device_get_attribute(driver.DeviceAttribute.PCI_BUS_ID, dev) assert isinstance(pci_bus_id, int) result.append({"name": name, "id": pci_bus_id}) diff --git a/cuda_bindings/tests/test_cuda.py b/cuda_bindings/tests/test_cuda.py index 369190c6b64..9db0fe4f884 100644 --- a/cuda_bindings/tests/test_cuda.py +++ b/cuda_bindings/tests/test_cuda.py @@ -1,22 +1,24 @@ # SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import builtins +import contextlib import ctypes import os import shutil import tempfile -import textwrap import numpy as np import pytest -from cuda_python_test_helpers.subprocess_runner import run_python_snippet -import cuda.bindings.driver as cuda import cuda.bindings.runtime as cudart -from cuda.bindings import driver from cuda.bindings._internal.utils import FunctionNotFoundError +from cuda.bindings._v2 import driver from cuda_python_test_helpers import driver_version_less_than +# NULL dependency array: the node has no dependencies. +NO_DEPS = 0 + def supportsMemoryPool(): err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrMemoryPoolsSupported, 0) @@ -29,13 +31,19 @@ def supportsManagedMemory(): def supportsCudaAPI(name): - return name in dir(cuda) + return name in dir(driver) def callableBinary(name): return shutil.which(name) is not None +def node_array(nodes): + # Build a C array of graph node handles; the caller passes + # ctypes.addressof(array) and must keep the array alive during the call. + return (ctypes.c_void_p * len(nodes))(*nodes) + + @pytest.mark.skipif(True, reason="Always skip!") def test_always_skip(): pass @@ -46,8 +54,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 = driver.mem_alloc_v2(size) # Set h1 and h2 memory to be different h1 = np.full(size, 1).astype(np.uint8) @@ -55,390 +62,373 @@ 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 + driver.memcpy_htod_v2(dptr, h1, size) # D to h2 - (err,) = cuda.cuMemcpyDtoH(h2, dptr, size) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.memcpy_dtoh_v2(h2, dptr, size) # Validate h1 == h2 assert np.array_equal(h1, h2) + # Host arguments accept any contiguous buffer: ctypes scalars and arrays, not just NumPy. + src = (ctypes.c_int * 4)(1, 2, 3, 4) + driver.memcpy_htod_v2(dptr, src, ctypes.sizeof(src)) + dst = (ctypes.c_int * 4)() + driver.memcpy_dtoh_v2(dst, dptr, ctypes.sizeof(dst)) + assert list(dst) == [1, 2, 3, 4] + + scalar = ctypes.c_int(42) + driver.memcpy_htod_v2(dptr, scalar, ctypes.sizeof(scalar)) + out = ctypes.c_int() + driver.memcpy_dtoh_v2(out, dptr, ctypes.sizeof(out)) + assert out.value == 42 + + matrix = np.arange(4, dtype=np.int32).reshape(2, 2) + driver.memcpy_htod_v2(dptr, matrix, matrix.nbytes) + back = np.zeros((2, 2), dtype=np.int32) + driver.memcpy_dtoh_v2(back, dptr, back.nbytes) + assert np.array_equal(matrix, back) + # Cleanup - (err,) = cuda.cuMemFree(dptr) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.mem_free_v2(dptr) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +@pytest.mark.skipif(driver_version_less_than(13041), reason="cuGraphAddNode_v3 was added in CUDA 13.4.1") +def test_graph_add_node_v3_returns_the_node(): + graph = driver.graph_create(0) + params = driver.GraphNodeParams() + params.type = driver.GraphNodeType.EMPTY + node = driver.graph_add_node_v3(graph, NO_DEPS, None, 0, params) + assert isinstance(node, int) and node != 0 + driver.graph_destroy(graph) 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.InvalidContextError, driver.InvalidValueError)): + driver.array_create_v2(desc) # Desciption not filled - err, arr = cuda.cuArrayCreate(desc) - assert err == cuda.CUresult.CUDA_ERROR_INVALID_VALUE + with pytest.raises(driver.InvalidValueError): + driver.array_create_v2(desc) # 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 + desc.format = driver.ArrayFormat.SIGNED_INT8 + desc.num_channels = 1 + desc.width = 1 + arr = driver.array_create_v2(desc) - # 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) + driver.array_destroy(arr) 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 + uuid = driver.device_get_uuid_v2(device) + assert isinstance(uuid.bytes, bytes) + assert len(uuid.bytes) == 16 + + # The UUID is 16 raw bytes, not text: values that are not valid UTF-8 round-trip. + raw = bytes(range(0x80, 0x90)) + copy = driver.Uuid() + copy.bytes = raw + assert copy.bytes == raw + with pytest.raises(ValueError): + copy.bytes = b"too short" + + jit_option = driver.JitOption 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, + jit_option.INFO_LOG_BUFFER: 1, + jit_option.INFO_LOG_BUFFER_SIZE_BYTES: 2, + jit_option.ERROR_LOG_BUFFER: 3, + jit_option.ERROR_LOG_BUFFER_SIZE_BYTES: 4, + jit_option.LOG_VERBOSE: 5, } -def test_cuda_cuModuleLoadDataEx(): +_JIT_PTX = b""".version 7.5 +.target sm_75 +.address_size 64 +.visible .entry k() +{ + ret; +} +\0""" + + +def _load_ptx_with_log_options(ptx): + # Returns (module-or-exception, info_log, error_log, error_log_size) for a load using the JIT log options. 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.INFO_LOG_BUFFER, + driver.JitOption.INFO_LOG_BUFFER_SIZE_BYTES, + driver.JitOption.ERROR_LOG_BUFFER, + driver.JitOption.ERROR_LOG_BUFFER_SIZE_BYTES, + driver.JitOption.LOG_VERBOSE, ] - # FIXME: This function call raises CUDA_ERROR_INVALID_VALUE - err, mod = cuda.cuModuleLoadDataEx(0, 0, option_keys, []) + keys = (ctypes.c_int * len(option_keys))(*[int(k) for k in option_keys]) + info_log = ctypes.create_string_buffer(1024) + error_log = ctypes.create_string_buffer(1024) + values = (ctypes.c_void_p * len(option_keys))( + ctypes.addressof(info_log), len(info_log), ctypes.addressof(error_log), len(error_log), 1 + ) + try: + result = driver.module_load_data_ex(ptx, len(option_keys), ctypes.addressof(keys), ctypes.addressof(values)) + except driver.DriverError as e: + result = e + return result, info_log.value, error_log.value, values[3] + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_cuda_cuModuleLoadDataEx(): + mod, _, error_log, _ = _load_ptx_with_log_options(_JIT_PTX) + assert not isinstance(mod, Exception), mod + try: + assert error_log == b"" + assert driver.module_get_function(mod, b"k") + finally: + driver.module_unload(mod) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_cuda_cuModuleLoadDataEx_error_log(): + # The JIT writes its diagnostics into the caller's buffer, and updates the size option value to the + # number of bytes written. + bad_ptx = b".version 7.5\n.target sm_75\nbogus\n\0" + result, _, error_log, error_log_size = _load_ptx_with_log_options(bad_ptx) + assert isinstance(result, driver.InvalidPtxError) + assert b"syntax error" in error_log + assert 0 < error_log_size <= 1024 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() + # The v2 structs do not have a custom __repr__; check the default-initialized values instead. + actual = driver.ExternalSemaphoreSignalParams_v1() + assert isinstance(actual, driver.ExternalSemaphoreSignalParams_v1) + assert actual.flags_ == 0 + assert actual.params.fence.value == 0 + assert actual.params.nv_sci_sync.fence == 0 + assert actual.params.keyed_mutex.key == 0 + + kernel_params = driver.KernelNodeParams_v2() + assert kernel_params.func == 0 + assert kernel_params.grid_dim_x == 0 + assert kernel_params.grid_dim_y == 0 + assert kernel_params.grid_dim_z == 0 + assert kernel_params.block_dim_x == 0 + assert kernel_params.block_dim_y == 0 + assert kernel_params.block_dim_z == 0 + assert kernel_params.shared_mem_bytes == 0 + assert kernel_params.kernel_params == 0 + assert kernel_params.extra == 0 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, + desc = driver.TextureDesc_v1() + desc.address_mode = [ + driver.AddressMode.WRAP, + driver.AddressMode.CLAMP, + driver.AddressMode.MIRROR, + ] + assert list(desc.address_mode) == [ + driver.AddressMode.WRAP, + driver.AddressMode.CLAMP, + driver.AddressMode.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] + # desc.address_mode = [driver.AddressMode.WRAP, + # driver.AddressMode.CLAMP, + # driver.AddressMode.MIRROR, + # driver.AddressMode.BORDER] # # Too little args - # desc.addressMode = [cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_WRAP, - # cuda.CUaddress_mode.CU_TR_ADDRESS_MODE_CLAMP] + # desc.address_mode = [driver.AddressMode.WRAP, + # driver.AddressMode.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 + params = driver.StreamBatchMemOpParams_v1() + params.operation = driver.StreamBatchMemOpType.WAIT_VALUE_32 + params.wait_value.operation = driver.StreamBatchMemOpType.WAIT_VALUE_32 + params.write_value.operation = driver.StreamBatchMemOpType.WAIT_VALUE_32 + params.flush_remote_writes.operation = driver.StreamBatchMemOpType.WAIT_VALUE_32 + params.wait_value.value64 = 666 + assert np.asarray(params.wait_value.value64).item() == 666 + + # A struct-valued member of an array-backed type is a wrapper object (its scalars are plain ints), + # never a raw NumPy record whose scalars come back as 1-element arrays. + batch = driver.StreamBatchMemOpParams_v1() + assert isinstance(batch.wait_value, driver.StreamMemOpWaitValueParams) + assert isinstance(batch.wait_value.flags_, int) + batch.wait_value.value = 7 + assert batch.wait_value.value == 7 + assert batch[0].wait_value.value == 7 + + access = driver.MemAccessDesc_v1() + assert isinstance(access.location, driver.MemLocation_v1) + assert isinstance(access.location.id, int) + + # Elements of a larger array behave the same way. + assert isinstance(driver.StreamBatchMemOpParams_v1(3)[2].wait_value.flags_, int) + assert isinstance(driver.ArrayMapInfo_v1(2)[1].resource.array, int) @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 = driver.MemPoolProps_v1() + poolProps.alloc_type = driver.MemAllocationType.PINNED poolProps.location.id = 0 - poolProps.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + poolProps.location.type = driver.MemLocationType.DEVICE attr_list = [None] * 8 - err, pool = cuda.cuMemPoolCreate(poolProps) - assert err == cuda.CUresult.CUDA_SUCCESS + pool = driver.mem_pool_create(poolProps) + + def get_attr(attr): + return int(driver.mem_pool_get_attribute(pool, attr)) 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.REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.REUSE_ALLOW_INTERNAL_DEPENDENCIES, + driver.MemPoolAttribute.RELEASE_THRESHOLD, + driver.MemPoolAttribute.RESERVED_MEM_CURRENT, + driver.MemPoolAttribute.RESERVED_MEM_HIGH, + driver.MemPoolAttribute.USED_MEM_CURRENT, + driver.MemPoolAttribute.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, + driver.MemPoolAttribute.REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.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 + value = ctypes.c_int(0) + driver.mem_pool_set_attribute(pool, attr, ctypes.addressof(value)) + for idx, attr in enumerate([driver.MemPoolAttribute.RELEASE_THRESHOLD]): + value = ctypes.c_uint64(9) + driver.mem_pool_set_attribute(pool, attr, ctypes.addressof(value)) 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.REUSE_FOLLOW_EVENT_DEPENDENCIES, + driver.MemPoolAttribute.REUSE_ALLOW_OPPORTUNISTIC, + driver.MemPoolAttribute.REUSE_ALLOW_INTERNAL_DEPENDENCIES, + driver.MemPoolAttribute.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 - (err,) = cuda.cuMemPoolDestroy(pool) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 = driver.mem_alloc_managed(0x1000, driver.MemAttachFlags.GLOBAL.value) # 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.CONTEXT, + driver.PointerAttribute.MEMORY_TYPE, + driver.PointerAttribute.DEVICE_POINTER, + driver.PointerAttribute.HOST_POINTER, + # driver.PointerAttribute.P2P_TOKENS, # TODO: Can I somehow test this? + driver.PointerAttribute.SYNC_MEMOPS, + driver.PointerAttribute.BUFFER_ID, + driver.PointerAttribute.IS_MANAGED, + driver.PointerAttribute.DEVICE_ORDINAL, + driver.PointerAttribute.IS_LEGACY_CUDA_IPC_CAPABLE, + driver.PointerAttribute.RANGE_START_ADDR, + driver.PointerAttribute.RANGE_SIZE, + driver.PointerAttribute.MAPPED, + driver.PointerAttribute.ALLOWED_HANDLE_TYPES, + driver.PointerAttribute.IS_GPU_DIRECT_RDMA_CAPABLE, + driver.PointerAttribute.ACCESS_FLAGS, + driver.PointerAttribute.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 + attr_value_list = [driver.pointer_get_attribute(attr, ptr) for attr in attr_type_list] # List version - err, attr_value_list_v2 = cuda.cuPointerGetAttributes(len(attr_type_list), attr_type_list, ptr) - assert err == cuda.CUresult.CUDA_SUCCESS + attr_value_list_v2 = driver.pointer_get_attributes(attr_type_list, ptr) for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): - assert str(attr1) == str(attr2) + assert attr1 == 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 + value = ctypes.c_int(val) + driver.pointer_set_attribute(ctypes.addressof(value), driver.PointerAttribute.SYNC_MEMOPS, ptr) + assert bool(driver.pointer_get_attribute(driver.PointerAttribute.SYNC_MEMOPS, ptr)) == val - (err,) = cuda.cuMemFree(ptr) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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, - ] + (value,) = driver.pointer_get_attributes([driver.PointerAttribute.DEVICE_ORDINAL], 0) - err, attrs = cuda.cuPointerGetAttributes(len(attributes), attributes, 0) - - assert err == cuda.CUresult.CUDA_SUCCESS # Drivers use either negative sentinel for a null pointer. Both ensure the # signed device ordinal is returned rather than an unsigned value. - assert attrs[0] in (cuda.CU_DEVICE_CPU, cuda.CU_DEVICE_INVALID) + assert value in (driver.SpecialDevice.CPU, driver.SpecialDevice.INVALID) @pytest.mark.agent_authored(model="gpt-5.6-sol") +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsManagedMemory(), reason="When new attributes were introduced" +) def test_pointer_allowed_handle_types_preserves_64_bits(): - helper = cuda._HelperCUpointer_attribute( - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES, 0, is_getter=True - ) - expected = 1 << 40 - ctypes.c_uint64.from_address(helper.cptr).value = expected - - assert helper.pyObj() == expected + ptr = driver.mem_alloc_managed(0x1000, driver.MemAttachFlags.GLOBAL.value) + try: + assert driver.pointer_get_attribute(driver.PointerAttribute.ALLOWED_HANDLE_TYPES, ptr) == 0 + finally: + driver.mem_free_v2(ptr) @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.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 + location_cpu = driver.MemLocation_v1() + location_cpu.type = driver.MemLocationType.HOST + location_cpu.id = int(driver.SpecialDevice.CPU) + + ptr = driver.mem_alloc_managed(size, driver.MemAttachFlags.GLOBAL.value) + driver.mem_advise_v2(ptr, size, driver.MemAdvise.SET_READ_MOSTLY, location_device) + driver.mem_advise_v2(ptr, size, driver.MemAdvise.SET_PREFERRED_LOCATION, location_cpu) + driver.mem_advise_v2(ptr, size, driver.MemAdvise.SET_ACCESSED_BY, location_cpu) + concurrentSupported = driver.device_get_attribute(driver.DeviceAttribute.CONCURRENT_MANAGED_ACCESS, device) if concurrentSupported: - (err,) = cuda.cuMemAdvise(ptr, size, cuda.CUmem_advise.CU_MEM_ADVISE_SET_ACCESSED_BY, location_device) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.mem_advise_v2(ptr, size, driver.MemAdvise.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.READ_MOSTLY, + driver.MemRangeAttribute.PREFERRED_LOCATION, + driver.MemRangeAttribute.ACCESSED_BY, + driver.MemRangeAttribute.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 + attr_value_list[idx] = driver.mem_range_get_attribute(attr_type_size_list[idx], attr_type_list[idx], ptr, size) matched = False for expected_values in expected_values_list: @@ -449,15 +439,11 @@ def test_cuda_mem_range_attr(device): 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 + attr_value_list_v2 = driver.mem_range_get_attributes(attr_type_size_list, attr_type_list, ptr, size) for attr1, attr2 in zip(attr_value_list, attr_value_list_v2): - assert str(attr1) == str(attr2) + assert attr1 == attr2 - (err,) = cuda.cuMemFree(ptr) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.mem_free_v2(ptr) @pytest.mark.skipif( @@ -465,88 +451,71 @@ 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 + stream = driver.stream_create(0) - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = driver.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_v1() + params.pool_props.location.type = driver.MemLocationType.DEVICE + params.pool_props.location.id = device + params.pool_props.alloc_type = driver.MemAllocationType.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 - 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 + try: + allocNode = driver.graph_add_mem_alloc_node(graph, NO_DEPS, 0, params) + except driver.OutOfMemoryError: + driver.graph_destroy(graph) + driver.stream_destroy_v2(stream) + raise + deps = node_array([allocNode]) + freeNode = driver.graph_add_mem_free_node(graph, ctypes.addressof(deps), 1, params.dptr) + + graphExec = driver.graph_instantiate(graph, 0) + + driver.graph_launch(graphExec, stream) + + def get_graph_mem_attr(attr): + return int(driver.device_get_graph_mem_attribute(device, attr)) + + used = get_graph_mem_attr(driver.GraphMemAttribute.USED_MEM_CURRENT) + usedHigh = get_graph_mem_attr(driver.GraphMemAttribute.USED_MEM_HIGH) + reserved = get_graph_mem_attr(driver.GraphMemAttribute.RESERVED_MEM_CURRENT) + reservedHigh = get_graph_mem_attr(driver.GraphMemAttribute.RESERVED_MEM_HIGH) 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 + driver.graph_destroy(graph) + driver.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 + driver.coredump_set_attribute_global(driver.CoredumpSettings.TRIGGER_HOST, False) + driver.coredump_set_attribute_global(driver.CoredumpSettings.FILE, b"corefile") + driver.coredump_set_attribute_global(driver.CoredumpSettings.PIPE, b"corepipe") + driver.coredump_set_attribute_global(driver.CoredumpSettings.LIGHTWEIGHT, True) 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, + driver.CoredumpSettings.TRIGGER_HOST, + driver.CoredumpSettings.FILE, + driver.CoredumpSettings.PIPE, + driver.CoredumpSettings.LIGHTWEIGHT, ] ): - err, attr_tmp = cuda.cuCoredumpGetAttributeGlobal(attr) - assert err == cuda.CUresult.CUDA_SUCCESS + attr_tmp = driver.coredump_get_attribute_global(attr) attr_list[idx] = attr_tmp assert attr_list[0] is False @@ -557,132 +526,128 @@ def test_cuda_coredump_attr(): @pytest.mark.agent_authored(model="gpt-5.6-sol") def test_coredump_bool_uses_single_byte_storage(): - helper = cuda._HelperCUcoredumpSettings(cuda.CUcoredumpSettings.CU_COREDUMP_TRIGGER_HOST, 0, is_getter=True) - ctypes.c_uint32.from_address(helper.cptr).value = 0xFFFFFFFF - ctypes.c_uint8.from_address(helper.cptr).value = 0 - - assert helper.size() == ctypes.sizeof(ctypes.c_bool) - assert helper.pyObj() is False + # Round-trip a bool-valued setting in both directions; a getter that read + # more than one byte of the storage would be affected by stale high bytes. + driver.coredump_set_attribute_global(driver.CoredumpSettings.TRIGGER_HOST, True) + assert driver.coredump_get_attribute_global(driver.CoredumpSettings.TRIGGER_HOST) is True + driver.coredump_set_attribute_global(driver.CoredumpSettings.TRIGGER_HOST, False) + assert driver.coredump_get_attribute_global(driver.CoredumpSettings.TRIGGER_HOST) is False @pytest.mark.agent_authored(model="claude-sonnet-4-6") def test_ffi_coverage_new_pointer_attributes(): - """Smoke-test that every newly added CUpointer_attribute branch can be - constructed without raising TypeError.""" + """Smoke-test that every newly added PointerAttribute can be queried + without raising TypeError (driver errors for unsupported attributes are tolerated).""" new_attrs = [ - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPING_SIZE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MEMORY_BLOCK_ID, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_IS_HW_DECOMPRESS_CAPABLE, - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_LOCALITY_DOMAIN_ORDINAL, + driver.PointerAttribute.MAPPING_SIZE, + driver.PointerAttribute.MEMORY_BLOCK_ID, + driver.PointerAttribute.IS_HW_DECOMPRESS_CAPABLE, + driver.PointerAttribute.LOCALITY_DOMAIN_ORDINAL, ] - for attr in new_attrs: - helper = cuda._HelperCUpointer_attribute(attr, 0, is_getter=True) - assert helper.cptr != 0 - _ = helper.pyObj() + ptr = driver.mem_alloc_v2(0x1000) + try: + for attr in new_attrs: + # Not supported by this driver version: tolerate driver errors + with contextlib.suppress(driver.DriverError): + driver.pointer_get_attribute(attr, ptr) + finally: + driver.mem_free_v2(ptr) @pytest.mark.agent_authored(model="claude-sonnet-4-6") def test_ffi_coverage_mapping_base_addr(): - """CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR uses the CUdeviceptr getter path.""" - helper = cuda._HelperCUpointer_attribute( - cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR, 0, is_getter=True - ) - assert helper.cptr != 0 - _ = helper.pyObj() + """PointerAttribute.MAPPING_BASE_ADDR uses the CUdeviceptr getter path.""" + ptr = driver.mem_alloc_v2(0x1000) + try: + assert driver.pointer_get_attribute(driver.PointerAttribute.MAPPING_BASE_ADDR, ptr) != 0 + finally: + driver.mem_free_v2(ptr) @pytest.mark.agent_authored(model="claude-sonnet-4-6") +@pytest.mark.skipif( + driver_version_less_than(11030) or not supportsMemoryPool(), reason="When new attributes were introduced" +) def test_ffi_coverage_new_mempool_attributes(): - """Smoke-test all newly added CUmemPool_attribute branches.""" - int_attrs = [ - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_ALLOCATION_TYPE, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCATION_ID, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCATION_TYPE, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED, - cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID, - ] - for attr in int_attrs: - helper = cuda._HelperCUmemPool_attribute(attr, 0, is_getter=True) - assert helper.cptr != 0 - assert helper.pyObj() == 0 - - uint_attr = cuda.CUmemPool_attribute.CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES - helper = cuda._HelperCUmemPool_attribute(uint_attr, 0, is_getter=True) - assert helper.cptr != 0 - assert helper.pyObj() == 0 + """Smoke-test all newly added MemPoolAttribute queries (driver errors for + attributes unsupported by this driver are tolerated).""" + pool_props = driver.MemPoolProps_v1() + pool_props.alloc_type = driver.MemAllocationType.PINNED + pool_props.location.id = 0 + pool_props.location.type = driver.MemLocationType.DEVICE + pool = driver.mem_pool_create(pool_props) + try: + for attr in [ + driver.MemPoolAttribute.ALLOCATION_TYPE, + driver.MemPoolAttribute.LOCATION_ID, + driver.MemPoolAttribute.LOCATION_TYPE, + driver.MemPoolAttribute.HW_DECOMPRESS_ENABLED, + driver.MemPoolAttribute.LOCALITY_DOMAIN_ID, + driver.MemPoolAttribute.EXPORT_HANDLE_TYPES, + ]: + # Not supported by this driver version: tolerate driver errors + with contextlib.suppress(driver.DriverError): + driver.mem_pool_get_attribute(pool, attr) + finally: + driver.mem_pool_destroy(pool) @pytest.mark.agent_authored(model="claude-sonnet-4-6") +@pytest.mark.skipif(not supportsManagedMemory(), reason="When new attributes were introduced") def test_ffi_coverage_new_mem_range_attributes(): - """Smoke-test all newly added CUmem_range_attribute branches (scalar int).""" - new_attrs = [ - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_TYPE, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION_ID, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_TYPE, - cuda.CUmem_range_attribute.CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION_ID, - ] - for attr in new_attrs: - helper = cuda._HelperCUmem_range_attribute(attr, 4) - assert helper.cptr != 0 - assert helper.pyObj() == 0 - - -@pytest.mark.agent_authored(model="claude-sonnet-4-6") -def test_ffi_coverage_jit_option_new_int_attrs(): - """Newly added int-type CUjit_option branches should construct without TypeError. - - These options use the value-cast pattern: the int value is encoded directly - in the void* slot (cptr == NULL when value is 0, which is expected). - """ - new_int_attrs = [ - cuda.CUjit_option.CU_JIT_POSITION_INDEPENDENT_CODE, - cuda.CUjit_option.CU_JIT_MAX_THREADS_PER_BLOCK, - cuda.CUjit_option.CU_JIT_OVERRIDE_DIRECTIVE_VALUES, - ] - for attr in new_int_attrs: - helper = cuda._HelperCUjit_option(attr, 1) - assert helper.cptr == 1 # value is encoded as pointer - - -@pytest.mark.agent_authored(model="claude-sonnet-4-6") -def test_ffi_coverage_jit_option_binary_loader_thread_count(): - """CU_JIT_BINARY_LOADER_THREAD_COUNT is unsigned int, value-cast like other uint options.""" - helper = cuda._HelperCUjit_option(cuda.CUjit_option.CU_JIT_BINARY_LOADER_THREAD_COUNT, 4) - assert helper.cptr != 0 - - -@pytest.mark.agent_authored(model="claude-sonnet-4-6") -def test_ffi_coverage_jit_wall_time_pointer_is_valid(): - """CU_JIT_WALL_TIME must give CUDA a valid writable float address, not a garbage pointer.""" - helper = cuda._HelperCUjit_option(cuda.CUjit_option.CU_JIT_WALL_TIME, 0.0) - # Guard against NULL so a regression fails instead of segfaulting. - assert helper.cptr != 0 - # Write a sentinel float via ctypes to confirm the pointer is addressable. - ctypes.c_float.from_address(helper.cptr).value = 3.14 - assert ctypes.c_float.from_address(helper.cptr).value == pytest.approx(3.14, rel=1e-5) + """Smoke-test all newly added MemRangeAttribute queries (scalar int).""" + size = 0x1000 + ptr = driver.mem_alloc_managed(size, driver.MemAttachFlags.GLOBAL.value) + try: + new_attrs = [ + driver.MemRangeAttribute.PREFERRED_LOCATION_TYPE, + driver.MemRangeAttribute.PREFERRED_LOCATION_ID, + driver.MemRangeAttribute.LAST_PREFETCH_LOCATION_TYPE, + driver.MemRangeAttribute.LAST_PREFETCH_LOCATION_ID, + ] + for attr in new_attrs: + # Not supported by this driver version: tolerate driver errors + with contextlib.suppress(driver.DriverError): + driver.mem_range_get_attribute(4, attr, ptr, size) + finally: + driver.mem_free_v2(ptr) @pytest.mark.agent_authored(model="claude-sonnet-4-6") def test_ffi_coverage_coredump_generation_flags(): - """CU_COREDUMP_GENERATION_FLAGS is an unsigned int bitmask.""" - helper = cuda._HelperCUcoredumpSettings(cuda.CUcoredumpSettings.CU_COREDUMP_GENERATION_FLAGS, 0, is_getter=True) - assert helper.size() == ctypes.sizeof(ctypes.c_uint) - ctypes.c_uint.from_address(helper.cptr).value = 0xDEAD - assert helper.pyObj() == 0xDEAD + """CoredumpSettings.GENERATION_FLAGS is an unsigned int bitmask.""" + settings = driver.CoredumpSettings.GENERATION_FLAGS + flags_enum = driver.CoredumpGenerationFlags + original = driver.coredump_get_attribute_global(settings) + assert isinstance(original, int) + try: + wanted = int(flags_enum.SKIP_GLOBAL_MEMORY) | int(flags_enum.SKIP_SHARED_MEMORY) + driver.coredump_set_attribute_global(settings, wanted) + assert driver.coredump_get_attribute_global(settings) == wanted + finally: + driver.coredump_set_attribute_global(settings, original) -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" +def test_get_error_name_and_string(): + device = driver.device_get(0) + s = driver.get_error_string(driver.Result.SUCCESS) + assert s == "no error" + s = driver.get_error_name(driver.Result.SUCCESS) + assert s == "CUDA_SUCCESS" + + with pytest.raises(driver.InvalidDeviceError) as excinfo: + driver.device_get(-1) + err = excinfo.value.status + s = driver.get_error_string(err) + assert s == "invalid device ordinal" + s = driver.get_error_name(err) + assert s == "CUDA_ERROR_INVALID_DEVICE" + + with pytest.raises(driver.InvalidValueError): + driver.get_error_string(123456) + with pytest.raises(driver.InvalidValueError): + driver.get_error_name(123456) # TODO: cuStreamGetCaptureInfo_v2 @@ -702,111 +667,81 @@ def test_cuda_launch_host_func_graph_replay(): def host_fn(userData): ctypes.c_int.from_address(userData).value += 1 - callback = cuda.CUhostFn(_ptr=ctypes.addressof(host_fn)) - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + callback = ctypes.cast(host_fn, ctypes.c_void_p).value + stream = driver.stream_create(0) try: - (err,) = cuda.cuStreamBeginCapture(stream, cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_GLOBAL) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuLaunchHostFunc(stream, callback, ctypes.addressof(counter)) - assert err == cuda.CUresult.CUDA_SUCCESS - err, graph = cuda.cuStreamEndCapture(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.stream_begin_capture_v2(stream, driver.StreamCaptureMode.GLOBAL) + driver.launch_host_func(stream, callback, ctypes.addressof(counter)) + graph = driver.stream_end_capture(stream) try: - err, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph_exec = driver.graph_instantiate(graph, 0) try: for launch in range(1, 6): - (err,) = cuda.cuGraphLaunch(graphExec, stream) - assert err == cuda.CUresult.CUDA_SUCCESS - (err,) = cuda.cuStreamSynchronize(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.graph_launch(graph_exec, stream) + driver.stream_synchronize(stream) assert counter.value == launch finally: - (err,) = cuda.cuGraphExecDestroy(graphExec) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.graph_exec_destroy(graph_exec) finally: - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.graph_destroy(graph) finally: - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.stream_destroy_v2(stream) 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 + driver.profiler_start() + driver.profiler_stop() def test_anon_assign(): - val1 = cuda.CUexecAffinityParam_st() - val2 = cuda.CUexecAffinityParam_st() + val1 = driver.ExecAffinityParam_v1() + val2 = driver.ExecAffinityParam_v1() - 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 + assert val1.param.sm_count.val == 0 + val1.param.sm_count.val = 5 + assert val1.param.sm_count.val == 5 + val2.param.sm_count.val = 11 + assert val2.param.sm_count.val == 11 val1.param = val2.param - assert val1.param.smCount.val == 11 + assert val1.param.sm_count.val == 11 def test_union_assign(): - val = cuda.CUlaunchAttributeValue() - val.clusterDim.x, val.clusterDim.y, val.clusterDim.z = 9, 9, 9 - attr = cuda.CUlaunchAttribute() + val = driver.LaunchAttributeValue() + val.cluster_dim.x, val.cluster_dim.y, val.cluster_dim.z = 9, 9, 9 + attr = driver.LaunchAttribute() attr.value = val - assert val.clusterDim.x == 9 - assert val.clusterDim.y == 9 - assert val.clusterDim.z == 9 + assert val.cluster_dim.x == 9 + assert val.cluster_dim.y == 9 + assert val.cluster_dim.z == 9 + assert not hasattr(val, "pad") + + # A union blob is raw bytes, not text: values that are not valid UTF-8 round-trip. + params = driver.GraphNodeParams() + assert isinstance(params.as_bytes, bytes) + raw = bytes((0x80 + i) % 256 for i in range(len(params.as_bytes))) + params.as_bytes = raw + assert params.as_bytes == raw + with pytest.raises(ValueError): + params.as_bytes = b"short" def test_invalid_repr_attribute(): - val = cuda.CUlaunchAttributeValue() + val = driver.LaunchAttributeValue() string = str(val) @pytest.mark.skipif( driver_version_less_than(12020) - or not supportsCudaAPI("cuGraphAddNode") - or not supportsCudaAPI("cuGraphNodeSetParams") - or not supportsCudaAPI("cuGraphExecNodeSetParams"), + or not supportsCudaAPI("graph_add_node_v2") + or not supportsCudaAPI("graph_node_set_params") + or not supportsCudaAPI("graph_exec_node_set_params"), reason="Polymorphic graph APIs required", ) def test_graph_poly(): - err, stream = cuda.cuStreamCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + stream = driver.stream_create(0) # cuGraphAddNode @@ -814,178 +749,150 @@ def test_graph_poly(): size = int(1024 * np.uint8().itemsize) buffers = [] for _ in range(2): - err, dptr = cuda.cuMemAlloc(size) - assert err == cuda.CUresult.CUDA_SUCCESS + dptr = driver.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 + driver.memcpy_htod_v2(device, host, size) # Create graph nodes = [] - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = driver.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 = driver.GraphNodeParams() + memsetParams.type = driver.GraphNodeType.MEMSET + memsetParams.memset.element_size = 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 + node = driver.graph_add_node_v2(graph, NO_DEPS, None, 0, memsetParams) 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.GraphNodeParams() + memcpyParams.type = driver.GraphNodeType.MEMCPY + memcpyParams.memcpy.copy_params.src_memory_type = driver.MemoryType.DEVICE + memcpyParams.memcpy.copy_params.src_device = device + memcpyParams.memcpy.copy_params.dst_memory_type = driver.MemoryType.HOST + memcpyParams.memcpy.copy_params.dst_host = host.ctypes.data + memcpyParams.memcpy.copy_params.width_in_bytes = size + memcpyParams.memcpy.copy_params.height = 1 + memcpyParams.memcpy.copy_params.depth = 1 + node = driver.graph_add_node_v2(graph, NO_DEPS, None, 0, memcpyParams) 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 = driver.graph_instantiate(graph, 0) + driver.graph_launch(graphExec, stream) + driver.stream_synchronize(stream) # Validate for host, device in buffers: - (err,) = cuda.cuMemcpyDtoH(host, device, size) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 host, device = buffers[1] - err, memcpyParamsCopy = cuda.cuGraphMemcpyNodeGetParams(nodes[1]) - assert err == cuda.CUresult.CUDA_SUCCESS - assert int(memcpyParamsCopy.srcDevice) == int(device) + memcpyParamsCopy = driver.graph_memcpy_node_get_params(nodes[1]) + 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) + memcpyParams.memcpy.copy_params.src_device = device + driver.graph_node_set_params(nodes[1], memcpyParams) + memcpyParamsCopy = driver.graph_memcpy_node_get_params(nodes[1]) + assert int(memcpyParamsCopy.src_device) == 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 + driver.graph_exec_node_set_params(graphExec, nodes[0], memsetParams) + driver.graph_launch(graphExec, stream) + driver.stream_synchronize(stream) + driver.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 + driver.mem_free_v2(buffers[0][1]) + driver.mem_free_v2(buffers[1][1]) + driver.graph_exec_destroy(graphExec) + driver.graph_destroy(graph) + driver.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) - - 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 +def test_cuDeviceGetDevResource(device, ctx): + resource_in = driver.device_get_dev_resource(device, driver.DevResourceType.SM) + resource_from_ctx = driver.ctx_get_dev_resource(ctx, driver.DevResourceType.SM) + for resource in (resource_in, resource_from_ctx): + assert isinstance(resource, driver.DevResource_v1) + assert resource.type == driver.DevResourceType.SM + assert resource.sm.sm_count > 0 + + # The wrapper queries the number of groups itself and returns all of them, plus the remainder + res, remainder = driver.dev_sm_resource_split_by_count(resource_in, 0, 2) + assert len(res) != 0 + assert isinstance(remainder, driver.DevResource_v1) + assert len(res[:3]) == min(3, len(res)) @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 + graph = driver.graph_create(0) + handle = driver.graph_conditional_handle_create(graph, ctx, 0, 0) - params = cuda.CUgraphNodeParams() - params.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_CONDITIONAL + params = driver.GraphNodeParams() + params.type = driver.GraphNodeType.CONDITIONAL params.conditional.handle = handle - params.conditional.type = cuda.CUgraphConditionalNodeType.CU_GRAPH_COND_TYPE_IF - params.conditional.size = 1 + params.conditional.type = driver.GraphConditionalNodeType.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 + # ph_graph_out is a pointer to an array of `size` graphs filled in by the driver + assert params.conditional.ph_graph_out == 0 + node = driver.graph_add_node_v2(graph, NO_DEPS, None, 0, params) - assert len(params.conditional.phGraph_out) == 1 - assert int(params.conditional.phGraph_out[0]) != 0 + assert params.conditional.ph_graph_out != 0 + assert ctypes.c_void_p.from_address(params.conditional.ph_graph_out).value != 0 def test_CUmemDecompressParams_st(): - desc = cuda.CUmemDecompressParams_st() - assert int(desc.dstActBytes) == 0 + desc = driver.MemDecompressParams() + assert int(desc.dst_act_bytes) == 0 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 + pass # enum does not exist for this code else: - err_name, name = cuda.cuGetErrorName(error) - if err_name == cuda.CUresult.CUDA_SUCCESS: + try: + name = driver.get_error_name(error) + except driver.InvalidValueError: + # enum exists but is not known to an older driver + # (example: cuda-bindings built with CTK 12.8, driver from CTK 12.0) + with pytest.raises(driver.InvalidValueError): + driver.get_error_string(error) + else: assert name - err_desc, desc = cuda.cuGetErrorString(error) - assert err_desc == cuda.CUresult.CUDA_SUCCESS + desc = driver.get_error_string(error) 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. @@ -994,26 +901,23 @@ 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.InvalidValueError): + driver.kernel_get_name(0) @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.InvalidValueError): + driver.func_get_name(0) @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): + driver.checkpoint_process_get_state(123434) @pytest.mark.skipif( @@ -1021,30 +925,33 @@ def test_cuCheckpointProcessGetState_failure(): reason="cuLogs* functions were introduced in CUDA 12.9", ) def test_culogs_functions(): + # The driver rejects a NULL callback, so register a real (no-op) one. + log_callback_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_size_t) + + def log_callback(data, level, message, length): + pass + + log_callback_c = log_callback_type(log_callback) try: - err, callback_handle = cuda.cuLogsRegisterCallback(0, None) - assert err == cuda.CUresult.CUDA_SUCCESS + callback_handle = driver.logs_register_callback(ctypes.cast(log_callback_c, ctypes.c_void_p).value, 0) - err, _ = cuda.cuLogsCurrent(0) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.logs_current(0) with tempfile.NamedTemporaryFile(delete=False) as f: log_path = f.name try: - err, _ = cuda.cuLogsDumpToFile(None, log_path.encode(), 0) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.logs_dump_to_file(0, log_path.encode(), 0) finally: os.remove(log_path) # cuLogsDumpToMemory's own docstring states the driver's internal log # buffer is capped at 25600 bytes, so a buffer of that size is always # large enough to hold the dump without risking a buffer overrun. - buf = bytearray(25600) - err, _, _ = cuda.cuLogsDumpToMemory(None, buf, len(buf), 0) - assert err == cuda.CUresult.CUDA_SUCCESS + buf = ctypes.create_string_buffer(25600) + size = ctypes.c_size_t(len(buf)) + driver.logs_dump_to_memory(0, ctypes.addressof(buf), ctypes.addressof(size), 0) - (err,) = cuda.cuLogsUnregisterCallback(callback_handle) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.logs_unregister_callback(callback_handle) except FunctionNotFoundError as e: pytest.fail(f"cuLogs* function unexpectedly not found on the driver: {e}") @@ -1055,104 +962,58 @@ 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) - - @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 + graph = driver.graph_create(0) - err, graph_id = cuda.cuGraphGetId(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + graph_id = driver.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 = driver.graph_create(0) + graph_id2 = driver.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 + driver.graph_destroy(graph) + driver.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 + stream = driver.stream_create(0) - err, graph = cuda.cuGraphCreate(0) - assert err == cuda.CUresult.CUDA_SUCCESS + graph = driver.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 + node = driver.graph_add_empty_node(graph, NO_DEPS, 0) - err, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + graphExec = driver.graph_instantiate(graph, 0) - err, graph_exec_id = cuda.cuGraphExecGetId(graphExec) - assert err == cuda.CUresult.CUDA_SUCCESS + graph_exec_id = driver.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 = driver.graph_create(0) + node2 = driver.graph_add_empty_node(graph2, NO_DEPS, 0) + graphExec2 = driver.graph_instantiate(graph2, 0) + graph_exec_id2 = driver.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 + driver.graph_exec_destroy(graphExec) + driver.graph_exec_destroy(graphExec2) + driver.graph_destroy(graph) + driver.graph_destroy(graph2) + driver.stream_destroy_v2(stream) def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): @@ -1161,29 +1022,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 = driver.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 = driver.graph_add_empty_node(graph, NO_DEPS, 0) + # A raw address of an array of handles is accepted ... + deps = node_array([n0]) + n1 = driver.graph_add_empty_node(graph, ctypes.addressof(deps), 1) + # ... as is a sequence of handles. + n2 = driver.graph_add_empty_node(graph, [n0, n1], 2) + + from_nodes, to_nodes, edge_data = driver.graph_get_edges_v2(graph) + num_edges = len(edge_data) 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 + assert len(from_nodes) == len(to_nodes) == 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 + driver.graph_get_edges_v2(graph) + driver.graph_node_get_dependencies_v2(n1) # Each wrapper must still own its data. for ed in edge_data: @@ -1191,350 +1047,353 @@ def test_cuGraphGetEdges_edgeData_outlives_call(device, ctx): assert ed.to_port == 0 assert int(ed.type) == 0 # CUgraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] - raw = (ctypes.c_uint8 * 8).from_address(ed.getPtr()) + raw = (ctypes.c_uint8 * 8).from_address(ed.ptr) assert bytes(raw[3:]) == b"\x00" * 5 finally: - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 = driver.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 = driver.graph_add_empty_node(graph, [], 0) + n1 = driver.graph_add_empty_node(graph, [n0], 1) - err, _, _, num_deps = cuda.cuGraphNodeGetDependencies(n1) - assert err == cuda.CUresult.CUDA_SUCCESS + dependencies, edge_data = driver.graph_node_get_dependencies_v2(n1) + num_deps = len(edge_data) 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 + assert len(dependencies) == 1 - err, _, _, num_dependents = cuda.cuGraphNodeGetDependentNodes(n0) - assert err == cuda.CUresult.CUDA_SUCCESS + dependents, dep_edge_data = driver.graph_node_get_dependent_nodes_v2(n0) + num_dependents = len(dep_edge_data) 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 + assert len(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 + driver.graph_node_get_dependencies_v2(n1) + driver.graph_node_get_dependent_nodes_v2(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 # CUgraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] - raw = (ctypes.c_uint8 * 8).from_address(ed.getPtr()) + raw = (ctypes.c_uint8 * 8).from_address(ed.ptr) assert bytes(raw[3:]) == b"\x00" * 5 finally: - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 + graph = driver.graph_create(0) # Add multiple nodes - err, node1 = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node1 = driver.graph_add_empty_node(graph, NO_DEPS, 0) - err, node2 = cuda.cuGraphAddEmptyNode(graph, [node1], 1) - assert err == cuda.CUresult.CUDA_SUCCESS + deps = node_array([node1]) + node2 = driver.graph_add_empty_node(graph, ctypes.addressof(deps), 1) - err, node3 = cuda.cuGraphAddEmptyNode(graph, [node1, node2], 2) - assert err == cuda.CUresult.CUDA_SUCCESS + deps = node_array([node1, node2]) + node3 = driver.graph_add_empty_node(graph, ctypes.addressof(deps), 2) # Get local IDs for each node - err, node_id1 = cuda.cuGraphNodeGetLocalId(node1) - assert err == cuda.CUresult.CUDA_SUCCESS + node_id1 = driver.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 = driver.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 = driver.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 + driver.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 + graph = driver.graph_create(0) - err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node = driver.graph_add_empty_node(graph, NO_DEPS, 0) - err, tools_node_id = cuda.cuGraphNodeGetToolsId(node) - assert err == cuda.CUresult.CUDA_SUCCESS + tools_node_id = driver.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 = node_array([node]) + node2 = driver.graph_add_empty_node(graph, ctypes.addressof(deps), 1) + tools_node_id2 = driver.graph_node_get_tools_id(node2) assert tools_node_id2 != tools_node_id - (err,) = cuda.cuGraphDestroy(graph) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 + graph = driver.graph_create(0) - err, node = cuda.cuGraphAddEmptyNode(graph, None, 0) - assert err == cuda.CUresult.CUDA_SUCCESS + node = driver.graph_add_empty_node(graph, NO_DEPS, 0) # Get the containing graph - err, containing_graph = cuda.cuGraphNodeGetContainingGraph(node) - assert err == cuda.CUresult.CUDA_SUCCESS + containing_graph = driver.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) + # Test with a child graph node # 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 = driver.graph_create(0) + child_node = driver.graph_add_empty_node(child_graph, NO_DEPS, 0) # Add child graph node to parent graph - childGraphNodeParams = cuda.CUgraphNodeParams() - childGraphNodeParams.type = cuda.CUgraphNodeType.CU_GRAPH_NODE_TYPE_GRAPH + childGraphNodeParams = driver.GraphNodeParams() + childGraphNodeParams.type = driver.GraphNodeType.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) + child_graph_node = driver.graph_add_node_v2(graph, NO_DEPS, None, 0, childGraphNodeParams) + + # Get containing graph for the child graph node + containing_graph_for_child = driver.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 - assert int(containing_graph_for_nested) == int(child_graph) + # Get containing graph for node inside child graph + containing_graph_for_nested = driver.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 + driver.graph_destroy(graph) + driver.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 + stream = driver.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.stream_get_dev_resource(stream, driver.DevResourceType.SM) + # Verify the resource was filled in + assert resource.type == driver.DevResourceType.SM - (err,) = cuda.cuStreamDestroy(stream) - assert err == cuda.CUresult.CUDA_SUCCESS + driver.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 + resource_in = driver.device_get_dev_resource(device, driver.DevResourceType.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 + group_params[0].sm_count = 4 + group_params[0].coscheduled_sm_count = 2 - err, res, rem = cuda.cuDevSmResourceSplit(nb_groups, resource_in, 0, group_params) - assert err == cuda.CUresult.CUDA_SUCCESS + res, rem = driver.dev_sm_resource_split(nb_groups, resource_in, 0, group_params) assert len(res) == nb_groups - assert rem is not None or len(res) > 0 + assert isinstance(rem, driver.DevResource_v1) # 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.device_get_dev_resource(device, driver.DevResourceType.SM) nb_groups = 2 - group_params = [ - cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), - cuda.CU_DEV_SM_RESOURCE_GROUP_PARAMS(), - ] + group_params = driver.DevSmResourceGroupParams(nb_groups) # First group: request 4 SMs with coscheduled count of 2 - group_params[0].smCount = 4 - group_params[0].coscheduledSmCount = 2 + group_params[0].sm_count = 4 + group_params[0].coscheduled_sm_count = 2 # Second group: request 4 SMs with coscheduled count of 2 - group_params[1].smCount = 4 - group_params[1].coscheduledSmCount = 2 + group_params[1].sm_count = 4 + group_params[1].coscheduled_sm_count = 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: + try: + res, rem = driver.dev_sm_resource_split(nb_groups, resource_in, 0, group_params) + except (driver.InvalidResourceConfigurationError, driver.InvalidValueError): # 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, - ) + pass + else: + assert len(res) == nb_groups # 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 + # But we test that the binding accepts a NULL group 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, + # If it fails, it should be a valid CUDA error, not a Python binding error + with contextlib.suppress(driver.InvalidValueError, driver.InvalidResourceConfigurationError): + driver.dev_sm_resource_split(nb_groups, resource_in, 0, None) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_memcpy_batch_async(device, ctx): + stream = driver.stream_create(0) + src = driver.mem_alloc_v2(16) + dst = driver.mem_alloc_v2(16) + try: + driver.memcpy_htod_v2(src, np.arange(16, dtype=np.uint8), 16) + attrs = driver.MemCpyAttributes_v1() + attrs.src_access_order = driver.MemCpySrcAccessOrder.STREAM + + driver.memcpy_batch_async( + np.array([dst], dtype=np.uint64), + np.array([src], dtype=np.uint64), + np.array([16], dtype=np.uint64), + attrs, + np.array([0], dtype=np.uint64), + stream, ) + driver.stream_synchronize(stream) + + result = np.zeros(16, dtype=np.uint8) + driver.memcpy_dtoh_v2(result, dst, 16) + assert np.array_equal(result, np.arange(16, dtype=np.uint8)) + + # Inconsistent buffers are rejected before reaching the C call. + u64 = lambda *values: np.array(values, dtype=np.uint64) # noqa: E731 + with pytest.raises(ValueError, match="same number of items"): + driver.memcpy_batch_async(u64(1, 2), u64(1), u64(1), attrs, u64(0), stream) + # Items of the wrong size would be reinterpreted by the C call. + with pytest.raises(ValueError, match="8 bytes"): + driver.memcpy_batch_async(np.array([1], dtype=np.uint32), u64(1), u64(1), attrs, u64(0), stream) + with pytest.raises(ValueError, match="both be None or both be provided"): + driver.memcpy_batch_async(u64(1), u64(1), u64(1), attrs, None, stream) + with pytest.raises(ValueError, match="same number of items"): + driver.memcpy_batch_async(u64(1), u64(1), u64(1), attrs, u64(0, 0), stream) + finally: + driver.mem_free_v2(src) + driver.mem_free_v2(dst) + driver.stream_destroy_v2(stream) -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)] - """ - ) - run_python_snippet(code) - - -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" +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +@pytest.mark.skipif(not supportsCudaAPI("device_get_host_atomic_capabilities"), reason="Requires a newer CUDA") +def test_device_get_host_atomic_capabilities_item_size(device, ctx): + operations = np.array([driver.AtomicOperation.INTEGER_ADD], dtype=np.int32) + assert len(driver.device_get_host_atomic_capabilities(operations, device)) == 1 - # Destroy the wrapper. With the fix, __dealloc__ also clears the field - # in the externally-owned struct; without it, the field remains dangling. - del inner + # int64 items would be read as pairs of 4-byte operations. + with pytest.raises(ValueError, match="4 bytes"): + driver.device_get_host_atomic_capabilities(operations.astype(np.int64), device) - 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" - ) + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_get_error_string_and_name_reject_unknown_error_code(): + with pytest.raises(driver.InvalidValueError): + driver.get_error_string(123456) + with pytest.raises(driver.InvalidValueError): + driver.get_error_name(123456) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_thread_exchange_stream_capture_mode(ctx): + # The new mode is taken as an argument and the previous one is returned. + previous = driver.thread_exchange_stream_capture_mode(driver.StreamCaptureMode.RELAXED) + try: + assert previous == driver.StreamCaptureMode.GLOBAL + assert driver.thread_exchange_stream_capture_mode(driver.StreamCaptureMode.THREAD_LOCAL) == ( + driver.StreamCaptureMode.RELAXED + ) + assert driver.thread_exchange_stream_capture_mode(previous) == driver.StreamCaptureMode.THREAD_LOCAL + finally: + driver.thread_exchange_stream_capture_mode(previous) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_driver_namespace_naming(): + # Enum members are named without the C prefix; the legacy full C names are not kept as aliases. + assert driver.GraphConditionalNodeType.IF_ == 0 + assert not hasattr(driver.GraphConditionalNodeType, "CU_GRAPH_COND_TYPE_IF") + assert not hasattr(driver.Result, "CUDA_SUCCESS") + + classes = {name: getattr(driver, name) for name in dir(driver) if isinstance(getattr(driver, name), type)} + + # Struct class names drop the C tag suffix. + assert not [name for name in classes if name.endswith(("_st", "St"))] + assert driver.StreamMemOpAtomicReductionParams is not None + + # Helper types that are used publicly are not underscore-prefixed. + params = driver.DevSmResourceGroupParams(2) + assert len(params) == 2 + assert not hasattr(driver, "_DevSmResourceGroupParams") + + # `cl_event_flags` (the NVCL scheduling enum) and `CUevent_flags` both want the name `EventFlags`. + assert driver.EventFlags is not driver.NvclEventFlags + assert driver.EventFlags.DEFAULT == 0 + assert driver.EventFlags.BLOCKING_SYNC == 1 + assert set(driver.NvclEventFlags.__members__) != set(driver.EventFlags.__members__) + + # Exceptions do not shadow Python builtins ... + exceptions = [cls for cls in classes.values() if issubclass(cls, driver.DriverError)] + assert exceptions + assert [cls.__name__ for cls in exceptions if hasattr(builtins, cls.__name__)] == [] + # ... but the status codes of the builtin-named errors are still mapped, to the prefixed classes. + assert issubclass(driver.DriverTimeoutError, driver.DriverError) + assert issubclass(driver.DriverFileNotFoundError, driver.DriverError) + assert not hasattr(driver, "TimeoutError") + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_pointer_member_is_raw_address(): + # The v2 structs never copy or take a reference to the memory a pointer member refers to: the member holds + # exactly the address it is given, and the caller keeps the buffer alive. + host = np.full(1024, 2, dtype=np.uint8) + params = driver.GraphNodeParams() + params.memcpy.copy_params.dst_host = host.ctypes.data + assert params.memcpy.copy_params.dst_host == host.ctypes.data + + # Passing the buffer object itself is rejected rather than silently storing a dangling pointer. + with pytest.raises(TypeError): + params.memcpy.copy_params.dst_host = host + + ptr = ctypes.cast(params.memcpy.copy_params.dst_host, ctypes.POINTER(ctypes.c_uint8)) + assert np.all(np.ctypeslib.as_array(ptr, shape=(host.size,)) == 2) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_array_member_assignment_and_aliased_dealloc(): + # Counterpart of the legacy double-free / dangling-pointer regressions for list-valued struct members. + # In the v2 structs the array member (`LaunchConfig.attrs`) is a raw address plus a separate count, so no + # buffer is allocated or freed by the setter, and repeated assignment must not corrupt anything. + attrs = ctypes.create_string_buffer(8 * ctypes.sizeof(ctypes.c_uint64) * 8) + outer = driver.LaunchConfig() + outer.attrs = ctypes.addressof(attrs) + outer.num_attrs = 4 + outer.attrs = 0 + outer.num_attrs = 0 + outer.attrs = ctypes.addressof(attrs) + outer.num_attrs = 8 + assert outer.attrs == ctypes.addressof(attrs) + assert outer.num_attrs == 8 + + # A wrapper aliasing the same struct must leave the member untouched when it is destroyed. + inner = driver.LaunchConfig.from_ptr(outer.ptr) + assert inner.attrs == ctypes.addressof(attrs) + del inner + assert outer.attrs == ctypes.addressof(attrs) + assert outer.num_attrs == 8 diff --git a/cuda_bindings/tests/test_cufile.py b/cuda_bindings/tests/test_cufile.py index 055f9018175..32be54836bc 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 ctx - 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 @@ -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) @@ -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 @@ -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) @@ -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") @@ -654,13 +634,11 @@ def test_cufile_write_async(tmpdir): # 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) @@ -744,13 +722,11 @@ def test_cufile_read_async(tmpdir): # 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) @@ -817,17 +793,14 @@ def test_cufile_async_read_write(tmpdir): # 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 @@ -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 @@ -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) @@ -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: @@ -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 @@ -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): @@ -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( @@ -1611,8 +1579,7 @@ def test_get_stats_l1(tmpdir): # 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) @@ -1622,7 +1589,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) @@ -1655,7 +1622,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) @@ -1690,8 +1657,7 @@ def test_get_stats_l2(tmpdir): # 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) @@ -1701,7 +1667,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) @@ -1737,7 +1703,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) @@ -1772,8 +1738,7 @@ def test_get_stats_l3(tmpdir): # 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) @@ -1783,7 +1748,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 @@ -1829,7 +1794,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 b8774af13fe..20503e8310e 100644 --- a/cuda_bindings/tests/test_interoperability.py +++ b/cuda_bindings/tests/test_interoperability.py @@ -4,8 +4,8 @@ import numpy as np import pytest -import cuda.bindings.driver as cuda import cuda.bindings.runtime as cudart +from cuda.bindings._v2 import driver # Cap for the memory pool created by test_interop_memPool. Touching the device's # default pool (e.g. via cuDeviceGetDefaultMemPool, cudaDeviceGetDefaultMemPool, @@ -14,6 +14,9 @@ # cannot be satisfied in a 39-bit address space. POOL_SIZE = 2 * 1024 * 1024 # 2 MiB +# NULL dependency array: the node has no dependencies. +NO_DEPS = 0 + def supportsMemoryPool(): err, isSupported = cudart.cudaDeviceGetAttribute(cudart.cudaDeviceAttr.cudaDevAttrMemoryPoolsSupported, 0) @@ -22,61 +25,52 @@ def supportsMemoryPool(): def test_interop_stream(): # DRV to RT - err_dr, stream = cuda.cuStreamCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + stream = driver.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 + driver.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 = driver.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 + driver.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 = driver.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 + driver.graph_destroy(int(graph)) def test_interop_graphNode(): - err_dr, graph = cuda.cuGraphCreate(0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graph = driver.graph_create(0) # DRV to RT - err_dr, node = cuda.cuGraphAddEmptyNode(graph, [], 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + node = driver.graph_add_empty_node(graph, NO_DEPS, 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 + driver.graph_destroy_node(int(node)) (err_rt,) = cudart.cudaGraphDestroy(graph) assert err_rt == cudart.cudaError_t.cudaSuccess @@ -97,14 +91,13 @@ def test_interop_memPool(): # Use a small, capped pool instead of the device's default pool. The pool # must be set before it is queried below because the getters create (and # reserve address space for) the default pool if none has been set. - props = cuda.CUmemPoolProps() - props.allocType = cuda.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED - props.handleTypes = cuda.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_NONE - props.location.type = cuda.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE + props = driver.MemPoolProps_v1() + props.alloc_type = driver.MemAllocationType.PINNED + props.handle_types = driver.MemAllocationHandleType.NONE + props.location.type = driver.MemLocationType.DEVICE props.location.id = 0 - props.maxSize = POOL_SIZE - err_dr, pool = cuda.cuMemPoolCreate(props) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + props.max_size = POOL_SIZE + pool = driver.mem_pool_create(props) try: # DRV to RT @@ -114,31 +107,25 @@ def test_interop_memPool(): # RT to DRV err_rt, rt_pool = cudart.cudaDeviceGetMemPool(0) assert err_rt == cudart.cudaError_t.cudaSuccess - assert int(rt_pool) == int(pool) - (err_dr,) = cuda.cuDeviceSetMemPool(0, rt_pool) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + assert int(rt_pool) == pool + driver.device_set_mem_pool(0, int(rt_pool)) finally: - (err_dr,) = cuda.cuMemPoolDestroy(pool) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + driver.mem_pool_destroy(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 = driver.graph_create(0) + node = driver.graph_add_empty_node(graph, NO_DEPS, 0) # DRV to RT - err_dr, graphExec = cuda.cuGraphInstantiate(graph, 0) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + graphExec = driver.graph_instantiate(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 + driver.graph_exec_destroy(int(graphExec)) (err_rt,) = cudart.cudaGraphDestroy(graph) assert err_rt == cudart.cudaError_t.cudaSuccess @@ -147,8 +134,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 = driver.mem_alloc_v2(size) # Allocate host memory h1 = np.full(size, 1).astype(np.uint8) @@ -167,5 +153,4 @@ def test_interop_deviceptr(): assert np.array_equal(h1, h2) # Cleanup - (err_dr,) = cuda.cuMemFree(dptr) - assert err_dr == cuda.CUresult.CUDA_SUCCESS + driver.mem_free_v2(dptr) diff --git a/cuda_bindings/tests/test_kernelParams.py b/cuda_bindings/tests/test_kernelParams.py index 3457965086e..e05b3859887 100644 --- a/cuda_bindings/tests/test_kernelParams.py +++ b/cuda_bindings/tests/test_kernelParams.py @@ -7,15 +7,12 @@ import pytest import cuda.bindings._v2.nvrtc as nvrtc -import cuda.bindings.driver as cuda import cuda.bindings.runtime as cudart +from cuda.bindings._v2 import driver 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 = driver.device_get_attribute(driver.DeviceAttribute.COMPUTE_CAPABILITY_MAJOR, dev) + minor = driver.device_get_attribute(driver.DeviceAttribute.COMPUTE_CAPABILITY_MINOR, dev) _, nvrtc_minor = nvrtc.version() use_cubin = nvrtc_minor >= 1 prefix = "sm" if use_cubin else "compute" @@ -46,8 +41,7 @@ def common_nvrtc(allKernelStrings, dev): else: data = nvrtc.get_ptx(prog) - err, module = cuda.cuModuleLoadData(np.char.array(data)) - ASSERT_DRV(err) + module = driver.module_load_data(np.char.array(data)) return module @@ -66,13 +60,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 = driver.module_get_function(module, b"empty_kernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.stream_create(0) - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -85,8 +77,7 @@ def test_kernelParams_empty(device): ((), ()), 0, ) # arguments - ASSERT_DRV(err) - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -99,23 +90,30 @@ 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 = driver.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) + driver.memcpy_dtoh_async_v2(ctypes.addressof(isDone_host), isDonePtr_device, ctypes.sizeof(ctypes.c_bool), stream) + driver.stream_synchronize(stream) assert isDone_host.value is True - (err,) = cuda.cuStreamDestroy(stream) - ASSERT_DRV(err) - (err,) = cuda.cuModuleUnload(module) - ASSERT_DRV(err) + driver.stream_destroy_v2(stream) + driver.module_unload(module) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_module_get_function_errors(device): + module = common_nvrtc('extern "C" __global__ void empty_kernel() {}', device) + try: + # Symbol names are `bytes`, as in the legacy API; a `str` is not encoded implicitly. + with pytest.raises(driver.NotFoundError): + driver.module_get_function(module, b"no_such_kernel") + with pytest.raises(ValueError): + driver.module_get_function(module, "empty_kernel") + finally: + driver.module_unload(module) @pytest.mark.parametrize("use_ctypes_as_values", [False, True], ids=["no-ctypes", "ctypes"]) @@ -254,69 +252,51 @@ def test_kernelParams(use_ctypes_as_values, device): module = common_nvrtc(basicKernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"basic") - ASSERT_DRV(err) + kernel = driver.module_get_function(module, b"basic") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.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 = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_bool)) + pc = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_char)) + pwc = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_wchar)) + pbyte = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_byte)) + pubyte = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_ubyte)) + ps = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_short)) + pus = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_ushort)) + pi = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_int)) + pui = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_uint)) + pl = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_long)) + pul = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_ulong)) + pll = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_longlong)) + pull = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_ulonglong)) + psize = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_size_t)) + pf = driver.mem_alloc_v2(ctypes.sizeof(ctypes.c_float)) + pd = driver.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, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_void_p, ) basicKernelValues = assertValues_host + assertValues_device basicKernelTypes = assertTypes_host + assertTypes_device - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -329,19 +309,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 + driver.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) + driver.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 +329,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) + driver.mem_free_v2(pb) + driver.mem_free_v2(pc) + driver.mem_free_v2(pwc) + driver.mem_free_v2(pbyte) + driver.mem_free_v2(pubyte) + driver.mem_free_v2(ps) + driver.mem_free_v2(pus) + driver.mem_free_v2(pi) + driver.mem_free_v2(pui) + driver.mem_free_v2(pl) + driver.mem_free_v2(pul) + driver.mem_free_v2(pll) + driver.mem_free_v2(pull) + driver.mem_free_v2(psize) + driver.mem_free_v2(pf) + driver.mem_free_v2(pd) + driver.stream_destroy_v2(stream) + driver.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 = driver.device_get_attribute(driver.DeviceAttribute.UNIFIED_ADDRESSING, device) err, perr = cudart.cudaMalloc(ctypes.sizeof(ctypes.c_int)) ASSERT_DRV(err) @@ -448,13 +404,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 = driver.module_get_function(module, b"structsCuda") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.stream_create(0) - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -467,7 +421,6 @@ def test_kernelParams_types_cuda(device): (kernelValues, kernelTypes), 0, ) # arguments - ASSERT_DRV(err) # Retrieve each dptr host_err = ctypes.c_int() @@ -481,8 +434,7 @@ def test_kernelParams_types_cuda(device): ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + driver.stream_synchronize(stream) cuda_err = cudart.cudaError_t(host_err.value) if uvaSupported: @@ -506,17 +458,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) + driver.stream_destroy_v2(stream) + driver.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 = driver.device_get_attribute(driver.DeviceAttribute.UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -532,11 +479,9 @@ def test_kernelParams_struct_custom(device): module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"structCustom") - ASSERT_DRV(err) + kernel = driver.module_get_function(module, b"structCustom") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.stream_create(0) # structCustom kernel class testStruct(ctypes.Structure): @@ -554,7 +499,7 @@ class testStruct(ctypes.Structure): kernelValues = (testStruct(5), pStruct_device) kernelTypes = (None, ctypes.c_void_p) - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -567,28 +512,21 @@ class testStruct(ctypes.Structure): (kernelValues, kernelTypes), 0, ) # arguments - ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + driver.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) + driver.stream_destroy_v2(stream) + driver.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 = driver.device_get_attribute(driver.DeviceAttribute.UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -607,11 +545,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 = driver.module_get_function(module, b"testkernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.stream_create(0) # testkernel kernel class testStruct(ctypes.Structure): @@ -653,7 +589,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( + driver.launch_kernel( kernel, 1, 1, @@ -666,28 +602,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) + driver.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) + driver.stream_destroy_v2(stream) + driver.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 = driver.device_get_attribute(driver.DeviceAttribute.UNIFIED_ADDRESSING, device) kernelString = """\ struct testStruct { @@ -706,11 +635,9 @@ def test_kernelParams_buffer_protocol_numpy(device): module = common_nvrtc(kernelString, device) - err, kernel = cuda.cuModuleGetFunction(module, b"testkernel") - ASSERT_DRV(err) + kernel = driver.module_get_function(module, b"testkernel") - err, stream = cuda.cuStreamCreate(0) - ASSERT_DRV(err) + stream = driver.stream_create(0) # testkernel kernel testStruct = np.dtype([("value", np.int32)]) @@ -749,7 +676,7 @@ def test_kernelParams_buffer_protocol_numpy(device): ) packagedParams = np.array([arg.ctypes.data for arg in kernelValues], dtype=np.uint64) - (err,) = cuda.cuLaunchKernel( + driver.launch_kernel( kernel, 1, 1, @@ -762,11 +689,9 @@ def test_kernelParams_buffer_protocol_numpy(device): packagedParams, 0, ) # arguments - ASSERT_DRV(err) # Validate kernel values - (err,) = cuda.cuStreamSynchronize(stream) - ASSERT_DRV(err) + driver.stream_synchronize(stream) class numpy_address_wrapper: def __init__(self, address, typestr): @@ -778,10 +703,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) + driver.stream_destroy_v2(stream) + driver.module_unload(module) def test_kernelParams_c_int_out_of_range_raises(device): @@ -791,25 +714,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 = driver.module_get_function(module, b"take_int") + stream = driver.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) + driver.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) + driver.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) + driver.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) + driver.stream_synchronize(stream) + driver.stream_destroy_v2(stream) + driver.module_unload(module) diff --git a/cuda_bindings/tests/test_nvrtc.py b/cuda_bindings/tests/test_nvrtc.py index fd73b86eaa2..507a60f47aa 100644 --- a/cuda_bindings/tests/test_nvrtc.py +++ b/cuda_bindings/tests/test_nvrtc.py @@ -20,9 +20,9 @@ def test_get_supported_archs(): @pytest.mark.skipif(nvrtc_version_less_than(12, 1), reason="Preempt Segmentation Fault (see #499)") def test_get_lowered_name_failure(): with pytest.raises(nvrtc.InvalidProgramError): - nvrtc.get_lowered_name(0, b"I'm an elevated name!") + nvrtc.get_lowered_name(0, "I'm an elevated name!") with pytest.raises(nvrtc.InvalidProgramError): - nvrtc.get_lowered_name(0, b"I'm another elevated name!") + nvrtc.get_lowered_name(0, "I'm another elevated name!") @pytest.mark.agent_authored(model="claude-sonnet-5") @@ -39,4 +39,34 @@ def test_get_bundled_headers_info(): assert info.cuda_version_major >= 0 assert info.cuda_version_minor >= 0 assert info.num_files >= 0 - assert error_log is None + # No error: the error log is empty. + assert error_log == b"" + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +@pytest.mark.skipif(nvrtc_version_less_than(13, 3), reason="When nvrtcInstallBundledHeaders was introduced") +def test_install_and_remove_bundled_headers(tmp_path): + install_path = str(tmp_path / "headers") + + # The error log is empty on success. + assert nvrtc.install_bundled_headers(install_path, 0) == b"" + assert any((tmp_path / "headers").iterdir()) + assert nvrtc.remove_bundled_headers(install_path) == b"" + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_get_lowered_name(): + # destroy_program takes `nvrtcProgram *`: passing the handle value itself as that pointer + # corrupts the heap and aborts the process. + for _ in range(8): + scratch = nvrtc.create_program(b'extern "C" __global__ void k() {}', b"k.cu", [], []) + assert scratch != 0 + nvrtc.destroy_program(scratch) + + prog = nvrtc.create_program(b'extern "C" __global__ void k() {}', b"k.cu", [], []) + try: + nvrtc.add_name_expression(prog, "k") + nvrtc.compile_program(prog, []) + assert nvrtc.get_lowered_name(prog, "k") == b"k" + finally: + nvrtc.destroy_program(prog) diff --git a/cuda_core/cuda/core/system/exceptions.py b/cuda_core/cuda/core/system/exceptions.py index 21f258edb1f..108ec7c45c3 100644 --- a/cuda_core/cuda/core/system/exceptions.py +++ b/cuda_core/cuda/core/system/exceptions.py @@ -15,6 +15,7 @@ InsufficientSizeError = nvml.InsufficientSizeError InsufficientPowerError = nvml.InsufficientPowerError DriverNotLoadedError = nvml.DriverNotLoadedError +NvmlTimeoutError = nvml.TimeoutError TimeoutError = nvml.TimeoutError IrqIssueError = nvml.IrqIssueError LibraryNotFoundError = nvml.LibraryNotFoundError @@ -25,6 +26,7 @@ OperatingSystemError = nvml.OperatingSystemError LibRmVersionMismatchError = nvml.LibRmVersionMismatchError InUseError = nvml.InUseError +NvmlMemoryError = nvml.MemoryError MemoryError = nvml.MemoryError NoDataError = nvml.NoDataError VgpuEccNotSupportedError = nvml.VgpuEccNotSupportedError diff --git a/cuda_core/docs/source/release/1.3.0-notes.rst b/cuda_core/docs/source/release/1.3.0-notes.rst index f292bb209a6..49def503809 100644 --- a/cuda_core/docs/source/release/1.3.0-notes.rst +++ b/cuda_core/docs/source/release/1.3.0-notes.rst @@ -300,3 +300,13 @@ Fixes and enhancements while operands from plain ``cuMemAlloc`` allocations accept it. The node's ``repr`` now shows ``U`` for unified operands. (`#2649 `__) + +Deprecations +------------ + +- Two ``cuda.core.system`` exception classes were renamed so that they no longer have the same name as a Python builtin + exception. Code that did ``from cuda.core.system import *`` + replaced the builtin ``TimeoutError`` and ``MemoryError`` in its namespace. Update code that refers to the old names: + + - ``TimeoutError`` is now ``NvmlTimeoutError``. + - ``MemoryError`` is now ``NvmlMemoryError``.