Coverage for transformer_lens/tools/analysis/interchange.py: 100%
233 statements
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
1"""Interchange interventions on linear subspaces.
3An interchange intervention runs the model on a *base* input while setting the base's activation
4at one hook point, inside a subspace, to its value on a *source* input::
6 h' = h_base + strength * (h_source - h_base) @ B @ B.T
8``B`` is an orthonormal ``[d_model, rank]`` basis, the convention of
9:func:`~transformer_lens.tools.analysis.projection_kernel.orthonormal_subspace`. The base keeps its
10own coordinates outside the subspace. If the model then produces the output a high-level causal
11model predicts for the base with one variable taken from the source, the subspace carries that
12variable at that hook point (Geiger et al., 2021).
14The module provides the intervention, fixed-direction bases to intervene on (the difference of
15class means, a linear probe's weights, a random basis), and a norm-matched random-subspace placebo.
16:func:`neuron_basis` turns a set of MLP neurons, such as the features a sparse probe selects, into a
17basis, and :func:`random_neuron_basis` draws random neurons as its placebo.
18:func:`fit_das` learns the basis instead, by distributed alignment search (DAS; Geiger et al.,
192024): it trains an orthonormal basis so that the interchange produces the high-level model's
20predicted outputs.
22An interchange accuracy is not evidence on its own. DAS fits arbitrary label mappings and finds
23effects in randomly initialised models (Arora et al., 2024), so the module also provides the
24controls to train the same way: :func:`arbitrary_targets` for an arbitrary-label control, and
25:func:`random_init_bridge` or :func:`reinitialized` for an untrained copy of the model. Compare a
26learned subspace with both, and with the placebo and the baselines.
28Works with any model exposing the hook API (``TransformerBridge`` or a ``HookedRootModule``).
29Activations at the hook must be ``[batch, d_model]``, or ``[batch, pos, d_model]`` with one
30position index per example.
31"""
33from __future__ import annotations
35import copy
36import hashlib
37from dataclasses import dataclass
38from typing import Any, Callable, Hashable, Iterator, Optional, Sequence, Union, cast
40import numpy as np
41import torch
42import torch.nn.functional as F
43from jaxtyping import Float, Int
44from torch import nn
45from torch.nn.utils.parametrizations import orthogonal
47from transformer_lens.tools.analysis._model_state import (
48 compute_dtype,
49 require_eval_mode,
50)
51from transformer_lens.tools.analysis.projection_kernel import orthonormal_subspace
53TaskLogits = Callable[[torch.Tensor], Float[torch.Tensor, "batch n_classes"]]
54"""Runs the model on a batch of inputs in one forward pass and returns task logits, e.g.
55``lambda tokens: model(tokens)[:, -1, answer_token_ids]``."""
57Intervention = Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
58"""Maps (base activations, source activations), both ``[batch, d_model]``, to new base activations."""
61def random_basis(d_model: int, rank: int, seed: int) -> Float[torch.Tensor, "d_model rank"]:
62 """A seeded random orthonormal basis: the baseline any aligned basis should beat.
64 Args:
65 seed: Seed for the Gaussian matrix the basis is drawn from.
67 Returns:
68 Orthonormal basis, ``[d_model, rank]``.
69 """
70 generator = torch.Generator().manual_seed(seed)
71 return orthonormal_subspace(torch.randn(d_model, rank, generator=generator), rank=rank).basis
74def mean_difference_basis(
75 activations: Float[torch.Tensor, "batch d_model"], labels: Sequence[Hashable]
76) -> Float[torch.Tensor, "d_model rank"]:
77 """The span of the centred class means: for two classes, the difference-in-means direction.
79 Args:
80 activations: Activations, one row per example.
81 labels: The variable's value for each example; at least two distinct values.
83 Returns:
84 Orthonormal basis of rank ``n_classes - 1``, ``[d_model, n_classes - 1]``.
86 Raises:
87 ValueError: If fewer than two classes are present.
88 """
89 values = np.asarray(labels)
90 classes = np.unique(values)
91 if len(classes) < 2:
92 raise ValueError("mean_difference_basis needs at least two classes")
93 acts = activations.float().cpu()
94 means = torch.stack([acts[torch.as_tensor(values == c)].mean(0) for c in classes])
95 return orthonormal_subspace((means - means.mean(0)).T, rank=len(classes) - 1).basis
98def probe_basis(
99 weights: Float[torch.Tensor, "n_rows d_model"],
100) -> Float[torch.Tensor, "d_model rank"]:
101 """The directions of a linear probe's weights, in activation space.
103 Undo any input scaling first: for a probe fit on standardised inputs, divide each weight by its
104 feature's standard deviation.
106 Args:
107 weights: Probe weights; one row for a binary probe, one row per class otherwise.
109 Returns:
110 Orthonormal basis: the weight direction for one row, the span of the centred rows (rank
111 ``n_rows - 1``) for several.
112 """
113 w = torch.as_tensor(weights, dtype=torch.float32)
114 if w.shape[0] == 1:
115 return orthonormal_subspace(w.T, rank=1).basis
116 return orthonormal_subspace((w - w.mean(0)).T, rank=w.shape[0] - 1).basis
119Neurons = Union[Sequence[int], np.ndarray, torch.Tensor]
120"""Integer neuron indices: a list, a NumPy array, or a tensor such as a sparse probe's
121``selected_features``."""
124def neuron_basis(d_mlp: int, neurons: Neurons) -> Float[torch.Tensor, "d_mlp k"]:
125 """The coordinate basis of a set of MLP neurons, e.g. the features a sparse probe selects.
127 Interchanging it sets exactly those neurons to the source's values, at a neuron hook such as
128 ``blocks.N.mlp.hook_post``. Compare it with :func:`random_neuron_basis` of the same size: a random
129 direction is the wrong placebo for a claim about neurons, because it spreads over every neuron.
131 Args:
132 d_mlp: Number of neurons at the hook.
133 neurons: Integer indices of the neurons, each in ``[0, d_mlp)`` and none repeated.
135 Returns:
136 Orthonormal basis of unit vectors, ``[d_mlp, k]``, in the order given.
138 Raises:
139 ValueError: If no neuron is given, or an index is not an integer, out of range or repeated.
140 """
141 index = _neuron_indices(d_mlp, neurons)
142 if index.numel() == 0:
143 raise ValueError("neuron_basis needs at least one neuron")
144 basis = torch.zeros(d_mlp, index.numel())
145 basis[index, torch.arange(index.numel())] = 1.0
146 return basis
149def random_neuron_basis(
150 d_mlp: int,
151 k: int,
152 seed: int,
153 exclude: Optional[Neurons] = None,
154) -> Float[torch.Tensor, "d_mlp k"]:
155 """The coordinate basis of ``k`` neurons drawn at random: the placebo for :func:`neuron_basis`.
157 Args:
158 d_mlp: Number of neurons at the hook.
159 seed: Seed for the draw; the caller's random stream is untouched.
160 exclude: Neurons the draw must avoid, usually the ones the placebo is compared with.
162 Returns:
163 Orthonormal basis of unit vectors, ``[d_mlp, k]``.
165 Raises:
166 ValueError: If fewer than ``k`` neurons remain to draw from, or ``exclude`` holds an
167 invalid index.
168 """
169 excluded = _neuron_indices(d_mlp, exclude if exclude is not None else [])
170 allowed = torch.ones(d_mlp, dtype=torch.bool)
171 allowed[excluded] = False
172 pool = allowed.nonzero().flatten()
173 if not 0 < k <= len(pool):
174 raise ValueError(
175 f"k must be in [1, {len(pool)}] with {len(excluded)} neurons excluded, got {k}"
176 )
177 generator = torch.Generator().manual_seed(seed)
178 return neuron_basis(d_mlp, pool[torch.randperm(len(pool), generator=generator)[:k]])
181def _neuron_indices(d_mlp: int, neurons: Neurons) -> Int[torch.Tensor, "k"]:
182 index = torch.as_tensor(neurons)
183 if index.numel() == 0: # an empty list arrives as a float tensor
184 return torch.empty(0, dtype=torch.long)
185 if index.dtype == torch.bool or index.is_floating_point() or index.is_complex():
186 raise ValueError(f"neuron indices must be integers, got dtype {index.dtype}")
187 if index.dim() != 1:
188 raise ValueError(f"neuron indices must be one-dimensional, got shape {tuple(index.shape)}")
189 index = index.long().cpu()
190 if ((index < 0) | (index >= d_mlp)).any():
191 raise ValueError(f"neuron indices must be in [0, {d_mlp}), got {index.tolist()}")
192 if index.unique().numel() != index.numel():
193 raise ValueError(f"neuron indices must not repeat, got {index.tolist()}")
194 return index
197class LearnedSubspace(nn.Module):
198 """A trainable rank-``rank`` subspace of ``d_model`` whose basis stays orthonormal.
200 Args:
201 rank: Number of basis directions, in ``[1, d_model]``.
202 """
204 def __init__(self, d_model: int, rank: int):
205 super().__init__()
206 if not 0 < rank <= d_model:
207 raise ValueError(f"rank must be in [1, {d_model}], got {rank}")
208 self.proj = orthogonal(nn.Linear(rank, d_model, bias=False))
210 @property
211 def basis(self) -> Float[torch.Tensor, "d_model rank"]:
212 return cast(torch.Tensor, self.proj.weight)
215Basis = Union[torch.Tensor, LearnedSubspace]
218def _basis(basis: Basis, like: torch.Tensor) -> torch.Tensor:
219 b = basis.basis if isinstance(basis, LearnedSubspace) else basis
220 return b.to(like.device, like.dtype)
223@dataclass(frozen=True)
224class SubspaceInterchange:
225 """Set the base's coordinates inside ``basis`` to the source's.
227 Attributes:
228 basis: Orthonormal basis, ``[d_model, rank]``, or a :class:`LearnedSubspace`.
229 strength: 1 interchanges the coordinates; other values scale the move, 0 leaves the base.
230 """
232 basis: Basis
233 strength: float = 1.0
235 def __call__(self, base: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
236 B = _basis(self.basis, base)
237 return base + self.strength * ((source - base) @ B) @ B.T
240@dataclass(frozen=True)
241class NormMatchedPlacebo:
242 """Move each base exactly as far as ``reference`` does, but inside a random subspace.
244 An effect that the placebo also produces comes from displacing the activation by that much,
245 not from the aligned subspace.
247 Zero reference displacement leaves the base unchanged. A zero placebo projection with a
248 nonzero reference displacement raises ``ValueError``: no projected direction can be rescaled
249 to match that distance. Normalization uses at least float32, and the output keeps base's dtype.
251 Attributes:
252 reference: The intervention whose displacement is matched.
253 basis: Orthonormal basis of the placebo subspace, usually from :func:`random_basis` with
254 the reference's rank, or from :func:`random_neuron_basis` for a reference built by
255 :func:`neuron_basis`.
256 """
258 reference: SubspaceInterchange
259 basis: torch.Tensor
261 def __call__(self, base: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
262 dtype = compute_dtype(base.dtype)
263 base_work = base.to(dtype)
264 distance = (self.reference(base, source).to(dtype) - base_work).norm(dim=-1, keepdim=True)
265 B = self.basis.to(base.device, dtype)
266 move = ((source.to(dtype) - base_work) @ B) @ B.T
267 move_norm = move.norm(dim=-1, keepdim=True)
268 unmatchable = (move_norm == 0) & (distance != 0)
269 if unmatchable.any():
270 raise ValueError(
271 "Cannot norm-match a zero placebo projection to a nonzero reference displacement: "
272 f"{int(unmatchable.sum())} of {unmatchable.numel()} rows have no base-to-source "
273 "difference inside the placebo subspace. Try a different placebo basis or a "
274 "higher rank."
275 )
276 # Divide before multiplying to avoid overflowing the distance-to-norm ratio.
277 direction = move / torch.where(move_norm == 0, torch.ones_like(move_norm), move_norm)
278 return (base_work + direction * distance).to(base.dtype)
281def _select(act: torch.Tensor, positions: Optional[torch.Tensor]) -> torch.Tensor:
282 if positions is None:
283 if act.ndim != 2:
284 raise ValueError(
285 f"activation has shape {tuple(act.shape)}; pass one position index per example"
286 )
287 return act
288 if act.ndim != 3:
289 raise ValueError(
290 f"with positions, the activation must be [batch, pos, d_model]; "
291 f"got shape {tuple(act.shape)}"
292 )
293 if positions.shape != (act.shape[0],):
294 raise ValueError(
295 f"positions must hold one index per example, shape ({act.shape[0]},); "
296 f"got {tuple(positions.shape)}"
297 )
298 return act[torch.arange(act.shape[0], device=act.device), positions.to(act.device)]
301def _write(act: torch.Tensor, positions: Optional[torch.Tensor], new: torch.Tensor) -> torch.Tensor:
302 if positions is None:
303 return new
304 out = act.clone()
305 out[torch.arange(act.shape[0], device=act.device), positions.to(act.device)] = new
306 return out
309def _chunks(n: int, size: int) -> Iterator[slice]:
310 for start in range(0, n, size):
311 yield slice(start, min(start + size, n))
314def _at(
315 positions: Optional[torch.Tensor], idx: Union[slice, torch.Tensor]
316) -> Optional[torch.Tensor]:
317 return None if positions is None else positions[idx]
320@torch.no_grad()
321def collect_activations(
322 model: Any,
323 hook_name: str,
324 inputs: torch.Tensor,
325 task_logits: TaskLogits,
326 *,
327 positions: Optional[Int[torch.Tensor, "batch"]] = None,
328 batch_size: int = 256,
329) -> Float[torch.Tensor, "batch d_model"]:
330 """Activations at ``hook_name``, at one position per example if given, returned on the CPU.
332 Args:
333 model: A model exposing the hook API.
334 inputs: Model inputs, one row per example.
335 task_logits: Runs the model on a batch of inputs.
336 positions: For ``[batch, pos, d_model]`` activations, the position to read per example.
337 batch_size: Rows per forward pass.
339 Returns:
340 Activations, ``[batch, d_model]``.
342 Raises:
343 ValueError: If any part of the model is in training mode, or the activation does not match
344 the positions given (or not given).
345 RuntimeError: If the hook does not fire exactly once per forward pass.
346 """
347 require_eval_mode(model, operation="collect_activations")
348 out = []
349 for idx in _chunks(len(inputs), batch_size):
350 store: list[torch.Tensor] = []
352 def grab(
353 act: torch.Tensor, hook: Any, _positions: Optional[torch.Tensor] = _at(positions, idx)
354 ) -> None:
355 store.append(_select(act, _positions).detach().cpu())
357 with model.hooks(fwd_hooks=[(hook_name, grab)]):
358 task_logits(inputs[idx])
359 if len(store) != 1:
360 raise RuntimeError(f"{hook_name} fired {len(store)} times in one forward pass")
361 out.append(store[0])
362 return torch.cat(out)
365def run_with_intervention(
366 model: Any,
367 hook_name: str,
368 intervention: Intervention,
369 base_inputs: torch.Tensor,
370 source_activations: Float[torch.Tensor, "batch d_model"],
371 task_logits: TaskLogits,
372 *,
373 positions: Optional[Int[torch.Tensor, "batch"]] = None,
374) -> Float[torch.Tensor, "batch n_classes"]:
375 """Task logits for ``base_inputs`` with ``intervention`` applied at ``hook_name``, in one pass.
377 Differentiable with respect to any parameters of ``intervention``, for training an
378 intervention. To evaluate one over many pairs in bounded memory, use :func:`intervened_logits`.
380 Args:
381 model: A model exposing the hook API.
382 intervention: Maps base and source activations to new base activations, e.g. a
383 :class:`SubspaceInterchange`.
384 source_activations: Activations from the source inputs at the same hook point, one row per
385 base, e.g. from :func:`collect_activations`.
386 task_logits: Runs the model on a batch of inputs.
387 positions: For ``[batch, pos, d_model]`` activations, the position to intervene on per base.
389 Returns:
390 Task logits under the intervention.
392 Raises:
393 ValueError: If the activation does not match the positions given (or not given).
394 RuntimeError: If the hook does not fire exactly once in the forward pass.
395 """
396 calls = 0
398 def hook(act: torch.Tensor, hook: Any) -> torch.Tensor:
399 nonlocal calls
400 calls += 1
401 selected = _select(act, positions)
402 source = source_activations.to(act.device, act.dtype)
403 return _write(act, positions, intervention(selected, source))
405 with model.hooks(fwd_hooks=[(hook_name, hook)]):
406 logits = task_logits(base_inputs)
407 # A second firing would reuse source activations collected for the first
408 if calls != 1:
409 raise RuntimeError(f"{hook_name} fired {calls} times in one forward pass")
410 return logits
413@torch.no_grad()
414def intervened_logits(
415 model: Any,
416 hook_name: str,
417 intervention: Intervention,
418 base_inputs: torch.Tensor,
419 source_activations: Float[torch.Tensor, "batch d_model"],
420 task_logits: TaskLogits,
421 *,
422 positions: Optional[Int[torch.Tensor, "batch"]] = None,
423 batch_size: int = 256,
424) -> Float[torch.Tensor, "batch n_classes"]:
425 """Task logits under ``intervention``, in batches without gradients, returned on the CPU.
427 The evaluation counterpart of :func:`run_with_intervention`, with the same arguments and
428 checks: memory is bounded by ``batch_size`` rather than by the number of pairs.
430 Args:
431 model: A model exposing the hook API.
432 intervention: Maps base and source activations to new base activations.
433 source_activations: Activations from the source inputs at the same hook point, one row per
434 base.
435 task_logits: Runs the model on a batch of inputs.
436 positions: For ``[batch, pos, d_model]`` activations, the position to intervene on per base.
437 batch_size: Rows per forward pass.
439 Returns:
440 Task logits under the intervention, ``[batch, n_classes]``.
442 Raises:
443 ValueError: If any part of the model is in training mode, or the inputs do not pair up.
444 """
445 require_eval_mode(model, operation="intervened_logits")
446 if len(source_activations) != len(base_inputs):
447 raise ValueError("source_activations must have one row per base input")
448 out = []
449 for idx in _chunks(len(base_inputs), batch_size):
450 logits = run_with_intervention(
451 model,
452 hook_name,
453 intervention,
454 base_inputs[idx],
455 source_activations[idx],
456 task_logits,
457 positions=_at(positions, idx),
458 )
459 out.append(logits.detach().cpu())
460 return torch.cat(out)
463def _model_device(model: Any) -> torch.device:
464 parameter = next(iter(model.parameters()), None)
465 return parameter.device if parameter is not None else torch.device("cpu")
468@dataclass(frozen=True)
469class DASResult:
470 """A subspace learned by :func:`fit_das`.
472 Attributes:
473 subspace: The learned subspace; pass it to :class:`SubspaceInterchange`.
474 losses: Mean training loss per epoch.
475 hook_name: The hook point it was trained at.
476 """
478 subspace: LearnedSubspace
479 losses: tuple[float, ...]
480 hook_name: str
481 rank: int
483 @property
484 def basis(self) -> Float[torch.Tensor, "d_model rank"]:
485 return self.subspace.basis.detach()
488def fit_das(
489 model: Any,
490 hook_name: str,
491 base_inputs: torch.Tensor,
492 source_inputs: torch.Tensor,
493 targets: Int[torch.Tensor, "batch"],
494 task_logits: TaskLogits,
495 *,
496 rank: int,
497 base_positions: Optional[Int[torch.Tensor, "batch"]] = None,
498 source_positions: Optional[Int[torch.Tensor, "batch"]] = None,
499 epochs: int = 20,
500 batch_size: int = 128,
501 lr: float = 1e-2,
502 strength: float = 1.0,
503 seed: int = 0,
504 device: Optional[Union[str, torch.device]] = None,
505 micro_batch_size: Optional[int] = None,
506) -> DASResult:
507 """Learn the subspace whose interchange makes the model output ``targets`` (DAS).
509 ``targets[i]`` is the class the high-level causal model predicts for base ``i`` with the
510 aligned variable set to its value in source ``i``. The basis is trained with cross-entropy
511 on the task logits under the interchange. Model parameters are frozen during the call and
512 their ``requires_grad`` flags restored afterwards.
514 Train on pairs where several variables differ between base and source, labelled by the
515 high-level model's interchange, as well as on pairs that differ only in the aligned variable:
516 otherwise the subspace can learn whatever the pairs happen to move together.
518 Args:
519 model: A model exposing the hook API.
520 hook_name: The hook point to align.
521 base_inputs: Base inputs, one row per pair.
522 source_inputs: Source inputs, one row per pair.
523 targets: The high-level model's output class for each pair under the interchange.
524 task_logits: Runs the model on a batch of inputs and returns task logits.
525 rank: Dimension of the subspace.
526 base_positions: For ``[batch, pos, d_model]`` activations, the base position per pair.
527 source_positions: Likewise for the sources.
528 epochs: Passes over the pairs.
529 batch_size: Pairs per optimisation step.
530 lr: Adam learning rate.
531 strength: Interchange strength during training.
532 seed: Seed for the basis initialisation and the batch order.
533 device: Device for the subspace's parameters; by default the device of the model's
534 parameters, or the CPU for a model without any.
535 micro_batch_size: Split each batch into parts this size and accumulate gradients: the same
536 gradients, up to floating-point rounding, in less memory.
538 Returns:
539 The learned subspace with its training losses.
541 Raises:
542 ValueError: If any part of the model is in training mode, or the inputs and targets differ
543 in length.
544 """
545 require_eval_mode(model, operation="fit_das")
546 if not (len(base_inputs) == len(source_inputs) == len(targets)):
547 raise ValueError("base_inputs, source_inputs and targets must have the same length")
548 rng = np.random.default_rng(seed)
549 micro = micro_batch_size or batch_size
550 source_acts = collect_activations(
551 model, hook_name, source_inputs, task_logits, positions=source_positions, batch_size=micro
552 )
553 # The subspace is built on the CPU, so seed only the CPU generator, inside a fork that restores
554 # it; torch.manual_seed would also reseed every CUDA, MPS and XPU generator
555 with torch.random.fork_rng(devices=[]):
556 torch.default_generator.manual_seed(seed)
557 subspace = LearnedSubspace(source_acts.shape[1], rank)
558 subspace = subspace.to(device if device is not None else _model_device(model))
559 step = SubspaceInterchange(subspace, strength)
560 optimizer = torch.optim.Adam(subspace.parameters(), lr=lr)
561 labels = torch.as_tensor(targets, dtype=torch.long)
563 flags = [p.requires_grad for p in model.parameters()]
564 model.requires_grad_(False)
565 losses = []
566 try:
567 for _ in range(epochs):
568 order = torch.as_tensor(rng.permutation(len(labels)))
569 total = 0.0
570 for chunk in _chunks(len(order), batch_size):
571 batch = order[chunk]
572 optimizer.zero_grad()
573 for part in _chunks(len(batch), micro):
574 idx = batch[part]
575 logits = run_with_intervention(
576 model,
577 hook_name,
578 step,
579 base_inputs[idx],
580 source_acts[idx],
581 task_logits,
582 positions=_at(base_positions, idx),
583 )
584 # Summed, then divided by the whole batch, so split batches give equal gradients
585 loss = F.cross_entropy(
586 logits, labels[idx].to(logits.device), reduction="sum"
587 ) / len(batch)
588 loss.backward()
589 total += loss.item() * len(batch)
590 optimizer.step()
591 losses.append(total / len(order))
592 finally:
593 for p, flag in zip(model.parameters(), flags):
594 p.requires_grad_(flag)
595 return DASResult(subspace.eval(), tuple(losses), hook_name, rank)
598def arbitrary_targets(
599 keys: Sequence[Hashable], n_classes: int, seed: int
600) -> Int[torch.Tensor, "batch"]:
601 """A fixed pseudo-random class per key: targets for the arbitrary-label control.
603 Train :func:`fit_das` on these instead of the high-level model's targets, with the same pairs,
604 rank and budget. The interchange accuracy it reaches shows how much accuracy the method's
605 expressivity alone produces; a learned subspace should clearly exceed it.
607 Args:
608 keys: One key per pair identifying its source, e.g. the source text.
610 Returns:
611 A class in ``[0, n_classes)`` per key; equal keys always get equal classes.
612 """
614 def draw(key: Hashable) -> int:
615 digest = hashlib.sha256(f"{seed}:{key!r}".encode()).digest()
616 return int.from_bytes(digest[:8], "big") % n_classes
618 return torch.tensor([draw(k) for k in keys], dtype=torch.long)
621def reinitialized(model: nn.Module, seed: int) -> nn.Module:
622 """A copy of ``model`` with freshly initialised parameters: the random-init control.
624 For models built from standard ``nn`` layers, such as a ``HookedRootModule``: every module with
625 ``reset_parameters`` is reset, so every parameter must belong to one. Buffers, such as fixed
626 architectural matrices, are kept. For HuggingFace models use :func:`random_init_bridge`, which
627 applies the architecture's own initialisation scheme.
629 Args:
630 model: The trained model; it is not modified.
632 Returns:
633 The untrained copy, on the device of the model's parameters, in evaluation mode.
635 Raises:
636 ValueError: If a parameter belongs to no module with ``reset_parameters``, so it would keep
637 its trained value.
638 """
639 covered = {
640 id(parameter)
641 for module in model.modules()
642 if callable(getattr(module, "reset_parameters", None))
643 for parameter in module.parameters(recurse=False)
644 }
645 missing = [name for name, parameter in model.named_parameters() if id(parameter) not in covered]
646 if missing:
647 more = f" and {len(missing) - 5} more" if len(missing) > 5 else ""
648 raise ValueError(
649 f"reinitialized cannot reset {', '.join(missing[:5])}{more}: no module's "
650 "reset_parameters covers them, so they would keep their trained values. Reset them "
651 "yourself, or use random_init_bridge for a HuggingFace model."
652 )
653 device = _model_device(model)
654 clone = copy.deepcopy(model).cpu()
655 # Reset on the CPU, seeding only the CPU generator inside a fork that restores it;
656 # torch.manual_seed would also reseed every CUDA, MPS and XPU generator
657 with torch.random.fork_rng(devices=[]):
658 torch.default_generator.manual_seed(seed)
659 for module in clone.modules():
660 reset = getattr(module, "reset_parameters", None)
661 if callable(reset):
662 reset()
663 return clone.to(device).eval()
666def random_init_bridge(
667 model_name: str,
668 *,
669 seed: int,
670 dtype: torch.dtype = torch.float32,
671 device: Optional[Union[str, torch.device]] = None,
672 **boot_kwargs: Any,
673) -> Any:
674 """A ``TransformerBridge`` with the architecture's HuggingFace initialisation and no training.
676 The random-init control: train :func:`fit_das` on it with the same pairs, rank and budget as
677 on the trained model. Effects DAS finds here come from the method and the architecture, not
678 from anything the model learned. Built with ``load_weights=False``, so the model class and
679 prepared configuration match the trained bridge.
681 Args:
682 model_name: Model name or alias, as for ``TransformerBridge.boot_transformers``.
683 device: Device for the bridge; by default the device ``boot_transformers`` would choose.
684 **boot_kwargs: Passed on to ``TransformerBridge.boot_transformers``, e.g. ``revision``.
686 Returns:
687 The untrained ``TransformerBridge``, in evaluation mode.
688 """
689 from transformer_lens.model_bridge import TransformerBridge
690 from transformer_lens.utilities.multi_gpu import maybe_cast_floating_params
692 # The model is built on the CPU, so seed only the CPU generator, inside a fork that restores it
693 with torch.random.fork_rng(devices=[]):
694 torch.default_generator.manual_seed(seed)
695 bridge = TransformerBridge.boot_transformers(
696 model_name, load_weights=False, dtype=dtype, device=device, **boot_kwargs
697 )
698 # Building from a config follows the config's dtype and leaves the weights on the CPU,
699 # whatever device boot recorded; HuggingFace also leaves the model in training mode
700 maybe_cast_floating_params(bridge.original_model, dtype)
701 return bridge.to(bridge.cfg.device).eval()