Skip to content
Open
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
9645219
Add a linear attention interface, starting with Mamba2's SSD core
hmellor Sep 29, 2026
84d89a8
small cleanup
hmellor Sep 29, 2026
9673790
fix double attr
hmellor Sep 29, 2026
d09dc86
Use a single linear attention registry keyed by mechanism
hmellor Sep 29, 2026
c8a3c68
Revert to one linear attention registry per mechanism
hmellor Sep 29, 2026
97ecc73
Merge branch 'main' into mamba2-linear-attention-interface
hmellor Oct 7, 2026
571d9a3
Split the Mamba2 SSD interface into conv and scan interfaces
hmellor Oct 14, 2026
3aa8158
Merge branch 'main' into mamba2-linear-attention-interface
hmellor Nov 17, 2026
5157924
Share the causal conv1d of linear attention layers in modeling_linear…
hmellor Nov 17, 2026
6731513
Share the Mamba2 SSD and make the shared steps kernelizable
hmellor Nov 17, 2026
dbc4955
Replace the linear attention interfaces with shared kernelizable func…
hmellor Nov 17, 2026
69ca9e3
Inline the shared linear attention steps with modular
hmellor Nov 18, 2026
eaea981
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
a0e0828
Make the Mamba selective scan kernelizable
hmellor Nov 18, 2026
e6b48eb
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
e94b862
Drop the per-width torch fallback of the shared causal conv1d
hmellor Nov 18, 2026
fadd192
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
d33ec3e
Serve LFM3's conv with mamba-ssm v5 and hide runtime-only mapping war…
hmellor Nov 18, 2026
e5fbf5f
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
9fa71ab
Merge branch 'main' into linear-attn-utils-conv
hmellor Nov 18, 2026
1439bb6
Fix CI after merging main
hmellor Nov 18, 2026
819f848
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
a746a39
Merge remote-tracking branch 'upstream/main' into linear-attn-utils-conv
hmellor Nov 18, 2026
70684c0
Address review: shared kernels log suppression, LFM3 kernels test, Ol…
hmellor Nov 18, 2026
afaca88
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
ec415ed
Address review: keep `mamba_`/`mamba2_` names and reuse Mamba via mod…
hmellor Nov 18, 2026
e610c89
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
9bb2e51
Use the generic sequence classification head for Zamba and Zamba2
hmellor Nov 18, 2026
e1cb6cd
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
05cbdad
Take Zamba's sequence classification head from Llama
hmellor Nov 18, 2026
7bd2215
Merge branch 'linear-attn-utils-conv' into mamba2-linear-attention-in…
hmellor Nov 18, 2026
eb98632
Address review: forward kwargs to causal_conv1d_forward, simplify sup…
hmellor Nov 20, 2026
9d13e62
Merge main into mamba2-linear-attention-interface
hmellor Nov 23, 2026
38c0f12
Address review: read the recurrent state in the scans, modernise Mamb…
hmellor Nov 25, 2026
a968d16
Address review: inherit more of Zamba
hmellor Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/transformers/integrations/hub_kernels.py
Comment thread
hmellor marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from ..modeling_flash_attention_utils import FLASH_ATTN_KERNEL_VERSIONS
from ..monkey_patching import register_patch_mapping
from ..utils import ENV_VARS_TRUE_VALUES, logging
from ..utils.generic import suppress_kernels_logging
from ..utils.import_utils import (
KERNELS_MAX_VERSION,
KERNELS_MIN_VERSION,
Expand Down Expand Up @@ -950,6 +951,8 @@ def lazy_load_kernel(kernel_name: str, mapping: dict[str, ModuleType | None] = _
return mapping[kernel_name]


# Runtimes managing their own state (e.g. vLLM) replace these layers with `kernelize`, they have no kernel on the Hub
@suppress_kernels_logging(layers={"causal_conv1d_forward", "mamba_scan_forward", "mamba2_scan_forward"})
Comment thread
hmellor marked this conversation as resolved.
Resolved
def kernelize(model: "PreTrainedModel", mode: "Mode | None" = None):
"""Temporarily register hidden kernel wrappers so `kernelize` can discover and replace them."""
if not is_kernels_available():
Expand Down
96 changes: 71 additions & 25 deletions src/transformers/models/bailing_hybrid/modeling_bailing_hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,59 @@ def causal_conv1d_fn(
return out.to(hidden_states.dtype)


@use_kernel_forward_from_hub("causal_conv1d_forward")
def causal_conv1d_forward(
conv1d: nn.Conv1d,
hidden_states: torch.Tensor,
cache: Cache | None,
layer_idx: int,
activation: str | None = None,
state_idx: int = 0,
**kwargs,
) -> torch.Tensor:
"""
Causal depthwise convolution of a linear attention layer, reading and updating its conv state in `cache`.
Layers list it in `use_kernelized_func`, so that `kernelize` can replace it, e.g. with a runtime that manages
the conv state itself.

Args:
conv1d (`nn.Conv1d`):
The depthwise convolution, whose weights and kernel size are used.
hidden_states (`torch.Tensor` of shape `(batch_size, channels, seq_len)`):
The input to the convolution.
cache (`Cache`, *optional*):
The cache holding the conv state, updated in place.
layer_idx (`int`):
The index of the layer in `cache`.
activation (`str`, *optional*):
The activation applied to the output of the convolution.
state_idx (`int`, *optional*, defaults to 0):
Which of the layer's conv states to use.
kwargs:
Passed to the convolution kernel, e.g. `seq_idx` for packed sequences.

Returns:
`torch.Tensor` of shape `(batch_size, channels, seq_len)`: The output of the convolution.
"""
seq_len = hidden_states.shape[-1]
conv_state = cache.get_conv_state(layer_idx, state_idx=state_idx) if cache is not None else None
weight = conv1d.weight.squeeze(1)

# Single-token cached decode: the fused per-step kernel updates the conv state in-place.
if conv_state is not None and seq_len == 1 and not cache.is_recording_past(layer_idx):
return causal_conv1d_update(hidden_states, conv_state, weight, conv1d.bias, activation=activation)

if cache is not None:
hidden_states = cache.update_conv_state(
hidden_states, layer_idx, state_idx=state_idx, conv_kernel_size=conv1d.kernel_size[0]
)
hidden_states = causal_conv1d_fn(hidden_states, weight, conv1d.bias, activation=activation, **kwargs)
# Drop the previous states prepended by the cache
if cache is not None:
hidden_states = hidden_states[:, :, -seq_len:]
return hidden_states


def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6):
"""
This function is intended to align with the l2norm implementation in the FLA library.
Expand Down Expand Up @@ -668,7 +721,13 @@ def chunk_kimi_delta_attention(


@use_kernelized_func(
[chunk_kimi_delta_attention, recurrent_kimi_delta_attention, causal_conv1d_fn, causal_conv1d_update]
[
chunk_kimi_delta_attention,
recurrent_kimi_delta_attention,
causal_conv1d_forward,
causal_conv1d_fn,
causal_conv1d_update,
]
)
class BailingHybridDeltaAttention(nn.Module):
"""Linear attention module."""
Expand Down Expand Up @@ -720,33 +779,20 @@ def forward(
[self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)], dim=-1
).transpose(1, 2)

# Retrieve conv and recurrent states if there is a cache. They may be None if the layer is not initialized.
# Retrieve the recurrent state if there is a cache. It may be None if the layer is not initialized.
if cache is not None:
conv_state = cache.get_conv_state(self.layer_idx, state_idx=0)
recurrent_state = cache.get_recurrent_state(self.layer_idx, state_idx=0)
else:
conv_state, recurrent_state = None, None

if conv_state is not None and seq_len == 1:
mixed_qkv = causal_conv1d_update(
mixed_qkv,
conv_state,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
)
else:
if cache is not None:
mixed_qkv = cache.update_conv_state(mixed_qkv, self.layer_idx, conv_kernel_size=self.conv_kernel_size)
mixed_qkv = causal_conv1d_fn(
mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
**kwargs,
)
if cache is not None:
mixed_qkv = mixed_qkv[:, :, -seq_len:]
recurrent_state = None

mixed_qkv = causal_conv1d_forward(
self.conv1d,
mixed_qkv,
cache,
self.layer_idx,
activation=self.activation,
**kwargs,
)

query, key, value = torch.split(mixed_qkv.transpose(1, 2), [self.qkv_dim] * 3, dim=-1)
query, key, value = [states.view(hidden_shape) for states in (query, key, value)]
Expand Down
38 changes: 12 additions & 26 deletions src/transformers/models/bailing_hybrid/modular_bailing_hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@
from ...models.glm5_next.modeling_glm5_next import (
Glm5NextTextLinearAttention,
Glm5NextTextRMSNormGated,
causal_conv1d_fn,
causal_conv1d_update,
chunk_kimi_delta_attention,
recurrent_kimi_delta_attention,
)
Expand All @@ -57,6 +55,7 @@
from ...utils import TransformersKwargs, auto_docstring
from ...utils.deprecation import deprecate_kwarg
from ...utils.output_capturing import OutputRecorder
from ..mamba.modeling_mamba import causal_conv1d_forward


@auto_docstring(checkpoint="inclusionAI/Ling-3.0-Flash")
Expand Down Expand Up @@ -326,33 +325,20 @@ def forward(
[self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)], dim=-1
).transpose(1, 2)

# Retrieve conv and recurrent states if there is a cache. They may be None if the layer is not initialized.
# Retrieve the recurrent state if there is a cache. It may be None if the layer is not initialized.
if cache is not None:
conv_state = cache.get_conv_state(self.layer_idx, state_idx=0)
recurrent_state = cache.get_recurrent_state(self.layer_idx, state_idx=0)
else:
conv_state, recurrent_state = None, None

if conv_state is not None and seq_len == 1:
mixed_qkv = causal_conv1d_update(
mixed_qkv,
conv_state,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
)
else:
if cache is not None:
mixed_qkv = cache.update_conv_state(mixed_qkv, self.layer_idx, conv_kernel_size=self.conv_kernel_size)
mixed_qkv = causal_conv1d_fn(
mixed_qkv,
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
**kwargs,
)
if cache is not None:
mixed_qkv = mixed_qkv[:, :, -seq_len:]
recurrent_state = None

mixed_qkv = causal_conv1d_forward(
self.conv1d,
mixed_qkv,
cache,
self.layer_idx,
activation=self.activation,
**kwargs,
)

query, key, value = torch.split(mixed_qkv.transpose(1, 2), [self.qkv_dim] * 3, dim=-1)
query, key, value = [states.view(hidden_shape) for states in (query, key, value)]
Expand Down
Loading
Loading