Repository: pytorch/vision

Issue:
torchvision.transforms.v2.Lambda Transform Not Working
### 🐛 Describe the bug

Replacing `torchvision.transforms` with `torchvision.transforms.v2` results in the `Lambda` transform not executing, i.e. it is like the lambda function is never called.

The following does not execute Lambda:
```python
import torch
import torchvision.transforms.v2 as transforms
from torchvision.utils import flow_to_image

class FlowToPILImage(transforms.Compose):
    def __init__(self):
        super().__init__([
            transforms.Lambda(lambda flow: flow_to_image(torch.from_numpy(flow))),
            transforms.ToPILImage(mode='RGB'),
        ])
```

whereas the following is working as expected:
```python
import torch
import torchvision.transforms as transforms
from torchvision.utils import flow_to_image

class FlowToPILImage(transforms.Compose):
    def __init__(self):
        super().__init__([
            transforms.Lambda(lambda flow: flow_to_image(torch.from_numpy(flow))),
            transforms.ToPILImage(mode='RGB'),
        ])
```

The bug was found by overriding the `forward` method of the `transforms.Compose` and debugging step-by-step.

### Versions

PyTorch version: 2.0.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.9.16 | packaged by conda-forge | (main, Feb  1 2023, 21:39:03)  [GCC 11.3.0] (64-bit runtime)
Python platform: Linux-5.19.0-41-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce GTX 1080 Ti
GPU 1: NVIDIA GeForce GTX 1080 Ti

Nvidia driver version: 530.41.03
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Address sizes:                   46 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          20
On-line CPU(s) list:             0-19
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) CPU E5-2650 v3 @ 2.30GHz
CPU family:                      6
Model:                           63
Thread(s) per core:              2
Core(s) per socket:              10
Socket(s):                       1
Stepping:                        2
CPU max MHz:                     3000.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        4597.03
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm cpuid_fault epb invpcid_single pti intel_ppin ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc dtherm ida arat pln pts md_clear flush_l1d
Virtualization:                  VT-x
L1d cache:                       320 KiB (10 instances)
L1i cache:                       320 KiB (10 instances)
L2 cache:                        2.5 MiB (10 instances)
L3 cache:                        25 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-19
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] pytorch-lightning==2.0.2
[pip3] torch==2.0.0
[pip3] torchaudio==2.0.0
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.0
[pip3] triton==2.0.0
[conda] blas                      2.116                       mkl    conda-forge
[conda] blas-devel                3.9.0            16_linux64_mkl    conda-forge
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libblas                   3.9.0            16_linux64_mkl    conda-forge
[conda] libcblas                  3.9.0            16_linux64_mkl    conda-forge
[conda] liblapack                 3.9.0            16_linux64_mkl    conda-forge
[conda] liblapacke                3.9.0            16_linux64_mkl    conda-forge
[conda] mkl                       2022.1.0           h84fe81f_915    conda-forge
[conda] mkl-devel                 2022.1.0           ha770c72_916    conda-forge
[conda] mkl-include               2022.1.0           h84fe81f_915    conda-forge
[conda] numpy                     1.24.3           py39h6183b62_0    conda-forge
[conda] pytorch                   2.0.0           py3.9_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_3    pytorch
[conda] pytorch-lightning         2.0.2                    pypi_0    pypi
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.0                py39_cu118    pytorch
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchtriton               2.0.0                      py39    pytorch
[conda] torchvision               0.15.0               py39_cu118    pytorch


cc @vfdev-5


Discussion:

Resolving patch:
diff --git a/torchvision/transforms/v2/_misc.py b/torchvision/transforms/v2/_misc.py
--- a/torchvision/transforms/v2/_misc.py
+++ b/torchvision/transforms/v2/_misc.py
@@ -32,10 +32,12 @@ class Lambda(Transform):
         lambd (function): Lambda/function to be used for transform.
     """
 
+    _transformed_types = (object,)
+
     def __init__(self, lambd: Callable[[Any], Any], *types: Type):
         super().__init__()
         self.lambd = lambd
-        self.types = types or (object,)
+        self.types = types or self._transformed_types
 
     def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
         if isinstance(inpt, self.types):


Test patch:
diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py
--- a/test/test_transforms_v2.py
+++ b/test/test_transforms_v2.py
@@ -2137,3 +2137,38 @@ def test_no_warnings_v1_namespace():
         from torchvision.datasets import ImageNet
     """
     assert_run_python_script(textwrap.dedent(source))
+
+
+class TestLambda:
+    inputs = pytest.mark.parametrize("input", [object(), torch.empty(()), np.empty(()), "string", 1, 0.0])
+
+    @inputs
+    def test_default(self, input):
+        was_applied = False
+
+        def was_applied_fn(input):
+            nonlocal was_applied
+            was_applied = True
+            return input
+
+        transform = transforms.Lambda(was_applied_fn)
+
+        transform(input)
+
+        assert was_applied
+
+    @inputs
+    def test_with_types(self, input):
+        was_applied = False
+
+        def was_applied_fn(input):
+            nonlocal was_applied
+            was_applied = True
+            return input
+
+        types = (torch.Tensor, np.ndarray)
+        transform = transforms.Lambda(was_applied_fn, *types)
+
+        transform(input)
+
+        assert was_applied is isinstance(input, types)