Repository: huggingface/transformers
Pull request: Fix attention mask expansion when converting to executorch

# What does this PR do?

I was trying to convert clip to Executorch and had an issue with `AttentionMaskConverter._expand_mask`

```
# load model
import torch
from transformers import  AutoProcessor, AutoModel

model_clip = AutoModel.from_pretrained("openai/clip-vit-base-patch32", torch_dtype=torch.float16) # be ceraful with alternative attention implementations
processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")

class TextModel(torch.nn.Module):
    def __init__(self, text_model, text_projection):
        super().__init__()
        self.text_model =text_model 
        self.text_projection = text_projection

    def forward(self, input_ids, attention_mask = None):
        output = self.text_model(input_ids, attention_mask)
        output = output.pooler_output
        output = self.text_projection(output)
        output = torch.flatten(output)
        return output

text_model = TextModel(model_clip.text_model, model_clip.text_projection)

from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
from torch.export import export

input_ids2 = (torch.randint(0, 20000, (1,76), dtype=torch.int64), torch.randint(0, 2, (1,76), dtype=torch.int))

exported_program = export(text_model, input_ids2)
executorch_program = to_edge_transform_and_lower(
    exported_program,
    partitioner = [XnnpackPartitioner()]
).to_executorch()

with open("clip_text_model.pte", "wb") as file:
    file.write(executorch_program.buffer)
```

used to fail with:
```
SpecViolationError: These operators are taking Tensor inputs with mismatched dtypes:

Operator: <EdgeOpOverload: aten.sub.Tensor>: schema = aten::sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor with args: {'self': torch.float32, 'other': torch.float16, '__ret_0': torch.float16}
stack trace:   File "/var/folders/wr/dzqrxx290wdd7hsn7dnrjn3r0000gn/T/ipykernel_84249/3576045078.py", line 8, in forward
    output = self.text_model(input_ids, attention_mask)
  File "/Users/przemek/anaconda3/envs/executorch-2/lib/python3.10/site-packages/transformers/utils/generic.py", line 969, in wrapper
    output = func(self, *args, **kwargs)
  File "/Users/przemek/anaconda3/envs/executorch-2/lib/python3.10/site-packages/transformers/models/clip/modeling_clip.py", line 731, in forward
    attention_mask = _prepare_4d_attention_mask(
  File "/Users/przemek/anaconda3/envs/executorch-2/lib/python3.10/site-packages/transformers/modeling_attn_mask_utils.py", line 478, in _prepare_4d_attention_mask
    return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
  File "/Users/przemek/anaconda3/envs/executorch-2/lib/python3.10/site-packages/transformers/modeling_attn_mask_utils.py", line 212, in _expand_mask
    inverted_mask = 1.0 - expanded_mask

Please make sure the dtypes of the Tensor inputs are the same as the dtypes of the corresponding outputs.
```

It was caused by 1.0 being float32 while mask was converted to dtype of model (float16 in my case and that's what caused problems). After this small fix, it converts correctly.

<!--
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 partially #32506


## 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).
- [ ] 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

 -->


Changed files:
filename: src/transformers/modeling_attn_mask_utils.py
patch: @@ -193,7 +193,7 @@ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int]
 
         expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
 
-        inverted_mask = 1.0 - expanded_mask
+        inverted_mask = torch.tensor(1.0, dtype=dtype) - expanded_mask
 
         return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)