Fix Causality Handling in Flash Attention to Support Bidirectional Attention
Author: lucaswychan
Pull request: yes

# What does this PR do?
Fixes #39554 

The original implementation of the `flash_attention_forward` function is restricted to performing **causal attention** and does not support **bidirectional attention**. This behavior stems from how the function handles causality:

- The function relies on the `Attention.is_causal` attribute, which belongs to the `Attention` class in the model.
- By default, `Attention.is_causal` is set to `True`, enforcing causal attention (where the model only attends to previous tokens in a sequence).
- This attribute is never modified in the code, meaning the setting is effectively fixed.
- Additionally, while the function removes the `is_causal` key from the keyword arguments (`kwargs`) passed to it, this value is not used. Instead, it always defers to the hardcoded `Attention.is_causal` value.

As a result, even if a user attempts to pass `is_causal=False` through `kwargs` to enable bidirectional attention (where the model can attend to both previous and future tokens), the input is ignored. Consequently, the current setup makes it impossible to perform bidirectional attention when using flash attention.

<!--
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.
- [ ] 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.

@ArthurZucker @Cyrilvallez @vasqu 

<!-- 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, @SunMarc and @qgallouedec
- 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

 -->


Comments:
After checking #35390 , it seems like it only pops `is_causal` from `kwargs` without saving and using it (which is the reason I created this PR). My approach takes a similar way, but I first store the value of `is_causal` when popping, and fallback to `module.is_causal` only when `is_causal is None` (which means `is_causal` does not exist in `kwargs`). Below are the sample code to check my fix:

```python
import torch
from transformers import AutoTokenizer, AutoModel

model_name = "Qwen/Qwen2.5-7B"
device = torch.device("cuda")

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, device_map=device, attn_implementation="flash_attention_2", torch_dtype="auto")

input_sentence = "I want bidirectional attention"
inputs = tokenizer([input_sentence], return_tensors="pt", padding=True).to(model.device)

output_with_causal = model(**inputs, is_causal=True)
print(f'last hidden state with causal : {output_with_causal["last_hidden_state"]}')

output_without_causal = model(**inputs, is_causal=False)
print(f'last hidden state without causal : {output_without_causal["last_hidden_state"]}')
```

and you should see the output:

```
last hidden state with causal : tensor([[[-2.1719,  2.5469, -6.6875,  ...,  2.9531, -0.2100,  2.2031],
         [-0.7305, -0.2656, -1.5156,  ..., -0.7461, -0.0952, -1.6641],
         [-0.4668,  1.8125,  0.2021,  ...,  0.8867, -1.1875, -1.0547],
         [ 1.8359,  2.3750, -1.5547,  ...,  0.6445, -1.3906, -2.0469],
         [ 4.1562, -3.6250, -2.9844,  ..., -2.1562, -1.2031, -0.3086]]],
       device='cuda:7', dtype=torch.bfloat16, grad_fn=<MulBackward0>)

last hidden state without causal : tensor([[[ 3.0156, -0.7070, -1.5234,  ..., -1.1875,  0.7188, -0.0464],
         [ 0.4629, -1.0781,  0.0135,  ..., -2.2656,  0.2412, -2.6250],
         [ 0.2334, -2.0469, -0.6680,  ..., -1.8906, -0.7305, -3.2969],
         [ 0.9961, -0.9844, -0.9805,  ..., -1.2500, -0.3555, -2.1094],
         [ 1.3125,  0.7539, -0.5781,  ..., -0.4824,  0.0216,  0.3633]]],
       device='cuda:7', dtype=torch.bfloat16, grad_fn=<MulBackward0>)
```

which indeed the output is changed by altering `is_causal`.

run-slow: auto

https://github.com/huggingface/transformers/issues/39554#issuecomment-3133120685 as per his comment we need to make sure the attention mask creation takes this into account imo!

This comment contains run-slow, running the specified jobs: 

models: ['models/auto']
quantizations: [] ...

I believe the attention mask creation is handled well in FA2, as reflected by the function `flash_attn_varlen_func`, which allows passing an argument `causal` (the same as `is_causal` with a different name) to control the causality of the attention. 

For SDPA, I ran a small experiment to see if we can enable bidirectional attention, and the answer is yes evidenced by the following result:
```
# SDPA

last hidden state with causal : tensor([[[-2.1719,  2.5469, -6.6875,  ...,  2.9531, -0.2100,  2.2031],
         [-0.7227, -0.2656, -1.5156,  ..., -0.7383, -0.0923, -1.6719],
         [-0.4590,  1.8281,  0.1631,  ...,  0.9141, -1.1875, -1.0859],
         [ 1.8359,  2.3594, -1.5625,  ...,  0.6484, -1.3516, -2.0625],
         [ 4.1875, -3.6406, -3.0000,  ..., -2.1562, -1.2578, -0.2637]]],
       device='cuda:6', dtype=torch.bfloat16, grad_fn=<MulBackward0>)
last hidden state without causal : tensor([[[ 2.8906, -0.6758, -1.5234,  ..., -1.1797,  0.7148, -0.0840],
         [ 0.4395, -1.1094,  0.0476,  ..., -2.3281,  0.1611, -2.6094],
         [ 0.2158, -2.1562, -0.6406,  ..., -1.9297, -0.7266, -3.3438],
         [ 0.9023, -1.1484, -1.0000,  ..., -1.3828, -0.3301, -2.1719],
         [ 1.2500,  0.5391, -0.4492,  ..., -0.4629,  0.0056,  0.2520]]],
       device='cuda:6', dtype=torch.bfloat16, grad_fn=<MulBackward0>)
```

Can you merge/rebase? Just need to make sure CI is green

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_39707). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Thx for the PR @lucaswychan :hugs: (and for bearing with me :p)

@lucaswychan One tiny nitpick: could you please update `Refer to #<issue number>` to `Fixes #<issue number>` in the PR description? The word `Fixes` tells GitHub that this PR will fix the underlying issue, displays a PR icon near the issue in the issue list, and automatically closes the issue once the PR is merged. I don't know if it will close the issue now since the PR is already merged but you can always close the underlying issue manually. 🙏

@vasqu hello，can you share how i can convert qwen3 to bidirectional attention for embedding detailly thank u

@Inistlwq You can just pass `is_causal=False` in your forward, e.g. something along 
```
...
output = model.forward(**inputs, is_causal=False)
...
```
Note that this will only work with Flash Attention out of the box. 

@vasqu  I tested it on v100，which doesn't support Flash Attention，I tried pass is_causal=False many times，but it doesn't work。If no Flash Attention，how I can convert qwen3 to bidirectional attention

@vasqu `batch_dict = tokenizer(
    input_texts,
    padding=True,
    truncation=True,
    max_length=max_length,
    return_tensors="pt",
)
batch_dict.to(model.device)
outputs = model(**batch_dict,is_causal=False)` and i just test it on h20，it does work ；but if don't want to use flash attention,how I can convert ,for example on v100

@Inistlwq

For Flash Attention, you can use https://github.com/huggingface/transformers/pull/39707#issuecomment-3127851175
```python
import torch
from transformers import AutoTokenizer, AutoModel

model_name = "Qwen/Qwen2.5-7B"
device = torch.device("cuda")

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, device_map=device, attn_implementation="flash_attention_2", torch_dtype="auto")

input_sentence = "I want bidirectional attention"
inputs = tokenizer([input_sentence], return_tensors="pt", padding=True).to(model.device)

output_with_causal = model(**inputs, is_causal=True)
print(f'last hidden state with causal : {output_with_causal["last_hidden_state"]}')

output_without_causal = model(**inputs, is_causal=False)
print(f'last hidden state without causal : {output_without_causal["last_hidden_state"]}')
```
For anything else, you will need to provide your own mask
```python
import torch
from transformers import AutoTokenizer, AutoModel
from transformers.masking_utils import create_bidirectional_mask


model_name = "Qwen/Qwen2.5-7B"
device = torch.device("cuda")

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, device_map=device, torch_dtype="auto")

input_sentence = "I want bidirectional attention"
inputs = tokenizer([input_sentence], return_tensors="pt", padding=True).to(model.device)

output_with_causal = model(**inputs)
print(f'last hidden state with causal : {output_with_causal["last_hidden_state"]}')

inputs["attention_mask"] = create_bidirectional_mask(
    config=model.config,
    input_embeds=torch.ones_like(inputs["input_ids"])[..., None].to(model.dtype),
    attention_mask=inputs["attention_mask"],
)
output_without_causal = model(**inputs, is_causal=False)
print(f'last hidden state without causal : {output_without_causal["last_hidden_state"]}')
```
Note, that flash attention does not really need extra care for the mask while the other variations do.

> ```python
> create_bidirectional_mask
> ```

@vasqu  thank u very much，I will try!