Skip to content

docs: tutorial on SAE activation analysis with optional SAE Lens - #1152

Merged
bruAristimunha merged 15 commits into
braindecode:masterfrom
ShahVandit:topk-sae
Sep 30, 2026
Merged

bruAristimunha merged 15 commits into
braindecode:masterfrom
ShahVandit:topk-sae

Conversation

@ShahVandit

@ShahVandit ShahVandit commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

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.py uses 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 the 0train/1test session split follow plot_interpretability.py / plot_bcic_iv_2a_moabb_trial.py. No synthetic or random EEG is used.
  • A ShallowFBCSPNet is trained for 30 epochs on the training session only (EEGClassifier). pool_nonlin_exp activations are captured with the existing capture_activations. A Top-K SAE (160 features, k = 8, 2000 updates, SAE Lens SAETrainer on tensor batches) is fitted to the train-standardized activations.
  • Evaluation happens once, on the test session: FVU (trained vs. an untrained SAE with the same initialization), active-feature statistics, and balanced accuracy/agreement when the reconstruction is substituted into the forward pass with 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.
  • SAE Lens stays in an isolated optional sae extra: it is not a core dependency and not part of docs or all. .github/workflows/docs.yml appends sae to DOCS_EXTRAS, so build_docs installs it and executes the tutorial. That hunk and the pyproject.toml hunk are byte-identical to docs: REVE sparse-feature intervention tutorial with optional SAE Lens #1120's.
  • No docs/conf.py change any more. The find_spec("sae_lens") guard was removed (review): docs CI always installs the extra. docs/conf.py is identical to the merge base.
  • Vandit Shah's authorship and branch history are kept. All changes are additive commits.

Review follow-up (this push)

  • Plain sae_lens imports; no try/except ImportError. The optional install is mentioned in the prose only.
  • Data: skorch SliceDataset + skorch.utils.to_tensor for the hook inputs; labels from the window metadata (get_metadata()["target"]); native predictions from EEGClassifier.predict.
  • Evaluation with scikit-learn: balanced_accuracy_score (equal to accuracy here; 72 test trials per class), agreement as accuracy_score(native, substituted), FVU as 1 - r2_score(..., multioutput="variance_weighted") (identical definition; the prose now says "around their mean", which is what the code always computed), ConfusionMatrixDisplay.
  • Class selectivity via 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).
  • einops patterns 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 Lens SAETrainer takes any iterator of tensor batches, and SAE Lens's own ActivationsStore needs a language model. This 3-line generator samples training rows with replacement.
  • substitute_with(dictionary) and mean_ablation: these are the callables that braindecode.visualization.run_with_activation_substitution requires. They define the interventions (scale, encode/decode, unscale, restore axes).
  • mean/std stay 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).

test-session balanced accuracy agreement with native
native ShallowFBCSPNet 69.4% 100%
trained SAE substituted 67.4% 93.4%
untrained SAE (same init) 25.0% 18.8%
layer := training mean 25.0% 18.8%
  • Test FVU: 0.135 in standardized units, 0.134 in log-power units. The untrained dictionary gives 1.021.
  • Mean active features per observation: 8.00 (k = 8). 6.2% of the features never fire on the test session.
  • All 8 class-selective features (2 per class, picked on the training session) have their largest mean test-session code on the class they were picked for.

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) and HF_HUB_OFFLINE=1. Nothing was downloaded, and the MNE data cache was unchanged (mtime and size).

  • End to end with Python 3.12, PyTorch 2.14.0, SAE Lens 6.51.3 and MOABB 1.7.2 on CPU: 31.4 s wall time (26.4 s on a second run), peak RSS 2.3 GB. Extra checks:
    • EEGClassifier.predict equals model(x_test).argmax;
    • no hooks are left behind;
    • the substitution keeps shape and dtype and does not modify its input;
    • the scaling inverts exactly.
  • Strict isolated single-example Sphinx-Gallery build (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.
  • Existing activation-helper tests: 5 passed. Repository pre-commit hooks on the changed files (ruff, codespell, mypy, …): passed.
  • Grep of the tutorial and docs/conf.py:
    • no randn, np.random or synthetic inputs; the only randomness is torch.randint for SAE batch indices;
    • no try:/ImportError;
    • no find_spec/importlib;
    • no removed helper (to_rows, fvu, per_window_codes, the hand-written accuracy or selectivity).
  • Merge previews (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, whose docs/conf.py is byte-identical to master.
  • Dependency impact (unchanged by this push). I resolved the docs extras with and without sae (Python 3.12, linux x86_64, CPU torch):
    • The core stack is unchanged: torch 2.14.0+cpu, numpy 2.5.3, mne 1.13.2, moabb 1.7.2, sphinx-gallery 0.22.1.
    • One transitive downgrade: fsspec 2026.9.0 → 2026.6.0, because datasets, pulled in by sae-lens, caps it.
    • 42 packages are added.
    • braindecode[all] does not pull sae-lens.

Not run: GPU execution, the full gallery, the full test suite, and multiple subjects or seeds.

CI

  • Previous head b35fb0e: build_docs run 36616521966 finished green (20:29 UTC). The log shows + sae-lens==6.51.3 installed and, in the full gallery pass, plot_sae_activation_analysis.py: 73.65 sec with "executed 34 out of 34 files". Its 3 Sphinx warnings are the usual infrastructure ones (parallel-read / config cache), not from this tutorial.
  • This head a06a617, snapshot at 20:44 UTC: docs 36628389170 in progress, pre-commit in progress, tests pending, "Check Whats News Changes" passed. The docs build takes about 2 h; nobody is watching it.

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 touches docs/conf.py any more.

Figures (head b7fe673)

One additive commit, plot_sae_activation_analysis.py only, restyling the figures as requested in review.

  • Colors follow the Braindecode documentation (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 cosmetic rcParams block 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.
  • The figures, in order:
    1. A new headline figure, also the thumbnail: FVU, balanced accuracy and agreement for the native decoder, the trained SAE and both controls.
    2. The confusion matrices.
    3. The selectivity heatmap, with an inset outline on the class each feature was picked for.
    4. and 5. One feature card for each of the top left-hand and right-hand features: trial-mean codes, code when active, time course ± s.e.m., the most active test trials shaded by the code, and the channel-power association, labelled "an association, not a source map".
  • All 17 printed result lines are identical to a06a617. Offline end-to-end run: 17.7 s. Strict single-example 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.

@codecov

codecov Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.71%. Comparing base (e1fbd7b) to head (811ce21).
⚠️ Report is 15 commits behind head on master.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Encodes an activation into n_inputs * expansion features, keeps the k largest rectified outputs, and decodes back. No optimizer, resampling or diagnostics.
@ShahVandit

Copy link
Copy Markdown
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.

@bruAristimunha bruAristimunha changed the title Add a Top-K sparse autoencoder over model activations docs: tutorial on SAE activation analysis with optional SAE Lens Sep 29, 2026
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
bruAristimunha merged commit 4e1d48e into braindecode:master Sep 30, 2026
19 of 20 checks passed
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]>
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