Skip to content
Open
Show file tree
Hide file tree
Changes from 9 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
22 changes: 19 additions & 3 deletions src/transformers/integrations/finegrained_fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,7 @@ def __init__(
has_bias: bool = False,
has_gate: bool = True,
expert_dtype: str = "fp8",
layer_idx: int | None = None,
Comment thread
icavan marked this conversation as resolved.
Resolved
):
super().__init__()

Expand All @@ -741,7 +742,16 @@ def __init__(
self.swiglu_alpha = getattr(config, "swiglu_alpha", None)
self.swiglu_limit = getattr(config, "swiglu_limit", None)
self.act_fn = ACT2FN[_first_attr(config, "hidden_activation", "hidden_act")]
self.limit = getattr(config, "swiglu_limit", None)
Comment thread
icavan marked this conversation as resolved.
Resolved
# swiglu_limit is a scalar shared across layers; swiglu_limits is a per-layer list.
# Post-activation clipping prefers the list, falling back to the scalar if absent.
# Zero/None disables clipping in this path; other gate formulas keep their scalar semantics.
self.limit_after_act = getattr(config, "limit_after_act", False)
self.limit = None
if self.limit_after_act:
limits = getattr(config, "swiglu_limits", None)
if limits is not None and layer_idx is None:
raise ValueError("Per-layer SwiGLU limits require a layer index.")
self.limit = (limits[layer_idx] if limits is not None else self.swiglu_limit) or float("inf")
Comment thread
icavan marked this conversation as resolved.
Resolved
self.gate_softcap = getattr(config, "mlp_gate_softcap", None)
self.up_softcap = getattr(config, "mlp_up_softcap", None)

Expand Down Expand Up @@ -802,9 +812,13 @@ 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 is not None:
gate = gate.clamp(max=self.limit)
elif self.limit_after_act:
gate = self.act_fn(gate).clamp(max=self.limit)
up = up.clamp(min=-self.limit, max=self.limit)
return gate * up
elif self.swiglu_limit is not None:
gate = gate.clamp(max=self.swiglu_limit)
up = up.clamp(min=-self.swiglu_limit, max=self.swiglu_limit)
return self.act_fn(gate) * up

def forward(
Expand Down Expand Up @@ -962,6 +976,7 @@ def replace_with_fp8_linear(
if module_name.endswith(".experts"):
has_gate = getattr(module, "has_gate", True)
has_bias = getattr(module, "has_bias", False)
layer_idx = getattr(module, "layer_idx", None)
config = getattr(module, "config", model.config.get_text_config())
new_class = use_experts_implementation(
experts_class=FP8Experts,
Expand All @@ -977,6 +992,7 @@ def replace_with_fp8_linear(
has_bias=has_bias,
has_gate=has_gate,
expert_dtype=quantization_config.expert_dtype,
layer_idx=layer_idx,
)
elif type(module) is nn.Linear:
# Vanilla `nn.Linear` → standard FP8Linear swap.
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) and (limit > 0 or not getattr(self, "limit_after_act", False)):
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",
"swiglu_limits": "expert_swiglu_limit_list",
"swiglu_limits_shared": "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,17 @@ def __post_init__(self, **kwargs):
self.head_dim = self.qk_rope_head_dim
super().__post_init__(**kwargs)

for name in ("swiglu_limits", "swiglu_limits_shared"):
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.")

@property
def limit_after_act(self) -> bool:
"""Clipping order is fixed by the architecture and is not serialized."""
return True


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

def __init__(self, config):
def __init__(self, config, layer_idx):
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 = (config.swiglu_limits[layer_idx] if config.swiglu_limits else None) or float("inf")
self.config = config
self.layer_idx = layer_idx
self.limit_after_act = config.limit_after_act

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):
def __init__(self, config, intermediate_size=None):
"""Ling's shared experts use the same post-activation clipping as Step3p7."""

def __init__(self, config, intermediate_size=None, layer_idx=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
Expand All @@ -192,10 +191,15 @@ 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]
# Zero or a missing per-layer limit disables clipping.
self.limit = (
config.swiglu_limits_shared[layer_idx] if layer_idx is not None and config.swiglu_limits_shared else None
) or 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
def forward(self, x) -> torch.Tensor:
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,13 +835,13 @@ 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.experts = BailingHybridExperts(config, layer_idx)
self.gate = BailingHybridTopkRouter(config)
self.shared_experts = BailingHybridMLP(
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts, layer_idx=layer_idx
)

def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
Expand All @@ -860,9 +864,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
53 changes: 46 additions & 7 deletions src/transformers/models/bailing_hybrid/modular_bailing_hybrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@
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,
DeepseekV3RotaryEmbedding,
DeepseekV3TopkRouter,
Expand All @@ -53,6 +52,7 @@
Qwen3NextPreTrainedModel,
apply_mask_to_padding_states,
)
from ...models.step3p7.modeling_step3p7 import Step3p7Experts, Step3p7MLP
from ...processing_utils import Unpack
from ...utils import TransformersKwargs, auto_docstring
from ...utils.deprecation import deprecate_kwarg
Expand Down Expand Up @@ -85,6 +85,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 +124,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",
"swiglu_limits": "expert_swiglu_limit_list",
"swiglu_limits_shared": "share_expert_swiglu_limit_list",
}

vocab_size: int = 157184
Expand Down Expand Up @@ -164,13 +170,20 @@ 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

# Ling checkpoints use `num_experts`; the DeepSeek compatibility name is not part of this architecture.
n_routed_experts = AttributeError()
rope_interleave = AttributeError()

@property
def limit_after_act(self) -> bool:
"""Clipping order is fixed by the architecture and is not serialized."""
return True

def __post_init__(self, **kwargs):
self.linear_head_dim = self.head_dim
self.linear_num_heads = self.num_attention_heads
Expand All @@ -191,6 +204,13 @@ def __post_init__(self, **kwargs):

super().__post_init__(**kwargs)

for name in ("swiglu_limits", "swiglu_limits_shared"):
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 +224,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):
pass
class BailingHybridMLP(Step3p7MLP):
"""Ling's shared experts use the same post-activation clipping as Step3p7."""

def __init__(self, config, intermediate_size=None, layer_idx=None):
super().__init__(config, layer_idx)
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
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)


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


class BailingHybridMoE(DeepseekV3MoE):
pass
def __init__(self, config: BailingHybridConfig, layer_idx: int):
super().__init__(config)
self.experts = BailingHybridExperts(config, layer_idx)
self.shared_experts = BailingHybridMLP(
config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts, layer_idx=layer_idx
)


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
Loading
Loading