Skip to content

Make the causal conv1d, Mamba scan and Mamba2 SSD of linear attention layers kernelizable - #49186

Open
hmellor wants to merge 35 commits into
huggingface:mainfrom
hmellor:mamba2-linear-attention-interface
Open

hmellor wants to merge 35 commits into
huggingface:mainfrom
hmellor:mamba2-linear-attention-interface

Conversation

@hmellor

@hmellor hmellor commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

This PR gives linear attention layers kernelizable seams for their stateful steps, so that runtimes which manage the conv and recurrent state themselves can swap those steps out with kernelize. The motivating case is vLLM's Transformers modeling backend, which runs packed batches that mix prefill and decode: vllm-project/vllm#59224.

Each seam is a function that reads and updates its state in the cache. It is decorated with use_kernel_forward_from_hub and listed in the layer's use_kernelized_func, so kernelize replaces each layer's own copy:

  • causal_conv1d_forward, in modeling_mamba.py: the causal depthwise conv. It replaces the conv and conv-cache code that every linear attention model duplicated, and 23 models now use it.
  • ssd_forward, in modeling_mamba2.py: Mamba2's SSD scan, inherited by Bamba, FalconH1, GraniteMoeHybrid, NemotronH and Zamba2.
  • selective_scan_forward, in modeling_mamba.py: Mamba's selective scan, inherited by FalconMamba and Jamba. Zamba scans each of its Mamba heads separately, so it keeps calling the kernels directly.

Modular copies each seam into every modeling file that uses it, and this adds modular files for Mamba2 and Zamba. None of the seams has a kernel on the Hub, so kernelize no longer logs a missing-mapping warning for them. Gated DeltaNet and KDA would get seams of their own in follow-ups.

This also raises kernels-community/mamba-ssm to version 5 for every layer mapped to it. Its conv serves widths up to 8 in half precision, so LFM3 (width 7) drops its torch-only override. LFM3's kernels test is skipped, because float32 is still limited to widths 2 to 4.

Without kernels, the only numerical change is in FalconH1's decode path with mamba_rms_norm=False, which now applies silu(gate) after the scan, as its prefill path already did.

Validation, on a B200:

  • Logits and greedy generation vs main, with use_kernels=True: bit-identical for every model the comparison could load, except GraniteMoeHybrid (max logit diff 3e-8, from mamba-ssm v5). LFM3 runs its width 7 conv through the v5 kernel in bf16. Without kernels, Mamba, FalconMamba and Jamba are bit-identical.
  • Model test suites of the 23 affected models, on GPU: the same failures as main, before the mamba-ssm v5 bump. After it, the LFM3 suite passes.
  • vLLM end to end: [Transformers backend] Support Mamba2 (SSD) layers vllm-project/vllm#59224 serves Mamba2 and Bamba through ssd_forward and causal_conv1d_forward. It matches native vLLM and Transformers generate, both eager and with torch.compile and CUDA graphs.

This is a draft for design feedback, written with AI assistance (Claude Code). I will review every changed line before marking it ready.

Linear attention layers now dispatch only their stateful core (causal
convolution, recurrence and recurrent state handling) through a
per-mechanism interface selected by `config._linear_attn_implementation`.
Projections, gating and the output projection stay in the modeling file.
This lets runtimes that manage recurrent state themselves (e.g. vLLM's
Transformers modeling backend) swap the core without re-implementing the
layer.

- Add `LinearAttentionInterface` and `ALL_SSD_FUNCTIONS` for Mamba2
- Add `linear_attn_implementation` to configs and `from_pretrained`
- Move `Mamba2Mixer`'s conv + scan into `eager_ssd_forward`
- Propagate to Bamba, Zamba2, GraniteMoeHybrid, NemotronH and FalconH1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

hmellor and others added 4 commits September 29, 2026 13:09
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Replace the per-mechanism interface classes with one
`ALL_LINEAR_ATTENTION_FUNCTIONS`, whose keys are
`"<implementation>|<mechanism>"` (e.g. `"vllm|ssd"`). Backends register
in one place, validation reads one registry and the mechanism is a
string literal that modular conversion cannot rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This reverts commit d09dc86. One registry per contract (e.g.
`ALL_SSD_FUNCTIONS`) matches `AttentionInterface` and
`ExpertsInterface` and keeps each contract's docstring next to its
registry, instead of introducing a two-part key convention.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

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

Just some quick initial comments but imo we could create a lot of interfaces based on each implementation (ssd, gdn, kda) right?

hmellor and others added 2 commits October 7, 2026 18:06
Dispatch the two stateful pieces of the Mamba2 mixer separately:
`CausalConv1dInterface` owns the conv state and `SSDInterface` owns the
recurrent state. Projections, masking, gated norm and output projection
stay in the modeling file. `use_precomputed_states` is computed once
before the convolution, since the convolution marks the cache as having
a previous state.

Document that layers must read their sizes from module attributes at
forward time, so runtimes can shard them for tensor parallelism.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 36570539415:1
Result: success | Jobs: 16 | Tests: 196,653 | Failures: 0 | Duration: 13h 53m

hmellor and others added 8 commits November 17, 2026 15:33
Port the linear attention interfaces to the renamed `cache` argument and
the new cache getters (`get_conv_state`, `get_recurrent_state`,
`is_recording_past`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
…_attn_utils

Every linear attention model had the same copy of the causal_conv1d kernels and of the
code that runs them against the conv state in the cache. Move both to
modeling_linear_attn_utils.causal_conv1d_forward and use it in all 23 models. Kernel widths
the causal_conv1d kernels don't support fall back to PyTorch, which replaces LFM3's
PyTorch-only override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Move the SSD step of the Mamba2 family (recurrent vs chunk scan and the recurrent state
handling) and its kernels to modeling_linear_attn_utils.ssd_forward. Decorate
causal_conv1d_forward and ssd_forward with use_kernel_forward_from_hub and list them in
each layer's use_kernelized_func, so kernelize can replace the whole stateful step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
…tions

Merge linear-attn-utils-conv, taking its tree: the interfaces and
_linear_attn_implementation are gone, and linear attention layers run their conv and scan
through causal_conv1d_forward and ssd_forward in modeling_linear_attn_utils, which
kernelize can replace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Move the causal conv1d into modeling_mamba and the SSD into modeling_mamba2,
and have the other models import them in their modular files, so that each
modeling file contains its own copy. Add modular files for Mamba2 and Zamba,
which reuse the Mamba conv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Move the scan of the Mamba mixer, which reads and updates the recurrent
state in the cache, into selective_scan_forward, which kernelize can
replace. FalconMamba and Jamba inherit it with modular. Zamba scans each
of its Mamba heads separately, so it keeps calling the kernels directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@hmellor hmellor changed the title Add a linear attention interface, starting with Mamba2's SSD core Make the conv and scan of linear attention layers kernelizable Nov 18, 2026
hmellor and others added 4 commits November 18, 2026 14:28
Restore the torch code into the decorated causal_conv1d_update and
causal_conv1d_fn, as on main, and keep LFM3's width 7 torch-only override in
its modular file. Lfm3ShortConv still lists causal_conv1d_forward in
use_kernelized_func so kernelize can replace it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
…nings

Version 5 of the kernels-community/mamba-ssm causal conv1d serves widths up
to 8 in half precision, so LFM3 no longer needs its torch-only override.
Its kernels test is skipped, as the kernels still serve only widths 2 to 4
in float32.

causal_conv1d_forward, ssd_forward and selective_scan_forward are for
runtimes that bring their own kernels, so hide the warnings kernelize logs
for having no Hub mapping for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@hmellor
hmellor marked this pull request as ready for review November 18, 2026 14:43
hmellor and others added 2 commits November 18, 2026 14:51
Kernelize LaraMini's causal_conv1d_forward, which its gated DeltaNet
inherits, drop the _skip_keys_device_placement that main removed from the
Zamba modular file, and shorten the GPT-2 init comment in the Mamba2
modular file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

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

Ok I guess this is limited to conv1d, mamba, and mamba2 I'd definitely make this more explicit in the pr (title)

Also cc @remi-or @qgallouedec as you work on the CB side rn which needs to be communicated properly whether this works for you

Comment thread tests/models/lfm3/test_modeling_lfm3.py Resolved
hmellor and others added 3 commits November 18, 2026 19:21
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

# Conflicts:
#	src/transformers/models/lfm3/modeling_lfm3.py
#	src/transformers/models/lfm3/modular_lfm3.py
…moHybrid style

- Hide the runtime-only mapping warnings with `suppress_kernels_logging`, copied
  from huggingface#47773
- Unskip LFM3's kernels test, main now serves its conv with the Hub kernels
- Use if/else for OlmoHybrid's recurrent state, like the other models

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@hmellor hmellor changed the title Make the conv and scan of linear attention layers kernelizable Make the causal conv1d, Mamba scan and Mamba2 SSD of linear attention layers kernelizable Nov 18, 2026
hmellor and others added 6 commits November 18, 2026 19:34
…ular

- Revert the `ssd_*` renames to the original `mamba2_selective_state_update`
  and `mamba2_chunk_scan`, and name the new seams `mamba_scan_forward` and
  `mamba2_scan_forward`, which the converter never renames
- Mamba2 (derived from Mamba) inherits its norm, block, pretrained model,
  model and causal LM classes from Mamba, overriding only what differs
- Zamba (a Mamba backbone with shared attention) takes its norm and selective
  scan helpers from Mamba and `eager_attention_forward` from Llama

`apply_mask_to_padding_states` stays local, as modular would rewrite the
`state-spaces/mamba` link in its docstring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Zamba's head was a hand-copied version of `GenericForSequenceClassification`,
so it now inherits it via Mistral. Zamba2 keeps its own `forward` and drops the
`__init__` that only swapped in `Zamba2Model`, which `AutoModel` now resolves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Comment thread src/transformers/utils/generic.py Resolved
Comment thread src/transformers/utils/generic.py Resolved
hmellor and others added 2 commits November 20, 2026 11:16
…press_kernels_logging

- Inkling, Inkling2 and Zamba pass `**kwargs` to `causal_conv1d_forward` like every other caller
- `suppress_kernels_logging` takes `layers` as required and uses a callable filter

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve conflicts in inkling2 (use causal_conv1d_forward with the new cache_layer_idx) and qwen3_5_moe imports, then regenerate modular outputs (inkling2, inkling2_loop, qwen3_5_moe, qwen4_exp).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: bailing_hybrid, bamba, falcon_h1, falcon_mamba, glm5_next, granitemoehybrid, inkling, inkling2, inkling2_loop, jamba, kimi_linear, lara_mini, lfm2, lfm2_moe, lfm3, mamba

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

Im mainly focusing on last details. The core and overall design im in

Comment thread src/transformers/utils/generic.py Resolved
`self.out_proj`. The pre-activations, coming from different mamba heads, are then concatenated and fed into `self.out_proj`.
"""

def __init__(self, config: ZambaConfig, layer_idx):

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.

is the init not similar to mamba for most of the init?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not much is shared here: Zamba keeps per-head x_proj_weight, dt_proj_weight and dt_proj_bias as raw parameters where Mamba has nn.Linear modules, and its config fields have different names (mamba_d_state, mamba_d_conv, mamba_expand, mamba_dt_rank, ...). Inheriting would mean deleting Mamba's modules and overriding almost every line, so I left it as is.

AI-assisted reply (Claude Code).

pass


class ZambaAttentionDecoderLayer(nn.Module):

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.

a few renames (conversion mapping) and we can just inherit here from e.g. llama no?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Its forward can't be shared: Zamba's attention block has no residual connections, takes the concatenated 2 * hidden_size input and gets layer_idx per call. Jamba's layer already uses the same names (feed_forward, pre_ff_layernorm), so no renames would be needed, but its __init__ reads config.layers_num_experts and it is a GradientCheckpointingLayer, whereas Zamba's is a plain module shared inside ZambaHybridLayer (the checkpointed layer). Both methods would be overridden and nothing inherited, so I kept it standalone.

AI-assisted reply (Claude Code).

hmellor and others added 2 commits November 25, 2026 09:42
…a2Model

- `mamba_scan_forward` and `mamba2_scan_forward` read the recurrent state from `cache` themselves, like
  `causal_conv1d_forward` does for the conv state
- Restore `suppress_kernels_logging` as in huggingface#47773
- Rename `MambaRMSNormGated` to `Mamba2RMSNormGated`; the gated norm is part of the final projection step
- `Mamba2Model` uses `merge_with_config_defaults` and `capture_outputs`, `Mamba2ForCausalLM` uses `can_return_tuple`
- Seam docstrings: "The mixer", no `seq_idx` example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
- `ZambaAttention` inherits from `JambaAttention`
- `ZambaForCausalLM` inherits from `LlamaForCausalLM`, without a TP plan as before (its head is tied to the
  unsharded embedding)
- Import `apply_mask_to_padding_states` from Mamba2
- `ZambaHybridLayer` concatenates the embeddings before calling the shared attention block
- Support flex attention and the attention backend interface

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

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.

4 participants