Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions cuda_core/tests/example_tests/test_sample_verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
from __future__ import annotations

import ast
import io
import sys
from pathlib import Path
from types import SimpleNamespace

import numpy as np
import pytest
Expand All @@ -14,7 +17,9 @@
UTILITIES_DIR = REPO_ROOT / "samples" / "cuda_core" / "Utilities"
WAIVER_SAMPLE_NAMES = (
"blurImageUnifiedMemory",
"copyImageArraytoGPU",
"glInteropFluid",
"glInteropFluidNumbaCudaMlir",
"glInteropMipmapLod",
"glInteropPlasma",
"ipcMemoryPool",
Expand All @@ -30,6 +35,85 @@
)


def _load_sample_function(sample_name: str, function_name: str, **namespace):
"""Exercise sample functions without importing their optional GPU packages."""
sample_path = REPO_ROOT / "samples" / "cuda_core" / sample_name / f"{sample_name}.py"
tree = ast.parse(sample_path.read_text(encoding="utf-8"), filename=str(sample_path))
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == function_name)
module = ast.Module(body=[function], type_ignores=[])
exec(compile(module, str(sample_path), "exec"), namespace) # noqa: S102 - trusted sample source
return namespace[function_name]


@pytest.mark.parametrize("host_pools_supported", [False, True])
@pytest.mark.agent_authored(model="GPT-6")
def test_image_sample_requires_host_memory_pools(host_pools_supported: bool) -> None:
def create_stream():
raise RuntimeError("stream setup failed")

device = SimpleNamespace(
properties=SimpleNamespace(memory_pools_supported=True, host_memory_pools_supported=host_pools_supported),
set_current=lambda: None,
create_stream=create_stream,
)
main = _load_sample_function("copyImageArraytoGPU", "main", Device=lambda: device, np=np, sys=sys, EXIT_WAIVED=77)

if host_pools_supported:
with pytest.raises(RuntimeError, match="stream setup failed"):
main()
else:
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 77


@pytest.mark.parametrize(("handle_types", "supported"), [(2, False), (3, True)])
@pytest.mark.agent_authored(model="GPT-6")
def test_ipc_sample_checks_memory_pool_handle_support(handle_types: int, supported: bool) -> None:
from cuda.bindings import driver

check_ipc_support = _load_sample_function(
"ipcMemoryPool",
"check_ipc_support",
platform=SimpleNamespace(system=lambda: "Linux"),
open=lambda _path: io.StringIO("6.1.0"),
driver=driver,
)
device = SimpleNamespace(
properties=SimpleNamespace(
memory_pools_supported=True,
handle_type_posix_file_descriptor_supported=True,
mempool_supported_handle_types=handle_types,
)
)

assert check_ipc_support(device) is supported


@pytest.mark.parametrize("display", [None, ":0"])
@pytest.mark.agent_authored(model="GPT-6")
def test_mlir_sample_waives_missing_display_before_cuda_setup(display: str | None) -> None:
def is_available():
raise RuntimeError("CUDA query failed")

main = _load_sample_function(
"glInteropFluidNumbaCudaMlir",
"main",
os=SimpleNamespace(environ={} if display is None else {"DISPLAY": display}),
sys=SimpleNamespace(platform="linux", stderr=sys.stderr, exit=sys.exit),
cuda=SimpleNamespace(is_available=is_available),
EXIT_WAIVED=77,
)

if display is None:
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 77
else:
with pytest.raises(RuntimeError, match="CUDA query failed"):
main()


@pytest.mark.parametrize("sample_name", WAIVER_SAMPLE_NAMES)
@pytest.mark.agent_authored(model="gpt-5")
def test_core_sample_waivers_use_negotiated_exit_code(
Expand Down
15 changes: 11 additions & 4 deletions cuda_core/tests/graph/test_graph_memory_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

"""Tests for GraphMemoryResource allocation and attributes during graph capture."""

import gc
import threading

import pytest
Expand Down Expand Up @@ -385,10 +386,16 @@ def worker():
try:
device = Device(device_id)
device.set_current()
gb = device.create_stream().create_graph_builder().begin_building(mode=mode)
device.memory_resource # noqa: B018 - first touch on this thread constructs the resource
result["building"] = gb.is_building
gb.end_building().complete()
# Unrelated buffer finalizers must run before capture, not during it.
gc.collect()
gb = device.create_stream().create_graph_builder()
try:
gb.begin_building(mode=mode)
device.memory_resource # noqa: B018 - first touch on this thread constructs the resource
result["building"] = gb.is_building
gb.end_building().complete()
finally:
gb.close()
except BaseException as exc:
result["error"] = exc

Expand Down
4 changes: 4 additions & 0 deletions samples/cuda_core/copyImageArraytoGPU/copyImageArraytoGPU.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ def main():
print("PinnedMemoryResource requires CUDA memory pools, which are not supported on this device. Waiving.")
sys.exit(EXIT_WAIVED)

if not dev.properties.host_memory_pools_supported:
print("PinnedMemoryResource requires host memory pools, which are not supported on this device. Waiving.")
sys.exit(EXIT_WAIVED)

stream = dev.create_stream() # Create stream for async operations

print(f"Device: {dev.name}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,10 @@ def upload_and_draw(gl, shader_prog, vao_id, tex_id, host_rgba):


def main():
if sys.platform == "linux" and not os.environ.get("DISPLAY"):
print("No DISPLAY available; waiving glInteropFluidNumbaCudaMlir.", file=sys.stderr)
sys.exit(EXIT_WAIVED)

if not cuda.is_available():
print("No CUDA GPU available to numba.", file=sys.stderr)
sys.exit(1)
Expand Down
5 changes: 5 additions & 0 deletions samples/cuda_core/ipcMemoryPool/ipcMemoryPool.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import numpy as np
from cuda_samples_utils import print_gpu_info

from cuda.bindings import driver
from cuda.core import (
Device,
DeviceMemoryResource,
Expand Down Expand Up @@ -103,6 +104,10 @@ def check_ipc_support(device) -> bool:
if not device.properties.handle_type_posix_file_descriptor_supported:
print("Device/platform does not support POSIX-fd IPC handles.")
return False
posix_fd = int(driver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR)
if not device.properties.mempool_supported_handle_types & posix_fd:
print("Device/platform does not support POSIX-fd IPC memory pools.")
return False
return True


Expand Down
Loading