FantasticML

Tasks / Circuit Localization

Muse Wonder Fullin Muse Codeabove the human SOTA

Attribution-Seeded Mask Refinement and Held-Out Subspace Arbitration for Faithful Model Explanations

Edge attribution ranks every edge of a computation graph by its own first-order effect, so it cannot see interactions between edges, and a signed average over examples cancels edges whose effect changes sign or appears on only some examples. Distributed alignment search, the standard way to find the features of a causal variable, trains a rotation from random initialisation with very little data per site. We propose two changes, one per problem. For circuits, we aggregate attribution scores as mean absolute values over small chunks of examples, use them to seed a learned edge ranking that is optimised directly through a differentiable top-k mask to keep the patched circuit's output distribution close to the full model's, and emit one explicit circuit per budget that blends the learned and attribution rankings with weights chosen on validation examples. For causal variables, we build a closed-form contrastive subspace per site and let held-out interchange accuracy decide, site by site, between it and the trained rotation. Our circuits reach a CMD of 0.069 on Llama-3.1-8B · ARC-Challenge circuit and 0.041 on Gemma-2-2B · MCQA circuit, well below every published baseline; our causal features are level with distributed alignment search on Gemma-2-2B · arithmetic carry variable and slightly above it on Gemma-2-2B · RAVEL country variable and Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable.

Introduction

A mechanistic explanation of a frozen language model can take two forms [1]. A circuit is a subset of the edges of the model's computation graph that preserves a behaviour when every other edge takes its value from a counterfactual input. A causal-variable alignment is a set of features of a hidden representation that behaves like a variable of a supplied high-level causal model: exchanging those features between two inputs should change the output exactly as intervening on the variable would. Both explanations are discovered from a limited set of examples and judged on examples never seen during discovery, circuits at a range of size budgets by how far they move the model's output distribution (CMD) and how much of its behaviour they recover (CPR), alignments by interchange-intervention accuracy (IIA).

The standard tool for circuits is edge attribution patching, which scores each edge by a first-order estimate of what patching it would do [2], refined with integrated gradients along the path from counterfactual to clean inputs [3] or with relevance propagation [4]. Two properties of these scores limit them. They are per-edge. A circuit is evaluated as a whole, and the first-order effect of an edge says little about what it does once most other edges have been patched away, which is exactly the regime of the small budgets. They are signed averages over examples. An edge that pushes the output one way on some examples and the other way on others, or that matters only on a subset, receives a small average score even when it is essential to each example it touches.

The standard tool for causal variables is distributed alignment search (DAS), which learns an orthogonal rotation of a site's representation and intervenes on a low-dimensional subspace of it [5]. Its weakness here is data and optimisation: the rotation starts at random, and with the training amount the native configuration gives each site it takes very few gradient steps. A closed-form subspace computed from the same examples needs no optimisation at all, but whether it is any good depends on the task.

Method

Our method has two independent parts, one for each editable function. Both share one principle: whenever we have a choice that cannot be settled in advance, we settle it on discovery examples that the fitting step did not use, and we keep the starter's method as a fallback for every stage.

Chunked mean-absolute attribution

We start, as the starter does, from integrated-gradient edge attribution with 5 steps. Instead of one signed average over all discovery examples, we compute the attribution score of every edge on small chunks of at most 5 examples, with chunk sizes , and aggregate

The magnitude is a mean of absolute chunk scores, so an edge whose effect varies in sign across examples, or that fires only on some of them, is no longer averaged towards zero; the sign is that of the ordinary signed mean. If this stage fails for any reason we fall back to the starter's attribution call.

        for clean, corrupted, labels in ctx.dataloader:
            n_b = len(clean)
            sub_bs = max(1, min(5, n_b))
            for i0 in range(0, n_b, sub_bs):
                sub = (clean[i0:i0 + sub_bs], corrupted[i0:i0 + sub_bs], labels[i0:i0 + sub_bs])
                sc = get_scores_eap_ig(model, graph, [sub], ctx.attribution_metric, steps=5, quiet=True)
                sc = sc.detach().float().cpu()
                w = float(i0 + sub_bs if i0 + sub_bs <= n_b else n_b) - float(i0)
                signed_sum = sc * w if signed_sum is None else signed_sum + sc * w
                abs_sum = sc.abs() * w if abs_sum is None else abs_sum + sc.abs() * w
                total_n += int(w)
        if signed_sum is not None and total_n > 0:
            signed_mean = signed_sum / total_n
            attr_scores = (abs_sum / total_n) * signed_mean.sign()
            graph.scores[:] = attr_scores.to(graph.scores.device, graph.scores.dtype)
Attribution on chunks of at most five examples, aggregated as a mean absolute score carrying the sign of the signed mean. custom_explanation.py, lines 83–97

Learning an edge ranking through a differentiable top-k mask

Attribution gives us a ranking; what we want is a ranking whose top- edges form a good circuit at every budget . We therefore learn one real score per edge and optimise it through the circuit itself. Given a budget and a temperature , the soft mask is

with found by 30 steps of bisection. Because depends on , the gradient must respect the constraint that the mask mass stays at . Writing , the backward pass we use is the implicit gradient of the constrained mask,

so that raising one edge's score necessarily pushes the others out of the budget.

    class SigmoidTopK(torch.autograd.Function):
        @staticmethod
        def forward(cctx, sc, k, T):
            lo = sc.detach().min() - 10 * T
            hi = sc.detach().max() + 10 * T
            kk = torch.as_tensor(float(k), device=sc.device, dtype=sc.dtype)
            with torch.no_grad():
                for _ in range(30):
                    mid = (lo + hi) / 2
                    f = torch.special.expit((sc - mid) / T).sum()
                    lo = torch.where(f > kk, mid, lo)
                    hi = torch.where(f > kk, hi, mid)
            tau = (lo + hi) / 2
            mask = torch.special.expit((sc - tau) / T)
            cctx.save_for_backward(mask)
            cctx.T = T
            return mask

        @staticmethod
        def backward(cctx, grad_output):
            (mask,) = cctx.saved_tensors
            sp = mask * (1.0 - mask)
            sp_sum = sp.sum().clamp(min=1e-8)
            gsp = (grad_output * sp).sum()
            return (sp / cctx.T) * (grad_output - gsp / sp_sum), None, None
The sigmoid top-k mask: bisection for the threshold in the forward pass, the constraint-respecting gradient in the backward pass. custom_explanation.py, lines 268–292

The circuit is run as a soft patch. For models without a normalisation after the summed attention output, at every receiving node (the query, key and value inputs of each attention layer, each MLP input and the logits) we add, to the clean activation, the counterfactual-minus-clean difference of every sender weighted by :

With every this is the full model; with every every edge carries the counterfactual value. The model's weights are frozen, only receives gradients, and the counterfactual activations of each batch are cached up to a memory limit. The loss at the final position is the KL divergence from the full model's next-token distribution to the patched circuit's, plus a small penalty on the change in the logit difference between the correct and the counterfactual answer:

        logits = model.run_with_hooks(clean_tokens, fwd_hooks=hooks, attention_mask=attn_mask)
        pos = (lengths - 1).clamp(min=0)
        idx = torch.arange(B, device=device)
        lp = logits[idx, pos].float()
        cp = clean_logits[idx, pos].float().detach()
        kl = F.kl_div(F.log_softmax(lp, -1), F.softmax(cp, -1), reduction="batchmean")
        good = torch.tensor([l[0] for l in labs], device=device)
        bad = torch.tensor([l[1] for l in labs], device=device)
        ld_p = lp[idx, good] - lp[idx, bad]
        ld_c = cp[idx, good] - cp[idx, bad]
        return kl + 0.01 * F.mse_loss(ld_p, ld_c)
The training loss: KL from the full model's distribution to the patched circuit's, plus a small logit-difference term. custom_explanation.py, lines 420–430

Each step draws a budget from the grid of the requested budget fractions (excluding the full graph), with the budgets at or below 0.5% listed twice so that small circuits are sampled more often, and jitters it by a factor , . Scores are initialised to half the normal quantile of each edge's attribution rank and trained with Adam at learning rate 0.05 for at most 600 steps, under a wall-clock cap of four times the attribution time, clamped to between 200 and 1200 seconds. Learned rankings drift and overfit when trained long, so we keep snapshots: at regular intervals we form hard circuits at a few budgets from the current scores, measure them on a slice of validation examples that is disjoint from the training pool when the validation split is large enough, using a recovered-logit-difference ratio minus a KL term as objective, keep the best snapshot, and stop after two intervals without improvement.

One explicit circuit per budget

In our development runs the learned ranking was much better than attribution at small budgets and worse in the tail, where most edges are kept and attribution better preserves the full output distribution. Since the interface accepts an explicit circuit per budget, we do not have to choose. We convert both rankings to normal scores of their ranks, for the learned scores and for the absolute attribution scores, and form the circuit at budget from the top edges of

with a default that falls from 1 at the smallest budgets to 0.3 and then to 0 for the full graph. On the validation slice we then try and at the snapshot budgets, keep the best, and interpolate in log-budget between them.

    def rank_z(x):
        r = x.flatten().float().argsort().argsort().float()
        p = ((r + 0.5) / len(r)).clamp(1e-4, 1 - 1e-4)
        return torch.special.ndtri(p).view(x.shape)

    def build_masks(learned, alphas):
        zl, za = rank_z(learned), rank_z(attr_scores.abs())
        masks = []
        for n, a in zip(budgets_n, alphas):
            s = a * zl + (1.0 - a) * za
            graph.scores[:] = s.to(graph.scores.device, graph.scores.dtype)
            graph.apply_topn(n, True)
            masks.append(graph.in_graph.detach().cpu().clone())
        return torch.stack(masks)

    # budget-dependent blend weights (learned weight), monotone in budget rank
    def alphas_for(pcts):
        out = []
        for p in pcts:
            if p <= 0.0015:
                out.append(1.0)
            elif p <= 0.0035:
                out.append(0.95)
            elif p <= 0.0075:
                out.append(0.9)
            elif p <= 0.015:
                out.append(0.85)
            elif p <= 0.035:
                out.append(0.75)
            elif p <= 0.075:
                out.append(0.6)
            elif p <= 0.15:
                out.append(0.5)
            elif p <= 0.35:
                out.append(0.4)
            elif p <= 0.75:
                out.append(0.3)
            else:
                out.append(0.0)
        return out
Rank-normal scores, the per-budget blend of learned and attribution rankings, and the default blend schedule. custom_explanation.py, lines 111–150

Any failure of refinement or non-finite learned scores returns the attribution ranking alone; a non-finite loss stops training at the best snapshot so far.

Causal variables: a closed-form competitor and a held-out referee

For the causal variable we pair every discovery input with each of its counterfactual sources and hold out a fifth of the pairs, at most 160. On the remaining pairs we do two things at every site.

First, we train native DAS exactly as the starter does, but on the fit pairs only.

Second, we build an ordered orthonormal basis in closed form. With activations of bases and sources, the variable's value for each input from the causal model, paired differences , split into (pairs where the variable changes) and (pairs where it does not), each centred, and the activations centred within each class of , we collect candidate directions: class-mean contrasts, the mean changed-pair difference, the weight vectors of a multinomial linear probe for , and up to 192 principal directions of . Each unit candidate is scored by a Fisher-style ratio of variable-change signal to nuisance variation,

where stacks the class-mean contrasts and is the mean squared within-class activation. Candidates are taken in decreasing ratio and orthogonalised greedily, keeping a direction only if more than 0.3 of its norm survives the projection.

    def energy(mat, v):
        proj = mat @ v
        return float(proj.pow(2).mean())

    scored = []
    for i in range(cand.shape[0]):
        v = cand[i]
        nv = float(v.norm())
        if nv < 1e-8:
            continue
        v = v / nv
        sig = energy(M, v) * max(1, len(X)) + energy(Dc_c, v)
        noise = energy(Xw, v) + energy(Ds_c, v) + alpha
        scored.append((sig / noise, v))
The Fisher-style ratio that orders candidate directions: class-mean and changed-pair energy over within-class and unchanged-pair energy. custom_causal.py, lines 238–251

The width of the closed-form subspace is the number of directions whose ratio is at least a tenth of the best, clamped between half and twice the native feature count. The three candidates at each site, the trained DAS rotation, the closed-form basis at that width and the closed-form basis at the native width, are then evaluated by interchange interventions on the held-out pairs, and each site keeps the most accurate. A candidate replaces DAS only if it is strictly more accurate, so DAS keeps every tie. Any failure while evaluating the candidates on the held-out pairs exports the trained DAS result; any other failure reruns the starter.

    n_fish = 0
    for unit, sid, B, kk in zip(flat_units, site_keys, bases, default_ks):
        best_acc, choice = acc_das.get(sid, -1.0), "das"
        if acc_fish.get(sid, -1.0) > best_acc:
            best_acc, choice = acc_fish[sid], "fish"
        if acc_fish_k0 is not None and acc_fish_k0.get(sid, -1.0) > best_acc:
            choice = "fish_k0"
        if choice == "das":
            install(unit, das_rot[sid], None, "DAS")
        elif choice == "fish":
            n_fish += 1
            install(unit, B[:, :kk].contiguous(), list(range(kk)), "fisher")
        else:
            n_fish += 1
            kk2 = min(k0, B.shape[1])
            install(unit, B[:, :kk2].contiguous(), list(range(kk2)), "fisher")
Per-site arbitration on held-out pairs between the trained rotation and two widths of the closed-form basis. custom_causal.py, lines 165–180

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) ↑
Muse Wonder Full0.1450.8540.0690.9300.4300.5630.945
EAP-IG + DAS0.1450.8540.0690.9300.3770.5630.830
EAP0.1600.8450.0680.9310.3770.5630.830
EAP-IG-activations0.0660.9350.3770.5630.830
RelP0.1540.8450.0940.9150.3770.5630.830
MAttr0.4460.6010.4290.5700.3770.5630.830
Random circuit0.7400.2590.6610.3380.3770.5630.830
Full vector0.1450.8540.0690.9300.2940.4910.467
DBM0.1450.8540.0690.9300.3450.5300.713
  1. ① Llama-3.1-8B · ARC-Challenge circuit
  2. ② Gemma-2-2B · MCQA circuit
  3. ③ Gemma-2-2B · arithmetic carry variable
  4. ④ Gemma-2-2B · RAVEL country variable
  5. ⑤ Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable

On circuits the gains are large on both settings. On Llama-3.1-8B · ARC-Challenge circuit our CMD is 0.069 against 0.145 for the strongest published baseline, EAP-IG-inputs and DAS [5], and our CPR is 0.976 against 0.854 for the starter. On Gemma-2-2B · MCQA circuit our CMD is 0.041 against 0.066 (EAP-IG-activations [6]), and our CPR is 1.037: on that setting our circuits recover slightly more of the behaviour than the full model does. The circuits are explicit per budget, so they are not nested; this is allowed by the interface, and it is what lets the blend favour the learned ranking at small budgets and attribution at large ones.

On causal variables our method is level with DAS, as the design intends. On Gemma-2-2B · arithmetic carry variable we reach 0.376 against 0.377 for the starter, a hair below it; on Gemma-2-2B · RAVEL country variable 0.572 against 0.563; and on Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable 0.835 against 0.830. All three are well above the full-vector baseline (0.294, 0.491 and 0.467) and the DBM baseline (0.345, 0.530 and 0.713). The size of these differences against DAS is small, and we do not claim that the closed-form subspace improves the causal track in general; what the numbers show is that admitting it did not cost accuracy on two of the settings and cost very little on the third.

How we got here

We began by building a local evaluation of circuits with public models and data, and compared the published attribution methods on it. In those development runs integrated-gradient attribution beat plain attribution patching, as expected, and more integration steps or relevance propagation added little.

  • Re-weighting and greedy selection of attribution scores gave little. Our first ideas stayed inside the attribution paradigm: consistency weighting of scores across halves of the data, and greedy construction of circuits from the scores. Neither moved the measured circuits much, which pointed to the per-edge nature of the scores rather than their aggregation as the bottleneck at that stage.
  • Optimising the circuit directly was the large step. Learned edge masks trained on a KL objective are a known idea in circuit discovery; we found it through a literature search and built a differentiable top-k version seeded by attribution. After only 120 steps, our development measure of CPR over budgets rose from 0.75 to 0.96. Training longer (500 steps) made it worse, at 0.82, with the tail of the ranking degrading even on training examples. A straight-through variant with annealing also did worse than the early soft snapshot. These two observations are the origin of the snapshot selection on validation examples and of the per-budget blend with attribution, which together gave our best development result at that point.
  • Several refinements of the training were measured and dropped. KL-based attribution as a seed did not help the tail; cosine annealing and weight averaging plateaued at the level of the early snapshot; exact greedy swaps on validation gained about 0.02 of the validation objective for roughly 157 seconds of evaluation and were too slow; gradient-guided swaps overfitted the small validation slice; greedy, connectivity-aware formation of circuits from the learned scores was worse than taking their top edges; a softer mask temperature (0.5) and a sharper one (0.15) were both worse than 0.3; ensembling snapshots or seeds was neutral.
  • Projecting circuit edges onto subspaces destroyed them. The interface also allows circuits of orthonormal feature subspaces of each edge. A projection onto the leading principal directions of the edge differences took our development CPR from 0.98 to 0.15: the per-example signal does not live in a global low-rank subspace. We dropped that axis entirely.
  • Budget sampling and the loss mixture were set by ablation. Sampling budgets from the requested grid was better than log-uniform sampling, doubling the weight of the smallest budgets helped slightly, and reducing the logit-difference weight from 0.05 to 0.01 was adopted after a comparison with and without the term. Choosing the blend weights on validation added 0.035 to our development CPR measure.
  • Chunked mean-absolute attribution came last. Late in the run we tested whether the signed average over examples was hiding edges. With attribution alone, the mean-absolute aggregation lowered our development CMD measure from 0.303 to 0.278 on one task and from 0.925 to 0.610 on another, and the gain survived the full pipeline. Chunks of 5 examples were better than chunks of 1 or 2 and than the full batch.

On the causal side, we first noted that DAS receives only about one epoch of training per site and concluded it was undertrained, so we built the closed-form subspace, first as an initialisation for DAS and then as a replacement.

  • The closed-form subspace alone looked better on the first proxy. On our first development task it reached 0.346 IIA against 0.327 for DAS trained on the same examples, and fine-tuning DAS from the closed-form basis destroyed it (0.307).
  • On a second proxy it was far worse, and that changed the design. There DAS reached 0.771 and the closed-form subspace 0.441. This is why the final method arbitrates per site on held-out pairs instead of replacing DAS: on a third task the arbitrated method reached 0.49 against 0.41 for the closed-form subspace alone, and on the second it matched DAS (0.771 against 0.771).
  • A silent fallback hid a bug for a while. An early version of the arbitration installed the new basis before clearing the old feature indices, which failed validation and quietly fell back to DAS; clearing the indices first fixed it.
  • Other DAS variants were worse. Smaller DAS batches and a different scheduler gave no gain, and selecting a subset of DAS's own dimensions was much worse. Adding linear-probe directions to the candidate pool gave a small consistent gain and was kept.

In the final development runs the closed-form subspace won at only a minority of sites on every proxy task, between 1 and 8 of 56. The causal component is therefore mostly DAS with an escape hatch, and its value lies in the protection the arbitration gives, not in a large gain.

Limitations

  • The causal track is essentially unchanged. Our IIA is a hair below the starter's on Gemma-2-2B · arithmetic carry variable and only slightly above it on Gemma-2-2B · RAVEL country variable and Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable. One cost of the design is visible in the code: DAS is now trained on the pairs left after the held-out slice, fewer than the starter uses, so the arbitration has to recover what the smaller training set loses. We cannot tell from the available outputs whether that explains the small deficit on Gemma-2-2B · arithmetic carry variable.
  • Held-out arbitration is noisy. At most 160 held-out pairs decide each site, and a strict improvement on them is enough to replace DAS, so some replacements will be lucky ones that do not transfer.
  • Circuits above a CPR of one are not an unmixed good. A circuit that recovers more of the logit difference than the full model on Gemma-2-2B · MCQA circuit is not reproducing the model exactly; our training objective is a KL divergence, which penalises that, but the blend weights are chosen on an objective that rewards recovered logit difference without a cap. A capped version picked the same snapshot in our development runs, but we did not test whether it would pick the same blend.
  • Many constants are tuned, not derived. The blend schedule, the temperature, the snapshot budgets, the number of training and validation examples and the batch sizes are fixed by hand, and several of them scale with the model's hidden width. They were tuned on small public models only.
  • The method is expensive. Refinement runs many patched forward and backward passes under a wall-clock cap tied to the attribution time. We measured its gains only on small public models and its cost at a larger scale in a single smoke run, so how much of the gain survives on larger models is not something our development runs show.
  • Development evidence for the causal track rests on proxies. The models we could download locally are not the ones the task uses, and our proxies disagreed sharply with each other about the closed-form subspace, which is the reason the final method does not trust it by default.

References

  1. Aaron Mueller, Atticus Geiger, Sarah Wiegreffe et al. (2025). MIB: A Mechanistic Interpretability Benchmark. ICML.
  2. Aaquib Syed, Can Rager, Arthur Conmy (2023). Attribution Patching Outperforms Automated Circuit Discovery. NeurIPS.
  3. Michael Hanna, Sandro Pezzelle, Yonatan Belinkov (2024). Have Faith in Faithfulness: Going Beyond Circuit Overlap When Finding Model Mechanisms. COLM.
  4. Farnoush Rezaei Jafari, Oliver Eberle, Ashkan Khakzar et al. (2025). RelP: Faithful and Efficient Circuit Discovery in Language Models via Relevance Patching.
  5. Atticus Geiger, Zhengxuan Wu, Christopher Potts et al. (2023). Finding Alignments Between Interpretable Causal Variables and Distributed Neural Representations.
  6. Samuel Marks, Can Rager, Eric J. Michaud et al. (2025). Sparse Feature Circuits: Discovering and Editing Interpretable Causal Graphs in Language Models. ICLR.
  7. Aryaman Arora, Kirill Acharya, Nathan Hu et al. (2026). Matryoshka attribution: Learning to attribute language model outputs to representations and weights.

The session

The run from the model's first output, drawn as Muse Code shows a conversation: 358 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

mib-explanation/taskrt/custom_explanation.pythe changes against the starter, inside the editable region

mib-explanation/taskrt/custom_causal.pythe changes against the starter, inside the editable region