Add sdpa for Detr
Author: OmarManzoor
Pull request: yes
Labels: name: Vision

name: SDPA

name: run-slow

# 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 -->

Towards #28005


- Adds sdpa for Detr model



## Who can review?
CC: @amyeroberts @ArthurZucker 

<!-- 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 @OmarManzoor! Thanks for taking this up, feel free to ping me when it's ready for review!

@qubvel I posted a question in the description. Could you kindly have a look?

@OmarManzoor Yes, for some models we see that the threshold should be different. You can override model tests

@qubvel I tried make the required adjustments. I don't really know about these test failures.

Hi @OmarManzoor! Thanks for iterating! 

Re tests:

This one looks unrelated
```
FAILED tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py::XLMRobertaXLModelTest::test_assisted_decoding_matches_greedy_search_1_same - AssertionError: False is not true
```

However this one might be related to the PR
```
FAILED examples/pytorch/test_pytorch_examples.py::ExamplesTests::test_run_object_detection - AssertionError: 0.0152 not greater than or equal to 0.1
```

Can you also push an empty commit with the message `[run-slow] detr` to trigger slow tests? (it should be the last commit in a sequence so I can approve the CI run)

@qubvel I tried running some benchmarks for training. This is the script I used. [train benchmark script](https://gist.github.com/OmarManzoor/81ee4b2a9e1103cd005b49a8c06ed6b6)
However it seems that the speedups have been decreasing instead of increasing.


Interesting observation! Did you try with larger images? I observed something similar for the RT-DETR model, `SDPA` implementation did not give any speedups

> Interesting observation! Did you try with larger images?

No not beyond 128. Does the script look okay though? 
One thing that was different from the case with text models, was that this line
```python
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=True)
```
resulted is no kernel found errors. I had to set `enable_math=True` to run the code.

@qubvel I think the tests are generally looking okay now. I also pushed a commit with run slow for Detr.

Also one thing that I observed was that this test for table transformer currently seems to be failing. This happens on the main branch as well when I tested locally, probably because the values don't match.
https://github.com/huggingface/transformers/blob/1de7dc7403b3b89ec421d43a8c9ee245211a61f6/tests/models/table_transformer/test_modeling_table_transformer.py#L594-L601

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

> Hi @OmarManzoor, thanks for iterating! Can you post here some benchmarks you have? I'd recommended to test it on real input, e.g. for DETR it might be an image of size ~1300x800, please use the image processor to prepare some inputs. At least for inference mode.

I don't think I can run for larger inputs since I only have a GPU with 8GB available to run the benchmarks.


This is a benchmark I just ran for 1048 x 640 with float16 for training
| num_training_steps | batch_size | image_size   | is cuda | Time per batch (eager - s) | Time per batch (sdpa - s) | Speedup (%) | Eager peak mem (MB) | sdpa peak mem (MB) | Mem saving (%) |
|--------------------|------------|--------------|---------|----------------------------|---------------------------|-------------|----------------------|--------------------|----------------|
| 50                 | 2          | (1048, 640)  | True    | 0.173                      | 0.181                     | -4.707      | 5948.894            | 6320.631          | -5.881         |


Hi @OmarManzoor, thanks for sharing this! To move forward with this PR, we need to ensure it performs at least as fast as the eager implementation or offers better memory efficiency. I plan to test it on my side next week to see if the performance depends on specific hardware. Maybe worth benchmarking the compiled version as well.

If we can't achieve this improvement now, it might **not** be ideal to merge at this point, as SDPA is the default setting. Slower performance and additional maintenance code could introduce challenges. However, this approach might work better with newer GPUs and future torch versions, so even if we don’t identify a solution right away, we could revisit and integrate it at a more optimal time.

Looking forward to hearing your thoughts!

I agree with you. However I would be grateful if you could try out some benchmarks on your end using better GPUs and better configurations and maybe some tweaks in the benchmarking script if required. That would confirm if we are getting any performance upgrades or not. If the results are similar to what I observed then I think we can close this PR for now. Also I haven't really tested for inference because not once did I observe any sort of improvement for the training script, even with float32 it was almost the same speed with eager being slightly better.

Closing as no specific performance improvements were noted for Detr. Thank you for your support on this @qubvel and if you observe any performance improvements at your side, we can reopen.