Repository navigation
feat(relevance_lens): RelevanceLens.fit + provenance + integration + docs - #1834
Conversation
jlarson4
left a comment
There was a problem hiding this comment.
Thanks for closing out the R-lens issue @janmenjayap, cool to see it come to fruition! A handful of comments on artifact provenance, the fit and merge paths shared with JacobianLens, and the docs.
| """ | ||
| lens = cast("RelevanceLens", super().load(path)) | ||
| recorded_estimator = lens.metadata.get("estimator") | ||
| if isinstance(recorded_estimator, str) and recorded_estimator != ESTIMATOR_RELEVANCE: |
There was a problem hiding this comment.
This refuses only an artifact that names a different estimator. A file with no estimator key therefore loads as a RelevanceLens: that covers every J-lens fitted before this PR and reference-package files such as the published neuronpedia/jacobian-lens lenses. Saving it then writes relevance_lens in for good. RelevanceLens.merge of two J-lens shards has the same gap. Can load and merge require a positive relevance record rather than assuming one?
There was a problem hiding this comment.
Fixed. The loader now checks the original artifact metadata before construction and requires the exact estimator="relevance_lens" record. Missing, malformed, or foreign estimator values are rejected rather than filled in by the constructor. The relevance loader also refuses the Jacobian-specific running-sum checkpoint conversion.
RelevanceLens.merge() now requires relevance shards with positive relevance metadata, including singleton merges. Added regressions for homogeneous legacy J-lens shards, mixed estimators in both orders, and unlabelled reference-format artifacts. Legacy artifacts remain loadable through JacobianLens
| the recorded provenance from claiming a rule contributed when every mount | ||
| for it was skipped. | ||
| """ | ||
| installed_mounts = {name.rsplit(".", 1)[-1] for name in coverage.installed} |
There was a problem hiding this comment.
activation and multiplicative_gate share the mlp mount, and coverage paths carry no kind. So this reports both kinds whenever either installed, and rule_coverage lists each MLP twice. It holds today only because a gated MLP installs both or raises. Could the coverage record the kind with each path before artifacts start persisting the path-only form?
There was a problem hiding this comment.
Updated coverage to store immutable (kind, path) entries for both installed and skipped rules, with a separate coverage schema version. enabled_rules is now derived directly from installed kinds, not inferred from mount names. Activation and gate rules at the same MLP path are distinct records rather than indistinguishable duplicate paths.
Added activation-only, gate-only, partial-support, alias-deduplication, and persistence tests. Existing path-only coverage is rejected as ambiguous, with a refitting diagnostic; the loader does not guess which MLP rule contributed
| UserWarning: If some rule mounts were skipped, so the matrices mix | ||
| rule-modified and ordinary gradients. | ||
| """ | ||
| _require_raw_bridge(model, estimator=cls.__name__) |
There was a problem hiding this comment.
Apart from the rule scope and three provenance keys, this fit is a copy of JacobianLens.fit, and the dtype warning text has already drifted. A guard added there later won't reach this estimator. Can the shared validation and provenance live in one place that both fits use?
There was a problem hiding this comment.
Extracted _prepare_fit() and _build_fit_metadata(), used by both estimators. They now share model-state checks, layer resolution, option validation, the reduced-precision warning, and common provenance assembly. R-lens retains its rule scope, coverage checks, and three estimator-specific provenance fields.
Reserved-key collisions and unsafe user metadata are also checked before fitting or rule installation. Added parameterized tests across both estimators and a comparison of their common fit provenance
| first = lenses[0] | ||
| for lens in lenses: | ||
| _validate_metadata(lens.metadata) | ||
| _require_matching_merge_identity(lenses) |
There was a problem hiding this comment.
The R-lens constructor stamps the same fields into metadata, so the provenance comparison below already refuses every mixed merge the tests build. Is there a test we can add where only this check catches, or should the check go?
There was a problem hiding this comment.
Agreed; the ordinary provenance comparison already covers estimator and rule-configuration mismatches. Removed _require_matching_merge_identity() and the _merge_identity() methods rather than keeping a second comparison without an independent purpose.
The separate destination-estimator check remains necessary: matching J-lens shards can agree perfectly with each other but still must not become an R-lens through RelevanceLens.merge(). That boundary now has homogeneous-shard and singleton regressions
| from transformer_lens.model_bridge import TransformerBridge | ||
| from transformer_lens.tools.analysis import RelevanceLens | ||
|
|
||
| model = TransformerBridge.boot_transformers("openai-community/gpt2", device="cuda") |
There was a problem hiding this comment.
This section later says GPT-2 raises, so the example fails as written. The module docstring example in relevance_lens.py fails the same way. Lets update both bits of documentation to use a model the estimator covers.
There was a problem hiding this comment.
Both examples now use Qwen/Qwen2-0.5B, explicitly select fp32, call eval(), and define the prompts and bounded fit options. The guide also makes clear that the single-prompt walkthrough is not a research-quality corpus.
Ran the exact documented example against the published model, including coverage checks, readout, and save/load/validation. All three rule kinds installed, with no skipped mounts. The module and guide examples use the same code; the Jacobian-only GPT-2 examples are unchanged
| Face Hub) are not accepted by the current loader; converting them is separate | ||
| work. | ||
|
|
||
| The relevance lens targets `TransformerBridge` exclusively. `HookedTransformer` is |
There was a problem hiding this comment.
Remove this line, this will be merging into v4, and never overlap with HookedTransformer, so there is no room for confusion.
There was a problem hiding this comment.
Removed that paragraph. The section now states the raw TransformerBridge requirement directly, without comparing it to an API absent from v4
| def test_rule_scope_does_not_leak_past_the_fit(self, fitted: _FittedPair) -> None: | ||
| with torch.no_grad(): | ||
| logits_after_fit = fitted.model(fitted.model.to_tokens(PROMPTS[0])) | ||
| assert torch.equal(logits_after_fit, fitted.logits_before_fit) |
There was a problem hiding this comment.
The rules never change the forward pass, so comparing logits before and after the fit still passes when the scope is left installed. The integration test's forward-identity check has the same gap. Could this assert on something the rules do change, such as a gradient taken after the fit?
There was a problem hiding this comment.
Replaced the cleanup proof with fresh-graph residual-gradient comparisons in the unit and integration tests. Each has an active-rule control to establish that the probe actually detects changed backward semantics. Forward identity remains a separate invariant.
Added backward-failure and nested-fit coverage. The nested test also exposed an activation wrapper starting in training mode inside an eval model; fixed its initialization without changing existing modules' modes.
Verified sensitivity by temporarily disabling rule release in a subprocess: all four gradient-cleanup tests failed, while both forward-identity tests still passed. No mutation remains in the implementation.
Preserve activation-wrapper mode without changing existing modules, so nested fits remain valid. Verify gradient restoration after successful and failed fits and preserve outer relevance scopes.
|
Looks good, thanks @janmenjayap |
Summary
Lands
RelevanceLens, a second estimator for the Jacobian lens's transportmatrices. It keeps the fitting loop, readout, vocabulary vectors, sparse
decomposition, and interventions unchanged, and changes only the backward pass:
each per-layer matrix is estimated with the scoped LN-, Identity-, and Half-rules
installed on the model for the duration of the fit. The forward pass is
bit-identical to the model's native forward, so the two estimators differ solely
in the backward semantics they select.
Part of #1755 (R-lens). This is PR3 of the 3-PR plan on that issue. PR1
(#1764) landed
the estimator-independent fit driver; PR2
(#1785) landed
the shared relevance-rule backend this PR consumes. With this PR the issue's
scope is complete.
Motivation
The source post reports that ordinary gradients accumulate noise at early layers,
and that a small set of LRP rules produce earlier, cleaner, and more causally
load-bearing readouts. Those findings motivate the estimator; they are not
proposed as small-model CI assertions. This PR ships the estimator and its
artifact-safety guards, not a quality claim.
Three bugs found while building this
The plan called for eight commits. Probing the implementation surfaced three
correctness bugs, each fixed in its own commit with a failing test first. They are
the most interesting part of this PR, so they lead.
A fit that installed no rule silently returned a J-lens.
On a model that can honor none of the three rules — a dense MLP with
plain-python norms, such as GPT-2 —
fitreturned transport matricesbit-identical to an ordinary
JacobianLenswhile labelling the artifactestimator="relevance_lens". The artifact was indistinguishable from a realrelevance fit, so a downstream J-lens/R-lens comparison would have been
silently meaningless.
fitnow raises, naming the skipped mounts.Partial coverage recorded rules that never ran.
A model can honor some rules and not others. OPT takes the LN-rule but its
dense ReLU MLP takes neither MLP rule, so every MLP mount is skipped — yet the
artifact recorded all three rules as enabled.
enabled_rulesis now derivedfrom the mounts that were actually installed, so OPT records
["normalization"].Partial coverage was silent.
The issue requires that partial rule installation never be silent. A fit that
mixed rule-modified and ordinary gradients looked identical to a fully covered
one.
fitnow warns with the installed rules and the skipped mounts.Bug 1 was found by probing a dense-MLP model; bugs 2 and 3 by sweeping rule
coverage across 16 architectures. The plan's Qwen2/Phi-3 fixtures both have full
coverage, so neither would have caught them.
What ships (commit by commit)
test(relevance_lens): fit shape/finite + rule-coverage selectionShape/finite parity with
JacobianLens, requested coverage is residual-norm LNJ-lens. Red as expected —
RelevanceLensdoes not exist yet.feat(relevance_lens): RelevanceLens type + fit via shared driverThe estimator, driving PR1's
_fit_transport_matricesunder PR2'suse_relevance_rules. Adds the estimator identity to the shared raw-bridgeguard so diagnostics name the caller's estimator.
test(relevance_lens): provenance + merge + registry guardsJ/R mixtures rejected, mismatched rule configuration rejected, identical
shards merge by prompt count, and a short name cannot resolve the J-lens
registry. Red as expected.
feat(relevance_lens): persist rule provenance across save, load, and mergeRule configuration is read back from artifact metadata in the constructor, so
a loaded lens reports the semantics its matrices were estimated under. Loading
an artifact that records a different estimator is refused.
feat(analysis): export RelevanceLensReachable from the same import path as
JacobianLens.test(integration): tiny gated Bridge fit + joint-vs-merged consistencyFull coverage on a real assembled Bridge, forward identity across a fit, and
joint fit equals the prompt-count-weighted merge of shards.
docs(jacobian_lens_fitting): R-lens section + support matrixThe three rules, per-component support matrix, provenance guards, and the
RelP / R-lens / published-artifact distinction.
test(relevance_lens): pin the inherited analysis surfacePins that the 17 downstream methods are inherited, not reimplemented, so a
future fork of the two surfaces fails loudly.
fix(relevance_lens): refuse a fit that installs no relevance rule— bug 1.fix(relevance_lens): record installed rules, not requested rules— bug 2.fix(relevance_lens): warn when a fit installs only some rules— bug 3.test(relevance_lens): pin the unsupported-activation refusalValidation item 6: a relu-family gated MLP raises before fitting, and the
refusal leaves the model untouched.
docs(relevance_lens): document the fit coverage contractThe
fitdocstring'sRaises:/Warns:sections, stale after commits 9-11.Coverage contract
Three outcomes, all explicit:
Testing
tests/unit/tools/test_relevance_lens.py— 30 passed.tests/integration/test_relevance_lens.py— 10 passed.tests/unit/tools/— 1055 passed.tests/unit(full tier) — see the verification table below.tests/integration(full tier) — 1377 passed, 5 skipped, 1 failed. Thefailure is
test_granite_moe_hybrid_adapter.py::test_granite_eager_scan_device_correctness[mps](
eager vs fused rel diff on mps: 1.11e+00). It is pre-existing andunrelated: this PR touches no granite/MoE/MPS code, and the test fails
identically at
origin/dev. It is not in the CImps-checksfile list, so CIdoes not see it. Filed separately.
uv run mypy .— clean, 386 files.pycln/isort/black— clean.uv run build-docs— clean; the R-lens section renders with its tables. Theonly warnings are two pre-existing demo cross-references, untouched here.
Validation plan coverage
The issue's validation plan items 1-6 and 8 are covered across the three PRs.
Item 7 (tolerant parity against the pinned
FarnoushRJ/RelP) is deferred to theRelP issue, as the plan states.
Out of scope
Published-artifact conversion, pass@k / lens-comparison harness, CKA utility,
linear-probe upper bound, MoE/router/shared-expert and mHC rules, and a demo
notebook. All are tracked as separate follow-up issues.
API
One new public name:
RelevanceLens, exported fromtransformer_lens.tools.analysis. It subclassesJacobianLens, so code thataccepts a fitted lens accepts either estimator. The shared backend
(
_relevance_rules.py) stays underscore-private and is consumed by internalimport only.
Checklist
dev; working branchfeat/r-lens-fit.RelevanceLens.fitreturns finite, shape-parity matrices; at least oneearly transport differs from J-lens.
duplicated (pinned by test).
merge.
scope.
make formatequivalent anduv run mypy .clean.model.cfgflags; no.data.make test-prattached before submit.Note for reviewers
Commit 1 is intentionally red: it is the TDD test commit, and the module it
imports does not exist until commit 2. This matches how PR2 landed. Commits 2-13
are each green.