Skip to content

functional.scaled_dot_product_attention (public, exact op order); five models' attention through it, bit-identical - #1457

Merged
bruAristimunha merged 2 commits into
braindecode:masterfrom
bruAristimunha:cleanup/t21-sdpa
Oct 18, 2026
Merged

bruAristimunha merged 2 commits into
braindecode:masterfrom
bruAristimunha:cleanup/t21-sdpa

Conversation

@bruAristimunha

Copy link
Copy Markdown
Collaborator

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 MultiHeadAttention with nn.MultiheadAttention by 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 by emb_size**0.5 instead of head_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:

  • torch's default CPU kernel (flash-attention CPU) runs a blocked online softmax: never bit-identical.
  • torch's SDPBackend.MATH scales q and k each by sqrt(scale) before the matmul; the models scale the scores after it (/ sqrt(d) or * scale), or scale q (EEGDINO). These agree bit for bit only when sqrt(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.
model old op order head_dim first diverging op default SDPA vs old MATH vs old result
AttnSleep (q@kᵀ)/√d 16 — (MATH equal) / scores (default) 3.7e-08 0 bit-identical
TMSA-Net (q@kᵀ)/√d 4 scaled scores 9.5e-07 4.8e-07 bit-identical
ATCNet (q@kᵀ)/√d 8 scaled scores 1.8e-07 1.8e-07 bit-identical
TCFormer (q@kᵀ)*scale 12 scaled scores 7.2e-07 4.8e-07 bit-identical
EEGDINO (q*scale)@kᵀ 25 scaled scores 7.2e-07 4.8e-07 bit-identical
MEDFormer scale*(q@kᵀ) — not reached: default output_attention=True returns the weights, which SDPA cannot produce — — left as is

(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.MATH with explicit scale (AttnSleep only; for EEGDINO, pre-scaled q with scale=1.0 under 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 from modules.attention, whose private names stay as aliases): adds scale and exact. exact=True runs softmax((q @ kᵀ) / sqrt(d)) @ v, or * scale when given, dropout on the weights, masks honoured; bit-identical to a hand-written attention. exact=False keeps the previous behaviour (torch kernels, Gaudi fused kernel on HPU) for the 14 existing users, unchanged.
  • ATCNet, AttnSleep, TCFormer, TMSA-Net call it with exact=True; EEGDINO passes q * scale with scale=1.0 (its reference order). Private _attention in AttnSleep deleted.
  • Tests (written failing first): test_attention_exact.py swaps the per-model old op order back in and asserts torch.equal on the eval forward and on loss and every gradient after a training step with the same seed (10 cases); exact vs the three formulas for head_dim 4/8/12/16/25 incl. dropout draws and TorchScript; exact vs default within 1e-6. test_multi_head_attention_supports_torch_2_0_sdpa patches the helper at its new module.
  • Characterization against master: all six models, identical state_dict keys and weights, torch.equal outputs. 499 modules/functional tests and 336 related model tests pass.

The 1e-6 fallback Bruno allowed was not needed for any model.

…r); five models' hand-written attention through it, bit-identical
Copilot AI balanced review requested due to automatic review settings October 17, 2026 21:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.87097% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.02%. Comparing base (47912a9) to head (1a40d8d).
⚠️ Report is 5 commits behind head on master.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI balanced review requested due to automatic review settings October 18, 2026 00:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@bruAristimunha
bruAristimunha merged commit 579b46a into braindecode:master Oct 18, 2026
7 checks passed
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.

2 participants