Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(utils): make the deprecation shims drop-in replacements for the 0.8.2 functions (#5912)

Dmytro Mishkinb19ebcacd02c
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index e21d01ba2..bf69ab696 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -179,7 +179,7 @@ jobs:
pytorch-version: '["2.14.0"]'
pytorch-dtype: float32
optimizer: inductor
- pytest-extra: 'tests/augmentation tests/enhance tests/feature tests/filters tests/color tests/geometry tests/losses tests/morphology tests/models -k "dynamo or compile"'
+ pytest-extra: 'tests/augmentation tests/enhance tests/feature tests/filters tests/color tests/geometry tests/losses tests/morphology tests/models tests/core tests/utils -k "dynamo or compile"'
cache-path: weights/
cache-key: model-weights-${{ needs.pre-tests.outputs.hash }}
cache-restore-keys: |
diff --git a/changelog.d/+migration-011.breaking.md b/changelog.d/+migration-011.breaking.md
index 79fb52533..01f6f062e 100644
--- a/changelog.d/+migration-011.breaking.md
+++ b/changelog.d/+migration-011.breaking.md
@@ -5,7 +5,8 @@ to lazily transpile the library to TensorFlow, JAX or NumPy through the third-pa
integration unreliable across all three targets β€” a checkout-path crash in Ivy's module walker, a
torch/triton segfault when `transformers` is also installed, an undocumented `flax` requirement for
JAX, and a `jaxlib`/`numpy` API-compatibility break β€” against Ivy's latest release (1.0.0.5, June
-2025), with the upstream project showing little ongoing maintenance. Reaching for any of the three
-functions, at the top level or under `kornia.transpiler`, now raises an `AttributeError` that says
-what was removed and links the page below, rather than a bare "has no attribute". See
-`get-started/multi-framework-support` for what was tested and why. (#4196)
+2025), with the upstream project showing little ongoing maintenance. The three names still
+import, at the top level and from `kornia.transpiler`, so `from kornia import to_jax` and
+`hasattr(kornia, "to_jax")` keep working; calling any of them raises a `RuntimeError` that says
+what was removed and links the page below. See `get-started/multi-framework-support` for what
+was tested and why. (#4196)
diff --git a/changelog.d/5912.fixed.md b/changelog.d/5912.fixed.md
new file mode 100644
index 000000000..cc388356a
--- /dev/null
+++ b/changelog.d/5912.fixed.md
@@ -0,0 +1,13 @@
+The deprecated `kornia.utils` names and the deprecated top-level aliases such as `kornia.create_meshgrid` work as the
+0.8.2 functions did again. `kornia.utils.<name>` resolves after a plain `import kornia`, where it raised
+`AttributeError` unless `kornia.utils` had been imported first, and the 0.8.2 path
+`kornia.utils.sample.get_sample_images` is back as a deprecated alias. Each shim takes the signature of the function it
+forwards to, so `inspect.signature` and `help()` show the real parameters. Code that calls a shim compiles with
+`torch.compile(fullgraph=True)` and scripts with `torch.jit.script` wherever the function it forwards to does: the
+deprecation warning is skipped while a graph is captured and inside TorchScript, and eager calls still warn.
+`kornia.losses.one_hot` scripts with `torch.jit.script`.
+`torch.load(..., map_location=kornia.utils.map_location_to_cpu)` warns at the line that called `torch.load`, so the
+default warning filters show it there once. `from kornia import to_jax`, and the same for `to_numpy`,
+`to_tensorflow` and `kornia.transpiler`, imports again, and calling the name raises the `RuntimeError` that explains
+the removal instead of a bare `ImportError`. The deprecation messages no longer say that the `kornia.utils` module has
+been removed.
diff --git a/docs/export_support/cases_misc.py b/docs/export_support/cases_misc.py
index 1512adef8..f72833737 100644
--- a/docs/export_support/cases_misc.py
+++ b/docs/export_support/cases_misc.py
@@ -1141,7 +1141,7 @@ add(
g,
None,
[],
- skip="deprecated alias of kornia.losses.one_hot (kornia.utils is a deprecation shim, not an attribute of kornia)",
+ skip="deprecated alias of kornia.losses.one_hot; measured as losses.one_hot",
)
add(
"utils.draw_line",
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 223e5a266..00b535f6f 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -19348,14 +19348,14 @@
},
{
"compile": "n/a",
- "compile_detail": "deprecated alias of kornia.losses.one_hot (kornia.utils is a deprecation shim, not an attribute of kornia)",
+ "compile_detail": "deprecated alias of kornia.losses.one_hot; measured as losses.one_hot",
"export": "n/a",
- "export_detail": "deprecated alias of kornia.losses.one_hot (kornia.utils is a deprecation shim, not an attribute of kornia)",
+ "export_detail": "deprecated alias of kornia.losses.one_hot; measured as losses.one_hot",
"graph_breaks": 0,
"name": "utils.one_hot",
"note": "",
"onnx": "n/a",
- "onnx_detail": "deprecated alias of kornia.losses.one_hot (kornia.utils is a deprecation shim, not an attribute of kornia)",
+ "onnx_detail": "deprecated alias of kornia.losses.one_hot; measured as losses.one_hot",
"operator": "one_hot",
"package": "kornia.utils",
"ref": "",
@@ -19500,11 +19500,11 @@
"where": ""
},
{
- "compile": "ok-breaks",
- "compile_detail": "2 graph breaks",
+ "compile": "ok",
+ "compile_detail": "",
"export": "ok",
"export_detail": "",
- "graph_breaks": 2,
+ "graph_breaks": 0,
"name": "utils.torch_meshgrid",
"note": "thin wrapper over torch.meshgrid (kornia.utils shim)",
"onnx": "ok",
diff --git a/docs/source/get-started/stability.rst b/docs/source/get-started/stability.rst
index f06f74efc..4d7aff955 100644
--- a/docs/source/get-started/stability.rst
+++ b/docs/source/get-started/stability.rst
@@ -63,11 +63,11 @@ The promises (stable core)
1. **Deprecation before removal.** A public symbol is never removed or given
an incompatible signature in a single step. It first spends at least one
- minor release wrapped in ``kornia.core._compat.deprecated``, which
+ minor release as a deprecated alias -- ``kornia.core._compat.deprecated``, or a shim
+ with the old signature where the old function scripted with TorchScript -- which
keeps the old call working while emitting a :class:`DeprecationWarning`
that names the replacement and the version that introduced the
- deprecation (this is the mechanism the 0.8.3 ``kornia.utils`` β†’
- ``kornia.image`` migration used).
+ deprecation.
2. **No silent semantic changes.** Changing a default that alters numerical
output (interpolation flags, ``align_corners``, padding modes, coordinate
conventions) counts as a breaking change and gets the same
diff --git a/kornia/__init__.py b/kornia/__init__.py
index c6031ec9d..39f8235ca 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -21,6 +21,7 @@ This package exposes core modules (filters, geometry, etc.) and provides
convenience imports at the top level.
"""
+from importlib import import_module as _import_module
from typing import Any
# NOTE: kornia filters and geometry must go first since are the core of the library
@@ -46,11 +47,11 @@ from . import (
tracking,
)
-# The Ivy-powered multi-framework entry points were removed, but the module stays bound so that
-# `kornia.transpiler` still resolves after a plain `import kornia` and explains the removal
-# instead of raising a bare AttributeError. See the `__getattr__` at the bottom of this file.
+# The Ivy-powered multi-framework entry points were removed. The module stays bound, and `to_jax`, `to_numpy` and
+# `to_tensorflow` stay bound here and in it as functions that raise an error explaining the removal, so that
+# `kornia.to_jax()` and `from kornia import to_jax` both lead to the explanation. See `kornia/transpiler/__init__.py`.
from . import transpiler
-from .transpiler import _REMOVED as _REMOVED_TRANSPILER_NAMES, _removed_message
+from .transpiler import _removed_entry_point
# NOTE: we are going to expose to top level very few things
from kornia.constants import pi
@@ -58,203 +59,43 @@ from kornia.constants import pi
# Deprecated top-level imports - use kornia.core.ops or kornia.core.utils instead
from kornia.core._compat import deprecated
-# Import the actual functions to wrap
-from kornia.core.ops import eye_like as _eye_like, vec_like as _vec_like
-from kornia.core.utils import (
- get_cuda_device_if_available as _get_cuda_device_if_available,
- get_cuda_or_mps_device_if_available as _get_cuda_or_mps_device_if_available,
- get_mps_device_if_available as _get_mps_device_if_available,
- is_autocast_enabled as _is_autocast_enabled,
- xla_is_available as _xla_is_available,
+# The aliases are defined in their own module, which keeps the names their annotations need off `kornia`.
+from ._deprecated_aliases import (
+ create_meshgrid,
+ create_meshgrid3d,
+ draw_convex_polygon,
+ draw_line,
+ draw_point2d,
+ draw_rectangle,
+ eye_like,
+ get_cuda_device_if_available,
+ get_cuda_or_mps_device_if_available,
+ get_mps_device_if_available,
+ image_to_string,
+ image_to_tensor,
+ is_autocast_enabled,
+ load_pointcloud_ply,
+ one_hot,
+ print_image,
+ save_pointcloud_ply,
+ tensor_to_image,
+ vec_like,
+ xla_is_available,
)
-from kornia.geometry import (
- create_meshgrid as _create_meshgrid,
- create_meshgrid3d as _create_meshgrid3d,
- load_pointcloud_ply as _load_pointcloud_ply,
- save_pointcloud_ply as _save_pointcloud_ply,
-)
-from kornia.image import (
- draw_convex_polygon as _draw_convex_polygon,
- draw_line as _draw_line,
- draw_point2d as _draw_point2d,
- draw_rectangle as _draw_rectangle,
- image_to_string as _image_to_string,
- image_to_tensor as _image_to_tensor,
- print_image as _print_image,
- tensor_to_image as _tensor_to_image,
-)
-from kornia.losses.one_hot import one_hot as _one_hot
-
-
-@deprecated(replace_with="kornia.core.ops.eye_like", version="0.8.3")
-def eye_like(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.ops.eye_like` instead."""
- return _eye_like(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.ops.vec_like", version="0.8.3")
-def vec_like(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.ops.vec_like` instead."""
- return _vec_like(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.utils.xla_is_available", version="0.8.3")
-def xla_is_available(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.utils.xla_is_available` instead."""
- return _xla_is_available(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.geometry.create_meshgrid", version="0.8.3")
-def create_meshgrid(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
- return _create_meshgrid(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.image.image_to_tensor", version="0.8.3")
-def image_to_tensor(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.image_to_tensor` instead."""
- return _image_to_tensor(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.image.tensor_to_image", version="0.8.3")
-def tensor_to_image(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.tensor_to_image` instead."""
- return _tensor_to_image(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.utils.get_cuda_device_if_available", version="0.8.3")
-def get_cuda_device_if_available(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""
- return _get_cuda_device_if_available(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.utils.get_mps_device_if_available", version="0.8.3")
-def get_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""
- return _get_mps_device_if_available(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.utils.get_cuda_or_mps_device_if_available", version="0.8.3")
-def get_cuda_or_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""
- return _get_cuda_or_mps_device_if_available(*args, **kwargs)
-
-
-@deprecated(replace_with="kornia.core.utils.is_autocast_enabled", version="0.8.3")
-def is_autocast_enabled(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""
- return _is_autocast_enabled(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.geometry.create_meshgrid3d",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.create_meshgrid3d`.",
-)
-def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead (previously `kornia.utils.create_meshgrid3d`)."""
- return _create_meshgrid3d(*args, **kwargs)
-
-@deprecated(
- replace_with="kornia.geometry.load_pointcloud_ply",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.load_pointcloud_ply`.",
-)
-def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead (previously `kornia.utils.load_pointcloud_ply`)."""
- return _load_pointcloud_ply(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.geometry.save_pointcloud_ply",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.save_pointcloud_ply`.",
-)
-def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead (previously `kornia.utils.save_pointcloud_ply`)."""
- return _save_pointcloud_ply(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.draw_line",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.draw_line`.",
-)
-def draw_line(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.draw_line` instead (previously `kornia.utils.draw_line`)."""
- return _draw_line(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.draw_rectangle",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.draw_rectangle`.",
-)
-def draw_rectangle(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.draw_rectangle` instead (previously `kornia.utils.draw_rectangle`)."""
- return _draw_rectangle(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.draw_point2d",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.draw_point2d`.",
-)
-def draw_point2d(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.draw_point2d` instead (previously `kornia.utils.draw_point2d`)."""
- return _draw_point2d(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.draw_convex_polygon",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.draw_convex_polygon`.",
-)
-def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.draw_convex_polygon` instead (previously `kornia.utils.draw_convex_polygon`)."""
- return _draw_convex_polygon(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.image_to_string",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.image_to_string`.",
-)
-def image_to_string(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.image_to_string` instead (previously `kornia.utils.image_to_string`)."""
- return _image_to_string(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.print_image",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.print_image`.",
-)
-def print_image(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.image.print_image` instead (previously `kornia.utils.print_image`)."""
- return _print_image(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.losses.one_hot",
- version="0.8.3",
- extra_reason=" Previously available as `kornia.utils.one_hot`.",
-)
-def one_hot(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.losses.one_hot` instead (previously `kornia.utils.one_hot`)."""
- return _one_hot(*args, **kwargs)
+to_jax = _removed_entry_point(__name__, "to_jax")
+to_numpy = _removed_entry_point(__name__, "to_numpy")
+to_tensorflow = _removed_entry_point(__name__, "to_tensorflow")
def __getattr__(name: str) -> Any:
- """Explain the removed multi-framework entry points instead of a bare AttributeError.
+ """Import the deprecated ``kornia.utils`` on first access.
- ``kornia.to_tensorflow()``, ``kornia.to_jax()`` and ``kornia.to_numpy()`` were the documented
- way to reach the Ivy transpiler, so that is where the removal has to be explained; the message
- under `kornia.transpiler` is only reached by code that imported the submodule directly.
+ ``import kornia`` does not import the deprecated ``kornia.utils``; ``kornia.utils.<name>``, the attribute style
+ kornia's 0.8.2 documentation used, still reaches its shims after ``import kornia`` alone.
"""
- if name in _REMOVED_TRANSPILER_NAMES:
- raise AttributeError(_removed_message(f"kornia.{name}"))
+ if name == "utils":
+ return _import_module("kornia.utils")
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/kornia/_deprecated_aliases.py b/kornia/_deprecated_aliases.py
new file mode 100644
index 000000000..14d09ab19
--- /dev/null
+++ b/kornia/_deprecated_aliases.py
@@ -0,0 +1,279 @@
+# 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.
+#
+
+
+"""Deprecated top-level aliases such as ``kornia.create_meshgrid``; ``kornia/__init__.py`` binds them.
+
+Each alias takes the signature of the function it forwards to and warns only outside TorchScript and outside
+``torch.compile``/``torch.export`` graph capture, so code written against 0.8.2 scripts and compiles wherever the
+function the alias forwards to does. They live in their own module so that the names their annotations need
+(``torch``, ``os``, ``typing``) do not become attributes of ``kornia``.
+"""
+
+import os
+from typing import Any, List, Optional, Union
+
+import torch
+
+from kornia.core._compat import _emit_deprecation_warning
+from kornia.core.ops import eye_like as _eye_like
+from kornia.core.ops import vec_like as _vec_like
+from kornia.core.utils import (
+ get_cuda_device_if_available as _get_cuda_device_if_available,
+)
+from kornia.core.utils import (
+ get_cuda_or_mps_device_if_available as _get_cuda_or_mps_device_if_available,
+)
+from kornia.core.utils import (
+ get_mps_device_if_available as _get_mps_device_if_available,
+)
+from kornia.core.utils import (
+ is_autocast_enabled as _is_autocast_enabled,
+)
+from kornia.core.utils import (
+ xla_is_available as _xla_is_available,
+)
+from kornia.geometry import (
+ create_meshgrid as _create_meshgrid,
+)
+from kornia.geometry import (
+ create_meshgrid3d as _create_meshgrid3d,
+)
+from kornia.geometry import (
+ load_pointcloud_ply as _load_pointcloud_ply,
+)
+from kornia.geometry import (
+ save_pointcloud_ply as _save_pointcloud_ply,
+)
+from kornia.image import (
+ draw_convex_polygon as _draw_convex_polygon,
+)
+from kornia.image import (
+ draw_line as _draw_line,
+)
+from kornia.image import (
+ draw_point2d as _draw_point2d,
+)
+from kornia.image import (
+ draw_rectangle as _draw_rectangle,
+)
+from kornia.image import (
+ image_to_string as _image_to_string,
+)
+from kornia.image import (
+ image_to_tensor as _image_to_tensor,
+)
+from kornia.image import (
+ print_image as _print_image,
+)
+from kornia.image import (
+ tensor_to_image as _tensor_to_image,
+)
+from kornia.losses.one_hot import one_hot as _one_hot
+
+__all__ = [
+ "create_meshgrid",
+ "create_meshgrid3d",
+ "draw_convex_polygon",
+ "draw_line",
+ "draw_point2d",
+ "draw_rectangle",
+ "eye_like",
+ "get_cuda_device_if_available",
+ "get_cuda_or_mps_device_if_available",
+ "get_mps_device_if_available",
+ "image_to_string",
+ "image_to_tensor",
+ "is_autocast_enabled",
+ "load_pointcloud_ply",
+ "one_hot",
+ "print_image",
+ "save_pointcloud_ply",
+ "tensor_to_image",
+ "vec_like",
+ "xla_is_available",
+]
+
+
+def _warn(name: str, replace_with: str, previously_in_utils: bool = False) -> None:
+ """Warn that ``kornia.<name>`` is deprecated in favor of ``replace_with``, at the line that used it."""
+ extra_reason = f" Previously available as `kornia.utils.{name}`." if previously_in_utils else None
+ _emit_deprecation_warning(name, replace_with, "0.8.3", extra_reason, stacklevel=4)
+
+
+def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
+ """Deprecated: Use `kornia.core.ops.eye_like` instead."""
+ if not torch.jit.is_scripting():
+ _warn("eye_like", "kornia.core.ops.eye_like")
+ return _eye_like(n, input, shared_memory)
+
+
+def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
+ """Deprecated: Use `kornia.core.ops.vec_like` instead."""
+ if not torch.jit.is_scripting():
+ _warn("vec_like", "kornia.core.ops.vec_like")
+ return _vec_like(n, tensor, shared_memory)
+
+
+def xla_is_available() -> bool:
+ """Deprecated: Use `kornia.core.utils.xla_is_available` instead."""
+ if not torch.jit.is_scripting():
+ _warn("xla_is_available", "kornia.core.utils.xla_is_available")
+ return _xla_is_available()
+
+
+def create_meshgrid(
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ align_corners: bool = True,
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
+ if not torch.jit.is_scripting():
+ _warn("create_meshgrid", "kornia.geometry.create_meshgrid")
+ return _create_meshgrid(height, width, normalized_coordinates, device, dtype, align_corners)
+
+
+def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
+ """Deprecated: Use `kornia.image.image_to_tensor` instead."""
+ if not torch.jit.is_scripting():
+ _warn("image_to_tensor", "kornia.image.image_to_tensor")
+ return _image_to_tensor(image, keepdim)
+
+
+def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
+ """Deprecated: Use `kornia.image.tensor_to_image` instead."""
+ if not torch.jit.is_scripting():
+ _warn("tensor_to_image", "kornia.image.tensor_to_image")
+ return _tensor_to_image(tensor, keepdim, force_contiguous)
+
+
+def get_cuda_device_if_available(index: int = 0) -> torch.device:
+ """Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""
+ if not torch.jit.is_scripting():
+ _warn("get_cuda_device_if_available", "kornia.core.utils.get_cuda_device_if_available")
+ return _get_cuda_device_if_available(index)
+
+
+def get_mps_device_if_available() -> torch.device:
+ """Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""
+ if not torch.jit.is_scripting():
+ _warn("get_mps_device_if_available", "kornia.core.utils.get_mps_device_if_available")
+ return _get_mps_device_if_available()
+
+
+def get_cuda_or_mps_device_if_available() -> torch.device:
+ """Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""
+ if not torch.jit.is_scripting():
+ _warn("get_cuda_or_mps_device_if_available", "kornia.core.utils.get_cuda_or_mps_device_if_available")
+ return _get_cuda_or_mps_device_if_available()
+
+
+def is_autocast_enabled(both: bool = True) -> bool:
+ """Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""
+ if not torch.jit.is_scripting():
+ _warn("is_autocast_enabled", "kornia.core.utils.is_autocast_enabled")
+ return _is_autocast_enabled(both)
+
+
+def create_meshgrid3d(
+ depth: int,
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.geometry.create_meshgrid3d` instead (previously `kornia.utils.create_meshgrid3d`)."""
+ if not torch.jit.is_scripting():
+ _warn("create_meshgrid3d", "kornia.geometry.create_meshgrid3d", previously_in_utils=True)
+ return _create_meshgrid3d(depth, height, width, normalized_coordinates, device, dtype)
+
+
+def load_pointcloud_ply(filename: str | os.PathLike[str], header_size: Optional[int] = None) -> torch.Tensor:
+ """Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead (previously `kornia.utils.load_pointcloud_ply`)."""
+ if not torch.jit.is_scripting():
+ _warn("load_pointcloud_ply", "kornia.geometry.load_pointcloud_ply", previously_in_utils=True)
+ return _load_pointcloud_ply(filename, header_size)
+
+
+def save_pointcloud_ply(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:
+ """Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead (previously `kornia.utils.save_pointcloud_ply`)."""
+ if not torch.jit.is_scripting():
+ _warn("save_pointcloud_ply", "kornia.geometry.save_pointcloud_ply", previously_in_utils=True)
+ return _save_pointcloud_ply(filename, pointcloud)
+
+
+def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
+ """Deprecated: Use `kornia.image.draw_line` instead (previously `kornia.utils.draw_line`)."""
+ if not torch.jit.is_scripting():
+ _warn("draw_line", "kornia.image.draw_line", previously_in_utils=True)
+ return _draw_line(image, p1, p2, color)
+
+
+def draw_rectangle(
+ image: torch.Tensor,
+ rectangle: torch.Tensor,
+ color: Optional[torch.Tensor] = None,
+ fill: Optional[bool] = None,
+ line_width: int = 1,
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.image.draw_rectangle` instead (previously `kornia.utils.draw_rectangle`)."""
+ if not torch.jit.is_scripting():
+ _warn("draw_rectangle", "kornia.image.draw_rectangle", previously_in_utils=True)
+ return _draw_rectangle(image, rectangle, color, fill, line_width)
+
+
+def draw_point2d(image: torch.Tensor, points: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
+ """Deprecated: Use `kornia.image.draw_point2d` instead (previously `kornia.utils.draw_point2d`)."""
+ if not torch.jit.is_scripting():
+ _warn("draw_point2d", "kornia.image.draw_point2d", previously_in_utils=True)
+ return _draw_point2d(image, points, color)
+
+
+def draw_convex_polygon(
+ images: torch.Tensor, polygons: Union[torch.Tensor, List[torch.Tensor]], colors: torch.Tensor
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.image.draw_convex_polygon` instead (previously `kornia.utils.draw_convex_polygon`)."""
+ if not torch.jit.is_scripting():
+ _warn("draw_convex_polygon", "kornia.image.draw_convex_polygon", previously_in_utils=True)
+ return _draw_convex_polygon(images, polygons, colors)
+
+
+def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
+ """Deprecated: Use `kornia.image.image_to_string` instead (previously `kornia.utils.image_to_string`)."""
+ if not torch.jit.is_scripting():
+ _warn("image_to_string", "kornia.image.image_to_string", previously_in_utils=True)
+ return _image_to_string(image, max_width)
+
+
+def print_image(image: Union[str, os.PathLike, torch.Tensor], max_width: int = 96) -> None:
+ """Deprecated: Use `kornia.image.print_image` instead (previously `kornia.utils.print_image`)."""
+ if not torch.jit.is_scripting():
+ _warn("print_image", "kornia.image.print_image", previously_in_utils=True)
+ return _print_image(image, max_width)
+
+
+def one_hot(
+ labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 0.0
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.losses.one_hot` instead (previously `kornia.utils.one_hot`)."""
+ if not torch.jit.is_scripting():
+ _warn("one_hot", "kornia.losses.one_hot", previously_in_utils=True)
+ return _one_hot(labels, num_classes, device, dtype, eps)
diff --git a/kornia/core/_compat.py b/kornia/core/_compat.py
index cf2e9582d..1047d2f4f 100644
--- a/kornia/core/_compat.py
+++ b/kornia/core/_compat.py
@@ -23,6 +23,8 @@ from typing import Any, Callable, Optional, Tuple, cast
import torch
+from kornia.core.utils import is_compiling
+
def torch_version() -> str:
"""Parse the PyTorch version string and remove build metadata.
@@ -129,12 +131,19 @@ def torch_version_ge(major: int, minor: int, patch: Optional[int] = None) -> boo
def _emit_deprecation_warning(
- name: str, replace_with: Optional[str], version: Optional[str], extra_reason: Optional[str]
+ name: str, replace_with: Optional[str], version: Optional[str], extra_reason: Optional[str], stacklevel: int = 3
) -> None:
"""Emit a deprecation warning with the given parameters.
``extra_reason`` is joined to the sentence with exactly one space, whatever whitespace it starts or ends with.
+ ``stacklevel`` counts from this function, so the default 3 names the line that called its caller.
+
+ Nothing is emitted while ``torch.compile`` or ``torch.export`` captures a graph: dynamo cannot trace
+ ``warnings.warn``, so warning there would break ``fullgraph=True`` for any code that calls a deprecated name.
+ Eager calls still warn on every call.
"""
+ if is_compiling():
+ return
beginning = f"Since kornia {version} the " if version is not None else ""
extra_reason = extra_reason.strip() if extra_reason else ""
extra = f" {extra_reason}" if extra_reason else ""
@@ -146,7 +155,7 @@ def _emit_deprecation_warning(
warnings.warn(
msg,
category=DeprecationWarning,
- stacklevel=3,
+ stacklevel=stacklevel,
)
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index 9d62109e5..3095943cd 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -60,7 +60,13 @@ def one_hot(
KORNIA_CHECK_IS_TENSOR(labels, "Input labels must be a torch.Tensor")
KORNIA_CHECK(labels.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {labels.dtype}")
KORNIA_CHECK(num_classes >= 1, f"The number of classes must be >= 1. Got: {num_classes}")
- KORNIA_CHECK(eps == 0 or dtype.is_floating_point, f"A non-zero eps needs a floating point dtype. Got: {dtype}")
+ if eps != 0:
+ # TorchScript represents a ``torch.dtype`` as an int, which has no ``is_floating_point``.
+ if torch.jit.is_scripting():
+ is_floating = torch.empty(0, dtype=dtype).is_floating_point()
+ else:
+ is_floating = dtype.is_floating_point
+ KORNIA_CHECK(is_floating, f"A non-zero eps needs a floating point dtype. Got: {dtype}")
# Use PyTorch's built-in one_hot function
one_hot_tensor = F.one_hot(labels, num_classes=num_classes)
@@ -70,7 +76,7 @@ def one_hot(
# Permute: move the last dimension (num_classes) to position 1
ndim = labels.ndim
permute_dims = [0] + [ndim] + list(range(1, ndim))
- one_hot_tensor = one_hot_tensor.permute(*permute_dims)
+ one_hot_tensor = one_hot_tensor.permute(permute_dims)
one_hot_tensor = one_hot_tensor.to(dtype=dtype, device=device)
if eps == 0:
diff --git a/kornia/transpiler/__init__.py b/kornia/transpiler/__init__.py
index 23e9b3947..ee785ccb8 100644
--- a/kornia/transpiler/__init__.py
+++ b/kornia/transpiler/__init__.py
@@ -20,11 +20,12 @@
Testing in September 2026 found the Ivy-powered transpiler these functions used unreliable
across all three target frameworks, so it was removed. See
``docs/source/get-started/multi-framework-support.rst`` for what was tested and why.
-"""
-from typing import Any
+The three names stay bound, here and at the top level, to functions that raise :class:`RuntimeError`
+explaining the removal when called, and stay out of ``__all__``.
+"""
-_REMOVED = ("to_jax", "to_numpy", "to_tensorflow")
+from typing import Any, Callable, List, NoReturn
_DOCS_URL = "https://kornia.readthedocs.io/en/latest/get-started/multi-framework-support.html"
@@ -42,7 +43,27 @@ def _removed_message(qualified_name: str) -> str:
)
-def __getattr__(name: str) -> Any:
- if name in _REMOVED:
- raise AttributeError(_removed_message(f"kornia.transpiler.{name}"))
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+def _removed_entry_point(module: str, name: str) -> Callable[..., NoReturn]:
+ """Return the stand-in bound as ``<module>.<name>``, which raises :class:`RuntimeError` explaining the removal.
+
+ The name has to stay bound: for ``from kornia import to_jax`` Python replaces the ``AttributeError`` of a missing
+ name with a bare ``ImportError``, which drops the explanation. Looking the name up therefore succeeds, and calling
+ it explains.
+ """
+ qualified_name = f"{module}.{name}"
+
+ def removed(*args: Any, **kwargs: Any) -> NoReturn:
+ raise RuntimeError(_removed_message(qualified_name))
+
+ removed.__name__ = removed.__qualname__ = name
+ removed.__module__ = module
+ removed.__doc__ = f"Removed: calling ``{qualified_name}()`` raises :class:`RuntimeError` explaining why."
+ return removed
+
+
+to_jax = _removed_entry_point(__name__, "to_jax")
+to_numpy = _removed_entry_point(__name__, "to_numpy")
+to_tensorflow = _removed_entry_point(__name__, "to_tensorflow")
+
+# The stand-ins above are not API.
+__all__: List[str] = []
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index b2d26d249..a2a4e77aa 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -15,16 +15,26 @@
# limitations under the License.
#
+
"""Utils submodule for Kornia.
This module has been deprecated. Functions have been moved to their respective modules.
Import from the new locations instead (e.g., `kornia.image.draw_line` instead of `kornia.utils.draw_line`).
+
+Each shim takes the signature of the function it forwards to (``torch_meshgrid`` and ``map_location_to_cpu`` keep their
+0.8.2 signatures) and warns only outside TorchScript and outside ``torch.compile``/``torch.export`` graph capture, so
+code written against 0.8.2 scripts and compiles wherever the function the shim forwards to does.
"""
-from __future__ import annotations
+import importlib
+import os
+import sys
+from types import FrameType
+from typing import Any, Dict, List, Optional, Tuple, Type, Union
-from typing import Any
+import torch
+# ``deprecated`` was importable from here in 0.8.2, so it stays bound.
from kornia.core._compat import _emit_deprecation_warning, deprecated
from kornia.core.ops import (
eye_like as _eye_like,
@@ -32,6 +42,10 @@ from kornia.core.ops import (
from kornia.core.ops import (
vec_like as _vec_like,
)
+from kornia.core.utils import T as _T
+from kornia.core.utils import (
+ batched_forward as _batched_forward,
+)
from kornia.core.utils import (
dataclass_to_dict as _dataclass_to_dict,
)
@@ -104,138 +118,136 @@ from kornia.image import (
from kornia.image import (
tensor_to_image as _tensor_to_image,
)
+from kornia.io.sample import _IMAGE_URLS
+from kornia.io.sample import get_sample_images as _get_sample_images
from kornia.losses.one_hot import one_hot as _one_hot
-# Re-export with deprecation warnings
-@deprecated(
- replace_with="kornia.geometry.create_meshgrid",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
-)
-def create_meshgrid(*args: Any, **kwargs: Any) -> Any:
- """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
- return _create_meshgrid(*args, **kwargs)
+def _warn(name: str, module: str) -> None:
+ """Warn that ``kornia.utils.<name>`` is deprecated in favor of ``<module>.<name>``, at the line that used it."""
+ _emit_deprecation_warning(
+ name,
+ f"{module}.{name}",
+ "0.8.3",
+ f" The `kornia.utils` module is deprecated. Import from `{module}` instead.",
+ stacklevel=4,
+ )
-@deprecated(
- replace_with="kornia.geometry.create_meshgrid3d",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
-)
-def create_meshgrid3d(*args: Any, **kwargs: Any) -> Any:
+# Re-export with deprecation warnings
+def create_meshgrid(
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ align_corners: bool = True,
+) -> torch.Tensor:
+ """Deprecated: Use `kornia.geometry.create_meshgrid` instead."""
+ if not torch.jit.is_scripting():
+ _warn("create_meshgrid", "kornia.geometry")
+ return _create_meshgrid(height, width, normalized_coordinates, device, dtype, align_corners)
+
+
+def create_meshgrid3d(
+ depth: int,
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
"""Deprecated: Use `kornia.geometry.create_meshgrid3d` instead."""
- return _create_meshgrid3d(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("create_meshgrid3d", "kornia.geometry")
+ return _create_meshgrid3d(depth, height, width, normalized_coordinates, device, dtype)
-@deprecated(
- replace_with="kornia.geometry.load_pointcloud_ply",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
-)
-def load_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+def load_pointcloud_ply(filename: str | os.PathLike[str], header_size: Optional[int] = None) -> torch.Tensor:
"""Deprecated: Use `kornia.geometry.load_pointcloud_ply` instead."""
- return _load_pointcloud_ply(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("load_pointcloud_ply", "kornia.geometry")
+ return _load_pointcloud_ply(filename, header_size)
-@deprecated(
- replace_with="kornia.geometry.save_pointcloud_ply",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.geometry` instead.",
-)
-def save_pointcloud_ply(*args: Any, **kwargs: Any) -> Any:
+def save_pointcloud_ply(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:
"""Deprecated: Use `kornia.geometry.save_pointcloud_ply` instead."""
- return _save_pointcloud_ply(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("save_pointcloud_ply", "kornia.geometry")
+ return _save_pointcloud_ply(filename, pointcloud)
-@deprecated(
- replace_with="kornia.image.draw_line",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def draw_line(*args: Any, **kwargs: Any) -> Any:
+def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
"""Deprecated: Use `kornia.image.draw_line` instead."""
- return _draw_line(*args, **kwargs)
-
-
-@deprecated(
- replace_with="kornia.image.draw_rectangle",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def draw_rectangle(*args: Any, **kwargs: Any) -> Any:
+ if not torch.jit.is_scripting():
+ _warn("draw_line", "kornia.image")
+ return _draw_line(image, p1, p2, color)
+
+
+def draw_rectangle(
+ image: torch.Tensor,
+ rectangle: torch.Tensor,
+ color: Optional[torch.Tensor] = None,
+ fill: Optional[bool] = None,
+ line_width: int = 1,
+) -> torch.Tensor:
"""Deprecated: Use `kornia.image.draw_rectangle` instead."""
- return _draw_rectangle(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("draw_rectangle", "kornia.image")
+ return _draw_rectangle(image, rectangle, color, fill, line_width)
-@deprecated(
- replace_with="kornia.image.draw_point2d",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def draw_point2d(*args: Any, **kwargs: Any) -> Any:
+def draw_point2d(image: torch.Tensor, points: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
"""Deprecated: Use `kornia.image.draw_point2d` instead."""
- return _draw_point2d(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("draw_point2d", "kornia.image")
+ return _draw_point2d(image, points, color)
-@deprecated(
- replace_with="kornia.image.draw_convex_polygon",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def draw_convex_polygon(*args: Any, **kwargs: Any) -> Any:
+def draw_convex_polygon(
+ images: torch.Tensor, polygons: Union[torch.Tensor, List[torch.Tensor]], colors: torch.Tensor
+) -> torch.Tensor:
"""Deprecated: Use `kornia.image.draw_convex_polygon` instead."""
- return _draw_convex_polygon(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("draw_convex_polygon", "kornia.image")
+ return _draw_convex_polygon(images, polygons, colors)
-@deprecated(
- replace_with="kornia.image.image_to_string",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def image_to_string(*args: Any, **kwargs: Any) -> Any:
+def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
"""Deprecated: Use `kornia.image.image_to_string` instead."""
- return _image_to_string(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("image_to_string", "kornia.image")
+ return _image_to_string(image, max_width)
-@deprecated(
- replace_with="kornia.image.print_image",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def print_image(*args: Any, **kwargs: Any) -> Any:
+def print_image(image: Union[str, os.PathLike, torch.Tensor], max_width: int = 96) -> None:
"""Deprecated: Use `kornia.image.print_image` instead."""
- return _print_image(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("print_image", "kornia.image")
+ return _print_image(image, max_width)
-@deprecated(
- replace_with="kornia.image.image_to_tensor",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def image_to_tensor(*args: Any, **kwargs: Any) -> Any:
+def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
"""Deprecated: Use `kornia.image.image_to_tensor` instead."""
- return _image_to_tensor(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("image_to_tensor", "kornia.image")
+ return _image_to_tensor(image, keepdim)
-@deprecated(
- replace_with="kornia.image.tensor_to_image",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def tensor_to_image(*args: Any, **kwargs: Any) -> Any:
+def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
"""Deprecated: Use `kornia.image.tensor_to_image` instead."""
- return _tensor_to_image(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("tensor_to_image", "kornia.image")
+ return _tensor_to_image(tensor, keepdim, force_contiguous)
-@deprecated(
- replace_with="kornia.losses.one_hot",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.losses` instead.",
-)
-def one_hot(*args: Any, **kwargs: Any) -> Any:
+def one_hot(
+ labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 0.0
+) -> torch.Tensor:
"""Deprecated: Use `kornia.losses.one_hot` instead."""
- return _one_hot(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("one_hot", "kornia.losses")
+ return _one_hot(labels, num_classes, device, dtype, eps)
# The 0.8.3 removal shipped without shims for these public names, breaking
@@ -243,84 +255,60 @@ def one_hot(*args: Any, **kwargs: Any) -> Any:
# standard warning so the documented deprecation policy holds.
-@deprecated(
- replace_with="kornia.core.ops.eye_like",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.ops` instead.",
-)
-def eye_like(*args: Any, **kwargs: Any) -> Any:
+def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
"""Deprecated: Use `kornia.core.ops.eye_like` instead."""
- return _eye_like(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("eye_like", "kornia.core.ops")
+ return _eye_like(n, input, shared_memory)
-@deprecated(
- replace_with="kornia.core.ops.vec_like",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.ops` instead.",
-)
-def vec_like(*args: Any, **kwargs: Any) -> Any:
+def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
"""Deprecated: Use `kornia.core.ops.vec_like` instead."""
- return _vec_like(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("vec_like", "kornia.core.ops")
+ return _vec_like(n, tensor, shared_memory)
-@deprecated(
- replace_with="kornia.core.utils.safe_solve_with_mask",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def safe_solve_with_mask(*args: Any, **kwargs: Any) -> Any:
+def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Deprecated: Use `kornia.core.utils.safe_solve_with_mask` instead."""
- return _safe_solve_with_mask(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("safe_solve_with_mask", "kornia.core.utils")
+ return _safe_solve_with_mask(B, A)
-@deprecated(
- replace_with="kornia.core.utils.safe_inverse_with_mask",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def safe_inverse_with_mask(*args: Any, **kwargs: Any) -> Any:
+def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Deprecated: Use `kornia.core.utils.safe_inverse_with_mask` instead."""
- return _safe_inverse_with_mask(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("safe_inverse_with_mask", "kornia.core.utils")
+ return _safe_inverse_with_mask(A)
-@deprecated(
- replace_with="kornia.core.utils.is_mps_tensor_safe",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def is_mps_tensor_safe(*args: Any, **kwargs: Any) -> Any:
+def is_mps_tensor_safe(x: torch.Tensor) -> bool:
"""Deprecated: Use `kornia.core.utils.is_mps_tensor_safe` instead."""
- return _is_mps_tensor_safe(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("is_mps_tensor_safe", "kornia.core.utils")
+ return _is_mps_tensor_safe(x)
-@deprecated(
- replace_with="kornia.core.utils.dataclass_to_dict",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def dataclass_to_dict(*args: Any, **kwargs: Any) -> Any:
+def dataclass_to_dict(obj: Any) -> Any:
"""Deprecated: Use `kornia.core.utils.dataclass_to_dict` instead."""
- return _dataclass_to_dict(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("dataclass_to_dict", "kornia.core.utils")
+ return _dataclass_to_dict(obj)
-@deprecated(
- replace_with="kornia.core.utils.dict_to_dataclass",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def dict_to_dataclass(*args: Any, **kwargs: Any) -> Any:
+def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[_T]) -> _T:
"""Deprecated: Use `kornia.core.utils.dict_to_dataclass` instead."""
- return _dict_to_dataclass(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("dict_to_dataclass", "kornia.core.utils")
+ return _dict_to_dataclass(dict_obj, dataclass_type)
-@deprecated(
- replace_with="kornia.image.image_list_to_tensor",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
-)
-def image_list_to_tensor(*args: Any, **kwargs: Any) -> Any:
+def image_list_to_tensor(images: List[Any]) -> torch.Tensor:
"""Deprecated: Use `kornia.image.image_list_to_tensor` instead."""
- return _image_list_to_tensor(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("image_list_to_tensor", "kornia.image")
+ return _image_list_to_tensor(images)
class ImageToTensor(_ImageToTensor):
@@ -330,124 +318,126 @@ class ImageToTensor(_ImageToTensor):
deprecated; `isinstance` checks and further subclassing keep working.
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None:
- _emit_deprecation_warning(
- "ImageToTensor",
- "kornia.image.ImageToTensor",
- "0.8.3",
- " The `kornia.utils` module has been removed. Import from `kornia.image` instead.",
- )
- super().__init__(*args, **kwargs)
+ def __init__(self, keepdim: bool = False) -> None:
+ _warn("ImageToTensor", "kornia.image")
+ super().__init__(keepdim)
-@deprecated(
- replace_with="kornia.io.get_sample_images",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.io` instead.",
-)
-def get_sample_images(*args: Any, **kwargs: Any) -> Any:
+def get_sample_images(
+ resize: Optional[Tuple[int, int]] = None,
+ paths: List[str] = _IMAGE_URLS,
+ download: bool = True,
+ cache_dir: Optional[str] = None,
+ as_list: Optional[bool] = None,
+ divisible_factor: Optional[int] = None,
+ **kwargs: Any,
+) -> Union[torch.Tensor, List[torch.Tensor]]:
"""Deprecated: Use `kornia.io.get_sample_images` instead."""
- from kornia.io import get_sample_images as _get_sample_images
+ if not torch.jit.is_scripting():
+ _warn("get_sample_images", "kornia.io")
+ return _get_sample_images(resize, paths, download, cache_dir, as_list, divisible_factor, **kwargs)
- return _get_sample_images(*args, **kwargs)
-
-@deprecated(
- replace_with="kornia.core.utils.batched_forward",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def batched_forward(*args: Any, **kwargs: Any) -> Any:
+def batched_forward(
+ model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargs: Any
+) -> torch.Tensor:
"""Deprecated: Use `kornia.core.utils.batched_forward` instead."""
- from kornia.core.utils import batched_forward as _batched_forward
+ if not torch.jit.is_scripting():
+ _warn("batched_forward", "kornia.core.utils")
+ return _batched_forward(model, data, device, batch_size, **kwargs)
- return _batched_forward(*args, **kwargs)
-
-@deprecated(
- replace_with="torch.meshgrid",
- version="0.8.3",
- extra_reason=" This compatibility wrapper predates torch 1.10; call `torch.meshgrid(tensors, indexing=...)`.",
-)
-def torch_meshgrid(tensors: Any, indexing: str) -> Any:
+def torch_meshgrid(tensors: List[torch.Tensor], indexing: str): # the 0.8.2 signature, return left unannotated
"""Deprecated: Use `torch.meshgrid` directly."""
- import torch
-
+ if not torch.jit.is_scripting():
+ _emit_deprecation_warning(
+ "torch_meshgrid",
+ "torch.meshgrid",
+ "0.8.3",
+ " This compatibility wrapper predates torch 1.10; call `torch.meshgrid(tensors, indexing=...)`.",
+ )
return torch.meshgrid(tensors, indexing=indexing)
-@deprecated(
- replace_with='torch.load(..., map_location="cpu")',
- version="0.8.3",
- extra_reason=" This identity hook predates `map_location` accepting device strings.",
-)
+def _in_torch_or_kornia(frame: FrameType) -> bool:
+ return str(frame.f_globals.get("__name__", "")).split(".", 1)[0] in ("torch", "kornia")
+
+
+def _warn_map_location_to_cpu() -> None:
+ """Warn at the line that called ``torch.load``.
+
+ ``torch.load`` calls the hook from inside torch, once for every storage it restores. A fixed ``stacklevel`` names
+ a torch frame, and the default filters hide a ``DeprecationWarning`` that is not attributed to ``__main__``, so the
+ warning goes to the first frame outside torch and kornia instead. Every storage of a call then warns at the same
+ line, so the warnings registry shows it once there under the default filters, as for any repeated warning.
+ """
+ level = 4 # counted from _emit_deprecation_warning: this function, map_location_to_cpu, then the hook's caller
+ frame: Optional[FrameType] = sys._getframe(2)
+ while frame is not None and _in_torch_or_kornia(frame):
+ frame, level = frame.f_back, level + 1
+ if frame is None: # nothing outside torch and kornia: name the hook's caller
+ level = 4
+ _emit_deprecation_warning(
+ "map_location_to_cpu",
+ 'torch.load(..., map_location="cpu")',
+ "0.8.3",
+ " This identity hook predates `map_location` accepting device strings.",
+ stacklevel=level,
+ )
+
+
def map_location_to_cpu(storage: Any, *args: Any, **kwargs: Any) -> Any:
"""Deprecated: Pass `map_location="cpu"` to `torch.load` instead."""
+ _warn_map_location_to_cpu()
return storage
-@deprecated(
- replace_with="kornia.core.utils.get_cuda_device_if_available",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def get_cuda_device_if_available(*args: Any, **kwargs: Any) -> Any:
+def get_cuda_device_if_available(index: int = 0) -> torch.device:
"""Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""
- return _get_cuda_device_if_available(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("get_cuda_device_if_available", "kornia.core.utils")
+ return _get_cuda_device_if_available(index)
-@deprecated(
- replace_with="kornia.core.utils.get_mps_device_if_available",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def get_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
+def get_mps_device_if_available() -> torch.device:
"""Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""
- return _get_mps_device_if_available(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("get_mps_device_if_available", "kornia.core.utils")
+ return _get_mps_device_if_available()
-@deprecated(
- replace_with="kornia.core.utils.get_cuda_or_mps_device_if_available",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def get_cuda_or_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:
+def get_cuda_or_mps_device_if_available() -> torch.device:
"""Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""
- return _get_cuda_or_mps_device_if_available(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("get_cuda_or_mps_device_if_available", "kornia.core.utils")
+ return _get_cuda_or_mps_device_if_available()
-@deprecated(
- replace_with="kornia.core.utils.is_autocast_enabled",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def is_autocast_enabled(*args: Any, **kwargs: Any) -> Any:
+def is_autocast_enabled(both: bool = True) -> bool:
"""Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""
- return _is_autocast_enabled(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("is_autocast_enabled", "kornia.core.utils")
+ return _is_autocast_enabled(both)
-@deprecated(
- replace_with="kornia.core.utils.xla_is_available",
- version="0.8.3",
- extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",
-)
-def xla_is_available(*args: Any, **kwargs: Any) -> Any:
+def xla_is_available() -> bool:
"""Deprecated: Use `kornia.core.utils.xla_is_available` instead."""
- return _xla_is_available(*args, **kwargs)
+ if not torch.jit.is_scripting():
+ _warn("xla_is_available", "kornia.core.utils")
+ return _xla_is_available()
def __getattr__(name: str) -> Any:
- # Lazy so that `import kornia.utils` never pulls in the onnx machinery.
+ # ``CachedDownloader`` is used through its classmethods without being constructed, so it cannot warn from
+ # ``__init__`` the way ``ImageToTensor`` does: it resolves here instead, and warns on access.
+ # ``kornia.utils.sample`` is the v0.8.2 submodule path of ``get_sample_images``.
if name == "CachedDownloader":
from kornia.onnx.download import CachedDownloader as _CachedDownloader
- _emit_deprecation_warning(
- "CachedDownloader",
- "kornia.onnx.download.CachedDownloader",
- "0.8.3",
- " The `kornia.utils` module has been removed. Import from `kornia.onnx.download` instead.",
- )
+ _warn("CachedDownloader", "kornia.onnx.download")
return _CachedDownloader
+ if name == "sample":
+ return importlib.import_module("kornia.utils.sample")
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/kornia/utils/sample.py b/kornia/utils/sample.py
new file mode 100644
index 000000000..fe86568ea
--- /dev/null
+++ b/kornia/utils/sample.py
@@ -0,0 +1,23 @@
+# 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.
+#
+
+
+"""Deprecated: the v0.8.2 path of `get_sample_images`, which moved to `kornia.io.get_sample_images`."""
+
+from kornia.utils import get_sample_images
+
+__all__ = ["get_sample_images"]
diff --git a/tests/api_surface.json b/tests/api_surface.json
index c27a87315..5324f73a3 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -1206,5 +1206,8 @@
"torch_meshgrid",
"vec_like",
"xla_is_available"
+ ],
+ "kornia.utils.sample": [
+ "get_sample_images"
]
}
diff --git a/tests/core/test_compat.py b/tests/core/test_compat.py
index 90659f07b..d03c2bc4e 100644
--- a/tests/core/test_compat.py
+++ b/tests/core/test_compat.py
@@ -382,6 +382,24 @@ class TestDeprecatedFunction:
assert str(w.message) == "Since kornia 0.9.0 the `old` is deprecated in favor of `Holder.new`."
assert (w.filename, w.lineno) == (__file__, line)
+ def test_compile_fullgraph_of_code_calling_it(self, torch_optimizer):
+ # Dynamo cannot trace ``warnings.warn``; the warning is skipped while it captures the graph (#5901).
+ @deprecated(replace_with="new", version="0.8.3")
+ def old(x: torch.Tensor) -> torch.Tensor:
+ return x + 1
+
+ x = torch.rand(3)
+ compiled = torch_optimizer(lambda t: old(t) * 2, fullgraph=True)
+ with _caught() as caught:
+ out = compiled(x)
+ assert torch.equal(out, (x + 1) * 2)
+ assert caught == []
+ with _caught() as caught:
+ line = _line_below()
+ old(x)
+ (w,) = caught
+ assert (w.filename, w.lineno) == (__file__, line)
+
class TestDeprecatedClass:
"""The decorated name has to stay a class: the issue's repro turned it into a function."""
diff --git a/tests/losses/test_one_hot.py b/tests/losses/test_one_hot.py
index 263645923..0e27ce027 100644
--- a/tests/losses/test_one_hot.py
+++ b/tests/losses/test_one_hot.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
import torch.nn.functional as F
@@ -75,6 +77,29 @@ class TestOneHot:
with pytest.raises(BaseError, match="floating point dtype"):
one_hot(labels, 2, device, torch.int64, eps=1e-6)
+ @pytest.mark.parametrize("eps", [0.0, 0.125])
+ def test_jit_script(self, device, dtype, eps):
+ # The replacement of ``kornia.utils.one_hot``, which scripted in 0.8.2, has to script too (#5901).
+ labels = torch.tensor([[[0, 2, 1], [1, 0, 0]]], device=device)
+ scripted = torch.jit.script(one_hot)
+ for shape in [(2, 3), (2,), (1, 2, 3)]:
+ lbl = labels.flatten()[: math.prod(shape)].reshape(shape)
+ got, expected = scripted(lbl, 3, device, dtype, eps), one_hot(lbl, 3, device, dtype, eps)
+ assert (got.dtype, got.shape) == (expected.dtype, expected.shape)
+ assert torch.equal(got, expected)
+
+ def test_jit_script_integer_dtype(self, device):
+ labels = torch.tensor([[0, 2], [1, 0]], device=device)
+ assert torch.equal(
+ torch.jit.script(one_hot)(labels, 3, device, torch.uint8), one_hot(labels, 3, device, torch.uint8)
+ )
+
+ def test_jit_script_rejects_eps_with_an_integer_dtype(self, device):
+ # the scripted path checks the dtype through a tensor, since TorchScript has no ``dtype.is_floating_point``
+ labels = torch.tensor([[0, 2], [1, 0]], device=device)
+ with pytest.raises(torch.jit.Error, match="A non-zero eps needs a floating point dtype"):
+ torch.jit.script(one_hot)(labels, 3, device, torch.int64, 0.125)
+
class TestConventionsOneHot(BaseTester):
"""Pins for the layout of :func:`kornia.losses.one_hot`."""
diff --git a/tests/test_transpiler.py b/tests/test_transpiler.py
new file mode 100644
index 000000000..11f9d0a02
--- /dev/null
+++ b/tests/test_transpiler.py
@@ -0,0 +1,59 @@
+# 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.
+#
+
+"""The removed Ivy-powered entry points explain their removal whichever way 0.8.2 code reaches them (#5906)."""
+
+import re
+
+import pytest
+
+import kornia
+import kornia.transpiler
+
+_REMOVED = ("to_jax", "to_numpy", "to_tensorflow")
+
+
+def _message(qualified_name: str) -> str:
+ return re.escape(f"{qualified_name}() was removed: testing found the Ivy-powered multi-framework transpiler")
+
+
[email protected]("name", _REMOVED)
[email protected]("module", ["kornia", "kornia.transpiler"])
+class TestRemovedEntryPoints:
+ def test_from_import_then_call_explains_the_removal(self, module, name):
+ namespace: dict = {}
+ exec(f"from {module} import {name}", namespace) # noqa: S102 a fixed import statement
+ with pytest.raises(RuntimeError, match=_message(f"{module}.{name}")) as info:
+ namespace[name]()
+ assert "multi-framework-support.html" in str(info.value)
+
+ def test_attribute_call_explains_the_removal(self, module, name):
+ fn = getattr(kornia if module == "kornia" else kornia.transpiler, name)
+ with pytest.raises(RuntimeError, match=_message(f"{module}.{name}")):
+ fn(kornia, source="torch")
+
+ def test_looking_the_name_up_does_not_raise(self, module, name):
+ assert hasattr(kornia if module == "kornia" else kornia.transpiler, name)
+
+
+def test_names_stay_out_of_the_transpiler_public_surface():
+ assert kornia.transpiler.__all__ == []
+
+
+def test_star_imports_do_not_raise():
+ for module in ("kornia", "kornia.transpiler"):
+ exec(f"from {module} import *", {}) # noqa: S102 a fixed import statement
diff --git a/tests/utils/test_deprecated.py b/tests/utils/test_deprecated.py
index 86f9bf772..c70ed8770 100644
--- a/tests/utils/test_deprecated.py
+++ b/tests/utils/test_deprecated.py
@@ -17,14 +17,34 @@
from __future__ import annotations
+import contextlib
+import dataclasses
+import inspect
+import io
+import os
+import subprocess
+import sys
+import textwrap
+import types
import warnings
+from pathlib import Path
+from typing import Any, Callable
import numpy as np
import pytest
import torch
+import kornia
+import kornia.core.ops
+import kornia.core.utils
+import kornia.geometry
+import kornia.image
+import kornia.io
+import kornia.losses
from kornia import utils
+from testing.base import BaseTester
+
class TestDeprecatedWrappers:
"""Verify that every re-exported function in kornia.utils emits a DeprecationWarning."""
@@ -332,3 +352,558 @@ class TestRestoredWrappers:
"xla_is_available",
}
assert expected.issubset(set(utils.__all__))
+
+
+# The shims stand in for the 0.8.2 functions on every surface those supported: attribute access after a plain
+# ``import kornia`` (#5900), the full signature, TorchScript and ``torch.compile(fullgraph=True)`` (#5901), and a
+# visible warning when ``torch.load`` calls ``map_location_to_cpu`` (#5905).
+
+
+def _run_fresh(code: str) -> subprocess.CompletedProcess:
+ """Run ``code`` in a fresh interpreter that imports the kornia tree under test.
+
+ The child runs from the directory holding that ``kornia`` package, so ``-c`` resolves it ahead of any installed
+ copy, and without ``PYTHONWARNINGS``, so it starts from Python's default warning filters.
+ """
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONWARNINGS"}
+ # Trusted, fixed command: the current interpreter running a literal script; no external input.
+ return subprocess.run( # noqa: S603
+ [sys.executable, "-c", textwrap.dedent(code)],
+ cwd=Path(kornia.__file__).resolve().parents[1],
+ env=env,
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=300,
+ )
+
+
+def _same_kornia(path: str) -> bool:
+ return os.path.realpath(path) == os.path.realpath(kornia.__file__)
+
+
+class TestReachableAfterBareImport:
+ """``import kornia`` alone reaches the shims, the way kornia's 0.8.2 documentation used them (#5900)."""
+
+ def test_attribute_access_after_import_kornia(self):
+ result = _run_fresh(
+ """
+ import sys
+ import warnings
+
+ import torch # torch's own import-time warnings are not kornia's
+
+ warnings.simplefilter("error")
+ import kornia
+
+ print(kornia.__file__)
+ print("kornia.utils imported by import kornia:", "kornia.utils" in sys.modules)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ grid = kornia.utils.create_meshgrid(2, 3); line = sys._getframe().f_lineno
+ print("shape:", tuple(grid.shape))
+ print("warnings:", [(w.category.__name__, w.lineno == line) for w in caught])
+ """
+ )
+ assert result.returncode == 0, result.stderr
+ first, *rest = result.stdout.splitlines()
+ assert _same_kornia(first)
+ assert rest == [
+ "kornia.utils imported by import kornia: False",
+ "shape: (1, 2, 3, 2)",
+ "warnings: [('DeprecationWarning', True)]",
+ ]
+
+ def test_v082_sample_submodule_after_import_kornia(self, tmp_path):
+ result = _run_fresh(
+ f"""
+ import warnings
+
+ import kornia
+
+ print(kornia.__file__)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ fn = kornia.utils.sample.get_sample_images
+ print("warnings on access:", len(caught))
+ print("result:", fn(paths=[], download=False, cache_dir={str(tmp_path)!r}))
+ names_replacement = ["`kornia.io.get_sample_images`" in str(w.message) for w in caught]
+ print("warnings:", list(zip([w.category.__name__ for w in caught], names_replacement)))
+ """
+ )
+ assert result.returncode == 0, result.stderr
+ first, *rest = result.stdout.splitlines()
+ assert _same_kornia(first)
+ assert rest == ["warnings on access: 0", "result: []", "warnings: [('DeprecationWarning', True)]"]
+
+ def test_v082_sample_submodule_import(self, tmp_path):
+ from kornia.utils import sample
+ from kornia.utils.sample import get_sample_images
+
+ assert sample.__all__ == ["get_sample_images"]
+ with pytest.warns(DeprecationWarning, match=r"`kornia\.io\.get_sample_images`"):
+ assert get_sample_images(paths=[], download=False, cache_dir=str(tmp_path)) == []
+
+
+class _Cfg:
+ a: int
+ b: float = 2.0
+
+
+class _Scale(torch.nn.Module):
+ def forward(self, x: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
+ return x * scale
+
+
+# Each shim's name -> the replacement its warning names, which is also the function it forwards to.
+_UTILS_REPLACEMENTS = {
+ "batched_forward": "kornia.core.utils.batched_forward",
+ "create_meshgrid": "kornia.geometry.create_meshgrid",
+ "create_meshgrid3d": "kornia.geometry.create_meshgrid3d",
+ "dataclass_to_dict": "kornia.core.utils.dataclass_to_dict",
+ "dict_to_dataclass": "kornia.core.utils.dict_to_dataclass",
+ "draw_convex_polygon": "kornia.image.draw_convex_polygon",
+ "draw_line": "kornia.image.draw_line",
+ "draw_point2d": "kornia.image.draw_point2d",
+ "draw_rectangle": "kornia.image.draw_rectangle",
+ "eye_like": "kornia.core.ops.eye_like",
+ "get_cuda_device_if_available": "kornia.core.utils.get_cuda_device_if_available",
+ "get_cuda_or_mps_device_if_available": "kornia.core.utils.get_cuda_or_mps_device_if_available",
+ "get_mps_device_if_available": "kornia.core.utils.get_mps_device_if_available",
+ "get_sample_images": "kornia.io.get_sample_images",
+ "image_list_to_tensor": "kornia.image.image_list_to_tensor",
+ "image_to_string": "kornia.image.image_to_string",
+ "image_to_tensor": "kornia.image.image_to_tensor",
+ "is_autocast_enabled": "kornia.core.utils.is_autocast_enabled",
+ "is_mps_tensor_safe": "kornia.core.utils.is_mps_tensor_safe",
+ "load_pointcloud_ply": "kornia.geometry.load_pointcloud_ply",
+ "map_location_to_cpu": 'torch.load(..., map_location="cpu")',
+ "one_hot": "kornia.losses.one_hot",
+ "print_image": "kornia.image.print_image",
+ "safe_inverse_with_mask": "kornia.core.utils.safe_inverse_with_mask",
+ "safe_solve_with_mask": "kornia.core.utils.safe_solve_with_mask",
+ "save_pointcloud_ply": "kornia.geometry.save_pointcloud_ply",
+ "tensor_to_image": "kornia.image.tensor_to_image",
+ "torch_meshgrid": "torch.meshgrid",
+ "vec_like": "kornia.core.ops.vec_like",
+ "xla_is_available": "kornia.core.utils.xla_is_available",
+}
+
+# The deprecated top-level aliases in ``kornia/__init__.py`` -> their replacements.
+_TOP_LEVEL_REPLACEMENTS = {
+ name: _UTILS_REPLACEMENTS[name]
+ for name in (
+ "create_meshgrid",
+ "create_meshgrid3d",
+ "draw_convex_polygon",
+ "draw_line",
+ "draw_point2d",
+ "draw_rectangle",
+ "eye_like",
+ "get_cuda_device_if_available",
+ "get_cuda_or_mps_device_if_available",
+ "get_mps_device_if_available",
+ "image_to_string",
+ "image_to_tensor",
+ "is_autocast_enabled",
+ "load_pointcloud_ply",
+ "one_hot",
+ "print_image",
+ "save_pointcloud_ply",
+ "tensor_to_image",
+ "vec_like",
+ "xla_is_available",
+ )
+}
+
+# Shims that forward to a kornia function of the same signature (the other two keep their 0.8.2 signatures).
+_FORWARDING = sorted(set(_UTILS_REPLACEMENTS) - {"map_location_to_cpu", "torch_meshgrid"})
+
+
+def _resolve(dotted: str) -> Any:
+ obj: Any = kornia
+ for part in dotted.split(".")[1:]:
+ obj = getattr(obj, part)
+ return obj
+
+
+def _target(name: str) -> Callable[..., Any]:
+ if name == "torch_meshgrid":
+ return lambda tensors, indexing: torch.meshgrid(tensors, indexing=indexing)
+ if name == "map_location_to_cpu":
+ return lambda storage, location: storage
+ return _resolve(_UTILS_REPLACEMENTS[name])
+
+
+def _call_args(name: str, device: torch.device, dtype: torch.dtype, tmp_path: Path) -> tuple[tuple, dict]:
+ """Fresh arguments for one call of ``name``, giving every parameter that has a default a non-default value."""
+ img = torch.zeros(1, 3, 6, 7, device=device, dtype=dtype)
+ color = torch.tensor([1.0, 0.5, 0.25], device=device, dtype=dtype)
+ x = torch.eye(2, device=device, dtype=dtype) * 2 + 0.25
+ arr = np.arange(4 * 5 * 3, dtype=np.uint8).reshape(4, 5, 3)
+ calls: dict[str, Callable[[], tuple[tuple, dict]]] = {
+ "batched_forward": lambda: ((_Scale(), x[None].repeat(3, 1, 1), device, 2), {"scale": 3.0}),
+ # align_corners only matters for normalized coordinates, so those stay on.
+ "create_meshgrid": lambda: ((3, 4, True, device, dtype, False), {}),
+ "create_meshgrid3d": lambda: ((2, 3, 4, False, device, dtype), {}),
+ "dataclass_to_dict": lambda: ((_Cfg(1, 3.0),), {}),
+ "dict_to_dataclass": lambda: (({"a": 1, "b": 3.0}, _Cfg), {}),
+ "draw_convex_polygon": lambda: (
+ (img, torch.tensor([[[1.0, 1.0], [5.0, 1.0], [3.0, 4.0]]], device=device, dtype=dtype), color),
+ {},
+ ),
+ "draw_line": lambda: (
+ (img[0], torch.tensor([0, 0], device=device), torch.tensor([6, 5], device=device), color),
+ {},
+ ),
+ "draw_point2d": lambda: ((img[0], torch.tensor([[1, 2], [4, 3]], device=device), color), {}),
+ "draw_rectangle": lambda: ((img, torch.tensor([[[1, 1, 5, 4]]], device=device), color, None, 2), {}),
+ "eye_like": lambda: ((3, x[None].repeat(2, 1, 1), True), {}),
+ "get_cuda_device_if_available": lambda: ((0,), {}),
+ "get_cuda_or_mps_device_if_available": lambda: ((), {}),
+ "get_mps_device_if_available": lambda: ((), {}),
+ "get_sample_images": lambda: ((None, [], False, str(tmp_path), True, None), {}),
+ "image_list_to_tensor": lambda: (([arr, arr + 1],), {}),
+ "image_to_string": lambda: ((img[0] + 0.5, 4), {}),
+ "image_to_tensor": lambda: ((arr, False), {}),
+ "is_autocast_enabled": lambda: ((False,), {}),
+ "is_mps_tensor_safe": lambda: ((x,), {}),
+ "load_pointcloud_ply": lambda: ((tmp_path / "in.ply", None), {}),
+ "map_location_to_cpu": lambda: ((x, "cuda:0"), {}),
+ "one_hot": lambda: ((torch.tensor([[0, 2], [1, 0]], device=device), 3, device, dtype, 0.25), {}),
+ "print_image": lambda: ((img[0] + 0.5, 4), {}),
+ "safe_inverse_with_mask": lambda: ((x[None],), {}),
+ "safe_solve_with_mask": lambda: ((x[None], x[None] + 1), {}),
+ "save_pointcloud_ply": lambda: ((tmp_path / "out.ply", torch.arange(9.0).view(3, 3)), {}),
+ "tensor_to_image": lambda: ((img + 0.5, True, True), {}),
+ "torch_meshgrid": lambda: (([torch.arange(2, device=device), torch.arange(3, device=device)], "xy"), {}),
+ "vec_like": lambda: ((3, x[None].repeat(2, 1, 1), True), {}),
+ "xla_is_available": lambda: ((), {}),
+ }
+ if name == "load_pointcloud_ply":
+ kornia.geometry.save_pointcloud_ply(tmp_path / "in.ply", torch.arange(9.0).view(3, 3) / 7)
+ return calls[name]()
+
+
+def _outcome(fn: Callable[..., Any], args: tuple, kwargs: dict) -> tuple:
+ """What calling ``fn`` gives: ``("returned", value, stdout)`` or ``("raised", type, message)``."""
+ out = io.StringIO()
+ try:
+ with contextlib.redirect_stdout(out):
+ value = fn(*args, **kwargs)
+ except Exception as e: # the comparison is between two calls, whatever they raise
+ return ("raised", type(e), str(e))
+ return ("returned", value, out.getvalue())
+
+
+def _assert_same(got: Any, expected: Any) -> None:
+ assert type(got) is type(expected)
+ if isinstance(got, torch.Tensor):
+ assert (got.dtype, got.device, got.shape) == (expected.dtype, expected.device, expected.shape)
+ assert got.stride() == expected.stride()
+ assert torch.equal(got, expected)
+ elif isinstance(got, np.ndarray):
+ assert got.dtype == expected.dtype
+ np.testing.assert_array_equal(got, expected)
+ elif isinstance(got, (tuple, list)):
+ assert len(got) == len(expected)
+ for g, e in zip(got, expected):
+ _assert_same(g, e)
+ else:
+ assert got == expected
+
+
+def _signature(fn: Callable[..., Any]) -> str:
+ return str(inspect.signature(fn, eval_str=True))
+
+
+class TestShimsForwardEveryParameter(BaseTester):
+ """Every shim forwards each parameter to its replacement and warns once, at the caller's line (#5901)."""
+
+ @pytest.mark.parametrize("name", sorted(_UTILS_REPLACEMENTS))
+ def test_utils_shim_matches_its_replacement(self, name, device, dtype, tmp_path):
+ expected = _outcome(_target(name), *_call_args(name, device, dtype, tmp_path))
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ got = _outcome(getattr(utils, name), *_call_args(name, device, dtype, tmp_path))
+ _assert_same(got, expected)
+ (w,) = [w for w in caught if issubclass(w.category, DeprecationWarning)]
+ assert w.filename == __file__
+ assert f"`{_UTILS_REPLACEMENTS[name]}`" in str(w.message)
+ # kornia.utils is deprecated, not removed: every name in it still works.
+ assert "removed" not in str(w.message)
+
+ @pytest.mark.parametrize("name", sorted(_TOP_LEVEL_REPLACEMENTS))
+ def test_top_level_alias_matches_its_replacement(self, name, device, dtype, tmp_path):
+ expected = _outcome(_target(name), *_call_args(name, device, dtype, tmp_path))
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ got = _outcome(getattr(kornia, name), *_call_args(name, device, dtype, tmp_path))
+ _assert_same(got, expected)
+ (w,) = [w for w in caught if issubclass(w.category, DeprecationWarning)]
+ assert w.filename == __file__
+ assert f"`{_TOP_LEVEL_REPLACEMENTS[name]}`" in str(w.message)
+
+ @pytest.mark.parametrize("name", _FORWARDING)
+ def test_utils_shim_has_its_replacements_signature(self, name):
+ assert _signature(getattr(utils, name)) == _signature(_target(name))
+
+ @pytest.mark.parametrize("name", sorted(_TOP_LEVEL_REPLACEMENTS))
+ def test_top_level_alias_has_its_replacements_signature(self, name):
+ assert _signature(getattr(kornia, name)) == _signature(_target(name))
+
+ def test_v082_signatures_of_the_other_two(self):
+ assert _signature(utils.torch_meshgrid) == "(tensors: List[torch.Tensor], indexing: str)"
+ assert _signature(utils.map_location_to_cpu) == "(storage: Any, *args: Any, **kwargs: Any) -> Any"
+
+ def test_image_to_tensor_class_has_its_replacements_signature(self):
+ assert _signature(utils.ImageToTensor) == _signature(kornia.image.ImageToTensor)
+
+ def test_warning_points_at_the_callers_line(self):
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ line = sys._getframe().f_lineno
+ utils.create_meshgrid(2, 2)
+ kornia.create_meshgrid(2, 2)
+ utils.ImageToTensor()
+ utils.CachedDownloader # noqa: B018 the attribute access is what warns
+ assert [(w.category, w.filename, w.lineno) for w in caught] == [
+ (DeprecationWarning, __file__, line + offset) for offset in (1, 2, 3, 4)
+ ]
+
+
+# User code that calls a shim, as 0.8.2 code did. Each takes and returns one tensor so that one test scripts or
+# compiles all of them. Before #3449 the six ``kornia.utils`` calls among them scripted (#5901).
+
+
+def _call_utils_create_meshgrid(x: torch.Tensor) -> torch.Tensor:
+ return utils.create_meshgrid(3, 4, False, x.device, x.dtype)
+
+
+def _call_utils_create_meshgrid3d(x: torch.Tensor) -> torch.Tensor:
+ return utils.create_meshgrid3d(2, 3, 4, False, x.device, x.dtype)
+
+
+def _call_utils_one_hot(x: torch.Tensor) -> torch.Tensor:
+ return utils.one_hot(torch.tensor([[0, 2], [1, 0]], device=x.device), 3, x.device, x.dtype)
+
+
+def _call_utils_draw_rectangle(x: torch.Tensor) -> torch.Tensor:
+ image = torch.zeros(1, 3, 6, 7, device=x.device, dtype=x.dtype)
+ return utils.draw_rectangle(image, torch.tensor([[[1, 1, 5, 4]]], device=x.device))
+
+
+def _call_utils_torch_meshgrid(x: torch.Tensor) -> torch.Tensor:
+ return torch.stack(utils.torch_meshgrid([x[0, 0], x[0, 1, :2]], "ij"))
+
+
+def _call_utils_safe_inverse_with_mask(x: torch.Tensor) -> torch.Tensor:
+ inverse, mask = utils.safe_inverse_with_mask(x)
+ return torch.cat([inverse.flatten(), mask.to(inverse.dtype)])
+
+
+def _call_utils_eye_like(x: torch.Tensor) -> torch.Tensor:
+ return utils.eye_like(3, x)
+
+
+def _call_utils_vec_like(x: torch.Tensor) -> torch.Tensor:
+ return utils.vec_like(3, x)
+
+
+def _call_utils_draw_point2d(x: torch.Tensor) -> torch.Tensor:
+ image = torch.zeros(3, 6, 7, device=x.device, dtype=x.dtype)
+ color = torch.ones(3, device=x.device, dtype=x.dtype)
+ return utils.draw_point2d(image, torch.tensor([[1, 2], [4, 3]], device=x.device), color)
+
+
+def _call_create_meshgrid(x: torch.Tensor) -> torch.Tensor:
+ return kornia.create_meshgrid(3, 4, False, x.device, x.dtype)
+
+
+def _call_create_meshgrid3d(x: torch.Tensor) -> torch.Tensor:
+ return kornia.create_meshgrid3d(2, 3, 4, False, x.device, x.dtype)
+
+
+def _call_one_hot(x: torch.Tensor) -> torch.Tensor:
+ return kornia.one_hot(torch.tensor([[0, 2], [1, 0]], device=x.device), 3, x.device, x.dtype)
+
+
+def _call_draw_rectangle(x: torch.Tensor) -> torch.Tensor:
+ image = torch.zeros(1, 3, 6, 7, device=x.device, dtype=x.dtype)
+ return kornia.draw_rectangle(image, torch.tensor([[[1, 1, 5, 4]]], device=x.device))
+
+
+def _call_eye_like(x: torch.Tensor) -> torch.Tensor:
+ return kornia.eye_like(3, x)
+
+
+def _call_vec_like(x: torch.Tensor) -> torch.Tensor:
+ return kornia.vec_like(3, x)
+
+
+def _call_draw_point2d(x: torch.Tensor) -> torch.Tensor:
+ image = torch.zeros(3, 6, 7, device=x.device, dtype=x.dtype)
+ color = torch.ones(3, device=x.device, dtype=x.dtype)
+ return kornia.draw_point2d(image, torch.tensor([[1, 2], [4, 3]], device=x.device), color)
+
+
+_SCRIPTABLE_CALLERS = [
+ _call_utils_create_meshgrid,
+ _call_utils_create_meshgrid3d,
+ _call_utils_one_hot,
+ _call_utils_draw_rectangle,
+ _call_utils_torch_meshgrid,
+ _call_utils_safe_inverse_with_mask,
+ _call_utils_eye_like,
+ _call_utils_vec_like,
+ _call_utils_draw_point2d,
+ _call_create_meshgrid,
+ _call_create_meshgrid3d,
+ _call_one_hot,
+ _call_draw_rectangle,
+ _call_eye_like,
+ _call_vec_like,
+ _call_draw_point2d,
+]
+
+# The callers whose replacement compiles with ``fullgraph=True`` (the draw functions read tensor values back).
+_COMPILABLE_CALLERS = [
+ _call_utils_create_meshgrid,
+ _call_utils_create_meshgrid3d,
+ _call_utils_one_hot,
+ _call_utils_torch_meshgrid,
+ _call_utils_safe_inverse_with_mask,
+ _call_utils_eye_like,
+ _call_utils_vec_like,
+ _call_create_meshgrid,
+ _call_one_hot,
+]
+
+
+def _invertible(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ return torch.eye(3, device=device, dtype=dtype) * 2 + torch.arange(9, device=device, dtype=dtype).view(3, 3) / 16
+
+
+class TestShimsUnderScriptAndCompile(BaseTester):
+ """Code that calls a shim scripts and compiles as it did with the 0.8.2 function (#5901)."""
+
+ @pytest.mark.parametrize("caller", _SCRIPTABLE_CALLERS, ids=lambda f: f.__name__[len("_call_") :])
+ def test_jit_script_of_code_calling_a_shim(self, caller, device, dtype):
+ x = _invertible(device, dtype)[None].repeat(2, 1, 1)
+ with warnings.catch_warnings():
+ # The shim's DeprecationWarning in eager, and torch.jit.script's own FutureWarning on torch >= 2.10.
+ warnings.simplefilter("ignore")
+ expected = _outcome(caller, (x,), {})
+ if expected[0] == "raised":
+ pytest.skip(f"the replacement itself raises here: {expected[1].__name__}: {expected[2]}")
+ scripted = torch.jit.script(caller)
+ self.assert_close(scripted(x), expected[1], rtol=0, atol=0)
+
+ @pytest.mark.parametrize("caller", _COMPILABLE_CALLERS, ids=lambda f: f.__name__[len("_call_") :])
+ def test_compile_fullgraph_of_code_calling_a_shim(self, caller, device, dtype, torch_optimizer):
+ x = _invertible(device, dtype)[None].repeat(2, 1, 1)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ expected = _outcome(caller, (x,), {})
+ if expected[0] == "raised":
+ pytest.skip(f"the replacement itself raises here: {expected[1].__name__}: {expected[2]}")
+ compiled = torch_optimizer(caller, fullgraph=True)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ got = compiled(x)
+ self.assert_close(got, expected[1])
+ assert not [w for w in caught if issubclass(w.category, DeprecationWarning) and "kornia" in str(w.message)]
+ # Eager calls still warn, once each.
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ caller(x)
+ assert len([w for w in caught if issubclass(w.category, DeprecationWarning)]) == 1
+
+
+def _checkpoint(n: int = 6) -> io.BytesIO:
+ buf = io.BytesIO()
+ torch.save({f"t{i}": torch.full((2,), float(i)) for i in range(n)}, buf)
+ buf.seek(0)
+ return buf
+
+
+def _map_location_warnings(caught: list[warnings.WarningMessage]) -> list[tuple[str, int]]:
+ return [
+ (w.filename, w.lineno)
+ for w in caught
+ if issubclass(w.category, DeprecationWarning) and "`map_location_to_cpu`" in str(w.message)
+ ]
+
+
+class TestMapLocationToCpuUnderTorchLoad:
+ """``torch.load`` calls the hook once per storage, from inside torch (#5905).
+
+ Every storage warns at the line that called ``torch.load``, so the default filters show that line once.
+ """
+
+ @pytest.mark.parametrize("weights_only", [True, False])
+ def test_every_storage_warns_at_the_callers_line(self, weights_only):
+ buf = _checkpoint()
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ state = torch.load(buf, map_location=utils.map_location_to_cpu, weights_only=weights_only)
+ line = sys._getframe().f_lineno - 1
+ assert len(state) == 6
+ assert _map_location_warnings(caught) == [(__file__, line)] * 6
+
+ def test_default_action_shows_the_callers_line_once(self):
+ buf = _checkpoint()
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("default")
+ for _ in range(3):
+ buf.seek(0)
+ torch.load(buf, map_location=utils.map_location_to_cpu, weights_only=True)
+ line = sys._getframe().f_lineno - 1
+ assert _map_location_warnings(caught) == [(__file__, line)]
+
+ @pytest.mark.parametrize("weights_only", [True, False])
+ def test_error_filter_raises_out_of_torch_load(self, weights_only):
+ buf = _checkpoint()
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", DeprecationWarning)
+ with pytest.raises(DeprecationWarning, match="`map_location_to_cpu`"):
+ torch.load(buf, map_location=utils.map_location_to_cpu, weights_only=weights_only)
+
+ def test_kornia_frames_between_the_caller_and_torch_load_are_skipped(self):
+ # kornia.core.download.load_state_dict_from_url, for one, forwards map_location to torch.load
+ loader = types.ModuleType("kornia._map_location_probe")
+ source = "import torch\ndef load(buf, ml):\n return torch.load(buf, map_location=ml, weights_only=True)\n"
+ exec(source, vars(loader)) # noqa: S102 a fixed literal
+ buf = _checkpoint()
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ loader.load(buf, utils.map_location_to_cpu)
+ line = sys._getframe().f_lineno - 1
+ assert _map_location_warnings(caught) == [(__file__, line)] * 6
+
+ def test_shown_under_the_default_filters(self):
+ result = _run_fresh(
+ """
+ import io
+
+ import torch
+
+ import kornia
+ import kornia.utils
+
+ print(kornia.__file__)
+ buf = io.BytesIO()
+ torch.save({f"t{i}": torch.full((2,), float(i)) for i in range(6)}, buf)
+ buf.seek(0)
+ state = torch.load(buf, map_location=kornia.utils.map_location_to_cpu, weights_only=True)
+ print(len(state))
+ """
+ )
+ assert result.returncode == 0, result.stderr
+ assert _same_kornia(result.stdout.splitlines()[0])
+ assert result.stdout.splitlines()[1] == "6"
+ shown = [line for line in result.stderr.splitlines() if "DeprecationWarning" in line]
+ assert len(shown) == 1, result.stderr
+ assert shown[0].startswith("<string>:13: DeprecationWarning: ")
+ assert "`map_location_to_cpu`" in shown[0]