Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): accept an int fill_value in RandomChannelDropout (#4607)

Dipak Chaudharia5d724265667
diff --git a/changelog.d/4607.fixed.md b/changelog.d/4607.fixed.md
new file mode 100644
index 000000000..a653ecbaf
--- /dev/null
+++ b/changelog.d/4607.fixed.md
@@ -0,0 +1 @@
+`RandomChannelDropout` accepts an `int` `fill_value` such as `0` or `1`, as `RandomErasing` does for `value`, instead of raising `TypeCheckError`. The value is stored as a float buffer, so the output is identical to passing the float.
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index eb1bf8fb4..aaad1972b 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -45,11 +45,11 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
Convention:
- the channels named by the drawn ``channel_idx`` are overwritten with the literal ``fill_value``,
- which has to be a ``float`` in ``[0, 1]``: this class's own ``__init__`` rejects anything outside
- the bounds, and an ``int`` such as ``0`` on type. ``ChannelDropoutGenerator`` never sees
- ``fill_value`` -- unlike :class:`RandomErasing`, whose ``value`` guard does live in its generator,
- and which accepts an ``int`` ``value`` (`#4606 <https://github.com/kornia/kornia/issues/4606>`_).
- Every other channel is left exactly as it came in, so the
+ which has to be an ``int`` or a ``float`` in ``[0, 1]``: this class's own ``__init__`` rejects
+ anything outside the bounds, and anything that is not a Python ``int`` or ``float`` on type. As with
+ :class:`RandomErasing`'s ``value``, ``0`` and ``1`` are accepted, and so are ``False`` and ``True``.
+ ``ChannelDropoutGenerator`` never sees ``fill_value`` -- unlike :class:`RandomErasing`, whose
+ ``value`` guard does live in its generator. Every other channel is left exactly as it came in, so the
input's value range is carried through.
- the dropped channels are drawn independently per sample; ``same_on_batch=True`` collapses the
draw to one set of channels for the whole batch.
@@ -99,17 +99,18 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
- KORNIA_CHECK_TYPE(fill_value, float, f"`fill_value` must be a float. Got: {type(fill_value)}")
+ KORNIA_CHECK_TYPE(fill_value, (int, float), f"`fill_value` must be an int or a float. Got: {type(fill_value)}")
KORNIA_CHECK(
0.0 <= fill_value <= 1.0,
- f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}",
+ f"Invalid value in `fill_value`. Must be a number between 0 and 1. Got: {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)
+ # float() keeps an int fill_value from registering an int64 buffer, which `.half()` would not cast.
+ self.register_buffer("fill_value", torch.tensor(float(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/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 70027018e..c41bb10e3 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4674,15 +4674,32 @@ class TestRandomChannelDropout(BaseTester):
):
RandomChannelDropout(num_drop_channels=num_drop_channels, p=1.0)(input_tensor)
- fill_value = 2.0
- with pytest.raises(
- BaseError, match=f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}"
- ):
+ # an out-of-range int is rejected on the bound just like a float
+ for fill_value in (2.0, 2, -1):
+ with pytest.raises(
+ BaseError, match=f"Invalid value in `fill_value`. Must be a number between 0 and 1. Got: {fill_value}"
+ ):
+ RandomChannelDropout(fill_value=fill_value)
+
+ fill_value = "1"
+ with pytest.raises(TypeCheckError, match=f"`fill_value` must be an int or a float. Got: {type(fill_value)}"):
RandomChannelDropout(fill_value=fill_value)
- fill_value = 1
- with pytest.raises(TypeCheckError, match=f"`fill_value` must be a float. Got: {type(fill_value)}"):
- RandomChannelDropout(fill_value=fill_value)
+ @pytest.mark.parametrize(("fill_value", "as_float"), [(0, 0.0), (1, 1.0), (True, 1.0)])
+ def test_int_fill_value_matches_float_4606(self, fill_value, as_float, device, dtype):
+ # RandomErasing accepts an int `value`; an int `fill_value` used to be rejected on type here.
+ input_tensor = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ torch.manual_seed(0)
+ out_int = RandomChannelDropout(fill_value=fill_value, p=1.0)(input_tensor)
+ torch.manual_seed(0)
+ out_float = RandomChannelDropout(fill_value=as_float, p=1.0)(input_tensor)
+ assert out_int.dtype == dtype
+ self.assert_close(out_int, out_float, rtol=0.0, atol=0.0)
+
+ def test_int_fill_value_buffer_follows_module_casts_4606(self, device):
+ aug = RandomChannelDropout(fill_value=1, p=1.0)
+ assert aug.fill_value.dtype == torch.float32
+ assert aug.to(device).half().fill_value.dtype == torch.float16
@pytest.mark.parametrize("channel_shape, batch_shape", [(3, 1), (1, 1), (5, 5)])
def test_cardinality(self, batch_shape, channel_shape, device, dtype):
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 65a191cab..7214aa510 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -1679,7 +1679,7 @@ class TestIntensityColourConventions(BaseTester):
"channel_dropout_fill_value_above_one",
"construction",
BaseError,
- r"Invalid value in .fill_value.\. Must be a float between 0 and 1",
+ r"Invalid value in .fill_value.\. Must be a number between 0 and 1",
),
(
"color_jiggle_brightness_range_above_two",
@@ -1765,7 +1765,7 @@ class TestIntensityColourConventions(BaseTester):
"median_blur_even_kernel": lambda: K.RandomMedianBlur((4, 4), p=1.0),
# An even bound is rounded up to the next odd size, so (0, 2) draws 1 and the kernel rejects it.
"motion_blur_even_bound_rounds_up": lambda: K.RandomMotionBlur((0, 2), 35.0, 0.5, p=1.0),
- # `fill_value` is bounded to [0, 1] at construction, unlike RandomErasing's `value` type check.
+ # `fill_value` is bounded to [0, 1] in __init__; RandomErasing bounds `value` alike, in its generator.
"channel_dropout_fill_value_above_one": lambda: K.RandomChannelDropout(fill_value=2.0, p=1.0),
# ColorJiggle's brightness bound is (0, 2); ColorJitter accepts the same range.
"color_jiggle_brightness_range_above_two": lambda: K.ColorJiggle(brightness=(0.0, 3.0), p=1.0),