Skip to content

Make residual-decomposition APIs work on SSM / hybrid bridges - #1987

Merged
jlarson4 merged 2 commits into
TransformerLensOrg:devfrom
SBrouck:fix/ssm-hybrid-resid-decomposition
Nov 6, 2026
Merged

jlarson4 merged 2 commits into
TransformerLensOrg:devfrom
SBrouck:fix/ssm-hybrid-resid-decomposition

Conversation

@SBrouck

@SBrouck SBrouck commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Description

On every SSM or hybrid bridge (Qwen3.5, Qwen3Next, NemotronH, Mamba-2, GraniteMoeHybrid…), the ActivationCache residual-decomposition APIs raise on the first block without attention:

_, cache = bridge.run_with_cache(tokens)   # e.g. Qwen/Qwen3.5-0.8B
cache.decompose_resid()                    # KeyError: 'blocks.0.hook_attn_out'
cache.stack_head_results()                 # KeyError: 'blocks.0.attn.hook_z'
cache.get_full_resid_decomposition()       # KeyError: 'blocks.0.attn.hook_z'
cache.logit_attrs(cache.decompose_resid(), tokens=...)  # KeyError

They loop over range(n_layers) and assume each block has attn and mlp. Since #1578, gated-delta-net and Mamba blocks intentionally expose their mixer output (linear_attn.hook_out, mixer.hook_out) instead of hook_attn_out, and Mamba / NemotronH blocks have no MLP. accumulated_resid already 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 no mlp_out. mode="mlp" on a model with no MLP returns an empty stack instead of failing in torch.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 the bias row already accumulates via accumulated_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_PREFIXES constants 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 as test_ssm_effective_attention_dispatch.py, no Hub access):

  • decompose_resid sums to resid_post of the last layer and to resid_pre of intermediate layers; mlp_input=True sums to resid_mid (Qwen3.5); mode="attn" + mode="mlp" + embed partitions the stream; labels name the mixer.
  • stack_head_results labels only attention layers; heads + remainder sum to the stream; per-head results + b_O equal hook_attn_out.
  • get_full_resid_decomposition sums to the stream with and without expand_neurons, and with apply_ln=True + project_output_onto.

All 37 relevant cases failed before the fix with the KeyErrors above. Disabling the bias subtraction makes the four mamba2_bias full-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_decomposition within 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 format and uv run mypy . are clean. Locally, I ran the 147 test files that use ActivationCache with 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

  • NemotronH: every block wraps its sublayer in a passthrough mixer, so attention and MLP-type blocks also appear as {l}_mixer_out in the attention slot and expose no per-head results. Sums are exact; the attn/mlp split follows block structure rather than layers_block_type. Happy to route by layers_block_type if you prefer.
  • GraniteMoeHybrid is unchanged: its MoE blocks have no mlp slot or hook_mlp_out, so decompose_resid still raises on mlp_out. Separately, resid_post - resid_pre differs 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

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (docstrings)
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective
  • New and existing unit tests pass locally with my changes

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 jlarson4 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread transformer_lens/ActivationCache.py Outdated
labels.append(f"{l}_attn_out")
if incl_mlp:
else:
mixers, mixer_labels = self._mixer_stack(l, Slice(None))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@jlarson4

jlarson4 commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

Looks good! Thanks for making those updates. Merging now

@jlarson4
jlarson4 merged commit e1c31b1 into TransformerLensOrg:dev Nov 6, 2026
30 checks passed
jlarson4 pushed a commit that referenced this pull request Nov 9, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants