Skip to content

Activation hooks - #1138

Merged
bruAristimunha merged 5 commits into
braindecode:masterfrom
ShahVandit:activation-hooks
Aug 31, 2026
Merged

bruAristimunha merged 5 commits into
braindecode:masterfrom
ShahVandit:activation-hooks

Conversation

@ShahVandit

Copy link
Copy Markdown
Contributor

Adds two forward-hook primitives to braindecode.visualization:

  • capture_activations(model, x, layers, ...) — records what one or more submodules emitted during a forward pass. A single module, a list, or a dict of modules is accepted; tuple and dict outputs keep their structure.
  • run_with_activation_substitution(model, x, layer, substitute_fn, ...) — replaces a module's output so everything downstream runs on the substitute. This is how a layer is ablated, or a stand-in representation tested.

Hooks are registered immediately before the forward pass and removed in a finally block, so a raising forward pass cannot leave them attached to the model.

Braindecode currently has no helper for reading or replacing an intermediate representation — attribution.py delegates its hook handling to captum, and the models expose only final-layer features via return_features=True. These two functions fill that gap and depend on nothing beyond torch.

Scope

This is the first of the split @bruAristimunha asked for in #1120. It contains only the hook primitives, their tests, and a changelog entry, no SAE, no dataset, no training loop, and no paper claim. The remaining pieces stay in that draft and are not proposed here.

On the lineage question raised there: both functions were written against the public register_forward_hook contract in the PyTorch documentation and are not derived from any third-party implementation. The companion code for arXiv:2605.13930 captures activations through a stateful ActivationExtractor class with a manually invoked remove_hooks(); these are plain functions with try/finally cleanup and were not modelled on it.

Two silent failure modes are rejected rather than tolerated

Both were reachable in the first draft of this module and both would produce plausible-looking output:

  • substitute_fn returning None raises TypeError. Torch treats a None hook return as "keep the original output", so forgetting the return gave a full run with no substitution and an unchanged metric.
  • capture_activations raises RuntimeError if a requested module never ran, and names it.

A module called more than once in a single pass keeps only its last output; that is documented rather than rejected.

Tests

test/unit_tests/visualization/test_activations.py, 6 tests / 15 cases, ~9 s.

The main test is a round trip on a real model: capture a layer's activation, feed that exact value back in through the substitution hook, and require the model output to be unchanged. It then substitutes a perturbed activation and requires the output to change — the round trip alone cannot distinguish a working substitution from a hook that never fires, since both leave the output untouched.

It runs against two topologies:

id model hooked module
cnn ShallowFBCSPNet conv_nonlin_exp, a top-level child
residual EEGConformer transformer.0.0, a residual block three levels deep, with a second residual block and the head still downstream

Both are bit-exact on the round trip.

Also covered: tuple and dict outputs keep their structure and are detached through the container; detach=False leaves the graph intact and a gradient flows; hooks are removed when the forward raises and when substitute_fn itself raises; and the two rejections above.

Test inputs are drawn from a local torch.Generator rather than torch.manual_seed, so they do not reseed the process-global RNG for tests that run afterwards.

Unrelated one-line fix

The last commit corrects my author email in braindecode/visualization/attribution.py (shahvandit@ → shahvanditt@).

Adds capture_activations and run_with_activation_substitution to
braindecode.visualization, built directly on register_forward_hook. Hooks
are removed in a finally block so a raising forward pass cannot leave them
attached. Nested tuple and dict outputs keep their structure.
Replace shape-only assertions with value-based ones: a round-trip on
ShallowFBCSPNet that feeds a captured activation back in and requires the
output to be unchanged, and a hand-computed substitution result. Adds dict
outputs and a raising substitute_fn, and drops the tests that only checked
keys and shapes.
A substitute_fn returning None left the module's own output in place, so a
missing return ran to completion and reported an unchanged metric as
though the substitution had happened; it now raises. A requested module
that never ran was dropped from the result dict, deferring the failure to
whoever first indexed the missing key; capture now raises and names it.

Tests draw from a local generator instead of reseeding the global RNG, and
the round-trip runs on an EEGConformer residual block as well as a
convolutional stack.
@ShahVandit

Copy link
Copy Markdown
Contributor Author

This PR only adds the two hook functions, capture_activations and run_with_activation_substitution. Neither is related to visualization. The subpackage docstring says "Functions for visualisations, especially of the ConvNets", and these functions produce nothing visual. I put them in visualization/ only because that is where the interpretability code currently lives. Should they go in modules/ or somewhere else instead?

@bruAristimunha
bruAristimunha merged commit 59a1e8b into braindecode:master Aug 31, 2026
9 of 10 checks passed
@bruAristimunha

Copy link
Copy Markdown
Collaborator

Thank you @ShahVandit!

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