-
Notifications
You must be signed in to change notification settings - Fork 5
[rocm, test] feat: add ROCm controller and test tooling #56
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e146e5b
Implement ROCm GPU controller and tests
Wangmerlyn 926e6ba
Gate ROCm tests behind marker/flag
Wangmerlyn 54bc422
Add developer testing notes for CUDA/ROCm
Wangmerlyn b52e8dc
Refactor GPU controllers and ROCm tests
Wangmerlyn 16e05a3
Cleanup ROCm controller tweaks and tests
Wangmerlyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| import threading | ||
| import time | ||
| from typing import Optional | ||
|
|
||
| import torch | ||
|
|
||
| from keep_gpu.single_gpu_controller.base_gpu_controller import BaseGPUController | ||
| from keep_gpu.utilities.logger import setup_logger | ||
|
|
||
| logger = setup_logger(__name__) | ||
|
|
||
|
|
||
| class RocmGPUController(BaseGPUController): | ||
| """ | ||
| Keep a single ROCm GPU busy by running lightweight elementwise ops | ||
| in a background thread. Requires a ROCm-enabled torch build. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| rank: int, | ||
| interval: float = 1.0, | ||
| vram_to_keep: str | int = "1000 MB", | ||
| busy_threshold: int = 10, | ||
| iterations: int = 5000, | ||
| ): | ||
| super().__init__(vram_to_keep=vram_to_keep, interval=interval) | ||
| self.rank = rank | ||
| self.device = torch.device(f"cuda:{rank}") | ||
| self.busy_threshold = busy_threshold | ||
| self.iterations = iterations | ||
| self._stop_evt: Optional[threading.Event] = None | ||
| self._thread: Optional[threading.Thread] = None | ||
|
|
||
| # Lazy rocm_smi import; keep handle for reuse | ||
| try: | ||
| import rocm_smi # type: ignore | ||
|
|
||
| self._rocm_smi = rocm_smi | ||
| except Exception as exc: # pragma: no cover - env-specific | ||
| logger.debug("rocm_smi not available: %s", exc) | ||
| self._rocm_smi = None | ||
|
|
||
| def keep(self) -> None: | ||
| if self._thread and self._thread.is_alive(): | ||
| logger.warning("rank %s: keep thread already running", self.rank) | ||
| return | ||
| if self._rocm_smi: | ||
| try: | ||
| self._rocm_smi.rsmi_init() | ||
| except Exception as exc: # pragma: no cover - env-specific | ||
| logger.debug("rsmi_init failed: %s", exc) | ||
|
|
||
| self._stop_evt = threading.Event() | ||
| self._thread = threading.Thread( | ||
| target=self._keep_loop, | ||
| name=f"gpu-keeper-rocm-{self.rank}", | ||
| daemon=True, | ||
| ) | ||
| self._thread.start() | ||
| logger.info("rank %s: ROCm keep thread started", self.rank) | ||
|
|
||
| def release(self) -> None: | ||
| if not (self._thread and self._thread.is_alive()): | ||
| logger.warning("rank %s: keep thread not running", self.rank) | ||
| return | ||
| self._stop_evt.set() | ||
| self._thread.join() | ||
| torch.cuda.empty_cache() | ||
| if self._rocm_smi: | ||
| try: | ||
| self._rocm_smi.rsmi_shut_down() | ||
| except Exception as exc: # pragma: no cover - best effort | ||
| logger.debug("rsmi_shut_down failed: %s", exc) | ||
| logger.info("rank %s: keep thread stopped & cache cleared", self.rank) | ||
|
|
||
| def __enter__(self): | ||
| self.keep() | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc, tb): | ||
| self.release() | ||
|
|
||
| def _query_utilization(self) -> Optional[int]: | ||
| if not self._rocm_smi: | ||
| return None | ||
| try: | ||
| util = self._rocm_smi.rsmi_dev_busy_percent_get(self.rank) | ||
| return int(util) | ||
| except Exception as exc: # pragma: no cover - env-specific | ||
| logger.debug("ROCm utilization query failed: %s", exc) | ||
| return None | ||
|
|
||
| def _keep_loop(self) -> None: | ||
| torch.cuda.set_device(self.rank) | ||
| tensor = None | ||
| while not self._stop_evt.is_set(): | ||
| try: | ||
| tensor = torch.rand( | ||
| self.vram_to_keep, | ||
| device=self.device, | ||
| dtype=torch.float32, | ||
| requires_grad=False, | ||
| ) | ||
| break | ||
| except RuntimeError: | ||
| logger.exception("rank %s: failed to allocate tensor", self.rank) | ||
| time.sleep(self.interval) | ||
| if tensor is None: | ||
| logger.error("rank %s: failed to allocate tensor, exiting loop", self.rank) | ||
| raise RuntimeError("Failed to allocate tensor for ROCm GPU keeping") | ||
|
|
||
| while not self._stop_evt.is_set(): | ||
| try: | ||
| util = self._query_utilization() | ||
| if util is not None and util > self.busy_threshold: | ||
| logger.debug("rank %s: GPU busy (%d%%), sleeping", self.rank, util) | ||
| else: | ||
| self._run_batch(tensor) | ||
| time.sleep(self.interval) | ||
| except RuntimeError as exc: | ||
| if "out of memory" in str(exc).lower(): | ||
| torch.cuda.empty_cache() | ||
| time.sleep(self.interval) | ||
| except Exception: | ||
| logger.exception("rank %s: unexpected error", self.rank) | ||
| time.sleep(self.interval) | ||
|
|
||
| @torch.no_grad() | ||
| def _run_batch(self, tensor: torch.Tensor) -> None: | ||
| tic = time.time() | ||
| for _ in range(self.iterations): | ||
| torch.relu_(tensor) | ||
| if self._stop_evt.is_set(): | ||
| break | ||
| torch.cuda.synchronize() | ||
| toc = time.time() | ||
| logger.debug( | ||
| "rank %s: elementwise batch done - avg %.2f ms", | ||
| self.rank, | ||
| (toc - tic) * 1000 / max(1, self.iterations), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import pytest | ||
| import torch | ||
|
|
||
|
|
||
| def pytest_addoption(parser): | ||
| parser.addoption( | ||
| "--run-rocm", | ||
| action="store_true", | ||
| default=False, | ||
| help="run tests marked as rocm (require ROCm stack)", | ||
| ) | ||
|
|
||
|
|
||
| def pytest_configure(config): | ||
| config.addinivalue_line("markers", "rocm: tests that require ROCm stack") | ||
| config.addinivalue_line("markers", "large_memory: tests that use large VRAM") | ||
|
|
||
|
|
||
| def pytest_collection_modifyitems(config, items): | ||
| if config.getoption("--run-rocm"): | ||
| return | ||
|
|
||
| skip_rocm = pytest.mark.skip(reason="need --run-rocm option to run") | ||
| for item in items: | ||
| if "rocm" in item.keywords: | ||
| item.add_marker(skip_rocm) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def rocm_available(): | ||
| return bool(torch.cuda.is_available() and getattr(torch.version, "hip", None)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import sys | ||
|
|
||
| import pytest | ||
|
|
||
| from keep_gpu.single_gpu_controller import rocm_gpu_controller as rgc | ||
|
|
||
|
|
||
| @pytest.mark.rocm | ||
| def test_query_rocm_utilization_with_mock(monkeypatch, rocm_available): | ||
| if not rocm_available: | ||
| pytest.skip("ROCm stack not available") | ||
|
|
||
| class DummyRocmSMI: | ||
| calls = 0 | ||
|
|
||
| @classmethod | ||
| def rsmi_init(cls): | ||
| cls.calls += 1 | ||
|
|
||
| @staticmethod | ||
| def rsmi_dev_busy_percent_get(index): | ||
| assert index == 1 | ||
| return 42 | ||
|
|
||
| @classmethod | ||
| def rsmi_shut_down(cls): | ||
| cls.calls += 1 | ||
|
|
||
| # Ensure the counter is reset to avoid leaking state between tests | ||
| DummyRocmSMI.calls = 0 | ||
| monkeypatch.setitem(sys.modules, "rocm_smi", DummyRocmSMI) | ||
| util = rgc._query_rocm_utilization(1) | ||
| assert util == 42 | ||
| assert DummyRocmSMI.calls == 2 # init + shutdown | ||
| # Reset after test for cleanliness | ||
| DummyRocmSMI.calls = 0 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
The pytest markers
rocmandlarge_memoryare already registered inpyproject.tomlunder[tool.pytest.ini_options]. Thispytest_configurefunction is therefore redundant and can be removed to avoid duplicated configuration.