diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index c0469271889f..efd782d69e0b 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -320,6 +320,63 @@ Set the `USE_HUB_KERNELS` environment variable to disable Hub kernels everywhere export USE_HUB_KERNELS=0 # or OFF or NO ``` +## Processor kernels + +Image and video processors can run some of their operations with Hub kernels from [kernels-community/cv-utils](https://huggingface.co/kernels-community/cv-utils). Pass `use_kernels=True` when loading the processor. Processors keep kernels off by default because the resize kernels change pixel values (see below), and the flag is not saved with the processor configuration. + +| Operation | What the kernel does | Processors | +|---|---|---| +| Resize and normalize | Resizes a batch of images of different sizes in one launch, then rescales and normalizes in the same pass. | Processors that use the default [`TorchvisionBackend`] preprocessing, such as ViT, CLIP and SigLIP | +| Resize, normalize and patchify | Writes each resized and normalized pixel directly at its place in the flattened patch sequence, for images and video frames. | Qwen2-VL and Qwen3-VL image and video processors, and the processors built on them (e.g. HunYuanVL, PaddleOCR-VL) | +| Connected components | Measures the area of every connected region of a mask, to fill small holes and remove small islands. | SAM 2 and SAM 3 image processors (`max_hole_area`, `max_sprinkle_area`) | +| Upsample and argmax | Computes the class of every pixel of the upsampled segmentation logits without storing the upsampled logits. | `post_process_semantic_segmentation` of semantic segmentation processors (e.g. SegFormer, BEiT, DPT) | + +```py +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True) +inputs = processor(text=prompt, images=images, return_tensors="pt", device="cuda") +``` + +[`AutoProcessor`] passes the flag to its image and video processors. Kernels run on the device of the inputs, so pass `device="cuda"`. The processor keeps its default implementation when the inputs are on CPU, when the kernel fails to load, or when the kernel does not support the arguments. + +`use_kernels` is an attribute of each image and video processor. Set it on one of them to use kernels for images only, for example. + +```py +processor.video_processor.use_kernels = False +``` + +> [!NOTE] +> The resize kernels are antialiased and round to `uint8` after each pass, like the torchvision path, but in a different order. On photos the mean difference stays below a quarter of a `uint8` level. Bicubic resampling can differ by several levels on a few pixels near sharp edges. +> +> When both sides are upsampled at least 2x, the upsample and argmax kernel runs on tensor cores in float16. A few pixels at near-ties between two classes can then get another class, about 1e-4 of the pixels on ADE20K, with no change in mIoU. + +### Adding a processing kernel + +`use_processing_kernel` connects a processor method to a kernel. It decorates the method with a function that receives the processor and the named arguments of the method. That function returns the result, or `None` to run the method as usual. It only runs when the processor was loaded with `use_kernels=True`. An optional `condition` receives the processor and returns whether it can use the kernel, like the `condition` of `use_kernel_forward_from_hub`. `load_cv_utils_kernel(device)` returns the cv-utils kernel for tensors on `device`, or `None` when they are not on a CUDA device or the kernel does not load. For example, this is how semantic segmentation post-processing uses `upsample_argmax`: + +```py +from transformers import TorchvisionBackend +from transformers.integrations.hub_processing_kernels import load_cv_utils_kernel, use_processing_kernel + + +def upsample_argmax_with_kernel(processor, outputs, target_sizes, return_segmentation_scores): + if return_segmentation_scores or target_sizes is None: + return None + kernel = load_cv_utils_kernel(outputs.logits.device) + if kernel is None: + return None + return kernel.upsample_argmax(outputs.logits, target_sizes) + + +class MyImageProcessor(TorchvisionBackend): + @use_processing_kernel(upsample_argmax_with_kernel) + def post_process_semantic_segmentation(self, outputs, target_sizes=None, return_segmentation_scores=False): + ... +``` + +Subclasses that keep the method keep the kernel. The function reads what differs between models from the processor, such as its `_resized_size` method or its `patch_block_size` attribute. A model that replaces `_preprocess` with a different pipeline marks it with `@no_inherit_decorator`. + ## Troubleshooting Kernel integration depends on hardware, drivers, and package versions working together. The following sections cover common failures. diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 7fb95b37e26e..dfb3fe778b02 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,6 +53,7 @@ is_valid_image, load_image_as_tensor, ) +from .integrations.hub_processing_kernels import resize_normalize_with_kernel, use_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -258,34 +259,30 @@ def resize( ) interpolation = tvF.InterpolationMode.BICUBIC - if size.shortest_edge and size.longest_edge: - new_size = get_size_with_aspect_ratio( - image.size()[-2:], - size.shortest_edge, - size.longest_edge, - ) - elif size.shortest_edge: - new_size = get_resize_output_image_size( - image, - size=size.shortest_edge, - default_to_square=False, - input_data_format=ChannelDimension.FIRST, - ) - elif size.max_height and size.max_width: - new_size = get_image_size_for_max_height_width(image.size()[-2:], size.max_height, size.max_width) - elif size.height and size.width: - new_size = (size.height, size.width) - else: - raise ValueError( - "Size must contain 'height' and 'width' keys, or 'max_height' and 'max_width', or 'shortest_edge' key. Got" - f" {size}." - ) + new_size = self._resize_output_size(image, size) # Workaround for torch.compile issue with uint8 on AMD GPUs if is_torchdynamo_compiling() and is_rocm_platform(): return self._compile_friendly_resize(image, new_size, interpolation, antialias) return tvF.resize(image, new_size, interpolation=interpolation, antialias=antialias) + def _resize_output_size(self, image: "torch.Tensor", size: SizeDict) -> tuple[int, int]: + """The `(height, width)` that `resize` gives `image` for `size`.""" + if size.shortest_edge and size.longest_edge: + return get_size_with_aspect_ratio(image.size()[-2:], size.shortest_edge, size.longest_edge) + if size.shortest_edge: + return get_resize_output_image_size( + image, size=size.shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST + ) + if size.max_height and size.max_width: + return get_image_size_for_max_height_width(image.size()[-2:], size.max_height, size.max_width) + if size.height and size.width: + return (size.height, size.width) + raise ValueError( + "Size must contain 'height' and 'width' keys, or 'max_height' and 'max_width', or 'shortest_edge' key. Got" + f" {size}." + ) + @staticmethod def _compile_friendly_resize( image: "torch.Tensor", @@ -396,6 +393,13 @@ def center_crop( crop_left = int((image_width - crop_width) / 2.0) return tvF.crop(image, crop_top, crop_left, crop_height, crop_width) + @use_processing_kernel( + resize_normalize_with_kernel, + condition=lambda processor: all( + getattr(type(processor), name) is getattr(TorchvisionBackend, name) + for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") + ), + ) def _preprocess( self, images: list["torch.Tensor"], @@ -449,6 +453,8 @@ class PilBackend(BaseImageProcessor): """PIL/NumPy backend for portable CPU-only image processing.""" def __init__(self, **kwargs: Unpack[ImagesKwargs]): + if kwargs.get("use_kernels"): + raise ValueError("`use_kernels=True` needs a torchvision image processor, pass `backend='torchvision'`.") super().__init__(**kwargs) self._set_attributes(**kwargs) diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index 31ff39dfe00c..6009874f1824 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -138,6 +138,11 @@ def from_pretrained( subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. + use_kernels (`bool`, *optional*, defaults to `False`): + Whether to run the processing ops with Hub kernels when the processor supports them, and to fall + back to the default implementation otherwise. Requires the torchvision backend and a CUDA device. + This is a runtime flag, it is not saved by + [`~image_processing_utils.ImageProcessingMixin.save_pretrained`]. kwargs (`dict[str, Any]`, *optional*): The values in kwargs of any keys which are image processor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is @@ -382,8 +387,11 @@ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs): """ image_processor_dict = image_processor_dict.copy() return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) + use_kernels = kwargs.pop("use_kernels", None) valid_keys = cls.valid_kwargs.__annotations__.keys() image_processor_dict.update({k: kwargs.pop(k) for k in list(kwargs) if k in valid_keys}) + if use_kernels is not None: + image_processor_dict["use_kernels"] = use_kernels image_processor = cls(**image_processor_dict) # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) @@ -413,6 +421,7 @@ def to_dict(self) -> dict[str, Any]: `dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance. """ output = copy.deepcopy(self.__dict__) + output.pop("use_kernels", None) # runtime flag, never saved output["image_processor_type"] = self.__class__.__name__ return output diff --git a/src/transformers/image_processing_utils.py b/src/transformers/image_processing_utils.py index e4d7a332466e..c7add2c8a1ae 100644 --- a/src/transformers/image_processing_utils.py +++ b/src/transformers/image_processing_utils.py @@ -187,6 +187,7 @@ class MyImageProcessor(TorchvisionBackend): """ valid_kwargs = ImagesKwargs + use_kernels = False default_to_square = True rescale_factor = 1 / 255 diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 619f1357ea45..95777f5d9d8d 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -335,6 +335,7 @@ def register_kernel_mapping_transformers(*args, **kwargs): "deep-gemm": {"repo_id": "kernels-community/deep-gemm", "version": 2}, "sonic-moe": {"repo_id": "kernels-community/sonic-moe", "revision": "ep-support"}, "nvfp4": {"repo_id": "kernels-community/nvfp4-gemm", "version": 1}, + "cv-utils": {"repo_id": "kernels-community/cv-utils", "version": 2}, } _KERNEL_MODULE_MAPPING: dict[str, ModuleType | None] = {} diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py new file mode 100644 index 000000000000..3eb880bfedbb --- /dev/null +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -0,0 +1,257 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +from collections.abc import Callable +from functools import wraps +from types import ModuleType + +from ..feature_extraction_utils import BatchFeature +from ..utils.import_utils import get_device_type, is_torch_available, is_vision_available + + +if is_torch_available(): + import torch + + from .hub_kernels import lazy_load_kernel + +if is_vision_available(): + from ..image_utils import PILImageResampling + + KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} + + +_CV_UTILS_FUNCTIONS = ("resize_normalize", "resize_normalize_patchify", "connected_component_areas", "upsample_argmax") + +_CV_UTILS: ModuleType | None = None + + +def _load_cv_utils_kernel() -> None: + """Load `kernels-community/cv-utils` once into the `_CV_UTILS` module global, like `_load_finegrained_fp8_kernel`.""" + global _CV_UTILS + if _CV_UTILS is not None: + return + kernel = lazy_load_kernel("cv-utils") + if kernel is None: + return + missing = [name for name in _CV_UTILS_FUNCTIONS if not hasattr(kernel, name)] + if missing: + raise ImportError(f"The cv-utils kernel is missing required symbols: {', '.join(missing)}.") + _CV_UTILS = kernel + + +if is_torch_available(): + _load_cv_utils_kernel = torch._dynamo.allow_in_graph(_load_cv_utils_kernel) + + +def load_cv_utils_kernel(device) -> ModuleType | None: + """The `kernels-community/cv-utils` kernel for tensors on `device`, or `None` to keep the default path.""" + if get_device_type(device) not in ("cuda", "rocm"): + return None + _load_cv_utils_kernel() + return _CV_UTILS + + +def kernel_can_resize(images, resample): + """Whether one launch of the resize kernels can resize `images` with `resample`: uint8, one device, one channel count.""" + return ( + resample in KERNEL_INTERPOLATIONS + and bool(images) + and all( + image.dtype == torch.uint8 and image.device == images[0].device and image.shape[-3] == images[0].shape[-3] + for image in images + ) + ) + + +def use_processing_kernel(run_with_kernel: Callable, condition: Callable | None = None): + """ + Decorate a processor method so that `use_kernels=True` first runs `run_with_kernel`. + + `run_with_kernel` receives the processor and the named arguments of the method. It returns the kernel result, or + `None` to run the method as usual. `condition` receives the processor and returns whether it can use the kernel. + """ + + def decorator(method: Callable) -> Callable: + parameters = list(inspect.signature(method).parameters.values())[1:] + parameter_names = tuple( + parameter.name for parameter in parameters if parameter.kind is not parameter.VAR_KEYWORD + ) + parameter_defaults = { + parameter.name: parameter.default for parameter in parameters if parameter.default is not parameter.empty + } + + @wraps(method) + def wrapper(self, *args, **kwargs): + if self.use_kernels and (condition is None or condition(self)): + named_arguments = {**parameter_defaults, **dict(zip(parameter_names, args)), **kwargs} + output = run_with_kernel(self, **named_arguments) + if output is not None: + return output + return method(self, *args, **kwargs) + + return wrapper + + return decorator + + +def resize_normalize_with_kernel( + processor, + images, + do_resize, + size, + resample, + do_center_crop, + crop_size, + do_rescale, + rescale_factor, + do_normalize, + image_mean, + image_std, + do_pad, + return_tensors, + **kwargs, +): + """`pixel_values` of the default torchvision pipeline from one kernel call, `None` to fall back.""" + if not (do_resize and do_rescale and do_normalize and not do_pad and kernel_can_resize(images, resample)): + return None + kernel = load_cv_utils_kernel(images[0].device) + if kernel is None: + return None + sizes = [processor._resize_output_size(image, size) for image in images] + crop = None + if do_center_crop: + crop = (crop_size.height, crop_size.width) + if any(crop[0] > height or crop[1] > width for height, width in sizes): + return None + pixel_values = kernel.resize_normalize( + images, + sizes, + image_mean=image_mean, + image_std=image_std, + rescale_factor=rescale_factor, + resample=KERNEL_INTERPOLATIONS[resample], + crop_size=crop, + ) + return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) + + +def resize_normalize_patchify_images_with_kernel( + processor, + images, + do_resize, + size, + resample, + do_rescale, + rescale_factor, + do_normalize, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + return_tensors, + **kwargs, +): + """`pixel_values` and `image_grid_thw` of the Qwen2-VL image pipeline, from one kernel call for the batch.""" + if not (do_resize and do_rescale and do_normalize and kernel_can_resize(images, resample)): + return None + kernel = load_cv_utils_kernel(images[0].device) + if kernel is None: + return None + target_sizes = [ + processor._resized_size( + height=image.shape[-2], width=image.shape[-1], size=size, factor=patch_size * merge_size + ) + for image in images + ] + pixel_values, image_grid_thw = kernel.resize_normalize_patchify( + [image[None] for image in images], + target_sizes, + image_mean=image_mean, + image_std=image_std, + rescale_factor=rescale_factor, + resample=KERNEL_INTERPOLATIONS[resample], + patch_size=patch_size, + block_size=getattr(processor, "patch_block_size", merge_size), + temporal_patch_size=temporal_patch_size, + ) + if not getattr(processor, "flatten_patches", True): + pixel_values = pixel_values.view(-1, images[0].shape[0] * temporal_patch_size, patch_size, patch_size) + return BatchFeature( + data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors + ) + + +def resize_normalize_patchify_videos_with_kernel( + processor, + videos, + do_resize, + size, + resample, + do_rescale, + rescale_factor, + do_normalize, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + cap_pixels_per_frame, + max_video_tokens, + return_tensors, + **kwargs, +): + """`pixel_values_videos` and `video_grid_thw` of the Qwen2-VL video pipeline, from one kernel call for all frames.""" + if not (do_resize and do_rescale and do_normalize and kernel_can_resize(videos, resample)): + return None + kernel = load_cv_utils_kernel(videos[0].device) + if kernel is None: + return None + target_sizes = [ + processor._resized_size( + height=video.shape[-2], + width=video.shape[-1], + num_frames=video.shape[0], + size=size, + factor=patch_size * merge_size, + temporal_factor=temporal_patch_size, + cap_pixels_per_frame=cap_pixels_per_frame, + max_video_tokens=max_video_tokens, + ) + for video in videos + ] + pixel_values_videos, video_grid_thw = kernel.resize_normalize_patchify( + videos, + target_sizes, + image_mean=image_mean, + image_std=image_std, + rescale_factor=rescale_factor, + resample=KERNEL_INTERPOLATIONS[resample], + patch_size=patch_size, + block_size=getattr(processor, "patch_block_size", merge_size), + temporal_patch_size=temporal_patch_size, + ) + return BatchFeature( + data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw}, tensor_type=return_tensors + ) + + +def upsample_argmax_with_kernel(processor, outputs, target_sizes, return_segmentation_scores): + """Class maps of `outputs.logits` upsampled to `target_sizes`, without storing the upsampled logits.""" + if return_segmentation_scores or target_sizes is None: + return None + kernel = load_cv_utils_kernel(outputs.logits.device) + if kernel is None: + return None + return kernel.upsample_argmax(outputs.logits, target_sizes) diff --git a/src/transformers/models/beit/image_processing_beit.py b/src/transformers/models/beit/image_processing_beit.py index ba7e31ce5d58..a32f082277fe 100644 --- a/src/transformers/models/beit/image_processing_beit.py +++ b/src/transformers/models/beit/image_processing_beit.py @@ -31,6 +31,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -180,6 +181,7 @@ def _preprocess( return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False ) -> "list[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]": diff --git a/src/transformers/models/chmv2/image_processing_chmv2.py b/src/transformers/models/chmv2/image_processing_chmv2.py index 17aaff1d31cb..61a712c25058 100644 --- a/src/transformers/models/chmv2/image_processing_chmv2.py +++ b/src/transformers/models/chmv2/image_processing_chmv2.py @@ -31,6 +31,7 @@ from ...image_processing_outputs import SemanticSegmentationPostProcessorOutput from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import ChannelDimension, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...modeling_outputs import DepthEstimatorOutput from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -248,6 +249,7 @@ def _preprocess( return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False ) -> "list[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]": diff --git a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py index fad157f0e03e..acc7e1ebe4d2 100644 --- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py @@ -29,6 +29,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -151,23 +152,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -203,6 +201,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py index f178b1a48486..4eb8f181f79d 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -26,6 +26,7 @@ from ...image_processing_utils import BatchFeature from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_videos_with_kernel, use_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor @@ -187,16 +188,29 @@ def resize( size: SizeDict, resample: "PILImageResampling | tvF.InterpolationMode | int | None", factor: int, - temporal_factor: int, + temporal_factor: int = 2, cap_pixels_per_frame: bool | None = None, max_video_tokens: int | None = None, **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input video aspect ratio.""" + resized_height, resized_width = self._resized_size( + *videos.shape[-2:], videos.shape[1], size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens + ) + return super().resize( + image=videos, + size=SizeDict(height=resized_height, width=resized_width), + resample=resample, + ) + + def _resized_size( + self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens=None + ): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" + # get_num_of_video_patches repeats this rule because vLLM needs a patch count if not size.shortest_edge or not size.longest_edge: raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - num_frames = videos.shape[1] max_pixels = size.longest_edge if cap_pixels_per_frame: # per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame @@ -205,8 +219,7 @@ def resize( pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05)) max_pixels = pixels_per_frame * num_frames - height, width = videos.shape[-2:] - resized_height, resized_width = smart_resize( + return smart_resize( height=height, width=width, num_frames=num_frames, @@ -215,11 +228,6 @@ def resize( min_pixels=size.shortest_edge, max_pixels=max_pixels, ) - return super().resize( - image=videos, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) def patchify( self, @@ -261,6 +269,7 @@ def patchify( return flatten_patches, grid_t, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_videos_with_kernel) def _preprocess( self, videos: list["torch.Tensor"], diff --git a/src/transformers/models/dpt/image_processing_dpt.py b/src/transformers/models/dpt/image_processing_dpt.py index a2e71dcaa7d6..b500dfb1d431 100644 --- a/src/transformers/models/dpt/image_processing_dpt.py +++ b/src/transformers/models/dpt/image_processing_dpt.py @@ -39,6 +39,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -258,6 +259,7 @@ def _preprocess( return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False ) -> "list[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]": diff --git a/src/transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py b/src/transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py index 8db1bfb9663a..e0361c1045ff 100644 --- a/src/transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py +++ b/src/transformers/models/ernie4_5_vl_moe/image_processing_ernie4_5_vl_moe.py @@ -27,6 +27,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, logging @@ -115,23 +116,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -167,6 +165,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/glm_image/image_processing_glm_image.py b/src/transformers/models/glm_image/image_processing_glm_image.py index ae28a2bfecdd..40d2230d7190 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -29,6 +29,7 @@ from ...image_processing_backends import TorchvisionBackend from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -163,23 +164,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -215,6 +213,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py index 3de042dc3122..f12b12e87b68 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -29,6 +29,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -121,6 +122,10 @@ def _standardize_kwargs( max_pixels: int | None = None, **kwargs, ) -> dict: + # The reference HunyuanOCR processor calls `PIL.Image.resize` without a + # resampling argument, which uses BICUBIC for RGB images. Its config has + # `resample=1` (LANCZOS), but the original implementation never uses it. + kwargs["resample"] = PILImageResampling.BICUBIC if min_pixels is not None or max_pixels is not None: warnings.warn( "Passing `min_pixels` and `max_pixels` to a processor call is deprecated and will be removed in v5.23. " @@ -153,26 +158,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), - # The reference HunyuanOCR processor calls `PIL.Image.resize` without a - # resampling argument, which uses BICUBIC for RGB images. Its config has - # `resample=1` (LANCZOS), but the original implementation never uses it. - resample=PILImageResampling.BICUBIC, + resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -183,22 +182,14 @@ def patchify( """Patchifies each image into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels.""" batch_size, channel, resized_height, resized_width = images.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = images.reshape( - batch_size, - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order in comparison to Qwen - patches = patches.permute(0, 2, 3, 5, 6, 1, 4, 7) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the permute joined them back, which gave this same order. + patches = images.reshape(batch_size, channel, grid_h, patch_size, grid_w, patch_size) + patches = patches.permute(0, 2, 4, 1, 3, 5) flatten_patches = ( - patches.unsqueeze(6) - .expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1) + patches.unsqueeze(4) + .expand(-1, -1, -1, -1, temporal_patch_size, -1, -1) .reshape( batch_size, grid_h * grid_w, @@ -208,6 +199,7 @@ def patchify( return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], @@ -296,5 +288,10 @@ def get_number_of_image_patches( ) return resized_height // patch_size, resized_width // patch_size + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 + __all__ = ["HunYuanVLImageProcessor"] diff --git a/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py index 7bbac6cfd4c5..39a822d36409 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import math import warnings from collections.abc import Iterable @@ -177,22 +176,15 @@ def patchify( channel, resized_height, resized_width = image.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = image.reshape( - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order - (gh, mh, gw, mw, C, ph, pw) - patches = np.transpose(patches, (1, 2, 4, 5, 0, 3, 6)) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the transpose joined them back, which gave this same order. + patches = image.reshape(channel, grid_h, patch_size, grid_w, patch_size) + patches = np.transpose(patches, (1, 3, 0, 2, 4)) # expand temporal_patch_size as a broadcast (zero-copy) patches = np.broadcast_to( - patches[:, :, :, :, :, None, :, :], - (*patches.shape[:5], temporal_patch_size, *patches.shape[5:]), + patches[:, :, :, None, :, :], + (*patches.shape[:3], temporal_patch_size, *patches.shape[3:]), ) flatten_patches = patches.reshape( diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index 940c6b9210e9..ae3ea6506cef 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -13,20 +13,19 @@ # limitations under the License. import itertools -from collections.abc import Callable +from collections.abc import Callable, Iterable import numpy as np import torch from huggingface_hub.dataclasses import strict from torch import nn -from torchvision.transforms.v2 import functional as tvF from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...configuration_utils import PreTrainedConfig from ...generation import GenerationMixin -from ...image_processing_backends import PilBackend, TorchvisionBackend +from ...image_processing_backends import PilBackend from ...image_utils import PILImageResampling, SizeDict from ...integrations import use_kernel_forward_from_hub from ...masking_utils import create_causal_mask @@ -339,35 +338,23 @@ class HunYuanVLImageProcessor(Qwen2VLImageProcessor): spatial_patch_size = 1 valid_kwargs = HunYuanVLImageProcessorKwargs - def resize( + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 + + def _standardize_kwargs( self, - images: "torch.Tensor", - size: SizeDict, - resample: "PILImageResampling | tvF.InterpolationMode | int | None", - factor: int, + size: int | Iterable[int] | dict[str, int] | SizeDict | None = None, + min_pixels: int | None = None, + max_pixels: int | None = None, **kwargs, - ) -> "torch.Tensor": - """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - return TorchvisionBackend.resize( - self, - image=images, - size=SizeDict(height=resized_height, width=resized_width), - # The reference HunyuanOCR processor calls `PIL.Image.resize` without a - # resampling argument, which uses BICUBIC for RGB images. Its config has - # `resample=1` (LANCZOS), but the original implementation never uses it. - resample=PILImageResampling.BICUBIC, - ) + ) -> dict: + # The reference HunyuanOCR processor calls `PIL.Image.resize` without a + # resampling argument, which uses BICUBIC for RGB images. Its config has + # `resample=1` (LANCZOS), but the original implementation never uses it. + kwargs["resample"] = PILImageResampling.BICUBIC + return super()._standardize_kwargs(size=size, min_pixels=min_pixels, max_pixels=max_pixels, **kwargs) def patchify( self, @@ -379,22 +366,14 @@ def patchify( """Patchifies each image into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels.""" batch_size, channel, resized_height, resized_width = images.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = images.reshape( - batch_size, - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order in comparison to Qwen - patches = patches.permute(0, 2, 3, 5, 6, 1, 4, 7) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the permute joined them back, which gave this same order. + patches = images.reshape(batch_size, channel, grid_h, patch_size, grid_w, patch_size) + patches = patches.permute(0, 2, 4, 1, 3, 5) flatten_patches = ( - patches.unsqueeze(6) - .expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1) + patches.unsqueeze(4) + .expand(-1, -1, -1, -1, temporal_patch_size, -1, -1) .reshape( batch_size, grid_h * grid_w, @@ -488,22 +467,15 @@ def patchify( channel, resized_height, resized_width = image.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = image.reshape( - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order - (gh, mh, gw, mw, C, ph, pw) - patches = np.transpose(patches, (1, 2, 4, 5, 0, 3, 6)) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the transpose joined them back, which gave this same order. + patches = image.reshape(channel, grid_h, patch_size, grid_w, patch_size) + patches = np.transpose(patches, (1, 3, 0, 2, 4)) # expand temporal_patch_size as a broadcast (zero-copy) patches = np.broadcast_to( - patches[:, :, :, :, :, None, :, :], - (*patches.shape[:5], temporal_patch_size, *patches.shape[5:]), + patches[:, :, :, None, :, :], + (*patches.shape[:3], temporal_patch_size, *patches.shape[3:]), ) flatten_patches = patches.reshape( diff --git a/src/transformers/models/hy_v4_vl/image_processing_hy_v4_vl.py b/src/transformers/models/hy_v4_vl/image_processing_hy_v4_vl.py index a22735daef9f..e8b841e869bc 100644 --- a/src/transformers/models/hy_v4_vl/image_processing_hy_v4_vl.py +++ b/src/transformers/models/hy_v4_vl/image_processing_hy_v4_vl.py @@ -29,6 +29,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -121,6 +122,10 @@ def _standardize_kwargs( max_pixels: int | None = None, **kwargs, ) -> dict: + # The reference HunyuanOCR processor calls `PIL.Image.resize` without a + # resampling argument, which uses BICUBIC for RGB images. Its config has + # `resample=1` (LANCZOS), but the original implementation never uses it. + kwargs["resample"] = PILImageResampling.BICUBIC if min_pixels is not None or max_pixels is not None: warnings.warn( "Passing `min_pixels` and `max_pixels` to a processor call is deprecated and will be removed in v5.23. " @@ -153,26 +158,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), - # The reference HunyuanOCR processor calls `PIL.Image.resize` without a - # resampling argument, which uses BICUBIC for RGB images. Its config has - # `resample=1` (LANCZOS), but the original implementation never uses it. - resample=PILImageResampling.BICUBIC, + resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -183,22 +182,14 @@ def patchify( """Patchifies each image into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels.""" batch_size, channel, resized_height, resized_width = images.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = images.reshape( - batch_size, - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order in comparison to Qwen - patches = patches.permute(0, 2, 3, 5, 6, 1, 4, 7) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the permute joined them back, which gave this same order. + patches = images.reshape(batch_size, channel, grid_h, patch_size, grid_w, patch_size) + patches = patches.permute(0, 2, 4, 1, 3, 5) flatten_patches = ( - patches.unsqueeze(6) - .expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1) + patches.unsqueeze(4) + .expand(-1, -1, -1, -1, temporal_patch_size, -1, -1) .reshape( batch_size, grid_h * grid_w, @@ -208,6 +199,7 @@ def patchify( return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], @@ -296,5 +288,10 @@ def get_number_of_image_patches( ) return resized_height // patch_size, resized_width // patch_size + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 + __all__ = ["HYV4VLImageProcessor"] diff --git a/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py b/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py index a2b84dea380b..5611102945df 100644 --- a/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py +++ b/src/transformers/models/hy_v4_vl/image_processing_pil_hy_v4_vl.py @@ -175,22 +175,15 @@ def patchify( channel, resized_height, resized_width = image.shape grid_h, grid_w = resized_height // patch_size, resized_width // patch_size - patches = image.reshape( - channel, - grid_h // merge_size, - merge_size, - patch_size, - grid_w // merge_size, - merge_size, - patch_size, - ) - # Flatten patches in row-major order - (gh, mh, gw, mw, C, ph, pw) - patches = np.transpose(patches, (1, 2, 4, 5, 0, 3, 6)) + # Patches in plain row-major order, unlike Qwen2-VL's `merge_size` x `merge_size` blocks. The original code + # split rows and columns by `merge_size` and the transpose joined them back, which gave this same order. + patches = image.reshape(channel, grid_h, patch_size, grid_w, patch_size) + patches = np.transpose(patches, (1, 3, 0, 2, 4)) # expand temporal_patch_size as a broadcast (zero-copy) patches = np.broadcast_to( - patches[:, :, :, :, :, None, :, :], - (*patches.shape[:5], temporal_patch_size, *patches.shape[5:]), + patches[:, :, :, None, :, :], + (*patches.shape[:3], temporal_patch_size, *patches.shape[3:]), ) flatten_patches = patches.reshape( diff --git a/src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py b/src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py index aa8a02a62b5c..edacf171fd44 100644 --- a/src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py +++ b/src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py @@ -34,7 +34,7 @@ ) from ...modeling_utils import slice_logits_to_keep from ...processing_utils import MultiModalData, Unpack -from ...utils import TensorType, TransformersKwargs, auto_docstring +from ...utils import TensorType, TransformersKwargs, auto_docstring, no_inherit_decorator from ...video_processing_utils import BaseVideoProcessor from ...video_utils import group_videos_by_shape, reorder_videos from ..ernie4_5.modeling_ernie4_5 import apply_rotary_pos_emb # noqa: F401 @@ -821,6 +821,9 @@ def resize( resample=resample, ) + def _resized_size(self, *args, **kwargs): + raise AttributeError("Not needed for HY-V4-VL") + def patchify( self, videos: "torch.Tensor", @@ -856,6 +859,7 @@ def patchify( ) return flatten_patches, grid_t, grid_h, grid_w + @no_inherit_decorator def _preprocess( self, videos: list["torch.Tensor"], diff --git a/src/transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py index 9168ea077ffd..3d5ea060bf4b 100644 --- a/src/transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py @@ -29,6 +29,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -155,23 +156,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -207,6 +205,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py b/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py index 6b49e727f675..ce8d3876e070 100644 --- a/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py +++ b/src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py @@ -30,6 +30,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -181,6 +182,7 @@ def _preprocess( return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, diff --git a/src/transformers/models/mobilevit/image_processing_mobilevit.py b/src/transformers/models/mobilevit/image_processing_mobilevit.py index 9cf314a8003d..f7e90345edd2 100644 --- a/src/transformers/models/mobilevit/image_processing_mobilevit.py +++ b/src/transformers/models/mobilevit/image_processing_mobilevit.py @@ -30,6 +30,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import ( TensorType, @@ -204,6 +205,7 @@ def _preprocess( processed_images = reorder_images(processed_images_grouped, grouped_images_index) return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, diff --git a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py index 058315505fd9..df20a6aab061 100644 --- a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py @@ -34,6 +34,7 @@ from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -159,23 +160,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -211,6 +209,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], @@ -298,5 +297,15 @@ def get_number_of_image_patches(self, height: int, width: int, images_kwargs: di grid_h, grid_w = resized_height // patch_size, resized_width // patch_size return grid_h * grid_w + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 + + @property + def flatten_patches(self): + """Patches are returned as `(C * T, P, P)` blocks.""" + return False + __all__ = ["PaddleOCRVLImageProcessor"] diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index f81fa78d1e4b..ebc65dd0e025 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -184,6 +184,16 @@ class PaddleOCRVLImageProcessor(Qwen2VLImageProcessor): size = {"shortest_edge": 384 * 384, "longest_edge": 1536 * 1536} temporal_patch_size = 1 + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 + + @property + def flatten_patches(self): + """Patches are returned as `(C * T, P, P)` blocks.""" + return False + def patchify( self, images: "torch.Tensor", diff --git a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py index 78f992affdf5..60a6596a8d21 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -35,6 +35,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -157,23 +158,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", @@ -209,6 +207,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py index 03a2943104d3..491fb7615601 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -31,6 +31,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import resize_normalize_patchify_videos_with_kernel, use_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor @@ -247,32 +248,32 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input video aspect ratio.""" + resized_height, resized_width = self._resized_size( + *videos.shape[-2:], videos.shape[1], size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens + ) + return super().resize( + image=videos, + size=SizeDict(height=resized_height, width=resized_width), + resample=resample, + ) + + def _resized_size( + self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens=None + ): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" + # get_num_of_video_patches repeats this rule, without the per-frame cap, because vLLM needs a patch count if not size.shortest_edge or not size.longest_edge: raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") max_pixels = size.longest_edge if cap_pixels_per_frame: # the per-frame cap (`size.longest_edge`) is bounded by an even share of the `max_video_tokens` - num_frames = videos.shape[1] max_video_tokens = self.max_video_tokens if max_video_tokens is None else max_video_tokens total_pixels = int(max_video_tokens * factor * factor * 0.9) max_pixels = max( min(max_pixels, total_pixels * temporal_factor // num_frames), int(size.shortest_edge * 1.05) ) - - height, width = videos.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=max_pixels, - ) - return super().resize( - image=videos, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=max_pixels) def patchify( self, @@ -314,6 +315,7 @@ def patchify( return flatten_patches, grid_t, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_videos_with_kernel) def _preprocess( self, videos: list["torch.Tensor"], diff --git a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py index 086ffe9344c5..be52ae4e7097 100644 --- a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py @@ -26,7 +26,7 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...configuration_utils import PreTrainedConfig -from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict +from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from ...masking_utils import create_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_outputs import ( @@ -38,7 +38,7 @@ from ...modeling_rope_utils import RopeParameters from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, slice_logits_to_keep from ...processing_utils import _UNMARKED, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs -from ...utils import auto_docstring, is_torchvision_available, logging +from ...utils import auto_docstring, logging from ...utils.deprecation import deprecate_attr, deprecate_kwarg from ...utils.generic import ( merge_with_config_defaults, @@ -77,10 +77,6 @@ ) -if is_torchvision_available(): - from torchvision.transforms.v2 import functional as tvF - - logger = logging.get_logger(__name__) @@ -1042,22 +1038,14 @@ def __init__(self, **kwargs: Unpack[Qwen3VLVideoProcessorInitKwargs]): def _standardize_kwargs(self, **super_kwargs): raise NotImplementedError("No need to override, fallback to base class implementation") - def resize( - self, - videos: "torch.Tensor", - size: SizeDict, - resample: "PILImageResampling | tvF.InterpolationMode | int | None", - factor: int, - temporal_factor: int, - cap_pixels_per_frame: bool | None = None, - max_video_tokens: int | None = None, - **kwargs, - ) -> "torch.Tensor": - """Resize dynamically based on input video aspect ratio.""" + def _resized_size( + self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens=None + ): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" + # get_num_of_video_patches repeats this rule because vLLM needs a patch count if not size.shortest_edge or not size.longest_edge: raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - num_frames = videos.shape[1] max_pixels = size.longest_edge if cap_pixels_per_frame: # per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame @@ -1066,8 +1054,7 @@ def resize( pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05)) max_pixels = pixels_per_frame * num_frames - height, width = videos.shape[-2:] - resized_height, resized_width = smart_resize( + return smart_resize( height=height, width=width, num_frames=num_frames, @@ -1076,12 +1063,6 @@ def resize( min_pixels=size.shortest_edge, max_pixels=max_pixels, ) - return BaseVideoProcessor.resize( - self, - image=videos, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) def get_num_of_video_patches(self, num_frames: int, height: int, width: int, videos_kwargs=None): """ diff --git a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py index 8ec8abf5bcf7..1952171a576e 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -25,6 +25,7 @@ from ...image_processing_utils import BatchFeature from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict +from ...integrations.hub_processing_kernels import resize_normalize_patchify_videos_with_kernel, use_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, is_torchvision_available, logging from ...video_processing_utils import BaseVideoProcessor @@ -190,16 +191,29 @@ def resize( size: SizeDict, resample: "PILImageResampling | tvF.InterpolationMode | int | None", factor: int, - temporal_factor: int, + temporal_factor: int = 2, cap_pixels_per_frame: bool | None = None, max_video_tokens: int | None = None, **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input video aspect ratio.""" + resized_height, resized_width = self._resized_size( + *videos.shape[-2:], videos.shape[1], size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens + ) + return super().resize( + image=videos, + size=SizeDict(height=resized_height, width=resized_width), + resample=resample, + ) + + def _resized_size( + self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame, max_video_tokens=None + ): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" + # get_num_of_video_patches repeats this rule because vLLM needs a patch count if not size.shortest_edge or not size.longest_edge: raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - num_frames = videos.shape[1] max_pixels = size.longest_edge if cap_pixels_per_frame: # per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame @@ -208,8 +222,7 @@ def resize( pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05)) max_pixels = pixels_per_frame * num_frames - height, width = videos.shape[-2:] - resized_height, resized_width = smart_resize( + return smart_resize( height=height, width=width, num_frames=num_frames, @@ -218,11 +231,6 @@ def resize( min_pixels=size.shortest_edge, max_pixels=max_pixels, ) - return super().resize( - image=videos, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) def patchify( self, @@ -264,6 +272,7 @@ def patchify( return flatten_patches, grid_t, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_videos_with_kernel) def _preprocess( self, videos: list["torch.Tensor"], diff --git a/src/transformers/models/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index 65f0fc4e278e..c036882f29d8 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,6 +37,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import load_cv_utils_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available @@ -635,13 +636,14 @@ def post_process_masks( """ if isinstance(original_sizes, (torch.Tensor, np.ndarray)): original_sizes = original_sizes.tolist() - # TODO: add connected components kernel for postprocessing output_masks = [] for i, original_size in enumerate(original_sizes): if isinstance(masks[i], np.ndarray): masks[i] = torch.from_numpy(masks[i]) elif not isinstance(masks[i], torch.Tensor): raise TypeError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`") + if max_hole_area > 0 or max_sprinkle_area > 0: + masks[i] = self._remove_small_regions(masks[i], mask_threshold, max_hole_area, max_sprinkle_area) interpolated_mask = F.interpolate(masks[i], original_size, mode="bilinear", align_corners=False) if apply_non_overlapping_constraints: interpolated_mask = self._apply_non_overlapping_constraints(interpolated_mask) @@ -687,5 +689,23 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) return pred_masks + def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, both found on `masks`.""" + kernel = load_cv_utils_kernel(masks.device) if self.use_kernels else None + if kernel is None: + raise ValueError( + "`max_hole_area` and `max_sprinkle_area` need the connected components kernel: load the processor " + "with `use_kernels=True` and pass masks on a CUDA device." + ) + regions = masks.flatten(0, 1).unsqueeze(1) + output = regions + for max_area, is_foreground, score_offset in ((max_hole_area, False, 10.0), (max_sprinkle_area, True, -10.0)): + if max_area <= 0: + continue + region = regions > mask_threshold if is_foreground else regions <= mask_threshold + areas = kernel.connected_component_areas(region) + output = torch.where(region & (areas <= max_area), mask_threshold + score_offset, output) + return output.reshape_as(masks) + __all__ = ["Sam2ImageProcessor"] diff --git a/src/transformers/models/sam2/modular_sam2.py b/src/transformers/models/sam2/modular_sam2.py index d4b4fba0b53f..4f78a36f248c 100644 --- a/src/transformers/models/sam2/modular_sam2.py +++ b/src/transformers/models/sam2/modular_sam2.py @@ -34,6 +34,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import load_cv_utils_kernel from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -240,13 +241,14 @@ def post_process_masks( """ if isinstance(original_sizes, (torch.Tensor, np.ndarray)): original_sizes = original_sizes.tolist() - # TODO: add connected components kernel for postprocessing output_masks = [] for i, original_size in enumerate(original_sizes): if isinstance(masks[i], np.ndarray): masks[i] = torch.from_numpy(masks[i]) elif not isinstance(masks[i], torch.Tensor): raise TypeError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`") + if max_hole_area > 0 or max_sprinkle_area > 0: + masks[i] = self._remove_small_regions(masks[i], mask_threshold, max_hole_area, max_sprinkle_area) interpolated_mask = F.interpolate(masks[i], original_size, mode="bilinear", align_corners=False) if apply_non_overlapping_constraints: interpolated_mask = self._apply_non_overlapping_constraints(interpolated_mask) @@ -256,6 +258,24 @@ def post_process_masks( return output_masks + def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, both found on `masks`.""" + kernel = load_cv_utils_kernel(masks.device) if self.use_kernels else None + if kernel is None: + raise ValueError( + "`max_hole_area` and `max_sprinkle_area` need the connected components kernel: load the processor " + "with `use_kernels=True` and pass masks on a CUDA device." + ) + regions = masks.flatten(0, 1).unsqueeze(1) + output = regions + for max_area, is_foreground, score_offset in ((max_hole_area, False, 10.0), (max_sprinkle_area, True, -10.0)): + if max_area <= 0: + continue + region = regions > mask_threshold if is_foreground else regions <= mask_threshold + areas = kernel.connected_component_areas(region) + output = torch.where(region & (areas <= max_area), mask_threshold + score_offset, output) + return output.reshape_as(masks) + def _get_preprocess_shape(self): raise NotImplementedError("No _get_preprocess_shape for SAM 2.") diff --git a/src/transformers/models/sam3/image_processing_sam3.py b/src/transformers/models/sam3/image_processing_sam3.py index d87236557e4d..a1939356abf3 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,6 +40,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import load_cv_utils_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available @@ -666,13 +667,14 @@ def post_process_masks( """ if isinstance(original_sizes, (torch.Tensor, np.ndarray)): original_sizes = original_sizes.tolist() - # TODO: add connected components kernel for postprocessing output_masks = [] for i, original_size in enumerate(original_sizes): if isinstance(masks[i], np.ndarray): masks[i] = torch.from_numpy(masks[i]) elif not isinstance(masks[i], torch.Tensor): raise TypeError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`") + if max_hole_area > 0 or max_sprinkle_area > 0: + masks[i] = self._remove_small_regions(masks[i], mask_threshold, max_hole_area, max_sprinkle_area) interpolated_mask = F.interpolate(masks[i], original_size, mode="bilinear", align_corners=False) if apply_non_overlapping_constraints: interpolated_mask = self._apply_non_overlapping_constraints(interpolated_mask) @@ -718,6 +720,24 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) return pred_masks + def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, both found on `masks`.""" + kernel = load_cv_utils_kernel(masks.device) if self.use_kernels else None + if kernel is None: + raise ValueError( + "`max_hole_area` and `max_sprinkle_area` need the connected components kernel: load the processor " + "with `use_kernels=True` and pass masks on a CUDA device." + ) + regions = masks.flatten(0, 1).unsqueeze(1) + output = regions + for max_area, is_foreground, score_offset in ((max_hole_area, False, 10.0), (max_sprinkle_area, True, -10.0)): + if max_area <= 0: + continue + region = regions > mask_threshold if is_foreground else regions <= mask_threshold + areas = kernel.connected_component_areas(region) + output = torch.where(region & (areas <= max_area), mask_threshold + score_offset, output) + return output.reshape_as(masks) + def post_process_semantic_segmentation( self, outputs, diff --git a/src/transformers/models/sam3_video/modeling_sam3_video.py b/src/transformers/models/sam3_video/modeling_sam3_video.py index 6fcebe1ef443..8bb5ce468371 100644 --- a/src/transformers/models/sam3_video/modeling_sam3_video.py +++ b/src/transformers/models/sam3_video/modeling_sam3_video.py @@ -33,7 +33,7 @@ if is_kernels_available(): - from ...integrations.hub_kernels import get_kernel + from ...integrations.hub_kernels import lazy_load_kernel logger = logging.get_logger(__name__) @@ -55,7 +55,7 @@ def _load_cv_utils_kernel_once(): return try: - cv_utils_kernel = get_kernel("kernels-community/cv-utils", version=1) + cv_utils_kernel = lazy_load_kernel("cv-utils") or False except Exception as e: logger.warning_once( f"Failed to load cv_utils kernel (your torch/cuda setup may not be supported): {e}. " diff --git a/src/transformers/models/sapiens2/image_processing_sapiens2.py b/src/transformers/models/sapiens2/image_processing_sapiens2.py index 7e60b35b61d8..2622a7ac88ce 100644 --- a/src/transformers/models/sapiens2/image_processing_sapiens2.py +++ b/src/transformers/models/sapiens2/image_processing_sapiens2.py @@ -36,6 +36,7 @@ get_image_size_for_max_height_width, make_list_of_images, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -607,6 +608,7 @@ def _preprocess( return reorder_images(processed_images_grouped, grouped_images_index) + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False ) -> "list[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]": diff --git a/src/transformers/models/segformer/image_processing_segformer.py b/src/transformers/models/segformer/image_processing_segformer.py index fcf4aac70092..f912f6568567 100644 --- a/src/transformers/models/segformer/image_processing_segformer.py +++ b/src/transformers/models/segformer/image_processing_segformer.py @@ -36,6 +36,7 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_processing_kernels import upsample_argmax_with_kernel, use_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_torch_available @@ -189,6 +190,7 @@ def _preprocess( return processed_images + @use_processing_kernel(upsample_argmax_with_kernel) def post_process_semantic_segmentation( self, outputs, target_sizes: list[tuple] | None = None, return_segmentation_scores: bool = False ) -> "list[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]": diff --git a/src/transformers/models/video_llama_3/image_processing_video_llama_3.py b/src/transformers/models/video_llama_3/image_processing_video_llama_3.py index 5a28938e7968..59af7fc24af0 100644 --- a/src/transformers/models/video_llama_3/image_processing_video_llama_3.py +++ b/src/transformers/models/video_llama_3/image_processing_video_llama_3.py @@ -154,23 +154,20 @@ def resize( **kwargs, ) -> "torch.Tensor": """Resize dynamically based on input image aspect ratio.""" - if not size.shortest_edge or not size.longest_edge: - raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") - - height, width = images.shape[-2:] - resized_height, resized_width = smart_resize( - height, - width, - factor=factor, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) + resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), resample=resample, ) + def _resized_size(self, height, width, size, factor): + """Size an image of `height` x `width` pixels is resized to.""" + # get_number_of_image_patches repeats this rule because vLLM needs a patch count + if not size.shortest_edge or not size.longest_edge: + raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.") + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=size.longest_edge) + def patchify( self, images: "torch.Tensor", diff --git a/src/transformers/models/video_llama_3/modular_video_llama_3.py b/src/transformers/models/video_llama_3/modular_video_llama_3.py index a26fcd9b480f..52b923732b3f 100644 --- a/src/transformers/models/video_llama_3/modular_video_llama_3.py +++ b/src/transformers/models/video_llama_3/modular_video_llama_3.py @@ -40,6 +40,7 @@ get_max_seqlen, is_flash_attention_requested, merge_with_config_defaults, + no_inherit_decorator, ) from ...utils.output_capturing import capture_outputs from ...video_processing_utils import BaseVideoProcessor @@ -793,6 +794,7 @@ class VideoLlama3ImageProcessor(Qwen2VLImageProcessor): "image_merge_sizes", ] + @no_inherit_decorator def _preprocess( self, images: list["torch.Tensor"], @@ -975,6 +977,10 @@ def resize( resample=resample, ) + def _resized_size(self): + raise AttributeError("Not needed for VideoLLaMA3") + + @no_inherit_decorator def _preprocess( self, videos: list["torch.Tensor"], diff --git a/src/transformers/processing_utils.py b/src/transformers/processing_utils.py index c6ba705aeaee..5a35f8342b3b 100644 --- a/src/transformers/processing_utils.py +++ b/src/transformers/processing_utils.py @@ -2079,6 +2079,7 @@ def _resolve_subprocessors(cls, pretrained_model_name_or_path, processor_dict, * # Remove subfolder from kwargs to avoid duplicate keyword arguments keys_to_remove = set({"return_unused_kwargs"}) processor_sig = list(inspect.signature(cls.__init__).parameters) + use_kernels = kwargs.pop("use_kernels", None) # get attributes from processor init signature sub_processors = cls.get_attributes() @@ -2115,10 +2116,13 @@ def _resolve_subprocessors(cls, pretrained_model_name_or_path, processor_dict, * ) auto_processor_class = cls.get_possibly_dynamic_module(sub_processor_class_name) + sub_processor_kwargs = {**kwargs, "return_unused_kwargs": True} + if use_kernels is not None and modality in ("image_processor", "video_processor"): + sub_processor_kwargs["use_kernels"] = use_kernels sub_processor = auto_processor_class.from_pretrained( pretrained_model_name_or_path, processor_config=sub_processor_config, - **{**kwargs, "return_unused_kwargs": True}, + **sub_processor_kwargs, ) # Remote-code sub-processors may override `from_dict` / `from_pretrained` without supporting # `return_unused_kwargs` and return the bare object: then none of the kwargs counts as used. diff --git a/src/transformers/video_processing_utils.py b/src/transformers/video_processing_utils.py index 6950a47f18d8..13bf37d16731 100644 --- a/src/transformers/video_processing_utils.py +++ b/src/transformers/video_processing_utils.py @@ -443,8 +443,11 @@ def from_dict(cls, video_processor_dict: dict[str, Any], **kwargs): """ video_processor_dict = video_processor_dict.copy() return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) + use_kernels = kwargs.pop("use_kernels", None) valid_keys = cls.valid_kwargs.__annotations__.keys() video_processor_dict.update({k: v for k, v in kwargs.items() if k in valid_keys}) + if use_kernels is not None: + video_processor_dict["use_kernels"] = use_kernels video_processor = cls(**video_processor_dict) # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) diff --git a/tests/kernels/test_processing_kernels.py b/tests/kernels/test_processing_kernels.py new file mode 100644 index 000000000000..a21aefad0291 --- /dev/null +++ b/tests/kernels/test_processing_kernels.py @@ -0,0 +1,508 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Run the slow tests: CUDA_VISIBLE_DEVICES=0 RUN_SLOW=1 pytest -sv tests/kernels/test_processing_kernels.py + +import json +import os +import tempfile +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import numpy as np +import torch +from parameterized import parameterized +from tokenizers import Tokenizer, models + +from transformers import ( + CLIPImageProcessor, + CLIPProcessor, + CohereCompassImageProcessor, + CohereCompassVideoProcessor, + Ernie4_5_VLMoeImageProcessor, + GlmImageImageProcessor, + HunYuanVLImageProcessor, + HYV4VLImageProcessor, + LevitImageProcessor, + MiniMaxM3VLImageProcessor, + PaddleOCRVLImageProcessor, + Qwen2VLImageProcessor, + Qwen2VLVideoProcessor, + Qwen3VLVideoProcessor, + Sam2ImageProcessor, + SegformerImageProcessor, + SegformerImageProcessorPil, + TokenizersBackend, + ViTImageProcessor, +) +from transformers.image_utils import PILImageResampling, SizeDict, load_image +from transformers.integrations.hub_kernels import lazy_load_kernel +from transformers.integrations.hub_processing_kernels import kernel_can_resize, load_cv_utils_kernel +from transformers.testing_utils import TestCasePlus, require_kernels, require_torch_gpu, slow, torch_device +from transformers.video_processing_utils import BaseVideoProcessor + + +PATCHIFY_KERNEL_PROCESSORS = [ + Qwen2VLImageProcessor, + Qwen2VLVideoProcessor, + Qwen3VLVideoProcessor, + CohereCompassImageProcessor, + CohereCompassVideoProcessor, + Ernie4_5_VLMoeImageProcessor, + GlmImageImageProcessor, + HunYuanVLImageProcessor, + HYV4VLImageProcessor, + MiniMaxM3VLImageProcessor, + PaddleOCRVLImageProcessor, +] + + +def connected_component_areas_reference(regions): + """Area of the 8-connected component of every pixel, by label propagation. Slow, for tests only.""" + flat_regions = regions.flatten(1) + labels = torch.arange(1, flat_regions.shape[1] + 1, dtype=torch.float32, device=regions.device) + labels = (labels * flat_regions).view(regions.shape) + while True: + propagated = torch.nn.functional.max_pool2d(labels, kernel_size=3, stride=1, padding=1) * regions + if torch.equal(propagated, labels): + break + labels = propagated + areas = torch.zeros_like(labels, dtype=torch.int32) + for index in range(labels.shape[0]): + _, inverse, counts = labels[index].unique(return_inverse=True, return_counts=True) + areas[index] = counts[inverse].to(torch.int32) * regions[index] + return areas + + +def patchify_kernel_layout_reference( + inputs, + target_sizes, + image_mean, + image_std, + rescale_factor, + resample, + patch_size, + block_size, + temporal_patch_size, +): + """What `resize_normalize_patchify` writes for `(T, C, H, W)` inputs whose frames are already at their target size.""" + mean = torch.tensor(image_mean).view(-1, 1, 1) + std = torch.tensor(image_std).view(-1, 1, 1) + item_patches = [] + for input_frames in inputs: + input_frames = torch.cat( + [input_frames, input_frames[-1:].expand(-input_frames.shape[0] % temporal_patch_size, -1, -1, -1)] + ) + input_frames = (input_frames.float() * rescale_factor - mean) / std + frame_count, channels, height, width = input_frames.shape + patches = input_frames.reshape( + frame_count // temporal_patch_size, + temporal_patch_size, + channels, + height // (patch_size * block_size), + block_size, + patch_size, + width // (patch_size * block_size), + block_size, + patch_size, + ) + patches = patches.permute(0, 3, 6, 4, 7, 2, 1, 5, 8) + item_patches.append(patches.reshape(-1, channels * temporal_patch_size * patch_size * patch_size)) + return torch.cat(item_patches) + + +HUB_PROCESSING_KERNELS = "transformers.integrations.hub_processing_kernels" + + +@contextmanager +def loaded_kernel(kernel): + """Serve `kernel` as the loaded Hub kernel, `None` as a failed load, and accept CPU tensors as CUDA tensors.""" + with patch.multiple( + HUB_PROCESSING_KERNELS, + _CV_UTILS=kernel, + lazy_load_kernel=MagicMock(return_value=None), + get_device_type=MagicMock(return_value="cuda"), + ): + yield + + +class ReferenceConnectedComponentsKernel: + """Stand-in for `kernels-community/cv-utils`: records the input of `connected_component_areas`, answers the reference.""" + + def __init__(self): + self.inputs = [] + + def connected_component_areas(self, mask): + self.inputs.append(mask) + return connected_component_areas_reference(mask) + + +class TestProcessingKernels(TestCasePlus): + """Dispatch and gating of processing kernels. Runs on CPU, `kernels` is not needed.""" + + def setUp(self): + super().setUp() + # One 8x8 object with a 2x2 hole, and a 1 pixel island away from it. + self.mask_logits = torch.full((1, 1, 16, 16), -1.0) + self.mask_logits[..., 2:10, 2:10] = 1.0 + self.mask_logits[..., 5:7, 5:7] = -1.0 + self.mask_logits[..., 13, 13] = 1.0 + + def post_process(self, use_kernels, **kwargs): + processor = Sam2ImageProcessor(use_kernels=use_kernels) + return processor.post_process_masks([self.mask_logits.clone()], [(16, 16)], **kwargs)[0] + + def test_load_cv_utils_kernel_skips_other_devices(self): + with patch(f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel") as lazy_load: + self.assertIsNone(load_cv_utils_kernel(torch.device("cpu"))) + lazy_load.assert_not_called() + with loaded_kernel(None): + self.assertIsNone(load_cv_utils_kernel(torch.device("cpu"))) + + def test_load_cv_utils_kernel_checks_the_kernel_functions(self): + with loaded_kernel(None): + with patch( + f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel", return_value=SimpleNamespace(upsample_argmax=None) + ): + with self.assertRaisesRegex(ImportError, "resize_normalize, resize_normalize_patchify"): + load_cv_utils_kernel(torch.device("cpu")) + kernel = MagicMock() + with patch(f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel", return_value=kernel) as lazy_load: + self.assertIs(load_cv_utils_kernel(torch.device("cpu")), kernel) + self.assertIs(load_cv_utils_kernel(torch.device("cpu")), kernel) + lazy_load.assert_called_once() + + def test_sam2_finds_holes_and_sprinkles_on_the_input_masks(self): + # A 3x3 ring around a 1 pixel hole: like upstream SAM 2, the hole is filled and the ring is a sprinkle. + mask_logits = torch.full((1, 1, 9, 9), -1.0) + mask_logits[..., 3:6, 3:6] = 1.0 + mask_logits[..., 4, 4] = -1.0 + with loaded_kernel(ReferenceConnectedComponentsKernel()): + masks = Sam2ImageProcessor(use_kernels=True).post_process_masks( + [mask_logits], [(9, 9)], max_hole_area=1, max_sprinkle_area=8 + )[0] + expected = torch.zeros(1, 1, 9, 9, dtype=torch.bool) + expected[..., 4, 4] = True + self.assertTrue(torch.equal(masks, expected)) + + def test_sam2_fills_holes_and_removes_sprinkles(self): + kernel = ReferenceConnectedComponentsKernel() + with loaded_kernel(kernel): + masks = self.post_process(use_kernels=True, max_hole_area=4, max_sprinkle_area=1) + too_small_thresholds = self.post_process(use_kernels=True, max_hole_area=3, max_sprinkle_area=0) + self.assertEqual(kernel.inputs[0].shape, (1, 1, 16, 16)) + expected = torch.zeros(1, 1, 16, 16, dtype=torch.bool) + expected[..., 2:10, 2:10] = True + self.assertTrue(torch.equal(masks, expected)) + self.assertTrue(torch.equal(too_small_thresholds, self.post_process(use_kernels=False))) + + def test_sam2_small_regions_need_the_kernel(self): + for use_kernels in (False, True): + with self.assertRaisesRegex(ValueError, "connected components kernel"): + self.post_process(use_kernels, max_hole_area=4, max_sprinkle_area=1) + + def test_kernel_can_resize(self): + image = torch.zeros(3, 4, 4, dtype=torch.uint8) + self.assertTrue(kernel_can_resize([image, image], PILImageResampling.BICUBIC)) + + @parameterized.expand( + [ + ("lanczos", [torch.zeros(3, 4, 4, dtype=torch.uint8)], PILImageResampling.LANCZOS), + ("no_images", [], PILImageResampling.BICUBIC), + ("float_images", [torch.rand(3, 4, 4)], PILImageResampling.BICUBIC), + ( + "mixed_channels", + [torch.zeros(3, 4, 4, dtype=torch.uint8), torch.zeros(1, 4, 4, dtype=torch.uint8)], + PILImageResampling.BICUBIC, + ), + ] + ) + def test_kernel_cannot_resize(self, name, inputs, resample): + self.assertFalse(kernel_can_resize(inputs, resample)) + + def test_semantic_segmentation_calls_the_upsample_argmax_kernel(self): + kernel = MagicMock() + outputs = SimpleNamespace(logits=torch.randn(2, 5, 8, 8)) + processor = SegformerImageProcessor(use_kernels=True) + with loaded_kernel(kernel): + segmentation = processor.post_process_semantic_segmentation(outputs, target_sizes=[(16, 16), (20, 12)]) + with_scores = processor.post_process_semantic_segmentation( + outputs, target_sizes=[(16, 16), (20, 12)], return_segmentation_scores=True + ) + native_size = processor.post_process_semantic_segmentation(outputs) + self.assertIs(segmentation, kernel.upsample_argmax.return_value) + kernel.upsample_argmax.assert_called_once_with(outputs.logits, [(16, 16), (20, 12)]) + self.assertEqual(with_scores[1].segmentation_scores.shape, (5, 20, 12)) + self.assertEqual(native_size[0].shape, (8, 8)) + + def run_vit_with_kernel(self, **kwargs): + kernel = MagicMock() + images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] + with loaded_kernel(kernel): + output = ViTImageProcessor(use_kernels=True)(images, return_tensors=None, **kwargs) + return kernel, output + + def test_resize_normalize_calls_the_kernel(self): + kernel, output = self.run_vit_with_kernel(do_center_crop=True, crop_size={"height": 6, "width": 6}) + self.assertIs(output["pixel_values"], kernel.resize_normalize.return_value) + kernel.resize_normalize.assert_called_once() + self.assertEqual(kernel.resize_normalize.call_args.kwargs["crop_size"], (6, 6)) + self.assertEqual(kernel.resize_normalize.call_args.kwargs["resample"], "bilinear") + + def test_resize_normalize_falls_back_on_a_crop_larger_than_the_resize(self): + kernel, output = self.run_vit_with_kernel( + size={"height": 8, "width": 8}, do_center_crop=True, crop_size={"height": 8, "width": 10} + ) + kernel.resize_normalize.assert_not_called() + self.assertEqual(tuple(output["pixel_values"][0].shape), (3, 8, 10)) + + @parameterized.expand( + [ + ("shortest_edge", {"shortest_edge": 20}), + ("shortest_and_longest_edge", {"shortest_edge": 20, "longest_edge": 25}), + ("max_height_and_width", {"max_height": 20, "max_width": 20}), + ("height_and_width", {"height": 16, "width": 24}), + ] + ) + def test_resize_normalize_receives_the_sizes_of_resize(self, name, size): + images = [ + torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8), + torch.randint(0, 255, (3, 50, 30), dtype=torch.uint8), + ] + processor = ViTImageProcessor(use_kernels=True) + kernel = MagicMock() + with loaded_kernel(kernel): + processor(images, size=size, do_center_crop=False, return_tensors=None) + self.assertEqual( + [tuple(kernel_size) for kernel_size in kernel.resize_normalize.call_args.args[1]], + [tuple(processor.resize(image, SizeDict(**size)).shape[-2:]) for image in images], + ) + + def test_qwen2_vl_uses_the_patchify_kernel_output(self): + images = [torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)] + pixel_values = torch.zeros(24, 3 * 2 * 14 * 14) + kernel = MagicMock() + kernel.resize_normalize_patchify.return_value = (pixel_values, torch.tensor([[1, 4, 6]])) + with loaded_kernel(kernel): + output = Qwen2VLImageProcessor(use_kernels=True)(images, return_tensors="pt") + Qwen2VLImageProcessor(use_kernels=False)(images, return_tensors="pt") + kernel.resize_normalize_patchify.assert_called_once() + call_kwargs = kernel.resize_normalize_patchify.call_args.kwargs + self.assertEqual( + (call_kwargs["patch_size"], call_kwargs["block_size"], call_kwargs["temporal_patch_size"]), (14, 2, 2) + ) + self.assertIs(output["pixel_values"], pixel_values) + self.assertEqual(output["image_grid_thw"].tolist(), [[1, 4, 6]]) + + def test_hunyuan_vl_kernel_resizes_bicubic_like_its_default_path(self): + self.assertEqual( + HunYuanVLImageProcessor(resample=PILImageResampling.BILINEAR).resample, PILImageResampling.BICUBIC + ) + kernel = MagicMock() + kernel.resize_normalize_patchify.return_value = (torch.zeros(0), torch.zeros(1, 3)) + images = [torch.randint(0, 256, (3, 64, 96), dtype=torch.uint8)] + with loaded_kernel(kernel): + HunYuanVLImageProcessor(use_kernels=True)( + images, resample=PILImageResampling.BILINEAR, return_tensors="pt" + ) + self.assertEqual(kernel.resize_normalize_patchify.call_args.kwargs["resample"], "bicubic") + + def test_qwen2_vl_video_passes_one_target_size_per_video(self): + videos = [ + torch.randint(0, 255, (3, 3, 64, 96), dtype=torch.uint8), + torch.randint(0, 255, (2, 3, 32, 32), dtype=torch.uint8), + ] + kernel = MagicMock() + kernel.resize_normalize_patchify.return_value = (torch.zeros(1, 1), torch.tensor([[2, 4, 6], [1, 2, 2]])) + with loaded_kernel(kernel): + output = Qwen2VLVideoProcessor(use_kernels=True)( + videos, do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" + ) + kernel_inputs, target_sizes = kernel.resize_normalize_patchify.call_args.args[:2] + self.assertEqual([input_frames.shape[0] for input_frames in kernel_inputs], [3, 2]) + self.assertEqual(len(target_sizes), 2) + self.assertEqual(output["video_grid_thw"].tolist(), [[2, 4, 6], [1, 2, 2]]) + + def test_processor_overriding_resize_does_not_use_the_resize_kernel(self): + kernel = MagicMock() + with loaded_kernel(kernel): + output = LevitImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) + kernel.resize_normalize.assert_not_called() + self.assertIn("pixel_values", output) + + @parameterized.expand( + [(processor_class.__name__, processor_class, {}) for processor_class in PATCHIFY_KERNEL_PROCESSORS] + + [ + ( + "Qwen2VLImageProcessor_qwen3_vl_settings", + Qwen2VLImageProcessor, + {"patch_size": 16, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5]}, + ) + ] + ) + def test_processors_reaching_the_patchify_kernel_use_its_layout(self, name, processor_class, settings): + is_video = issubclass(processor_class, BaseVideoProcessor) + + def run(height, width): + """The arguments the kernel receives, and the output of the processor without kernels.""" + kernel = MagicMock() + kernel.resize_normalize_patchify.return_value = (torch.zeros(0), torch.zeros(1, 3)) + shape = (3, 3, height, width) if is_video else (3, height, width) + inputs = [torch.randint(0, 256, shape, dtype=torch.uint8)] + call_kwargs = {"do_sample_frames": False} if is_video else {} + with loaded_kernel(kernel): + processor_class(use_kernels=True, **settings)(inputs, return_tensors="pt", **call_kwargs) + self.assertTrue(kernel.resize_normalize_patchify.called, "the processor did not call the kernel") + output = processor_class(use_kernels=False, **settings)(inputs, return_tensors="pt", **call_kwargs) + output_name = "pixel_values_videos" if is_video else "pixel_values" + return kernel.resize_normalize_patchify.call_args, output[output_name] + + height, width = 112, 168 + for _ in range(4): + kernel_call, pixel_values = run(height, width) + if tuple(kernel_call.args[1][0]) == (height, width): + break + height, width = kernel_call.args[1][0] + kernel_inputs, target_sizes = kernel_call.args + self.assertEqual( + [tuple(input_frames.shape[-2:]) for input_frames in kernel_inputs], + [tuple(size) for size in target_sizes], + ) + torch.testing.assert_close( + pixel_values.reshape(-1), + patchify_kernel_layout_reference(*kernel_call.args, **kernel_call.kwargs).reshape(-1), + ) + + def test_use_kernels_is_a_runtime_flag(self): + processor = Sam2ImageProcessor(use_kernels=True) + self.assertNotIn("use_kernels", processor.to_dict()) + with tempfile.TemporaryDirectory() as tmp_dir: + processor.save_pretrained(tmp_dir) + self.assertFalse(Sam2ImageProcessor.from_pretrained(tmp_dir).use_kernels) + self.assertTrue(Sam2ImageProcessor.from_pretrained(tmp_dir, use_kernels=True).use_kernels) + + def test_pil_processor_rejects_use_kernels(self): + with self.assertRaisesRegex(ValueError, "torchvision"): + SegformerImageProcessorPil(use_kernels=True) + + def test_processor_passes_use_kernels_to_the_image_processor_only(self): + tokenizer = TokenizersBackend( + tokenizer_object=Tokenizer(models.WordLevel({"[UNK]": 0, "a": 1}, unk_token="[UNK]")) + ) + with tempfile.TemporaryDirectory() as saved, tempfile.TemporaryDirectory() as resaved: + CLIPProcessor(image_processor=CLIPImageProcessor(), tokenizer=tokenizer).save_pretrained(saved) + processor = CLIPProcessor.from_pretrained(saved, use_kernels=True) + self.assertTrue(processor.image_processor.use_kernels) + self.assertNotIn("use_kernels", processor.tokenizer.init_kwargs) + processor.save_pretrained(resaved) + with open(os.path.join(resaved, "tokenizer_config.json"), encoding="utf-8") as tokenizer_config: + self.assertNotIn("use_kernels", json.load(tokenizer_config)) + self.assertFalse(CLIPProcessor.from_pretrained(resaved).image_processor.use_kernels) + + +@require_kernels +@require_torch_gpu +@slow +class TestConnectedComponentsKernel(TestCasePlus): + """The `kernels-community/cv-utils` connected components kernel against the reference, through the processor.""" + + def test_matches_reference(self): + generator = torch.Generator().manual_seed(0) + masks = torch.randn(4, 3, 63, 65, generator=generator).to(torch_device) + processor = Sam2ImageProcessor(use_kernels=True) + kernel = lazy_load_kernel("cv-utils") + self.assertIsNotNone(kernel, "the cv-utils kernel did not load") + regions = (masks.flatten(0, 1) > 0).unsqueeze(1) + areas = kernel.connected_component_areas(regions) + torch.testing.assert_close(areas.to(torch.int32).cpu(), connected_component_areas_reference(regions.cpu())) + filled = processor.post_process_masks([masks], [(63, 65)], max_hole_area=8, max_sprinkle_area=8)[0] + with patch(f"{HUB_PROCESSING_KERNELS}._CV_UTILS", ReferenceConnectedComponentsKernel()): + expected = processor.post_process_masks([masks], [(63, 65)], max_hole_area=8, max_sprinkle_area=8)[0] + self.assertTrue(torch.equal(filled, expected)) + + +@require_kernels +@require_torch_gpu +@slow +class TestUpsampleArgmaxKernel(TestCasePlus): + def test_matches_default(self): + kernel = lazy_load_kernel("cv-utils") + self.assertIsNotNone(kernel, "the cv-utils kernel did not load") + logits = torch.nn.functional.avg_pool2d(torch.randn(2, 150, 64, 64), 5, stride=1, padding=2) * 5 + outputs = SimpleNamespace(logits=logits.to(torch_device)) + target_sizes = [(256, 341), (480, 640)] + with patch.object(kernel, "upsample_argmax", wraps=kernel.upsample_argmax) as upsample_argmax: + with_kernels = SegformerImageProcessor(use_kernels=True).post_process_semantic_segmentation( + outputs, target_sizes=target_sizes + ) + upsample_argmax.assert_called_once() + without_kernels = SegformerImageProcessor().post_process_semantic_segmentation( + outputs, target_sizes=target_sizes + ) + for with_kernel, without_kernel in zip(with_kernels, without_kernels): + self.assertEqual(with_kernel.shape, without_kernel.shape) + # The kernel upsamples on float16 tensor cores here, so near-ties between two classes can flip. + self.assertLess((with_kernel != without_kernel).float().mean().item(), 1e-3) + + +@require_kernels +@require_torch_gpu +@slow +class TestResizeKernels(TestCasePlus): + """The resize kernels of `kernels-community/cv-utils` against the default torchvision path, on photos.""" + + def setUp(self): + super().setUp() + image = torch.from_numpy(np.array(load_image("http://images.cocodataset.org/val2017/000000039769.jpg"))) + image = image.permute(2, 0, 1).contiguous().to(torch_device) + self.images = [image, image[:, :300, :500].contiguous(), image[:, 100:, 50:].contiguous()] + + def assert_kernel_matches_default(self, operation, processor_class, call): + kernel = lazy_load_kernel("cv-utils") + self.assertIsNotNone(kernel, "the cv-utils kernel did not load") + with patch.object(kernel, operation, wraps=getattr(kernel, operation)) as kernel_operation: + with_kernels = call(processor_class(use_kernels=True)) + kernel_operation.assert_called_once() + without_kernels = call(processor_class(use_kernels=False)) + for key in without_kernels: + self.assertEqual(with_kernels[key].shape, without_kernels[key].shape) + # Both paths round to uint8 after each resize pass, in a different order of operations. + one_level = 1 / 255 / min(processor_class().image_std) + difference = ( + with_kernels.data[list(without_kernels)[0]] - without_kernels.data[list(without_kernels)[0]] + ).abs() + self.assertLess(difference.mean().item(), one_level / 4) + self.assertLess((difference > one_level * 1.01).float().mean().item(), 1e-3) + + def test_resize_normalize(self): + self.assert_kernel_matches_default( + "resize_normalize", ViTImageProcessor, lambda processor: processor(self.images, return_tensors="pt") + ) + + def test_resize_normalize_patchify_images(self): + self.assert_kernel_matches_default( + "resize_normalize_patchify", + Qwen2VLImageProcessor, + lambda processor: processor(self.images, return_tensors="pt"), + ) + + def test_resize_normalize_patchify_video(self): + video = torch.stack([self.images[0]] * 5) + self.assert_kernel_matches_default( + "resize_normalize_patchify", + Qwen2VLVideoProcessor, + lambda processor: processor( + [video], do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" + ), + )