Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): convert nested dataclass fields in dict_to_dataclass, store integer module state as buffers (#5910)

Dmytro Mishkin0febf67835ba
diff --git a/changelog.d/5910.breaking.md b/changelog.d/5910.breaking.md
new file mode 100644
index 000000000..e62f12a74
--- /dev/null
+++ b/changelog.d/5910.breaking.md
@@ -0,0 +1,14 @@
+`kornia.core.utils.dict_to_dataclass` now raises `TypeCheckError` for a value that is neither a dict nor an instance
+of the dataclass its annotation names, wherever the annotation names it: a list or tuple element, a dict value, or a
+field whose annotation is a string, which includes every field of a module with `from __future__ import annotations`.
+Such values used to pass through unchanged; a field annotated with the dataclass class itself already raised. For
+example, `[5]` for a `List[Inner]` field, `["x", 2]` for a `Tuple[Inner, int]` field, `{"k": 5}` for a
+`Dict[str, Inner]` field and `None` for a `"Inner"` field used to be stored as given and now raise, and in a module
+with `from __future__ import annotations` the round trip of a `sub: Sub = None` default through `dataclass_to_dict`
+now raises: annotate the field `Optional[Sub]`.
+
+`ParametrizedLine`, `So2`, `Se2` and `Se3` given an integer or bool tensor now raise `TypeCheckError` at construction,
+naming the field and its dtype; cast the tensor to a floating-point dtype first. In eager mode they used to raise torch's
+"Only Tensors of floating point and complex dtype can require gradients" `RuntimeError`. Under `torch.compile`,
+`torch.jit.trace` and export they used to keep the integer tensor as a plain attribute, and now raise as well.
+`Hyperplane` still stores integer coefficients as buffers.
diff --git a/changelog.d/5910.fixed.md b/changelog.d/5910.fixed.md
new file mode 100644
index 000000000..c79c38aa4
--- /dev/null
+++ b/changelog.d/5910.fixed.md
@@ -0,0 +1,5 @@
+`kornia.core.utils.dict_to_dataclass` now converts nested dicts in fields annotated `Optional[...]`, other unions,
+`list`, `tuple` and `dict` of a dataclass, and in string annotations (including modules with
+`from __future__ import annotations`), and keeps a value that is already an instance of the field's dataclass
+instead of raising `TypeCheckError`. The API reference now renders the `kornia.core.utils` device and autocast
+helpers that the `kornia.utils` deprecation warnings point to.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index fe2017648..54565b9d3 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -132,9 +132,9 @@ The following example only illustrates the method signatures, not an invertible
import torch
from torch import Tensor
- import kornia as K
from kornia.augmentation import GeometricAugmentationBase2D
from kornia.augmentation import random_generator as rg
+ from kornia.core.ops import eye_like
class MyRandomTransform(GeometricAugmentationBase2D):
@@ -151,7 +151,7 @@ The following example only illustrates the method signatures, not an invertible
def compute_transformation(self, input, params, flags):
# return the (B, 3, 3) transform matrix for this augmentation
# identity shown only to illustrate the required matrix shape
- return K.eye_like(3, input)
+ return eye_like(3, input)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/docs/source/core.rst b/docs/source/core.rst
index 3febf5baa..bca269aa5 100644
--- a/docs/source/core.rst
+++ b/docs/source/core.rst
@@ -12,6 +12,17 @@ kornia.core
.. autofunction:: kornia.core.utils.batched_forward
+Device and autocast helpers
+---------------------------
+
+.. autofunction:: kornia.core.utils.get_cuda_device_if_available
+
+.. autofunction:: kornia.core.utils.get_mps_device_if_available
+
+.. autofunction:: kornia.core.utils.get_cuda_or_mps_device_if_available
+
+.. autofunction:: kornia.core.utils.is_autocast_enabled
+
Weights
-------
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 244469e1f..e9253697a 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -19,8 +19,10 @@
import importlib.util
import platform
import sys
+from collections.abc import Mapping, Sequence
from dataclasses import asdict, fields, is_dataclass
-from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union
+from types import UnionType
+from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, get_args, get_origin, get_type_hints
import torch
import torch.nn.functional as F
@@ -687,17 +689,28 @@ def is_exporting() -> bool:
def register_module_state(module: torch.nn.Module, name: str, x: torch.Tensor) -> None:
"""Store tensor ``x`` on ``module`` as ``name`` so it is optimizable, movable and serializable.
- An existing ``nn.Parameter`` is kept, and a tensor that takes no part in autograd (no
- ``grad_fn`` and ``requires_grad=False``) becomes an ``nn.Parameter``, so the module is
- optimizable. ``nn.Parameter(x)`` would re-root any other tensor as a new leaf: a group built
- from ``Se3.exp(v)`` would stop propagating gradients to ``v``, and a group built from the
- caller's own leaf that requires grad would take its gradient away from that leaf. Such a
- tensor is registered as a buffer instead, which keeps it and its history while ``.to()``,
- ``state_dict()`` and ``load_state_dict()`` still reach it under the same key. Under graph
- capture (``torch.jit.trace``, ``torch.compile``, ``torch.export`` and the dynamo ONNX
- exporter) neither a parameter nor a buffer can be created inside the traced region, so the
- tensor is kept as a plain attribute of the module being built.
+ ``x`` must be a floating-point or complex tensor, or an existing ``nn.Parameter``: an integer or bool tensor can
+ neither require grad nor follow the module's dtype conversions, so it raises ``TypeCheckError`` naming its dtype.
+ An existing ``nn.Parameter`` is kept, and a tensor that takes no part in autograd (no ``grad_fn`` and
+ ``requires_grad=False``) becomes an ``nn.Parameter``, so the module is optimizable. ``nn.Parameter(x)`` would
+ re-root any other tensor as a new leaf: a group built from ``Se3.exp(v)`` would stop propagating gradients to
+ ``v``, and a group built from the caller's own leaf that requires grad would take its gradient away from that
+ leaf. Such a tensor is registered as a buffer instead, which keeps it and its history while ``.to()``,
+ ``state_dict()`` and ``load_state_dict()`` still reach it under the same key. Under graph capture
+ (``torch.jit.trace``, ``torch.compile``, ``torch.export`` and the dynamo ONNX exporter) neither a parameter nor a
+ buffer can be created inside the traced region, so the tensor is kept as a plain attribute of the module being
+ built.
+
+ Raises:
+ TypeCheckError: if ``x`` is neither a floating-point nor a complex tensor, nor an ``nn.Parameter``.
+
"""
+ if not (isinstance(x, torch.nn.Parameter) or x.is_floating_point() or x.is_complex()):
+ raise TypeCheckError(
+ f"{type(module).__name__} stores {name.lstrip('_')!r} as module state, which needs a floating-point or "
+ f"complex tensor; got {x.dtype}. Cast it first, for example with `.float()`.",
+ actual_type=x.dtype,
+ )
if isinstance(x, torch.nn.Parameter) or not (torch.jit.is_tracing() or is_compiling() or is_exporting()):
if isinstance(x, torch.nn.Parameter) or (x.grad_fn is None and not x.requires_grad):
x = x if isinstance(x, torch.nn.Parameter) else torch.nn.Parameter(x)
@@ -708,7 +721,14 @@ def register_module_state(module: torch.nn.Module, name: str, x: torch.Tensor) -
def dataclass_to_dict(obj: Any) -> Any:
- """Recursively convert dataclass instances to dictionaries."""
+ """Recursively convert dataclass instances to dictionaries.
+
+ A dataclass becomes a dict of its fields through :func:`dataclasses.asdict`, and lists, tuples,
+ namedtuples and dicts are rebuilt with their items converted; any other value is returned as it is.
+ Values reached through a dataclass are deep-copied by :func:`dataclasses.asdict`, tensors included,
+ so a tensor with autograd history (not a leaf) raises ``RuntimeError``. Outside any dataclass the
+ containers are rebuilt, but their items are not copied.
+ """
if is_dataclass(obj) and not isinstance(obj, type):
return {key: dataclass_to_dict(value) for key, value in asdict(obj).items()}
if isinstance(obj, tuple) and hasattr(obj, "_fields"):
@@ -724,18 +744,86 @@ def dataclass_to_dict(obj: Any) -> Any:
T = TypeVar("T")
+def _is_sequence_of(value: Any, origin: type) -> bool:
+ """Whether ``value`` is a list or tuple that ``dict_to_dataclass`` converts for a sequence annotation."""
+ return type(value) in (list, tuple) and issubclass(origin, Sequence) and not issubclass(origin, (str, bytes))
+
+
+def _fits_annotation(value: Any, annotation: Any) -> bool:
+ """Whether ``value`` can be held by ``annotation``, as ``dict_to_dataclass`` converts it."""
+ target = get_origin(annotation) or annotation
+ if annotation is Any or not isinstance(target, type):
+ return True # Any, a TypeVar, a Literal, ...: the value cannot be ruled out
+ if is_dataclass(target):
+ return isinstance(value, (dict, target))
+ try:
+ return _is_sequence_of(value, target) or isinstance(value, target)
+ except TypeError: # a class that rejects isinstance, such as a Protocol that is not runtime-checkable
+ return True
+
+
+def _value_for_annotation(value: Any, annotation: Any) -> Any:
+ """Return ``value`` with each dict that ``annotation`` types as a dataclass converted to that dataclass."""
+ if isinstance(annotation, type) and is_dataclass(annotation):
+ return value if isinstance(value, annotation) else dict_to_dataclass(value, annotation)
+ origin, args = get_origin(annotation), get_args(annotation)
+ if origin is Union or origin is UnionType:
+ # Optional[X] and other unions: follow the one member that can hold the value, if there is exactly one
+ fitting = [arg for arg in args if _fits_annotation(value, arg)]
+ return _value_for_annotation(value, fitting[0]) if len(fitting) == 1 else value
+ if not (isinstance(origin, type) and args):
+ return value
+ if _is_sequence_of(value, origin):
+ if origin is tuple and args[-1] is not Ellipsis: # Tuple[X, Y]: one annotation per position
+ if len(args) != len(value):
+ return value
+ return type(value)(_value_for_annotation(item, arg) for item, arg in zip(value, args))
+ return type(value)(_value_for_annotation(item, args[0]) for item in value)
+ if type(value) is dict and issubclass(origin, Mapping) and len(args) == 2:
+ return {key: _value_for_annotation(item, args[1]) for key, item in value.items()}
+ return value
+
+
def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:
- """Recursively convert dictionaries to dataclass instances."""
+ """Recursively convert dictionaries to dataclass instances.
+
+ A field annotated with a dataclass gets its dict value converted to that dataclass, and so does a
+ dataclass inside the field's ``Optional[...]`` or other union, the elements of a plain ``list`` or ``tuple``
+ value under a sequence annotation, or the values of a plain ``dict`` value under a mapping annotation (a
+ namedtuple or a ``dict`` subclass is kept whole). String annotations, including every annotation
+ in a module with ``from __future__ import annotations``, are resolved with :func:`typing.get_type_hints`.
+ A value that is already an instance of the annotated dataclass is kept as it is, and values of other
+ fields are passed on unchanged.
+
+ A union is followed only when exactly one of its members can hold the value: a dict for a
+ ``Union[A, B]`` of two dataclasses, or for ``Union[A, dict]``, stays a dict. When the annotations
+ cannot be resolved, for example a string that names a class defined inside a function, they are used
+ as written, and a string annotation converts nothing.
+
+ Args:
+ dict_obj: the field values, keyed by field name.
+ dataclass_type: the dataclass to build.
+
+ Returns:
+ An instance of ``dataclass_type``.
+
+ Raises:
+ TypeCheckError: if ``dict_obj`` is not a dict, or a value annotated with a dataclass outside a union
+ is neither a dict nor an instance of that dataclass.
+ BaseError: if ``dataclass_type`` is not a dataclass.
+
+ """
KORNIA_CHECK_TYPE(dict_obj, dict, "Input conf must be dict")
KORNIA_CHECK(is_dataclass(dataclass_type), "dataclass_type must be a dataclass")
- field_types: dict[str, Any] = {f.name: f.type for f in fields(dataclass_type)}
- constructor_args = {}
- for key, value in dict_obj.items():
- if key in field_types and is_dataclass(field_types[key]):
- constructor_args[key] = dict_to_dataclass(value, field_types[key])
- else:
- constructor_args[key] = value
- # TODO: remove type ignore when https://github.com/python/mypy/issues/14941 be andressed
+ try:
+ hints = get_type_hints(dataclass_type)
+ except (AttributeError, NameError, SyntaxError, TypeError):
+ hints = {}
+ field_types: dict[str, Any] = {f.name: hints.get(f.name, f.type) for f in fields(dataclass_type)}
+ constructor_args = {
+ key: _value_for_annotation(value, field_types[key]) if key in field_types else value
+ for key, value in dict_obj.items()
+ }
return dataclass_type(**constructor_args)
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 870343add..ae83d5924 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -94,6 +94,9 @@ class Se2(nn.Module):
translation: translation torch.Tensor with the shape of :math:`(B, 2)`, or a Vector2 wrapping one; the
tensor is what gets stored.
+ Raises:
+ TypeCheckError: if the translation is an integer or bool tensor.
+
Example:
>>> so2 = So2.identity(1)
>>> t = torch.ones((1, 2))
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 96676e1b4..ee7e91274 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -78,6 +78,9 @@ class Se3(nn.Module):
translation: translation torch.Tensor with the shape of :math:`(B, 3)`, or a Vector3 wrapping one; the
tensor is what gets stored.
+ Raises:
+ TypeCheckError: if the translation is an integer or bool tensor.
+
Example:
>>> from kornia.geometry.quaternion import Quaternion
>>> q = Quaternion.identity(batch_size=1)
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index de5347e28..bb82644ca 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -74,6 +74,9 @@ class So2(nn.Module):
Args:
z: Complex number with the shape of :math:`(B,)` or :math:`()`; :math:`(B, 1)` is read as :math:`(B,)`.
+ Raises:
+ TypeCheckError: if ``z`` is an integer or bool tensor.
+
Example:
>>> real = torch.tensor(0.6)
>>> imag = torch.tensor(0.8)
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index b632989ba..c02e7fb9b 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -60,6 +60,9 @@ class ParametrizedLine(nn.Module):
origin: any point on the line of any dimension.
direction: the direction vector of the line, of the same dimension.
+ Raises:
+ TypeCheckError: if ``origin`` or ``direction`` is an integer or bool tensor.
+
Example:
>>> o = torch.tensor([0.0, 0.0])
>>> d = torch.tensor([0.6, 0.8])
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 5133f1a7c..c345509f9 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -53,7 +53,7 @@ class Hyperplane(nn.Module):
an ``nn.Parameter``: a plane built from plain tensors, including the result of :meth:`through` and
:func:`fit_plane` on points without autograd history, has trainable parameters, and the distances and
projections it returns require grad. A caller's ``nn.Parameter`` is kept, a tensor with autograd history
- keeps that history, and an integer tensor is stored as a buffer.
+ keeps that history, and an integer tensor is stored as a buffer (ParametrizedLine rejects one).
Args:
n: The normal vector :math:`n`, a :class:`~kornia.geometry.vector.Vector3`.
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index 8a08e480a..c4f63f312 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -410,6 +410,30 @@ class TestExportHelpers:
moved.y.sum().backward()
assert_close(v.grad, torch.full_like(v, 2.0))
+ @pytest.mark.parametrize("state_dtype", [torch.int64, torch.int32, torch.uint8, torch.bool])
+ def test_register_module_state_rejects_non_floating(self, device, state_dtype):
+ # Only a floating-point or complex tensor can be optimizable state: any other dtype raises a kornia error
+ # that names it, instead of torch's autograd RuntimeError (#5201).
+ m = torch.nn.Module()
+ x = torch.tensor([1, 0, 1], device=device).to(state_dtype)
+ with pytest.raises(TypeCheckError, match=f"got {state_dtype}") as err:
+ register_module_state(m, "_x", x)
+ assert err.value.actual_type == state_dtype
+ assert not hasattr(m, "_x")
+
+ def test_register_module_state_keeps_an_integer_parameter(self, device):
+ # A caller's own nn.Parameter is kept whatever its dtype, as before the dtype check.
+ m = torch.nn.Module()
+ p = torch.nn.Parameter(torch.tensor([1, 2], device=device), requires_grad=False)
+ register_module_state(m, "p", p)
+ assert m.p is p
+
+ def test_register_module_state_complex_leaf_is_parameter(self, device):
+ m = torch.nn.Module()
+ register_module_state(m, "z", torch.tensor([0.6 + 0.8j], device=device))
+ assert isinstance(m.z, torch.nn.Parameter)
+ assert m.z.dtype == torch.complex64
+
class TestHistcCast(BaseTester):
def test_smoke(self, device, dtype):
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 0b50c13dc..018c4913a 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -20,6 +20,7 @@ import math
import pytest
import torch
+from kornia.core.exceptions import TypeCheckError
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
@@ -405,6 +406,12 @@ class TestSe2(BaseTester):
self.assert_close(t.grad, torch.ones_like(t))
assert "_translation" in s.state_dict()
+ def test_integer_translation_raises(self, device):
+ # An integer translation cannot be optimizable state: a kornia error names its dtype instead of torch's
+ # autograd error (#5201). Cast it to a floating-point dtype first.
+ with pytest.raises(TypeCheckError, match=r"Se2 stores 'translation'.*torch.int64"):
+ Se2(So2.identity(1, device), torch.tensor([[1, 2]], device=device))
+
def test_derived_state_moves_and_serializes(self, device, dtype):
# A group built from a tensor with autograd history keeps that history; its state must
# still be registered so ``state_dict`` and ``.to()`` / ``.double()`` reach it.
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index bdb4efab7..d7cdd0d9f 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -20,6 +20,7 @@ import math
import pytest
import torch
+from kornia.core.exceptions import TypeCheckError
from kornia.geometry.conversions import euler_from_quaternion, rotation_matrix_to_quaternion
from kornia.geometry.liegroup import Se3, So3
from kornia.geometry.quaternion import Quaternion
@@ -422,6 +423,10 @@ class TestSe3(BaseTester):
plain = Se3(So3.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))
assert [name for name, _ in plain.named_parameters()] == ["_translation"]
+ def test_integer_translation_raises(self, device):
+ with pytest.raises(TypeCheckError, match=r"Se3 stores 'translation'.*torch.int64"):
+ Se3(Quaternion.identity(1, device), torch.tensor([[1, 2, 3]], device=device))
+
def test_derived_state_moves_and_serializes(self, device, dtype):
v = torch.rand(2, 6, device=device, dtype=dtype, requires_grad=True)
s = Se3.exp(v)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index bbbb89792..3bf153d95 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -20,6 +20,7 @@ import math
import pytest
import torch
+from kornia.core.exceptions import TypeCheckError
from kornia.geometry.conversions import angle_to_rotation_matrix
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
@@ -33,6 +34,11 @@ class TestSo2(BaseTester):
shape = input_shape[1:] if batch_size is None else input_shape
return torch.rand(shape, device=device, dtype=dtype)
+ def test_integer_z_raises(self, device):
+ # So2 needs a complex z; an integer one gets a kornia error naming its dtype at construction (#5201).
+ with pytest.raises(TypeCheckError, match=r"So2 stores 'z'.*torch.int64"):
+ So2(torch.tensor([1], device=device))
+
@pytest.mark.parametrize("cdtype", [torch.cfloat, torch.cdouble])
def test_smoke(self, device, cdtype):
z = torch.randn(2, 1, dtype=cdtype, device=device)
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 60de64dd0..5a769c439 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -373,6 +373,19 @@ class TestParametrizedLine(BaseTester):
# a tensor that does not require grad still becomes an optimizable parameter
plain = ParametrizedLine(origin.detach().clone(), direction.detach().clone())
assert [name for name, _ in plain.named_parameters()] == ["_origin", "_direction"]
+ plain.point_at(2.0).sum().backward()
+ self.assert_close(plain.origin.grad, torch.ones_like(origin))
+ self.assert_close(plain.direction.grad, torch.full_like(direction, 2.0))
+
+ def test_integer_input_raises(self, device):
+ # An integer origin or direction cannot be optimizable state: the constructor names the dtype instead of
+ # raising torch's autograd error (#5201). Cast it to a floating-point dtype first.
+ integer = torch.tensor([0, 0], device=device)
+ floating = torch.tensor([1.0, 0.0], device=device)
+ with pytest.raises(TypeCheckError, match=r"ParametrizedLine stores 'origin'.*torch.int64"):
+ ParametrizedLine(integer, floating)
+ with pytest.raises(TypeCheckError, match=r"ParametrizedLine stores 'direction'.*torch.int64"):
+ ParametrizedLine(floating, integer)
def _near_vertical_points_5040(device, dtype) -> torch.Tensor:
diff --git a/tests/utils/test_dataclass_to_dict.py b/tests/utils/test_dataclass_to_dict.py
index bbe6604c2..9f5ad377c 100644
--- a/tests/utils/test_dataclass_to_dict.py
+++ b/tests/utils/test_dataclass_to_dict.py
@@ -16,10 +16,17 @@
#
# TEST OFFICIAL SUPPORT
+import importlib.util
+import sys
from dataclasses import dataclass, field
-from typing import Any, NamedTuple
+from typing import Annotated, Any, Dict, List, NamedTuple, Optional, Tuple, Union
-from kornia.core.utils import dataclass_to_dict
+import pytest
+import torch
+
+from kornia.core.exceptions import TypeCheckError
+from kornia.core.utils import dataclass_to_dict, dict_to_dataclass
+from kornia.feature.sold2.structures import DetectorCfg, LineDetectorCfg
class Point(NamedTuple):
@@ -69,3 +76,198 @@ def test_namedtuple_items_are_converted():
# a namedtuple reached outside `asdict` (top level, in a list or a dict) still has its items converted
assert dataclass_to_dict(Pair(Inner(1), [Inner(2)])) == Pair({"v": 1}, [{"v": 2}])
assert dataclass_to_dict({"k": [Pair(Inner(3), 4)]}) == {"k": [Pair({"v": 3}, 4)]}
+
+
+def test_values_reached_through_a_dataclass_are_deep_copied():
+ t = torch.zeros(2)
+ got = dataclass_to_dict(Outer(Inner(1), [t]))
+ assert got["points"][0] is not t
+ assert got["points"][0].data_ptr() != t.data_ptr()
+ # outside any dataclass the containers are rebuilt and their items returned as they are
+ assert dataclass_to_dict({"k": [t]})["k"][0] is t
+
+
+@dataclass
+class Holder:
+ inner: Inner = field(default_factory=lambda: Inner(0))
+ maybe: Optional[Inner] = None
+ either: Union[Inner, str, None] = None
+ pep604: Inner | None = None
+ many: List[Inner] = field(default_factory=list)
+ builtin_many: list[Inner] = field(default_factory=list)
+ nested: List[List[Inner]] = field(default_factory=list)
+ maybe_many: Optional[List[Inner]] = None
+ maybe_variadic: Optional[Tuple[Inner, ...]] = None
+ text_or_many: Union[str, List[Inner]] = ""
+ variadic: Tuple[Inner, ...] = ()
+ fixed: Tuple[Inner, int] = (Inner(0), 0)
+ mapping: Dict[str, Inner] = field(default_factory=dict)
+ quoted: "Inner" = field(default_factory=lambda: Inner(0))
+ quoted_optional: "Optional[Inner]" = None
+ plain: Any = None
+ ambiguous: Union[Inner, dict] = None
+ fwd_many: List["Inner"] = field(default_factory=list)
+ annotated: Annotated[Inner, "meta"] = field(default_factory=lambda: Inner(0))
+
+
+def test_dict_to_dataclass_converts_optional_list_and_string_annotations():
+ # The repro of #5201: only the plain ``inner: Inner`` field used to be converted.
+ got = dict_to_dataclass({"inner": {"v": 1}, "maybe": {"v": 2}, "many": [{"v": 3}], "quoted": {"v": 4}}, Holder)
+ assert got == Holder(inner=Inner(1), maybe=Inner(2), many=[Inner(3)], quoted=Inner(4))
+
+
+def test_dict_to_dataclass_converts_through_unions_and_containers():
+ got = dict_to_dataclass(
+ {
+ "either": {"v": 1},
+ "pep604": {"v": 2},
+ "builtin_many": [{"v": 3}],
+ "nested": [[{"v": 4}], []],
+ "maybe_many": [{"v": 5}],
+ "maybe_variadic": [{"v": 12}], # a list, as JSON or YAML gives for a tuple
+ "text_or_many": [{"v": 13}],
+ "variadic": ({"v": 6}, {"v": 7}),
+ "fixed": [{"v": 8}, 9],
+ "mapping": {"a": {"v": 10}},
+ "quoted_optional": {"v": 11},
+ },
+ Holder,
+ )
+ assert got == Holder(
+ either=Inner(1),
+ pep604=Inner(2),
+ builtin_many=[Inner(3)],
+ nested=[[Inner(4)], []],
+ maybe_many=[Inner(5)],
+ maybe_variadic=[Inner(12)],
+ text_or_many=[Inner(13)],
+ variadic=(Inner(6), Inner(7)),
+ fixed=[Inner(8), 9],
+ mapping={"a": Inner(10)},
+ quoted_optional=Inner(11),
+ )
+
+
+def test_dict_to_dataclass_keeps_dataclass_instances_and_other_values():
+ inner = Inner(5)
+ got = dict_to_dataclass(
+ {"inner": inner, "maybe": Inner(6), "many": [Inner(7), {"v": 8}], "plain": {"v": 9}, "pep604": None}, Holder
+ )
+ assert got.inner is inner
+ assert got == Holder(inner=inner, maybe=Inner(6), many=[Inner(7), Inner(8)], plain={"v": 9})
+ # a value that does not match a fixed-length tuple annotation is kept whole
+ assert dict_to_dataclass({"fixed": [{"v": 1}, 2, 3]}, Holder).fixed == [{"v": 1}, 2, 3]
+
+
+def test_dict_to_dataclass_follows_a_union_only_when_one_member_fits():
+ got = dict_to_dataclass({"ambiguous": {"v": 1}, "maybe": 5}, Holder)
+ assert got.ambiguous == {"v": 1}
+ assert got.maybe == 5
+
+
+def test_dict_to_dataclass_rejects_other_values_for_a_dataclass_field():
+ # A position annotated with a dataclass takes a dict or an instance, whatever the annotation style or container.
+ for value in ({"inner": 5}, {"many": [5]}, {"fixed": ["x", 2]}, {"mapping": {"a": 5}}, {"quoted": None}):
+ with pytest.raises(TypeCheckError):
+ dict_to_dataclass(value, Holder)
+
+
+def test_dict_to_dataclass_resolves_nested_forward_refs_and_annotated():
+ got = dict_to_dataclass({"fwd_many": [{"v": 1}], "annotated": {"v": 2}}, Holder)
+ assert got.fwd_many == [Inner(1)]
+ assert got.annotated == Inner(2)
+
+
+def test_dict_to_dataclass_keeps_a_namedtuple_value_whole():
+ # only a plain list or tuple is rebuilt: a namedtuple's constructor takes one argument per field
+ assert dict_to_dataclass({"fixed": Pair({"v": 1}, 2)}, Holder).fixed == Pair({"v": 1}, 2)
+ assert dict_to_dataclass({"variadic": Point(1, 2)}, Holder).variadic == Point(1, 2)
+
+
+def test_dict_to_dataclass_round_trips_dataclass_to_dict():
+ holder = Holder(
+ inner=Inner(1),
+ maybe=Inner(2),
+ pep604=Inner(3),
+ many=[Inner(4)],
+ nested=[[Inner(5)]],
+ variadic=(Inner(6),),
+ fixed=(Inner(7), 8),
+ mapping={"a": Inner(9)},
+ quoted=Inner(10),
+ quoted_optional=Inner(11),
+ )
+ assert dict_to_dataclass(dataclass_to_dict(holder), Holder) == holder
+
+
+_POSTPONED_SOURCE = """
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class Leaf:
+ v: int = 0
+
+
+@dataclass
+class Tree:
+ leaf: Leaf = field(default_factory=Leaf)
+ maybe: Optional[Leaf] = None
+ leaves: list[Leaf] = field(default_factory=list)
+
+
+@dataclass
+class NoneDefault:
+ sub: Leaf = None
+"""
+
+
+def _load_postponed_module(tmp_path, monkeypatch):
+ path = tmp_path / "_kornia_test_postponed_dataclasses.py"
+ path.write_text(_POSTPONED_SOURCE)
+ spec = importlib.util.spec_from_file_location(path.stem, path)
+ module = importlib.util.module_from_spec(spec)
+ monkeypatch.setitem(sys.modules, path.stem, module)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_dict_to_dataclass_resolves_postponed_annotations(tmp_path, monkeypatch):
+ # With ``from __future__ import annotations`` every annotation is a string, including a plain ``Leaf``.
+ module = _load_postponed_module(tmp_path, monkeypatch)
+ tree = dict_to_dataclass({"leaf": {"v": 1}, "maybe": {"v": 2}, "leaves": [{"v": 3}]}, module.Tree)
+ assert tree == module.Tree(module.Leaf(1), module.Leaf(2), [module.Leaf(3)])
+
+
+def test_dict_to_dataclass_postponed_none_for_a_dataclass_field_raises(tmp_path, monkeypatch):
+ # ``sub: Leaf = None`` resolves to ``Leaf``, which takes a dict or an instance: None used to pass through while
+ # the annotation stayed a string, and now raises like it does for a field annotated with the class itself.
+ module = _load_postponed_module(tmp_path, monkeypatch)
+ with pytest.raises(TypeCheckError):
+ dict_to_dataclass(dataclass_to_dict(module.NoneDefault()), module.NoneDefault)
+
+
+def test_dict_to_dataclass_unresolvable_annotation_is_used_as_written():
+ @dataclass
+ class Local:
+ v: int
+
+ @dataclass
+ class WithLocal:
+ local: "Local"
+ inner: Inner
+
+ got = dict_to_dataclass({"local": {"v": 1}, "inner": {"v": 2}}, WithLocal)
+ assert got.local == {"v": 1}
+ assert got.inner == Inner(2)
+
+
+def test_sold2_detector_config_round_trips():
+ cfg = DetectorCfg(grid_size=4, line_detector_cfg=LineDetectorCfg(detect_thresh=0.7, num_samples=32))
+ cfg.line_detector_cfg.heatmap_refine_cfg.ratio = 0.3
+ assert dict_to_dataclass(dataclass_to_dict(cfg), DetectorCfg) == cfg
+ partial = dict_to_dataclass({"line_detector_cfg": LineDetectorCfg(detect_thresh=0.7)}, DetectorCfg)
+ assert partial == DetectorCfg(line_detector_cfg=LineDetectorCfg(detect_thresh=0.7))