Repository: huggingface/transformers
Pull request: Fix smart resize

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

This currently throws:

```python
import torch
from transformers import Qwen2VLImageProcessorFast
from transformers.image_utils import ChannelDimension

processor = Qwen2VLImageProcessorFast()
format = ChannelDimension.FIRST
image = torch.zeros((3, 100, 100))
size = {"shortest_edge": 100, "longest_edge": 100}
processor.preprocess(image, input_data_format=format, size=size)
```

<details>

<summary>Error</summary>

```
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[38], line 8
      6 image = torch.zeros((3, 100, 100))
      7 size = {"shortest_edge":100, "longest_edge":100}
----> 8 processor.preprocess(image, input_data_format=format, size=size)

File /nix/store/xg7lc4jxm5p199b01nndbfqr3fy4p8g7-python3.10-transformers-4.50.3/lib/python3.10/site-packages/transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py:397, in Qwen2VLImageProcessorFast.preprocess(self, images, videos, do_resize, size, resample, do_rescale, rescale_factor, do_normalize, image_mean, image_std, min_pixels, max_pixels, patch_size, temporal_patch_size, merge_size, do_convert_rgb, return_tensors, data_format, input_data_format, device, **kwargs)
    395 pixel_values, vision_grid_thws = [], []
    396 for image in images:
--> 397     patches, image_grid_thw = self._preprocess(
    398         image,
    399         do_resize=do_resize,
    400         size=size,
    401         interpolation=interpolation,
    402         do_rescale=do_rescale,
    403         rescale_factor=rescale_factor,
    404         do_normalize=do_normalize,
    405         image_mean=image_mean,
    406         image_std=image_std,
    407         patch_size=patch_size,
    408         temporal_patch_size=temporal_patch_size,
    409         merge_size=merge_size,
    410         do_convert_rgb=do_convert_rgb,
    411         input_data_format=input_data_format,
    412         device=device,
    413     )
    414     pixel_values.extend(patches)
    415     vision_grid_thws.append(image_grid_thw)

File /nix/store/xg7lc4jxm5p199b01nndbfqr3fy4p8g7-python3.10-transformers-4.50.3/lib/python3.10/site-packages/transformers/models/qwen2_vl/image_processing_qwen2_vl_fast.py:209, in Qwen2VLImageProcessorFast._preprocess(self, images, do_resize, size, interpolation, do_rescale, rescale_factor, do_normalize, image_mean, image_std, patch_size, temporal_patch_size, merge_size, do_convert_rgb, input_data_format, device)
    201     if do_resize:
    202         resized_height, resized_width = smart_resize(
    203             height,
    204             width,
   (...)
    207             max_pixels=size["longest_edge"],
    208         )
--> 209         stacked_images = F.resize(
    210             stacked_images, size=(resized_height, resized_width), interpolation=interpolation
    211         )
    212     resized_images_grouped[shape] = stacked_images
    213 resized_images = reorder_images(resized_images_grouped, grouped_images_index)

File /nix/store/cifrlch412l6cnpa06qaf8lrqbs47pzh-python3.10-torchvision-0.20.1/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_geometry.py:188, in resize(inpt, size, interpolation, max_size, antialias)
    185 _log_api_usage_once(resize)
    187 kernel = _get_kernel(resize, type(inpt))
--> 188 return kernel(inpt, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias)

File /nix/store/cifrlch412l6cnpa06qaf8lrqbs47pzh-python3.10-torchvision-0.20.1/lib/python3.10/site-packages/torchvision/transforms/v2/functional/_geometry.py:260, in resize_image(image, size, interpolation, max_size, antialias)
    257 if need_cast:
    258     image = image.to(dtype=torch.float32)
--> 260 image = interpolate(
    261     image,
    262     size=[new_height, new_width],
    263     mode=interpolation.value,
    264     align_corners=align_corners,
    265     antialias=antialias,
    266 )
    268 if need_cast:
    269     if interpolation == InterpolationMode.BICUBIC and dtype == torch.uint8:
    270         # This path is hit on non-AVX archs, or on GPU.

File /nix/store/93vlnr4hqnr20y3fm9j952p9zrjr3dqp-python3.10-torch-2.5.1/lib/python3.10/site-packages/torch/nn/functional.py:4591, in interpolate(input, size, scale_factor, mode, align_corners, recompute_scale_factor, antialias)
   4589     assert align_corners is not None
   4590     if antialias:
-> 4591         return torch._C._nn._upsample_bicubic2d_aa(
   4592             input, output_size, align_corners, scale_factors
   4593         )
   4594     return torch._C._nn.upsample_bicubic2d(
   4595         input, output_size, align_corners, scale_factors
   4596     )
   4598 if input.dim() == 3 and mode == "bilinear":

RuntimeError: Input and output sizes should be greater than 0, but got input (H: 100, W: 100) output (H: 0, W: 0)
```

</details>

This PR incorporates [the fix](https://github.com/QwenLM/Qwen2.5-VL/commit/a30e36facd0a5131d9ed59e93210c7ac5de75adb) from the Qwen repo. It also applies the same patch to Emu3 (replaces https://github.com/huggingface/transformers/pull/38150).

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [X] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [X] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->

@zucchini-nlp

Changed files:
filename: src/transformers/models/emu3/image_processing_emu3.py
patch: @@ -81,18 +81,16 @@ def smart_resize(
     3. The aspect ratio of the image is maintained as closely as possible.
 
     """
-    if height < factor or width < factor:
-        raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
-    elif max(height, width) / min(height, width) > 200:
+    if max(height, width) / min(height, width) > 200:
         raise ValueError(
             f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
         )
     h_bar = round(height / factor) * factor
     w_bar = round(width / factor) * factor
     if h_bar * w_bar > max_pixels:
         beta = math.sqrt((height * width) / max_pixels)
-        h_bar = math.floor(height / beta / factor) * factor
-        w_bar = math.floor(width / beta / factor) * factor
+        h_bar = max(factor, math.floor(height / beta / factor) * factor)
+        w_bar = max(factor, math.floor(width / beta / factor) * factor)
     elif h_bar * w_bar < min_pixels:
         beta = math.sqrt(min_pixels / (height * width))
         h_bar = math.ceil(height * beta / factor) * factor

filename: src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py
patch: @@ -64,18 +64,16 @@ def smart_resize(
     3. The aspect ratio of the image is maintained as closely as possible.
 
     """
-    if height < factor or width < factor:
-        raise ValueError(f"height:{height} and width:{width} must be larger than factor:{factor}")
-    elif max(height, width) / min(height, width) > 200:
+    if max(height, width) / min(height, width) > 200:
         raise ValueError(
             f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
         )
     h_bar = round(height / factor) * factor
     w_bar = round(width / factor) * factor
     if h_bar * w_bar > max_pixels:
         beta = math.sqrt((height * width) / max_pixels)
-        h_bar = math.floor(height / beta / factor) * factor
-        w_bar = math.floor(width / beta / factor) * factor
+        h_bar = max(factor, math.floor(height / beta / factor) * factor)
+        w_bar = max(factor, math.floor(width / beta / factor) * factor)
     elif h_bar * w_bar < min_pixels:
         beta = math.sqrt(min_pixels / (height * width))
         h_bar = math.ceil(height * beta / factor) * factor

filename: tests/models/qwen2_vl/test_image_processing_qwen2_vl.py
patch: @@ -12,6 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import itertools
 import tempfile
 import unittest
 
@@ -169,18 +170,18 @@ def test_call_pil(self):
                 self.assertIsInstance(image[0], Image.Image)
 
             # Test not batched input
-            prcocess_out = image_processing(image_inputs[0], return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs[0], return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (4900, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]])
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
             self.assertTrue((image_grid_thws == expected_image_grid_thws).all())
 
             # Test batched
-            prcocess_out = image_processing(image_inputs, return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs, return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (34300, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]] * 7)
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
@@ -196,18 +197,18 @@ def test_call_numpy(self):
                 self.assertIsInstance(image[0], np.ndarray)
 
             # Test not batched input
-            prcocess_out = image_processing(image_inputs[0], return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs[0], return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (4900, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]])
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
             self.assertTrue((image_grid_thws == expected_image_grid_thws).all())
 
             # Test batched
-            prcocess_out = image_processing(image_inputs, return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs, return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (34300, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]] * 7)
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
@@ -224,18 +225,18 @@ def test_call_pytorch(self):
                 self.assertIsInstance(image[0], torch.Tensor)
 
             # Test not batched input
-            prcocess_out = image_processing(image_inputs[0], return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs[0], return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (4900, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]])
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
             self.assertTrue((image_grid_thws == expected_image_grid_thws).all())
 
             # Test batched
-            prcocess_out = image_processing(image_inputs, return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs, return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (34300, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]] * 7)
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
@@ -251,19 +252,19 @@ def test_nested_input(self):
             image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
 
             # Test batched as a list of images
-            prcocess_out = image_processing(image_inputs, return_tensors="pt")
-            encoded_images = prcocess_out.pixel_values
-            image_grid_thws = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs, return_tensors="pt")
+            encoded_images = process_out.pixel_values
+            image_grid_thws = process_out.image_grid_thw
             expected_output_image_shape = (34300, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]] * 7)
             self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
             self.assertTrue((image_grid_thws == expected_image_grid_thws).all())
 
             # Test batched as a nested list of images, where each sublist is one batch
             image_inputs_nested = image_inputs[:3] + image_inputs[3:]
-            prcocess_out = image_processing(image_inputs_nested, return_tensors="pt")
-            encoded_images_nested = prcocess_out.pixel_values
-            image_grid_thws_nested = prcocess_out.image_grid_thw
+            process_out = image_processing(image_inputs_nested, return_tensors="pt")
+            encoded_images_nested = process_out.pixel_values
+            image_grid_thws_nested = process_out.image_grid_thw
             expected_output_image_shape = (34300, 1176)
             expected_image_grid_thws = torch.Tensor([[1, 70, 70]] * 7)
             self.assertEqual(tuple(encoded_images_nested.shape), expected_output_image_shape)
@@ -281,8 +282,8 @@ def test_video_inputs(self):
             for num_frames, expected_dims in expected_dims_by_frames.items():
                 image_processor_tester = Qwen2VLImageProcessingTester(self, num_frames=num_frames)
                 video_inputs = image_processor_tester.prepare_video_inputs(equal_resolution=True)
-                prcocess_out = image_processing(None, videos=video_inputs, return_tensors="pt")
-                encoded_video = prcocess_out.pixel_values_videos
+                process_out = image_processing(None, videos=video_inputs, return_tensors="pt")
+                encoded_video = process_out.pixel_values_videos
                 expected_output_video_shape = (expected_dims, 1176)
                 self.assertEqual(tuple(encoded_video.shape), expected_output_video_shape)
 
@@ -293,8 +294,8 @@ def test_custom_patch_size(self):
             for patch_size in (1, 3, 5, 7):
                 image_processor_tester = Qwen2VLImageProcessingTester(self, patch_size=patch_size)
                 video_inputs = image_processor_tester.prepare_video_inputs(equal_resolution=True)
-                prcocess_out = image_processing(None, videos=video_inputs, return_tensors="pt")
-                encoded_video = prcocess_out.pixel_values_videos
+                process_out = image_processing(None, videos=video_inputs, return_tensors="pt")
+                encoded_video = process_out.pixel_values_videos
                 expected_output_video_shape = (171500, 1176)
                 self.assertEqual(tuple(encoded_video.shape), expected_output_video_shape)
 
@@ -308,9 +309,21 @@ def test_custom_image_size(self):
                 )
 
             image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
-            prcocess_out = image_processor_loaded(image_inputs, return_tensors="pt")
+            process_out = image_processor_loaded(image_inputs, return_tensors="pt")
             expected_output_video_shape = [112, 1176]
-            self.assertListEqual(list(prcocess_out.pixel_values.shape), expected_output_video_shape)
+            self.assertListEqual(list(process_out.pixel_values.shape), expected_output_video_shape)
+
+    def test_custom_pixels(self):
+        pixel_choices = frozenset(itertools.product((100, 150, 200, 20000), (100, 150, 200, 20000)))
+        for image_processing_class in self.image_processor_list:
+            image_processor_dict = self.image_processor_dict.copy()
+            for a_pixels, b_pixels in pixel_choices:
+                image_processor_dict["min_pixels"] = min(a_pixels, b_pixels)
+                image_processor_dict["max_pixels"] = max(a_pixels, b_pixels)
+                image_processor = image_processing_class(**image_processor_dict)
+                image_inputs = self.image_processor_tester.prepare_image_inputs()
+                # Just checking that it doesn't raise an error
+                image_processor(image_inputs, return_tensors="pt")
 
     def test_temporal_padding(self):
         for image_processing_class in self.image_processor_list: