diff --git a/cuda_core/tests/example_tests/test_samples.py b/cuda_core/tests/example_tests/test_samples.py index a25da39eb7bc..13e20e5b9484 100644 --- a/cuda_core/tests/example_tests/test_samples.py +++ b/cuda_core/tests/example_tests/test_samples.py @@ -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) diff --git a/cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py b/cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py index 362363c57c5f..495a57019176 100644 --- a/cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py +++ b/cuda_python_test_helpers/cuda_python_test_helpers/sample_runner.py @@ -15,6 +15,7 @@ from __future__ import annotations import argparse +import ast import concurrent.futures import importlib.metadata import json @@ -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)) + 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 @@ -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) diff --git a/samples/cuda_core/Utilities/README.md b/samples/cuda_core/Utilities/README.md index 4482298ef79e..acdb330ad8fa 100644 --- a/samples/cuda_core/Utilities/README.md +++ b/samples/cuda_core/Utilities/README.md @@ -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: diff --git a/samples/cuda_core/Utilities/graphics.py b/samples/cuda_core/Utilities/graphics.py new file mode 100644 index 000000000000..4e08e2ddcddd --- /dev/null +++ b/samples/cuda_core/Utilities/graphics.py @@ -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) + 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})" + ) diff --git a/samples/cuda_core/glInteropFluid/README.md b/samples/cuda_core/glInteropFluid/README.md index a483436a0df3..235e49d90e3e 100644 --- a/samples/cuda_core/glInteropFluid/README.md +++ b/samples/cuda_core/glInteropFluid/README.md @@ -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 diff --git a/samples/cuda_core/glInteropFluid/glInteropFluid.py b/samples/cuda_core/glInteropFluid/glInteropFluid.py index daec5cc91631..95ae359644bf 100644 --- a/samples/cuda_core/glInteropFluid/glInteropFluid.py +++ b/samples/cuda_core/glInteropFluid/glInteropFluid.py @@ -95,7 +95,6 @@ import ctypes import math import os -import platform import random import sys import time @@ -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) @@ -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() @@ -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() diff --git a/samples/cuda_core/glInteropMipmapLod/README.md b/samples/cuda_core/glInteropMipmapLod/README.md index 96013a67e17b..739945963a76 100644 --- a/samples/cuda_core/glInteropMipmapLod/README.md +++ b/samples/cuda_core/glInteropMipmapLod/README.md @@ -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 diff --git a/samples/cuda_core/glInteropMipmapLod/glInteropMipmapLod.py b/samples/cuda_core/glInteropMipmapLod/glInteropMipmapLod.py index 6d4b4da40c6e..3ccf27dfcf12 100644 --- a/samples/cuda_core/glInteropMipmapLod/glInteropMipmapLod.py +++ b/samples/cuda_core/glInteropMipmapLod/glInteropMipmapLod.py @@ -89,7 +89,6 @@ import ctypes import math import os -import platform import sys import time from pathlib import Path @@ -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) @@ -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() @@ -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() diff --git a/samples/cuda_core/glInteropPlasma/README.md b/samples/cuda_core/glInteropPlasma/README.md index c3b9c443421c..da93679173c7 100644 --- a/samples/cuda_core/glInteropPlasma/README.md +++ b/samples/cuda_core/glInteropPlasma/README.md @@ -59,8 +59,10 @@ Each frame: ### 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`) will 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 @@ -111,11 +113,8 @@ closes automatically after `--frames` frames: Rendered 60 frames via CUDA/OpenGL interop. Done ``` -On a headless Linux runner the sample self-waives with: - -``` -No DISPLAY available; waiving GL interop sample. -``` +On a headless Linux runner the sample renders the same frames offscreen and +prints the same message. It waives when no NVIDIA GL context is available. ## Files diff --git a/samples/cuda_core/glInteropPlasma/glInteropPlasma.py b/samples/cuda_core/glInteropPlasma/glInteropPlasma.py index ff96d5980799..11165e4d1581 100644 --- a/samples/cuda_core/glInteropPlasma/glInteropPlasma.py +++ b/samples/cuda_core/glInteropPlasma/glInteropPlasma.py @@ -55,13 +55,13 @@ By default this sample runs for a bounded number of frames so it is CI-friendly; pass ``--interactive`` to run until the window is closed. -Headless environments (no ``DISPLAY``) waive the sample. +On Linux without ``DISPLAY``, it renders offscreen through EGL and checks +the last frame. """ import argparse import ctypes import os -import platform import sys import time from pathlib import Path @@ -78,8 +78,12 @@ launch, ) - 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, + ) except ImportError as e: print(f"Error: Required package not found: {e}") print("Please install from requirements.txt:") @@ -305,12 +309,9 @@ def main(): parser.add_argument("--device", type=int, default=0, help="CUDA device id") args = parser.parse_args() - # Waive the sample when there is no display available. On Linux we look - # at $DISPLAY; on other platforms we just try and let pyglet fail below - # if it cannot open a window. - if platform.system() == "Linux" and not os.environ.get("DISPLAY"): - print("No DISPLAY available; waiving GL interop sample.", 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(args.device) # --- Step 1: Set up CUDA (compile kernel, create stream) --- _dev, stream, kernel, config = setup_cuda(PLASMA_KERNEL_SOURCE, device_id=args.device) @@ -402,6 +403,10 @@ def on_draw(): # Terminate after --frames iterations when not interactive. if not args.interactive 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()