Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core)!: place converted images on module device and dtype (#5451)

Karnajeet Gosaviaef65df326b4
diff --git a/changelog.d/5451.breaking.md b/changelog.d/5451.breaking.md
new file mode 100644
index 000000000..07e47e366
--- /dev/null
+++ b/changelog.d/5451.breaking.md
@@ -0,0 +1,7 @@
+`ImageModule`, `ImageSequential` and `AugmentationSequential` with parameters or buffers now convert NumPy, PIL and
+image-path inputs onto the device of their first parameter (or first buffer) and the dtype of their first floating
+parameter or buffer. Previously a converted image was always created on the CPU, in the default dtype for an integer
+image and in its own dtype for a floating one: a module moved to CUDA or MPS raised a device-mismatch error, or
+returned a CPU output when its forward did not touch its state, and a `float64` NumPy image fed to a `float32` module
+gave a `float64` output where it now gives `float32`. NumPy masks, keypoints and boxes given to `AugmentationSequential`
+move to the same device and keep their dtype. Stateless modules, tensor inputs and the standalone mixin are unchanged.
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 6d1601592..ba1b70e3d 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -693,7 +693,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Arguments convert by data key, and only an image takes the image conversion. A mask given as a NumPy array,
a PIL image or an image file path keeps its dtype and label values, palette indices included. Every mask
- must match the image's height and width, with a batch size of 1 or the image's.
+ must match the image's height and width, with a batch size of 1 or the image's. Arguments converted from NumPy
+ go to the container's device when it has parameters or buffers, as the image does.
Args:
inputs: Inputs to operate on.
@@ -770,10 +771,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if _is_numpy_array(arg):
if not arg.dtype.isnative: # torch.from_numpy rejects big-endian data, such as PIL's "I;16B" mode
arg = arg.astype(arg.dtype.newbyteorder("="))
- return image_to_tensor(arg)
+ return self._to_module_device(image_to_tensor(arg))
return arg
if _is_numpy_array(arg):
- return torch.as_tensor(arg)
+ return self._to_module_device(torch.as_tensor(arg))
return arg
def _select_output_image(
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 9b9148425..55e022706 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -87,9 +87,13 @@ class ImageModuleMixIn:
or :math:`(B, H, W, C)`, a PIL image or an image path becomes a :math:`(C, H, W)` or :math:`(B, C, H, W)` tensor.
An integer image is scaled by the maximum of its dtype (``uint8`` by 255, ``uint16`` by 65535; a signed image keeps
its negative values), a ``bool`` image becomes 0 and 1, and a floating image keeps its values. Tensors pass through
- unchanged. ``output_type="numpy"`` returns channels-last arrays with the values of the output tensor, so a floating
- output fed back in converts to the same tensor. ``output_type="pil"``, :meth:`show` and :meth:`save` clamp a
- floating image to ``[0, 1]`` and round it to 8 bits on the CPU, and pass a ``uint8`` image through with its values.
+ unchanged. For an :class:`torch.nn.Module` with state, converted inputs use the device of its first parameter (or
+ first buffer when it has no parameters) and the dtype of its first floating parameter or buffer, falling back to
+ the default floating dtype when none exists. A module without state and a standalone mixin keep the CPU and
+ default floating dtype. ``output_type="numpy"`` returns
+ channels-last arrays with the values of the output tensor, so a floating output fed back in converts to the same
+ tensor. ``output_type="pil"``, :meth:`show` and :meth:`save` clamp a floating image to ``[0, 1]`` and round it to
+ 8 bits on the CPU, and pass a ``uint8`` image through with its values.
"""
_output_image: Any
@@ -248,8 +252,9 @@ class ImageModuleMixIn:
``PA``) is converted to RGB, or RGBA when it has transparency, first. An integer image is divided by the maximum
of its dtype (``uint8`` by 255, ``uint16`` by 65535, a PIL mode ``I`` image by the ``int32`` maximum); a signed
image maps to ``[iinfo.min / iinfo.max, 1]``, so its negative values stay negative. A ``bool`` image becomes 0
- and 1, and a floating image keeps its values; integer and ``bool`` images become the default floating dtype. A
- tensor is returned unchanged.
+ and 1, and a floating image keeps its values; integer and ``bool`` images become the default floating dtype.
+ When this mixin belongs to a stateful :class:`torch.nn.Module`, the converted image is moved to the module's
+ device and first floating parameter or buffer dtype. A tensor is returned unchanged.
Args:
x: The input to convert.
@@ -261,16 +266,43 @@ class ImageModuleMixIn:
if isinstance(x, str):
from kornia.io import ImageLoadType, load_image # pylint: disable=C0415
- return _image_to_float(load_image(x, ImageLoadType.UNCHANGED))
- if isinstance(x, torch.Tensor):
+ image = _image_to_float(load_image(x, ImageLoadType.UNCHANGED))
+ elif isinstance(x, torch.Tensor):
return x
- if isinstance(x, np.ndarray): # type: ignore
- return _array_to_float_image(x)
- if isinstance(x, Image.Image): # type: ignore
+ elif isinstance(x, np.ndarray): # type: ignore
+ image = _array_to_float_image(x)
+ elif isinstance(x, Image.Image): # type: ignore
if x.mode in ("P", "PA"): # palette indices are not intensities
x = x.convert("RGBA" if x.mode == "PA" or "transparency" in x.info else "RGB")
- return _array_to_float_image(np.array(x)) # type: ignore
- raise TypeError("Input type not supported")
+ image = _array_to_float_image(np.array(x)) # type: ignore
+ else:
+ raise TypeError("Input type not supported")
+ return self._to_module_device_dtype(image)
+
+ def _module_state_reference(self) -> Optional[torch.Tensor]:
+ """Return the module's first parameter, else its first buffer, or None for a stateless module or a mixin."""
+ if not isinstance(self, torch.nn.Module):
+ return None
+ first_parameter = next(self.parameters(), None)
+ return first_parameter if first_parameter is not None else next(self.buffers(), None)
+
+ def _to_module_device(self, data: torch.Tensor) -> torch.Tensor:
+ """Move a tensor converted from a non-tensor input to the module's device, keeping its dtype."""
+ reference = self._module_state_reference()
+ return data if reference is None else data.to(reference.device)
+
+ def _to_module_device_dtype(self, image: torch.Tensor) -> torch.Tensor:
+ reference = self._module_state_reference()
+ if reference is None or not isinstance(self, torch.nn.Module):
+ return image
+ floating_dtype = next(
+ (parameter.dtype for parameter in self.parameters() if parameter.is_floating_point()), None
+ )
+ if floating_dtype is None:
+ floating_dtype = next((buffer.dtype for buffer in self.buffers() if buffer.is_floating_point()), None)
+ if floating_dtype is None:
+ floating_dtype = torch.get_default_dtype()
+ return image.to(device=reference.device, dtype=floating_dtype)
def to_numpy(self, x: Any) -> "np.array": # type: ignore
"""Convert input to numpy array.
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index cbbc9eead..8abd1ca54 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1575,6 +1575,33 @@ class TestConventionAugmentationSequential(BaseTester):
expected[..., 2:5, 6:8] = 3
assert torch.equal(out_mask, expected)
+ def test_numpy_annotations_follow_the_image_to_the_module_device_5207(self):
+ # A stateful container converts a NumPy image onto its device; NumPy masks, keypoints and boxes go to the
+ # same device and keep their dtype, so a mask keeps its labels. The meta device stands in for an accelerator.
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ aug.register_buffer("reference", torch.empty((), device="meta", dtype=torch.float64))
+ mask = aug._convert_non_image(np.zeros((8, 9, 1), dtype=np.int64), DataKey.MASK)
+ keypoints = aug._convert_non_image(np.zeros((1, 2, 2), dtype=np.float32), DataKey.KEYPOINTS)
+ boxes = aug._convert_non_image(np.zeros((1, 1, 4), dtype=np.float32), DataKey.BBOX_XYXY)
+ image = aug.to_tensor(np.zeros((8, 9, 3), dtype=np.uint8))
+ assert [x.device.type for x in (image, mask, keypoints, boxes)] == ["meta"] * 4
+ assert [x.dtype for x in (image, mask, keypoints, boxes)] == [torch.float64, torch.int64] + [torch.float32] * 2
+
+ def test_numpy_image_and_mask_run_on_the_module_device_5207(self, device):
+ # RandomBrightness holds buffers, so the container's NumPy image moves to its device; the mask must follow
+ # it, or the flip mixes devices.
+ image = np.zeros((8, 9, 3), dtype=np.uint8)
+ mask = np.zeros((8, 9), dtype=np.int64)
+ mask[2:5, 1:3] = 3
+ aug = K.AugmentationSequential(
+ K.RandomBrightness((1.0, 1.0), p=1.0), K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"]
+ ).to(device)
+ out_image, out_mask = aug(image, mask)
+ expected = torch.zeros(1, 1, 8, 9, dtype=torch.int64)
+ expected[..., 2:5, 6:8] = 3
+ assert out_image.device == out_mask.device == torch.device(device)
+ assert torch.equal(out_mask.cpu(), expected)
+
def test_argument_without_a_data_key_raises(self):
# ``__call__`` converts NumPy arguments by data key; an argument with no key must still reach ``forward``,
# which rejects the count, instead of being dropped.
diff --git a/tests/core/test_module.py b/tests/core/test_module.py
index ee9d01505..6fa7f3d99 100644
--- a/tests/core/test_module.py
+++ b/tests/core/test_module.py
@@ -484,6 +484,22 @@ class TestImageModuleConversions(BaseTester):
out = _Identity().to_tensor(image)
self.assert_close(out, torch.from_numpy(image).permute(2, 0, 1), rtol=0.0, atol=0.0)
+ @pytest.mark.parametrize("container", [ImageModule, ImageSequential, AugmentationImageSequential])
+ @pytest.mark.parametrize("state", ["parameter", "buffer"])
+ @pytest.mark.parametrize("dtype", [torch.float16, torch.float64])
+ def test_to_tensor_uses_module_device_and_dtype_5207(self, container, state, dtype):
+ module = container()
+ reference = torch.empty((), device="meta", dtype=dtype)
+ if state == "parameter":
+ module.register_parameter("reference", torch.nn.Parameter(reference))
+ else:
+ module.register_buffer("reference", reference)
+
+ image = np.full((2, 4, 3), 0.5, dtype=np.float32)
+ out = module.to_tensor(image)
+ assert out.device == torch.device("meta")
+ assert out.dtype == dtype
+
def test_to_tensor_maps_bool_numpy_to_zero_one_5207(self):
mask = np.array([[True, False, True], [False, True, False]])
out = _Identity().to_tensor(mask)