Add SDPA and FlashAttention-2 support to LayoutLMv3 #42225
+202
−70
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Adds SDPA and FlashAttention-2 support to LayoutLMv3 using the unified attention interface pattern, following the same architecture used in BERT and other recent model implementations.
Fixes #35467
Implementation
LayoutLMv3SelfAttentionto useALL_ATTENTION_FUNCTIONSinterface instead of separate attention classeslayoutlmv3_eager_attention_forwardfunction that implements the CogView attention mechanism (alpha=32 scaling) with support for LayoutLMv3's relative position bias and spatial attention bias_supports_sdpa = Trueand_supports_flash_attn = Trueflags toLayoutLMv3PreTrainedModelcreate_bidirectional_mask(replacingget_extended_attention_mask)layer_idxparameter through attention classes for consistencyBackward compatibility
SDPA and FlashAttention-2 backends are incompatible with LayoutLMv3's relative position bias and spatial attention bias. The code raises a clear
ValueErrorwhen users attempt to combine these features, directing them to use eager mode. Default behavior (eager attention with all bias features) remains unchanged.Type of change
How has this change been tested?
ruff checkandruff formatboth passBefore submitting
Who can review?
@vasqu - Thank you for the detailed feedback on #41801! I've refactored the implementation to use the unified attention interface pattern as you suggested. Would definitely appreciate your feedback on this updated approach.
@ArthurZucker @Cyrilvallez - attention implementation reviewers