Repository navigation
feat(svd_circuits): singular-direction readout, projection, and causal patch gate - #1775
Conversation
…a cross-check test HeadSVD's docstring had U and V swapped for the OV map: for a factored map A @ B, U's columns live in A's input space and V's columns live in B's output space, so for OV (A = W_V_h, B = W_O_h) it is V, not U, whose columns are the residual-stream directions this head writes into and should be projected through W_U for a vocab or logit readout. The swap never raised a shape error because both spaces are d_model-dimensional, so it would have silently used the wrong basis in every downstream readout, projection, or patch built on top of it. Adds a regression test that cross-checks HeadSVD.OV.V against the already-shipped SVDInterpreter (which projects its OV singular vectors through the unembedding the other way), on a tiny no-download TransformerBridge, so the assertion cannot pass under either labeling by construction.
vocab_readout projects a head's top-k OV output directions (HeadSVD.V, per the corrected convention) through the unembedding, gated on TransformerBridge compatibility mode so LayerNorm stays folded into W_U. logit_signature reconstructs one direction's rank-1 OV output and reads its signed logit effect on given tokens; it requires the direction to be isolated first, since a rotation-ambiguous or null direction's signature is not attributable to it alone.
Add ActivationProjection and project_activations to recover per-position firing coefficients by projecting a head's actual OV output (hook_result) onto its V basis. Summing the coefficients against V reconstructs the head's output because V's columns are orthonormal and define the basis the head writes in. Restore the model's prior use_attn_result setting after the forward pass so read-only analysis does not leave a configuration side effect.
patch_along_directions causally validates a claimed OV subfunction by reconstructing a head's hook_result onto a chosen span of HeadSVD.V directions (keep) or its complement (ablate), then comparing a caller's metric before and after against an equally-sized random-subspace baseline. gated is true only when the requested subspace moves the metric by more than the random baseline does, so a claim cannot be called causal merely because patching moved the metric at all. Before touching the model, the retained set is checked against every degenerate block reported by HeadSVD.degenerate_blocks(): a block must be kept whole or dropped whole, since attributing an effect to part of a rotation-ambiguous or null block would let a caller hand-pick around the same guard require_isolated already enforces per direction. The forward passes run under torch.no_grad(), matching the other analysis tools that repeat a forward pass per call, and the model's prior use_attn_result setting is restored in a finally block so this read-only check leaves no configuration side effect.
…ty mode Adds decompose_head, project_activations, patch_along_directions, vocab_readout, logit_signature, and their supporting types (HeadSVD, HeadDecomposition, RankReportRow, ActivationProjection, LogitSignature, PatchResult, DegenerateDirectionError) to transformer_lens.tools.analysis's imports, __all__, and tool-listing docstring, in the same ASCII-sorted order the module already uses for its other tools. No compatibility-mode logic changes here: vocab_readout and logit_signature already gate on TransformerBridge compatibility mode, and patch_along_directions already restores use_attn_result. This commit only widens the public surface, so the causal gate ships alongside the readouts rather than either landing without the other.
Exercise vocab_readout and patch_along_directions against GPT-2 small's layer 9 head 9 (name-mover head) on an IOI-style prompt with a Mary/John logit-diff metric, checking that the readout and causal gate agree on a real Bridge with compatibility mode enabled.
jlarson4
left a comment
There was a problem hiding this comment.
Thanks for the U/V correction and for cross-checking it against SVDInterpreter rather than the module's own arithmetic, that is the correct test point. Let me know if you have any questions on the below comments!
HookedTransformer is being removed, so the four consumer docstrings (vocab_readout, logit_signature, project_activations, patch_along_directions) and _validate_bridge_compatibility no longer list it as an accepted model or cite its LayerNorm folding as the reason the compatibility-mode guard fires only for TransformerBridge. The contract is now stated in terms of TransformerBridge alone: vocab_readout and logit_signature require compatibility mode so that W_U carries the folded final LayerNorm weights. Docstring-only, no behavior change. The guard still returns early for a non-TransformerBridge model; tightening that early-return to fail loudly is a behavior change, not a documentation one, so it is left out of this commit.
…state enable_compatibility_mode folds ln1 into W_V and centres W_O and W_U, so a HeadSVD taken before the call describes a different OV map than the model then computes. The existing guard inspected only the live model, so re-running a consumer with a decomposition captured under the other state returned a silently wrong result, and project_activations and patch_along_directions had no guard at all. Record the model's compatibility-mode state on HeadSVD at decomposition time and add an orthogonal guard that refuses a mismatch in all four consumers, pointing the caller at re-running decompose_head.
…eject a batched tensor pre-forward
jlarson4
left a comment
There was a problem hiding this comment.
Thanks for working through all those comments. The compatibility-state binding and the dtype and device fixes are excellent. An additional batch of comments added below:
Averaging the signed control deltas and then taking abs() understates the typical control effect and shrinks as n_baseline grows wherever the controls mix sign, so ablate gates pass too easily and keep too rarely. Make baseline_delta_metric the mean of the per-draw delta magnitudes, a non-negative typical control effect, and compare abs(delta_metric) against it directly. Update the PatchResult and patch_along_directions docstrings to state the field is a magnitude, and add a test on a mixed-sign stub that pins the threshold to the magnitude mean and guards against a regression to abs(signed mean).
A full-rank keep reconstructs the head onto span(V) itself (V V^T), and every width-rank in-span control also spans span(V), so the kept and control projectors coincide and their deltas tie by construction, just as the empty set does on the zero subspace. Extend the empty-set guard to reject a full-rank retained set unless an explicit threshold is given, reword the message and comment to cover both degenerate cases, and update the docstring. The integration full-keep call and a new unit case pass a threshold accordingly.
Both project_activations and patch_along_directions enable use_attn_result via set_use_attn_result(True) to read a head's per-head output. On an attention adapter with no per-head result fork point that call raises NotImplementedError, but neither Raises block listed it. Document it in both.
Requiring exactly two dimensions rejected a 1-D [pos] token tensor, which the previous revision accepted and which patch_along_directions still accepts. Reject only a tensor whose leading dimension is larger than one, so a bare [pos] prompt flows through to the forward while the post-cache batch guard still backstops a batched string list.
The span-aligned stub's readout equals its head output, so every control delta shares a sign and no gate test on it can tell the magnitude mean from the signed mean's magnitude; the same geometry lets a full-residual-stream control and a single draw pass every existing test. Add a many-draw assertion against the analytic Haar expectation E[baseline_delta] = pos * ||h||^2 * (1 - w/rank), whose 0.5 band separates the in-span value 3.0 from the full-stream value 9.0, and a second test that threading one generator through single-draw calls reproduces the multi-draw average bit for bit.
The sibling-head test called _make_subspace_hook directly and every patch_along_directions test used head 0, so the control-draw call inside patch_along_directions could have been hardcoded to head 0 without any unit test failing. Parametrize test_patch_along_directions_discriminates_causal_direction over both heads and add a wrong-head assertion: a copy mislabeled via dataclasses.replace(ov, head=other) keeps the same V but points at the sibling slice, so a head-faithful baseline draw yields a different baseline_delta_metric while a draw hardcoded to head 0 would tie the two. The strong-vs-weak 5x margin holds for both heads unchanged.
jlarson4
left a comment
There was a problem hiding this comment.
Thanks for the quick updates @janmenjayap! I am hopeful this will be my last review pass on this, sorry for the multitude of review requests. It is a big feature, and we are very close to shipping it!
Thirty-five adapters declare no fold support, so enable_compatibility_mode() leaves the final LayerNorm in place while the bridge still reports processed weights. The readout guard read only _weights_processed and _fold_ln_requested, so on those adapters vocab_readout projected through an unfolded W_U. Compute the folded-LayerNorm predicate in one helper so the readout guard and the staleness guard cannot drift apart.
…s seed sensitivity
|
Great work on getting this tackled @janmenjayap, this is approved and I am merging it now |
Description
Adds the causal-validation layer on top of PR1's per-head QK/OV SVD (#1768): a direction can now be read out to vocab/logit space, projected against a real forward pass, and, critically, causally patched before any subfunction claim is accepted. Second of three PRs implementing per-head singular-vector decomposition of a head's QK (
W_Q W_K^T) and OV (W_V W_O) maps (tracking issue: #1767).vocab_readout(model, head_svd, k=10)— projects the top-k OV output directions (HeadSVD.V) through the unembedding, gated onTransformerBridgecompatibility mode.logit_signature(model, head_svd, direction, tokens)— signed logit effect of one OV direction's rank-1 reconstruction; requires the direction to passrequire_isolatedfirst, since a rotation-ambiguous or null direction's signature is not attributable to it alone.project_activations(model, head_svd, prompt)— per-position firing coefficients of a head's actualhook_resultoutput against itsVbasis; summing the coefficients againstVreconstructs the real output to numerical precision, since both read the same basis the head actually writes in.patch_along_directions(model, head_svd, prompt, metric, keep=..., ablate=...)— the mandatory causal gate. Reconstructs or ablates a head's output onto a chosen span ofVdirections via a directhook_resulthook, and reportsdelta_metricagainst an equally-sized random-subspace baseline (gatedis true only when the requested subspace beats that baseline, not merely when the metric moves at all). Degenerate blocks reported byHeadSVD.degenerate_blocks()must be kept or dropped whole; a caller cannot route aroundrequire_isolatedby hand-picking part of a rotation-ambiguous block throughkeep/ablate.decompose_head,project_activations,patch_along_directions,vocab_readout,logit_signature, and their supporting types now ship fromtransformer_lens.tools.analysis— the first time this module is part of the public API, by design, so a readout was never importable without the causal gate attached to it.tests/integration/test_svd_circuits.py(new): exercisesvocab_readoutandpatch_along_directionsend to end against GPT-2 small's layer 9 head 9 (name-mover head) on an IOI-style prompt.Correctness fix folded in first:
HeadSVD's docstring had the OV output direction backwards —U's columns are the value-computation input space,V's are the residual-stream output space this head writes into and the one to project throughW_U. The swap never raised a shape error because both spaces ared_model-dimensional, so every downstream readout, projection, or patch would have silently used the wrong basis. Fixed first, with a regression test that cross-checks against the already-shippedSVDInterpreter(which projects the OV map the other way already), so the assertion cannot pass under either labeling.Two implementation notes for anyone diffing this against the original proposal:
vocab_readoutdoes not wrapSVDInterpreter.get_singular_vectors. That method indexesW_V/W_Kwith a raw query-head index, which is wrong on grouped-query models (the same bug PR1 already fixed for this module's own weight reads).vocab_readoutreuses PR1's already-kv-mappedHeadSVD.Vand projects it throughW_Udirectly instead of introducing a second, buggy SVD path.patch_along_directionscallsmodel.run_with_hooksdirectly rather thangeneric_activation_patch. That helper is built for a clean-vs-corrupted two-run sweep over an index grid; this tool is a single-prompt reconstruct/ablate on a live projection, which does not fit the sweep shape.Unit-tested with a tiny no-download
TransformerBridge(real forward passes, no Hub access) for projection/patch behavior, plus model-free tests for the pure weight-space math. Integration test downloadsgpt2-small.PR3 (docs, demo notebook, slow multi-head oracle-parity check) follows this one.
Part of #1767
Type of change
Checklist: