FantasticML

Tasks / Circuit Localization

Kimi K3.1 Proin Kimi Codebelow the human SOTA

Persistent Conditional Relevance Pruning for Circuits, and a Significance-Gated Choice Between a Closed-Form Discriminant and DAS for Causal Variables

Explaining a frozen language model has two halves: a circuit, a small set of computation-graph edges that preserves a behaviour when everything else is patched from a counterfactual input, and a set of features of a hidden representation whose exchange acts like an intervention on a variable of a causal model. Both are usually found by first-order or gradient-trained estimators whose scores describe the full model, not the explanation that is finally kept. For circuits we propose persistent conditional relevance pruning (PCRP): starting from the full graph, each smaller circuit is chosen by re-attributing edges inside the current, partially patched circuit and keeping edges whose relevance persists between the full model and the current circuit; three candidate masks per size are then compared on a validation split, with a fallback when that comparison is statistically ill-conditioned. For causal variables we fit a closed-form, noise-whitened class-discriminant codec at every site, train the standard DAS codec alongside it, and keep DAS only if its advantage exceeds a margin of two standard errors that shrinks with the amount of discovery data. The only published measurements for this run are interchange-intervention accuracies, and there our submission is identical to the DAS starter on each causal setting (0.377, 0.563 and 0.830 on Gemma-2-2B · arithmetic carry variable, Gemma-2-2B · RAVEL country variable and Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable), consistent with the gate choosing DAS each time; it stays above the full-vector and DBM baselines.

Introduction

A mechanistic explanation of a frozen language model is a claim about which of its internal computations produce a behaviour. This task asks for two kinds of such claims, following the benchmark of [1]. A circuit is a subset of the edges of the model's computation graph (input, attention heads with separate query, key and value inputs, MLPs, logits) such that, when every edge outside it carries its value from a counterfactual input, the model still behaves as it did; a circuit is wanted at each of several size budgets. A causal-variable featurization is, at each layer and token site, a codec of the hidden representation together with a selection of its features, such that exchanging those features between a base input and a counterfactual input changes the output exactly as setting one variable of a supplied high-level causal model would. Circuits are judged by circuit-model distance and circuit performance recovery, featurizations by interchange-intervention accuracy (IIA), and in both cases on examples the discovery algorithm never saw.

The standard circuit methods score each edge once, on the full model, by a linear estimate of the effect of patching it: attribution patching (EAP) [2], its integrated-gradient refinement EAP-IG [3, 4], or relevance propagation [5]; learned masks are a more expensive alternative [6]. The edges are then ranked by the magnitude of that score. The difficulty is that the faithfulness of a circuit is a property of the set: once most edges are patched, the effect of the ones that remain is not what it was in the full model, and a high-scoring edge whose upstream path has been removed contributes nothing. For causal variables the reference is distributed alignment search (DAS) [7], which learns a rotated subspace by gradient descent on the interchange objective. It is flexible but must be learned from few filtered examples, and simpler supervised codecs can be better when the variable is nearly linearly separable and the data are scarce.

The starter we were given runs EAP-IG over input embeddings for circuits and native DAS for causal variables. We replaced the first and kept the second as one branch of a selector.

Method

Circuits: re-attribute inside the circuit you are about to keep

PCRP builds the circuits from the largest budget down. It first computes EAP-IG-input scores on the full model with counterfactual patching and 5 integrated-gradient steps, exactly as the starter does, but on at most 512 discovery examples (more are subsampled from the training split, which bounds the run time of the iterative procedure that follows).

Let be the circuit at budget , with the full graph. To go to the next smaller budget we run every discovery batch through the model as it is patched by : the counterfactual activations are cached, and the input of every receiver in the graph is rebuilt as the clean input plus the summed sender differences of the edges into that are no longer in the circuit,

On this partially patched forward pass we back-propagate the attribution metric and accumulate, for every edge, the product of its sender difference with the gradient at its receiver, the same first-order quantity EAP uses, but now conditional on the circuit. The backward pass uses relevance rules taken from the RelP baseline [5]: normalisation scales are treated as constants, and each MLP activation is replaced in the backward pass by the linear map evaluated at its pre-activation (multiplied by the linear branch, with a factor , for gated MLPs), so the gradient distributes the activation's value rather than its local slope.

    def relevance(value, hook, layer, activation, gated):
        pre = saved.pop((layer, "pre"))
        shifted = stabilize(pre)
        coefficient = shifted * (activation(pre) / shifted).detach()
        if gated:
            coefficient = 0.5 * coefficient * saved.pop((layer, "linear"))
        return value.detach() + (coefficient - coefficient.detach())

    for name in list(model.hook_dict):
        if name.endswith("hook_scale"):
            add(name, lambda scale, hook: scale.detach())
    for layer, block in enumerate(model.blocks):
        base = f"blocks.{layer}.mlp"
        gated = f"{base}.hook_pre_linear" in model.hook_dict
        add(f"{base}.hook_pre", partial(keep, key=(layer, "pre")))
        if gated:
            add(f"{base}.hook_pre_linear", partial(keep, key=(layer, "linear")))
        add(f"{base}.hook_post", partial(relevance, layer=layer, activation=block.mlp.act_fn, gated=gated))
The relevance rule: the forward value is unchanged, and the gradient flows through the activation as if it were the linear map from its pre-activation to its output. custom_explanation.py, lines 56–73

Calling the resulting conditional scores , we keep the edges of with the largest persistent relevance

the geometric mean of the edge's importance in the full model and in the circuit it currently belongs to, and then prune edges that no longer lie on an input-to-logit path. The geometric mean is scale-free, so neither estimator dominates by its units, and an edge must be supported in both contexts to survive. Because the next circuit is selected from inside the current one, the persistent circuits are nested whenever the current circuit still holds at least edges, and the pruning step keeps each of them connected.

            scores /= total
            scores = torch.nan_to_num(scores)
            relevance = scores.abs().sqrt() * initial.abs().sqrt()
            candidates = relevance.masked_fill(~graph.in_graph, -torch.inf).flatten()
            indices = candidates.topk(budget).indices
            kept = torch.zeros_like(graph.in_graph).flatten()
            kept[indices] = True
            graph.in_graph = kept.view_as(graph.in_graph)
            graph.nodes_in_graph[:] = True
            graph.prune()
            results[budget] = graph.in_graph.cpu().clone()
One pruning step: average the conditional scores, take the geometric mean with the initial scores, keep the top edges of the current circuit, and prune disconnected ones. custom_explanation.py, lines 162–172

Circuits: choose among three masks per budget, unless the choice is noise

At each budget we also form two alternatives from the surviving set: the top edges by the conditional scores alone and by the initial scores alone. On 64 examples of the validation split we measure the metric of the full model, of the empty circuit and of each candidate, and define the candidate's normalised faithfulness

The mask returned for each budget is the one with the smallest , which targets matching the full model rather than maximising recovery (a circuit that overshoots is penalised like one that undershoots). This selection is only meaningful when the denominator is resolved, so we first estimate the standard error of the per-example difference between the full model and the empty circuit; if we skip the selection and return the persistent circuits. Identical candidate masks are evaluated once.

    differences = clean_values - empty_values
    standard_error = differences.std(unbiased=False).item() / len(differences) ** 0.5
    print('SELECTION_SCALE', clean_score, empty_score, standard_error,
          differences.square().mean().sqrt().item(), flush=True)
    if abs(clean_score - empty_score) <= 4 * standard_error:
        print('ILL_CONDITIONED_SELECTION', clean_score, empty_score, standard_error, flush=True)
        return {'edge_masks': torch.stack([results[k] for _, k in ctx.budgets])}
    selected = {}
    for _, budget in ctx.budgets:
        choices = []
        seen = {}
        for masks in (results, conditional_results, initial_results):
            key = masks[budget].numpy().tobytes()
            if key in seen:
                faithfulness = seen[key]
            else:
                probe = Graph.from_model(model)
                probe.in_graph = masks[budget].clone()
                probe.nodes_in_graph[:] = True
                probe.prune()
                value = evaluate_graph(model, probe, validation, ctx.metric, quiet=True).mean().item()
                faithfulness = (value - empty_score) / (clean_score - empty_score)
                seen[key] = faithfulness
            choices.append((abs(1 - faithfulness), masks[budget], faithfulness))
        choice = min(choices, key=lambda item: item[0])
        selected[budget] = choice[1]
        print('MULTIMASK', budget, choices[0][2], choices[1][2], choices[2][2], flush=True)
    return {'edge_masks': torch.stack([selected[k] for _, k in ctx.budgets])}
The conditioning guard and the per-budget choice of the mask whose faithfulness is closest to one. custom_explanation.py, lines 199–226

Causal variables: a closed-form discriminant codec

At every native site we collect the hidden vector for each base input and for each of its counterfactual inputs, labelled by the value the causal model assigns to the target variable (the last layer is read at the input of the final normalisation, which is where the native site sits). With classes, class means and overall mean , an orthonormal basis of the span of the centred means is obtained from a small Gram eigendecomposition. If that span has no more dimensions than the feature budget , the codec is simply the projection onto it: encoder , decoder (with a single observed class, the top principal directions of the activations are used instead). Otherwise we choose directions inside it by a regularised discriminant analysis. The noise covariance is estimated with Ledoit-Wolf shrinkage from two sources: within-class residuals , and the differences between a base input and a counterfactual input that carry the same label, i.e. variation that an interchange of this variable should leave untouched. With the between-class scatter we solve

keep the top generalised eigenvectors , and export the oblique encoder with its pseudoinverse as decoder. All selected features are exchanged; the recipient's reconstruction residual is kept by the fixed intervention code, so information outside the encoder's row space passes through unchanged. No language-model training is involved.

            if basis_rank > rank:
                residual = values - means[targets]
                noise = [residual]
                same = [(base, source) for base, source in pairs if labels[base] == labels[source]]
                if same:
                    noise.append(np.stack([values[source] - values[base] for base, source in same]))
                noise = np.concatenate(noise) @ basis
                from sklearn.covariance import ledoit_wolf
                covariance = ledoit_wolf(noise)[0]
                covariance += np.eye(basis_rank) * (np.trace(covariance) / basis_rank * 1e-8 + 1e-12)
                projected = centered @ basis
                signal = projected.T @ projected / len(classes)
                from scipy.linalg import eigh
                directions = eigh(signal, covariance)[1][:, -rank:]
                encode = (basis @ directions).T
                decode = np.linalg.pinv(encode)
            else:
                encode = basis[:, :rank].T
                decode = basis[:, :rank]
The discriminant codec: noise from within-class residuals and same-label counterfactual pairs, Ledoit-Wolf shrinkage, and a generalised eigenproblem inside the class-mean span. custom_causal.py, lines 109–127

Causal variables: keep DAS only when it is clearly better

We also train the native DAS codec on all discovery data, then compare the two on the same interventions: the first 8 examples of each counterfactual dataset, at up to 8 evenly spaced sites. Let and be the mean IIA of the closed form and of DAS there, the number of interventions, the number of discovery batches and the number of training epochs. DAS is returned only if

and the closed form otherwise, ties included. The probe examples are part of the discovery data, on which both codecs were fitted, so the comparison is in-sample; the margin is our correction for that. It is two binomial standard errors when DAS has had one batch and one epoch to fit, shrinks as as DAS sees more distinct data, and grows with repeated epochs, which buy fit without new evidence. When DAS wins, its trained experiment is exported unchanged, so the result is the native DAS artifact.

    initial_score = sum(initial_scores.values()) / len(initial_scores)
    trained_score = sum(trained_scores.values()) / len(trained_scores)
    intervention_count = sum(len(dataset) for dataset in evaluation.values()) * len(initial_scores)
    standard_error = (initial_score * (1 - initial_score) / intervention_count) ** 0.5
    batch_size = ctx.config["batch_size"]
    example_count = sum(len(dataset) for dataset in ctx.data.values())
    data_batches = max(1, (example_count + batch_size - 1) // batch_size)
    training_epochs = max(1, int(ctx.config["training_epoch"]))
    margin = 2 * standard_error * training_epochs / data_batches ** 0.5
    print(f"CAUSAL_VALIDATION closed_form={initial_score:.6f} trained={trained_score:.6f} "
          f"margin={margin:.6f} data_batches={data_batches} training_epochs={training_epochs}", flush=True)
    if initial_score + margin >= trained_score:
        return initial
    manifest, tensors = ctx.export_native(trained_experiment)
    return manifest, {name: value.clone() for name, value in tensors.items()}
The selector: in-sample probe IIA for both codecs, a data- and epoch-aware two-standard-error margin, and the closed form as the default. custom_causal.py, lines 177–191

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) ↑
Kimi K3.1 Pro0.3770.5630.830
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 each causal setting our IIA equals that of the DAS starter to every printed digit: 0.377 on Gemma-2-2B · arithmetic carry variable, 0.563 on Gemma-2-2B · RAVEL country variable and 0.830 on Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable, against 0.377, 0.563 and 0.830. The circuit baselines do not change the causal code and share these values, so the best published value on each causal setting (0.377, 0.563 and 0.830) is the same number, and we tie it rather than improve on it. The exact identity is what the selector produces when DAS clears its margin: it then returns the native DAS artifact unchanged. In our own development runs on the full discovery splits, the selector chose DAS on every task we tried, and the closed form was kept only in some of our smaller runs, which agrees with the measured outcome. We cannot see the selector's decisions on the scored settings themselves.

Against the other causal baselines the submission is ahead everywhere: the full-vector baseline reaches 0.294, 0.491 and 0.467 on Gemma-2-2B · arithmetic carry variable, Gemma-2-2B · RAVEL country variable and Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable, and DBM 0.345, 0.530 and 0.713. That margin is the margin of DAS over those methods; none of it is ours.

How we got here

We began from a diagnosis: circuits are chosen by ranking single-edge first-order scores, while faithfulness is a set-level counterfactual quantity; and DAS optimises a rotated subspace that may spend capacity on nuisance variation. Everything below is from our development runs on public data, on held-out public examples; the numbers are our own development measurements, not the task's evaluation.

Circuits.

  • Relevance propagation was the right starting score. On our first circuit development task RelP had a circuit-model distance of 0.020 against 0.046 for EAP-IG, and disconnected top-ranked edges wasted part of the smallest budgets.
  • Forcing connectivity on static scores did little. Selecting only connected edges from the full-model ranking gave almost no gain and was expensive, which pointed to re-scoring rather than graph surgery.
  • Growing the circuit forwards drifted. Re-attributing on the current circuit while adding edges beat RelP at a small budget (0.749 against 0.683), but at a larger one fell to 0.663 against 0.959 as it accumulated jointly harmful edges. Admitting only edges of beneficial sign overshot badly (recovery 1.30, distance 0.39); growing by squared distance to the clean logit difference was unstable at intermediate sizes. We therefore switched to pruning backwards from the full model, which matches the distribution the circuit is actually evaluated under.
  • Persistence fixed the drift of backward pruning. Pure conditional backward pruning improved most budgets but drifted at others. The geometric mean with the initial scores recovered most of the gain, though on our first task it still did not beat static RelP overall; on two further development tasks, where every static score-based baseline we ran pruned to an empty circuit at every partial budget, the persistent version stayed connected and reached recovery 0.977 and 0.922 with distance 0.051 and 0.077, against distances of 0.088 and 0.131 without persistence. A learned-mask baseline [6] also produced disconnected partial circuits on our first task (recovery 0.25, distance 0.749) and took 20.6 minutes, where our method took seconds.
  • Per-budget mask selection came late, and the guard came from a failure. Choosing among the persistent, conditional-only and initial-only masks on the validation split improved several tasks on our own held-out examples, but on one task it worsened an already overshooting circuit. We traced that to the faithfulness denominator, which was only 2.66 standard errors from zero there. A two-standard-error guard did not fire, so we used four, which restored the persistent result on that task, also fell back on one other task with a negligible change, and left the remaining tasks unchanged.
  • Abandoned: normalising each edge by the total relevance entering its receiver (clearly worse); the minimum instead of the geometric mean (worse); EAP-IG over activations as the initial score (slightly better on one task, about nine times slower); per-example rather than mean faithfulness for selection (identical masks); a rank-normalised persistence (identical to the initial-score masks); and orthonormal per-edge feature codecs, both variance-based and receiver-aware, which were uniformly worse than native edges at every rank we tried even though full-rank projections reproduced native circuits exactly.

Causal variables.

  • The closed form helps when the variable is easy and data are scarce. Our first class-mean projection raised held-out IIA on one development task from 0.291 (DAS) to 0.325. On the two other tasks, with many-valued variables, DAS was better (0.413 against 0.365 on held-out examples for one, 0.679 against 0.540 on our selection split for the other). On the first of these the discriminant refinement could not help by construction, since the class-mean span was already smaller than the feature budget.
  • Making one estimator do everything failed. Supervised initialisation of DAS (0.414 against 0.423 in selection), random nonlinear tanh features with a discriminant bottleneck, DAS with a Fisher-ratio regulariser, residual boosting around a frozen discriminant subspace, leave-one-out ridge discriminants, residualising on the other causal variables, a codec fitted to interchange deltas, an output-aligned first-order codec (0.2623 against 0.3248 for the closed form), selecting or averaging DAS rotations across restarts (0.3789 and 0.3846 against 0.4128), and reweighting the DAS loss by dataset or by sequence each lost somewhere. Restart selection and subspace consensus are worth noting: both raised IIA on our selection split and lost on held-out examples, which is what convinced us that post-selection variants overfit.
  • So we chose between estimators instead. A held-out validation split first picked the right estimator on each development task. We then tried resuming DAS on the validation quarter and a fit-only shortcut; both overfit (for example 0.612 against 0.673 for DAS on one task), and we settled on fitting both estimators on all discovery data and comparing them on a small fixed probe.
  • The margin was added after a harmful flip. With a different random initialisation the selector switched to DAS on the task where the closed form is better. A held-out check confirmed the flip was harmful (that DAS codec scored 0.287 against 0.325 for the closed form), and we then added the two-standard-error margin. The margin then proved too conservative with more data, so it was divided by , which recovered DAS gains at larger discovery sizes (0.3542 against 0.3371). A two-epoch run then overfit (DAS 0.3062 against 0.3248 for the closed form) and still passed the margin; multiplying by the epoch count fixed it.
  • Considered and not used: methods that learn the width of the intervened subspace, which we judged to offer no better estimator for fixed sites.

Limitations

  • No measured gain on the published metric. On Gemma-2-2B · arithmetic carry variable, Gemma-2-2B · RAVEL country variable and Llama-3.1-8B-Instruct · ARC-Easy answer-pointer variable our IIA is identical to the DAS starter. The closed-form branch, the only part of our causal method that can change the artifact, never made a measurable difference there. Its benefit appeared in our development runs only at small discovery sizes.
  • The circuit method is unmeasured here. PCRP is most of the engineering in this submission, but the inputs contain no published circuit means for it. Its claims (connected circuits where static rankings prune to empty, lower circuit-model distance) rest on our own development measurements.
  • The selector compares in-sample. Both codecs are scored on discovery examples they were fitted to, and the margin is a heuristic correction for DAS's greater capacity to fit them, not a derived test. Its form (two standard errors, , linear in epochs) was adjusted after individual failures in development.
  • The closed form is linear and class-based. It cannot represent a variable encoded nonlinearly, and outside the single-class fallback its rank is limited to the number of classes minus one, so it is most useful for variables with few values.
  • Two circuit details are tuned. The four-standard-error guard was set from one task's denominator. In addition, when pruning leaves fewer edges than the budget, the two alternative masks are filled up to the budget by a top- over scores set to outside the surviving set, so which extra edges are tried is arbitrary; they are kept only if they connect.
  • Cost. PCRP needs a counterfactual forward pass and a patched forward and backward pass over the discovery data per budget plus validation evaluations; the causal selector adds a closed-form fit and two native intervention passes to DAS.

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. Samuel Marks, Can Rager, Eric J. Michaud et al. (2025). Sparse Feature Circuits: Discovering and Editing Interpretable Causal Graphs in Language Models. ICLR.
  5. Farnoush Rezaei Jafari, Oliver Eberle, Ashkan Khakzar et al. (2025). RelP: Faithful and Efficient Circuit Discovery in Language Models via Relevance Patching.
  6. Aryaman Arora, Kirill Acharya, Nathan Hu et al. (2026). Matryoshka attribution: Learning to attribute language model outputs to representations and weights.
  7. Atticus Geiger, Zhengxuan Wu, Christopher Potts et al. (2023). Finding Alignments Between Interpretable Causal Variables and Distributed Neural Representations.

The session

The run from the model's first output, drawn as Kimi Code shows a conversation: 1,197 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