Add optimized `PixtralImageProcessorFast`
Author: mgoin
Pull request: yes
Labels: name: Vision

name: optimization

name: Multimodal

name: Processing

# What does this PR do?

This PR implements a fast image processor for Pixtral. Follows issue https://github.com/huggingface/transformers/issues/33810.

The key acceleration comes from replacing Pillow/Numpy tensors and functions (resize, rescale, normalize) with torch tensors and torchvisionv2 functions. It comes along with support for `torch.compile` and passing `device="cuda"` during inference to process the input on GPU. One limitation is that only `return_tensors="pt"` will be supported. 

Usage
```python
from transformers import AutoImageProcessor

slow_processor = AutoImageProcessor.from_pretrained("mistral-community/pixtral-12b", use_fast=False)
fast_processor = AutoImageProcessor.from_pretrained("mistral-community/pixtral-12b", use_fast=True)
compiled_processor = torch.compile(fast_processor, mode="reduce-overhead")
```

From simple benchmarking with a single image of size `[3, 876, 1300]`, I see 6x to 10x speedup

![image](https://github.com/user-attachments/assets/7674c923-4c76-4629-aac1-ffc7856824c4)

```
--------------------------------------------------
Slow Processor (PIL Image) Statistics (milliseconds):
          Mean: 23.680
        Median: 23.098
       Std Dev: 2.240
           Min: 21.824
           Max: 36.064

--------------------------------------------------
Fast Processor (PIL Image) Statistics (milliseconds):
          Mean: 3.759
        Median: 3.762
       Std Dev: 0.133
           Min: 3.556
           Max: 4.223

--------------------------------------------------
Compiled Processor (PIL Image) Statistics (milliseconds):
          Mean: 4.632
        Median: 4.794
       Std Dev: 1.086
           Min: 3.488
           Max: 11.707

--------------------------------------------------
Slow Processor (Torch Image) Statistics (milliseconds):
          Mean: 22.331
        Median: 21.878
       Std Dev: 1.821
           Min: 21.316
           Max: 36.603

--------------------------------------------------
Fast Processor (Torch Image) Statistics (milliseconds):
          Mean: 2.242
        Median: 2.209
       Std Dev: 0.164
           Min: 2.182
           Max: 3.803

--------------------------------------------------
Compiled Processor (Torch Image) Statistics (milliseconds):
          Mean: 2.125
        Median: 2.117
       Std Dev: 0.073
           Min: 2.062
           Max: 2.594
```


## 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?
- [x] 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.
- [x] 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: @ylacombe, @eustlb
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- 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: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Hi @mgoin! Sounds great! Thanks for working on this 🤗 

cc @yonigozlan maybe if you have bandwidth

Thanks for the review and context @yonigozlan ! I will look into it later today. Yes you are correct about using it within a Processor, however I have tested this works within vLLM simply by adding `use_fast=True` to our `AutoProcessor.from_pretrained()` call [here](https://github.com/vllm-project/vllm/blob/da7e702c6fae521bf8633affb8fe7b834f5cb94b/vllm/transformers_utils/processor.py#L18-L22). No need to manually specify the Processor class.

One bug I noticed is that if I specify `use_fast=True` and there isn't a Fast version of the ImageProcessor available, I get an exception. I can look into this, but would be good to get clarity that this is unintended behavior.

Oh great news that it already works with AutoProcessor. As I said this is the first fast image processor used in a processor so it was not guaranteed :).

> One bug I noticed is that if I specify use_fast=True and there isn't a Fast version of the ImageProcessor available, I get an exception. I can look into this, but would be good to get clarity that this is unintended behavior.

Yes this is the same right now when using ImageProcessingAuto. I don't think it should be that way though, especially as more and more people will want to use fast image processors by default. I'll open a PR to fix this.

Current plan is:
- keep use_fast to False by default in Auto classes during a deprecation cycle, fall back on slow image processor (with a warning) if use_fast is set to True and no fast image processor exists
- set use_fast to True by default in Auto classes after the deprecation cycle (by then most models will hopefully have a fast image processor), still fall back on slow if no fast image processor exists.

The deprecation cycle is needed as there are slight differences in outputs when using torchvision vs PIL, see this PR https://github.com/huggingface/transformers/pull/34785 for more info.

Feel free to ping us for another round of review! 🚀 

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_34836). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Thanks @yonigozlan and @ArthurZucker - this PR is ready for more review! I believe the failing test is unrelated

Hi @yonigozlan what do you think about the use of `math.ceil`?

> Hi @yonigozlan what do you think about the use of math.ceil?

Sorry to be annoying with this but I'd prefer `torch.ceil`. I'd say we leave the `get_resize_output_image_size` function as it is (with np.ceil) in `image_processing_pixtral`, and rewrite one with torch in `image_processing_pixtral_fast`.


Sorry if I am misunderstanding something @yonigozlan  but `torch.ceil` only works on [`torch.Tensor`](https://pytorch.org/docs/stable/generated/torch.ceil.html). Since we are working with `height`/`width` as `int` primitives I cannot substitute `torch.ceil`. 

Are you suggesting that I wrap the values in a Tensor just to extract them back out as primitives? This is inefficient and unneeded to work with `torch.compile`

```python
height = int(np.ceil(height / ratio))
# versus
height = int(torch.ceil(torch.tensor(height / ratio)).item())
```

Considering [`torchvision.transforms.v2.functional.resize`](https://pytorch.org/vision/main/generated/torchvision.transforms.v2.functional.resize.html) takes in size as a list of ints (`size: Optional[List[int]]`), I don't see the benefit of using `torch.Tensor` for the height and width. If using numpy is the concern, I think using `math.ceil` makes sense.

Hi @mgoin,
Sorry about that, I went over the code too quickly and completely missed that we were dealing with floats and not arrays in the np.ceil. So what you did with `ImageInput` and `math.ceil` in `image_processing_pixtral.get_resize_output_image_size` makes perfect sense, you can ignore my last few messages🤗. 
LGTM then! :)

Nice thanks for clarification! Hi @ArthurZucker would you mind signing off?

Yep having a look!

Thanks a lot @mgoin for this contribution! 🔥 

> LGTM, sorry for the delay! My main question is for @yonigozlan , do we have compile tests for image processor fast?

I don't think so, I'll open a PR for that!

Cool thanks!