Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): make RandomPlasma params replay deterministic (#4462)

Hrithik Sharma539c9ecc7586
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 363c94547..1992700e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -392,6 +392,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Fixed `RandomPlasmaBrightness`, `RandomPlasmaContrast`, and `RandomPlasmaShadow` to replay deterministically from stored `params=`. (#4462)
* `ManyToManyAugmentationDispather` now rejects mismatched numbers of input bundles and
augmentations before applying any transformation, instead of silently dropping surplus inputs
or skipping augmentations. (#4461)
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index c48fe8126..0e09ef097 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -24,6 +24,29 @@ from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.contrib import diamond_square
+def _generate_plasma(
+ shape: Tuple[int, ...],
+ roughness: torch.Tensor,
+ device: torch.device,
+ dtype: torch.dtype,
+ channels: Optional[int] = None,
+) -> torch.Tensor:
+ if len(shape) == 4:
+ batch_size, shape_channels, height, width = shape
+ elif len(shape) == 3:
+ batch_size, height, width = shape
+ shape_channels = 1
+ else:
+ raise ValueError(f"Expected a 3D or 4D shape. Got {shape}.")
+
+ num_channels = shape_channels if channels is None else channels
+ return diamond_square((batch_size, num_channels, height, width), roughness, device=device, dtype=dtype)
+
+
+def _plasma_for_input(plasma: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
+ return plasma[..., : image.shape[-2], : image.shape[-1]].to(image)
+
+
class RandomPlasmaBrightness(IntensityAugmentationBase2D):
r"""Adds brightness to the image based on a fractal map generated by the diamond square algorithm.
@@ -66,6 +89,12 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
(roughness, "roughness", None, None), (intensity, "intensity", None, None)
)
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
+ params = super().generate_parameters(shape)
+ roughness = params["roughness"].to(device=self.device, dtype=self.dtype)
+ params["plasma"] = _generate_plasma(shape, roughness, self.device, self.dtype)
+ return params
+
def apply_transform(
self,
image: torch.Tensor,
@@ -73,10 +102,8 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- B, C, H, W = image.shape
- roughness = params["roughness"].to(image)
intensity = params["intensity"].to(image).view(-1, 1, 1, 1)
- brightness_map = 2 * diamond_square((B, C, H, W), roughness, device=image.device, dtype=image.dtype) - 1
+ brightness_map = 2 * _plasma_for_input(params["plasma"], image) - 1
brightness_map = brightness_map * intensity
return (image + brightness_map).clamp_(0, 1)
@@ -119,6 +146,12 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator((roughness, "roughness", None, None))
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
+ params = super().generate_parameters(shape)
+ roughness = params["roughness"].to(device=self.device, dtype=self.dtype)
+ params["plasma"] = _generate_plasma(shape, roughness, self.device, self.dtype)
+ return params
+
def apply_transform(
self,
image: torch.Tensor,
@@ -126,9 +159,7 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- B, C, H, W = image.shape
- roughness = params["roughness"].to(image)
- contrast_map = 4 * diamond_square((B, C, H, W), roughness, device=image.device, dtype=image.dtype)
+ contrast_map = 4 * _plasma_for_input(params["plasma"], image)
return ((image - 0.5) * contrast_map + 0.5).clamp_(0, 1)
@@ -178,6 +209,12 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
(shade_quantity, "shade_quantity", None, None),
)
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
+ params = super().generate_parameters(shape)
+ roughness = params["roughness"].to(device=self.device, dtype=self.dtype)
+ params["plasma"] = _generate_plasma(shape, roughness, self.device, self.dtype, channels=1)
+ return params
+
def apply_transform(
self,
image: torch.Tensor,
@@ -185,10 +222,8 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
flags: Dict[str, Any],
transform: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- B, _, H, W = image.shape
- roughness = params["roughness"].to(image)
shade_intensity = params["shade_intensity"].to(image).view(-1, 1, 1, 1)
shade_quantity = params["shade_quantity"].to(image).view(-1, 1, 1, 1)
- shade_map = diamond_square((B, 1, H, W), roughness, device=image.device, dtype=image.dtype)
+ shade_map = _plasma_for_input(params["plasma"], image)
shade_map = (shade_map < shade_quantity).to(image.dtype) * shade_intensity
return (image + shade_map).clamp_(0, 1)
diff --git a/tests/augmentation/container/test_patch_sequential_plasma.py b/tests/augmentation/container/test_patch_sequential_plasma.py
new file mode 100644
index 000000000..c44aa8020
--- /dev/null
+++ b/tests/augmentation/container/test_patch_sequential_plasma.py
@@ -0,0 +1,54 @@
+# 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.
+#
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+
+
+ "augmentation_cls",
+ [
+ K.RandomPlasmaBrightness,
+ K.RandomPlasmaContrast,
+ K.RandomPlasmaShadow,
+ ],
+)
+ ("patchwise_apply", "random_apply"),
+ [
+ (False, False),
+ (True, False),
+ (True, True),
+ ],
+)
+def test_random_plasma_patch_sequential_4445(augmentation_cls, patchwise_apply, random_apply):
+ torch.manual_seed(0)
+
+ input = torch.rand(2, 3, 8, 8)
+ modules = [augmentation_cls(p=1.0) for _ in range(4 if patchwise_apply else 1)]
+ seq = K.PatchSequential(
+ *modules,
+ grid_size=(2, 2),
+ patchwise_apply=patchwise_apply,
+ random_apply=random_apply,
+ )
+
+ output = seq(input)
+
+ assert output.shape == input.shape
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index d91f4095f..b6c918779 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4867,6 +4867,28 @@ class TestRandomPlasma:
out = aug(img)
assert out.shape == (2, 3, 4, 5)
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ def test_params_replay_4445(self, augmentation_cls, device, dtype):
+ torch.manual_seed(0)
+
+ input = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ aug = augmentation_cls(p=1.0).to(device)
+
+ output = aug(input)
+ params = aug._params
+
+ torch.manual_seed(123)
+ replayed = aug(input, params=params)
+
+ assert torch.equal(output, replayed)
+
class TestPlanckianJitter(BaseTester):
def _get_expected_output_blackbody(self, device, dtype):