pytorch / vision

Datasets, Transforms and Models specific to Computer Vision
https://pytorch.org/vision
BSD 3-Clause "New" or "Revised" License
16.27k stars 6.96k forks source link

Transforms v2.RandomRotation fail when expand=True with ValueError(f"Found multiple HxW dimensions in the sample: {sequence_to_str(sorted(sizes))}") #8654

Open jeff-zimmerman opened 2 months ago

jeff-zimmerman commented 2 months ago

🐛 Describe the bug

Example:

import torchvision
from torchvision.transforms import v2

 transforms = v2.Compose([
        v2.ToImage(),
        v2.RandomRotation(degrees=(-45, 45), expand=True),
    ])

    # Set up COCO dataset

    train_dataset = torchvision.datasets.CocoDetection(coco_img_root, coco_ann_root, transforms=transforms)
    train_dataset = torchvision.datasets.wrap_dataset_for_transforms_v2(train_dataset, target_keys=['boxes', 'labels'])
    img, labels = train_dataset[0]

Suggested Solution

The off by one error is thrown in v2.RandomRotation when expand=True. A similar error is referenced for image rotation in issue #7714, however a similar solution was not implemented for bounding boxes.

The issue can be solved by changing line 837 of torchvision/transforms/v2/functional/_geometry.py in _affine_bounding_boxes_with_expand().

from:

def _affine_bounding_boxes_with_expand()
...
    if expand:
    ....
    # Estimate meta-data for image with inverted=True
    affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear)
...

to:

def _affine_bounding_boxes_with_expand()
...
    if expand:
    ....
    # Estimate meta-data for image with inverted=True
    affine_vector = _get_inverse_affine_matrix([0, 0], angle, translate, scale, shear)
...

Versions

Collecting environment information... PyTorch version: 2.4.0+cu124 Is debug build: False CUDA used to build PyTorch: 12.4 ROCM used to build PyTorch: N/A

OS: Linux Mint 21.3 (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.35

Python version: 3.11.10 (main, Sep 7 2024, 18:35:41) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-6.8.0-40-generic-x86_64-with-glibc2.35 Is CUDA available: False CUDA runtime version: No CUDA CUDA_MODULE_LOADING set to: N/A GPU models and configuration: No CUDA Nvidia driver version: No CUDA cuDNN version: No CUDA 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: 43 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 8 On-line CPU(s) list: 0-7 Vendor ID: AuthenticAMD Model name: AMD Ryzen 5 3500U with Radeon Vega Mobile Gfx CPU family: 23 Model: 24 Thread(s) per core: 2 Core(s) per socket: 4 Socket(s): 1 Stepping: 1 Frequency boost: enabled CPU max MHz: 2100.0000 CPU min MHz: 1400.0000 BogoMIPS: 4192.45 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sev sev_es Virtualization: AMD-V L1d cache: 128 KiB (4 instances) L1i cache: 256 KiB (4 instances) L2 cache: 2 MiB (4 instances) L3 cache: 4 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-7 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; untrained return thunk; SMT vulnerable Vulnerability Spec rstack overflow: Mitigation; Safe RET 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; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] numpy==2.1.0 [pip3] torch==2.4.0+cu124 [pip3] torchmetrics==1.4.1 [pip3] torchvision==0.19.0+cu124 [pip3] triton==3.0.0 [conda] Could not collect

venkatram-dev commented 1 month ago

not able to replicate with coco 2017 dataset https://cocodataset.org/#download.

Will you be able to share any other dataset to replicate this ?

jeff-zimmerman commented 1 month ago

Same thing happened with WIDERFace dataset. It seems inherent to the image/box rotation. When expand=True, image rotation uses _get_inverse_affine_matrix([0, 0], angle, translate, scale, shear) while box rotation uses _get_inverse_affine_matrix(center, angle, translate, scale, shear) by default.

venkatram-dev commented 1 month ago

Not able to replicate the error with widerface dataset as well. Used the code below. If possible, please share exact code which shows the exception.

import torch
import torchvision
from torchvision.transforms import v2
from torchvision.datasets import WIDERFace

# Define the v2 transformation with expand=True
transforms = v2.Compose([
    v2.ToImage(),
    v2.RandomRotation(degrees=(-45, 45), expand=True),
])

widerface_dataset = WIDERFace(root='./widerface', split='train', transform=transforms, download=False)

valid_target_keys = ['bbox', 'blur', 'expression', 'illumination', 'occlusion', 'pose', 'invalid']

widerface_dataset = torchvision.datasets.wrap_dataset_for_transforms_v2(widerface_dataset, target_keys=valid_target_keys)

# Attempt to access a sample from the dataset

for i in range(len(widerface_dataset)):
    try:
        img, labels = widerface_dataset[i]
        print(f"Successfully processed image {i}")
    except Exception as e:
        print(f"Error encountered on image {i}: {e}")
        break
jeff-zimmerman commented 1 month ago

I see the problem now. The sizes are still affected, but without a call to torchvision.transforms.v2._utils.query_size(), they not checked for mismatch. In addition, WIDERFace does not have a transforms argument, only transform, which calls the transforms only on the image, leaving the labels unaffected. RandomIOUCrop() does check for size mismatch. Try the following code:

import torch
import torchvision
from torchvision.transforms import v2
from torchvision.datasets import CocoDetection

# Define the v2 transformation with expand=True
transforms = v2.Compose([
    v2.ToImage(),
    v2.RandomRotation(degrees=(-45, 45), expand=True),
    v2.RandomIoUCrop(),
])

coco_images = './data/coco/images/val2017'
coco_anns = './data/coco/annotations/instances_val2017.json'
coco_dataset = CocoDetection(root=coco_images, annFile=coco_anns, transforms=transforms, download=False)

valid_target_keys = ['boxes', 'labels']

coco_dataset = torchvision.datasets.wrap_dataset_for_transforms_v2(coco_dataset, target_keys=valid_target_keys)

# Attempt to access a sample from the dataset

for i in range(len(coco_dataset)):
    try:
        img, labels = coco_dataset[i]
        print(f"Successfully processed image {i}")
        break
    except Exception as e:
        print(f"Error encountered on image {i}: {e}")
        break

If you still want to use the WIDERFace dataset, you can add a transforms parameter like so:

widerface_dataset = WIDERFace(root='./widerface', split='train', download=False)
widerface_dataset.transforms = transforms
widerface_dataset = torchvision.datasets.wrap_dataset_for_transforms_v2(widerface_dataset, target_keys=valid_target_keys)

the v2 wrapper will handle the transforms as long as it exists in the wrapped dataset.

venkatram-dev commented 1 month ago

Created PR https://github.com/pytorch/vision/pull/8667

NicolasHug commented 1 month ago

Thanks for the report @jeff-zimmerman . Would you be able to share a minimal reproducing example that doesn't include one of the datatasets? Maybe sharing the original input shapes of the images and bboxes should be enough. I'd like to make sure we can write a non-regression test for this. Thank you!