Repository navigation
Support custom kernels for processing ops #46771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
9776f5e
09833c8
98767b7
a3d1e52
052c651
db06e8a
147671e
5f4a1ca
8b9eced
8ef19e9
ba561ca
7e3c333
9616d97
17ed7dc
fc773fa
9accfa9
a1ad4b1
df47109
ede482a
9d8b67e
aeb80c9
6bf8b22
fd61482
91a06a9
43486df
74842c5
ab755b4
a71afb1
aa2b46a
26115b0
8a67620
3020c0a
c5cea96
cc5da32
5d9e579
1a95107
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -320,6 +320,63 @@ 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 (e.g. HunYuanVL, PaddleOCR-VL) | | ||
| | Connected components | Measures the area of every connected region of a mask, to fill small holes and remove small islands. | SAM 2 and SAM 3 image processors (`max_hole_area`, `max_sprinkle_area`) | | ||
| | Upsample and argmax | Computes the class of every pixel of the upsampled segmentation logits without storing the upsampled logits. | `post_process_semantic_segmentation` of semantic segmentation processors (e.g. SegFormer, BEiT, DPT) | | ||
|
|
||
| ```py | ||
| from transformers import AutoProcessor | ||
|
|
||
| processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", use_kernels=True) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes, 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"`. 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. | ||
|
|
||
| `use_kernels` is an attribute of each image and video processor. Set it on one of them to use kernels for images only, for example. | ||
|
|
||
| ```py | ||
| processor.video_processor.use_kernels = False | ||
| ``` | ||
|
|
||
| > [!NOTE] | ||
| > 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`. An optional `condition` receives the processor and returns whether it can use the kernel, like the `condition` of `use_kernel_forward_from_hub`. `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): | ||
| 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. gotta read a bit more, but does kernel config potentially also allow users to pass their own kernels depending on the name we associate to that kernel?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. not right now. tbh we can go back to the registry but I'm not 100% sold on it |
||
| 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. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -53,6 +53,7 @@ | |
| is_valid_image, | ||
| load_image_as_tensor, | ||
| ) | ||
| from .integrations.hub_processing_kernels import resize_normalize_with_kernel, use_processing_kernel | ||
| from .processing_utils import ImagesKwargs, Unpack | ||
| from .utils import ( | ||
| TensorType, | ||
|
|
@@ -258,34 +259,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
+269
to
+283
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nice helper |
||
| ) | ||
|
|
||
| @staticmethod | ||
| def _compile_friendly_resize( | ||
| image: "torch.Tensor", | ||
|
|
@@ -396,6 +393,13 @@ 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, | ||
| condition=lambda processor: all( | ||
| getattr(type(processor), name) is getattr(TorchvisionBackend, name) | ||
| for name in ("resize", "center_crop", "rescale_and_normalize", "rescale", "normalize") | ||
| ), | ||
| ) | ||
| def _preprocess( | ||
| self, | ||
| images: list["torch.Tensor"], | ||
|
|
@@ -449,6 +453,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) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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_valuesa bit for every vision checkpoint at once