diff --git a/CHANGELOG.md b/CHANGELOG.md index c7a05c4d..617c8493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## Unreleased +- Fix crash of the CuPy backend when CuPy returns a GPU UUID that is shorter than 16 bytes. The UUID is `None` in this case. ## [1.6.0] - 2026-11-13 - Extended Julia functionality: diff --git a/kernel_tuner/backends/cupy.py b/kernel_tuner/backends/cupy.py index 91554c0e..79a62e43 100644 --- a/kernel_tuner/backends/cupy.py +++ b/kernel_tuner/backends/cupy.py @@ -78,7 +78,11 @@ def __init__(self, device=0, iterations=7, compiler_options=None, observers=None env["device_properties"] = self.devprops props = cp.cuda.runtime.getDeviceProperties(device) - env["uuid"] = str(uuid.UUID(bytes=props["uuid"])) + # CuPy stops at the first zero byte of the UUID, so a valid UUID can be too short. + # Do not pad it: the result would be a wrong UUID. + env["uuid"] = None + if len(props["uuid"]) == 16: + env["uuid"] = str(uuid.UUID(bytes=props["uuid"])) self.env = env self.name = env["device_name"] diff --git a/test/test_cupy_functions.py b/test/test_cupy_functions.py index 4bb4d16f..a73f4959 100644 --- a/test/test_cupy_functions.py +++ b/test/test_cupy_functions.py @@ -1,5 +1,11 @@ +import uuid +from unittest import mock + +import pytest + import kernel_tuner +from kernel_tuner.backends import cupy as kt_cupy from .context import skip_if_no_cupy from .test_runners import env # noqa: F401 @@ -10,3 +16,36 @@ def test_tune_kernel(env): result, _ = kernel_tuner.tune_kernel(*env, lang="cupy", verbose=True) assert len(result) > 0 + +def _mock_cupy(uuid_bytes): + """Make a fake cupy module, so that this test needs no GPU.""" + cp = mock.MagicMock() + cp.cuda.Device.return_value.attributes = {"MaxThreadsPerBlock": 1024} + cp.cuda.runtime.getDeviceProperties.return_value = {"uuid": uuid_bytes} + return cp + + +def _mock_runtime_info(*args): + return "Device 0 Name : Fake GPU\nDevice 0 PCI Bus ID : 0000:00:00.0\n" + + +@pytest.mark.parametrize( + "uuid_bytes, expected", + [ + (bytes.fromhex("1eed7047720e7d2e45614205587600d0"), "1eed7047-720e-7d2e-4561-4205587600d0"), + # CuPy stops at the first zero byte of this UUID + (bytes.fromhex("1eed7047720e7d2e456142055876"), None), + (b"", None), + ], +) +def test_device_uuid(uuid_bytes, expected): + """The device UUID is valid, or None if CuPy returns less than 16 bytes.""" + with ( + mock.patch.object(kt_cupy, "cp", _mock_cupy(uuid_bytes)), + mock.patch.object(kt_cupy, "get_runtime_info", _mock_runtime_info, create=True), + ): + dev = kt_cupy.CupyFunctions(0) + + assert dev.env["uuid"] == expected + if expected is not None: + assert str(uuid.UUID(dev.env["uuid"])) == expected