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
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 |
|---|---|---|
|
|
@@ -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, | ||
|
|
@@ -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 | ||
|
|
@@ -82,6 +84,58 @@ | |
| logger = logging.get_logger(__name__) | ||
|
|
||
|
|
||
| def resize_normalize_with_kernel( | ||
|
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. cant see where it is called, forgot to cleanup? 👀
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. 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.""" | ||
|
|
@@ -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
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 +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"], | ||
|
|
@@ -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) | ||
|
|
||
|
|
||
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.
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-resizeafter transforms?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.
so the kernel takes in a
merge_sizearg 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. Actuallyblock_sizeis a slighlty better naming, maybevision_block_size?merge_sizeis a bad nameThere 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.
switched the names a bit, it should be better