Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: restore the exact default-device state after set_default_device (#5927)

Dmytro Mishkin7958ba67c936
diff --git a/testing/default_device.py b/testing/default_device.py
new file mode 100644
index 000000000..d2e6b8b8a
--- /dev/null
+++ b/testing/default_device.py
@@ -0,0 +1,64 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import torch
+from torch.overrides import _get_current_function_mode_stack
+from torch.utils._device import DeviceContext
+
+_MISSING = object()
+
+
+@contextmanager
+def default_device(device: str | torch.device) -> Iterator[None]:
+ """Run a block under ``torch.set_default_device(device)`` and restore the exact prior state afterwards.
+
+ ``torch.set_default_device`` pushes a ``DeviceContext`` torch-function mode that nothing pops. The obvious
+ restore, ``torch.set_default_device(torch.get_default_device())``, puts one ``DeviceContext(cpu)`` in place of
+ none when no default was set, and it stays on for the rest of the pytest process (#5508, #5916).
+ ``torch.set_default_device(None)`` pops it, but on torch 2.5 to 2.9 it also stores ``None`` where
+ ``torch.get_default_device()`` expects a context, so every later call raises ``AttributeError``. This manager
+ pops the context it pushed, then puts the thread-local back to what it held before: no attribute at all,
+ ``None``, or a context for the same device.
+
+ It refuses to run inside ``with torch.device(...)`` (``RuntimeError``, state untouched): on torch 2.9.1 or older
+ ``DeviceContext.__exit__`` asserts on the mode it finds on top of the stack, which corrupts the state. torch 2.14
+ handles that nesting, but the helper rejects it on every version so a test cannot pass on one and break on another.
+ """
+ device = torch.device(device) # validate first: torch pops the prior context before it checks the new device
+ store = torch._GLOBAL_DEVICE_CONTEXT
+ prior = getattr(store, "device_context", _MISSING)
+ foreign = [
+ mode for mode in _get_current_function_mode_stack() if isinstance(mode, DeviceContext) and mode is not prior
+ ]
+ if foreign:
+ raise RuntimeError("default_device cannot be used inside `with torch.device(...)`")
+ prior_device = None if prior is _MISSING or prior is None else prior.device
+ torch.set_default_device(device)
+ try:
+ yield
+ finally:
+ torch.set_default_device(None) # pops the context pushed above, leaves ``None`` behind
+ if prior_device is not None:
+ # The first call popped ``prior``; push a fresh context for its device.
+ torch.set_default_device(prior_device)
+ elif prior is _MISSING:
+ del store.device_context
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 870b42065..9d3bee324 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -39,6 +39,7 @@ from testing.base import (
supports_replicate_padding,
supports_topk,
)
+from testing.default_device import default_device
def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:
@@ -100,18 +101,9 @@ class TestScaleSpaceDetector(BaseTester):
# SIFTFeatureScaleSpace explicitly moves to CPU unless its device argument is given.
constructor_kwargs = {"device": "meta"} if constructor is kornia.feature.SIFTFeatureScaleSpace else {}
- original = torch.get_default_device()
- try:
- with NoDoubleOffCPU():
- if use_set_default_device:
- torch.set_default_device("meta")
- module = constructor(**constructor_kwargs)
- else:
- with torch.device("meta"):
- module = constructor(**constructor_kwargs)
- finally:
- if use_set_default_device:
- torch.set_default_device(original)
+ # ``default_device`` leaves neither a DeviceContext mode nor a broken ``get_default_device`` behind (#5916).
+ with default_device("meta") if use_set_default_device else torch.device("meta"), NoDoubleOffCPU():
+ module = constructor(**constructor_kwargs)
pyramids = [child for child in module.modules() if isinstance(child, ScalePyramid)]
assert len(pyramids) == 1
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 1f07344ef..32892d233 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -39,6 +39,7 @@ from kornia.geometry.ransac import _normalize_correspondences
from testing.base import BaseTester, dynamo_is_available
from testing.casts import dict_to
+from testing.default_device import default_device
from testing.geometry.create import create_dominant_plane_scene
# RANSAC's batched minimal solvers take the Metal shader compiler down on the paravirtualized GPU
@@ -2410,14 +2411,8 @@ class TestRANSACCompiled(BaseTester):
monkeypatch.setattr(_ransac_program, "load_program", load)
points = torch.rand(8, 2)
- original = torch.get_default_device()
- try:
- torch.set_default_device("meta")
+ with default_device("meta"):
RANSAC("homography", compile=True, seed=0)(points, points)
- finally:
- # With no override, ``original`` reads ``cpu``, and ``set_default_device("cpu")`` would leave a
- # DeviceContext mode on for the rest of the session instead of clearing the override (#5508).
- torch.set_default_device(None if original.type == "cpu" else original)
assert captured[0][0][-1] == "meta"
assert all(control.device.type == "cpu" for control in captured[0][1][2:])
diff --git a/tests/test_default_device.py b/tests/test_default_device.py
new file mode 100644
index 000000000..787c740bc
--- /dev/null
+++ b/tests/test_default_device.py
@@ -0,0 +1,114 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+
+from __future__ import annotations
+
+import pytest
+import torch
+from torch.overrides import _get_current_function_mode_stack
+from torch.utils._device import DeviceContext
+
+from testing.default_device import default_device
+
+
+def _device_contexts():
+ return [mode for mode in _get_current_function_mode_stack() if isinstance(mode, DeviceContext)]
+
+
+def clean_device_state():
+ """Run a test from a pristine default-device state (no attribute on the thread-local) and put it back."""
+ store = torch._GLOBAL_DEVICE_CONTEXT
+ had_attribute = hasattr(store, "device_context")
+ saved = getattr(store, "device_context", None)
+ saved_device = None if saved is None else saved.device
+ torch.set_default_device(None)
+ if hasattr(store, "device_context"):
+ del store.device_context
+ try:
+ yield
+ finally:
+ torch.set_default_device(None)
+ if saved_device is not None:
+ torch.set_default_device(saved_device)
+ elif not had_attribute and hasattr(store, "device_context"):
+ del store.device_context # originally absent; an originally-``None`` attribute stays ``None``
+
+
+class TestDefaultDevice:
+ def test_default_is_applied_inside_and_state_is_restored(self, clean_device_state):
+ stack_before = list(_get_current_function_mode_stack())
+ with default_device("meta"):
+ assert torch.get_default_device().type == "meta"
+ assert torch.empty(1).device.type == "meta"
+ assert len(_device_contexts()) == 1
+ assert list(_get_current_function_mode_stack()) == stack_before
+ assert not _device_contexts()
+ assert torch.get_default_device() == torch.device("cpu")
+ assert torch.empty(1).device.type == "cpu"
+ # Exact pre-block state: no thread-local attribute (a ``None`` there breaks get_default_device on torch <= 2.9).
+ assert not hasattr(torch._GLOBAL_DEVICE_CONTEXT, "device_context")
+
+ def test_restores_after_an_exception(self, clean_device_state):
+ with pytest.raises(RuntimeError, match="boom"), default_device("meta"):
+ raise RuntimeError("boom")
+ assert not _device_contexts()
+ assert torch.get_default_device() == torch.device("cpu")
+
+ def test_previously_set_default_survives(self, clean_device_state):
+ torch.set_default_device("meta")
+ try:
+ with default_device("cpu"):
+ assert torch.get_default_device().type == "cpu"
+ assert torch.get_default_device().type == "meta"
+ assert len(_device_contexts()) == 1
+ assert torch.empty(1).device.type == "meta"
+ finally:
+ torch.set_default_device(None)
+ assert not _device_contexts()
+
+ def test_nested(self, clean_device_state):
+ with default_device("meta"):
+ with default_device("cpu"):
+ assert torch.get_default_device().type == "cpu"
+ assert torch.get_default_device().type == "meta"
+ assert len(_device_contexts()) == 1
+ assert not _device_contexts()
+ assert torch.get_default_device() == torch.device("cpu")
+
+ def test_invalid_device_with_a_prior_default_leaves_state_intact(self, clean_device_state):
+ torch.set_default_device("meta")
+ try:
+ with pytest.raises((RuntimeError, ValueError)), default_device("not-a-device"):
+ pass # pragma: no cover
+ assert torch.get_default_device().type == "meta"
+ assert len(_device_contexts()) == 1
+ assert torch.empty(1).device.type == "meta"
+ finally:
+ torch.set_default_device(None)
+ assert not _device_contexts()
+
+ def test_refuses_to_nest_inside_torch_device(self, clean_device_state):
+ with torch.device("cpu"):
+ outer = list(_get_current_function_mode_stack())
+ with pytest.raises(RuntimeError, match="cannot be used inside"), default_device("meta"):
+ pass # pragma: no cover
+ assert list(_get_current_function_mode_stack()) == outer
+ assert not _device_contexts()
+ assert not hasattr(torch._GLOBAL_DEVICE_CONTEXT, "device_context")