Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
9776f5e
speaking words of wisdom
molbap Jun 19, 2026
09833c8
improve interfacing a bit
molbap Jun 19, 2026
98767b7
simplify
molbap Jun 19, 2026
a3d1e52
guard torch
molbap Jun 19, 2026
052c651
pop use kernels arg at init
molbap Jun 19, 2026
db06e8a
change registration
molbap Jun 22, 2026
147671e
big update for processing kernels
molbap Aug 21, 2026
5f4a1ca
update doc
molbap Aug 21, 2026
8b9eced
fix conflicts in update
molbap Aug 21, 2026
8ef19e9
update and upstream
molbap Sep 24, 2026
ba561ca
massive upgrade with SAM2 kernels and better patchify
molbap Sep 24, 2026
7e3c333
model-specific changes
molbap Oct 7, 2026
9616d97
remove lazy load modifs
molbap Oct 7, 2026
17ed7dc
conflict
molbap Oct 7, 2026
fc773fa
load by kernel_name
molbap Oct 7, 2026
9accfa9
move processing kernels to their spot
molbap Oct 9, 2026
a1ad4b1
merge main
molbap Oct 9, 2026
df47109
overhaul again registering and usage
molbap Oct 9, 2026
ede482a
add test to be able to hook kernels to processor
molbap Oct 9, 2026
9d8b67e
set use_kernels once
molbap Oct 15, 2026
aeb80c9
kernel API and processors
molbap Oct 15, 2026
6bf8b22
better tests
molbap Oct 15, 2026
fd61482
update doc
molbap Oct 15, 2026
91a06a9
Merge branch 'main' into processing-kernels-ship
molbap Oct 15, 2026
43486df
upsample + argmax cv-utils kernel
molbap Oct 21, 2026
74842c5
upsample more
molbap Oct 21, 2026
ab755b4
better func split
molbap Oct 21, 2026
a71afb1
restore kernel registry, address review
molbap Oct 29, 2026
aa2b46a
rebase fixes
molbap Oct 29, 2026
26115b0
test these processing kernels
molbap Oct 30, 2026
8a67620
fix import
molbap Oct 30, 2026
3020c0a
drop registration in the end
molbap Nov 25, 2026
c5cea96
fix conflict
molbap Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/source/en/kernel_doc/loading_kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,56 @@ Set the `USE_HUB_KERNELS` environment variable to disable Hub kernels everywhere
export USE_HUB_KERNELS=0 # or OFF or NO
```

## Processor kernels

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

| Operation | What the kernel does | Processors |
|---|---|---|
| Resize and normalize | Resizes a batch of images of different sizes in one launch, then rescales and normalizes in the same pass. | Processors that use the default [`TorchvisionBackend`] preprocessing, such as ViT, CLIP and SigLIP |
| Resize, normalize and patchify | Writes each resized and normalized pixel directly at its place in the flattened patch sequence, for images and video frames. | Qwen2-VL and Qwen3-VL image and video processors, and the processors built on them (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

| 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

processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True)
inputs = processor(text=prompt, images=images, return_tensors="pt", device="cuda")
```

[`AutoProcessor`] passes the flag to its image and video processors. Kernels run on the device of the inputs, so pass `device="cuda"`. 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.

When both sides are upsampled at least 2x, the upsample and argmax kernel runs on tensor cores in float16. A few pixels at near-ties between two classes can then get another class, about 1e-4 of the pixels on ADE20K, with no change in mIoU.

### Adding a processing kernel

`use_processing_kernel` connects a processor method to a kernel. It decorates the method with a function that receives the processor and the named arguments of the method. That function returns the result, or `None` to run the method as usual. It only runs when the processor was loaded with `use_kernels=True`. `load_cv_utils_kernel(device)` returns the cv-utils kernel for tensors on `device`, or `None` when they are not on a CUDA device or the kernel does not load. For example, this is how semantic segmentation post-processing uses `upsample_argmax`:

```py
from transformers import TorchvisionBackend
from transformers.integrations.hub_processing_kernels import load_cv_utils_kernel, use_processing_kernel


def upsample_argmax_with_kernel(processor, outputs, target_sizes, return_segmentation_scores, **kwargs):
if return_segmentation_scores or target_sizes is None:
return None
kernel = load_cv_utils_kernel(outputs.logits.device)
if kernel is None:
return None
return kernel.upsample_argmax(outputs.logits, target_sizes)


class MyImageProcessor(TorchvisionBackend):
@use_processing_kernel(upsample_argmax_with_kernel)
def post_process_semantic_segmentation(self, outputs, target_sizes=None, return_segmentation_scores=False):
...
```

Subclasses that keep the method keep the kernel. The function reads what differs between models from the processor, such as its `_resized_size` method or its `patch_block_size` attribute. A model that replaces `_preprocess` with a different pipeline marks it with `@no_inherit_decorator`.

## Troubleshooting

Kernel integration depends on hardware, drivers, and package versions working together. The following sections cover common failures.
Expand Down
97 changes: 75 additions & 22 deletions src/transformers/image_processing_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
is_valid_image,
load_image_as_tensor,
)
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,
Expand All @@ -66,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
Expand All @@ -82,6 +84,58 @@
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!

processor,
images,
do_resize,
size,
resample,
do_center_crop,
crop_size,
do_rescale,
rescale_factor,
do_normalize,
image_mean,
image_std,
do_pad,
return_tensors,
**kwargs,
):
"""`pixel_values` of the default torchvision pipeline from one kernel call, `None` to fall back."""
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
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
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)


@requires(backends=("torch", "torchvision"))
class TorchvisionBackend(BaseImageProcessor):
"""Torchvision backend for GPU-accelerated batched image processing."""
Expand Down Expand Up @@ -258,34 +312,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}."
Comment on lines +322 to +336

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

)

@staticmethod
def _compile_friendly_resize(
image: "torch.Tensor",
Expand Down Expand Up @@ -396,6 +446,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)
def _preprocess(
self,
images: list["torch.Tensor"],
Expand Down Expand Up @@ -449,6 +500,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)

Expand Down
9 changes: 9 additions & 0 deletions src/transformers/image_processing_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ def from_pretrained(
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
specify the folder name here.
use_kernels (`bool`, *optional*, defaults to `False`):
Whether to run the processing ops with Hub kernels when 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*):
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
Expand Down Expand Up @@ -382,7 +387,10 @@ 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__})
if use_kernels is not None:
image_processor_dict["use_kernels"] = use_kernels
image_processor = cls(**image_processor_dict)

# Apply extra kwargs to instance (BC for remote code, e.g. phi4_multimodal)
Expand Down Expand Up @@ -412,6 +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, never saved
output["image_processor_type"] = self.__class__.__name__

return output
Expand Down
9 changes: 9 additions & 0 deletions src/transformers/image_processing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -187,12 +189,19 @@ class MyImageProcessor(TorchvisionBackend):
"""

valid_kwargs = ImagesKwargs
use_kernels = False

default_to_square = True
rescale_factor = 1 / 255
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.
Expand Down
1 change: 1 addition & 0 deletions src/transformers/integrations/hub_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,7 @@ def register_kernel_mapping_transformers(*args, **kwargs):
"deep-gemm": {"repo_id": "kernels-community/deep-gemm", "version": 2},
"sonic-moe": {"repo_id": "kernels-community/sonic-moe", "revision": "ep-support"},
"nvfp4": {"repo_id": "kernels-community/nvfp4-gemm", "version": 1},
"cv-utils": {"repo_id": "kernels-community/cv-utils", "version": 2},
}

_KERNEL_MODULE_MAPPING: dict[str, ModuleType | None] = {}
Expand Down
Loading
Loading