Repository navigation
Make residual-decomposition APIs work on SSM / hybrid bridges - #1987
Conversation
decompose_resid, compute_head_results, stack_head_results, stack_neuron_results and get_full_resid_decomposition assumed every block has attention and an MLP, so they raised KeyError on the first gated-delta-net or Mamba block (Qwen3.5, Qwen3Next, NemotronH, Mamba-2). Blocks without attention now contribute their sequence-mixer output in the attention slot (minus its output bias in the full decomposition, where the bias row already counts it). Only attention layers contribute heads, and only blocks with an MLP contribute mlp_out or neurons. Every decomposition still sums to the residual stream.
jlarson4
left a comment
There was a problem hiding this comment.
Thank you for your work on this @SBrouck! I have a couple comments related to specific architectures that will need to be addressed before this can merge. Take a look when you have a moment, and let me know if you have any questions
| out = pos_slice.apply(self[f"blocks.{layer}.{name}.hook_out"], dim=-2) | ||
| if i == 0 and isinstance(bias, torch.Tensor): | ||
| out = out - bias.to(out.device, out.dtype) | ||
| components.append(out) |
There was a problem hiding this comment.
On ScaledResidualBlockBridge blocks (Granite 4.0-H) the mixer's hook_out fires before the residual_multiplier, so these rows come in unscaled while the head and neuron paths multiply by block.residual_contribution_scale. On a dense GraniteMoeHybrid, decompose_resid now returns a stack that no longer sums to the residual stream. Can we ensure the mixer rows apply the same scale after the bias subtraction?
There was a problem hiding this comment.
Good catch, thanks. Fixed in b63c0df: mixer rows are now multiplied by block.residual_contribution_scale after the bias subtraction, in both decompose_resid and get_full_resid_decomposition, so they line up with the scaled hook_attn_out / hook_mlp_out and with the bias row. I added a dense GraniteMoeHybrid fixture with residual_multiplier=0.22 to the test matrix; removing the scaling makes 6 of its cases fail.
While adding it I noticed that neuron expansion reads blocks.{l}.mlp, while GraniteMoeHybrid keeps its MLP in shared_mlp. expand_neurons=True now raises an explicit NotImplementedError there instead of a KeyError. Happy to add shared_mlp support in a follow-up if you want it.
| labels.append(f"{l}_attn_out") | ||
| if incl_mlp: | ||
| else: | ||
| mixers, mixer_labels = self._mixer_stack(l, Slice(None)) |
There was a problem hiding this comment.
On NemotronH, mode="mlp" returns only the embedding and mode="attn" includes the MLP block, because the slot is chosen from the submodule name only. The adapters that do this set cfg.layers_block_type, it would be worthwhile to consult it for the slot and label when it is present.
There was a problem hiding this comment.
Done in b63c0df. When cfg.layers_block_type is set, passthrough mixers use it: mlp / moe blocks go to the MLP slot as {l}_mlp_out, attention blocks are labelled {l}_attn_out, and Mamba blocks keep {l}_mixer_out. In get_full_resid_decomposition, MLP-type mixers come through the MLP rows when expand_neurons=False and as their own row otherwise, so nothing is counted twice. A new test checks on the tiny NemotronH that mode="mlp" gives ["3_mlp_out"] and mode="attn" gives ["0_mixer_out", "1_attn_out", "2_mixer_out"].
| mixer_layers.append(layer) | ||
| mixer_list: List[torch.Tensor] = [] | ||
| for l in mixer_layers: | ||
| mixers, mixer_labels = self._mixer_stack(l, pos_slice, subtract_bias=True) |
There was a problem hiding this comment.
The row-order list in the get_full_resid_decomposition docstring does not mention the mixer rows that now sit between the head and neuron blocks. Would you please add an entry to the list for them?
There was a problem hiding this comment.
Added in b63c0df as row 2, between the head and neuron rows, including the NemotronH MLP-type case.
- Scale mixer rows by the block's residual_contribution_scale after the
bias subtraction, matching the head, neuron and bias paths (Granite 4.0-H
applies residual_multiplier after the mixer's hook_out).
- Use cfg.layers_block_type for passthrough mixers (NemotronH): MLP-type
blocks fill the mlp slot as {l}_mlp_out, attention blocks are labelled
{l}_attn_out. In get_full_resid_decomposition they come through the MLP
rows unless expand_neurons=True, so nothing is counted twice.
- Neuron expansion raises NotImplementedError on blocks whose MLP is not
in the mlp slot (GraniteMoeHybrid shared_mlp) instead of a KeyError.
- Document the mixer rows in get_full_resid_decomposition.
- Tests: dense GraniteMoeHybrid with residual_multiplier=0.22, NemotronH
slot assignment.
|
Looks good! Thanks for making those updates. Merging now |
LFM2 and LFM2-MoE put their short convolution in a `conv` block slot, which was not in VARIANT_SUBMODULE_NAMES. The residual-decomposition APIs from #1987 therefore treated conv layers as attention blocks and raised KeyError on `blocks.0.hook_attn_out` / `blocks.0.attn.hook_z`. Register `conv` as a variant slot and map its `out_proj.bias` so the full decomposition's bias row cancels it. Add a tiny LFM2 (with non-zero conv biases) to the SSM / hybrid decomposition tests.
Description
On every SSM or hybrid bridge (Qwen3.5, Qwen3Next, NemotronH, Mamba-2, GraniteMoeHybrid…), the
ActivationCacheresidual-decomposition APIs raise on the first block without attention:They loop over
range(n_layers)and assume each block hasattnandmlp. Since #1578, gated-delta-net and Mamba blocks intentionally expose their mixer output (linear_attn.hook_out,mixer.hook_out) instead ofhook_attn_out, and Mamba / NemotronH blocks have no MLP.accumulated_residalready worked.This PR keeps the attention path unchanged and, for blocks without attention:
decompose_resid: the block's sequence-mixer output takes the attention slot, labelled after its variant (0_linear_attn_out,0_mixer_out); blocks without an MLP contribute nomlp_out.mode="mlp"on a model with no MLP returns an empty stack instead of failing intorch.stack.compute_head_results/stack_head_results: only attention layers contribute heads; the other blocks' outputs fall into the remainder.stack_neuron_results: only blocks with an MLP contribute neurons.get_full_resid_decomposition: adds each mixer output as one component, minus its output bias (which thebiasrow already accumulates viaaccumulated_bias), so the decomposition still sums to the residual stream.Block structure is read from the block's bridged submodules with the existing
VARIANT_SUBMODULE_NAMES/_NORM_PREFIXESconstants and_get_block_variant_bias, so there is no per-architecture code.Tests
New
tests/integration/model_bridge/test_ssm_hybrid_resid_decomposition.py, on tiny random Qwen3.5, NemotronH, Mamba-2 and Mamba-2 with non-zero output biases (same fixtures astest_ssm_effective_attention_dispatch.py, no Hub access):decompose_residsums toresid_postof the last layer and toresid_preof intermediate layers;mlp_input=Truesums toresid_mid(Qwen3.5);mode="attn"+mode="mlp"+ embed partitions the stream; labels name the mixer.stack_head_resultslabels only attention layers; heads + remainder sum to the stream; per-head results +b_Oequalhook_attn_out.get_full_resid_decompositionsums to the stream with and withoutexpand_neurons, and withapply_ln=True+project_output_onto.All 37 relevant cases failed before the fix with the
KeyErrors above. Disabling the bias subtraction makes the fourmamba2_biasfull-decomposition cases fail.Checked on the real
Qwen/Qwen3.5-0.8B(fp32, CPU):decompose_resid(49 components) sums to the final residual within 9.5e-7, heads + remainder within 2.1e-7,get_full_resid_decompositionwithin 4.3e-6. Direct logit attribution for " Berlin" after "The capital of Germany is" now runs (top:15_attn_out,23_mlp_out,7_attn_out).make formatanduv run mypy .are clean. Locally, I ran the 147 test files that useActivationCachewith Hub access disabled, with and without this change: per-test results are identical (2065 passed). Tests that need to download checkpoints did not run locally because of a slow connection, so I am relying on CI for those.Known limits / open questions
mixer, so attention and MLP-type blocks also appear as{l}_mixer_outin the attention slot and expose no per-head results. Sums are exact; the attn/mlp split follows block structure rather thanlayers_block_type. Happy to route bylayers_block_typeif you prefer.mlpslot orhook_mlp_out, sodecompose_residstill raises onmlp_out. Separately,resid_post - resid_prediffers from the sum of its sublayer hooks by ~6e-3 on the tiny fixture (residual_multiplier), which deserves its own issue.Fixes #1986
Type of change
Checklist: