π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): detect autocast across device types (#5454)
NiteeshGowda72d72465b05ad3
diff --git a/changelog.d/5454.fixed.md b/changelog.d/5454.fixed.mdnew file mode 100644index 000000000..cf1b90dd2--- /dev/null+++ b/changelog.d/5454.fixed.md@@ -0,0 +1,6 @@+`kornia.core.utils.is_autocast_enabled` now reports CPU, CUDA, MPS and XPU autocast on every supported torch version. It+used to miss MPS autocast on torch 2.5.1 and XPU autocast on every version, so on torch 2.5.1 inside+`torch.autocast("mps", dtype=torch.float16)` augmentations such as `RandomGaussianBlur` returned float16 for a float32+input; they now return the input dtype, as they already did on torch 2.14. `LightGlue` now checks autocast for the+device type of its descriptors, so running it on CPU inside an MPS autocast region no longer raises a dtype-mismatch+`RuntimeError` on torch 2.14.diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex 5b149a793..7ffe01278 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -26,7 +26,6 @@ import torchimport torch.nn.functional as Ffrom torch.linalg import inv_ex-from kornia.core._compat import torch_version_gefrom kornia.core._small_linalg import (_adjugate_2x2,_adjugate_3x3,@@ -427,20 +426,17 @@ def is_autocast_enabled(both: bool = True) -> bool:"""Check if torch autocast is enabled.Args:- both: if True will consider autocast region for both types of devices+ both: if True, consider the autocast regions of the CPU, CUDA, MPS and XPU device types.Returns:- Return a Bool,- will always return False for a torch without support, otherwise will be: if both is True- `torch.is_autocast_enabled() or torch.is_autocast_enabled('cpu')`. If both is False will return just- `torch.is_autocast_enabled()`.+ If ``both`` is True, whether autocast is enabled for any of the CPU, CUDA, MPS or XPU device types, on every+ supported torch version. If ``both`` is False, ``torch.is_autocast_enabled()`` without a device type, whose+ device type depends on the torch version: it never reports CPU autocast, and on torch 2.5.1 it does not+ report MPS autocast either."""- # Since kornia requires torch>=2.5.1, autocast is always availableif both:- if torch_version_ge(2, 4):- return torch.is_autocast_enabled() or torch.is_autocast_enabled("cpu")- return torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled()+ return any(torch.is_autocast_enabled(device_type) for device_type in ("cpu", "cuda", "mps", "xpu"))return torch.is_autocast_enabled()diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex e8793eada..11960ef3e 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -762,7 +762,8 @@ class LightGlue(nn.Module):KORNIA_CHECK(desc0.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")KORNIA_CHECK(desc1.shape[-1] == self.conf.input_dim, "Descriptor dimension does not match input dim in config")- if torch.is_autocast_enabled():+ device_type = desc0.device.type+ if device_type != "cpu" and torch.is_autocast_enabled(device_type):desc0 = desc0.half()desc1 = desc1.half()diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex e276e6423..8b45251bc 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -28,6 +28,7 @@ from kornia.core.utils import (_torch_linalg_svdvals,_torch_solve_cast,_torch_svd_cast,+ is_autocast_enabled,is_exporting,is_mps_tensor_safe,register_module_state,@@ -469,3 +470,38 @@ class TestInverseWithMask:A = torch.ones(10, 3, 3, device=device, dtype=dtype)_X, mask = safe_inverse_with_mask(A)assert torch.equal(mask, torch.zeros_like(mask))+++def test_is_autocast_enabled_cpu():+ assert not is_autocast_enabled()++ with torch.autocast("cpu", dtype=torch.bfloat16):+ assert torch.is_autocast_enabled("cpu")+ assert is_autocast_enabled()++ assert not is_autocast_enabled()+++def test_is_autocast_enabled_mps():+ if not torch.backends.mps.is_available():+ pytest.skip("MPS is not available")++ assert not is_autocast_enabled()++ with torch.autocast("mps", dtype=torch.float16):+ assert torch.is_autocast_enabled("mps")+ assert is_autocast_enabled()++ assert not is_autocast_enabled()+++def test_is_autocast_enabled_xpu():+ # XPU autocast can be entered without an XPU device, and ``torch.is_autocast_enabled()`` without a device type+ # never reports it, so this case pins the per-device-type query on every CI leg (#5198).+ assert not is_autocast_enabled()++ with torch.autocast("xpu", dtype=torch.bfloat16):+ assert torch.is_autocast_enabled("xpu")+ assert is_autocast_enabled()++ assert not is_autocast_enabled()diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.pyindex 38d4fcfff..da5d713b0 100644--- a/tests/feature/test_lightglue.py+++ b/tests/feature/test_lightglue.py@@ -465,3 +465,23 @@ class TestLightGlue(BaseTester):with torch.no_grad():out = lg(data)assert "matches0" in out++[email protected](not torch.backends.mps.is_available(), reason="MPS is not available")+ ("model_device", "autocast_device", "autocast_dtype"),+ [("cpu", "mps", torch.float16), ("mps", "cpu", torch.bfloat16)],+ # Ids must not start with "mps": conftest skips every "[mps" node whose name mentions autocast.+ ids=["model_cpu-autocast_mps", "model_mps-autocast_cpu"],+)+def test_autocast_of_another_device_type_leaves_descriptors_alone(model_device, autocast_device, autocast_dtype):+ """An autocast region of another device type must not cast the descriptors to half (#5198).++ The no-argument ``torch.is_autocast_enabled()`` reports MPS autocast on torch 2.14, so the half cast hit CPU+ descriptors and the CPU float32 projection raised a dtype mismatch.+ """+ lg = _make_lightglue(model_device, torch.float32)+ data = _make_data(model_device, torch.float32)+ with torch.no_grad(), torch.autocast(autocast_device, dtype=autocast_dtype):+ out = lg(data)+ assert out["log_assignment"].dtype == torch.float32