Fix SwinLayer / DonutSwinLayer / ClapAudioLayer attention mask device
Author: gorodnitskiy
Pull request: yes

# 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 -->


## 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. [Issue link](https://github.com/huggingface/transformers/issues/31294)
- [ ] 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 and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

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

 -->

## Fixes

I recently used DONUT (OCR-free Document Understanding Transformer) from HuggingFace and noticed that in the DonutSwinLayer (or SwinLayer / ClapAudioLayer), the attention mask is initially created on the CPU, processed, and then moved to the device.

In the case of using a GPU, this issue leads to a significant slowdown in inference speed. By adding a device argument to the first tensor initialization for the attention mask, I achieved a 39% speed improvement for `model.generate` on A100:
- Original: 0.15148±0.00961 s/iter
- Fixed: 0.09294±0.00118 s/iter

I understand that the main branch is ahead of my branch, but I’ll merge the main branch into my branch once the PR is confirmed to be okay.

## Benchmark code

```python
import torch
from time import perf_counter
import numpy as np

from transformers import DonutProcessor, VisionEncoderDecoderModel
from datasets import load_dataset

_TOTAL_ITERATION = 500
_WARMUP = 20


def main() -> None:
    # load processor and model
    processor = DonutProcessor.from_pretrained(
        "naver-clova-ix/donut-base-finetuned-rvlcdip"
    )
    model = VisionEncoderDecoderModel.from_pretrained(
        "naver-clova-ix/donut-base-finetuned-rvlcdip"
    )
    
    model.half()
    model.eval()
    model.to(torch.device("cuda"))
    
    # load test image
    dataset = load_dataset(
        "hf-internal-testing/example-documents", split="test"
    )
    images = dataset[1]["image"]
    
    # first run
    with torch.no_grad():
        task_prompt = "<s_rvlcdip>"
        decoder_input_ids = processor.tokenizer(
            task_prompt, add_special_tokens=False, return_tensors="pt"
        ).input_ids.to(model.decoder.device)
        pixel_values = processor(images, return_tensors="pt").pixel_values.to(
            model.encoder.device, model.encoder.dtype
        )
        _ = model.generate(
            pixel_values,
            decoder_input_ids=decoder_input_ids,
            max_length=model.decoder.config.max_position_embeddings,
            pad_token_id=processor.tokenizer.pad_token_id,
            eos_token_id=processor.tokenizer.eos_token_id,
            use_cache=True,
            bad_words_ids=[[processor.tokenizer.unk_token_id]],
            return_dict_in_generate=True,
        )
    torch.cuda.synchronize()
    
    # main run
    times = []
    times_gen = []
    times_pr = []
    times_tok = []
    for _ in range(_TOTAL_ITERATION):
        torch.cuda.synchronize()
        t1 = perf_counter()

        with torch.no_grad():
            task_prompt = "<s_rvlcdip>"

            torch.cuda.synchronize()
            t1_tok = perf_counter()
            decoder_input_ids = processor.tokenizer(
                task_prompt, add_special_tokens=False, return_tensors="pt"
            ).input_ids.to(model.decoder.device)
            torch.cuda.synchronize()
            t2_tok = perf_counter()
            times_tok.append(t2_tok - t1_tok)
            
            torch.cuda.synchronize()
            t1_pr = perf_counter()
            pixel_values = processor(images, return_tensors="pt").pixel_values.to(
                model.encoder.device, model.encoder.dtype
            )
            torch.cuda.synchronize()
            t2_pr = perf_counter()
            times_pr.append(t2_pr - t1_pr)
            
            torch.cuda.synchronize()
            t1_gen = perf_counter()
            _ = model.generate(
                pixel_values,
                decoder_input_ids=decoder_input_ids,
                max_length=model.decoder.config.max_position_embeddings,
                pad_token_id=processor.tokenizer.pad_token_id,
                eos_token_id=processor.tokenizer.eos_token_id,
                use_cache=True,
                bad_words_ids=[[processor.tokenizer.unk_token_id]],
                return_dict_in_generate=True,
            )
            torch.cuda.synchronize()
            t2_gen = perf_counter()
            times_gen.append(t2_gen - t1_gen)
        
        torch.cuda.synchronize()
        t2 = perf_counter()
        times.append(t2 - t1)
    
    print("processor.tokenizer", np.mean(times_tok[_WARMUP:]), np.std(times_tok[_WARMUP:]))
    print("processor.__call__", np.mean(times_pr[_WARMUP:]), np.std(times_pr[_WARMUP:]))
    print("model.generate",np.mean(times_gen[_WARMUP:]), np.std(times_gen[_WARMUP:]))
    print("Total", np.mean(times[_WARMUP:]), np.std(times[_WARMUP:]))


if __name__ == "__main__":
    main()
```

Comments: