Skip to content

Make RandomApply torchscriptable in V2 #7256

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 2 commits into from
Feb 15, 2023
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
5 changes: 5 additions & 0 deletions test/test_prototype_transforms_consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,11 @@ def test_random_apply(self, p, sequence_type):

check_call_consistency(prototype_transform, legacy_transform)

if sequence_type is nn.ModuleList:
# quick and dirty test that it is jit-scriptable
scripted = torch.jit.script(prototype_transform)
scripted(torch.rand(1, 3, 300, 300))

# We can't test other values for `p` since the random parameter generation is different
@pytest.mark.parametrize("probabilities", [(0, 1), (1, 0)])
def test_random_choice(self, probabilities):
Expand Down
8 changes: 7 additions & 1 deletion torchvision/prototype/transforms/_container.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import warnings
from typing import Any, Callable, List, Optional, Sequence, Union
from typing import Any, Callable, Dict, List, Optional, Sequence, Union

import torch

from torch import nn
from torchvision import transforms as _transforms
from torchvision.prototype.transforms import Transform


Expand All @@ -28,6 +29,8 @@ def extra_repr(self) -> str:


class RandomApply(Transform):
_v1_transform_cls = _transforms.RandomApply

def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: float = 0.5) -> None:
super().__init__()

Expand All @@ -39,6 +42,9 @@ def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: floa
raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].")
self.p = p

def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
return {"transforms": self.transforms, "p": self.p}
Comment on lines +45 to +46
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why, but the transforms key was missing when using _extract_params_for_v1_transform() from the base class.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nn.Module overwrites __setattr__. One of the things it is doing is to not assign other nn.Module's into self.__dict__, but rather into self._modules. Since we only go through self.__dict__, we don't pick up self.transforms since isinstance(nn.ModuleList(...), nn.Module).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow, good catch! thanks for the explanation


def forward(self, *inputs: Any) -> Any:
sample = inputs if len(inputs) > 1 else inputs[0]

Expand Down
5 changes: 3 additions & 2 deletions torchvision/prototype/transforms/_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,9 @@ def __prepare_scriptable__(self) -> nn.Module:
if self._v1_transform_cls is None:
raise RuntimeError(
f"Transform {type(self).__name__} cannot be JIT scripted. "
f"This is only support for backward compatibility with transforms which already in v1."
f"For torchscript support (on tensors only), you can use the functional API instead."
"torchscript is only supported for backward compatibility with transforms "
"which are already in torchvision.transforms. "
"For torchscript support (on tensors only), you can use the functional API instead."
)

return self._v1_transform_cls(**self._extract_params_for_v1_transform())
Expand Down