Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): honor same_on_batch in plasma augmentations (#4584)

Dex Hunterafe24ea6fcf0
diff --git a/changelog.d/4584.fixed.md b/changelog.d/4584.fixed.md
new file mode 100644
index 000000000..dca9cf675
--- /dev/null
+++ b/changelog.d/4584.fixed.md
@@ -0,0 +1,3 @@
+`RandomPlasmaBrightness`, `RandomPlasmaContrast`, and `RandomPlasmaShadow` now share one sampled map
+when `same_on_batch=True` (#4570). Seeded outputs and the subsequent RNG stream therefore differ
+from earlier releases for batches with multiple samples; `same_on_batch=False` is unchanged.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index b0f7d2133..47523ac88 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -398,9 +398,9 @@ Randomness in augmentations
for ``RandomDissolving``, which samples VAE latents during application.
Replaying it also needs control of that application-time random state.
- ``same_on_batch=True`` shares the standard per-sample gate and sampled
- transform factors. It does not equate batch-pairing indices, and the
- ``RandomPlasma*`` noise stored in the parameters is drawn independently per
- sample whatever the flag says.
+ transform factors. It does not equate batch-pairing indices. For
+ ``RandomPlasma*``, the stored noise map is sampled once and expanded
+ across the batch when this flag is enabled.
Color adjustment order is one permutation shared across the batch,
independently of this flag. On ``AugmentationSequential``, ``None`` keeps
each child's setting, while ``True`` and ``False`` overwrite it.
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index e190b5c33..2fdbbc0b8 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -78,8 +78,8 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
``mask_salt`` and ``mask_pepper`` -- whose stored shape normally follows the original batched
``(B, C, H, W)`` input shape. A ``(C, H, W)`` input remains batched in those parameters even when
``keepdim=True``. ``gaussian_noise`` instead stores ``(1, C, H, W)`` with ``same_on_batch=True``,
- then expands it at application time, while the plasma classes keep one map per sample even then
- (`#4570 <https://github.com/kornia/kornia/issues/4570>`_); ``RandomPlasmaShadow`` stores
+ then expands it at application time, while the plasma classes with ``same_on_batch=True`` store an
+ expanded ``(B, C, H, W)`` view with shared storage for the batch; ``RandomPlasmaShadow`` stores
``(B, 1, H, W)``. :class:`ColorJiggle` and :class:`ColorJitter` both draw an application ``order``;
it is shared by the whole batch. Only :class:`ColorJitter` takes a fixed ``order`` constructor
argument. Without one, on either class, an ``order`` tensor passed as a forward keyword, or
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index fbaf92d3a..d37845a0b 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -30,6 +30,7 @@ def _generate_plasma(
device: torch.device,
dtype: torch.dtype,
channels: Optional[int] = None,
+ same_on_batch: bool = False,
) -> torch.Tensor:
if len(shape) == 4:
batch_size, shape_channels, height, width = shape
@@ -40,7 +41,11 @@ def _generate_plasma(
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)
+ share_map = same_on_batch and batch_size > 1
+ map_batch_size = 1 if share_map else batch_size
+ map_roughness = roughness[:1] if share_map else roughness
+ plasma = diamond_square((map_batch_size, num_channels, height, width), map_roughness, device=device, dtype=dtype)
+ return plasma.expand(batch_size, -1, -1, -1) if share_map else plasma
def _plasma_for_input(plasma: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
@@ -76,11 +81,6 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
does not.
- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
- .. warning::
- With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
- its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
- `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
-
.. warning::
An all-negative input can come back as an all-zero image when the sampled brightness map does not raise
it above zero. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
@@ -111,7 +111,7 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
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)
+ params["plasma"] = _generate_plasma(shape, roughness, self.device, self.dtype, same_on_batch=self.same_on_batch)
return params
def apply_transform(
@@ -155,11 +155,6 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
does not.
- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
- .. warning::
- With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
- its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
- `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
-
.. warning::
An all-negative input can come back as an all-zero image, depending on the sampled contrast map.
Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
@@ -187,7 +182,7 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
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)
+ params["plasma"] = _generate_plasma(shape, roughness, self.device, self.dtype, same_on_batch=self.same_on_batch)
return params
def apply_transform(
@@ -232,11 +227,6 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
does not.
- a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
- .. warning::
- With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
- its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
- `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
-
.. warning::
At the default non-positive ``shade_intensity``, an input whose values are all negative comes back as
an all-zero image; a positive ``shade_intensity``, which the constructor accepts, can lift it. Tracked
@@ -271,7 +261,9 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
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)
+ params["plasma"] = _generate_plasma(
+ shape, roughness, self.device, self.dtype, channels=1, same_on_batch=self.same_on_batch
+ )
return params
def apply_transform(
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 4bbcf0b6d..b300db3d1 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5102,6 +5102,116 @@ class TestRandomPlasma:
out = aug(img)
assert out.shape == (2, 3, 4, 5)
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ @pytest.mark.parametrize("spatial_shape", [(8, 8), (5, 9)])
+ def test_same_on_batch_reuses_plasma_map_4570(self, augmentation_cls, device, dtype, spatial_shape):
+ torch.manual_seed(4570)
+ image = torch.full((4, 3, *spatial_shape), 0.3, device=device, dtype=dtype)
+ aug = augmentation_cls(roughness=(0.2, 0.8), same_on_batch=True, p=1.0).to(device, dtype)
+ output = aug(image)
+ plasma = aug._params["plasma"]
+ expected_channels = 1 if augmentation_cls is RandomPlasmaShadow else 3
+ assert plasma.shape == (4, expected_channels, *spatial_shape)
+ assert plasma.device == image.device
+ assert plasma.dtype == image.dtype
+ assert torch.isfinite(plasma).all(), "plasma-same-on-batch: nonfinite map"
+ assert torch.equal(plasma, plasma[:1].expand_as(plasma)), "plasma-same-on-batch: map differs across batch"
+ assert torch.isfinite(output).all(), "plasma-same-on-batch: nonfinite output"
+ assert torch.equal(output, output[:1].expand_as(output)), "plasma-same-on-batch: output differs across batch"
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == image.dtype
+
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ def test_different_on_batch_keeps_independent_maps_4570(self, augmentation_cls, device, dtype):
+ torch.manual_seed(4570)
+ image = torch.full((4, 3, 8, 8), 0.3, device=device, dtype=dtype)
+ aug = augmentation_cls(roughness=(0.2, 0.8), same_on_batch=False, p=1.0).to(device, dtype)
+ output = aug(image)
+ plasma = aug._params["plasma"]
+ assert plasma.shape[0] == image.shape[0]
+ assert torch.max(torch.abs(plasma[0] - plasma[1:])).item() > 0, "plasma-independent: maps unexpectedly equal"
+ assert torch.isfinite(output).all(), "plasma-independent: nonfinite output"
+
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ def test_same_on_batch_params_replay_4570(self, augmentation_cls, device, dtype):
+ torch.manual_seed(4570)
+ image = torch.full((4, 3, 8, 8), 0.3, device=device, dtype=dtype)
+ aug = augmentation_cls(roughness=(0.2, 0.8), same_on_batch=True, p=1.0).to(device, dtype)
+ output = aug(image)
+ params = {key: value.clone() for key, value in aug._params.items()}
+ torch.manual_seed(123)
+ replayed = aug(image, params=params)
+ assert torch.equal(output, replayed), "plasma-replay: output changed with saved parameters"
+ assert torch.equal(params["plasma"], aug._params["plasma"]), "plasma-replay: saved map changed"
+ assert params["forward_input_shape"].tolist() == list(image.shape), (
+ "plasma-replay: input shape metadata changed"
+ )
+
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ def test_same_on_batch_unbatched_keepdim_4570(self, augmentation_cls, device, dtype):
+ image = torch.full((3, 8, 8), 0.3, device=device, dtype=dtype)
+ aug = augmentation_cls(roughness=(0.2, 0.8), same_on_batch=True, p=1.0, keepdim=True).to(device, dtype)
+ output = aug(image)
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == image.dtype
+
+ @pytest.mark.parametrize(
+ "augmentation_cls",
+ [
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
+ ],
+ )
+ def test_same_on_batch_single_batch_map_4570(self, augmentation_cls, device, dtype):
+ torch.manual_seed(4570)
+ image = torch.full((1, 3, 5, 9), 0.3, device=device, dtype=dtype)
+ aug = augmentation_cls(roughness=(0.2, 0.8), same_on_batch=True, p=1.0).to(device, dtype)
+ output = aug(image)
+ plasma = aug._params["plasma"]
+ expected_channels = 1 if augmentation_cls is RandomPlasmaShadow else 3
+ assert plasma.shape == (1, expected_channels, 5, 9)
+ assert plasma.device == image.device
+ assert plasma.dtype == image.dtype
+ assert torch.isfinite(plasma).all(), "plasma-single-batch: nonfinite map"
+ assert torch.isfinite(output).all(), "plasma-single-batch: nonfinite output"
+ assert output.shape == image.shape
+ assert output.device == image.device
+ assert output.dtype == image.dtype
+ params = {key: value.clone() for key, value in aug._params.items()}
+ torch.manual_seed(123)
+ assert torch.equal(output, aug(image, params=params)), "plasma-single-batch: replay mismatch"
+
@pytest.mark.parametrize(
"augmentation_cls",
[
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index c27d7195a..b7ec1c3ed 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -1687,19 +1687,16 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
assert float((out - image).abs().max()) > 0.03
assert torch.equal(aug(image, params=aug._params), out)
- # Issue #4570: with same_on_batch=True the three RandomPlasma* classes share their scalar draws, but
- # diamond_square draws one fractal map per sample, so identical inputs can come back different. #3624
- # reported this together with RandomGaussianNoise and RandomChannelShuffle, and #3723 fixed only those two.
- # The maps differ on every draw; the outputs need not. RandomPlasmaShadow shades a pixel only where its
- # map is below the shared `shade_quantity`, so a high quantity shades every pixel alike -- on this 0.3
- # fixture its outputs are identical for 66 of seeds 0..199 (0 for the other two classes) -- and its
- # output leg is not asserted.
+ # Issue #4570: with same_on_batch=True the three RandomPlasma* classes share their scalar draws and
+ # expanded fractal map view, so identical inputs receive identical transformations. #3624 reported this
+ # together with RandomGaussianNoise and RandomChannelShuffle, and #3723 fixed only those two.
# Snippet used to generate expected:
# torch.manual_seed(0); aug = K.RandomPlasmaBrightness(p=1.0, same_on_batch=True)
# y = aug(torch.full((4, 3, 8, 8), 0.3)); print(torch.equal(aug._params["plasma"][0], aug._params["plasma"][1]))
- # executed 2026-09-15 (torch 2.14.0, cpu) -> `False` for all three classes, with the outputs differing too.
+ # print(torch.equal(y[0], y[1]))
+ # executed 2026-09-16 (torch 2.9.1+cpu, cpu) -> `True` for maps and outputs for all three classes.
@pytest.mark.parametrize("name", ["RandomPlasmaBrightness", "RandomPlasmaContrast", "RandomPlasmaShadow"])
- def test_wart_plasma_same_on_batch_draws_one_map_per_sample_4570(self, device, dtype, name):
+ def test_convention_plasma_same_on_batch_shares_map_4570(self, device, dtype, name):
image = torch.full((4, 3, 8, 8), 0.3, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
aug = getattr(K, name)(p=1.0, same_on_batch=True)
@@ -1707,9 +1704,12 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
for key, value in aug._params.items():
if key not in ("plasma", "forward_input_shape"):
assert all(torch.equal(value[0], value[b]) for b in range(4)), f"{key} is not shared"
- assert not torch.equal(aug._params["plasma"][0], aug._params["plasma"][1])
- if name != "RandomPlasmaShadow":
- assert not torch.equal(out[0], out[1])
+ assert torch.equal(aug._params["plasma"][0], aug._params["plasma"][1])
+ # The map is expanded, not repeated: a batch stride of 0 is the storage promise
+ # `IntensityAugmentationBase2D`'s Convention block makes, and `repeat` would satisfy the
+ # equality above while quietly allocating (and un-aliasing) one map per sample.
+ assert aug._params["plasma"].stride()[0] == 0
+ assert torch.equal(out[0], out[1])
# Row 6c-43 in its new state: the `math domain error` the audit saw on a one-pixel axis is gone,
# so a 1x1 and a 1x8 image now run and keep their shape.