Skip to content

Raise validation error when no transforms passed to RandomApply, RandomChoice and RandomOrder. #9130

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions test/test_transforms_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -2520,14 +2520,29 @@ def test_errors(self):
with pytest.raises(TypeError, match="Argument transforms should be a sequence of callables"):
cls(lambda x: x)

with pytest.raises(ValueError, match="at least one transform"):
transforms.Compose([])
for cls in (
transforms.Compose,
transforms.RandomApply,
transforms.RandomChoice,
transforms.RandomOrder,
):

with pytest.raises(ValueError, match="at least one transform"):
cls([])

for p in [-1, 2]:
with pytest.raises(ValueError, match=re.escape("value in the interval [0.0, 1.0]")):
transforms.RandomApply([lambda x: x], p=p)

for transforms_, p in [([lambda x: x], []), ([], [1.0])]:
for transforms_, p in [
([lambda x: x], []),
(
[lambda x: x, lambda x: x],
[
1.0,
],
),
]:
with pytest.raises(ValueError, match="Length of p doesn't match the number of transforms"):
transforms.RandomChoice(transforms_, p=p)

Expand Down
7 changes: 6 additions & 1 deletion torchvision/transforms/v2/_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: floa

if not isinstance(transforms, (Sequence, nn.ModuleList)):
raise TypeError("Argument transforms should be a sequence of callables or a `nn.ModuleList`")
elif not transforms:
raise ValueError("Pass at least one transform")
self.transforms = transforms

if not (0.0 <= p <= 1.0):
Expand Down Expand Up @@ -133,7 +135,8 @@ def __init__(
) -> None:
if not isinstance(transforms, Sequence):
raise TypeError("Argument transforms should be a sequence of callables")

elif not transforms:
raise ValueError("Pass at least one transform")
if p is None:
p = [1] * len(transforms)
elif len(p) != len(transforms):
Expand Down Expand Up @@ -163,6 +166,8 @@ class RandomOrder(Transform):
def __init__(self, transforms: Sequence[Callable]) -> None:
if not isinstance(transforms, Sequence):
raise TypeError("Argument transforms should be a sequence of callables")
elif not transforms:
raise ValueError("Pass at least one transform")
super().__init__()
self.transforms = transforms

Expand Down
Loading