Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(color): register colormap colors as buffer (#5335)

NiteeshGowda72ea7ca896b917
diff --git a/changelog.d/5335.breaking.md b/changelog.d/5335.breaking.md
new file mode 100644
index 000000000..56ab1be32
--- /dev/null
+++ b/changelog.d/5335.breaking.md
@@ -0,0 +1,8 @@
+`ApplyColorMap` registers its palette as the buffer `colors`, so `.to(device, dtype)`, `.half()` and `.double()`
+move and convert it with the module, and `state_dict()` saves it. Previously the palette stayed where its `ColorMap`
+was built: forward on a module moved to MPS or CUDA raised a device-mismatch error, a converted module kept returning
+the palette's dtype (float32 after `.half()` or `.double()`), and `state_dict()` was empty. The output now follows
+the module's dtype, and `state_dict()` gains the `colors` key. A state dict saved by an earlier release still loads
+with `strict=True` and keeps the palette the module was built with; one saved by this release carries `colors` and
+fails `strict=True` on an earlier kornia, which does not know the key. `module.colormap` still holds the `ColorMap`
+as passed and is not moved by `.to()`. (#5317)
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 63fa029ba..cbd1e4102 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -18,7 +18,7 @@
from __future__ import annotations
from enum import Enum
-from typing import Optional, Union
+from typing import Any, Optional, Union
import torch
from torch import nn
@@ -216,6 +216,11 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tens
[0.0000, 0.0000, 0.0000]]]])
"""
+ return _apply_colormap(input_tensor, colormap.colors)
+
+
+def _apply_colormap(input_tensor: torch.Tensor, colors: torch.Tensor) -> torch.Tensor:
+ """Apply the palette ``colors`` of shape (3, N); shared by :func:`apply_colormap` and :class:`ApplyColorMap`."""
KORNIA_CHECK(
isinstance(input_tensor, torch.Tensor), f"`input_tensor` must be a torch.Tensor. Got: {type(input_tensor)}"
)
@@ -247,7 +252,7 @@ def apply_colormap(input_tensor: torch.Tensor, colormap: ColorMap) -> torch.Tens
)
input_tensor = input_tensor.float() / max_value
- colors = colormap.colors.permute(1, 0)
+ colors = colors.permute(1, 0)
num_colors, channels_cmap = colors.shape
keys = torch.linspace(0.0, 1.0, num_colors - 1, device=input_tensor.device, dtype=input_tensor.dtype)
indices = torch.bucketize(input_tensor, keys)
@@ -304,6 +309,24 @@ class ApplyColorMap(nn.Module):
) -> None:
super().__init__()
self.colormap = colormap
+ self.register_buffer("colors", colormap.colors)
+
+ def _load_from_state_dict(
+ self,
+ state_dict: dict[str, torch.Tensor],
+ prefix: str,
+ local_metadata: dict[str, Any],
+ strict: bool,
+ missing_keys: list[str],
+ unexpected_keys: list[str],
+ error_msgs: list[str],
+ ) -> None:
+ # State dicts saved before the palette became a buffer have no ``colors`` key. Keep the palette this
+ # module was built with, so they still load with ``strict=True``, including when nested in another module.
+ state_dict.setdefault(prefix + "colors", self.colors)
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
r"""Apply the colormap to the input torch.Tensor.
@@ -318,4 +341,4 @@ class ApplyColorMap(nn.Module):
The output torch.Tensor representing the image with the applied colormap.
"""
- return apply_colormap(input_tensor, self.colormap)
+ return _apply_colormap(input_tensor, self.colors)
diff --git a/tests/color/test_colormap.py b/tests/color/test_colormap.py
index 4d853ae39..4d0d6f038 100644
--- a/tests/color/test_colormap.py
+++ b/tests/color/test_colormap.py
@@ -199,3 +199,36 @@ class TestApplyColorMap(BaseTester):
img = torch.ones(1, 3, 3, device=device, dtype=dtype)
self.assert_close(op(img, colormap=cm), op_module(img))
+ assert "colors" in dict(op_module.named_buffers())
+ assert op_module.colors is cm.colors
+
+ def test_module_palette_follows_to(self, device):
+ # The palette is a buffer, so converting or moving the module converts or moves it.
+ module = ApplyColorMap(ColorMap(base="autumn")).to(device=device, dtype=torch.float16)
+ expected = ApplyColorMap(ColorMap(base="autumn", device=device, dtype=torch.float16))
+ img = torch.tensor([[[[0, 64, 128, 255]]]], device=device, dtype=torch.uint8)
+
+ actual = module(img)
+
+ assert actual.dtype == torch.float16
+ self.assert_close(actual, expected(img))
+
+ def test_module_state_dict_round_trip(self, device, dtype):
+ source = ApplyColorMap(ColorMap(base="winter", device=device, dtype=dtype))
+ target = ApplyColorMap(ColorMap(base="autumn", device=device, dtype=dtype))
+ img = torch.tensor([[[[0, 64, 128, 255]]]], device=device, dtype=torch.uint8)
+
+ target.load_state_dict(source.state_dict())
+
+ self.assert_close(target(img), source(img))
+
+ def test_module_loads_state_dict_without_palette(self, device, dtype):
+ # State dicts saved before the palette was a buffer have no "colors" key: they still load strictly,
+ # also when the module is nested, and keep the palette the module was built with.
+ model = torch.nn.Sequential(ApplyColorMap(ColorMap(base="autumn", device=device, dtype=dtype)))
+ img = torch.tensor([[[[0, 64, 128, 255]]]], device=device, dtype=torch.uint8)
+ expected = model(img)
+
+ model.load_state_dict({})
+
+ self.assert_close(model(img), expected)