Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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):
limit_after_act = 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.limit_after_act:
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, "limit_after_act", False):
new_module.limit_after_act = 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
4 changes: 4 additions & 0 deletions src/transformers/integrations/sonicmoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from __future__ import annotations

import importlib.metadata
import math
from collections.abc import Callable
from dataclasses import dataclass

Expand Down Expand Up @@ -169,6 +170,9 @@ def sonicmoe_experts_forward(
raise ValueError("sonicmoe requires gated experts (has_gate=True)")
if self.has_post_expert_norm:
raise ValueError("The `sonicmoe` experts implementation does not support experts with a post-expert norm.")
limit = getattr(self, "limit", None)
if limit is not None and math.isfinite(limit):
raise ValueError("The `sonicmoe` experts implementation does not support expert clipping.")

device = hidden_states.device
num_top_k = top_k_index.size(-1)
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 @@ -87,6 +91,8 @@ class BailingHybridConfig(PreTrainedConfig):
"num_experts_per_tok": "num_experts_per_token",
"n_shared_experts": "num_shared_experts",
"num_mtp_layers": "num_nextn_predict_layers",
"experts_swiglu_limits": "expert_swiglu_limit_list",
"shared_experts_swiglu_limits": "share_expert_swiglu_limit_list",
}

vocab_size: int = 157184
Expand Down Expand Up @@ -134,6 +140,8 @@ 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

Expand Down Expand Up @@ -161,5 +169,12 @@ def __post_init__(self, **kwargs):
self.head_dim = self.qk_rope_head_dim
super().__post_init__(**kwargs)

for name in ("experts_swiglu_limits", "shared_experts_swiglu_limits"):
limits = getattr(self, name)
if limits is None:
setattr(self, name, [0] * self.num_hidden_layers)
elif len(limits) != self.num_hidden_layers:
raise ValueError(f"`{name}` must contain one limit per decoder layer.")


__all__ = ["BailingHybridConfig"]
64 changes: 34 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,41 @@ def forward(self, x, position_ids):
class BailingHybridExperts(nn.Module):
"""Collection of expert weights stored as 3D tensors."""

def __init__(self, config):
# Declare the clipping order for replacement expert implementations.
limit_after_act = 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 +189,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 +830,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
)
expert_limit = config.experts_swiglu_limits[layer_idx]
shared_limit = config.shared_experts_swiglu_limits[layer_idx]
self.experts.limit = expert_limit if expert_limit > 0 else float("inf")
self.shared_experts.limit = shared_limit if shared_limit > 0 else float("inf")

def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
residuals = hidden_states
Expand All @@ -860,9 +863,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
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 @@ -120,6 +125,8 @@ class BailingHybridConfig(DeepseekV3Config):
"num_experts_per_tok": "num_experts_per_token",
"n_shared_experts": "num_shared_experts",
"num_mtp_layers": "num_nextn_predict_layers",
"experts_swiglu_limits": "expert_swiglu_limit_list",
"shared_experts_swiglu_limits": "share_expert_swiglu_limit_list",
}

vocab_size: int = 157184
Expand Down Expand Up @@ -164,6 +171,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 Down Expand Up @@ -191,6 +200,13 @@ def __post_init__(self, **kwargs):

super().__post_init__(**kwargs)

for name in ("experts_swiglu_limits", "shared_experts_swiglu_limits"):
limits = getattr(self, name)
if limits is None:
setattr(self, name, [0] * self.num_hidden_layers)
elif len(limits) != self.num_hidden_layers:
raise ValueError(f"`{name}` must contain one limit per decoder layer.")


class BailingHybridRMSNorm(LlamaRMSNorm):
pass
Expand All @@ -204,12 +220,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 +422,22 @@ class BailingHybridTopkRouter(DeepseekV3TopkRouter):


class BailingHybridMoE(DeepseekV3MoE):
pass
def __init__(self, config: BailingHybridConfig, layer_idx: int):
super().__init__(config)
expert_limit = config.experts_swiglu_limits[layer_idx]
shared_limit = config.shared_experts_swiglu_limits[layer_idx]
self.experts.limit = expert_limit if expert_limit > 0 else float("inf")
self.shared_experts.limit = shared_limit if shared_limit > 0 else 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
3 changes: 2 additions & 1 deletion src/transformers/models/step3p7/modeling_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,8 @@ def forward(self, x) -> torch.Tensor:
class Step3p7Experts(nn.Module):
"""Collection of expert weights stored as 3D tensors."""

_fp8_experts_clamp_after_activation = True
# Declare the clipping order for replacement expert implementations.
limit_after_act = True

def __init__(self, config, swiglu_limit=None):
super().__init__()
Expand Down
3 changes: 2 additions & 1 deletion src/transformers/models/step3p7/modular_step3p7.py
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,8 @@ def forward(self, x):

@no_inherit_decorator
class Step3p7Experts(DeepseekV4Experts):
_fp8_experts_clamp_after_activation = True
# Declare the clipping order for replacement expert implementations.
limit_after_act = True
Comment thread
icavan marked this conversation as resolved.
Resolved

def __init__(self, config, swiglu_limit=None):
super().__init__(config)
Expand Down
Loading
Loading