Skip to content

Support custom kernels for processing ops - #46771

Open
molbap wants to merge 36 commits into
mainfrom
processing_kernels
Open

molbap wants to merge 36 commits into
mainfrom
processing_kernels

Conversation

@molbap

@molbap molbap commented Jun 19, 2026 •

Copy link
Copy Markdown
Collaborator

🤗 Transformers CI

What does this PR do?

TL;DR Preprocessing and postprocessing ops can be offloaded to Hub kernels the same way model layers currently are. This PR allows this and goes with a first simple kernel that is common to many image processors.

use_kernels=True swaps a processor op for a registered Hub kernel and falls back to the default implementation when none applies. So custom or hard-to-vectorize ops (beyond resize or normalize: patchify, NMS, mask decoding, ...) can move onto the GPU without rewriting the processor or the call site.

However the adapter is uglier than for modeling components, mainly because there's no same-signature forward to swap and no kernelize pass over processors. Open to ideas here!

I pushed a fast image processors' resize + normalize that is automatic for processors using the base fast-processing path others fall back and can opt in later. The kernel batches the resize over a ragged set of images and folds rescale and normalize into the same pass.

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.

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")

Some benchmarks for processors of vision models showing the speedup:

processor() resize+normalize, use_kernels off -> on:
siglip2-base-patch16-224     3.92 -> 1.30 ms   3.0x   pixΔ 3.9e-3
paligemma2-3b-pt-224         4.26 -> 1.36 ms   3.1x   pixΔ 3.9e-3
clip-vit-base-patch32        7.30 -> 1.41 ms   5.2x   pixΔ 1.8e-2
dinov2-small                 7.26 -> 1.42 ms   5.1x   pixΔ 2.5e-1


standalone resize stage (siglip-so400m, bicubic+AA):
torchvision eager loop   2.95 ms
torch.compile (dynamic)  5.65 ms   (slower; ~2.6s warmup)
fused triton (2D)       11.53 ms
separable triton        1.37 ms    -> 2.9x the real processor (3.96 ms)

Need to move the kernel from Molbap/<kernel_name> and open this to the community. Feedback welcome :)

@HuggingFaceDocBuilderDev

HuggingFaceDocBuilderDev commented Jun 19, 2026 •

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@molbap molbap changed the title [WIP] Support custom kernels for processing ops Support custom kernels for processing ops Oct 9, 2026

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super happy to have it in transformers! First review i left mostly questions since i am not following in some places

| 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) |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some of these patchify/permute into slightly different shape, eg. iirc hunyuan. Does the kernel somehow know how to handle it or do we have to re-permute-resize after transforms?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the kernel takes in a merge_size arg and writes directly the patches, there's no permute. qwen2 vl writes patches in blocks of that size but hunyuan (and padddle ocr vl) write them row by row so it's equivalent to a block size of 1. Actually block_size is a slighlty better naming, maybe vision_block_size? merge_size is a bad name

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switched the names a bit, it should be better

Comment on lines +80 to +81
or image.device != images[0].device
or image.shape[0] != images[0].shape[0]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why we verify against the first image and not a hardcoded expected value?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's one launch for the whole batch, so the images need the same device and channel count. The count can be 1 or 3, so I compare to the first image instead of hardcoding it. Looking back at it, the function was doing too much anyway, and the isinstance/ndim checks never trigger after process_image. Split it into _kernel_supports + the interpolation lookup

Comment on lines +99 to +105
if size.height and size.width:
if crop is not None and (crop[0] > size.height or crop[1] > size.width):
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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so if we want to only resize and crop=None , the kernel can't be applied?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed height/width without a crop did use the kernel but shortest_edge without a crop didn't.. that was hard to follow anyway, simplified a bit, now the processor computes every target size with _resize_output_size (same method resize uses) and the kernel just takes one size per image, so crop or no crop doesn't matter anymore.

patch_size,
merge_size,
temporal_patch_size,
items=items,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are items here? not sure if we should document more these kernel-fns as they're private. oke, lemme check qwen files, maybe it will make more sense

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those were the frame indices of videos, but again, bad naming. it's just "inputs" now, and hopefully clearer

"resize_normalize",
images,
size,
crop_size if do_center_crop else None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow, we have do_center_crop? seeing it first time lol, ig a new flag added in v5

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, it was from CLIP haha. It's still used by their processors

Comment on lines +248 to +257
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
]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not all models expect same args for smart resize, can we infer it outside kernel fn and pass a valid size ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, I moved the size logic of resize to a _resized_size method. It's what's tricky with these kernels, have to keep track of 2 mechanisms for the same job in 2 places

"resize_normalize_patchify",
images,
target_sizes,
resample if forced_resample is None else forced_resample,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is that hunyuanl-vl?
i asked them to update config on the hub and got ignored 💀 IIRC it's the only weird model so i can try to push for it again, not liking the force override

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes it is... 😬 I rmoved forced_resample, hunyuan now sets BICUBIC once in its init so resize and the kernel have to read resample and that's it, a bit better no?

If you manage to get the hub config fixed we can drop that line too 🙏

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i will ping him again now, lets see

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update: bicubic is now forced on every call, not just at init. the override stays until the hub config is fixed

--- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py
+++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py
-    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(
+    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),
-            resample=resample,
-        )
+    ) -> 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)

Comment on lines -190 to +199
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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am not following here, why we needed a default for only one of args and split the fn into two?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modular modular, why are you modular

so the video kernel needs the frame size, but not resizing, qwen3vl does not override resize, so compass inherits that bejaviour and gets temporal_factor=2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modular modular, why are you modular

readin my mind every time smth breaks 😆

"""Torchvision backend for GPU-accelerated batched image processing."""

def __init__(self, **kwargs: Unpack[ImagesKwargs]):
self.use_kernels = kwargs.pop("use_kernels", False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like the same thing as in proc.from_dict, and in most cases overriden afterwards. I suppose left-over from prev commit since PIL class doesn't have it ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, it was set twice yes. I changed it in from_dicrt of the processor to pass use_kernels but not sure abt it, maybe @vasqu has an idea?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

follow-up: the line is gone. use_kernels = False is a class default now, and from_pretrained only forwards it to the image and video processors

--- a/src/transformers/image_processing_backends.py
+++ b/src/transformers/image_processing_backends.py
     def __init__(self, **kwargs: Unpack[ImagesKwargs]):
-        self.use_kernels = kwargs.pop("use_kernels", False)
         super().__init__(**kwargs)
         self._set_attributes(**kwargs)
--- a/src/transformers/image_processing_utils.py
+++ b/src/transformers/image_processing_utils.py
     valid_kwargs = ImagesKwargs
+    use_kernels = False
--- a/src/transformers/processing_utils.py
+++ b/src/transformers/processing_utils.py
+                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
                 )

@molbap molbap left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @zucchini-nlp , did a simplify/update round and answered your comments!

| 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) |

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the kernel takes in a merge_size arg and writes directly the patches, there's no permute. qwen2 vl writes patches in blocks of that size but hunyuan (and padddle ocr vl) write them row by row so it's equivalent to a block size of 1. Actually block_size is a slighlty better naming, maybe vision_block_size? merge_size is a bad name

| 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) |

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switched the names a bit, it should be better

Comment on lines +80 to +81
or image.device != images[0].device
or image.shape[0] != images[0].shape[0]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's one launch for the whole batch, so the images need the same device and channel count. The count can be 1 or 3, so I compare to the first image instead of hardcoding it. Looking back at it, the function was doing too much anyway, and the isinstance/ndim checks never trigger after process_image. Split it into _kernel_supports + the interpolation lookup

Comment on lines +99 to +105
if size.height and size.width:
if crop is not None and (crop[0] > size.height or crop[1] > size.width):
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:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed height/width without a crop did use the kernel but shortest_edge without a crop didn't.. that was hard to follow anyway, simplified a bit, now the processor computes every target size with _resize_output_size (same method resize uses) and the kernel just takes one size per image, so crop or no crop doesn't matter anymore.

patch_size,
merge_size,
temporal_patch_size,
items=items,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those were the frame indices of videos, but again, bad naming. it's just "inputs" now, and hopefully clearer

Comment on lines +248 to +257
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
]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, I moved the size logic of resize to a _resized_size method. It's what's tricky with these kernels, have to keep track of 2 mechanisms for the same job in 2 places

"resize_normalize_patchify",
images,
target_sizes,
resample if forced_resample is None else forced_resample,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes it is... 😬 I rmoved forced_resample, hunyuan now sets BICUBIC once in its init so resize and the kernel have to read resample and that's it, a bit better no?

If you manage to get the hub config fixed we can drop that line too 🙏

Comment on lines -190 to +199
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(

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modular modular, why are you modular

so the video kernel needs the frame size, but not resizing, qwen3vl does not override resize, so compass inherits that bejaviour and gets temporal_factor=2

"""Torchvision backend for GPU-accelerated batched image processing."""

def __init__(self, **kwargs: Unpack[ImagesKwargs]):
self.use_kernels = kwargs.pop("use_kernels", False)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, it was set twice yes. I changed it in from_dicrt of the processor to pass use_kernels but not sure abt it, maybe @vasqu has an idea?

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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually better like this too

@molbap

molbap commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

BTW be sure to look at huggingface/kernels-community#1182 as well that contains the new custom kernels + a part of the needed-to-know processing logic I initially put on transformers side and is now there

@zucchini-nlp

Copy link
Copy Markdown
Member

i will take a look today if i have a chance but dont feel blocked by me, @vasqu if you want to review

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a few more comments but looks much easier to follow or me now, thanks for adding more docstring and pointers around

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]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we can do inside loop image.device == _KERNEL_DEVICE_TYPE directly

Also just curious - so the kernel actually supports 1/4 channel images?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure ! and yes, any channel count works, the kernel takes one mean/std per channel, it only needs the same count across the batch, that's why it compares to the first image

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, it's in the loop in kernel_can_resize

-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
-        )
-    )
+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
+        )
+    )

Comment on lines +101 to +102
merge_size = 2
patch_block_size = 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what s the diff betweem merge size and the new arg?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

worth explaining a bit yeah so, hunyuan has merge_size=2 like qwen2: in the model, 2x2 patches become one toke. patch_block_size is only about the processor output, that is, in which order the patches are listed in pixel_values (what I'm interested in when writing the kernel). So:

  • qwen2: the 4 patches of each 2x2 group come one after the other (block of 2), because the qwen2 merger just takes 4 consecutive rows
  • hunyuan: patches are listed row by row (block of 1), because the hunyuan merger reshapes back to the 2D grid and finds the 2x2 groups itself

So basically

qwen2, block 2         hunyuan / paddle, block 1
 0  1 |  4  5           0  1  2  3
 2  3 |  6  7           4  5  6  7
------+------           8  9 10 11
 8  9 | 12 13          12 13 14 15
10 11 | 14 15

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merger reshapes back to the 2D grid and finds the 2x2 groups itself

wtf 🫠 Oke that is on me i think, didn't realize it was same code under after all permiutations

then i think my only concern would be to make them a non-saved class attr, maybe a property so it can't be set and is only read or smth like that

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tbh the code is real hard to read haha. after 6 args in permute() call my brain stops working

and yeah I think it'd be better indeed, checking

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, patch_block_size is a read-only property now

     patch_size = 16
     temporal_patch_size = 1
     merge_size = 2
-    patch_block_size = 1
-    flat_patches = True
     valid_kwargs = HunYuanVLImageProcessorKwargs
@@
+    @property
+    def patch_block_size(self):
+        """Patches are written row by row, not in `merge_size` blocks."""
+        return 1

Comment on lines +181 to +182
patch_block_size = 1
flat_patches = False

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah here i see the diff, so iiuc it's about permuting inputs when "pathcify"? Though hunyan actually permutes the merge dim with grid_h // merge_size, 🤔

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, it just changes the order of patches in pixel_values. For hunyuan, it splits the grid by merge_size, like qwen2, but the permite keeps the dim in same order so there is no split, and the patches come out row by row

qwen2 does shift the dims, so groups are created (see the ASCII in my other comment), I simplified hunyuan patchify to reshape to rows directly. Same output but my understanding is wrong

Comment on lines +284 to +298
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}."

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice helper

logger = logging.get_logger(__name__)


def resize_normalize_with_kernel(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cant see where it is called, forgot to cleanup? 👀

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is the default in the decorator call!

temporal_patch_size = 2
merge_size = 2
patch_block_size = None
flat_patches = True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really a fan of adding more fields into config tbh. This looks more like a ClassVar in configs, the non-saved static class attr that is not supposed to be set/changes etc

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed, only hunyuan and paddle define them now, as read-only properties

--- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py
+++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py
     temporal_patch_size = 2
     merge_size = 2
-    patch_block_size = None
-    flat_patches = True
     valid_kwargs = CohereCompassImageProcessorKwargs
--- a/src/transformers/integrations/hub_processing_kernels.py
+++ b/src/transformers/integrations/hub_processing_kernels.py
-        merge_size if processor.patch_block_size is None else processor.patch_block_size,
+        block_size=getattr(processor, "patch_block_size", merge_size),
@@
-    if not processor.flat_patches:
+    if not getattr(processor, "flatten_patches", True):

@guarin guarin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very very cool! Looking forward to kernelize pre- and post-processing!

factor: int,
temporal_factor: int,
temporal_factor: int = 2,
cap_pixels_per_frame: bool | None = None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed because it is called temporal_patch_size in _preprocess?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, every caller passes it. the default came along when I moved resize up into qwen2-vl, removed it

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correction: I put the default back, it's public since v5.16

Comment on lines +102 to +103
patch_block_size = 1
flat_patches = True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these attributes be saved in the config or not?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, it's the patch order the model expects. it's a read-only property now

     patch_size = 16
     temporal_patch_size = 1
     merge_size = 2
-    patch_block_size = 1
-    flat_patches = True
     valid_kwargs = HunYuanVLImageProcessorKwargs
@@
+    @property
+    def patch_block_size(self):
+        """Patches are written row by row, not in `merge_size` blocks."""
+        return 1

Comment on lines +732 to +735
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."
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't logger warning crash under torch.compile?

Also I think we should avoid logger altogether in code that can run in a torch dataloader as it is error prone to random deadlocks due to process forking.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point... now it raises!


def __init__(self, **kwargs: Unpack[ImagesKwargs]):
self.use_kernels = kwargs.pop("use_kernels", False)
super().__init__(**kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if use_kernels is passed to a pil processor?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

before it was doing nothing, now it will raise :D

- 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
drbh pushed a commit to huggingface/kernels-community that referenced this pull request Nov 10, 2026
This adds Triton functions to cv-utils for pre- and post-processing in
transformers.

- resize_normalize: antialiased resize, center crop, rescale and
normalize of uint8 images of different sizes, in one call.
- resize_normalize_patchify: the same, written directly in the Qwen2-VL
patch layout, for images and videos.
- upsample_argmax: segmentation class map from low-resolution logits,
without storing the upsampled logits.
- connected_component_areas: cc_2d for masks of any height and width.
                         
The transformers side is github.com/huggingface/transformers/pull/46771,
where image processors call these kernels with use_kernels=True.

This bumps cv-utils to v2. Tests compare against
torch.nn.functional.interpolate and are in the kernels_ci subset.

---------

Co-authored-by: guarin <43336610+guarin@users.noreply.github.com>

@molbap molbap left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @zucchini-nlp @guarin ! main changes since your last review:

  • after a loooot of hesitation I dropped the kernel registry, the helpers load cv-utils directly (like deepgemm / sonicmoe)
  • kept temporal_factor=2 in qwen2-vl's resize, it's public since v5.16
  • sam2 / sam3 find holes and sprinkles on the input mask, like upstream
  • hunyuan always resizes bicubic, like the reference
  • use_kernels=True raises without kernels installed, and on pil processors
  • new op: upsample + argmax for semantic segmentation
  • hy-v4-vl images use the kernel, its video stays on the default path, since it's a new model I think it's ok

"""Torchvision backend for GPU-accelerated batched image processing."""

def __init__(self, **kwargs: Unpack[ImagesKwargs]):
self.use_kernels = kwargs.pop("use_kernels", False)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

follow-up: the line is gone. use_kernels = False is a class default now, and from_pretrained only forwards it to the image and video processors

--- a/src/transformers/image_processing_backends.py
+++ b/src/transformers/image_processing_backends.py
     def __init__(self, **kwargs: Unpack[ImagesKwargs]):
-        self.use_kernels = kwargs.pop("use_kernels", False)
         super().__init__(**kwargs)
         self._set_attributes(**kwargs)
--- a/src/transformers/image_processing_utils.py
+++ b/src/transformers/image_processing_utils.py
     valid_kwargs = ImagesKwargs
+    use_kernels = False
--- a/src/transformers/processing_utils.py
+++ b/src/transformers/processing_utils.py
+                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
                 )

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]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, it's in the loop in kernel_can_resize

-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
-        )
-    )
+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
+        )
+    )

"resize_normalize_patchify",
images,
target_sizes,
resample if forced_resample is None else forced_resample,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update: bicubic is now forced on every call, not just at init. the override stays until the hub config is fixed

--- a/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py
+++ b/src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py
-    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(
+    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),
-            resample=resample,
-        )
+    ) -> 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)

temporal_patch_size = 2
merge_size = 2
patch_block_size = None
flat_patches = True

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed, only hunyuan and paddle define them now, as read-only properties

--- a/src/transformers/models/cohere_compass/image_processing_cohere_compass.py
+++ b/src/transformers/models/cohere_compass/image_processing_cohere_compass.py
     temporal_patch_size = 2
     merge_size = 2
-    patch_block_size = None
-    flat_patches = True
     valid_kwargs = CohereCompassImageProcessorKwargs
--- a/src/transformers/integrations/hub_processing_kernels.py
+++ b/src/transformers/integrations/hub_processing_kernels.py
-        merge_size if processor.patch_block_size is None else processor.patch_block_size,
+        block_size=getattr(processor, "patch_block_size", merge_size),
@@
-    if not processor.flat_patches:
+    if not getattr(processor, "flatten_patches", True):

factor: int,
temporal_factor: int,
temporal_factor: int = 2,
cap_pixels_per_frame: bool | None = None,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correction: I put the default back, it's public since v5.16

Comment on lines +101 to +102
merge_size = 2
patch_block_size = 1

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, patch_block_size is a read-only property now

     patch_size = 16
     temporal_patch_size = 1
     merge_size = 2
-    patch_block_size = 1
-    flat_patches = True
     valid_kwargs = HunYuanVLImageProcessorKwargs
@@
+    @property
+    def patch_block_size(self):
+        """Patches are written row by row, not in `merge_size` blocks."""
+        return 1

Comment on lines +102 to +103
patch_block_size = 1
flat_patches = True

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, it's the patch order the model expects. it's a read-only property now

     patch_size = 16
     temporal_patch_size = 1
     merge_size = 2
-    patch_block_size = 1
-    flat_patches = True
     valid_kwargs = HunYuanVLImageProcessorKwargs
@@
+    @property
+    def patch_block_size(self):
+        """Patches are written row by row, not in `merge_size` blocks."""
+        return 1

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super happy with how it looks now! Lets get this merged soon 🚀


def _resized_size(self, height, width, size, factor):
"""Size an image of `height` x `width` pixels is resized to."""
# get_number_of_image_patches repeats this rule because vLLM needs a patch count

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

repeats which rule?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the smart_resize call just below. get_number_of_image_patches does the same computation on its own, vLLM calls it to count patches without an image

Comment on lines +105 to +117
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
and kernel_can_resize(images, resample)
):
return None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am curious if there are some remote models with weird custom code compltely in self._preprocess, so they might pass these checks

IIUC unless they opt in with kernel decorator, nothing weird happens since kernels are off by default? Asking for safety, remote models cause hidden issues almost every time 😭

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, if they don't touch the decorator nothing weird will happen. Now, if their agent find the decorator and think it's a good idea... 😭

Comment on lines +49 to +54
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
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i know i asked that but i forgot your reply 😆

why we can't check only image.device.type == _KERNEL_DEVICE_TYPE for each image, without checking and image.device == images[0].device?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hey no prob :D so say cuda:0 and cuda:1 both have type cuda, and the kernel resizes the whole batch in one launch on one gpu, so the images also have to be on the same device

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hahaha, atp it won't hurt adding a small comment in code or i will just keep asking 😆

@zucchini-nlp

Copy link
Copy Markdown
Member

i caused you gh conflicts, sorry...

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initial design round! Sorry for all the delays, glad I can focus on this now. This is exciting 🫡


## Processor kernels

Image and video processors can run some of their operations with Hub kernels from [kernels-community/cv-utils](https://huggingface.co/kernels-community/cv-utils). Pass `use_kernels=True` when loading the processor. Processors keep kernels off by default because the resize kernels change pixel values (see below), and the flag is not saved with the processor configuration.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wdyt about making it a default as well or too risky for now and we go the slower path for now?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too risky for now I think yeah, the resize kernels are close to torchvision but not bit-exactt so default-on would shift pixel_values a bit for every vision checkpoint at once

| 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) |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would not list all archs just do a e.g. in the (..) so it doesnt seem we list all

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, both rows only give a few examples now

```py
from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

qq can we be granular and for example only kernelize img processor but not vid processor? Wondering whether one part could be more sensitive e.g. videos with a lot of frames -> more small diff accumms -> too big of a diff

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, use_kernels is a plain attribute on each image / video processor, so processor.video_processor.use_kernels = False keeps kernels for images only

AFAIK tho frames are resized one by one, so a video gets the same per-pixel difference as an image, it shouldn't accumulate with the number of frames

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"`. 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to slightly adjust as its now a base dep we shouldnt need the err :D

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol yeah 🎉 dropped the check in BaseImageProcessor.__init__ and the sentence here

KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"}


_KERNEL_DEVICE_TYPE = "cuda"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need it as constant? :D feels a bit overkill

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, gone, the check is inline in load_cv_utils_kernel


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 (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we can adopt something closer to #48335 using "conditionals" as optional kwarg?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah true! ok, use_processing_kernel takes a condition now. TorchvisionBackend._preprocess uses it to skip processors that override resize / normalize.

Comment on lines +72 to +76
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", {}))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be done before wrapping? just fearing again compile

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done! you're right to fear compile 👀

kernel = load_cv_utils_kernel(outputs.logits.device)
if kernel is None:
return None
return kernel.upsample_argmax(outputs.logits, target_sizes)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should make sure the expected fns actually exist (see fp8 again, we can check for signatures to match)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in the loader like fp8, it raises an ImportError with the missing funcs. however iit checks names only since we use kwargs (not the signature_)

resample=KERNEL_INTERPOLATIONS[resample],
crop_size=crop,
)
return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldnt this still be in hub kernels processors then tho?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved it, it was here because it compared the processor's resize / normalize to TorchvisionBackend's, and that check is now the condition on the decorator (we discussed above)

@molbap molbap left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks @vasqu for the review!
I ran tests on an HF job on an A10G and all seems green as well 😁
Answered open threads (and also 2 comments I forgot @zucchini-nlp sorry)


## Processor kernels

Image and video processors can run some of their operations with Hub kernels from [kernels-community/cv-utils](https://huggingface.co/kernels-community/cv-utils). Pass `use_kernels=True` when loading the processor. Processors keep kernels off by default because the resize kernels change pixel values (see below), and the flag is not saved with the processor configuration.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too risky for now I think yeah, the resize kernels are close to torchvision but not bit-exactt so default-on would shift pixel_values a bit for every vision checkpoint at once

```py
from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, use_kernels is a plain attribute on each image / video processor, so processor.video_processor.use_kernels = False keeps kernels for images only

AFAIK tho frames are resized one by one, so a video gets the same per-pixel difference as an image, it shouldn't accumulate with the number of frames

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"`. 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol yeah 🎉 dropped the check in BaseImageProcessor.__init__ and the sentence here



class MyImageProcessor(TorchvisionBackend):
@use_processing_kernel(upsample_argmax_with_kernel)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not right now. KernelConfig remaps layer names of the model, and a processor has no layers, the helpers just call cv-utils. I had a name -> kernel registry in an earlier version and dropped it because every op comes from one repo, a custom kernel is a subclass with its own function under use_processing_kernel

tbh we can go back to the registry but I'm not 100% sold on it

resample=KERNEL_INTERPOLATIONS[resample],
crop_size=crop,
)
return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=return_tensors)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved it, it was here because it compared the processor's resize / normalize to TorchvisionBackend's, and that check is now the condition on the decorator (we discussed above)

KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"}


_KERNEL_DEVICE_TYPE = "cuda"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, gone, the check is inline in load_cv_utils_kernel

| 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) |

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, both rows only give a few examples now


def _resized_size(self, height, width, size, factor):
"""Size an image of `height` x `width` pixels is resized to."""
# get_number_of_image_patches repeats this rule because vLLM needs a patch count

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the smart_resize call just below. get_number_of_image_patches does the same computation on its own, vLLM calls it to count patches without an image

Comment on lines +49 to +54
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
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hey no prob :D so say cuda:0 and cuda:1 both have type cuda, and the kernel resizes the whole batch in one launch on one gpu, so the images also have to be on the same device

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: beit, chmv2, cohere_compass, dpt, ernie4_5_vl_moe, glm_image, hunyuan_vl, hy_v4_vl, minimax_m3_vl, mobilenet_v2, mobilevit, paddleocr_vl, qwen2_vl, qwen3_vl, sam2, sam3

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants