π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
# 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
import kornia.augmentation as K
from kornia.core._compat import torch_version_lt
from testing.augmentation.utils import reproducibility_test
from testing.base import BaseTester
class TestSequential:
@pytest.mark.parametrize(
"random_apply_weights,match",
[(None, r"No parameters available for inversing"), ([0.8, 0.9], r"length of `random_apply_weights`")],
)
def test_exception(self, random_apply_weights, match, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
with pytest.raises(ValueError, match=match):
K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights
).inverse(inp)
@pytest.mark.parametrize("same_on_batch", [True, False, None])
@pytest.mark.parametrize("keepdim", [True, False, None])
@pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 20, True, False])
def test_construction(self, same_on_batch, keepdim, random_apply):
aug = K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
K.RandomMixUpV2(p=1.0),
same_on_batch=same_on_batch,
keepdim=keepdim,
random_apply=random_apply,
)
aug.same_on_batch = True
aug.keepdim = True
for m in aug.children():
assert m.same_on_batch is True, m.same_on_batch
assert m.keepdim is True, m.keepdim
@pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward(self, random_apply, device, dtype):
with torch.random.fork_rng():
torch.manual_seed(0)
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
aug = K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
kornia.filters.MedianBlur((3, 3)),
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)),
K.ImageSequential(K.RandomAffine(360, p=1.0)),
K.RandomAffine(360, p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=random_apply,
)
out = aug(inp)
assert out.shape == inp.shape
reproducibility_test(inp, aug)
@pytest.mark.usefixtures("restore_torch_rng")
class TestConventionImageSequential(BaseTester):
"""Batch-6 convention pins for `ImageSequential`.
Literals generated by the body of each pin, executed on this worktree on 2026-09-11 with
`.venv/bin/python` (torch 2.14.0, python 3.11, cpu, float32).
"""
def test_convention_if_unsupported_ops_skip_leaves_plain_modules_applied_4423(self, device, dtype):
# #4423: the inverse used to skip a plain `nn.Module` under every value of the flag. That behavior is now
# what "skip" selects: `inverse` undoes only the invertible members and returns something that is not the
# input. The deterministic checkerboard ensures the omitted blur visibly changes the output.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")
x = ((yy + xx) % 2).to(dtype).expand(2, 3, 6, 8)
assert K.ImageSequential(K.RandomHorizontalFlip(p=1.0)).if_unsupported_ops == "raise"
seq = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),
if_unsupported_ops="skip",
)
out = seq(x)
inverted = seq.inverse(out)
self.assert_close(inverted, out.flip(-1)) # only the flip was undone, the blur was skipped
assert (inverted - x).abs().max().item() > 0.1 # and the round trip is not the input
@pytest.mark.parametrize("container", ["ImageSequential", "AugmentationSequential"])
@pytest.mark.parametrize("output_type", ["numpy", "pil"])
def test_show_and_save_after_a_numpy_or_pil_output_4956(self, container, output_type, tmp_path, device, dtype):
# `.show()` / `.save()` render a tensor cache, so the container caches the augmented tensor before it
# converts the output to NumPy or PIL; it used to cache the converted output and the helpers failed on it
from PIL import Image as PILImage
if output_type == "numpy" and dtype == torch.bfloat16:
pytest.skip("NumPy has no bfloat16")
image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)
aug = getattr(K, container)(K.RandomHorizontalFlip(p=1.0))
output = aug(image, output_type=output_type)
if output_type == "numpy":
# channels-last (#5207)
assert output.shape == (2, 6, 8, 3)
assert not isinstance(output, torch.Tensor)
else:
assert len(output) == 2
assert all(isinstance(out, PILImage.Image) for out in output)
cached = aug._output_image
assert isinstance(cached, torch.Tensor)
assert not cached.requires_grad
self.assert_close(cached.to(device), image.detach().flip(-1))
if container == "AugmentationSequential":
assert cached.device == image.device # no device-to-host copy in the forward pass (#4918)
assert isinstance(aug.show(display=False), PILImage.Image)
output_path = tmp_path / "output.png"
aug.save(name=str(output_path))
assert output_path.is_file()
@pytest.mark.parametrize("container", ["ImageSequential", "AugmentationSequential"])
def test_invalid_output_type_raises(self, container, device, dtype):
aug = getattr(K, container)(K.RandomHorizontalFlip(p=1.0))
with pytest.raises(ValueError, match="Invalid output_type"):
aug(torch.zeros(1, 3, 4, 4, device=device, dtype=dtype), output_type="jpg")
@pytest.mark.parametrize("random_apply", [0, (0,), (0, 0), (0, 1), (0, 2)])
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_range_with_zero_never_crashes_6055(self, random_apply, container, device, dtype):
# A drawn count of 0 used to reach torch.multinomial and raise "cannot sample n_sample <= 0 samples", so a
# range that includes 0 crashed whenever the draw was 0. It now applies no transformation.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=random_apply)
counts = set()
for seed in range(30):
torch.manual_seed(seed)
out = seq(x)
counts.add(len(seq._params))
if len(seq._params) == 0:
self.assert_close(out, x, rtol=0.0, atol=0.0)
assert 0 in counts
@pytest.mark.parametrize("random_apply", [-1, (-1,), (-1, 1), (2, 1)])
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_rejects_negative_or_inverted_ranges_6055(self, random_apply, container):
# These used to fail only at call time, with torch.multinomial's or torch.randint's own error.
with pytest.raises(ValueError, match="random_apply must select a non-negative number of transformations"):
container(K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=random_apply)
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_zero_draw_adds_no_mix_6055(self, container, device, dtype):
# A mix member replaces one of the drawn members, so a drawn count of 0 must not add it either.
x = torch.rand(4, 3, 6, 8, device=device, dtype=dtype)
seq = container(K.RandomHorizontalFlip(p=1.0), K.RandomMixUpV2(p=1.0), random_apply=0)
for seed in range(20):
torch.manual_seed(seed)
out = seq(x)
assert seq._params == []
self.assert_close(out, x, rtol=0.0, atol=0.0)
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_mix_insertion_skips_zero_weight_members_6068(self, container, device, dtype):
# The mix-insertion step drew among every member whose weight was 0 once the mix weights were zeroed, which
# included ordinary members given weight 0, so RandomVerticalFlip was applied in about a third of the calls.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=1,
random_apply_weights=[1.0, 0.0, 1.0],
)
selected = set()
for seed in range(100):
torch.manual_seed(seed)
seq(x)
selected.add(tuple(p.name for p in seq._params))
assert selected == {("RandomHorizontalFlip_0",), ("RandomMixUpV2_2",)}
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_mix_insertion_with_all_ordinary_weights_zero_6068(self, container, device, dtype):
# With every ordinary weight 0, nothing ordinary is drawn, and the insertion step may add only the mix member.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=(1, 2),
random_apply_weights=[0.0, 0.0, 1.0],
)
selected = set()
for seed in range(100):
torch.manual_seed(seed)
out = seq(x)
selected.add(tuple(p.name for p in seq._params))
if not seq._params:
self.assert_close(out, x, rtol=0.0, atol=0.0)
assert selected == {(), ("RandomMixUpV2_2",)}
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_mix_insertion_draws_among_every_mix_member_6068(self, container, device, dtype):
# The insertion draws uniformly among the mix members and does not honor their own weights, as on main: both
# mix members are inserted although their weights are 0.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomMixUpV2(p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=2,
random_apply_weights=[1.0, 1.0, 0.0, 0.0],
)
mixes = set()
for seed in range(30):
torch.manual_seed(seed)
seq(x)
names = [p.name for p in seq._params]
assert len(names) == 2
mixes.update(name for name in names if name.startswith("RandomMixUpV2"))
assert mixes == {"RandomMixUpV2_2", "RandomMixUpV2_3"}
def test_convention_slice_crop_inverse_restores_the_canvas(self, device, dtype):
seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))
out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))
restored = seq.inverse(out)
assert restored.shape == (1, 3, 6, 8)
self.assert_close(restored[..., 1:5, 1:7], out)
def test_convention_get_transformation_matrix_recomputes_older_params(self, device, dtype):
# Module matrices hold only the most recent call. Supplying recorded parameters from an earlier call
# therefore requires recompute=True.
image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
seq = K.ImageSequential(K.RandomHorizontalFlip(p=0.5), K.RandomVerticalFlip(p=0.5))
torch.manual_seed(1)
seq(image)
old_params = seq._params
torch.manual_seed(101)
seq(image)
current = seq.get_transformation_matrix(image, old_params)
recomputed = seq.get_transformation_matrix(image, old_params, recompute=True)
assert current is not None
assert recomputed is not None
assert not torch.equal(current, recomputed)
def test_convention_if_unsupported_ops_raise_raises_not_implemented(self, device, dtype):
# #4423: `if_unsupported_ops` defaults to "raise", so inverting a chain that holds a non-invertible
# plain `nn.Module` raises `NotImplementedError` rather than silently skipping it.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),
if_unsupported_ops="raise",
)
out = seq(x)
with pytest.raises(NotImplementedError):
seq.inverse(out)
def test_convention_if_unsupported_ops_raise_leaves_intensity_augmentations_applied_4423(self, device, dtype):
# #4423: "raise" is about plain `nn.Module` members only. An intensity augmentation has no geometry to
# undo and is left applied on the inverse path, as before, under both settings.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = K.ImageSequential(K.RandomHorizontalFlip(p=1.0), K.ColorJiggle(0.3, 0.3, p=1.0))
out = seq(x)
self.assert_close(seq.inverse(out), out.flip(-1))
def test_convention_if_unsupported_ops_applies_to_each_container_own_members_4423(self, device, dtype):
# #4423: a nested container inverts its own members, so its own setting decides for the plain modules it
# holds, and a nested container is never itself an unsupported member of the outer one.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))
inner_skips = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
K.ImageSequential(blur, if_unsupported_ops="skip"),
if_unsupported_ops="raise",
)
out = inner_skips(x)
self.assert_close(inner_skips.inverse(out), out.flip(-1))
inner_raises = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
K.ImageSequential(blur, if_unsupported_ops="raise"),
if_unsupported_ops="skip",
)
out = inner_raises(x)
with pytest.raises(NotImplementedError, match="GaussianBlur2d"):
inner_raises.inverse(out)
def test_convention_if_unsupported_ops_ignores_members_random_apply_did_not_select_4423(self, device, dtype):
# #4423: only the members recorded in `params` are checked, so a plain module that `random_apply` did not
# select cannot make "raise" fire.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))
seq = K.ImageSequential(K.RandomHorizontalFlip(p=1.0), blur, random_apply=1, random_apply_weights=[1.0, 0.0])
out = seq(x)
assert [p.name for p in seq._params] == ["RandomHorizontalFlip_0"]
self.assert_close(seq.inverse(out), out.flip(-1))
@pytest.mark.parametrize(
"weights",
[
[1, 0],
(1, 0),
[True, False],
torch.tensor([1, 0]),
torch.tensor([True, False]),
torch.tensor([1.0, 0.0]),
torch.tensor([1.0, 0.0], dtype=torch.float64),
],
)
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_weights_accept_integer_and_tensor_weights_6049(self, weights, container, device, dtype):
# Integer and boolean weights used to reach torch.multinomial as an int64/bool tensor, and a tensor of weights
# was tested for its truth value; both raised. Any of them now selects in proportion, like float weights.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=1, random_apply_weights=weights
)
assert seq.random_apply_weights.is_floating_point()
for seed in range(5):
torch.manual_seed(seed)
out = seq(x)
assert [p.name for p in seq._params] == ["RandomHorizontalFlip_0"]
self.assert_close(out, x.flip(-1))
def test_random_apply_weights_keep_a_float_dtype_6049(self):
# Float weights keep their dtype, so the selections of existing calls are unchanged.
flips = (K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0))
assert K.ImageSequential(
*flips, random_apply=1, random_apply_weights=[0.7, 0.3]
).random_apply_weights.dtype == (torch.get_default_dtype())
weights64 = torch.tensor([0.7, 0.3], dtype=torch.float64)
assert K.ImageSequential(*flips, random_apply=1, random_apply_weights=weights64).random_apply_weights.dtype == (
torch.float64
)
assert K.ImageSequential(*flips, random_apply=1).random_apply_weights.dtype == torch.get_default_dtype()
@pytest.mark.parametrize("weights", [[7, 2, 1], torch.tensor([7, 2, 1])])
def test_random_apply_weights_integer_select_like_floats_6049(self, weights):
# Integer weights are relative weights, converted to the default dtype: they select exactly as the same values
# given as floats.
def build(w):
augs = (K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), K.RandomInvert(p=1.0))
return K.ImageSequential(*augs, random_apply=1, random_apply_weights=w)
x = torch.zeros(1, 3, 4, 4)
reference, seq = build([7.0, 2.0, 1.0]), build(weights)
assert seq.random_apply_weights.dtype == torch.get_default_dtype()
for seed in range(30):
torch.manual_seed(seed)
reference(x)
torch.manual_seed(seed)
seq(x)
assert [p.name for p in seq._params] == [p.name for p in reference._params]
@pytest.mark.parametrize("weights", [torch.tensor([[0.7], [0.3]]), [[1.0, 0.0], [0.0, 1.0]]])
def test_random_apply_weights_reject_non_vectors_6049(self, weights):
# A nested float list used to be accepted and drew a selection per row, so random_apply=1 applied two.
with pytest.raises(ValueError, match="must be one-dimensional"):
K.ImageSequential(
K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=1, random_apply_weights=weights
)
@pytest.mark.parametrize("weights", [[7.0, 2.0, 1.0], [7, 2, 1], [0.7, 0.2, 0.1]])
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_count_above_members_samples_with_replacement_6069(self, weights, container, device, dtype):
# A count above the number of members used to sample without replacement whenever the weights summed to at
# least the count, and torch.multinomial raised "cannot sample n_sample > prob_dist.size(-1) samples without
# replacement". It now samples with replacement, as the default weights already did.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomInvert(p=1.0),
random_apply=4,
random_apply_weights=weights,
)
for seed in range(20):
torch.manual_seed(seed)
seq(x)
assert len(seq._params) == 4
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_count_above_nonzero_weights_skips_zero_weight_members_6069(self, container, device, dtype):
# Three draws without replacement from two nonzero weights summing to 10 filled the third place with the
# member of weight 0; they now repeat the two members with a nonzero weight and never select it.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
seq = container(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomInvert(p=1.0),
random_apply=3,
random_apply_weights=[7, 0, 3],
)
for seed in range(20):
torch.manual_seed(seed)
seq(x)
names = [p.name for p in seq._params]
assert len(names) == 3
assert set(names) <= {"RandomHorizontalFlip_0", "RandomInvert_2"}
@pytest.mark.parametrize(
("weights", "random_apply", "with_mix", "repeats"),
[
([7.0, 2.0, 1.0], True, False, False),
([7, 2, 1, 4], True, True, False),
([2.0, 1.0, 1.0, 1.0], 4, True, False),
([7, 0, 3, 1], 3, True, False),
([7, 0, 3, 1], True, True, True),
([7, 2, 1, 4], 5, True, True),
([0.7, 0.2, 0.1], 2, False, True),
],
)
@pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
def test_random_apply_repeats_only_past_the_weights_6069(
self, weights, random_apply, with_mix, repeats, container, device, dtype
):
# A count the nonzero weights can fill is drawn without repetition, also when a mix augmentation is certain to
# take the last place, as with random_apply=True; a count they cannot fill, or one above the sum of the weights,
# repeats. A mix augmentation is applied at most once either way.
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
members = [K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), K.RandomInvert(p=1.0)]
if with_mix:
members.append(K.RandomMixUpV2(p=1.0))
seq = container(*members, random_apply=random_apply, random_apply_weights=weights)
count = len(members) if random_apply is True else random_apply
repeated = 0
for seed in range(20):
torch.manual_seed(seed)
seq(x)
names = [p.name for p in seq._params]
assert len(names) == count
assert sum(name.startswith("RandomMixUpV2") for name in names) <= 1
repeated += len(set(names)) < len(names)
assert (repeated > 0) == repeats
def test_random_apply_uncertain_mix_insertion_draws_no_member_of_weight_0_6069(self):
# Three places from four ordinary members and a mix are not certain to include the mix, so a draw from two
# nonzero weights repeats them; when no mix is inserted, no member of weight 0 fills the third place.
seq = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomInvert(p=1.0),
K.RandomGrayscale(p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=3,
random_apply_weights=[7.0, 0.0, 0.0, 3.0, 1.0],
)
without_mix = 0
for seed in range(40):
torch.manual_seed(seed)
children, mix_added = seq.get_random_forward_sequence()
names = [name for name, _ in children]
assert len(names) == 3
if not mix_added:
without_mix += 1
assert set(names) <= {"RandomHorizontalFlip_0", "RandomGrayscale_3"}
assert without_mix > 0
def test_random_apply_without_mix_never_draws_a_mix_member_6069(self):
# Four places from three nonzero ordinary weights summing to 10 were filled with the mix member, whose weight
# is zeroed for this draw, although with_mix=False asks for no mix augmentation.
seq = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0),
K.RandomVerticalFlip(p=1.0),
K.RandomInvert(p=1.0),
K.RandomMixUpV2(p=1.0),
random_apply=4,
random_apply_weights=[7.0, 2.0, 1.0, 1.0],
)
for seed in range(20):
torch.manual_seed(seed)
children, mix_added = seq.get_random_forward_sequence(with_mix=False)
names = [name for name, _ in children]
assert not mix_added
assert len(names) == 4
assert "RandomMixUpV2_3" not in names
def test_convention_augmentation_sequential_leaves_plain_modules_applied_4423(self, device, dtype):
# #4423: `AugmentationSequential` does not take `if_unsupported_ops`; it leaves a plain module child applied,
# also when nested in another container, while a nested `ImageSequential` follows its own setting.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))
nested_aug = K.ImageSequential(
K.RandomHorizontalFlip(p=1.0), K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), blur)
)
out = nested_aug(x)
self.assert_close(nested_aug.inverse(out), out.flip(-2).flip(-1))
nested_image = K.AugmentationSequential(
K.RandomHorizontalFlip(p=1.0), K.ImageSequential(K.RandomVerticalFlip(p=1.0), blur)
)
out = nested_image(x)
with pytest.raises(NotImplementedError, match="GaussianBlur2d"):
nested_image.inverse(out)
def test_convention_video_sequential_passes_if_unsupported_ops_through_4423(self, device, dtype):
# #4423: VideoSequential inverts through ImageSequential, so it takes the same setting.
x = torch.rand(1, 3, 3, 6, 8, device=device, dtype=dtype)
blur = kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5))
raises = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), blur)
assert raises.if_unsupported_ops == "raise"
out = raises(x)
with pytest.raises(NotImplementedError, match="GaussianBlur2d"):
raises.inverse(out)
skips = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), blur, if_unsupported_ops="skip")
out = skips(x)
self.assert_close(skips.inverse(out), out.flip(-1))
with pytest.raises(ValueError, match=r"if_unsupported_ops.*must be either"):
K.VideoSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")
def test_convention_if_unsupported_ops_rejects_invalid_value(self):
# #4423: construction accepts only "raise" and "skip".
with pytest.raises(ValueError, match=r"if_unsupported_ops.*must be either"):
K.ImageSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")