Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): register fill_value/sigma as buffers, not plain attrs (#4337)

tritsystemccd6213a45c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2dde39509..8f289acd9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -384,6 +384,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
-- is written as one file per item rather than passed whole to `write_image`, which takes
`(3, H, W)` and rejected the rank with a message naming neither. (#4322)
+* `RandomChannelDropout.fill_value` and `RandomGaussianBlurGenerator.sigma` (when passed as a
+ Tensor) are registered as non-persistent buffers instead of plain attributes, so they move with
+ `Module.to()`/`.half()`/`.cuda()` and appear in `named_buffers()` like the rest of the module's
+ state; `state_dict()` keys are unchanged. Neither crashed before this change (both re-derived
+ device and dtype inline on every call), so this is a hygiene fix, not a bug fix for a crash.
+ One user-visible effect: after `.half()`/`.bfloat16()` the fill value is now held in that dtype,
+ so an input already in the module's dtype is unaffected, while a `float32` input fed to a
+ half-converted `RandomChannelDropout(fill_value=0.3)` is filled with `0.300048828125` (float16)
+ or `0.30078125` (bfloat16) rather than `0.3` -- the same buffer semantics as `Normalize`.
+ (#4337)
+
* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`
resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into
`kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raised
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index 5a83a5a7e..e8dc768cc 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -89,7 +89,12 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
0.0 <= fill_value <= 1.0,
f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}",
)
- self.fill_value = torch.tensor(fill_value)
+ # `fill_value` is fully determined by the constructor arg (derived state, not
+ # learned) -- register as a non-persistent buffer so `.to()` / `.cuda()` /
+ # `.half()` move it through the normal nn.Module machinery instead of leaving
+ # it behind as a plain attribute. persistent=False keeps state_dict() keys
+ # unchanged, same rationale/convention as #4079/#4319.
+ self.register_buffer("fill_value", torch.tensor(fill_value), persistent=False)
KORNIA_CHECK_TYPE(num_drop_channels, int, f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}")
KORNIA_CHECK(
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index e355ee881..789ba4ea1 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -55,7 +55,16 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):
if sigma[1] < sigma[0]:
raise TypeError(f"sigma_max should be higher than sigma_min: {sigma} passed.")
- self.sigma = sigma
+ # `sigma` may be a plain (min, max) tuple of Python floats -- no device/dtype,
+ # nothing for `.to()`/`.half()` to move -- or a Tensor supplied by the caller.
+ # Only the Tensor case is derived state that needs to track the module: register
+ # it as a non-persistent buffer so `.to()` moves it through the normal nn.Module
+ # machinery instead of leaving it behind as a plain attribute. persistent=False
+ # keeps state_dict() keys unchanged, same rationale/convention as #4079/#4319.
+ if isinstance(sigma, torch.Tensor):
+ self.register_buffer("sigma", sigma, persistent=False)
+ else:
+ self.sigma = sigma
self.sigma_sampler: UniformDistribution
def __repr__(self) -> str:
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 0b7e3a69f..c28bdb041 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4541,6 +4541,25 @@ class TestRandomChannelDropout(BaseTester):
output_tensor = transform(input_tensor)
self.assert_close(output_tensor[0], output_tensor[1])
+ def test_fill_value_is_a_registered_buffer(self, device, dtype):
+ # `fill_value` used to be a plain attribute -- invisible to state_dict() and to
+ # Module.to()/.half()/.cuda() (apply_transform compensated with its own inline
+ # `.to()`, so this was never a crash risk, just missing buffer hygiene).
+ aug = RandomChannelDropout(fill_value=0.3, p=1.0)
+ # persistent=False -> visible via named_buffers()/.to() but excluded from
+ # state_dict(), as in the buffer fixes #4079 and #4319 (keeps checkpoint
+ # keys unchanged); not every kornia buffer is non-persistent.
+ assert "fill_value" in dict(aug.named_buffers())
+ assert "fill_value" not in aug.state_dict()
+
+ moved = aug.to(device=device, dtype=dtype)
+ assert moved.fill_value.device.type == torch.device(device).type
+ assert moved.fill_value.dtype == dtype
+ # the moved buffer is the value the forward actually fills with
+ out = moved(torch.zeros(1, 3, 8, 8, device=device, dtype=dtype))
+ assert (out == moved.fill_value).any()
+ assert out.max() == moved.fill_value
+
class TestNormalize(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index cd27f084c..3e4224cb7 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -19,6 +19,7 @@ import pytest
import torch
from torch import Tensor
+from kornia.augmentation import RandomGaussianBlur
from kornia.augmentation.random_generator import (
AffineGenerator,
ColorJiggleGenerator,
@@ -31,6 +32,7 @@ from kornia.augmentation.random_generator import (
PlainUniformGenerator,
PosterizeGenerator,
ProbabilityGenerator,
+ RandomGaussianBlurGenerator,
RectangleEraseGenerator,
ResizedCropGenerator,
center_crop_generator,
@@ -1557,3 +1559,37 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
assert res.keys() == expected.keys(), res.keys()
assert_close(res["mix_pairs"], expected["mix_pairs"], rtol=1e-4, atol=1e-4)
assert_close(res["crop_src"], expected["crop_src"], rtol=1e-4, atol=1e-4)
+
+
+class TestGaussianBlurGenBufferHygiene:
+ # `sigma` used to be a plain attribute when passed as a Tensor -- invisible to
+ # state_dict() and to Module.to()/.half()/.cuda() (make_samplers compensated with
+ # its own inline `.to()`, so this was never a crash risk, just missing buffer
+ # hygiene). A plain (min, max) tuple of Python floats has no device/dtype and stays
+ # a plain attribute, which is correct.
+ def test_tensor_sigma_is_a_registered_buffer(self, device, dtype):
+ gen = RandomGaussianBlurGenerator(sigma=torch.tensor([0.1, 2.0]))
+ # persistent=False -> visible via named_buffers() but excluded from
+ # state_dict(), as in the buffer fixes #4079 and #4319 (keeps checkpoint
+ # keys unchanged); not every kornia buffer is non-persistent.
+ assert "sigma" in dict(gen.named_buffers())
+ assert "sigma" not in gen.state_dict()
+
+ # RandomGeneratorBase.to() is a special-cased override (see its own "TODO:
+ # refine the logic with module.to()") that only rebuilds sigma_sampler via
+ # make_samplers() -- it never calls nn.Module.to(), so calling it directly on
+ # a standalone generator does NOT exercise the buffer-move machinery this fix
+ # relies on. The real path this fix targets is a PARENT module's .to()/.half(),
+ # which nn.Module recurses into via `_apply()` (not `.to()`) on every
+ # submodule -- including this generator when assigned as `_param_generator`,
+ # exactly how RandomGaussianBlur uses it. Exercise that real path directly.
+ aug = RandomGaussianBlur((3, 3), sigma=torch.tensor([0.1, 2.0]))
+ moved = aug.to(device=device, dtype=dtype)
+ moved_sigma = moved._param_generator.sigma
+ assert moved_sigma.device == torch.tensor(0.0, device=device).device
+ assert moved_sigma.dtype == dtype
+
+ def test_tuple_sigma_stays_a_plain_attribute(self):
+ gen = RandomGaussianBlurGenerator(sigma=(0.1, 2.0))
+ assert "sigma" not in dict(gen.named_buffers())
+ assert gen.sigma == (0.1, 2.0)