Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
4 changes: 4 additions & 0 deletions docs/source/en/model_doc/bailing_hybrid.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ The native Transformers architecture is exposed as `BailingHybridForCausalLM` an

Ling 3.1 Flash is distributed in block-wise FP8. Native FP8 execution requires a compatible `kernels` installation.

The checkpoint's `expert_swiglu_limit_list` and `share_expert_swiglu_limit_list` control per-layer clipping in routed
and shared experts. Positive limits clip the gate after SiLU and bound the up projection symmetrically; zero or
omitted limits disable clipping.

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

Expand Down
7 changes: 7 additions & 0 deletions src/transformers/integrations/finegrained_fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,7 @@ def fp8_grouped_mm_experts_forward(


class FP8Experts(nn.Module):
_fp8_experts_clamp_after_activation = False
Comment thread
icavan marked this conversation as resolved.
Resolved
# Internal: set True by `_disable_deepgemm_on_multi_device` when the model spans >1 CUDA device.
_deepgemm_disabled = False

Expand Down Expand Up @@ -802,6 +803,8 @@ def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
up = up.clamp(min=-self.swiglu_limit, max=self.swiglu_limit)
glu = gate * torch.sigmoid(gate * self.swiglu_alpha)
return (up + 1.0) * glu
elif self._fp8_experts_clamp_after_activation:
return self.act_fn(gate).clamp(max=self.limit) * up.clamp(min=-self.limit, max=self.limit)
elif self.limit is not None:
gate = gate.clamp(max=self.limit)
up = up.clamp(min=-self.limit, max=self.limit)
Expand Down Expand Up @@ -978,6 +981,10 @@ def replace_with_fp8_linear(
has_gate=has_gate,
expert_dtype=quantization_config.expert_dtype,
)
# Preserve layer-specific post-activation clipping when replacing the expert module.
if getattr(module, "_fp8_experts_clamp_after_activation", False):
new_module._fp8_experts_clamp_after_activation = True
new_module.limit = module.limit
Comment thread
icavan marked this conversation as resolved.
Resolved
elif type(module) is nn.Linear:
# Vanilla `nn.Linear` → standard FP8Linear swap.
new_module = FP8Linear(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ class BailingHybridConfig(PreTrainedConfig):
Lower bound of the KDA forget gate in log space.
mlp_layer_types (`list[str]`, *optional*):
Per-layer MLP types. Derived from `first_k_dense_replace` when omitted.
expert_swiglu_limit_list (`list[float]`, *optional*):
Per-layer SwiGLU clipping limits for routed experts. Zero disables clipping.
share_expert_swiglu_limit_list (`list[float]`, *optional*):
Per-layer SwiGLU clipping limits for shared experts. Zero disables clipping.
mtp_loss_scaling_factor (`float`, *optional*, defaults to 0.0):
Scaling factor used for the auxiliary multi-token-prediction loss during pretraining.
"""
Expand Down Expand Up @@ -134,10 +138,16 @@ class BailingHybridConfig(PreTrainedConfig):
kda_lower_bound: float = -5.0
layer_types: list[str] | None = None
mlp_layer_types: list[str] | None = None
expert_swiglu_limit_list: list[float | int] | None = None
share_expert_swiglu_limit_list: list[float | int] | None = None

mtp_loss_scaling_factor: float | int = 0.0

def __post_init__(self, **kwargs):
for name in ("expert_swiglu_limit_list", "share_expert_swiglu_limit_list"):
limits = getattr(self, name)
if limits is not None and len(limits) != self.num_hidden_layers:
raise ValueError(f"`{name}` must contain one limit per decoder layer.")
self.linear_head_dim = self.head_dim
self.linear_num_heads = self.num_attention_heads
self.linear_conv_kernel_dim = self.short_conv_kernel_size
Expand Down
68 changes: 38 additions & 30 deletions src/transformers/models/bailing_hybrid/modeling_bailing_hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,9 @@
from ...activations import ACT2FN
from ...cache_utils import Cache, DynamicCache
from ...generation import GenerationMixin
from ...integrations import (
use_experts_implementation,
use_kernel_forward_from_hub,
use_kernel_func_from_hub_with_fallback,
use_kernelized_func,
)
from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub_with_fallback, use_kernelized_func
from ...integrations.accelerate import force_accelerate_hooks
from ...integrations.moe import use_experts_implementation
from ...masking_utils import create_causal_mask, create_recurrent_attention_mask
from ...modeling_flash_attention_utils import FlashAttentionKwargs
from ...modeling_layers import GradientCheckpointingLayer
Expand Down Expand Up @@ -146,40 +142,40 @@ def forward(self, x, position_ids):
class BailingHybridExperts(nn.Module):
"""Collection of expert weights stored as 3D tensors."""

def __init__(self, config):
_fp8_experts_clamp_after_activation = True

def __init__(self, config, swiglu_limit=None):
super().__init__()
self.num_experts = config.num_local_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.moe_intermediate_size
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
self.act_fn = ACT2FN[config.hidden_act]
self.limit = float("inf") if swiglu_limit is None else swiglu_limit

def forward(
self,
hidden_states: torch.Tensor,
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
) -> torch.Tensor:
final_hidden_states = torch.zeros_like(hidden_states)
final = torch.zeros_like(hidden_states)
with torch.no_grad():
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts + 1)
expert_mask = expert_mask.permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()

for expert_idx in expert_hit:
mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0)
hit = torch.greater(mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx in hit:
expert_idx = expert_idx[0]
if expert_idx == self.num_experts:
continue
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
current_state = hidden_states[token_idx]
gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
current_hidden_states = self.act_fn(gate) * up
current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
top_k_pos, token_idx = torch.where(mask[expert_idx])
current = self._apply_gate(F.linear(hidden_states[token_idx], self.gate_up_proj[expert_idx]))
current = F.linear(current, self.down_proj[expert_idx]) * top_k_weights[token_idx, top_k_pos, None]
final.index_add_(0, token_idx, current.to(final.dtype))
return final

return final_hidden_states
def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
gate, up = gate_up.chunk(2, dim=-1)
gate = self.act_fn(gate).clamp(max=self.limit)
up = up.clamp(min=-self.limit, max=self.limit)
return gate * up


class BailingHybridMLP(nn.Module):
Expand All @@ -192,10 +188,12 @@ def __init__(self, config, intermediate_size=None):
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
self.limit = float("inf")

def forward(self, x):
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
gate = self.act_fn(self.gate_proj(x)).clamp(max=self.limit)
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
return self.down_proj(gate * up)


def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
Expand Down Expand Up @@ -831,14 +829,18 @@ class BailingHybridMoE(nn.Module):
A mixed expert module containing shared experts.
"""

def __init__(self, config: BailingHybridConfig):
def __init__(self, config: BailingHybridConfig, layer_idx: int):
super().__init__()
self.config = config
self.experts = BailingHybridExperts(config)
self.gate = BailingHybridTopkRouter(config)
self.shared_experts = BailingHybridMLP(
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
)
if config.expert_swiglu_limit_list is not None:
self.experts.limit = config.expert_swiglu_limit_list[layer_idx] or float("inf")
if config.share_expert_swiglu_limit_list is not None:
self.shared_experts.limit = config.share_expert_swiglu_limit_list[layer_idx] or float("inf")

def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
residuals = hidden_states
Expand All @@ -860,9 +862,10 @@ def __init__(self, config: BailingHybridConfig, layer_idx: int):
if config.layer_types[layer_idx] == "full_attention"
else BailingHybridDeltaAttention(config, layer_idx)
)

self.mlp = (
BailingHybridMoE(config) if config.mlp_layer_types[layer_idx] == "sparse" else BailingHybridMLP(config)
BailingHybridMoE(config, layer_idx)
if config.mlp_layer_types[layer_idx] == "sparse"
else BailingHybridMLP(config)
)

self.input_layernorm = BailingHybridRMSNorm(config.hidden_size, config.rms_norm_eps)
Expand Down Expand Up @@ -947,6 +950,11 @@ def _init_weights(self, module):
elif isinstance(module, BailingHybridRMSNormGated):
init.ones_(module.weight)

def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
if requested_experts == "sonicmoe" and any(self.config.expert_swiglu_limit_list or []):
raise ValueError("SonicMoE does not support Ling's post-activation SwiGLU clipping.")
return super().get_correct_experts_implementation(requested_experts)
Comment thread
icavan marked this conversation as resolved.
Resolved


@auto_docstring
class BailingHybridModel(BailingHybridPreTrainedModel):
Expand Down
45 changes: 40 additions & 5 deletions src/transformers/models/bailing_hybrid/modular_bailing_hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
from ...cache_utils import Cache
from ...generation import GenerationMixin
from ...integrations.accelerate import force_accelerate_hooks
from ...integrations.moe import use_experts_implementation
from ...modeling_flash_attention_utils import FlashAttentionKwargs
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from ...models.deepseek_v3.configuration_deepseek_v3 import DeepseekV3Config
from ...models.deepseek_v3.modeling_deepseek_v3 import (
DeepseekV3Attention,
DeepseekV3Experts,
DeepseekV3ForCausalLM,
DeepseekV3MLP,
DeepseekV3MoE,
Expand All @@ -53,6 +53,7 @@
Qwen3NextPreTrainedModel,
apply_mask_to_padding_states,
)
from ...models.step3p7.modeling_step3p7 import Step3p7Experts
from ...processing_utils import Unpack
from ...utils import TransformersKwargs, auto_docstring
from ...utils.deprecation import deprecate_kwarg
Expand Down Expand Up @@ -85,6 +86,10 @@ class BailingHybridConfig(DeepseekV3Config):
Lower bound of the KDA forget gate in log space.
mlp_layer_types (`list[str]`, *optional*):
Per-layer MLP types. Derived from `first_k_dense_replace` when omitted.
expert_swiglu_limit_list (`list[float]`, *optional*):
Per-layer SwiGLU clipping limits for routed experts. Zero disables clipping.
share_expert_swiglu_limit_list (`list[float]`, *optional*):
Per-layer SwiGLU clipping limits for shared experts. Zero disables clipping.
mtp_loss_scaling_factor (`float`, *optional*, defaults to 0.0):
Scaling factor used for the auxiliary multi-token-prediction loss during pretraining.
"""
Expand Down Expand Up @@ -164,6 +169,8 @@ class BailingHybridConfig(DeepseekV3Config):
kda_lower_bound: float = -5.0
layer_types: list[str] | None = None
mlp_layer_types: list[str] | None = None
expert_swiglu_limit_list: list[float | int] | None = None
share_expert_swiglu_limit_list: list[float | int] | None = None
Comment thread
icavan marked this conversation as resolved.
Resolved

mtp_loss_scaling_factor: float | int = 0.0

Expand All @@ -172,6 +179,10 @@ class BailingHybridConfig(DeepseekV3Config):
rope_interleave = AttributeError()

def __post_init__(self, **kwargs):
for name in ("expert_swiglu_limit_list", "share_expert_swiglu_limit_list"):
limits = getattr(self, name)
if limits is not None and len(limits) != self.num_hidden_layers:
raise ValueError(f"`{name}` must contain one limit per decoder layer.")
self.linear_head_dim = self.head_dim
self.linear_num_heads = self.num_attention_heads
self.linear_conv_kernel_dim = self.short_conv_kernel_size
Expand Down Expand Up @@ -204,12 +215,20 @@ class BailingHybridRotaryEmbedding(DeepseekV3RotaryEmbedding):
pass


class BailingHybridExperts(DeepseekV3Experts):
@use_experts_implementation
Comment thread
icavan marked this conversation as resolved.
Resolved
class BailingHybridExperts(Step3p7Experts):
pass


class BailingHybridMLP(DeepseekV3MLP):
Comment thread
icavan marked this conversation as resolved.
Resolved
pass
def __init__(self, config, intermediate_size=None):
super().__init__(config, intermediate_size)
self.limit = float("inf")
Comment thread
icavan marked this conversation as resolved.
Resolved

def forward(self, x):
gate = self.act_fn(self.gate_proj(x)).clamp(max=self.limit)
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
return self.down_proj(gate * up)


class BailingHybridAttention(DeepseekV3Attention):
Expand Down Expand Up @@ -398,11 +417,22 @@ class BailingHybridTopkRouter(DeepseekV3TopkRouter):


class BailingHybridMoE(DeepseekV3MoE):
pass
def __init__(self, config: BailingHybridConfig, layer_idx: int):
super().__init__(config)
if config.expert_swiglu_limit_list is not None:
self.experts.limit = config.expert_swiglu_limit_list[layer_idx] or float("inf")
if config.share_expert_swiglu_limit_list is not None:
self.shared_experts.limit = config.share_expert_swiglu_limit_list[layer_idx] or float("inf")
Comment thread
icavan marked this conversation as resolved.
Resolved


class BailingHybridDecoderLayer(KimiLinearDecoderLayer):
pass
def __init__(self, config: BailingHybridConfig, layer_idx: int):
Comment thread
icavan marked this conversation as resolved.
Resolved
super().__init__(config, layer_idx)
self.mlp = (
BailingHybridMoE(config, layer_idx)
if config.mlp_layer_types[layer_idx] == "sparse"
else BailingHybridMLP(config)
)


@auto_docstring
Expand Down Expand Up @@ -437,6 +467,11 @@ def _init_weights(self, module):
elif isinstance(module, BailingHybridRMSNormGated):
init.ones_(module.weight)

def get_correct_experts_implementation(self, requested_experts: str | None) -> str:
if requested_experts == "sonicmoe" and any(self.config.expert_swiglu_limit_list or []):
raise ValueError("SonicMoE does not support Ling's post-activation SwiGLU clipping.")
return PreTrainedModel.get_correct_experts_implementation(self, requested_experts)


@auto_docstring
class BailingHybridModel(Qwen3NextModel):
Expand Down
35 changes: 35 additions & 0 deletions tests/kernels/test_finegrained_fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import contextlib
import unittest
from types import SimpleNamespace
from unittest import mock

import torch
Expand All @@ -48,6 +49,40 @@ def _add_one(x, *args, **kwargs):
return x + 1


@require_torch
class FinegrainedFp8GatingTest(unittest.TestCase):
Comment thread
icavan marked this conversation as resolved.
Resolved
def test_clipping_order_and_existing_gates(self):
gate_up = torch.tensor([[2.0, -2.0, 3.0, -3.0]], device=torch_device)
gate, up = gate_up.chunk(2, dim=-1)
for limit, after_activation, alpha in (
(None, False, None),
(1.5, False, None),
(1.5, True, None),
(1.5, False, 1.7),
):
with self.subTest(limit=limit, after_activation=after_activation, alpha=alpha):
config = SimpleNamespace(
hidden_size=4,
num_local_experts=2,
moe_intermediate_size=2,
hidden_act="silu",
swiglu_limit=limit,
swiglu_alpha=alpha,
)
experts = fg.FP8Experts(config)
experts._fp8_experts_clamp_after_activation = after_activation
if alpha is not None:
clipped_gate = gate.clamp(max=limit)
expected = clipped_gate * torch.sigmoid(alpha * clipped_gate) * (up.clamp(-limit, limit) + 1)
elif after_activation:
expected = torch.nn.functional.silu(gate).clamp(max=limit) * up.clamp(-limit, limit)
elif limit is not None:
expected = torch.nn.functional.silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)
else:
expected = torch.nn.functional.silu(gate) * up
torch.testing.assert_close(experts._apply_gate(gate_up), expected, rtol=0, atol=0)


# ── Fake kernels (a "good" one exposing every symbol the loader resolves, plus a variant missing one) ──


Expand Down
Loading
Loading