transformer_lens.utilities.activation_quantiles module

Per-unit activation quantiles over a corpus, and a hook that ablates a quantile band.

Each unit at a hook (e.g. each MLP neuron at blocks.N.mlp.hook_post) gets thresholds from its own activation distribution. ActivationQuantiles estimates them in bounded memory over any number of batches; band_ablation_hook() then replaces every activation inside its unit’s central band (say between the unit’s 3rd and 97th percentiles) and keeps only the tails, on either sign.

class transformer_lens.utilities.activation_quantiles.ActivationQuantiles(max_samples: int = 100000, *, generator: Generator | None = None)

Bases: object

Streaming per-unit quantiles of activations whose last dimension indexes units.

Keeps a uniform random sample (without replacement) of at most max_samples rows, where a row is one unit vector such as one token’s d_mlp neuron activations. While no more than max_samples rows have been seen the sample is every row, so quantiles() is exact; beyond that it is computed on the sample. mean is always exact over every row seen. The sample is max_samples × d float32 values on the device of the first batch; at peak, update() holds about three times that in total and quantiles() about four times. A NaN activation makes its unit’s mean NaN from then on, and its unit’s quantiles NaN while the row holding it is in the sample.

Examples

>>> import torch
>>> from transformer_lens.utilities import ActivationQuantiles
>>> stats = ActivationQuantiles(max_samples=1000)
>>> stats.update(torch.arange(10.0).reshape(5, 2))  # 5 rows, 2 units
>>> stats.quantiles([0.0, 0.5, 1.0])
tensor([[0., 1.],
        [4., 5.],
        [8., 9.]])
>>> stats.mean
tensor([4., 5.])

With a model, update from the cache batch by batch, passing the attention mask so padding positions are left out:

stats = ActivationQuantiles(max_samples=50_000)
for tokens, attention_mask in batches:
    _, cache = model.run_with_cache(tokens, names_filter=hook_name)
    stats.update(cache[hook_name], mask=attention_mask.bool())
low, high = stats.quantiles([0.03, 0.97])
__init__(max_samples: int = 100000, *, generator: Generator | None = None)
Parameters:
  • max_samples – Maximum number of rows kept for the quantile estimate, at most 2**24 (the largest input torch.quantile accepts).

  • generator – CPU generator for the sampling keys, for reproducible estimates once more than max_samples rows have been seen. Defaults to torch’s global generator, which update then advances.

property mean: Float[Tensor, 'd']

Exact per-unit mean over every row seen, e.g. a value for mean-ablation.

property n_samples: int

Number of rows currently in the sample (min(n_seen, max_samples)).

quantiles(q: float | Sequence[float] | Tensor) → Tensor

Per-unit quantiles at levels q in [0, 1], linearly interpolated.

Returns:

Shape [d] for a scalar q, otherwise [len(q), d].

update(activations: Tensor, mask: Tensor | None = None) → None

Add a batch of activations; every dimension but the last indexes rows.

Parameters:
  • activations – Floating-point activations, e.g. [batch, pos, d_mlp].

  • mask – Optional boolean tensor of shape activations.shape[:-1]; rows where it is False (such as padding positions) are skipped.

transformer_lens.utilities.activation_quantiles.band_ablation_hook(low: float | Tensor, high: float | Tensor, value: float | Tensor = 0.0) → Callable[[...], Tensor]

Forward hook that replaces activations inside a per-unit band and keeps the tails.

An activation x of unit i is replaced by value when low[i] <= x <= high[i], so only the firings below low or above high pass through. With low and high at each neuron’s 3rd and 97th percentiles (from ActivationQuantiles) this keeps each neuron’s strongest firings of both signs. The input is not modified in place, so a tensor already stored in a cache stays intact.

Parameters:
  • low – Lower edge of the band: a float, or a tensor of shape [d] (one per unit). -inf ablates everything up to high.

  • high – Upper edge, same form as low and >= low everywhere. inf ablates everything from low up.

  • value – Replacement inside the band: a float or a [d] tensor, e.g. ActivationQuantiles.mean for mean-ablation. Defaults to 0.0.

Returns:

A hook function for run_with_hooks / add_hook at a hook whose last dimension indexes the same units, e.g. blocks.N.mlp.hook_post.

Examples

>>> import torch
>>> from transformer_lens.utilities import band_ablation_hook
>>> hook_fn = band_ablation_hook(torch.tensor([-1.0, 0.0]), torch.tensor([1.0, 2.0]))
>>> hook_fn(torch.tensor([[-3.0, 1.0], [0.5, 5.0]]), hook=None)
tensor([[-3.,  0.],
        [ 0.,  5.]])