Repository: huggingface/transformers
Pull request: [`Flex Attn`] Fix torch 2.5.1 incompatibilities

Flex attention with `torch==2.5.1` is broken, see e.g. https://github.com/huggingface/transformers/issues/37380#issuecomment-2790650478

The PR has 3 changes:
1. Removes the compilation on the block mask as it does not provide any major benefits in perf either way and seems to be the root cause behind the issues (torch 2.5.x specific). Open to making it version dependable but thought it's easier this way for now.
2. Change the mask padding to be not addition but up to a value, e.g. 4 -> 4 + 6 -> 10 (before) vs 4 -> 6 (after); unsure if this is breaking but seemed appropriate. Edit: changed this back to old behavior.
3. Mask padding goes to at least the value of the default block size in flex attention (can be observed on smaller seq_lens leading to indexing errors) (torch 2.5.x specific).

# 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?

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

 -->
cc @ArthurZucker @Cyrilvallez 

Changed files:
filename: src/transformers/integrations/flex_attention.py
patch: @@ -32,10 +32,11 @@
 from packaging import version
 
 from ..utils import is_torch_flex_attn_available, logging
-from ..utils.import_utils import _torch_version, is_torchdynamo_compiling
+from ..utils.import_utils import _torch_version, is_torch_less_or_equal, is_torchdynamo_compiling
 
 
 if is_torch_flex_attn_available():
+    from torch.nn.attention.flex_attention import _DEFAULT_SPARSE_BLOCK_SIZE as flex_default_block_size  # noqa: N811
     from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
 
 
@@ -63,16 +64,20 @@ def __init__(self, training):
         Initialize or update the singleton instance.
         """
         if not self._is_flex_compiled or training != self.training:
+            self.training = training
+            if is_torch_less_or_equal("2.5.1"):
+                self._compiled_flex_attention = torch.compile(flex_attention, dynamic=False)
             # In PyTorch 2.6.0, there's a known issue with flex attention compilation which may
             # cause errors. The suggested fix is to compile with "max-autotune-no-cudagraphs"
             # see https://github.com/pytorch/pytorch/issues/146260 for training
-            self.training = training
-            if version.parse(_torch_version).base_version == "2.6.0" and training:
+            elif version.parse(_torch_version).base_version == "2.6.0" and training:
                 self._compiled_flex_attention = torch.compile(
                     flex_attention, dynamic=False, mode="max-autotune-no-cudagraphs"
                 )
+            # Fallback, usually the most recent torch 2.7.x+ versions
             else:
                 self._compiled_flex_attention = torch.compile(flex_attention)
+
             self._is_flex_compiled = True
 
     def __call__(self):
@@ -140,7 +145,9 @@ def make_flex_block_causal_mask(
         key_length = total_seq_len
     if not query_length:
         query_length = total_seq_len
-    attention_mask_2d = torch.nn.functional.pad(attention_mask_2d, value=0, pad=(0, key_length))
+    # older torch (2.5.x) cannot handle sequences not in multiples of 128 (default block size)
+    pad_len = ((key_length // flex_default_block_size) + 1) * flex_default_block_size
+    attention_mask_2d = torch.nn.functional.pad(attention_mask_2d, value=0, pad=(0, pad_len - key_length))
     device = attention_mask_2d.device
     document_ids = attention_mask_2d.clone()
 
@@ -208,7 +215,8 @@ def mask_mod(batch_idx, head_idx, q_idx, kv_idx):
         Q_LEN=query_length,
         KV_LEN=key_length,
         device=device,
-        _compile=True,
+        # compiling the mask is not BC with older torch
+        _compile=not is_torch_less_or_equal("2.5.1"),
     )
 
 

filename: src/transformers/masking_utils.py
patch: @@ -25,6 +25,7 @@
 
 
 if is_torch_flex_attn_available():
+    from torch.nn.attention.flex_attention import _DEFAULT_SPARSE_BLOCK_SIZE as flex_default_block_size  # noqa: N811
     from torch.nn.attention.flex_attention import BlockMask, create_block_mask
 else:
     # Register a fake type to avoid crashing for annotations and `isinstance` checks
@@ -550,6 +551,13 @@ def flex_attention_mask(
 
     # Potentially add the padding 2D mask
     if attention_mask is not None:
+        # Older torch (2.5.x) cannot handle sequences not in multiples of 128 (default block size)
+        # Hence we pad to multiples of this as a minimum to ensure this
+        pad_len = ((attention_mask.shape[1] // flex_default_block_size) + 1) * flex_default_block_size
+        pad_len = pad_len - attention_mask.shape[1]
+        if not _is_torch_greater_or_equal_than_2_6 and pad_len > 0:
+            attention_mask = torch.nn.functional.pad(attention_mask, value=0, pad=(0, pad_len))
+
         padding_mask = prepare_padding_mask(attention_mask, kv_length, kv_offset, _slice=False)
         mask_function = and_masks(mask_function, padding_mask_function(padding_mask))
 
@@ -564,7 +572,7 @@ def flex_attention_mask(
         Q_LEN=q_length,
         KV_LEN=kv_length,
         device=cache_position.device,
-        _compile=True,
+        _compile=_is_torch_greater_or_equal_than_2_6,
     )
     return block_mask
 

filename: src/transformers/utils/import_utils.py
patch: @@ -1173,6 +1173,24 @@ def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False):
         return version.parse(importlib.metadata.version("torch")) >= version.parse(library_version)
 
 
+@lru_cache
+def is_torch_less_or_equal(library_version: str, accept_dev: bool = False):
+    """
+    Accepts a library version and returns True if the current version of the library is less than or equal to the
+    given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+    2.7.0).
+    """
+    if not _is_package_available("torch"):
+        return False
+
+    if accept_dev:
+        return version.parse(version.parse(importlib.metadata.version("torch")).base_version) <= version.parse(
+            library_version
+        )
+    else:
+        return version.parse(importlib.metadata.version("torch")) <= version.parse(library_version)
+
+
 @lru_cache
 def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False):
     if not _is_package_available("huggingface_hub"):