gpushift 0.1.2__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {gpushift-0.1.2 → gpushift-0.1.4}/CHANGELOG.md +11 -0
  2. {gpushift-0.1.2 → gpushift-0.1.4}/PKG-INFO +9 -2
  3. {gpushift-0.1.2 → gpushift-0.1.4}/README.md +8 -1
  4. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/__init__.py +1 -1
  5. gpushift-0.1.4/src/gpushift/amd.py +275 -0
  6. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/cli.py +6 -6
  7. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/daemon.py +2 -2
  8. gpushift-0.1.4/src/gpushift/gpus.py +113 -0
  9. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/hook.py +6 -3
  10. gpushift-0.1.2/src/gpushift/gpus.py → gpushift-0.1.4/src/gpushift/nvidia.py +32 -59
  11. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/runner.py +4 -6
  12. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/scheduler.py +7 -1
  13. gpushift-0.1.4/src/gpushift/windows.py +160 -0
  14. gpushift-0.1.4/tests/test_amd.py +208 -0
  15. {gpushift-0.1.2 → gpushift-0.1.4}/tests/test_hook.py +2 -0
  16. {gpushift-0.1.2 → gpushift-0.1.4}/tests/test_integration.py +16 -0
  17. {gpushift-0.1.2 → gpushift-0.1.4}/tests/test_scheduler.py +16 -0
  18. gpushift-0.1.2/src/gpushift/gpumem.py +0 -102
  19. {gpushift-0.1.2 → gpushift-0.1.4}/.gitignore +0 -0
  20. {gpushift-0.1.2 → gpushift-0.1.4}/LICENSE +0 -0
  21. {gpushift-0.1.2 → gpushift-0.1.4}/examples/hf_trainer_resumable.py +0 -0
  22. {gpushift-0.1.2 → gpushift-0.1.4}/examples/lightning_resumable.py +0 -0
  23. {gpushift-0.1.2 → gpushift-0.1.4}/examples/pytorch_resumable.py +0 -0
  24. {gpushift-0.1.2 → gpushift-0.1.4}/pyproject.toml +0 -0
  25. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/__main__.py +0 -0
  26. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/_entry.py +0 -0
  27. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/_proc.py +0 -0
  28. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/autostart.py +0 -0
  29. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/checkpoint.py +0 -0
  30. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/config.py +0 -0
  31. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/control.py +0 -0
  32. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/cpustat.py +0 -0
  33. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/db.py +0 -0
  34. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/notify.py +0 -0
  35. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/paths.py +0 -0
  36. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/ui.html +0 -0
  37. {gpushift-0.1.2 → gpushift-0.1.4}/src/gpushift/ui.py +0 -0
  38. {gpushift-0.1.2 → gpushift-0.1.4}/tests/conftest.py +0 -0
  39. {gpushift-0.1.2 → gpushift-0.1.4}/tests/jobs/counter.py +0 -0
  40. {gpushift-0.1.2 → gpushift-0.1.4}/tests/test_units.py +0 -0
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4 (2026-11-15)
4
+
5
+ - AMD GPUs on Linux and Windows (not macOS). Integrated graphics with less than
6
+ 2 GB of dedicated memory are skipped.
7
+ - The hook also catches `HIP_VISIBLE_DEVICES=...` and `ROCR_VISIBLE_DEVICES=...`.
8
+
9
+ ## 0.1.3 (2026-11-13)
10
+
11
+ - A job that needs more GPU memory than is free with no jobs running (because
12
+ other programs use it) no longer blocks the jobs behind it.
13
+
3
14
  ## 0.1.2 (2026-11-12)
4
15
 
5
16
  - Removed automatic free mode (freeing the GPUs while you run a game or other
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: gpushift
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: Share one GPU machine between AI coding agents and yourself: a GPU job queue that steps aside when you need the GPUs.
5
5
  Project-URL: Homepage, https://github.com/EdwardGlockner/gpushift
6
6
  Project-URL: Issues, https://github.com/EdwardGlockner/gpushift/issues
@@ -49,7 +49,8 @@ the queue steps aside whenever you need the GPUs yourself.
49
49
  a GPU that would otherwise sit idle, and small jobs share a GPU.
50
50
  - **You stay informed.** Agents hear when their jobs end, you get a desktop
51
51
  notification when one fails, and a local dashboard shows everything.
52
- - Windows, Linux and macOS, any number of NVIDIA GPUs. No configuration needed.
52
+ - Windows, Linux and macOS, any number of NVIDIA GPUs, and AMD GPUs on Linux and
53
+ Windows. No configuration needed.
53
54
 
54
55
  <picture>
55
56
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/EdwardGlockner/gpushift/main/docs/img/gpushift-dark.svg">
@@ -113,6 +114,12 @@ Jobs run in the folder and environment you submitted them from (including your
113
114
  virtualenv), on the GPUs gpushift picked for them. See `gpushift submit --help` for
114
115
  everything else.
115
116
 
117
+ On AMD GPUs, jobs get their GPUs through `ROCR_VISIBLE_DEVICES` (Linux) or
118
+ `HIP_VISIBLE_DEVICES` (Windows). No ROCm tools are needed. If NVIDIA GPUs are
119
+ present too, only those are used. Integrated AMD graphics with less than 2 GB of
120
+ dedicated memory are skipped. AMD GPUs on macOS are not supported (ROCm doesn't
121
+ run there).
122
+
116
123
  ## When you need the GPUs
117
124
 
118
125
  ```bash
@@ -18,7 +18,8 @@ the queue steps aside whenever you need the GPUs yourself.
18
18
  a GPU that would otherwise sit idle, and small jobs share a GPU.
19
19
  - **You stay informed.** Agents hear when their jobs end, you get a desktop
20
20
  notification when one fails, and a local dashboard shows everything.
21
- - Windows, Linux and macOS, any number of NVIDIA GPUs. No configuration needed.
21
+ - Windows, Linux and macOS, any number of NVIDIA GPUs, and AMD GPUs on Linux and
22
+ Windows. No configuration needed.
22
23
 
23
24
  <picture>
24
25
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/EdwardGlockner/gpushift/main/docs/img/gpushift-dark.svg">
@@ -82,6 +83,12 @@ Jobs run in the folder and environment you submitted them from (including your
82
83
  virtualenv), on the GPUs gpushift picked for them. See `gpushift submit --help` for
83
84
  everything else.
84
85
 
86
+ On AMD GPUs, jobs get their GPUs through `ROCR_VISIBLE_DEVICES` (Linux) or
87
+ `HIP_VISIBLE_DEVICES` (Windows). No ROCm tools are needed. If NVIDIA GPUs are
88
+ present too, only those are used. Integrated AMD graphics with less than 2 GB of
89
+ dedicated memory are skipped. AMD GPUs on macOS are not supported (ROCm doesn't
90
+ run there).
91
+
85
92
  ## When you need the GPUs
86
93
 
87
94
  ```bash
@@ -4,4 +4,4 @@ Keep this module free of imports: ``gpushift.checkpoint`` is imported by user
4
4
  training scripts and must stay dependency-free.
5
5
  """
6
6
 
7
- __version__ = "0.1.2"
7
+ __version__ = "0.1.4"
@@ -0,0 +1,275 @@
1
+ """AMD GPUs on Linux (amdgpu driver) and Windows (DXGI). Indices follow HIP's order."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .gpus import GPU
10
+
11
+ LINUX = sys.platform.startswith("linux")
12
+
13
+ AMD = 0x1002
14
+ KFD = "class/kfd/kfd"
15
+ PCI_IDS = ("/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids", "/usr/share/pci.ids")
16
+ MiB = 1024 * 1024
17
+ # Less dedicated memory than this means integrated graphics with a small
18
+ # carve-out (most Ryzen CPUs): useless for jobs, and ROCm usually skips it. APUs
19
+ # with a large carve-out (Strix Halo etc.) stay in.
20
+ MIN_VRAM_MIB = 2048
21
+
22
+
23
+ def _read(p: Path) -> str | None:
24
+ try:
25
+ return p.read_text().strip()
26
+ except (OSError, UnicodeDecodeError):
27
+ return None
28
+
29
+
30
+ def _int(p: Path) -> int | None:
31
+ s = _read(p)
32
+ try:
33
+ return int(s, 0) if s else None
34
+ except ValueError:
35
+ return None
36
+
37
+
38
+ def _props(node: Path) -> dict[str, int]:
39
+ out = {}
40
+ for line in (_read(node / "properties") or "").splitlines():
41
+ k, _, v = line.partition(" ")
42
+ try:
43
+ out[k] = int(v)
44
+ except ValueError:
45
+ pass
46
+ return out
47
+
48
+
49
+ def devices(sys_root: str = "/sys") -> list[tuple[int, int | None, Path, dict[str, int]]]:
50
+ """(index, gpu_id, PCI device dir, properties) per GPU."""
51
+ nodes_dir = Path(sys_root, KFD, "topology", "nodes")
52
+ try:
53
+ nodes = sorted((n for n in nodes_dir.iterdir() if n.name.isdigit()), key=lambda n: int(n.name))
54
+ except OSError:
55
+ return []
56
+ out = []
57
+ for n in nodes:
58
+ p = _props(n)
59
+ if not p.get("simd_count"): # CPU node
60
+ continue
61
+ loc, dom = p.get("location_id", 0), p.get("domain", 0)
62
+ bdf = f"{dom:04x}:{loc >> 8 & 0xFF:02x}:{loc >> 3 & 0x1F:02x}.{loc & 7:x}"
63
+ out.append((len(out), _int(n / "gpu_id"), Path(sys_root, "bus/pci/devices", bdf), p))
64
+ return out
65
+
66
+
67
+ _names: dict[int, str | None] = {}
68
+
69
+
70
+ def _pci_name(device_id: int) -> str | None:
71
+ if device_id in _names:
72
+ return _names[device_id]
73
+ name = None
74
+ want = f"\t{device_id:04x} "
75
+ for f in PCI_IDS:
76
+ try:
77
+ with open(f, encoding="utf-8", errors="replace") as fh:
78
+ in_amd = False
79
+ for line in fh:
80
+ if not line.strip() or line.startswith("#"):
81
+ continue
82
+ if not line.startswith("\t"):
83
+ if in_amd:
84
+ break
85
+ in_amd = line.startswith(f"{AMD:04x} ")
86
+ elif in_amd and line.startswith(want):
87
+ name = line[len(want) :].strip()
88
+ break
89
+ break
90
+ except OSError:
91
+ continue
92
+ _names[device_id] = name
93
+ return name
94
+
95
+
96
+ def usable(sys_root: str = "/sys") -> list[tuple[int, Path, dict[str, int]]]:
97
+ """(ROCr index, PCI device dir, properties) of the GPUs jobs can use, in
98
+ gpushift's order."""
99
+ return [
100
+ (i, dev, props)
101
+ for i, _, dev, props in devices(sys_root)
102
+ if (_int(dev / "mem_info_vram_total") or 0) // MiB >= MIN_VRAM_MIB
103
+ ]
104
+
105
+
106
+ def _name(dev: Path, props: dict[str, int]) -> str:
107
+ product = _read(dev / "product_name")
108
+ if product:
109
+ return product
110
+ pci = _pci_name(_int(dev / "device") or props.get("device_id", 0))
111
+ if pci:
112
+ if "[" in pci and pci.endswith("]"):
113
+ pci = pci[pci.index("[") + 1 : -1]
114
+ return f"AMD {pci}"
115
+ v = props.get("gfx_target_version", 0)
116
+ return f"AMD GPU (gfx{v // 10000}{v // 100 % 100:x}{v % 100:x})" if v else "AMD GPU"
117
+
118
+
119
+ def _hwmon(dev: Path) -> Path | None:
120
+ try:
121
+ return next(iter(sorted((dev / "hwmon").iterdir())), None)
122
+ except OSError:
123
+ return None
124
+
125
+
126
+ def available() -> bool:
127
+ if os.name == "nt":
128
+ return bool(_windows_adapters())
129
+ return LINUX and bool(usable())
130
+
131
+
132
+ def query() -> list[GPU]:
133
+ if os.name == "nt":
134
+ return query_windows()
135
+ return query_linux() if LINUX else []
136
+
137
+
138
+ def per_process(pids=None) -> dict[int, int] | None:
139
+ return per_process_linux(pids) if LINUX and devices() else None
140
+
141
+
142
+ def visible_env(env: dict[str, str], gpus: list[int], windows: bool = os.name == "nt", sys_root: str = "/sys") -> None:
143
+ if windows:
144
+ # HIP on Windows skips integrated GPUs it doesn't support, as usable() does.
145
+ env["HIP_VISIBLE_DEVICES"] = env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, gpus)) or "-1"
146
+ return
147
+ # ROCr counts every GPU, skipped integrated ones included.
148
+ rocr = [i for i, _, _ in usable(sys_root)]
149
+ env["ROCR_VISIBLE_DEVICES"] = ",".join(str(rocr[g] if g < len(rocr) else g) for g in gpus)
150
+ # HIP filters again after ROCR, so it gets 0..n-1. -1 hides all GPUs.
151
+ env["HIP_VISIBLE_DEVICES"] = env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, range(len(gpus)))) or "-1"
152
+
153
+
154
+ def _windows_adapters():
155
+ from . import windows
156
+
157
+ try:
158
+ return [a for a in windows.adapters() if a.vendor == AMD and a.mem_total >= MIN_VRAM_MIB]
159
+ except OSError:
160
+ return []
161
+
162
+
163
+ _counters = None
164
+
165
+
166
+ def query_windows() -> list[GPU]:
167
+ # Assumes HIP numbers AMD GPUs in DXGI order.
168
+ from . import windows
169
+
170
+ global _counters
171
+ found = _windows_adapters()
172
+ if not found:
173
+ return []
174
+ if _counters is None:
175
+ _counters = windows.Counters(
176
+ r"\GPU Adapter Memory(*)\Dedicated Usage", r"\GPU Engine(*)\Utilization Percentage"
177
+ )
178
+ r = _counters.read()
179
+ mem, load = (windows.by_luid(r[0]), windows.busiest_engine(r[1])) if r else ({}, {})
180
+ return [
181
+ GPU(
182
+ i,
183
+ a.name,
184
+ a.mem_total,
185
+ int(mem.get(a.luid, 0)) // MiB,
186
+ util=round(load[a.luid]) if a.luid in load else None,
187
+ vendor="amd",
188
+ )
189
+ for i, a in enumerate(found)
190
+ ]
191
+
192
+
193
+ def query_linux(sys_root: str = "/sys") -> list[GPU]:
194
+ out = []
195
+ for idx, (_, dev, props) in enumerate(usable(sys_root)):
196
+ g = GPU(
197
+ idx,
198
+ _name(dev, props),
199
+ (_int(dev / "mem_info_vram_total") or 0) // MiB,
200
+ (_int(dev / "mem_info_vram_used") or 0) // MiB,
201
+ vendor="amd",
202
+ )
203
+ g.util = _int(dev / "gpu_busy_percent")
204
+ hw = _hwmon(dev)
205
+ if hw is not None:
206
+ t = next((p for p in sorted(hw.glob("temp*_label")) if _read(p) == "edge"), hw / "temp1_label")
207
+ temp = _int(hw / t.name.replace("_label", "_input"))
208
+ g.temp = temp // 1000 if temp is not None else None
209
+ power = _int(hw / "power1_input") or _int(hw / "power1_average")
210
+ cap = _int(hw / "power1_cap")
211
+ g.power = round(power / 1e6, 1) if power is not None else None
212
+ g.power_limit = round(cap / 1e6, 1) if cap else None
213
+ pwm, pwm_max = _int(hw / "pwm1"), _int(hw / "pwm1_max")
214
+ g.fan = round(100 * pwm / pwm_max) if pwm is not None and pwm_max else None
215
+ clock = _int(hw / "freq1_input")
216
+ g.clock = clock // 1_000_000 if clock is not None and _read(hw / "freq1_label") == "sclk" else None
217
+ out.append(g)
218
+ return out
219
+
220
+
221
+ def _kib(v: str | None) -> int:
222
+ """Size in KiB. No unit means bytes."""
223
+ if not v:
224
+ return 0
225
+ num, _, unit = v.partition(" ")
226
+ try:
227
+ n = int(num)
228
+ except ValueError:
229
+ return 0
230
+ return {"": n // 1024, "KiB": n, "MiB": n * 1024, "GiB": n * 1024 * 1024}.get(unit.strip(), 0)
231
+
232
+
233
+ def _fdinfo_kib(proc: Path) -> int:
234
+ try:
235
+ fds = os.listdir(proc / "fd")
236
+ except OSError:
237
+ return 0
238
+ seen: set[tuple[str | None, str | None]] = set()
239
+ total = 0
240
+ for fd in fds:
241
+ try:
242
+ if not os.readlink(proc / "fd" / fd).startswith("/dev/dri/"):
243
+ continue
244
+ except OSError:
245
+ continue
246
+ info = {}
247
+ for line in (_read(proc / "fdinfo" / fd) or "").splitlines():
248
+ k, _, v = line.partition(":")
249
+ info[k.strip()] = v.strip()
250
+ if info.get("drm-driver") != "amdgpu":
251
+ continue
252
+ client = (info.get("drm-pdev"), info.get("drm-client-id"))
253
+ if client in seen:
254
+ continue
255
+ seen.add(client)
256
+ total += _kib(info.get("drm-resident-vram") or info.get("drm-memory-vram"))
257
+ return total
258
+
259
+
260
+ def per_process_linux(pids=None, proc_root: str = "/proc", sys_root: str = "/sys") -> dict[int, int]:
261
+ if pids is None:
262
+ try:
263
+ pids = [int(p) for p in os.listdir(proc_root) if p.isdigit()]
264
+ except OSError:
265
+ return {}
266
+ gpu_ids = [gid for _, gid, _, _ in devices(sys_root) if gid is not None]
267
+ kfd = Path(sys_root, KFD, "proc")
268
+ used = {}
269
+ for pid in pids:
270
+ kib = _fdinfo_kib(Path(proc_root, str(pid)))
271
+ kfd_kib = sum(_int(kfd / str(pid) / f"vram_{gid}") or 0 for gid in gpu_ids) // 1024
272
+ mib = max(kib, kfd_kib) // 1024
273
+ if mib:
274
+ used[pid] = mib
275
+ return used
@@ -454,7 +454,7 @@ def cmd_status(a) -> int:
454
454
 
455
455
  for g in s["gpus"]:
456
456
  mem = f"{g['mem_used_mb'] / 1024:.1f}/{g['mem_total_mb'] / 1024:.1f} GB" if g["mem_total_mb"] else ""
457
- name = trunc((g["name"] or "").replace("NVIDIA ", "").replace("GeForce ", ""), 16)
457
+ name = trunc((g["name"] or "").replace("NVIDIA ", "").replace("GeForce ", "").replace("AMD ", ""), 16)
458
458
  label = f"GPU {g['index']} {name:<16} {mem:<13}" + ("(shared) " if g["shared"] else " ")
459
459
  if not g["jobs"]:
460
460
  print(f"{label}idle")
@@ -854,7 +854,7 @@ def cmd_init(a) -> int:
854
854
  for g in detected:
855
855
  print(f" GPU {g.index}: {g.name}, {g.mem_total / 1024:.1f} GB ({g.mem_used / 1024:.1f} GB in use)")
856
856
  else:
857
- print(" no NVIDIA GPUs found -> CPU-only mode (only --cpu/--exclusive jobs)")
857
+ print(" no NVIDIA or AMD GPUs found -> CPU-only mode (only --cpu/--exclusive jobs)")
858
858
  f = paths.config_file()
859
859
  if f.exists() and not a.force:
860
860
  print(f"config: keeping existing {f}")
@@ -893,18 +893,18 @@ def cmd_doctor(a) -> int:
893
893
  print(f"[{tag}] {label}{(': ' + detail) if detail else ''}")
894
894
 
895
895
  check(True, "gpushift", f"{__version__}, python {sys.version.split()[0]} at {sys.executable}")
896
- smi = gpus.nvidia_smi_path()
896
+ found = []
897
897
  try:
898
898
  found = gpus.query()
899
899
  check(
900
900
  True if found else None,
901
901
  "GPUs",
902
- ", ".join(f"{g.index}:{g.name}" for g in found) or "none found (CPU-only mode)",
902
+ ", ".join(f"{g.index}:{g.name} ({g.vendor})" for g in found) or "none found (CPU-only mode)",
903
903
  )
904
904
  except gpus.GPUQueryError as e:
905
905
  check(False, "GPUs", str(e))
906
- if not smi and not os.environ.get("GPUSHIFT_FAKE_GPUS"):
907
- check(None, "nvidia-smi", "not found; install the NVIDIA driver to use GPUs")
906
+ if not found and not os.environ.get("GPUSHIFT_FAKE_GPUS"):
907
+ check(None, "GPU driver", "no NVIDIA or AMD GPU found; install the GPU driver to use GPUs")
908
908
  f = paths.config_file()
909
909
  try:
910
910
  cfg = config.load()
@@ -14,7 +14,7 @@ import sys
14
14
  import time
15
15
  from pathlib import Path
16
16
 
17
- from . import _proc, config, control, cpustat, db, gpumem, gpus, notify, paths, scheduler
17
+ from . import _proc, config, control, cpustat, db, gpus, notify, paths, scheduler
18
18
 
19
19
  log = logging.getLogger("gpushift.daemon")
20
20
 
@@ -173,8 +173,8 @@ class Daemon:
173
173
  db.set_kv(self.con, "gpu_state_at", now)
174
174
  except gpus.GPUQueryError as e:
175
175
  log.warning("%s", e)
176
- self.procs = gpumem.per_process()
177
176
  self.read_job_processes()
177
+ self.procs = gpus.per_process(set().union(*self.job_pids.values()))
178
178
  self.measure_jobs()
179
179
  self.poll_cpu()
180
180
 
@@ -0,0 +1,113 @@
1
+ """GPUs from NVIDIA (nvidia.py) or AMD (amd.py). With nvidia-smi present, only
2
+ NVIDIA GPUs are used.
3
+
4
+ ``GPUSHIFT_FAKE_GPUS`` (comma-separated memory sizes in MiB, e.g. ``8192,6144``;
5
+ empty or ``0`` for none) replaces detection; ``GPUSHIFT_FAKE_GPU_VENDOR`` sets
6
+ their vendor. ``GPUSHIFT_FAKE_GPU_PROCS=<file.json>`` ({"pid": MiB, ...})
7
+ replaces per-process memory. Tests and CI use them.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ from dataclasses import asdict, dataclass
15
+
16
+
17
+ @dataclass
18
+ class GPU:
19
+ index: int
20
+ name: str
21
+ mem_total: int # MiB
22
+ mem_used: int # MiB
23
+ util: int | None = None # % of time the GPU was busy
24
+ temp: int | None = None # degrees C
25
+ power: float | None = None # W drawn
26
+ power_limit: float | None = None # W
27
+ fan: int | None = None # %
28
+ clock: int | None = None # SM clock, MHz
29
+ vendor: str = "nvidia" # nvidia | amd
30
+
31
+ @property
32
+ def free_perc(self) -> float:
33
+ if not self.mem_total:
34
+ return 0.0
35
+ return 100.0 * (self.mem_total - self.mem_used) / self.mem_total
36
+
37
+ def to_dict(self) -> dict:
38
+ return asdict(self)
39
+
40
+
41
+ class GPUQueryError(RuntimeError):
42
+ pass
43
+
44
+
45
+ def backend(vendor: str):
46
+ from . import amd, nvidia
47
+
48
+ return amd if vendor == "amd" else nvidia
49
+
50
+
51
+ def _fake() -> list[GPU] | None:
52
+ fake = os.environ.get("GPUSHIFT_FAKE_GPUS")
53
+ if fake is None:
54
+ return None
55
+ fake = fake.strip()
56
+ if fake in ("", "0"):
57
+ return []
58
+ vendor = os.environ.get("GPUSHIFT_FAKE_GPU_VENDOR", "nvidia")
59
+ return [GPU(i, f"Fake GPU {i}", int(m), 0, vendor=vendor) for i, m in enumerate(fake.split(","))]
60
+
61
+
62
+ def query() -> list[GPU]:
63
+ """All GPUs, ``[]`` if there is no GPU driver.
64
+
65
+ Raises GPUQueryError if nvidia-smi exists but fails."""
66
+ fake = _fake()
67
+ if fake is not None:
68
+ return fake
69
+ from . import amd, nvidia
70
+
71
+ return nvidia.query() if nvidia.available() else amd.query()
72
+
73
+
74
+ def vendor() -> str:
75
+ """Whose GPUs query() returns: nvidia or amd."""
76
+ if os.environ.get("GPUSHIFT_FAKE_GPUS") is not None:
77
+ return os.environ.get("GPUSHIFT_FAKE_GPU_VENDOR", "nvidia")
78
+ from . import amd, nvidia
79
+
80
+ return "amd" if not nvidia.available() and amd.available() else "nvidia"
81
+
82
+
83
+ def detect() -> list[GPU]:
84
+ """Like query(), but returns [] instead of raising."""
85
+ try:
86
+ return query()
87
+ except GPUQueryError:
88
+ return []
89
+
90
+
91
+ def per_process(pids=None) -> dict[int, int] | None:
92
+ """pid -> MiB of GPU memory. None if unknown."""
93
+ fake = os.environ.get("GPUSHIFT_FAKE_GPU_PROCS")
94
+ if fake is not None:
95
+ try:
96
+ with open(fake, encoding="utf-8") as f:
97
+ return {int(k): int(v) for k, v in json.load(f).items()}
98
+ except (OSError, ValueError):
99
+ return {}
100
+ try:
101
+ if os.name == "nt": # nvidia-smi can't report per-process memory under WDDM
102
+ from . import windows
103
+
104
+ return windows.process_memory()
105
+ from . import amd, nvidia
106
+
107
+ return nvidia.per_process() if nvidia.available() else amd.per_process(pids)
108
+ except Exception:
109
+ return None
110
+
111
+
112
+ def visible_env(env: dict[str, str], gpus: list[int], vendor: str) -> None:
113
+ backend(vendor).visible_env(env, gpus)
@@ -133,6 +133,9 @@ def strip_prefixes(t: list[str]) -> tuple[list[str], dict[str, str]]:
133
133
  return t, env
134
134
 
135
135
 
136
+ VISIBLE_VARS = ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES")
137
+
138
+
136
139
  def classify(seg: str, env_vars: set[str]) -> Verdict:
137
140
  t, env = strip_prefixes(tokens(seg))
138
141
  if not t:
@@ -144,7 +147,7 @@ def classify(seg: str, env_vars: set[str]) -> Verdict:
144
147
  return Verdict(False)
145
148
  if any(a in QUICK_FLAGS for a in args):
146
149
  return Verdict(False)
147
- cvd = "CUDA_VISIBLE_DEVICES" in env or "CUDA_VISIBLE_DEVICES" in env_vars
150
+ cvd = next((v for v in VISIBLE_VARS if v in env or v in env_vars), None)
148
151
 
149
152
  def multi() -> str:
150
153
  joined = " ".join(args)
@@ -182,14 +185,14 @@ def classify(seg: str, env_vars: set[str]) -> Verdict:
182
185
  if TRAIN_NAME.search(mod.split(".")[-1]):
183
186
  return Verdict(True, f"`python -m {mod}` looks like a training run", seg, "one")
184
187
  if cvd:
185
- return Verdict(True, "it sets CUDA_VISIBLE_DEVICES and runs Python", seg, "one")
188
+ return Verdict(True, f"it sets {cvd} and runs Python", seg, "one")
186
189
  return Verdict(False)
187
190
  script = basename(args[i])
188
191
  stem = re.sub(r"\.py$", "", script)
189
192
  if script.endswith(".py") and TRAIN_NAME.search(stem):
190
193
  return Verdict(True, f"`{script}` looks like a training script", seg, "one")
191
194
  if cvd:
192
- return Verdict(True, "it sets CUDA_VISIBLE_DEVICES and runs Python", seg, "one")
195
+ return Verdict(True, f"it sets {cvd} and runs Python", seg, "one")
193
196
  return Verdict(False)
194
197
 
195
198