braindecode 1.3.0.dev180329405__py3-none-any.whl → 1.3.0.dev182330353__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braindecode/augmentation/base.py +1 -1
- braindecode/datasets/__init__.py +12 -4
- braindecode/datasets/base.py +115 -151
- braindecode/datasets/bcicomp.py +4 -4
- braindecode/datasets/bids.py +3 -3
- braindecode/datasets/experimental.py +2 -2
- braindecode/datasets/mne.py +3 -5
- braindecode/datasets/moabb.py +17 -7
- braindecode/datasets/nmt.py +2 -2
- braindecode/datasets/sleep_physio_challe_18.py +2 -2
- braindecode/datasets/sleep_physionet.py +2 -2
- braindecode/datasets/tuh.py +2 -2
- braindecode/datasets/xy.py +2 -2
- braindecode/datautil/__init__.py +11 -1
- braindecode/datautil/channel_utils.py +114 -0
- braindecode/datautil/serialization.py +7 -7
- braindecode/functional/functions.py +6 -2
- braindecode/functional/initialization.py +2 -3
- braindecode/models/__init__.py +6 -0
- braindecode/models/atcnet.py +26 -27
- braindecode/models/attentionbasenet.py +37 -32
- braindecode/models/attn_sleep.py +2 -0
- braindecode/models/base.py +280 -2
- braindecode/models/bendr.py +469 -0
- braindecode/models/biot.py +2 -0
- braindecode/models/contrawr.py +2 -0
- braindecode/models/ctnet.py +8 -3
- braindecode/models/deepsleepnet.py +28 -19
- braindecode/models/eegconformer.py +2 -2
- braindecode/models/eeginception_erp.py +31 -25
- braindecode/models/eegitnet.py +2 -0
- braindecode/models/eegminer.py +2 -0
- braindecode/models/eegnet.py +1 -1
- braindecode/models/eegsym.py +917 -0
- braindecode/models/eegtcnet.py +2 -0
- braindecode/models/fbcnet.py +5 -1
- braindecode/models/fblightconvnet.py +2 -0
- braindecode/models/fbmsnet.py +20 -6
- braindecode/models/ifnet.py +2 -0
- braindecode/models/labram.py +33 -26
- braindecode/models/medformer.py +758 -0
- braindecode/models/msvtnet.py +2 -0
- braindecode/models/patchedtransformer.py +1 -1
- braindecode/models/signal_jepa.py +111 -27
- braindecode/models/sinc_shallow.py +12 -9
- braindecode/models/sstdpn.py +11 -11
- braindecode/models/summary.csv +3 -0
- braindecode/models/syncnet.py +2 -0
- braindecode/models/tcn.py +2 -0
- braindecode/models/usleep.py +26 -21
- braindecode/models/util.py +3 -0
- braindecode/modules/attention.py +10 -10
- braindecode/modules/blocks.py +3 -3
- braindecode/modules/filter.py +2 -9
- braindecode/modules/layers.py +18 -17
- braindecode/preprocessing/__init__.py +232 -3
- braindecode/preprocessing/eegprep_preprocess.py +1202 -0
- braindecode/preprocessing/mne_preprocess.py +142 -10
- braindecode/preprocessing/preprocess.py +28 -18
- braindecode/preprocessing/util.py +166 -0
- braindecode/preprocessing/windowers.py +26 -20
- braindecode/samplers/base.py +8 -8
- braindecode/version.py +1 -1
- {braindecode-1.3.0.dev180329405.dist-info → braindecode-1.3.0.dev182330353.dist-info}/METADATA +6 -2
- braindecode-1.3.0.dev182330353.dist-info/RECORD +109 -0
- braindecode-1.3.0.dev180329405.dist-info/RECORD +0 -103
- {braindecode-1.3.0.dev180329405.dist-info → braindecode-1.3.0.dev182330353.dist-info}/WHEEL +0 -0
- {braindecode-1.3.0.dev180329405.dist-info → braindecode-1.3.0.dev182330353.dist-info}/licenses/LICENSE.txt +0 -0
- {braindecode-1.3.0.dev180329405.dist-info → braindecode-1.3.0.dev182330353.dist-info}/licenses/NOTICE.txt +0 -0
- {braindecode-1.3.0.dev180329405.dist-info → braindecode-1.3.0.dev182330353.dist-info}/top_level.txt +0 -0
braindecode/models/base.py
CHANGED
|
@@ -5,15 +5,35 @@
|
|
|
5
5
|
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
|
+
import json
|
|
8
9
|
import warnings
|
|
9
10
|
from collections import OrderedDict
|
|
10
|
-
from
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Dict, Iterable, Optional, Type, Union
|
|
11
13
|
|
|
12
14
|
import numpy as np
|
|
13
15
|
import torch
|
|
14
16
|
from docstring_inheritance import NumpyDocstringInheritanceInitMeta
|
|
17
|
+
from mne.utils import _soft_import
|
|
15
18
|
from torchinfo import ModelStatistics, summary
|
|
16
19
|
|
|
20
|
+
from braindecode.version import __version__
|
|
21
|
+
|
|
22
|
+
huggingface_hub = _soft_import(
|
|
23
|
+
"huggingface_hub", "Hugging Face Hub integration", strict=False
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
HAS_HF_HUB = huggingface_hub is not False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _BaseHubMixin:
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Define base class for hub mixin
|
|
34
|
+
if HAS_HF_HUB:
|
|
35
|
+
_BaseHubMixin: Type = huggingface_hub.PyTorchModelHubMixin # type: ignore
|
|
36
|
+
|
|
17
37
|
|
|
18
38
|
def deprecated_args(obj, *old_new_args):
|
|
19
39
|
out_args = []
|
|
@@ -32,10 +52,14 @@ def deprecated_args(obj, *old_new_args):
|
|
|
32
52
|
return out_args
|
|
33
53
|
|
|
34
54
|
|
|
35
|
-
class EEGModuleMixin(metaclass=NumpyDocstringInheritanceInitMeta):
|
|
55
|
+
class EEGModuleMixin(_BaseHubMixin, metaclass=NumpyDocstringInheritanceInitMeta):
|
|
36
56
|
"""
|
|
37
57
|
Mixin class for all EEG models in braindecode.
|
|
38
58
|
|
|
59
|
+
This class integrates with Hugging Face Hub when the ``huggingface_hub`` package
|
|
60
|
+
is installed, enabling models to be pushed to and loaded from the Hub using
|
|
61
|
+
:func:`push_to_hub()` and :func:`from_pretrained()` methods.
|
|
62
|
+
|
|
39
63
|
Parameters
|
|
40
64
|
----------
|
|
41
65
|
n_outputs : int
|
|
@@ -62,8 +86,87 @@ class EEGModuleMixin(metaclass=NumpyDocstringInheritanceInitMeta):
|
|
|
62
86
|
-----
|
|
63
87
|
If some input signal-related parameters are not specified,
|
|
64
88
|
there will be an attempt to infer them from the other parameters.
|
|
89
|
+
|
|
90
|
+
.. rubric:: Hugging Face Hub integration
|
|
91
|
+
|
|
92
|
+
When the optional ``huggingface_hub`` package is installed, all models
|
|
93
|
+
automatically gain the ability to be pushed to and loaded from the
|
|
94
|
+
Hugging Face Hub. Install with::
|
|
95
|
+
|
|
96
|
+
pip install braindecode[hug]
|
|
97
|
+
|
|
98
|
+
**Pushing a model to the Hub:**
|
|
99
|
+
|
|
100
|
+
.. code-block:: python
|
|
101
|
+
|
|
102
|
+
from braindecode.models import EEGNetv4
|
|
103
|
+
|
|
104
|
+
# Train your model
|
|
105
|
+
model = EEGNetv4(n_chans=22, n_outputs=4, n_times=1000)
|
|
106
|
+
# ... training code ...
|
|
107
|
+
|
|
108
|
+
# Push to the Hub
|
|
109
|
+
model.push_to_hub(
|
|
110
|
+
repo_id="username/my-eegnet-model", commit_message="Initial model upload"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
**Loading a model from the Hub:**
|
|
114
|
+
|
|
115
|
+
.. code-block:: python
|
|
116
|
+
|
|
117
|
+
from braindecode.models import EEGNetv4
|
|
118
|
+
|
|
119
|
+
# Load pretrained model
|
|
120
|
+
model = EEGNetv4.from_pretrained("username/my-eegnet-model")
|
|
121
|
+
|
|
122
|
+
The integration automatically handles EEG-specific parameters (n_chans,
|
|
123
|
+
n_times, sfreq, chs_info, etc.) by saving them in a config file alongside
|
|
124
|
+
the model weights. This ensures that loaded models are correctly configured
|
|
125
|
+
for their original data specifications.
|
|
126
|
+
|
|
127
|
+
.. important::
|
|
128
|
+
Currently, only EEG-specific parameters (n_outputs, n_chans, n_times,
|
|
129
|
+
input_window_seconds, sfreq, chs_info) are saved to the Hub. Model-specific
|
|
130
|
+
parameters (e.g., dropout rates, activation functions, number of filters)
|
|
131
|
+
are not preserved and will use their default values when loading from the Hub.
|
|
132
|
+
|
|
133
|
+
To use non-default model parameters, specify them explicitly when calling
|
|
134
|
+
:func:`from_pretrained()`::
|
|
135
|
+
|
|
136
|
+
model = EEGNet.from_pretrained("user/model", dropout=0.3, activation='relu')
|
|
137
|
+
|
|
138
|
+
Full parameter serialization will be addressed in a future update.
|
|
65
139
|
"""
|
|
66
140
|
|
|
141
|
+
def __init_subclass__(cls, **kwargs):
|
|
142
|
+
if not HAS_HF_HUB:
|
|
143
|
+
super().__init_subclass__(**kwargs)
|
|
144
|
+
return
|
|
145
|
+
|
|
146
|
+
base_tags = ["braindecode", cls.__name__]
|
|
147
|
+
user_tags = kwargs.pop("tags", None)
|
|
148
|
+
tags = list(user_tags) if user_tags is not None else []
|
|
149
|
+
for tag in base_tags:
|
|
150
|
+
if tag not in tags:
|
|
151
|
+
tags.append(tag)
|
|
152
|
+
|
|
153
|
+
docs_url = kwargs.pop(
|
|
154
|
+
"docs_url",
|
|
155
|
+
f"https://braindecode.org/stable/generated/braindecode.models.{cls.__name__}.html",
|
|
156
|
+
)
|
|
157
|
+
repo_url = kwargs.pop("repo_url", "https://braindecode.org")
|
|
158
|
+
library_name = kwargs.pop("library_name", "braindecode")
|
|
159
|
+
license = kwargs.pop("license", "bsd-3-clause")
|
|
160
|
+
# TODO: model_card_template can be added in the future for custom model cards
|
|
161
|
+
super().__init_subclass__(
|
|
162
|
+
tags=tags,
|
|
163
|
+
docs_url=docs_url,
|
|
164
|
+
repo_url=repo_url,
|
|
165
|
+
library_name=library_name,
|
|
166
|
+
license=license,
|
|
167
|
+
**kwargs,
|
|
168
|
+
)
|
|
169
|
+
|
|
67
170
|
def __init__(
|
|
68
171
|
self,
|
|
69
172
|
n_outputs: Optional[int] = None, # type: ignore[assignment]
|
|
@@ -73,6 +176,16 @@ class EEGModuleMixin(metaclass=NumpyDocstringInheritanceInitMeta):
|
|
|
73
176
|
input_window_seconds: Optional[float] = None, # type: ignore[assignment]
|
|
74
177
|
sfreq: Optional[float] = None, # type: ignore[assignment]
|
|
75
178
|
):
|
|
179
|
+
# Deserialize chs_info if it comes as a list of dicts (from Hub)
|
|
180
|
+
if chs_info is not None and isinstance(chs_info, list):
|
|
181
|
+
if len(chs_info) > 0 and isinstance(chs_info[0], dict):
|
|
182
|
+
# Check if it needs deserialization (has 'loc' as list)
|
|
183
|
+
if "loc" in chs_info[0] and isinstance(chs_info[0]["loc"], list):
|
|
184
|
+
chs_info = self._deserialize_chs_info(chs_info)
|
|
185
|
+
warnings.warn(
|
|
186
|
+
"Modifying chs_info argument using the _deserialize_chs_info() method"
|
|
187
|
+
)
|
|
188
|
+
|
|
76
189
|
if n_chans is not None and chs_info is not None and len(chs_info) != n_chans:
|
|
77
190
|
raise ValueError(f"{n_chans=} different from {chs_info=} length")
|
|
78
191
|
if (
|
|
@@ -294,3 +407,168 @@ class EEGModuleMixin(metaclass=NumpyDocstringInheritanceInitMeta):
|
|
|
294
407
|
|
|
295
408
|
def __str__(self) -> str:
|
|
296
409
|
return str(self.get_torchinfo_statistics())
|
|
410
|
+
|
|
411
|
+
@staticmethod
|
|
412
|
+
def _serialize_chs_info(chs_info):
|
|
413
|
+
"""
|
|
414
|
+
Serialize MNE channel info to JSON-compatible format.
|
|
415
|
+
|
|
416
|
+
Parameters
|
|
417
|
+
----------
|
|
418
|
+
chs_info : list of dict or None
|
|
419
|
+
Channel information from MNE Info object.
|
|
420
|
+
|
|
421
|
+
Returns
|
|
422
|
+
-------
|
|
423
|
+
list of dict or None
|
|
424
|
+
Serialized channel information that can be saved to JSON.
|
|
425
|
+
"""
|
|
426
|
+
if chs_info is None:
|
|
427
|
+
return None
|
|
428
|
+
|
|
429
|
+
serialized = []
|
|
430
|
+
for ch in chs_info:
|
|
431
|
+
# Extract serializable fields from MNE channel info
|
|
432
|
+
ch_dict = {
|
|
433
|
+
"ch_name": ch.get("ch_name", ""),
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
# Handle kind field - can be either string or integer
|
|
437
|
+
kind_val = ch.get("kind")
|
|
438
|
+
if kind_val is not None:
|
|
439
|
+
ch_dict["kind"] = (
|
|
440
|
+
kind_val if isinstance(kind_val, str) else int(kind_val)
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
# Add numeric fields with safe conversion
|
|
444
|
+
coil_type = ch.get("coil_type")
|
|
445
|
+
if coil_type is not None:
|
|
446
|
+
ch_dict["coil_type"] = int(coil_type)
|
|
447
|
+
|
|
448
|
+
unit = ch.get("unit")
|
|
449
|
+
if unit is not None:
|
|
450
|
+
ch_dict["unit"] = int(unit)
|
|
451
|
+
|
|
452
|
+
cal = ch.get("cal")
|
|
453
|
+
if cal is not None:
|
|
454
|
+
ch_dict["cal"] = float(cal)
|
|
455
|
+
|
|
456
|
+
range_val = ch.get("range")
|
|
457
|
+
if range_val is not None:
|
|
458
|
+
ch_dict["range"] = float(range_val)
|
|
459
|
+
|
|
460
|
+
# Serialize location array if present
|
|
461
|
+
if "loc" in ch and ch["loc"] is not None:
|
|
462
|
+
ch_dict["loc"] = (
|
|
463
|
+
ch["loc"].tolist()
|
|
464
|
+
if hasattr(ch["loc"], "tolist")
|
|
465
|
+
else list(ch["loc"])
|
|
466
|
+
)
|
|
467
|
+
serialized.append(ch_dict)
|
|
468
|
+
|
|
469
|
+
return serialized
|
|
470
|
+
|
|
471
|
+
@staticmethod
|
|
472
|
+
def _deserialize_chs_info(chs_info_dict):
|
|
473
|
+
"""
|
|
474
|
+
Deserialize channel info from JSON-compatible format to MNE-like structure.
|
|
475
|
+
|
|
476
|
+
Parameters
|
|
477
|
+
----------
|
|
478
|
+
chs_info_dict : list of dict or None
|
|
479
|
+
Serialized channel information.
|
|
480
|
+
|
|
481
|
+
Returns
|
|
482
|
+
-------
|
|
483
|
+
list of dict or None
|
|
484
|
+
Deserialized channel information compatible with MNE.
|
|
485
|
+
"""
|
|
486
|
+
if chs_info_dict is None:
|
|
487
|
+
return None
|
|
488
|
+
|
|
489
|
+
deserialized = []
|
|
490
|
+
for ch_dict in chs_info_dict:
|
|
491
|
+
ch = ch_dict.copy()
|
|
492
|
+
# Convert location back to numpy array if present
|
|
493
|
+
if "loc" in ch and ch["loc"] is not None:
|
|
494
|
+
ch["loc"] = np.array(ch["loc"])
|
|
495
|
+
deserialized.append(ch)
|
|
496
|
+
|
|
497
|
+
return deserialized
|
|
498
|
+
|
|
499
|
+
def _save_pretrained(self, save_directory):
|
|
500
|
+
"""
|
|
501
|
+
Save model configuration and weights to the Hub.
|
|
502
|
+
|
|
503
|
+
This method is called by PyTorchModelHubMixin.push_to_hub() to save
|
|
504
|
+
model-specific configuration alongside the model weights.
|
|
505
|
+
|
|
506
|
+
Parameters
|
|
507
|
+
----------
|
|
508
|
+
save_directory : str or Path
|
|
509
|
+
Directory where the configuration should be saved.
|
|
510
|
+
"""
|
|
511
|
+
if not HAS_HF_HUB:
|
|
512
|
+
return
|
|
513
|
+
|
|
514
|
+
save_directory = Path(save_directory)
|
|
515
|
+
|
|
516
|
+
# Collect EEG-specific configuration
|
|
517
|
+
config = {
|
|
518
|
+
"n_outputs": self._n_outputs,
|
|
519
|
+
"n_chans": self._n_chans,
|
|
520
|
+
"n_times": self._n_times,
|
|
521
|
+
"input_window_seconds": self._input_window_seconds,
|
|
522
|
+
"sfreq": self._sfreq,
|
|
523
|
+
"chs_info": self._serialize_chs_info(self._chs_info),
|
|
524
|
+
"braindecode_version": __version__,
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
# Save to config.json
|
|
528
|
+
config_path = save_directory / "config.json"
|
|
529
|
+
with open(config_path, "w") as f:
|
|
530
|
+
json.dump(config, f, indent=2)
|
|
531
|
+
|
|
532
|
+
# Save model weights with standard Hub filename
|
|
533
|
+
weights_path = save_directory / "pytorch_model.bin"
|
|
534
|
+
torch.save(self.state_dict(), weights_path)
|
|
535
|
+
|
|
536
|
+
# Also save in safetensors format using parent's implementation
|
|
537
|
+
try:
|
|
538
|
+
super()._save_pretrained(save_directory)
|
|
539
|
+
except (ImportError, RuntimeError) as e:
|
|
540
|
+
# Fallback to pytorch_model.bin if safetensors saving fails
|
|
541
|
+
warnings.warn(
|
|
542
|
+
f"Could not save model in safetensors format: {e}. "
|
|
543
|
+
"Model weights saved in pytorch_model.bin instead.",
|
|
544
|
+
stacklevel=2,
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
if HAS_HF_HUB:
|
|
548
|
+
|
|
549
|
+
@classmethod
|
|
550
|
+
def _from_pretrained(
|
|
551
|
+
cls,
|
|
552
|
+
*,
|
|
553
|
+
model_id: str,
|
|
554
|
+
revision: Optional[str],
|
|
555
|
+
cache_dir: Optional[Union[str, Path]],
|
|
556
|
+
force_download: bool,
|
|
557
|
+
local_files_only: bool,
|
|
558
|
+
token: Union[str, bool, None],
|
|
559
|
+
map_location: str = "cpu",
|
|
560
|
+
strict: bool = False,
|
|
561
|
+
**model_kwargs,
|
|
562
|
+
):
|
|
563
|
+
model_kwargs.pop("braindecode_version", None)
|
|
564
|
+
return super()._from_pretrained( # type: ignore
|
|
565
|
+
model_id=model_id,
|
|
566
|
+
revision=revision,
|
|
567
|
+
cache_dir=cache_dir,
|
|
568
|
+
force_download=force_download,
|
|
569
|
+
local_files_only=local_files_only,
|
|
570
|
+
token=token,
|
|
571
|
+
map_location=map_location,
|
|
572
|
+
strict=strict,
|
|
573
|
+
**model_kwargs,
|
|
574
|
+
)
|