Skip to content

Commit 6884cc2

Browse files
committed
Record device after successful switch
1 parent 3b3cea4 commit 6884cc2

2 files changed

Lines changed: 30 additions & 7 deletions

File tree

python/cudf_polars/cudf_polars/callback.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -235,15 +235,14 @@ def set_device(device: int | None) -> Generator[int, None, None]:
235235
f"A previous query used device-{SEEN_DEVICE}, "
236236
f"the current query is using device-{to_use}."
237237
)
238+
if to_use != current:
239+
gpu.setDevice(to_use)
238240
SEEN_DEVICE = to_use
239-
if to_use != current:
240-
gpu.setDevice(to_use)
241-
try:
242-
yield to_use
243-
finally:
244-
gpu.setDevice(current)
245-
else:
241+
try:
246242
yield to_use
243+
finally:
244+
if to_use != current:
245+
gpu.setDevice(current)
247246

248247

249248
@overload

python/cudf_polars/tests/test_config.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,30 @@ def test_invalid_device_raises(device, monkeypatch):
8989
q.collect(engine=pl.GPUEngine(device=device))
9090

9191

92+
def test_failed_device_switch_does_not_set_seen_device(monkeypatch):
93+
monkeypatch.setattr(cudf_polars.callback, "SEEN_DEVICE", None)
94+
monkeypatch.setattr(gpu, "getDevice", lambda: 0)
95+
96+
def fail_for_invalid_device(device):
97+
if device == -1:
98+
raise RuntimeError("invalid device")
99+
100+
monkeypatch.setattr(gpu, "setDevice", fail_for_invalid_device)
101+
102+
with (
103+
pytest.raises(RuntimeError, match="invalid device"),
104+
cudf_polars.callback.set_device(-1),
105+
):
106+
pass
107+
108+
assert cudf_polars.callback.SEEN_DEVICE is None
109+
110+
with cudf_polars.callback.set_device(0):
111+
pass
112+
113+
assert cudf_polars.callback.SEEN_DEVICE == 0
114+
115+
92116
def test_multiple_devices_in_same_process_raise(monkeypatch):
93117
# A device we haven't already seen
94118
monkeypatch.setattr(cudf_polars.callback, "SEEN_DEVICE", 4)

0 commit comments

Comments
 (0)