Skip to content

fix: fire the conv hooks of Mamba-family mixers on transformers >= 5.15 - #2053

Open
XiaoyuanWang111 wants to merge 2 commits into
TransformerLensOrg:devfrom
XiaoyuanWang111:fix/ssm-conv-hooks-transformers-5-15
Open

XiaoyuanWang111 wants to merge 2 commits into
TransformerLensOrg:devfrom
XiaoyuanWang111:fix/ssm-conv-hooks-transformers-5-15

Conversation

@XiaoyuanWang111

Copy link
Copy Markdown

Description

transformers 5.15.0 (released 2026-08-10, huggingface/transformers#47452) changed how the Mamba-family mixers run their causal convolution. They no longer call self.conv1d(...). Instead they pass self.conv1d.weight and self.conv1d.bias to a module-level causal_conv1d_fn in the modeling file, which runs the torch path or the causal-conv1d kernel. The adapters swap a DepthwiseConv1DBridge in for the conv, and that bridge now never runs. As a result its hook_in and hook_out never fire, and neither does the mixer's hook_conv alias. run_with_cache stores nothing for them, and a hook added there is silently ignored. Mamba-2's compute_effective_attention and compute_ssm_state read conv1d.hook_out from the cache, so they raise.

This affects 11 architectures: Mamba, FalconMamba, Mamba-2, Bamba, Falcon-H1, GraniteMoeHybrid, Jamba, LFM2, LFM2-MoE, NemotronH and Zamba2. GatedDeltaNetBridge already handles the 5.15 change, so Qwen3-Next and Qwen3.5 are fine.

pyproject.toml asks for transformers>=5.9.0 with no upper bound, so a fresh install gets 5.24.1. CI runs the lock's 5.13.0, which is why this does not show there.

The change

The change adds route_causal_conv1d(hf_module, conv_attr) in depthwise_conv1d.py. SSMMixerBridge, SSM2MixerBridge and Lfm2ShortConvBridge enter it around the HF forward. While it is active, it replaces the causal_conv1d_fn global of the module that defines the HF forward with a routing function:

  • A call with this conv's own weight (HF passes weight.squeeze(1)) and bias runs the conv bridge, trims the output to the input length and applies the activation. This is what the function's torch path computes.
  • Any other call goes to the original function.

The original function is put back on exit, including after an exception.

When the routing does nothing:

  • On transformers < 5.15, where the mixers call the conv module themselves.
  • When the conv is not a bridge.
  • When the modeling file has no such function.

Two existing limits stay as they are:

  • Decode steps (causal_conv1d_update) are not routed, so the conv hooks still fire only on prefill during generate(). The class docstring already notes this.
  • Where the causal-conv1d kernel is installed, prefill now runs the torch Conv1d through the bridge instead of the kernel, so that the hooks fire.

Reproduce

Run this on dev with transformers 5.24.1. It builds a tiny Mamba-2 from a config and downloads nothing:

import torch
from transformers import AutoConfig, AutoModelForCausalLM

from transformer_lens.model_bridge.sources import build_bridge_from_module

cfg = AutoConfig.for_model(
    "mamba2", vocab_size=128, hidden_size=64, num_hidden_layers=2, num_heads=8, head_dim=16,
    n_groups=1, state_size=16, conv_kernel=4, chunk_size=8, expand=2,
)
torch.manual_seed(0)
hf = AutoModelForCausalLM.from_config(cfg).eval()
bridge = build_bridge_from_module(hf, "Mamba2ForCausalLM", hf_config=cfg).eval()
with torch.no_grad():
    _, cache = bridge.run_with_cache(torch.tensor([[1, 2, 3, 4]]))
print([k for k in cache.keys() if k.startswith("blocks.0.mixer.conv1d")])
print(bridge.blocks[0].mixer.compute_effective_attention(cache, layer_idx=0).shape)

On dev with 5.24.1, the first line prints []. The second line raises:

RuntimeError: SSD reconstruction needs 'blocks.0.mixer.in_proj.hook_out' and 'blocks.0.mixer.conv1d.hook_out' in cache.

With this change, the first line prints ['blocks.0.mixer.conv1d.hook_in', 'blocks.0.mixer.conv1d.hook_out'] and the second prints torch.Size([1, 8, 4, 4]). dev with 5.13.0 prints the same.

Across architectures

I ran each of the 11 architectures with its tiny config from transformers' own testers, used run_with_cache, and compared the hook names and shapes with those on 5.13.0:

Architecture Hooks missing on 5.24 (dev) Missing with this change
Mamba, FalconMamba conv1d and dt_proj dt_proj
Mamba-2, Bamba, Falcon-H1, GraniteMoeHybrid, NemotronH, Zamba2 conv1d none
Jamba conv1d and dt_proj dt_proj
LFM2, LFM2-MoE conv none

The restored hooks have the same shapes as on 5.13. The bridge's logits match Hugging Face's exactly (max abs diff 0.0) for all 11, both before and after the change. Under 5.13.0 the change alters nothing: the same hook names and shapes appear as on dev.

Still missing with this change: Mamba-1's dt_proj hooks (Mamba, FalconMamba, Jamba), and with them compute_effective_attention / compute_ssm_state on those models. Since 5.15, HF computes self.dt_proj.weight @ time_step inline and passes the bias to the scan as delta_bias. That leaves no call to route, so these hooks need a different mechanism. I have a follow-up that restores them on top of this PR and will open it separately.

Tests

tests/unit/model_bridge/generalized_components/test_ssm_conv_hooks.py has two groups:

  • A stand-in mixer shaped like transformers >= 5.15. This checks the routing on any installed transformers:
    • the hooks fire;
    • the output is bit-exact with the function's;
    • a patch on hook_out reaches the output;
    • other convs and the module function are left alone;
    • the function is restored after an error.
  • The real HF Mamba, Mamba-2, NemotronH and LFM2 mixers, wired as the adapters wire them:
    • the conv hooks fire with the 5.13 shapes;
    • the output is bit-exact with HF's;
    • a patch on hook_out reaches the output.

With the routing disabled, the 8 HF-mixer cases fail under 5.24.0 and pass under 5.13.0. With it, all 13 pass under 5.24.1 and 5.13.0.

Existing tests: I ran the test files of these 11 architectures and the SSM files. That is 27 files:

  • the unit and integration test files of these architectures;
  • test_ssm_bridges.py and test_ssm_hooked_forward_parity.py;
  • test_ssm_effective_attention_dispatch.py, test_ssm_hybrid_resid_decomposition.py and test_ssm_real_weights.py.

I left out both test_nemotron_h_adapter.py files. The integration one loads a 9B checkpoint. The unit one passes all 45 on dev and with this change, under 5.24.1 and 5.13.0.

Under 5.24.1, 46 tests that fail on dev pass with this change, and no test starts failing. Under 5.13.0, dev passes all 791 and this change all 804, the 13 new tests included (38 skipped).

Under 5.24.1, 37 still fail or error with this change:

  • 10 come from Jamba's MoE router, which changed in transformers 5.22 (I'll send that fix separately);
  • 26 are the Mamba-1 dt_proj gap above;
  • 1 is a RecurrentGemma label case in test_ssm_hybrid_resid_decomposition.py that I have not looked into.

With the router fix applied as well, those 10 pass, which leaves the 26 dt_proj cases and the RecurrentGemma one.

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
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not rewritten tests relating to key interfaces which would affect backward compatibility

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

Thanks for adding a patch for this @XiaoyuanWang111, these transformers version based patches are very helpful! Just a handful of small comments on this one.

def routed(*args: Any, **kwargs: Any) -> Any:
weight = args[1] if len(args) > 1 else kwargs.get("weight")
bias = args[2] if len(args) > 2 else kwargs.get("bias")
if (

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.

HF passes the mixer's extra keyword arguments to causal_conv1d_fn, and this routing reads only activation. With seq_idx set, an LFM2 forward that HF refuses now returns as if the argument were not there. Could you leave calls that carry seq_idx or cu_seqlens to the original function?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in e3ac550. A call that carries seq_idx or cu_seqlens now goes to the original function. Without causal-conv1d it raises HF's ValueError, and with the kernel the packed sequences stay apart. Before this, with 5.24.1, the bridged Mamba, Mamba-2, NemotronH and LFM2 mixers all returned an output for either argument where HF raises. Now they raise the same error. Two new tests cover it: test_route_leaves_packed_sequences_to_the_function (stand-in) and test_hf_mixer_packed_sequences_behave_as_hf (the four real mixers). The second requires the bridge to return what HF returns or raise what HF raises, so it also holds on 5.13.

out = ACT2FN[activation](out)
return out.to(hidden_states.dtype)

namespace[_CAUSAL_CONV1D_FN] = routed

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 swap is process-wide and unsynchronised. Two threads running bridged forwards at once restore each other's function, which leaves the routing installed in HF's module and silently skips some conv hooks. Could you make the swap safe for concurrent forwards?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in e3ac550. The context no longer saves and restores whatever it finds. The first context to enter installs a single dispatcher in the modeling file, and a count kept under a lock tracks the contexts that use it. The last one to leave puts the original function back, but only if the dispatcher is still the function installed there. Each call goes only to the calling thread's routes, which are thread-local, so a forward on another thread, bridged or not, gets the original function. test_route_keeps_concurrent_forwards_apart makes two threads overlap so that thread B's route outlives thread A's. On the previous version it fails, because B's conv hook does not fire. I also ran two threads of 200 bridged forwards each on all four HF mixers with 5.24.1. Before the change, 1 to 11 forwards per thread skipped the conv hook on Mamba, Mamba-2 and NemotronH, and the routing stayed installed on all four. Now no hook is missed, the outputs are bit-exact with HF's, and the function is put back.

with pytest.raises(RuntimeError, match="hook failed"):
with torch.no_grad(), route_causal_conv1d(mixer, "conv1d"):
mixer(torch.randn(2, 6, 5))
assert sys.modules[__name__].causal_conv1d_fn is causal_conv1d_fn

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.

Both sides of this assert read the same module global, so it holds even when the function is never put back (same on lines 117 and 140). Can you please use a reference taken before the context is entered to compare?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in e3ac550. The asserts on lines 117, 130 and 140 now compare with function_before, read from the module before the context is entered. As a check, I removed the restore from the routing. Two of these tests then fail, and so does the new threading test. The third, the no-op case, still holds because nothing is installed there. With the old asserts, all of them passed. test_ssm_conv_hooks.py now has 24 tests, all passing on 5.24.1 and 5.13.0. Merged onto current dev, the 27 other SSM-related test files plus this one show the same failures with and without e3ac550 on 5.24.1. All of them are outside this change: Mamba-1 dt_proj, the Jamba router and the RecurrentGemma labels. On 5.13.0 they all pass.

route_causal_conv1d swapped the modeling file's causal_conv1d_fn for the
length of each context and put back whatever it found on entry, so two
threads in overlapping forwards restored each other's function: some conv
hooks were skipped and the routing could stay installed. The function is
now replaced by one dispatcher while any thread is inside a context and
put back when the last one leaves (reference count under a lock), and
each call goes only to the calling thread's routes.

Calls that carry seq_idx or cu_seqlens go to the original function, which
refuses them without the causal-conv1d kernel and keeps packed sequences
apart with it; the bridge used to run them as if the argument were absent.

The tests compare the module function with a reference taken before the
context is entered, and cover packed-sequence calls (stand-in and the
real HF mixers) and two threads with overlapping routes.

This branch has not been deployed

No deployments
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