Skip to content

[SAM3] Compute masks once instead of per-layer, fix fa2 crash#42543

Merged
yonigozlan merged 4 commits into
huggingface:mainfrom
yonigozlan:sam3-compute-mask-before-layers
Dec 2, 2025
Merged

[SAM3] Compute masks once instead of per-layer, fix fa2 crash#42543
yonigozlan merged 4 commits into
huggingface:mainfrom
yonigozlan:sam3-compute-mask-before-layers

Conversation

@yonigozlan

Copy link
Copy Markdown
Contributor

Some small improvements for SAM3. There will be more to come as we discussed @molbap ;), including using modular.

This PR adds the following improvements:

  • Compute attention masks once instead of per layer in the DETR encoder and decoder.
  • Fall-back to sdpa when using FA2 in DETR decoder layer attention, as we pass a relative position bias matrix as an attention mask but fa2 doesn't support float attention masks. Cc @vasqu Is there any better ways to handle this?
  • Remove unnecessary logic for presence token, pad rpb matric/attention mask directly.

@yonigozlan yonigozlan requested review from molbap and vasqu December 2, 2025 03:41
@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.

@molbap molbap 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.

Better already, thanks for the refacto!

hidden_states = torch.cat([presence_token, hidden_states], dim=1)
query_pos = torch.cat([torch.zeros_like(presence_token), query_pos], dim=1)
# Prepend zeros to query_pos for presence token
query_pos = F.pad(query_pos, (0, 0, 1, 0), mode="constant", value=0)

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.

🙏

Comment thread src/transformers/models/sam3/modeling_sam3.py Outdated

@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 overall, just some info on FA and a bit of fixes there.

Where are the relative biases introduced? Not important but moreso FMI. Sadly, most FA versions can't support this.

Comment on lines +377 to +388
if (
self.config._attn_implementation == "flash_attention_2"
and attention_mask is not None
and attention_mask.dtype != torch.bool
):
# Relative position bias tensors are represented as float masks and are incompatible with Flash Attention 2.
# Fallback to SDPA for this call only so the rest of the model can still benefit from FA2.
attention_interface = ALL_ATTENTION_FUNCTIONS["sdpa"]
logger.warning_once(
"Sam3Attention: falling back to SDPA for relative-position cross-attention because "
"Flash Attention 2 does not support additive bias masks."
)

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.

Is this common in the model? Maybe we should just deactivate FA support if that's the case --> it seldomly can work at all. But given the comment I doubt it?

Suggested change
if (
self.config._attn_implementation == "flash_attention_2"
and attention_mask is not None
and attention_mask.dtype != torch.bool
):
# Relative position bias tensors are represented as float masks and are incompatible with Flash Attention 2.
# Fallback to SDPA for this call only so the rest of the model can still benefit from FA2.
attention_interface = ALL_ATTENTION_FUNCTIONS["sdpa"]
logger.warning_once(
"Sam3Attention: falling back to SDPA for relative-position cross-attention because "
"Flash Attention 2 does not support additive bias masks."
)
if (
"flash" in self.config._attn_implementation
and attention_mask is not None
and attention_mask.dtype != torch.bool
):
# Relative position bias tensors are represented as float masks and are incompatible with Flash Attention
# Fallback to SDPA for this call only so the rest of the model can still benefit from FA
attention_interface = ALL_ATTENTION_FUNCTIONS["sdpa"]
logger.warning_once(
"Sam3Attention: falling back to SDPA for relative-position cross-attention because "
"Flash Attention does not support additive bias masks."
)

For FA, you should only check for the "flash" keyword. The reason is that we also support different other attentions such as FA3 and kernel variations (+ FA4 soon I hope, working on that one).

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.

But yea, FA itself cannot support relative biases (except alibi). There was a different library which might support this #41882 (FA with biases).

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.

Thanks for the info! I'll put "flash" to handle fa3/4.

Is this common in the model? Maybe we should just deactivate FA support if that's the case --> it seldomly can work at all. But given the comment I doubt it?

It's only used in DETR decoder layer attention, so other attentions (there are quite a few) can still benefit from fa.

_checkpoint_conversion_mapping = {
r"detector_model.(.+)": r"\1" # the regex allows to remove the prefix, and add it back in revert mode
}
_checkpoint_conversion_mapping = {"detector_model.": ""}

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.

I know Cyril worked a lot on this to work, just want to double check if this works :D

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.

This must have been changed back by mistake during a merge, thanks for catching that!

@github-actions

github-actions Bot commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

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

run-slow: sam3

@yonigozlan yonigozlan enabled auto-merge (squash) December 2, 2025 17:13
@yonigozlan yonigozlan merged commit 80b408d into huggingface:main Dec 2, 2025
17 checks passed
sarathc-cerebras pushed a commit to sarathc-cerebras/transformers that referenced this pull request Dec 7, 2025
…gface#42543)

* Compute masks once instead of per-layer, fix fa2 crash

* nit

* Change after review
SangbumChoi pushed a commit to SangbumChoi/transformers that referenced this pull request Jan 23, 2026
…gface#42543)

* Compute masks once instead of per-layer, fix fa2 crash

* nit

* Change after review
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