Skip to content

MultiHeadAttention scaling factor #873

Closed

Description

@Leob000

Hello,

Forgive me if this is intentional, in braindecode/modules/attention.py line 754 for the MultiHeadAttention class, the scaling factor is

scaling = self.emb_size ** (1 / 2)

when it should probably be

scaling = (self.emb_size // self.num_heads) ** (1 / 2), as per the multihead case.

(This class is currently used for the ctnet and eegconformer models).

Furthermore, this class might benefit from wrapping PyTorch's native implementation to support features like FlashAttention.

Activity

  1. bruAristimunha commented on Dec 17, 2025

    @bruAristimunha
    Collaborator

    hey @Leob000 :)

    Many thanks for reporting this! In fact, we should make maximum use of the native attention mechanism.

    During the implementation of this class, we conducted extensive experimentation to understand the rationale behind why these small details significantly impacted performance.

    #454 (comment)

    Since our tests didn't reveal the exact root cause that you identified, we left it as is. I remember we were very curious about this issue, and even @martinwimpff conducted a more systematic study on it, but again, without a conclusion. We can definitely revive this question to remove as much code as possible :)

  2. agramfort commented on Dec 17, 2025

    @agramfort
    Collaborator

    +1 to use native pytorch code. Here it seems more like a bug report. If the data does not allow to conclude as error bars are too big due to limited data let's just do what the theory / common practice suggests !

  3. martinwimpff commented on Dec 17, 2025

    @martinwimpff
    Collaborator

    I agree with @agramfort. Even though we might sacrifice some performance/reproducability (on the reported datasets), there is no reason to build custom attention layers like this without a clear justification of the differences to the original implementation.

  4. bruAristimunha commented on Dec 17, 2025

    @bruAristimunha
    Collaborator

    hey @Leob000,

    Looks like we have your first official braindecode PR coming! Now it's no longer the case study for the internship :)

    And to start well with @agramfort and @martinwimpff reviewing ;)

    @martinwimpff, can you share here the code that you showed me once, with all the key components that you studied to match the value for the multiattention? I recall that initialization was a crucial step.

  5. added 6 commits that reference this issue on Apr 12, 2026
    9bcc41a
    fd08ba9
    1eec23d
    38fb212
    45bef9f
    cd04172
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions