Repository navigation
fix: Changed MultiHeadAttention's implementation from a naive one to pytorch's native one - #902
Conversation
|
Can you just run the benchmark example from the EEG Conformer PR? |
Codecov Report✅ All modified and coverable lines are covered by tests. 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:
|
|
Sure, here is the benchmark: Loss curves
Confusion matrices
CodeI used the following code (with some tweaks compared to #454 else it wouldn't work), and changed the MultiHeadAttention class directly in 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) |
|
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! |
|
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.
|
fd08ba9 to
1eec23d
Compare
There was a problem hiding this comment.
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 + maskwill 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 whereTruemeans "masked/ignored". Consider supporting both mask types explicitly: ifmask.dtype==torch.bool, usemasked_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.,
Truemeans "ignore"), butforward()currently passesmaskthrough unchanged toscaled_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_attentionbut this module no longer importstorch.nn.functional as Fand the implementation callstorch.nn.functional.scaled_dot_product_attentiondirectly. 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.
38fb212 to
45bef9f
Compare
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
45bef9f to
cd04172
Compare
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_headssilently truncates whenemb_sizeis not divisible bynum_heads, and the subsequent einops split will fail later with a less clear error. Consider validating in__init__(e.g., raise aValueErrorifemb_size % num_heads != 0) and/or computinghead_dimonly 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
MultiHeadAttentionnow 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., intest/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.
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.
There was a problem hiding this comment.
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.
| ) | ||
| self.emb_size = emb_size | ||
| self.num_heads = num_heads | ||
| self.head_dim = emb_size // num_heads |
There was a problem hiding this comment.
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.
| self.head_dim = emb_size // num_heads |
| 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, | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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).
- 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)
|
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 :) |
|
many thanks for push what @agramfort suggested, we didn't replace for native layer, but we are much more faster now :) |









Hello,
This is intended to fix #873
Two "breaking changes" different from the initial naive implementation:
(self.emb_size // self.num_heads) ** (1 / 2)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.
Output