Introduction
A mechanistic explanation of a frozen language model makes a counterfactual claim. A circuit claims that if every edge outside it takes its value from a counterfactual input, the model's behaviour is preserved; a feature explanation of a causal variable claims that exchanging those features between two inputs has the effect of setting the variable to the donor's value. Both claims are judged on examples the discovery procedure never saw [1]: circuits by how far they move the model's behaviour (CMD) and how much of it they recover (CPR), averaged over a range of circuit sizes, and causal features by interchange-intervention accuracy (IIA).
The standard tools approach both problems through a proxy. Edge attribution patching scores every edge once with a first-order estimate of its effect in the dense model [2], and its integrated-gradient variant averages that estimate along a path of inputs [3]; related methods attribute to activations or features [4], propagate relevance [5] or learn the attribution [6]. A circuit is then the top of the ranking at each size. But a ranking describes the dense model, and a sparse circuit is not the dense model: once most edges carry counterfactual values, an edge that scored highly may carry nothing, and edges compose. For causal variables, distributed alignment search trains a rotation whose leading coordinates are exchanged [7]; it is trained on the discovery counterfactuals only, and nothing in it says when exchanging less, or more, would transfer better.
We therefore ask a single question of every candidate: what does the intervention this explanation defines actually do to the model, on discovery examples held back from fitting it? Our method is the answer applied to both problems.
Method
Circuits: the patched circuit, differentiated where it stands
We evaluate a candidate circuit exactly as it will be judged, with one change: each edge from a sender to a receiver carries a continuous gate . The receiver's input is its counterfactual input plus the gated differences of its senders,
where is the sender's value in the patched run, not in the clean model. With this is the circuit; differentiating the logit-difference margin of example gives a per-example Jacobian evaluated at the current circuit. Unlike an attribution computed once on the dense model, is recomputed after every cut, so it describes the circuit we actually have. A custom autograd function routes the bank of sender differences to every reader without storing a copy per reader; for models with a normalisation after attention we carry an exact expansion of that normalisation through the same route, and, when that shared prefix is long enough, positions before the first token where clean and counterfactual prompts differ are skipped, since every sender difference vanishes there.
class _MixEdges(torch.autograd.Function):
"""Route a bank of sender differences without saving a copy at each reader."""
@staticmethod
def forward(ctx, weight, anchor, bank, *senders):
ctx.save_for_backward(weight)
# Only unused rows beyond this prefix can change subsequently.
ctx.bank = bank
ctx.widths = [sender.shape[1] for sender in senders]
return torch.bmm((weight - anchor).transpose(1, 2), bank)
@staticmethod
def backward(ctx, grad):
(weight,) = ctx.saved_tensors
grad_weight = torch.bmm(ctx.bank, grad.transpose(1, 2))
grad_sender = torch.bmm(weight, grad)
return (grad_weight, None, None, *grad_sender.split(ctx.widths, dim=1))Compression by cuts that the data must accept
We start from the full graph and compress towards each budget , largest first; each step limits the circuit to edges. At each step we fit the local surface on a sample of discovery examples. With residual (clean margin minus circuit margin), the magnitude gives a first candidate, the largest connected circuit within the limit ranked by . The linear prediction of the residual that cut would leave,
defines a relevance , and two more candidates rank by and . Every ranking is projected onto connected circuits: a bisection over prefixes finds the longest one whose edges that still connect input to logits number at most the limit, so no budget is spent on edges that are pruned anyway.
while int(current.sum()) > k:
limit = max(k, int(current.sum() * 0.58))
jacobian, residual = surface(current)
magnitude = jacobian.square().mean(0).sqrt()
first = topology.project(magnitude, current, limit)
missing = residual + (jacobian * (current & ~first)).sum((1, 2))
relevance = (jacobian * missing[:, None, None]).mean(0) / (
missing.square().mean().sqrt() + 1e-8
)
alternatives = [
topology.project(magnitude + factor * relevance, current, limit)
for factor in (0.55, 1.15)
]
del jacobian
current = compare.choose([first, *alternatives])The choice between candidates is not made by the linear model. It is made by running each candidate circuit on held-back discovery examples and comparing per-example errors , paired across candidates on the same prompts. The risk we minimise is
where the first column of is , so the second term contains the squared mean error, and the remaining columns are shrunk principal directions of per-example covariates (clean and counterfactual margins, their difference and its magnitude, prompt length). Errors that are systematic in these covariates are therefore charged twice. The comparison is a race: after a checkpoint of about examples, candidates whose risk gap exceeds paired standard errors are dropped, the checkpoint doubles, and the race ends when one candidate is left or the panel is exhausted. When the incumbent circuit is among the candidates, it is kept unless the winner beats it by more than standard errors.
for i in order:
used.append(int(i))
new = self.experiment.scores(i, masks[live])
errors = new if errors is None else torch.cat((errors, new), dim=1)
n = errors.shape[1]
if n < checkpoint and len(used) < len(order):
continue
basis = self.risk.basis(used)
systematic = errors @ basis
loss = (errors.square().sum(1) + systematic.square().sum(1)) / n
best = int(loss.argmin())
# Influence of each sample on both the individual distortion and
# the squared conditional mean error. Pairing cancels prompt difficulty.
influence = errors.square() + 2 * errors * (systematic @ basis.T)
gap = loss - loss[best]
uncertainty = (influence - influence[best]).std(1, unbiased=False) / math.sqrt(n)
incumbent = live.index(0) if conservative and 0 in live else None
if n >= limit or len(used) == len(order):
if incumbent is not None and gap[incumbent] <= 0.35 * uncertainty[incumbent]:
best = incumbent
return unique[live[best]]
remain = (gap <= 1.8 * uncertainty + 1e-12).nonzero().flatten().tolist()
if incumbent is not None and incumbent not in remain:
remain.append(incumbent)
live = [live[q] for q in remain]
if len(live) == 1:
return unique[live[0]]
errors = errors[remain]
checkpoint = min(limit, 2 * n)
return unique[live[0]]Once a budget is reached, we fit the same surface again and build a short greedy sequence of additions and add-remove swaps on it, scored by so that the quadratic term penalises steps the linear model cannot be trusted with; up to four connected masks along that sequence enter the race against the incumbent, for at most six rounds and until the incumbent survives twice. Finally, each budget's circuit competes on the whole held-back panel against the two next smaller circuits, which also fit its budget.
Refining the smallest circuits
For the five smallest budgets we do two more things. First, the final readout is a known function of the senders that write to it: given the circuit's upstream computation, we model the logit-difference margin exactly as a function of which senders connect directly to the logits, charging each sender for the ancestors it needs. This lets us test thousands of readout subsets after one pass per example, exhaustively when at most fifteen senders qualify and by a seeded local search otherwise; the best subsets are checked by real interventions on held-back examples and replace the circuit only if they lower its risk by more than standard errors.
Second, a retained edge need not pass its whole signal. On edges into the logits and between attention heads we search for directions whose removal reduces the distortion of the output, eigenvectors of per-example bilinear forms between the sender's difference and the gradient it receives, and export the edge as an orthonormal subspace codec that keeps the complement, or, on edges into the logits, as a subset of its coordinates. The task's interface counts a non-empty selection on an edge as one edge, so this does not change the budget. A filter is used only if it lowers held-back risk by more than about half a standard error; otherwise the plain edge is kept.
Causal variables: a read-preserving exchange field
At each site we learn a read matrix with orthonormal columns and an exchange
applied as for recipient and donor . Because and , the edited state reads exactly like the donor, : the exchange is idempotent in its read, and the free part lets it write along directions other than the ones it reads. The term in adds a nonlinear part. When enough distinct levels of the variable are observed, is a calibrated estimate of which level the state encodes, from ridge-regularised contrasts between level groups with leave-one-out ridge choice and a monotone piecewise-linear calibration, and holds the shrunk mean displacement between those levels; otherwise consists of hinges at the quartiles of the leading read coordinates.
def factors(self):
u = self.read
write = u + self.extra - u @ (u.T @ self.extra)
curve = self.mix - u @ (u.T @ self.mix)
return u, write, curve
def delta(self, base, source, strength):
u, write, curve = self.factors()
difference = ((source - base) @ u) @ write.T
if strength:
axes = u @ self.axes
donor = ((source - self.center) @ axes - self.knots).relu()
recipient = ((base - self.center) @ axes - self.knots).relu()
difference = difference + strength * (donor - recipient) @ curve.T
return differenceThe read is initialised from the leading eigenvectors of a symmetrised cross-covariance between donor-recipient differences (shrunk toward the means of their variable levels) and the gradients of the answer's log-likelihood. When a fitted site already exists at a shallower layer for the same token position, its exchange is transported by ridge maps between the two layers' activations and used as the start only if it beats the fresh initialisation on a discovery panel by more than standard errors.
Training uses Adam with learning rate , removes the gradient's component inside the current read span and re-orthonormalises the read after each step. Each example is used twice. Once with its own counterfactual, against the teacher-forced log-likelihood of the answer the causal model assigns to the intervention; where the intervention leaves the answer unchanged, a fifth of that loss is replaced by a divergence to the model's own answer distribution. And once with a second donor drawn from the discovery pool, for which we query the causal model for the new answer. In three of every four rows, when such a donor exists, it is one that changes the answer, and the loss is then the log-probability mass of the new answer's tokens at the first token where it departs from the original one.
def _losses(site, design, i, field, epoch):
batch = site.batches[i]
y = batch["y"]
mask = y["attention_mask"]
donor, loc, _, allowed, equal = design.draw(i, epoch)
sl = slice(site.offset[i], site.offset[i + 1])
def edit(which):
if which == 0:
return site.edited(i, field, 1.0)
base = site.base[sl]
return base + field.delta(base, donor, 1.0)
step = min(2, site.capacity(i))
for begin in range(0, 2, step):
roles = list(range(begin, min(2, begin + step)))
logits = site.logits(i, torch.stack([edit(k) for k in roles]))
losses = []
for which, one in zip(roles, logits):
logp = one.float().log_softmax(-1)
target, _ = _answer_evidence(logp, y, need_margin=False)
entire = -(target * mask).sum(1) / mask.sum(1).clamp_min(1)
stable = site.stable[batch["idx"]]
entire = torch.where(stable, 0.8 * entire + 0.2 * _anchor_loss(logp, batch), entire)
if which:
rows = torch.arange(len(equal), device=logp.device)
alternate = -_logmass(logp[rows, loc], allowed)
entire = torch.where(equal, entire, alternate)
losses.append(entire.mean() * 0.5)
yield sum(losses)The best epoch is kept by a smoothed answer error, of the greedy answer, on discovery batches held out from training. The final explanation is then chosen among five options in order of increasing intervention: exchange nothing, the field without its nonlinear part, the field at half and at full nonlinear strength, and the full vector. We take the first option whose mean error is within half a standard error of the best.
options = [(None, 0.0), (field, 0.0), (field, 0.5), (field, 1.0), (None, 1.0)]
err = site.errors(options)
idx = int(err.mean(1).argmin())
gap = err - err[idx]
adequate = gap.mean(1) <= 0.5 * gap.std(1, unbiased=False) / math.sqrt(err.shape[1])
selected = int(adequate.nonzero()[0])
native = len(options) - 1 if err[-1].mean() < err[0].mean() else 0
site.reference_cost = (native != 0, float((err[native] - err[selected]).mean().clamp_min(0)))
return options[selected]Causal variables with little data
When the discovery set is too small to fit a field (fewer than four batches, or no more training steps than feature directions), we fit the exchange in closed form from measured interventions instead. With folds that hold out every recipient's prompt together, we estimate a discriminant subspace of the variable's levels, measure the model's answer under three partial exchanges (the part of the difference inside that subspace, the part outside it, and the whole), turn the measured answers into weights for which part carries the variable, and fit four candidate exchange operators to those weights: a symmetric low-rank operator, a reduced-rank oblique one, a set of coordinates and the discriminant projector itself. Each candidate is scored by real interventions on its held-out fold. Since these errors are noisy, they are smoothed across layers at the same token position by a Haar decomposition that mixes the hard greedy error with its soft margin version, and the smallest candidate within standard errors of the best is exported.
Results
| Method | ① | ② | ③ | ④ | ⑤ | ||
|---|---|---|---|---|---|---|---|
| Circuit-model distance (CMD) ↓ | Circuit performance ratio (CPR) ↑ | Circuit-model distance (CMD) ↓ | Circuit performance ratio (CPR) ↑ | Interchange accuracy (IIA) ↑ | Interchange accuracy (IIA) ↑ | Interchange accuracy (IIA) ↑ | |
| GPT-6.2 Astra | 0.140 | 0.859 | 0.072 | 0.927 | 0.377 | 0.563 | 0.830 |
| EAP-IG + DAS | 0.145 | 0.854 | 0.069 | 0.930 | 0.377 | 0.563 | 0.830 |
| EAP | 0.160 | 0.845 | 0.068 | 0.931 | 0.377 | 0.563 | 0.830 |
| EAP-IG-activations | 0.066 | 0.935 | 0.377 | 0.563 | 0.830 | ||
| RelP | 0.154 | 0.845 | 0.094 | 0.915 | 0.377 | 0.563 | 0.830 |
| MAttr | 0.446 | 0.601 | 0.429 | 0.570 | 0.377 | 0.563 | 0.830 |
| Random circuit | 0.740 | 0.259 | 0.661 | 0.338 | 0.377 | 0.563 | 0.830 |
| Full vector | 0.145 | 0.854 | 0.069 | 0.930 | 0.294 | 0.491 | 0.467 |
| DBM | 0.145 | 0.854 | 0.069 | 0.930 | 0.345 | 0.530 | 0.713 |
- ① Llama-3.1-8B · ARC-Challenge circuit
- ② Gemma-2-2B · MCQA circuit
- ③ Gemma-2-2B · arithmetic carry variable
- ④ Gemma-2-2B · RAVEL country variable
- ⑤ Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable
The circuits are where the method makes its largest difference. On Llama-3.1-8B · ARC-Challenge circuit our CMD is 0.004 against 0.145 for the strongest published baseline, EAP-IG-inputs and DAS [7], and on Gemma-2-2B · MCQA circuit it is 0.004 against 0.066 (EAP-IG-activations [4]). CPR moves the same way: 0.995 and 0.995, against 0.854 and 0.935. Averaged over the circuit sizes, our circuits stay close to the full model's behaviour on examples they were not fitted to.
The causal features are mixed. On Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable our IIA of 0.881 is clear of every published baseline, the best of which reaches 0.830 (EAP-IG-inputs and DAS [7]). On Gemma-2-2B · arithmetic carry variable we reach 0.385 against 0.377, a gain small enough that we do not claim it. On Gemma-2-2B · RAVEL country variable we reach 0.515, below the starter's alignment search at 0.563 and below DBM at 0.530, though above the full-vector exchange at 0.491.
How we got here
The circuit method came first and changed least. We began from the observation that an edge can rank highly in the full model and carry no signal once pruning has disconnected its sender, and that a ranking discards how edges compose. Our early version already started from the full graph, took per-example derivatives of the actually patched responses, and compressed along connected masks. On held-out prompts we generated ourselves with a small public model, it recovered 46% of the response with 32 edges and 92% with 64, where the starter recovered 0% and 15%, in our development measurements. It also overshot the full model's response at some larger budgets; checking proposed edge swaps against discovery examples brought those budgets much closer to the model. On a larger public model we measured 90% recovery at 183 edges against 67% for the starter, and on the largest model we tried 0.895 against 0.603 at the smallest budget.
Several later additions were each kept on a development measurement:
- Connected projection. Against an exhaustive oracle on small graphs, our way of choosing connected edges retained 96.5% of the available edge value at a three-edge budget, against 60.1% for pruning a ranked prefix.
- The exact readout model. Reusing a circuit's upstream computation to test readout subsets reduced average held-out per-example error in all six matched experiments we ran.
- Response-guided filters. Our first projection filters matched the full model's hidden vectors on retained edges. That reduced hidden-state error but lowered held-out recovery on a 64-edge circuit from 0.896 to 0.826 in our development run, so we abandoned hidden-state matching and judge filters only by the model's response, with the plain edge as the comparison.
- Receiver responses. Measuring each receiver's response to a proposed edge change predicted the real intervention better than the edge gradient; at 64 edges the relative prediction error fell from 0.82 to 0.35 in our measurement.
The causal method went through more versions, and more of them were rejected. Learning the read and the write separately improved accuracy on one of our own row-selection tasks from 76% to 81%. Training on a second donor with the recipient fixed raised accuracy on held-out entities from 0.666 to 0.752 on one public model and from 0.661 to 0.720 on another, while losing accuracy on one query task. A calibrated estimate of the donor's level added 2.7 percentage points on average across six matched development settings, and correcting an offset error in that calibration raised one shifted task from 0.671 to 0.689. Ideas that helped on one task and hurt on another were not installed: a codec learned from independent examples sharing a variable value (0.665 against 0.598 on one task, worse on two others), joint decoding of competing levels (0.715 to 0.739 on one task, 0.689 to 0.668 on another), adjustment for background variables (0.709 to 0.722, and 0.729 to 0.680), and a read of co-activation that recovered a synthetic interaction but was weaker on a frozen model. In one early measurement, leaving the representation untouched (0.516) beat our learned exchange (0.490) on a harder variable; the final selection rule keeps exchanging nothing among its options.
The small-data estimator was the last large change. Late in the run we found that the trained field struggled with very small discovery sets; fitting the exchange to measured partial exchanges raised IIA on independent 8- and 16-example tests from .494 and .489 to .536 and .559 in our development runs, and it was installed for that regime only. A numerical failure on a rank-deficient case was fixed by dropping zero-weight rows and solving the small eigensystem in double precision. The last hours went to cost: moving small eigensolves to the CPU cut one discovery run from 213 to 59 seconds with similar held-out errors; skipping identical prompt prefixes and reusing counterfactual states removed redundant model passes while preserving every checked quantity exactly, and reusing identical writes reduced measurement time.
All figures in this section are our own development measurements on data we generated or held out ourselves, as reported in the trace.
Limitations
- Gemma-2-2B · RAVEL country variable is a loss. Our features trail the starter's alignment search and DBM there. Our development runs showed the same pattern, gains on some variables and losses on others for most causal changes we tried, and the final method does not resolve it.
- Gemma-2-2B · arithmetic carry variable is level. The difference to the best baseline there is too small to count as a gain.
- Many thresholds are set by hand. The cut ratio , the race margins and , the selection margins of half a standard error and , and the switch between the trained and the closed-form causal estimators are chosen by hand, not derived.
- The method is expensive and large. It runs the patched circuit and its derivatives many times per budget, and both files together run to about four thousand lines. In one matched development run on the largest model we tried, an earlier version of our circuit search took 1,086 seconds against 185 seconds for the starter.
- Filtered edges are finer than edges. At the smallest sizes some retained edges pass only a subspace of their signal. The interface counts such an edge as one edge, so the budgets are respected, but the explanation is not a pure edge set, unlike those of the ranking baselines.
- Fallbacks are silent. When a size or memory bound is exceeded, the circuit side returns its plain edge masks and the causal side shrinks or drops codecs; which path was taken on each setting is not visible in the results.
References
- Aaron Mueller, Atticus Geiger, Sarah Wiegreffe et al. (2025). MIB: A Mechanistic Interpretability Benchmark. ICML.
- Aaquib Syed, Can Rager, Arthur Conmy (2023). Attribution Patching Outperforms Automated Circuit Discovery. NeurIPS.
- Michael Hanna, Sandro Pezzelle, Yonatan Belinkov (2024). Have Faith in Faithfulness: Going Beyond Circuit Overlap When Finding Model Mechanisms. COLM.
- Samuel Marks, Can Rager, Eric J. Michaud et al. (2025). Sparse Feature Circuits: Discovering and Editing Interpretable Causal Graphs in Language Models. ICLR.
- Farnoush Rezaei Jafari, Oliver Eberle, Ashkan Khakzar et al. (2025). RelP: Faithful and Efficient Circuit Discovery in Language Models via Relevance Patching.
- Aryaman Arora, Kirill Acharya, Nathan Hu et al. (2026). Matryoshka attribution: Learning to attribute language model outputs to representations and weights.
- Atticus Geiger, Zhengxuan Wu, Christopher Potts et al. (2023). Finding Alignments Between Interpretable Causal Variables and Distributed Neural Representations.