Skip to content

docs: REVE sparse-feature intervention tutorial with optional SAE Lens - #1120

Merged
bruAristimunha merged 15 commits into
braindecode:masterfrom
ShahVandit:topksae
Sep 30, 2026
Merged

bruAristimunha merged 15 commits into
braindecode:masterfrom
ShahVandit:topksae

Conversation

@ShahVandit

@ShahVandit ShahVandit commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Scope

A standalone Sphinx-Gallery tutorial on sparse-feature interventions in a frozen pretrained REVE (braindecode.models.REVE, brain-bzh/reve-base), using SAE Lens 6.51.3. It adds no SAE implementation, trainer, callback or core dependency to Braindecode. File: examples/advanced_training/plot_sae_reve.py, which replaced the earlier LaBraM version.

  • Real EEG only. Subject 3 of BCI IV 2a (MOABBDataset("BNCI2014_001")). No synthetic or random EEG.
    • REVE's preprocessing: EEG picks, 0.5–99.5 Hz, 200 Hz, then a per-recording channel z-score (Preprocessor(sklearn.preprocessing.scale, channel_wise=True)) clipped at 15 SD (np.clip).
    • Windows are the 4-s motor-imagery periods: 22 channels × 4 patches = 88 tokens of dimension 512.
    • Euclidean alignment with MOABB's EuclideanAlignment(estimator="scm"), fitted once per session on that session's windows, without labels. The head and the SAE are fitted on the training session only, so no test-session statistic enters their fitting. For the test session the alignment is transductive, as in REVE's evaluation; the tutorial says so.
  • Three splits. fit = runs 0–3 of 0train; validation = runs 4–5 of 0train; test = 1test.
  • Model. REVE.from_pretrained("brain-bzh/reve-base", n_outputs=4, n_chans=22, n_times=800, sfreq=200, chs_info=...). The encoder is frozen; only REVE's flattening head (final_layer) is trained, with EEGClassifier on cached last-block tokens (full-batch AdamW, 300 epochs).
  • Token stream. capture_activations / run_with_activation_substitution hook a submodule's output. In REVE, TransformerBackbone.forward computes x = attn(x) + x; x = ff(x) + x, so no submodule returns the stream. A hook on ff sees the update, and a pre-hook on the next block would leave the original tokens in its skip connection. The tutorial therefore uses:
    • token_streams: model(x, return_output=True), batched;
    • run_blocks: resume from a stream through the remaining pretrained blocks and the head. It is checked against model(x): max abs diff 2.2e-05.
    • A new schematic shows streams 0–22 (stream b = output of block b), the read at block 18, the SAE edit, run_blocks through blocks 19–22 and the head, and why hooks cannot reach the stream. Brackets mark what token_streams computes once and what run_blocks recomputes per edit, and the SAE card names the edit of each test (substitute the reconstruction; subtract the decoded removed features).
  • Analyses.
    • Skip-one-block check (validation).
    • Top-K SAE on block-18 tokens with fit-only standardization.
    • Test FVU.
    • Reconstruction substitution vs. untrained-SAE and mean-token controls: a headline figure (FVU, balanced accuracy and agreement for the native model, the trained SAE and both controls) and confusion matrices.
    • Scalp maps of the most class-selective feature per class, selected on fit.
    • Error-preserving removal of each class's 32 selected features vs. 20 random 32-feature sets and the other classes' sets (4×4 matrix), plus the drop on the other classes' trials.
  • Docs CI executes it. sae = ["sae-lens==6.51.3"] extra and sae appended to DOCS_EXTRAS; both hunks are byte-identical to docs: tutorial on SAE activation analysis with optional SAE Lens #1152's. sae is not a core dependency, not in docs and not in all. No docs/conf.py change any more: the find_spec guard was removed (review), and 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 in the prose only. The prose also states that MOABB ≥ 1.6 is needed for EuclideanAlignment; docs CI resolves 1.7.2, and the moabb extra floor was not changed.
  • standardize_and_clip → Preprocessor(standard_scale, channel_wise=True) (as in plot_relative_positioning.py / plot_transfer_learning.py) + np.clip. On session 0 the output is bitwise identical to the old helper, and no sample reaches ±15 SD.
    • np.clip sits in a lambda because MNE's apply_function calls getfullargspec, which rejects numpy 2's dispatcher object. plot_tuh_eeg_corpus.py does the same.
  • to_tensors → skorch SliceDataset + skorch.utils.to_tensor; labels and runs come from get_metadata().
  • Hand-written euclidean_alignment → moabb.datasets.preprocessing.EuclideanAlignment (MOABB ≥ 1.6, from MOABB docs(dance): show the published checkpoint result in the tutorial #1109; also on MOABB develop).
    • estimator="scm" is the sample covariance of He & Wu. MOABB's default Ledoit–Wolf shrinkage targets short or noisy trials, and it moved the aligned data 12% (relative), against 0.7% for scm. The remaining difference is window centring.
  • EA citations, verified on Crossref/doi.org:
    • He, H., & Wu, D. (2020). Transfer Learning for Brain–Computer Interfaces: A Euclidean Space Data Alignment Approach. IEEE TBME 67(2), 399–410. doi:10.1109/TBME.2019.2913914. Crossref dates the issue 2020; the article appeared online in 2019.
    • Junqueira, B., Aristimunha, B., Chevallier, S., & de Camargo, R. Y. (2024). A systematic evaluation of Euclidean alignment with deep learning for EEG decoding. J. Neural Eng. 21(3), 036038. doi:10.1088/1741-2552/ad4f18.
  • scikit-learn for evaluation:
    • balanced_accuracy_score (equal to accuracy here, since the splits are balanced);
    • agreement = accuracy_score(native, edited);
    • FVU = 1 - r2_score(..., multioutput="variance_weighted");
    • ConfusionMatrixDisplay;
    • class selectivity via r_regression (point-biserial; same ranking as the previous standardized mean difference).
  • The accuracy helper, the manual head-training loop, skip_block_predictions, standardize, reconstruct_with, edited_logits and remove_features are gone.
    • The block check uses the cached validation streams.
    • The interventions reuse the cached test codes and reconstructions. This gives the same numbers, with 24 fewer re-encodings.

Remaining helpers and why:

  • token_streams / run_blocks: see the token-stream note above. REVE's stream cannot be read or replaced through a module hook, and no library function resumes a REVE forward pass from an intermediate stream.
  • activation_batches: SAE Lens's SAETrainer takes any iterator of tensor batches, and its ActivationsStore needs a language model. This 3-line generator samples fit tokens with replacement.
  • probability_drops: the removal intervention itself. It zeroes a feature set in the codes, subtracts the decoded contribution, runs run_blocks and returns p and the per-class drops. It is called 24 times.

How the settings were chosen (session 0 only, before any test-session output)

The alignment changed (MOABB EA, which centres each window), so I re-ran the whole selection on the session-0 validation runs. Session 1 was dropped right after loading, and the choices were recorded (20:05 UTC) before any session-1 output of this pipeline existed.

choice candidates, validation split chosen
setup with EA: flatten head 58–64% at 300 epochs over 3 head inits (47–64% over 50–300 epochs); attention pooling 45–50% (300/1000 epochs). Without EA (unaffected, since the preprocessing is bitwise identical): 31–38% and 27–32%. Fine-tuning the last 2 blocks (no EA): ≤ 31% EA + frozen encoder + flatten head (unchanged)
block (SAE 2048, k = 32; blocks followed by ≥ 4 blocks) 6: 46%, 10: 42%, 14: 53%, 18: 73% agreement after substitution 18 (unchanged)
SAE size at block 18 2048/k16: 67%, 2048/k32: 73%, 4096/k32: 79% agreement 4096/k32 (changed from 2048/k32)

Disclosure. The pre-stated rule was "larger only if more than 2 points better". Previously 4096 was 2.08 points ahead, and I had kept 2048 on secondary grounds. Now 4096 is 6.25 points ahead (6 of 96 windows), so the rule selects it, and the tutorial now uses 4096 features. Its secondary costs are stated in the tutorial:

  • FVU 0.371 vs 0.355;
  • 201 vs 5 features inactive on validation;
  • about 1.6–2× the SAE training time.

The 32 features per class and the 20 random sets were fixed in advance. The random sets now come from np.random.default_rng(0) instead of a torch generator, so they are different draws.

Numbers from this run (laptop CPU, one seed); previous head in brackets

  • Balanced accuracy: fit 100% [100%], validation 58.3% [56.2%], test 76.0% [76.0%] (chance 25%).
  • Skip-one-block check (validation, unchanged predictions): block 1 26% [24%], block 9 35% [33%], block 12 57% [53%], blocks 15–22 78–88% [78–88%].
substitution at block 18 test balanced accuracy agreement with native
none (native) 76.0% [76.0%] 100%
trained SAE 72.2% [66.7%] 86.1% [81.2%]
untrained SAE (same init) 25.0% [25.0%] 34.0% [34.4%]
tokens := fit mean 25.0% [25.0%] 34.0% [34.4%]
  • Test FVU: 0.376 [0.361] trained vs 0.999 [1.001] untrained. Active features per token: 32.0 [32.0]. Features never active on fit: 52 of 4096 [6 of 2048].
  • Removing the 32 features selected for a class (drop in p(class) on its test trials):
class own set other classes' sets (mean) random mean / max of 20 own set on other trials class trials flipped
feet 0.062 [0.029] 0.022 [0.013] 0.000 / 0.013 [0.001 / 0.028] 0.010 [0.005] 18.1% [1.4%]
left hand 0.172 [0.204] 0.016 [−0.017] −0.002 / 0.024 [−0.001 / 0.022] 0.039 [0.039] 27.8% [31.9%]
right hand 0.141 [0.109] −0.016 [−0.014] 0.001 / 0.010 [0.002 / 0.015] 0.058 [0.041] 8.3% [5.6%]
tongue 0.196 [0.165] −0.008 [−0.021] 0.002 / 0.012 [0.001 / 0.046] 0.053 [0.047] 13.9% [15.3%]

How to read this:

  • Left hand, right hand, tongue: the own set lowers p(class) by 0.14–0.20. That is far more than every random set (max 0.024) and 2.4–4.4× the drop on the other classes' trials. The other classes' sets change it by less than 0.02 on average.
  • Feet: the own set (0.062) now exceeds every random set (max 0.013). But the 4×4 matrix shows that removing the tongue set lowers p(feet) more (0.10), so the feet features are not specific to feet. The tutorial says this explicitly.
  • Scalp maps: the left-hand feature fires over the right sensorimotor area and the right-hand feature over the left, consistent with contralateral hand motor imagery. The tongue feature is lateral in both hemispheres; the feet map is weak and scattered. This is one feature per class from one subject.
  • The SAE is trained in float32, so the numbers shift slightly with machine and thread count. This demonstrates a workflow and makes no scientific or physiological claim.

Validation (head 89ac394)

  • End-to-end runs, with outbound network blocked (sandbox-exec) and HF_HUB_OFFLINE=1; Python 3.12, PyTorch 2.14.0, SAE Lens 6.51.3, MOABB 1.7.2, CPU, 10 threads.
    • Nothing was downloaded. The MNE data (A03T/A03E, reve_positions.json) and the reve-base cache were unchanged (mtime and size).
    • Wall time was 86.4 s and 104.7 s in two direct runs, with other load on the machine [previously 66.8 s].
    • Peak RSS: 5.6–6.0 GB (macOS) [3.7 GB with 2048 features]. The 4096-feature codes of the 25,344 test tokens are 415 MB per copy; the docs job runs 2 gallery workers per directory.
    • Extra checks:
      • EEGClassifier.predict equals the torch argmax;
      • removing an empty feature set leaves the tokens exactly unchanged;
      • the aligned test session has an identity mean covariance (max deviation 1e-9).
  • Strict single-example Sphinx-Gallery build (sphinx-build -W), with no guard: executed 1/1 in 58.6 s, build succeeded, 0 warnings.
    • The rendered page has the same numbers as the direct run.
    • An earlier identical build took 944.7 s while the laptop was swapping (10.8 GB of swap used by other applications); it gave the same output.
    • The cross-reference labels (finetune-foundation-model, load-pretrained-models) were stubbed; both exist in the docs.
  • Activation tests: 5 passed. Pre-commit on the changed files (ruff, codespell, mypy, …): passed.
  • Grep:
    • no synthetic EEG; the only randomness is torch.randint for SAE batches and default_rng(0) for the random feature-set control;
    • no try:/ImportError;
    • no find_spec/importlib;
    • none of the removed helpers.
  • Merge previews (git merge-tree): master + this PR, master + docs: tutorial on SAE activation analysis with optional SAE Lens #1152, docs: tutorial on SAE activation analysis with optional SAE Lens #1152 + this PR, and master + both in either order are all clean. Both orders give the same tree:
    • one sae line and both changelog entries;
    • a docs/conf.py byte-identical to master.
  • Dependency impact (unchanged): 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). There is one transitive downgrade (fsspec 2026.9.0 → 2026.6.0, capped by datasets), and 42 packages are added. braindecode[all] does not pull sae-lens.
  • Checkpoint. brain-bzh/reve-base is public: the HF API reports gated: false, private: false at sha dc2a075c (checked today). Fork PRs have no HF_TOKEN, so CI execution relies on it staying public. The weights are under the REVE Responsible Use License, which the tutorial mentions.

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

CI

  • Previous head 6c32cf0: build_docs run 36616525126 was still in "Create Docs" when this push was made (20:43 UTC) and was cancelled at 20:44:44 UTC by the workflow's per-PR cancel-in-progress. No log of it is available, so it gives no evidence either way.
  • This head 89ac394, snapshot at 20:44 UTC: docs 36628394569 pending, pre-commit in progress, tests pending, "Check Whats News Changes" passed. The docs build takes about 2 h; nobody is watching it.
  • Head a759d59, snapshot at 21:45 UTC: docs 36635286831 in progress, tests pending, pre-commit and "Check Whats News Changes" passed. Nobody is watching it.

Relationship to #1152

#1152 fits an SAE to a ShallowFBCSPNet trained from scratch and uses the activation hooks. This PR covers a frozen pretrained transformer: which blocks influence the prediction, token features as scalp maps, and error-preserving feature removal with random-feature and other-class controls. Neither tutorial imports or references the other. The CI/extra hunks are identical in both PRs, and neither touches docs/conf.py any more.

Figures (commit 38dbfe2)

One additive commit, plot_sae_reve.py only, restyling the figures as requested in review, with the same style cell as #1152. The PR head is now 911c345, a later merge of master on top of it. That merge does not touch the tutorial, docs/conf.py, pyproject.toml or the workflows.

  • The token-stream schematic stays. Its block panel now marks the update a submodule returns and the + x skip that carries the stream.
  • The block check shows the share of validation decisions that change.
  • The confusion-matrix title compares the agreement with both controls. (Since a759d59 this comparison is the Test 1 headline figure; the confusion title counts the changed decisions.)
  • The scalp maps show the peak channel and scale instead of colorbars, and carry the aligned-virtual-channel caveat on the figure.
  • The removal figure draws all 20 random sets and each other-class set, not only their mean and maximum, and outlines the own-set cells of the 4×4 matrix. It is the thumbnail.
  • All 25 printed lines are identical to 89ac394. Offline end-to-end run: 54.7–57.1 s, peak RSS 5.6 GB. Strict single-example sphinx-build -W: executed 1/1 in 59.4 s with 0 warnings and no matplotlib/mne warnings. I also rendered it with DejaVu only, as CI does. Pre-commit passed.

Narrative and figures (commit a759d59)

One additive commit, plot_sae_reve.py only, on top of 911c345. Text and figures only; no computation changed.

Story. The first paragraph now poses the question: can a sparse dictionary fitted to a frozen pretrained EEG transformer expose features that its classifier actually uses? It splits the question into two tests, and the close answers in the same words: yes, for three of the four classes of this subject and seed.

  1. Does the dictionary preserve what the model computes? Substituting the reconstruction at block 18 keeps 86% of the test decisions (72.2% vs 76.0% balanced accuracy, FVU 0.376). Both controls keep 34%: they collapse to a single class ("all right hand"), and 34% is that class's share of the native predictions.
  2. Does the model use the features selected for a class for that class? For left hand, right hand and tongue, removing the class's own 32 features lowers p(class) by 0.14–0.20. That is more than every random set and every other class's set. The feet set beats every random set, but the tongue set lowers p(feet) more (0.10 vs 0.06).

The tutorial ends on one take-home: read the substitution test first, and call a feature set used for a class only when removing it lowers that class more than random sets and the other classes' sets do.

Structure.

  • Headings state claims: "Every block influences the decision", "The settings were fixed on the training session", "Test 1: the SAE reconstruction preserves most decisions", "The hand features fire over the opposite hemisphere", "Test 2: only the hand and tongue features are specific to their class", and the close "What the two tests show".
  • Each subsection opens with its purpose ("To test whether …, we …"). Controls are stated next to each claim.
  • The bounds are four bullets: interventions describe this model, not physiology; one subject and one seed; the test-session alignment is transductive, but no label or choice uses the test session; the effect of an edit depends on where it is made.
  • Citations are unchanged: He & Wu 2020, Junqueira et al. 2024 (JNE, doi:10.1088/1741-2552/ad4f18), and REVE.

Figures. Each figure answers one question. Every title is computed from the numbers it shows. Colors follow the Braindecode documentation (docs/_static/landing.css): brand blue for the result, ink for the native model, muted slate for controls, red (#b5332e) for the rerun blocks, the other classes' feature sets and negative values in the diverging maps. The cosmetic rcParams block runs inside a sphinx-gallery ignore block.

# Question Change in this commit
1 Where is the stream read and edited, and why not with a hook? Brackets for token_streams (once) and run_blocks (per edit); the edit of each test
2 Which blocks does the decision depend on? unchanged
3 Does the reconstruction preserve the decisions? new: bullet bars for FVU, balanced accuracy and agreement; chance line; single-class controls annotated
4 Which decisions change? Title: "40 of 288 test decisions change with the SAE, 23 of them to left hand"
5 Where do the selected features fire? Title names the hemisphere of each hand feature's peak (right/C4, left/C3). The caveat now reads "an association, not a source map"
6 (thumbnail) Is each class's feature set specific? Adds a specificity-contrast column (own set minus best control: −0.039 / +0.115 / +0.131 / +0.126) and names the set that beats the feet set ("tongue set")

Figure cells now end with plt.show(), so the gallery no longer prints a Text(…) repr under five figures.

Checks.

  • All 25 printed lines of the rendered page are identical to 89ac394.
  • Strict single-example sphinx-build -W, outbound network blocked (sandbox-exec) and HF_HUB_OFFLINE=1: executed 1/1 in 56.6 s, build succeeded, 0 warnings, peak RSS 5.7 GB.
  • The MNE, NEMAR and reve-base caches are unchanged (mtime and size).
  • Pre-commit on the file passed (ruff, codespell, mypy, isort).
  • The prose was checked with the Jean-Rémi King pack gate (validate.py --mode strict), with the 89ac394 prose as the fact list: ACCEPTED, with no fact dropped and none added beyond two printed values (FVU 0.376, 72%). The structure check gave no warning.

@adammounir
adammounir requested a lite review from Copilot August 10, 2026 09:30

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 wasn't able to review any files in this pull request.


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@bruAristimunha
bruAristimunha marked this pull request as draft August 12, 2026 14:08

@bruAristimunha bruAristimunha left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for putting together the public-data experiment. I reviewed the notebook as a Braindecode contribution and against the workflow it cites. This needs a redesign before it is mergeable, so I am moving it back to draft.

The blocking issues are:

  1. Braindecode's authored tutorials are Sphinx-Gallery Python scripts under examples/; the docs workflow generates notebooks from those scripts. A 1.27 MB executed Kaggle notebook under braindecode/mech-interp/ is neither an importable package module nor the project tutorial format. It contains 454 output objects, Papermill/Kaggle/widget metadata, and no Markdown cells. Please move the narrative to a gallery example and strip generated outputs and environment metadata.

  2. The example cannot be part of the normal docs execution path as written. It installs Python and system packages, downloads and extracts the 13.4 GB NMT archive, deletes caches/directories, and defaults FORCE_REBUILD = True. Library documentation must not mutate the environment or delete user data. Use existing Braindecode dataset/download APIs, explicit user-controlled paths and opt-in cleanup, and make the documented data/runtime cost clear. The CI-facing example needs a small bounded or synthetic path; the full experiment can be an explicitly opt-in external reproduction script.

  3. The experiment fails its own stated gate (0.6696 < 0.75) but only prints a warning and continues into SAE training and faithfulness analysis. The downstream interpretation therefore violates the notebook's own precondition. A gate must actually stop/skip the dependent stages.

  4. Do not use held-out test performance to decide whether to continue the analysis. Select architecture, preprocessing, checkpoint, and any performance threshold from training/validation only, then evaluate the test set once. The text says recording-level AUROC is clinically meaningful, but the checkpoint is selected using window-level validation AUROC; use and justify one validation target consistently. Data-dependent scaling constants must also be estimated from the training split only.

  5. Extract reusable behavior (activation capture/substitution and, if this belongs in Braindecode's public API, the Top-K SAE) into normal modules with focused unit tests. The current notebook duplicates capture helpers and leaves core correctness, hook cleanup, checkpoint round-trips, top-k bounds, dead-feature resampling, grouped splitting, and substitution behavior untested.

  6. Record clean-room provenance precisely. The cited companion repository says it is not end-to-end reproducible and is PolyForm Noncommercial, while Braindecode is BSD-3-Clause. Please identify the paper/method sources used for each independently implemented component and confirm that no code was copied or adapted from the noncommercial repository. This is a provenance requirement, not an accusation.

  7. Current pre-commit failures are real: the repository's JSON hook rewrites the entire notebook, and Ruff cannot parse cells 2/3 because of unexpected indentation. A changelog entry is also required.

The useful mergeable shape is: tested reusable code (if an API addition is intended) + a compact Sphinx-Gallery tutorial that runs on a bounded input + a separate, clearly documented opt-in full NMT reproduction path. Please also report results only after the validation gate passes; the current below-gate run should be described as a failed pilot, not evidence that the method reproduces the cited workflow.

@ShahVandit

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha,

The notebook was just for my own runs. I had used Kaggle for prototyping. It’s temporary and not something I’m proposing to merge. The temporary braindecode/mech-interp directory is for the same reason; it’s mainly for demo scripts.

For the library code, I’ve moved the SAE implementation under braindecode/visualization/ following your comments. I feel that a new braindecode/interpretability/ may make more sense, since this goes beyond visualization and the next steps are spectral decoding, TCAV,concept steering and more features. I can move it once we have a better sense of how everything should be organized together. We can also potentially extend this to port transformerlens here.

The example under examples/advanced_training/ uses the published ShallowFBCSPNet checkpoint for BCI IV 2a subject 3, which plot_interpretability.py already loads, so no fine-tuning is needed at doc-build time. It also shows that the method isn’t limited to transformers; here the dictionary decomposes a convolutional feature map. This is mainly a demonstration of the workflow rather than a result; the actual validation is the LaBraM run.

condition AUROC vs baseline
baseline 0.895 —
SAE 0.888 −0.007
random SAE 0.522 −0.373
zeroed layer 0.500 −0.395

sae.py adds a Top-K sparse autoencoder (Gao et al. 2024) with get_config/from_config, a fit_sparse_autoencoder training loop with Anthropic-style dead-feature resampling, sae_diagnostics, and two forward-hook primitives, capture_activations and run_with_activation_substitution, which remove their hooks in a finally block so nothing leaks if the forward pass raises. I've also written tests in test/unit_tests/visualization/test_sae.py.

To validate the method against the paper’s setup (braindecode/mech-interp/validate_sae_labram_nmt.py), I fine-tuned LaBraM on NMT (398 recordings, recording-grouped split) and fit the SAE on layer 11. The fine-tuned baseline is 0.774 window AUROC versus 0.939 reported in the paper. The difference seems expected given that the paper uses a private clinical corpus of 3,036 subjects with 27 channels and 60 s windows, while NMT gives me 398 recordings, 19 channels, and 15 s windows.

E features k dead R² ΔAUROC random SAE
1 200 8 25.0% 0.806 +0.0013 0.483
2 400 16 57.0% 0.871 +0.0017 0.457
4 800 32 71.5% 0.932 +0.0007 0.533
8 1600 64 79.1% 0.976 +0.0008 0.542

Window-level test AUROC; baseline 0.774. The random-SAE column is a same-shape untrained dictionary, i.e. the control.

The main observation here is that faithfulness stays essentially unchanged across an 8× range of dictionary sizes, even though reconstruction R² increases substantially.

I haven’t added api.rst, whats_new.rst, or references.bib yet. I think those can be added later, once we’re sure how all of this combines and what the final structure should look like.

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.
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Thanks for replacing the executed notebook with reviewable Python and focused tests. I re-reviewed the current exact head 6307d53ecafc538cf87cfde805c8e433a51f8da8. The hook cleanup tests and the validation-before-SAE control flow are real improvements, but this still needs to remain draft and should not be repaired as one 2,233-line contribution.

The paper-result gate is not met. The least-cost LaBraM-specific target I could freeze from the cited paper is Figure 2's last transformer block (zero-based layer 11), E=1, k=8: SAE-substituted test AUROC 0.9377 ± 0.0191 across five subject-disjoint folds, against baseline 0.9386 ± 0.0171. This target is not currently externally reproducible: the 3,036-subject BC-1 data, exact fine-tuned LaBraM checkpoints, and SAE caches are private; no immutable split manifest is published; and the paper and its public companion source disagree on the split, fine-tuning schedule, TopK semantics, activation cap, decoder normalization, resampling, evaluation head, and uncertainty calculation.

The NMT run is a useful exploratory pilot toward external validation, but it cannot satisfy that reproduction gate. It changes the cohort, windows, preprocessing, split, checkpoint lineage, and metric protocol. I am therefore not requesting an NMT download or Iceberg run from this PR. A future NMT experiment needs its own immutable inclusion/split/preprocessing/checkpoint manifest and must be labelled external validation.

There are also exact-head blockers independent of the unavailable paper artifacts:

  • On cache-building runs, validate_sae_labram_nmt.py unconditionally overwrites and recursively deletes a user-derived preprocessing directory without proving that this run created and owns it.
  • A stale fine-tuning checkpoint can supply best_valid without binding or re-evaluating the current dataset, split, preprocessing, model/weight revision, seed, or metric definition.
  • Public SAE inputs silently coerce booleans/non-integral dimensions; empty or one-row training and non-finite normalization can emit plausible-looking NaNs; batch_size=0 leaks a low-level error.
  • The group splitter accepts invalid fractions and can silently omit samples whose group is NaN.
  • fit_sparse_autoencoder(seed=...) mutates the caller's process-global PyTorch RNG.
  • The source cites behavior from a PolyForm Noncommercial companion implementation while the proposed files are BSD-3-Clause. Please provide a component-by-component clean-room declaration or BSD-compatible permission before a public SAE implementation is considered.

Please split this maximally instead of expanding it further:

  1. A fresh hook-primitives PR containing only independently sourced, provenance-documented capture_activations, run_with_activation_substitution, cleanup/nested-output tests, and a changelog entry; no SAE, dataset, training loop, or paper claim. The component-level clean-room or permission gate applies to these helpers too. Aim for well under 250 added lines.
  2. A separate, provenance-cleared SAE core with strict finite/type/shape/state contracts and focused tests. It remains paper-gated and should not include an optimizer, dead-feature resampling, diagnostics, splitter, gallery, or data runner.
  3. Training/resampling/diagnostics only after the core contract and paper target are independently qualified.
  4. Keep the full LaBraM/NMT runner outside the package as an opt-in, non-destructive experiment with an immutable manifest. Remove the generic group splitter and network/data-heavy gallery from this PR.

Please also replace the stale PR body: it still describes a removed notebook and an older below-gate run. The current state should be recorded as a draft prototype/external-validation pilot, not a paper reproduction. No spectral decoding, TCAV, steering, or TransformerLens scope should be added while these foundations remain unresolved.

@bruAristimunha

Copy link
Copy Markdown
Collaborator

Exact-head paper/scope audit (6307d53ecafc538cf87cfde805c8e433a51f8da8): SPLIT; keep draft; do not merge this head.

  • The public NMT pilot is workflow transfer, not replication of the EEG-SAE paper result on the private 3,036-subject BC-1 cohort and private fine-tuned checkpoints.
  • The companion EEG-SAE code is PolyForm Noncommercial 1.0.0, while this module declares BSD-3. A clean-room/source-lineage statement is required before extracting reusable code.
  • The driver evaluates the held-out test set throughout the layer/expansion/resampling sweep and accepts unbound caches/checkpoints; select on train/validation and evaluate test exactly once.
  • Keep the 13.4-GB NMT validation external with pinned dataset/checkpoint/environment manifests.
  • Split the library work into a minimal SAE/hook utility with edge tests and a separate bounded gallery that is explicitly a workflow demonstration. The current dead=0.50 output should be described as partial dictionary collapse, not evidence of specialization.

Under the current paper-result-before-merge policy, exact replication is unavailable because the paper data/checkpoints/caches are not released. The draft should remain blocked even if CI is green.

@ShahVandit ShahVandit mentioned this pull request Aug 27, 2026
@ShahVandit

Copy link
Copy Markdown
Contributor Author

the activations PR as requested - #1138

@ShahVandit

ShahVandit commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

The top-k mechanism is Makhzani & Frey (ICLR 2014), which the paper cites as [17]. I'd implement a minimal TopK SAE from those two: encode, decode, config round-trip, decoder normalisation, strict input contracts, and focused tests, with no optimizer, resampling, diagnostics, splitter, or data runner. It would cite neither the reference paper nor its companion code, and would make no claim about that paper's results. Is that an acceptable plan?

An SAE is a trained nn.Module with persisted weights. Should it live in visualization/sae.py following the get_config/from_config pattern from models/base.py, or does it belong in modules/ or a new subpackage? @bruAristimunha

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1120      +/-   ##
==========================================
+ Coverage   87.52%   87.71%   +0.18%     
==========================================
  Files         148      149       +1     
  Lines       17080    17433     +353     
==========================================
+ Hits        14950    15292     +342     
- Misses       2130     2141      +11     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bruAristimunha bruAristimunha changed the title Add LaBraM TopK SAE prototype docs: LaBraM sparse-feature intervention tutorial with optional SAE Lens Sep 29, 2026
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.
@bruAristimunha
bruAristimunha marked this pull request as ready for review September 29, 2026 18:28
Copilot AI lite review requested due to automatic review settings September 29, 2026 18:28

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 review overview

🟢 Approval recommended

The reviewed changes have no unresolved approval-blocking issues.

Review effort: Lite
Findings: None

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.
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.
bruAristimunha added a commit to ShahVandit/braindecode that referenced this pull request Sep 29, 2026
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 bruAristimunha changed the title docs: LaBraM sparse-feature intervention tutorial with optional SAE Lens docs: REVE sparse-feature intervention tutorial with optional SAE Lens Sep 29, 2026
bruAristimunha and others added 7 commits September 29, 2026 22:41
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
- 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.
- 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.
- 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).
…ts 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.
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
* Add a Top-K sparse autoencoder over model activations

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

* Fix sparse autoencoder API formatting

* docs: replace in-tree SAE with optional activation-analysis tutorial

* docs: avoid upstream changelog insertion conflict

* docs: separate SAE entry from concurrent template changelog

* docs: run SAE activation tutorial on real BNCI2014_001 EEG

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).

* docs: keep the SAE module repr out of the rendered tutorial

* ci: install SAE Lens for the docs build so the SAE tutorials execute

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 #1120 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 SAE activation tutorial

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.

* docs: restyle the SAE activation tutorial figures

- 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.

* docs: end SAE tutorial figure cells with plt.show()

The suptitle calls were the last expression in three cells, so
sphinx-gallery printed their Text(...) repr under the figures.

* docs: use the Braindecode palette and simplify the SAE tutorial 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.

* docs: hide the SAE tutorial's matplotlib styling and trim it

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.

* 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]>
@bruAristimunha
bruAristimunha merged commit 017809e into braindecode:master Sep 30, 2026
14 checks passed
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.

3 participants