Skip to content

fix: Changed MultiHeadAttention's implementation from a naive one to pytorch's native one - #902

Merged
bruAristimunha merged 10 commits into
braindecode:masterfrom
Leob000:native-multiheadattention
Apr 12, 2026
Merged

bruAristimunha merged 10 commits into
braindecode:masterfrom
Leob000:native-multiheadattention

Conversation

@Leob000

@Leob000 Leob000 commented Dec 20, 2025

Copy link
Copy Markdown
Contributor

Hello,
This is intended to fix #873

Two "breaking changes" different from the initial naive implementation:

  • The scaling factor becomes (self.emb_size // self.num_heads) ** (1 / 2)
  • The mask is inverted (the initial implementation used a mask where True meant to keep the value while Pytorch uses True to ignore the value). Braincode doesn't seem to use this mask in other parts of the codebase to I made a direct change without guardrails, I'm not sure how to handle that otherwise.

I made a quick standalone file to compare the difference in output of the two methods (with a fixed scaling factor for the naive method). Caveat: as the weight initialization differ, a manual copy of the initial weights is made between the two methods.

import torch
import torch.nn as nn
import torch.nn.functional as F
from einops.layers.torch import Rearrange


class MultiHeadAttention_new(nn.Module):
    def __init__(self, emb_size, num_heads, dropout=0.0):
        super().__init__()
        self.mha = nn.MultiheadAttention(
            emb_size, num_heads, dropout=dropout, batch_first=True
        )

    def forward(self, x, mask=None):
        return self.mha(x, x, x, attn_mask=mask, need_weights=False)[0]


class MultiHeadAttention_old(nn.Module):
    def __init__(self, emb_size, num_heads, dropout=0):
        super().__init__()
        self.emb_size = emb_size
        self.num_heads = num_heads
        self.keys = nn.Linear(emb_size, emb_size)
        self.queries = nn.Linear(emb_size, emb_size)
        self.values = nn.Linear(emb_size, emb_size)
        self.att_drop = nn.Dropout(dropout)
        self.projection = nn.Linear(emb_size, emb_size)

        self.rearrange_stack = Rearrange(
            "b n (h d) -> b h n d",
            h=num_heads,
        )
        self.rearrange_unstack = Rearrange(
            "b h n d -> b n (h d)",
        )

    def forward(self, x, mask=None):
        queries = self.rearrange_stack(self.queries(x))
        keys = self.rearrange_stack(self.keys(x))
        values = self.rearrange_stack(self.values(x))
        energy = torch.einsum("bhqd, bhkd -> bhqk", queries, keys)
        if mask is not None:
            fill_value = float("-inf")
            energy = energy.masked_fill(~mask, fill_value)

        # scaling = self.emb_size ** (1 / 2)
        scaling = (self.emb_size // self.num_heads) ** (1 / 2)
        att = F.softmax(energy / scaling, dim=-1)
        att = self.att_drop(att)
        out = torch.einsum("bhal, bhlv -> bhav ", att, values)
        out = self.rearrange_unstack(out)
        out = self.projection(out)
        return out


def run_comparison():
    print("--- Comparing Old vs New Attention ---")
    B, L, E, H = 4, 10, 16, 4
    torch.manual_seed(42)

    mha_old = MultiHeadAttention_old(E, H)
    mha_new = MultiHeadAttention_new(E, H)

    # Sync weights
    with torch.no_grad():
        w_q, b_q = mha_old.queries.weight, mha_old.queries.bias
        w_k, b_k = mha_old.keys.weight, mha_old.keys.bias
        w_v, b_v = mha_old.values.weight, mha_old.values.bias
        mha_new.mha.in_proj_weight.copy_(torch.cat([w_q, w_k, w_v], dim=0))
        mha_new.mha.in_proj_bias.copy_(torch.cat([b_q, b_k, b_v], dim=0))
        mha_new.mha.out_proj.weight.copy_(mha_old.projection.weight)
        mha_new.mha.out_proj.bias.copy_(mha_old.projection.bias)

    x = torch.randn(B, L, E)
    x_old = x.clone().detach().requires_grad_(True)
    x_new = x.clone().detach().requires_grad_(True)

    # Test 1: Forward (No Mask)
    out_old = mha_old(x_old)
    out_new = mha_new(x_new)
    diff = (out_old - out_new).abs()
    print(
        f"Forward Diff (No Mask): Max: {diff.max().item():.2e} | Mean: {diff.mean().item():.2e}"
    )

    # Test 2: Backward (No Mask)
    target = torch.randn_like(out_old)
    F.mse_loss(out_old, target).backward()
    F.mse_loss(out_new, target).backward()
    assert x_old.grad is not None and x_new.grad is not None
    diff_grad = (x_old.grad - x_new.grad).abs()
    print(
        f"Grad Diff (No Mask):    Max: {diff_grad.max().item():.2e} | Mean: {diff_grad.mean().item():.2e}"
    )

    # Test 3: Forward (With Mask - Raw / Wrong Convention)
    mask = torch.ones(L, L, dtype=torch.bool)
    mask[:, -3:] = False  # Mask last 3 positions
    out_old_masked = mha_old(x_old, mask=mask)

    # This demonstrates that Old uses True=Keep while New uses True=Ignore
    out_new_raw_mask = mha_new(x_new, mask=mask)
    diff_raw = (out_old_masked - out_new_raw_mask).abs()
    print(
        f"Forward Diff (Masked, Raw):      Max: {diff_raw.max().item():.2e} | Mean: {diff_raw.mean().item():.2e} (High diff confirms mask convention mismatch)"
    )

    # Test 4: Forward (With Mask - Inverted / Correct Convention)
    # Old: True=Keep, New: True=Ignore (so we pass ~mask)
    out_new_masked = mha_new(x_new, mask=~mask)
    diff_masked = (out_old_masked - out_new_masked).abs()
    print(
        f"Forward Diff (Masked, Inverted): Max: {diff_masked.max().item():.2e} | Mean: {diff_masked.mean().item():.2e}"
    )


if __name__ == "__main__":
    run_comparison()

Output

--- Comparing Old vs New Attention ---
Forward Diff (No Mask): Max: 8.94e-08 | Mean: 1.94e-08
Grad Diff (No Mask):    Max: 4.37e-10 | Mean: 7.25e-11
Forward Diff (Masked, Raw):      Max: 4.84e-01 | Mean: 1.63e-01 (High diff confirms mask convention mismatch)
Forward Diff (Masked, Inverted): Max: 8.94e-08 | Mean: 1.96e-08

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Can you just run the benchmark example from the EEG Conformer PR?

@bruAristimunha

Copy link
Copy Markdown
Collaborator

#454

@codecov

codecov Bot commented Dec 21, 2025

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.48%. Comparing base (3e4903e) to head (422adcb).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #902      +/-   ##
==========================================
- Coverage   87.49%   87.48%   -0.01%     
==========================================
  Files         113      113              
  Lines       10483    10462      -21     
==========================================
- Hits         9172     9153      -19     
+ Misses       1311     1309       -2     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Leob000

Leob000 commented Dec 22, 2025

Copy link
Copy Markdown
Contributor Author

Sure, here is the benchmark:

Loss curves

  • PR Implementation (native pytorch):
native_training_curves
  • Original naive implementation with a fixed scaling (scaling = (self.emb_size // self.num_heads) ** (1 / 2)):
oldfixed_training_curves
  • Original naive implementation with the original scaling (scaling = self.emb_size ** (1 / 2)):
oldnonfixed_training_curves

Confusion matrices

  • PR Implementation (native pytorch):
native_confusion_matrix
  • Original naive implementation with a fixed scaling (scaling = (self.emb_size // self.num_heads) ** (1 / 2)):
oldfixed_confusion_matrix
  • Original naive implementation with the original scaling (scaling = self.emb_size ** (1 / 2)):
oldnonfixed_confusion_matrix

Code

I used the following code (with some tweaks compared to #454 else it wouldn't work), and changed the MultiHeadAttention class directly in braindecode/modules/attention.py to test the three different cases.

import matplotlib.pyplot as plt
import pandas as pd
import torch
from matplotlib.lines import Line2D
from numpy import multiply
from sklearn.metrics import confusion_matrix
from skorch.callbacks import LRScheduler
from skorch.helper import predefined_split
from pathlib import Path

from braindecode import EEGClassifier
from braindecode.datasets import MOABBDataset
from braindecode.models import EEGConformer
from braindecode.preprocessing import (
    Preprocessor,
    create_windows_from_events,
    exponential_moving_standardize,
    preprocess,
)
from braindecode.util import set_random_seeds
from braindecode.visualization import plot_confusion_matrix

subject_id = 3
dataset = MOABBDataset(dataset_name="BNCI2014_001", subject_ids=[subject_id])


low_cut_hz = 4.0  # low cut frequency for filtering
high_cut_hz = 38.0  # high cut frequency for filtering
# Parameters for exponential moving standardization
factor_new = 1e-3
init_block_size = 1000
# Factor to convert from V to uV
factor = 1e6

preprocessors = [
    Preprocessor("pick_types", eeg=True, meg=False, stim=False),  # Keep EEG sensors
    Preprocessor(lambda data: multiply(data, factor)),  # Convert from V to uV
    Preprocessor("filter", l_freq=low_cut_hz, h_freq=high_cut_hz),  # Bandpass filter
    Preprocessor(
        exponential_moving_standardize,  # Exponential moving standardization
        factor_new=factor_new,
        init_block_size=init_block_size,
    ),
]

# Transform the data
preprocess(dataset, preprocessors)


trial_start_offset_seconds = -0.5
# Extract sampling frequency, check that they are same in all datasets
sfreq = dataset.datasets[0].raw.info["sfreq"]
assert all([ds.raw.info["sfreq"] == sfreq for ds in dataset.datasets])
# Calculate the trial start offset in samples.
trial_start_offset_samples = int(trial_start_offset_seconds * sfreq)

# Create windows using braindecode function for this. It needs parameters to define how
# trials should be used.
windows_dataset = create_windows_from_events(
    dataset,
    trial_start_offset_samples=trial_start_offset_samples,
    trial_stop_offset_samples=0,
    preload=True,
)


splitted = windows_dataset.split("session")
train_set = splitted["0train"]
valid_set = splitted["1test"]


cuda = torch.cuda.is_available()  # check if GPU is available, if True chooses to use it
mps = torch.backends.mps.is_available()
device = "cuda" if cuda else "mps" if mps else "cpu"
if cuda:
    torch.backends.cudnn.benchmark = True

seed = 20200220
set_random_seeds(seed=seed, cuda=cuda)

n_classes = 4
# Extract number of chans and time steps from dataset
n_chans = train_set[0][0].shape[0]
input_window_samples = windows_dataset[0][0].shape[1]

model = EEGConformer(
    n_chans=n_chans,
    n_outputs=n_classes,
    final_fc_length=2760,
)

# Send model to GPU
if cuda:
    model.cuda()
elif mps:
    model.to("mps")


# These values we found good for shallow network:
lr = 0.0625 * 0.01
weight_decay = 0

# For deep4 they should be:
# lr = 1 * 0.01
# weight_decay = 0.5 * 0.001

batch_size = 64
n_epochs = 100

clf = EEGClassifier(
    model,
    criterion=torch.nn.CrossEntropyLoss,
    optimizer=torch.optim.AdamW,
    train_split=predefined_split(valid_set),  # using valid_set for validation
    optimizer__lr=lr,
    optimizer__weight_decay=weight_decay,
    batch_size=batch_size,
    max_epochs=n_epochs,
    classes=[0, 1, 2, 3],
    callbacks=[
        "accuracy",
        ("lr_scheduler", LRScheduler("CosineAnnealingLR", T_max=n_epochs - 1)),
    ],
    device=device,
)
# Model training for a specified number of epochs. `y` is None as it is already supplied
# in the dataset.
clf.fit(train_set, y=None)


# Extract loss and accuracy values for plotting from history object
results_columns = ["train_loss", "valid_loss", "train_accuracy", "valid_accuracy"]
df = pd.DataFrame(
    clf.history[:, results_columns],
    columns=results_columns,  # type:ignore
    index=clf.history[:, "epoch"],
)

# get percent of misclass for better visual comparison to loss
df = df.assign(
    train_misclass=100 - 100 * df.train_accuracy,
    valid_misclass=100 - 100 * df.valid_accuracy,
)

# plt.style.use("seaborn")
output_dir = Path("temp")
output_dir.mkdir(parents=True, exist_ok=True)
fig, ax1 = plt.subplots(figsize=(8, 3))
df.loc[:, ["train_loss", "valid_loss"]].plot(
    ax=ax1, style=["-", ":"], marker="o", color="tab:blue", legend=False, fontsize=14
)

ax1.tick_params(axis="y", labelcolor="tab:blue", labelsize=14)
ax1.set_ylabel("Loss", color="tab:blue", fontsize=14)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

df.loc[:, ["train_misclass", "valid_misclass"]].plot(
    ax=ax2, style=["-", ":"], marker="o", color="tab:red", legend=False
)
ax2.tick_params(axis="y", labelcolor="tab:red", labelsize=14)
ax2.set_ylabel("Misclassification Rate [%]", color="tab:red", fontsize=14)
ax2.set_ylim(ax2.get_ylim()[0], 85)  # make some room for legend
ax1.set_xlabel("Epoch", fontsize=14)
plt.title("Model")
# where some data has already been plotted to ax
handles = []
handles.append(
    Line2D([0], [0], color="black", linewidth=1, linestyle="-", label="Train")
)
handles.append(
    Line2D([0], [0], color="black", linewidth=1, linestyle=":", label="Valid")
)
plt.legend(handles, [h.get_label() for h in handles], fontsize=14)
plt.tight_layout()
fig.savefig(output_dir / "training_curves.png", dpi=150)
plt.close(fig)


# generate confusion matrices
# get the targets
y_true = valid_set.get_metadata().target
y_pred = clf.predict(valid_set)

# generating confusion matrix
confusion_mat = confusion_matrix(y_true, y_pred)

# add class labels
if hasattr(windows_dataset.datasets[0], "windows"):
    label_dict = windows_dataset.datasets[0].windows.event_id.items()
    labels = list(dict(sorted(list(label_dict), key=lambda kv: kv[1])).keys())
else:
    labels = sorted(list(set(windows_dataset.datasets[0].raw.annotations.description)))

# plot the basic conf. matrix
plot_confusion_matrix(confusion_mat, class_names=labels)
confusion_fig = plt.gcf()
confusion_fig.savefig(output_dir / "confusion_matrix.png", dpi=150)
plt.close(confusion_fig)

@PierreGtch

Copy link
Copy Markdown
Collaborator

Hi @Leob000, Thanks for your contribution and this nice analysis 🚀

Could you plot the three implementations in the same figure, as different hue? And classification error and loss as different figure to keep things less cluttered

Thank you!

@Leob000

Leob000 commented Dec 23, 2025

Copy link
Copy Markdown
Contributor Author

I remade the plots, to get a better idea of the uncertainty I did multiple runs: for each method, 3 different subjects of the dataset, each having 3 runs with a different seed. (The code for the plots is on this branch for reference).

Strangely the native torch way seem to behave a bit worse on the Validation.

loss_comparison misclass_comparison

Copilot AI review requested due to automatic review settings April 12, 2026 17:20
@bruAristimunha
bruAristimunha force-pushed the native-multiheadattention branch from fd08ba9 to 1eec23d Compare April 12, 2026 17:22

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.

Pull request overview

This PR updates MultiHeadAttention to use PyTorch’s scaled dot-product attention (SDPA) for correct multi-head scaling and to enable optimized attention kernels when available, addressing #873.

Changes:

  • Replaced the previous manual attention computation with an SDPA-based implementation (with a PyTorch <2.0 fallback).
  • Corrected the scaling behavior by relying on head-dimension scaling (sqrt(head_dim)).
  • Refactored projections to explicit Q/K/V linear layers plus an output projection.
Comments suppressed due to low confidence (3)

braindecode/modules/attention.py:790

  • In the PyTorch <2.0 fallback, energy = energy + mask will not correctly apply a boolean attention mask (it will just add 0/1), and it also diverges from the SDPA path which supports boolean masks where True means "masked/ignored". Consider supporting both mask types explicitly: if mask.dtype==torch.bool, use masked_fill(mask, -inf) (with a dtype-appropriate -inf), otherwise treat it as an additive float mask and add it.
    References
    ----------
    .. [Wu2023] Wu, Z. et al., 2023 CAT: Learning to Collaborate Channel and
        Spatial Attention from Multi-Information Fusion. IET Computer Vision 2023.
    """

braindecode/modules/attention.py:783

  • The PR description mentions that the mask convention was inverted to match PyTorch (i.e., True means "ignore"), but forward() currently passes mask through unchanged to scaled_dot_product_attention. If callers still provide the old convention (True=keep), results will be wrong. Either implement the inversion here for boolean masks (and document it), or update the docstring/type contract to clearly state the expected convention and ensure call sites are updated.
        reduction ratio of the fully-connected layers
    bias : bool, default=True
        if True, adds a learnable bias will be used in the convolution,

    Examples
    --------
    >>> import torch
    >>> from braindecode.modules import CATLite
    >>> module = CATLite(in_channels=16, reduction_rate=4)
    >>> inputs = torch.randn(2, 16, 1, 64)
    >>> outputs = module(inputs)
    >>> outputs.shape
    torch.Size([2, 16, 1, 64])

braindecode/modules/attention.py:730

  • Docstring references F.scaled_dot_product_attention but this module no longer imports torch.nn.functional as F and the implementation calls torch.nn.functional.scaled_dot_product_attention directly. Updating the docstring to match the actual API name/import would avoid confusion for readers.
        Pytorch.Tensor
        """
        b, c, h, w = x.shape
        x_blurred = self.gauss_filter(x.transpose(1, 2)).transpose(1, 2)


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@bruAristimunha
bruAristimunha force-pushed the native-multiheadattention branch 2 times, most recently from 38fb212 to 45bef9f Compare April 12, 2026 17:26
Copilot AI review requested due to automatic review settings April 12, 2026 17:26
Replace nn.MultiheadAttention wrapper with direct use of
F.scaled_dot_product_attention (SDPA) for flash-attention support,
while keeping separate Q/K/V nn.Linear projections to preserve
the original Song et al. (2022) training dynamics.

Includes manual fallback for PyTorch < 2.0.

Fixes braindecode#873
@bruAristimunha
bruAristimunha force-pushed the native-multiheadattention branch from 45bef9f to cd04172 Compare April 12, 2026 17:28

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.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread braindecode/modules/attention.py Resolved
Comment thread braindecode/modules/attention.py Resolved
Comment thread braindecode/modules/attention.py Resolved
Copilot AI review requested due to automatic review settings April 12, 2026 17:32

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (2)

braindecode/modules/attention.py:862

  • self.head_dim = emb_size // num_heads silently truncates when emb_size is not divisible by num_heads, and the subsequent einops split will fail later with a less clear error. Consider validating in __init__ (e.g., raise a ValueError if emb_size % num_heads != 0) and/or computing head_dim only after this check to make failures deterministic and easier to diagnose.
    Examples
    --------
    >>> import torch
    >>> from braindecode.modules import MultiHeadAttention
    >>> module = MultiHeadAttention(emb_size=32, num_heads=4, dropout=0.1)

braindecode/modules/attention.py:895

  • MultiHeadAttention now has two execution paths (SDPA vs manual fallback) and updated mask/scaling behavior, but there don’t appear to be unit tests covering this module (e.g., in test/unit_tests/models/test_modules.py). Adding targeted tests that (1) verify the SDPA and fallback paths produce matching outputs/gradients for the same weights and (2) validate boolean vs additive mask semantics would help prevent regressions, especially on CI environments pinned to older PyTorch versions.
        position; for float masks the values are **added** to the
        attention scores before softmax.

    Examples
    --------
    >>> import torch
    >>> from braindecode.modules import MultiHeadAttention
    >>> module = MultiHeadAttention(emb_size=32, num_heads=4, dropout=0.1)
    >>> inputs = torch.randn(2, 10, 32)
    >>> outputs = module(inputs)
    >>> outputs.shape
    torch.Size([2, 10, 32])
    """

    _has_sdpa = hasattr(torch.nn.functional, "scaled_dot_product_attention")

    def __init__(self, emb_size, num_heads, dropout=0.0):
        super().__init__()
        if emb_size % num_heads != 0:
            raise ValueError(
                f"emb_size ({emb_size}) must be divisible by "
                f"num_heads ({num_heads})."
            )
        self.emb_size = emb_size
        self.num_heads = num_heads
        self.head_dim = emb_size // num_heads
        self.keys = nn.Linear(emb_size, emb_size)
        self.queries = nn.Linear(emb_size, emb_size)
        self.values = nn.Linear(emb_size, emb_size)
        self.att_drop = dropout
        self.projection = nn.Linear(emb_size, emb_size)

        self.rearrange_stack = Rearrange(
            "b n (h d) -> b h n d",
            h=num_heads,
        )
        self.rearrange_unstack = Rearrange(
            "b h n d -> b n (h d)",
        )

    def forward(self, x: Tensor, mask: Optional[Tensor] = None) -> Tensor:

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/whats_new.rst Resolved
Comment thread braindecode/modules/attention.py Resolved
braindecode requires torch>=2.0 so F.scaled_dot_product_attention
is always available. The fallback with _has_sdpa class attribute
broke torch.jit.script.
Copilot AI review requested due to automatic review settings April 12, 2026 18:26

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

Comments suppressed due to low confidence (1)

docs/whats_new.rst:41

  • This change is backward-incompatible (boolean mask convention flips to PyTorch’s True=ignore, and scaling behavior changes). Please add a note under the “API and behavior changes” section so users notice the behavior break, rather than only listing it as an enhancement.
- Use ``F.scaled_dot_product_attention`` in :class:`braindecode.modules.MultiHeadAttention`,
  enabling flash-attention and memory-efficient kernels on supported hardware.
  By `Léo Burgund`_ and `Bruno Aristimunha`_.
  (:gh:`902`)

API and behavior changes
========================

- None yet

Requirements

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread braindecode/modules/attention.py Resolved
)
self.emb_size = emb_size
self.num_heads = num_heads
self.head_dim = emb_size // num_heads

Copilot AI Apr 12, 2026

Copy link

Choose a reason for hiding this comment

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

self.head_dim is assigned but not used anywhere in this class or elsewhere in the codebase. Consider removing it to avoid dead state, or use it explicitly (e.g., for readability in any future scaling/mask handling) so it doesn’t become misleading.

Suggested change
self.head_dim = emb_size // num_heads

Copilot uses AI. Check for mistakes.
Comment thread braindecode/modules/attention.py Resolved
Comment on lines +896 to +903
dp = self.att_drop if self.training else 0.0
out = F.scaled_dot_product_attention(
queries,
keys,
values,
attn_mask=mask,
dropout_p=dp,
)

Copilot AI Apr 12, 2026

Copy link

Choose a reason for hiding this comment

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

There are unit tests for other modules (e.g., SqueezeAndExcitation) in test/unit_tests/models/test_modules.py, but none covering MultiHeadAttention. Since this PR changes the attention backend and mask semantics, please add a small unit test asserting forward shape and verifying mask convention (boolean True masks/ignores positions) to prevent regressions.

Copilot uses AI. Check for mistakes.
Copilot AI review requested due to automatic review settings April 12, 2026 18:32

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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/whats_new.rst Resolved
Comment thread test/unit_tests/models/test_modules.py Outdated
Comment on lines +1275 to +1279
out_masked = mha(x, mask=mask)
out_no_mask = mha(x)
assert out_masked.shape == out_no_mask.shape
# Outputs should differ when mask is applied
assert not torch.allclose(out_masked, out_no_mask, atol=1e-5)

Copilot AI Apr 12, 2026

Copy link

Choose a reason for hiding this comment

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

This assertion can be flaky because it relies on random initialization/input to ensure the mask changes the output. To make the test deterministic and robust, set a fixed torch.manual_seed(...) (and/or assert on a specific element / require max(abs(diff)) to exceed a threshold).

Copilot uses AI. Check for mistakes.
@bruAristimunha

Copy link
Copy Markdown
Collaborator
image

- Add torch.manual_seed to bool mask test for determinism
- Use max_diff threshold instead of allclose for robustness
- Fix docstring/whats_new to not overstate flash-attention availability
  (flash-attention is CUDA-only; SDPA picks best available kernel)
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Hi @Leob000,

I've been studying attention more, and it seems the key here is the initialization. The way it's defined leads to better results. I tested it with about 3 Moabb datasets, and nothing conclusive.

I tried studying and benchmarking to use the layer, but everything affected the behavior or changed something. In the end, the best trade-off I found was to use what Torch uses to compute attention.

That way, we get the best of both worlds :)

@bruAristimunha

Copy link
Copy Markdown
Collaborator

many thanks for push what @agramfort suggested, we didn't replace for native layer, but we are much more faster now :)

@bruAristimunha
bruAristimunha merged commit e160e11 into braindecode:master Apr 12, 2026
10 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.

MultiHeadAttention scaling factor

4 participants