From 9776f5e981466bc4f88cff93bb64404be2c1b536 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 19 Jun 2026 15:01:08 +0200 Subject: [PATCH 01/26] speaking words of wisdom --- docs/source/en/kernel_doc/loading_kernels.md | 26 +++++ src/transformers/image_processing_backends.py | 3 + src/transformers/integrations/hub_kernels.py | 96 +++++++++++++++++++ 3 files changed, 125 insertions(+) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index d59e58c66259..4ba3a55cbc81 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -221,6 +221,32 @@ Set the environment variable to disable kernels globally. export USE_HUB_KERNELS=0 # or OFF or NO ``` +## Processor kernels + +Preprocessing and postprocessing ops can be offloaded to Hub kernels the same way model layers are. `use_kernels=True` swaps a processor op for a registered Hub kernel and falls back to the default implementation when none applies — so custom, hot, or hard-to-vectorize ops (resize, normalize, patchify, NMS, mask decoding, ...) can move onto the GPU without rewriting the processor or the call site. + +Currently kernelized: the fast image processors' resize + normalize. The kernel batches the resize over a ragged set of images and folds rescale and normalize into the same pass. + +```py +from transformers import AutoImageProcessor + +processor = AutoImageProcessor.from_pretrained("google/siglip2-base-patch16-224", use_kernels=True) +pixel_values = processor(images, return_tensors="pt")["pixel_values"] +``` + +For vision-language models the image processor is wrapped in a processor, so the flag passes through [`AutoProcessor`] to the inner image processor. + +```py +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it", use_kernels=True) +inputs = processor(text=prompt, images=images, return_tensors="pt") +``` + +This is opt-in and CUDA only. It falls back to torchvision when the kernel cannot run or the processor is not supported. Supported processors do a fixed-size resize, optionally with a center crop or a shortest-edge resize, followed by rescale and normalize — the classic vision encoders (ViT, DINOv2/DINOv3, SigLIP, BEiT, ...) and SigLIP-based VLMs. Padding processors and dynamic-resolution VLMs fall back. + +The kernel resizes in float, so outputs are parity-close to torchvision (around `1e-4` against the float reference) but not byte-identical to the legacy uint8 resize path. Use the default backend if you need exact reproduction of the original processor. + ## 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 eb9c1e382518..96f5f7dfceae 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -20,6 +20,7 @@ from .image_processing_base import BatchFeature from .image_processing_utils import BaseImageProcessor +from .integrations.hub_kernels import use_image_kernel from .image_transforms import ( center_crop as np_center_crop, ) @@ -87,6 +88,7 @@ class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" def __init__(self, **kwargs: Unpack[ImagesKwargs]): + self.use_kernels = kwargs.pop("use_kernels", False) super().__init__(**kwargs) self._set_attributes(**kwargs) @@ -377,6 +379,7 @@ 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_image_kernel("resize_normalize") def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index f796874c0d69..504592e66bdf 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -11,6 +11,7 @@ # 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 functools import os import re import sys @@ -327,9 +328,103 @@ def register_kernel_mapping_transformers(mapping=None): mapping = _KERNEL_MAPPING register_kernel_mapping(mapping) + _PROCESSING_KERNEL_MAPPING: dict[str, str] = { + "resize_normalize": "Molbap/kernel_image_resize", # TODO: move to kernels-community or equivalent + version tag + } + _processing_kernel_cache: dict[str, "ModuleType | None"] = {} + + def _load_processing_kernel(name): + if name not in _processing_kernel_cache: + repo = _PROCESSING_KERNEL_MAPPING.get(name) + kernel = None + if repo is not None: + # needed before moving to authorized org + try: + kernel = get_kernel(repo, allow_all_kernels=True) + except Exception as primary_error: + try: + kernel = get_kernel_hub(repo, revision="main", trust_remote_code=True) # Yes I know, DO NOT MERGE AS IS + except Exception: + logger.warning_once( + f"use_kernels: could not load image kernel '{name}' from {repo} " + f"({primary_error}); using torchvision." + ) + _processing_kernel_cache[name] = kernel + return _processing_kernel_cache[name] + + def _resample_to_interp(resample): + """Map a PIL resample int or torchvision InterpolationMode to the kernel's name; None if unsupported.""" + if resample is None: + return None + try: + return {2: "bilinear", 3: "bicubic"}.get(int(resample)) + except (TypeError, ValueError): + name = getattr(resample, "name", str(resample)).upper() + return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None + + def _resize_normalize_runner(processor, images, **kwargs): + """Fixed-output resize(+crop)+normalize. Returns a BatchFeature, or None to fall back.""" + if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")) or not images: + return None + if not is_torch_available() or not torch.cuda.is_available() or images[0].dtype != torch.uint8: + return None + interp = _resample_to_interp(kwargs.get("resample")) + if interp is None: + return None + size = kwargs.get("size") + crop = kwargs.get("crop_size") if kwargs.get("do_center_crop") else None + if size.shortest_edge and not size.longest_edge: + if crop is None or not (crop.height and crop.width): + return None + resize_arg, crop_arg, mode = size.shortest_edge, (crop.height, crop.width), "shortest_edge" + elif size.height and size.width: + if crop is not None and (crop.height != size.height or crop.width != size.width): + resize_arg, crop_arg, mode = (size.height, size.width), (crop.height, crop.width), "square" + else: + resize_arg, crop_arg, mode = (size.height, size.width), None, "square" + else: + return None + kernel = _load_processing_kernel("resize_normalize") + if kernel is None: + return None + rescale = float(kwargs.get("rescale_factor")) if kwargs.get("do_rescale") else 1.0 + out = kernel.resize_normalize( + list(images), resize_arg, kwargs.get("image_mean"), kwargs.get("image_std"), + rescale_factor=rescale, resample=interp, antialias=True, crop_size=crop_arg, resize_mode=mode, + ) + from ..image_processing_base import BatchFeature + + return BatchFeature(data={"pixel_values": list(out)}, tensor_type=kwargs.get("return_tensors")) + + _PROCESSING_KERNEL_RUNNERS = { + "resize_normalize": _resize_normalize_runner, + } + + def use_image_kernel(name): + """Run the `name` processing kernel in place of the decorated method when use_kernels=True. + + The registered runner gets the method's args and returns its result, or None to fall back. + """ + + def decorator(method): + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + if _kernels_enabled and getattr(self, "use_kernels", False): + runner = _PROCESSING_KERNEL_RUNNERS.get(name) + if runner is not None and (out := runner(self, *args, **kwargs)) is not None: + return out + return method(self, *args, **kwargs) + + return wrapper + + return decorator + else: _kernels_enabled = False + def use_image_kernel(name): + return lambda method: method + # Stub to make decorators int transformers work when `kernels` # is not installed. def use_kernel_forward_from_hub(*args, **kwargs): @@ -823,6 +918,7 @@ def register_kernel_replacements_and_fusions( "register_kernel_mapping_transformers", "register_kernel_replacements_and_fusions", "replace_kernel_forward_from_hub", + "use_image_kernel", "use_kernel_forward_from_hub", "use_kernel_func_from_hub", "use_kernelized_func", From 09833c85319ea9b2a82404097f1187b7e1039840 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 19 Jun 2026 16:28:55 +0200 Subject: [PATCH 02/26] improve interfacing a bit --- src/transformers/integrations/hub_kernels.py | 38 ++++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 504592e66bdf..b8690dea832a 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -362,32 +362,30 @@ def _resample_to_interp(resample): name = getattr(resample, "name", str(resample)).upper() return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None + def _resize_target(size, crop): + """Resolve a processor size(+crop) to (resize_arg, crop_arg, resize_mode); None if unsupported.""" + if size.shortest_edge and not size.longest_edge: + if crop is None or not (crop.height and crop.width): + return None # shortest-edge without a crop is variable-size output + return size.shortest_edge, (crop.height, crop.width), "shortest_edge" + if size.height and size.width: + cropped = crop is not None and (crop.height, crop.width) != (size.height, size.width) + return (size.height, size.width), (crop.height, crop.width) if cropped else None, "square" + return None + def _resize_normalize_runner(processor, images, **kwargs): - """Fixed-output resize(+crop)+normalize. Returns a BatchFeature, or None to fall back.""" - if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")) or not images: + """Run resize(+crop)+normalize on the kernel; a BatchFeature, or None to fall back to torchvision.""" + if not (images and is_torch_available() and torch.cuda.is_available() and images[0].dtype == torch.uint8): return None - if not is_torch_available() or not torch.cuda.is_available() or images[0].dtype != torch.uint8: + if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): return None interp = _resample_to_interp(kwargs.get("resample")) - if interp is None: - return None - size = kwargs.get("size") - crop = kwargs.get("crop_size") if kwargs.get("do_center_crop") else None - if size.shortest_edge and not size.longest_edge: - if crop is None or not (crop.height and crop.width): - return None - resize_arg, crop_arg, mode = size.shortest_edge, (crop.height, crop.width), "shortest_edge" - elif size.height and size.width: - if crop is not None and (crop.height != size.height or crop.width != size.width): - resize_arg, crop_arg, mode = (size.height, size.width), (crop.height, crop.width), "square" - else: - resize_arg, crop_arg, mode = (size.height, size.width), None, "square" - else: - return None + target = _resize_target(kwargs["size"], kwargs.get("crop_size") if kwargs.get("do_center_crop") else None) kernel = _load_processing_kernel("resize_normalize") - if kernel is None: + if interp is None or target is None or kernel is None: return None - rescale = float(kwargs.get("rescale_factor")) if kwargs.get("do_rescale") else 1.0 + resize_arg, crop_arg, mode = target + rescale = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 out = kernel.resize_normalize( list(images), resize_arg, kwargs.get("image_mean"), kwargs.get("image_std"), rescale_factor=rescale, resample=interp, antialias=True, crop_size=crop_arg, resize_mode=mode, From 98767b7db1c1286c7d91109673a37be741353e83 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 19 Jun 2026 16:59:48 +0200 Subject: [PATCH 03/26] simplify --- src/transformers/image_processing_backends.py | 2 +- src/transformers/integrations/hub_kernels.py | 35 ++++++++----------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 96f5f7dfceae..23acdd5ac538 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -20,7 +20,6 @@ from .image_processing_base import BatchFeature from .image_processing_utils import BaseImageProcessor -from .integrations.hub_kernels import use_image_kernel from .image_transforms import ( center_crop as np_center_crop, ) @@ -54,6 +53,7 @@ is_valid_image, load_image_as_tensor, ) +from .integrations.hub_kernels import use_image_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index b8690dea832a..4a74568c1fc3 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -329,7 +329,7 @@ def register_kernel_mapping_transformers(mapping=None): register_kernel_mapping(mapping) _PROCESSING_KERNEL_MAPPING: dict[str, str] = { - "resize_normalize": "Molbap/kernel_image_resize", # TODO: move to kernels-community or equivalent + version tag + "resize_normalize": "Molbap/kernel_image_resize", # TODO: move to kernels-community + version tag } _processing_kernel_cache: dict[str, "ModuleType | None"] = {} @@ -338,22 +338,17 @@ def _load_processing_kernel(name): repo = _PROCESSING_KERNEL_MAPPING.get(name) kernel = None if repo is not None: - # needed before moving to authorized org try: kernel = get_kernel(repo, allow_all_kernels=True) except Exception as primary_error: try: - kernel = get_kernel_hub(repo, revision="main", trust_remote_code=True) # Yes I know, DO NOT MERGE AS IS + kernel = get_kernel_hub(repo, revision="main", trust_remote_code=True) # DO NOT MERGE AS IS except Exception: - logger.warning_once( - f"use_kernels: could not load image kernel '{name}' from {repo} " - f"({primary_error}); using torchvision." - ) + logger.warning_once(f"use_kernels: could not load '{name}' from {repo} ({primary_error})") _processing_kernel_cache[name] = kernel return _processing_kernel_cache[name] def _resample_to_interp(resample): - """Map a PIL resample int or torchvision InterpolationMode to the kernel's name; None if unsupported.""" if resample is None: return None try: @@ -363,10 +358,9 @@ def _resample_to_interp(resample): return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None def _resize_target(size, crop): - """Resolve a processor size(+crop) to (resize_arg, crop_arg, resize_mode); None if unsupported.""" if size.shortest_edge and not size.longest_edge: if crop is None or not (crop.height and crop.width): - return None # shortest-edge without a crop is variable-size output + return None return size.shortest_edge, (crop.height, crop.width), "shortest_edge" if size.height and size.width: cropped = crop is not None and (crop.height, crop.width) != (size.height, size.width) @@ -374,7 +368,6 @@ def _resize_target(size, crop): return None def _resize_normalize_runner(processor, images, **kwargs): - """Run resize(+crop)+normalize on the kernel; a BatchFeature, or None to fall back to torchvision.""" if not (images and is_torch_available() and torch.cuda.is_available() and images[0].dtype == torch.uint8): return None if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): @@ -387,22 +380,24 @@ def _resize_normalize_runner(processor, images, **kwargs): resize_arg, crop_arg, mode = target rescale = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 out = kernel.resize_normalize( - list(images), resize_arg, kwargs.get("image_mean"), kwargs.get("image_std"), - rescale_factor=rescale, resample=interp, antialias=True, crop_size=crop_arg, resize_mode=mode, + list(images), + resize_arg, + kwargs.get("image_mean"), + kwargs.get("image_std"), + rescale_factor=rescale, + resample=interp, + antialias=True, + crop_size=crop_arg, + resize_mode=mode, ) from ..image_processing_base import BatchFeature return BatchFeature(data={"pixel_values": list(out)}, tensor_type=kwargs.get("return_tensors")) - _PROCESSING_KERNEL_RUNNERS = { - "resize_normalize": _resize_normalize_runner, - } + _PROCESSING_KERNEL_RUNNERS = {"resize_normalize": _resize_normalize_runner} def use_image_kernel(name): - """Run the `name` processing kernel in place of the decorated method when use_kernels=True. - - The registered runner gets the method's args and returns its result, or None to fall back. - """ + """Run the `name` processing kernel in place of the decorated method when use_kernels=True.""" def decorator(method): @functools.wraps(method) From a3d1e520ddc65f8390f9305c1f1b8be94d8c6441 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 19 Jun 2026 17:57:31 +0200 Subject: [PATCH 04/26] guard torch --- src/transformers/image_processing_backends.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 23acdd5ac538..704d45bf2219 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,7 +53,6 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_kernels import use_image_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -71,6 +70,13 @@ if is_torch_available(): import torch + from .integrations.hub_kernels import use_image_kernel +else: + + def use_image_kernel(name): + return lambda method: method + + if is_torchvision_available(): from torchvision.transforms.v2 import functional as tvF From 052c651e5d77671142b44d068f9591226308a3e5 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 19 Jun 2026 18:00:42 +0200 Subject: [PATCH 05/26] pop use kernels arg at init --- src/transformers/image_processing_base.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index f5d362944ced..38cf6f46ce7a 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -396,6 +396,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, not part of the saved config output["image_processor_type"] = self.__class__.__name__ return output From db06e8a79c4916d9377b045114e8d6bcb8927b38 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Mon, 22 Jun 2026 10:54:17 +0200 Subject: [PATCH 06/26] change registration --- src/transformers/image_processing_backends.py | 79 +++++++++++- src/transformers/image_processing_base.py | 3 + src/transformers/integrations/hub_kernels.py | 122 ++++++------------ 3 files changed, 116 insertions(+), 88 deletions(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 704d45bf2219..70213b5719da 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -70,11 +70,14 @@ if is_torch_available(): import torch - from .integrations.hub_kernels import use_image_kernel + from .integrations.hub_kernels import register_processing_kernel, run_processing_kernel else: - def use_image_kernel(name): - return lambda method: method + def register_processing_kernel(name, repo_id, version=None, revision=None): + return lambda adapter: adapter + + def run_processing_kernel(name, *args, **kwargs): + return None if is_torchvision_available(): @@ -89,6 +92,55 @@ def use_image_kernel(name): logger = logging.get_logger(__name__) +def _resample_to_interpolation(resample): + if resample is None: + return None + try: + return {2: "bilinear", 3: "bicubic"}.get(int(resample)) + except (TypeError, ValueError): + name = getattr(resample, "name", str(resample)).upper() + return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None + + +def _resize_normalize_target(size, crop): + if size.shortest_edge and not size.longest_edge: + if crop is None or not (crop.height and crop.width): + return None + return size.shortest_edge, (crop.height, crop.width), "shortest_edge" + if size.height and size.width: + cropped = crop is not None and (crop.height, crop.width) != (size.height, size.width) + return (size.height, size.width), (crop.height, crop.width) if cropped else None, "square" + return None + + +@register_processing_kernel("resize_normalize", repo_id="kernels-community/kernel_image_resize", version=1) +def _resize_normalize_kernel(kernel, images, **kwargs): + if not (images and torch.cuda.is_available() and images[0].dtype == torch.uint8): + return None + if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): + return None + interpolation = _resample_to_interpolation(kwargs.get("resample")) + target = _resize_normalize_target( + kwargs["size"], kwargs.get("crop_size") if kwargs.get("do_center_crop") else None + ) + if interpolation is None or target is None: + return None + resize_size, crop_size, resize_mode = target + rescale_factor = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 + pixel_values = kernel.resize_normalize( + list(images), + resize_size, + kwargs.get("image_mean"), + kwargs.get("image_std"), + rescale_factor=rescale_factor, + resample=interpolation, + antialias=True, + crop_size=crop_size, + resize_mode=resize_mode, + ) + return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=kwargs.get("return_tensors")) + + @requires(backends=("torch", "torchvision")) class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" @@ -385,7 +437,6 @@ 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_image_kernel("resize_normalize") def _preprocess( self, images: list["torch.Tensor"], @@ -406,6 +457,26 @@ def _preprocess( **kwargs, ) -> BatchFeature: """Preprocess using Torchvision backend (fast, GPU-accelerated).""" + if self.use_kernels: + pixel_values = run_processing_kernel( + "resize_normalize", + images, + do_resize=do_resize, + size=size, + resample=resample, + do_center_crop=do_center_crop, + crop_size=crop_size, + do_rescale=do_rescale, + rescale_factor=rescale_factor, + do_normalize=do_normalize, + image_mean=image_mean, + image_std=image_std, + do_pad=do_pad, + return_tensors=return_tensors, + ) + if pixel_values is not None: + return pixel_values + # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index 38cf6f46ce7a..da86f0df61bf 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -366,8 +366,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) image_processor_dict.update({k: v for k, v in kwargs.items() if k in cls.valid_kwargs.__annotations__}) image_processor = cls(**image_processor_dict) + if use_kernels is not None: + image_processor.use_kernels = use_kernels # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) extra_keys = [] diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 4a74568c1fc3..e09a38f59d92 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -11,7 +11,6 @@ # 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 functools import os import re import sys @@ -328,95 +327,49 @@ def register_kernel_mapping_transformers(mapping=None): mapping = _KERNEL_MAPPING register_kernel_mapping(mapping) - _PROCESSING_KERNEL_MAPPING: dict[str, str] = { - "resize_normalize": "Molbap/kernel_image_resize", # TODO: move to kernels-community + version tag - } - _processing_kernel_cache: dict[str, "ModuleType | None"] = {} - - def _load_processing_kernel(name): - if name not in _processing_kernel_cache: - repo = _PROCESSING_KERNEL_MAPPING.get(name) - kernel = None - if repo is not None: - try: - kernel = get_kernel(repo, allow_all_kernels=True) - except Exception as primary_error: - try: - kernel = get_kernel_hub(repo, revision="main", trust_remote_code=True) # DO NOT MERGE AS IS - except Exception: - logger.warning_once(f"use_kernels: could not load '{name}' from {repo} ({primary_error})") - _processing_kernel_cache[name] = kernel - return _processing_kernel_cache[name] - - def _resample_to_interp(resample): - if resample is None: - return None - try: - return {2: "bilinear", 3: "bicubic"}.get(int(resample)) - except (TypeError, ValueError): - name = getattr(resample, "name", str(resample)).upper() - return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None - - def _resize_target(size, crop): - if size.shortest_edge and not size.longest_edge: - if crop is None or not (crop.height and crop.width): - return None - return size.shortest_edge, (crop.height, crop.width), "shortest_edge" - if size.height and size.width: - cropped = crop is not None and (crop.height, crop.width) != (size.height, size.width) - return (size.height, size.width), (crop.height, crop.width) if cropped else None, "square" - return None + _processing_kernels: dict[str, dict] = {} + + def register_processing_kernel(name, repo_id, version=None, revision=None): + def register(adapter): + _processing_kernels[name] = { + "adapter": adapter, + "repo_id": repo_id, + "version": version, + "revision": revision, + "module": None, + "loaded": False, + } + return adapter - def _resize_normalize_runner(processor, images, **kwargs): - if not (images and is_torch_available() and torch.cuda.is_available() and images[0].dtype == torch.uint8): - return None - if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): + return register + + def run_processing_kernel(name, *args, **kwargs): + entry = _processing_kernels.get(name) + if not _kernels_enabled or entry is None or entry["adapter"] is None: return None - interp = _resample_to_interp(kwargs.get("resample")) - target = _resize_target(kwargs["size"], kwargs.get("crop_size") if kwargs.get("do_center_crop") else None) - kernel = _load_processing_kernel("resize_normalize") - if interp is None or target is None or kernel is None: + if not entry["loaded"]: + entry["loaded"] = True + version, revision = entry["version"], entry["revision"] + if version is None and revision is None: + version = 1 + try: + entry["module"] = get_kernel( + entry["repo_id"], revision=revision, version=version, allow_all_kernels=ALLOW_ALL_KERNELS + ) + except Exception as error: + logger.warning_once(f"could not load processing kernel '{name}' from {entry['repo_id']}: {error}") + if entry["module"] is None: return None - resize_arg, crop_arg, mode = target - rescale = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 - out = kernel.resize_normalize( - list(images), - resize_arg, - kwargs.get("image_mean"), - kwargs.get("image_std"), - rescale_factor=rescale, - resample=interp, - antialias=True, - crop_size=crop_arg, - resize_mode=mode, - ) - from ..image_processing_base import BatchFeature - - return BatchFeature(data={"pixel_values": list(out)}, tensor_type=kwargs.get("return_tensors")) - - _PROCESSING_KERNEL_RUNNERS = {"resize_normalize": _resize_normalize_runner} - - def use_image_kernel(name): - """Run the `name` processing kernel in place of the decorated method when use_kernels=True.""" - - def decorator(method): - @functools.wraps(method) - def wrapper(self, *args, **kwargs): - if _kernels_enabled and getattr(self, "use_kernels", False): - runner = _PROCESSING_KERNEL_RUNNERS.get(name) - if runner is not None and (out := runner(self, *args, **kwargs)) is not None: - return out - return method(self, *args, **kwargs) - - return wrapper - - return decorator + return entry["adapter"](entry["module"], *args, **kwargs) else: _kernels_enabled = False - def use_image_kernel(name): - return lambda method: method + def register_processing_kernel(name, repo_id, version=None, revision=None): + return lambda adapter: adapter + + def run_processing_kernel(name, *args, **kwargs): + return None # Stub to make decorators int transformers work when `kernels` # is not installed. @@ -910,8 +863,9 @@ def register_kernel_replacements_and_fusions( "register_kernel_mapping", "register_kernel_mapping_transformers", "register_kernel_replacements_and_fusions", + "register_processing_kernel", "replace_kernel_forward_from_hub", - "use_image_kernel", + "run_processing_kernel", "use_kernel_forward_from_hub", "use_kernel_func_from_hub", "use_kernelized_func", From 147671e622f2933b59b7eeef5547cb8582548748 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 21 Aug 2026 21:19:11 +0200 Subject: [PATCH 07/26] big update for processing kernels --- src/transformers/image_processing_backends.py | 142 +++++++++- src/transformers/image_processing_base.py | 10 + src/transformers/integrations/hub_kernels.py | 92 +++--- .../glm_image/image_processing_glm_image.py | 46 +-- .../qwen2_vl/image_processing_qwen2_vl.py | 46 +-- src/transformers/video_processing_utils.py | 3 + tests/kernels/test_kernels.py | 261 +++++++++++++++++- 7 files changed, 497 insertions(+), 103 deletions(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 70213b5719da..5eb2e4068c14 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -73,7 +73,7 @@ from .integrations.hub_kernels import register_processing_kernel, run_processing_kernel else: - def register_processing_kernel(name, repo_id, version=None, revision=None): + def register_processing_kernel(name, repo_id, version=1, revision=None): return lambda adapter: adapter def run_processing_kernel(name, *args, **kwargs): @@ -103,35 +103,76 @@ def _resample_to_interpolation(resample): def _resize_normalize_target(size, crop): + """Resize target the kernel can reproduce as `(resize_size, crop_size, resize_mode)`, `None` to fall back. + + The kernel crops inside the resized image, so a crop larger than the resize target, which the default path + reaches by zero-padding, falls back. + """ + if size is None: + return None if size.shortest_edge and not size.longest_edge: - if crop is None or not (crop.height and crop.width): + if crop is None or not (crop.height and crop.width) or size.shortest_edge < max(crop.height, crop.width): return None return size.shortest_edge, (crop.height, crop.width), "shortest_edge" if size.height and size.width: - cropped = crop is not None and (crop.height, crop.width) != (size.height, size.width) - return (size.height, size.width), (crop.height, crop.width) if cropped else None, "square" + if crop is None or (crop.height, crop.width) == (size.height, size.width): + return (size.height, size.width), None, "square" + if not (crop.height and crop.width) or crop.height > size.height or crop.width > size.width: + return None + return (size.height, size.width), (crop.height, crop.width), "square" return None -@register_processing_kernel("resize_normalize", repo_id="kernels-community/kernel_image_resize", version=1) -def _resize_normalize_kernel(kernel, images, **kwargs): - if not (images and torch.cuda.is_available() and images[0].dtype == torch.uint8): +def _per_channel_stats(stats, channels): + """Normalization stats as one value per channel, `None` when they do not describe these images.""" + if isinstance(stats, (int, float)): + return [float(stats)] * channels + if stats is None or len(stats) != channels: return None + return [float(stat) for stat in stats] + + +_KERNEL_DEVICE_TYPE = "cuda" +_KERNEL_REPO = "Molbap/kernel_image_resize" +# Pinned by tag: `version=1` resolution does not find the tag of a repo outside `kernels-community`. +_KERNEL_REVISION = "v1.0.0" + + +def _kernel_channel_count(images): + """Channel count when the batch is uint8 CHW on one CUDA device, `None` when the kernel cannot run on it.""" + if not images or any(not isinstance(image, torch.Tensor) or image.ndim != 3 for image in images): + return None + reference = images[0] + if reference.device.type != _KERNEL_DEVICE_TYPE or any( + image.dtype != torch.uint8 or image.device != reference.device or image.shape[0] != reference.shape[0] + for image in images + ): + return None + return reference.shape[0] + + +@register_processing_kernel("resize_normalize", repo_id=_KERNEL_REPO, version=None, revision=_KERNEL_REVISION) +def _resize_normalize_kernel(kernel, images, **kwargs): if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): return None + channels = _kernel_channel_count(images) + if channels is None: + return None + image_mean = _per_channel_stats(kwargs.get("image_mean"), channels) + image_std = _per_channel_stats(kwargs.get("image_std"), channels) interpolation = _resample_to_interpolation(kwargs.get("resample")) target = _resize_normalize_target( - kwargs["size"], kwargs.get("crop_size") if kwargs.get("do_center_crop") else None + kwargs.get("size"), kwargs.get("crop_size") if kwargs.get("do_center_crop") else None ) - if interpolation is None or target is None: + if image_mean is None or image_std is None or interpolation is None or target is None: return None resize_size, crop_size, resize_mode = target rescale_factor = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 pixel_values = kernel.resize_normalize( - list(images), + images, resize_size, - kwargs.get("image_mean"), - kwargs.get("image_std"), + image_mean, + image_std, rescale_factor=rescale_factor, resample=interpolation, antialias=True, @@ -141,6 +182,29 @@ def _resize_normalize_kernel(kernel, images, **kwargs): return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=kwargs.get("return_tensors")) +@register_processing_kernel("resize_normalize_ragged", repo_id=_KERNEL_REPO, version=None, revision=_KERNEL_REVISION) +def _resize_normalize_ragged_kernel(kernel, images, target_sizes, **kwargs): + """One launch for a batch where every image has its own output size, as dynamic-resolution VLMs need.""" + channels = _kernel_channel_count(images) + if channels is None or len(target_sizes) != len(images): + return None + image_mean = _per_channel_stats(kwargs.get("image_mean"), channels) + image_std = _per_channel_stats(kwargs.get("image_std"), channels) + interpolation = _resample_to_interpolation(kwargs.get("resample")) + if image_mean is None or image_std is None or interpolation is None: + return None + rescale_factor = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 + return kernel.resize_normalize_ragged_output( + images, + [(int(height), int(width)) for height, width in target_sizes], + image_mean, + image_std, + rescale_factor, + interpolation, + True, + ) + + @requires(backends=("torch", "torchvision")) class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" @@ -409,6 +473,60 @@ def rescale_and_normalize( return images + def resize_normalize_batch( + self, + images: list["torch.Tensor"], + target_sizes: list[tuple[int, int]], + resample: "PILImageResampling | tvF.InterpolationMode | int | None", + do_rescale: bool, + rescale_factor: float, + do_normalize: bool, + image_mean: float | list[float] | None, + image_std: float | list[float] | None, + disable_grouping: bool | None = None, + ) -> list["torch.Tensor"]: + """Resize every image to its own target size, then rescale and normalize it. + + Processors whose output size depends on the input, such as the dynamic-resolution vision language models, + compute `target_sizes` themselves and call this once for the whole batch. The default implementation groups + the batch by shape and loops, which is what those processors used to write inline. A registered kernel does + the whole batch in one launch, which is why the loop lives here instead of in each processor. + + The target of a group is read from its first image, so images that share an input shape must share a target. + That holds for a rule computed from the input size, such as `smart_resize`. + """ + if self.use_kernels: + pixel_values = run_processing_kernel( + "resize_normalize_ragged", + images, + target_sizes, + resample=resample, + do_rescale=do_rescale, + rescale_factor=rescale_factor, + image_mean=image_mean, + image_std=image_std, + ) + if pixel_values is not None: + return list(pixel_values) + + grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) + target_per_group = {} + for image_index, (group_key, _) in grouped_images_index.items(): + if isinstance(image_index, int): + target_per_group.setdefault(group_key, target_sizes[image_index]) + processed_images_grouped = {} + for shape, stacked_images in grouped_images.items(): + target_height, target_width = target_per_group[shape] + stacked_images = self.resize( + image=stacked_images, + size=SizeDict(height=int(target_height), width=int(target_width)), + resample=resample, + ) + processed_images_grouped[shape] = self.rescale_and_normalize( + stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std + ) + return reorder_images(processed_images_grouped, grouped_images_index) + def center_crop( self, image: "torch.Tensor", diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index da86f0df61bf..adcf9166c3a5 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 preprocessing ops with Hub kernels when one is registered for them, and to fall + back to the default implementation otherwise. Requires the torchvision backend and an accelerator. + 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 @@ -371,6 +376,11 @@ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs): image_processor = cls(**image_processor_dict) if use_kernels is not None: image_processor.use_kernels = use_kernels + if use_kernels and getattr(image_processor, "backend", None) == "pil": + logger.warning_once( + f"`use_kernels=True` has no effect on {cls.__name__}: processing kernels run on the torchvision " + "backend. Load the processor with `backend='torchvision'` to use them." + ) # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) extra_keys = [] diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index e09a38f59d92..b7654b4461bb 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -327,50 +327,9 @@ def register_kernel_mapping_transformers(mapping=None): mapping = _KERNEL_MAPPING register_kernel_mapping(mapping) - _processing_kernels: dict[str, dict] = {} - - def register_processing_kernel(name, repo_id, version=None, revision=None): - def register(adapter): - _processing_kernels[name] = { - "adapter": adapter, - "repo_id": repo_id, - "version": version, - "revision": revision, - "module": None, - "loaded": False, - } - return adapter - - return register - - def run_processing_kernel(name, *args, **kwargs): - entry = _processing_kernels.get(name) - if not _kernels_enabled or entry is None or entry["adapter"] is None: - return None - if not entry["loaded"]: - entry["loaded"] = True - version, revision = entry["version"], entry["revision"] - if version is None and revision is None: - version = 1 - try: - entry["module"] = get_kernel( - entry["repo_id"], revision=revision, version=version, allow_all_kernels=ALLOW_ALL_KERNELS - ) - except Exception as error: - logger.warning_once(f"could not load processing kernel '{name}' from {entry['repo_id']}: {error}") - if entry["module"] is None: - return None - return entry["adapter"](entry["module"], *args, **kwargs) - else: _kernels_enabled = False - def register_processing_kernel(name, repo_id, version=None, revision=None): - return lambda adapter: adapter - - def run_processing_kernel(name, *args, **kwargs): - return None - # Stub to make decorators int transformers work when `kernels` # is not installed. def use_kernel_forward_from_hub(*args, **kwargs): @@ -510,15 +469,23 @@ def load_and_register_attn_kernel( def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _KERNEL_MODULE_MAPPING): - if kernel_name in mapping and isinstance(mapping[kernel_name], ModuleType): + if kernel_name in mapping: + # A cached `None` means the load already failed once; do not hit the Hub again on every call. return mapping[kernel_name] if kernel_name not in _HUB_KERNEL_MAPPING: logger.warning_once(f"Kernel {kernel_name} not found in _HUB_KERNEL_MAPPING") mapping[kernel_name] = None return None + repo_id = _HUB_KERNEL_MAPPING[kernel_name]["repo_id"] + if not ALLOW_ALL_KERNELS and not repo_id.startswith("kernels-community/"): + # Not cached: the answer changes inside `allow_all_hub_kernels()`. + logger.warning_once( + f"Kernel {kernel_name} is hosted in {repo_id}, outside `kernels-community`, so its code is not run by " + "default. Wrap the call in `transformers.integrations.hub_kernels.allow_all_hub_kernels()` to trust it." + ) + return None if is_kernels_available(): try: - repo_id = _HUB_KERNEL_MAPPING[kernel_name]["repo_id"] revision = _HUB_KERNEL_MAPPING[kernel_name].get("revision", None) version = _HUB_KERNEL_MAPPING[kernel_name].get("version", None) # Default version as it's mandatory @@ -527,12 +494,10 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _ kernel = get_kernel(repo_id, revision=revision, version=version, allow_all_kernels=ALLOW_ALL_KERNELS) mapping[kernel_name] = kernel - except FileNotFoundError as e: - mapping[kernel_name] = None - logger.warning_once(f"Failed to load kernel {kernel_name}: {e}") - except AssertionError: - # Happens when torch is built without an accelerator backend; fall back to slow path. + except Exception as error: + # Missing repo, no network, or torch built without an accelerator backend; fall back to slow path. mapping[kernel_name] = None + logger.warning_once(f"Failed to load kernel {kernel_name}: {error}") else: # Try to import is_{kernel_name}_available from ..utils @@ -561,6 +526,37 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _ return mapping[kernel_name] +_PROCESSING_KERNEL_ADAPTERS: dict[str, Callable] = {} + + +def register_processing_kernel(name: str, repo_id: str, version: int | str = 1, revision: str | None = None): + """ + Register a Hub kernel as an implementation of the processing op `name`, e.g. a processor's resize. + + Processing ops have no common signature to swap, so the decorated function is an adapter: it receives the loaded + kernel module followed by the arguments of the op, and returns the kernel result, or `None` when the kernel + cannot handle these arguments so that the caller keeps its default implementation. + """ + _HUB_KERNEL_MAPPING[name] = {"repo_id": repo_id, "version": version, "revision": revision} + + def register(adapter: Callable) -> Callable: + _PROCESSING_KERNEL_ADAPTERS[name] = adapter + return adapter + + return register + + +def run_processing_kernel(name: str, *args, **kwargs): + """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" + adapter = _PROCESSING_KERNEL_ADAPTERS.get(name) + if adapter is None or not _kernels_enabled or not is_torch_available() or not torch.cuda.is_available(): + return None + kernel = lazy_load_kernel(name) + if kernel is None: + return None + return adapter(kernel, *args, **kwargs) + + def kernelize(model: "PreTrainedModel", mode: "Mode | None" = None): """Temporarily register hidden kernel wrappers so `kernelize` can discover and replace them.""" if not is_kernels_available(): 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 bda2cd81b3d0..a4be8c7f363a 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -169,34 +169,38 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) - resized_images_grouped = {} - for shape, stacked_images in grouped_images.items(): - height, width = stacked_images.shape[-2:] - if do_resize: - resized_height, resized_width = smart_resize( - height, - width, + if do_resize: + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], factor=patch_size * merge_size, min_pixels=size.shortest_edge, max_pixels=size.longest_edge, ) - stacked_images = self.resize( - image=stacked_images, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) - resized_images_grouped[shape] = stacked_images - resized_images = reorder_images(resized_images_grouped, grouped_images_index) + for image in images + ] + else: + target_sizes = [(image.shape[-2], image.shape[-1]) for image in images] + normalized_images = self.resize_normalize_batch( + images, + target_sizes, + resample, + do_rescale, + rescale_factor, + do_normalize, + image_mean, + image_std, + disable_grouping=disable_grouping, + ) - grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) + grouped_images, grouped_images_index = group_images_by_shape( + normalized_images, disable_grouping=disable_grouping + ) processed_images_grouped = {} processed_grids = {} - for shape, stacked_images in grouped_images.items(): - resized_height, resized_width = stacked_images.shape[-2:] - patches = self.rescale_and_normalize( - stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std - ) + for shape, patches in grouped_images.items(): + resized_height, resized_width = patches.shape[-2:] batch_size, channel = patches.shape[:2] grid_h, grid_w = resized_height // patch_size, resized_width // patch_size patches = patches.reshape( 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 57c7935e0250..3e8036de4108 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -163,34 +163,38 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) - resized_images_grouped = {} - for shape, stacked_images in grouped_images.items(): - height, width = stacked_images.shape[-2:] - if do_resize: - resized_height, resized_width = smart_resize( - height, - width, + if do_resize: + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], factor=patch_size * merge_size, min_pixels=size.shortest_edge, max_pixels=size.longest_edge, ) - stacked_images = self.resize( - image=stacked_images, - size=SizeDict(height=resized_height, width=resized_width), - resample=resample, - ) - resized_images_grouped[shape] = stacked_images - resized_images = reorder_images(resized_images_grouped, grouped_images_index) + for image in images + ] + else: + target_sizes = [(image.shape[-2], image.shape[-1]) for image in images] + normalized_images = self.resize_normalize_batch( + images, + target_sizes, + resample, + do_rescale, + rescale_factor, + do_normalize, + image_mean, + image_std, + disable_grouping=disable_grouping, + ) - grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) + grouped_images, grouped_images_index = group_images_by_shape( + normalized_images, disable_grouping=disable_grouping + ) processed_images_grouped = {} processed_grids = {} - for shape, stacked_images in grouped_images.items(): - resized_height, resized_width = stacked_images.shape[-2:] - patches = self.rescale_and_normalize( - stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std - ) + for shape, patches in grouped_images.items(): + resized_height, resized_width = patches.shape[-2:] batch_size, channel = patches.shape[:2] grid_h, grid_w = resized_height // patch_size, resized_width // patch_size patches = patches.reshape( diff --git a/src/transformers/video_processing_utils.py b/src/transformers/video_processing_utils.py index f1bfbde680a8..e007b5fa9ac5 100644 --- a/src/transformers/video_processing_utils.py +++ b/src/transformers/video_processing_utils.py @@ -708,8 +708,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) video_processor_dict.update({k: v for k, v in kwargs.items() if k in cls.valid_kwargs.__annotations__}) video_processor = cls(**video_processor_dict) + if use_kernels is not None: + video_processor.use_kernels = use_kernels # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) extra_keys = [] diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index b330b1d9e9db..f4c2048b99f8 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -23,13 +23,17 @@ import torch -from transformers import AutoModelForCausalLM, AutoTokenizer, KernelConfig +from transformers import AutoModelForCausalLM, AutoTokenizer, KernelConfig, ViTImageProcessor +from transformers.image_processing_backends import _resize_normalize_kernel, _resize_normalize_ragged_kernel +from transformers.image_utils import PILImageResampling, SizeDict from transformers.integrations.hub_kernels import ( _HUB_KERNEL_MAPPING, _KERNEL_MODULE_MAPPING, + _PROCESSING_KERNEL_ADAPTERS, is_kernel, lazy_load_kernel, load_and_register_attn_kernel, + run_processing_kernel, ) from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS @@ -39,6 +43,7 @@ cleanup, require_kernels, require_torch_accelerator, + require_torch_gpu, slow, torch_device, ) @@ -686,3 +691,257 @@ def test_single_device_mapping_still_works(self): result_mapping = kernel_config.kernel_mapping self.assertIn("RMSNorm", result_mapping, "RMSNorm should be in mapping") + + +class RecordingKernel: + """Stand-in for a loaded kernel module: records the call and returns a fixed output.""" + + def __init__(self, output=None): + self.output = output + self.calls = [] + + def resize_normalize(self, images, size, image_mean, image_std, **kwargs): + self.calls.append({"images": images, "size": size, "image_mean": image_mean, "image_std": image_std, **kwargs}) + return self.output + + +class TestProcessingKernels(TestCasePlus): + """Dispatch and gating of processing kernels. Runs on CPU, `kernels` is not needed.""" + + def setUp(self): + super().setUp() + self.images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] + self.kwargs = { + "do_resize": True, + "size": SizeDict(height=8, width=8), + "resample": PILImageResampling.BICUBIC, + "do_rescale": True, + "rescale_factor": 1 / 255, + "do_normalize": True, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + + def run_adapter(self, output=None, images=None, **overrides): + kernel = RecordingKernel(output=output) + images = self.images if images is None else images + # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + result = _resize_normalize_kernel(kernel, images, **{**self.kwargs, **overrides}) + return kernel, result + + def test_registration_records_repo_and_adapter(self): + self.assertIs(_PROCESSING_KERNEL_ADAPTERS["resize_normalize"], _resize_normalize_kernel) + self.assertIs(_PROCESSING_KERNEL_ADAPTERS["resize_normalize_ragged"], _resize_normalize_ragged_kernel) + for name in ("resize_normalize", "resize_normalize_ragged"): + self.assertEqual(_HUB_KERNEL_MAPPING[name]["repo_id"], "Molbap/kernel_image_resize") + self.assertEqual(_HUB_KERNEL_MAPPING[name]["revision"], "v1.0.0") + + def test_kernel_outside_kernels_community_is_not_trusted_by_default(self): + mapping = {} + with patch.dict(_HUB_KERNEL_MAPPING, {"private_op": {"repo_id": "someone/private-kernel", "version": 1}}): + self.assertIsNone(lazy_load_kernel("private_op", mapping)) + # Not cached: the answer changes inside `allow_all_hub_kernels()`, so it must be asked again. + self.assertEqual(mapping, {}) + sentinel = types.ModuleType("trusted_kernel_module") + with ( + patch("transformers.integrations.hub_kernels.ALLOW_ALL_KERNELS", True), + patch("transformers.integrations.hub_kernels.is_kernels_available", return_value=True), + patch("transformers.integrations.hub_kernels.get_kernel", return_value=sentinel), + ): + self.assertIs(lazy_load_kernel("private_op", mapping), sentinel) + + def test_ragged_adapter_translates_per_image_targets(self): + kernel = MagicMock() + kernel.resize_normalize_ragged_output.return_value = [torch.zeros(3, 8, 8), torch.zeros(3, 4, 4)] + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + result = _resize_normalize_ragged_kernel( + kernel, + self.images, + [(8, 8), (4, 4)], + **{key: self.kwargs[key] for key in self.kwargs if key != "size"}, + ) + self.assertEqual(len(result), 2) + arguments = kernel.resize_normalize_ragged_output.call_args[0] + self.assertEqual(arguments[1], [(8, 8), (4, 4)]) + self.assertEqual(arguments[2], [0.5, 0.5, 0.5]) + self.assertEqual(arguments[4], 1 / 255) + self.assertEqual(arguments[5], "bicubic") + + def test_ragged_adapter_falls_back(self): + kernel = MagicMock() + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + # One target per image is required, and the images must be uint8 CHW on one device. + self.assertIsNone(_resize_normalize_ragged_kernel(kernel, self.images, [(8, 8)], **self.kwargs)) + self.assertIsNone( + _resize_normalize_ragged_kernel( + kernel, [image.float() for image in self.images], [(8, 8), (4, 4)], **self.kwargs + ) + ) + self.assertIsNone(_resize_normalize_ragged_kernel(kernel, self.images, [(8, 8), (4, 4)], **self.kwargs)) + kernel.resize_normalize_ragged_output.assert_not_called() + + def test_run_processing_kernel_calls_adapter(self): + sentinel = types.ModuleType("sentinel_kernel_module") + with ( + patch.object(torch.cuda, "is_available", return_value=True), + patch.dict( + run_processing_kernel.__globals__, + { + "_kernels_enabled": True, + "_PROCESSING_KERNEL_ADAPTERS": {"dummy_op": lambda kernel, value: (kernel, value)}, + "lazy_load_kernel": lambda name: sentinel, + }, + ), + ): + self.assertEqual(run_processing_kernel("dummy_op", 3), (sentinel, 3)) + + def test_run_processing_kernel_falls_back(self): + with patch.object(torch.cuda, "is_available", return_value=True): + # Unknown op, `USE_HUB_KERNELS=0`, and a kernel that cannot be loaded all keep the default path. + self.assertIsNone(run_processing_kernel("not_a_registered_op")) + with patch.dict(run_processing_kernel.__globals__, {"_kernels_enabled": False}): + self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) + with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": lambda name: None}): + self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) + + def test_run_processing_kernel_needs_accelerator(self): + with patch.object(torch.cuda, "is_available", return_value=False): + with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": self.fail}): + self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) + + def test_adapter_translates_square_resize(self): + kernel, result = self.run_adapter(output=torch.zeros(2, 3, 8, 8)) + self.assertEqual(len(kernel.calls), 1) + call = kernel.calls[0] + self.assertEqual(call["size"], (8, 8)) + self.assertIsNone(call["crop_size"]) + self.assertEqual(call["resize_mode"], "square") + self.assertEqual(call["resample"], "bicubic") + self.assertEqual(call["rescale_factor"], 1 / 255) + self.assertEqual(call["image_mean"], [0.5, 0.5, 0.5]) + # Same output shape as the default path: a list of images, stacked only when tensors are requested. + self.assertEqual([image.shape for image in result["pixel_values"]], [(3, 8, 8)] * 2) + _, stacked = self.run_adapter(output=torch.zeros(2, 3, 8, 8), return_tensors="pt") + self.assertEqual(stacked["pixel_values"].shape, (2, 3, 8, 8)) + + def test_adapter_translates_shortest_edge_resize_with_crop(self): + kernel, _ = self.run_adapter( + output=torch.zeros(2, 3, 6, 6), + size=SizeDict(shortest_edge=8), + do_center_crop=True, + crop_size=SizeDict(height=6, width=6), + ) + call = kernel.calls[0] + self.assertEqual(call["size"], 8) + self.assertEqual(call["crop_size"], (6, 6)) + self.assertEqual(call["resize_mode"], "shortest_edge") + + def test_adapter_scalar_normalization_stats(self): + kernel, _ = self.run_adapter(output=torch.zeros(2, 3, 8, 8), image_mean=0.5, image_std=0.5) + self.assertEqual(kernel.calls[0]["image_mean"], [0.5, 0.5, 0.5]) + + def test_adapter_skips_rescale(self): + kernel, _ = self.run_adapter(output=torch.zeros(2, 3, 8, 8), do_rescale=False) + self.assertEqual(kernel.calls[0]["rescale_factor"], 1.0) + + def test_adapter_falls_back_on_unsupported_arguments(self): + unsupported = { + "padding": {"do_pad": True, "pad_size": SizeDict(height=8, width=8)}, + "no_resize": {"do_resize": False}, + "no_normalize": {"do_normalize": False}, + "lanczos": {"resample": PILImageResampling.LANCZOS}, + "bounded_resize": {"size": SizeDict(max_height=8, max_width=8)}, + "crop_without_size": {"do_center_crop": True, "crop_size": SizeDict()}, + "crop_larger_than_resize": {"do_center_crop": True, "crop_size": SizeDict(height=12, width=12)}, + "shortest_edge_below_crop": { + "size": SizeDict(shortest_edge=4), + "do_center_crop": True, + "crop_size": SizeDict(height=6, width=6), + }, + "shortest_edge_without_crop": {"size": SizeDict(shortest_edge=8)}, + "stats_per_channel_mismatch": {"image_mean": [0.5, 0.5], "image_std": [0.5, 0.5]}, + } + for name, overrides in unsupported.items(): + with self.subTest(name): + kernel, result = self.run_adapter(**overrides) + self.assertIsNone(result) + self.assertEqual(kernel.calls, []) + + def test_adapter_falls_back_on_unsupported_images(self): + for name, images in { + "empty": [], + "float": [image.float() for image in self.images], + "batched": [image.unsqueeze(0) for image in self.images], + "mixed_channels": [self.images[0], self.images[1][:1]], + "nested": [[image] for image in self.images], + }.items(): + with self.subTest(name): + kernel, result = self.run_adapter(images=images) + self.assertIsNone(result) + self.assertEqual(kernel.calls, []) + + def test_adapter_falls_back_on_images_the_kernel_cannot_reach(self): + # Images stay on CPU unless the caller passes `device`, and the kernel runs where the images are. + kernel = RecordingKernel() + self.assertIsNone(_resize_normalize_kernel(kernel, self.images, **self.kwargs)) + self.assertEqual(kernel.calls, []) + + def test_resize_normalize_batch_matches_with_and_without_grouping(self): + processor = ViTImageProcessor() + images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] + [ + torch.randint(0, 255, (3, 30, 30), dtype=torch.uint8) + ] + targets = [(8, 12), (8, 12), (6, 6)] + arguments = (targets, PILImageResampling.BICUBIC, True, 1 / 255, True, (0.5,) * 3, (0.5,) * 3) + grouped = processor.resize_normalize_batch(images, *arguments, disable_grouping=False) + ungrouped = processor.resize_normalize_batch(images, *arguments, disable_grouping=True) + self.assertEqual([tuple(image.shape) for image in grouped], [(3, 8, 12), (3, 8, 12), (3, 6, 6)]) + for one, other in zip(grouped, ungrouped): + torch.testing.assert_close(one, other) + + def test_use_kernels_is_a_runtime_flag(self): + processor = ViTImageProcessor(use_kernels=True) + self.assertNotIn("use_kernels", processor.to_dict()) + with tempfile.TemporaryDirectory() as tmp_dir: + processor.save_pretrained(tmp_dir) + self.assertFalse(ViTImageProcessor.from_pretrained(tmp_dir).use_kernels) + self.assertTrue(ViTImageProcessor.from_pretrained(tmp_dir, use_kernels=True).use_kernels) + + def test_default_path_is_unchanged_when_the_kernel_cannot_run(self): + images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8)] + with patch.object(torch.cuda, "is_available", return_value=False): + with_kernels = ViTImageProcessor(use_kernels=True)(images, return_tensors="pt") + without_kernels = ViTImageProcessor(use_kernels=False)(images, return_tensors="pt") + torch.testing.assert_close(with_kernels["pixel_values"], without_kernels["pixel_values"]) + + +@require_kernels +@require_torch_gpu +@slow +class TestResizeNormalizeKernel(TestCasePlus): + """Parity of the resize + normalize kernel against the torchvision path. Needs the kernel repo to be published.""" + + def test_matches_default_path(self): + if lazy_load_kernel("resize_normalize") is None: + self.skipTest("kernel repo of `resize_normalize` is not available") + images = [ + torch.randint(0, 255, (3, height, width), dtype=torch.uint8, device=torch_device) + for height, width in [(480, 640), (300, 300), (1024, 768)] + ] + kernel_outputs = [] + + def recording_adapter(*args, **kwargs): + kernel_outputs.append(_resize_normalize_kernel(*args, **kwargs)) + return kernel_outputs[-1] + + with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {"resize_normalize": recording_adapter}): + with_kernels = ViTImageProcessor(use_kernels=True)(images, return_tensors="pt")["pixel_values"] + # Without this the test would compare the default path against itself and pass on a silent fallback. + self.assertTrue( + kernel_outputs and kernel_outputs[0] is not None, "the adapter fell back, the kernel never ran" + ) + without_kernels = ViTImageProcessor(use_kernels=False)(images, return_tensors="pt")["pixel_values"] + self.assertEqual(with_kernels.shape, without_kernels.shape) + # The kernel resizes in float where the default path resizes in uint8, so single pixels differ. + self.assertLess((with_kernels - without_kernels).abs().mean().item(), 0.02) From 5f4a1ca7449121aebab038aa72642ca69c2cdf5a Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 21 Aug 2026 21:19:33 +0200 Subject: [PATCH 08/26] update doc --- docs/source/en/kernel_doc/loading_kernels.md | 41 +++++++++++++++++--- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 4ba3a55cbc81..b3f33076b263 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -230,8 +230,8 @@ Currently kernelized: the fast image processors' resize + normalize. The kernel ```py from transformers import AutoImageProcessor -processor = AutoImageProcessor.from_pretrained("google/siglip2-base-patch16-224", use_kernels=True) -pixel_values = processor(images, return_tensors="pt")["pixel_values"] +processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224", use_kernels=True) +pixel_values = processor(images, return_tensors="pt", device="cuda")["pixel_values"] ``` For vision-language models the image processor is wrapped in a processor, so the flag passes through [`AutoProcessor`] to the inner image processor. @@ -239,14 +239,45 @@ For vision-language models the image processor is wrapped in a processor, so the ```py from transformers import AutoProcessor -processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it", use_kernels=True) -inputs = processor(text=prompt, images=images, return_tensors="pt") +processor = AutoProcessor.from_pretrained("facebook/chameleon-7b", use_kernels=True) +inputs = processor(text=prompt, images=images, return_tensors="pt", device="cuda") ``` -This is opt-in and CUDA only. It falls back to torchvision when the kernel cannot run or the processor is not supported. Supported processors do a fixed-size resize, optionally with a center crop or a shortest-edge resize, followed by rescale and normalize — the classic vision encoders (ViT, DINOv2/DINOv3, SigLIP, BEiT, ...) and SigLIP-based VLMs. Padding processors and dynamic-resolution VLMs fall back. +This is opt-in and CUDA only. The kernel runs on the device the images are already on, so pass `device="cuda"` to the +processor call: images left on CPU fall back to torchvision. It also falls back when the kernel cannot run or the +arguments are not supported. + +Two ops are registered today. + +`resize_normalize` handles a fixed-size resize, optionally with a center crop or a shortest-edge resize, followed by +rescale and normalize. It is called from `TorchvisionBackend._preprocess`, so it reaches the processors that use that +method as written: ViT, CLIP, SigLIP, DeiT, Levit, Blip, Chameleon, Chinese-CLIP, MobileNetV1, OwlViT, Pvt, PI0, +PPChart2Table, and Bit, which is what DINOv2 loads. A processor that defines its own `_preprocess` does not reach it, +which covers most vision language models, every tiling processor, and the detection and segmentation processors. + +`resize_normalize_ragged` handles a batch where every image has its own output size. It is called from +`TorchvisionBackend.resize_normalize_batch`, the primitive a dynamic-resolution processor calls once for the whole +batch after it has computed the target sizes itself. Qwen2-VL uses it. The kernel resizes in float, so outputs are parity-close to torchvision (around `1e-4` against the float reference) but not byte-identical to the legacy uint8 resize path. Use the default backend if you need exact reproduction of the original processor. +### Registering a processing kernel + +Processing ops have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an op name to a Hub repository, and the decorated adapter receives the loaded kernel module followed by the arguments of the op. Return `None` for arguments the kernel cannot reproduce, and the caller keeps its default implementation. + +```py +from transformers.integrations.hub_kernels import register_processing_kernel + + +@register_processing_kernel("my_op", repo_id="my-org/my-processing-kernel", version=1) +def my_op_kernel(kernel, images, **kwargs): + if kwargs.get("do_pad"): # the kernel does not pad, keep the default path + return None + return kernel.my_op(images, **kwargs) +``` + +The processor calls `run_processing_kernel("my_op", images, **kwargs)` and uses its default implementation when the result is `None`, which happens when the kernel is disabled, unavailable, or declined by the adapter. The kernel is downloaded on the first call that reaches it, and only on an accelerator. + ## Troubleshooting Kernel integration depends on hardware, drivers, and package versions working together. The following sections cover common failures. From ba561cab1912b70923e8ebfcae6935c8daf341de Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 24 Sep 2026 16:26:25 +0200 Subject: [PATCH 09/26] massive upgrade with SAM2 kernels and better patchify --- docs/source/en/kernel_doc/loading_kernels.md | 49 +- src/transformers/image_processing_backends.py | 226 +++------ src/transformers/image_processing_base.py | 9 +- .../image_processing_cohere_compass.py | 59 +++ .../video_processing_cohere_compass.py | 59 ++- .../image_processing_ernie4_5_vl_moe.py | 59 +++ .../glm_image/image_processing_glm_image.py | 59 +++ .../hunyuan_vl/image_processing_hunyuan_vl.py | 25 + .../models/hunyuan_vl/modular_hunyuan_vl.py | 4 + .../image_processing_minimax_m3_vl.py | 59 +++ .../qwen2_vl/image_processing_qwen2_vl.py | 98 +++- .../qwen2_vl/video_processing_qwen2_vl.py | 64 ++- .../models/qwen3_vl/modular_qwen3_vl.py | 31 +- .../qwen3_vl/video_processing_qwen3_vl.py | 59 ++- .../models/sam2/image_processing_sam2.py | 26 +- src/transformers/models/sam2/modular_sam2.py | 21 +- .../models/sam3/image_processing_sam3.py | 26 +- .../image_processing_video_llama_3.py | 38 ++ .../video_processing_video_llama_3.py | 14 + tests/kernels/test_kernels.py | 456 +++++++++++------- 20 files changed, 990 insertions(+), 451 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index e75e0308e9e1..30db4603939c 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -320,60 +320,41 @@ export USE_HUB_KERNELS=0 # or OFF or NO ## Processor kernels -Preprocessing and postprocessing ops can be offloaded to Hub kernels the same way model layers are. `use_kernels=True` swaps a processor op for a registered Hub kernel and falls back to the default implementation when none applies — so custom, hot, or hard-to-vectorize ops (resize, normalize, patchify, NMS, mask decoding, ...) can move onto the GPU without rewriting the processor or the call site. +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. The flag is not saved with the processor configuration. -Currently kernelized: the fast image processors' resize + normalize. The kernel batches the resize over a ragged set of images and folds rescale and normalize into the same pass. - -```py -from transformers import AutoImageProcessor - -processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224", use_kernels=True) -pixel_values = processor(images, return_tensors="pt", device="cuda")["pixel_values"] -``` - -For vision-language models the image processor is wrapped in a processor, so the flag passes through [`AutoProcessor`] to the inner image processor. +| 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 (Cohere Compass, ERNIE 4.5 VL, GLM-Image, MiniMax-M3-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`) | ```py from transformers import AutoProcessor -processor = AutoProcessor.from_pretrained("facebook/chameleon-7b", use_kernels=True) +processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True) inputs = processor(text=prompt, images=images, return_tensors="pt", device="cuda") ``` -This is opt-in and CUDA only. The kernel runs on the device the images are already on, so pass `device="cuda"` to the -processor call: images left on CPU fall back to torchvision. It also falls back when the kernel cannot run or the -arguments are not supported. - -Two ops are registered today. - -`resize_normalize` handles a fixed-size resize, optionally with a center crop or a shortest-edge resize, followed by -rescale and normalize. It is called from `TorchvisionBackend._preprocess`, so it reaches the processors that use that -method as written: ViT, CLIP, SigLIP, DeiT, Levit, Blip, Chameleon, Chinese-CLIP, MobileNetV1, OwlViT, Pvt, PI0, -PPChart2Table, and Bit, which is what DINOv2 loads. A processor that defines its own `_preprocess` does not reach it, -which covers most vision language models, every tiling processor, and the detection and segmentation processors. - -`resize_normalize_ragged` handles a batch where every image has its own output size. It is called from -`TorchvisionBackend.resize_normalize_batch`, the primitive a dynamic-resolution processor calls once for the whole -batch after it has computed the target sizes itself. Qwen2-VL uses it. +For vision-language models the flag passes through [`AutoProcessor`] to the image and video processors. Kernels run on the device the inputs are already on, so pass `device="cuda"` to the processor call. The processor uses its default implementation when there is no CUDA device, when the kernel fails to load, when the inputs are on CPU, or when the kernel does not support the requested arguments. -The kernel resizes in float, so outputs are parity-close to torchvision (around `1e-4` against the float reference) but not byte-identical to the legacy uint8 resize path. Use the default backend if you need exact reproduction of the original processor. +The resize kernels round to `uint8` after each pass, like the default torchvision path, so outputs differ from it by at most one `uint8` level on natural images. ### Registering a processing kernel -Processing ops have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an op name to a Hub repository, and the decorated adapter receives the loaded kernel module followed by the arguments of the op. Return `None` for arguments the kernel cannot reproduce, and the caller keeps its default implementation. +Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an operation name to a Hub repository, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. ```py from transformers.integrations.hub_kernels import register_processing_kernel -@register_processing_kernel("my_op", repo_id="my-org/my-processing-kernel", version=1) -def my_op_kernel(kernel, images, **kwargs): - if kwargs.get("do_pad"): # the kernel does not pad, keep the default path +@register_processing_kernel("my_op", repo_id="kernels-community/my-processing-kernel", version=1) +def my_op_kernel(kernel, images): + if images[0].device.type != "cuda": return None - return kernel.my_op(images, **kwargs) + return kernel.my_op(images) ``` -The processor calls `run_processing_kernel("my_op", images, **kwargs)` and uses its default implementation when the result is `None`, which happens when the kernel is disabled, unavailable, or declined by the adapter. The kernel is downloaded on the first call that reaches it, and only on an accelerator. +The processor calls `run_processing_kernel("my_op", images)` and uses its default implementation when the result is `None`. The kernel is downloaded on the first call that reaches it, and only when a CUDA device is available. ## Troubleshooting diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 270eb2802ce1..693cffc08e74 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -92,116 +92,107 @@ def run_processing_kernel(name, *args, **kwargs): logger = logging.get_logger(__name__) -def _resample_to_interpolation(resample): - if resample is None: - return None - try: - return {2: "bilinear", 3: "bicubic"}.get(int(resample)) - except (TypeError, ValueError): - name = getattr(resample, "name", str(resample)).upper() - return "bicubic" if "BICUBIC" in name else "bilinear" if "BILINEAR" in name else None - - -def _resize_normalize_target(size, crop): - """Resize target the kernel can reproduce as `(resize_size, crop_size, resize_mode)`, `None` to fall back. - - The kernel crops inside the resized image, so a crop larger than the resize target, which the default path - reaches by zero-padding, falls back. - """ - if size is None: - return None - if size.shortest_edge and not size.longest_edge: - if crop is None or not (crop.height and crop.width) or size.shortest_edge < max(crop.height, crop.width): - return None - return size.shortest_edge, (crop.height, crop.width), "shortest_edge" - if size.height and size.width: - if crop is None or (crop.height, crop.width) == (size.height, size.width): - return (size.height, size.width), None, "square" - if not (crop.height and crop.width) or crop.height > size.height or crop.width > size.width: - return None - return (size.height, size.width), (crop.height, crop.width), "square" - return None +_KERNEL_DEVICE_TYPE = "cuda" -def _per_channel_stats(stats, channels): - """Normalization stats as one value per channel, `None` when they do not describe these images.""" - if isinstance(stats, (int, float)): - return [float(stats)] * channels - if stats is None or len(stats) != channels: +@register_processing_kernel("connected_component_areas", repo_id="kernels-community/cv-utils", version=1) +def _connected_component_areas_kernel(kernel, regions): + """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" + if regions.device.type != _KERNEL_DEVICE_TYPE: return None - return [float(stat) for stat in stats] + height, width = regions.shape[-2:] + padded_regions = torch.nn.functional.pad(regions.to(torch.uint8), (0, width % 2, 0, height % 2)) + _, areas = kernel.cc_2d(padded_regions.contiguous(), get_counts=True) + return areas[..., :height, :width] -_KERNEL_DEVICE_TYPE = "cuda" -_KERNEL_REPO = "Molbap/kernel_image_resize" -# Pinned by tag: `version=1` resolution does not find the tag of a repo outside `kernels-community`. -_KERNEL_REVISION = "v1.0.0" +_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} -def _kernel_channel_count(images): - """Channel count when the batch is uint8 CHW on one CUDA device, `None` when the kernel cannot run on it.""" - if not images or any(not isinstance(image, torch.Tensor) or image.ndim != 3 for image in images): - return None - reference = images[0] - if reference.device.type != _KERNEL_DEVICE_TYPE or any( - image.dtype != torch.uint8 or image.device != reference.device or image.shape[0] != reference.shape[0] +def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std): + """Interpolation and per-channel stats for the resize kernels, `None` when they cannot process these inputs.""" + if not images or any( + not isinstance(image, torch.Tensor) + or image.ndim != 3 + or image.dtype != torch.uint8 + or image.device != images[0].device + or image.shape[0] != images[0].shape[0] for image in images ): return None - return reference.shape[0] + interpolation = _KERNEL_INTERPOLATIONS.get(resample) + channels = images[0].shape[0] + image_mean = [image_mean] * channels if isinstance(image_mean, (int, float)) else list(image_mean) + image_std = [image_std] * channels if isinstance(image_std, (int, float)) else list(image_std) + if images[0].device.type != _KERNEL_DEVICE_TYPE or interpolation is None or len(image_mean) != channels: + return None + return interpolation, image_mean, image_std, rescale_factor -@register_processing_kernel("resize_normalize", repo_id=_KERNEL_REPO, version=None, revision=_KERNEL_REVISION) -def _resize_normalize_kernel(kernel, images, **kwargs): - if kwargs.get("do_pad") or not (kwargs.get("do_resize") and kwargs.get("do_normalize")): +@register_processing_kernel("resize_normalize", repo_id="kernels-community/cv-utils", version=1) +def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): + """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" + arguments = _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std) + if arguments is None: return None - channels = _kernel_channel_count(images) - if channels is None: + interpolation, image_mean, image_std, rescale_factor = arguments + crop = (crop_size.height, crop_size.width) if crop_size is not None else None + if crop is not None and not all(crop): return None - image_mean = _per_channel_stats(kwargs.get("image_mean"), channels) - image_std = _per_channel_stats(kwargs.get("image_std"), channels) - interpolation = _resample_to_interpolation(kwargs.get("resample")) - target = _resize_normalize_target( - kwargs.get("size"), kwargs.get("crop_size") if kwargs.get("do_center_crop") else None - ) - if image_mean is None or image_std is None or interpolation is None or target is None: + if size.height and size.width: + if crop is not None and (crop[0] > size.height or crop[1] > size.width): + return None + resize, resize_mode = (size.height, size.width), "square" + elif size.shortest_edge and not size.longest_edge and crop is not None and size.shortest_edge >= max(crop): + resize, resize_mode = size.shortest_edge, "shortest_edge" + else: return None - resize_size, crop_size, resize_mode = target - rescale_factor = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 - pixel_values = kernel.resize_normalize( + return kernel.resize_normalize( images, - resize_size, + resize, image_mean, image_std, rescale_factor=rescale_factor, resample=interpolation, antialias=True, - crop_size=crop_size, + crop_size=crop, resize_mode=resize_mode, + round_to_uint8=True, ) - return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=kwargs.get("return_tensors")) -@register_processing_kernel("resize_normalize_ragged", repo_id=_KERNEL_REPO, version=None, revision=_KERNEL_REVISION) -def _resize_normalize_ragged_kernel(kernel, images, target_sizes, **kwargs): - """One launch for a batch where every image has its own output size, as dynamic-resolution VLMs need.""" - channels = _kernel_channel_count(images) - if channels is None or len(target_sizes) != len(images): - return None - image_mean = _per_channel_stats(kwargs.get("image_mean"), channels) - image_std = _per_channel_stats(kwargs.get("image_std"), channels) - interpolation = _resample_to_interpolation(kwargs.get("resample")) - if image_mean is None or image_std is None or interpolation is None: +@register_processing_kernel("resize_normalize_patchify", repo_id="kernels-community/cv-utils", version=1) +def _resize_normalize_patchify_kernel( + kernel, + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, +): + """Resize every frame to its target size, normalize, and write the flattened patches of every item in order.""" + arguments = _resize_kernel_arguments(frames, resample, rescale_factor, image_mean, image_std) + if arguments is None: return None - rescale_factor = float(kwargs["rescale_factor"]) if kwargs.get("do_rescale") else 1.0 - return kernel.resize_normalize_ragged_output( - images, - [(int(height), int(width)) for height, width in target_sizes], + interpolation, image_mean, image_std, rescale_factor = arguments + return kernel.resize_normalize_patchify( + frames, + target_sizes, + items, image_mean, image_std, rescale_factor, interpolation, True, + patch_size, + merge_size, + temporal_patch_size, + round_to_uint8=True, ) @@ -463,60 +454,6 @@ def rescale_and_normalize( return images - def resize_normalize_batch( - self, - images: list["torch.Tensor"], - target_sizes: list[tuple[int, int]], - resample: "PILImageResampling | tvF.InterpolationMode | int | None", - do_rescale: bool, - rescale_factor: float, - do_normalize: bool, - image_mean: float | list[float] | None, - image_std: float | list[float] | None, - disable_grouping: bool | None = None, - ) -> list["torch.Tensor"]: - """Resize every image to its own target size, then rescale and normalize it. - - Processors whose output size depends on the input, such as the dynamic-resolution vision language models, - compute `target_sizes` themselves and call this once for the whole batch. The default implementation groups - the batch by shape and loops, which is what those processors used to write inline. A registered kernel does - the whole batch in one launch, which is why the loop lives here instead of in each processor. - - The target of a group is read from its first image, so images that share an input shape must share a target. - That holds for a rule computed from the input size, such as `smart_resize`. - """ - if self.use_kernels: - pixel_values = run_processing_kernel( - "resize_normalize_ragged", - images, - target_sizes, - resample=resample, - do_rescale=do_rescale, - rescale_factor=rescale_factor, - image_mean=image_mean, - image_std=image_std, - ) - if pixel_values is not None: - return list(pixel_values) - - grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) - target_per_group = {} - for image_index, (group_key, _) in grouped_images_index.items(): - if isinstance(image_index, int): - target_per_group.setdefault(group_key, target_sizes[image_index]) - processed_images_grouped = {} - for shape, stacked_images in grouped_images.items(): - target_height, target_width = target_per_group[shape] - stacked_images = self.resize( - image=stacked_images, - size=SizeDict(height=int(target_height), width=int(target_width)), - resample=resample, - ) - processed_images_grouped[shape] = self.rescale_and_normalize( - stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std - ) - return reorder_images(processed_images_grouped, grouped_images_index) - def center_crop( self, image: "torch.Tensor", @@ -565,26 +502,19 @@ def _preprocess( **kwargs, ) -> BatchFeature: """Preprocess using Torchvision backend (fast, GPU-accelerated).""" - if self.use_kernels: + if self.use_kernels and do_resize and do_rescale and do_normalize and not do_pad: pixel_values = run_processing_kernel( "resize_normalize", images, - do_resize=do_resize, - size=size, - resample=resample, - do_center_crop=do_center_crop, - crop_size=crop_size, - do_rescale=do_rescale, - rescale_factor=rescale_factor, - do_normalize=do_normalize, - image_mean=image_mean, - image_std=image_std, - do_pad=do_pad, - return_tensors=return_tensors, + size, + crop_size if do_center_crop else None, + resample, + rescale_factor, + image_mean, + image_std, ) if pixel_values is not None: - return pixel_values - + return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=return_tensors) # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index 4c621f483662..7f825a8b3f98 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -139,8 +139,8 @@ def from_pretrained( 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 preprocessing ops with Hub kernels when one is registered for them, and to fall - back to the default implementation otherwise. Requires the torchvision backend and an accelerator. + Whether to run the processing ops with Hub kernels when one is registered for 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*): @@ -392,11 +392,6 @@ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs): image_processor = cls(**image_processor_dict) if use_kernels is not None: image_processor.use_kernels = use_kernels - if use_kernels and getattr(image_processor, "backend", None) == "pil": - logger.warning_once( - f"`use_kernels=True` has no effect on {cls.__name__}: processing kernels run on the torchvision " - "backend. Load the processor with `backend='torchvision'` to use them." - ) # Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal) extra_keys = [] 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 b2084bd8be29..8381dee3bb1a 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -221,6 +222,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -260,6 +282,43 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 9ecb487923a9..6e11786571be 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_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor @@ -188,15 +189,25 @@ 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, **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 + ) + 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): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" 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 @@ -204,8 +215,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, @@ -214,11 +224,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, @@ -289,6 +294,42 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False + if self.use_kernels and do_resize and do_rescale and do_normalize: + frames, target_sizes, items = [], [], [] + for video in videos: + target_size = self._resized_size( + *video.shape[-2:], + video.shape[0], + size, + patch_size * merge_size, + temporal_patch_size, + cap_pixels_per_frame, + ) + items.append(list(range(len(frames), len(frames) + video.shape[0]))) + frames.extend(video) + target_sizes.extend([target_size] * video.shape[0]) + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + if kernel_output is not None: + pixel_values_videos, video_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values_videos": pixel_values_videos, + "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} 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 268b40a226d0..1bbb1c762f82 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, logging @@ -185,6 +186,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -224,6 +246,43 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 719926106bcc..7552033a77ab 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -233,6 +234,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -272,6 +294,43 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 3a05220fc355..0287fa2d05c5 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -226,6 +226,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -265,6 +286,10 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel(self, *args, **kwargs): + """The kernel writes the Qwen2-VL patch order and resamples with `resample`, HunYuanVL needs neither.""" + return None + def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None ) -> tuple[int, int]: diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index ce34093c28b3..dfe0d3df0b7f 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -421,6 +421,10 @@ def patchify( return flatten_patches, grid_h, grid_w + def _resize_normalize_patchify_kernel(self, *args, **kwargs): + """The kernel writes the Qwen2-VL patch order and resamples with `resample`, HunYuanVL needs neither.""" + return None + def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None ) -> tuple[int, int]: 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 d281f5961dab..fb6490bfd1b8 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -225,6 +226,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -264,6 +286,43 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 1b4786568920..ebc0d07c8ba3 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -227,37 +228,47 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if do_resize: - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) + grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) + resized_images_grouped = {} + for shape, stacked_images in grouped_images.items(): + if do_resize: + stacked_images = self.resize( + images=stacked_images, + size=size, + resample=resample, factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, ) - for image in images - ] - else: - target_sizes = [(image.shape[-2], image.shape[-1]) for image in images] - normalized_images = self.resize_normalize_batch( - images, - target_sizes, - resample, - do_rescale, - rescale_factor, - do_normalize, - image_mean, - image_std, - disable_grouping=disable_grouping, - ) + resized_images_grouped[shape] = stacked_images + resized_images = reorder_images(resized_images_grouped, grouped_images_index) - grouped_images, grouped_images_index = group_images_by_shape( - normalized_images, disable_grouping=disable_grouping - ) + grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} processed_grids = {} for shape, stacked_images in grouped_images.items(): + stacked_images = self.rescale_and_normalize( + stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std + ) patches, grid_h, grid_w = self.patchify( stacked_images, patch_size=patch_size, @@ -277,6 +288,43 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 7885145f4930..21a7681bd76a 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_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor @@ -248,31 +249,28 @@ 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 + ) + 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): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" 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] total_pixels = int(self.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, @@ -343,6 +341,42 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False + if self.use_kernels and do_resize and do_rescale and do_normalize: + frames, target_sizes, items = [], [], [] + for video in videos: + target_size = self._resized_size( + *video.shape[-2:], + video.shape[0], + size, + patch_size * merge_size, + temporal_patch_size, + cap_pixels_per_frame, + ) + items.append(list(range(len(frames), len(frames) + video.shape[0]))) + frames.extend(video) + target_sizes.extend([target_size] * video.shape[0]) + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + if kernel_output is not None: + pixel_values_videos, video_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values_videos": pixel_values_videos, + "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} diff --git a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py index 0de1d215e70f..3be78089d80a 100644 --- a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py @@ -25,14 +25,14 @@ 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 BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_rope_utils import RopeParameters from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import ProcessingKwargs, Unpack, VideosKwargs -from ...utils import auto_docstring, can_return_tuple, is_torchvision_available, logging +from ...utils import auto_docstring, can_return_tuple, logging from ...utils.generic import ( merge_with_config_defaults, ) @@ -72,10 +72,6 @@ ) -if is_torchvision_available(): - from torchvision.transforms.v2 import functional as tvF - - logger = logging.get_logger(__name__) @@ -1102,21 +1098,11 @@ 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, - **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): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" 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 @@ -1124,8 +1110,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, @@ -1134,12 +1119,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 9127689db410..a4677fa9dbd3 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_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, is_torchvision_available, logging from ...video_processing_utils import BaseVideoProcessor @@ -191,15 +192,25 @@ 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, **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 + ) + 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): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" 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 @@ -207,8 +218,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, @@ -217,11 +227,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, @@ -292,6 +297,42 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False + if self.use_kernels and do_resize and do_rescale and do_normalize: + frames, target_sizes, items = [], [], [] + for video in videos: + target_size = self._resized_size( + *video.shape[-2:], + video.shape[0], + size, + patch_size * merge_size, + temporal_patch_size, + cap_pixels_per_frame, + ) + items.append(list(range(len(frames), len(frames) + video.shape[0]))) + frames.extend(video) + target_sizes.extend([target_size] * video.shape[0]) + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + if kernel_output is not None: + pixel_values_videos, video_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values_videos": pixel_values_videos, + "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} diff --git a/src/transformers/models/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index e5eb4d2d747d..880ea70d3823 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,14 +37,18 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack -from ...utils import TensorType, auto_docstring, is_vision_available +from ...utils import TensorType, auto_docstring, is_vision_available, logging if is_vision_available(): import PIL +logger = logging.get_logger(__name__) + + class Sam2ImageProcessorKwargs(ImagesKwargs, total=False): r""" mask_size (`dict[str, int]`, *optional*): @@ -632,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) @@ -684,5 +689,22 @@ 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 background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + regions = masks.flatten(0, 1).unsqueeze(1) + 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + return regions.reshape_as(masks) + __all__ = ["Sam2ImageProcessor"] diff --git a/src/transformers/models/sam2/modular_sam2.py b/src/transformers/models/sam2/modular_sam2.py index 9b444817c0d0..21c50c4eee14 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_kernels import run_processing_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,23 @@ def post_process_masks( return output_masks + def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): + """Fill background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + regions = masks.flatten(0, 1).unsqueeze(1) + 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + return regions.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 b91416677dd3..bbdf6a7fd5aa 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,14 +40,18 @@ PILImageResampling, SizeDict, ) +from ...integrations.hub_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack -from ...utils import TensorType, auto_docstring, is_vision_available +from ...utils import TensorType, auto_docstring, is_vision_available, logging if is_vision_available(): import PIL +logger = logging.get_logger(__name__) + + class Sam3ImageProcessorKwargs(ImagesKwargs, total=False): r""" mask_size (`dict[str, int]`, *optional*): @@ -663,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) @@ -715,6 +720,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 background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + regions = masks.flatten(0, 1).unsqueeze(1) + 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + return regions.reshape_as(masks) + def post_process_semantic_segmentation( self, outputs, 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 dd84527623a1..081bd1cbc931 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 @@ -28,6 +28,7 @@ from ...image_processing_backends import TorchvisionBackend from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageInput, PILImageResampling, SizeDict +from ...integrations.hub_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -273,6 +274,43 @@ def _preprocess( tensor_type=return_tensors, ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + ) + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. diff --git a/src/transformers/models/video_llama_3/video_processing_video_llama_3.py b/src/transformers/models/video_llama_3/video_processing_video_llama_3.py index fbff76a50cef..0d0a99845807 100644 --- a/src/transformers/models/video_llama_3/video_processing_video_llama_3.py +++ b/src/transformers/models/video_llama_3/video_processing_video_llama_3.py @@ -242,6 +242,20 @@ def resize( resample=resample, ) + def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): + """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" + 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` + total_pixels = int(self.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) + ) + return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=max_pixels) + def patchify( self, videos: "torch.Tensor", diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index fc645197a3fe..2dd983bcbe3a 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -22,14 +22,28 @@ import types from unittest.mock import MagicMock, patch +import numpy as np import torch from huggingface_hub import snapshot_download from parameterized import parameterized from tests.test_memory_cleanup_mixin import MemoryCleanupTestCase -from transformers import AutoModelForCausalLM, AutoTokenizer, KernelConfig, ViTImageProcessor -from transformers.image_processing_backends import _resize_normalize_kernel, _resize_normalize_ragged_kernel -from transformers.image_utils import PILImageResampling, SizeDict +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + HunYuanVLImageProcessor, + KernelConfig, + Qwen2VLImageProcessor, + Qwen2VLVideoProcessor, + Sam2ImageProcessor, + ViTImageProcessor, +) +from transformers.image_processing_backends import ( + _connected_component_areas_kernel, + _resize_normalize_kernel, + _resize_normalize_patchify_kernel, +) +from transformers.image_utils import PILImageResampling, SizeDict, load_image from transformers.integrations.hub_kernels import ( _HUB_KERNEL_MAPPING, _KERNEL_MODULE_MAPPING, @@ -911,16 +925,32 @@ def test_single_device_mapping_still_works(self): self.assertIn("RMSNorm", result_mapping, "RMSNorm should be in mapping") -class RecordingKernel: - """Stand-in for a loaded kernel module: records the call and returns a fixed output.""" +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 __init__(self, output=None): - self.output = output - self.calls = [] +class ReferenceConnectedComponentsKernel: + """Stand-in for `kernels-community/cv-utils`: records the input of `cc_2d` and answers with the reference.""" - def resize_normalize(self, images, size, image_mean, image_std, **kwargs): - self.calls.append({"images": images, "size": size, "image_mean": image_mean, "image_std": image_std, **kwargs}) - return self.output + def __init__(self): + self.inputs = [] + + def cc_2d(self, inputs, get_counts): + self.inputs.append(inputs) + return None, connected_component_areas_reference(inputs.bool()) class TestProcessingKernels(TestCasePlus): @@ -928,32 +958,20 @@ class TestProcessingKernels(TestCasePlus): def setUp(self): super().setUp() - self.images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] - self.kwargs = { - "do_resize": True, - "size": SizeDict(height=8, width=8), - "resample": PILImageResampling.BICUBIC, - "do_rescale": True, - "rescale_factor": 1 / 255, - "do_normalize": True, - "image_mean": [0.5, 0.5, 0.5], - "image_std": [0.5, 0.5, 0.5], - } + # 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 run_adapter(self, output=None, images=None, **overrides): - kernel = RecordingKernel(output=output) - images = self.images if images is None else images - # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): - result = _resize_normalize_kernel(kernel, images, **{**self.kwargs, **overrides}) - return kernel, result + 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_registration_records_repo_and_adapter(self): - self.assertIs(_PROCESSING_KERNEL_ADAPTERS["resize_normalize"], _resize_normalize_kernel) - self.assertIs(_PROCESSING_KERNEL_ADAPTERS["resize_normalize_ragged"], _resize_normalize_ragged_kernel) - for name in ("resize_normalize", "resize_normalize_ragged"): - self.assertEqual(_HUB_KERNEL_MAPPING[name]["repo_id"], "Molbap/kernel_image_resize") - self.assertEqual(_HUB_KERNEL_MAPPING[name]["revision"], "v1.0.0") + self.assertIs(_PROCESSING_KERNEL_ADAPTERS["connected_component_areas"], _connected_component_areas_kernel) + self.assertEqual(_HUB_KERNEL_MAPPING["connected_component_areas"]["repo_id"], "kernels-community/cv-utils") + self.assertEqual(_HUB_KERNEL_MAPPING["connected_component_areas"]["version"], 1) def test_kernel_outside_kernels_community_is_not_trusted_by_default(self): mapping = {} @@ -970,36 +988,6 @@ def test_kernel_outside_kernels_community_is_not_trusted_by_default(self): ): self.assertIs(lazy_load_kernel("private_op", mapping), sentinel) - def test_ragged_adapter_translates_per_image_targets(self): - kernel = MagicMock() - kernel.resize_normalize_ragged_output.return_value = [torch.zeros(3, 8, 8), torch.zeros(3, 4, 4)] - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): - result = _resize_normalize_ragged_kernel( - kernel, - self.images, - [(8, 8), (4, 4)], - **{key: self.kwargs[key] for key in self.kwargs if key != "size"}, - ) - self.assertEqual(len(result), 2) - arguments = kernel.resize_normalize_ragged_output.call_args[0] - self.assertEqual(arguments[1], [(8, 8), (4, 4)]) - self.assertEqual(arguments[2], [0.5, 0.5, 0.5]) - self.assertEqual(arguments[4], 1 / 255) - self.assertEqual(arguments[5], "bicubic") - - def test_ragged_adapter_falls_back(self): - kernel = MagicMock() - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): - # One target per image is required, and the images must be uint8 CHW on one device. - self.assertIsNone(_resize_normalize_ragged_kernel(kernel, self.images, [(8, 8)], **self.kwargs)) - self.assertIsNone( - _resize_normalize_ragged_kernel( - kernel, [image.float() for image in self.images], [(8, 8), (4, 4)], **self.kwargs - ) - ) - self.assertIsNone(_resize_normalize_ragged_kernel(kernel, self.images, [(8, 8), (4, 4)], **self.kwargs)) - kernel.resize_normalize_ragged_output.assert_not_called() - def test_run_processing_kernel_calls_adapter(self): sentinel = types.ModuleType("sentinel_kernel_module") with ( @@ -1016,151 +1004,273 @@ def test_run_processing_kernel_calls_adapter(self): self.assertEqual(run_processing_kernel("dummy_op", 3), (sentinel, 3)) def test_run_processing_kernel_falls_back(self): + regions = self.mask_logits > 0 with patch.object(torch.cuda, "is_available", return_value=True): # Unknown op, `USE_HUB_KERNELS=0`, and a kernel that cannot be loaded all keep the default path. self.assertIsNone(run_processing_kernel("not_a_registered_op")) with patch.dict(run_processing_kernel.__globals__, {"_kernels_enabled": False}): - self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) + self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": lambda name: None}): - self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) + self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) def test_run_processing_kernel_needs_accelerator(self): with patch.object(torch.cuda, "is_available", return_value=False): with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": self.fail}): - self.assertIsNone(run_processing_kernel("resize_normalize", self.images, **self.kwargs)) - - def test_adapter_translates_square_resize(self): - kernel, result = self.run_adapter(output=torch.zeros(2, 3, 8, 8)) - self.assertEqual(len(kernel.calls), 1) - call = kernel.calls[0] - self.assertEqual(call["size"], (8, 8)) - self.assertIsNone(call["crop_size"]) - self.assertEqual(call["resize_mode"], "square") - self.assertEqual(call["resample"], "bicubic") - self.assertEqual(call["rescale_factor"], 1 / 255) - self.assertEqual(call["image_mean"], [0.5, 0.5, 0.5]) - # Same output shape as the default path: a list of images, stacked only when tensors are requested. - self.assertEqual([image.shape for image in result["pixel_values"]], [(3, 8, 8)] * 2) - _, stacked = self.run_adapter(output=torch.zeros(2, 3, 8, 8), return_tensors="pt") - self.assertEqual(stacked["pixel_values"].shape, (2, 3, 8, 8)) - - def test_adapter_translates_shortest_edge_resize_with_crop(self): - kernel, _ = self.run_adapter( - output=torch.zeros(2, 3, 6, 6), - size=SizeDict(shortest_edge=8), - do_center_crop=True, - crop_size=SizeDict(height=6, width=6), - ) - call = kernel.calls[0] - self.assertEqual(call["size"], 8) - self.assertEqual(call["crop_size"], (6, 6)) - self.assertEqual(call["resize_mode"], "shortest_edge") + self.assertIsNone(run_processing_kernel("connected_component_areas", self.mask_logits > 0)) + + def test_connected_component_areas_adapter_pads_to_even_size(self): + kernel = ReferenceConnectedComponentsKernel() + regions = torch.zeros(2, 1, 5, 7, dtype=torch.bool) + regions[:, :, 1:3, 1:4] = True + # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + areas = _connected_component_areas_kernel(kernel, regions) + self.assertEqual(tuple(kernel.inputs[0].shape), (2, 1, 6, 8)) + self.assertEqual(kernel.inputs[0].dtype, torch.uint8) + self.assertEqual(tuple(areas.shape), (2, 1, 5, 7)) + self.assertTrue(torch.equal(areas, connected_component_areas_reference(regions))) + + def test_connected_component_areas_adapter_needs_cuda_tensors(self): + kernel = ReferenceConnectedComponentsKernel() + self.assertIsNone(_connected_component_areas_kernel(kernel, self.mask_logits > 0)) + self.assertEqual(kernel.inputs, []) + + def test_sam2_fills_holes_and_removes_sprinkles(self): + with patch( + "transformers.models.sam2.image_processing_sam2.run_processing_kernel", + side_effect=lambda name, regions: connected_component_areas_reference(regions), + ): + 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) + 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_keeps_masks_without_the_kernel(self): + default = self.post_process(use_kernels=False) + self.assertTrue(default[0, 0, 5, 5].item() is False and default[0, 0, 13, 13].item() is True) + self.assertTrue(torch.equal(self.post_process(False, max_hole_area=4, max_sprinkle_area=1), default)) + with patch.object(torch.cuda, "is_available", return_value=False): + self.assertTrue(torch.equal(self.post_process(True, max_hole_area=4, max_sprinkle_area=1), default)) - def test_adapter_scalar_normalization_stats(self): - kernel, _ = self.run_adapter(output=torch.zeros(2, 3, 8, 8), image_mean=0.5, image_std=0.5) - self.assertEqual(kernel.calls[0]["image_mean"], [0.5, 0.5, 0.5]) + def run_resize_adapter(self, images=None, **overrides): + kernel = MagicMock() + arguments = { + "size": SizeDict(height=8, width=8), + "crop_size": None, + "resample": PILImageResampling.BICUBIC, + "rescale_factor": 1 / 255, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + images = ( + [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] if images is None else images + ) + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + result = _resize_normalize_kernel(kernel, images, **{**arguments, **overrides}) + return kernel, result - def test_adapter_skips_rescale(self): - kernel, _ = self.run_adapter(output=torch.zeros(2, 3, 8, 8), do_rescale=False) - self.assertEqual(kernel.calls[0]["rescale_factor"], 1.0) + def test_resize_adapter_translates_arguments(self): + kernel, result = self.run_resize_adapter() + self.assertIs(result, kernel.resize_normalize.return_value) + arguments, keyword_arguments = kernel.resize_normalize.call_args + self.assertEqual(arguments[1:], ((8, 8), [0.5, 0.5, 0.5], [0.5, 0.5, 0.5])) + self.assertEqual(keyword_arguments["resample"], "bicubic") + self.assertEqual(keyword_arguments["resize_mode"], "square") + self.assertTrue(keyword_arguments["round_to_uint8"]) + + kernel, _ = self.run_resize_adapter( + size=SizeDict(shortest_edge=8), crop_size=SizeDict(height=6, width=6), image_mean=0.5, image_std=0.5 + ) + arguments, keyword_arguments = kernel.resize_normalize.call_args + self.assertEqual(arguments[1:], (8, [0.5] * 3, [0.5] * 3)) + self.assertEqual((keyword_arguments["resize_mode"], keyword_arguments["crop_size"]), ("shortest_edge", (6, 6))) - def test_adapter_falls_back_on_unsupported_arguments(self): + def test_resize_adapter_falls_back(self): unsupported = { - "padding": {"do_pad": True, "pad_size": SizeDict(height=8, width=8)}, - "no_resize": {"do_resize": False}, - "no_normalize": {"do_normalize": False}, "lanczos": {"resample": PILImageResampling.LANCZOS}, - "bounded_resize": {"size": SizeDict(max_height=8, max_width=8)}, - "crop_without_size": {"do_center_crop": True, "crop_size": SizeDict()}, - "crop_larger_than_resize": {"do_center_crop": True, "crop_size": SizeDict(height=12, width=12)}, - "shortest_edge_below_crop": { - "size": SizeDict(shortest_edge=4), - "do_center_crop": True, - "crop_size": SizeDict(height=6, width=6), - }, + "crop_larger_than_resize": {"crop_size": SizeDict(height=12, width=12)}, + "empty_crop": {"crop_size": SizeDict()}, "shortest_edge_without_crop": {"size": SizeDict(shortest_edge=8)}, - "stats_per_channel_mismatch": {"image_mean": [0.5, 0.5], "image_std": [0.5, 0.5]}, + "bounded_resize": {"size": SizeDict(shortest_edge=8, longest_edge=16)}, + "stats_do_not_match_channels": {"image_mean": [0.5, 0.5], "image_std": [0.5, 0.5]}, + "float_images": {"images": [torch.rand(3, 40, 60)]}, + "mixed_channels": { + "images": [torch.zeros(3, 4, 4, dtype=torch.uint8), torch.zeros(1, 4, 4, dtype=torch.uint8)] + }, } for name, overrides in unsupported.items(): with self.subTest(name): - kernel, result = self.run_adapter(**overrides) + kernel, result = self.run_resize_adapter(**overrides) self.assertIsNone(result) - self.assertEqual(kernel.calls, []) - - def test_adapter_falls_back_on_unsupported_images(self): - for name, images in { - "empty": [], - "float": [image.float() for image in self.images], - "batched": [image.unsqueeze(0) for image in self.images], - "mixed_channels": [self.images[0], self.images[1][:1]], - "nested": [[image] for image in self.images], - }.items(): - with self.subTest(name): - kernel, result = self.run_adapter(images=images) - self.assertIsNone(result) - self.assertEqual(kernel.calls, []) - - def test_adapter_falls_back_on_images_the_kernel_cannot_reach(self): - # Images stay on CPU unless the caller passes `device`, and the kernel runs where the images are. - kernel = RecordingKernel() - self.assertIsNone(_resize_normalize_kernel(kernel, self.images, **self.kwargs)) - self.assertEqual(kernel.calls, []) - - def test_resize_normalize_batch_matches_with_and_without_grouping(self): - processor = ViTImageProcessor() - images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] + [ - torch.randint(0, 255, (3, 30, 30), dtype=torch.uint8) + kernel.resize_normalize.assert_not_called() + # Outside the patch the kernel device is CUDA, and these images are on CPU. + kernel = MagicMock() + self.assertIsNone( + _resize_normalize_kernel( + kernel, + [torch.zeros(3, 4, 4, dtype=torch.uint8)], + SizeDict(height=2, width=2), + None, + 3, + 1 / 255, + 0.5, + 0.5, + ) + ) + kernel.resize_normalize.assert_not_called() + + def test_patchify_adapter_translates_arguments(self): + kernel = MagicMock() + frames = [torch.zeros(3, 30, 40, dtype=torch.uint8), torch.zeros(3, 20, 20, dtype=torch.uint8)] + with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + result = _resize_normalize_patchify_kernel( + kernel, frames, [(28, 28), (28, 28)], [[0], [1]], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 + ) + self.assertIs(result, kernel.resize_normalize_patchify.return_value) + arguments, keyword_arguments = kernel.resize_normalize_patchify.call_args + self.assertEqual( + arguments[1:], ([(28, 28), (28, 28)], [[0], [1]], [0.5] * 3, [0.5] * 3, 1 / 255, "bicubic", True, 14, 2, 2) + ) + self.assertTrue(keyword_arguments["round_to_uint8"]) + + 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) + with patch( + "transformers.models.qwen2_vl.image_processing_qwen2_vl.run_processing_kernel", + return_value=(pixel_values, [(1, 4, 6)]), + ) as run_kernel: + output = Qwen2VLImageProcessor(use_kernels=True)(images, return_tensors="pt") + Qwen2VLImageProcessor(use_kernels=False)(images, return_tensors="pt") + self.assertEqual(run_kernel.call_count, 1) + self.assertEqual(run_kernel.call_args[0][0], "resize_normalize_patchify") + self.assertIs(output["pixel_values"], pixel_values) + self.assertEqual(output["image_grid_thw"].tolist(), [[1, 4, 6]]) + + def test_qwen2_vl_video_groups_frames_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), ] - targets = [(8, 12), (8, 12), (6, 6)] - arguments = (targets, PILImageResampling.BICUBIC, True, 1 / 255, True, (0.5,) * 3, (0.5,) * 3) - grouped = processor.resize_normalize_batch(images, *arguments, disable_grouping=False) - ungrouped = processor.resize_normalize_batch(images, *arguments, disable_grouping=True) - self.assertEqual([tuple(image.shape) for image in grouped], [(3, 8, 12), (3, 8, 12), (3, 6, 6)]) - for one, other in zip(grouped, ungrouped): - torch.testing.assert_close(one, other) + with patch( + "transformers.models.qwen2_vl.video_processing_qwen2_vl.run_processing_kernel", + return_value=(torch.zeros(1, 1), [(2, 4, 6), (1, 2, 2)]), + ) as run_kernel: + output = Qwen2VLVideoProcessor(use_kernels=True)( + videos, do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" + ) + frames, target_sizes, items = run_kernel.call_args[0][1:4] + self.assertEqual(len(frames), 5) + self.assertEqual(items, [[0, 1, 2], [3, 4]]) + self.assertEqual(len(set(target_sizes[:3])), 1) + self.assertEqual(output["video_grid_thw"].tolist(), [[2, 4, 6], [1, 2, 2]]) + + def test_hunyuan_vl_does_not_use_the_patchify_kernel(self): + with ( + patch.object(torch.cuda, "is_available", return_value=True), + patch.dict( + run_processing_kernel.__globals__, + { + "_kernels_enabled": True, + "_PROCESSING_KERNEL_ADAPTERS": {"resize_normalize_patchify": self.fail}, + "lazy_load_kernel": lambda name: types.ModuleType("sentinel_kernel_module"), + }, + ), + ): + output = HunYuanVLImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) + self.assertIn("pixel_values", output) def test_use_kernels_is_a_runtime_flag(self): - processor = ViTImageProcessor(use_kernels=True) + 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(ViTImageProcessor.from_pretrained(tmp_dir).use_kernels) - self.assertTrue(ViTImageProcessor.from_pretrained(tmp_dir, use_kernels=True).use_kernels) + self.assertFalse(Sam2ImageProcessor.from_pretrained(tmp_dir).use_kernels) + self.assertTrue(Sam2ImageProcessor.from_pretrained(tmp_dir, use_kernels=True).use_kernels) - def test_default_path_is_unchanged_when_the_kernel_cannot_run(self): - images = [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8)] - with patch.object(torch.cuda, "is_available", return_value=False): - with_kernels = ViTImageProcessor(use_kernels=True)(images, return_tensors="pt") - without_kernels = ViTImageProcessor(use_kernels=False)(images, return_tensors="pt") - torch.testing.assert_close(with_kernels["pixel_values"], without_kernels["pixel_values"]) + +@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) + regions = (masks.flatten(0, 1) > 0).unsqueeze(1) + areas = run_processing_kernel("connected_component_areas", regions) + self.assertIsNotNone(areas, "the kernel did not run") + 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( + "transformers.models.sam2.image_processing_sam2.run_processing_kernel", + side_effect=lambda name, regions: connected_component_areas_reference(regions), + ): + 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 TestResizeNormalizeKernel(TestCasePlus): - """Parity of the resize + normalize kernel against the torchvision path. Needs the kernel repo to be published.""" - - def test_matches_default_path(self): - if lazy_load_kernel("resize_normalize") is None: - self.skipTest("kernel repo of `resize_normalize` is not available") - images = [ - torch.randint(0, 255, (3, height, width), dtype=torch.uint8, device=torch_device) - for height, width in [(480, 640), (300, 300), (1024, 768)] - ] +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(operation) + if not hasattr(kernel, operation): + self.skipTest(f"`{operation}` is not available in `kernels-community/cv-utils`") + adapter = _PROCESSING_KERNEL_ADAPTERS[operation] kernel_outputs = [] def recording_adapter(*args, **kwargs): - kernel_outputs.append(_resize_normalize_kernel(*args, **kwargs)) + kernel_outputs.append(adapter(*args, **kwargs)) return kernel_outputs[-1] - with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {"resize_normalize": recording_adapter}): - with_kernels = ViTImageProcessor(use_kernels=True)(images, return_tensors="pt")["pixel_values"] - # Without this the test would compare the default path against itself and pass on a silent fallback. + with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {operation: recording_adapter}): + with_kernels = call(processor_class(use_kernels=True)) self.assertTrue( kernel_outputs and kernel_outputs[0] is not None, "the adapter fell back, the kernel never ran" ) - without_kernels = ViTImageProcessor(use_kernels=False)(images, return_tensors="pt")["pixel_values"] - self.assertEqual(with_kernels.shape, without_kernels.shape) - # The kernel resizes in float where the default path resizes in uint8, so single pixels differ. - self.assertLess((with_kernels - without_kernels).abs().mean().item(), 0.02) + 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" + ), + ) From 7e3c33326974a01aa83d313b9123ef6ad8735d3a Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 7 Oct 2026 16:39:20 +0200 Subject: [PATCH 10/26] model-specific changes --- .../hunyuan_vl/image_processing_hunyuan_vl.py | 40 +++++++++++++++-- .../models/hunyuan_vl/modular_hunyuan_vl.py | 40 +++++++++++++++-- .../paddleocr_vl/modular_paddleocr_vl.py | 43 +++++++++++++++++++ 3 files changed, 117 insertions(+), 6 deletions(-) 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 0287fa2d05c5..45881b235487 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -286,9 +287,42 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel(self, *args, **kwargs): - """The kernel writes the Qwen2-VL patch order and resamples with `resample`, HunYuanVL needs neither.""" - return None + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """Row-major patches are the kernel layout with `merge_size=1`, resampled with BICUBIC like `resize`.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + PILImageResampling.BICUBIC, + rescale_factor, + image_mean, + image_std, + patch_size, + 1, + temporal_patch_size, + ) def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index dfe0d3df0b7f..133c40ab6266 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -30,6 +30,7 @@ from ...image_processing_backends import PilBackend, TorchvisionBackend from ...image_utils import PILImageResampling, SizeDict from ...integrations import use_kernel_forward_from_hub +from ...integrations.hub_kernels import run_processing_kernel from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast from ...modeling_utils import ALL_ATTENTION_FUNCTIONS @@ -421,9 +422,42 @@ def patchify( return flatten_patches, grid_h, grid_w - def _resize_normalize_patchify_kernel(self, *args, **kwargs): - """The kernel writes the Qwen2-VL patch order and resamples with `resample`, HunYuanVL needs neither.""" - return None + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """Row-major patches are the kernel layout with `merge_size=1`, resampled with BICUBIC like `resize`.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + return run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + PILImageResampling.BICUBIC, + rescale_factor, + image_mean, + image_std, + patch_size, + 1, + temporal_patch_size, + ) def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index 401959082d5b..fc0b8aba5890 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -27,6 +27,7 @@ from ... import initialization as init from ...activations import GELUActivation from ...cache_utils import Cache, DynamicCache +from ...integrations.hub_kernels import run_processing_kernel from ...masking_utils import create_bidirectional_mask, create_causal_mask from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_utils import PreTrainedModel @@ -213,6 +214,48 @@ def patchify( ) return flatten_patches, grid_h, grid_w + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """Row by row patches are the kernel layout with `merge_size=1`, viewed as `(C * T, P, P)` blocks.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + 1, + temporal_patch_size, + ) + if kernel_output is None: + return None + pixel_values, image_grid_thw = kernel_output + channels = images[0].shape[0] + return pixel_values.view(-1, channels * temporal_patch_size, patch_size, patch_size), image_grid_thw + class PaddleOCRVLProcessorKwargs(ProcessingKwargs, total=False): _defaults = { From 9616d975eee867b5f4434db5c860a3873b5fadb4 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 7 Oct 2026 16:39:47 +0200 Subject: [PATCH 11/26] remove lazy load modifs --- src/transformers/integrations/hub_kernels.py | 38 +++++++++----------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 308d9b4fbe90..da1b538c1956 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -787,6 +787,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}, } # Flash attention version -> major version of its hub kernel repo. Flash attention flavors that are not @@ -898,23 +899,15 @@ def load_and_register_attn_kernel( def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _KERNEL_MODULE_MAPPING): - if kernel_name in mapping: - # A cached `None` means the load already failed once; do not hit the Hub again on every call. + if kernel_name in mapping and isinstance(mapping[kernel_name], ModuleType): return mapping[kernel_name] if kernel_name not in _HUB_KERNEL_MAPPING: logger.warning_once(f"Kernel {kernel_name} not found in _HUB_KERNEL_MAPPING") mapping[kernel_name] = None return None - repo_id = _HUB_KERNEL_MAPPING[kernel_name]["repo_id"] - if not ALLOW_ALL_KERNELS and not repo_id.startswith("kernels-community/"): - # Not cached: the answer changes inside `allow_all_hub_kernels()`. - logger.warning_once( - f"Kernel {kernel_name} is hosted in {repo_id}, outside `kernels-community`, so its code is not run by " - "default. Wrap the call in `transformers.integrations.hub_kernels.allow_all_hub_kernels()` to trust it." - ) - return None if is_kernels_available() and _kernels_enabled: try: + repo_id = _HUB_KERNEL_MAPPING[kernel_name]["repo_id"] revision = _HUB_KERNEL_MAPPING[kernel_name].get("revision", None) version = _HUB_KERNEL_MAPPING[kernel_name].get("version", None) # Default version as it's mandatory @@ -923,10 +916,12 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _ kernel = get_kernel(repo_id, revision=revision, version=version, allow_all_kernels=ALLOW_ALL_KERNELS) mapping[kernel_name] = kernel - except Exception as error: - # Missing repo, no network, or torch built without an accelerator backend; fall back to slow path. + except FileNotFoundError as e: + mapping[kernel_name] = None + logger.warning_once(f"Failed to load kernel {kernel_name}: {e}") + except AssertionError: + # Happens when torch is built without an accelerator backend; fall back to slow path. mapping[kernel_name] = None - logger.warning_once(f"Failed to load kernel {kernel_name}: {error}") else: # Try to import is_{kernel_name}_available from ..utils @@ -953,21 +948,20 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _ return mapping[kernel_name] -_PROCESSING_KERNEL_ADAPTERS: dict[str, Callable] = {} +_PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} -def register_processing_kernel(name: str, repo_id: str, version: int | str = 1, revision: str | None = None): +def register_processing_kernel(name: str, kernel_name: str): """ - Register a Hub kernel as an implementation of the processing op `name`, e.g. a processor's resize. + Register the kernel `kernel_name` of `_HUB_KERNEL_MAPPING` as an implementation of the processing op `name`. Processing ops have no common signature to swap, so the decorated function is an adapter: it receives the loaded kernel module followed by the arguments of the op, and returns the kernel result, or `None` when the kernel cannot handle these arguments so that the caller keeps its default implementation. """ - _HUB_KERNEL_MAPPING[name] = {"repo_id": repo_id, "version": version, "revision": revision} def register(adapter: Callable) -> Callable: - _PROCESSING_KERNEL_ADAPTERS[name] = adapter + _PROCESSING_KERNEL_ADAPTERS[name] = (kernel_name, adapter) return adapter return register @@ -975,10 +969,12 @@ def register(adapter: Callable) -> Callable: def run_processing_kernel(name: str, *args, **kwargs): """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" - adapter = _PROCESSING_KERNEL_ADAPTERS.get(name) - if adapter is None or not _kernels_enabled or not is_torch_available() or not torch.cuda.is_available(): + if name not in _PROCESSING_KERNEL_ADAPTERS or not _kernels_enabled: + return None + if not is_torch_available() or not torch.cuda.is_available(): return None - kernel = lazy_load_kernel(name) + kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[name] + kernel = lazy_load_kernel(kernel_name) if kernel is None: return None return adapter(kernel, *args, **kwargs) From fc773fade66363f24f7a6d8510897e5e9e700053 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 7 Oct 2026 16:57:40 +0200 Subject: [PATCH 12/26] load by kernel_name --- docs/source/en/kernel_doc/loading_kernels.md | 6 +- src/transformers/image_processing_backends.py | 21 ++- .../image_processing_paddleocr_vl.py | 64 ++++++++ tests/kernels/test_kernels.py | 150 ++++++++++++++---- 4 files changed, 205 insertions(+), 36 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 30db4603939c..55a9535667ff 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -325,7 +325,7 @@ Image and video processors can run some of their operations with Hub kernels fro | 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 (Cohere Compass, ERNIE 4.5 VL, GLM-Image, MiniMax-M3-VL) | +| 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 (Cohere Compass, ERNIE 4.5 VL, GLM-Image, HunYuanVL, MiniMax-M3-VL, 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`) | ```py @@ -341,13 +341,13 @@ The resize kernels round to `uint8` after each pass, like the default torchvisio ### Registering a processing kernel -Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an operation name to a Hub repository, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. +Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an operation name to a kernel of `_HUB_KERNEL_MAPPING` in `integrations/hub_kernels.py`, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. ```py from transformers.integrations.hub_kernels import register_processing_kernel -@register_processing_kernel("my_op", repo_id="kernels-community/my-processing-kernel", version=1) +@register_processing_kernel("my_op", kernel_name="my-processing-kernel") def my_op_kernel(kernel, images): if images[0].device.type != "cuda": return None diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 693cffc08e74..757e8f19f0ed 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -73,7 +73,7 @@ from .integrations.hub_kernels import register_processing_kernel, run_processing_kernel else: - def register_processing_kernel(name, repo_id, version=1, revision=None): + def register_processing_kernel(name, kernel_name): return lambda adapter: adapter def run_processing_kernel(name, *args, **kwargs): @@ -95,7 +95,7 @@ def run_processing_kernel(name, *args, **kwargs): _KERNEL_DEVICE_TYPE = "cuda" -@register_processing_kernel("connected_component_areas", repo_id="kernels-community/cv-utils", version=1) +@register_processing_kernel("connected_component_areas", kernel_name="cv-utils") def _connected_component_areas_kernel(kernel, regions): """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" if regions.device.type != _KERNEL_DEVICE_TYPE: @@ -129,7 +129,7 @@ def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image return interpolation, image_mean, image_std, rescale_factor -@register_processing_kernel("resize_normalize", repo_id="kernels-community/cv-utils", version=1) +@register_processing_kernel("resize_normalize", kernel_name="cv-utils") def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" arguments = _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std) @@ -161,7 +161,7 @@ def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_ ) -@register_processing_kernel("resize_normalize_patchify", repo_id="kernels-community/cv-utils", version=1) +@register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") def _resize_normalize_patchify_kernel( kernel, frames, @@ -502,7 +502,18 @@ def _preprocess( **kwargs, ) -> BatchFeature: """Preprocess using Torchvision backend (fast, GPU-accelerated).""" - if self.use_kernels and do_resize and do_rescale and do_normalize and not do_pad: + kernel_replaces_default_methods = all( + getattr(type(self), name) is getattr(TorchvisionBackend, name) + for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") + ) + if ( + self.use_kernels + and kernel_replaces_default_methods + and do_resize + and do_rescale + and do_normalize + and not do_pad + ): pixel_values = run_processing_kernel( "resize_normalize", images, 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 058bf7521d4d..31f0f1fa2ab3 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_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -229,6 +230,27 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: + if self.use_kernels and do_resize and do_rescale and do_normalize: + kernel_output = self._resize_normalize_patchify_kernel( + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ) + if kernel_output is not None: + pixel_values, image_grid_thw = kernel_output + return BatchFeature( + data={ + "pixel_values": pixel_values, + "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), + }, + tensor_type=return_tensors, + ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -268,6 +290,48 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) + def _resize_normalize_patchify_kernel( + self, + images, + size, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + temporal_patch_size, + merge_size, + ): + """Row by row patches are the kernel layout with `merge_size=1`, viewed as `(C * T, P, P)` blocks.""" + target_sizes = [ + smart_resize( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + [[index] for index in range(len(images))], + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + 1, + temporal_patch_size, + ) + if kernel_output is None: + return None + pixel_values, image_grid_thw = kernel_output + channels = images[0].shape[0] + return pixel_values.view(-1, channels * temporal_patch_size, patch_size, patch_size), image_grid_thw + def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 2dd983bcbe3a..8aada8d37025 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -16,10 +16,13 @@ import copy +import importlib +import inspect import os import sys import tempfile import types +from pathlib import Path from unittest.mock import MagicMock, patch import numpy as np @@ -27,18 +30,22 @@ from huggingface_hub import snapshot_download from parameterized import parameterized +import transformers from tests.test_memory_cleanup_mixin import MemoryCleanupTestCase from transformers import ( AutoModelForCausalLM, AutoTokenizer, HunYuanVLImageProcessor, KernelConfig, + LevitImageProcessor, + PaddleOCRVLImageProcessor, Qwen2VLImageProcessor, Qwen2VLVideoProcessor, Sam2ImageProcessor, ViTImageProcessor, ) from transformers.image_processing_backends import ( + TorchvisionBackend, _connected_component_areas_kernel, _resize_normalize_kernel, _resize_normalize_patchify_kernel, @@ -68,6 +75,7 @@ ) from transformers.utils.import_utils import is_kernels_available from transformers.utils.kernel_config import add_to_mapping_local +from transformers.video_processing_utils import BaseVideoProcessor if is_kernels_available(): @@ -942,6 +950,55 @@ def connected_component_areas_reference(regions): return areas +def patchify_kernel_layout_reference( + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, +): + """What `resize_normalize_patchify` writes for frames that 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 item in items: + padded_item = list(item) + [item[-1]] * (-len(item) % temporal_patch_size) + video = (torch.stack([frames[index] for index in padded_item]).float() * rescale_factor - mean) / std + frame_count, channels, height, width = video.shape + patches = video.reshape( + frame_count // temporal_patch_size, + temporal_patch_size, + channels, + height // (patch_size * merge_size), + merge_size, + patch_size, + width // (patch_size * merge_size), + merge_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) + + +def processors_calling_the_patchify_kernel(): + """Torchvision image and video processor classes whose module mentions the `resize_normalize_patchify` kernel.""" + classes = [] + for path in sorted(Path(transformers.__file__).parent.glob("models/*/*_processing_*.py")): + if "resize_normalize_patchify" not in path.read_text() or path.stem.startswith("modular_"): + continue + module = importlib.import_module(f"transformers.models.{path.parent.name}.{path.stem}") + for _, cls in inspect.getmembers(module, inspect.isclass): + if cls.__module__ == module.__name__ and issubclass(cls, TorchvisionBackend): + classes.append(cls) + return classes + + class ReferenceConnectedComponentsKernel: """Stand-in for `kernels-community/cv-utils`: records the input of `cc_2d` and answers with the reference.""" @@ -969,24 +1026,11 @@ def post_process(self, use_kernels, **kwargs): return processor.post_process_masks([self.mask_logits.clone()], [(16, 16)], **kwargs)[0] def test_registration_records_repo_and_adapter(self): - self.assertIs(_PROCESSING_KERNEL_ADAPTERS["connected_component_areas"], _connected_component_areas_kernel) - self.assertEqual(_HUB_KERNEL_MAPPING["connected_component_areas"]["repo_id"], "kernels-community/cv-utils") - self.assertEqual(_HUB_KERNEL_MAPPING["connected_component_areas"]["version"], 1) - - def test_kernel_outside_kernels_community_is_not_trusted_by_default(self): - mapping = {} - with patch.dict(_HUB_KERNEL_MAPPING, {"private_op": {"repo_id": "someone/private-kernel", "version": 1}}): - self.assertIsNone(lazy_load_kernel("private_op", mapping)) - # Not cached: the answer changes inside `allow_all_hub_kernels()`, so it must be asked again. - self.assertEqual(mapping, {}) - sentinel = types.ModuleType("trusted_kernel_module") - with ( - patch("transformers.integrations.hub_kernels.ALLOW_ALL_KERNELS", True), - patch("transformers.integrations.hub_kernels._kernels_enabled", True), - patch("transformers.integrations.hub_kernels.is_kernels_available", return_value=True), - patch("transformers.integrations.hub_kernels.get_kernel", return_value=sentinel, create=True), - ): - self.assertIs(lazy_load_kernel("private_op", mapping), sentinel) + self.assertEqual( + _PROCESSING_KERNEL_ADAPTERS["connected_component_areas"], + ("cv-utils", _connected_component_areas_kernel), + ) + self.assertEqual(_HUB_KERNEL_MAPPING["cv-utils"]["repo_id"], "kernels-community/cv-utils") def test_run_processing_kernel_calls_adapter(self): sentinel = types.ModuleType("sentinel_kernel_module") @@ -996,8 +1040,10 @@ def test_run_processing_kernel_calls_adapter(self): run_processing_kernel.__globals__, { "_kernels_enabled": True, - "_PROCESSING_KERNEL_ADAPTERS": {"dummy_op": lambda kernel, value: (kernel, value)}, - "lazy_load_kernel": lambda name: sentinel, + "_PROCESSING_KERNEL_ADAPTERS": { + "dummy_op": ("dummy-kernel", lambda kernel, value: (kernel, value)) + }, + "lazy_load_kernel": {"dummy-kernel": sentinel}.get, }, ), ): @@ -1167,21 +1213,70 @@ def test_qwen2_vl_video_groups_frames_per_video(self): self.assertEqual(len(set(target_sizes[:3])), 1) self.assertEqual(output["video_grid_thw"].tolist(), [[2, 4, 6], [1, 2, 2]]) - def test_hunyuan_vl_does_not_use_the_patchify_kernel(self): + def test_processor_overriding_resize_does_not_use_the_resize_kernel(self): with ( patch.object(torch.cuda, "is_available", return_value=True), patch.dict( run_processing_kernel.__globals__, { "_kernels_enabled": True, - "_PROCESSING_KERNEL_ADAPTERS": {"resize_normalize_patchify": self.fail}, + "_PROCESSING_KERNEL_ADAPTERS": {"resize_normalize": ("cv-utils", self.fail)}, "lazy_load_kernel": lambda name: types.ModuleType("sentinel_kernel_module"), }, ), ): - output = HunYuanVLImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) + output = LevitImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) self.assertIn("pixel_values", output) + def test_processors_reaching_the_patchify_kernel_use_its_layout(self): + processor_classes = processors_calling_the_patchify_kernel() + for processor_class in (Qwen2VLImageProcessor, PaddleOCRVLImageProcessor, HunYuanVLImageProcessor): + self.assertIn(processor_class, processor_classes) + for processor_class in processor_classes: + with self.subTest(processor_class=processor_class.__name__): + processor = processor_class(use_kernels=True) + is_video = issubclass(processor_class, BaseVideoProcessor) + recorded_arguments = [] + + def run(height, width): + recorded_arguments.clear() + if is_video: + videos = [torch.randint(0, 256, (3, 3, height, width), dtype=torch.uint8)] + return processor(videos, do_sample_frames=False, return_tensors="pt")["pixel_values_videos"] + images = [torch.randint(0, 256, (3, height, width), dtype=torch.uint8)] + return processor(images, return_tensors="pt")["pixel_values"] + + with ( + patch.object(torch.cuda, "is_available", return_value=True), + patch.dict( + run_processing_kernel.__globals__, + { + "_kernels_enabled": True, + "_PROCESSING_KERNEL_ADAPTERS": { + "resize_normalize_patchify": ( + "cv-utils", + lambda kernel, *arguments: recorded_arguments.append(arguments), + ) + }, + "lazy_load_kernel": lambda name: types.ModuleType("sentinel_kernel_module"), + }, + ), + ): + height, width = 112, 168 + pixel_values = run(height, width) + if not recorded_arguments: + continue + for _ in range(3): + if recorded_arguments[0][1][0] == (height, width): + break + height, width = recorded_arguments[0][1][0] + pixel_values = run(height, width) + frames, target_sizes = recorded_arguments[0][:2] + self.assertEqual([tuple(frame.shape[-2:]) for frame in frames], [tuple(size) for size in target_sizes]) + torch.testing.assert_close( + pixel_values.reshape(-1), patchify_kernel_layout_reference(*recorded_arguments[0]).reshape(-1) + ) + def test_use_kernels_is_a_runtime_flag(self): processor = Sam2ImageProcessor(use_kernels=True) self.assertNotIn("use_kernels", processor.to_dict()) @@ -1227,17 +1322,16 @@ def setUp(self): 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(operation) - if not hasattr(kernel, operation): - self.skipTest(f"`{operation}` is not available in `kernels-community/cv-utils`") - adapter = _PROCESSING_KERNEL_ADAPTERS[operation] + kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[operation] + if not hasattr(lazy_load_kernel(kernel_name), operation): + self.skipTest(f"`{operation}` is not available in `{kernel_name}`") kernel_outputs = [] def recording_adapter(*args, **kwargs): kernel_outputs.append(adapter(*args, **kwargs)) return kernel_outputs[-1] - with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {operation: recording_adapter}): + with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {operation: (kernel_name, recording_adapter)}): with_kernels = call(processor_class(use_kernels=True)) self.assertTrue( kernel_outputs and kernel_outputs[0] is not None, "the adapter fell back, the kernel never ran" From 9accfa9af44ef9e4146f5e216495f28fe4d58e08 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 9 Oct 2026 11:11:32 +0200 Subject: [PATCH 13/26] move processing kernels to their spot --- docs/source/en/kernel_doc/loading_kernels.md | 4 +- src/transformers/image_processing_backends.py | 114 +------------ src/transformers/integrations/hub_kernels.py | 34 ---- .../integrations/hub_processing_kernels.py | 158 ++++++++++++++++++ .../image_processing_cohere_compass.py | 2 +- .../video_processing_cohere_compass.py | 2 +- .../image_processing_ernie4_5_vl_moe.py | 2 +- .../glm_image/image_processing_glm_image.py | 2 +- .../hunyuan_vl/image_processing_hunyuan_vl.py | 2 +- .../models/hunyuan_vl/modular_hunyuan_vl.py | 2 +- .../image_processing_minimax_m3_vl.py | 2 +- .../image_processing_paddleocr_vl.py | 2 +- .../paddleocr_vl/modular_paddleocr_vl.py | 2 +- .../qwen2_vl/image_processing_qwen2_vl.py | 2 +- .../qwen2_vl/video_processing_qwen2_vl.py | 2 +- .../qwen3_vl/video_processing_qwen3_vl.py | 2 +- .../models/sam2/image_processing_sam2.py | 2 +- src/transformers/models/sam2/modular_sam2.py | 2 +- .../models/sam3/image_processing_sam3.py | 2 +- .../image_processing_video_llama_3.py | 2 +- tests/kernels/test_kernels.py | 85 +++++----- 21 files changed, 221 insertions(+), 206 deletions(-) create mode 100644 src/transformers/integrations/hub_processing_kernels.py diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 55a9535667ff..0cd973299084 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -341,10 +341,10 @@ The resize kernels round to `uint8` after each pass, like the default torchvisio ### Registering a processing kernel -Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. `register_processing_kernel` maps an operation name to a kernel of `_HUB_KERNEL_MAPPING` in `integrations/hub_kernels.py`, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. +Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. Adapters live in `integrations/hub_processing_kernels.py`. `register_processing_kernel` maps an operation name to a kernel of `_HUB_KERNEL_MAPPING` in `integrations/hub_kernels.py`, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. ```py -from transformers.integrations.hub_kernels import register_processing_kernel +from transformers.integrations.hub_processing_kernels import register_processing_kernel @register_processing_kernel("my_op", kernel_name="my-processing-kernel") diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 757e8f19f0ed..78ada52957ff 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 run_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -70,15 +71,6 @@ if is_torch_available(): import torch - from .integrations.hub_kernels import register_processing_kernel, run_processing_kernel -else: - - def register_processing_kernel(name, kernel_name): - return lambda adapter: adapter - - def run_processing_kernel(name, *args, **kwargs): - return None - if is_torchvision_available(): from torchvision.transforms.v2 import functional as tvF @@ -92,110 +84,6 @@ def run_processing_kernel(name, *args, **kwargs): logger = logging.get_logger(__name__) -_KERNEL_DEVICE_TYPE = "cuda" - - -@register_processing_kernel("connected_component_areas", kernel_name="cv-utils") -def _connected_component_areas_kernel(kernel, regions): - """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" - if regions.device.type != _KERNEL_DEVICE_TYPE: - return None - height, width = regions.shape[-2:] - padded_regions = torch.nn.functional.pad(regions.to(torch.uint8), (0, width % 2, 0, height % 2)) - _, areas = kernel.cc_2d(padded_regions.contiguous(), get_counts=True) - return areas[..., :height, :width] - - -_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} - - -def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std): - """Interpolation and per-channel stats for the resize kernels, `None` when they cannot process these inputs.""" - if not images or any( - not isinstance(image, torch.Tensor) - or image.ndim != 3 - or image.dtype != torch.uint8 - or image.device != images[0].device - or image.shape[0] != images[0].shape[0] - for image in images - ): - return None - interpolation = _KERNEL_INTERPOLATIONS.get(resample) - channels = images[0].shape[0] - image_mean = [image_mean] * channels if isinstance(image_mean, (int, float)) else list(image_mean) - image_std = [image_std] * channels if isinstance(image_std, (int, float)) else list(image_std) - if images[0].device.type != _KERNEL_DEVICE_TYPE or interpolation is None or len(image_mean) != channels: - return None - return interpolation, image_mean, image_std, rescale_factor - - -@register_processing_kernel("resize_normalize", kernel_name="cv-utils") -def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): - """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" - arguments = _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std) - if arguments is None: - return None - interpolation, image_mean, image_std, rescale_factor = arguments - crop = (crop_size.height, crop_size.width) if crop_size is not None else None - if crop is not None and not all(crop): - return None - if size.height and size.width: - if crop is not None and (crop[0] > size.height or crop[1] > size.width): - return None - resize, resize_mode = (size.height, size.width), "square" - elif size.shortest_edge and not size.longest_edge and crop is not None and size.shortest_edge >= max(crop): - resize, resize_mode = size.shortest_edge, "shortest_edge" - else: - return None - return kernel.resize_normalize( - images, - resize, - image_mean, - image_std, - rescale_factor=rescale_factor, - resample=interpolation, - antialias=True, - crop_size=crop, - resize_mode=resize_mode, - round_to_uint8=True, - ) - - -@register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") -def _resize_normalize_patchify_kernel( - kernel, - frames, - target_sizes, - items, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, -): - """Resize every frame to its target size, normalize, and write the flattened patches of every item in order.""" - arguments = _resize_kernel_arguments(frames, resample, rescale_factor, image_mean, image_std) - if arguments is None: - return None - interpolation, image_mean, image_std, rescale_factor = arguments - return kernel.resize_normalize_patchify( - frames, - target_sizes, - items, - image_mean, - image_std, - rescale_factor, - interpolation, - True, - patch_size, - merge_size, - temporal_patch_size, - round_to_uint8=True, - ) - - @requires(backends=("torch", "torchvision")) class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 0da2d0139b37..26f634d07ffa 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -947,38 +947,6 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _ return mapping[kernel_name] -_PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} - - -def register_processing_kernel(name: str, kernel_name: str): - """ - Register the kernel `kernel_name` of `_HUB_KERNEL_MAPPING` as an implementation of the processing op `name`. - - Processing ops have no common signature to swap, so the decorated function is an adapter: it receives the loaded - kernel module followed by the arguments of the op, and returns the kernel result, or `None` when the kernel - cannot handle these arguments so that the caller keeps its default implementation. - """ - - def register(adapter: Callable) -> Callable: - _PROCESSING_KERNEL_ADAPTERS[name] = (kernel_name, adapter) - return adapter - - return register - - -def run_processing_kernel(name: str, *args, **kwargs): - """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" - if name not in _PROCESSING_KERNEL_ADAPTERS or not _kernels_enabled: - return None - if not is_torch_available() or not torch.cuda.is_available(): - return None - kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[name] - kernel = lazy_load_kernel(kernel_name) - if kernel is None: - return None - return adapter(kernel, *args, **kwargs) - - def kernelize(model: "PreTrainedModel", mode: "Mode | None" = None): """Temporarily register hidden kernel wrappers so `kernelize` can discover and replace them.""" if not is_kernels_available(): @@ -1284,9 +1252,7 @@ def _noop_forward(self, *args, **kwargs): "register_kernel_mapping", "register_kernel_mapping_transformers", "register_kernel_replacements_and_fusions", - "register_processing_kernel", "replace_kernel_forward_from_hub", - "run_processing_kernel", "use_kernel_forward_from_hub", "use_kernel_func_from_hub", "use_kernelized_func", diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py new file mode 100644 index 000000000000..a764d6a4a0ea --- /dev/null +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -0,0 +1,158 @@ +# 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. +from collections.abc import Callable + +from ..utils.import_utils import is_torch_available + + +if is_torch_available(): + import torch + + from . import hub_kernels + + +_PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} + + +def register_processing_kernel(name: str, kernel_name: str): + """ + Register the kernel `kernel_name` of `_HUB_KERNEL_MAPPING` as an implementation of the processing op `name`. + + Processing ops have no common signature to swap, so the decorated function is an adapter: it receives the loaded + kernel module followed by the arguments of the op, and returns the kernel result, or `None` when the kernel + cannot handle these arguments so that the caller keeps its default implementation. + """ + + def register(adapter: Callable) -> Callable: + _PROCESSING_KERNEL_ADAPTERS[name] = (kernel_name, adapter) + return adapter + + return register + + +def run_processing_kernel(name: str, *args, **kwargs): + """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" + if not is_torch_available() or name not in _PROCESSING_KERNEL_ADAPTERS or not hub_kernels._kernels_enabled: + return None + if not torch.cuda.is_available(): + return None + kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[name] + kernel = hub_kernels.lazy_load_kernel(kernel_name) + if kernel is None: + return None + return adapter(kernel, *args, **kwargs) + + +_KERNEL_DEVICE_TYPE = "cuda" + + +@register_processing_kernel("connected_component_areas", kernel_name="cv-utils") +def _connected_component_areas_kernel(kernel, regions): + """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" + if regions.device.type != _KERNEL_DEVICE_TYPE: + return None + height, width = regions.shape[-2:] + padded_regions = torch.nn.functional.pad(regions.to(torch.uint8), (0, width % 2, 0, height % 2)) + _, areas = kernel.cc_2d(padded_regions.contiguous(), get_counts=True) + return areas[..., :height, :width] + + +_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} + + +def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std): + """Interpolation and per-channel stats for the resize kernels, `None` when they cannot process these inputs.""" + if not images or any( + not isinstance(image, torch.Tensor) + or image.ndim != 3 + or image.dtype != torch.uint8 + or image.device != images[0].device + or image.shape[0] != images[0].shape[0] + for image in images + ): + return None + interpolation = _KERNEL_INTERPOLATIONS.get(resample) + channels = images[0].shape[0] + image_mean = [image_mean] * channels if isinstance(image_mean, (int, float)) else list(image_mean) + image_std = [image_std] * channels if isinstance(image_std, (int, float)) else list(image_std) + if images[0].device.type != _KERNEL_DEVICE_TYPE or interpolation is None or len(image_mean) != channels: + return None + return interpolation, image_mean, image_std, rescale_factor + + +@register_processing_kernel("resize_normalize", kernel_name="cv-utils") +def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): + """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" + arguments = _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std) + if arguments is None: + return None + interpolation, image_mean, image_std, rescale_factor = arguments + crop = (crop_size.height, crop_size.width) if crop_size is not None else None + if crop is not None and not all(crop): + return None + if size.height and size.width: + if crop is not None and (crop[0] > size.height or crop[1] > size.width): + return None + resize, resize_mode = (size.height, size.width), "square" + elif size.shortest_edge and not size.longest_edge and crop is not None and size.shortest_edge >= max(crop): + resize, resize_mode = size.shortest_edge, "shortest_edge" + else: + return None + return kernel.resize_normalize( + images, + resize, + image_mean, + image_std, + rescale_factor=rescale_factor, + resample=interpolation, + antialias=True, + crop_size=crop, + resize_mode=resize_mode, + round_to_uint8=True, + ) + + +@register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") +def _resize_normalize_patchify_kernel( + kernel, + frames, + target_sizes, + items, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, +): + """Resize every frame to its target size, normalize, and write the flattened patches of every item in order.""" + arguments = _resize_kernel_arguments(frames, resample, rescale_factor, image_mean, image_std) + if arguments is None: + return None + interpolation, image_mean, image_std, rescale_factor = arguments + return kernel.resize_normalize_patchify( + frames, + target_sizes, + items, + image_mean, + image_std, + rescale_factor, + interpolation, + True, + patch_size, + merge_size, + temporal_patch_size, + round_to_uint8=True, + ) 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 8381dee3bb1a..cd0c96ad1d05 100644 --- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py @@ -29,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring 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 e6ac85dd1c30..e83654b92e3a 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -26,7 +26,7 @@ from ...image_processing_utils import BatchFeature from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor 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 1bbb1c762f82..4aa2b5fd93e6 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,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, logging 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 7552033a77ab..c51c9d714a99 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -29,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring 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 45881b235487..5fec741fe1bb 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -29,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index 62ba01d787c2..4d3db51a6701 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -30,7 +30,7 @@ from ...image_processing_backends import PilBackend, TorchvisionBackend from ...image_utils import PILImageResampling, SizeDict from ...integrations import use_kernel_forward_from_hub -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast from ...modeling_utils import ALL_ATTENTION_FUNCTIONS 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 fb6490bfd1b8..381ee41dd588 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,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring 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 31f0f1fa2ab3..493bd046574c 100644 --- a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py @@ -34,7 +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_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index 9292fd2c6c7f..e01fa5674146 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -27,7 +27,7 @@ from ... import initialization as init from ...activations import GELUActivation from ...cache_utils import Cache, DynamicCache -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...masking_utils import create_bidirectional_mask, create_causal_mask from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_utils import PreTrainedModel 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 ebc0d07c8ba3..37d2b85dff98 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -35,7 +35,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring 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 50f29c8cc449..d1c34a615bdd 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -31,7 +31,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, logging from ...video_processing_utils import BaseVideoProcessor 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 fa37ed4fee1d..665570fe36f1 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -25,7 +25,7 @@ from ...image_processing_utils import BatchFeature from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, auto_docstring, is_torchvision_available, logging from ...video_processing_utils import BaseVideoProcessor diff --git a/src/transformers/models/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index 880ea70d3823..8d9e8c8e50ed 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,7 +37,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available, logging diff --git a/src/transformers/models/sam2/modular_sam2.py b/src/transformers/models/sam2/modular_sam2.py index 21c50c4eee14..53c38250c306 100644 --- a/src/transformers/models/sam2/modular_sam2.py +++ b/src/transformers/models/sam2/modular_sam2.py @@ -34,7 +34,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel diff --git a/src/transformers/models/sam3/image_processing_sam3.py b/src/transformers/models/sam3/image_processing_sam3.py index bbdf6a7fd5aa..a0d335eadd31 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,7 +40,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available, logging 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 081bd1cbc931..ca26f3334459 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 @@ -28,7 +28,7 @@ from ...image_processing_backends import TorchvisionBackend from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageInput, PILImageResampling, SizeDict -from ...integrations.hub_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 8aada8d37025..6bc0d099e5df 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -44,23 +44,23 @@ Sam2ImageProcessor, ViTImageProcessor, ) -from transformers.image_processing_backends import ( - TorchvisionBackend, - _connected_component_areas_kernel, - _resize_normalize_kernel, - _resize_normalize_patchify_kernel, -) +from transformers.image_processing_backends import TorchvisionBackend from transformers.image_utils import PILImageResampling, SizeDict, load_image from transformers.integrations.hub_kernels import ( _HUB_KERNEL_MAPPING, _KERNEL_MODULE_MAPPING, - _PROCESSING_KERNEL_ADAPTERS, is_kernel, lazy_load_kernel, load_and_register_attn_kernel, - run_processing_kernel, use_kernel_func_from_hub_with_fallback, ) +from transformers.integrations.hub_processing_kernels import ( + _PROCESSING_KERNEL_ADAPTERS, + _connected_component_areas_kernel, + _resize_normalize_kernel, + _resize_normalize_patchify_kernel, + run_processing_kernel, +) from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS from transformers.monkey_patching import clear_patch_mapping, get_patch_mapping, register_patch_mapping @@ -1037,14 +1037,14 @@ def test_run_processing_kernel_calls_adapter(self): with ( patch.object(torch.cuda, "is_available", return_value=True), patch.dict( - run_processing_kernel.__globals__, - { - "_kernels_enabled": True, - "_PROCESSING_KERNEL_ADAPTERS": { - "dummy_op": ("dummy-kernel", lambda kernel, value: (kernel, value)) - }, - "lazy_load_kernel": {"dummy-kernel": sentinel}.get, - }, + _PROCESSING_KERNEL_ADAPTERS, + {"dummy_op": ("dummy-kernel", lambda kernel, value: (kernel, value))}, + clear=True, + ), + patch.multiple( + "transformers.integrations.hub_kernels", + _kernels_enabled=True, + lazy_load_kernel={"dummy-kernel": sentinel}.get, ), ): self.assertEqual(run_processing_kernel("dummy_op", 3), (sentinel, 3)) @@ -1054,14 +1054,14 @@ def test_run_processing_kernel_falls_back(self): with patch.object(torch.cuda, "is_available", return_value=True): # Unknown op, `USE_HUB_KERNELS=0`, and a kernel that cannot be loaded all keep the default path. self.assertIsNone(run_processing_kernel("not_a_registered_op")) - with patch.dict(run_processing_kernel.__globals__, {"_kernels_enabled": False}): + with patch("transformers.integrations.hub_kernels._kernels_enabled", False): self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) - with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": lambda name: None}): + with patch("transformers.integrations.hub_kernels.lazy_load_kernel", lambda name: None): self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) def test_run_processing_kernel_needs_accelerator(self): with patch.object(torch.cuda, "is_available", return_value=False): - with patch.dict(run_processing_kernel.__globals__, {"lazy_load_kernel": self.fail}): + with patch("transformers.integrations.hub_kernels.lazy_load_kernel", self.fail): self.assertIsNone(run_processing_kernel("connected_component_areas", self.mask_logits > 0)) def test_connected_component_areas_adapter_pads_to_even_size(self): @@ -1069,7 +1069,7 @@ def test_connected_component_areas_adapter_pads_to_even_size(self): regions = torch.zeros(2, 1, 5, 7, dtype=torch.bool) regions[:, :, 1:3, 1:4] = True # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): areas = _connected_component_areas_kernel(kernel, regions) self.assertEqual(tuple(kernel.inputs[0].shape), (2, 1, 6, 8)) self.assertEqual(kernel.inputs[0].dtype, torch.uint8) @@ -1113,7 +1113,7 @@ def run_resize_adapter(self, images=None, **overrides): images = ( [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] if images is None else images ) - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): result = _resize_normalize_kernel(kernel, images, **{**arguments, **overrides}) return kernel, result @@ -1170,7 +1170,7 @@ def test_resize_adapter_falls_back(self): def test_patchify_adapter_translates_arguments(self): kernel = MagicMock() frames = [torch.zeros(3, 30, 40, dtype=torch.uint8), torch.zeros(3, 20, 20, dtype=torch.uint8)] - with patch("transformers.image_processing_backends._KERNEL_DEVICE_TYPE", "cpu"): + with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): result = _resize_normalize_patchify_kernel( kernel, frames, [(28, 28), (28, 28)], [[0], [1]], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 ) @@ -1216,13 +1216,11 @@ def test_qwen2_vl_video_groups_frames_per_video(self): def test_processor_overriding_resize_does_not_use_the_resize_kernel(self): with ( patch.object(torch.cuda, "is_available", return_value=True), - patch.dict( - run_processing_kernel.__globals__, - { - "_kernels_enabled": True, - "_PROCESSING_KERNEL_ADAPTERS": {"resize_normalize": ("cv-utils", self.fail)}, - "lazy_load_kernel": lambda name: types.ModuleType("sentinel_kernel_module"), - }, + patch.dict(_PROCESSING_KERNEL_ADAPTERS, {"resize_normalize": ("cv-utils", self.fail)}, clear=True), + patch.multiple( + "transformers.integrations.hub_kernels", + _kernels_enabled=True, + lazy_load_kernel=lambda name: types.ModuleType("sentinel_kernel_module"), ), ): output = LevitImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) @@ -1232,9 +1230,12 @@ def test_processors_reaching_the_patchify_kernel_use_its_layout(self): processor_classes = processors_calling_the_patchify_kernel() for processor_class in (Qwen2VLImageProcessor, PaddleOCRVLImageProcessor, HunYuanVLImageProcessor): self.assertIn(processor_class, processor_classes) - for processor_class in processor_classes: - with self.subTest(processor_class=processor_class.__name__): - processor = processor_class(use_kernels=True) + qwen3_vl_image_settings = {"patch_size": 16, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5]} + cases = [(processor_class, {}) for processor_class in processor_classes] + cases.append((Qwen2VLImageProcessor, qwen3_vl_image_settings)) + for processor_class, settings in cases: + with self.subTest(processor_class=processor_class.__name__, **settings): + processor = processor_class(use_kernels=True, **settings) is_video = issubclass(processor_class, BaseVideoProcessor) recorded_arguments = [] @@ -1249,17 +1250,19 @@ def run(height, width): with ( patch.object(torch.cuda, "is_available", return_value=True), patch.dict( - run_processing_kernel.__globals__, + _PROCESSING_KERNEL_ADAPTERS, { - "_kernels_enabled": True, - "_PROCESSING_KERNEL_ADAPTERS": { - "resize_normalize_patchify": ( - "cv-utils", - lambda kernel, *arguments: recorded_arguments.append(arguments), - ) - }, - "lazy_load_kernel": lambda name: types.ModuleType("sentinel_kernel_module"), + "resize_normalize_patchify": ( + "cv-utils", + lambda kernel, *arguments: recorded_arguments.append(arguments), + ) }, + clear=True, + ), + patch.multiple( + "transformers.integrations.hub_kernels", + _kernels_enabled=True, + lazy_load_kernel=lambda name: types.ModuleType("sentinel_kernel_module"), ), ): height, width = 112, 168 From df47109b0e40caead28754c52921f73e200d7e7a Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 9 Oct 2026 14:16:46 +0200 Subject: [PATCH 14/26] overhaul again registering and usage --- docs/source/en/kernel_doc/loading_kernels.md | 32 ++- src/transformers/image_processing_backends.py | 28 +- .../integrations/hub_processing_kernels.py | 242 +++++++++++++++--- .../image_processing_cohere_compass.py | 61 +---- .../video_processing_cohere_compass.py | 39 +-- .../image_processing_ernie4_5_vl_moe.py | 61 +---- .../glm_image/image_processing_glm_image.py | 61 +---- .../hunyuan_vl/image_processing_hunyuan_vl.py | 66 +---- .../models/hunyuan_vl/modular_hunyuan_vl.py | 46 +--- .../image_processing_minimax_m3_vl.py | 61 +---- .../image_processing_paddleocr_vl.py | 71 +---- .../paddleocr_vl/modular_paddleocr_vl.py | 41 +-- .../qwen2_vl/image_processing_qwen2_vl.py | 61 +---- .../qwen2_vl/video_processing_qwen2_vl.py | 39 +-- .../qwen3_vl/video_processing_qwen3_vl.py | 39 +-- .../image_processing_video_llama_3.py | 38 --- .../video_llama_3/modular_video_llama_3.py | 6 + .../video_processing_video_llama_3.py | 14 - tests/kernels/test_kernels.py | 53 ++-- 19 files changed, 318 insertions(+), 741 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 0cd973299084..9edf1f126931 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -335,13 +335,15 @@ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kerne inputs = processor(text=prompt, images=images, return_tensors="pt", device="cuda") ``` -For vision-language models the flag passes through [`AutoProcessor`] to the image and video processors. Kernels run on the device the inputs are already on, so pass `device="cuda"` to the processor call. The processor uses its default implementation when there is no CUDA device, when the kernel fails to load, when the inputs are on CPU, or when the kernel does not support the requested arguments. +[`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. -The resize kernels round to `uint8` after each pass, like the default torchvision path, so outputs differ from it by at most one `uint8` level on natural images. +The resize kernels 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. -### Registering a processing kernel +### Adding a processing kernel -Processing operations have no shared signature to swap, so a kernel is plugged in through an adapter instead of a `kernelize` pass. Adapters live in `integrations/hub_processing_kernels.py`. `register_processing_kernel` maps an operation name to a kernel of `_HUB_KERNEL_MAPPING` in `integrations/hub_kernels.py`, and the decorated adapter receives the loaded kernel module followed by the arguments of the operation. Return `None` for arguments the kernel cannot handle, and the caller keeps its default implementation. +A processing kernel has two levels in `integrations/hub_processing_kernels.py`. + +`register_processing_kernel` maps an operation to a kernel of `_HUB_KERNEL_MAPPING`. The adapter receives the loaded kernel module and the arguments of the operation. It translates them to the kernel call and returns `None` for arguments the kernel cannot handle. ```py from transformers.integrations.hub_processing_kernels import register_processing_kernel @@ -354,7 +356,27 @@ def my_op_kernel(kernel, images): return kernel.my_op(images) ``` -The processor calls `run_processing_kernel("my_op", images)` and uses its default implementation when the result is `None`. The kernel is downloaded on the first call that reaches it, and only when a CUDA device is available. +`use_processing_kernel` connects a processor to it. It decorates `_preprocess` with a function that receives the processor, the named arguments of `_preprocess` and the options of the decorator. That function owns everything the kernel needs, such as the target sizes and the output `BatchFeature`, so the processor code does not change. When `use_kernels=True` and the function returns a result, `_preprocess` returns it. Otherwise `_preprocess` runs as usual. + +```py +from transformers import BatchFeature, TorchvisionBackend +from transformers.integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel + + +def my_op_with_kernel(processor, images, return_tensors, **kwargs): + pixel_values = run_processing_kernel("my_op", images) + if pixel_values is None: + return None + return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) + + +class MyImageProcessor(TorchvisionBackend): + @use_processing_kernel(my_op_with_kernel) + def _preprocess(self, images, return_tensors, **kwargs): + ... +``` + +Subclasses that keep `_preprocess` keep the kernel. In a modular file, a model passes its own options by redefining `_preprocess` with the decorator and a call to `super()._preprocess(**super_kwargs)`. A model that replaces `_preprocess` with a different pipeline marks it with `@no_inherit_decorator`. ## Troubleshooting diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 78ada52957ff..dc1c05dcb93f 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,7 +53,7 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_processing_kernels import run_processing_kernel +from .integrations.hub_processing_kernels import resize_normalize_with_kernel, use_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -71,7 +71,6 @@ if is_torch_available(): import torch - if is_torchvision_available(): from torchvision.transforms.v2 import functional as tvF @@ -370,6 +369,7 @@ 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, default_methods_of="TorchvisionBackend") def _preprocess( self, images: list["torch.Tensor"], @@ -390,30 +390,6 @@ def _preprocess( **kwargs, ) -> BatchFeature: """Preprocess using Torchvision backend (fast, GPU-accelerated).""" - kernel_replaces_default_methods = all( - getattr(type(self), name) is getattr(TorchvisionBackend, name) - for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") - ) - if ( - self.use_kernels - and kernel_replaces_default_methods - and do_resize - and do_rescale - and do_normalize - and not do_pad - ): - pixel_values = run_processing_kernel( - "resize_normalize", - images, - size, - crop_size if do_center_crop else None, - resample, - rescale_factor, - image_mean, - image_std, - ) - if pixel_values is not None: - return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=return_tensors) # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py index a764d6a4a0ea..d8bf2f0cdb07 100644 --- a/src/transformers/integrations/hub_processing_kernels.py +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -11,8 +11,11 @@ # 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 ..feature_extraction_utils import BatchFeature from ..utils.import_utils import is_torch_available @@ -62,17 +65,14 @@ def _connected_component_areas_kernel(kernel, regions): """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" if regions.device.type != _KERNEL_DEVICE_TYPE: return None - height, width = regions.shape[-2:] - padded_regions = torch.nn.functional.pad(regions.to(torch.uint8), (0, width % 2, 0, height % 2)) - _, areas = kernel.cc_2d(padded_regions.contiguous(), get_counts=True) - return areas[..., :height, :width] + return kernel.connected_component_areas(regions) _KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} -def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std): - """Interpolation and per-channel stats for the resize kernels, `None` when they cannot process these inputs.""" +def _kernel_interpolation(images, resample): + """Interpolation of the resize kernels for `resample`, `None` when they cannot process these images.""" if not images or any( not isinstance(image, torch.Tensor) or image.ndim != 3 @@ -82,44 +82,30 @@ def _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image for image in images ): return None - interpolation = _KERNEL_INTERPOLATIONS.get(resample) - channels = images[0].shape[0] - image_mean = [image_mean] * channels if isinstance(image_mean, (int, float)) else list(image_mean) - image_std = [image_std] * channels if isinstance(image_std, (int, float)) else list(image_std) - if images[0].device.type != _KERNEL_DEVICE_TYPE or interpolation is None or len(image_mean) != channels: + if images[0].device.type != _KERNEL_DEVICE_TYPE: return None - return interpolation, image_mean, image_std, rescale_factor + return _KERNEL_INTERPOLATIONS.get(resample) @register_processing_kernel("resize_normalize", kernel_name="cv-utils") def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" - arguments = _resize_kernel_arguments(images, resample, rescale_factor, image_mean, image_std) - if arguments is None: + interpolation = _kernel_interpolation(images, resample) + if interpolation is None: return None - interpolation, image_mean, image_std, rescale_factor = arguments crop = (crop_size.height, crop_size.width) if crop_size is not None else None if crop is not None and not all(crop): return None if size.height and size.width: if crop is not None and (crop[0] > size.height or crop[1] > size.width): return None - resize, resize_mode = (size.height, size.width), "square" + resize = {"size": (size.height, size.width)} elif size.shortest_edge and not size.longest_edge and crop is not None and size.shortest_edge >= max(crop): - resize, resize_mode = size.shortest_edge, "shortest_edge" + resize = {"shortest_edge": size.shortest_edge} else: return None return kernel.resize_normalize( - images, - resize, - image_mean, - image_std, - rescale_factor=rescale_factor, - resample=interpolation, - antialias=True, - crop_size=crop, - resize_mode=resize_mode, - round_to_uint8=True, + images, image_mean, image_std, rescale_factor, interpolation, crop_size=crop, **resize ) @@ -128,7 +114,6 @@ def _resize_normalize_patchify_kernel( kernel, frames, target_sizes, - items, resample, rescale_factor, image_mean, @@ -136,23 +121,212 @@ def _resize_normalize_patchify_kernel( patch_size, merge_size, temporal_patch_size, + items=None, ): """Resize every frame to its target size, normalize, and write the flattened patches of every item in order.""" - arguments = _resize_kernel_arguments(frames, resample, rescale_factor, image_mean, image_std) - if arguments is None: + interpolation = _kernel_interpolation(frames, resample) + if interpolation is None: return None - interpolation, image_mean, image_std, rescale_factor = arguments return kernel.resize_normalize_patchify( frames, target_sizes, - items, image_mean, image_std, rescale_factor, interpolation, - True, patch_size, merge_size, temporal_patch_size, - round_to_uint8=True, + items=items, + ) + + +def use_processing_kernel(preprocess_with_kernel: Callable, **options): + """ + Decorate the `_preprocess` method of a processor so that `use_kernels=True` first runs `preprocess_with_kernel`. + + `preprocess_with_kernel` receives the processor, the named arguments of `_preprocess` and `options`. It returns + the `BatchFeature` computed by a kernel, or `None` to keep the decorated implementation. + """ + + def decorator(preprocess: Callable) -> Callable: + signature = inspect.signature(preprocess) + + @wraps(preprocess) + def wrapper(self, *args, **kwargs): + if self.use_kernels: + arguments = signature.bind(self, *args, **kwargs) + arguments.apply_defaults() + named_arguments = dict(arguments.arguments) + named_arguments.pop("self") + named_arguments.update(named_arguments.pop("kwargs", {})) + output = preprocess_with_kernel(self, **named_arguments, **options) + if output is not None: + return output + return preprocess(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, + default_methods_of, + **kwargs, +): + """ + `pixel_values` of the default torchvision pipeline, computed by one `resize_normalize` kernel call. + + Processors that override a step of the pipeline of the class named `default_methods_of` keep their own path. + """ + default_class = next(cls for cls in type(processor).__mro__ if cls.__name__ == default_methods_of) + uses_default_resize_and_normalize = all( + getattr(type(processor), name) is getattr(default_class, name) + for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") + ) + if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): + return None + pixel_values = run_processing_kernel( + "resize_normalize", + images, + size, + crop_size if do_center_crop else None, + resample, + rescale_factor, + image_mean, + image_std, + ) + if pixel_values is None: + return None + return BatchFeature(data={"pixel_values": list(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, + compute_resized_height_and_width, + merge_patches=True, + flatten_patches=True, + forced_resample=None, + **kwargs, +): + """ + `pixel_values` and `image_grid_thw` of the Qwen2-VL image pipeline, computed by one kernel call for the batch. + + `compute_resized_height_and_width` is the size rule of the processor, its `smart_resize`, called on every image. `merge_patches=False` writes patches row by row instead of + in `merge_size` blocks, `flatten_patches=False` returns them as `(C * T, P, P)` blocks, and `forced_resample` + replaces `resample` for processors whose `resize` ignores it. + """ + if not (do_resize and do_rescale and do_normalize): + return None + target_sizes = [ + compute_resized_height_and_width( + image.shape[-2], + image.shape[-1], + factor=patch_size * merge_size, + min_pixels=size.shortest_edge, + max_pixels=size.longest_edge, + ) + for image in images + ] + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + images, + target_sizes, + resample if forced_resample is None else forced_resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size if merge_patches else 1, + temporal_patch_size, + ) + if kernel_output is None: + return None + pixel_values, image_grid_thw = kernel_output + if not flatten_patches: + 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, + return_tensors, + **kwargs, +): + """`pixel_values_videos` and `video_grid_thw` of the Qwen2-VL video pipeline, one kernel call for all frames.""" + if not (do_resize and do_rescale and do_normalize): + return None + frames, target_sizes, items = [], [], [] + for video in videos: + target_size = processor._resized_size( + *video.shape[-2:], + video.shape[0], + size, + patch_size * merge_size, + temporal_patch_size, + bool(cap_pixels_per_frame), + ) + items.append(list(range(len(frames), len(frames) + video.shape[0]))) + frames.extend(video) + target_sizes.extend([target_size] * video.shape[0]) + kernel_output = run_processing_kernel( + "resize_normalize_patchify", + frames, + target_sizes, + resample, + rescale_factor, + image_mean, + image_std, + patch_size, + merge_size, + temporal_patch_size, + items=items, + ) + if kernel_output is None: + return None + pixel_values_videos, video_grid_thw = kernel_output + return BatchFeature( + data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw}, tensor_type=return_tensors ) 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 cd0c96ad1d05..591179acbf15 100644 --- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py @@ -29,7 +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 run_processing_kernel +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 @@ -204,6 +204,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) def _preprocess( self, images: list["torch.Tensor"], @@ -222,27 +223,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -282,43 +262,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 e83654b92e3a..31646ff69a48 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -26,7 +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 run_processing_kernel +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 @@ -264,6 +264,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"], @@ -292,42 +293,6 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False - if self.use_kernels and do_resize and do_rescale and do_normalize: - frames, target_sizes, items = [], [], [] - for video in videos: - target_size = self._resized_size( - *video.shape[-2:], - video.shape[0], - size, - patch_size * merge_size, - temporal_patch_size, - cap_pixels_per_frame, - ) - items.append(list(range(len(frames), len(frames) + video.shape[0]))) - frames.extend(video) - target_sizes.extend([target_size] * video.shape[0]) - kernel_output = run_processing_kernel( - "resize_normalize_patchify", - frames, - target_sizes, - items, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - if kernel_output is not None: - pixel_values_videos, video_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values_videos": pixel_values_videos, - "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} 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 4aa2b5fd93e6..34d79206fb89 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,7 +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 run_processing_kernel +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 @@ -168,6 +168,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) def _preprocess( self, images: list["torch.Tensor"], @@ -186,27 +187,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -246,43 +226,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 c51c9d714a99..19ef4761ed56 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -29,7 +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 run_processing_kernel +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 @@ -216,6 +216,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) def _preprocess( self, images: list["torch.Tensor"], @@ -234,27 +235,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -294,43 +274,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 5fec741fe1bb..3e7432df079c 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -29,7 +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 run_processing_kernel +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 @@ -209,6 +209,12 @@ def patchify( return flatten_patches, grid_h, grid_w + @use_processing_kernel( + resize_normalize_patchify_images_with_kernel, + compute_resized_height_and_width=smart_resize, + merge_patches=False, + forced_resample=PILImageResampling.BICUBIC, + ) def _preprocess( self, images: list["torch.Tensor"], @@ -227,27 +233,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -287,43 +272,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """Row-major patches are the kernel layout with `merge_size=1`, resampled with BICUBIC like `resize`.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - PILImageResampling.BICUBIC, - rescale_factor, - image_mean, - image_std, - patch_size, - 1, - temporal_patch_size, - ) - def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None ) -> tuple[int, int]: diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index 3b8a5f7e443a..cd530a4d1e2a 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -30,7 +30,7 @@ from ...image_processing_backends import PilBackend, TorchvisionBackend from ...image_utils import PILImageResampling, SizeDict from ...integrations import use_kernel_forward_from_hub -from ...integrations.hub_processing_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast from ...modeling_utils import ALL_ATTENTION_FUNCTIONS @@ -411,42 +411,14 @@ def patchify( return flatten_patches, grid_h, grid_w - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """Row-major patches are the kernel layout with `merge_size=1`, resampled with BICUBIC like `resize`.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - PILImageResampling.BICUBIC, - rescale_factor, - image_mean, - image_std, - patch_size, - 1, - temporal_patch_size, - ) + @use_processing_kernel( + resize_normalize_patchify_images_with_kernel, + compute_resized_height_and_width=smart_resize, + merge_patches=False, + forced_resample=PILImageResampling.BICUBIC, + ) + def _preprocess(self, **super_kwargs): + return super()._preprocess(**super_kwargs) def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None 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 381ee41dd588..a9d1fd223f19 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,7 +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 run_processing_kernel +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 @@ -208,6 +208,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) def _preprocess( self, images: list["torch.Tensor"], @@ -226,27 +227,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -286,43 +266,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 493bd046574c..a8794d719571 100644 --- a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py @@ -34,7 +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 run_processing_kernel +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 @@ -212,6 +212,12 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel( + resize_normalize_patchify_images_with_kernel, + compute_resized_height_and_width=smart_resize, + merge_patches=False, + flatten_patches=False, + ) def _preprocess( self, images: list["torch.Tensor"], @@ -230,27 +236,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -290,48 +275,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """Row by row patches are the kernel layout with `merge_size=1`, viewed as `(C * T, P, P)` blocks.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - kernel_output = run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - 1, - temporal_patch_size, - ) - if kernel_output is None: - return None - pixel_values, image_grid_thw = kernel_output - channels = images[0].shape[0] - return pixel_values.view(-1, channels * temporal_patch_size, patch_size, patch_size), image_grid_thw - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index 92c8b9200b6f..920c4f25ec0d 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -28,7 +28,7 @@ from ...activations import GELUActivation from ...cache_utils import Cache, DynamicCache from ...configuration_utils import SubConfigSpec -from ...integrations.hub_processing_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...masking_utils import create_bidirectional_mask, create_causal_mask from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_utils import PreTrainedModel @@ -215,37 +215,14 @@ def patchify( ) return flatten_patches, grid_h, grid_w - def _resize_normalize_patchify_kernel( - self, - images, - target_sizes, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """Row by row patches are the kernel layout with `merge_size=1`, viewed as `(C * T, P, P)` blocks.""" - kernel_output = run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - 1, - temporal_patch_size, - ) - if kernel_output is None: - return None - pixel_values, image_grid_thw = kernel_output - channels = images[0].shape[0] - return pixel_values.view(-1, channels * temporal_patch_size, patch_size, patch_size), image_grid_thw + @use_processing_kernel( + resize_normalize_patchify_images_with_kernel, + compute_resized_height_and_width=smart_resize, + merge_patches=False, + flatten_patches=False, + ) + def _preprocess(self, **super_kwargs): + return super()._preprocess(**super_kwargs) class PaddleOCRVLProcessorKwargs(ProcessingKwargs, total=False): 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 37d2b85dff98..2b3543a288a7 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -35,7 +35,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +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 @@ -210,6 +210,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w + @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) def _preprocess( self, images: list["torch.Tensor"], @@ -228,27 +229,6 @@ def _preprocess( return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: - if self.use_kernels and do_resize and do_rescale and do_normalize: - kernel_output = self._resize_normalize_patchify_kernel( - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ) - if kernel_output is not None: - pixel_values, image_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values": pixel_values, - "image_grid_thw": torch.tensor(image_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): @@ -288,43 +268,6 @@ def _preprocess( data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 d1c34a615bdd..573d216601b1 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -31,7 +31,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +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 @@ -310,6 +310,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"], @@ -338,42 +339,6 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False - if self.use_kernels and do_resize and do_rescale and do_normalize: - frames, target_sizes, items = [], [], [] - for video in videos: - target_size = self._resized_size( - *video.shape[-2:], - video.shape[0], - size, - patch_size * merge_size, - temporal_patch_size, - cap_pixels_per_frame, - ) - items.append(list(range(len(frames), len(frames) + video.shape[0]))) - frames.extend(video) - target_sizes.extend([target_size] * video.shape[0]) - kernel_output = run_processing_kernel( - "resize_normalize_patchify", - frames, - target_sizes, - items, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - if kernel_output is not None: - pixel_values_videos, video_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values_videos": pixel_values_videos, - "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} 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 665570fe36f1..3e2c49a3b0bf 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -25,7 +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 run_processing_kernel +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 @@ -267,6 +267,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"], @@ -295,42 +296,6 @@ def _preprocess( "warning." ) cap_pixels_per_frame = False - if self.use_kernels and do_resize and do_rescale and do_normalize: - frames, target_sizes, items = [], [], [] - for video in videos: - target_size = self._resized_size( - *video.shape[-2:], - video.shape[0], - size, - patch_size * merge_size, - temporal_patch_size, - cap_pixels_per_frame, - ) - items.append(list(range(len(frames), len(frames) + video.shape[0]))) - frames.extend(video) - target_sizes.extend([target_size] * video.shape[0]) - kernel_output = run_processing_kernel( - "resize_normalize_patchify", - frames, - target_sizes, - items, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - if kernel_output is not None: - pixel_values_videos, video_grid_thw = kernel_output - return BatchFeature( - data={ - "pixel_values_videos": pixel_values_videos, - "video_grid_thw": torch.tensor(video_grid_thw, dtype=torch.long), - }, - tensor_type=return_tensors, - ) # Group videos by size for batched resizing grouped_videos, grouped_videos_index = group_videos_by_shape(videos) resized_videos_grouped = {} 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 ca26f3334459..dd84527623a1 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 @@ -28,7 +28,6 @@ from ...image_processing_backends import TorchvisionBackend from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageInput, PILImageResampling, SizeDict -from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring @@ -274,43 +273,6 @@ def _preprocess( tensor_type=return_tensors, ) - def _resize_normalize_patchify_kernel( - self, - images, - size, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - temporal_patch_size, - merge_size, - ): - """`(pixel_values, image_grid_thw)` computed by one kernel call for the whole batch, `None` when it cannot run.""" - target_sizes = [ - smart_resize( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, - ) - for image in images - ] - return run_processing_kernel( - "resize_normalize_patchify", - images, - target_sizes, - [[index] for index in range(len(images))], - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - merge_size, - temporal_patch_size, - ) - def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ A utility that returns number of image patches for a given image size. 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 5774cfc7795e..b57047cb66e0 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 @@ -845,6 +846,7 @@ class VideoLlama3ImageProcessor(Qwen2VLImageProcessor): "image_merge_sizes", ] + @no_inherit_decorator def _preprocess( self, images: list["torch.Tensor"], @@ -1027,6 +1029,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/models/video_llama_3/video_processing_video_llama_3.py b/src/transformers/models/video_llama_3/video_processing_video_llama_3.py index f2ee3c7503c0..032bd9f9ea42 100644 --- a/src/transformers/models/video_llama_3/video_processing_video_llama_3.py +++ b/src/transformers/models/video_llama_3/video_processing_video_llama_3.py @@ -240,20 +240,6 @@ def resize( resample=resample, ) - def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): - """Frame size a video of `num_frames` frames of `height` x `width` pixels is resized to.""" - 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` - total_pixels = int(self.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) - ) - return smart_resize(height, width, factor=factor, min_pixels=size.shortest_edge, max_pixels=max_pixels) - def patchify( self, videos: "torch.Tensor", diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 6bc0d099e5df..1b5c0295dfad 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -1000,14 +1000,14 @@ def processors_calling_the_patchify_kernel(): class ReferenceConnectedComponentsKernel: - """Stand-in for `kernels-community/cv-utils`: records the input of `cc_2d` and answers with the reference.""" + """Stand-in for `kernels-community/cv-utils`: records the input of `connected_component_areas`, answers the reference.""" def __init__(self): self.inputs = [] - def cc_2d(self, inputs, get_counts): - self.inputs.append(inputs) - return None, connected_component_areas_reference(inputs.bool()) + def connected_component_areas(self, mask): + self.inputs.append(mask) + return connected_component_areas_reference(mask) class TestProcessingKernels(TestCasePlus): @@ -1064,16 +1064,14 @@ def test_run_processing_kernel_needs_accelerator(self): with patch("transformers.integrations.hub_kernels.lazy_load_kernel", self.fail): self.assertIsNone(run_processing_kernel("connected_component_areas", self.mask_logits > 0)) - def test_connected_component_areas_adapter_pads_to_even_size(self): + def test_connected_component_areas_adapter_calls_the_kernel(self): kernel = ReferenceConnectedComponentsKernel() regions = torch.zeros(2, 1, 5, 7, dtype=torch.bool) regions[:, :, 1:3, 1:4] = True # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): areas = _connected_component_areas_kernel(kernel, regions) - self.assertEqual(tuple(kernel.inputs[0].shape), (2, 1, 6, 8)) - self.assertEqual(kernel.inputs[0].dtype, torch.uint8) - self.assertEqual(tuple(areas.shape), (2, 1, 5, 7)) + self.assertIs(kernel.inputs[0], regions) self.assertTrue(torch.equal(areas, connected_component_areas_reference(regions))) def test_connected_component_areas_adapter_needs_cuda_tensors(self): @@ -1121,17 +1119,15 @@ def test_resize_adapter_translates_arguments(self): kernel, result = self.run_resize_adapter() self.assertIs(result, kernel.resize_normalize.return_value) arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[1:], ((8, 8), [0.5, 0.5, 0.5], [0.5, 0.5, 0.5])) - self.assertEqual(keyword_arguments["resample"], "bicubic") - self.assertEqual(keyword_arguments["resize_mode"], "square") - self.assertTrue(keyword_arguments["round_to_uint8"]) + self.assertEqual(arguments[1:], ([0.5, 0.5, 0.5], [0.5, 0.5, 0.5], 1 / 255, "bicubic")) + self.assertEqual(keyword_arguments, {"crop_size": None, "size": (8, 8)}) kernel, _ = self.run_resize_adapter( size=SizeDict(shortest_edge=8), crop_size=SizeDict(height=6, width=6), image_mean=0.5, image_std=0.5 ) arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[1:], (8, [0.5] * 3, [0.5] * 3)) - self.assertEqual((keyword_arguments["resize_mode"], keyword_arguments["crop_size"]), ("shortest_edge", (6, 6))) + self.assertEqual(arguments[1:3], (0.5, 0.5)) + self.assertEqual(keyword_arguments, {"crop_size": (6, 6), "shortest_edge": 8}) def test_resize_adapter_falls_back(self): unsupported = { @@ -1140,7 +1136,6 @@ def test_resize_adapter_falls_back(self): "empty_crop": {"crop_size": SizeDict()}, "shortest_edge_without_crop": {"size": SizeDict(shortest_edge=8)}, "bounded_resize": {"size": SizeDict(shortest_edge=8, longest_edge=16)}, - "stats_do_not_match_channels": {"image_mean": [0.5, 0.5], "image_std": [0.5, 0.5]}, "float_images": {"images": [torch.rand(3, 40, 60)]}, "mixed_channels": { "images": [torch.zeros(3, 4, 4, dtype=torch.uint8), torch.zeros(1, 4, 4, dtype=torch.uint8)] @@ -1172,21 +1167,19 @@ def test_patchify_adapter_translates_arguments(self): frames = [torch.zeros(3, 30, 40, dtype=torch.uint8), torch.zeros(3, 20, 20, dtype=torch.uint8)] with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): result = _resize_normalize_patchify_kernel( - kernel, frames, [(28, 28), (28, 28)], [[0], [1]], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 + kernel, frames, [(28, 28), (28, 28)], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 ) self.assertIs(result, kernel.resize_normalize_patchify.return_value) arguments, keyword_arguments = kernel.resize_normalize_patchify.call_args - self.assertEqual( - arguments[1:], ([(28, 28), (28, 28)], [[0], [1]], [0.5] * 3, [0.5] * 3, 1 / 255, "bicubic", True, 14, 2, 2) - ) - self.assertTrue(keyword_arguments["round_to_uint8"]) + self.assertEqual(arguments[1:], ([(28, 28), (28, 28)], [0.5] * 3, [0.5] * 3, 1 / 255, "bicubic", 14, 2, 2)) + self.assertEqual(keyword_arguments, {"items": None}) 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) with patch( - "transformers.models.qwen2_vl.image_processing_qwen2_vl.run_processing_kernel", - return_value=(pixel_values, [(1, 4, 6)]), + "transformers.integrations.hub_processing_kernels.run_processing_kernel", + return_value=(pixel_values, torch.tensor([[1, 4, 6]])), ) as run_kernel: output = Qwen2VLImageProcessor(use_kernels=True)(images, return_tensors="pt") Qwen2VLImageProcessor(use_kernels=False)(images, return_tensors="pt") @@ -1201,13 +1194,14 @@ def test_qwen2_vl_video_groups_frames_per_video(self): torch.randint(0, 255, (2, 3, 32, 32), dtype=torch.uint8), ] with patch( - "transformers.models.qwen2_vl.video_processing_qwen2_vl.run_processing_kernel", - return_value=(torch.zeros(1, 1), [(2, 4, 6), (1, 2, 2)]), + "transformers.integrations.hub_processing_kernels.run_processing_kernel", + return_value=(torch.zeros(1, 1), torch.tensor([[2, 4, 6], [1, 2, 2]])), ) as run_kernel: output = Qwen2VLVideoProcessor(use_kernels=True)( videos, do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" ) - frames, target_sizes, items = run_kernel.call_args[0][1:4] + frames, target_sizes = run_kernel.call_args.args[1:3] + items = run_kernel.call_args.kwargs["items"] self.assertEqual(len(frames), 5) self.assertEqual(items, [[0, 1, 2], [3, 4]]) self.assertEqual(len(set(target_sizes[:3])), 1) @@ -1254,7 +1248,14 @@ def run(height, width): { "resize_normalize_patchify": ( "cv-utils", - lambda kernel, *arguments: recorded_arguments.append(arguments), + lambda kernel, frames, target_sizes, *arguments, items=None: recorded_arguments.append( + ( + frames, + target_sizes, + items or [[index] for index in range(len(frames))], + *arguments, + ) + ), ) }, clear=True, From ede482af6a456c254ee2d1a6dbc856c3aaa64935 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 9 Oct 2026 14:19:06 +0200 Subject: [PATCH 15/26] add test to be able to hook kernels to processor --- tests/kernels/test_kernels.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 1b5c0295dfad..b5d8a7d09332 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -15,6 +15,7 @@ # Run the test: CUDA_VISIBLE_DEVICES=0 RUN_SLOW=1 pytest -sv tests/kernels/test_kernels.py +import ast import copy import importlib import inspect @@ -1281,6 +1282,27 @@ def run(height, width): pixel_values.reshape(-1), patchify_kernel_layout_reference(*recorded_arguments[0]).reshape(-1) ) + def test_image_and_video_processors_run_through_preprocess(self): + """`use_processing_kernel` decorates `_preprocess`, so a processor whose entry point skips it never runs a kernel.""" + allowed = {"timm_wrapper.TimmWrapperImageProcessor"} + bypassing = [] + for path in sorted(Path(transformers.__file__).parent.glob("models/*/*_processing_*.py")): + if path.stem.startswith("modular_"): + continue + for node in ast.parse(path.read_text()).body: + if not isinstance(node, ast.ClassDef) or not node.name.endswith( + ("ImageProcessor", "ImageProcessorPil", "VideoProcessor") + ): + continue + for method in node.body: + if not isinstance(method, ast.FunctionDef) or method.name not in ("preprocess", "__call__"): + continue + source = ast.unparse(method) + name = f"{path.parent.name}.{node.name}" + if "_preprocess" not in source and "super()" not in source and name not in allowed: + bypassing.append(f"{name}.{method.name}") + self.assertEqual(bypassing, [], "these processors do not reach `_preprocess`") + def test_use_kernels_is_a_runtime_flag(self): processor = Sam2ImageProcessor(use_kernels=True) self.assertNotIn("use_kernels", processor.to_dict()) From 9d8b67e4b7288c3ad180910a8a153cbd942abb99 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 15 Oct 2026 16:08:45 +0200 Subject: [PATCH 16/26] set use_kernels once --- src/transformers/image_processing_base.py | 4 ++-- src/transformers/video_processing_utils.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/transformers/image_processing_base.py b/src/transformers/image_processing_base.py index 7f825a8b3f98..94267665fe7c 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -389,9 +389,9 @@ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs): return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) use_kernels = kwargs.pop("use_kernels", None) image_processor_dict.update({k: v for k, v in kwargs.items() if k in cls.valid_kwargs.__annotations__}) - image_processor = cls(**image_processor_dict) if use_kernels is not None: - image_processor.use_kernels = use_kernels + 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) extra_keys = [] diff --git a/src/transformers/video_processing_utils.py b/src/transformers/video_processing_utils.py index f949b5de74dd..b4be99430f95 100644 --- a/src/transformers/video_processing_utils.py +++ b/src/transformers/video_processing_utils.py @@ -449,9 +449,9 @@ def from_dict(cls, video_processor_dict: dict[str, Any], **kwargs): return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) use_kernels = kwargs.pop("use_kernels", None) video_processor_dict.update({k: v for k, v in kwargs.items() if k in cls.valid_kwargs.__annotations__}) - video_processor = cls(**video_processor_dict) if use_kernels is not None: - video_processor.use_kernels = use_kernels + 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) extra_keys = [] From aeb80c9a87e2664d3e9fe11d5a0bd42912389e9e Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 15 Oct 2026 16:13:11 +0200 Subject: [PATCH 17/26] kernel API and processors --- src/transformers/image_processing_backends.py | 87 ++++++--- .../integrations/hub_processing_kernels.py | 177 +++++------------- .../image_processing_cohere_compass.py | 23 ++- .../video_processing_cohere_compass.py | 1 + .../image_processing_ernie4_5_vl_moe.py | 23 ++- .../glm_image/image_processing_glm_image.py | 23 ++- .../hunyuan_vl/image_processing_hunyuan_vl.py | 37 ++-- .../image_processing_pil_hunyuan_vl.py | 9 +- .../models/hunyuan_vl/modular_hunyuan_vl.py | 47 ++--- .../image_processing_minimax_m3_vl.py | 23 ++- .../image_processing_paddleocr_vl.py | 28 ++- .../paddleocr_vl/modular_paddleocr_vl.py | 12 +- .../qwen2_vl/image_processing_qwen2_vl.py | 23 ++- .../qwen2_vl/video_processing_qwen2_vl.py | 1 + .../models/qwen3_vl/modular_qwen3_vl.py | 1 + .../qwen3_vl/video_processing_qwen3_vl.py | 1 + .../image_processing_video_llama_3.py | 21 +-- 17 files changed, 236 insertions(+), 301 deletions(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index dc1c05dcb93f..ec7832ed3f5c 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,7 +53,7 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_processing_kernels import resize_normalize_with_kernel, use_processing_kernel +from .integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -83,6 +83,49 @@ logger = logging.get_logger(__name__) +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, computed by one `resize_normalize` kernel call. + + Processors that override a step of the `TorchvisionBackend` pipeline keep their own path. + """ + uses_default_resize_and_normalize = all( + getattr(type(processor), name) is getattr(TorchvisionBackend, name) + for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") + ) + if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): + return None + pixel_values = run_processing_kernel( + "resize_normalize", + images, + [processor._resize_output_size(image, size) for image in images], + crop_size if do_center_crop else None, + resample, + rescale_factor, + image_mean, + image_std, + ) + if pixel_values is None: + return None + return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) + + @requires(backends=("torch", "torchvision")) class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" @@ -231,34 +274,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", @@ -369,7 +408,7 @@ 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, default_methods_of="TorchvisionBackend") + @use_processing_kernel(resize_normalize_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py index d8bf2f0cdb07..bf369f6bb0f2 100644 --- a/src/transformers/integrations/hub_processing_kernels.py +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -26,6 +26,8 @@ _PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} +_KERNEL_DEVICE_TYPE = "cuda" +_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} def register_processing_kernel(name: str, kernel_name: str): @@ -57,9 +59,6 @@ def run_processing_kernel(name: str, *args, **kwargs): return adapter(kernel, *args, **kwargs) -_KERNEL_DEVICE_TYPE = "cuda" - - @register_processing_kernel("connected_component_areas", kernel_name="cv-utils") def _connected_component_areas_kernel(kernel, regions): """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" @@ -68,84 +67,67 @@ def _connected_component_areas_kernel(kernel, regions): return kernel.connected_component_areas(regions) -_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} - - -def _kernel_interpolation(images, resample): - """Interpolation of the resize kernels for `resample`, `None` when they cannot process these images.""" - if not images or any( - not isinstance(image, torch.Tensor) - or image.ndim != 3 - or image.dtype != torch.uint8 - or image.device != images[0].device - or image.shape[0] != images[0].shape[0] - for image in images - ): - return None - if images[0].device.type != _KERNEL_DEVICE_TYPE: - return None - return _KERNEL_INTERPOLATIONS.get(resample) +def _kernel_supports(images): + """Whether the resize kernels can process `images` in one launch: uint8, one kernel device, one channel count.""" + return ( + bool(images) + and images[0].device.type == _KERNEL_DEVICE_TYPE + and all( + image.dtype == torch.uint8 and image.device == images[0].device and image.shape[-3] == images[0].shape[-3] + for image in images + ) + ) @register_processing_kernel("resize_normalize", kernel_name="cv-utils") -def _resize_normalize_kernel(kernel, images, size, crop_size, resample, rescale_factor, image_mean, image_std): - """Resize every image to `size`, center crop to `crop_size` when given, then rescale and normalize.""" - interpolation = _kernel_interpolation(images, resample) - if interpolation is None: +def _resize_normalize_kernel(kernel, images, sizes, crop_size, resample, rescale_factor, image_mean, image_std): + """Resize every image to its size in `sizes`, center crop to `crop_size` when given, then rescale and normalize.""" + interpolation = _KERNEL_INTERPOLATIONS.get(resample) + if interpolation is None or not _kernel_supports(images): return None - crop = (crop_size.height, crop_size.width) if crop_size is not None else None - if crop is not None and not all(crop): - return None - if size.height and size.width: - if crop is not None and (crop[0] > size.height or crop[1] > size.width): + crop = None + if crop_size is not None: + crop = (crop_size.height, crop_size.width) + if not all(crop) or any(crop[0] > height or crop[1] > width for height, width in sizes): return None - resize = {"size": (size.height, size.width)} - elif size.shortest_edge and not size.longest_edge and crop is not None and size.shortest_edge >= max(crop): - resize = {"shortest_edge": size.shortest_edge} - else: - return None - return kernel.resize_normalize( - images, image_mean, image_std, rescale_factor, interpolation, crop_size=crop, **resize - ) + return kernel.resize_normalize(images, sizes, image_mean, image_std, rescale_factor, interpolation, crop_size=crop) @register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") def _resize_normalize_patchify_kernel( kernel, - frames, + inputs, target_sizes, resample, rescale_factor, image_mean, image_std, patch_size, - merge_size, + block_size, temporal_patch_size, - items=None, ): - """Resize every frame to its target size, normalize, and write the flattened patches of every item in order.""" - interpolation = _kernel_interpolation(frames, resample) - if interpolation is None: + """Resize every `(T, C, H, W)` input to its target frame size, normalize, and write its flattened patches in order.""" + interpolation = _KERNEL_INTERPOLATIONS.get(resample) + if interpolation is None or not _kernel_supports(inputs): return None return kernel.resize_normalize_patchify( - frames, + inputs, target_sizes, image_mean, image_std, rescale_factor, interpolation, patch_size, - merge_size, + block_size, temporal_patch_size, - items=items, ) -def use_processing_kernel(preprocess_with_kernel: Callable, **options): +def use_processing_kernel(preprocess_with_kernel: Callable): """ Decorate the `_preprocess` method of a processor so that `use_kernels=True` first runs `preprocess_with_kernel`. - `preprocess_with_kernel` receives the processor, the named arguments of `_preprocess` and `options`. It returns + `preprocess_with_kernel` receives the processor and the named arguments of `_preprocess`. It returns the `BatchFeature` computed by a kernel, or `None` to keep the decorated implementation. """ @@ -160,7 +142,7 @@ def wrapper(self, *args, **kwargs): named_arguments = dict(arguments.arguments) named_arguments.pop("self") named_arguments.update(named_arguments.pop("kwargs", {})) - output = preprocess_with_kernel(self, **named_arguments, **options) + output = preprocess_with_kernel(self, **named_arguments) if output is not None: return output return preprocess(self, *args, **kwargs) @@ -170,51 +152,6 @@ def wrapper(self, *args, **kwargs): 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, - default_methods_of, - **kwargs, -): - """ - `pixel_values` of the default torchvision pipeline, computed by one `resize_normalize` kernel call. - - Processors that override a step of the pipeline of the class named `default_methods_of` keep their own path. - """ - default_class = next(cls for cls in type(processor).__mro__ if cls.__name__ == default_methods_of) - uses_default_resize_and_normalize = all( - getattr(type(processor), name) is getattr(default_class, name) - for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") - ) - if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): - return None - pixel_values = run_processing_kernel( - "resize_normalize", - images, - size, - crop_size if do_center_crop else None, - resample, - rescale_factor, - image_mean, - image_std, - ) - if pixel_values is None: - return None - return BatchFeature(data={"pixel_values": list(pixel_values)}, tensor_type=return_tensors) - - def resize_normalize_patchify_images_with_kernel( processor, images, @@ -230,47 +167,39 @@ def resize_normalize_patchify_images_with_kernel( temporal_patch_size, merge_size, return_tensors, - compute_resized_height_and_width, - merge_patches=True, - flatten_patches=True, - forced_resample=None, **kwargs, ): """ `pixel_values` and `image_grid_thw` of the Qwen2-VL image pipeline, computed by one kernel call for the batch. - `compute_resized_height_and_width` is the size rule of the processor, its `smart_resize`, called on every image. `merge_patches=False` writes patches row by row instead of - in `merge_size` blocks, `flatten_patches=False` returns them as `(C * T, P, P)` blocks, and `forced_resample` - replaces `resample` for processors whose `resize` ignores it. + Target sizes come from the `_resized_size` method of the processor. Patches are written in blocks of + `processor.patch_block_size`, `merge_size` when it is `None`, and returned as `(C * T, P, P)` blocks when + `processor.flat_patches` is `False`. """ if not (do_resize and do_rescale and do_normalize): return None target_sizes = [ - compute_resized_height_and_width( - image.shape[-2], - image.shape[-1], - factor=patch_size * merge_size, - min_pixels=size.shortest_edge, - max_pixels=size.longest_edge, + processor._resized_size( + height=image.shape[-2], width=image.shape[-1], size=size, factor=patch_size * merge_size ) for image in images ] kernel_output = run_processing_kernel( "resize_normalize_patchify", - images, + [image[None] for image in images], target_sizes, - resample if forced_resample is None else forced_resample, + resample, rescale_factor, image_mean, image_std, patch_size, - merge_size if merge_patches else 1, + merge_size if processor.patch_block_size is None else processor.patch_block_size, temporal_patch_size, ) if kernel_output is None: return None pixel_values, image_grid_thw = kernel_output - if not flatten_patches: + if not processor.flat_patches: 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 @@ -298,22 +227,21 @@ def resize_normalize_patchify_videos_with_kernel( """`pixel_values_videos` and `video_grid_thw` of the Qwen2-VL video pipeline, one kernel call for all frames.""" if not (do_resize and do_rescale and do_normalize): return None - frames, target_sizes, items = [], [], [] - for video in videos: - target_size = processor._resized_size( - *video.shape[-2:], - video.shape[0], - size, - patch_size * merge_size, - temporal_patch_size, - bool(cap_pixels_per_frame), + 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, ) - items.append(list(range(len(frames), len(frames) + video.shape[0]))) - frames.extend(video) - target_sizes.extend([target_size] * video.shape[0]) + for video in videos + ] kernel_output = run_processing_kernel( "resize_normalize_patchify", - frames, + videos, target_sizes, resample, rescale_factor, @@ -322,7 +250,6 @@ def resize_normalize_patchify_videos_with_kernel( patch_size, merge_size, temporal_patch_size, - items=items, ) if kernel_output is None: return None 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 591179acbf15..a872b8d5dad6 100644 --- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py @@ -98,6 +98,8 @@ class CohereCompassImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 + patch_block_size = None + flat_patches = True valid_kwargs = CohereCompassImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -152,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -204,7 +203,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) + @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 31646ff69a48..a9b8b313b53f 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -204,6 +204,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs 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}.") 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 34d79206fb89..7760fc1f3299 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 @@ -93,6 +93,8 @@ class Ernie4_5_VLMoeImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 2 + patch_block_size = None + flat_patches = True valid_kwargs = Ernie4_5_VLMoeImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -116,23 +118,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -168,7 +167,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) + @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 19ef4761ed56..d196824a7c60 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -110,6 +110,8 @@ class GlmImageImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 + patch_block_size = None + flat_patches = True valid_kwargs = GlmImageImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw", "images_per_sample"] @@ -164,23 +166,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -216,7 +215,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) + @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 3e7432df079c..cb62884388b7 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -99,6 +99,8 @@ class HunYuanVLImageProcessor(TorchvisionBackend): patch_size = 16 temporal_patch_size = 1 merge_size = 2 + patch_block_size = 1 + flat_patches = True valid_kwargs = HunYuanVLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] spatial_patch_size = 1 @@ -114,6 +116,10 @@ def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): size["longest_edge"] = max_pixels size.pop("max_pixels", None) super().__init__(size=size, **kwargs) + # 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. + self.resample = PILImageResampling.BICUBIC def _standardize_kwargs( self, @@ -154,26 +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), - # 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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,12 +209,7 @@ def patchify( return flatten_patches, grid_h, grid_w - @use_processing_kernel( - resize_normalize_patchify_images_with_kernel, - compute_resized_height_and_width=smart_resize, - merge_patches=False, - forced_resample=PILImageResampling.BICUBIC, - ) + @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_pil_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/image_processing_pil_hunyuan_vl.py index 60239ead6a3a..d38a070ea571 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 @@ -114,6 +114,10 @@ def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): size["longest_edge"] = max_pixels size.pop("max_pixels", None) super().__init__(size=size, **kwargs) + # 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. + self.resample = PILImageResampling.BICUBIC def _standardize_kwargs( self, @@ -160,10 +164,7 @@ def resize( return super().resize( image=image, 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 patchify( diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index cd530a4d1e2a..6317f36ed900 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -30,7 +30,6 @@ from ...image_processing_backends import PilBackend, TorchvisionBackend from ...image_utils import PILImageResampling, SizeDict from ...integrations import use_kernel_forward_from_hub -from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...masking_utils import create_causal_mask from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast from ...modeling_utils import ALL_ATTENTION_FUNCTIONS @@ -344,8 +343,16 @@ class HunYuanVLImageProcessor(Qwen2VLImageProcessor): temporal_patch_size = 1 merge_size = 2 spatial_patch_size = 1 + patch_block_size = 1 valid_kwargs = HunYuanVLImageProcessorKwargs + def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): + super().__init__(**kwargs) + # 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. + self.resample = PILImageResampling.BICUBIC + def resize( self, images: "torch.Tensor", @@ -355,25 +362,12 @@ 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 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, + resample=resample, ) def patchify( @@ -411,15 +405,6 @@ def patchify( return flatten_patches, grid_h, grid_w - @use_processing_kernel( - resize_normalize_patchify_images_with_kernel, - compute_resized_height_and_width=smart_resize, - merge_patches=False, - forced_resample=PILImageResampling.BICUBIC, - ) - def _preprocess(self, **super_kwargs): - return super()._preprocess(**super_kwargs) - def get_number_of_image_patches( self, height: int, width: int, images_kwargs: dict | None = None ) -> tuple[int, int]: @@ -462,6 +447,13 @@ class HunYuanVLImageProcessorPil(Qwen2VLImageProcessorPil): spatial_patch_size = 1 valid_kwargs = HunYuanVLImageProcessorKwargs + def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): + super().__init__(**kwargs) + # 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. + self.resample = PILImageResampling.BICUBIC + def resize( self, image: np.ndarray, @@ -486,10 +478,7 @@ def resize( self, image=image, 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 patchify( 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 a9d1fd223f19..7c77ae525fe2 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 @@ -98,6 +98,8 @@ class MiniMaxM3VLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 + patch_block_size = None + flat_patches = True valid_kwargs = MiniMaxM3VLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -156,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -208,7 +207,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], 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 a8794d719571..3d9783ec3e4e 100644 --- a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py @@ -106,6 +106,8 @@ class PaddleOCRVLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 2 + patch_block_size = 1 + flat_patches = False valid_kwargs = PaddleOCRVLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -160,23 +162,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -212,12 +211,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel( - resize_normalize_patchify_images_with_kernel, - compute_resized_height_and_width=smart_resize, - merge_patches=False, - flatten_patches=False, - ) + @use_processing_kernel(resize_normalize_patchify_images_with_kernel) def _preprocess( self, images: list["torch.Tensor"], diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index 920c4f25ec0d..e1aa6ec8ea37 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -28,7 +28,6 @@ from ...activations import GELUActivation from ...cache_utils import Cache, DynamicCache from ...configuration_utils import SubConfigSpec -from ...integrations.hub_processing_kernels import resize_normalize_patchify_images_with_kernel, use_processing_kernel from ...masking_utils import create_bidirectional_mask, create_causal_mask from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_utils import PreTrainedModel @@ -179,6 +178,8 @@ def patchify( class PaddleOCRVLImageProcessor(Qwen2VLImageProcessor): size = {"shortest_edge": 384 * 384, "longest_edge": 1536 * 1536} temporal_patch_size = 1 + patch_block_size = 1 + flat_patches = False def patchify( self, @@ -215,15 +216,6 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel( - resize_normalize_patchify_images_with_kernel, - compute_resized_height_and_width=smart_resize, - merge_patches=False, - flatten_patches=False, - ) - def _preprocess(self, **super_kwargs): - return super()._preprocess(**super_kwargs) - class PaddleOCRVLProcessorKwargs(ProcessingKwargs, total=False): _defaults = { 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 2b3543a288a7..37c76307f8b0 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -104,6 +104,8 @@ class Qwen2VLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 + patch_block_size = None + flat_patches = True valid_kwargs = Qwen2VLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -158,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", @@ -210,7 +209,7 @@ def patchify( ) return flatten_patches, grid_h, grid_w - @use_processing_kernel(resize_normalize_patchify_images_with_kernel, compute_resized_height_and_width=smart_resize) + @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 573d216601b1..466f12723e6b 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -258,6 +258,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs 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}.") diff --git a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py index 475008455915..a1492aeaaa56 100644 --- a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py @@ -1011,6 +1011,7 @@ def _standardize_kwargs(self, **super_kwargs): def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs 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}.") 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 3e2c49a3b0bf..e684b2b4b9a5 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -207,6 +207,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs 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}.") 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 dd84527623a1..c1df2260ad8a 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 @@ -96,6 +96,8 @@ class VideoLlama3ImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 1 + patch_block_size = None + flat_patches = True valid_kwargs = VideoLlama3ImageProcessorKwargs model_input_names = [ "pixel_values", @@ -154,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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + 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", From 6bf8b2271c02bca3dacac35f224279711b2ebff4 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 15 Oct 2026 16:13:25 +0200 Subject: [PATCH 18/26] better tests --- tests/kernels/test_kernels.py | 112 +++++++++++++++++++--------------- 1 file changed, 62 insertions(+), 50 deletions(-) diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index b5d8a7d09332..055842282ed1 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -952,34 +952,35 @@ def connected_component_areas_reference(regions): def patchify_kernel_layout_reference( - frames, + inputs, target_sizes, - items, resample, rescale_factor, image_mean, image_std, patch_size, - merge_size, + block_size, temporal_patch_size, ): - """What `resize_normalize_patchify` writes for frames that are already at their target 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 item in items: - padded_item = list(item) + [item[-1]] * (-len(item) % temporal_patch_size) - video = (torch.stack([frames[index] for index in padded_item]).float() * rescale_factor - mean) / std - frame_count, channels, height, width = video.shape - patches = video.reshape( + 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 * merge_size), - merge_size, + height // (patch_size * block_size), + block_size, patch_size, - width // (patch_size * merge_size), - merge_size, + width // (patch_size * block_size), + block_size, patch_size, ) patches = patches.permute(0, 3, 6, 4, 7, 2, 1, 5, 8) @@ -1102,7 +1103,7 @@ def test_sam2_keeps_masks_without_the_kernel(self): def run_resize_adapter(self, images=None, **overrides): kernel = MagicMock() arguments = { - "size": SizeDict(height=8, width=8), + "sizes": [(8, 8), (8, 12)], "crop_size": None, "resample": PILImageResampling.BICUBIC, "rescale_factor": 1 / 255, @@ -1120,23 +1121,19 @@ def test_resize_adapter_translates_arguments(self): kernel, result = self.run_resize_adapter() self.assertIs(result, kernel.resize_normalize.return_value) arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[1:], ([0.5, 0.5, 0.5], [0.5, 0.5, 0.5], 1 / 255, "bicubic")) - self.assertEqual(keyword_arguments, {"crop_size": None, "size": (8, 8)}) + self.assertEqual(arguments[1:], ([(8, 8), (8, 12)], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5], 1 / 255, "bicubic")) + self.assertEqual(keyword_arguments, {"crop_size": None}) - kernel, _ = self.run_resize_adapter( - size=SizeDict(shortest_edge=8), crop_size=SizeDict(height=6, width=6), image_mean=0.5, image_std=0.5 - ) + kernel, _ = self.run_resize_adapter(crop_size=SizeDict(height=6, width=6), image_mean=0.5, image_std=0.5) arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[1:3], (0.5, 0.5)) - self.assertEqual(keyword_arguments, {"crop_size": (6, 6), "shortest_edge": 8}) + self.assertEqual(arguments[2:4], (0.5, 0.5)) + self.assertEqual(keyword_arguments, {"crop_size": (6, 6)}) def test_resize_adapter_falls_back(self): unsupported = { "lanczos": {"resample": PILImageResampling.LANCZOS}, - "crop_larger_than_resize": {"crop_size": SizeDict(height=12, width=12)}, + "crop_larger_than_one_resize": {"crop_size": SizeDict(height=8, width=10)}, "empty_crop": {"crop_size": SizeDict()}, - "shortest_edge_without_crop": {"size": SizeDict(shortest_edge=8)}, - "bounded_resize": {"size": SizeDict(shortest_edge=8, longest_edge=16)}, "float_images": {"images": [torch.rand(3, 40, 60)]}, "mixed_channels": { "images": [torch.zeros(3, 4, 4, dtype=torch.uint8), torch.zeros(1, 4, 4, dtype=torch.uint8)] @@ -1151,29 +1148,48 @@ def test_resize_adapter_falls_back(self): kernel = MagicMock() self.assertIsNone( _resize_normalize_kernel( - kernel, - [torch.zeros(3, 4, 4, dtype=torch.uint8)], - SizeDict(height=2, width=2), - None, - 3, - 1 / 255, - 0.5, - 0.5, + kernel, [torch.zeros(3, 4, 4, dtype=torch.uint8)], [(2, 2)], None, 3, 1 / 255, 0.5, 0.5 ) ) kernel.resize_normalize.assert_not_called() + def test_resize_kernel_receives_the_sizes_of_resize(self): + images = [ + torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8), + torch.randint(0, 255, (3, 50, 30), dtype=torch.uint8), + ] + size_dicts = { + "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}, + } + processor = ViTImageProcessor() + for name, size in size_dicts.items(): + with self.subTest(name): + with patch( + "transformers.image_processing_backends.run_processing_kernel", return_value=None + ) as run_kernel: + processor.use_kernels = True + processor(images, size=size, do_center_crop=False, return_tensors=None) + sizes = run_kernel.call_args.args[2] + self.assertEqual( + [tuple(size) for size in sizes], + [tuple(processor.resize(image, SizeDict(**size)).shape[-2:]) for image in images], + ) + def test_patchify_adapter_translates_arguments(self): kernel = MagicMock() - frames = [torch.zeros(3, 30, 40, dtype=torch.uint8), torch.zeros(3, 20, 20, dtype=torch.uint8)] + inputs = [torch.zeros(1, 3, 30, 40, dtype=torch.uint8), torch.zeros(2, 3, 20, 20, dtype=torch.uint8)] with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): result = _resize_normalize_patchify_kernel( - kernel, frames, [(28, 28), (28, 28)], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 + kernel, inputs, [(28, 28), (28, 28)], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 ) self.assertIs(result, kernel.resize_normalize_patchify.return_value) arguments, keyword_arguments = kernel.resize_normalize_patchify.call_args + self.assertIs(arguments[0], inputs) self.assertEqual(arguments[1:], ([(28, 28), (28, 28)], [0.5] * 3, [0.5] * 3, 1 / 255, "bicubic", 14, 2, 2)) - self.assertEqual(keyword_arguments, {"items": None}) + self.assertEqual(keyword_arguments, {}) def test_qwen2_vl_uses_the_patchify_kernel_output(self): images = [torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)] @@ -1189,7 +1205,7 @@ def test_qwen2_vl_uses_the_patchify_kernel_output(self): self.assertIs(output["pixel_values"], pixel_values) self.assertEqual(output["image_grid_thw"].tolist(), [[1, 4, 6]]) - def test_qwen2_vl_video_groups_frames_per_video(self): + 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), @@ -1201,11 +1217,9 @@ def test_qwen2_vl_video_groups_frames_per_video(self): output = Qwen2VLVideoProcessor(use_kernels=True)( videos, do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" ) - frames, target_sizes = run_kernel.call_args.args[1:3] - items = run_kernel.call_args.kwargs["items"] - self.assertEqual(len(frames), 5) - self.assertEqual(items, [[0, 1, 2], [3, 4]]) - self.assertEqual(len(set(target_sizes[:3])), 1) + kernel_inputs, target_sizes = run_kernel.call_args.args[1:3] + 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): @@ -1249,13 +1263,8 @@ def run(height, width): { "resize_normalize_patchify": ( "cv-utils", - lambda kernel, frames, target_sizes, *arguments, items=None: recorded_arguments.append( - ( - frames, - target_sizes, - items or [[index] for index in range(len(frames))], - *arguments, - ) + lambda kernel, inputs, target_sizes, *arguments: recorded_arguments.append( + (inputs, target_sizes, *arguments) ), ) }, @@ -1276,8 +1285,11 @@ def run(height, width): break height, width = recorded_arguments[0][1][0] pixel_values = run(height, width) - frames, target_sizes = recorded_arguments[0][:2] - self.assertEqual([tuple(frame.shape[-2:]) for frame in frames], [tuple(size) for size in target_sizes]) + kernel_inputs, target_sizes = recorded_arguments[0][:2] + 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(*recorded_arguments[0]).reshape(-1) ) From fd61482e6cfa77fb9fa9b0d529e7970c448ea6b0 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 15 Oct 2026 16:13:34 +0200 Subject: [PATCH 19/26] update doc --- docs/source/en/kernel_doc/loading_kernels.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 9edf1f126931..55a4cca1e4c8 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -356,7 +356,7 @@ def my_op_kernel(kernel, images): return kernel.my_op(images) ``` -`use_processing_kernel` connects a processor to it. It decorates `_preprocess` with a function that receives the processor, the named arguments of `_preprocess` and the options of the decorator. That function owns everything the kernel needs, such as the target sizes and the output `BatchFeature`, so the processor code does not change. When `use_kernels=True` and the function returns a result, `_preprocess` returns it. Otherwise `_preprocess` runs as usual. +`use_processing_kernel` connects a processor to it. It decorates `_preprocess` with a function that receives the processor and the named arguments of `_preprocess`. That function owns everything the kernel needs, such as the target sizes and the output `BatchFeature`, so the processor code does not change. When `use_kernels=True` and the function returns a result, `_preprocess` returns it. Otherwise `_preprocess` runs as usual. ```py from transformers import BatchFeature, TorchvisionBackend @@ -376,7 +376,7 @@ class MyImageProcessor(TorchvisionBackend): ... ``` -Subclasses that keep `_preprocess` keep the kernel. In a modular file, a model passes its own options by redefining `_preprocess` with the decorator and a call to `super()._preprocess(**super_kwargs)`. A model that replaces `_preprocess` with a different pipeline marks it with `@no_inherit_decorator`. +Subclasses that keep `_preprocess` 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 From 43486dfba6491fab145f630b2c2d4e58f09a9ba5 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 21 Oct 2026 15:44:00 +0200 Subject: [PATCH 20/26] upsample + argmax cv-utils kernel --- .../image_processing_mobilenet_v2.py | 2 ++ .../mobilevit/image_processing_mobilevit.py | 2 ++ .../models/sam2/image_processing_sam2.py | 31 ++++++++++--------- src/transformers/models/sam2/modular_sam2.py | 31 ++++++++++--------- .../models/sam3/image_processing_sam3.py | 31 ++++++++++--------- .../sapiens2/image_processing_sapiens2.py | 2 ++ .../segformer/image_processing_segformer.py | 2 ++ 7 files changed, 59 insertions(+), 42 deletions(-) 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 8bd45321bbea..4a86fd4563c4 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, @@ -205,6 +206,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/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index 8d9e8c8e50ed..00a2651229df 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,7 +37,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import cv_utils_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available, logging @@ -690,20 +690,23 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. return pred_masks def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): - """Fill background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + kernel = cv_utils_kernel(regions.device) if self.use_kernels else None + if kernel is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + if max_hole_area > 0: + holes = regions <= mask_threshold + hole_areas = kernel.connected_component_areas(holes) + regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) + if max_sprinkle_area > 0: + sprinkles = regions > mask_threshold + sprinkle_areas = kernel.connected_component_areas(sprinkles) + regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, regions) return regions.reshape_as(masks) diff --git a/src/transformers/models/sam2/modular_sam2.py b/src/transformers/models/sam2/modular_sam2.py index 53c38250c306..b9e6e70c7178 100644 --- a/src/transformers/models/sam2/modular_sam2.py +++ b/src/transformers/models/sam2/modular_sam2.py @@ -34,7 +34,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import cv_utils_kernel from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -259,20 +259,23 @@ def post_process_masks( return output_masks def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): - """Fill background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + kernel = cv_utils_kernel(regions.device) if self.use_kernels else None + if kernel is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + if max_hole_area > 0: + holes = regions <= mask_threshold + hole_areas = kernel.connected_component_areas(holes) + regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) + if max_sprinkle_area > 0: + sprinkles = regions > mask_threshold + sprinkle_areas = kernel.connected_component_areas(sprinkles) + regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, regions) return regions.reshape_as(masks) def _get_preprocess_shape(self): diff --git a/src/transformers/models/sam3/image_processing_sam3.py b/src/transformers/models/sam3/image_processing_sam3.py index a0d335eadd31..1fa3e200665f 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,7 +40,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +from ...integrations.hub_processing_kernels import cv_utils_kernel from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring, is_vision_available, logging @@ -721,20 +721,23 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. return pred_masks def _remove_small_regions(self, masks, mask_threshold, max_hole_area, max_sprinkle_area): - """Fill background holes up to `max_hole_area` pixels and drop foreground islands up to `max_sprinkle_area`.""" + """Fill holes up to `max_hole_area` pixels and drop islands up to `max_sprinkle_area`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - regions = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) + kernel = cv_utils_kernel(regions.device) if self.use_kernels else None + if kernel is None: + logger.warning_once( + "`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. Skipping this step." + ) + return masks + if max_hole_area > 0: + holes = regions <= mask_threshold + hole_areas = kernel.connected_component_areas(holes) + regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) + if max_sprinkle_area > 0: + sprinkles = regions > mask_threshold + sprinkle_areas = kernel.connected_component_areas(sprinkles) + regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, regions) return regions.reshape_as(masks) def post_process_semantic_segmentation( diff --git a/src/transformers/models/sapiens2/image_processing_sapiens2.py b/src/transformers/models/sapiens2/image_processing_sapiens2.py index 26f500fb3ef0..a2633fd61f04 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]": From 74842c5de6ce9e2bacf9192b3fecb23325e986c0 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 21 Oct 2026 18:07:05 +0200 Subject: [PATCH 21/26] upsample more --- src/transformers/models/beit/image_processing_beit.py | 2 ++ src/transformers/models/chmv2/image_processing_chmv2.py | 2 ++ src/transformers/models/dpt/image_processing_dpt.py | 2 ++ 3 files changed, 6 insertions(+) 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 1b1e34c3cd7d..c4900871aa64 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, requires_backends @@ -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/dpt/image_processing_dpt.py b/src/transformers/models/dpt/image_processing_dpt.py index 054ee3331dcd..13fdfac8ebb8 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, requires_backends @@ -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]": From ab755b47d1030036d10bf6408f1e06090fbaf879 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 21 Oct 2026 18:07:35 +0200 Subject: [PATCH 22/26] better func split --- src/transformers/image_processing_backends.py | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index ec7832ed3f5c..bde7c3e627b8 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,7 +53,12 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel +from .integrations.hub_processing_kernels import ( + KERNEL_INTERPOLATIONS, + cv_utils_kernel, + kernel_can_resize, + use_processing_kernel, +) from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -100,29 +105,27 @@ def resize_normalize_with_kernel( return_tensors, **kwargs, ): - """ - `pixel_values` of the default torchvision pipeline, computed by one `resize_normalize` kernel call. - - Processors that override a step of the `TorchvisionBackend` pipeline keep their own path. - """ + """`pixel_values` of the default torchvision pipeline from one kernel call, `None` to fall back.""" uses_default_resize_and_normalize = all( getattr(type(processor), name) is getattr(TorchvisionBackend, name) for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") ) if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): return None - pixel_values = run_processing_kernel( - "resize_normalize", - images, - [processor._resize_output_size(image, size) for image in images], - crop_size if do_center_crop else None, - resample, - rescale_factor, - image_mean, - image_std, - ) - if pixel_values is None: + if not kernel_can_resize(images, resample): return None + kernel = 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_std, rescale_factor, KERNEL_INTERPOLATIONS[resample], crop_size=crop + ) return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) @@ -131,7 +134,6 @@ class TorchvisionBackend(BaseImageProcessor): """Torchvision backend for GPU-accelerated batched image processing.""" def __init__(self, **kwargs: Unpack[ImagesKwargs]): - self.use_kernels = kwargs.pop("use_kernels", False) super().__init__(**kwargs) self._set_attributes(**kwargs) From a71afb151b4bf55eeb3d174b1b163d07fa9e9079 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Thu, 29 Oct 2026 06:27:49 +0100 Subject: [PATCH 23/26] restore kernel registry, address review - keep register_processing_kernel / run_processing_kernel, add upsample_argmax op - device check in the kernel_can_resize loop - pil processors raise on use_kernels=True - sam small-region removal raises without the kernel - drop temporal_factor default in qwen2-vl video resize --- docs/source/en/kernel_doc/loading_kernels.md | 46 +- src/transformers/image_processing_backends.py | 20 +- src/transformers/image_processing_base.py | 2 +- src/transformers/image_processing_utils.py | 1 + .../integrations/hub_processing_kernels.py | 110 ++-- .../image_processing_cohere_compass.py | 4 +- .../video_processing_cohere_compass.py | 4 +- .../image_processing_ernie4_5_vl_moe.py | 4 +- .../glm_image/image_processing_glm_image.py | 4 +- .../hunyuan_vl/image_processing_hunyuan_vl.py | 38 +- .../image_processing_pil_hunyuan_vl.py | 28 +- .../models/hunyuan_vl/modular_hunyuan_vl.py | 67 +-- .../image_processing_minimax_m3_vl.py | 4 +- .../image_processing_paddleocr_vl.py | 14 +- .../paddleocr_vl/modular_paddleocr_vl.py | 12 +- .../qwen2_vl/image_processing_qwen2_vl.py | 4 +- .../qwen2_vl/video_processing_qwen2_vl.py | 4 +- .../models/qwen3_vl/modular_qwen3_vl.py | 2 +- .../qwen3_vl/video_processing_qwen3_vl.py | 4 +- .../models/sam2/image_processing_sam2.py | 33 +- src/transformers/models/sam2/modular_sam2.py | 28 +- .../models/sam3/image_processing_sam3.py | 33 +- .../image_processing_video_llama_3.py | 4 +- src/transformers/processing_utils.py | 6 +- tests/kernels/test_kernels.py | 504 +----------------- 25 files changed, 219 insertions(+), 761 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index 55a4cca1e4c8..aefd706176d8 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -320,13 +320,14 @@ 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. The flag is not saved with the processor configuration. +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 (Cohere Compass, ERNIE 4.5 VL, GLM-Image, HunYuanVL, MiniMax-M3-VL, 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 BEiT, SegFormer, DPT, CHMv2, Sapiens2, MobileNetV2 and MobileViT | ```py from transformers import AutoProcessor @@ -337,46 +338,47 @@ 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. -The resize kernels 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. +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 A processing kernel has two levels in `integrations/hub_processing_kernels.py`. -`register_processing_kernel` maps an operation to a kernel of `_HUB_KERNEL_MAPPING`. The adapter receives the loaded kernel module and the arguments of the operation. It translates them to the kernel call and returns `None` for arguments the kernel cannot handle. +`register_processing_kernel` maps an operation to a kernel of `_HUB_KERNEL_MAPPING`, so each operation can come from its own kernel repository. The adapter receives the loaded kernel module and the arguments of the operation. It checks what the kernel supports, such as the device, and returns `None` for arguments the kernel cannot handle. `run_processing_kernel` loads the kernel and calls the adapter, or returns `None` when the kernel does not load. + +`use_processing_kernel` connects a processor method to an operation. 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`. For example, this is how semantic segmentation post-processing uses `upsample_argmax`: ```py -from transformers.integrations.hub_processing_kernels import register_processing_kernel +from transformers import TorchvisionBackend +from transformers.integrations.hub_processing_kernels import ( + register_processing_kernel, + run_processing_kernel, + use_processing_kernel, +) -@register_processing_kernel("my_op", kernel_name="my-processing-kernel") -def my_op_kernel(kernel, images): - if images[0].device.type != "cuda": +@register_processing_kernel("upsample_argmax", kernel_name="cv-utils") +def _upsample_argmax_kernel(kernel, logits, target_sizes): + if logits.device.type != "cuda": return None - return kernel.my_op(images) -``` - -`use_processing_kernel` connects a processor to it. It decorates `_preprocess` with a function that receives the processor and the named arguments of `_preprocess`. That function owns everything the kernel needs, such as the target sizes and the output `BatchFeature`, so the processor code does not change. When `use_kernels=True` and the function returns a result, `_preprocess` returns it. Otherwise `_preprocess` runs as usual. - -```py -from transformers import BatchFeature, TorchvisionBackend -from transformers.integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel + return kernel.upsample_argmax(logits, target_sizes) -def my_op_with_kernel(processor, images, return_tensors, **kwargs): - pixel_values = run_processing_kernel("my_op", images) - if pixel_values is None: +def upsample_argmax_with_kernel(processor, outputs, target_sizes, return_segmentation_scores, **kwargs): + if return_segmentation_scores or target_sizes is None: return None - return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) + return run_processing_kernel("upsample_argmax", outputs.logits, target_sizes) class MyImageProcessor(TorchvisionBackend): - @use_processing_kernel(my_op_with_kernel) - def _preprocess(self, images, return_tensors, **kwargs): + @use_processing_kernel(upsample_argmax_with_kernel) + def post_process_semantic_segmentation(self, outputs, target_sizes=None, return_segmentation_scores=False): ... ``` -Subclasses that keep `_preprocess` 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`. +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 diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index bde7c3e627b8..e5ad779122d6 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,12 +53,7 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_processing_kernels import ( - KERNEL_INTERPOLATIONS, - cv_utils_kernel, - kernel_can_resize, - use_processing_kernel, -) +from .integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -112,20 +107,17 @@ def resize_normalize_with_kernel( ) if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): return None - if not kernel_can_resize(images, resample): - return None - kernel = 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_std, rescale_factor, KERNEL_INTERPOLATIONS[resample], crop_size=crop + pixel_values = run_processing_kernel( + "resize_normalize", images, sizes, crop, resample, rescale_factor, image_mean, image_std ) + if pixel_values is None: + return None return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors) @@ -464,6 +456,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 94267665fe7c..ecb04f80671e 100644 --- a/src/transformers/image_processing_base.py +++ b/src/transformers/image_processing_base.py @@ -420,7 +420,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, not part of the saved config + 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 da15adbaf078..16f35afc12e3 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_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py index bf369f6bb0f2..a0e43bfb09ac 100644 --- a/src/transformers/integrations/hub_processing_kernels.py +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -16,18 +16,19 @@ from functools import wraps from ..feature_extraction_utils import BatchFeature +from ..image_utils import PILImageResampling from ..utils.import_utils import is_torch_available if is_torch_available(): import torch - from . import hub_kernels + from .hub_kernels import lazy_load_kernel _PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} _KERNEL_DEVICE_TYPE = "cuda" -_KERNEL_INTERPOLATIONS = {2: "bilinear", 3: "bicubic"} +KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} def register_processing_kernel(name: str, kernel_name: str): @@ -48,17 +49,30 @@ def register(adapter: Callable) -> Callable: def run_processing_kernel(name: str, *args, **kwargs): """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" - if not is_torch_available() or name not in _PROCESSING_KERNEL_ADAPTERS or not hub_kernels._kernels_enabled: - return None - if not torch.cuda.is_available(): + if not is_torch_available() or name not in _PROCESSING_KERNEL_ADAPTERS: return None kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[name] - kernel = hub_kernels.lazy_load_kernel(kernel_name) + kernel = lazy_load_kernel(kernel_name) if kernel is None: return None return adapter(kernel, *args, **kwargs) +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.device.type == _KERNEL_DEVICE_TYPE + and image.dtype == torch.uint8 + and image.device == images[0].device + and image.shape[-3] == images[0].shape[-3] + for image in images + ) + ) + + @register_processing_kernel("connected_component_areas", kernel_name="cv-utils") def _connected_component_areas_kernel(kernel, regions): """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" @@ -67,30 +81,14 @@ def _connected_component_areas_kernel(kernel, regions): return kernel.connected_component_areas(regions) -def _kernel_supports(images): - """Whether the resize kernels can process `images` in one launch: uint8, one kernel device, one channel count.""" - return ( - bool(images) - and images[0].device.type == _KERNEL_DEVICE_TYPE - and all( - image.dtype == torch.uint8 and image.device == images[0].device and image.shape[-3] == images[0].shape[-3] - for image in images - ) - ) - - @register_processing_kernel("resize_normalize", kernel_name="cv-utils") def _resize_normalize_kernel(kernel, images, sizes, crop_size, resample, rescale_factor, image_mean, image_std): """Resize every image to its size in `sizes`, center crop to `crop_size` when given, then rescale and normalize.""" - interpolation = _KERNEL_INTERPOLATIONS.get(resample) - if interpolation is None or not _kernel_supports(images): + if not kernel_can_resize(images, resample): return None - crop = None - if crop_size is not None: - crop = (crop_size.height, crop_size.width) - if not all(crop) or any(crop[0] > height or crop[1] > width for height, width in sizes): - return None - return kernel.resize_normalize(images, sizes, image_mean, image_std, rescale_factor, interpolation, crop_size=crop) + return kernel.resize_normalize( + images, sizes, image_mean, image_std, rescale_factor, KERNEL_INTERPOLATIONS[resample], crop_size=crop_size + ) @register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") @@ -103,12 +101,11 @@ def _resize_normalize_patchify_kernel( image_mean, image_std, patch_size, - block_size, + patch_block_size, temporal_patch_size, ): - """Resize every `(T, C, H, W)` input to its target frame size, normalize, and write its flattened patches in order.""" - interpolation = _KERNEL_INTERPOLATIONS.get(resample) - if interpolation is None or not _kernel_supports(inputs): + """Resize every `(T, C, H, W)` input to its target frame size, normalize, and write its patches in order.""" + if not kernel_can_resize(inputs, resample): return None return kernel.resize_normalize_patchify( inputs, @@ -116,25 +113,33 @@ def _resize_normalize_patchify_kernel( image_mean, image_std, rescale_factor, - interpolation, + KERNEL_INTERPOLATIONS[resample], patch_size, - block_size, + patch_block_size, temporal_patch_size, ) -def use_processing_kernel(preprocess_with_kernel: Callable): +@register_processing_kernel("upsample_argmax", kernel_name="cv-utils") +def _upsample_argmax_kernel(kernel, logits, target_sizes): + """Class of every pixel of `logits` `(B, C, h, w)` upsampled to `target_sizes`, without the upsampled logits.""" + if logits.device.type != _KERNEL_DEVICE_TYPE: + return None + return kernel.upsample_argmax(logits, target_sizes) + + +def use_processing_kernel(run_with_kernel: Callable): """ - Decorate the `_preprocess` method of a processor so that `use_kernels=True` first runs `preprocess_with_kernel`. + Decorate a processor method so that `use_kernels=True` first runs `run_with_kernel`. - `preprocess_with_kernel` receives the processor and the named arguments of `_preprocess`. It returns - the `BatchFeature` computed by a kernel, or `None` to keep the decorated implementation. + `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. """ - def decorator(preprocess: Callable) -> Callable: - signature = inspect.signature(preprocess) + def decorator(method: Callable) -> Callable: + signature = inspect.signature(method) - @wraps(preprocess) + @wraps(method) def wrapper(self, *args, **kwargs): if self.use_kernels: arguments = signature.bind(self, *args, **kwargs) @@ -142,10 +147,10 @@ def wrapper(self, *args, **kwargs): named_arguments = dict(arguments.arguments) named_arguments.pop("self") named_arguments.update(named_arguments.pop("kwargs", {})) - output = preprocess_with_kernel(self, **named_arguments) + output = run_with_kernel(self, **named_arguments) if output is not None: return output - return preprocess(self, *args, **kwargs) + return method(self, *args, **kwargs) return wrapper @@ -169,13 +174,7 @@ def resize_normalize_patchify_images_with_kernel( return_tensors, **kwargs, ): - """ - `pixel_values` and `image_grid_thw` of the Qwen2-VL image pipeline, computed by one kernel call for the batch. - - Target sizes come from the `_resized_size` method of the processor. Patches are written in blocks of - `processor.patch_block_size`, `merge_size` when it is `None`, and returned as `(C * T, P, P)` blocks when - `processor.flat_patches` is `False`. - """ + """`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): return None target_sizes = [ @@ -193,13 +192,13 @@ def resize_normalize_patchify_images_with_kernel( image_mean, image_std, patch_size, - merge_size if processor.patch_block_size is None else processor.patch_block_size, + getattr(processor, "patch_block_size", merge_size), temporal_patch_size, ) if kernel_output is None: return None pixel_values, image_grid_thw = kernel_output - if not processor.flat_patches: + 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 @@ -224,7 +223,7 @@ def resize_normalize_patchify_videos_with_kernel( return_tensors, **kwargs, ): - """`pixel_values_videos` and `video_grid_thw` of the Qwen2-VL video pipeline, one kernel call for all frames.""" + """`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): return None target_sizes = [ @@ -248,7 +247,7 @@ def resize_normalize_patchify_videos_with_kernel( image_mean, image_std, patch_size, - merge_size, + getattr(processor, "patch_block_size", merge_size), temporal_patch_size, ) if kernel_output is None: @@ -257,3 +256,10 @@ def resize_normalize_patchify_videos_with_kernel( 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, **kwargs): + """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 + return run_processing_kernel("upsample_argmax", outputs.logits, target_sizes) 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 a872b8d5dad6..d1f3a85f7599 100644 --- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py @@ -98,8 +98,6 @@ class CohereCompassImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - patch_block_size = None - flat_patches = True valid_kwargs = CohereCompassImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -163,7 +161,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) 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 a9b8b313b53f..8d3a5a6a7b2a 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -188,7 +188,7 @@ def resize( size: SizeDict, resample: "PILImageResampling | tvF.InterpolationMode | int | None", factor: int, - temporal_factor: int = 2, + temporal_factor: int, cap_pixels_per_frame: bool | None = None, **kwargs, ) -> "torch.Tensor": @@ -204,7 +204,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs + # 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}.") 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 7760fc1f3299..91af20167d54 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 @@ -93,8 +93,6 @@ class Ernie4_5_VLMoeImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 2 - patch_block_size = None - flat_patches = True valid_kwargs = Ernie4_5_VLMoeImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -127,7 +125,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) 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 d196824a7c60..36b52738438b 100644 --- a/src/transformers/models/glm_image/image_processing_glm_image.py +++ b/src/transformers/models/glm_image/image_processing_glm_image.py @@ -110,8 +110,6 @@ class GlmImageImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - patch_block_size = None - flat_patches = True valid_kwargs = GlmImageImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw", "images_per_sample"] @@ -175,7 +173,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) 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 cb62884388b7..ee698bbab734 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -99,8 +99,6 @@ class HunYuanVLImageProcessor(TorchvisionBackend): patch_size = 16 temporal_patch_size = 1 merge_size = 2 - patch_block_size = 1 - flat_patches = True valid_kwargs = HunYuanVLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] spatial_patch_size = 1 @@ -116,10 +114,6 @@ def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): size["longest_edge"] = max_pixels size.pop("max_pixels", None) super().__init__(size=size, **kwargs) - # 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. - self.resample = PILImageResampling.BICUBIC def _standardize_kwargs( self, @@ -164,12 +158,15 @@ def resize( return super().resize( image=images, size=SizeDict(height=resized_height, width=resized_width), - resample=resample, + # 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, ) 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) @@ -184,22 +181,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, @@ -298,5 +287,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 d38a070ea571..f93869349335 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 @@ -114,10 +114,6 @@ def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): size["longest_edge"] = max_pixels size.pop("max_pixels", None) super().__init__(size=size, **kwargs) - # 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. - self.resample = PILImageResampling.BICUBIC def _standardize_kwargs( self, @@ -164,7 +160,10 @@ def resize( return super().resize( image=image, size=SizeDict(height=resized_height, width=resized_width), - resample=resample, + # 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, ) def patchify( @@ -180,22 +179,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 cf62e7aff416..7230045b7b75 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -343,15 +343,12 @@ class HunYuanVLImageProcessor(Qwen2VLImageProcessor): temporal_patch_size = 1 merge_size = 2 spatial_patch_size = 1 - patch_block_size = 1 valid_kwargs = HunYuanVLImageProcessorKwargs - def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): - super().__init__(**kwargs) - # 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. - self.resample = PILImageResampling.BICUBIC + @property + def patch_block_size(self): + """Patches are written row by row, not in `merge_size` blocks.""" + return 1 def resize( self, @@ -367,7 +364,10 @@ def resize( self, image=images, size=SizeDict(height=resized_height, width=resized_width), - resample=resample, + # 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, ) def patchify( @@ -380,22 +380,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, @@ -447,13 +439,6 @@ class HunYuanVLImageProcessorPil(Qwen2VLImageProcessorPil): spatial_patch_size = 1 valid_kwargs = HunYuanVLImageProcessorKwargs - def __init__(self, **kwargs: Unpack[HunYuanVLImageProcessorKwargs]): - super().__init__(**kwargs) - # 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. - self.resample = PILImageResampling.BICUBIC - def resize( self, image: np.ndarray, @@ -478,7 +463,10 @@ def resize( self, image=image, size=SizeDict(height=resized_height, width=resized_width), - resample=resample, + # 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, ) def patchify( @@ -494,22 +482,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/minimax_m3_vl/image_processing_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/image_processing_minimax_m3_vl.py index 7c77ae525fe2..ac2f05ee0e5e 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 @@ -98,8 +98,6 @@ class MiniMaxM3VLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - patch_block_size = None - flat_patches = True valid_kwargs = MiniMaxM3VLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -167,7 +165,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) 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 3d9783ec3e4e..694bcaa023a1 100644 --- a/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/image_processing_paddleocr_vl.py @@ -106,8 +106,6 @@ class PaddleOCRVLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 2 - patch_block_size = 1 - flat_patches = False valid_kwargs = PaddleOCRVLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -171,7 +169,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) @@ -299,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 e1aa6ec8ea37..c57ec448994b 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -178,8 +178,16 @@ def patchify( class PaddleOCRVLImageProcessor(Qwen2VLImageProcessor): size = {"shortest_edge": 384 * 384, "longest_edge": 1536 * 1536} temporal_patch_size = 1 - patch_block_size = 1 - flat_patches = False + + @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, 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 37c76307f8b0..4513b33d240a 100644 --- a/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py @@ -104,8 +104,6 @@ class Qwen2VLImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 2 merge_size = 2 - patch_block_size = None - flat_patches = True valid_kwargs = Qwen2VLImageProcessorKwargs model_input_names = ["pixel_values", "image_grid_thw"] @@ -169,7 +167,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) 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 466f12723e6b..908d40bc1cdd 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -242,7 +242,7 @@ def resize( size: SizeDict, resample: "PILImageResampling | tvF.InterpolationMode | int | None", factor: int, - temporal_factor: int = 2, + temporal_factor: int, cap_pixels_per_frame: bool | None = None, **kwargs, ) -> "torch.Tensor": @@ -258,7 +258,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs + # 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}.") diff --git a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py index a1492aeaaa56..8924f4a4bbf4 100644 --- a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py @@ -1011,7 +1011,7 @@ def _standardize_kwargs(self, **super_kwargs): def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs + # 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}.") 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 e684b2b4b9a5..fbbd5f1ead2f 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -191,7 +191,7 @@ def resize( size: SizeDict, resample: "PILImageResampling | tvF.InterpolationMode | int | None", factor: int, - temporal_factor: int = 2, + temporal_factor: int, cap_pixels_per_frame: bool | None = None, **kwargs, ) -> "torch.Tensor": @@ -207,7 +207,7 @@ def resize( def _resized_size(self, height, width, num_frames, size, factor, temporal_factor, cap_pixels_per_frame): """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, but vLLM calls it and it returns a patch count, not the frame dimensions the kernel needs + # 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}.") diff --git a/src/transformers/models/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index 00a2651229df..5c4eb323a804 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,18 +37,15 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import cv_utils_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack -from ...utils import TensorType, auto_docstring, is_vision_available, logging +from ...utils import TensorType, auto_docstring, is_vision_available if is_vision_available(): import PIL -logger = logging.get_logger(__name__) - - class Sam2ImageProcessorKwargs(ImagesKwargs, total=False): r""" mask_size (`dict[str, int]`, *optional*): @@ -692,21 +689,17 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. 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`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - kernel = cv_utils_kernel(regions.device) if self.use_kernels else None - if kernel is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - if max_hole_area > 0: - holes = regions <= mask_threshold - hole_areas = kernel.connected_component_areas(holes) - regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) - if max_sprinkle_area > 0: - sprinkles = regions > mask_threshold - sprinkle_areas = kernel.connected_component_areas(sprinkles) - regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) return regions.reshape_as(masks) diff --git a/src/transformers/models/sam2/modular_sam2.py b/src/transformers/models/sam2/modular_sam2.py index b9e6e70c7178..3e718472c86d 100644 --- a/src/transformers/models/sam2/modular_sam2.py +++ b/src/transformers/models/sam2/modular_sam2.py @@ -34,7 +34,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import cv_utils_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -261,21 +261,17 @@ def post_process_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`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - kernel = cv_utils_kernel(regions.device) if self.use_kernels else None - if kernel is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - if max_hole_area > 0: - holes = regions <= mask_threshold - hole_areas = kernel.connected_component_areas(holes) - regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) - if max_sprinkle_area > 0: - sprinkles = regions > mask_threshold - sprinkle_areas = kernel.connected_component_areas(sprinkles) - regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) return regions.reshape_as(masks) def _get_preprocess_shape(self): diff --git a/src/transformers/models/sam3/image_processing_sam3.py b/src/transformers/models/sam3/image_processing_sam3.py index 1fa3e200665f..8515fb5e4df7 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,18 +40,15 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import cv_utils_kernel +from ...integrations.hub_processing_kernels import run_processing_kernel from ...processing_utils import ImagesKwargs, Unpack -from ...utils import TensorType, auto_docstring, is_vision_available, logging +from ...utils import TensorType, auto_docstring, is_vision_available if is_vision_available(): import PIL -logger = logging.get_logger(__name__) - - class Sam3ImageProcessorKwargs(ImagesKwargs, total=False): r""" mask_size (`dict[str, int]`, *optional*): @@ -723,21 +720,17 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. 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`, with the cv-utils kernel.""" regions = masks.flatten(0, 1).unsqueeze(1) - kernel = cv_utils_kernel(regions.device) if self.use_kernels else None - if kernel is None: - logger.warning_once( - "`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. Skipping this step." - ) - return masks - if max_hole_area > 0: - holes = regions <= mask_threshold - hole_areas = kernel.connected_component_areas(holes) - regions = torch.where(holes & (hole_areas <= max_hole_area), mask_threshold + 10.0, regions) - if max_sprinkle_area > 0: - sprinkles = regions > mask_threshold - sprinkle_areas = kernel.connected_component_areas(sprinkles) - regions = torch.where(sprinkles & (sprinkle_areas <= max_sprinkle_area), mask_threshold - 10.0, 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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None + if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) return regions.reshape_as(masks) def post_process_semantic_segmentation( 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 c1df2260ad8a..7c4bf79aa910 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 @@ -96,8 +96,6 @@ class VideoLlama3ImageProcessor(TorchvisionBackend): patch_size = 14 temporal_patch_size = 1 merge_size = 1 - patch_block_size = None - flat_patches = True valid_kwargs = VideoLlama3ImageProcessorKwargs model_input_names = [ "pixel_values", @@ -165,7 +163,7 @@ def resize( 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, but vLLM calls it and it returns a patch count, not the image dimensions the kernel needs + # 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) diff --git a/src/transformers/processing_utils.py b/src/transformers/processing_utils.py index 56bc8bb06fbc..8b41e804bd02 100644 --- a/src/transformers/processing_utils.py +++ b/src/transformers/processing_utils.py @@ -1858,6 +1858,7 @@ def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, processor processor_dict = processor_dict if processor_dict is not None else {} # Remove subfolder from kwargs to avoid duplicate keyword arguments subfolder = kwargs.pop("subfolder", "") + use_kernels = kwargs.pop("use_kernels", None) # get args from processor init signature sub_processors = cls.get_attributes() @@ -1891,8 +1892,11 @@ def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, processor f"which is deprecated. Register the correct mapping in `{auto_processor_class.__name__}` instead.", ) auto_processor_class = cls.get_possibly_dynamic_module(sub_processor_class_name) + sub_processor_kwargs = dict(kwargs) + 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, subfolder=subfolder, **kwargs + pretrained_model_name_or_path, subfolder=subfolder, **sub_processor_kwargs ) args.append(sub_processor) diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 7768e68fedb9..8dbe08a7dbce 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -15,38 +15,19 @@ # Run the test: CUDA_VISIBLE_DEVICES=0 RUN_SLOW=1 pytest -sv tests/kernels/test_kernels.py -import ast import copy -import importlib -import inspect import os import sys import tempfile import types -from pathlib import Path from unittest.mock import MagicMock, patch -import numpy as np import torch from huggingface_hub import snapshot_download from parameterized import parameterized -import transformers from tests.test_memory_cleanup_mixin import MemoryCleanupTestCase -from transformers import ( - AutoModelForCausalLM, - AutoTokenizer, - HunYuanVLImageProcessor, - KernelConfig, - LevitImageProcessor, - PaddleOCRVLImageProcessor, - Qwen2VLImageProcessor, - Qwen2VLVideoProcessor, - Sam2ImageProcessor, - ViTImageProcessor, -) -from transformers.image_processing_backends import TorchvisionBackend -from transformers.image_utils import PILImageResampling, SizeDict, load_image +from transformers import AutoModelForCausalLM, AutoTokenizer, KernelConfig from transformers.integrations.hub_kernels import ( _HUB_KERNEL_MAPPING, _KERNEL_MODULE_MAPPING, @@ -55,13 +36,6 @@ load_and_register_attn_kernel, use_kernel_func_from_hub_with_fallback, ) -from transformers.integrations.hub_processing_kernels import ( - _PROCESSING_KERNEL_ADAPTERS, - _connected_component_areas_kernel, - _resize_normalize_kernel, - _resize_normalize_patchify_kernel, - run_processing_kernel, -) from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS from transformers.monkey_patching import clear_patch_mapping, get_patch_mapping, register_patch_mapping @@ -70,13 +44,11 @@ require_kernels, require_rocm, require_torch_accelerator, - require_torch_gpu, slow, torch_device, ) from transformers.utils.import_utils import is_kernels_available from transformers.utils.kernel_config import add_to_mapping_local -from transformers.video_processing_utils import BaseVideoProcessor if is_kernels_available(): @@ -966,477 +938,3 @@ def test_single_device_mapping_still_works(self): result_mapping = kernel_config.kernel_mapping self.assertIn("RMSNorm", result_mapping, "RMSNorm should be in mapping") - - -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, - resample, - rescale_factor, - image_mean, - image_std, - 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) - - -def processors_calling_the_patchify_kernel(): - """Torchvision image and video processor classes whose module mentions the `resize_normalize_patchify` kernel.""" - classes = [] - for path in sorted(Path(transformers.__file__).parent.glob("models/*/*_processing_*.py")): - if "resize_normalize_patchify" not in path.read_text() or path.stem.startswith("modular_"): - continue - module = importlib.import_module(f"transformers.models.{path.parent.name}.{path.stem}") - for _, cls in inspect.getmembers(module, inspect.isclass): - if cls.__module__ == module.__name__ and issubclass(cls, TorchvisionBackend): - classes.append(cls) - return classes - - -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_registration_records_repo_and_adapter(self): - self.assertEqual( - _PROCESSING_KERNEL_ADAPTERS["connected_component_areas"], - ("cv-utils", _connected_component_areas_kernel), - ) - self.assertEqual(_HUB_KERNEL_MAPPING["cv-utils"]["repo_id"], "kernels-community/cv-utils") - - def test_run_processing_kernel_calls_adapter(self): - sentinel = types.ModuleType("sentinel_kernel_module") - with ( - patch.object(torch.cuda, "is_available", return_value=True), - patch.dict( - _PROCESSING_KERNEL_ADAPTERS, - {"dummy_op": ("dummy-kernel", lambda kernel, value: (kernel, value))}, - clear=True, - ), - patch.multiple( - "transformers.integrations.hub_kernels", - _kernels_enabled=True, - lazy_load_kernel={"dummy-kernel": sentinel}.get, - ), - ): - self.assertEqual(run_processing_kernel("dummy_op", 3), (sentinel, 3)) - - def test_run_processing_kernel_falls_back(self): - regions = self.mask_logits > 0 - with patch.object(torch.cuda, "is_available", return_value=True): - # Unknown op, `USE_HUB_KERNELS=0`, and a kernel that cannot be loaded all keep the default path. - self.assertIsNone(run_processing_kernel("not_a_registered_op")) - with patch("transformers.integrations.hub_kernels._kernels_enabled", False): - self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) - with patch("transformers.integrations.hub_kernels.lazy_load_kernel", lambda name: None): - self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) - - def test_run_processing_kernel_needs_accelerator(self): - with patch.object(torch.cuda, "is_available", return_value=False): - with patch("transformers.integrations.hub_kernels.lazy_load_kernel", self.fail): - self.assertIsNone(run_processing_kernel("connected_component_areas", self.mask_logits > 0)) - - def test_connected_component_areas_adapter_calls_the_kernel(self): - kernel = ReferenceConnectedComponentsKernel() - regions = torch.zeros(2, 1, 5, 7, dtype=torch.bool) - regions[:, :, 1:3, 1:4] = True - # The kernel is CUDA only; pretend CPU is its device so the adapter can be tested without a GPU. - with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): - areas = _connected_component_areas_kernel(kernel, regions) - self.assertIs(kernel.inputs[0], regions) - self.assertTrue(torch.equal(areas, connected_component_areas_reference(regions))) - - def test_connected_component_areas_adapter_needs_cuda_tensors(self): - kernel = ReferenceConnectedComponentsKernel() - self.assertIsNone(_connected_component_areas_kernel(kernel, self.mask_logits > 0)) - self.assertEqual(kernel.inputs, []) - - def test_sam2_fills_holes_and_removes_sprinkles(self): - with patch( - "transformers.models.sam2.image_processing_sam2.run_processing_kernel", - side_effect=lambda name, regions: connected_component_areas_reference(regions), - ): - 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) - 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_keeps_masks_without_the_kernel(self): - default = self.post_process(use_kernels=False) - self.assertTrue(default[0, 0, 5, 5].item() is False and default[0, 0, 13, 13].item() is True) - self.assertTrue(torch.equal(self.post_process(False, max_hole_area=4, max_sprinkle_area=1), default)) - with patch.object(torch.cuda, "is_available", return_value=False): - self.assertTrue(torch.equal(self.post_process(True, max_hole_area=4, max_sprinkle_area=1), default)) - - def run_resize_adapter(self, images=None, **overrides): - kernel = MagicMock() - arguments = { - "sizes": [(8, 8), (8, 12)], - "crop_size": None, - "resample": PILImageResampling.BICUBIC, - "rescale_factor": 1 / 255, - "image_mean": [0.5, 0.5, 0.5], - "image_std": [0.5, 0.5, 0.5], - } - images = ( - [torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8) for _ in range(2)] if images is None else images - ) - with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): - result = _resize_normalize_kernel(kernel, images, **{**arguments, **overrides}) - return kernel, result - - def test_resize_adapter_translates_arguments(self): - kernel, result = self.run_resize_adapter() - self.assertIs(result, kernel.resize_normalize.return_value) - arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[1:], ([(8, 8), (8, 12)], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5], 1 / 255, "bicubic")) - self.assertEqual(keyword_arguments, {"crop_size": None}) - - kernel, _ = self.run_resize_adapter(crop_size=SizeDict(height=6, width=6), image_mean=0.5, image_std=0.5) - arguments, keyword_arguments = kernel.resize_normalize.call_args - self.assertEqual(arguments[2:4], (0.5, 0.5)) - self.assertEqual(keyword_arguments, {"crop_size": (6, 6)}) - - def test_resize_adapter_falls_back(self): - unsupported = { - "lanczos": {"resample": PILImageResampling.LANCZOS}, - "crop_larger_than_one_resize": {"crop_size": SizeDict(height=8, width=10)}, - "empty_crop": {"crop_size": SizeDict()}, - "float_images": {"images": [torch.rand(3, 40, 60)]}, - "mixed_channels": { - "images": [torch.zeros(3, 4, 4, dtype=torch.uint8), torch.zeros(1, 4, 4, dtype=torch.uint8)] - }, - } - for name, overrides in unsupported.items(): - with self.subTest(name): - kernel, result = self.run_resize_adapter(**overrides) - self.assertIsNone(result) - kernel.resize_normalize.assert_not_called() - # Outside the patch the kernel device is CUDA, and these images are on CPU. - kernel = MagicMock() - self.assertIsNone( - _resize_normalize_kernel( - kernel, [torch.zeros(3, 4, 4, dtype=torch.uint8)], [(2, 2)], None, 3, 1 / 255, 0.5, 0.5 - ) - ) - kernel.resize_normalize.assert_not_called() - - def test_resize_kernel_receives_the_sizes_of_resize(self): - images = [ - torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8), - torch.randint(0, 255, (3, 50, 30), dtype=torch.uint8), - ] - size_dicts = { - "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}, - } - processor = ViTImageProcessor() - for name, size in size_dicts.items(): - with self.subTest(name): - with patch( - "transformers.image_processing_backends.run_processing_kernel", return_value=None - ) as run_kernel: - processor.use_kernels = True - processor(images, size=size, do_center_crop=False, return_tensors=None) - sizes = run_kernel.call_args.args[2] - self.assertEqual( - [tuple(size) for size in sizes], - [tuple(processor.resize(image, SizeDict(**size)).shape[-2:]) for image in images], - ) - - def test_patchify_adapter_translates_arguments(self): - kernel = MagicMock() - inputs = [torch.zeros(1, 3, 30, 40, dtype=torch.uint8), torch.zeros(2, 3, 20, 20, dtype=torch.uint8)] - with patch("transformers.integrations.hub_processing_kernels._KERNEL_DEVICE_TYPE", "cpu"): - result = _resize_normalize_patchify_kernel( - kernel, inputs, [(28, 28), (28, 28)], 3, 1 / 255, [0.5] * 3, [0.5] * 3, 14, 2, 2 - ) - self.assertIs(result, kernel.resize_normalize_patchify.return_value) - arguments, keyword_arguments = kernel.resize_normalize_patchify.call_args - self.assertIs(arguments[0], inputs) - self.assertEqual(arguments[1:], ([(28, 28), (28, 28)], [0.5] * 3, [0.5] * 3, 1 / 255, "bicubic", 14, 2, 2)) - self.assertEqual(keyword_arguments, {}) - - 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) - with patch( - "transformers.integrations.hub_processing_kernels.run_processing_kernel", - return_value=(pixel_values, torch.tensor([[1, 4, 6]])), - ) as run_kernel: - output = Qwen2VLImageProcessor(use_kernels=True)(images, return_tensors="pt") - Qwen2VLImageProcessor(use_kernels=False)(images, return_tensors="pt") - self.assertEqual(run_kernel.call_count, 1) - self.assertEqual(run_kernel.call_args[0][0], "resize_normalize_patchify") - self.assertIs(output["pixel_values"], pixel_values) - self.assertEqual(output["image_grid_thw"].tolist(), [[1, 4, 6]]) - - 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), - ] - with patch( - "transformers.integrations.hub_processing_kernels.run_processing_kernel", - return_value=(torch.zeros(1, 1), torch.tensor([[2, 4, 6], [1, 2, 2]])), - ) as run_kernel: - output = Qwen2VLVideoProcessor(use_kernels=True)( - videos, do_sample_frames=False, cap_pixels_per_frame=False, return_tensors="pt" - ) - kernel_inputs, target_sizes = run_kernel.call_args.args[1:3] - 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): - with ( - patch.object(torch.cuda, "is_available", return_value=True), - patch.dict(_PROCESSING_KERNEL_ADAPTERS, {"resize_normalize": ("cv-utils", self.fail)}, clear=True), - patch.multiple( - "transformers.integrations.hub_kernels", - _kernels_enabled=True, - lazy_load_kernel=lambda name: types.ModuleType("sentinel_kernel_module"), - ), - ): - output = LevitImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) - self.assertIn("pixel_values", output) - - def test_processors_reaching_the_patchify_kernel_use_its_layout(self): - processor_classes = processors_calling_the_patchify_kernel() - for processor_class in (Qwen2VLImageProcessor, PaddleOCRVLImageProcessor, HunYuanVLImageProcessor): - self.assertIn(processor_class, processor_classes) - qwen3_vl_image_settings = {"patch_size": 16, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5]} - cases = [(processor_class, {}) for processor_class in processor_classes] - cases.append((Qwen2VLImageProcessor, qwen3_vl_image_settings)) - for processor_class, settings in cases: - with self.subTest(processor_class=processor_class.__name__, **settings): - processor = processor_class(use_kernels=True, **settings) - is_video = issubclass(processor_class, BaseVideoProcessor) - recorded_arguments = [] - - def run(height, width): - recorded_arguments.clear() - if is_video: - videos = [torch.randint(0, 256, (3, 3, height, width), dtype=torch.uint8)] - return processor(videos, do_sample_frames=False, return_tensors="pt")["pixel_values_videos"] - images = [torch.randint(0, 256, (3, height, width), dtype=torch.uint8)] - return processor(images, return_tensors="pt")["pixel_values"] - - with ( - patch.object(torch.cuda, "is_available", return_value=True), - patch.dict( - _PROCESSING_KERNEL_ADAPTERS, - { - "resize_normalize_patchify": ( - "cv-utils", - lambda kernel, inputs, target_sizes, *arguments: recorded_arguments.append( - (inputs, target_sizes, *arguments) - ), - ) - }, - clear=True, - ), - patch.multiple( - "transformers.integrations.hub_kernels", - _kernels_enabled=True, - lazy_load_kernel=lambda name: types.ModuleType("sentinel_kernel_module"), - ), - ): - height, width = 112, 168 - pixel_values = run(height, width) - if not recorded_arguments: - continue - for _ in range(3): - if recorded_arguments[0][1][0] == (height, width): - break - height, width = recorded_arguments[0][1][0] - pixel_values = run(height, width) - kernel_inputs, target_sizes = recorded_arguments[0][:2] - 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(*recorded_arguments[0]).reshape(-1) - ) - - def test_image_and_video_processors_run_through_preprocess(self): - """`use_processing_kernel` decorates `_preprocess`, so a processor whose entry point skips it never runs a kernel.""" - allowed = {"timm_wrapper.TimmWrapperImageProcessor"} - bypassing = [] - for path in sorted(Path(transformers.__file__).parent.glob("models/*/*_processing_*.py")): - if path.stem.startswith("modular_"): - continue - for node in ast.parse(path.read_text()).body: - if not isinstance(node, ast.ClassDef) or not node.name.endswith( - ("ImageProcessor", "ImageProcessorPil", "VideoProcessor") - ): - continue - for method in node.body: - if not isinstance(method, ast.FunctionDef) or method.name not in ("preprocess", "__call__"): - continue - source = ast.unparse(method) - name = f"{path.parent.name}.{node.name}" - if "_preprocess" not in source and "super()" not in source and name not in allowed: - bypassing.append(f"{name}.{method.name}") - self.assertEqual(bypassing, [], "these processors do not reach `_preprocess`") - - 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) - - -@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) - regions = (masks.flatten(0, 1) > 0).unsqueeze(1) - areas = run_processing_kernel("connected_component_areas", regions) - self.assertIsNotNone(areas, "the kernel did not run") - 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( - "transformers.models.sam2.image_processing_sam2.run_processing_kernel", - side_effect=lambda name, regions: connected_component_areas_reference(regions), - ): - 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 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_name, adapter = _PROCESSING_KERNEL_ADAPTERS[operation] - if not hasattr(lazy_load_kernel(kernel_name), operation): - self.skipTest(f"`{operation}` is not available in `{kernel_name}`") - kernel_outputs = [] - - def recording_adapter(*args, **kwargs): - kernel_outputs.append(adapter(*args, **kwargs)) - return kernel_outputs[-1] - - with patch.dict(_PROCESSING_KERNEL_ADAPTERS, {operation: (kernel_name, recording_adapter)}): - with_kernels = call(processor_class(use_kernels=True)) - self.assertTrue( - kernel_outputs and kernel_outputs[0] is not None, "the adapter fell back, the kernel never ran" - ) - 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" - ), - ) From 26115b0771f2f85b72daebdccc723f92e23f4be9 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 30 Oct 2026 11:45:18 +0900 Subject: [PATCH 24/26] test these processing kernels --- tests/kernels/test_processing_kernels.py | 454 +++++++++++++++++++++++ 1 file changed, 454 insertions(+) create mode 100644 tests/kernels/test_processing_kernels.py diff --git a/tests/kernels/test_processing_kernels.py b/tests/kernels/test_processing_kernels.py new file mode 100644 index 000000000000..b529c3c70d38 --- /dev/null +++ b/tests/kernels/test_processing_kernels.py @@ -0,0 +1,454 @@ +# 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 tokenizers import Tokenizer, models + +from transformers import ( + CLIPImageProcessor, + CLIPProcessor, + CohereCompassImageProcessor, + CohereCompassVideoProcessor, + Ernie4_5_VLMoeImageProcessor, + GlmImageImageProcessor, + HunYuanVLImageProcessor, + 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, run_processing_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, + 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, + interpolation, + 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, and accept CPU tensors as the kernel device.""" + with patch(f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel", return_value=kernel): + with patch(f"{HUB_PROCESSING_KERNELS}._KERNEL_DEVICE_TYPE", "cpu"): + 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_run_processing_kernel_falls_back(self): + regions = torch.zeros(1, 1, 4, 4, dtype=torch.bool) + kernel = MagicMock() + with patch(f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel", return_value=kernel): + self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) + kernel.connected_component_areas.assert_not_called() + with loaded_kernel(None): + self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) + self.assertIsNone(run_processing_kernel("not_a_registered_op", regions)) + + 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) + unsupported = { + "lanczos": ([image], PILImageResampling.LANCZOS), + "no_images": ([], PILImageResampling.BICUBIC), + "float_images": ([torch.rand(3, 4, 4)], PILImageResampling.BICUBIC), + "mixed_channels": ([image, torch.zeros(1, 4, 4, dtype=torch.uint8)], PILImageResampling.BICUBIC), + } + self.assertFalse(kernel_can_resize([image, image], PILImageResampling.BICUBIC)) + with patch(f"{HUB_PROCESSING_KERNELS}._KERNEL_DEVICE_TYPE", "cpu"): + for name, (inputs, resample) in unsupported.items(): + with self.subTest(name): + self.assertFalse(kernel_can_resize(inputs, resample)) + self.assertTrue(kernel_can_resize([image, image], PILImageResampling.BICUBIC)) + + 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.args[5], "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)) + + def test_resize_normalize_receives_the_sizes_of_resize(self): + images = [ + torch.randint(0, 255, (3, 40, 60), dtype=torch.uint8), + torch.randint(0, 255, (3, 50, 30), dtype=torch.uint8), + ] + size_dicts = { + "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}, + } + processor = ViTImageProcessor(use_kernels=True) + for name, size in size_dicts.items(): + with self.subTest(name): + kernel = MagicMock() + with loaded_kernel(kernel): + processor(images, size=size, do_center_crop=False, return_tensors=None) + self.assertEqual( + [tuple(size) for 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() + self.assertEqual(kernel.resize_normalize_patchify.call_args.args[6:], (14, 2, 2)) + self.assertIs(output["pixel_values"], pixel_values) + self.assertEqual(output["image_grid_thw"].tolist(), [[1, 4, 6]]) + + 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): + with patch("transformers.image_processing_backends.run_processing_kernel", self.fail): + output = LevitImageProcessor(use_kernels=True)([torch.randint(0, 255, (3, 64, 96), dtype=torch.uint8)]) + self.assertIn("pixel_values", output) + + def test_processors_reaching_the_patchify_kernel_use_its_layout(self): + qwen3_vl_image_settings = {"patch_size": 16, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5]} + cases = [(processor_class, {}) for processor_class in PATCHIFY_KERNEL_PROCESSORS] + cases.append((Qwen2VLImageProcessor, qwen3_vl_image_settings)) + for processor_class, settings in cases: + with self.subTest(processor_class=processor_class.__name__, **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.args, output[output_name] + + height, width = 112, 168 + for _ in range(4): + kernel_arguments, pixel_values = run(height, width) + if tuple(kernel_arguments[1][0]) == (height, width): + break + height, width = kernel_arguments[1][0] + kernel_inputs, target_sizes = kernel_arguments[:2] + 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_arguments).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}.lazy_load_kernel", return_value=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") + if not hasattr(kernel, "upsample_argmax"): + self.skipTest("`upsample_argmax` is not available in this build of cv-utils") + 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") + if not hasattr(kernel, operation): + self.skipTest(f"`{operation}` is not available in this build of cv-utils") + 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" + ), + ) From 8a67620211af0bf706316e2f8574c703a6e2a66a Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Fri, 30 Oct 2026 12:39:12 +0900 Subject: [PATCH 25/26] fix import --- src/transformers/integrations/hub_processing_kernels.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py index a0e43bfb09ac..64081f724450 100644 --- a/src/transformers/integrations/hub_processing_kernels.py +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -16,8 +16,7 @@ from functools import wraps from ..feature_extraction_utils import BatchFeature -from ..image_utils import PILImageResampling -from ..utils.import_utils import is_torch_available +from ..utils.import_utils import is_torch_available, is_vision_available if is_torch_available(): @@ -25,10 +24,14 @@ from .hub_kernels import lazy_load_kernel +if is_vision_available(): + from ..image_utils import PILImageResampling + + KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} + _PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} _KERNEL_DEVICE_TYPE = "cuda" -KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} def register_processing_kernel(name: str, kernel_name: str): From 3020c0aad61a98a186d6d5163e13b32b46f55cb6 Mon Sep 17 00:00:00 2001 From: Pablo Montalvo Date: Wed, 25 Nov 2026 11:33:31 +0100 Subject: [PATCH 26/26] drop registration in the end --- docs/source/en/kernel_doc/loading_kernels.md | 26 +-- src/transformers/image_processing_backends.py | 27 ++- src/transformers/image_processing_utils.py | 8 + .../integrations/hub_processing_kernels.py | 139 +++--------- .../video_processing_cohere_compass.py | 2 +- .../hunyuan_vl/image_processing_hunyuan_vl.py | 9 +- .../image_processing_pil_hunyuan_vl.py | 1 - .../models/hunyuan_vl/modular_hunyuan_vl.py | 32 +-- .../qwen2_vl/video_processing_qwen2_vl.py | 2 +- .../qwen3_vl/video_processing_qwen3_vl.py | 2 +- .../models/sam2/image_processing_sam2.py | 22 +- src/transformers/models/sam2/modular_sam2.py | 22 +- .../models/sam3/image_processing_sam3.py | 22 +- .../models/sam3_video/modeling_sam3_video.py | 4 +- tests/kernels/test_processing_kernels.py | 207 +++++++++++------- 15 files changed, 254 insertions(+), 271 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index aefd706176d8..8df636c7d87f 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -336,7 +336,7 @@ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kerne 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. +[`AutoProcessor`] passes the flag to its image and video processors. Kernels run on the device of the inputs, so pass `device="cuda"`. Loading a processor with `use_kernels=True` raises an error when `kernels` is not installed. 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. 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. @@ -344,32 +344,20 @@ When both sides are upsampled at least 2x, the upsample and argmax kernel runs o ### Adding a processing kernel -A processing kernel has two levels in `integrations/hub_processing_kernels.py`. - -`register_processing_kernel` maps an operation to a kernel of `_HUB_KERNEL_MAPPING`, so each operation can come from its own kernel repository. The adapter receives the loaded kernel module and the arguments of the operation. It checks what the kernel supports, such as the device, and returns `None` for arguments the kernel cannot handle. `run_processing_kernel` loads the kernel and calls the adapter, or returns `None` when the kernel does not load. - -`use_processing_kernel` connects a processor method to an operation. 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`. For example, this is how semantic segmentation post-processing uses `upsample_argmax`: +`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`. `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 ( - register_processing_kernel, - run_processing_kernel, - use_processing_kernel, -) - - -@register_processing_kernel("upsample_argmax", kernel_name="cv-utils") -def _upsample_argmax_kernel(kernel, logits, target_sizes): - if logits.device.type != "cuda": - return None - return kernel.upsample_argmax(logits, target_sizes) +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, **kwargs): if return_segmentation_scores or target_sizes is None: return None - return run_processing_kernel("upsample_argmax", outputs.logits, target_sizes) + 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): diff --git a/src/transformers/image_processing_backends.py b/src/transformers/image_processing_backends.py index 73e45aaa8ee5..6ea94a518c4d 100644 --- a/src/transformers/image_processing_backends.py +++ b/src/transformers/image_processing_backends.py @@ -53,7 +53,7 @@ is_valid_image, load_image_as_tensor, ) -from .integrations.hub_processing_kernels import run_processing_kernel, use_processing_kernel +from .integrations.hub_processing_kernels import kernel_can_resize, load_cv_utils_kernel, use_processing_kernel from .processing_utils import ImagesKwargs, Unpack from .utils import ( TensorType, @@ -67,6 +67,7 @@ if is_vision_available(): from .image_utils import PILImageResampling + from .integrations.hub_processing_kernels import KERNEL_INTERPOLATIONS if is_torch_available(): import torch @@ -105,7 +106,14 @@ def resize_normalize_with_kernel( getattr(type(processor), name) is getattr(TorchvisionBackend, name) for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") ) - if not (uses_default_resize_and_normalize and do_resize and do_rescale and do_normalize and not do_pad): + if not ( + uses_default_resize_and_normalize + and do_resize + and do_rescale + and do_normalize + and not do_pad + and kernel_can_resize(images, resample) + ): return None sizes = [processor._resize_output_size(image, size) for image in images] crop = None @@ -113,11 +121,18 @@ def resize_normalize_with_kernel( 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 = run_processing_kernel( - "resize_normalize", images, sizes, crop, resample, rescale_factor, image_mean, image_std - ) - if pixel_values is None: + kernel = load_cv_utils_kernel(images[0].device) + if kernel is None: 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) diff --git a/src/transformers/image_processing_utils.py b/src/transformers/image_processing_utils.py index 16f35afc12e3..437431fda626 100644 --- a/src/transformers/image_processing_utils.py +++ b/src/transformers/image_processing_utils.py @@ -34,10 +34,12 @@ from .processing_utils import ImagesKwargs, Unpack from .utils import ( auto_docstring, + is_kernels_available, is_torchvision_available, is_vision_available, logging, ) +from .utils.import_utils import KERNELS_MAX_VERSION, KERNELS_MIN_VERSION if is_vision_available(): @@ -194,6 +196,12 @@ class MyImageProcessor(TorchvisionBackend): model_input_names = ["pixel_values"] def __init__(self, **kwargs: Unpack[ImagesKwargs]): + if kwargs.get("use_kernels") and not is_kernels_available(): + raise ValueError( + "Kernels are not available. " + f"Please install a compatible version ({KERNELS_MIN_VERSION} <= version < {KERNELS_MAX_VERSION}), " + f"e.g. `pip install kernels=={KERNELS_MIN_VERSION}`" + ) super().__init__(**kwargs) # We don't call self._set_attributes in BaseImageProcessor for backward compatibility with remote code # We call it instead in the backend subclasses' __init__ methods. diff --git a/src/transformers/integrations/hub_processing_kernels.py b/src/transformers/integrations/hub_processing_kernels.py index 64081f724450..7d0d2912d7f0 100644 --- a/src/transformers/integrations/hub_processing_kernels.py +++ b/src/transformers/integrations/hub_processing_kernels.py @@ -30,35 +30,14 @@ KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} -_PROCESSING_KERNEL_ADAPTERS: dict[str, tuple[str, Callable]] = {} _KERNEL_DEVICE_TYPE = "cuda" -def register_processing_kernel(name: str, kernel_name: str): - """ - Register the kernel `kernel_name` of `_HUB_KERNEL_MAPPING` as an implementation of the processing op `name`. - - Processing ops have no common signature to swap, so the decorated function is an adapter: it receives the loaded - kernel module followed by the arguments of the op, and returns the kernel result, or `None` when the kernel - cannot handle these arguments so that the caller keeps its default implementation. - """ - - def register(adapter: Callable) -> Callable: - _PROCESSING_KERNEL_ADAPTERS[name] = (kernel_name, adapter) - return adapter - - return register - - -def run_processing_kernel(name: str, *args, **kwargs): - """Run the kernel registered for the processing op `name`, or return `None` if the default path should be used.""" - if not is_torch_available() or name not in _PROCESSING_KERNEL_ADAPTERS: +def load_cv_utils_kernel(device): + """The `kernels-community/cv-utils` kernel for tensors on `device`, or `None` to keep the default path.""" + if device.type != _KERNEL_DEVICE_TYPE: return None - kernel_name, adapter = _PROCESSING_KERNEL_ADAPTERS[name] - kernel = lazy_load_kernel(kernel_name) - if kernel is None: - return None - return adapter(kernel, *args, **kwargs) + return lazy_load_kernel("cv-utils") def kernel_can_resize(images, resample): @@ -76,61 +55,6 @@ def kernel_can_resize(images, resample): ) -@register_processing_kernel("connected_component_areas", kernel_name="cv-utils") -def _connected_component_areas_kernel(kernel, regions): - """Area of the 8-connected component of every pixel of a boolean `(batch_size, 1, height, width)` tensor.""" - if regions.device.type != _KERNEL_DEVICE_TYPE: - return None - return kernel.connected_component_areas(regions) - - -@register_processing_kernel("resize_normalize", kernel_name="cv-utils") -def _resize_normalize_kernel(kernel, images, sizes, crop_size, resample, rescale_factor, image_mean, image_std): - """Resize every image to its size in `sizes`, center crop to `crop_size` when given, then rescale and normalize.""" - if not kernel_can_resize(images, resample): - return None - return kernel.resize_normalize( - images, sizes, image_mean, image_std, rescale_factor, KERNEL_INTERPOLATIONS[resample], crop_size=crop_size - ) - - -@register_processing_kernel("resize_normalize_patchify", kernel_name="cv-utils") -def _resize_normalize_patchify_kernel( - kernel, - inputs, - target_sizes, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - patch_block_size, - temporal_patch_size, -): - """Resize every `(T, C, H, W)` input to its target frame size, normalize, and write its patches in order.""" - if not kernel_can_resize(inputs, resample): - return None - return kernel.resize_normalize_patchify( - inputs, - target_sizes, - image_mean, - image_std, - rescale_factor, - KERNEL_INTERPOLATIONS[resample], - patch_size, - patch_block_size, - temporal_patch_size, - ) - - -@register_processing_kernel("upsample_argmax", kernel_name="cv-utils") -def _upsample_argmax_kernel(kernel, logits, target_sizes): - """Class of every pixel of `logits` `(B, C, h, w)` upsampled to `target_sizes`, without the upsampled logits.""" - if logits.device.type != _KERNEL_DEVICE_TYPE: - return None - return kernel.upsample_argmax(logits, target_sizes) - - def use_processing_kernel(run_with_kernel: Callable): """ Decorate a processor method so that `use_kernels=True` first runs `run_with_kernel`. @@ -178,7 +102,10 @@ def resize_normalize_patchify_images_with_kernel( **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): + 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( @@ -186,21 +113,17 @@ def resize_normalize_patchify_images_with_kernel( ) for image in images ] - kernel_output = run_processing_kernel( - "resize_normalize_patchify", + pixel_values, image_grid_thw = kernel.resize_normalize_patchify( [image[None] for image in images], target_sizes, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - getattr(processor, "patch_block_size", merge_size), - temporal_patch_size, + 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 kernel_output is None: - return None - pixel_values, image_grid_thw = kernel_output 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( @@ -227,7 +150,10 @@ def resize_normalize_patchify_videos_with_kernel( **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): + 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( @@ -241,21 +167,17 @@ def resize_normalize_patchify_videos_with_kernel( ) for video in videos ] - kernel_output = run_processing_kernel( - "resize_normalize_patchify", + pixel_values_videos, video_grid_thw = kernel.resize_normalize_patchify( videos, target_sizes, - resample, - rescale_factor, - image_mean, - image_std, - patch_size, - getattr(processor, "patch_block_size", merge_size), - temporal_patch_size, + 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 kernel_output is None: - return None - pixel_values_videos, video_grid_thw = kernel_output return BatchFeature( data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw}, tensor_type=return_tensors ) @@ -265,4 +187,7 @@ def upsample_argmax_with_kernel(processor, outputs, target_sizes, return_segment """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 - return run_processing_kernel("upsample_argmax", outputs.logits, target_sizes) + 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/cohere_compass/video_processing_cohere_compass.py b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py index 8d3a5a6a7b2a..e6716321ba95 100644 --- a/src/transformers/models/cohere_compass/video_processing_cohere_compass.py +++ b/src/transformers/models/cohere_compass/video_processing_cohere_compass.py @@ -188,7 +188,7 @@ 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, **kwargs, ) -> "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 ee698bbab734..18f075405a36 100644 --- a/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/image_processing_hunyuan_vl.py @@ -122,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. " @@ -158,10 +162,7 @@ def resize( 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): 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 58f8accdfba4..5d3ba44aca1b 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 diff --git a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py index 2217e638de65..a071b005f576 100644 --- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py @@ -13,21 +13,20 @@ # limitations under the License. import itertools -from collections.abc import Callable +from collections.abc import Callable, Iterable from dataclasses import dataclass 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 @@ -349,25 +348,18 @@ def patch_block_size(self): """Patches are written row by row, not in `merge_size` blocks.""" return 1 - def resize( + 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.""" - resized_height, resized_width = self._resized_size(*images.shape[-2:], size, factor) - 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, 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 908d40bc1cdd..1b83f7b04029 100644 --- a/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py @@ -242,7 +242,7 @@ 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, **kwargs, ) -> "torch.Tensor": 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 fbbd5f1ead2f..ed5b826ff9ad 100644 --- a/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/video_processing_qwen3_vl.py @@ -191,7 +191,7 @@ 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, **kwargs, ) -> "torch.Tensor": diff --git a/src/transformers/models/sam2/image_processing_sam2.py b/src/transformers/models/sam2/image_processing_sam2.py index 021042d1fbde..c036882f29d8 100644 --- a/src/transformers/models/sam2/image_processing_sam2.py +++ b/src/transformers/models/sam2/image_processing_sam2.py @@ -37,7 +37,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +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 @@ -690,20 +690,22 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. 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`, with the cv-utils kernel.""" + """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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) - return regions.reshape_as(masks) + 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 c94ed5f01e9f..71e61609855c 100644 --- a/src/transformers/models/sam2/modular_sam2.py +++ b/src/transformers/models/sam2/modular_sam2.py @@ -34,7 +34,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +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 @@ -259,20 +259,22 @@ 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`, with the cv-utils kernel.""" + """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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) - return regions.reshape_as(masks) + 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 28bfea8a3f21..a1939356abf3 100644 --- a/src/transformers/models/sam3/image_processing_sam3.py +++ b/src/transformers/models/sam3/image_processing_sam3.py @@ -40,7 +40,7 @@ PILImageResampling, SizeDict, ) -from ...integrations.hub_processing_kernels import run_processing_kernel +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 @@ -721,20 +721,22 @@ def _apply_non_overlapping_constraints(self, pred_masks: torch.Tensor) -> torch. 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`, with the cv-utils kernel.""" + """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 = run_processing_kernel("connected_component_areas", region) if self.use_kernels else None - if areas 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 = torch.where(region & (areas <= max_area), mask_threshold + score_offset, regions) - return regions.reshape_as(masks) + 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, diff --git a/src/transformers/models/sam3_video/modeling_sam3_video.py b/src/transformers/models/sam3_video/modeling_sam3_video.py index 17003aba1ca7..b4bd28fddae9 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/tests/kernels/test_processing_kernels.py b/tests/kernels/test_processing_kernels.py index b529c3c70d38..b910f092bc9c 100644 --- a/tests/kernels/test_processing_kernels.py +++ b/tests/kernels/test_processing_kernels.py @@ -22,6 +22,7 @@ import numpy as np import torch +from parameterized import parameterized from tokenizers import Tokenizer, models from transformers import ( @@ -46,7 +47,7 @@ ) 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, run_processing_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 @@ -88,7 +89,7 @@ def patchify_kernel_layout_reference( image_mean, image_std, rescale_factor, - interpolation, + resample, patch_size, block_size, temporal_patch_size, @@ -146,6 +147,9 @@ class TestProcessingKernels(TestCasePlus): def setUp(self): super().setUp() + kernels_available = patch("transformers.image_processing_utils.is_kernels_available", return_value=True) + kernels_available.start() + self.addCleanup(kernels_available.stop) # 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 @@ -156,15 +160,33 @@ 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_run_processing_kernel_falls_back(self): - regions = torch.zeros(1, 1, 4, 4, dtype=torch.bool) - kernel = MagicMock() - with patch(f"{HUB_PROCESSING_KERNELS}.lazy_load_kernel", return_value=kernel): - self.assertIsNone(run_processing_kernel("connected_component_areas", regions)) - kernel.connected_component_areas.assert_not_called() + 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(run_processing_kernel("connected_component_areas", regions)) - self.assertIsNone(run_processing_kernel("not_a_registered_op", regions)) + self.assertIsNone(load_cv_utils_kernel(torch.device("cpu"))) + + def test_use_kernels_needs_kernels(self): + with patch("transformers.image_processing_utils.is_kernels_available", return_value=False): + with self.assertRaisesRegex(ValueError, "Kernels are not available"): + ViTImageProcessor(use_kernels=True) + with self.assertRaisesRegex(ValueError, "Kernels are not available"): + Qwen2VLVideoProcessor(use_kernels=True) + ViTImageProcessor(use_kernels=False) + + 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() @@ -184,19 +206,26 @@ def test_sam2_small_regions_need_the_kernel(self): def test_kernel_can_resize(self): image = torch.zeros(3, 4, 4, dtype=torch.uint8) - unsupported = { - "lanczos": ([image], PILImageResampling.LANCZOS), - "no_images": ([], PILImageResampling.BICUBIC), - "float_images": ([torch.rand(3, 4, 4)], PILImageResampling.BICUBIC), - "mixed_channels": ([image, torch.zeros(1, 4, 4, dtype=torch.uint8)], PILImageResampling.BICUBIC), - } self.assertFalse(kernel_can_resize([image, image], PILImageResampling.BICUBIC)) with patch(f"{HUB_PROCESSING_KERNELS}._KERNEL_DEVICE_TYPE", "cpu"): - for name, (inputs, resample) in unsupported.items(): - with self.subTest(name): - self.assertFalse(kernel_can_resize(inputs, resample)) 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): + with patch(f"{HUB_PROCESSING_KERNELS}._KERNEL_DEVICE_TYPE", "cpu"): + 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)) @@ -223,8 +252,8 @@ 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.args[5], "bilinear") + 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( @@ -233,27 +262,27 @@ def test_resize_normalize_falls_back_on_a_crop_larger_than_the_resize(self): kernel.resize_normalize.assert_not_called() self.assertEqual(tuple(output["pixel_values"][0].shape), (3, 8, 10)) - def test_resize_normalize_receives_the_sizes_of_resize(self): + @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), ] - size_dicts = { - "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}, - } processor = ViTImageProcessor(use_kernels=True) - for name, size in size_dicts.items(): - with self.subTest(name): - kernel = MagicMock() - with loaded_kernel(kernel): - processor(images, size=size, do_center_crop=False, return_tensors=None) - self.assertEqual( - [tuple(size) for size in kernel.resize_normalize.call_args.args[1]], - [tuple(processor.resize(image, SizeDict(**size)).shape[-2:]) for image in images], - ) + 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)] @@ -264,10 +293,26 @@ def test_qwen2_vl_uses_the_patchify_kernel_output(self): output = Qwen2VLImageProcessor(use_kernels=True)(images, return_tensors="pt") Qwen2VLImageProcessor(use_kernels=False)(images, return_tensors="pt") kernel.resize_normalize_patchify.assert_called_once() - self.assertEqual(kernel.resize_normalize_patchify.call_args.args[6:], (14, 2, 2)) + 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), @@ -285,46 +330,54 @@ def test_qwen2_vl_video_passes_one_target_size_per_video(self): 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): - with patch("transformers.image_processing_backends.run_processing_kernel", self.fail): + 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) - def test_processors_reaching_the_patchify_kernel_use_its_layout(self): - qwen3_vl_image_settings = {"patch_size": 16, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5]} - cases = [(processor_class, {}) for processor_class in PATCHIFY_KERNEL_PROCESSORS] - cases.append((Qwen2VLImageProcessor, qwen3_vl_image_settings)) - for processor_class, settings in cases: - with self.subTest(processor_class=processor_class.__name__, **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.args, output[output_name] - - height, width = 112, 168 - for _ in range(4): - kernel_arguments, pixel_values = run(height, width) - if tuple(kernel_arguments[1][0]) == (height, width): - break - height, width = kernel_arguments[1][0] - kernel_inputs, target_sizes = kernel_arguments[:2] - 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_arguments).reshape(-1) - ) + @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) @@ -381,8 +434,6 @@ class TestUpsampleArgmaxKernel(TestCasePlus): def test_matches_default(self): kernel = lazy_load_kernel("cv-utils") self.assertIsNotNone(kernel, "the cv-utils kernel did not load") - if not hasattr(kernel, "upsample_argmax"): - self.skipTest("`upsample_argmax` is not available in this build of cv-utils") 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)] @@ -415,8 +466,6 @@ def setUp(self): 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") - if not hasattr(kernel, operation): - self.skipTest(f"`{operation}` is not available in this build of cv-utils") 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()