Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Fix] Enforce same_on_batch consistency for RandomGaussianNoise and RandomChannelShuffle (#3723)

Siddharth Jaspalb5f8176e80bd
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index 4e132fab6..31a419455 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -15,10 +15,11 @@
# limitations under the License.
#
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional
import torch
+from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
@@ -53,11 +54,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
-
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
- B, C, _, _ = shape
- channels = torch.rand(B, C).argsort(dim=1)
- return {"channels": channels}
+ self._param_generator = rg.ChannelShuffleGenerator()
def apply_transform(
self,
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index 1f662a503..a05bde582 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -15,22 +15,14 @@
# limitations under the License.
#
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional
import torch
+from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
-def _randn_like(input: torch.Tensor, mean: float, std: float) -> torch.Tensor:
- x = torch.randn_like(input) # Generating on GPU is fastest with `torch.randn_like(...)`
- if std != 1.0: # `if` is cheaper than multiplication
- x *= std
- if mean != 0.0: # `if` is cheaper than addition
- x += mean
- return x
-
-
class RandomGaussianNoise(IntensityAugmentationBase2D):
r"""Add gaussian noise to a batch of multi-dimensional images.
@@ -63,10 +55,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
self, mean: float = 0.0, std: float = 1.0, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
- self.flags = {"mean": mean, "std": std}
-
- def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
- return {}
+ self._param_generator = rg.GaussianNoiseGenerator(mean, std)
def apply_transform(
self,
@@ -75,9 +64,8 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- if "gaussian_noise" in params:
- gaussian_noise = params["gaussian_noise"]
- else:
- gaussian_noise = _randn_like(input, mean=flags["mean"], std=flags["std"])
- self._params["gaussian_noise"] = gaussian_noise
+ gaussian_noise = params["gaussian_noise"].to(input)
+ # When same_on_batch=True the generator produces shape (1, C, H, W); expand to full batch.
+ if gaussian_noise.shape[0] != input.shape[0]:
+ gaussian_noise = gaussian_noise.expand_as(input)
return input + gaussian_noise
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index ca8e3ae74..49657ca38 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -17,12 +17,14 @@
from kornia.augmentation.random_generator._2d.affine import *
from kornia.augmentation.random_generator._2d.channel_dropout import *
+from kornia.augmentation.random_generator._2d.channel_shuffle import *
from kornia.augmentation.random_generator._2d.color_jiggle import *
from kornia.augmentation.random_generator._2d.color_jitter import *
from kornia.augmentation.random_generator._2d.crop import *
from kornia.augmentation.random_generator._2d.cutmix import *
from kornia.augmentation.random_generator._2d.gaussian_blur import *
from kornia.augmentation.random_generator._2d.gaussian_illumination import *
+from kornia.augmentation.random_generator._2d.gaussian_noise import *
from kornia.augmentation.random_generator._2d.jigsaw import *
from kornia.augmentation.random_generator._2d.jpeg import *
from kornia.augmentation.random_generator._2d.linear_illumination import *
diff --git a/kornia/augmentation/random_generator/_2d/channel_shuffle.py b/kornia/augmentation/random_generator/_2d/channel_shuffle.py
new file mode 100644
index 000000000..50f3cc9d8
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/channel_shuffle.py
@@ -0,0 +1,70 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import torch
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
+
+__all__ = ["ChannelShuffleGenerator"]
+
+
+class ChannelShuffleGenerator(RandomGeneratorBase):
+ r"""Generate random channel permutation indices for a batch of images.
+
+ Returns:
+ A dictionary containing the channel permutation indices.
+ - ``channels``: Long tensor of permuted channel indices with a shape of ``(B, C)``.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
+ """
+
+ def __repr__(self) -> str:
+ return ""
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ """Create a Uniform(0, 1) sampler used to generate random channel scores for argsort shuffling."""
+ self.shuffle_sampler = UniformDistribution(
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.tensor(1.0, device=device, dtype=dtype),
+ validate_args=False,
+ )
+
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
+ """Generate channel permutation indices.
+
+ Args:
+ batch_shape: Shape of the input batch ``(B, C, H, W)``.
+ same_on_batch: If ``True``, the same permutation is applied to all items in the batch.
+
+ Returns:
+ Dictionary with key ``"channels"`` mapping to a ``(B, C)`` long tensor of permuted indices.
+ """
+ batch_size, C = batch_shape[0], batch_shape[1]
+ _common_param_check(batch_size, same_on_batch)
+
+ # Sample uniform scores of shape (B, C); _adapted_rsampling handles same_on_batch by
+ # generating (1, C) and repeating across the batch dimension when same_on_batch=True.
+ scores = _adapted_rsampling((batch_size, C), self.shuffle_sampler, same_on_batch)
+ channels = scores.argsort(dim=1).to(dtype=torch.long)
+ return {"channels": channels}
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_noise.py b/kornia/augmentation/random_generator/_2d/gaussian_noise.py
new file mode 100644
index 000000000..0014ce4e5
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/gaussian_noise.py
@@ -0,0 +1,88 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import torch
+from torch.distributions import Normal
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _common_param_check
+
+__all__ = ["GaussianNoiseGenerator"]
+
+
+class GaussianNoiseGenerator(RandomGeneratorBase):
+ r"""Generate random Gaussian noise tensors for a batch of images.
+
+ Args:
+ mean: Mean of the Gaussian distribution.
+ std: Standard deviation of the Gaussian distribution.
+
+ Returns:
+ A dictionary containing the pre-generated noise tensor.
+ - ``gaussian_noise``: Float tensor of noise values with a shape of ``(B, C, H, W)``
+ (or ``(1, C, H, W)`` when ``same_on_batch=True``, to be expanded in ``apply_transform``).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
+ """
+
+ def __init__(self, mean: float, std: float) -> None:
+ super().__init__()
+ self.mean = mean
+ self.std = std
+
+ def __repr__(self) -> str:
+ return f"mean={self.mean}, std={self.std}"
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ """Store device and dtype for the Normal distribution (created on demand in forward)."""
+ # Normal is created fresh in forward() so device/dtype are always consistent.
+ # No persistent sampler is needed beyond what the base class tracks.
+
+ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
+ """Generate a Gaussian noise tensor matching the input batch shape.
+
+ Args:
+ batch_shape: Shape of the input batch ``(B, C, H, W)``.
+ same_on_batch: If ``True``, generate a single noise map ``(1, C, H, W)`` shared
+ across all batch items. The augmentation's ``apply_transform`` is responsible
+ for expanding it to the full batch size.
+
+ Returns:
+ Dictionary with key ``"gaussian_noise"`` containing the noise tensor.
+ """
+ batch_size, C, H, W = batch_shape
+ _common_param_check(batch_size, same_on_batch)
+
+ device = self.device if self.device is not None else torch.device("cpu")
+ dtype = self.dtype if self.dtype is not None else torch.get_default_dtype()
+
+ dist = Normal(
+ torch.tensor(self.mean, device=device, dtype=dtype),
+ torch.tensor(self.std, device=device, dtype=dtype),
+ )
+
+ # When same_on_batch, generate a single (1, C, H, W) map β€” apply_transform will expand it.
+ sample_B = 1 if same_on_batch else batch_size
+ gaussian_noise = dist.rsample((sample_B, C, H, W))
+
+ return {"gaussian_noise": gaussian_noise}
diff --git a/pr_body.txt b/pr_body.txt
new file mode 100644
index 000000000..8d47aaa2e
--- /dev/null
+++ b/pr_body.txt
@@ -0,0 +1,5 @@
+> Description: This PR introduces Google-style structural docstrings to the kornia.losses.dice module, resolving the missing D101, D102, and D103 Ruff violations.
+
+Related Issue: Fixes #3083
+Verification: 12 passed, 43 warnings (local Windows test-bed).
+AI Disclosure: ?? AI-assisted via GitHub Copilot CLI; verified by Siddharth Jaspal.
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index a9ec75e22..fa38b5e51 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -3987,6 +3987,12 @@ class TestRandomChannelShuffle(BaseTester):
out = aug(img)
self.assert_close(out, out_expected)
+ def test_same_on_batch(self, device, dtype):
+ input_tensor = torch.rand(1, 3, 5, 5, device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ transform = RandomChannelShuffle(p=1.0, same_on_batch=True)
+ output_tensor = transform(input_tensor)
+ self.assert_close(output_tensor[0], output_tensor[1])
+
class TestRandomClahe(BaseTester):
def test_smoke(self, device, dtype):
@@ -4008,6 +4014,13 @@ class TestRandomGaussianNoise(BaseTester):
aug = RandomGaussianNoise(p=1.0)
assert img.shape == aug(img).shape
+ def test_same_on_batch(self, device, dtype):
+ input_tensor = torch.rand(1, 1, 5, 5, device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ transform = RandomGaussianNoise(p=1.0, same_on_batch=True)
+ output_tensor = transform(input_tensor)
+ self.assert_close(output_tensor[0], output_tensor[1])
+ assert not torch.allclose(input_tensor, output_tensor)
+
class TestRandomSaltAndPepperNoise(BaseTester):
@pytest.mark.parametrize(