FantasticML

Tasks / Activation Readout

Claude Opus 5.5in Claude Codeabove the human SOTA

HDJ: Separating Same-Position and Future Effects in the Jacobian Lens

A readout lens transports a mid-layer residual into the final-layer basis so that the model's own unembedding can decode it, and it is asked to do two things that pull against each other: recover latent, not-yet-said content, and predict faithfully how a perturbation of the residual propagates. We observe that the corpus-averaged Jacobian used by the Jacobian lens mixes two different operators, the same-position Jacobian, which is what a perturbation actually does, and a future-position part, which carries what the activation will make the model say later. We estimate both from the same backward passes, take them with respect to the normalised final residual, strip the future part of its dominant corpus-variance output modes and strip everything except the identity path of a contrastive subspace that format tokens read far more than content tokens, and drop the future part in the earliest layers. A gated calibration fixes the response magnitude when the unembedding has a logit-inert direction. The lens is ahead of every published baseline on probe sets 3 and 4 wherever they are scored, and on probe set 2 and perturbation fidelity on Qwen3.5-4B and OLMo3-7B, but it trails the Jacobian lens on probe set 1 on every setting, and on Gemma3-4B its perturbation fidelity collapses to 0.017, against 7.849 for the best baseline.

Introduction

A lens reads out what an internal residual-stream activation of a decoder transformer is disposed to make the model say. It maps a residual at layer into the final-layer residual basis, and the model's own final norm and unembedding decode the result into a ranking of the vocabulary:

The question this task poses is what the transport should be. It must work from a residual and its layer index alone, it may be fitted only on generic web text, and it is judged on two things at once: how much latent content the readout recovers, and how faithfully it predicts what a small change to does to the model's output.

The field offers three reference points. The logit lens uses the identity: simple, training-free, but early residuals are not yet in the final basis, so it under-reads them. The tuned lens learns a per-layer affine translator trained to match the model's final distribution [1]. The Jacobian lens transports by the corpus-averaged input-output Jacobian of the residual stack [2].

What makes the problem hard is that the two goals pull against each other, and the existing transports sit at different points of that trade-off without saying so. Our starting observation is that the Jacobian lens averages, over every later position , the response of the final residual to . Only the term is what a perturbation of the residual does to its own read-out position; the terms describe what the activation is disposed to make the model say later, which is where latent content lives but which a same-position perturbation does not produce. A transport that does well on both goals has to separate those two quantities and treat them differently.

Method

We call the method the horizon-decomposed Jacobian lens (HDJ). It is a per-layer linear map , assembled at fit time from four pieces, plus an optional magnitude calibration.

Splitting the Jacobian by horizon

Let be the final residual and the vector the final norm hands to the unembedding (we use ). We take every Jacobian with respect to rather than , so that each context is weighted by how its logits actually respond. The quantity the Jacobian lens transports by is the summed Jacobian, which we split into a same-position part and a future part:

is the best constant linear predictor of the same-position response, the faithful part; is the broadcast part, which carries content the activation will make the model say at later positions.

Both are estimated from the same forward pass. Each prompt is replicated DIM_BATCH times so that a block of output coordinates can be back-propagated at once. For each block we run two backward passes. The first places a one-hot cotangent at every valid target position, which returns row of at every source position . The second places the same cotangent multiplied by an independent Rademacher sign per target position, and we demodulate the gradient at source by :

because every cross-position term has zero mean. Rows are averaged over the valid source positions (positions from 16 to the second-to-last, the first 16 being treated as attention sinks) and over prompts. The signs come from a generator seeded with 0, so the fit is deterministic unless the wall-clock cap below binds.

            # to the unembedding): logit-space Jacobian, per-context 1/rms weighting
            y = rec.activations[target].float()
            tgt = y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + 1e-6)
            srcs = [rec.activations[l] for l in sources]
            pos = torch.arange(self.SKIP_FIRST, T - 1, device=tgt.device)
            b = torch.arange(db, device=tgt.device)
            cot = torch.zeros_like(tgt)
            k, total = 0, 2 * n_passes
            for d0 in range(0, d, db):
                n = min(db, d - d0)
                for mode in ("sum", "self"):
                    cot.zero_()
                    if mode == "sum":
                        cot[b[:n, None], pos[None, :], d0 + b[:n, None]] = 1.0
                    else:
                        s = torch.randint(0, 2, (n, pos.numel()), device=tgt.device,
                                          generator=gen).to(cot.dtype) * 2 - 1
                        cot[b[:n, None], pos[None, :], d0 + b[:n, None]] = s
                    grads = torch.autograd.grad(tgt, srcs, grad_outputs=cot,
                                                retain_graph=(k < total - 1))
                    k += 1
                    for l, g in zip(sources, grads):
                        g = g[:n][:, pos.to(g.device), :].float()
                        if mode == "sum":
                            acc_sum[l][d0:d0 + n] += g.mean(1).to(acc_sum[l].device)
                        else:
                            sg = s[:, :, None].float().to(g.device)
                            acc_self[l][d0:d0 + n] += (g * sg).mean(1).to(acc_self[l].device)
One forward, two backward passes per block of output coordinates: a one-hot cotangent for the summed Jacobian and a sign-modulated one, demodulated at the source, for the same-position Jacobian. custom_lens.py, lines 161–188

The fit loop stops after 40 prompts, or earlier once at least 12 are in and a fixed wall-clock cap is passed; on running out of GPU memory it restarts with half the replication.

Removing the structural modes of the broadcast part

Inspecting what the future part alone reads out showed that its top ranks are filled with generic text structure: line and paragraph breaks, sentence ends, quotes, runs of underscores. Those predictions are shared by almost every input, crowd item-specific content out of the top-, and add a response to same-position perturbations that the model does not have. We identify them as the output directions that carry most of the second moment of over corpus residuals. With the uncentred second moment of layer- residuals (positions 16 to 126 of up to 1024 further corpus sequences), we take the top eigenvectors of

and project them out of the broadcast part only:

The projection is applied to the future part and not to the same-position part, because the structure in is part of the true perturbation response; "How we got here" records what happened when we projected it out of both.

In the first source layers, the number of layers, the broadcast term is dropped altogether. At those depths the residual is still token-level, we found almost no recovered content there, and the future part only costs same-position faithfulness.

A contrastive vocabulary prior

The variance criterion above depends on the fitting corpus. A second prior that does not comes from the vocabulary: tokens whose decoded text contains no alphanumeric character (punctuation, whitespace, line breaks, separators) carry format, not latent content. Let be the readout vector of token , obtained by applying the model's unembedding to the unit residuals, and let and be the mean of over the format tokens and over the remaining (content) tokens. We want the output directions that format tokens read much more than content tokens do, which is a generalised eigenproblem:

The top solutions, orthonormalised, form . Because they are contrastive, these directions barely move content-token logits.

    def _structural_basis(self, model):
        """R_STRUCT output-space directions that structural tokens read much more than
        content tokens: top generalized eigenvectors of (C_struct, C_content), the
        second moments of the tokens' readout vectors.  model.unembed of the unit
        residuals gives every token's readout vector (up to a constant)."""
        d = self.d_model
        E = torch.eye(d, device="cuda", dtype=torch.float32)
        W = torch.cat([model.unembed(E[i:i + 256]) for i in range(0, d, 256)])   # [d, V]
        mask = self._structural_mask(model.tokenizer, W.shape[1]).to(W.device)
        ns = int(mask.sum())
        nc = W.shape[1] - ns
        if ns < self.R_STRUCT or nc < d:
            return None
        Ws = W[:, mask].double()
        Cs = Ws @ Ws.T
        G = torch.zeros(d, d, dtype=torch.float64, device=W.device)
        for j in range(0, W.shape[1], 16384):
            B = W[:, j:j + 16384].double()
            G += B @ B.T
        Cc = (G - Cs) / nc
        Cs = Cs / ns
        del W, Ws, G
        Id = torch.eye(d, dtype=torch.float64, device=Cs.device)
        Lc = torch.linalg.cholesky(Cc + 1e-3 * torch.trace(Cc) / d * Id)
        Li = torch.linalg.solve_triangular(Lc, Id, upper=False)
        _, U = torch.linalg.eigh(Li @ Cs @ Li.T)
        Q, _ = torch.linalg.qr(Li.T @ U[:, -self.R_STRUCT:])
        return Q.float()
The contrastive structural subspace: generalised eigenvectors of the format-token versus content-token second moments of the model's own unembedding rows. custom_lens.py, lines 210–237

We project out of everything the lens adds on top of the activation itself, keeping the identity path exact. With and ,

The assembly of in fit, including the fallbacks to the uncleaned map when a step fails or produces non-finite values, is:

        for l in sources:
            Js = acc_self[l] / n_done
            Jf = acc_sum[l] / n_done - Js
            if l < self.n_layers // 10:
                Jf = torch.zeros_like(Jf)            # pre-workspace: no broadcast term
            M = Js + self.ALPHA * Jf
            try:
                C = Jf.double() @ S[l].double().to(Jf.device) @ Jf.double().T
                C = 0.5 * (C + C.T)
                _, U = torch.linalg.eigh(C)
                V = U[:, -self.K_MODES:].float()
                Jf = Jf - V @ (V.T @ Jf)
                Mc = Js + self.ALPHA * Jf
                if bool(torch.isfinite(Mc).all()):
                    M = Mc
            except Exception:  # noqa: BLE001
                pass
            if Ws is not None:
                try:
                    W = Ws.to(M.device)
                    c = torch.trace(Js) / Js.shape[0]
                    P = M - c * torch.eye(M.shape[0], device=M.device, dtype=M.dtype)
                    Ms = M - W @ (W.T @ P)          # = c I + P_s (M - c I)
                    if bool(torch.isfinite(Ms).all()):
                        M = Ms
                except Exception:  # noqa: BLE001
                    pass
            if not bool(torch.isfinite(M).all()):
                M = torch.nan_to_num(M, nan=0.0, posinf=0.0, neginf=0.0)
Assembling the per-layer map: split, zero the broadcast part in the earliest layers, remove its variance modes, then project the contrastive subspace out of everything except the scalar identity path. custom_lens.py, lines 339–367

Gated magnitude calibration

The final norm makes the readout depend only on the direction of the transported vector, but the size of the predicted response to a perturbation is . Since targets the normalised residual, the response is on the model's scale when the transported vector has rms 1, which a linear map does not guarantee. We correct this only when the unembedding has a logit-inert direction , a direction that every token reads almost equally, so that adding it shifts all logits uniformly and leaves the ranking alone. We take as the smallest eigenvector of the token-centred readout Gram and accept it only if .

    def _inert_direction(self, model):
        """Unit output direction whose logits vary least across tokens (smallest
        eigenvector of the token-centred readout Gram), if it is nearly uniform."""
        d = self.d_model
        E = torch.eye(d, device="cuda", dtype=torch.float32)
        W = torch.cat([model.unembed(E[i:i + 256]) for i in range(0, d, 256)])   # [d, V]
        mu = W.float().mean(1, keepdim=True).double()
        G = torch.zeros(d, d, dtype=torch.float64, device=W.device)
        for j in range(0, W.shape[1], 16384):
            B = W[:, j:j + 16384].double() - mu
            G += B @ B.T
        del W
        ev, U = torch.linalg.eigh(G)
        ratio = float((ev[0].clamp_min(0) / ev.mean()).sqrt())
        if not ratio < self.INERT_TOL:
            return None
        return U[:, 0].float().cpu().contiguous()
Finding a logit-inert output direction and gating on how inert it is. custom_lens.py, lines 240–256

When the gate fires, layer stores , the root-mean-square of over corpus residuals, provided , and the transport becomes

which essentially keeps the ranking and keeps the direction of the predicted response and puts its magnitude on the model's scale. When the gate does not fire, or falls outside that range, .

    def transport(self, H: torch.Tensor, layer: int) -> torch.Tensor:
        M = self.maps.get(layer)
        if M is None:
            return H
        Hf = H.float().reshape(-1, self.d_model)
        if M.device != Hf.device:
            M = M.to(Hf.device)
            self.maps[layer] = M      # keep the device copy (same values, no state in the output)
        # fixed-size row blocks: every GEMM has the same shape, so a row's output is
        # bit-identical whatever rows share its batch
        B, n = self.ROW_BLOCK, Hf.shape[0]
        if n == 0:
            return Hf
        pad = (-n) % B
        if pad:
            Hf = torch.cat([Hf, Hf.new_zeros(pad, Hf.shape[1])])
        MT = M.T
        out = torch.cat([Hf[i:i + B] @ MT for i in range(0, Hf.shape[0], B)])[:n]
        a = self.scale.get(layer) if self.inert is not None else None
        if a is not None:
            u = self.inert.to(out.device, out.dtype)
            b = max(0.0, float(self.d_model) - a * a) ** 0.5
            out = a * out / out.norm(dim=-1, keepdim=True).clamp_min(1e-12) + b * u[None, :]
        return out
The transport: a fixed-block matrix product, bit-identical for any batch composition, followed by the calibrated normalisation when an inert direction was found. custom_lens.py, lines 382–405

The product is computed in fixed blocks of 64 rows, padded with zeros, so that every matrix multiply has the same shape and a row's output does not depend on which rows share its batch.

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 ↑
Claude Opus 5.548.1546.0022.4220.0746.6940.5014.4473.410.01744.4145.7925.3872.3221.80
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 results differ by probe set, and one setting has a failure we cannot explain.

Probe sets 3 and 4: ahead everywhere they are scored. On probe set 3 we reach 22.42, 14.44 and 25.38 on Qwen3.5-4B, Gemma3-4B and OLMo3-7B, against the best baselines' 18.12 (Jacobian lens [2]), 12.28 (Jacobian lens [2]) and 22.37 (Logit lens). On probe set 4, scored on Gemma3-4B and OLMo3-7B, we reach 73.41 and 72.32, against 61.35 and 54.95 for the strongest baseline, Jacobian lens [2]. The probe set 4 margins are the largest in the table.

Probe set 2: ahead on two settings, behind the logit lens on one. On Qwen3.5-4B we reach 46.00 against 39.27 (Tuned lens [1]), and on OLMo3-7B 45.79 against 43.04 (Jacobian lens [2]). On Gemma3-4B our 40.50 is above the Jacobian lens's 37.84 but below the logit lens's 45.83.

Probe set 1: behind the Jacobian lens on every setting. We reach 48.15, 46.69 and 44.41, against the Jacobian lens's 49.04, 49.59 and 47.44; on Gemma3-4B the logit lens, at 52.65, is ahead of both. Some of what our transport changes relative to the Jacobian lens costs readout on this probe set.

Perturbation fidelity: ahead on Qwen3.5-4B and OLMo3-7B, collapsed on Gemma3-4B. On Qwen3.5-4B our fidelity of 20.07 is well clear of the best baseline's 15.33 (Jacobian lens [2]). On OLMo3-7B we reach 21.80 against 20.86 (Tuned lens [1]), a narrow lead in a column where every non-trivial baseline is close together. On Gemma3-4B our fidelity is 0.017: barely above the zero transport's 0.000 and far below every other baseline, the best being Logit lens at 7.849. Nothing in our development measurements predicted this; on every decoder we developed on, our fidelity proxy for the final lens was at or above the Jacobian lens's. We return to it under Limitations.

How we got here

The design came out of one diagnostic and a sequence of attempts to escape the trade-off it showed. All figures below are our own development measurements, on hand-written readout items and on perturbation probes of our own, scored with a direction-only fidelity proxy; they are not evaluation results.

  • The trade-off is the horizon. After reading the Jacobian lens paper and its package, we interpolated between the same-position Jacobian and the summed one on one development decoder. Pure gave readout 0.276 and fidelity 0.384; the summed Jacobian, 0.361 and 0.301; the future part alone, 0.419 and 0.130. Readout and fidelity traded roughly one for one along that line, which told us the two goals live in different horizons of the same average.
  • Estimating both parts cheaply. A random-probe estimator of the same-position Jacobian over many sequences was fast and accurate, but the same trick for the summed Jacobian was far noisier than the one-hot estimator (readout 0.290 against 0.361). We kept one-hot cotangents for the sum and added the sign-demodulated pass for the same-position part inside the same forward. Going from 40 to 100 prompts changed readout by 0.002 on the decoder we tested, so we stopped at 40.
  • Looking at what fills the top-. Printing the future part's top tokens on our items showed ellipses, line breaks and underscore runs at every layer we printed. The top 16 output modes of held between 0.21 and 0.77 of its second moment depending on decoder and layer. Removing the top modes from the future part raised readout and fidelity together (0.381 and 0.321 against 0.361 and 0.301 for the summed Jacobian). Low-rank truncation of the future part, projections in a logit metric, mean offsets and centring gave no improvement.
  • The normalised target added about 0.01 to 0.02 to the fidelity proxy for no readout cost (for example 0.399 to 0.414 on realistic perturbations, with mode removal).
  • Cleaning the same-position part was a mistake. Projecting the top variance modes of the non-identity part of out of it raised readout further but dropped fidelity on realistic perturbations from 0.406 to 0.268. Removing the modes from the undecomposed summed Jacobian kept the readout gain but dropped the same fidelity to 0.240. That ablation is why the split is not optional: the cleaning helps only when it is confined to the broadcast part.
  • Choosing . The broadcast spectra have no clear elbow; we moved from to , which gave more readout for a small fidelity cost, and a later fine sweep over and was flat to within 0.002 on our combined readout-and-fidelity score, so , sit on the plateau.
  • From principal to contrastive format directions. A first version of the vocabulary prior used the principal directions of the format tokens' readout vectors. It raised readout but cost up to 0.038 of realistic-perturbation fidelity on one decoder, presumably because those directions are also read by content tokens. The contrastive version kept fidelity unchanged on that decoder (0.405) while lifting readout; its result was insensitive to the ridge between and and to . Projecting the subspace from the identity path as well made little difference and we kept the identity exact.
  • Dropping the earliest broadcast. A histogram of the layer at which each recovered target is best ranked showed the first three source layers contributing at most one target. Dropping the broadcast part below left readout unchanged and raised fidelity slightly on every probe we had.
  • Magnitude, last. Every Jacobian lens, the original included, over-predicted the size of the response on our probes, by up to about 11 times on one decoder (8.5 for the Jacobian lens there). Two simpler fixes failed: an input-dependent term along the largest residual direction cost realistic-perturbation fidelity (0.414 to 0.371), and a constant offset along the least logit-sensitive direction cut readout on the decoders where that direction is not inert (0.386 to 0.356 on one). On the decoder whose unembedding had an inertness ratio of , the normalised calibration brought the magnitude error to about 1.0 with readout and the direction-only fidelity proxy unchanged; the other two decoders had ratios of 0.12 and 0.31, so the gate stays off and the transport there is the plain linear map.
  • Ideas that did not survive: stopping gradients through attention queries and keys while estimating the Jacobians, measuring the broadcast toward an intermediate layer instead of the final one, the penultimate layer as target, per-cluster Jacobians, partial input whitening, input-side shrinkage toward the data support (which cut readout from 0.387 to 0.326), fitting on earlier positions, and further token classes for the vocabulary prior.

A final cumulative ablation on our combined score put the Jacobian lens at 0.359, 0.387 and 0.391 on our three development decoders and the lens without calibration at 0.405, 0.428 and 0.446, with the variance cleaning and the contrastive projection contributing most. Removing any one component lowered the average across decoders, though on one decoder removing the variance cleaning, or the output normalisation, was slightly better (by about 0.001). During development, a literature check found work noting that intermediate logit-lens reads are dominated by generic tokens [3], which we recorded as consistent with our structural-mode diagnosis without adopting anything from it; after the design was final, we looked up work on massive, near-constant activation directions [4] that may explain why some unembeddings have an inert direction. Neither shaped the design.

Limitations

  • Gemma3-4B's fidelity is a failure we cannot account for. Our perturbation fidelity there is 0.017, essentially the zero transport's level, while our development proxy showed the final lens at or above the Jacobian lens on every decoder we tried. Our proxy scored only the direction of the predicted response, and we assumed the evaluation's fidelity would not depend much on its size; we cannot tell from our inputs whether the calibration branch was active on Gemma3-4B. If it was, it is the first suspect, being the only part of the transport that is not a fixed linear map. If it was not, nothing we measured explains the result.
  • Probe set 1 is uniformly worse than the Jacobian lens, on every setting, and on Gemma3-4B the logit lens also leads on probe sets 1 and 2. Our transport loses something that those probe sets use, and we did not identify what.
  • The OLMo3-7B fidelity lead is small, inside a band where every non-trivial baseline sits close together.
  • Our development evidence is narrow. It rests on a few hundred hand-written readout items and our own perturbation probes; the bootstrap intervals we computed cover item sampling within those sets, not how well they match the evaluation.
  • Several constants are tuned, not derived. , , , the pre-workspace cut and the inertness gate were all chosen on the same development decoders. The vocabulary prior depends on the tokenizer's decoding of single tokens, and a tokenizer with few format tokens disables it (the basis is skipped if there are fewer than of them).
  • Magnitude remains off where the gate is closed. On the decoders without an inert direction the predicted response stayed about two to three times too large on our probes; a partial calibration looked cheap in our last scratch tests but was never validated in the submitted code.
  • The fit is capped in time. On the largest decoder the Jacobian loop can stop a prompt or two earlier from run to run, which in our tests moved the development metrics by under 0.01.

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. Olli Tuomi (2026). Contrastive Projection: Reading Transformer Internals by Differencing Logit Lenses.
  4. Mingjie Sun, Xinlei Chen, J. Zico Kolter et al. (2024). Massive Activations in Large Language Models. COLM.

The session

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