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
| return adapter(kernel, *args, **kwargs) | ||
|
|
||
|
|
||
| _KERNEL_DEVICE_TYPE = "cuda" |
There was a problem hiding this comment.
nit: lets put all global vars on the top of file
| 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
| 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?
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
| 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
| 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
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
| patch_block_size = 1 | ||
| flat_patches = True |
There was a problem hiding this comment.
Should these attributes be saved in the config or not?
| 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>
|
[For maintainers] Suggested jobs to run (before merge) run-slow: beit, chmv2, cohere_compass, dpt, ernie4_5_vl_moe, glm_image, hunyuan_vl, minimax_m3_vl, mobilenet_v2, mobilevit, paddleocr_vl, qwen2_vl, qwen3_vl, sam2, sam3, sam3_video |
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 :)