Repository navigation
feat(backward_lens): support gated MLP gate/up/down gradient factors - #1833
janmenjayap wants to merge 22 commits into
Conversation
jlarson4
left a comment
There was a problem hiding this comment.
Another step for BackwardLens! A couple small notes
bf9e0b5 to
bc2bcba
Compare
| ) | ||
| aliases = getattr(block, "hook_aliases", None) | ||
| boundary = aliases.get("hook_mlp_out") if isinstance(aliases, Mapping) else None | ||
| if boundary != "mlp.hook_out": |
There was a problem hiding this comment.
Bloom and MPT alias hook_mlp_out to mlp.out.hook_out because their HF MLP adds the residual inside its own forward. The down projection's output is still the direct residual contribution, but both are now rejected even though they analyze exactly on dev. Can the check resolve hook_mlp_out and accept it when it lands on the MLP's own output, rejecting only when it lands on a norm?
|
@janmenjayap After spending most of this week doing a thorough review of our |
Description
Backward Lens previously accepted only dense-MLP
TransformerBridgemodels (GPT-2, Pythia/GPT-NeoX).This PR adds gated (SwiGLU-style) MLP support, covering the Llama/Mistral/Qwen2/Gemma family, whose MLP
block has three linear projections instead of two.
The factorization math is unchanged per linear. A linear's weight gradient is still the sum of
per-position outer products of its captured forward input and its output-side VJP. The new work is a
three-matrix result contract, the correct choice of which factor is vocabulary-projectable for each
matrix, and honest documentation of why the gate and up projections coincide in the vocabulary while
the down projection does not.
Fixes #1832
The gated MLP math
A gated MLP block computes, for residual-width input
x:Each of the three linears factorizes its own weight gradient the same way GPT-2's two do:
grad_W(autograd)gate(gate_proj)x[pos, d_model]dL/dg[pos, d_mlp]sum_i outer(x_i, dL/dg_i)in(up_proj)x[pos, d_model]dL/du[pos, d_mlp]sum_i outer(x_i, dL/du_i)out(down_proj)h[pos, d_mlp]dL/dy[pos, d_model]sum_i outer(h_i, dL/dy_i)No new factorization math is required. The existing
_build_linear_gradient_factorsalreadyreconstructs any linear given
(forward_inputs, output_gradients, weight_gradient, weight_layout), andthe Bridge weight-layout oracle already resolves
torch.nn.Linearto"out_in"for all three gatedprojections.
Which factor is vocabulary-projectable
Only residual-width (
d_model) factors can pass throughln_final+unembed. Classifying the sixgated factors by width:
gate.forward_inputs = x: residual width, projectable (the "imprint" direction).in.forward_inputs = x: residual width, projectable, and it is the same tensor asgate.forward_inputs.gate.output_gradients,in.output_gradients,out.forward_inputs:d_mlpwidth, not projectable.out.output_gradients = dL/dy: residual width, projectable (the "shift" direction, exactlyGPT-2's FF2 treatment).
Two consequences drive the contract:
x, their vocabulary projections are identical by construction. The gate-vs-up distinction isreal but lives in the two independent weight-gradient reconstructions and the two distinct
d_mlp-width output gradients, not in the projected vocabulary. This is stated plainly in the docsand asserted by a test so users do not read a nonexistent difference into two identical token tables.
Result schema
The merged two-matrix schema is preserved and one optional third matrix is added, so dense models stay
byte-for-byte compatible:
BackwardLensLayerResultgainsgate_projection: BackwardLensMatrixResult | None = Noneas atrailing, default-
Nonefield. Dense models leave itNone; gated models populate it.BackwardLensMatrixResultis unchanged.analyze()produces three matrix results:gate_projectionandinput_projectionboth withprojected_factor="forward_inputs"(the shared imprintx), andoutput_projectionwithprojected_factor="output_gradients"(the shiftdL/dy).This deliberately does not rename
input_projection/output_projectiontoup/down. The namesalready map cleanly, renaming would break the merged public API for no gain, and adding
gate_projectionis sufficient to distinguish which matrix a factor belongs to.Implementation details
_get_mlp_projectionsbranches ongetattr(mlp, "gate", None): dense MLPs yield two records(input, output); gated MLPs yield three(gate, input, output). Each projection reuses the sameper-linear validation (is
LinearBridge; original weight is a floating,requires_gradParameter;layout from the Bridge oracle;
hook_in/hook_outareHookPoints).input/output, so theweightsandoutputslists extend automatically. The singletorch.autograd.gradcall now returns gradients forthree outputs plus three weights per gated layer.
_require_raw_mlp_bridgeand no longer rejects gated models. Every otherguard is retained: raw single-device
TransformerBridge, no compatibility mode, no processedweights, tokenizer present,
blocks/ln_final/unembedpresent._DenseMLPGradientCapture,_capture_dense_mlp_gradient_factors, and_get_dense_mlp_projectionsare renamed to drop the now-misleadingdensequalifier, since theyhandle gated MLPs.
Feasibility: does gated capture reach the three linears?
Yes, via the existing hook mechanism.
GatedMLPBridge.forwardin non-compatibility mode calls the HFMLP as an opaque forward, and its docstring warns that the bridge's own intermediate hooks fire only in
compatibility mode. That warning concerns
GatedMLPBridge.forwardexplicitly callingself.gate.hook_out(...); it does not govern thegate/in/outLinearBridgesubmodules' ownhooks. Those submodules are installed into the HF module tree by
replace_remote_componentviasetattr, so when the opaque HF forward runsself.gate_proj(x)/self.up_proj(x)/self.down_proj(h), it calls theLinearBridgewrappers, whoseforwardfireshook_in/hook_out.This is the identical mechanism the merged GPT-2 capture already relies on. Because the interaction is
load-bearing and the docstring is easy to misread, it is verified empirically by a test that asserts all
six
gate/in/outhook_in/hook_outhooks fire exactly once during one gated forward.Deviation from the proposal: fused gate/up is supported
The proposal listed fused gate+up matrices (e.g.
joint_gate_up_mlp) as out of scope, on the assumptionthat such an MLP exposes no distinct gate projection. That assumption is wrong.
JointGateUpMLPBridgesplits the fusedgate_up_projinto distinct gate and upLinearBridges atboot, so the MLP does expose a distinct gate projection and the gated path applies unchanged.
Verified empirically on a tiny
Phi3ForCausalLM: discovery returns three orientedout_inrecords,gate_projectionis populated, and the gate reconstruction error is0.0. A test locks this in, andthe docs now state the accurate boundary: fused-storage families are supported when the Bridge splits
the matrix at boot; a gated MLP exposing no distinct gate is rejected.
Model matrix
gpt2Conv1D; stays byte-for-byte compatible (gate_projection is None)EleutherAI/pythia-70mnn.Linear; confirms the dense path is untouchedstas/tiny-random-llama-2Qwen/Qwen2-0.5BPhi3ForCausalLM(built in-test)Note: the proposal named
trl-internal-testing/tiny-random-llama-2, but the model in the CI cache isstas/tiny-random-llama-2. The latter is used.Tokenizer finding on tiny-llama
tiny-llama's role is conditional on its tokenizer being usable. It is not: the
LlamaTokenizershipped withstas/tiny-random-llama-2is degenerate, emitting a fixed three-tokenprefix for every non-empty string, so no single-token target exists. tiny-llama is therefore
structural-only and
Qwen2-0.5Bcarries the reconstruction and projection assertions.Files
transformer_lens/tools/analysis/backward_lens.pygate_projectionon private and public results; gated bridges accepted; symbol renames; docstringstransformer_lens/tools/analysis/__init__.pytests/unit/tools/test_backward_lens.pytests/integration/test_backward_lens.pydocs/source/content/backward_lens.mddocs/source/content/analysis_tools.mddemos/Backward_Lens_Demo.ipynbType of change
Checklist
Verification
pytest tests/unit/tools/test_backward_lens.pypytest tests/integration/test_backward_lens.pypytest --nbval-sanitize-with demos/doc_sanitize.cfg demos/Backward_Lens_Demo.ipynbblack --check/isort --check-onlymypyon changed filesgit diff --checkScope boundaries
Out of scope, each its own follow-up:
orient. These are rejected with a clear error rather than silently mis-factored.
Qwen2-0.5Bis the required real model.Vocabulary readability remains a diagnostic, not causal evidence. No code is vendored from
shacharKZ/BackwardLens; the in-repo algebraic and projection oracles are used.