|
20 | 20 | from typing import ( |
21 | 21 | Optional, |
22 | 22 | Dict, |
| 23 | + List, |
| 24 | + Tuple, |
23 | 25 | Union, |
24 | 26 | ) |
25 | 27 | from bioimageio.spec.model.v0_5 import ( |
@@ -107,14 +109,33 @@ def isatty(self): |
107 | 109 | return False |
108 | 110 |
|
109 | 111 |
|
| 112 | +GpuArg = Union[str, int, List[Union[str, int]], Tuple[Union[str, int], ...], None] |
| 113 | + |
| 114 | + |
| 115 | +def _normalize_gpu_arg(gpu: GpuArg) -> str: |
| 116 | + """Normalize 'gpu' (str, int, or list/tuple of either) into a CUDA_VISIBLE_DEVICES-style string.""" |
| 117 | + if gpu is None: |
| 118 | + return "" |
| 119 | + if isinstance(gpu, str): |
| 120 | + return gpu.strip() |
| 121 | + if isinstance(gpu, int): |
| 122 | + return str(gpu) |
| 123 | + if isinstance(gpu, (list, tuple)): |
| 124 | + return ",".join(str(g).strip() for g in gpu) |
| 125 | + raise TypeError( |
| 126 | + f"'gpu' must be a str, int, list or tuple (got {type(gpu).__name__}). " |
| 127 | + "Examples: gpu=0, gpu='0', gpu='0,1', gpu=[0, 1]." |
| 128 | + ) |
| 129 | + |
| 130 | + |
110 | 131 | class BiaPy: |
111 | 132 | def __init__( |
112 | 133 | self, |
113 | 134 | config: Union[str, dict, CN], |
114 | 135 | result_dir: Optional[str] = None, |
115 | 136 | name: Optional[str] = "unknown_job", |
116 | 137 | run_id: Optional[int] = 1, |
117 | | - gpu: Optional[str] = "", |
| 138 | + gpu: GpuArg = "", |
118 | 139 | world_size: Optional[int] = 1, |
119 | 140 | local_rank: Optional[int] = -1, |
120 | 141 | dist_on_itp: Optional[bool] = False, |
@@ -146,8 +167,10 @@ def __init__( |
146 | 167 | run_id: int, optional |
147 | 168 | Run number of the same job. Defaults to 1. |
148 | 169 |
|
149 | | - gpu: str, optional |
150 | | - GPU number according to 'nvidia-smi' command. Defaults to None. |
| 170 | + gpu: str, int, list or tuple, optional |
| 171 | + GPU number(s) according to 'nvidia-smi' command, or "mps" for Apple Silicon. Accepts |
| 172 | + a single value (``0`` or ``"0"``) or multiple (``"0,1"``, ``[0, 1]``, ``(0, 1)``). |
| 173 | + Defaults to "" (CPU). |
151 | 174 |
|
152 | 175 | world_size: int, optional |
153 | 176 | Number of distributed processes. Defaults to 1. |
@@ -220,7 +243,7 @@ def __init__( |
220 | 243 | result_dir=result_dir, |
221 | 244 | name=name, |
222 | 245 | run_id=run_id, |
223 | | - gpu=gpu, |
| 246 | + gpu=_normalize_gpu_arg(gpu), |
224 | 247 | world_size=world_size, |
225 | 248 | local_rank=local_rank, |
226 | 249 | dist_on_itp=dist_on_itp, |
|
0 commit comments