Skip to content

Add ActivationQuantiles and band_ablation_hook for per-neuron quantile-band ablation - #2059

Open
albertlieyingadrian wants to merge 1 commit into
TransformerLensOrg:devfrom
albertlieyingadrian:feat/neuron-quantile-band-ablation
Open

albertlieyingadrian wants to merge 1 commit into
TransformerLensOrg:devfrom
albertlieyingadrian:feat/neuron-quantile-band-ablation

Conversation

@albertlieyingadrian

@albertlieyingadrian albertlieyingadrian commented Nov 26, 2026 •

Copy link
Copy Markdown

Description

Adds two small, model-agnostic helpers to transformer_lens.utilities for working with a hook's units (e.g. MLP neurons at blocks.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]; mean is the exact per-unit mean over every row seen. It keeps a uniform sample without replacement of at most max_samples rows (bottom-k random keys), so quantiles are exact until more than max_samples rows 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_samples is capped at 2**24, the largest input torch.quantile accepts.
  • band_ablation_hook(low, high, value=0.0): returns a forward hook that replaces activations with low[i] <= x <= high[i] by value (a float or a [d] tensor such as stats.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:

from transformer_lens.utilities import ActivationQuantiles, band_ablation_hook

hook_name = f"blocks.{layer}.mlp.hook_post"
stats = ActivationQuantiles(max_samples=50_000)
for tokens in batches:
    _, cache = model.run_with_cache(tokens, names_filter=hook_name)
    stats.update(cache[hook_name])
low, high = stats.quantiles([0.03, 0.97])
logits = model.run_with_hooks("text", fwd_hooks=[(hook_name, band_ablation_hook(low, high))])

References for the method (per-neuron percentile thresholds and ablating the central band):

The same pattern is added to docs/source/content/hook_system.md under "Common patterns". No existing API changes. No new dependencies.

Type of change

  • New feature (non-breaking change which adds functionality)

Testing

  • New tests/unit/utilities/test_activation_quantiles.py (14 tests plus 2 doctests in the new module; synthetic tensors plus a small HookedRootModule; 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-end run_with_cache then run_with_hooks round trip with zero and mean replacement.
  • The aliasing and threshold-rounding tests fail on an earlier draft of this code and pass now.
  • Before and after this change: pytest tests/unit/utilities tests/unit/test_hook_points.py tests/unit/test_utils.py gave 518 passed on dev; with the new test file and module doctests added, 534 passed on this branch (518 + 14 + 2). make unit-test on this branch: 8414 passed, 59 skipped, 3 xfailed, 0 failed.
  • make check-format and uv run mypy . are clean.
  • A manual check on TransformerBridge with Qwen2.5-0.5B-Instruct (SwiGLU, d_mlp 4864) on CPU worked end to end at blocks.10.mlp.hook_post. A manual check on MPS: update, quantiles, mean and the hook all ran on mps tensors.

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not rewritten tests relating to key interfaces which would affect backward compatibility

cc @jlarson4: happy to adjust the API or move this elsewhere if you'd prefer.

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

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

1 participant