[Fix] Fix bug of mismatched input type and weight type for SigLIP
Author: KooSung
Pull request: yes

Fix bug of mismatched input type and weight type for SigLIP.  Otherwise, the following error will occur:
RuntimeError: Input type (torch.cuda.floattensor) and weight type (cudabfloat16type) should be the same.

# 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).
- [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?
@amyeroberts
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: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- 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

 -->


Comments:
Hi @KooSung, thanks for opening this PR! 

For context, could you share a snippet to reproduce this error? Am I correct in interpreting this is happening if the model is loaded in bf16? 

Hello @amyeroberts, this PR is the same as #28504 that I submitted for Dinov2, which you approved on Jan 18.

You can reproduce it with the following code:

```
import torch
from transformers import SiglipImageProcessor, SiglipVisionModel
from PIL import Image
import requests

# URL of the image you want to process
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'

# Open the image
image = Image.open(requests.get(url, stream=True).raw)

# Load the image processor and the model
processor = SiglipImageProcessor.from_pretrained('google/siglip-so400m-patch14-384')
model = SiglipVisionModel.from_pretrained('google/siglip-so400m-patch14-384', torch_dtype=torch.bfloat16)

# Prepare the inputs
inputs = processor(images=image, return_tensors="pt")

# Get the model outputs
outputs = model(**inputs)
```
And you will get the following error: 

```
[/usr/local/lib/python3.10/dist-packages/transformers/models/siglip/modeling_siglip.py](https://localhost:8080/#) in forward(self, pixel_values, output_attentions, output_hidden_states, return_dict)
    955         return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    956 
--> 957         return self.vision_model(
    958             pixel_values=pixel_values,
    959             output_attentions=output_attentions,

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _wrapped_call_impl(self, *args, **kwargs)
   1516             return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1517         else:
-> 1518             return self._call_impl(*args, **kwargs)
   1519 
   1520     def _call_impl(self, *args, **kwargs):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *args, **kwargs)
   1525                 or _global_backward_pre_hooks or _global_backward_hooks
   1526                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1527             return forward_call(*args, **kwargs)
   1528 
   1529         try:

[/usr/local/lib/python3.10/dist-packages/transformers/models/siglip/modeling_siglip.py](https://localhost:8080/#) in forward(self, pixel_values, output_attentions, output_hidden_states, return_dict)
    854         return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    855 
--> 856         hidden_states = self.embeddings(pixel_values)
    857 
    858         encoder_outputs = self.encoder(

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _wrapped_call_impl(self, *args, **kwargs)
   1516             return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1517         else:
-> 1518             return self._call_impl(*args, **kwargs)
   1519 
   1520     def _call_impl(self, *args, **kwargs):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *args, **kwargs)
   1525                 or _global_backward_pre_hooks or _global_backward_hooks
   1526                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1527             return forward_call(*args, **kwargs)
   1528 
   1529         try:

[/usr/local/lib/python3.10/dist-packages/transformers/models/siglip/modeling_siglip.py](https://localhost:8080/#) in forward(self, pixel_values)
    266 
    267     def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
--> 268         patch_embeds = self.patch_embedding(pixel_values)  # shape = [*, width, grid, grid]
    269         embeddings = patch_embeds.flatten(2).transpose(1, 2)
    270 

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _wrapped_call_impl(self, *args, **kwargs)
   1516             return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1517         else:
-> 1518             return self._call_impl(*args, **kwargs)
   1519 
   1520     def _call_impl(self, *args, **kwargs):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *args, **kwargs)
   1525                 or _global_backward_pre_hooks or _global_backward_hooks
   1526                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1527             return forward_call(*args, **kwargs)
   1528 
   1529         try:

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/conv.py](https://localhost:8080/#) in forward(self, input)
    458 
    459     def forward(self, input: Tensor) -> Tensor:
--> 460         return self._conv_forward(input, self.weight, self.bias)
    461 
    462 class Conv3d(_ConvNd):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/conv.py](https://localhost:8080/#) in _conv_forward(self, input, weight, bias)
    454                             weight, bias, self.stride,
    455                             _pair(0), self.dilation, self.groups)
--> 456         return F.conv2d(input, weight, bias, self.stride,
    457                         self.padding, self.dilation, self.groups)
    458 

RuntimeError: Input type (torch.FloatTensor) and weight type (CPUBFloat16Type) should be the same or input should be a MKLDNN tensor and weight is a dense tensor
```

I guess it's a common problem for many models in transformers

The proper way to handle this is to cast the input to be in-line with the model:

```python
import torch
from transformers import SiglipImageProcessor, SiglipVisionModel
from PIL import Image
import requests

# URL of the image you want to process
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'

# Open the image
image = Image.open(requests.get(url, stream=True).raw)

# Load the image processor and the model
processor = SiglipImageProcessor.from_pretrained('google/siglip-so400m-patch14-384')
model = SiglipVisionModel.from_pretrained('google/siglip-so400m-patch14-384', torch_dtype=torch.bfloat16)

# Prepare the inputs
inputs = processor(images=image, return_tensors="pt")
inputs = inputs.to(torch.bfloat16)
```

i.e. I shouldn't have approved the other PR either :) 

Thanks @StarCycle .

Hello @amyeroberts,  other visual models also have related automatic dtype transformation code implementations, such as the following.  I think it makes sense to automatically transform the tensor type, and LLM and vision encoder often need this feature in Vision-Language Models (e.g. LLaVA).
**CLIP**
https://github.com/huggingface/transformers/blob/a3f9221a449e9b949e71d9b047c66186f023481f/src/transformers/models/clip/modeling_clip.py#L189-L190

**BLIP**
https://github.com/huggingface/transformers/blob/a3f9221a449e9b949e71d9b047c66186f023481f/src/transformers/models/blip/modeling_blip.py#L248-L249

**InstructBLIP**
https://github.com/huggingface/transformers/blob/a3f9221a449e9b949e71d9b047c66186f023481f/src/transformers/models/instructblip/modeling_instructblip.py#L112-L113


@StarCycle Yes, I understand. Most transformer model don't perform this casting, so it's a safer assumption to assume that the model's won't handle this and you need to cast the input dtypes yourself. 

For example, you won't see `input_ids.to(layer.weight)` in the library (apart from one erroneous case for BLIP text). 

The responsibility for handling this is on the tools or user, rather than within the model here. 

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.