diff --git a/docs/source/content/hook_system.md b/docs/source/content/hook_system.md index b7b88461f..87290585f 100644 --- a/docs/source/content/hook_system.md +++ b/docs/source/content/hook_system.md @@ -149,6 +149,29 @@ def ablate(z, hook): model.run_with_hooks("text", fwd_hooks=[(f"blocks.{layer}.attn.hook_z", ablate)]) ``` +### Ablate each neuron's central quantile band, keeping its tails + +Thresholds come from each neuron's own activation distribution. `ActivationQuantiles` estimates +per-unit quantiles over a corpus in bounded memory (exact up to `max_samples` rows, a uniform +sample beyond), and `band_ablation_hook` replaces every activation inside `[low, high]` with +`value`, so only firings below `low` or above `high` pass: + +```python +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]) # pass mask= to skip padding positions +low, high = stats.quantiles([0.03, 0.97]) + +logits = model.run_with_hooks( + "text", + fwd_hooks=[(hook_name, band_ablation_hook(low, high))], # or value=stats.mean +) +``` + ### Activation patching (swap an activation from one prompt into another) ```python diff --git a/tests/unit/utilities/test_activation_quantiles.py b/tests/unit/utilities/test_activation_quantiles.py new file mode 100644 index 000000000..7ada0b49b --- /dev/null +++ b/tests/unit/utilities/test_activation_quantiles.py @@ -0,0 +1,204 @@ +"""Checks for streaming per-unit quantiles and the quantile-band ablation hook.""" + +import pytest +import torch +from torch import nn + +from transformer_lens.hook_points import HookPoint +from transformer_lens.HookedRootModule import HookedRootModule +from transformer_lens.utilities import ActivationQuantiles, band_ablation_hook + + +class _Toy(HookedRootModule): + def __init__(self, d: int = 4): + super().__init__() + torch.manual_seed(0) + self.inp = nn.Linear(d, d) + self.hook_post = HookPoint() + self.setup() + self.eval() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.hook_post(self.inp(x)) + + +def test_quantiles_are_exact_below_max_samples_across_batches_and_mask(): + torch.manual_seed(0) + a, b = torch.randn(3, 5, 4), torch.randn(2, 7, 4) + mask = torch.rand(2, 7) > 0.3 + stats = ActivationQuantiles(max_samples=1000) + stats.update(a) + stats.update(b, mask=mask) + rows = torch.cat([a.reshape(-1, 4), b[mask]]) + levels = torch.tensor([0.0, 0.03, 0.5, 0.97, 1.0]) + torch.testing.assert_close(stats.quantiles(levels), torch.quantile(rows, levels, dim=0)) + torch.testing.assert_close(stats.quantiles(0.5), rows.quantile(0.5, dim=0)) + torch.testing.assert_close(stats.mean, rows.mean(0)) + assert stats.n_seen == stats.n_samples == rows.shape[0] + + +def test_sampling_bounds_memory_keeps_real_rows_and_an_exact_mean(): + rows = torch.randn(5000, 3) + stats = ActivationQuantiles(max_samples=500, generator=torch.Generator().manual_seed(0)) + for chunk in rows.split(700): + stats.update(chunk) + assert stats.n_seen == 5000 and stats.n_samples == 500 + sample = stats._sample + assert sample is not None + # Every kept row is an input row, and none is kept twice. + matches = (sample[:, None, :] == rows[None, :, :]).all(-1) + assert (matches.sum(1) == 1).all() and matches.any(0).sum() == 500 + torch.testing.assert_close(stats.mean, rows.mean(0), rtol=1e-5, atol=1e-6) + + +def test_sample_is_uniform_over_the_stream(): + # Bottom-k keys over many small batches should not favour early or late rows. + index = torch.arange(10_000, dtype=torch.float32)[:, None] + kept_means = [] + for seed in range(20): + stats = ActivationQuantiles(max_samples=1000, generator=torch.Generator().manual_seed(seed)) + for chunk in index.split(37): + stats.update(chunk) + assert stats._sample is not None + kept_means.append(stats._sample.mean().item()) + # Mean kept index of a uniform 1000-of-10000 sample: 4999.5 with s.e. ~ 86 per run. + assert abs(sum(kept_means) / len(kept_means) - 4999.5) < 100 + + +def test_sampled_quantiles_are_close_and_reproducible(): + rows = torch.rand(20_000, 2) + q = torch.tensor([0.03, 0.97]) + + def run(seed: int) -> torch.Tensor: + stats = ActivationQuantiles(max_samples=4000, generator=torch.Generator().manual_seed(seed)) + for chunk in rows.split(1000): + stats.update(chunk) + return stats.quantiles(q) + + torch.testing.assert_close(run(1), torch.quantile(rows, q, dim=0), atol=0.02, rtol=0) + torch.testing.assert_close(run(1), run(1)) + + +def test_low_precision_activations_are_accepted(): + x = torch.randn(10, 3).to(torch.bfloat16) + stats = ActivationQuantiles() + stats.update(x) + torch.testing.assert_close(stats.quantiles(0.5), x.float().quantile(0.5, dim=0)) + + +def test_quantiles_input_validation(): + with pytest.raises(ValueError, match="between 1 and"): + ActivationQuantiles(max_samples=0) + with pytest.raises(ValueError, match="between 1 and"): + ActivationQuantiles(max_samples=2**24 + 1) + with pytest.raises(ValueError, match="positive integer"): + ActivationQuantiles(max_samples=True) + stats = ActivationQuantiles() + with pytest.raises(ValueError, match="no activations"): + stats.quantiles(0.5) + with pytest.raises(ValueError, match="no activations"): + stats.mean + with pytest.raises(TypeError, match="floating-point"): + stats.update(torch.ones(2, 3, dtype=torch.long)) + with pytest.raises(ValueError, match="mask"): + stats.update(torch.ones(2, 3), mask=torch.ones(3, dtype=torch.bool)) + with pytest.raises(ValueError, match="mask"): + stats.update(torch.ones(2, 3), mask=torch.ones(2)) + stats.update(torch.ones(2, 3)) + with pytest.raises(ValueError, match="3 units"): + stats.update(torch.ones(2, 4)) + for bad in (1.5, -0.1, float("nan"), torch.tensor([[0.5]])): + with pytest.raises(ValueError): + stats.quantiles(bad) + + +def test_all_masked_batch_is_a_no_op(): + stats = ActivationQuantiles() + stats.update(torch.ones(2, 3), mask=torch.zeros(2, dtype=torch.bool)) + assert stats.n_seen == 0 + with pytest.raises(ValueError, match="no activations"): + stats.quantiles(0.5) + + +def test_band_hook_replaces_inside_inclusive_band_and_keeps_both_tails(): + low = torch.tensor([-1.0, 0.0, 2.0]) + high = torch.tensor([1.0, 0.0, 3.0]) + x = torch.tensor([[-1.0, 0.0, 3.0], [-1.5, 0.1, 1.0], [1.0, -0.1, 2.5]]) + original = x.clone() + out = band_ablation_hook(low, high)(x, hook=None) + expected = torch.tensor([[0.0, 0.0, 0.0], [-1.5, 0.1, 1.0], [0.0, -0.1, 0.0]]) + torch.testing.assert_close(out, expected) + torch.testing.assert_close(x, original) + + +def test_band_hook_scalar_thresholds_and_per_unit_value(): + value = torch.tensor([10.0, 20.0]) + out = band_ablation_hook(-0.5, 0.5, value)(torch.tensor([[0.0, 0.2], [0.9, -0.4]]), hook=None) + torch.testing.assert_close(out, torch.tensor([[10.0, 20.0], [0.9, 20.0]])) + + +def test_band_hook_preserves_dtype(): + x = torch.tensor([[0.25, 4.0]], dtype=torch.bfloat16) + out = band_ablation_hook(torch.tensor([0.0, 0.0]), torch.tensor([1.0, 1.0]))(x, hook=None) + assert out.dtype == torch.bfloat16 + assert out.tolist() == [[0.0, 4.0]] + + +def test_band_hook_does_not_round_scalar_thresholds_to_activation_precision(): + # 0.1001 rounds to bf16's 0.10009765625, which sits below the threshold and must be kept. + x = torch.tensor([[0.10009765625]], dtype=torch.bfloat16) + assert band_ablation_hook(0.1001, 1.0)(x, hook=None).item() == x.item() + assert band_ablation_hook(torch.tensor([0.1001]), 1.0)(x, hook=None).item() == x.item() + # A float64 threshold just above a float32 activation rounds onto it in float32. + x32 = torch.tensor([0.1]) + low64 = x32.double() + 1e-12 + assert band_ablation_hook(low64, 1.0)(x32, hook=None).item() == x32.item() + + +def test_sample_does_not_alias_the_input(): + x = torch.randn(4, 3) + stats = ActivationQuantiles() + stats.update(x) + expected = x.quantile(1.0, dim=0) + x.zero_() + torch.testing.assert_close(stats.quantiles(1.0), expected) + + +def test_band_hook_validation(): + with pytest.raises(ValueError, match="low must be <= high"): + band_ablation_hook(torch.tensor([0.0, 2.0]), torch.tensor([1.0, 1.0])) + with pytest.raises(ValueError, match="finite"): + band_ablation_hook(float("nan"), 1.0) + with pytest.raises(ValueError, match="scalar or a"): + band_ablation_hook(torch.zeros(2, 2), torch.ones(2, 2)) + with pytest.raises(ValueError, match="same number of units"): + band_ablation_hook(torch.zeros(2), torch.ones(3)) + with pytest.raises(ValueError, match="same number of units"): + band_ablation_hook(torch.zeros(3), torch.ones(3), torch.zeros(4)) + hook_fn = band_ablation_hook(torch.zeros(3), torch.ones(3)) + with pytest.raises(ValueError, match="3 units but the activation has 4"): + hook_fn(torch.zeros(2, 4), hook=None) + + +def test_quantiles_then_band_ablation_through_run_with_hooks(): + model = _Toy() + torch.manual_seed(1) + inputs = [torch.randn(3, 5, 4) for _ in range(4)] + stats = ActivationQuantiles() + for x in inputs: + _, cache = model.run_with_cache(x, names_filter="hook_post") + stats.update(cache["hook_post"]) + low, high = stats.quantiles([0.1, 0.9]) + + x = inputs[0] + clean = model(x) + ablated = model.run_with_hooks(x, fwd_hooks=[("hook_post", band_ablation_hook(low, high))]) + tail = (clean < low) | (clean > high) + assert tail.any() and (~tail).any() + torch.testing.assert_close(ablated[tail], clean[tail]) + assert (ablated[~tail] == 0).all() + + mean_ablated = model.run_with_hooks( + x, fwd_hooks=[("hook_post", band_ablation_hook(low, high, stats.mean))] + ) + torch.testing.assert_close(mean_ablated[~tail], stats.mean.expand_as(clean)[~tail]) diff --git a/transformer_lens/utilities/__init__.py b/transformer_lens/utilities/__init__.py index 7be8faef1..ebdfe82a2 100644 --- a/transformer_lens/utilities/__init__.py +++ b/transformer_lens/utilities/__init__.py @@ -8,6 +8,7 @@ softcap_enabled, solu, ) +from .activation_quantiles import ActivationQuantiles, band_ablation_hook from .attribute_utils import get_nested_attr, set_nested_attr from .components_utils import get_act_name from .defaults_utils import ( diff --git a/transformer_lens/utilities/activation_quantiles.py b/transformer_lens/utilities/activation_quantiles.py new file mode 100644 index 000000000..db31fad18 --- /dev/null +++ b/transformer_lens/utilities/activation_quantiles.py @@ -0,0 +1,219 @@ +"""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. :class:`ActivationQuantiles` estimates them in bounded memory over +any number of batches; :func:`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. +""" + +from __future__ import annotations + +from typing import Callable, Optional, Sequence, Union + +import torch +from jaxtyping import Float + +from transformer_lens.hook_points import HookPoint + +Threshold = Union[float, torch.Tensor] + +_MAX_QUANTILE_INPUT = 2**24 + + +class ActivationQuantiles: + """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 :meth:`quantiles` is exact; + beyond that it is computed on the sample. :attr:`mean` is always exact over every row seen. + The sample is ``max_samples × d`` float32 values on the device of the first batch, and + :meth:`update` and :meth:`quantiles` briefly need about twice that. A NaN activation makes + its unit's quantiles and mean NaN. + + 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]) + """ + + def __init__(self, max_samples: int = 100_000, *, generator: Optional[torch.Generator] = None): + """ + Args: + 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. + """ + if isinstance(max_samples, bool) or not isinstance(max_samples, int): + raise ValueError(f"max_samples must be a positive integer, got {max_samples!r}") + if not 1 <= max_samples <= _MAX_QUANTILE_INPUT: + raise ValueError( + f"max_samples must be between 1 and {_MAX_QUANTILE_INPUT}, got {max_samples}" + ) + if generator is not None and generator.device.type != "cpu": + raise ValueError(f"generator must be a CPU generator, got {generator.device}") + self.max_samples = max_samples + self.generator = generator + self.n_seen = 0 + self._sample: Optional[torch.Tensor] = None + # Rows are kept by smallest random key (bottom-k sampling): a uniform sample of the stream. + # Keys and the running sum stay on CPU in float64, which MPS does not support. + self._keys: Optional[torch.Tensor] = None + self._sum: Optional[torch.Tensor] = None + + def update( + self, + activations: torch.Tensor, + mask: Optional[torch.Tensor] = None, + ) -> None: + """Add a batch of activations; every dimension but the last indexes rows. + + Args: + 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. + """ + if not isinstance(activations, torch.Tensor) or not activations.is_floating_point(): + raise TypeError("activations must be a floating-point tensor") + if activations.ndim == 0: + raise ValueError("activations need a last dimension indexing units") + rows = activations.detach().reshape(-1, activations.shape[-1]) + if mask is not None: + if mask.dtype != torch.bool or mask.shape != activations.shape[:-1]: + raise ValueError( + f"mask must be a bool tensor of shape {tuple(activations.shape[:-1])}, " + f"got {mask.dtype} of shape {tuple(mask.shape)}" + ) + rows = rows[mask.reshape(-1).to(rows.device)] + if self._sample is not None: + if rows.shape[-1] != self._sample.shape[-1]: + raise ValueError( + f"expected {self._sample.shape[-1]} units per row, got {rows.shape[-1]}" + ) + rows = rows.to(self._sample.device) + if rows.shape[0] == 0: + return + # Copy, so the sample never aliases a tensor the caller may reuse or edit. + rows = rows.to(torch.float32, copy=True) + + keys = torch.rand(rows.shape[0], generator=self.generator, dtype=torch.float64) + batch_sum = rows.sum(0).cpu().double() + if self._sample is None or self._keys is None or self._sum is None: + sample, all_keys = rows, keys + self._sum = batch_sum + else: + sample = torch.cat([self._sample, rows]) + all_keys = torch.cat([self._keys, keys]) + self._sum += batch_sum + if sample.shape[0] > self.max_samples: + keep = all_keys.topk(self.max_samples, largest=False).indices + sample, all_keys = sample[keep.to(sample.device)], all_keys[keep] + self._sample, self._keys = sample, all_keys + self.n_seen += rows.shape[0] + + @property + def n_samples(self) -> int: + """Number of rows currently in the sample (``min(n_seen, max_samples)``).""" + return 0 if self._sample is None else self._sample.shape[0] + + @property + def mean(self) -> Float[torch.Tensor, "d"]: + """Exact per-unit mean over every row seen, e.g. a value for mean-ablation.""" + if self._sum is None or self._sample is None: + raise ValueError("no activations have been added yet") + return (self._sum / self.n_seen).to(self._sample.device, torch.float32) + + def quantiles(self, q: Union[float, Sequence[float], torch.Tensor]) -> torch.Tensor: + """Per-unit quantiles at levels ``q`` in ``[0, 1]``, linearly interpolated. + + Returns: + Shape ``[d]`` for a scalar ``q``, otherwise ``[len(q), d]``. + """ + if self._sample is None: + raise ValueError("no activations have been added yet") + levels = torch.as_tensor(q, dtype=self._sample.dtype, device=self._sample.device) + if levels.ndim > 1: + raise ValueError("q must be a scalar or one-dimensional") + if not bool(((levels >= 0) & (levels <= 1)).all()): + raise ValueError(f"quantile levels must be in [0, 1], got {q!r}") + return torch.quantile(self._sample, levels, dim=0) + + +def band_ablation_hook( + low: Threshold, + high: Threshold, + value: Threshold = 0.0, +) -> Callable[..., torch.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 :class:`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. + + Args: + low: Lower edge of the band: a float, or a tensor of shape ``[d]`` (one per unit). + high: Upper edge, same form as ``low`` and ``>= low`` everywhere. + value: Replacement inside the band: a float or a ``[d]`` tensor, e.g. + :attr:`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.]]) + """ + low_t, high_t, value_t = (torch.as_tensor(t) for t in (low, high, value)) + for name, t in (("low", low_t), ("high", high_t), ("value", value_t)): + if t.ndim > 1: + raise ValueError(f"{name} must be a scalar or a [d] tensor, got shape {tuple(t.shape)}") + if not bool(torch.isfinite(t).all()): + raise ValueError(f"{name} must be finite") + sizes = {t.shape[0] for t in (low_t, high_t, value_t) if t.ndim == 1} + if len(sizes) > 1: + raise ValueError(f"low, high and value must have the same number of units, got {sizes}") + if not bool((low_t.cpu() <= high_t.cpu()).all()): + raise ValueError("low must be <= high for every unit") + + def hook_fn(activation: torch.Tensor, hook: Optional[HookPoint]) -> torch.Tensor: + d = activation.shape[-1] + for name, t in (("low", low_t), ("high", high_t), ("value", value_t)): + if t.ndim == 1 and t.shape[0] != d: + raise ValueError(f"{name} has {t.shape[0]} units but the activation has {d}") + # Compare in at least float32 so thresholds are not rounded to a bf16/fp16 grid. + dtype = torch.promote_types(activation.dtype, torch.float32) + dtype = torch.promote_types(dtype, torch.promote_types(low_t.dtype, high_t.dtype)) + x = activation.to(dtype) + inside = (x >= low_t.to(activation.device, dtype)) & ( + x <= high_t.to(activation.device, dtype) + ) + fill = value_t.to(device=activation.device, dtype=activation.dtype) + return torch.where(inside, fill, activation) + + return hook_fn