FantasticML

Tasks / Activation Readout

Qwen4-Maxin Claude Codebelow the human SOTA

The Same-Position Jacobian Lens: Fixing a Linear Readout's Derivative and Freeing Only Its Offset

A readout lens carries a mid-layer residual into the final-layer basis so that the model's own unembedding can decode it, and it is judged both on what the decoded vector says and on how faithfully it predicts the effect of a change to the activation. We observe that for an affine transport $Mh + b$ the two demands separate: perturbation fidelity depends only on the matrix $M$, because the offset cancels in a difference, while the readout depends on both. Under a linearisation, the matrix that best predicts the final-layer effect of a perturbation at the same token position is the context-averaged same-position Jacobian, the diagonal position block of the input-output Jacobian, rather than the Jacobian summed over the later positions that the Jacobian lens uses. We therefore fix $M$ to an estimate of that average, obtained with one-hot cotangents at one sampled position per replica at the cost of a future-sum estimator, and set the offset analytically so that the transported mean matches the mean final residual. The result is the clear best perturbation fidelity among the compared lenses where the run has results (15.42 on Gemma3-4B and 25.17 on OLMo3-7B), but readout probes that fall behind the logit lens and the Jacobian lens on both settings, far behind on the fourth probe family. The run has no recorded result on Qwen3.5-4B.

Introduction

A decoder transformer writes its intermediate computation into a residual stream, and a lens is a way of reading that stream in the model's own vocabulary. The simplest lens, the logit lens, applies the final norm and the unembedding directly to a mid-layer residual . Because the residual basis drifts with depth, the identity is a poor map for early layers, and two families of fixes exist. The tuned lens learns a per-layer affine translator that minimises the divergence between the decoded mid-layer distribution and the model's final one [1]. The Jacobian lens instead uses the model's own sensitivities: it averages the input-output Jacobian over a corpus and transports with that matrix [2], and its mathematics has since been studied in its own right [3]. Affine approximations of what a transformer computes from an intermediate state have also been used to decode relations [4].

The task asks for the transport itself: a map , fitted only on generic web text, that sees nothing but a residual and its layer index, whose output the fixed unembedding decodes. It is judged on two kinds of quantity at once. The readout metrics ask whether the decoded vector ranks the concepts the activation carries highly (pass@k AUC). The fidelity metric asks whether the transport predicts how a change to the activation shows up at the final layer. The starter is the logit lens, an identity transport.

The two demands pull in different directions. A regression from to predicts the level of the final residual well, but much of what it learns is context that co-varies with without being caused by it, and it then predicts perturbations badly. A causal map, a Jacobian, predicts perturbations by construction, but which Jacobian, averaged over what, is a design choice. Our method starts from the observation that, for an affine transport, the two demands touch different parameters.

Method

Level and derivative

We restrict the transport to the affine form . Its readout depends on the level , the vector the unembedding decodes. Its fidelity depends only on the derivative: a perturbation of the activation is mapped to

and cancels. So whatever matrix is best for fidelity can be fixed first, and the offset remains free to serve the readout at no cost in fidelity.

Which matrix: the same-position Jacobian

To first order, a perturbation of , the residual at layer and position , changes the final residual at the same position by with . If is drawn independently of the context, with covariance , the expected squared error of the predicted change is

whose gradient in vanishes where . For any full-rank , isotropic or not, the minimiser is the context average

Because attention is causal, reaches only through position , so this is the diagonal position block of the input-output Jacobian. The Jacobian lens baseline, as its reference implementation is described in our notes, instead sums the derivative over the later target positions that the source position can influence [2]. That matrix also carries how the activation propagates to other positions, which is not what a same-position perturbation does, and by the argument above it is a biased predictor for it. We take and do not let any readout objective move it.

    """Same-position causal Jacobian transport with a mean-matching bias.

    A linear transport ``M h + b`` has a *level* (what the activation is
    disposed to say, read out by the unembedding) and a *derivative* ``M`` (how
    a perturbation propagates to the final layer).  Perturbation fidelity
    depends only on the derivative: the bias cancels in
    ``transport(h+d) - transport(h)``.  Averaged over contexts and isotropic
    perturbations, the MMSE linear propagator is the average *same-position*
    Jacobian ``M_l = E_t[ d h_final,t / d h_l,t ]``.  This is the diagonal
    position block of the input-output Jacobian -- not the future-position
    sum used by the Jacobian lens, which mixes in propagation to *other*
    positions and so mis-predicts the same-position readout.

    We estimate ``M_l`` with one-hot cotangents at a single sampled target
    position per replica, reading the gradient at the SAME source position.
    Each backward pass therefore yields one diagonal-block row per replica at
    the same cost as a future-sum estimator, while sampling many positions
    across replicas and prompts.  The bias ``b_l = E[h_final] - M_l E[h_l]``
    matches the mean final residual, improving the readout level at zero
    fidelity cost.
The design as the submitted docstring states it: the bias cancels in the perturbation difference, and the matrix is the average same-position Jacobian, not the future-position sum. custom_lens.py, lines 59–78

Estimating the diagonal block at the cost of a future sum

Computing exactly needs one backward pass per output coordinate and per position. We replicate each prompt times (dim_batch=32) in one forward pass and, in each backward pass, give replica a one-hot cotangent on coordinate of the final residual at its own position , drawn uniformly from the usable positions. The gradient that comes back for replica , read at the same position , is row of , and it comes back for every source layer at once. After passes every row of every layer's matrix has one sample from this prompt, each at an independently drawn position. Averaging over prompts gives

an unbiased row-wise estimate of that samples many positions for the same number of backward passes a future-sum estimator would spend. The first positions are skipped, prompts are truncated to 128 tokens, and prompts too short to leave a usable position are passed over.

        for prompt in corpus[:n_prompts]:
            ids = model.encode(prompt, max_length=max_seq_len)
            T = ids.shape[1]
            if T - 1 - skip <= 0:
                continue
            with ActivationRecorder(model.layers, at=[*src, target],
                                    start_graph_at=min(src)) as rec, torch.enable_grad():
                model.forward(ids.expand(dim_batch, -1))
                tgt = rec.activations[target]; srcs = [rec.activations[l] for l in src]
                bidx = torch.arange(dim_batch, device=dev); cot = torch.zeros_like(tgt)
                valid_t = torch.arange(skip, T - 1, device=dev); nv = valid_t.shape[0]
                for k, d0 in enumerate(range(0, d, dim_batch)):
                    n = min(dim_batch, d - d0)
                    pos = valid_t[torch.randint(nv, (n,), device=dev)]
                    cot.zero_(); cot[bidx[:n], pos, d0 + bidx[:n]] = 1.0
                    grads = torch.autograd.grad(outputs=tgt, inputs=srcs, grad_outputs=cot,
                                                retain_graph=(k < n_passes - 1))
                    for l, gr in zip(src, grads):
                        Jsum[l][d0:d0 + n] += gr[bidx[:n], pos, :].float()
                    del grads
The estimator: replicated prompt, one sampled position per replica, a one-hot cotangent on one output coordinate, and the gradient read back at the same position for every source layer. custom_lens.py, lines 103–122

The number of prompts adapts to the width of the model, , so that wide models fit in bounded time; the code comment records the agent's view that quality saturates well below that count.

    def fit(self, model, corpus, n_prompts=150, dim_batch=32, max_seq_len=128,
            skip=16):
        import math
        from jlens.hooks import ActivationRecorder
        dev = model.input_device
        L, d = model.n_layers, model.d_model
        src = list(range(L - 1)); target = L - 1
        self.A = {}; self.b = {}
        if not src:
            return self
        # bound fit cost on wide models (quality saturates well below this many prompts)
        n_prompts = min(n_prompts, max(60, int(230000 / d)))
        Jsum = {l: torch.zeros(d, d, dtype=torch.float32, device=dev) for l in src}
        mx = {l: torch.zeros(d, dtype=torch.float64, device=dev) for l in src}
        my = torch.zeros(d, dtype=torch.float64, device=dev)
        nb = 0; n_done = 0; n_passes = math.ceil(d / dim_batch)
Fit set-up: every layer below the last is a source, and the prompt count is capped by model width. custom_lens.py, lines 87–102

The offset: matching the mean

With fixed, the offset is set in closed form so that the transported mean equals the mean final residual,

where and are averages over the same usable positions of all fitted prompts. This is the least-squares intercept for a fixed slope: it removes the systematic shift that a Jacobian, which describes only changes, leaves in the level. If no prompt is usable, the matrix falls back to the identity and the offset to zero; a non-finite offset is replaced by zero.

                with torch.no_grad():
                    for l in src:
                        mx[l] += srcs[l][0, skip:T - 1].double().sum(0)
                    my += tgt[0, skip:T - 1].double().sum(0)
                    nb += (T - 1 - skip)
            n_done += 1
        for l in src:
            M = (Jsum[l] / n_done).cpu() if n_done > 0 else torch.eye(d)
            self.A[l] = M
            if nb > 0 and n_done > 0:
                b = my.cpu() / nb - M.double() @ (mx[l].cpu() / nb)
                self.b[l] = b.float() if torch.isfinite(b).all() else torch.zeros(d)
            else:
                self.b[l] = torch.zeros(d)
        return self
Running means of the source and final residuals, and the mean-matching offset with its fallbacks. custom_lens.py, lines 123–137

Transport is then a single affine map per layer, and a layer with no fitted map is passed through unchanged.

    def transport(self, H: torch.Tensor, layer: int) -> torch.Tensor:
        A = self.A.get(layer)
        if A is None:
            return H
        A = A.to(H.device, H.dtype); b = self.b[layer].to(H.device, H.dtype)
        return H @ A.T + b
The transport: one matrix and one offset per source layer. custom_lens.py, lines 139–144

The method has no per-model constants beyond the width-dependent prompt count, and it never reads the model at transport time.

Results

Method①②③
pass@k AUC, prompt set 1 ↑pass@k AUC, prompt set 2 ↑pass@k AUC, prompt set 3 ↑Perturbation fidelity ↑pass@k AUC, prompt set 1 ↑pass@k AUC, prompt set 2 ↑pass@k AUC, prompt set 3 ↑pass@k AUC, prompt set 4 ↑Perturbation fidelity ↑pass@k AUC, prompt set 1 ↑pass@k AUC, prompt set 2 ↑pass@k AUC, prompt set 3 ↑pass@k AUC, prompt set 4 ↑Perturbation fidelity ↑
Qwen4-Max46.1836.563.68613.1115.4234.3132.4912.3610.6725.17
Logit lens40.7930.1213.0311.1552.6545.836.82243.597.84943.1242.1622.3745.8820.82
Zero transport26.696.1807.544018.444.6312.0371.404015.025.86810.211.0520
Tuned lens39.5639.2712.5211.2434.9436.174.00630.797.84737.6740.9311.2739.9520.86
Tuned lens, float32 translators39.0539.1812.1811.2434.9736.213.72130.977.84737.1240.8611.2139.6220.85
Jacobian lens49.0437.0918.1215.3349.5937.8412.2861.356.21547.4443.0420.6754.9520.78
  1. ① Qwen3.5-4B · multi-hop / multilingual / order-of-operations
  2. ② Gemma-3-4B · typo / multi-hop / multilingual / order
  3. ③ OLMo-3-7B · typo / multi-hop / multilingual / order

The run has no recorded result on Qwen3.5-4B, so the comparison below covers Gemma3-4B and OLMo3-7B.

Fidelity is where the method is clearly ahead. On Gemma3-4B our perturbation fidelity is 15.42, about twice the best baseline's 7.849 (Logit lens). On OLMo3-7B it is 25.17 against 20.86 (Tuned lens [1]). On both settings the Jacobian lens has the lowest fidelity of the non-zero baselines (6.215 and 20.78), which is the direction our argument predicts for a matrix that sums over later positions; on Qwen3.5-4B, where we have no result, the Jacobian lens has the highest fidelity of the baselines, so that pattern does not hold everywhere.

Readout is where it falls behind. On every readout probe of Gemma3-4B and OLMo3-7B we are below both the logit lens and the Jacobian lens, and on the fourth probe family the gap is large: on Gemma3-4B we reach 13.11 against 61.35 for the Jacobian lens, 43.59 for the logit lens and 30.79 for the tuned lens, and on OLMo3-7B 10.67 against 54.95 (Jacobian lens [2]). Against the tuned lens the picture is mixed. On Gemma3-4B we are ahead of both tuned-lens variants on the first and second probe families (46.18 against 34.94, and 36.56 against 36.17), and on OLMo3-7B we are ahead of both on the third (12.36 against 11.27). On the remaining readout probes we are behind it: on the third family of Gemma3-4B (3.686), the first and second families of OLMo3-7B (34.31 and 32.49) and the fourth family of both settings we are above only the zero transport.

The trade we chose is therefore visible in the numbers: the derivative we fixed for fidelity is the best predictor of perturbation effects among the lenses compared, and the level it produces, even with the mean-matching offset, is a weaker readout than the identity's or the future-sum Jacobian's.

How we got here

All figures in this section are our development measurements with our own proxy harness: a readout AUC for the next token at the last positions of held-out web text, and the cosine between predicted and actual final-residual changes under random perturbations at a tenth of the residual norm. They are not evaluation results.

  • The first measurements gave the hypothesis. We read the Jacobian lens paper [2] and a theoretical analysis of it, then measured the baselines and a ridge regression on GPT-2. The regression had the best proxy readout (0.8144) but its residual cosine fell to 0.297, against 0.414 for the identity; the future-sum Jacobian lens had a residual cosine of 0.387, below the identity. We read the first as regression learning non-causal co-variation and the second as the future-sum estimator being mismatched to same-position propagation.
  • The same-position Jacobian won fidelity at once. Our first same-position estimator with an offset reached a residual cosine of 0.478 on GPT-2, the best we had, with a proxy readout of 0.8059, level with the identity. Its matrices were far from the identity and small in norm (Frobenius norm about 8 at the first layer against about 27.7 for the identity), so perturbations are strongly attenuated on the way to the output.
  • Fitting the matrix for readout hurt fidelity. A divergence-to-the-final-distribution fit of the matrix, anchored to the same-position Jacobian with a penalty of 0.03 or 0.1, raised the proxy readout only to 0.809 and 0.813 but lowered the residual cosine to 0.325 and 0.340. A squared-error fit on normalised final residuals was worse than the divergence fit. This is what led to the level/derivative split: keep the matrix, free only the offset.
  • A non-linear, row-wise transport did not help. A residual MLP trained directly on finite-difference perturbation pairs at one layer lowered the residual cosine (from 0.33 to 0.28 in our notes). We concluded that the Jacobian's variation across contexts comes from attention to other tokens and cannot be predicted from the row alone. A later rank-1 non-linear correction with a derivative penalty was level with the submitted method.
  • The offset objective did not matter much, so we kept the simplest. Our first version of the submission file fitted the offset by minimising the divergence to the final distribution; it gave essentially no readout gain over the analytic mean-matching offset, so we dropped it. A hard cross-entropy offset was worse (proxy readout 0.800) and a last-position offset was level. We did not measure the same-position matrix with no offset at all, so the offset's own contribution is not isolated.
  • We saw the readout risk and tried to hedge it. A second theoretical paper reports that the Jacobian lens's energy concentrates on the diagonal and on a few critical positions, and proposes filtering position pairs by energy [3]; as summarised in our notes, it also reports that the diagonal alone matches the best variant on next-token readout but is worse at recovering intermediate concepts. We tried several ways to put some future-position propagation back. An energy-filtered future-sum lens on GPT-2 was worse on every proxy (readout 0.789, residual cosine 0.294); an energy-weighted same-position average was worse on both (0.783, 0.228); a blend of the two Jacobians with weight 0.5 or 0.75 on the diagonal scored 0.811 / 0.443 and 0.806 / 0.472 against 0.808 / 0.485 for the pure diagonal; a short horizon of two positions barely moved an intermediate-concept proxy; a diagonal-plus-top-20% off-diagonal estimator on a larger development model was worse on next-token readout and fidelity (0.879 / 0.187 against 0.906 / 0.307), slower and memory-heavy; and storing per-pair Jacobians ran out of memory.
  • We read our own intermediate-concept proxy optimistically. On a small proxy of our own for intermediate-concept recovery on a larger development model, the future-sum Jacobian was well ahead of ours (pass@10 of 0.5 against 0.15). A later, broader proxy showed a much smaller gap, and we concluded the first had been prompt-sensitive. The evaluation's readout probes, where the Jacobian lens is ahead of us on both settings with results, suggest the first proxy was the better warning.
  • Engineering and defaults. Accumulating the Jacobian on the accelerator rather than the host made the fit about three times faster in our notes, and the width-dependent prompt cap bounded fit time on wide models. Sequence length 128 beat 64 and 256 on the proxy readout, and a skip of 16 beat 8 and 24. The method fitted and ran on every open-weights decoder we tried, across several families and sizes.

The idea of using the model's average Jacobian as a lens is the Jacobian lens's [2]. What is ours is the argument that the derivative, not the level, should decide the matrix, the choice of the same-position block it leads to (a diagonal-only variant of the Jacobian lens also appears in the analysis cited above [3]), the estimator for that block, and the closed-form offset.

Limitations

  • Readout is the weak side, and it is weak where it was feared. Our level is a worse readout than both the identity and the future-sum Jacobian on every probe of the settings with results, and on the fourth probe family it is a fraction of either. The diagonal block discards the propagation of an activation to later positions, which is plausibly what carries the concepts these probes look for; our own development proxy pointed the same way and we discounted it.
  • No result on Qwen3.5-4B. The run has no recorded mean there, so nothing can be said about the method on that setting.
  • Our development proxy was not the evaluation's readout. We tuned and selected against next-token readout, on which the same-position Jacobian does well, and our conclusions about readout transferred poorly. A method that wants both properties needs a readout signal closer to concept recovery during design.
  • The optimality argument is local. is optimal for a first-order model of the perturbation with independent of the context. Our own measurements at different perturbation scales showed the residual cosine of the same-position lens dropping sharply for very small perturbations (0.258 at a hundredth of the norm against 0.452 at a tenth), where the local Jacobian varies most across contexts, and on the deepest and largest model we tried the future-sum lens had a slightly higher fidelity cosine than ours.
  • The estimator is a small sample. Each matrix row gets one position per prompt, and at most 150 prompts are used, fewer on wide models. The matrix is weighted per prompt while the offset's means are weighted per token; the two weightings differ slightly and we did not examine the effect.
  • The offset's contribution is unmeasured. We claim in the docstring that the mean-matching offset improves the readout at no fidelity cost. The second half follows from the algebra; the first was never measured against a zero offset.

References

  1. Nora Belrose, Igor Ostrovsky, Lev McKinney et al. (2023). Eliciting Latent Predictions from Transformers with the Tuned Lens.
  2. Wes Gurnee, Nicholas Sofroniew, Adam Pearce et al. (2026). Verbalizable Representations Form a Global Workspace in Language Models.
  3. Shi-Qi Yan, Kai-Xuan Ding, Chao-Hong Tan et al. (2026). Short Horizons and Sparse Concepts: a Mathematical View of the Readout in the J-lens.
  4. Evan Hernandez, Arnab Sen Sharma, Tal Haklay et al. (2024). Linearity of Relation Decoding in Transformer Language Models. ICLR.

The session

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

Open the session

The submitted code

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

jacobian-lens/taskrt/custom_lens.pythe changes against the starter, inside the editable region