Llama4 Scout fails to generate output for `use_cache=True`
Author: srijanie03
Pull request: no
Labels: name: bug

### System Info
PyTorch version: 2.5.1
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (aarch64)
GCC version: (GCC) 13.3.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.29.6
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-1019-nvidia-64k-aarch64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 11.5.119
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: NVIDIA GH200 480GB
Nvidia driver version: 550.90.07
cuDNN version: Probably one of the following:
/usr/lib/aarch64-linux-gnu/libcudnn.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_adv.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_cnn.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_engines_precompiled.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_graph.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_heuristic.so.9.3.0
/usr/lib/aarch64-linux-gnu/libcudnn_ops.so.9.3.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       aarch64
CPU op-mode(s):                     64-bit
Byte Order:                         Little Endian
CPU(s):                             72
On-line CPU(s) list:                0-71
Vendor ID:                          ARM
Model name:                         Neoverse-V2
Model:                              0
Thread(s) per core:                 1
Core(s) per socket:                 72
Socket(s):                          1
Stepping:                           r0p0
Frequency boost:                    disabled
CPU max MHz:                        3375.0000
CPU min MHz:                        81.0000
BogoMIPS:                           2000.00
Flags:                              fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti
L1d cache:                          4.5 MiB (72 instances)
L1i cache:                          4.5 MiB (72 instances)
L2 cache:                           72 MiB (72 instances)
L3 cache:                           114 MiB (1 instance)
NUMA node(s):                       9
NUMA node0 CPU(s):                  0-71
NUMA node1 CPU(s):                  
NUMA node2 CPU(s):                  
NUMA node3 CPU(s):                  
NUMA node4 CPU(s):                  
NUMA node5 CPU(s):                  
NUMA node6 CPU(s):                  
NUMA node7 CPU(s):                  
NUMA node8 CPU(s):                  
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; __user pointer sanitization
Vulnerability Spectre v2:           Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.4
[pip3] onnx==1.17.0
[pip3] onnxruntime-training==1.20.0+cpu
[pip3] onnxscript==0.2.3
[pip3] torch==2.5.1
[pip3] torchvision==0.20.1
[conda] numpy                     2.2.4                    pypi_0    pypi
[conda] torch                     2.6.0                    pypi_0    pypi
[conda] torchvision               0.21.0                   pypi_0    pypi

With the new transformers version 4.51.1, I am unable to get the model to generate the outputs. It works fine for the earlier version  4.51.0. I am using the default Llama4 example from HF.


Error trace:
```
File "venv/lib/python3.10/site-packages/transformers/integrations/sdpa_attention.py", line 54, in sdpa_attention_forward
    attn_output = torch.nn.functional.scaled_dot_product_attention(
RuntimeError: The size of tensor a (8192) must match the size of tensor b (4959) at non-singleton dimension 3
```


This `print(model(**inputs), use_cache=False)` works correctly. 

However, for version 4.51.0, both options worked fine. 

### Who can help?

@ArthurZucker  would really appreciate your input.

### Information

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

### Tasks

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

### Reproduction

```
processor = AutoProcessor.from_pretrained("meta-llama/Llama-4-Scout-17B-16E")
model = AutoModelForImageTextToText.from_pretrained("meta-llama/Llama-4-Scout-17B-16E",torch_dtype=torch.bfloat16)


url1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
url2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_layout.png"
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": url1},
            {"type": "image", "url": url2},
            {"type": "text", "text": "Can you describe how these two images are similar, and how they differ?"},
        ]
    },
]

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
)

print(model(**inputs))
```

### Expected behavior

Output result as this:
```
Llama4CausalLMOutputWithPast(loss=None, logits=tensor([[[ 0.0104, -1.6641, -1.6562,  ..., -1.6641, -1.6641, -1.6641],
         [-6.6562,  0.1108,  0.1113,  ...,  0.1108,  0.1118,  0.1260],
         [-2.6094, -5.8125, -5.8125,  ..., -5.8125, -5.8125, -5.8125],
         ...,
         [ 9.5000,  2.6875,  2.6875,  ...,  2.6875,  2.6875,  2.6875],
         [-4.0938,  6.7188,  6.7188,  ...,  6.7188,  6.7188,  6.7188],
         [ 5.6562, -2.7031, -2.7031,  ..., -2.7031, -2.7031, -2.7031]]],
       dtype=torch.bfloat16, grad_fn=<UnsafeViewBackward0>), past_key_values=DynamicCacheObject, hidden_states=None, attentions=None, image_hidden_states=tensor([[[-1.6016e-01,  8.0078e-02,  6.9141e-01,  ...,  5.4688e-01,
          -1.6016e-01, -1.6992e-01],
```

Comments:
Seems like it was introduced in https://github.com/huggingface/transformers/commit/2da82e432dbc08f9e497b353cdccfee7e84bd6a8 

Will be fixed by #37370 

Thanks for the quick fix. I tried the latest commit and it works fine with eager and sdpa.

However, it still failed with flex_attention, and I got this error:
torch._dynamo.exc.Unsupported: data dependent operator: aten._local_scalar_dense.default; to enable, set torch._dynamo.config.capture_scalar_outputs = True

Simply wondering whether I need to do anything special to use flex attention? Many thanks.

Closing as it should be fixed with latest commit, it is probably a torch version issue?! Use 2.6! 

got it, thanks a bunch!