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
7 changes: 3 additions & 4 deletions cuda_core/tests/example_tests/test_samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,9 @@
# Samples launch full GPU workloads in their own subprocess, so keep them
# serialized when the suite is run under pytest-run-parallel.
# For sample_key values: cuda_core/binarySearch, cuda_core/cudaComputeLambdas, cuda_core/customTensorFlowKernel,
# cuda_core/glInteropFluidNumbaCudaMlir, cuda_core/glInteropFluid, cuda_core/glInteropMipmapLod,
# cuda_core/glInteropPlasma, cuda_core/greenContext, cuda_core/matrixMulSharedMem, cuda_core/multiGPUGradientAverage,
# cuda_core/pageRank, cuda_core/parallelReduction, cuda_core/prefixSum, cuda_core/processCheckpoint,
# cuda_core/reductionMultiBlockCG, cuda_core/simplePrint, cuda_core/tmaTensorMap:
# cuda_core/glInteropFluidNumbaCudaMlir, cuda_core/greenContext, cuda_core/matrixMulSharedMem,
# cuda_core/multiGPUGradientAverage, cuda_core/pageRank, cuda_core/parallelReduction, cuda_core/prefixSum,
# cuda_core/processCheckpoint, cuda_core/reductionMultiBlockCG, cuda_core/simplePrint, cuda_core/tmaTensorMap:
# This test is not currently run in any CI job
@pytest.mark.parallel_threads_limit(1)
@pytest.mark.parametrize("sample_key", _SAMPLES)
Expand Down
42 changes: 42 additions & 0 deletions cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import argparse
import ast
import concurrent.futures
import importlib.metadata
import json
Expand Down Expand Up @@ -461,6 +462,42 @@ def build_run_plan(
# ---------------------------------------------------------------------------


# Samples are run by users who do not have this package (it is not published
# to PyPI), so a sample must not import it, directly or through Utilities.
_FORBIDDEN_SAMPLE_IMPORT = "cuda_python_test_helpers"


def forbidden_imports(sample: Path) -> list[str]:
"""Return ``path:line`` for each import of ``cuda_python_test_helpers`` the sample can reach.

Checks every Python file in the sample's directory and in the nearest
shared ``Utilities`` directory that samples import from.
"""
directories = [sample.parent]
for ancestor in sample.parents[1:3]:
if (ancestor / "Utilities").is_dir():
directories.append(ancestor / "Utilities")
break

found = []
for directory in directories:
for path in sorted(directory.rglob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

important: Convert source-inspection errors into a sample result.

If a sample contains a syntax error, ast.parse raises before run_sample reaches its subprocess handling. The exception escapes into main, interrupts the batch, and prevents its summary. Previously, the same sample produced a nonzero child exit and a FAIL result.

Handle inspection failures narrowly and return an ERROR result with the source diagnostic. Do not waive the sample. Valid samples must continue through the existing checks.

for node in ast.walk(tree):
if isinstance(node, ast.Import):
modules = [alias.name for alias in node.names]
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
modules = [node.module]
else:
continue
if any(
module == _FORBIDDEN_SAMPLE_IMPORT or module.startswith(f"{_FORBIDDEN_SAMPLE_IMPORT}.")
for module in modules
):
found.append(f"{path}:{node.lineno}")
return found


@dataclass
class RunResult:
sample: Path
Expand All @@ -474,6 +511,11 @@ def run_sample(plan: RunPlan) -> RunResult:
sample = plan.sample
name = plan.sample_key or sample.parent.name

if forbidden := forbidden_imports(sample):
reason = f"imports {_FORBIDDEN_SAMPLE_IMPORT}, which users cannot install: {', '.join(forbidden)}"
_safe_print(f" [FAIL ] {name}: {reason}")
return RunResult(sample, "FAIL", -1, reason, plan.sample_key)

if plan.skip_reason is not None:
_safe_print(f" [WAIVED] {name}: {plan.skip_reason}")
return RunResult(sample, "WAIVED", EXIT_WAIVED, plan.skip_reason, plan.sample_key)
Expand Down
29 changes: 29 additions & 0 deletions samples/cuda_core/Utilities/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,35 @@ if not check_cuda_requirements():
sys.exit(1)
```

## OpenGL Interop Helpers (`graphics.py`)

Helpers shared by the CUDA/OpenGL interop samples (`glInteropPlasma`,
`glInteropFluid`, `glInteropMipmapLod`). They need `pyglet` and `numpy`:

```python
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "Utilities"))
from graphics import (
gl_context_not_on_nvidia_gpu_reason,
use_headless_gl_if_no_display,
verify_frame_shows_pixel_buffer,
)
```

- `use_headless_gl_if_no_display(cuda_device_ordinal)`: on Linux without
`DISPLAY`, switch pyglet to an offscreen EGL context on the GPU behind the
CUDA device. Call it before importing `pyglet.gl` or `pyglet.window`.
Returns `True` if headless mode was enabled.
- `gl_context_not_on_nvidia_gpu_reason()`: return a reason to waive the
sample if the current GL context is not on an NVIDIA GPU, else `None`.
- `verify_frame_shows_pixel_buffer(pbo_id, width, height)`: check that the
frame just drawn shows the CUDA-written pixel buffer; raises
`RuntimeError` otherwise. The samples use it when rendering offscreen,
where nobody sees the frame.

Samples must not import `cuda_python_test_helpers`: it is a test-only package
that users cannot install. The sample test harness fails any sample that
imports it.

## Design Philosophy

These utilities focus on common operations that are **not** part of `cuda.core` API:
Expand Down
149 changes: 149 additions & 0 deletions samples/cuda_core/Utilities/graphics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""
OpenGL helpers for the CUDA/OpenGL interop samples.

Samples import this module using a path-based import (see README.md). It
needs ``pyglet`` and ``numpy``, which every GL sample already requires.

This module does **not** import ``pyglet.gl`` or ``pyglet.window`` at module
load time: either import creates pyglet's shadow window, which must not happen
before ``use_headless_gl_if_no_display`` has configured headless mode.
"""

import ctypes
import ctypes.util
import os
import sys

# Offscreen EGL surfaces may store fewer bits per channel than the 8-bit pixel
# buffer (RGB565 is common), so each channel may differ by the dropped bits.
_FRAME_CHANNEL_TOLERANCE = 8

# EGL_CUDA_DEVICE_NV, from the EGL_NV_device_cuda extension.
_EGL_CUDA_DEVICE_NV = 0x323A


def _select_egl_device_for_cuda(cuda_device_ordinal):
"""Return the index of the EGL device behind *cuda_device_ordinal*, or None.

``CUDA_VISIBLE_DEVICES`` reorders CUDA's device enumeration but not EGL's,
so EGL device ``N`` is not necessarily CUDA device ``N``. The
``EGL_NV_device_cuda`` extension reports the CUDA ordinal of each EGL
device. Returns None if the extension is unavailable or no EGL device
matches; pyglet then uses EGL device 0.
"""
from pyglet.libs.egl import egl, eglext
from pyglet.libs.egl.lib import link_EGL

query_device_attrib = link_EGL(
"eglQueryDeviceAttribEXT",
egl.EGLBoolean,
[eglext.EGLDeviceEXT, egl.EGLint, ctypes.POINTER(ctypes.c_ssize_t)],
)

# link_EGL returns a stub for a missing entry point that raises
# pyglet.gl.lib.MissingFunctionException when called. Match it by name:
# importing pyglet.gl here would create the shadow window too early.
try:
num_devices = egl.EGLint()
if not eglext.eglQueryDevicesEXT(0, None, ctypes.byref(num_devices)) or num_devices.value <= 0:
return None
devices = (eglext.EGLDeviceEXT * num_devices.value)()
if not eglext.eglQueryDevicesEXT(num_devices.value, devices, ctypes.byref(num_devices)):
return None
for index in range(num_devices.value):
ordinal = ctypes.c_ssize_t(-1)
if (
query_device_attrib(devices[index], _EGL_CUDA_DEVICE_NV, ctypes.byref(ordinal))
and ordinal.value == cuda_device_ordinal
):
return index
except Exception as exc:
if type(exc).__name__ == "MissingFunctionException":
return None
raise
return None


def use_headless_gl_if_no_display(cuda_device_ordinal):
"""Switch pyglet to an offscreen EGL context on Linux when there is no X display.

pyglet opens Linux windows through X11, so without ``DISPLAY`` (a headless
CI runner, for example) it cannot create a GL context. When EGL is
available, this sets ``pyglet.options["headless"]`` and selects the EGL
device behind *cuda_device_ordinal*; pyglet's windows then render to an
offscreen surface. Without EGL it changes nothing, and opening a window
fails as before.

Must be called before importing ``pyglet.gl`` or ``pyglet.window``.
Returns True if headless mode was enabled.
"""
if sys.platform != "linux" or os.environ.get("DISPLAY") or ctypes.util.find_library("EGL") is None:
return False

import pyglet

pyglet.options["headless"] = True
egl_device = _select_egl_device_for_cuda(cuda_device_ordinal)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Stability & Availability · Quick win

Waive the samples when the EGL loader fails during headless setup.

use_headless_gl_if_no_display finds libEGL with ctypes.util.find_library. It then calls _select_egl_device_for_cuda, which imports pyglet.libs.egl at samples/cuda_core/Utilities/graphics.py:37. If the library is present but a native dependency cannot load, pyglet raises during that import. The import is outside the try block in _select_egl_device_for_cuda. Each sample calls use_headless_gl_if_no_display before its create_window waiver handler, and no outer handler translates the error. The sample then exits with an uncaught traceback instead of EXIT_WAIVED.

The PR waives a sample when no NVIDIA EGL device is available. Route this setup failure to the same waiver path. Keep unrelated errors visible. The exception class and the handler location are a design choice for the author. The inspected code does not establish either one.

if egl_device is not None:
pyglet.options["headless_device"] = egl_device
return True


def gl_context_not_on_nvidia_gpu_reason():
"""Return a reason to waive if the current GL context is not on an NVIDIA GPU, else None.

CUDA/OpenGL interop needs a GL context rendered by an NVIDIA GPU. On
another vendor's GPU, registering a GL object with CUDA fails with an
unhelpful error. The caller must have a current GL context.
"""
from pyglet.gl import gl

def get_string(name):
value = gl.glGetString(name)
if not value:
return ""
return ctypes.cast(value, ctypes.c_char_p).value.decode(errors="replace")

vendor = get_string(gl.GL_VENDOR)
if "NVIDIA" in vendor:
return None
renderer = get_string(gl.GL_RENDERER)
return (
f"GL context is not on an NVIDIA GPU (GL_VENDOR={vendor!r}, GL_RENDERER={renderer!r}); "
"CUDA-GL interop requires one."
)


def verify_frame_shows_pixel_buffer(pbo_id, width, height):
"""Check that the frame just drawn shows the RGBA8 pixel buffer *pbo_id* 1:1.

For samples that draw a CUDA-written pixel buffer object (PBO) as a
full-window texture of *width* x *height*: read back the PBO and the
current framebuffer and compare their RGB channels. Call it after drawing
and before the buffer swap. Raises ``RuntimeError`` if the frame differs
from the PBO, or if the PBO is a single flat color (the kernel wrote
nothing visible).
"""
import numpy as np
from pyglet.gl import gl

expected = np.empty((height, width, 4), dtype=np.uint8)
gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, pbo_id)
gl.glGetBufferSubData(gl.GL_PIXEL_UNPACK_BUFFER, 0, expected.nbytes, expected.ctypes.data_as(ctypes.c_void_p))
gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, 0)

frame = np.empty_like(expected)
gl.glReadPixels(0, 0, width, height, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, frame.ctypes.data_as(ctypes.c_void_p))

expected_rgb = expected[..., :3].astype(np.int16)
if (expected_rgb == expected_rgb[0, 0]).all():
raise RuntimeError(f"the pixel buffer is a single color {tuple(expected_rgb[0, 0])}")
max_diff = int(np.abs(frame[..., :3].astype(np.int16) - expected_rgb).max())
if max_diff > _FRAME_CHANNEL_TOLERANCE:
raise RuntimeError(
f"the rendered frame does not match the pixel buffer (max channel difference {max_diff}, "
f"tolerance {_FRAME_CHANNEL_TOLERANCE})"
)
6 changes: 4 additions & 2 deletions samples/cuda_core/glInteropFluid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ introduced in cuda-core 1.1.
### Hardware

- NVIDIA GPU with Compute Capability 7.0 or higher
- A display (X11 on Linux, native window server on macOS / Windows).
Headless Linux environments (no `$DISPLAY`) waive the sample.
- A display (X11 on Linux, native window server on macOS / Windows). On
Linux without `$DISPLAY`, the sample renders offscreen through EGL on the
GPU and checks that the last frame shows the CUDA kernel's output. It
waives when neither a display nor an NVIDIA EGL device is available.

### Software

Expand Down
20 changes: 13 additions & 7 deletions samples/cuda_core/glInteropFluid/glInteropFluid.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@
import ctypes
import math
import os
import platform
import random
import sys
import time
Expand Down Expand Up @@ -123,8 +122,12 @@
ReadModeType,
)

sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "cuda_python_test_helpers"))
from cuda_python_test_helpers.graphics import gl_context_not_on_nvidia_gpu_reason
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "Utilities"))
from graphics import (
gl_context_not_on_nvidia_gpu_reason,
use_headless_gl_if_no_display,
verify_frame_shows_pixel_buffer,
)

# ---------------------------------------------------------------------------
# Simulation parameters (feel free to change these)
Expand Down Expand Up @@ -549,10 +552,9 @@ def main(argv=None):
)
args = parser.parse_args(argv)

# Waive when no display is available (headless CI, Wayland-only, etc.).
if platform.system() == "Linux" and not os.environ.get("DISPLAY"):
print("No DISPLAY available; waiving glInteropFluid.", file=sys.stderr)
sys.exit(EXIT_WAIVED)
# Without an X display (a headless CI runner, for example), render
# offscreen with an EGL context on the GPU behind the CUDA device.
headless = use_headless_gl_if_no_display(0)

# --- Step 1: Set up CUDA (compile kernels, create stream) ---
dev, stream, kernels, config = setup_cuda()
Expand Down Expand Up @@ -969,6 +971,10 @@ def on_draw():
fps_time = now

if args.frames is not None and frames_rendered >= args.frames:
if headless:
# Nobody sees an offscreen frame, so check that it shows the
# kernel's output.
verify_frame_shows_pixel_buffer(pbo_id, WIDTH, HEIGHT)
# Let pyglet finish the current refresh/flip before tearing down
# the GL context and registered CUDA graphics resource.
pyglet.app.exit()
Expand Down
6 changes: 4 additions & 2 deletions samples/cuda_core/glInteropMipmapLod/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ The sample:
### Hardware

- NVIDIA GPU with Compute Capability 7.0 or higher
- A display (X11 on Linux, native window server on macOS / Windows).
Headless environments waive the sample.
- A display (X11 on Linux, native window server on macOS / Windows). On
Linux without `$DISPLAY`, the sample renders offscreen through EGL on the
GPU and checks that the last frame shows the CUDA kernel's output. It
waives when neither a display nor an NVIDIA EGL device is available.

### Software

Expand Down
20 changes: 13 additions & 7 deletions samples/cuda_core/glInteropMipmapLod/glInteropMipmapLod.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@
import ctypes
import math
import os
import platform
import sys
import time
from pathlib import Path
Expand All @@ -116,8 +115,12 @@
ReadModeType,
)

sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "cuda_python_test_helpers"))
from cuda_python_test_helpers.graphics import gl_context_not_on_nvidia_gpu_reason
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "Utilities"))
from graphics import (
gl_context_not_on_nvidia_gpu_reason,
use_headless_gl_if_no_display,
verify_frame_shows_pixel_buffer,
)

# ---------------------------------------------------------------------------
# Configuration (feel free to change these)
Expand Down Expand Up @@ -423,10 +426,9 @@ def main(argv=None):
)
args = parser.parse_args(argv)

# Waive when no display is available (headless CI, Wayland-only, etc.).
if platform.system() == "Linux" and not os.environ.get("DISPLAY"):
print("No DISPLAY available; waiving glInteropMipmapLod.", file=sys.stderr)
sys.exit(EXIT_WAIVED)
# Without an X display (a headless CI runner, for example), render
# offscreen with an EGL context on the GPU behind the CUDA device.
headless = use_headless_gl_if_no_display(0)

# --- Step 1: Set up CUDA (compile kernels, create stream) ---
dev, stream, kernels, _arch = setup_cuda()
Expand Down Expand Up @@ -561,6 +563,10 @@ def on_draw():
fps_time[0] = now

if args.frames is not None and frames_rendered[0] >= args.frames:
if headless:
# Nobody sees an offscreen frame, so check that it shows the
# kernel's output.
verify_frame_shows_pixel_buffer(pbo_id, WIDTH, HEIGHT)
# Let pyglet finish the current refresh/flip before tearing down
# the GL context and registered CUDA graphics resource.
pyglet.app.exit()
Expand Down
Loading
Loading