|
| 1 | +import threading |
| 2 | +import time |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import torch |
| 6 | + |
| 7 | +from keep_gpu.single_gpu_controller.base_gpu_controller import BaseGPUController |
| 8 | +from keep_gpu.utilities.logger import setup_logger |
| 9 | + |
| 10 | +logger = setup_logger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class RocmGPUController(BaseGPUController): |
| 14 | + """ |
| 15 | + Keep a single ROCm GPU busy by running lightweight elementwise ops |
| 16 | + in a background thread. Requires a ROCm-enabled torch build. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + *, |
| 22 | + rank: int, |
| 23 | + interval: float = 1.0, |
| 24 | + vram_to_keep: str | int = "1000 MB", |
| 25 | + busy_threshold: int = 10, |
| 26 | + iterations: int = 5000, |
| 27 | + ): |
| 28 | + super().__init__(vram_to_keep=vram_to_keep, interval=interval) |
| 29 | + self.rank = rank |
| 30 | + self.device = torch.device(f"cuda:{rank}") |
| 31 | + self.busy_threshold = busy_threshold |
| 32 | + self.iterations = iterations |
| 33 | + self._stop_evt: Optional[threading.Event] = None |
| 34 | + self._thread: Optional[threading.Thread] = None |
| 35 | + |
| 36 | + # Lazy rocm_smi import; keep handle for reuse |
| 37 | + try: |
| 38 | + import rocm_smi # type: ignore |
| 39 | + |
| 40 | + self._rocm_smi = rocm_smi |
| 41 | + except Exception as exc: # pragma: no cover - env-specific |
| 42 | + logger.debug("rocm_smi not available: %s", exc) |
| 43 | + self._rocm_smi = None |
| 44 | + |
| 45 | + def keep(self) -> None: |
| 46 | + if self._thread and self._thread.is_alive(): |
| 47 | + logger.warning("rank %s: keep thread already running", self.rank) |
| 48 | + return |
| 49 | + if self._rocm_smi: |
| 50 | + try: |
| 51 | + self._rocm_smi.rsmi_init() |
| 52 | + except Exception as exc: # pragma: no cover - env-specific |
| 53 | + logger.debug("rsmi_init failed: %s", exc) |
| 54 | + |
| 55 | + self._stop_evt = threading.Event() |
| 56 | + self._thread = threading.Thread( |
| 57 | + target=self._keep_loop, |
| 58 | + name=f"gpu-keeper-rocm-{self.rank}", |
| 59 | + daemon=True, |
| 60 | + ) |
| 61 | + self._thread.start() |
| 62 | + logger.info("rank %s: ROCm keep thread started", self.rank) |
| 63 | + |
| 64 | + def release(self) -> None: |
| 65 | + if not (self._thread and self._thread.is_alive()): |
| 66 | + logger.warning("rank %s: keep thread not running", self.rank) |
| 67 | + return |
| 68 | + self._stop_evt.set() |
| 69 | + self._thread.join() |
| 70 | + torch.cuda.empty_cache() |
| 71 | + if self._rocm_smi: |
| 72 | + try: |
| 73 | + self._rocm_smi.rsmi_shut_down() |
| 74 | + except Exception as exc: # pragma: no cover - best effort |
| 75 | + logger.debug("rsmi_shut_down failed: %s", exc) |
| 76 | + logger.info("rank %s: keep thread stopped & cache cleared", self.rank) |
| 77 | + |
| 78 | + def __enter__(self): |
| 79 | + self.keep() |
| 80 | + return self |
| 81 | + |
| 82 | + def __exit__(self, exc_type, exc, tb): |
| 83 | + self.release() |
| 84 | + |
| 85 | + def _query_utilization(self) -> Optional[int]: |
| 86 | + if not self._rocm_smi: |
| 87 | + return None |
| 88 | + try: |
| 89 | + util = self._rocm_smi.rsmi_dev_busy_percent_get(self.rank) |
| 90 | + return int(util) |
| 91 | + except Exception as exc: # pragma: no cover - env-specific |
| 92 | + logger.debug("ROCm utilization query failed: %s", exc) |
| 93 | + return None |
| 94 | + |
| 95 | + def _keep_loop(self) -> None: |
| 96 | + torch.cuda.set_device(self.rank) |
| 97 | + tensor = None |
| 98 | + while not self._stop_evt.is_set(): |
| 99 | + try: |
| 100 | + tensor = torch.rand( |
| 101 | + self.vram_to_keep, |
| 102 | + device=self.device, |
| 103 | + dtype=torch.float32, |
| 104 | + requires_grad=False, |
| 105 | + ) |
| 106 | + break |
| 107 | + except RuntimeError: |
| 108 | + logger.exception("rank %s: failed to allocate tensor", self.rank) |
| 109 | + time.sleep(self.interval) |
| 110 | + if tensor is None: |
| 111 | + logger.error("rank %s: failed to allocate tensor, exiting loop", self.rank) |
| 112 | + raise RuntimeError("Failed to allocate tensor for ROCm GPU keeping") |
| 113 | + |
| 114 | + while not self._stop_evt.is_set(): |
| 115 | + try: |
| 116 | + util = self._query_utilization() |
| 117 | + if util is not None and util > self.busy_threshold: |
| 118 | + logger.debug("rank %s: GPU busy (%d%%), sleeping", self.rank, util) |
| 119 | + else: |
| 120 | + self._run_batch(tensor) |
| 121 | + time.sleep(self.interval) |
| 122 | + except RuntimeError as exc: |
| 123 | + if "out of memory" in str(exc).lower(): |
| 124 | + torch.cuda.empty_cache() |
| 125 | + time.sleep(self.interval) |
| 126 | + except Exception: |
| 127 | + logger.exception("rank %s: unexpected error", self.rank) |
| 128 | + time.sleep(self.interval) |
| 129 | + |
| 130 | + @torch.no_grad() |
| 131 | + def _run_batch(self, tensor: torch.Tensor) -> None: |
| 132 | + tic = time.time() |
| 133 | + for _ in range(self.iterations): |
| 134 | + torch.relu_(tensor) |
| 135 | + if self._stop_evt.is_set(): |
| 136 | + break |
| 137 | + torch.cuda.synchronize() |
| 138 | + toc = time.time() |
| 139 | + logger.debug( |
| 140 | + "rank %s: elementwise batch done - avg %.2f ms", |
| 141 | + self.rank, |
| 142 | + (toc - tic) * 1000 / max(1, self.iterations), |
| 143 | + ) |
0 commit comments