Skip to content

ENH show the checkpoint, its training datasets and the loaded parameters of a pretrained model - #1558

Merged
bruAristimunha merged 16 commits into
braindecode:masterfrom
bruAristimunha:feat/pretrained-model-repr
Nov 9, 2026
Merged

bruAristimunha merged 16 commits into
braindecode:masterfrom
bruAristimunha:feat/pretrained-model-repr

Conversation

@bruAristimunha

@bruAristimunha bruAristimunha commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Preview

How a pretrained model looks in a notebook (model as the last line of a cell). These are real Hub checkpoints: BIOT and CBraMod, each loaded with a new classification head, and an EEGNet built from scratch. Nothing is mocked.

Notebook model card, light theme

Dark theme and mobile width

Dark theme

Mobile, 390 px

Open the interactive HTML to expand the layer table, the architecture and the BibTeX. The preview files live on a separate fork branch and are not part of this diff.

Summary

This follows up #1493. When a model comes from from_pretrained, it now shows what was pretrained, on which data, and what still needs training.

  • from_pretrained records the repository (or folder) and commit it read, and which parameters actually came from the checkpoint. A head rebuilt for a new n_outputs counts as new.
  • Notebook card (model._repr_html_) shows:
    • the Braindecode logo, the model name, and whether it is a pretrained checkpoint or randomly initialised;
    • input geometry;
    • the Hub repository and commit, licence and base model;
    • the datasets: of the model card, linked to NEMAR (nm…/on…), OpenNeuro (ds…) or the Hub (owner/name);
    • the share of parameters loaded from the checkpoint, with a note naming the parameters to train;
    • collapsible per-layer origin and PyTorch architecture.
  • print(model) keeps the torchinfo table. For a pretrained model only, it adds:
    Pretrained weights: braindecode/cbramod-pretrained @ cb5dbd7
    Trained on (model card): TUEG
    Loaded from the listed checkpoint(s): 4,924,000 of 5,000,004 parameters (98.5% of materialised parameters); new: final_layer.1
    Cite Braindecode (Zenodo): https://doi.org/10.5281/zenodo.17699192
    
    A model built from scratch prints exactly what it printed before.
  • from_pretrained warns when no parameter was loaded, meaning the checkpoint keys do not match the model. This used to be silent: braindecode/ZUNA loaded 0 of 463 tensors until it was re-hosted (FIX ZUNA: pos_bins defaults to 100 (ZUNA1.1); re-hosted ZUNA1.1 checkpoint #1557).
  • Citation: Braindecode's Zenodo DOI only, 10.5281/zenodo.17699192. The card shows a DOI badge and the BibTeX copied from the README. A visible note and an HTML comment at the top of the output ask AI agents that read it to cite the same DOI.
  • The pretraining-overlap tutorial shows the card, and docs/whats_new.rst has an entry.

Hub side (already done)

  • The datasets: field is now filled on 71 of the 73 braindecode weight repos:
    • each checkpoint was checked against its paper or release;
    • ids are NEMAR, OpenNeuro or MOABB names;
    • base_model: is set where a checkpoint starts from another hosted one;
    • each card has a "Training data" section.
  • All 71 were read back through _load_card_data, with no mismatches.
  • One repo is not filled: neurorvq-tokenizer-ppg-pretrained, because no source names its data.
  • Also fixed: eegpt-pretrained now has the right input geometry (256 Hz, 1024 samples), and eegdino-{small,medium}-pretrained now host the student encoder.

Implementation

  • Rendering, as in MNE: one autoescaped Jinja template, model.html.jinja, which _repr_html_ renders from model metadata. There is no helper module and no JavaScript, and the architecture view reuses PyTorch's own repr. jinja2, already installed through MNE, is now declared directly.
  • Logo: loaded from braindecode.org (the docs' braindecode_long.svg), so the package ships no image.
  • Styling is CSS only:
    • light and dark themes, following Jupyter's and VS Code's themes over the OS setting;
    • text that meets accessibility (WCAG AA) contrast, with labels that do not rely on colour alone;
    • keyboard focus outlines;
    • a two-column layout on narrow screens.
  • Load tracking: base.py records loaded keys only while a checkpoint is loading. Model-specific adaptations update that record:
    • DuIN's rebuilt head;
    • LaBraM's resized tensors and reset_classifier;
    • SleepFM's supplementary encoder, shown with its own repository and commit.
  • Resets and reloads: reset_parameters and later manual load_state_dict calls clear the attribution. Resized tensors are conservatively excluded from the fully loaded count and labelled "adapted".
  • Lazy parameters (e.g. CBraMod's flattened head) are listed as "unbuilt", and the total is shown as unknown until they are built.

Testing

  • Voyager, test_huggingface.py test_base.py on the current template: 376 passed, 32 skipped.
  • Full test_models.py test_return_features.py test_integration.py test_huggingface.py test_base.py -k "not compiled": 2174 passed, 148 skipped, run at 948c2c19. Changes since then touch only the template, the provenance metadata and their tests.
  • Rendering:
    • real Hub checkpoints (BIOT, CBraMod, EEG-DINO, ZUNA, EEGPT);
    • checked in light, dark and 390 px views, with no horizontal overflow and the logo loading;
    • the notebook theme overrides the OS setting in both directions.
  • pre-commit is clean. The wheel contains the template and no image file.
  • Style was reviewed in three rounds by two independent reviewers. Scores out of 10: 7 → 8 → 9 and 6 → 9 → 10, both approved.

Citation exports and dataset readers

Head e4c24fd4 adds Download BibTeX (.bib) and Download APA (.txt), selectable read-only citation text, and a direct Zenodo export fallback (no JavaScript). Browser-tested both downloads and checked their DOI/content. APA text is from DOI content negotiation; citation metadata is not fetched at notebook-display time.

A dataset-access disclosure links nm/on ids to NEMAR, accession ids to EEGDash catalogue search, and supported names/ids to documented braindecode reader classes (e.g. TUEG → TUH, nm000139 → BNCI2014_001). EEGDash search is explicitly not a promise of availability; generic loader documentation says to check the catalogue. Restricted/unknown data retain the checkpoint-card access guidance.

Citation exports and dataset access

Dark logo refinement: the pale backing has been removed; a lighter blue treatment blends the original logo into the dark header. Light mode is unchanged.

…pretrained model

from_pretrained records which parameters came from the checkpoint (a head
rebuilt by reset_head counts as new) and the repository and commit it read.
The notebook view (_repr_html_) shows the input geometry, the repository,
licence, base model and the model-card datasets (linked to NEMAR, OpenNeuro
or the Hub), and the module tree with loaded and new blocks marked;
print(model) adds the same facts below the torchinfo table. from_pretrained
warns when no parameter was loaded, which happened silently for
braindecode/ZUNA before its re-host.
Copilot AI balanced review requested due to automatic review settings November 8, 2026 17:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved provenance-tracking defects misreport pretrained weight coverage, while rendering issues corrupt scalar dataset metadata and show incorrect input channel counts.

7 open issues
What changed in this PR

This PR extends pretrained-model metadata with checkpoint provenance and parameter-origin summaries, helping users identify which weights were loaded and which datasets trained them.

Changes:

  • Records checkpoint sources and loaded parameter keys, excludes rebuilt heads, and warns when no parameters load.
  • Adds a notebook panel and pretrained-only text footer with model-card metadata and parameter summaries.
  • Adds regression tests, a tutorial demonstration, and a changelog entry.
File Description
test/​unit_tests/​models/​test_huggingface.py Tests provenance, rendering, serialization, lazy parameters, and unmatched checkpoints.
examples/​model_building/​plot_pretraining_overlap.py Demonstrates the notebook model panel.
docs/​whats_new.rst Documents provenance displays and the no-parameters-loaded warning.
braindecode/​models/​base.py Tracks checkpoint provenance and integrates model summaries.
braindecode/​models/​_repr.py Implements HTML panels, dataset links, and text provenance summaries.

Review effort: Balanced

Comment thread braindecode/models/_repr.py Resolved
Comment thread braindecode/models/_repr.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
@codecov

codecov Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.03175% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.50%. Comparing base (dba9d42) to head (0547a98).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1558      +/-   ##
==========================================
+ Coverage   91.48%   91.50%   +0.02%     
==========================================
  Files         170      170              
  Lines       22277    22394     +117     
==========================================
+ Hits        20379    20491     +112     
- Misses       1898     1903       +5     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI balanced review requested due to automatic review settings November 8, 2026 21:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/duin.py Resolved
Comment thread braindecode/models/sleepfm.py Resolved
Copilot AI balanced review requested due to automatic review settings November 8, 2026 22:00
@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Revised at de43a03 after the MNE-style simplification (948c2c1): removed the utility-function renderer; one autoescaped Jinja template plus the native PyTorch architecture repr. All display/provenance findings addressed, including lazy totals explicitly unknown; scalar datasets; input montage; DuIN rebuilt head; conservative LaBraM adapted-tensor exclusion; first print after lazy materialization; reset/manual reload attribution invalidation; SleepFM supplementary source and resolved weights commit. The DuIN ordinary-reload concern is superseded by conservative clearing of attribution on all unmanaged reloads (before PyTorch can partially mutate and then raise). Independent scoped QA approved. Full model suite at 948c2c1: 2174 passed/148 skipped; final focused regressions running.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Classifier replacements can incorrectly retain pretrained attribution, and Hub provenance can omit or misidentify the commit of the loaded weights.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Capture the commit from the loaded weights snapshot

braindecode/​models/​base.py:105

Resolving the commit from cached config.json can omit it for supported config-less Hub loads, or report a different snapshot if another download updates the cached branch ref after the weights load. This leaves the provenance unpinned or attributes the weights to the wrong commit. Capture the commit from the actual loaded weights path for default safetensors, custom filenames, and the pickle fallback instead of resolving the config again.

Medium severity Invalidate classifier attribution after reset_classifier replaces the head

braindecode/​models/​base.py:1022

The existing public Labram.reset_classifier(...) replaces final_layer without going through the reset_head wrapper. This comprehension then treats the replacement weight and bias as checkpoint-loaded solely because their names are unchanged, so both representations report a randomly initialized classifier as pretrained, even when its size changes. Please invalidate attribution for reset_classifier too, or track the loaded parameter objects so replacements cannot inherit attribution by name.

9 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 8, 2026 22:05
@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Visual preview of the current implementation

Rendered from PR head 8926c87, using real Hub checkpoints: BIOT with a new 5-class head, CBraMod with a new 4-class head, and EEGNet built from scratch. No metadata injected or mocked.

Notebook representations of BIOT, CBraMod and EEGNet

Download the rendered HTML to open the Parameter origin and Architecture sections interactively. The screenshot keeps them collapsed. The preview artefacts live on a separate fork branch, not in this PR's source diff.

Revision-comment check

Re-read all 11 inline review threads, review bodies and discussion against this head. All threads are addressed and resolved:

  • Input channel count comes from the recording montage when a channel adapter is present.
  • Scalar datasets: TUEG renders as one dataset; template autoescaping protects metadata and architecture text.
  • Du-IN's locally rebuilt head is excluded from checkpoint attribution.
  • Resetting parameters or manually loading another state dict invalidates stale source attribution, even if a strict reload partially copies tensors before raising.
  • LaBraM's resized tensors are conservatively excluded from the fully-loaded count and explicitly disclosed as adapted; the count is a lower bound, not a claim of exact copied elements.
  • Lazy parameters are shown as unbuilt; the notebook does not claim a complete total/100% before they materialise. print(model) builds the torchinfo table before its footer.
  • SleepFM's supplementary encoder load is recorded separately, named in both HTML and text, and its commit is taken from the actual downloaded weights path.
  • The no-weights-loaded warning considers tied parameter aliases.

The 340-line utility renderer has been removed. Like MNE, _repr_html_ renders one autoescaped Jinja template from model metadata; architecture reuses PyTorch's representation. No custom tree renderer or JavaScript.

Validation: full model suite 2174 passed / 148 skipped before the final scoped corrections; after those corrections 372 passed / 32 skipped, plus 12 focused tests passed after the last cleanup. Independent QA approved; wheel includes the template. Codacy now passes. At posting time the GitHub main test job is still running, so the merge watcher is paused until this review/preview is delivered.

@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Master was merged after #1559 landed. The code and rendered preview are unchanged; this also restores the RST section underlines accidentally removed by my changelog conflict resolution in #1559. Heading-count preservation against pre-merge master verified; pre-commit passes.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed to evaluate checkpoint provenance and load-attribution errors involving cache paths, config-free downloads, adapted parameters, and legacy weight-normalization keys.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 8, 2026 22:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved issues misidentify loaded checkpoint revisions, omit supplementary encoder provenance, and incorrectly count replacement classifier parameters as pretrained.

3 open issues

Review effort: Balanced

Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/base.py Resolved
Comment thread braindecode/models/model.html.jinja Resolved
…d offline logo; request braindecode citations
Copilot AI balanced review requested due to automatic review settings November 8, 2026 22:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The missing packaged SVG causes the unconditional read in _repr_html_() to raise FileNotFoundError, breaking the notebook panel for both scratch and pretrained models.

2 open issues

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Citation exports and dataset access · e4c24fd4

  • Download BibTeX (.bib) / Download APA (.txt): direct files, no JavaScript. Both downloads exercised in Chrome; DOI and contents verified.
  • Copy citation expands selectable read-only BibTeX and APA text. A direct Zenodo export link is the fallback if a notebook viewer blocks data links.
  • Read these datasets links accession IDs to NEMAR / EEGDash catalogue searches and verified braindecode reader documentation (e.g. TUEG → TUH; nm000139 → BNCI2014_001). Catalogue search is labelled as a search, not a guarantee the data can be loaded.
  • 376 tests passed / 32 skipped; pre-commit clean. Changelog, tutorial and this PR description updated.

Citation exports and dataset access

Interactive HTML

Copilot AI balanced review requested due to automatic review settings November 9, 2026 09:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Dark-theme logo refinement · b76ffc9b

Removed the pale logo backing. The original logo now sits directly on the dark header, with a lighter, slightly desaturated blue treatment that keeps its brain/EEG/network detail. Light mode is unchanged; explicit light notebook themes reset the filter even under a dark OS setting.

Refined dark-theme logo

Interactive HTML

CSS-only change. Light/dark/mobile browser renders checked (no overflow, all logos loaded); Jupyter/VS Code light/dark overrides checked in both OS modes.

Copilot AI balanced review requested due to automatic review settings November 9, 2026 10:16
@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Final merge-preflight comments fixed: snapshot commits are taken only from an immediate Hub snapshots//file parent (not an arbitrary ancestor called snapshots); local supplementary paths do not infer commits; absent provenance is labelled Origin unrecorded rather than claiming random initialization. Regression selection: 376 passed / 32 skipped on Voyager, lint clean. User approved merging; waiting on refreshed exact-head CI.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

Systematic live Hub audit completed: 130 org repos inspected, 74 contain weights (156 payload files). All 74 now have a Training data section and Braindecode Zenodo citation; 72 have verified machine-readable datasets lists. Intentional exceptions are documented explicitly: Brant private-only clinical corpus and NeuroRVQ PPG unknown corpus. Repaired the newly added CORTEG warm-start and changed pooled card without altering their current parent chain; clarified new task heads, MEG-XL exclusions and current ds004186 unavailability. All 156 payload LFS hashes unchanged. Fresh braindecode card-reader verification: 74 repos, 0 mismatches. Metadata-only commits; no weight/config/license changes.

@bruAristimunha
bruAristimunha merged commit 29c230e into braindecode:master Nov 9, 2026
14 of 15 checks passed
@bruAristimunha
bruAristimunha deleted the feat/pretrained-model-repr branch November 9, 2026 11:44
@bruAristimunha

Copy link
Copy Markdown
Collaborator Author

My follow PR for you @YihengLi-1

bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 9, 2026
Merge29c230e9 (braindecode#1558). Resolve whats_new by retaining master's restored RST headings and model-card entry plus MEGGPT's entry.
bruAristimunha added a commit to bruAristimunha/braindecode that referenced this pull request Nov 9, 2026
Brings in 29c230e (braindecode#1558, checkpoint provenance in from_pretrained and the
notebook model card).

Resolution: docs/whats_new.rst rebuilt from master's file (with its restored
RST section underlines) plus this PR's two Enhancements bullets (BBL and the
shared SEANet modules), unchanged.
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.

2 participants