Mask2former & Maskformer Fast Image Processor
Author: SangbumChoi
Pull request: yes
Labels: name: Vision

name: Processing

# 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 -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] 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).
- [ ] 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:
@yonigozlan @qubvel Hi, While I am doing this PR I had a one question of `pad_size`. Normally original processor of transformer have both `do_pad` and `pad_size`. I think the exsitance of `pad_size` can be many reason but one is for making strict size for inference in ONNX or torch.jit.trace model. (Since it can only accept the static size of image)

However, currently maskformer's processing policy is always pad the max size of width height in the given batch of images. So I was planning to give pad_size in the `MaskFormerImageProcessor` in order to add `pad_size` in the `MaskFormerImageProcessorFast` and modular_file in mask2former also. Can I have some feedback about this idea?

Hi @SangbumChoi! Thanks for working on fast processors 🤗 I think it would be nice to have in case the change is backward compatible with current configs, e.g. pad_size=None by default

Hi @SangbumChoi great to see more work with fast processors :). Agreed with @qubvel, I don't see any issues with adding functionalities to image processor as long as they are fully backward compatible and the default processing stays the same.

@qubvel @yonigozlan Requesting first round review.

@yonigozlan Hi, I have pushed all the commit except for https://github.com/huggingface/transformers/pull/35685#discussion_r1920557854.

Test failure seem unrelated!



@yonigozlan Reminder :)

@ArthurZucker Soft ping

Thanks again @SangbumChoi for adding this! As Arthur said, since my last review, there was a big refactor of fast image processors. Now in most cases you should only have to add custom code in the _preprocess function, and add docstrings to init and preprocess for added image processing kwargs if needed. However maskformer seems a bit more involved for backward compatibility because of the deprecated kwargs such as _maxsize, though the modifications needed should be very similar to the ones that were made for [detr](https://github.com/huggingface/transformers/blob/31bb662db19355e56b3125ab5c48b780ec13111c/src/transformers/models/detr/image_processing_detr_fast.py) in #35069 , so hopefully that can help ! 
If you can make these modifications that would be great, and as this is quite a recent refactor I’d be glad to have your feedback and I’m happy to answer any questions you may have 🤗

@yonigozlan @ArthurZucker Hi team, I want to also upload the benchmark also. I think I have seen some code from @yonigozlan to test these changes and visualize in the graph but I think it can be accessed only internally can you share? (Otherwise you can share me through slack)

Hi @SangbumChoi! Could you run a simple benchmark like this one?
```python
def benchmark_image_processor(image_processor, images,benchmark_it=10, warmup_it=10):
    # warm up
    for _ in range(warmup_it):
        _ = image_processor(images=images, return_tensors="pt", device=device)
    # benchmark
    start_time = time.time()
    for _ in range(benchmark_it):
        _ = image_processor(images=images, return_tensors="pt", device=device)
    end_time = time.time()

    return (end_time - start_time) / benchmark_it

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
checkpoint = "maskformer/mask2former checkpoint"
image_processor_fast = AutoImageProcessor.from_pretrained(checkpoint, use_fast=True)
image_processor_slow = AutoImageProcessor.from_pretrained(checkpoint)
device = "cuda"
batch_size = 4

slow_time_one = benchmark_image_processor(image_processor_slow, image, benchmark_it=10)
fast_time_one = benchmark_image_processor(image_processor_fast, image, benchmark_it=10)
slow_time_batch = benchmark_image_processor(image_processor_slow, [image]*batch_size, benchmark_it=10)
fast_time_batch = benchmark_image_processor(image_processor_fast, [image]*batch_size, benchmark_it=10)

print(f"slow_time_one: {slow_time_one}, fast_time_one: {fast_time_one}, speedup: {slow_time_one/fast_time_one}")
print(f"slow_time_batch: {slow_time_batch}, fast_time_batch: {fast_time_batch}, speedup: {slow_time_batch/fast_time_batch}")
```
Thanks!

**[For maintainers]** Suggested jobs to run (before merge)

run-slow: auto, mask2former, maskformer

Also removed the zero shot examples as they seem out of scope for this PR, happy to review in another PR!

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