Repository navigation
docs: tutorial on SAE activation analysis with optional SAE Lens - #1152
Merged
Merged
Conversation
bruAristimunha
force-pushed
the
topk-sae
branch
from
September 9, 2026 14:50
b08c270 to
da20351
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1152 +/- ##
==========================================
+ Coverage 86.87% 87.71% +0.83%
==========================================
Files 144 149 +5
Lines 16509 17433 +924
==========================================
+ Hits 14343 15292 +949
+ Misses 2166 2141 -25 🚀 New features to boost your workflow:
|
Encodes an activation into n_inputs * expansion features, keeps the k largest rectified outputs, and decodes back. No optimizer, resampling or diagnostics.
ShahVandit
force-pushed
the
topk-sae
branch
from
September 28, 2026 20:31
222d685 to
6d9b6b3
Compare
Contributor
Author
|
Hi @bruAristimunha , I rebased this PR onto the current master and fixed the previous pre-commit formatting failure. The new pre-commit, docs, and What’s New checks are all passing. The only remaining failure is the Ubuntu/Python 3.12 sampler test, which appears to be an unrelated flaky Gloo multiprocessing failure: the same PR passed on Ubuntu 3.13, Windows, and macOS, and the PR does not modify sampler code. Could you please rerun that failed job? If it passes, I believe this is ready to merge. |
Replace the synthetic windows and random model with subject 3 of BCI IV 2a loaded through MOABBDataset, the standard trial-wise preprocessing and a session split. A ShallowFBCSPNet is trained for 30 epochs on the training session; the SAE, scaling statistics and feature selection are fitted on training activations only and evaluated once on the test session (FVU, accuracy/agreement under substitution with untrained-SAE and mean-ablation controls, class selectivity and feature time courses).
Append the docs-only `sae` extra (sae-lens==6.51.3) to DOCS_EXTRAS in the docs workflow. It stays out of core dependencies, the `docs` extra and `all`. docs/conf.py keeps rendering the SAE tutorials without executing them when sae_lens is not importable. The hunk is identical to the one in braindecode#1120 so the two PRs merge cleanly.
bruAristimunha
added a commit
to ShahVandit/braindecode
that referenced
this pull request
Sep 29, 2026
Add the docs-only `sae` extra (sae-lens==6.51.3) and append it to DOCS_EXTRAS in the docs workflow. It is not a core dependency, not in the `docs` extra and not in `all`. docs/conf.py keeps rendering the SAE tutorials without executing them when sae_lens is not importable. The hunks are identical to those in braindecode#1152 so the two PRs merge cleanly.
The build_docs job installs the `sae` extra through DOCS_EXTRAS, so the SAE tutorials always execute there and the filename_pattern fallback is not needed. docs/conf.py is back to the merge base.
Review follow-up: - plain SAE Lens imports; the optional install is mentioned in prose only - skorch SliceDataset/to_tensor for the hook inputs, window metadata for labels, EEGClassifier.predict for the native predictions - scikit-learn for evaluation: balanced_accuracy_score, agreement as accuracy_score(native, substituted), FVU as 1 - r2_score(..., variance_weighted), ConfusionMatrixDisplay for true/native and native/substituted decisions, r_regression (point-biserial) for class selectivity (same ranking and the same selected features as before) - einops patterns instead of the reshape helpers - references in the footnote style of the other tutorials Every printed number is unchanged on BNCI2014_001 subject 3.
- One narrated rcParams cell at the top: orange for the trained SAE, near-black for the native decoder, warm grey for every control, left-aligned titles computed from the numbers they report, monospace numbers, no legend boxes. Fonts fall back to DejaVu on CI. - New first figure (and gallery thumbnail): FVU, balanced accuracy and agreement for the native decoder, the trained SAE and both controls. - Confusion matrices restyled; the title counts the changed decisions. - Selectivity heatmap: annotated cells, an inset outline on the class each feature was picked for, class groups separated, no colorbar. - The time-course figure becomes one feature card per hand feature: trial-mean codes, code when active, time course with s.e.m., the most active test trials shaded by the code, and the channel-power association (labelled as an association, not a source map). No computation that produces the printed results changed; all printed numbers are identical to the previous head.
The suptitle calls were the last expression in three cells, so sphinx-gallery printed their Text(...) repr under the figures.
Brand blue for the trained SAE and the picked class, ink for the native decoder, muted slate for controls, amber outlines, from docs/_static/landing.css. The feature card drops the redundant code histogram and the per-class time courses (now target vs other classes, labelled at the line ends), moves the EEG 'most active trials' panel to the full width, and replaces the topomap's text legend with a colorbar. Bar tracks are removed, and cell labels switch to white only on dark cells. Printed outputs are unchanged.
The rcParams block is cosmetic, so it now sits in a sphinx-gallery ignore block: it still runs, but readers only see the four palette colors the plotting code uses. Settings whose defaults look the same are dropped, fonts fall back to matplotlib's DejaVu (what CI renders with), and the channel-power panel title is shortened so it no longer clips.
Bruno asked for red. #b5332e has about the brand blue's lightness (L* 42 vs 44), 6.0:1 contrast on white, and stays separable from the blue under simulated protan, deutan and tritan vision, so the blue-red diverging maps keep their meaning. Printed outputs are unchanged.
bruAristimunha
added a commit
that referenced
this pull request
Sep 30, 2026
#1120) * Add Top-K sparse autoencoders for mechanistic interpretability Adds SparseAutoencoder, fit_sparse_autoencoder and sae_diagnostics, plus the forward-hook primitives capture_activations and run_with_activation_substitution for measuring whether a dictionary kept what the model actually uses. Includes tests, a gallery example on the published BCI IV 2a checkpoint, and the LaBraM validation script. * docs: replace SAE infrastructure and NMT runner with optional LaBraM tutorial * docs: keep tutorial changelog independent of upstream additions * docs: run LaBraM SAE tutorial on real BNCI2014_001 EEG Replace the synthetic windows and random two-block LaBraM with subject 3 of BCI IV 2a (MOABBDataset, LaBraM preprocessing, session split) and the pretrained braindecode/labram-pretrained weights, fine-tuned for ten epochs on the training session. A training-session check shows which blocks' patch tokens can reach the CLS head; the Top-K SAE is fitted to block-6 patch tokens and evaluated on the test session with reconstruction substitution, untrained-SAE and mean-token controls, per-channel feature maps and error-preserving removal of class-selective features against random feature sets. * docs: move the SAE intervention tutorial to a frozen pretrained REVE Rename plot_sae_labram.py to plot_sae_reve.py and rewrite it around braindecode.models.REVE with brain-bzh/reve-base (from_pretrained, chs_info for the position bank, 200 Hz, 4-s windows = 88 tokens). Same data: BNCI2014_001 subject 3, session 0 for fitting, session 1 for testing, now with REVE's preprocessing (0.5-99.5 Hz, per-recording z-score clipped at 15 SD) and per-session Euclidean alignment. The encoder is frozen and only REVE's flattening head is trained on the first four runs of session 0; the last two runs are a validation split. Model setup, SAE block (18) and size (2048 features, k=32) were chosen on that split before the test session was used; the tutorial states the validation numbers behind each choice. It shows a skip-one-block check of which blocks influence the prediction, a Top-K SAE on block-18 tokens with trained/untrained/mean-token substitution controls, per-channel feature maps, and error-preserving removal of class-selective features against random feature sets and the other classes' sets. * ci: install SAE Lens for the docs build so the SAE tutorials execute Add the docs-only `sae` extra (sae-lens==6.51.3) and append it to DOCS_EXTRAS in the docs workflow. It is not a core dependency, not in the `docs` extra and not in `all`. docs/conf.py keeps rendering the SAE tutorials without executing them when sae_lens is not importable. The hunks are identical to those in #1152 so the two PRs merge cleanly. * docs: drop the SAE Lens conf.py guard; docs CI installs the sae extra The build_docs job installs the `sae` extra through DOCS_EXTRAS, so the SAE tutorials always execute there and the filename_pattern fallback is not needed. docs/conf.py is back to the merge base. * docs: use library functions in the REVE SAE tutorial Review follow-up: - plain SAE Lens imports; the optional install is mentioned in prose only - REVE's per-recording z-score/clip via Preprocessor(sklearn scale, channel_wise=True) and np.clip (bitwise identical to the old helper) - MOABB EuclideanAlignment(estimator="scm"), fitted per session on that session's windows; the head and SAE see the training session only - skorch SliceDataset/to_tensor for the arrays, window metadata for labels, EEGClassifier for the linear head instead of a hand-written loop - scikit-learn for evaluation: balanced_accuracy_score, agreement as accuracy_score(native, edited), FVU as 1 - r2_score(variance_weighted), ConfusionMatrixDisplay, r_regression for class selectivity - narrative and a schematic of REVE's residual stream: streams 0-22, where tokens are read (block 18), SAE edits, run_blocks through 19-22 and the head, and why forward hooks cannot reach the stream - interventions reuse the cached test codes; fewer helpers - cite He & Wu (2020) and Junqueira et al. (2024) for EA With the MOABB alignment the session-0 validation selection was re-run (session 1 dropped before any model output). Setup and block are unchanged; the dictionary-size rule now picks 4096 features (79% vs 73% validation agreement), which the tutorial states. * docs: restyle the REVE SAE tutorial figures - One narrated rcParams cell at the top, shared with the SAE activation tutorial: orange for the result, warm grey for controls, blue for the pretrained blocks that finish an edited forward pass, left-aligned titles computed from the numbers they report, monospace numbers, no legend boxes or colorbars. Fonts fall back to DejaVu on CI. - Token-stream schematic kept and restyled; the block panel now marks the update a submodule returns and the "+ x" skip that carries the stream. - Block check shows the share of validation decisions that change, with value labels and the SAE block in orange. - Confusion matrices restyled; the title compares the trained SAE's agreement with both controls. - Scalp maps: diverging orange/blue maps, peak channel and scale under each map instead of four colorbars, and a footnote that the channels are aligned virtual channels, not a source map. - Feature removal: every random set and every other-class set is drawn, not only a mean and maximum; the 4x4 matrix outlines the own-set cells. The thumbnail is this figure. No computation that produces the printed results changed; all printed numbers are identical to the previous head. * docs: tell the REVE SAE tutorial as two tests, with a headline figure - Pose the question in the first paragraph (can a sparse dictionary on a frozen pretrained EEG transformer expose features its classifier uses?) and split it into two tests: the reconstruction must preserve the decisions, and removing a class's features must beat random sets and the other classes' sets. The close answers in the same words, then states four bounds and one take-home. - Claim headings backed by computed titles; purpose-clause openers; the controls sit next to each claim; association vs use, the feet caveat and the transductive test alignment are stated where they apply. - New Test 1 figure: FVU, balanced accuracy and agreement for the native model, the trained SAE and both controls, with the single-class collapse of the controls annotated. The confusion figure now answers which decisions change. - Schematic: brackets for what token_streams (once) and run_blocks (per edit) compute, and the two edits of the two tests. - Scalp maps: the title names the hemisphere of each hand feature's peak; the caveat reads "an association, not a source map". - Removal figure (thumbnail): specificity contrast (own minus best control) per class, and the other class's set that beats the feet set is named. - End figure cells with plt.show() so no Text repr is printed. Printed numbers are unchanged (checked line by line against 89ac394). * docs: use the Braindecode palette in the REVE SAE tutorial and hide its styling Brand blue for the result, ink for the native model, muted slate for controls and amber for the rerun blocks and the other classes' feature sets, from docs/_static/landing.css. The cosmetic rcParams block is trimmed and moved into a sphinx-gallery ignore block. Less ink: no bar tracks, one value label on the block chart, no sensor dots on the scalp maps, and cell labels that switch to white only on dark cells. Printed outputs are unchanged. * docs: use red instead of amber for the SAE tutorial's secondary accent Bruno asked for red. #b5332e has about the brand blue's lightness (L* 42 vs 44), 6.0:1 contrast on white, and stays separable from the blue under simulated protan, deutan and tritan vision, so the blue-red diverging maps keep their meaning. Printed outputs are unchanged. --------- Co-authored-by: Bruno Aristimunha <[email protected]> Co-authored-by: Bru <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Scope
A standalone Sphinx-Gallery tutorial that fits a sparse autoencoder with SAE Lens 6.51.3 to the activations of a braindecode decoder. It does not add an SAE implementation to Braindecode.
examples/advanced_training/plot_sae_activation_analysis.pyuses real EEG: subject 3 of BCI IV 2a (MOABBDataset("BNCI2014_001")). Loading, preprocessing (EEG picks, V→µV, 4–38 Hz, exponential moving standardization), trial windowing and the0train/1testsession split followplot_interpretability.py/plot_bcic_iv_2a_moabb_trial.py. No synthetic or random EEG is used.EEGClassifier).pool_nonlin_expactivations are captured with the existingcapture_activations. A Top-K SAE (160 features, k = 8, 2000 updates, SAE LensSAETraineron tensor batches) is fitted to the train-standardized activations.run_with_activation_substitution. Controls are the untrained SAE and replacing the layer with its training mean. Confusion matrices show true vs. native and native vs. substituted decisions. Class-selective features are chosen on the training session and then shown on the test session as a heatmap and as time courses.saeextra: it is not a core dependency and not part ofdocsorall..github/workflows/docs.ymlappendssaetoDOCS_EXTRAS, sobuild_docsinstalls it and executes the tutorial. That hunk and thepyproject.tomlhunk are byte-identical to docs: REVE sparse-feature intervention tutorial with optional SAE Lens #1120's.docs/conf.pychange any more. Thefind_spec("sae_lens")guard was removed (review): docs CI always installs the extra.docs/conf.pyis identical to the merge base.Review follow-up (this push)
sae_lensimports; notry/except ImportError. The optional install is mentioned in the prose only.SliceDataset+skorch.utils.to_tensorfor the hook inputs; labels from the window metadata (get_metadata()["target"]); native predictions fromEEGClassifier.predict.balanced_accuracy_score(equal to accuracy here; 72 test trials per class), agreement asaccuracy_score(native, substituted), FVU as1 - r2_score(..., multioutput="variance_weighted")(identical definition; the prose now says "around their mean", which is what the code always computed),ConfusionMatrixDisplay.sklearn.feature_selection.r_regression(point-biserial correlation). For each class it ranks features exactly like the previous standardized mean difference; the selected features are the same (checked).einopspatterns replace the reshape helpers; references use the footnote style of the other tutorials (Schirrmeister et al. 2017, DOI 10.1002/hbm.23730, verified on Crossref).Remaining helpers and why:
activation_batches: SAE LensSAETrainertakes any iterator of tensor batches, and SAE Lens's ownActivationsStoreneeds a language model. This 3-line generator samples training rows with replacement.substitute_with(dictionary)andmean_ablation: these are the callables thatbraindecode.visualization.run_with_activation_substitutionrequires. They define the interventions (scale, encode/decode, unscale, restore axes).mean/stdstay torch tensors because the hook has to undo the scaling inside the forward pass.Numbers from this run (real data: BNCI2014_001 subject 3, CPU, one seed)
Unchanged by the review changes (bit-for-bit the same printed values as the previous head).
These numbers describe one subject, one seed and a short CPU budget. They support no scientific claim about motor imagery or about what the features mean physiologically.
Validation (head a06a617)
All evidence below comes from the cached real EEG, with outbound network blocked (
sandbox-exec) andHF_HUB_OFFLINE=1. Nothing was downloaded, and the MNE data cache was unchanged (mtime and size).EEGClassifier.predictequalsmodel(x_test).argmax;sphinx-build -b html -W), with no guard: executed 1/1, 30.84 s, build succeeded, 0 warnings, and the rendered page shows the printed table and figures. The cross-reference targets (interpretability-tutorial,bcic-iv-2a-moabb-trial) were stubbed; both exist in the docs.docs/conf.py:randn,np.randomor synthetic inputs; the only randomness istorch.randintfor SAE batch indices;try:/ImportError;find_spec/importlib;to_rows,fvu,per_window_codes, the hand-written accuracy or selectivity).git merge-tree): master + this PR, master + docs: REVE sparse-feature intervention tutorial with optional SAE Lens #1120, docs: REVE sparse-feature intervention tutorial with optional SAE Lens #1120 + this PR, and master + both in either order are all clean. Both orders give the same tree, whosedocs/conf.pyis byte-identical to master.sae(Python 3.12, linux x86_64, CPU torch):fsspec2026.9.0 → 2026.6.0, becausedatasets, pulled in by sae-lens, caps it.braindecode[all]does not pull sae-lens.Not run: GPU execution, the full gallery, the full test suite, and multiple subjects or seeds.
CI
build_docsrun 36616521966 finished green (20:29 UTC). The log shows+ sae-lens==6.51.3installed and, in the full gallery pass,plot_sae_activation_analysis.py: 73.65 secwith "executed 34 out of 34 files". Its 3 Sphinx warnings are the usual infrastructure ones (parallel-read / config cache), not from this tutorial.Relationship to #1120
#1120 is the complementary tutorial on the same real recording, with a frozen pretrained REVE (
brain-bzh/reve-base): which blocks influence the prediction, token features as scalp maps, and error-preserving feature removal with random-feature and other-class controls. Neither PR imports or references the other's tutorial, and neither adds an SAE framework. The docs-CI and extra hunks are identical in both PRs, and neither touchesdocs/conf.pyany more.Figures (head b7fe673)
One additive commit,
plot_sae_activation_analysis.pyonly, restyling the figures as requested in review.docs/_static/landing.css): brand blue for the trained SAE and the picked class, ink for the native decoder, muted slate for the controls, red (#b5332e) for outlines and negative correlations. The cosmeticrcParamsblock runs inside a sphinx-gallery ignore block, so readers only see the four color constants the plotting code uses. Titles are computed from the numbers they report, and fonts fall back to DejaVu. No new helpers or dependencies.sphinx-build -W: executed 1/1 in 19.9 s with 0 warnings and no matplotlib/mne warnings. I also rendered it with DejaVu only, as CI does. Pre-commit passed.