From 44db71c0772e5ef5758c38d0e4e8ad9995946c80 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Tue, 25 Nov 2025 09:14:49 -0800 Subject: [PATCH 01/14] implement additional cvcuda infra for all branches to avoid duplicate setup --- torchvision/transforms/v2/_transform.py | 4 ++-- torchvision/transforms/v2/_utils.py | 3 ++- .../transforms/v2/functional/__init__.py | 2 +- .../transforms/v2/functional/_augment.py | 11 ++++++++++- .../transforms/v2/functional/_color.py | 12 +++++++++++- .../transforms/v2/functional/_geometry.py | 19 +++++++++++++++++-- torchvision/transforms/v2/functional/_misc.py | 11 +++++++++-- .../transforms/v2/functional/_utils.py | 16 ++++++++++++++++ 8 files changed, 68 insertions(+), 10 deletions(-) diff --git a/torchvision/transforms/v2/_transform.py b/torchvision/transforms/v2/_transform.py index ac84fcb6c82..bec9ffcf714 100644 --- a/torchvision/transforms/v2/_transform.py +++ b/torchvision/transforms/v2/_transform.py @@ -11,7 +11,7 @@ from torchvision.transforms.v2._utils import check_type, has_any, is_pure_tensor from torchvision.utils import _log_api_usage_once -from .functional._utils import _get_kernel +from .functional._utils import _get_kernel, is_cvcuda_tensor class Transform(nn.Module): @@ -23,7 +23,7 @@ class Transform(nn.Module): # Class attribute defining transformed types. Other types are passed-through without any transformation # We support both Types and callables that are able to do further checks on the type of the input. - _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image) + _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image, is_cvcuda_tensor) def __init__(self) -> None: super().__init__() diff --git a/torchvision/transforms/v2/_utils.py b/torchvision/transforms/v2/_utils.py index bb6051b4e61..765a772fe41 100644 --- a/torchvision/transforms/v2/_utils.py +++ b/torchvision/transforms/v2/_utils.py @@ -15,7 +15,7 @@ from torchvision._utils import sequence_to_str from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 -from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor +from torchvision.transforms.v2.functional import get_dimensions, get_size, is_cvcuda_tensor, is_pure_tensor from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT @@ -207,6 +207,7 @@ def query_size(flat_inputs: list[Any]) -> tuple[int, int]: tv_tensors.Mask, tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, + is_cvcuda_tensor, ), ) } diff --git a/torchvision/transforms/v2/functional/__init__.py b/torchvision/transforms/v2/functional/__init__.py index 032a993b1f0..52181e4624b 100644 --- a/torchvision/transforms/v2/functional/__init__.py +++ b/torchvision/transforms/v2/functional/__init__.py @@ -1,6 +1,6 @@ from torchvision.transforms import InterpolationMode # usort: skip -from ._utils import is_pure_tensor, register_kernel # usort: skip +from ._utils import is_pure_tensor, register_kernel, is_cvcuda_tensor # usort: skip from ._meta import ( clamp_bounding_boxes, diff --git a/torchvision/transforms/v2/functional/_augment.py b/torchvision/transforms/v2/functional/_augment.py index a904d8d7cbd..7ce5bdc7b7e 100644 --- a/torchvision/transforms/v2/functional/_augment.py +++ b/torchvision/transforms/v2/functional/_augment.py @@ -1,4 +1,5 @@ import io +from typing import TYPE_CHECKING import PIL.Image @@ -8,7 +9,15 @@ from torchvision.transforms.functional import pil_to_tensor, to_pil_image from torchvision.utils import _log_api_usage_once -from ._utils import _get_kernel, _register_kernel_internal +from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal + + +CVCUDA_AVAILABLE = _is_cvcuda_available() + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] +if CVCUDA_AVAILABLE: + cvcuda = _import_cvcuda() # noqa: F811 def erase( diff --git a/torchvision/transforms/v2/functional/_color.py b/torchvision/transforms/v2/functional/_color.py index be254c0d63a..5be9c62902a 100644 --- a/torchvision/transforms/v2/functional/_color.py +++ b/torchvision/transforms/v2/functional/_color.py @@ -1,3 +1,5 @@ +from typing import TYPE_CHECKING + import PIL.Image import torch from torch.nn.functional import conv2d @@ -9,7 +11,15 @@ from ._misc import _num_value_bits, to_dtype_image from ._type_conversion import pil_to_tensor, to_pil_image -from ._utils import _get_kernel, _register_kernel_internal +from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal + + +CVCUDA_AVAILABLE = _is_cvcuda_available() + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] +if CVCUDA_AVAILABLE: + cvcuda = _import_cvcuda() # noqa: F811 def rgb_to_grayscale(inpt: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py index 4fcb7fabe0d..c029488001c 100644 --- a/torchvision/transforms/v2/functional/_geometry.py +++ b/torchvision/transforms/v2/functional/_geometry.py @@ -2,7 +2,7 @@ import numbers import warnings from collections.abc import Sequence -from typing import Any, Optional, Union +from typing import Any, Optional, TYPE_CHECKING, Union import PIL.Image import torch @@ -26,7 +26,22 @@ from ._meta import _get_size_image_pil, clamp_bounding_boxes, convert_bounding_box_format -from ._utils import _FillTypeJIT, _get_kernel, _register_five_ten_crop_kernel_internal, _register_kernel_internal +from ._utils import ( + _FillTypeJIT, + _get_kernel, + _import_cvcuda, + _is_cvcuda_available, + _register_five_ten_crop_kernel_internal, + _register_kernel_internal, +) + + +CVCUDA_AVAILABLE = _is_cvcuda_available() + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] +if CVCUDA_AVAILABLE: + cvcuda = _import_cvcuda() # noqa: F811 def _check_interpolation(interpolation: Union[InterpolationMode, int]) -> InterpolationMode: diff --git a/torchvision/transforms/v2/functional/_misc.py b/torchvision/transforms/v2/functional/_misc.py index daf263df046..0fa05a2113c 100644 --- a/torchvision/transforms/v2/functional/_misc.py +++ b/torchvision/transforms/v2/functional/_misc.py @@ -1,5 +1,5 @@ import math -from typing import Optional +from typing import Optional, TYPE_CHECKING import PIL.Image import torch @@ -13,7 +13,14 @@ from ._meta import _convert_bounding_box_format -from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor +from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal, is_pure_tensor + +CVCUDA_AVAILABLE = _is_cvcuda_available() + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] +if CVCUDA_AVAILABLE: + cvcuda = _import_cvcuda() # noqa: F811 def normalize( diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index ad1eddd258b..73fafaf7425 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -169,3 +169,19 @@ def _is_cvcuda_available(): return True except ImportError: return False + + +def is_cvcuda_tensor(inpt: Any) -> bool: + """ + Check if the input is a CVCUDA tensor. + + Args: + inpt: The input to check. + + Returns: + True if the input is a CV-CUDA tensor, False otherwise. + """ + if _is_cvcuda_available(): + cvcuda = _import_cvcuda() + return isinstance(inpt, cvcuda.Tensor) + return False From e3dd70022fa1c87aca7a9a98068b6e13e802a375 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Tue, 25 Nov 2025 09:26:19 -0800 Subject: [PATCH 02/14] update make_image_cvcuda to have default batch dim --- test/common_utils.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/common_utils.py b/test/common_utils.py index 8c3c9dd58a8..e7bae60c41b 100644 --- a/test/common_utils.py +++ b/test/common_utils.py @@ -400,8 +400,9 @@ def make_image_pil(*args, **kwargs): return to_pil_image(make_image(*args, **kwargs)) -def make_image_cvcuda(*args, **kwargs): - return to_cvcuda_tensor(make_image(*args, **kwargs)) +def make_image_cvcuda(*args, batch_dims=(1,), **kwargs): + # explicitly default batch_dims to (1,) since to_cvcuda_tensor requires a batch dimension (ndims == 4) + return to_cvcuda_tensor(make_image(*args, batch_dims=batch_dims, **kwargs)) def make_keypoints(canvas_size=DEFAULT_SIZE, *, num_points=4, dtype=None, device="cpu"): From c035df1c6eaebcad25604f8c298a7d9eaf86864b Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Mon, 1 Dec 2025 18:16:27 -0800 Subject: [PATCH 03/14] add stanardized setup to main for easier updating of PRs and branches --- test/common_utils.py | 21 ++++++++++++++-- test/test_transforms_v2.py | 2 +- torchvision/transforms/v2/_utils.py | 2 +- torchvision/transforms/v2/functional/_meta.py | 24 +++++++++++++++++-- 4 files changed, 43 insertions(+), 6 deletions(-) diff --git a/test/common_utils.py b/test/common_utils.py index e7bae60c41b..3b889e93d2e 100644 --- a/test/common_utils.py +++ b/test/common_utils.py @@ -20,13 +20,15 @@ from torch.testing._comparison import BooleanPair, NonePair, not_close_error_metas, NumberPair, TensorLikePair from torchvision import io, tv_tensors from torchvision.transforms._functional_tensor import _max_value as get_max_value -from torchvision.transforms.v2.functional import to_cvcuda_tensor, to_image, to_pil_image +from torchvision.transforms.v2.functional import cvcuda_to_tensor, to_cvcuda_tensor, to_image, to_pil_image +from torchvision.transforms.v2.functional._utils import _import_cvcuda, _is_cvcuda_available from torchvision.utils import _Image_fromarray IN_OSS_CI = any(os.getenv(var) == "true" for var in ["CIRCLECI", "GITHUB_ACTIONS"]) IN_RE_WORKER = os.environ.get("INSIDE_RE_WORKER") is not None IN_FBCODE = os.environ.get("IN_FBCODE_TORCHVISION") == "1" +CVCUDA_AVAILABLE = _is_cvcuda_available() CUDA_NOT_AVAILABLE_MSG = "CUDA device not available" MPS_NOT_AVAILABLE_MSG = "MPS device not available" OSS_CI_GPU_NO_CUDA_MSG = "We're in an OSS GPU machine, and this test doesn't need cuda." @@ -275,6 +277,17 @@ def combinations_grid(**kwargs): return [dict(zip(kwargs.keys(), values)) for values in itertools.product(*kwargs.values())] +def cvcuda_to_pil_compatible_tensor(tensor: "cvcuda.Tensor") -> torch.Tensor: + tensor = cvcuda_to_tensor(tensor) + if tensor.ndim != 4: + raise ValueError(f"CV-CUDA Tensor should be 4 dimensional. Got {tensor.ndim} dimensions.") + if tensor.shape[0] != 1: + raise ValueError( + f"CV-CUDA Tensor should have batch dimension 1 for comparison with PIL.Image.Image. Got {tensor.shape[0]}." + ) + return tensor.squeeze(0).cpu() + + class ImagePair(TensorLikePair): def __init__( self, @@ -287,6 +300,11 @@ def __init__( if all(isinstance(input, PIL.Image.Image) for input in [actual, expected]): actual, expected = (to_image(input) for input in [actual, expected]) + # handle check for CV-CUDA Tensors + if CVCUDA_AVAILABLE and isinstance(actual, _import_cvcuda().Tensor): + # Use the PIL compatible tensor, so we can always compare with PIL.Image.Image + actual = cvcuda_to_pil_compatible_tensor(actual) + super().__init__(actual, expected, **other_parameters) self.mae = mae @@ -401,7 +419,6 @@ def make_image_pil(*args, **kwargs): def make_image_cvcuda(*args, batch_dims=(1,), **kwargs): - # explicitly default batch_dims to (1,) since to_cvcuda_tensor requires a batch dimension (ndims == 4) return to_cvcuda_tensor(make_image(*args, batch_dims=batch_dims, **kwargs)) diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index 670a9d00ffb..7eba65550da 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -21,6 +21,7 @@ import torchvision.transforms.v2 as transforms from common_utils import ( + assert_close, assert_equal, cache, cpu_and_cuda, @@ -41,7 +42,6 @@ ) from torch import nn -from torch.testing import assert_close from torch.utils._pytree import tree_flatten, tree_map from torch.utils.data import DataLoader, default_collate from torchvision import tv_tensors diff --git a/torchvision/transforms/v2/_utils.py b/torchvision/transforms/v2/_utils.py index 765a772fe41..3fc33ce5964 100644 --- a/torchvision/transforms/v2/_utils.py +++ b/torchvision/transforms/v2/_utils.py @@ -182,7 +182,7 @@ def query_chw(flat_inputs: list[Any]) -> tuple[int, int, int]: chws = { tuple(get_dimensions(inpt)) for inpt in flat_inputs - if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video)) + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video, is_cvcuda_tensor)) } if not chws: raise TypeError("No image or video was found in the sample") diff --git a/torchvision/transforms/v2/functional/_meta.py b/torchvision/transforms/v2/functional/_meta.py index 6b8f19f12f4..ee562cb2aee 100644 --- a/torchvision/transforms/v2/functional/_meta.py +++ b/torchvision/transforms/v2/functional/_meta.py @@ -51,6 +51,16 @@ def get_dimensions_video(video: torch.Tensor) -> list[int]: return get_dimensions_image(video) +def _get_dimensions_cvcuda(image: "cvcuda.Tensor") -> list[int]: + # CV-CUDA tensor is always in NHWC layout + # get_dimensions is CHW + return [image.shape[3], image.shape[1], image.shape[2]] + + +if CVCUDA_AVAILABLE: + _register_kernel_internal(get_dimensions, cvcuda.Tensor)(_get_dimensions_cvcuda) + + def get_num_channels(inpt: torch.Tensor) -> int: if torch.jit.is_scripting(): return get_num_channels_image(inpt) @@ -87,6 +97,16 @@ def get_num_channels_video(video: torch.Tensor) -> int: get_image_num_channels = get_num_channels +def _get_num_channels_cvcuda(image: "cvcuda.Tensor") -> int: + # CV-CUDA tensor is always in NHWC layout + # get_num_channels is C + return image.shape[3] + + +if CVCUDA_AVAILABLE: + _register_kernel_internal(get_num_channels, cvcuda.Tensor)(_get_num_channels_cvcuda) + + def get_size(inpt: torch.Tensor) -> list[int]: if torch.jit.is_scripting(): return get_size_image(inpt) @@ -114,7 +134,7 @@ def _get_size_image_pil(image: PIL.Image.Image) -> list[int]: return [height, width] -def get_size_image_cvcuda(image: "cvcuda.Tensor") -> list[int]: +def _get_size_cvcuda(image: "cvcuda.Tensor") -> list[int]: """Get size of `cvcuda.Tensor` with NHWC layout.""" hw = list(image.shape[-3:-1]) ndims = len(hw) @@ -125,7 +145,7 @@ def get_size_image_cvcuda(image: "cvcuda.Tensor") -> list[int]: if CVCUDA_AVAILABLE: - _get_size_image_cvcuda = _register_kernel_internal(get_size, cvcuda.Tensor)(get_size_image_cvcuda) + _register_kernel_internal(get_size, cvcuda.Tensor)(_get_size_cvcuda) @_register_kernel_internal(get_size, tv_tensors.Video, tv_tensor_wrapper=False) From 98d7dfb2059eaf2c10c3f549ea45f1d27875134c Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Mon, 1 Dec 2025 18:25:09 -0800 Subject: [PATCH 04/14] update is_cvcuda_tensor --- torchvision/transforms/v2/functional/_utils.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index 73fafaf7425..44b2edeaf2d 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -181,7 +181,8 @@ def is_cvcuda_tensor(inpt: Any) -> bool: Returns: True if the input is a CV-CUDA tensor, False otherwise. """ - if _is_cvcuda_available(): + try: cvcuda = _import_cvcuda() return isinstance(inpt, cvcuda.Tensor) - return False + except ImportError: + return False From ddc116d13febdae1d53507bcde9f103a4c14eba7 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Tue, 2 Dec 2025 12:37:03 -0800 Subject: [PATCH 05/14] add cvcuda to pil compatible to transforms by default --- test/test_transforms_v2.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index 7eba65550da..87166477669 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -25,6 +25,7 @@ assert_equal, cache, cpu_and_cuda, + cvcuda_to_pil_compatible_tensor, freeze_rng_state, ignore_jit_no_profile_information_warning, make_bounding_boxes, From e51dc7eabd254261347245f4492892fd0944aae5 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Tue, 2 Dec 2025 12:46:23 -0800 Subject: [PATCH 06/14] remove cvcuda from transform class --- torchvision/transforms/v2/_transform.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/torchvision/transforms/v2/_transform.py b/torchvision/transforms/v2/_transform.py index bec9ffcf714..ac84fcb6c82 100644 --- a/torchvision/transforms/v2/_transform.py +++ b/torchvision/transforms/v2/_transform.py @@ -11,7 +11,7 @@ from torchvision.transforms.v2._utils import check_type, has_any, is_pure_tensor from torchvision.utils import _log_api_usage_once -from .functional._utils import _get_kernel, is_cvcuda_tensor +from .functional._utils import _get_kernel class Transform(nn.Module): @@ -23,7 +23,7 @@ class Transform(nn.Module): # Class attribute defining transformed types. Other types are passed-through without any transformation # We support both Types and callables that are able to do further checks on the type of the input. - _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image, is_cvcuda_tensor) + _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image) def __init__(self) -> None: super().__init__() From 4939355a2c7421eeba95d7f155fe7953066aec6d Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 11:07:08 -0800 Subject: [PATCH 07/14] resolve more formatting naming --- torchvision/transforms/v2/functional/__init__.py | 2 +- torchvision/transforms/v2/functional/_meta.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/torchvision/transforms/v2/functional/__init__.py b/torchvision/transforms/v2/functional/__init__.py index 52181e4624b..032a993b1f0 100644 --- a/torchvision/transforms/v2/functional/__init__.py +++ b/torchvision/transforms/v2/functional/__init__.py @@ -1,6 +1,6 @@ from torchvision.transforms import InterpolationMode # usort: skip -from ._utils import is_pure_tensor, register_kernel, is_cvcuda_tensor # usort: skip +from ._utils import is_pure_tensor, register_kernel # usort: skip from ._meta import ( clamp_bounding_boxes, diff --git a/torchvision/transforms/v2/functional/_meta.py b/torchvision/transforms/v2/functional/_meta.py index e8630f788ca..af03ad018d4 100644 --- a/torchvision/transforms/v2/functional/_meta.py +++ b/torchvision/transforms/v2/functional/_meta.py @@ -51,14 +51,14 @@ def get_dimensions_video(video: torch.Tensor) -> list[int]: return get_dimensions_image(video) -def _get_dimensions_cvcuda(image: "cvcuda.Tensor") -> list[int]: +def get_dimensions_image_cvcuda(image: "cvcuda.Tensor") -> list[int]: # CV-CUDA tensor is always in NHWC layout # get_dimensions is CHW return [image.shape[3], image.shape[1], image.shape[2]] if CVCUDA_AVAILABLE: - _register_kernel_internal(get_dimensions, cvcuda.Tensor)(_get_dimensions_cvcuda) + _register_kernel_internal(get_dimensions, cvcuda.Tensor)(get_dimensions_image_cvcuda) def get_num_channels(inpt: torch.Tensor) -> int: @@ -97,14 +97,14 @@ def get_num_channels_video(video: torch.Tensor) -> int: get_image_num_channels = get_num_channels -def _get_num_channels_cvcuda(image: "cvcuda.Tensor") -> int: +def get_num_channels_image_cvcuda(image: "cvcuda.Tensor") -> int: # CV-CUDA tensor is always in NHWC layout # get_num_channels is C return image.shape[3] if CVCUDA_AVAILABLE: - _register_kernel_internal(get_num_channels, cvcuda.Tensor)(_get_num_channels_cvcuda) + _register_kernel_internal(get_num_channels, cvcuda.Tensor)(get_num_channels_image_cvcuda) def get_size(inpt: torch.Tensor) -> list[int]: From fbea584365311ae6b56be7e4f6bbff1f834dd31a Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 11:15:49 -0800 Subject: [PATCH 08/14] update is cvcuda tensor impl --- torchvision/transforms/v2/_utils.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/torchvision/transforms/v2/_utils.py b/torchvision/transforms/v2/_utils.py index 3fc33ce5964..e803aa49c60 100644 --- a/torchvision/transforms/v2/_utils.py +++ b/torchvision/transforms/v2/_utils.py @@ -15,8 +15,8 @@ from torchvision._utils import sequence_to_str from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 -from torchvision.transforms.v2.functional import get_dimensions, get_size, is_cvcuda_tensor, is_pure_tensor -from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT +from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT, _is_cvcuda_tensor def _setup_number_or_seq(arg: int | float | Sequence[int | float], name: str) -> Sequence[float]: @@ -182,7 +182,7 @@ def query_chw(flat_inputs: list[Any]) -> tuple[int, int, int]: chws = { tuple(get_dimensions(inpt)) for inpt in flat_inputs - if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video, is_cvcuda_tensor)) + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video, _is_cvcuda_tensor)) } if not chws: raise TypeError("No image or video was found in the sample") @@ -207,7 +207,7 @@ def query_size(flat_inputs: list[Any]) -> tuple[int, int]: tv_tensors.Mask, tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, - is_cvcuda_tensor, + _is_cvcuda_tensor, ), ) } From 0a7886ce846d4b1e7be95c329bab057e004a0d55 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 13:09:59 -0800 Subject: [PATCH 09/14] add dummy func --- torchvision/transforms/v2/functional/_geometry.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py index 0e27218bc89..b8a5da5f0da 100644 --- a/torchvision/transforms/v2/functional/_geometry.py +++ b/torchvision/transforms/v2/functional/_geometry.py @@ -401,6 +401,16 @@ def __resize_image_pil_dispatch( return _resize_image_pil(image, size=size, interpolation=interpolation, max_size=max_size) +def _resize_image_cvcuda( + image: "cvcuda.Tensor", + size: Union[Sequence[int], int], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> "cvcuda.Tensor": + return cvcuda.resize(image, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + def resize_mask(mask: torch.Tensor, size: Optional[list[int]], max_size: Optional[int] = None) -> torch.Tensor: if mask.ndim < 3: mask = mask.unsqueeze(0) From aa3885589ca393c02877efe56e1749e33dfb1397 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 17:17:05 -0800 Subject: [PATCH 10/14] initial resize impl --- test/test_transforms_v2.py | 94 +++++++++++++++++-- torchvision/transforms/v2/_geometry.py | 3 + .../transforms/v2/functional/_augment.py | 11 +-- .../transforms/v2/functional/_color.py | 12 +-- .../transforms/v2/functional/_geometry.py | 62 +++++++++++- torchvision/transforms/v2/functional/_misc.py | 11 +-- .../transforms/v2/functional/_utils.py | 53 ++++++++++- 7 files changed, 207 insertions(+), 39 deletions(-) diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index f767e211125..24db0d381e0 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -25,7 +25,6 @@ assert_equal, cache, cpu_and_cuda, - cvcuda_to_pil_compatible_tensor, freeze_rng_state, ignore_jit_no_profile_information_warning, make_bounding_boxes, @@ -813,6 +812,9 @@ def test_kernel_video(self): make_segmentation_mask, make_video, make_keypoints, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), ], ) def test_functional(self, size, make_input): @@ -836,9 +838,16 @@ def test_functional(self, size, make_input): (F.resize_mask, tv_tensors.Mask), (F.resize_video, tv_tensors.Video), (F.resize_keypoints, tv_tensors.KeyPoints), + pytest.param( + F._geometry._resize_image_cvcuda, + None, + marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA"), + ), ], ) def test_functional_signature(self, kernel, input_type): + if kernel is F._geometry._resize_image_cvcuda: + input_type = _import_cvcuda().Tensor check_functional_kernel_signature_match(F.resize, kernel=kernel, input_type=input_type) @pytest.mark.parametrize("size", OUTPUT_SIZES) @@ -854,6 +863,9 @@ def test_functional_signature(self, kernel, input_type): make_detection_masks, make_video, make_keypoints, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), ], ) def test_transform(self, size, device, make_input): @@ -871,23 +883,68 @@ def _check_output_size(self, input, output, *, size, max_size): input_size=F.get_size(input), size=size, max_size=max_size ) + @pytest.mark.parametrize( + "make_input", + [ + make_image, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), + ], + ) @pytest.mark.parametrize("size", OUTPUT_SIZES) # `InterpolationMode.NEAREST` is modeled after the buggy `INTER_NEAREST` interpolation of CV2. # The PIL equivalent of `InterpolationMode.NEAREST` is `InterpolationMode.NEAREST_EXACT` @pytest.mark.parametrize("interpolation", set(INTERPOLATION_MODES) - {transforms.InterpolationMode.NEAREST}) @pytest.mark.parametrize("use_max_size", [True, False]) @pytest.mark.parametrize("fn", [F.resize, transform_cls_to_functional(transforms.Resize)]) - def test_image_correctness(self, size, interpolation, use_max_size, fn): + def test_image_correctness(self, make_input, size, interpolation, use_max_size, fn): if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)): return - image = make_image(self.INPUT_SIZE, dtype=torch.uint8) + image = make_input(self.INPUT_SIZE, dtype=torch.uint8) actual = fn(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=True) + + if make_input is make_image_cvcuda: + image = F.cvcuda_to_tensor(image)[0].cpu() + expected = F.to_image(F.resize(F.to_pil_image(image), size=size, interpolation=interpolation, **max_size_kwarg)) self._check_output_size(image, actual, size=size, **max_size_kwarg) - torch.testing.assert_close(actual, expected, atol=1, rtol=0) + + atol = 1 + # when using antialias, CV-CUDA is different for BICUBIC and BILINEAR, since antialias requires hq_resize + if make_input is make_image_cvcuda and ( + interpolation is transforms.InterpolationMode.BILINEAR + or interpolation is transforms.InterpolationMode.BICUBIC + ): + atol = 9 + assert_close(actual, expected, atol=atol, rtol=0) + + @pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + @pytest.mark.parametrize("size", OUTPUT_SIZES) + @pytest.mark.parametrize("interpolation", set(INTERPOLATION_MODES) - {transforms.InterpolationMode.NEAREST}) + @pytest.mark.parametrize("use_max_size", [True, False]) + @pytest.mark.parametrize("antialias", [True, False]) + def test_image_correctness_cvcuda(self, size, interpolation, use_max_size, antialias): + if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)): + return + + image = make_image_cvcuda(self.INPUT_SIZE, dtype=torch.uint8) + actual = F.resize(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=antialias) + expected = F.resize( + F.cvcuda_to_tensor(image), size=size, interpolation=interpolation, **max_size_kwarg, antialias=antialias + ) + + # assert_close will squeeze the batch dimension off the CV-CUDA tensor so we convert ahead of time + actual = F.cvcuda_to_tensor(actual) + + atol = 1 + if antialias: + # cvcuda.hq_resize is accurate within 9 for the tests + atol = 9 + assert_close(actual, expected, atol=atol, rtol=0) def _reference_resize_bounding_boxes(self, bounding_boxes, format, *, size, max_size=None): old_height, old_width = bounding_boxes.canvas_size @@ -973,7 +1030,15 @@ def test_keypoints_correctness(self, size, use_max_size, fn): @pytest.mark.parametrize("interpolation", set(transforms.InterpolationMode) - set(INTERPOLATION_MODES)) @pytest.mark.parametrize( "make_input", - [make_image_tensor, make_image_pil, make_image, make_video], + [ + make_image_tensor, + make_image_pil, + make_image, + make_video, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), + ], ) def test_pil_interpolation_compat_smoke(self, interpolation, make_input): input = make_input(self.INPUT_SIZE) @@ -1006,6 +1071,9 @@ def test_functional_pil_antialias_warning(self): make_detection_masks, make_video, make_keypoints, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), ], ) def test_max_size_error(self, size, make_input): @@ -1049,6 +1117,9 @@ def test_max_size_error(self, size, make_input): make_detection_masks, make_video, make_keypoints, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), ], ) def test_resize_size_none(self, input_size, max_size, expected_size, make_input): @@ -1059,7 +1130,15 @@ def test_resize_size_none(self, input_size, max_size, expected_size, make_input) @pytest.mark.parametrize("interpolation", INTERPOLATION_MODES) @pytest.mark.parametrize( "make_input", - [make_image_tensor, make_image_pil, make_image, make_video], + [ + make_image_tensor, + make_image_pil, + make_image, + make_video, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), + ], ) def test_interpolation_int(self, interpolation, make_input): input = make_input(self.INPUT_SIZE) @@ -1123,6 +1202,9 @@ def test_noop(self, size, make_input): make_detection_masks, make_video, make_keypoints, + pytest.param( + make_image_cvcuda, marks=pytest.mark.skipif(not CVCUDA_AVAILABLE, reason="test requires CVCUDA") + ), ], ) def test_no_regression_5405(self, make_input): diff --git a/torchvision/transforms/v2/_geometry.py b/torchvision/transforms/v2/_geometry.py index 96166e05e9a..d343dde2d68 100644 --- a/torchvision/transforms/v2/_geometry.py +++ b/torchvision/transforms/v2/_geometry.py @@ -139,6 +139,9 @@ class Resize(Transform): _v1_transform_cls = _transforms.Resize + if CVCUDA_AVAILABLE: + _transformed_types = Transform._transformed_types + (_is_cvcuda_tensor,) + def __init__( self, size: Union[int, Sequence[int], None], diff --git a/torchvision/transforms/v2/functional/_augment.py b/torchvision/transforms/v2/functional/_augment.py index 7ce5bdc7b7e..a904d8d7cbd 100644 --- a/torchvision/transforms/v2/functional/_augment.py +++ b/torchvision/transforms/v2/functional/_augment.py @@ -1,5 +1,4 @@ import io -from typing import TYPE_CHECKING import PIL.Image @@ -9,15 +8,7 @@ from torchvision.transforms.functional import pil_to_tensor, to_pil_image from torchvision.utils import _log_api_usage_once -from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal - - -CVCUDA_AVAILABLE = _is_cvcuda_available() - -if TYPE_CHECKING: - import cvcuda # type: ignore[import-not-found] -if CVCUDA_AVAILABLE: - cvcuda = _import_cvcuda() # noqa: F811 +from ._utils import _get_kernel, _register_kernel_internal def erase( diff --git a/torchvision/transforms/v2/functional/_color.py b/torchvision/transforms/v2/functional/_color.py index 5be9c62902a..be254c0d63a 100644 --- a/torchvision/transforms/v2/functional/_color.py +++ b/torchvision/transforms/v2/functional/_color.py @@ -1,5 +1,3 @@ -from typing import TYPE_CHECKING - import PIL.Image import torch from torch.nn.functional import conv2d @@ -11,15 +9,7 @@ from ._misc import _num_value_bits, to_dtype_image from ._type_conversion import pil_to_tensor, to_pil_image -from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal - - -CVCUDA_AVAILABLE = _is_cvcuda_available() - -if TYPE_CHECKING: - import cvcuda # type: ignore[import-not-found] -if CVCUDA_AVAILABLE: - cvcuda = _import_cvcuda() # noqa: F811 +from ._utils import _get_kernel, _register_kernel_internal def rgb_to_grayscale(inpt: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py index b8a5da5f0da..70c519f54fb 100644 --- a/torchvision/transforms/v2/functional/_geometry.py +++ b/torchvision/transforms/v2/functional/_geometry.py @@ -28,6 +28,7 @@ from ._utils import ( _FillTypeJIT, + _get_cvcuda_interp, _get_kernel, _import_cvcuda, _is_cvcuda_available, @@ -401,14 +402,71 @@ def __resize_image_pil_dispatch( return _resize_image_pil(image, size=size, interpolation=interpolation, max_size=max_size) +_dtype_to_format_cvcuda: dict["cvcuda.Type", "cvcuda.Format"] = {} + + def _resize_image_cvcuda( image: "cvcuda.Tensor", - size: Union[Sequence[int], int], + size: Optional[list[int]], interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, max_size: Optional[int] = None, antialias: Optional[bool] = True, ) -> "cvcuda.Tensor": - return cvcuda.resize(image, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + cvcuda = _import_cvcuda() + + if len(_dtype_to_format_cvcuda) == 0: + _dtype_to_format_cvcuda[cvcuda.Type.U8] = cvcuda.Format.U8 + _dtype_to_format_cvcuda[cvcuda.Type.U16] = cvcuda.Format.U16 + _dtype_to_format_cvcuda[cvcuda.Type.U32] = cvcuda.Format.U32 + _dtype_to_format_cvcuda[cvcuda.Type.S8] = cvcuda.Format.S8 + _dtype_to_format_cvcuda[cvcuda.Type.S16] = cvcuda.Format.S16 + _dtype_to_format_cvcuda[cvcuda.Type.S32] = cvcuda.Format.S32 + _dtype_to_format_cvcuda[cvcuda.Type.F32] = cvcuda.Format.F32 + _dtype_to_format_cvcuda[cvcuda.Type.F64] = cvcuda.Format.F64 + + interp = _get_cvcuda_interp(interpolation) + if interp == cvcuda.Interp.HAMMING: + raise NotImplementedError("Hamming interpolation is not supported for CV-CUDA resize.") + + old_height, old_width = image.shape[1], image.shape[2] + new_height, new_width = _compute_resized_output_size((old_height, old_width), size=size, max_size=max_size) + + # antialias is only supported for cvcuda.hq_resize, if set to true (which is also default) + # we will fast-track to use hq_resize (also matchs the size parameter) + if antialias: + return cvcuda.hq_resize( + image, + out_size=(new_height, new_width), + interpolation=interp, + antialias=antialias, + ) + + # if not using antialias, we will use cvcuda.resize/pillowresize instead + # resize requires that the shape has the same dimensions as the input + # CV-CUDA tensors are already in NHWC format so we can do a simple tuple creation + shape = image.shape + new_shape = (shape[0], new_height, new_width, shape[3]) + + # bicubic mode is not accurate when using cvcuda.resize + # cvcuda.pillowresize resolves some of the errors + if interp == cvcuda.Interp.CUBIC: + return cvcuda.pillowresize( + image, + shape=new_shape, + format=_dtype_to_format_cvcuda[image.dtype], + interp=interp, + ) + + # otherwise we will use cvcuda.resize + return cvcuda.resize( + image, + shape=new_shape, + interp=interp, + ) + + +if CVCUDA_AVAILABLE: + _register_kernel_internal(resize, _import_cvcuda().Tensor)(_resize_image_cvcuda) def resize_mask(mask: torch.Tensor, size: Optional[list[int]], max_size: Optional[int] = None) -> torch.Tensor: diff --git a/torchvision/transforms/v2/functional/_misc.py b/torchvision/transforms/v2/functional/_misc.py index 0fa05a2113c..daf263df046 100644 --- a/torchvision/transforms/v2/functional/_misc.py +++ b/torchvision/transforms/v2/functional/_misc.py @@ -1,5 +1,5 @@ import math -from typing import Optional, TYPE_CHECKING +from typing import Optional import PIL.Image import torch @@ -13,14 +13,7 @@ from ._meta import _convert_bounding_box_format -from ._utils import _get_kernel, _import_cvcuda, _is_cvcuda_available, _register_kernel_internal, is_pure_tensor - -CVCUDA_AVAILABLE = _is_cvcuda_available() - -if TYPE_CHECKING: - import cvcuda # type: ignore[import-not-found] -if CVCUDA_AVAILABLE: - cvcuda = _import_cvcuda() # noqa: F811 +from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor def normalize( diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index 11480b30ef9..cd322fbadcf 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -1,9 +1,13 @@ import functools from collections.abc import Sequence -from typing import Any, Callable, Optional, Union +from typing import Any, Callable, Optional, TYPE_CHECKING, Union import torch from torchvision import tv_tensors +from torchvision.transforms.functional import InterpolationMode + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] _FillType = Union[int, float, Sequence[int], Sequence[float], None] _FillTypeJIT = Optional[list[float]] @@ -177,3 +181,50 @@ def _is_cvcuda_tensor(inpt: Any) -> bool: return isinstance(inpt, cvcuda.Tensor) except ImportError: return False + + +_interpolation_mode_to_cvcuda_interp: dict[InterpolationMode | str | int, "cvcuda.Interp"] = {} + + +def _populate_interpolation_mode_to_cvcuda_interp(): + cvcuda = _import_cvcuda() + + global _interpolation_mode_to_cvcuda_interp + + # Note: CV-CUDA's NEAREST actually matches PyTorch's 'nearest-exact' (PIL-style), + # not PyTorch's 'nearest' (OpenCV-style). This means NEAREST_EXACT maps correctly, + # but NEAREST users may get slightly different results than torch.Tensor. + _interpolation_mode_to_cvcuda_interp = { + InterpolationMode.BILINEAR: cvcuda.Interp.LINEAR, + "bilinear": cvcuda.Interp.LINEAR, + "linear": cvcuda.Interp.LINEAR, + 2: cvcuda.Interp.LINEAR, + InterpolationMode.BICUBIC: cvcuda.Interp.CUBIC, + "bicubic": cvcuda.Interp.CUBIC, + 3: cvcuda.Interp.CUBIC, + InterpolationMode.NEAREST: cvcuda.Interp.NEAREST, + "nearest": cvcuda.Interp.NEAREST, + 0: cvcuda.Interp.NEAREST, + InterpolationMode.NEAREST_EXACT: cvcuda.Interp.NEAREST, + "nearest-exact": cvcuda.Interp.NEAREST, + InterpolationMode.BOX: cvcuda.Interp.BOX, + "box": cvcuda.Interp.BOX, + 4: cvcuda.Interp.BOX, + InterpolationMode.HAMMING: cvcuda.Interp.HAMMING, + "hamming": cvcuda.Interp.HAMMING, + 5: cvcuda.Interp.HAMMING, + InterpolationMode.LANCZOS: cvcuda.Interp.LANCZOS, + "lanczos": cvcuda.Interp.LANCZOS, + 1: cvcuda.Interp.LANCZOS, + } + + +def _get_cvcuda_interp(interpolation: InterpolationMode | str | int) -> "cvcuda.Interp": + if len(_interpolation_mode_to_cvcuda_interp) == 0: + _populate_interpolation_mode_to_cvcuda_interp() + + interp = _interpolation_mode_to_cvcuda_interp.get(interpolation) + if interp is None: + raise ValueError(f"Interpolation mode {interpolation} is not supported with CV-CUDA") + + return interp From 4f2752a1271e513b7441768ea002a5f62eb3f87e Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 17:40:15 -0800 Subject: [PATCH 11/14] resize impl complete --- test/test_transforms_v2.py | 9 +++++++++ torchvision/transforms/v2/functional/_geometry.py | 11 ++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index 24db0d381e0..97301d05da0 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -944,6 +944,9 @@ def test_image_correctness_cvcuda(self, size, interpolation, use_max_size, antia if antialias: # cvcuda.hq_resize is accurate within 9 for the tests atol = 9 + elif interpolation == transforms.InterpolationMode.BICUBIC: + # the CV-CUDA bicubic interpolation differences significantly + atol = 91 assert_close(actual, expected, atol=atol, rtol=0) def _reference_resize_bounding_boxes(self, bounding_boxes, format, *, size, max_size=None): @@ -1043,6 +1046,12 @@ def test_keypoints_correctness(self, size, use_max_size, fn): def test_pil_interpolation_compat_smoke(self, interpolation, make_input): input = make_input(self.INPUT_SIZE) + if make_input is make_image_cvcuda and interpolation in { + transforms.InterpolationMode.BOX, + transforms.InterpolationMode.LANCZOS, + }: + pytest.skip("CV-CUDA may support box and lanczos for certain configurations of resize") + with ( contextlib.nullcontext() if isinstance(input, PIL.Image.Image) diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py index 70c519f54fb..d6162a5a9cf 100644 --- a/torchvision/transforms/v2/functional/_geometry.py +++ b/torchvision/transforms/v2/functional/_geometry.py @@ -425,12 +425,21 @@ def _resize_image_cvcuda( _dtype_to_format_cvcuda[cvcuda.Type.F64] = cvcuda.Format.F64 interp = _get_cvcuda_interp(interpolation) + # hamming error for parity to resize_image if interp == cvcuda.Interp.HAMMING: - raise NotImplementedError("Hamming interpolation is not supported for CV-CUDA resize.") + raise NotImplementedError("Unsupported interpolation for CV-CUDA resize, got hamming.") + + # match the antialias behavior of resize_image + if not (interp == cvcuda.Interp.LINEAR or interp == cvcuda.Interp.CUBIC): + antialias = False old_height, old_width = image.shape[1], image.shape[2] new_height, new_width = _compute_resized_output_size((old_height, old_width), size=size, max_size=max_size) + # No resize needed if dimensions match + if new_height == old_height and new_width == old_width: + return image + # antialias is only supported for cvcuda.hq_resize, if set to true (which is also default) # we will fast-track to use hq_resize (also matchs the size parameter) if antialias: From 5fa8d4e293b4d2823b9671fced94afe030cb823c Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 17:43:31 -0800 Subject: [PATCH 12/14] test cvcuda with both functional and class --- test/test_transforms_v2.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index 97301d05da0..5325628e73b 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -927,13 +927,14 @@ def test_image_correctness(self, make_input, size, interpolation, use_max_size, @pytest.mark.parametrize("interpolation", set(INTERPOLATION_MODES) - {transforms.InterpolationMode.NEAREST}) @pytest.mark.parametrize("use_max_size", [True, False]) @pytest.mark.parametrize("antialias", [True, False]) - def test_image_correctness_cvcuda(self, size, interpolation, use_max_size, antialias): + @pytest.mark.parametrize("fn", [F.resize, transform_cls_to_functional(transforms.Resize)]) + def test_image_correctness_cvcuda(self, size, interpolation, use_max_size, antialias, fn): if not (max_size_kwarg := self._make_max_size_kwarg(use_max_size=use_max_size, size=size)): return image = make_image_cvcuda(self.INPUT_SIZE, dtype=torch.uint8) - actual = F.resize(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=antialias) - expected = F.resize( + actual = fn(image, size=size, interpolation=interpolation, **max_size_kwarg, antialias=antialias) + expected = fn( F.cvcuda_to_tensor(image), size=size, interpolation=interpolation, **max_size_kwarg, antialias=antialias ) @@ -945,7 +946,7 @@ def test_image_correctness_cvcuda(self, size, interpolation, use_max_size, antia # cvcuda.hq_resize is accurate within 9 for the tests atol = 9 elif interpolation == transforms.InterpolationMode.BICUBIC: - # the CV-CUDA bicubic interpolation differences significantly + # the CV-CUDA bicubic interpolation differs significantly atol = 91 assert_close(actual, expected, atol=atol, rtol=0) From a895baeb3116ee5545ec06df2ac9865eb686243d Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 17:45:25 -0800 Subject: [PATCH 13/14] update comment for nearest-exact interp --- torchvision/transforms/v2/functional/_utils.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index cd322fbadcf..4111416df79 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -191,9 +191,8 @@ def _populate_interpolation_mode_to_cvcuda_interp(): global _interpolation_mode_to_cvcuda_interp - # Note: CV-CUDA's NEAREST actually matches PyTorch's 'nearest-exact' (PIL-style), - # not PyTorch's 'nearest' (OpenCV-style). This means NEAREST_EXACT maps correctly, - # but NEAREST users may get slightly different results than torch.Tensor. + # CV-CUDA's NEAREST matches PyTorch's 'nearest-exact' (PIL-style) + # not PyTorch's 'nearest' (OpenCV-style). _interpolation_mode_to_cvcuda_interp = { InterpolationMode.BILINEAR: cvcuda.Interp.LINEAR, "bilinear": cvcuda.Interp.LINEAR, From 88d5c391a9b641774bfedcf5a97cf7370bcc5eb0 Mon Sep 17 00:00:00 2001 From: Justin Davis Date: Thu, 4 Dec 2025 18:16:08 -0800 Subject: [PATCH 14/14] refactor interp setup --- .../transforms/v2/functional/_utils.py | 54 ++++++++----------- 1 file changed, 21 insertions(+), 33 deletions(-) diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index 4111416df79..a1742ba149f 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -186,41 +186,29 @@ def _is_cvcuda_tensor(inpt: Any) -> bool: _interpolation_mode_to_cvcuda_interp: dict[InterpolationMode | str | int, "cvcuda.Interp"] = {} -def _populate_interpolation_mode_to_cvcuda_interp(): - cvcuda = _import_cvcuda() - - global _interpolation_mode_to_cvcuda_interp - - # CV-CUDA's NEAREST matches PyTorch's 'nearest-exact' (PIL-style) - # not PyTorch's 'nearest' (OpenCV-style). - _interpolation_mode_to_cvcuda_interp = { - InterpolationMode.BILINEAR: cvcuda.Interp.LINEAR, - "bilinear": cvcuda.Interp.LINEAR, - "linear": cvcuda.Interp.LINEAR, - 2: cvcuda.Interp.LINEAR, - InterpolationMode.BICUBIC: cvcuda.Interp.CUBIC, - "bicubic": cvcuda.Interp.CUBIC, - 3: cvcuda.Interp.CUBIC, - InterpolationMode.NEAREST: cvcuda.Interp.NEAREST, - "nearest": cvcuda.Interp.NEAREST, - 0: cvcuda.Interp.NEAREST, - InterpolationMode.NEAREST_EXACT: cvcuda.Interp.NEAREST, - "nearest-exact": cvcuda.Interp.NEAREST, - InterpolationMode.BOX: cvcuda.Interp.BOX, - "box": cvcuda.Interp.BOX, - 4: cvcuda.Interp.BOX, - InterpolationMode.HAMMING: cvcuda.Interp.HAMMING, - "hamming": cvcuda.Interp.HAMMING, - 5: cvcuda.Interp.HAMMING, - InterpolationMode.LANCZOS: cvcuda.Interp.LANCZOS, - "lanczos": cvcuda.Interp.LANCZOS, - 1: cvcuda.Interp.LANCZOS, - } - - def _get_cvcuda_interp(interpolation: InterpolationMode | str | int) -> "cvcuda.Interp": if len(_interpolation_mode_to_cvcuda_interp) == 0: - _populate_interpolation_mode_to_cvcuda_interp() + cvcuda = _import_cvcuda() + _interpolation_mode_to_cvcuda_interp[InterpolationMode.NEAREST] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[InterpolationMode.NEAREST_EXACT] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BILINEAR] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BICUBIC] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BOX] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp[InterpolationMode.HAMMING] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp[InterpolationMode.LANCZOS] = cvcuda.Interp.LANCZOS + _interpolation_mode_to_cvcuda_interp["nearest"] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp["nearest-exact"] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp["bilinear"] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp["bicubic"] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp["box"] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp["hamming"] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp["lanczos"] = cvcuda.Interp.LANCZOS + _interpolation_mode_to_cvcuda_interp[0] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[2] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp[3] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp[4] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp[5] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp[1] = cvcuda.Interp.LANCZOS interp = _interpolation_mode_to_cvcuda_interp.get(interpolation) if interp is None: