# SPDX-FileCopyrightText: Copyright (c) 2021-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import contextlib import ctypes import math import threading import numpy as np import pytest from cuda_python_test_helpers.memory import POOL_SIZE, supports_memory_pools from cuda import pathfinder from cuda.bindings._v2 import driver, runtime from cuda_python_test_helpers import driver_version_less_than # NULL dependency array: the node has no dependencies. NO_DEPS = 0 def supportsSparseTexturesDeviceFilter(): return bool(runtime.device_get_attribute(runtime.DeviceAttr.SPARSE_CUDA_ARRAY_SUPPORTED, 0)) def supportsCudaAPI(name): return name in dir(driver) or name in dir(runtime) @pytest.mark.agent_authored(model="claude-opus-5") def test_supportsCudaAPI(): # Guards the operator precedence: `name in dir(driver) or dir(runtime)` parses # as `(name in dir(driver)) or dir(runtime)`, which is truthy for every name. assert supportsCudaAPI("malloc") is True # runtime module assert supportsCudaAPI("init") is True # driver module assert supportsCudaAPI("this_is_not_a_cuda_api") is False def test_cudart_memcpy(): # Allocate dev memory size = 1024 * np.uint8().itemsize dptr = runtime.malloc(size) # 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 runtime.memcpy(dptr, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # D to h2 runtime.memcpy(h2, dptr, size, runtime.MemCpyKind.DEVICE_TO_HOST) # Validate h1 == h2 assert np.array_equal(h1, h2) # Cleanup runtime.free(dptr) def test_cudart_hostRegister(): # Use hostRegister API to check for correct error reporting page_size = 80 addr_host = np.full(page_size * 3, 1).astype(np.uint8) addr = addr_host.ctypes.data size_0 = (16 * page_size) // 8 addr_0 = addr + int((0 * page_size) / 8) size_1 = (16 * page_size) // 8 addr_1 = addr + int((8 * page_size) / 8) runtime.host_register(addr_0, size_0, 3) with pytest.raises(runtime.HostMemoryAlreadyRegisteredError): runtime.host_register(addr_1, size_1, 3) with pytest.raises(runtime.InvalidValueError): runtime.host_unregister(addr_1) runtime.host_unregister(addr_0) def test_cudart_class_reference(): offset = 1 width = 4 height = 5 depth = 6 flags = 0 numMipLevels = 1 extent = runtime.Extent() formatDesc = runtime.ChannelFormatDesc() externalMemoryMipmappedArrayDesc = runtime.ExternalMemoryMipmappedArrayDesc() # Get/set class attributes extent.width = width extent.height = height extent.depth = depth formatDesc.x = 8 formatDesc.y = 0 formatDesc.z = 0 formatDesc.w = 0 formatDesc.f = runtime.ChannelFormatKind.SIGNED externalMemoryMipmappedArrayDesc.offset = offset externalMemoryMipmappedArrayDesc.format_desc = formatDesc externalMemoryMipmappedArrayDesc.extent = extent externalMemoryMipmappedArrayDesc.flags_ = flags externalMemoryMipmappedArrayDesc.num_levels = numMipLevels # Can manipulate child structure values directly externalMemoryMipmappedArrayDesc.extent.width = width + 1 externalMemoryMipmappedArrayDesc.extent.height = height + 1 externalMemoryMipmappedArrayDesc.extent.depth = depth + 1 assert externalMemoryMipmappedArrayDesc.extent.width == width + 1 assert externalMemoryMipmappedArrayDesc.extent.height == height + 1 assert externalMemoryMipmappedArrayDesc.extent.depth == depth + 1 externalMemoryMipmappedArrayDesc.format_desc.x = 20 externalMemoryMipmappedArrayDesc.format_desc.y = 21 externalMemoryMipmappedArrayDesc.format_desc.z = 22 externalMemoryMipmappedArrayDesc.format_desc.w = 23 externalMemoryMipmappedArrayDesc.format_desc.f = runtime.ChannelFormatKind.FLOAT assert externalMemoryMipmappedArrayDesc.format_desc.x == 20 assert externalMemoryMipmappedArrayDesc.format_desc.y == 21 assert externalMemoryMipmappedArrayDesc.format_desc.z == 22 assert externalMemoryMipmappedArrayDesc.format_desc.w == 23 assert externalMemoryMipmappedArrayDesc.format_desc.f == runtime.ChannelFormatKind.FLOAT # Can copy classes over externalMemoryMipmappedArrayDesc.extent = extent assert externalMemoryMipmappedArrayDesc.extent.width == width assert externalMemoryMipmappedArrayDesc.extent.height == height assert externalMemoryMipmappedArrayDesc.extent.depth == depth externalMemoryMipmappedArrayDesc.format_desc = formatDesc assert externalMemoryMipmappedArrayDesc.format_desc.x == 8 assert externalMemoryMipmappedArrayDesc.format_desc.y == 0 assert externalMemoryMipmappedArrayDesc.format_desc.z == 0 assert externalMemoryMipmappedArrayDesc.format_desc.w == 0 assert externalMemoryMipmappedArrayDesc.format_desc.f == runtime.ChannelFormatKind.SIGNED @pytest.mark.skipif(not supportsSparseTexturesDeviceFilter(), reason="Sparse Texture Device Filter") def test_cudart_class_inline(): extent = runtime.Extent() extent.width = 1000 extent.height = 500 extent.depth = 0 desc = runtime.ChannelFormatDesc() desc.x = 32 desc.y = 32 desc.z = 32 desc.w = 32 desc.f = runtime.ChannelFormatKind.FLOAT numChannels = 4 numBytesPerChannel = desc.x / 8 numBytesPerTexel = numChannels * numBytesPerChannel flags = runtime.ArrayFlags.SPARSE maxDim = max(extent.width, extent.height) numLevels = int(1.0 + math.log(maxDim, 2)) mipmap = runtime.malloc_mipmapped_array(desc, extent, numLevels, flags) sparseProp = runtime.mipmapped_array_get_sparse_properties(mipmap) # tileExtent # TODO: Will these values always be this same? Maybe need a more stable test? # TODO: Are these values even correct? Need to research the function some more.. Maybe need an easier API test assert sparseProp.tile_extent.width == 64 assert sparseProp.tile_extent.height == 64 assert sparseProp.tile_extent.depth == 1 sparsePropNew = runtime.ArraySparseProperties() sparsePropNew.tile_extent.width = 15 sparsePropNew.tile_extent.height = 16 sparsePropNew.tile_extent.depth = 17 # Check that we can copy inner structs sparseProp.tile_extent = sparsePropNew.tile_extent assert sparseProp.tile_extent.width == 15 assert sparseProp.tile_extent.height == 16 assert sparseProp.tile_extent.depth == 17 assert sparseProp.miptail_first_level == 3 assert sparseProp.miptail_size == 196608 assert sparseProp.flags_ == 0 runtime.free_mipmapped_array(mipmap) _exercise_external_semaphore_signal_params() def _exercise_external_semaphore_signal_params(): # TODO example = runtime.ExternalSemaphoreSignalNodeParams() # The array members take the address of the underlying C array ext_sems = (ctypes.c_void_p * 3)(0, 123, 999) example.ext_sem_array = ctypes.addressof(ext_sems) a1 = runtime.ExternalSemaphoreSignalParams() a1.params.fence.value = 7 a1.params.nv_sci_sync.fence = 999 a1.params.keyed_mutex.key = 9 a1.flags_ = 1 a2 = runtime.ExternalSemaphoreSignalParams() a2.params.fence.value = 7 a2.params.nv_sci_sync.fence = 999 a2.params.keyed_mutex.key = 9 a2.flags_ = 2 a3 = runtime.ExternalSemaphoreSignalParams() a3.params.fence.value = 7 a3.params.nv_sci_sync.fence = 999 a3.params.keyed_mutex.key = 9 a3.flags_ = 3 example.params_array = a1.ptr # Note: Setting is a pass by value. Changing the object does not reflect internal value a3.params.fence.value = 4 a3.params.nv_sci_sync.fence = 4 a3.params.keyed_mutex.key = 4 a3.flags_ = 4 example.num_ext_sems = 3 def test_cudart_graphs(): graph = runtime.graph_create(0) pGraphNode0 = runtime.graph_add_empty_node(graph, None) pGraphNode1 = runtime.graph_add_empty_node(graph, [pGraphNode0]) pGraphNode2 = runtime.graph_add_empty_node(graph, [pGraphNode0, pGraphNode1]) nodes = runtime.graph_get_nodes(graph) assert len(nodes) == 3 stream_with_flags = runtime.stream_create_with_flags(runtime.StreamFlags.NON_BLOCKING) runtime.stream_destroy(stream_with_flags) runtime.graph_destroy(graph) def test_cudart_cudaGraphGetEdges_edgeData_outlives_call(): # Regression test for https://github.com/NVIDIA/cuda-python/issues/1804 # cudaGraphGetEdges previously returned cudaGraphEdgeData wrappers backed # by a scratch buffer that was freed before the call returned, leaving # the wrappers pointing at freed memory. Ensure the returned objects # remain readable after the call and after subsequent allocations. graph = runtime.graph_create(0) try: n0 = runtime.graph_add_empty_node(graph, None) n1 = runtime.graph_add_empty_node(graph, [n0]) n2 = runtime.graph_add_empty_node(graph, [n0, n1]) from_nodes, to_nodes, edge_data = runtime.graph_get_edges(graph) num_edges = len(edge_data) assert len(from_nodes) == len(to_nodes) == num_edges == 3 # Stir the heap to make a use-after-free more likely to surface # by reallocating the same-sized scratch buffer many times. for _ in range(64): runtime.graph_get_edges(graph) # Each wrapper must still own its data. Default-edge values are zero; # if the wrapper were holding a dangling pointer, attribute access # would be undefined behavior. We at minimum require it to not crash # and to report the documented defaults. for ed in edge_data: assert ed.from_port == 0 assert ed.to_port == 0 assert int(ed.type) == 0 # cudaGraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] raw = (ctypes.c_uint8 * 8).from_address(ed.ptr) assert bytes(raw[3:]) == b"\x00" * 5 finally: runtime.graph_destroy(graph) def test_cudart_cudaGraphNodeGetDependencies_edgeData_outlives_call(): # Companion regression test for #1804 covering the dependency-query path. graph = runtime.graph_create(0) try: n0 = runtime.graph_add_empty_node(graph, None) n1 = runtime.graph_add_empty_node(graph, [n0]) deps, edge_data = runtime.graph_node_get_dependencies(n1) num_deps = len(deps) assert len(edge_data) == num_deps == 1 dependents, dep_edge_data = runtime.graph_node_get_dependent_nodes(n0) num_dependents = len(dependents) assert len(dep_edge_data) == num_dependents == 1 for _ in range(64): runtime.graph_node_get_dependencies(n1) runtime.graph_node_get_dependent_nodes(n0) 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 # cudaGraphEdgeData_st layout: from_port(1), to_port(1), type(1), reserved[5] raw = (ctypes.c_uint8 * 8).from_address(ed.ptr) assert bytes(raw[3:]) == b"\x00" * 5 finally: runtime.graph_destroy(graph) def test_cudart_list_access(): prop = runtime.get_device_properties(0) prop.name = prop.name + " " * (255 - len(prop.name)) def test_cudart_class_setters(): dim = runtime.Dim3() dim.x = 1 dim.y = 2 dim.z = 3 assert dim.x == 1 assert dim.y == 2 assert dim.z == 3 def test_cudart_both_type(): mode = runtime.thread_exchange_stream_capture_mode(runtime.StreamCaptureMode.GLOBAL) mode = runtime.thread_exchange_stream_capture_mode(runtime.StreamCaptureMode.RELAXED) assert mode == runtime.StreamCaptureMode.GLOBAL mode = runtime.thread_exchange_stream_capture_mode(runtime.StreamCaptureMode.THREAD_LOCAL) assert mode == runtime.StreamCaptureMode.RELAXED mode = runtime.thread_exchange_stream_capture_mode(runtime.StreamCaptureMode.GLOBAL) assert mode == runtime.StreamCaptureMode.THREAD_LOCAL def test_cudart_cudaGetDeviceProperties(): prop = runtime.get_device_properties(0) attrs = [ "name", "uuid", "luid", "luid_device_node_mask", "total_global_mem", "shared_mem_per_block", "regs_per_block", "warp_size", "mem_pitch", "max_threads_per_block", "max_threads_dim", "max_grid_size", "total_const_mem", "major", "minor", "texture_alignment", "texture_pitch_alignment", "multi_processor_count", "integrated", "can_map_host_memory", "max_texture1d", "max_texture1d_mipmap", "max_texture2d", "max_texture2d_mipmap", "max_texture2d_linear", "max_texture2d_gather", "max_texture3d", "max_texture3d_alt", "max_texture_cubemap", "max_texture1d_layered", "max_texture2d_layered", "max_texture_cubemap_layered", "max_surface1d", "max_surface2d", "max_surface3d", "max_surface1d_layered", "max_surface2d_layered", "max_surface_cubemap", "max_surface_cubemap_layered", "surface_alignment", "concurrent_kernels", "ecc_enabled", "pci_bus_id", "pci_device_id", "pci_domain_id", "tcc_driver", "async_engine_count", "unified_addressing", "memory_bus_width", "l2cache_size", "persisting_l2cache_max_size", "max_threads_per_multi_processor", "stream_priorities_supported", "global_l1cache_supported", "local_l1cache_supported", "shared_mem_per_multiprocessor", "regs_per_multiprocessor", "managed_memory", "is_multi_gpu_board", "multi_gpu_board_group_id", "host_native_atomic_supported", "pageable_memory_access", "concurrent_managed_access", "compute_preemption_supported", "can_use_host_pointer_for_registered_mem", "cooperative_launch", "shared_mem_per_block_optin", "pageable_memory_access_uses_host_page_tables", "direct_managed_mem_access_from_host", "max_blocks_per_multi_processor", "access_policy_max_window_size", "reserved_shared_mem_per_block", "host_register_supported", "sparse_cuda_array_supported", "host_register_read_only_supported", "timeline_semaphore_interop_supported", "memory_pools_supported", "gpu_direct_rdma_supported", "gpu_direct_rdma_flush_writes_options", "gpu_direct_rdma_writes_ordering", "memory_pool_supported_handle_types", "deferred_mapping_cuda_array_supported", "ipc_event_supported", "cluster_launch", "unified_function_pointers", "device_numa_config", "device_numa_id", "mps_enabled", "host_numa_id", "gpu_pci_device_id", "gpu_pci_subsystem_id", "host_numa_multinode_ipc_supported", ] for attr in attrs: assert hasattr(prop, attr) assert len(prop.name) != 0 assert len(bytes(prop.uuid).hex()) != 0 _exercise_external_semaphore_signal_params() @pytest.mark.skipif( driver_version_less_than(11030) or not supports_memory_pools(), reason="When new attributes were introduced" ) def test_cudart_MemPool_attr(): poolProps = runtime.MemPoolProps() poolProps.alloc_type = runtime.MemAllocationType.PINNED poolProps.location.id = 0 poolProps.location.type = runtime.MemLocationType.DEVICE poolProps.max_size = POOL_SIZE attr_list = [None] * 8 pool = runtime.mem_pool_create(poolProps) for idx, attr in enumerate( [ runtime.MemPoolAttr.REUSE_FOLLOW_EVENT_DEPENDENCIES, runtime.MemPoolAttr.REUSE_ALLOW_OPPORTUNISTIC, runtime.MemPoolAttr.REUSE_ALLOW_INTERNAL_DEPENDENCIES, runtime.MemPoolAttr.RELEASE_THRESHOLD, runtime.MemPoolAttr.RESERVED_MEM_CURRENT, runtime.MemPoolAttr.RESERVED_MEM_HIGH, runtime.MemPoolAttr.USED_MEM_CURRENT, runtime.MemPoolAttr.USED_MEM_HIGH, ] ): attr_list[idx] = runtime.mem_pool_get_attribute(pool, attr) for idxA, attr in enumerate( [ runtime.MemPoolAttr.REUSE_FOLLOW_EVENT_DEPENDENCIES, runtime.MemPoolAttr.REUSE_ALLOW_OPPORTUNISTIC, runtime.MemPoolAttr.REUSE_ALLOW_INTERNAL_DEPENDENCIES, ] ): runtime.mem_pool_set_attribute(pool, attr, 0) for idx, attr in enumerate([runtime.MemPoolAttr.RELEASE_THRESHOLD]): runtime.mem_pool_set_attribute(pool, attr, 9) for idx, attr in enumerate( [ runtime.MemPoolAttr.REUSE_FOLLOW_EVENT_DEPENDENCIES, runtime.MemPoolAttr.REUSE_ALLOW_OPPORTUNISTIC, runtime.MemPoolAttr.REUSE_ALLOW_INTERNAL_DEPENDENCIES, runtime.MemPoolAttr.RELEASE_THRESHOLD, ] ): attr_list[idx] = runtime.mem_pool_get_attribute(pool, attr) assert attr_list[0] == 0 assert attr_list[1] == 0 assert attr_list[2] == 0 assert int(attr_list[3]) == 9 runtime.mem_pool_destroy(pool) def test_cudart_make_api(): channelDesc = runtime.create_channel_desc(32, 0, 0, 0, runtime.ChannelFormatKind.FLOAT) assert channelDesc.x == 32 assert channelDesc.y == 0 assert channelDesc.z == 0 assert channelDesc.w == 0 assert channelDesc.f == runtime.ChannelFormatKind.FLOAT # make_cudaPitchedPtr cudaPitchedPtr = runtime.make_pitched_ptr(1, 2, 3, 4) assert cudaPitchedPtr.ptr_ == 1 assert cudaPitchedPtr.pitch == 2 assert cudaPitchedPtr.xsize == 3 assert cudaPitchedPtr.ysize == 4 # make_cudaPos cudaPos = runtime.make_pos(1, 2, 3) assert cudaPos.x == 1 assert cudaPos.y == 2 assert cudaPos.z == 3 # make_cudaExtent cudaExtent = runtime.make_extent(1, 2, 3) assert cudaExtent.width == 1 assert cudaExtent.height == 2 assert cudaExtent.depth == 3 def test_cudart_cudaStreamGetCaptureInfo(): # create stream stream = runtime.stream_create() # validate that stream is not capturing status, *info = runtime.stream_get_capture_info(stream) assert status == runtime.StreamCaptureStatus.NONE # start capture # Thread-local mode: pytest-run-parallel runs this test in several threads # at once, and in global mode a call such as cudaGraphInstantiate in one # thread fails while another thread is capturing. runtime.stream_begin_capture(stream, runtime.StreamCaptureMode.THREAD_LOCAL) # validate that stream is capturing now status, *info = runtime.stream_get_capture_info(stream) assert status == runtime.StreamCaptureStatus.ACTIVE # clean up pgraph = runtime.stream_end_capture(stream) def test_cudart_cudaArrayGetInfo(): # create channel descriptor x, y, z, w = 8, 0, 0, 0 f = runtime.ChannelFormatKind.UNSIGNED desc = runtime.create_channel_desc(x, y, z, w, f) # allocate device array width = 10 height = 0 inFlags = 0 arr = runtime.malloc_array(desc, width, height, inFlags) # get device array info desc, extent, outFlags = runtime.array_get_info(arr) # validate descriptor, extent, flags assert desc.x == x assert desc.y == y assert desc.z == z assert desc.w == w assert desc.f == f assert extent.width == width assert extent.height == height assert inFlags == outFlags # clean up runtime.free_array(arr) def test_cudart_cudaMemcpy2DToArray(): # create host arrays size = int(1024 * np.uint8().itemsize) h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # h1 to arr runtime.memcpy_2d_to_array(arr, 0, 0, h1, size, size, 1, runtime.MemCpyKind.HOST_TO_DEVICE) # arr to h2 runtime.memcpy_2d_from_array(h2, size, arr, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) def test_cudart_cudaMemcpy2DToArray_DtoD(): # allocate device memory size = 1024 * np.uint8().itemsize d1 = runtime.malloc(size) d2 = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # h1 to d1 runtime.memcpy(d1, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # d1 to arr runtime.memcpy_2d_to_array(arr, 0, 0, d1, size, size, 1, runtime.MemCpyKind.DEVICE_TO_DEVICE) # arr to d2 runtime.memcpy_2d_from_array(d2, size, arr, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_DEVICE) # d2 to h2 runtime.memcpy(h2, d2, size, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) runtime.free(d2) runtime.free(d1) def test_cudart_cudaMemcpy2DArrayToArray(): # create host arrays size = 1024 * np.uint8().itemsize h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device arrays a1 = runtime.malloc_array(desc, size, 0, 0) a2 = runtime.malloc_array(desc, size, 0, 0) # h1 to a1 runtime.memcpy_2d_to_array(a1, 0, 0, h1, size, size, 1, runtime.MemCpyKind.HOST_TO_DEVICE) # a1 to a2 runtime.memcpy_2d_array_to_array(a2, 0, 0, a1, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_DEVICE) # a2 to h2 runtime.memcpy_2d_from_array(h2, size, a2, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(a2) runtime.free_array(a1) def test_cudart_cudaMemcpyArrayToArray(): # create host arrays size = 1024 * np.uint8().itemsize h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device arrays a1 = runtime.malloc_array(desc, size, 0, 0) a2 = runtime.malloc_array(desc, size, 0, 0) # h1 to a1 runtime.memcpy_2d_to_array(a1, 0, 0, h1, size, size, 1, runtime.MemCpyKind.HOST_TO_DEVICE) # a1 to a2 runtime.memcpy_array_to_array(a2, 0, 0, a1, 0, 0, size, runtime.MemCpyKind.DEVICE_TO_DEVICE) # a2 to h2 runtime.memcpy_2d_from_array(h2, size, a2, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(a2) runtime.free_array(a1) def test_cudart_cudaGetChannelDesc(): # create channel descriptor x, y, z, w = 8, 0, 0, 0 f = runtime.ChannelFormatKind.UNSIGNED desc = runtime.create_channel_desc(x, y, z, w, f) # allocate device array width = 10 height = 0 flags = 0 arr = runtime.malloc_array(desc, width, height, flags) # get channel descriptor from array desc = runtime.get_channel_desc(arr) # validate array channel descriptor assert desc.x == x assert desc.y == y assert desc.z == z assert desc.w == w assert desc.f == f # clean up runtime.free_array(arr) def test_cudart_cudaGetTextureObjectTextureDesc(): # create channel descriptor channelDesc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device arrays arr = runtime.malloc_array(channelDesc, 1024, 0, 0) # create descriptors for texture object resDesc = runtime.ResourceDesc() resDesc.res.array.array = arr inTexDesc = runtime.TextureDesc() # create texture object texObject = runtime.create_texture_object(resDesc, inTexDesc, None) # get texture descriptor outTexDesc = runtime.get_texture_object_texture_desc(texObject) # validate texture descriptor for attr in dir(outTexDesc): if attr in ["border_color", "ptr", "from_ptr", "from_data", "from_buffer"]: continue if not attr.startswith("_"): assert np.array_equal(getattr(outTexDesc, attr), getattr(inTexDesc, attr)) # clean up runtime.destroy_texture_object(texObject) def test_cudart_cudaMemset3D(): # create host arrays size = 1024 * np.uint8().itemsize h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # allocate device memory devExtent = runtime.make_extent(32, 32, 1) devPitchedPtr = runtime.malloc_3d(devExtent) # set memory memExtent = runtime.make_extent(devPitchedPtr.pitch, devPitchedPtr.ysize, 1) runtime.memset_3d(devPitchedPtr, 1, memExtent) # D to h2 runtime.memcpy(h2, devPitchedPtr.ptr_, size, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free(devPitchedPtr.ptr_) def test_cudart_cudaMemset3D_2D(): # create host arrays size = 512 * np.uint8().itemsize h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # allocate device memory devExtent = runtime.make_extent(1024, 1, 1) devPitchedPtr = runtime.malloc_3d(devExtent) # set memory memExtent = runtime.make_extent(size, devPitchedPtr.ysize, 1) runtime.memset_3d(devPitchedPtr, 1, memExtent) # D to h2 runtime.memcpy(h2, devPitchedPtr.ptr_, size, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free(devPitchedPtr.ptr_) def test_cudart_cudaMemcpyToArray(): # create host arrays size = 1024 * np.uint8().itemsize h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # h1 to arr runtime.memcpy_to_array(arr, 0, 0, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # arr to h2 runtime.memcpy_from_array(h2, arr, 0, 0, size, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) def test_cudart_cudaMemcpyToArray_DtoD(): # allocate device memory size = int(1024 * np.uint8().itemsize) d1 = runtime.malloc(size) d2 = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # h1 to d1 runtime.memcpy(d1, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # d1 to arr runtime.memcpy_to_array(arr, 0, 0, d1, size, runtime.MemCpyKind.DEVICE_TO_DEVICE) # arr to d2 runtime.memcpy_from_array(d2, arr, 0, 0, size, runtime.MemCpyKind.DEVICE_TO_DEVICE) # d2 to h2 runtime.memcpy(h2, d2, size, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) runtime.free(d2) runtime.free(d1) def test_cudart_cudaMemcpy3DAsync(): # create host arrays size = int(1024 * np.uint8().itemsize) h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # create stream stream = runtime.stream_create() # create memcpy params params = runtime.MemCpy3dParms() params.src_ptr = runtime.make_pitched_ptr(h1.ctypes.data, size, 1, 1) params.dst_array = arr params.extent = runtime.make_extent(size, 1, 1) params.kind = runtime.MemCpyKind.HOST_TO_DEVICE # h1 to arr runtime.memcpy_3d_async(params, stream) # await results runtime.stream_synchronize(stream) # arr to h2 runtime.memcpy_2d_from_array(h2, size, arr, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) def test_cudart_cudaGraphAddMemcpyNode1D(): # allocate device memory size = 1024 * np.uint8().itemsize dptr = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # build graph graph = runtime.graph_create(0) # add nodes hToDNode = runtime.graph_add_memcpy_node_1d(graph, None, dptr, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) dToHNode = runtime.graph_add_memcpy_node_1d(graph, [hToDNode], h2, dptr, size, runtime.MemCpyKind.DEVICE_TO_HOST) # create stream stream = runtime.stream_create() # execute graph execGraph = runtime.graph_instantiate(graph, 0) runtime.graph_launch(execGraph, stream) # await results runtime.stream_synchronize(stream) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free(dptr) def test_cudart_cudaGraphAddMemsetNode(): # allocate device memory size = 1024 * np.uint8().itemsize dptr = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # build graph graph = runtime.graph_create(0) # set memset params params = runtime.MemsetParams() params.dst = dptr params.pitch = size params.value = 1 params.element_size = 1 params.width = size params.height = 1 # add nodes setNode = runtime.graph_add_memset_node(graph, None, params) cpyNode = runtime.graph_add_memcpy_node_1d(graph, [setNode], h2, dptr, size, runtime.MemCpyKind.DEVICE_TO_HOST) # create stream stream = runtime.stream_create() # execute graph execGraph = runtime.graph_instantiate(graph, 0) runtime.graph_launch(execGraph, stream) # await results runtime.stream_synchronize(stream) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free(dptr) def test_cudart_cudaMemcpy3DPeer(): # allocate device memory size = int(1024 * np.uint8().itemsize) dptr = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # create memcpy params params = runtime.MemCpy3dPeerParms() params.src_ptr = runtime.make_pitched_ptr(dptr, size, 1, 1) params.dst_array = arr params.extent = runtime.make_extent(size, 1, 1) # h1 to D runtime.memcpy(dptr, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # D to arr runtime.memcpy_3d_peer(params) # arr to h2 runtime.memcpy_2d_from_array(h2, size, arr, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) runtime.free(dptr) def test_cudart_cudaMemcpy3DPeerAsync(): # allocate device memory size = 1024 * np.uint8().itemsize dptr = runtime.malloc(size) # create host arrays h1 = np.full(size, 1).astype(np.uint8) h2 = np.full(size, 2).astype(np.uint8) assert np.array_equal(h1, h2) is False # create channel descriptor desc = runtime.create_channel_desc(8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED) # allocate device array arr = runtime.malloc_array(desc, size, 0, 0) # create stream stream = runtime.stream_create() # create memcpy params params = runtime.MemCpy3dPeerParms() params.src_ptr = runtime.make_pitched_ptr(dptr, size, 1, 1) params.dst_array = arr params.extent = runtime.make_extent(size, 1, 1) # h1 to D runtime.memcpy(dptr, h1, size, runtime.MemCpyKind.HOST_TO_DEVICE) # ensure the DMA to device memory has completed runtime.stream_synchronize(0) # D to arr runtime.memcpy_3d_peer_async(params, stream) # await results runtime.stream_synchronize(stream) # arr to h2 runtime.memcpy_2d_from_array(h2, size, arr, 0, 0, size, 1, runtime.MemCpyKind.DEVICE_TO_HOST) # validate h1 == h2 assert np.array_equal(h1, h2) # clean up runtime.free_array(arr) runtime.free(dptr) def test_profiler(): runtime.profiler_start() runtime.profiler_stop() def test_cudart_eglFrame(): frame = runtime.EglFrame() # [0, 0, 0] assert int(frame.frame.p_array[0]) == 0 assert int(frame.frame.p_array[1]) == 0 assert int(frame.frame.p_array[2]) == 0 frame.frame.p_array = [1, 2, 3] # [1, 2, 3] assert int(frame.frame.p_array[0]) == 1 assert int(frame.frame.p_array[1]) == 2 assert int(frame.frame.p_array[2]) == 3 frame.frame.p_array[2] = 4 # [1, 2, 4] assert int(frame.frame.p_array[0]) == 1 assert int(frame.frame.p_array[1]) == 2 assert int(frame.frame.p_array[2]) == 4 # frame.frame.p_pitch pitch = frame.frame.p_pitch assert len(pitch) == 3 pitch[0].ptr_ = 1 pitch[0].pitch = 2 pitch[0].xsize = 4 assert int(pitch[0].ptr_) == 1 assert int(pitch[0].pitch) == 2 assert int(pitch[0].xsize) == 4 assert int(pitch[0].ysize) == 0 for i in (1, 2): assert int(pitch[i].ptr_) == 0 assert int(pitch[i].pitch) == 0 assert int(pitch[i].xsize) == 0 assert int(pitch[i].ysize) == 0 with pytest.raises(IndexError): pitch[3] # Elements alias the frame's memory, so writing through one is visible # through a fresh view of the array. for i in range(3): pitch[i].ptr_ = 0 pitch[i].pitch = 123 pitch[i].xsize = 0 pitch[i].ysize = 0 for i in range(3): assert int(frame.frame.p_pitch[i].ptr_) == 0 assert int(frame.frame.p_pitch[i].pitch) == 123 assert int(frame.frame.p_pitch[i].xsize) == 0 assert int(frame.frame.p_pitch[i].ysize) == 0 # A standalone struct is a separate copy x = runtime.PitchedPtr() x.pitch = 1234 for i in range(3): assert int(frame.frame.p_pitch[i].pitch) == 123 # The array can be copied wholesale from another frame's array other = runtime.EglFrame() other.frame.p_pitch[1].pitch = 7 frame.frame.p_pitch = other.frame.p_pitch assert [int(frame.frame.p_pitch[i].pitch) for i in range(3)] == [0, 7, 0] @pytest.mark.parametrize("use_host_api", [False, True], ids=["stream_callback", "host_function"]) @pytest.mark.agent_authored(model="gpt-6") def test_cudart_func_callback(use_host_api): class testStruct(ctypes.Structure): _fields_ = [ ("a", ctypes.c_int), ("b", ctypes.c_int), ("c", ctypes.c_int), ] calls = [] stream_results = [] def task_callback_host(userData): data = testStruct.from_address(userData) calls.append((userData, data.a, data.b, data.c)) def task_callback_stream(stream, status, userData): stream_results.append((stream, status)) task_callback_host(userData) if use_host_api: callback_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p) target_task = task_callback_host else: callback_type = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p) target_task = task_callback_stream # Construct ctype data c_callback = callback_type(target_task) c_data = testStruct(1, 2, 3) # ctypes is managing the pointer value for us callback = ctypes.cast(c_callback, ctypes.c_void_p).value # Run stream = runtime.stream_create() try: if use_host_api: runtime.launch_host_func(stream, callback, ctypes.addressof(c_data)) else: runtime.stream_add_callback(stream, callback, ctypes.addressof(c_data), 0) runtime.stream_synchronize(stream) # ctypes swallows callback exceptions, so assert on the test thread. assert calls == [(ctypes.addressof(c_data), 1, 2, 3)] if not use_host_api: assert stream_results == [(stream, int(runtime.Error.SUCCESS))] finally: runtime.stream_destroy(stream) @pytest.mark.agent_authored(model="claude-fable-5-1") def test_cudart_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 = ctypes.cast(host_fn, ctypes.c_void_p).value stream = runtime.stream_create() try: # Thread-local mode: pytest-run-parallel runs this test in several threads # at once, and in global mode a call such as cudaGraphInstantiate in one # thread fails while another thread is capturing. runtime.stream_begin_capture(stream, runtime.StreamCaptureMode.THREAD_LOCAL) runtime.launch_host_func(stream, callback, ctypes.addressof(counter)) graph = runtime.stream_end_capture(stream) try: graphExec = runtime.graph_instantiate(graph, 0) try: for launch in range(1, 6): runtime.graph_launch(graphExec, stream) runtime.stream_synchronize(stream) assert counter.value == launch finally: runtime.graph_exec_destroy(graphExec) finally: runtime.graph_destroy(graph) finally: runtime.stream_destroy(stream) @pytest.mark.skipif( driver_version_less_than(12030) or not supportsCudaAPI("graph_conditional_handle_create"), reason="Conditional graph APIs required", ) def test_cudart_conditional(): graph = runtime.graph_create(0) handle = runtime.graph_conditional_handle_create(graph, 0, 0) params = runtime.GraphNodeParams() params.type = runtime.GraphNodeType.CONDITIONAL params.conditional.handle = handle params.conditional.type = runtime.GraphConditionalNodeType.IF_ params.conditional.size_ = 1 # ph_graph_out is the address of a CUDA-owned array of child graphs assert params.conditional.ph_graph_out == 0 node = runtime.graph_add_node(graph, None, None, params) assert params.conditional.ph_graph_out != 0 assert ctypes.c_void_p.from_address(params.conditional.ph_graph_out).value != 0 def test_getLocalRuntimeVersion(): # verify that successive calls do not segfault the interpreter for _ in range(10): try: version = runtime.get_local_runtime_version() except pathfinder.DynamicLibNotFoundError: pytest.skip("cudart dynamic lib not available") else: assert version >= 12000 # CUDA 12.0 @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_get_id"), reason="Requires CUDA 13.1+", ) def test_cudaGraphGetId(): """Test cudaGraphGetId - get graph ID.""" graph = runtime.graph_create(0) graph_id = runtime.graph_get_id(graph) assert isinstance(graph_id, int) assert graph_id > 0 # Create another graph and verify it has a different ID graph2 = runtime.graph_create(0) graph_id2 = runtime.graph_get_id(graph2) assert graph_id2 != graph_id runtime.graph_destroy(graph) runtime.graph_destroy(graph2) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_exec_get_id"), reason="Requires CUDA 13.1+", ) def test_cudaGraphExecGetId(): """Test cudaGraphExecGetId - get graph exec ID.""" stream = runtime.stream_create() graph = runtime.graph_create(0) # Add an empty node to make the graph valid node = runtime.graph_add_empty_node(graph, None) graphExec = runtime.graph_instantiate(graph, 0) graph_exec_id = runtime.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 graph2 = runtime.graph_create(0) node2 = runtime.graph_add_empty_node(graph2, None) graphExec2 = runtime.graph_instantiate(graph2, 0) graph_exec_id2 = runtime.graph_exec_get_id(graphExec2) assert graph_exec_id2 != graph_exec_id runtime.graph_exec_destroy(graphExec) runtime.graph_exec_destroy(graphExec2) runtime.graph_destroy(graph) runtime.graph_destroy(graph2) runtime.stream_destroy(stream) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_local_id"), reason="Requires CUDA 13.1+", ) def test_cudaGraphNodeGetLocalId(): """Test cudaGraphNodeGetLocalId - get node local ID.""" graph = runtime.graph_create(0) # Add multiple nodes node1 = runtime.graph_add_empty_node(graph, None) node2 = runtime.graph_add_empty_node(graph, [node1]) node3 = runtime.graph_add_empty_node(graph, [node1, node2]) # Get local IDs for each node node_id1 = runtime.graph_node_get_local_id(node1) assert isinstance(node_id1, int) assert node_id1 >= 0 node_id2 = runtime.graph_node_get_local_id(node2) assert isinstance(node_id2, int) assert node_id2 >= 0 assert node_id2 != node_id1 node_id3 = runtime.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 runtime.graph_destroy(graph) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_tools_id"), reason="Requires CUDA 13.1+", ) def test_cudaGraphNodeGetToolsId(): """Test cudaGraphNodeGetToolsId - get node tools ID.""" graph = runtime.graph_create(0) node = runtime.graph_add_empty_node(graph, None) tools_node_id = runtime.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 node2 = runtime.graph_add_empty_node(graph, [node]) tools_node_id2 = runtime.graph_node_get_tools_id(node2) assert tools_node_id2 != tools_node_id runtime.graph_destroy(graph) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_node_get_containing_graph"), reason="Requires CUDA 13.1+", ) def test_cudaGraphNodeGetContainingGraph(): """Test cudaGraphNodeGetContainingGraph - get graph containing a node.""" graph = runtime.graph_create(0) node = runtime.graph_add_empty_node(graph, None) # Get the containing graph containing_graph = runtime.graph_node_get_containing_graph(node) # Verify it's the same graph assert containing_graph == graph # Test with a child graph node (if supported) # Create a child graph child_graph = runtime.graph_create(0) child_node = runtime.graph_add_empty_node(child_graph, None) # Add child graph node to parent graph childGraphNodeParams = runtime.GraphNodeParams() childGraphNodeParams.type = runtime.GraphNodeType.GRAPH childGraphNodeParams.graph.graph = child_graph try: child_graph_node = runtime.graph_add_node(graph, None, None, childGraphNodeParams) except runtime.CudaError: pass else: # Get containing graph for the child graph node containing_graph_for_child = runtime.graph_node_get_containing_graph(child_graph_node) assert containing_graph_for_child == graph # Get containing graph for node inside child graph containing_graph_for_nested = runtime.graph_node_get_containing_graph(child_node) assert containing_graph_for_nested == child_graph runtime.graph_destroy(graph) runtime.graph_destroy(child_graph) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("stream_get_dev_resource"), reason="Requires CUDA 13.1+", ) def test_cudaStreamGetDevResource(): """Test cudaStreamGetDevResource - get device resource from stream.""" stream = runtime.stream_create() # Get SM resource from stream resource = runtime.stream_get_dev_resource(stream, runtime.DevResourceType.SM) # Verify resource is valid (non-None) assert resource is not None runtime.stream_destroy(stream) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("device_get_dev_resource"), reason="Requires CUDA 13.1+", ) def test_cudaDeviceGetDevResource(): """Test cudaDeviceGetDevResource - get device resource.""" device = 0 # Get SM resource from device resource = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) # Verify resource is valid (non-None) assert resource is not None @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("device_get_execution_ctx"), reason="Requires CUDA 13.1+", ) def test_cudaExecutionCtxGetDevResource(): """Test cudaExecutionCtxGetDevResource - get device resource from execution context.""" # Get execution context for device 0 (primary context) exec_ctx = runtime.device_get_execution_ctx(0) assert exec_ctx is not None # Get SM resource from execution context resource = runtime.execution_ctx_get_dev_resource(exec_ctx, runtime.DevResourceType.SM) # Verify resource is valid (non-None) assert resource is not None @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("device_get_execution_ctx"), reason="Requires CUDA 13.1+", ) def test_cudaExecutionCtxGetDevice(): """Test cudaExecutionCtxGetDevice - get device from execution context.""" device = 0 # Get execution context for device exec_ctx = runtime.device_get_execution_ctx(device) assert exec_ctx is not None # Get device from execution context device_from_ctx = runtime.execution_ctx_get_device(exec_ctx) # Verify it returns the same device assert device_from_ctx == device @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("device_get_execution_ctx"), reason="Requires CUDA 13.1+", ) def test_cudaExecutionCtxGetId(): """Test cudaExecutionCtxGetId - get unique ID from execution context.""" # Get execution context for device 0 (primary context) exec_ctx = runtime.device_get_execution_ctx(0) assert exec_ctx is not None # Get unique ID from execution context ctx_id = runtime.execution_ctx_get_id(exec_ctx) assert isinstance(ctx_id, int) assert ctx_id > 0 # Get another execution context and verify it has a different ID exec_ctx2 = runtime.device_get_execution_ctx(0) # Should return the same context for the same device assert exec_ctx2 == exec_ctx ctx_id2 = runtime.execution_ctx_get_id(exec_ctx2) # Should have the same ID since it's the same context assert ctx_id2 == ctx_id @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("dev_sm_resource_split"), reason="Requires CUDA 13.1+", ) def test_cudaDevSmResourceSplit(): """Test cudaDevSmResourceSplit - split SM resource into structured groups.""" device = 0 resource_in = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) # Test case 1: Split into 1 group nb_groups = 1 group_params = runtime.DevSmResourceGroupParams(nb_groups) # Set up group: request 4 SMs with coscheduled count of 2 group_params[0].sm_count = 4 group_params[0].coscheduled_sm_count = 2 res, rem = runtime.dev_sm_resource_split(resource_in, 0, group_params) 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 resource_in = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) nb_groups = 2 group_params = runtime.DevSmResourceGroupParams(nb_groups) # First group: request 4 SMs with coscheduled count of 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].sm_count = 4 group_params[1].coscheduled_sm_count = 2 # This may succeed or fail depending on device SM count, but should handle gracefully try: res, rem = runtime.dev_sm_resource_split(resource_in, 0, group_params) except (runtime.InvalidResourceConfigurationError, runtime.InvalidValueError): # If it fails, it should be due to insufficient resources, not a binding error pass else: assert len(res) == nb_groups assert rem is not None or len(res) > 0 # 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 = runtime.DevSmResourceGroupParams(nb_groups) # If it fails, it should be a valid CUDA error, not a Python binding error try: res, rem = runtime.dev_sm_resource_split(resource_in, 0, group_params) except (runtime.InvalidValueError, runtime.InvalidResourceConfigurationError): pass else: # With 0 groups, result should be empty assert len(res) == 0 @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("dev_sm_resource_split_by_count"), reason="Requires CUDA 13.1+", ) def test_cudaDevSmResourceSplitByCount(): """Test cudaDevSmResourceSplitByCount - split SM resource by count.""" device = 0 resource_in = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) # The binding discovers the number of groups itself and returns them all res, rem = runtime.dev_sm_resource_split_by_count(resource_in, 0, 2) assert len(res) > 0 @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("dev_resource_generate_desc"), reason="Requires CUDA 13.1+", ) def test_cudaDevResourceGenerateDesc(): """Test cudaDevResourceGenerateDesc - generate resource descriptor.""" device = 0 resource = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) # Generate descriptor from a single resource desc = runtime.dev_resource_generate_desc(resource) assert desc is not None @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("green_ctx_create"), reason="Requires CUDA 13.1+", ) def test_cudaGreenCtxCreate(): """Test cudaGreenCtxCreate - create green context with resources.""" device = 0 # Set device to ensure primary context is ready runtime.set_device(device) # Get device resource resource = runtime.device_get_dev_resource(device, runtime.DevResourceType.SM) # Generate descriptor desc = runtime.dev_resource_generate_desc(resource) # Create green context green_ctx = runtime.green_ctx_create(desc, device, 0) assert green_ctx is not None # Cleanup: destroy the green context runtime.execution_ctx_destroy(green_ctx) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("execution_ctx_stream_create"), reason="Requires CUDA 13.1+", ) def test_cudaExecutionCtxStreamCreate(): """Test cudaExecutionCtxStreamCreate - create stream for execution context.""" # Get execution context for device 0 (primary context) exec_ctx = runtime.device_get_execution_ctx(0) assert exec_ctx is not None # Create stream for the execution context stream = runtime.execution_ctx_stream_create(exec_ctx, 0, 0) assert stream is not None # Cleanup: destroy the stream runtime.stream_destroy(stream) @pytest.mark.skipif( driver_version_less_than(13010) or not supportsCudaAPI("graph_conditional_handle_create_v2"), reason="Requires CUDA 13.1+", ) def test_cudaGraphConditionalHandleCreate_v2(): """Test cudaGraphConditionalHandleCreate_v2 - create conditional handle with execution context.""" graph = runtime.graph_create(0) # Get execution context (can be None for v2) exec_ctx = runtime.device_get_execution_ctx(0) # Create conditional handle with execution context handle = runtime.graph_conditional_handle_create_v2(graph, exec_ctx, 0, 0) assert handle is not None runtime.graph_destroy(graph) @pytest.mark.agent_authored(model="claude-sonnet-4-6") def test_ffi_phase2_normalized_channel_kinds_round_trip(): """Normalized 8/16-bit channel kinds passed validity but hit the else-branch in the case_desc chain and returned cudaErrorInvalidChannelDescriptor. Verify they no longer error at the binding layer (CUDA may still reject the format on a given device, which is fine).""" pairs = [ (8, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED8X1), (8, 8, 0, 0, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED8X2), (8, 8, 8, 8, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED8X4), (8, 0, 0, 0, runtime.ChannelFormatKind.SIGNED_NORMALIZED8X1), (8, 8, 0, 0, runtime.ChannelFormatKind.SIGNED_NORMALIZED8X2), (8, 8, 8, 8, runtime.ChannelFormatKind.SIGNED_NORMALIZED8X4), (16, 0, 0, 0, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED16X1), (16, 16, 0, 0, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED16X2), (16, 16, 16, 16, runtime.ChannelFormatKind.UNSIGNED_NORMALIZED16X4), (16, 0, 0, 0, runtime.ChannelFormatKind.SIGNED_NORMALIZED16X1), (16, 16, 0, 0, runtime.ChannelFormatKind.SIGNED_NORMALIZED16X2), (16, 16, 16, 16, runtime.ChannelFormatKind.SIGNED_NORMALIZED16X4), ] for x, y, z, w, kind in pairs: desc = runtime.ChannelFormatDesc() desc.x, desc.y, desc.z, desc.w, desc.f = x, y, z, w, kind assert desc.f == kind assert desc.x == x @pytest.mark.agent_authored(model="claude-sonnet-4-6") def test_ffi_phase2_new_yuv_channel_kinds_descriptor_construction(): """CUDA 13.3/13.4 packed and multi-planar YUV kinds can be placed in a cudaChannelFormatDesc without raising a Python exception. Whether CUDA's runtime accepts the descriptor for a given operation (e.g. cudaMallocArray) is hardware-dependent and is not asserted here — getDescInfo is only called from the EGL frame conversion path, not from cudaMallocArray.""" three_ch_8 = [ runtime.ChannelFormatKind.UNSIGNED8_SEMI_PLANAR420, runtime.ChannelFormatKind.UNSIGNED8_SEMI_PLANAR422, runtime.ChannelFormatKind.UNSIGNED8_SEMI_PLANAR444, runtime.ChannelFormatKind.UNSIGNED8_PLANAR420, runtime.ChannelFormatKind.UNSIGNED8_PLANAR422, runtime.ChannelFormatKind.UNSIGNED8_PLANAR444, ] three_ch_16 = [ runtime.ChannelFormatKind.UNSIGNED16_SEMI_PLANAR420, runtime.ChannelFormatKind.UNSIGNED16_SEMI_PLANAR422, runtime.ChannelFormatKind.UNSIGNED16_SEMI_PLANAR444, runtime.ChannelFormatKind.UNSIGNED16_PLANAR420, runtime.ChannelFormatKind.UNSIGNED16_PLANAR422, runtime.ChannelFormatKind.UNSIGNED16_PLANAR444, ] four_ch_8 = [ runtime.ChannelFormatKind.UNSIGNED8_PACKED422, runtime.ChannelFormatKind.UNSIGNED8_PACKED444, ] for bits, w_bit, kinds in ((8, 0, three_ch_8), (16, 0, three_ch_16), (8, 8, four_ch_8)): for kind in kinds: desc = runtime.ChannelFormatDesc() desc.x, desc.y, desc.z, desc.w, desc.f = bits, bits, bits, w_bit, kind assert desc.f == kind assert desc.x == bits @pytest.mark.agent_authored(model="claude-sonnet-5-5") @pytest.mark.skipif(runtime.CUDART_VERSION < 13050, reason="The locality domain sentinel requires CUDA 13.5 headers") def test_locality_domain_id_any_sentinel(): sentinel = runtime.DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID_ANY assert int(sentinel) == 0xFFFFFFFF # The field must accept the constant that the bindings export for it, and # the unsigned maximum itself. params = runtime.DevSmResourceGroupParams() params.locality_domain_id = sentinel assert params.locality_domain_id == 0xFFFFFFFF params.locality_domain_id = 0xFFFFFFFF assert params.locality_domain_id == 0xFFFFFFFF @contextlib.contextmanager def _stream_blocked_until_released(stream): """Queue a host function on ``stream`` that blocks until the context exits, so the stream has pending work.""" release = threading.Event() @ctypes.CFUNCTYPE(None, ctypes.c_void_p) def host_fn(user_data): assert release.wait(timeout=30) runtime.launch_host_func(stream, ctypes.cast(host_fn, ctypes.c_void_p).value, 0) try: yield finally: release.set() runtime.stream_synchronize(stream) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_stream_query_pending_and_idle(): stream = runtime.stream_create() try: assert runtime.stream_query(stream) is None assert runtime.stream_query_no_raise(stream) == 0 with _stream_blocked_until_released(stream): with pytest.raises(runtime.NotReadyError): runtime.stream_query(stream) assert runtime.stream_query_no_raise(stream) == runtime.Error.ERROR_NOT_READY assert runtime.stream_query(stream) is None assert runtime.stream_query_no_raise(stream) == 0 finally: runtime.stream_destroy(stream) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_event_query_pending_and_complete(): stream = runtime.stream_create() event = runtime.event_create() try: with _stream_blocked_until_released(stream): runtime.event_record(event, stream) with pytest.raises(runtime.NotReadyError): runtime.event_query(event) assert runtime.event_query_no_raise(event) == runtime.Error.ERROR_NOT_READY runtime.event_synchronize(event) assert runtime.event_query(event) is None assert runtime.event_query_no_raise(event) == 0 finally: runtime.event_destroy(event) runtime.stream_destroy(stream) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_get_last_error_and_peek_return_int_status(): runtime.get_last_error() # clear any earlier error of this thread assert runtime.peek_at_last_error() == 0 with pytest.raises(runtime.HostMemoryNotRegisteredError): runtime.host_unregister(0x1000) # peek leaves the error in place, get returns it and resets it assert runtime.peek_at_last_error() == runtime.Error.ERROR_HOST_MEMORY_NOT_REGISTERED assert runtime.peek_at_last_error() == runtime.Error.ERROR_HOST_MEMORY_NOT_REGISTERED assert runtime.get_last_error() == runtime.Error.ERROR_HOST_MEMORY_NOT_REGISTERED assert runtime.get_last_error() == 0 assert runtime.peek_at_last_error() == 0 @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_get_error_string_and_name(): assert isinstance(runtime.get_error_string(runtime.Error.ERROR_NOT_READY), str) assert runtime.get_error_name(runtime.Error.ERROR_NOT_READY) == "cudaErrorNotReady" # Unlike the driver, the runtime does not raise for a code it does not know. assert runtime.get_error_string(0x7FFF0000) == "unrecognized error code" assert runtime.get_error_name(0x7FFF0000) == "unrecognized error code" def _exec_for_single_empty_node_graph(): graph = runtime.graph_create(0) runtime.graph_add_empty_node(graph, None) return graph, runtime.graph_instantiate(graph, 0) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_graph_exec_update_success(): graph, graph_exec = _exec_for_single_empty_node_graph() new_graph = runtime.graph_create(0) try: runtime.graph_add_empty_node(new_graph, None) info = runtime.graph_exec_update(graph_exec, new_graph) assert info.result == runtime.GraphExecUpdateResult.SUCCESS finally: runtime.graph_destroy(new_graph) runtime.graph_exec_destroy(graph_exec) runtime.graph_destroy(graph) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_graph_exec_update_constraint_violation_returns_info_without_raising(): graph, graph_exec = _exec_for_single_empty_node_graph() new_graph = runtime.graph_create(0) try: first = runtime.graph_add_empty_node(new_graph, None) runtime.graph_add_empty_node(new_graph, [first]) # The topology differs from the one that was instantiated: not an exception, the info says why. info = runtime.graph_exec_update(graph_exec, new_graph) assert info.result == runtime.GraphExecUpdateResult.ERROR_TOPOLOGY_CHANGED finally: runtime.graph_destroy(new_graph) runtime.graph_exec_destroy(graph_exec) runtime.graph_destroy(graph) @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_graph_exec_update_other_errors_raise(): graph, graph_exec = _exec_for_single_empty_node_graph() try: with pytest.raises(runtime.CudaError): runtime.graph_exec_update(graph_exec, 0) finally: runtime.graph_exec_destroy(graph_exec) runtime.graph_destroy(graph)