Skip to content

Bug in flex attention #1824

Closed as not planned
Closed as not planned

Description

@Atif1727

try:
from torch.nn.attention.flex_attention import (
flex_attention as _flex_attention,
create_block_mask as _create_block_mask,
)
_flex_attention = torch.compile(_flex_attention, dynamic = True, options = torch_compile_options)
HAS_FLEX_ATTENTION = False
except:
HAS_FLEX_ATTENTION = False
pass

I am looking at the Flex Attention implementation code for a challenge I am solving by Unsloth. However, I noticed a bug in the following line:

_flex_attention = torch.compile(_flex_attention, dynamic=True, options=torch_compile_options)
HAS_FLEX_ATTENTION = False

The variable HAS_FLEX_ATTENTION should be set to True because if the import is successful, it indicates that Flex Attention is available."

Activity

  1. danielhanchen commented on Feb 26, 2025

    @danielhanchen
    Member

    Oh I left some code pre Flex Attention, but I didn't have time to actually enable it yet

  2. self-assigned this
    on Oct 8, 2026
  3. danielhanchen commented on Oct 8, 2026

    @danielhanchen
    Member

    Thanks for flagging this, and sorry on the delay! HAS_FLEX_ATTENTION = False on the success path is intentional: the old hand-written flex path in unsloth/kernels/flex_attention.py was deliberately disabled, so the flag acts as an off switch rather than an availability check.

    Flipping it to True would actually break Gemma 2 training today. That branch builds one causal BlockMask at max_seq_length and reuses it for every batch, and current PyTorch refuses a mask built for a longer length (ValueError: block_mask was created for block_mask.shape=(1, 1, 1024, 1024) but got q_len=37 and kv_len=37, reproduced on torch 2.13). It also ignores padding masks.

    Unsloth now uses flex attention through the transformers attention interface instead (for example Gemma 3 by default, and large head dim models via UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM), with BlockMasks built per batch. Gemma 2 stays on the softcapping kernel because it measured faster than flex.

    So I'm closing this as not planned. If you want flex attention on a model that supports it, pass attn_implementation = "flex_attention" to from_pretrained. Same reasoning as #5834.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions