diff --git a/.gitignore b/.gitignore index 0084085..8c29328 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,7 @@ output.yaml # Auto-generated version file src/somd2/_version.py + +# Cached inputs. +cache +tests/cache diff --git a/CHANGELOG.md b/CHANGELOG.md index c51698d..49e9768 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ Changelog * Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#296](https://github.com/OpenBioSim/somd2/pull/296). * Add a `rest2_profile` option. The default, `exponential`, gives a geometric ladder of REST2 scale factors, rather than the previous linear rise, which is still available as `linear`. REST2 runs started before this change must set `rest2_profile` to `linear` to restart [#296](https://github.com/OpenBioSim/somd2/pull/296). * Log the per-window GCMC, terminal flip and dynamics messages of replica exchange runs at debug level, rather than info, reducing the size of the log by around 30 times. Progress is still logged once per cycle [#298](https://github.com/OpenBioSim/somd2/pull/298). +* Fixed an `IndexError` when querying GPU memory if OpenCL enumerates fewer devices than the requested device index, allowing fallback to `pynvml` [#301](https://github.com/OpenBioSim/somd2/pull/301). [2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/src/somd2/runner/_dynamics_cache.py b/src/somd2/runner/_dynamics_cache.py index 7205dcb..2dfa5b8 100644 --- a/src/somd2/runner/_dynamics_cache.py +++ b/src/somd2/runner/_dynamics_cache.py @@ -1430,7 +1430,10 @@ def _check_device_memory(device=0): the visible set, whereas pynvml and pyopencl enumerate all devices on the machine, so the two only agree when the visible set starts at zero and is contiguous. CUDA_VISIBLE_DEVICES entries may be - either an index or a UUID. + either an index or a UUID. In containerized or cgroup-isolated + environments where only a subset of GPU device nodes is mounted, + OpenCL may expose fewer devices than the physical index and will + fall back to pynvml. """ device = str(device).strip() @@ -1461,11 +1464,11 @@ def _check_device_memory(device=0): ocl_device = all_devices[device_index] vendor = ocl_device.vendor else: - msg = f"Device index {device_index} out of range. Found {len(all_devices)} GPU(s)." - _logger.error(msg) - raise IndexError(msg) - except IndexError: - raise + msg = ( + f"Device index {device_index} out of range for OpenCL " + f"(found {len(all_devices)} GPU(s)); falling back to pynvml." + ) + _logger.warning(msg) except Exception: _logger.warning( "Could not query GPU platform via OpenCL; falling back to pynvml for NVIDIA detection." @@ -1477,13 +1480,15 @@ def _check_device_memory(device=0): import pynvml pynvml.nvmlInit() - if is_uuid: - handle = pynvml.nvmlDeviceGetHandleByUUID(device.encode()) - else: - handle = pynvml.nvmlDeviceGetHandleByIndex(device_index) - memory = pynvml.nvmlDeviceGetMemoryInfo(handle) - pynvml.nvmlShutdown() - return (memory.used, memory.free, memory.total) + try: + if is_uuid: + handle = pynvml.nvmlDeviceGetHandleByUUID(device.encode()) + else: + handle = pynvml.nvmlDeviceGetHandleByIndex(device_index) + memory = pynvml.nvmlDeviceGetMemoryInfo(handle) + return (memory.used, memory.free, memory.total) + finally: + pynvml.nvmlShutdown() except Exception as e: if vendor is None: msg = f"Could not get GPU memory info for device {device} via OpenCL or pynvml: {e}" diff --git a/tests/runner/test_dynamics_cache.py b/tests/runner/test_dynamics_cache.py new file mode 100644 index 0000000..2212c29 --- /dev/null +++ b/tests/runner/test_dynamics_cache.py @@ -0,0 +1,79 @@ +from unittest.mock import MagicMock, patch +from somd2.runner._dynamics_cache import DynamicsCache + + +def _mock_opencl(vendors): + """Build a mock pyopencl module exposing one GPU per vendor string.""" + devices = [] + for v in vendors: + dev = MagicMock() + dev.vendor = v + devices.append(dev) + + mock_platform = MagicMock() + mock_platform.get_devices.return_value = devices + + mock_cl = MagicMock() + mock_cl.get_platforms.return_value = [mock_platform] + return mock_cl + + +def _mock_pynvml(used=1024, free=2048, total=3072): + """Build a mock pynvml module returning fixed memory values.""" + mock_mem = MagicMock(used=used, free=free, total=total) + mock_pynvml = MagicMock() + mock_pynvml.nvmlDeviceGetMemoryInfo.return_value = mock_mem + return mock_pynvml + + +def test_in_range_nvidia_device_queries_pynvml(): + """When OpenCL finds the device and identifies NVIDIA, query pynvml by physical index.""" + mock_cl = _mock_opencl(["NVIDIA Corporation", "NVIDIA Corporation"]) + mock_pynvml = _mock_pynvml(1024, 2048, 3072) + + with patch.dict("sys.modules", {"pyopencl": mock_cl, "pynvml": mock_pynvml}): + result = DynamicsCache._check_device_memory(device=1) + + assert result == (1024, 2048, 3072) + mock_pynvml.nvmlDeviceGetHandleByIndex.assert_called_once_with(1) + mock_pynvml.nvmlShutdown.assert_called_once() + + +def test_out_of_range_opencl_index_falls_back_to_pynvml(): + """When OpenCL returns fewer devices than device_index, fall back cleanly to pynvml.""" + mock_cl = _mock_opencl(["NVIDIA Corporation"]) + mock_pynvml = _mock_pynvml(512, 1536, 2048) + + with patch.dict("sys.modules", {"pyopencl": mock_cl, "pynvml": mock_pynvml}): + result = DynamicsCache._check_device_memory(device="2") + + assert result == (512, 1536, 2048) + mock_pynvml.nvmlDeviceGetHandleByIndex.assert_called_once_with(2) + mock_pynvml.nvmlShutdown.assert_called_once() + + +def test_empty_opencl_devices_falls_back_to_pynvml(): + """When OpenCL returns no devices, fall back cleanly to pynvml.""" + mock_cl = _mock_opencl([]) + mock_pynvml = _mock_pynvml(256, 768, 1024) + + with patch.dict("sys.modules", {"pyopencl": mock_cl, "pynvml": mock_pynvml}): + result = DynamicsCache._check_device_memory(device=0) + + assert result == (256, 768, 1024) + mock_pynvml.nvmlDeviceGetHandleByIndex.assert_called_once_with(0) + mock_pynvml.nvmlShutdown.assert_called_once() + + +def test_uuid_device_queries_pynvml_by_uuid(): + """UUID strings skip OpenCL indexing and query pynvml directly by UUID.""" + gpu_uuid = "GPU-12345678-1234-1234-1234-123456789abc" + mock_cl = _mock_opencl(["NVIDIA Corporation"]) + mock_pynvml = _mock_pynvml(2048, 2048, 4096) + + with patch.dict("sys.modules", {"pyopencl": mock_cl, "pynvml": mock_pynvml}): + result = DynamicsCache._check_device_memory(device=gpu_uuid) + + assert result == (2048, 2048, 4096) + mock_pynvml.nvmlDeviceGetHandleByUUID.assert_called_once_with(gpu_uuid.encode()) + mock_pynvml.nvmlShutdown.assert_called_once()