Repository navigation
ENH record foundation-model pretraining corpora and add check_pretraining_overlap (#1492) - #1493
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1493 +/- ##
==========================================
+ Coverage 91.19% 91.21% +0.02%
==========================================
Files 168 169 +1
Lines 21862 21940 +78
==========================================
+ Hits 19937 20013 +76
- Misses 1925 1927 +2 🚀 New features to boost your workflow:
|
…foundation model Shows check_pretraining_overlap on one model/dataset pair, explains the four return values and the complete=False caveat, prints an overlap table for the recorded models against common benchmarks, and lists practical options for reporting results.
|
Added a short tutorial, |
cda277a to
2adb5fc
Compare
There was a problem hiding this comment.
I am not a fan of listing this...
Seems like a bad idea, because it will not scale up well...
| PRETRAINING_CORPORA = { | ||
| "BENDR": PretrainingCorpus( | ||
| frozenset({"TUEG"}), "Kostas et al. 2021, arXiv:2101.12037" | ||
| ), | ||
| "BIOT": PretrainingCorpus( | ||
| frozenset({"SHHS", "PREST"}), "Yang et al. 2023, arXiv:2305.10351" | ||
| ), | ||
| "Labram": PretrainingCorpus( | ||
| frozenset( | ||
| { | ||
| "BCIC-IV-1", | ||
| "Emobrain", | ||
| "GAL", | ||
| "KaggleERN", | ||
| "EEGMMIDB", | ||
| "Trujillo2020", | ||
| "Trujillo2017", | ||
| "SEED", | ||
| "SEED-IV", | ||
| "SEED-GER", | ||
| "SEED-FRA", |
There was a problem hiding this comment.
This should be in the model card on Hugging Face, and maybe we need to find a better way to show this once you load the pre-trained.... Can you please dig a little more to see how other libraries around Hugging Face handle this?
|
Thanks for the review, Bruno. I agree the Python registry does not scale, and I looked at how the libraries around the Hub handle this. What I found:
So yes, this is mostly about evolving the model cards. Proposal, in three small steps, replacing this PR:
One side note: the 2026 challenge rules ask participants to declare every external corpus they pretrained on. A If this direction works for you, I will close this PR and open the metadata PR first. |
|
Thanks @YihengLi-1, the problem is real and your audit is very useful. I looked at how this is done on the Hugging Face side, and I think we can get the same result with much less code and without a table to maintain in braindecode. What HF already gives us
Why per checkpoint and not per class BIOT shows the problem. We host three BIOT checkpoints, each trained on different data (BIOT README):
A class-level Proposal I have a small patch ready (about 30 lines of code in
With that in place, the overlap check is one line, Would you be ok to repurpose the PR this way? Concretely:
Patch (models/base.py + tests)diff --git a/braindecode/models/base.py b/braindecode/models/base.py
index ce3efec2..ec26a8d1 100644
--- a/braindecode/models/base.py
+++ b/braindecode/models/base.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import functools
import inspect
import json
+import logging
import warnings
from collections import OrderedDict
from pathlib import Path, PurePosixPath, PureWindowsPath
@@ -35,6 +36,7 @@ huggingface_hub = _soft_import(
)
HAS_HF_HUB = huggingface_hub is not False
+log = logging.getLogger(__name__)
# __init__ args that from_pretrained fills from config.json when not given.
_GEOMETRY_KWARGS = (
@@ -61,6 +63,26 @@ def _validate_weights_filename(filename):
raise ValueError("filename must be a relative weight path without traversal")
+def _load_card_data(pretrained_model_name_or_path, **kwargs):
+ """Metadata of a checkpoint's model card (``README.md``), or None.
+
+ Best effort: the card is informational, so a missing or unreadable card
+ (offline, no README, bad YAML) never blocks loading the weights.
+ """
+ keys = ("revision", "cache_dir", "force_download", "token", "local_files_only")
+ try:
+ card = Path(pretrained_model_name_or_path) / "README.md"
+ if not card.parent.is_dir():
+ card = huggingface_hub.hf_hub_download(
+ str(pretrained_model_name_or_path),
+ "README.md",
+ **{k: kwargs[k] for k in keys if k in kwargs},
+ )
+ return huggingface_hub.ModelCard.load(card, ignore_metadata_errors=True).data
+ except Exception:
+ return None
+
+
def _local_weights_path(model_id, filename):
"""Reject local weight paths (including symlinks) outside the model folder."""
root = Path(model_id).resolve()
@@ -212,6 +234,11 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
there will be an attempt to infer them from the other parameters.
"""
+ #: Hub model card metadata (:class:`huggingface_hub.ModelCardData`) of the
+ #: checkpoint, set by :meth:`from_pretrained` when the card can be read,
+ #: e.g. ``model.card_data.datasets`` lists the data the weights saw.
+ card_data = None
+
#: Template for model-specific Hub integration notes appended by
#: ``__init_subclass__``. ``{name}`` is replaced with the concrete
#: model class name.
@@ -234,10 +261,11 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
model = {name}(n_chans=22, n_outputs=4, n_times=1000)
# ... training code ...
- # Push to the Hub
+ # Push to the Hub; ``datasets`` and ``base_model`` go to the card
model.push_to_hub(
repo_id="username/my-{name_lower}-model",
commit_message="Initial model upload",
+ model_card_kwargs={{"datasets": ["BNCI2014_001"]}},
)
**Loading a model from the Hub:**
@@ -248,6 +276,8 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
# Load pretrained model
model = {name}.from_pretrained("username/my-{name_lower}-model")
+ # Data the weights were trained on, from the Hub model card
+ print(model.card_data.datasets if model.card_data else None)
# Load with a different number of outputs (head is rebuilt automatically)
model = {name}.from_pretrained("username/my-{name_lower}-model", n_outputs=4)
@@ -1015,7 +1045,26 @@ class EEGModuleMixin(_BaseHubMixin, metaclass=_BraindecodeDocstringMeta):
kwargs.setdefault("chs_info", None)
if "n_times" in kwargs or "sfreq" in kwargs:
kwargs.setdefault("input_window_seconds", None)
- return super().from_pretrained(*args, **kwargs)
+ model = super().from_pretrained(*args, **kwargs)
+ card_data = _load_card_data(*args, **kwargs)
+ if card_data is not None:
+ model.card_data = card_data
+ if card_data.datasets:
+ log.info(
+ "%s weights were trained on (model card): %s",
+ cls.__name__,
+ card_data.datasets,
+ )
+ return model
+
+ def generate_model_card(self, *args, **kwargs):
+ # ``model_card_kwargs`` only fill the card's Jinja template; also
+ # write these two to its YAML header so the Hub indexes them.
+ card = super().generate_model_card(*args, **kwargs)
+ for key in ("datasets", "base_model"):
+ if key in kwargs:
+ setattr(card.data, key, kwargs[key])
+ return card
@classmethod
def _from_pretrained(
diff --git a/test/unit_tests/models/test_huggingface.py b/test/unit_tests/models/test_huggingface.py
index ef09a6c9..8744d213 100644
--- a/test/unit_tests/models/test_huggingface.py
+++ b/test/unit_tests/models/test_huggingface.py
@@ -593,3 +593,43 @@ def test_custom_weights_legacy_options_do_not_reach_constructor(tmp_path, monkey
assert calls[-1]["resume_download"] is True
for key, value in model.state_dict().items():
torch.testing.assert_close(restored.state_dict()[key], value, rtol=0, atol=0)
+
+
+def test_model_card_datasets_roundtrip(tmp_path):
+ from .test_base import DummyModuleConfigRoundTrip
+
+ model = DummyModuleConfigRoundTrip(n_chans=2, n_times=8, n_outputs=2)
+ card = {"datasets": ["TUEG", "Siena"], "base_model": "org/parent"}
+ model.save_pretrained(tmp_path / "a", model_card_kwargs=card)
+ model.save_pretrained(tmp_path / "b") # card kwargs must not leak
+
+ restored = DummyModuleConfigRoundTrip.from_pretrained(tmp_path / "a")
+ assert restored.card_data.datasets == ["TUEG", "Siena"]
+ assert restored.card_data.base_model == "org/parent"
+ assert "braindecode" in restored.card_data.tags
+ assert DummyModuleConfigRoundTrip.from_pretrained(tmp_path / "b").card_data.datasets is None
+
+ (tmp_path / "a" / "README.md").unlink() # no card: still loads
+ assert DummyModuleConfigRoundTrip.from_pretrained(tmp_path / "a").card_data is None
+
+
+def test_model_card_read_from_hub_cache_without_network(tmp_path, monkeypatch):
+ import huggingface_hub
+
+ from braindecode.models.base import _load_card_data
+
+ readme = tmp_path / "README.md"
+ readme.write_text("---\ndatasets:\n- PREST\n- SHHS\n---\ncard\n")
+ calls = []
+
+ def download(*args, **kwargs):
+ calls.append((args, kwargs))
+ return str(readme)
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)
+ data = _load_card_data("org/repo", revision="v1", local_files_only=True, n_outputs=3)
+ assert data.datasets == ["PREST", "SHHS"]
+ assert calls == [(("org/repo", "README.md"), {"revision": "v1", "local_files_only": True})]
+
+ monkeypatch.undo() # real hub, nothing cached, no network: None, no error
+ assert _load_card_data("braindecode/no-such-repo", cache_dir=tmp_path / "c", local_files_only=True) is None |
|
And we have almost all the dataset at hugging face eegdash org, that try to be the dataset part of braindecode |
Replace the Python registry (braindecode/models/pretraining.py) with the Hugging Face convention: from_pretrained reads the checkpoint's README.md and exposes it as model.card_data, and save_pretrained/push_to_hub write datasets and base_model from model_card_kwargs to the card's YAML header. The tutorial now shows the round trip and the one-line overlap check. Co-authored-by: Bruno Aristimunha <[email protected]>
|
Yes, let's do it this way. Pushed to the branch (9aa1bae): On names, agreed: the Hub id where one exists ( Batch 1 of the per-checkpoint lists, for the checkpoints the audit already covers (sources and page quotes are in the table linked above):
Batch 2 (SignalJEPA, STEEGFormer, Brant, MVPFormer, BrainBERT, PoPT, SleepFM, ZUNA, MIREPNet, BaRISTA, DIVER-1, BrainTokenizer, MAPA, NeuroRVQ, DuIN, EpInT, the EMG models, EEGSym) is in progress. I'll post it here in the same format in a few days, each row tied to the variant the card says it is. Once you've checked the names I can turn the lists into a |
|
Batch 2, the remaining
Two cross-cutting points for the card text rather than the field: (1) BrainTreebank is the pretraining corpus of BrainBERT, PoPT, BaRISTA and MAPA and also the usual iEEG benchmark (Neuroprobe), so every published number for those checkpoints is same-subject, different-session; (2) three models (ZUNA, STEEGFormer, DIVER-1) cannot be fully declared because the authors did not itemise, which is exactly the case where If this looks right I will update the audit JSON with these rows and prepare the |
bruAristimunha
left a comment
There was a problem hiding this comment.
Thanks @YihengLi-1. This now does what we discussed: the pretraining data lives in each checkpoint's model card, from_pretrained exposes it as model.card_data, and push_to_hub/save_pretrained write datasets/base_model into the YAML header. The code matches the patch we tested offline (new tests RED on master, GREEN here; the existing Hub-loading tests unchanged), CI is green, and the tutorial reads well. Your two audit tables are the content for the metadata_update script; please go ahead with it in a follow-up. Merging.
|
I am doing some follow-up PR to incorporate your well-curated list across all the Hugging Face and improve also the HTML view of the model in the Jupyter to make this clearer. |
Summary
First step of the proposal in #1492: record the pretraining datasets of the foundation models in braindecode, and give users one call to check whether an evaluation dataset overlaps a model's pretraining data, so results can be labelled in-corpus or held-out.
Changes
braindecode/models/pretraining.py:PRETRAINING_CORPORAmaps 11 model classes (BENDR, BIOT, Labram, EEGPT, CBraMod, LUNA, REVE, CSBrain, CodeBrain, BrainOmni, EEGDINO) to the datasets listed in their papers, with the source.complete=Falsemarks papers that do not itemise every dataset (LaBraM's self-collected data, REVE's 92 datasets, BrainOmni's MEG part).check_pretraining_overlap(model, dataset)accepts a class, an instance or a name, plus a dataset name or a MOABB/braindecode dataset object. It returns"in_corpus","same_collection"(a TUH sub-corpus such as TUAB/TUEV while the model saw TUEG data),"held_out"or"unknown", and warns unless the result is held out.PhysionetMIto EEGMMIDB,BNCI2014_004to BCIC-IV-2b).test/unit_tests/models/test_pretraining_overlap.py: in-corpus warning, TUH collection, held-out and unknown without warnings, aliases, and a check that every key is a braindecode model.docs/whats_new.rstentry.The lists come from a page-cited audit of 20 EEG foundation models: https://github.com/YihengLi-1/eeg-motor-imagery-decoding/blob/main/docs/pretraining_overlap_eeg_fm.md
Testing
pytest test/unit_tests/models/test_pretraining_overlap.py: 5 passed (local, Python 3.12).ruff checkandruff formaton the two new files: clean.Full suite not run locally; relying on CI.
New or changed behavior is covered by relevant regression tests
Style checks recorded (ruff check / ruff format on changed files)
docs/whats_new.rstupdatedNotes for reviewers
summary.csvor on the Hugging Face cards (the open question in Proposal: record pretraining corpora for foundation models and add a "held-out evaluation" check #1492). I'm happy to follow up with docs and the HF card version.