Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): serialize ZCAWhitening fitted state (#5338)

NiteeshGowda72e54e3f3a102a
diff --git a/changelog.d/5338.fixed.md b/changelog.d/5338.fixed.md
new file mode 100644
index 000000000..07bb999d1
--- /dev/null
+++ b/changelog.d/5338.fixed.md
@@ -0,0 +1 @@
+`ZCAWhitening` now stores its fitted mean and transforms as buffers: `state_dict` saves them, loading a fitted state into an unfitted module fits it, and `.to()` moves and casts them. Before, a fitted module's `state_dict` was empty and `.to()` left the fit on its original device and dtype, so the moved module raised on input of the new dtype. A checkpoint saved before this change still loads with `strict=True` and keeps the current fit.
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index db749ede1..f1b60e6ea 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -42,6 +42,11 @@ class ZCAWhitening(nn.Module):
where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
eigenvalues of :math:`\Sigma`. After the transform is applied, the output is reshaped to same shape.
+ The fitted mean and transforms are buffers: ``state_dict`` saves them, ``.to()`` moves and casts them, and
+ loading a fitted state into an unfitted module fits it. An unfitted module holds no tensors, so the loaded
+ ones keep the device and dtype they were saved with; move the module after loading. A checkpoint saved
+ before the fitted state was persisted holds none of it, and loading it keeps the current fit.
+
Args:
dim: Determines the dimension that represents the samples axis.
eps: a small number used for numerical stability.
@@ -78,6 +83,9 @@ class ZCAWhitening(nn.Module):
"""
+ # Version 2 persists the fitted tensors; checkpoints of earlier versions hold none of them.
+ _version: int = 2
+
def __init__(
self,
dim: int = 0,
@@ -96,9 +104,43 @@ class ZCAWhitening(nn.Module):
self.fitted = False
- self.mean_vector: torch.Tensor
- self.transform_matrix: torch.Tensor
- self.transform_inv: Optional[torch.Tensor]
+ self.register_buffer("mean_vector", None)
+ self.register_buffer("transform_matrix", None)
+ self.register_buffer("transform_inv", None)
+
+ def _load_from_state_dict(
+ self,
+ state_dict: dict[str, torch.Tensor],
+ prefix: str,
+ local_metadata: dict,
+ strict: bool,
+ missing_keys: list[str],
+ unexpected_keys: list[str],
+ error_msgs: list[str],
+ ) -> None:
+ version = local_metadata.get("version", None)
+ for name in ("mean_vector", "transform_matrix", "transform_inv"):
+ key = prefix + name
+ current = self._buffers[name]
+ if key in state_dict:
+ if current is None:
+ # An unfitted module has no tensor to copy into: take the saved one's shape, dtype and device.
+ self._buffers[name] = torch.empty_like(state_dict[key])
+ elif current is not None and (version is None or version < 2):
+ # An older checkpoint did not save the fit: keep the current one, so strict loading still works.
+ state_dict[key] = current
+
+ super()._load_from_state_dict(
+ state_dict,
+ prefix,
+ local_metadata,
+ strict,
+ missing_keys,
+ unexpected_keys,
+ error_msgs,
+ )
+
+ self.fitted = self.transform_matrix is not None
def fit(self, x: torch.Tensor) -> "ZCAWhitening":
r"""Fit ZCA whitening matrices to the data.
@@ -119,7 +161,7 @@ class ZCAWhitening(nn.Module):
self.mean_vector = mean
self.transform_matrix = T
if T_inv is None:
- self.transform_inv = torch.empty([0])
+ self.transform_inv = T.new_empty(0)
else:
self.transform_inv = T_inv
diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.py
index 2d1d76187..edfac79c9 100644
--- a/tests/enhance/test_zca.py
+++ b/tests/enhance/test_zca.py
@@ -179,6 +179,111 @@ class TestZCA(BaseTester):
self.gradcheck(zca, (data,))
+ def test_fitted_state_is_serialized(self, device, dtype):
+ data = torch.randn(8, 3, device=device, dtype=dtype)
+ zca = kornia.enhance.ZCAWhitening().fit(data)
+
+ state_dict = zca.state_dict()
+
+ assert "mean_vector" in state_dict
+ assert "transform_matrix" in state_dict
+ assert "transform_inv" in state_dict
+ assert state_dict["mean_vector"].shape == zca.mean_vector.shape
+ assert state_dict["transform_matrix"].shape == zca.transform_matrix.shape
+ # Without compute_inv the inverse is an empty placeholder, made on the data's device and dtype.
+ assert state_dict["transform_inv"].shape == (0,)
+ assert all(tensor.device == device and tensor.dtype == dtype for tensor in state_dict.values())
+
+ def test_unfitted_state_is_empty(self):
+ zca = kornia.enhance.ZCAWhitening()
+
+ assert zca.state_dict() == {}
+
+ def test_fitted_state_follows_dtype_conversion(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ data = torch.randn(8, 3, device=device, dtype=torch.float32)
+ zca = kornia.enhance.ZCAWhitening().fit(data)
+
+ expected = zca(data)
+ zca.double()
+
+ actual = zca(data.double())
+
+ assert zca.mean_vector.dtype == torch.float64
+ assert zca.transform_matrix.dtype == torch.float64
+ assert zca.transform_inv.dtype == torch.float64
+ self.assert_close(actual, expected.double(), low_tolerance=True)
+
+ def test_fitted_state_follows_device_conversion(self, device, dtype):
+ data = torch.randn(8, 3, device=device, dtype=dtype)
+ zca = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data)
+
+ # The meta device needs no hardware, so every test leg moves the fit off the device it was made on.
+ zca.to("meta")
+
+ assert zca.mean_vector.device.type == "meta"
+ assert zca.transform_matrix.device.type == "meta"
+ assert zca.transform_inv.device.type == "meta"
+
+ output = zca(data.to("meta"))
+
+ assert output.device.type == "meta"
+
+ def test_fitted_state_round_trip(self, device, dtype):
+ data = torch.randn(8, 3, device=device, dtype=dtype)
+
+ zca = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data)
+ expected = zca(data)
+
+ loaded = kornia.enhance.ZCAWhitening(compute_inv=True)
+ result = loaded.load_state_dict(zca.state_dict())
+
+ assert result.missing_keys == []
+ assert result.unexpected_keys == []
+ assert loaded.fitted
+ self.assert_close(loaded(data), expected, low_tolerance=True)
+ self.assert_close(loaded.inverse_transform(expected), zca.inverse_transform(expected), low_tolerance=True)
+
+ def test_checkpoint_without_fitted_state_keeps_the_fit(self, device, dtype):
+ data = torch.randn(8, 3, device=device, dtype=dtype)
+ model = torch.nn.Sequential(kornia.enhance.ZCAWhitening().fit(data))
+ expected = model(data)
+
+ # A checkpoint saved before the fitted state was persisted: no ZCA keys and module version 1.
+ checkpoint = torch.nn.Sequential(kornia.enhance.ZCAWhitening()).state_dict()
+ checkpoint._metadata["0"]["version"] = 1
+ result = model.load_state_dict(checkpoint)
+
+ assert result.missing_keys == []
+ assert model[0].fitted
+ self.assert_close(model(data), expected)
+
+ # A plain dict, e.g. one rebuilt with renamed keys, carries no version and is read the same way.
+ assert model.load_state_dict({}).missing_keys == []
+ self.assert_close(model(data), expected)
+
+ # An unfitted module stays unfitted.
+ unfitted = torch.nn.Sequential(kornia.enhance.ZCAWhitening())
+ result = unfitted.load_state_dict(checkpoint)
+ assert result.missing_keys == []
+ assert result.unexpected_keys == []
+ assert not unfitted[0].fitted
+
+ # A checkpoint of this version saved from an unfitted module lacks the keys, and strict loading says so.
+ with pytest.raises(RuntimeError, match="Missing key"):
+ model.load_state_dict(torch.nn.Sequential(kornia.enhance.ZCAWhitening()).state_dict())
+
+ def test_unfitted_state_round_trip(self):
+ zca = kornia.enhance.ZCAWhitening()
+ loaded = kornia.enhance.ZCAWhitening()
+
+ result = loaded.load_state_dict(zca.state_dict())
+
+ assert result.missing_keys == []
+ assert result.unexpected_keys == []
+ assert not loaded.fitted
+
def test_not_fitted(self, device, dtype):
data = torch.rand(10, 2, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening()