Skip to content

[blip_2] Support attn_implementation dispatch - #46401

Merged
vasqu merged 11 commits into
huggingface:mainfrom
YangKai0616:sdpa-Blip2QFormerModel
Jun 16, 2026
Merged

vasqu merged 11 commits into
huggingface:mainfrom
YangKai0616:sdpa-Blip2QFormerModel

Conversation

@YangKai0616

Copy link
Copy Markdown
Contributor

What does this PR do?

As per the title.

@YangKai0616

Copy link
Copy Markdown
Contributor Author

@vasqu

class Blip2QFormerModel(Blip2PreTrainedModel):
config: Blip2QFormerConfig

_supports_attention_backend = False # adds position on attn weights before last matmul

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have to set it explicitly to True here and in other models

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

config: Blip2QFormerConfig

_supports_attention_backend = False # adds position on attn weights before last matmul
_supports_flash_attn = False

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think we can do FA and flex now, no?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FA still looks blocked by the QFormer fp32 path, flex does not seem blocked in the same way as FA, but flex fails with attention dropout in training, and QFormer attention recording expects attention weights while flex returns LSE instead. Perhaps we should keep this PR to SDPA content only?👀

Comment on lines -599 to +583
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))

mixed_query_layer = self.query(hidden_states)

query_layer = self.transpose_for_scores(mixed_query_layer)

# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))

attention_scores = attention_scores / math.sqrt(self.attention_head_size)

if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_scores = attention_scores + attention_mask
current_states = hidden_states

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh nice, i forgot we got rid of those position_embeddings which weren't used by official ckpt

@YangKai0616

Copy link
Copy Markdown
Contributor Author

For the test case test_modeling_instructblip.py::InstructBlipModelIntegrationTest::test_inference_flant5_xl, the output from the current default SDPA branch differs from the default eager mode in upstream/main.
However, it matches when using eager mode on the current branch or float32 dtype. Expectations should be updated, but since I don't know the device used in your CI, this PR will not be updated for now.

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a few smaller comments but overall looks good already

Comment on lines -564 to -579
def save_attn_gradients(self, attn_gradients):
self.attn_gradients = attn_gradients

def get_attn_gradients(self):
return self.attn_gradients

def save_attention_map(self, attention_map):
self.attention_map = attention_map

def get_attention_map(self):
return self.attention_map

def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh god that was ugly 😬 glad to get rid of this

_supports_attention_backend = True
_supports_sdpa = True
_supports_flash_attn = False # Q-Former is kept in fp32, which blocks reliable Flash Attention dispatch.
_supports_flex_attn = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Flex attention should work no?

@YangKai0616 YangKai0616 Jun 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, updated here.

_supports_attention_backend = False # adds position on attn weights before last matmul
_supports_attention_backend = True
_supports_sdpa = True
_supports_flash_attn = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets add comments when why not

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And same re flex

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously unverified. Verified now, updated the flag and related tests.

_supports_sdpa = True
_supports_flash_attn = False
_supports_sdpa = False
_supports_flex_attn = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@vasqu

vasqu commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

For the test case test_modeling_instructblip.py::InstructBlipModelIntegrationTest::test_inference_flant5_xl, the output from the current default SDPA branch differs from the default eager mode in upstream/main.
However, it matches when using eager mode on the current branch or float32 dtype. Expectations should be updated, but since I don't know the device used in your CI, this PR will not be updated for now.

Can we force eager attention at load time instead for now?

@YangKai0616

Copy link
Copy Markdown
Contributor Author

Can we force eager attention at load time instead for now?

Done.

@YangKai0616 YangKai0616 changed the title [blip_2] Support attn_implementation=sdpa dispatch [blip_2] Support attn_implementation dispatch Jun 8, 2026

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some smaller things but overall ready. Biggest thing to fix is imo to properly override _prepare_config_headdim instead of skipping as this affects the whole flex and FA test suite

self.scale = self.head_dim**-0.5
self.is_causal = False
self.attention_dropout = config.attention_dropout
self.dropout = config.attention_dropout

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I was missing this context previously: You named it attention_dropout because of this attribute naming here. This makes more sense then. Let's revert this back to attention dropout then (otherwise we are slightly breaking)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

pass

@unittest.skip(reason="_prepare_config_headdim breaks the qformer/vision cross-attention hidden-size invariant")
def test_flex_attention_with_grads(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we fix that with a small override?

def test_flash_attn_2_inference_equivalence_right_padding(self):
pass

@unittest.skip(reason="_prepare_config_headdim breaks the qformer/vision cross-attention hidden-size invariant")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, I think we should rather override _prepare_config_headdim to account for these models

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@YangKai0616

Copy link
Copy Markdown
Contributor Author

Friendly ping @vasqu

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, just see my last comments but nothing major

)

if encoder_attention_mask is not None:
query_embedding_output = embedding_output[:, :query_length, :] if query_length > 0 else embedding_output

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh where did you find this issue arising? Ig this is the issue potentially on cross attn?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's on the cross-attention path. The Q-Former's cross-attention queries come only from the query tokens, but embedding_output also contains the text tokens. create_bidirectional_mask infers the query dimension from inputs_embeds, so passing the full embedding_output produced a mask whose query dim didn't match the actual cross-attention query length. I found it in the error of the test case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comments added.

@require_bitsandbytes
@pytest.mark.flash_attn_test
@slow
def test_flash_attn_2_fp32_ln(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add small comments for the overrides as to why?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same for below

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: blip_2, instructblip, instructblipvideo

@vasqu

vasqu commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

run-slow: blip_2, instructblip, instructblipvideo

@vasqu

vasqu commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Just checking with slow CI but merging afterwards 🤗

@github-actions

Copy link
Copy Markdown
Contributor

Workflow Run ⚙️

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

models: ["models/blip_2", "models/instructblip", "models/instructblipvideo"]
quantizations: []

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@github-actions

Copy link
Copy Markdown
Contributor

CI Results

Workflow Run ⚙️

Commit Info

Context Commit Description
RUN dae955a0 workflow commit (merge commit)
PR 116fe1e7 branch commit (from PR)
main 7ff490ac base commit (on main)

✅ No failing test specific to this PR 🎉 👏 !

@vasqu
vasqu added this pull request to the merge queue Jun 16, 2026
Merged via the queue into huggingface:main with commit 0a4d1c8 Jun 16, 2026
46 checks passed
stevhliu pushed a commit to stevhliu/transformers that referenced this pull request Jul 30, 2026
* [blip_2] Support attn_implementation=sdpa dispatch

* Refine

* Update

* Doc

* CI check-repository-consistency

* Revert self.attention_dropout

* override test cases

* rename func

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants