Repository navigation
test(cuda.core): run the GL interop samples headless and drop their test-helper dependency #3654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Waive the samples when the EGL loader fails during headless setup.
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})" | ||
| ) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
important: Convert source-inspection errors into a sample result.
If a sample contains a syntax error,
ast.parseraises beforerun_samplereaches its subprocess handling. The exception escapes intomain, interrupts the batch, and prevents its summary. Previously, the same sample produced a nonzero child exit and aFAILresult.Handle inspection failures narrowly and return an
ERRORresult with the source diagnostic. Do not waive the sample. Valid samples must continue through the existing checks.