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:
objectStreaming per-unit quantiles of activations whose last dimension indexes units.
Keeps a uniform random sample (without replacement) of at most
max_samplesrows, where a row is one unit vector such as one token’sd_mlpneuron activations. While no more thanmax_samplesrows have been seen the sample is every row, soquantiles()is exact; beyond that it is computed on the sample.meanis always exact over every row seen. The sample ismax_samples × dfloat32 values on the device of the first batch; at peak,update()holds about three times that in total andquantiles()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 inputtorch.quantileaccepts).generator – CPU generator for the sampling keys, for reproducible estimates once more than
max_samplesrows have been seen. Defaults to torch’s global generator, whichupdatethen 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
qin[0, 1], linearly interpolated.- Returns:
Shape
[d]for a scalarq, 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 isFalse(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
xof unitiis replaced byvaluewhenlow[i] <= x <= high[i], so only the firings belowlowor abovehighpass through. Withlowandhighat each neuron’s 3rd and 97th percentiles (fromActivationQuantiles) 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).-infablates everything up tohigh.high – Upper edge, same form as
lowand>= loweverywhere.infablates everything fromlowup.value – Replacement inside the band: a float or a
[d]tensor, e.g.ActivationQuantiles.meanfor mean-ablation. Defaults to0.0.
- Returns:
A hook function for
run_with_hooks/add_hookat 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.]])