Skip to content

Adding Convolutional Transformer model - #454

Merged
bruAristimunha merged 58 commits into
braindecode:masterfrom
eeyhsong:eeyhsong
Aug 25, 2023
Merged

bruAristimunha merged 58 commits into
braindecode:masterfrom
eeyhsong:eeyhsong

Conversation

@eeyhsong

Copy link
Copy Markdown
Contributor

No description provided.

@martinwimpff martinwimpff left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@eeyhsong please check if your custom attention modules can be replaced by the torch version. If not, please let us know where your implementation differs and why it is important.
Thank you for contributing to braindecode!

Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread braindecode/models/conformer.py Resolved
Comment thread docs/whats_new.rst Resolved
@bruAristimunha

bruAristimunha commented Aug 3, 2023 •

Copy link
Copy Markdown
Collaborator

Hello @eeyhsong and @martinwimpff,

To speed up the integration process, I corrected some things that I suggested were wrong and some things that @martinwimpff pointed out.

Also, I realized that there is an error in the library unrelated to this PR that is being handled in the PR #460.

@eeyhsong, I think the fundamental thing missing is to see if we can replace attention with the native module without any problem, and the suggestion @martinwimpff made about Pytorch's native module for the transformer part.

After that, tests. Hope we can finish it by Friday :)

Fixing version
Comment thread braindecode/models/eegconformer.py Resolved
Comment thread braindecode/models/eegconformer.py Resolved
Comment thread braindecode/models/eegconformer.py Resolved
Comment thread braindecode/models/eegconformer.py Resolved
Comment thread braindecode/models/eegconformer.py Resolved
@sliwy

sliwy commented Aug 3, 2023 •

Copy link
Copy Markdown
Collaborator

Hi @eeyhsong, congrats for the PR! Nice that we can have one more model 🤗

I added some comments. @eeyhsong do you think you may use ShallowFBCSPNet model already implemented in braindecode with some specific parameters to match your article? Then we may reduce redundant code and also it may be easier to make link between your model and ShallowFBCSPNet by Robin.

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Hi @eeyhsong!

I corrected the tests I had created. I think you are very close to iterating your model to braindecode.

I was chatting with @martinwimpff, and the only point is that we are looking to switch to PyTorch for any possible part of the model. To minimize what we need to maintain and ensure that PyTorch guarantees sustainability for as many versions as possible. This will be better for your more general model usage.

In this context, can you please provide a mini-code version with the code you tested to native layers? 🙏🏽 It could be a comment on this GitHub PR, just for us to try it out and get on the same page about using personality layers.

I appreciate your effort on this thread, and we're almost done after these review rounds.

@eeyhsong

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha!
I've upload an implementation Line 306-332. You may test with the torch version. I'm not sure if it could be more simple with nn..
If you insist for the torch version, I think its okay, for more general usage.

Sincerey,

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Thank you @eeyhsong!

@martinwimpff and I will take a look :)

Comment thread braindecode/models/eegconformer.py Resolved
@eeyhsong

Copy link
Copy Markdown
Contributor Author

Thanks for your time. 🤝🤝

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Hello @eeyhsong and @martinwimpff,

I apologize for the delay of one week. I added a missing option such as automatic calculation of the last layers fc and nn.LogSoftmax to make sure it will work in the braindecode logic. During this time, I thoroughly examined your model and its transformer layers in comparison to the native ones in PyTorch. Based on my analysis, your model performs better with your current layers compared to the native layers in my testing.

In essence, the native layers converge faster but exhibit a tendency to "overfit" more (though I'm uncertain if this term is accurate). Thus, I recommend against replacing your layers with PyTorch's native layers for now. Maybe in the future with some tests, or during any potential refactoring. Given the considerable effort and time invested in integrating this model (+57 commits), I strongly lean towards maintaining the current integration approach. The consideration of this issue about default layers can be postponed for a future discussion.

Original Layer:
image
image

Native Layer with Xavier Initialization:
image
image

Native Layer without Xavier Initialization:
image
image

My code:

from braindecode.datasets import MOABBDataset

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


from braindecode.preprocessing import (
    exponential_moving_standardize, preprocess, Preprocessor)
from numpy import multiply

low_cut_hz = 4.  # low cut frequency for filtering
high_cut_hz = 38.  # 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)


######################################################################
# Cut Compute Windows
# ~~~~~~~~~~~~~~~~~~~
#
from braindecode.preprocessing import create_windows_from_events

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,
)


######################################################################
# Split dataset into train and valid
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
splitted = windows_dataset.split('session')
train_set = splitted['session_T']
valid_set = splitted['session_E']

import torch
from braindecode.util import set_random_seeds
from braindecode.models import EEGConformer, EEGConformer2

cuda = torch.cuda.is_available()  # check if GPU is available, if True chooses to use it
device = 'cuda' if cuda 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_channels=n_chans,
    n_classes=n_classes,
    final_fc_length=2760,
)

# Send model to GPU
if cuda:
    model.cuda()


######################################################################
# Training
# --------
#


from skorch.callbacks import LRScheduler
from skorch.helper import predefined_split

from braindecode import EEGClassifier
# 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.NLLLoss,
    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)


######################################################################
# Plot Results
# ------------
#


######################################################################
# Now we use the history stored by Skorch throughout training to plot
# accuracy and loss curves.
#

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import pandas as pd

# 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,
                  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')
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()

plt.show()

######################################################################
# Plot Confusion Matrix
# ---------------------
#


#######################################################################
# Generate a confusion matrix as in https://onlinelibrary.wiley.com/doi/full/10.1002/hbm.23730
#


from sklearn.metrics import confusion_matrix
from braindecode.visualization import plot_confusion_matrix

# 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
# label_dict is class_name : str -> i_class : int
label_dict = valid_set.datasets[0].windows.event_id.items()
# sort the labels by values (values are integer class labels)
labels = list(dict(sorted(list(label_dict), key=lambda kv: kv[1])).keys())

# plot the basic conf. matrix
plot_confusion_matrix(confusion_mat, class_names=labels)
plt.show()

Model part:

# Authors: Yonghao Song <[email protected]>
#
# License: BSD (3-clause)

import warnings

import torch
from einops.layers.torch import Rearrange
from torch import nn, Tensor


class EEGConformer2(nn.Module):
    """EEG Conformer.

    Convolutional Transformer for EEG decoding.

    The paper and original code with more details about the methodological
    choices are available at the [Song2022]_ and [ConformerCode]_.

    This neural network architecture recieves a traditional braindecode input.
    The input shape should be three-dimensional matrix representing the EEG
    signals.

         `(batch_size, n_channels, n_timesteps)`.

    The EEG Conformer architecture is composed of three modules:
        - PatchEmbedding
        - TransformerEncoder
        - ClassificationHead

    Notes
    -----
    The authors recommend using data augmentation before using Conformer,
    e.g. sementation and recombination,
    Please refer to the original paper and code for more details.

    The model was initially tuned on 4 seconds of 250 Hz data.
    Please adjust the scale of the temporal convolutional layer,
    and the pooling layer for better performance.

    .. versionadded:: 0.8

    We aggregate the parameters based on the parts of the models, or
    when the parameters were used first, e.g. n_filters_time.

    Parameters
    ----------
    n_classes: int
        Number of classes to predict (number of output filters of last layer).
    n_channels: int
        Number of channels to be used as number of spatial filters.
    n_filters_time: int
        Number of temporal filters, defines also embedding size.
    filter_time_length: int
        Length of the temporal filter.
    pool_time_length: int
        Length of temporal pooling filter.
    pool_time_stride: int
        Length of stride between temporal pooling filters.
    drop_prob: float
        Dropout rate of the convolutional layer.
    att_depth: int
        Number of self-attention layers.
    att_heads: int
        Number of attention heads.
    att_drop_prob: float
        Dropout rate of the self-attention layer.
    final_fc_length: int
        The dimension of the fully connected layer.
    return_features: bool
        If True, the forward method returns the features before the
        last classification layer. Defaults to False.
    References
    ----------
    .. [Song2022] Song, Y., Zheng, Q., Liu, B. and Gao, X., 2022. EEG
       conformer: Convolutional transformer for EEG decoding and visualization.
       IEEE Transactions on Neural Systems and Rehabilitation Engineering,
       31, pp.710-719. https://ieeexplore.ieee.org/document/9991178
    .. [ConformerCode] Song, Y., Zheng, Q., Liu, B. and Gao, X., 2022. EEG
       conformer: Convolutional transformer for EEG decoding and visualization.
       https://github.com/eeyhsong/EEG-Conformer.
    """

    def __init__(
            self,
            n_classes,
            n_channels,
            n_filters_time=40,
            filter_time_length=25,
            pool_time_length=75,
            pool_time_stride=15,
            drop_prob=0.5,
            att_depth=6,
            att_heads=10,
            att_drop_prob=0.5,
            final_fc_length=2440,
            return_features=False
    ):
        super().__init__()
        if not (n_channels <= 64):
            warnings.warn("This model has only been tested on no more " +
                          "than 64 channels. no guarantee to work with " +
                          "more channels.", UserWarning)

        self.patch_embedding = _PatchEmbedding(
            n_filters_time=n_filters_time,
            filter_time_length=filter_time_length,
            n_channels=n_channels,
            pool_time_length=pool_time_length,
            stride_avg_pool=pool_time_stride,
            drop_prob=drop_prob)

        self.transformer = _TransformerEncoder(
            att_depth=att_depth,
            emb_size=n_filters_time,
            att_heads=att_heads,
            att_drop=att_drop_prob)

        self.classification_head = _ClassificationHead(
            final_fc_length=final_fc_length, n_classes=n_classes,
            return_features=return_features)

    def forward(self, x: Tensor) -> Tensor:
        x = torch.unsqueeze(x, dim=1)  # add one extra dimension 64 x 22 x 1125
        print(x.shape)
        x = self.patch_embedding(x)
        print(x.shape)
        x = self.transformer(x)
        print(x.shape)
        x = self.classification_head(x)
        print(x.shape)

        return x


class _PatchEmbedding(nn.Module):
    """Patch Embedding.

    The authors used a convolution module to capture local features,
    instead of position embedding.

    Parameters
    ----------
    n_filters_time: int
        Number of temporal filters, defines also embedding size.
    filter_time_length: int
        Length of the temporal filter.
    n_channels: int
        Number of channels to be used as number of spatial filters.
    pool_time_length: int
        Length of temporal poling filter.
    stride_avg_pool: int
        Length of stride between temporal pooling filters.
    drop_prob: float
        Dropout rate of the convolutional layer.

    Returns
    -------
    x: torch.Tensor
        The output tensor of the patch embedding layer.
    """

    def __init__(
            self,
            n_filters_time,
            filter_time_length,
            n_channels,
            pool_time_length,
            stride_avg_pool,
            drop_prob,
    ):
        super().__init__()

        self.shallownet = nn.Sequential(
            nn.Conv2d(1, n_filters_time,
                      (1, filter_time_length), (1, 1)),
            nn.Conv2d(n_filters_time, n_filters_time,
                      (n_channels, 1), (1, 1)),

            nn.BatchNorm2d(num_features=n_filters_time),
            nn.ELU(),
            nn.AvgPool2d(
                kernel_size=(1, pool_time_length),
                stride=(1, stride_avg_pool)
            ),
            # pooling acts as slicing to obtain 'patch' along the
            # time dimension as in ViT
            nn.Dropout(p=drop_prob),
        )

        self.projection = nn.Sequential(
            nn.Conv2d(
                n_filters_time, n_filters_time, (1, 1), stride=(1, 1)
            ),  # transpose, conv could enhance fiting ability slightly
            Rearrange("b d_model 1 seq -> b seq d_model"),
        )

    def forward(self, x: Tensor) -> Tensor:
        x = self.shallownet(x)
        x = self.projection(x)
        return x


class _TransformerEncoder(nn.Sequential):
    """Transformer encoder module.

    Similar to the layers used in ViT.

    Parameters
    ----------
    att_depth : int
        Number of transformer encoder blocks.
    emb_size : int
        Embedding size of the transformer encoder.
    att_heads : int
        Number of attention heads.
    att_drop : float
        Dropout probability for the attention layers.

    """

    def __init__(self, att_depth, emb_size, att_heads, att_drop,
                 forward_expansion=4):
        super().__init__()
        self.enc_lay = nn.TransformerEncoderLayer(d_model=emb_size,
                                                  nhead=att_heads,
                                                  dim_feedforward=emb_size * forward_expansion,
                                                  dropout=att_drop)
        self.enc = nn.TransformerEncoder(self.enc_lay, num_layers=att_depth)

        nn.init.xavier_uniform_(self.enc_lay.self_attn.in_proj_weight, gain=1)
        nn.init.xavier_uniform_(self.enc_lay.linear1.weight, gain=1)

    def forward(self, x):
        return self.enc(x)


class _ClassificationHead(nn.Module):
    def __init__(self, final_fc_length, n_classes,
                 drop_prob_1=0.5, drop_prob_2=0.3, out_channels=256,
                 hidden_channels=32, return_features=False):
        """"Classification head for the transformer encoder.

        Parameters
        ----------
        final_fc_length : int
            Length of the final fully connected layer.
        n_classes : int
            Number of classes for classification.
        drop_prob_1 : float
            Dropout probability for the first dropout layer.
        drop_prob_2 : float
            Dropout probability for the second dropout layer.
        out_channels : int
            Number of output channels for the first linear layer.
        hidden_channels : int
            Number of output channels for the second linear layer.
        return_features : bool
            Whether to return input features.
        """

        super().__init__()
        self.fc = nn.Sequential(
            nn.Linear(final_fc_length, out_channels),
            nn.ELU(),
            nn.Dropout(drop_prob_1),
            nn.Linear(out_channels, hidden_channels),
            nn.ELU(),
            nn.Dropout(drop_prob_2),
            nn.Linear(hidden_channels, n_classes),
        )
        self.return_features = return_features
        self.classification = nn.LogSoftmax(dim=1)

    def forward(self, x):
        x = x.contiguous().view(x.size(0), -1)
        out = self.fc(x)
        if self.return_features:
            return out, x
        else:
            return self.classification(out)

@bruAristimunha

Copy link
Copy Markdown
Collaborator

@martinwimpff, If you approve your review, the PR will be merge =)

@eeyhsong

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha, you've done a detailed and clear comparison.
I also learned usages for braindecode with your code. I think I will strongly recommend my colleagues to use it.

Thanks again for your effort!

@bruAristimunha
bruAristimunha merged commit 550ce1b into braindecode:master Aug 25, 2023
@eeyhsong
eeyhsong deleted the eeyhsong branch August 25, 2023 09:17
@bruAristimunha

Copy link
Copy Markdown
Collaborator

@eeyhsong

Copy link
Copy Markdown
Contributor Author

Got it, thanks! 🤝🤝

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.

5 participants