Skip to content
Merged
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,7 @@ output.yaml

# Auto-generated version file
src/somd2/_version.py

# Cached inputs.
cache
tests/cache
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------------------------------------------------------------------------
Expand Down
31 changes: 18 additions & 13 deletions src/somd2/runner/_dynamics_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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."
Expand All @@ -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}"
Expand Down
79 changes: 79 additions & 0 deletions tests/runner/test_dynamics_cache.py
Original file line number Diff line number Diff line change
@@ -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()
Loading