SPDTransNet - A Transformer-based structure-preserving model for the analysis of Symmetric Positive Definite matrices
This repository is the official implementation of the SPDTransNet model, as presented in the paper Structure-Preserving Transformers for Sequences of SPD Matrices by Mathieu Seraphim, Alexis Lechervy, Florian Yger, Luc Brun and Olivier Etard - Conference EUSIPCO 2024, France (available on arXiv).
A previous, non-structure-preserving version of this method was presented in the paper
Temporal Sequences of EEG Covariance Matrices for Automated Sleep Stage Scoring with Attention Mechanisms
by Mathieu Seraphim, Paul Dequidt,
Alexis Lechervy, Florian Yger,
Luc Brun and Olivier Etard -
Conference CAIP 2023, Cyprus (official Version on Record here -
Accepted Manuscript here).
Other references can be found in this repository's main paper.
Important: due to space constraints, some specifics were left out of the paper. To selectively read the relevant
sections, please prioritize sections marked with an asterisk, as well as the similarly marked
subsections within them.
A spreadsheet with our model's results (as summarized in the paper) can be found here.
For additional information, feel free to contact us.
The SPDTransNet model
(see figure above) is designed to adapt Transformers
to analyze timeseries of Symmetric Positive Definite (SPD) matrices.
More specifically, it takes as input a sequence of elements, and outputs a classification only for the central element of
the sequence (the surrounding elements providing contextual information).
Each element described as a (potentially multichannel) sequence of SPD matrices (as seen in the figure),
bijectively tokenized
to be processed by the model.
A first intra-element step extracting element-wise features, and a second inter-element step to compare said features. Both steps are based on Transformer encoders, utilizing our SP-MHA auto-attention mechanism described below.
The SP-MHA bloc
generates
The tokens in V only undergo linear combinations weighted by the attention maps, without linear mappings or concatenations. Hence, this auto-attention mechanism does not alter the geometric properties of the inputs, as long as:
- Said inputs may be described in vector form without loss of structural information,
- Linear combinations between these tokens do not cause a loss of structural information.
Both of these are true for our tokenized SPD matrices (cf. paper).
EEG sleep staging refers to the subdivision of a set of concurrent 1D electrophysiological signals (including EEG) into
fixed-length windows called "epochs", which are manually labeled ("scored") with a given sleep stage.
Theoretical justifications for this approach can be found in the paper.
In this repository, we use the data from the Montreal Archive of Sleep Studies' SS3 dataset (MASS-SS3), comprised of 62 healthy subjects and scored using the AASM scoring rules, with 30s epochs and 5 sleep stages: Awake, REM sleep, and the N1, N2 and N3 non-REM sleep stages.
Each epoch is subdivided into 30 1s segments, to capture relevant events of around 1 to 2 seconds in duration. As these events also exhibit distinctive frequential characteristics, we filter the signals to isolate frequency bands.
Our default preprocessing strategy uses 8 EEG signals and 6 distinct frequency bands - giving us, for each epoch,
a timeseries of
| # | Model | MF1 | Macro Acc. | N1 F1 | Valid. metric | Token dim. |
# Feat. Tokens |
|---|---|---|---|---|---|---|---|
| 1 | SPDTransNet, |
81.06 |
84.87 |
60.39 |
MF1 | 351 ( |
7 |
| 2 | SPDTransNet, |
81.24 |
84.40 |
60.50 |
MF1 | 351 ( |
10 |
| 3 | SPDTransNet, |
80.83 |
84.29 |
60.35 |
N1 F1 | 351 ( |
5 |
| 4 | Classic MHA | 80.82 |
84.60 |
60.16 |
MF1 | 351 ( |
10 |
| 5 | DeepSleepNet | 78.14 |
80.05 |
53.52 |
N/A | N/A | N/A |
| 6 | IITNet | 78.48 |
81.88 |
56.01 |
N/A | N/A | N/A |
| 7 | GraphSleepNet | 75.58 |
79.75 |
50.80 |
N/A | N/A | N/A |
| 8 | Dequidt et al. | 81.04 |
82.59 |
58.42 |
N/A | N/A | N/A |
| 9 | Seraphim et al. | 79.78 |
81.76 |
58.43 |
MF1 | Concatenation | 1 |
The reported results for models from the literature differ from those published by the original authors, as we
re-trained their models using our methodology.
A more detailed account of our results can be found here.
More information in the paper.
In this repository, the term "epoch" may be used in two contexts:
- In reference to the model, it corresponds to a training cycle (standard Deep Learning nomenclature).
- In reference to the data, it corresponds to a period of 30s in the input signal, and the features describing it (standard sleep medicine nomenclature).
This implementation has been build with modularity in mind. However, the approach taken is fairly nonstandard:
- Folders are organized starting with an underscore, to keep them in a sorted order - this goes against Python coding conventions (marking them as "protected"), but doesn't impact computations,
- The way classes are instantiated from YAML files (the "Wrapper" classes) is a complete workaround to how the utilized functions were supposed to work.
Consequently, the code remains modular and adaptable, but might be challenging to reuse in another context.
EDIT / IMPORTANT: I recently got contacted by someone who spent way too much time trying to reuse my code in another context. I may have been too subtle in the above sentence, so let me be clear: the structure of this project is an overengineered piece of garbage. It works well enough as a standalone project, but making it compatible with any decent framework would be a nightmare. I beg of you, if you want to reuse my code, please contact me by e-mail using the link at the top of this page. You'll save yourself a world of trouble.
The following instructions should be sufficient to reproduce the results presented in the paper. To expand upon it,
see the further documentation linked below.
Please note that the MASS dataset is only available upon demand.
IMPORTANT: renaming or moving around files runs the risk of breaking absolutely everything.
Besides Python imports, many scripts refer to other repository files through some form of relative pathing,
including the present document.
You have been warned.
This repository was built with PyTorch 1.11 and PyTorch Lightning 1.9.5.
It has been tested with Python versions 3.8.10 and 3.9.12, with the full list of used libraries available
here.
Compatibility with other versions of the presented libraries is not guaranteed.
Due to the way Python imports are managed, almost all Python scripts must be ran from the repository root.
The only exceptions are scripts that do not import anything from other repository files.
.sh scripts can be ran from any directory, but must be ran with Bash.
IMPORTANT: this repository does not currently work with versions 2.x and above of PyTorch or PyTorch Lightning!
IMPORTANT: if you are running everything locally, you may ignore this section and any subsequent reference to Slurm.
This repository was built for mono-GPU usage on a remote server managed using Slurm.
Example Slurm scripts (with the .sl extension) can be found in the slurm_scripts subfolder
of the 6_3_slurm_execution folder.
Unless you are using the French Jean Zay supercomputer, you will have to modify the Slurm scripts before execution.
Should you wish to run the .sl Slurm scripts directly, follow these instructions:
- Unless you are using Slurm 23.02 or above, make sure that a
[ROOT]/logfolder exists. If not, create one. - Run the scripts using the
sbatchcommand, either from the repository root or by using the option--chdir=[ROOT].
Alternatively, you can use the provided .sh Bash files, which you can run from anywhere, doing one of the following:
- Run the
_bash_run_any_slurm_script.shscript, with the relevant Slurm script's file basename as argument (i.e.bash [PATH TO _6_3_slurm_execution]/_bash_run_any_slurm_script.sh [SLURM SCRIPT BASENAME].sl). - Directly run the Bash script associated with the wanted script, i.e. one of the other
.shfiles here.
This will generate the aforementioned [ROOT]/log folder.
For the rest of this documentation, the link associated with a given "Slurm script" will point to its associated Bash script.
IMPORTANT: do not delete the [ROOT]/log folder until all Slurm jobs have completed!
- Move the MASS SS3 dataset folder into the
_2_1_original_datasetsdirectory. It should be namedMASS_SS3, and contain all* Base.edfand* PSG.edffiles for all 62 subjects - numbered from01-03-0001to01-03-0064. Subjects 43 and 49 should be missing; that is normal. - Directly run the
MASS_extraction.pyPython script, or the corresponding Slurm script. This should generate theMASS_SS3_extractedfolder in the appropriate location, containing 62.pklfiles. - Directly run the
SPDFromEEGPreprocessor.pyPython script, or the corresponding Slurm script. This should generate the_2_4_preprocessed_datadirectory (if it doesn't exist), as well as theMASS_SS3_dataset_with_EUSIPCO_signals_configfolder folder therein. This folder contains a.pklfile for every epoch in the dataset (59317 in total).
- Run the model for training using the appropriate BASH script
31 times sequentially, e.g. through the command
bash bash_one_run_full_spd_best_mf1_length_21.sh [X], substituting[X]with every integer from 0 to 30; or run the corresponding Slurm script once. This should generate thelightning_logsfolder at the project root, as well as a log folder within calledversion_[X]. This will also create a folder calledtmp_vectorized_data(if it doesn't already exist), as well as.zipfiles that will be automatically deleted if the run terminates without error. - When all training runs have ended, the
tmp_vectorized_datafolder may be safely deleted. - Directly run the
command_line_tester.pyPython script, or the corresponding Slurm script. - This should generate the
test_logsfolder at the project root, which may safely be deleted after the program ends. Same thing fortmp_vectorized_data, which should be re-generated as before. - The
outputfolder should be generated within the_5_1_runs_analysisdirectory. It should contain theruns_analysis.csvfile, containing the computed metrics on all folds and corresponding hyperparameters, as well as theconfusion_matricesfolder, containing.pngimages of confusion matrices on the test set. To prevent any overrides, be sure to rename or move these elements before re-attempting step 3.
IMPORTANT: do not run the model training on a fold for which a folder exists in lightning_logs, as this will
combine both logs and lead to issues down the line. If you want to keep both log folders, rename the first one or remove
it from lightning_logs.
This is similar to the above instructions, with the following changes:
- Before step 1, generate the
[ROOT]/db/database.dbfile necessary for the hyperparameter research by running the appropriate BASH script (for local execution or on a Slurm server). - In step 1, run the hyperparameter research Slurm script, or a local equivalent (not provided here). This should run a total of 50 runs oo fold 11, with a maximum of 5 running at any moment.
- Once the search is finished, substitute contents of the current
hyperparameters configuration file
with the contents of the file
[ROOT]/lightning_logs/version_[X}/hparams.yaml, with[X]the index of the run yielding the highest validation MF1, as seen inruns_analysis.csv. Be sure to set the hyperparametersave_in_single_filetotrue. - Repeat the steps in the section above.
IMPORTANT: unlike in the above section, temporary data is stored in separate files within the tmp_vectorized_data
folder during hyperparameter research, as opposed to a single .zip files. This is way faster, but generates large
amounts of files (more than 50000 per simultaneous run). This behavior is controlled by the save_in_single_file
hyperparameter mentioned above.
As files systems usually have a limit to the amount of files allowed to exist at one given time, this behavior can be
a limiting factor in terms of amount of simultaneous runs possible.
If this aspect causes issues, please refer to the relevant documentation.
To further understand our approach and/or expand upon it, please refer to the following documentation files:
- Implemented Configuration Strategy - an overview of our configuration files, and how to make your own.
- From Signals To SPD Matrices To Tokens* - the various steps underwent to transform our data from 1D signals to multichannel sequences of SPD matrices.
- Formatting The Model Inputs - data rebalancing and trimming, batch formation and temporary storage strategies.
- The SPDTransNet Model* - the modular implementation of the model's various components.
- Running The Model - instructions on execution customization and hyperparameter researches.
The first author is supported by the French National Research Agency (ANR) and Region Normandie under grant HAISCoDe.
This work was granted access to the HPC resources of IDRIS under the allocation 2022-AD010613618 made by GENCI, and
to the computing resources of CRIANN (Normandy, France).
