Repository navigation
Add ActivationQuantiles and band_ablation_hook for per-neuron quantile-band ablation - #2059
Open
albertlieyingadrian wants to merge 1 commit into
Conversation
ActivationQuantiles streams per-unit quantiles of a hook's activations over many batches in bounded memory (exact up to max_samples rows, a uniform bottom-k sample beyond) with an exact running mean. band_ablation_hook replaces activations inside a per-unit [low, high] band and keeps the tails, e.g. ablating each MLP neuron's p3-p97 band at mlp.hook_post.
This branch has not been deployed
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.
Description
Adds two small, model-agnostic helpers to
transformer_lens.utilitiesfor working with a hook's units (e.g. MLP neurons atblocks.N.mlp.hook_post) in each unit's own activation basis:ActivationQuantiles(max_samples=100_000, *, generator=None): streaming per-unit quantiles over any number of batches in bounded memory.update(activations, mask=None)takes[..., d]activations (the optional bool mask drops rows such as padding positions);quantiles(q)returns[d]or[len(q), d];meanis the exact per-unit mean over every row seen. It keeps a uniform sample without replacement of at mostmax_samplesrows (bottom-k random keys), so quantiles are exact until more thanmax_samplesrows have been seen and come from the sample after that. Keys and the running sum stay on CPU in float64, so it works on CUDA, CPU and MPS.max_samplesis capped at2**24, the largest inputtorch.quantileaccepts.band_ablation_hook(low, high, value=0.0): returns a forward hook that replaces activations withlow[i] <= x <= high[i]byvalue(a float or a[d]tensor such asstats.mean) and keeps the tails on both signs. It does not modify the input in place, so cached tensors stay intact. It compares in at least float32, so scalar thresholds are not rounded to a bf16/fp16 grid, and it returns the activation's dtype.Motivation: neuron-level analyses often threshold each neuron against its own distribution, e.g. keeping only firings above a neuron's 97th percentile or below its 3rd and ablating the central band, rather than using one global threshold. Today that means collecting the activations, holding all of them in memory to call
torch.quantile, and writing a custom hook. These two helpers cover the common path:References for the method (per-neuron percentile thresholds and ablating the central band):
The same pattern is added to
docs/source/content/hook_system.mdunder "Common patterns". No existing API changes. No new dependencies.Type of change
Testing
tests/unit/utilities/test_activation_quantiles.py(14 tests plus 2 doctests in the new module; synthetic tensors plus a smallHookedRootModule; no model loads). It covers exact quantiles and mean across batches with a mask; the bounded sample holding only real rows, with no duplicates; uniformity across many small batches; sampled quantiles within 0.02 of the true ones, reproducible with a generator; bf16 input; the inclusive band edges and both tails; per-unit replacement values; dtype preservation; no rounding of thresholds to the activation's precision (scalar vs bf16, float64 vs float32); no aliasing of the caller's tensor; input validation; and an end-to-endrun_with_cachethenrun_with_hooksround trip with zero and mean replacement.pytest tests/unit/utilities tests/unit/test_hook_points.py tests/unit/test_utils.pygave 518 passed ondev; with the new test file and module doctests added, 534 passed on this branch (518 + 14 + 2).make unit-teston this branch: 8414 passed, 59 skipped, 3 xfailed, 0 failed.make check-formatanduv run mypy .are clean.TransformerBridgewith Qwen2.5-0.5B-Instruct (SwiGLU,d_mlp4864) on CPU worked end to end atblocks.10.mlp.hook_post. A manual check on MPS:update,quantiles,meanand the hook all ran onmpstensors.Checklist:
cc @jlarson4: happy to adjust the API or move this elsewhere if you'd prefer.