Repository navigation
functional.scaled_dot_product_attention (public, exact op order); five models' attention through it, bit-identical - #1457
Merged
bruAristimunha merged 2 commits intoOct 18, 2026
Conversation
…r); five models' hand-written attention through it, bit-identical
This was referenced Oct 17, 2026
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #1457 +/- ##
==========================================
- Coverage 91.04% 91.02% -0.03%
==========================================
Files 165 166 +1
Lines 21653 21632 -21
==========================================
- Hits 19714 19690 -24
- Misses 1939 1942 +3 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Part of #1442, Tier 1 of the consolidation plan. Follows Bruno's instruction to debug each model systematically for exact replication rather than accept a 1e-6 tolerance.
History: why EEGConformer could not be moved onto native attention (2023)
PR #454 (EEGConformer, Aug 2023, comment) compared the model's own
MultiHeadAttentionwithnn.MultiheadAttentionby training curves on BNCI2014001 subject 3 (original layer vs native with/without Xavier init): the native layer converged faster and "overfit" more, so the custom layer stayed. Issue #873 (2024) later found the custom layer scales byemb_size**0.5instead ofhead_dim**0.5. So the 2023 comparison was between two different models (another scale, another init), not a numerical-equivalence test, which is why it could not replicate. Here the weights and the math are the same; the only question is floating-point op order, and that can be settled exactly.Root cause (Phase 1, same for all)
Instrumented each model's attention call (
/tmp/sdpa_debug.py: same q/k/v, old op sequence vs the helper, tensor by tensor). The first diverging op is the scaled scores, before the softmax:SDPBackend.MATHscalesqandkeach bysqrt(scale)before the matmul; the models scale the scores after it (/ sqrt(d)or* scale), or scaleq(EEGDINO). These agree bit for bit only whensqrt(scale)is a power of two (head_dim 16, 256): AttnSleep (head_dim 16) matched under MATH; TMSA-Net (4), ATCNet (8), TCFormer (12), EEGDINO (25) did not.(q@kᵀ)/√d(q@kᵀ)/√d(q@kᵀ)/√d(q@kᵀ)*scale(q*scale)@kᵀscale*(q@kᵀ)output_attention=Truereturns the weights, which SDPA cannot produce(max |diff| on the attention output; whole-model output differences were 7e-09 to 2.4e-07.)
Hypotheses, one at a time: H1 default backend (no), H2
SDPBackend.MATHwith explicitscale(AttnSleep only; for EEGDINO, pre-scaled q withscale=1.0under MATH also matches, but not the other three), H3 the old op order inside the shared helper (all five). H3 is the fix.Change
braindecode.functional.scaled_dot_product_attention(public; moved frommodules.attention, whose private names stay as aliases): addsscaleandexact.exact=Truerunssoftmax((q @ kᵀ) / sqrt(d)) @ v, or* scalewhen given, dropout on the weights, masks honoured; bit-identical to a hand-written attention.exact=Falsekeeps the previous behaviour (torch kernels, Gaudi fused kernel on HPU) for the 14 existing users, unchanged.exact=True; EEGDINO passesq * scalewithscale=1.0(its reference order). Private_attentionin AttnSleep deleted.test_attention_exact.pyswaps the per-model old op order back in and assertstorch.equalon the eval forward and on loss and every gradient after a training step with the same seed (10 cases);exactvs the three formulas for head_dim 4/8/12/16/25 incl. dropout draws and TorchScript;exactvs default within 1e-6.test_multi_head_attention_supports_torch_2_0_sdpapatches the helper at its new module.state_dictkeys and weights,torch.equaloutputs. 499 modules/functional tests and 336 related model tests pass.The 1e-6 fallback Bruno allowed was not needed for any model.