Repository navigation
fix: fire the conv hooks of Mamba-family mixers on transformers >= 5.15 - #2053
XiaoyuanWang111 wants to merge 2 commits into
Conversation
jlarson4
left a comment
There was a problem hiding this comment.
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 ( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
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 passself.conv1d.weightandself.conv1d.biasto a module-levelcausal_conv1d_fnin the modeling file, which runs the torch path or the causal-conv1d kernel. The adapters swap aDepthwiseConv1DBridgein for the conv, and that bridge now never runs. As a result itshook_inandhook_outnever fire, and neither does the mixer'shook_convalias.run_with_cachestores nothing for them, and a hook added there is silently ignored. Mamba-2'scompute_effective_attentionandcompute_ssm_statereadconv1d.hook_outfrom the cache, so they raise.This affects 11 architectures: Mamba, FalconMamba, Mamba-2, Bamba, Falcon-H1, GraniteMoeHybrid, Jamba, LFM2, LFM2-MoE, NemotronH and Zamba2.
GatedDeltaNetBridgealready handles the 5.15 change, so Qwen3-Next and Qwen3.5 are fine.pyproject.tomlasks fortransformers>=5.9.0with 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)indepthwise_conv1d.py.SSMMixerBridge,SSM2MixerBridgeandLfm2ShortConvBridgeenter it around the HF forward. While it is active, it replaces thecausal_conv1d_fnglobal of the module that defines the HF forward with a routing function: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.The original function is put back on exit, including after an exception.
When the routing does nothing:
Two existing limits stay as they are:
causal_conv1d_update) are not routed, so the conv hooks still fire only on prefill duringgenerate(). The class docstring already notes this.Conv1dthrough the bridge instead of the kernel, so that the hooks fire.Reproduce
Run this on
devwith transformers 5.24.1. It builds a tiny Mamba-2 from a config and downloads nothing:On
devwith 5.24.1, the first line prints[]. The second line raises:With this change, the first line prints
['blocks.0.mixer.conv1d.hook_in', 'blocks.0.mixer.conv1d.hook_out']and the second printstorch.Size([1, 8, 4, 4]).devwith 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:dev)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_projhooks (Mamba, FalconMamba, Jamba), and with themcompute_effective_attention/compute_ssm_stateon those models. Since 5.15, HF computesself.dt_proj.weight @ time_stepinline and passes the bias to the scan asdelta_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.pyhas two groups:hook_outreaches the output;hook_outreaches 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:
test_ssm_bridges.pyandtest_ssm_hooked_forward_parity.py;test_ssm_effective_attention_dispatch.py,test_ssm_hybrid_resid_decomposition.pyandtest_ssm_real_weights.py.I left out both
test_nemotron_h_adapter.pyfiles. The integration one loads a 9B checkpoint. The unit one passes all 45 ondevand with this change, under 5.24.1 and 5.13.0.Under 5.24.1, 46 tests that fail on
devpass with this change, and no test starts failing. Under 5.13.0,devpasses 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:
dt_projgap above;test_ssm_hybrid_resid_decomposition.pythat I have not looked into.With the router fix applied as well, those 10 pass, which leaves the 26
dt_projcases and the RecurrentGemma one.Type of change
Checklist: