Skip to content

RandomOrder transform now accepts torch.Tensor and works well with torch.seed #7773

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
40 changes: 34 additions & 6 deletions torchvision/transforms/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,16 +550,44 @@ def __repr__(self) -> str:
return format_string


class RandomOrder(RandomTransforms):
"""Apply a list of transformations in a random order. This transform does not support torchscript."""
class RandomOrder(torch.nn.Module):
"""Apply a list of transformations in a random order.

def __call__(self, img):
order = list(range(len(self.transforms)))
random.shuffle(order)
.. note::
In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of
transforms as shown below:

>>> transforms = transforms.RandomOrder(torch.nn.ModuleList([
>>> transforms.ColorJitter(),
>>> ]))
>>> scripted_transforms = torch.jit.script(transforms)

Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
`lambda` functions or ``PIL.Image``.

Args:
transforms (sequence or torch.nn.Module): list of transformations
"""

def __init__(self, transforms):
super().__init__()
_log_api_usage_once(self)
self.transforms = transforms

def forward(self, img):
order = torch.randperm(len(self.transforms))
for i in order:
img = self.transforms[i](img)
img = self.transforms[i.item()](img)
return img

def __repr__(self) -> str:
format_string = self.__class__.__name__ + "("
for t in self.transforms:
format_string += "\n"
format_string += f" {t}"
format_string += "\n)"
return format_string


class RandomChoice(RandomTransforms):
"""Apply single transformation randomly picked from a list. This transform does not support torchscript."""
Expand Down