Skip to content

vllm.model_executor.models.bailing_moe

Inference-only BailingMoE model compatible with HuggingFace weights.

BailingAttention

Bases: Module

Source code in vllm/model_executor/models/bailing_moe.py
class BailingAttention(nn.Module):

    def __init__(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
        reduce_results: bool = True,
        prefix: str = "",
    ):
        super().__init__()
        self.hidden_size = config.hidden_size
        self.total_num_heads = config.num_attention_heads
        self.total_kv_heads = config.num_key_value_heads
        tp_size = get_tensor_model_parallel_world_size()

        assert self.total_num_heads % tp_size == 0
        assert self.total_kv_heads % tp_size == 0
        assert self.total_num_heads >= self.total_kv_heads

        self.num_heads = self.total_num_heads // tp_size
        self.head_dim = config.head_dim or (self.hidden_size //
                                            self.total_num_heads)
        self.q_size_per_rank = self.head_dim * self.num_heads
        self.num_kv_heads = self.total_kv_heads // tp_size
        self.kv_size_per_rank = self.num_kv_heads * self.head_dim
        self.scale = self.head_dim**-0.5
        self.use_qk_norm = getattr(config, "use_qk_norm", False)
        self.use_rmsnorm = getattr(config, "use_rmsnorm", False)

        self.query_key_value = QKVParallelLinear(
            self.hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_kv_heads,
            bias=(config.use_bias or config.use_qkv_bias),
            quant_config=quant_config,
            prefix=f"{prefix}.query_key_value",
        )

        if self.use_qk_norm:
            self.query_layernorm = (RMSNorm(
                self.head_dim, eps=config.rms_norm_eps) if self.use_rmsnorm
                                    else nn.LayerNorm(self.head_dim, eps=1e-6))
            self.key_layernorm = (RMSNorm(
                self.head_dim, eps=config.rms_norm_eps) if self.use_rmsnorm
                                  else nn.LayerNorm(self.head_dim, eps=1e-6))

        self.dense = RowParallelLinear(
            self.total_num_heads * self.head_dim,
            self.hidden_size,
            bias=config.use_bias,
            quant_config=quant_config,
            reduce_results=reduce_results,
            prefix=f"{prefix}.dense",
        )

        self.partial_rotary_factor = getattr(config, "partial_rotary_factor",
                                             1.0)

        self.rotary_dim = getattr(config, "rotary_dim", self.head_dim)

        self.rotary_emb = get_rope(
            self.head_dim,
            rotary_dim=self.rotary_dim,
            max_position=config.max_position_embeddings,
            base=config.rope_theta,
            is_neox_style=True,
            rope_scaling=config.rope_scaling,
            partial_rotary_factor=self.partial_rotary_factor,
        )

        self.attn = Attention(
            self.num_heads,
            self.head_dim,
            self.scale,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            prefix=f"{prefix}.attn",
        )

    def forward(
        self,
        hidden_states: torch.Tensor,
        position_ids: torch.Tensor,
    ) -> torch.Tensor:

        qkv, _ = self.query_key_value(hidden_states)
        q, k, v = qkv.split([
            self.q_size_per_rank, self.kv_size_per_rank, self.kv_size_per_rank
        ],
                            dim=-1)

        if self.use_qk_norm:
            q = q.view(-1, self.num_heads, self.head_dim)
            k = k.view(-1, self.num_kv_heads, self.head_dim)
            q = self.query_layernorm(q)
            k = self.key_layernorm(k)
            q = q.view(-1, self.q_size_per_rank)
            k = k.view(-1, self.kv_size_per_rank)

        q, k = self.rotary_emb(position_ids, q, k)

        context_layer = self.attn(q, k, v)

        attn_output, _ = self.dense(context_layer)
        return attn_output

attn instance-attribute

attn = Attention(
    num_heads,
    head_dim,
    scale,
    num_kv_heads=num_kv_heads,
    cache_config=cache_config,
    prefix=f"{prefix}.attn",
)

dense instance-attribute

dense = RowParallelLinear(
    total_num_heads * head_dim,
    hidden_size,
    bias=use_bias,
    quant_config=quant_config,
    reduce_results=reduce_results,
    prefix=f"{prefix}.dense",
)

head_dim instance-attribute

head_dim = head_dim or hidden_size // total_num_heads

hidden_size instance-attribute

hidden_size = hidden_size

key_layernorm instance-attribute

key_layernorm = (
    RMSNorm(head_dim, eps=rms_norm_eps)
    if use_rmsnorm
    else LayerNorm(head_dim, eps=1e-06)
)

kv_size_per_rank instance-attribute

kv_size_per_rank = num_kv_heads * head_dim

num_heads instance-attribute

num_heads = total_num_heads // tp_size

num_kv_heads instance-attribute

num_kv_heads = total_kv_heads // tp_size

partial_rotary_factor instance-attribute

partial_rotary_factor = getattr(
    config, "partial_rotary_factor", 1.0
)

q_size_per_rank instance-attribute

q_size_per_rank = head_dim * num_heads

query_key_value instance-attribute

query_key_value = QKVParallelLinear(
    hidden_size,
    head_dim,
    total_num_heads,
    total_kv_heads,
    bias=use_bias or use_qkv_bias,
    quant_config=quant_config,
    prefix=f"{prefix}.query_key_value",
)

query_layernorm instance-attribute

query_layernorm = (
    RMSNorm(head_dim, eps=rms_norm_eps)
    if use_rmsnorm
    else LayerNorm(head_dim, eps=1e-06)
)

rotary_dim instance-attribute

rotary_dim = getattr(config, 'rotary_dim', head_dim)

rotary_emb instance-attribute

rotary_emb = get_rope(
    head_dim,
    rotary_dim=rotary_dim,
    max_position=max_position_embeddings,
    base=rope_theta,
    is_neox_style=True,
    rope_scaling=rope_scaling,
    partial_rotary_factor=partial_rotary_factor,
)

scale instance-attribute

scale = head_dim ** -0.5

total_kv_heads instance-attribute

total_kv_heads = num_key_value_heads

total_num_heads instance-attribute

total_num_heads = num_attention_heads

use_qk_norm instance-attribute

use_qk_norm = getattr(config, 'use_qk_norm', False)

use_rmsnorm instance-attribute

use_rmsnorm = getattr(config, 'use_rmsnorm', False)

__init__

__init__(
    config: PretrainedConfig,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: bool = True,
    prefix: str = "",
)
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    config: PretrainedConfig,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: bool = True,
    prefix: str = "",
):
    super().__init__()
    self.hidden_size = config.hidden_size
    self.total_num_heads = config.num_attention_heads
    self.total_kv_heads = config.num_key_value_heads
    tp_size = get_tensor_model_parallel_world_size()

    assert self.total_num_heads % tp_size == 0
    assert self.total_kv_heads % tp_size == 0
    assert self.total_num_heads >= self.total_kv_heads

    self.num_heads = self.total_num_heads // tp_size
    self.head_dim = config.head_dim or (self.hidden_size //
                                        self.total_num_heads)
    self.q_size_per_rank = self.head_dim * self.num_heads
    self.num_kv_heads = self.total_kv_heads // tp_size
    self.kv_size_per_rank = self.num_kv_heads * self.head_dim
    self.scale = self.head_dim**-0.5
    self.use_qk_norm = getattr(config, "use_qk_norm", False)
    self.use_rmsnorm = getattr(config, "use_rmsnorm", False)

    self.query_key_value = QKVParallelLinear(
        self.hidden_size,
        self.head_dim,
        self.total_num_heads,
        self.total_kv_heads,
        bias=(config.use_bias or config.use_qkv_bias),
        quant_config=quant_config,
        prefix=f"{prefix}.query_key_value",
    )

    if self.use_qk_norm:
        self.query_layernorm = (RMSNorm(
            self.head_dim, eps=config.rms_norm_eps) if self.use_rmsnorm
                                else nn.LayerNorm(self.head_dim, eps=1e-6))
        self.key_layernorm = (RMSNorm(
            self.head_dim, eps=config.rms_norm_eps) if self.use_rmsnorm
                              else nn.LayerNorm(self.head_dim, eps=1e-6))

    self.dense = RowParallelLinear(
        self.total_num_heads * self.head_dim,
        self.hidden_size,
        bias=config.use_bias,
        quant_config=quant_config,
        reduce_results=reduce_results,
        prefix=f"{prefix}.dense",
    )

    self.partial_rotary_factor = getattr(config, "partial_rotary_factor",
                                         1.0)

    self.rotary_dim = getattr(config, "rotary_dim", self.head_dim)

    self.rotary_emb = get_rope(
        self.head_dim,
        rotary_dim=self.rotary_dim,
        max_position=config.max_position_embeddings,
        base=config.rope_theta,
        is_neox_style=True,
        rope_scaling=config.rope_scaling,
        partial_rotary_factor=self.partial_rotary_factor,
    )

    self.attn = Attention(
        self.num_heads,
        self.head_dim,
        self.scale,
        num_kv_heads=self.num_kv_heads,
        cache_config=cache_config,
        prefix=f"{prefix}.attn",
    )

forward

forward(
    hidden_states: Tensor, position_ids: Tensor
) -> Tensor
Source code in vllm/model_executor/models/bailing_moe.py
def forward(
    self,
    hidden_states: torch.Tensor,
    position_ids: torch.Tensor,
) -> torch.Tensor:

    qkv, _ = self.query_key_value(hidden_states)
    q, k, v = qkv.split([
        self.q_size_per_rank, self.kv_size_per_rank, self.kv_size_per_rank
    ],
                        dim=-1)

    if self.use_qk_norm:
        q = q.view(-1, self.num_heads, self.head_dim)
        k = k.view(-1, self.num_kv_heads, self.head_dim)
        q = self.query_layernorm(q)
        k = self.key_layernorm(k)
        q = q.view(-1, self.q_size_per_rank)
        k = k.view(-1, self.kv_size_per_rank)

    q, k = self.rotary_emb(position_ids, q, k)

    context_layer = self.attn(q, k, v)

    attn_output, _ = self.dense(context_layer)
    return attn_output

BailingMLP

Bases: Module

Source code in vllm/model_executor/models/bailing_moe.py
class BailingMLP(nn.Module):

    def __init__(
        self,
        intermediate_size: int,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig] = None,
        reduce_results: Optional[bool] = True,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.gate_up_proj = MergedColumnParallelLinear(
            config.hidden_size,
            [intermediate_size] * 2,
            bias=config.use_bias,
            quant_config=quant_config,
            prefix=f"{prefix}.gate_up_proj",
        )
        self.down_proj = RowParallelLinear(
            intermediate_size,
            config.hidden_size,
            bias=config.use_bias,
            quant_config=quant_config,
            reduce_results=reduce_results,
            prefix=f"{prefix}.down_proj",
        )
        self.act_fn = SiluAndMul()

    def forward(self, x):
        x, _ = self.gate_up_proj(x)
        x = self.act_fn(x)
        x, _ = self.down_proj(x)
        return x

act_fn instance-attribute

act_fn = SiluAndMul()

down_proj instance-attribute

down_proj = RowParallelLinear(
    intermediate_size,
    hidden_size,
    bias=use_bias,
    quant_config=quant_config,
    reduce_results=reduce_results,
    prefix=f"{prefix}.down_proj",
)

gate_up_proj instance-attribute

gate_up_proj = MergedColumnParallelLinear(
    hidden_size,
    [intermediate_size] * 2,
    bias=use_bias,
    quant_config=quant_config,
    prefix=f"{prefix}.gate_up_proj",
)

__init__

__init__(
    intermediate_size: int,
    config: PretrainedConfig,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: Optional[bool] = True,
    prefix: str = "",
) -> None
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    intermediate_size: int,
    config: PretrainedConfig,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: Optional[bool] = True,
    prefix: str = "",
) -> None:
    super().__init__()
    self.gate_up_proj = MergedColumnParallelLinear(
        config.hidden_size,
        [intermediate_size] * 2,
        bias=config.use_bias,
        quant_config=quant_config,
        prefix=f"{prefix}.gate_up_proj",
    )
    self.down_proj = RowParallelLinear(
        intermediate_size,
        config.hidden_size,
        bias=config.use_bias,
        quant_config=quant_config,
        reduce_results=reduce_results,
        prefix=f"{prefix}.down_proj",
    )
    self.act_fn = SiluAndMul()

forward

forward(x)
Source code in vllm/model_executor/models/bailing_moe.py
def forward(self, x):
    x, _ = self.gate_up_proj(x)
    x = self.act_fn(x)
    x, _ = self.down_proj(x)
    return x

BailingMoE

Bases: Module

Source code in vllm/model_executor/models/bailing_moe.py
class BailingMoE(nn.Module):

    def __init__(
        self,
        intermediate_size: int,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig] = None,
        reduce_results: Optional[bool] = True,
        prefix: str = "",
    ):
        super().__init__()

        self.tp_size = get_tensor_model_parallel_world_size()
        self.tp_rank = get_tensor_model_parallel_rank()
        self.num_experts = config.num_experts
        self.top_k = config.num_experts_per_tok
        self.norm_expert_prob = config.norm_topk_prob
        self.hidden_size = config.hidden_size
        self.quant_config = quant_config
        self.num_shared_experts = config.num_shared_experts
        self.score_function = getattr(config, "score_function", None)
        self.n_group = getattr(config, "n_group", None)
        self.topk_group = getattr(config, "topk_group", None)
        self.use_grouped_topk = (self.n_group is not None
                                 and self.topk_group is not None)
        self.routed_scaling_factor = getattr(config, "routed_scaling_factor",
                                             1.0)

        router_dtype = getattr(config, "router_dtype", None)
        if router_dtype is None:
            self.router_dtype = None
        elif router_dtype == "fp32":
            self.router_dtype = torch.float32
        else:
            self.router_dtype = torch.bfloat16

        self.gate = nn.Linear(
            self.hidden_size,
            self.num_experts,
            bias=False,
            dtype=self.router_dtype,
        )

        if getattr(config, "moe_router_enable_expert_bias", False):
            self.gate.expert_bias = nn.Parameter(
                torch.empty((config.num_experts, ), dtype=torch.float32))
        else:
            self.gate.expert_bias = None

        self.correction_bias = (self.gate.expert_bias.data
                                if self.gate.expert_bias is not None else None)

        if self.score_function is not None:
            assert (
                self.score_function == "softmax"
                and self.correction_bias is None
            ) or (
                self.score_function == "sigmoid"
                and self.correction_bias is not None
            ), "score_function and correction_bias should be in 2 combination (softmax, None) or (sigmoid, not None)"  # noqa: E501
        else:
            # default value for scoring_func
            self.score_function = "softmax"

        self.experts = FusedMoE(
            num_experts=self.num_experts,
            top_k=self.top_k,
            hidden_size=self.hidden_size,
            intermediate_size=config.moe_intermediate_size,
            reduce_results=False,
            renormalize=self.norm_expert_prob,
            quant_config=quant_config,
            prefix=f"{prefix}.experts",
            scoring_func=self.score_function,
            e_score_correction_bias=self.gate.expert_bias,
            num_expert_group=self.n_group,
            topk_group=self.topk_group,
            use_grouped_topk=self.use_grouped_topk,
        )

        if self.num_shared_experts > 0:
            if hasattr(config, "moe_shared_expert_intermediate_size"):
                intermediate_size = config.moe_shared_expert_intermediate_size
            else:
                intermediate_size = config.moe_intermediate_size
            intermediate_size *= config.num_shared_experts
            self.shared_experts = BailingMLP(
                intermediate_size=intermediate_size,
                config=config,
                quant_config=quant_config,
                reduce_results=False,
                prefix=f"{prefix}.shared_experts")
        else:
            self.shared_experts = None

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        num_tokens, hidden_size = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_size)
        if self.shared_experts:
            shared_output = self.shared_experts(hidden_states)
        # router_logits: (num_tokens, n_experts)
        router_logits = self.gate(hidden_states.to(self.router_dtype))
        router_logits = router_logits.to(hidden_states.dtype)

        final_hidden_states = self.experts(hidden_states=hidden_states,
                                           router_logits=router_logits)

        final_hidden_states *= self.routed_scaling_factor

        if self.shared_experts:
            final_hidden_states = final_hidden_states + shared_output

        if self.tp_size > 1:
            final_hidden_states = tensor_model_parallel_all_reduce(
                final_hidden_states)
        return final_hidden_states.view(num_tokens, hidden_size)

correction_bias instance-attribute

correction_bias = data if expert_bias is not None else None

experts instance-attribute

experts = FusedMoE(
    num_experts=num_experts,
    top_k=top_k,
    hidden_size=hidden_size,
    intermediate_size=moe_intermediate_size,
    reduce_results=False,
    renormalize=norm_expert_prob,
    quant_config=quant_config,
    prefix=f"{prefix}.experts",
    scoring_func=score_function,
    e_score_correction_bias=expert_bias,
    num_expert_group=n_group,
    topk_group=topk_group,
    use_grouped_topk=use_grouped_topk,
)

gate instance-attribute

gate = Linear(
    hidden_size, num_experts, bias=False, dtype=router_dtype
)

hidden_size instance-attribute

hidden_size = hidden_size

n_group instance-attribute

n_group = getattr(config, 'n_group', None)

norm_expert_prob instance-attribute

norm_expert_prob = norm_topk_prob

num_experts instance-attribute

num_experts = num_experts

num_shared_experts instance-attribute

num_shared_experts = num_shared_experts

quant_config instance-attribute

quant_config = quant_config

routed_scaling_factor instance-attribute

routed_scaling_factor = getattr(
    config, "routed_scaling_factor", 1.0
)

router_dtype instance-attribute

router_dtype = None

score_function instance-attribute

score_function = getattr(config, 'score_function', None)

shared_experts instance-attribute

shared_experts = BailingMLP(
    intermediate_size=intermediate_size,
    config=config,
    quant_config=quant_config,
    reduce_results=False,
    prefix=f"{prefix}.shared_experts",
)

top_k instance-attribute

top_k = num_experts_per_tok

topk_group instance-attribute

topk_group = getattr(config, 'topk_group', None)

tp_rank instance-attribute

tp_size instance-attribute

use_grouped_topk instance-attribute

use_grouped_topk = (
    n_group is not None and topk_group is not None
)

__init__

__init__(
    intermediate_size: int,
    config: PretrainedConfig,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: Optional[bool] = True,
    prefix: str = "",
)
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    intermediate_size: int,
    config: PretrainedConfig,
    quant_config: Optional[QuantizationConfig] = None,
    reduce_results: Optional[bool] = True,
    prefix: str = "",
):
    super().__init__()

    self.tp_size = get_tensor_model_parallel_world_size()
    self.tp_rank = get_tensor_model_parallel_rank()
    self.num_experts = config.num_experts
    self.top_k = config.num_experts_per_tok
    self.norm_expert_prob = config.norm_topk_prob
    self.hidden_size = config.hidden_size
    self.quant_config = quant_config
    self.num_shared_experts = config.num_shared_experts
    self.score_function = getattr(config, "score_function", None)
    self.n_group = getattr(config, "n_group", None)
    self.topk_group = getattr(config, "topk_group", None)
    self.use_grouped_topk = (self.n_group is not None
                             and self.topk_group is not None)
    self.routed_scaling_factor = getattr(config, "routed_scaling_factor",
                                         1.0)

    router_dtype = getattr(config, "router_dtype", None)
    if router_dtype is None:
        self.router_dtype = None
    elif router_dtype == "fp32":
        self.router_dtype = torch.float32
    else:
        self.router_dtype = torch.bfloat16

    self.gate = nn.Linear(
        self.hidden_size,
        self.num_experts,
        bias=False,
        dtype=self.router_dtype,
    )

    if getattr(config, "moe_router_enable_expert_bias", False):
        self.gate.expert_bias = nn.Parameter(
            torch.empty((config.num_experts, ), dtype=torch.float32))
    else:
        self.gate.expert_bias = None

    self.correction_bias = (self.gate.expert_bias.data
                            if self.gate.expert_bias is not None else None)

    if self.score_function is not None:
        assert (
            self.score_function == "softmax"
            and self.correction_bias is None
        ) or (
            self.score_function == "sigmoid"
            and self.correction_bias is not None
        ), "score_function and correction_bias should be in 2 combination (softmax, None) or (sigmoid, not None)"  # noqa: E501
    else:
        # default value for scoring_func
        self.score_function = "softmax"

    self.experts = FusedMoE(
        num_experts=self.num_experts,
        top_k=self.top_k,
        hidden_size=self.hidden_size,
        intermediate_size=config.moe_intermediate_size,
        reduce_results=False,
        renormalize=self.norm_expert_prob,
        quant_config=quant_config,
        prefix=f"{prefix}.experts",
        scoring_func=self.score_function,
        e_score_correction_bias=self.gate.expert_bias,
        num_expert_group=self.n_group,
        topk_group=self.topk_group,
        use_grouped_topk=self.use_grouped_topk,
    )

    if self.num_shared_experts > 0:
        if hasattr(config, "moe_shared_expert_intermediate_size"):
            intermediate_size = config.moe_shared_expert_intermediate_size
        else:
            intermediate_size = config.moe_intermediate_size
        intermediate_size *= config.num_shared_experts
        self.shared_experts = BailingMLP(
            intermediate_size=intermediate_size,
            config=config,
            quant_config=quant_config,
            reduce_results=False,
            prefix=f"{prefix}.shared_experts")
    else:
        self.shared_experts = None

forward

forward(hidden_states: Tensor) -> Tensor
Source code in vllm/model_executor/models/bailing_moe.py
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
    num_tokens, hidden_size = hidden_states.shape
    hidden_states = hidden_states.view(-1, hidden_size)
    if self.shared_experts:
        shared_output = self.shared_experts(hidden_states)
    # router_logits: (num_tokens, n_experts)
    router_logits = self.gate(hidden_states.to(self.router_dtype))
    router_logits = router_logits.to(hidden_states.dtype)

    final_hidden_states = self.experts(hidden_states=hidden_states,
                                       router_logits=router_logits)

    final_hidden_states *= self.routed_scaling_factor

    if self.shared_experts:
        final_hidden_states = final_hidden_states + shared_output

    if self.tp_size > 1:
        final_hidden_states = tensor_model_parallel_all_reduce(
            final_hidden_states)
    return final_hidden_states.view(num_tokens, hidden_size)

BailingMoeBlock

Bases: Module

Source code in vllm/model_executor/models/bailing_moe.py
class BailingMoeBlock(nn.Module):

    def __init__(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ):
        super().__init__()
        layer_idx = int(prefix.split('.')[-1])
        self.config = config
        hidden_size = config.hidden_size
        intermediate_size = config.intermediate_size

        self.input_layernorm = RMSNorm(hidden_size, eps=config.rms_norm_eps)
        self.attention = BailingAttention(config,
                                          cache_config,
                                          quant_config,
                                          prefix=f"{prefix}.attention")

        self.post_attention_layernorm = RMSNorm(hidden_size,
                                                eps=config.rms_norm_eps)

        # Choose MLP class based on the number of experts and layer index
        if layer_idx < config.first_k_dense_replace:
            mlp_class = BailingMLP
        else:
            mlp_class = BailingMoE
        self.mlp = mlp_class(intermediate_size,
                             config,
                             quant_config,
                             True,
                             prefix=f"{prefix}.mlp")

    def forward(
        self,
        hidden_states: torch.Tensor,
        position_ids: torch.Tensor,
        residual: Optional[torch.Tensor],
    ) -> torch.Tensor:
        if residual is None:
            residual = hidden_states
            hidden_states = self.input_layernorm(hidden_states)
        else:
            hidden_states, residual = self.input_layernorm(
                hidden_states, residual)

        hidden_states = self.attention(
            hidden_states=hidden_states,
            position_ids=position_ids,
        )

        hidden_states, residual = self.post_attention_layernorm(
            hidden_states, residual)
        hidden_states = self.mlp(hidden_states)
        return hidden_states, residual

attention instance-attribute

attention = BailingAttention(
    config,
    cache_config,
    quant_config,
    prefix=f"{prefix}.attention",
)

config instance-attribute

config = config

input_layernorm instance-attribute

input_layernorm = RMSNorm(hidden_size, eps=rms_norm_eps)

mlp instance-attribute

mlp = mlp_class(
    intermediate_size,
    config,
    quant_config,
    True,
    prefix=f"{prefix}.mlp",
)

post_attention_layernorm instance-attribute

post_attention_layernorm = RMSNorm(
    hidden_size, eps=rms_norm_eps
)

__init__

__init__(
    config: PretrainedConfig,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
)
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    config: PretrainedConfig,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
):
    super().__init__()
    layer_idx = int(prefix.split('.')[-1])
    self.config = config
    hidden_size = config.hidden_size
    intermediate_size = config.intermediate_size

    self.input_layernorm = RMSNorm(hidden_size, eps=config.rms_norm_eps)
    self.attention = BailingAttention(config,
                                      cache_config,
                                      quant_config,
                                      prefix=f"{prefix}.attention")

    self.post_attention_layernorm = RMSNorm(hidden_size,
                                            eps=config.rms_norm_eps)

    # Choose MLP class based on the number of experts and layer index
    if layer_idx < config.first_k_dense_replace:
        mlp_class = BailingMLP
    else:
        mlp_class = BailingMoE
    self.mlp = mlp_class(intermediate_size,
                         config,
                         quant_config,
                         True,
                         prefix=f"{prefix}.mlp")

forward

forward(
    hidden_states: Tensor,
    position_ids: Tensor,
    residual: Optional[Tensor],
) -> Tensor
Source code in vllm/model_executor/models/bailing_moe.py
def forward(
    self,
    hidden_states: torch.Tensor,
    position_ids: torch.Tensor,
    residual: Optional[torch.Tensor],
) -> torch.Tensor:
    if residual is None:
        residual = hidden_states
        hidden_states = self.input_layernorm(hidden_states)
    else:
        hidden_states, residual = self.input_layernorm(
            hidden_states, residual)

    hidden_states = self.attention(
        hidden_states=hidden_states,
        position_ids=position_ids,
    )

    hidden_states, residual = self.post_attention_layernorm(
        hidden_states, residual)
    hidden_states = self.mlp(hidden_states)
    return hidden_states, residual

BailingMoeForCausalLM

Bases: Module, SupportsPP, SupportsLoRA

Source code in vllm/model_executor/models/bailing_moe.py
class BailingMoeForCausalLM(nn.Module, SupportsPP, SupportsLoRA):

    packed_modules_mapping = {
        "query_key_value": ["query_key_value"],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }

    def __init__(
        self,
        *,
        vllm_config: VllmConfig,
        prefix: str = "",
    ) -> None:
        super().__init__()

        config = vllm_config.model_config.hf_config.get_text_config()
        vllm_config.model_config.hf_config = config
        quant_config = vllm_config.quant_config
        lora_config = vllm_config.lora_config

        self.config = config
        self.lora_config = lora_config
        self.quant_config = quant_config
        self.max_position_embeddings = config.max_position_embeddings
        self.model = BailingMoeModel(vllm_config=vllm_config,
                                     prefix=maybe_prefix(prefix, "model"))
        self.tie_word_embeddings = getattr(config, "tie_word_embeddings",
                                           False)

        if get_pp_group().is_last_rank:
            if self.tie_word_embeddings:
                self.lm_head = self.model.word_embeddings
            else:
                self.lm_head = ParallelLMHead(
                    config.vocab_size,
                    config.hidden_size,
                    quant_config=quant_config,
                    prefix=f"{prefix}.lm_head",
                )
            self.logits_processor = LogitsProcessor(config.vocab_size)
        else:
            self.lm_head = PPMissingLayer()

        self.make_empty_intermediate_tensors = (
            self.model.make_empty_intermediate_tensors)

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.get_input_embeddings(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> Union[torch.Tensor, IntermediateTensors]:
        model_output = self.model(input_ids, positions, intermediate_tensors,
                                  inputs_embeds)
        return model_output

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
    ) -> Optional[torch.Tensor]:
        logits = self.logits_processor(self.lm_head, hidden_states)
        return logits

    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(
            self,
            skip_prefixes=(["lm_head."] if self.tie_word_embeddings else None),
        )
        return loader.load_weights(weights)

    def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
        return self.model.get_expert_mapping()

config instance-attribute

config = config

lm_head instance-attribute

lm_head = word_embeddings

logits_processor instance-attribute

logits_processor = LogitsProcessor(vocab_size)

lora_config instance-attribute

lora_config = lora_config

make_empty_intermediate_tensors instance-attribute

make_empty_intermediate_tensors = (
    make_empty_intermediate_tensors
)

max_position_embeddings instance-attribute

max_position_embeddings = max_position_embeddings

model instance-attribute

model = BailingMoeModel(
    vllm_config=vllm_config,
    prefix=maybe_prefix(prefix, "model"),
)

packed_modules_mapping class-attribute instance-attribute

packed_modules_mapping = {
    "query_key_value": ["query_key_value"],
    "gate_up_proj": ["gate_proj", "up_proj"],
}

quant_config instance-attribute

quant_config = quant_config

tie_word_embeddings instance-attribute

tie_word_embeddings = getattr(
    config, "tie_word_embeddings", False
)

__init__

__init__(
    *, vllm_config: VllmConfig, prefix: str = ""
) -> None
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    *,
    vllm_config: VllmConfig,
    prefix: str = "",
) -> None:
    super().__init__()

    config = vllm_config.model_config.hf_config.get_text_config()
    vllm_config.model_config.hf_config = config
    quant_config = vllm_config.quant_config
    lora_config = vllm_config.lora_config

    self.config = config
    self.lora_config = lora_config
    self.quant_config = quant_config
    self.max_position_embeddings = config.max_position_embeddings
    self.model = BailingMoeModel(vllm_config=vllm_config,
                                 prefix=maybe_prefix(prefix, "model"))
    self.tie_word_embeddings = getattr(config, "tie_word_embeddings",
                                       False)

    if get_pp_group().is_last_rank:
        if self.tie_word_embeddings:
            self.lm_head = self.model.word_embeddings
        else:
            self.lm_head = ParallelLMHead(
                config.vocab_size,
                config.hidden_size,
                quant_config=quant_config,
                prefix=f"{prefix}.lm_head",
            )
        self.logits_processor = LogitsProcessor(config.vocab_size)
    else:
        self.lm_head = PPMissingLayer()

    self.make_empty_intermediate_tensors = (
        self.model.make_empty_intermediate_tensors)

compute_logits

compute_logits(hidden_states: Tensor) -> Optional[Tensor]
Source code in vllm/model_executor/models/bailing_moe.py
def compute_logits(
    self,
    hidden_states: torch.Tensor,
) -> Optional[torch.Tensor]:
    logits = self.logits_processor(self.lm_head, hidden_states)
    return logits

forward

forward(
    input_ids: Tensor,
    positions: Tensor,
    intermediate_tensors: Optional[
        IntermediateTensors
    ] = None,
    inputs_embeds: Optional[Tensor] = None,
) -> Union[Tensor, IntermediateTensors]
Source code in vllm/model_executor/models/bailing_moe.py
def forward(
    self,
    input_ids: torch.Tensor,
    positions: torch.Tensor,
    intermediate_tensors: Optional[IntermediateTensors] = None,
    inputs_embeds: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, IntermediateTensors]:
    model_output = self.model(input_ids, positions, intermediate_tensors,
                              inputs_embeds)
    return model_output

get_expert_mapping

get_expert_mapping() -> list[tuple[str, str, int, str]]
Source code in vllm/model_executor/models/bailing_moe.py
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
    return self.model.get_expert_mapping()

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/bailing_moe.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.model.get_input_embeddings(input_ids)

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/bailing_moe.py
def load_weights(self, weights: Iterable[tuple[str,
                                               torch.Tensor]]) -> set[str]:
    loader = AutoWeightsLoader(
        self,
        skip_prefixes=(["lm_head."] if self.tie_word_embeddings else None),
    )
    return loader.load_weights(weights)

BailingMoeModel

Bases: Module

Source code in vllm/model_executor/models/bailing_moe.py
@support_torch_compile
class BailingMoeModel(nn.Module):

    def __init__(
        self,
        *,
        vllm_config: VllmConfig,
        prefix: str = "",
    ):
        super().__init__()
        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config

        self.config = config
        self.vocab_size = config.vocab_size
        self.embed_dim = config.hidden_size
        self.tie_word_embeddings = getattr(config, "tie_word_embeddings",
                                           False)

        if get_pp_group().is_first_rank or (self.tie_word_embeddings
                                            and get_pp_group().is_last_rank):
            self.word_embeddings = VocabParallelEmbedding(
                self.vocab_size,
                self.embed_dim,
                quant_config=quant_config,
                prefix=f"{prefix}.word_embeddings",
            )
        else:
            self.word_embeddings = PPMissingLayer()

        self.embedding_dropout = torch.nn.Dropout(config.embedding_dropout)

        self.start_layer, self.end_layer, self.layers = make_layers(
            config.num_hidden_layers,
            lambda prefix: BailingMoeBlock(
                config=config,
                cache_config=cache_config,
                quant_config=quant_config,
                prefix=prefix,
            ),
            prefix=f"{prefix}.layers")

        self.make_empty_intermediate_tensors = (
            make_empty_intermediate_tensors_factory(
                ["hidden_states", "residual"], config.hidden_size))

        if get_pp_group().is_last_rank:
            self.norm = RMSNorm(self.embed_dim, eps=config.rms_norm_eps)
        else:
            self.norm = PPMissingLayer()

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.word_embeddings(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        position_ids: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors],
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> Union[torch.Tensor, IntermediateTensors]:
        if get_pp_group().is_first_rank:
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
                hidden_states = self.get_input_embeddings(input_ids)
            residual = None
        else:
            assert intermediate_tensors is not None
            hidden_states = intermediate_tensors["hidden_states"]
            residual = intermediate_tensors["residual"]

        for layer in islice(self.layers, self.start_layer, self.end_layer):
            hidden_states, residual = layer(
                hidden_states,
                position_ids,
                residual,
            )

        if not get_pp_group().is_last_rank:
            return IntermediateTensors({
                "hidden_states": hidden_states,
                "residual": residual
            })
        else:
            if residual is None:
                hidden_states = self.norm(hidden_states)
            else:
                hidden_states, _ = self.norm(hidden_states, residual)
        return hidden_states

    def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
        return FusedMoE.make_expert_params_mapping(
            ckpt_gate_proj_name="gate_proj",
            ckpt_down_proj_name="down_proj",
            ckpt_up_proj_name="up_proj",
            num_experts=self.config.num_experts,
        )

    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        stacked_params_mapping = [
            # (param_name, shard_name, shard_id)
            ("gate_up_proj", "gate_proj", 0),
            ("gate_up_proj", "up_proj", 1),
        ]

        params_dict = dict(self.named_parameters(remove_duplicate=False))
        loaded_params: set[str] = set()
        expert_params_mapping = self.get_expert_mapping()
        for name, loaded_weight in weights:
            if (hasattr(self.config, "norm_head") and self.config.norm_head
                    and "lm_head.weight" in name):
                loaded_weight = F.normalize(loaded_weight,
                                            dim=0,
                                            p=2,
                                            eps=1e-7)

            for (param_name, weight_name, shard_id) in stacked_params_mapping:
                if weight_name not in name:
                    continue
                if "mlp.experts" in name:
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
                if name not in params_dict:
                    continue

                if is_pp_missing_parameter(name, self):
                    continue

                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                break
            else:
                for mapping in expert_params_mapping:
                    param_name, weight_name, expert_id, shard_id = mapping
                    if weight_name not in name:
                        continue
                    name = name.replace(weight_name, param_name)

                    if is_pp_missing_parameter(name, self):
                        continue
                    if name not in params_dict:
                        continue
                    param = params_dict[name]
                    weight_loader = param.weight_loader
                    weight_loader(
                        param,
                        loaded_weight,
                        name,
                        shard_id=shard_id,
                        expert_id=expert_id,
                    )
                    break
                else:
                    if name.endswith(".bias") and name not in params_dict:
                        continue
                    if name not in params_dict:
                        continue

                    if is_pp_missing_parameter(name, self):
                        continue

                    param = params_dict[name]
                    weight_loader = getattr(param, "weight_loader",
                                            default_weight_loader)
                    weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params

config instance-attribute

config = config

embed_dim instance-attribute

embed_dim = hidden_size

embedding_dropout instance-attribute

embedding_dropout = Dropout(embedding_dropout)

make_empty_intermediate_tensors instance-attribute

make_empty_intermediate_tensors = (
    make_empty_intermediate_tensors_factory(
        ["hidden_states", "residual"], hidden_size
    )
)

norm instance-attribute

norm = RMSNorm(embed_dim, eps=rms_norm_eps)

tie_word_embeddings instance-attribute

tie_word_embeddings = getattr(
    config, "tie_word_embeddings", False
)

vocab_size instance-attribute

vocab_size = vocab_size

word_embeddings instance-attribute

word_embeddings = VocabParallelEmbedding(
    vocab_size,
    embed_dim,
    quant_config=quant_config,
    prefix=f"{prefix}.word_embeddings",
)

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/bailing_moe.py
def __init__(
    self,
    *,
    vllm_config: VllmConfig,
    prefix: str = "",
):
    super().__init__()
    config = vllm_config.model_config.hf_config
    cache_config = vllm_config.cache_config
    quant_config = vllm_config.quant_config

    self.config = config
    self.vocab_size = config.vocab_size
    self.embed_dim = config.hidden_size
    self.tie_word_embeddings = getattr(config, "tie_word_embeddings",
                                       False)

    if get_pp_group().is_first_rank or (self.tie_word_embeddings
                                        and get_pp_group().is_last_rank):
        self.word_embeddings = VocabParallelEmbedding(
            self.vocab_size,
            self.embed_dim,
            quant_config=quant_config,
            prefix=f"{prefix}.word_embeddings",
        )
    else:
        self.word_embeddings = PPMissingLayer()

    self.embedding_dropout = torch.nn.Dropout(config.embedding_dropout)

    self.start_layer, self.end_layer, self.layers = make_layers(
        config.num_hidden_layers,
        lambda prefix: BailingMoeBlock(
            config=config,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=prefix,
        ),
        prefix=f"{prefix}.layers")

    self.make_empty_intermediate_tensors = (
        make_empty_intermediate_tensors_factory(
            ["hidden_states", "residual"], config.hidden_size))

    if get_pp_group().is_last_rank:
        self.norm = RMSNorm(self.embed_dim, eps=config.rms_norm_eps)
    else:
        self.norm = PPMissingLayer()

forward

forward(
    input_ids: Tensor,
    position_ids: Tensor,
    intermediate_tensors: Optional[IntermediateTensors],
    inputs_embeds: Optional[Tensor] = None,
) -> Union[Tensor, IntermediateTensors]
Source code in vllm/model_executor/models/bailing_moe.py
def forward(
    self,
    input_ids: torch.Tensor,
    position_ids: torch.Tensor,
    intermediate_tensors: Optional[IntermediateTensors],
    inputs_embeds: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, IntermediateTensors]:
    if get_pp_group().is_first_rank:
        if inputs_embeds is not None:
            hidden_states = inputs_embeds
        else:
            hidden_states = self.get_input_embeddings(input_ids)
        residual = None
    else:
        assert intermediate_tensors is not None
        hidden_states = intermediate_tensors["hidden_states"]
        residual = intermediate_tensors["residual"]

    for layer in islice(self.layers, self.start_layer, self.end_layer):
        hidden_states, residual = layer(
            hidden_states,
            position_ids,
            residual,
        )

    if not get_pp_group().is_last_rank:
        return IntermediateTensors({
            "hidden_states": hidden_states,
            "residual": residual
        })
    else:
        if residual is None:
            hidden_states = self.norm(hidden_states)
        else:
            hidden_states, _ = self.norm(hidden_states, residual)
    return hidden_states

get_expert_mapping

get_expert_mapping() -> list[tuple[str, str, int, str]]
Source code in vllm/model_executor/models/bailing_moe.py
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
    return FusedMoE.make_expert_params_mapping(
        ckpt_gate_proj_name="gate_proj",
        ckpt_down_proj_name="down_proj",
        ckpt_up_proj_name="up_proj",
        num_experts=self.config.num_experts,
    )

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/bailing_moe.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.word_embeddings(input_ids)

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/bailing_moe.py
def load_weights(self, weights: Iterable[tuple[str,
                                               torch.Tensor]]) -> set[str]:
    stacked_params_mapping = [
        # (param_name, shard_name, shard_id)
        ("gate_up_proj", "gate_proj", 0),
        ("gate_up_proj", "up_proj", 1),
    ]

    params_dict = dict(self.named_parameters(remove_duplicate=False))
    loaded_params: set[str] = set()
    expert_params_mapping = self.get_expert_mapping()
    for name, loaded_weight in weights:
        if (hasattr(self.config, "norm_head") and self.config.norm_head
                and "lm_head.weight" in name):
            loaded_weight = F.normalize(loaded_weight,
                                        dim=0,
                                        p=2,
                                        eps=1e-7)

        for (param_name, weight_name, shard_id) in stacked_params_mapping:
            if weight_name not in name:
                continue
            if "mlp.experts" in name:
                continue
            name = name.replace(weight_name, param_name)
            # Skip loading extra bias for GPTQ models.
            if name.endswith(".bias") and name not in params_dict:
                continue
            if name not in params_dict:
                continue

            if is_pp_missing_parameter(name, self):
                continue

            param = params_dict[name]
            weight_loader = param.weight_loader
            weight_loader(param, loaded_weight, shard_id)
            break
        else:
            for mapping in expert_params_mapping:
                param_name, weight_name, expert_id, shard_id = mapping
                if weight_name not in name:
                    continue
                name = name.replace(weight_name, param_name)

                if is_pp_missing_parameter(name, self):
                    continue
                if name not in params_dict:
                    continue
                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(
                    param,
                    loaded_weight,
                    name,
                    shard_id=shard_id,
                    expert_id=expert_id,
                )
                break
            else:
                if name.endswith(".bias") and name not in params_dict:
                    continue
                if name not in params_dict:
                    continue

                if is_pp_missing_parameter(name, self):
                    continue

                param = params_dict[name]
                weight_loader = getattr(param, "weight_loader",
                                        default_weight_loader)
                weight_loader(param, loaded_weight)
        loaded_params.add(name)
    return loaded_params

BailingMoeV2ForCausalLM

Bases: BailingMoeForCausalLM

Source code in vllm/model_executor/models/bailing_moe.py
class BailingMoeV2ForCausalLM(BailingMoeForCausalLM):
    pass