ViT model's output_attention is not work
Author: naturesh
Pull request: no
Labels: name: bug

### System Info

macos 26.0


python 3.10
pytorch 2.7.1
transformers 4.57.1



### Who can help?

@yonigozlan @molbap 

### Information

- [ ] The official example scripts
- [ ] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)

### Reproduction


```python
import torch
from transformers import AutoModel, AutoProcessor
from transformers.image_utils import load_image

# load the model and processor
ckpt = "google/siglip2-so400m-patch16-naflex"
model = AutoModel.from_pretrained(ckpt).eval()
processor = AutoProcessor.from_pretrained(ckpt)

# load the image
image = load_image("https://huggingface.co/datasets/merve/coco/resolve/main/val2017/000000000285.jpg")
inputs = processor(images=[image], return_tensors="pt").to(model.device)

# run infernece
with torch.no_grad():
    image_embeddings = model.vision_model(
    pixel_values = inputs['pixel_values'],
    attention_mask = inputs['pixel_attention_mask'],
    spatial_shapes = inputs['spatial_shapes'],
    output_attentions = True,
    output_hidden_states = True
)   
print(image_embeddings)


```

### Expected behavior

I'm trying to get attributes, hidden_states from google/siglip2-so400m-patch16-naflex using the model.vision_model.forward() method.

from_pretrained(), you can also add output_attentions as a parameter, 
If you add it as a new config or as a parameter in .forward(), it always returns attributes and hidden_states to none in all operations.

Changing attn_implementation to eager does not solve the problem.



Comments:
Hi @naturesh, thank you for the issue! indeed it seems that SiglipVision model is missing an input tracing decorator. Opened a fix, you can try the branch on which it is.

I encountered the same problem. I was using the code example provided by the official qwen2.5-VL documentation, and after setting `output_attentions=True`, all output attention values ​​were `None`. I don't know what the problem is. My transformers are 0.5.0.dev. The code is as follows:
```
from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import debugpy

debugpy.listen(address=("0.0.0.0", 5678))
debugpy.wait_for_client()

local_model_path = "path/Qwen2.5-VL-3B-Instruct"
# default: Load the model on the available device(s)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    local_model_path, torch_dtype="auto", device_map="auto"
)

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-3B-Instruct",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processer
processor = AutoProcessor.from_pretrained(local_model_path)

# The default range for the number of visual tokens per image in the model is 4-16384.
# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# Inference: Generation of the output
generated_ids = model.generate(**inputs, 
                               max_new_tokens=128, 
                               output_hidden_states=True, 
                               return_dict_in_generate=True, 
                               output_attentions=True, 
                               output_scores =True,
                               output_logits=True
                            )

generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
```

Screenshot below.

<img width="1143" height="896" alt="Image" src="https://github.com/user-attachments/assets/96107578-af78-4862-bc9c-190ec56b261f" />

<img width="1144" height="743" alt="Image" src="https://github.com/user-attachments/assets/56941827-2197-4c75-bf01-001dda7e6088" />

The reason is that the decoder of the text model is not returning attention scores. I don't know how to solve this; I might consider changing the transformer version.

Hi @StoKou, make sure you are in `attn_implementation="eager"` when calling `from_pretrained` as it might default to `sdpa` which does not return intermediate attentions and hidden states. If you still encounter the problem please open an issue and ping me! 

thansk！！！the problem is solved！

Is there a simple way to fix this before it's officially resolved? You don't modify the package source code yourself 

Hi @naturesh , I'm not sure I understood properly? Currently the PR linked should fix it in next release, you can either pull the changes from there, for instance
```bash
git clone <...transformers repo>
cd transformers
git checkout siglip_and_check_model_changes
pip install -e .
```

and your transformers env version will be updated with that change. Does that answer your question?

Thank you for your reply, all I want is to know if I can solve the current problem by adding a few lines from this code snippet.

Is there a simple solution?

```python
import torch
from transformers import AutoModel, AutoProcessor
from transformers.image_utils import load_image

# load the model and processor
ckpt = "google/siglip2-so400m-patch16-naflex"
model = AutoModel.from_pretrained(ckpt).eval()
processor = AutoProcessor.from_pretrained(ckpt)

# load the image
image = load_image("https://huggingface.co/datasets/merve/coco/resolve/main/val2017/000000000285.jpg")
inputs = processor(images=[image], return_tensors="pt").to(model.device)

# run infernece
with torch.no_grad():
    image_embeddings = model.vision_model(
    pixel_values = inputs['pixel_values'],
    attention_mask = inputs['pixel_attention_mask'],
    spatial_shapes = inputs['spatial_shapes'],
    output_attentions = True,
    output_hidden_states = True
)   
print(image_embeddings)


```