Repository navigation
Conversation
|
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: |
zucchini-nlp
left a comment
There was a problem hiding this comment.
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) | |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
switched the names a bit, it should be better
| or image.device != images[0].device | ||
| or image.shape[0] != images[0].shape[0] |
There was a problem hiding this comment.
why we verify against the first image and not a hardcoded expected value?
There was a problem hiding this comment.
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
| 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: |
There was a problem hiding this comment.
so if we want to only resize and crop=None , the kernel can't be applied?
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
wow, we have do_center_crop? seeing it first time lol, ig a new flag added in v5
There was a problem hiding this comment.
yes, it was from CLIP haha. It's still used by their processors
| 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 | ||
| ] |
There was a problem hiding this comment.
not all models expect same args for smart resize, can we infer it outside kernel fn and pass a valid size ?
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 🙏
There was a problem hiding this comment.
i will ping him again now, lets see
There was a problem hiding this comment.
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_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( |
There was a problem hiding this comment.
i am not following here, why we needed a default for only one of args and split the fn into two?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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) | |
There was a problem hiding this comment.
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) | |
There was a problem hiding this comment.
switched the names a bit, it should be better
| or image.device != images[0].device | ||
| or image.shape[0] != images[0].shape[0] |
There was a problem hiding this comment.
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
| 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: |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
those were the frame indices of videos, but again, bad naming. it's just "inputs" now, and hopefully clearer
| 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 | ||
| ] |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 🙏
| 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( |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
actually better like this too
|
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 |
|
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
left a comment
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
nit: we can do inside loop image.device == _KERNEL_DEVICE_TYPE directly
Also just curious - so the kernel actually supports 1/4 channel images?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
+ )
+ )| merge_size = 2 | ||
| patch_block_size = 1 |
There was a problem hiding this comment.
what s the diff betweem merge size and the new arg?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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| patch_block_size = 1 | ||
| flat_patches = False |
There was a problem hiding this comment.
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, 🤔
There was a problem hiding this comment.
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
| 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}." |
| logger = logging.get_logger(__name__) | ||
|
|
||
|
|
||
| def resize_normalize_with_kernel( |
There was a problem hiding this comment.
cant see where it is called, forgot to cleanup? 👀
There was a problem hiding this comment.
it is the default in the decorator call!
| temporal_patch_size = 2 | ||
| merge_size = 2 | ||
| patch_block_size = None | ||
| flat_patches = True |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
Is this needed because it is called temporal_patch_size in _preprocess?
There was a problem hiding this comment.
no, every caller passes it. the default came along when I moved resize up into qwen2-vl, removed it
There was a problem hiding this comment.
correction: I put the default back, it's public since v5.16
| patch_block_size = 1 | ||
| flat_patches = True |
There was a problem hiding this comment.
Should these attributes be saved in the config or not?
There was a problem hiding this comment.
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| 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." | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
good point... now it raises!
|
|
||
| def __init__(self, **kwargs: Unpack[ImagesKwargs]): | ||
| self.use_kernels = kwargs.pop("use_kernels", False) | ||
| super().__init__(**kwargs) |
There was a problem hiding this comment.
What happens if use_kernels is passed to a pil processor?
There was a problem hiding this comment.
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
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
left a comment
There was a problem hiding this comment.
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=2in qwen2-vl'sresize, 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=Trueraises withoutkernelsinstalled, 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) |
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
correction: I put the default back, it's public since v5.16
| merge_size = 2 | ||
| patch_block_size = 1 |
There was a problem hiding this comment.
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| patch_block_size = 1 | ||
| flat_patches = True |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
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 😭
There was a problem hiding this comment.
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... 😭
| 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 | ||
| ) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
hahaha, atp it won't hurt adding a small comment in code or i will just keep asking 😆
|
i caused you gh conflicts, sorry... |
vasqu
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
wdyt about making it a default as well or too risky for now and we go the slower path for now?
There was a problem hiding this comment.
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) | |
There was a problem hiding this comment.
would not list all archs just do a e.g. in the (..) so it doesnt seem we list all
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
to slightly adjust as its now a base dep we shouldnt need the err :D
There was a problem hiding this comment.
lol yeah 🎉 dropped the check in BaseImageProcessor.__init__ and the sentence here
| KERNEL_INTERPOLATIONS = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"} | ||
|
|
||
|
|
||
| _KERNEL_DEVICE_TYPE = "cuda" |
There was a problem hiding this comment.
do we need it as constant? :D feels a bit overkill
There was a problem hiding this comment.
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 ( |
There was a problem hiding this comment.
maybe we can adopt something closer to #48335 using "conditionals" as optional kwarg?
There was a problem hiding this comment.
ah true! ok, use_processing_kernel takes a condition now. TorchvisionBackend._preprocess uses it to skip processors that override resize / normalize.
| 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", {})) |
There was a problem hiding this comment.
could be done before wrapping? just fearing again compile
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
we should make sure the expected fns actually exist (see fp8 again, we can check for signatures to match)
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
shouldnt this still be in hub kernels processors then tho?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
lol yeah 🎉 dropped the check in BaseImageProcessor.__init__ and the sentence here
|
|
||
|
|
||
| class MyImageProcessor(TorchvisionBackend): | ||
| @use_processing_kernel(upsample_argmax_with_kernel) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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) | |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
| 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 | ||
| ) |
There was a problem hiding this comment.
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
|
[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 |
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=Trueswaps 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.
For vision-language models the image processor is wrapped in a processor, so the flag passes through [
AutoProcessor] to the inner image processor.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 :)