Repository navigation
Activation hooks - #1138
Merged
Merged
Activation hooks#1138
Conversation
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.
This was referenced Aug 27, 2026
Contributor
Author
|
This PR only adds the two hook functions, |
Collaborator
|
Thank you @ShahVandit! |
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.
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
finallyblock, 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.pydelegates its hook handling to captum, and the models expose only final-layer features viareturn_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_hookcontract in the PyTorch documentation and are not derived from any third-party implementation. The companion code for arXiv:2605.13930 captures activations through a statefulActivationExtractorclass with a manually invokedremove_hooks(); these are plain functions withtry/finallycleanup 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_fnreturningNoneraisesTypeError. Torch treats aNonehook return as "keep the original output", so forgetting thereturngave a full run with no substitution and an unchanged metric.capture_activationsraisesRuntimeErrorif 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:
cnnShallowFBCSPNetconv_nonlin_exp, a top-level childresidualEEGConformertransformer.0.0, a residual block three levels deep, with a second residual block and the head still downstreamBoth are bit-exact on the round trip.
Also covered: tuple and dict outputs keep their structure and are detached through the container;
detach=Falseleaves the graph intact and a gradient flows; hooks are removed when the forward raises and whensubstitute_fnitself raises; and the two rejections above.Test inputs are drawn from a local
torch.Generatorrather thantorch.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@).