-
Notifications
You must be signed in to change notification settings - Fork 686
feat(svd_circuits): singular-direction readout, projection, and causal patch gate #1775
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
janmenjayap
wants to merge
14
commits into
TransformerLensOrg:dev
Choose a base branch
from
janmenjayap:feat/svd-circuits-causal
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,418
−12
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e6cc413
fix(svd_circuits): correct the OV output-direction docstring and add …
janmenjayap 7c4e283
feat(svd_circuits): add OV vocab readout and logit signature
janmenjayap 7a4c8eb
feat(svd_circuits): add project_activations firing coefficients
janmenjayap 5b8118d
feat(svd_circuits): add patch_along_directions causal gate
janmenjayap 5a29454
feat(svd_circuits): export public API and validate Bridge compatibili…
janmenjayap eb2bb3a
test(svd_circuits): add GPT-2 small IOI patch integration
janmenjayap e640796
docs(svd_circuits): drop HookedTransformer references from the module
janmenjayap b66092d
fix(svd_circuits): bind each decomposition to its compatibility-mode …
janmenjayap 06b4f6c
fix(svd_circuits): project W_U and V in a common dtype
janmenjayap 9b94861
fix(svd_circuits): validate direction indices against the map rank
janmenjayap 3b6d7df
fix(svd_circuits): place the subspace projector on the activation's d…
janmenjayap 85a1f8f
fix(svd_circuits): draw the causal baseline in-span, average it, and …
janmenjayap fb1c6c6
test(svd_circuits): pin the OV write basis and per-head isolation aga…
janmenjayap 095893a
fix(svd_circuits): filter project_activations cache to one hook and r…
janmenjayap File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| """Integration test: OV vocab readout and the causal patch gate on a real GPT-2 head. | ||
|
|
||
| The only file in the ``svd_circuits`` suite that downloads a pretrained model. Drives the | ||
| whole read-then-patch path against layer 9 head 9 (the paper's canonical name-mover head) on | ||
| a minimal IOI-style prompt, to check that the readout and the causal gate agree on a real | ||
| Bridge rather than only on the unit suite's synthetic and tiny-model fixtures. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import math | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| from transformer_lens.model_bridge import TransformerBridge | ||
| from transformer_lens.SVDInterpreter import SVDInterpreter | ||
| from transformer_lens.tools.analysis.svd_circuits import ( | ||
| decompose_head, | ||
| patch_along_directions, | ||
| vocab_readout, | ||
| ) | ||
|
|
||
| CLEAN_PROMPT = "When Mary and John went to the store, John gave a drink to" | ||
| LAYER, HEAD = 9, 9 | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def gpt2_bridge(): | ||
| model = TransformerBridge.boot_transformers("gpt2", device="cpu", dtype=torch.float32) | ||
| model.enable_compatibility_mode() | ||
| return model | ||
|
|
||
|
|
||
| def _logit_diff_metric(model): | ||
| mary_token = model.to_single_token(" Mary") | ||
| john_token = model.to_single_token(" John") | ||
|
|
||
| def metric(logits: torch.Tensor) -> float: | ||
| return float(logits[0, -1, mary_token] - logits[0, -1, john_token]) | ||
|
|
||
| return metric | ||
|
|
||
|
|
||
| def test_svd_circuits_readout_and_patch_gate_on_name_mover_head(gpt2_bridge) -> None: | ||
| decomposition = decompose_head(gpt2_bridge, layer=LAYER, head=HEAD, which=("OV",)) | ||
| ov = decomposition.OV | ||
| assert ov is not None | ||
|
|
||
| readout = vocab_readout(gpt2_bridge, ov, k=10) | ||
| assert readout.shape == (gpt2_bridge.cfg.d_vocab, 10) | ||
| assert torch.isfinite(readout).all() | ||
|
|
||
| # Pick the first non-degenerate direction rather than assuming index 0 is isolated. | ||
| top_direction = next(row.idx for row in ov.rank_report if not row.is_degenerate) | ||
|
|
||
| # readout reproduces the shipped SVDInterpreter reference up to sign, so a U-for-V swap | ||
| # or an all-zeros return in vocab_readout fails here rather than passing a finiteness check. | ||
| reference = SVDInterpreter(gpt2_bridge).get_singular_vectors( | ||
| "OV", LAYER, head_index=HEAD, num_vectors=top_direction + 1 | ||
| )[:, 0, top_direction] | ||
| assert torch.allclose(readout[:, top_direction], reference, atol=1e-4) or torch.allclose( | ||
| readout[:, top_direction], -reference, atol=1e-4 | ||
| ) | ||
|
|
||
| prompt = gpt2_bridge.to_tokens(CLEAN_PROMPT) | ||
| metric = _logit_diff_metric(gpt2_bridge) | ||
|
|
||
| result = patch_along_directions(gpt2_bridge, ov, prompt, metric, keep=[top_direction]) | ||
|
|
||
| assert result.retained == [top_direction] | ||
| assert math.isfinite(result.original_metric) | ||
| assert math.isfinite(result.patched_metric) | ||
| assert math.isfinite(result.delta_metric) | ||
| assert math.isfinite(result.baseline_delta_metric) | ||
| assert isinstance(result.gated, bool) | ||
|
|
||
| rank = ov.V.shape[1] | ||
|
|
||
| # Keeping every direction reconstructs the head onto its own full OV span: a no-op, so the | ||
| # metric barely moves. A hook never installed, or one projecting the wrong basis, breaks this. | ||
| full_keep = patch_along_directions(gpt2_bridge, ov, prompt, metric, keep=list(range(rank))) | ||
| assert abs(full_keep.delta_metric) < 1e-4 | ||
|
|
||
| # Ablating every direction zeroes the head's whole output, which must move the logit diff. | ||
| # An empty retained set ties the baseline by construction, so gate it with an explicit | ||
| # threshold; only delta_metric's magnitude is asserted here. | ||
| full_ablate = patch_along_directions( | ||
| gpt2_bridge, ov, prompt, metric, ablate=list(range(rank)), threshold=0.0 | ||
| ) | ||
| assert abs(full_ablate.delta_metric) > 1e-2 | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Every assertion is shape, finiteness,
isinstance, orretainedechoing thekeep=argument, so the only real-model test passes with the hook never installed, the gate hardcoded,vocab_readoutreturning zeros, or the wrong basis projected. Assert thatreadout[:, i]matchesSVDInterpreter(model).get_singular_vectors("OV", 9, head_index=9)up to sign, thatkeep=range(rank)leaves the logit diff within 1e-4, and that ablating every direction moves it by more than 1e-2.