[Feature] Support MTP speculative decoding for Bailing hybrid models (#44880)
Signed-off-by: zc02384840 <zc02384840@antgroup.com> Co-authored-by: zc02384840 <zc02384840@antgroup.com>
This commit is contained in:
co-authored by
zc02384840
parent
95a248faed
commit
f2aaf59151
@@ -30,11 +30,10 @@ from vllm.model_executor.layers.mamba.linear.base import LinearAttention
|
||||
from vllm.model_executor.layers.mamba.linear.minimax_linear_attn import (
|
||||
MiniMaxText01LinearAttention,
|
||||
MiniMaxText01LinearKernel,
|
||||
clear_linear_attention_cache_for_new_sequences,
|
||||
linear_attention_decode,
|
||||
linear_attention_prefill_and_mix,
|
||||
)
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.backends.linear_attn import LinearAttentionMetadata
|
||||
|
||||
|
||||
@@ -57,6 +56,290 @@ def _build_rope_parameters(config: PretrainedConfig) -> dict | None:
|
||||
return rope_parameters or None
|
||||
|
||||
|
||||
def clear_linear_attention_cache_for_new_sequences(
|
||||
kv_cache: torch.Tensor,
|
||||
state_indices_tensor: torch.Tensor,
|
||||
attn_metadata: LinearAttentionMetadata,
|
||||
) -> None:
|
||||
num_prefills = getattr(attn_metadata, "num_prefills", 0)
|
||||
if num_prefills <= 0:
|
||||
return
|
||||
|
||||
num_decodes = getattr(attn_metadata, "num_decodes", 0)
|
||||
prefill_state_indices = getattr(attn_metadata, "state_indices_tensor_p", None)
|
||||
for prefill_idx in range(num_prefills):
|
||||
if num_decodes + prefill_idx + 1 >= len(attn_metadata.query_start_loc):
|
||||
break
|
||||
q_start = attn_metadata.query_start_loc[num_decodes + prefill_idx]
|
||||
q_end = attn_metadata.query_start_loc[num_decodes + prefill_idx + 1]
|
||||
query_len = q_end - q_start
|
||||
context_len = attn_metadata.seq_lens[num_decodes + prefill_idx] - query_len
|
||||
if context_len == 0:
|
||||
if prefill_state_indices is not None:
|
||||
block_to_clear = prefill_state_indices[prefill_idx]
|
||||
else:
|
||||
block_to_clear = state_indices_tensor[num_decodes + prefill_idx]
|
||||
kv_cache[block_to_clear, ...] = 0
|
||||
|
||||
|
||||
def linear_attention_prefill_and_mix(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
state_indices_tensor: torch.Tensor,
|
||||
attn_metadata: LinearAttentionMetadata,
|
||||
slope_rate: torch.Tensor,
|
||||
block_size: int,
|
||||
decode_fn,
|
||||
prefix_fn,
|
||||
layer_idx: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
hidden = []
|
||||
req_offset = getattr(attn_metadata, "num_decodes", 0)
|
||||
prefill_state_indices = getattr(attn_metadata, "state_indices_tensor_p", None)
|
||||
for _prefill_idx in range(getattr(attn_metadata, "num_prefills", 0)):
|
||||
if req_offset + _prefill_idx + 1 >= len(attn_metadata.query_start_loc):
|
||||
break
|
||||
if prefill_state_indices is not None and _prefill_idx >= len(
|
||||
prefill_state_indices
|
||||
):
|
||||
break
|
||||
if prefill_state_indices is None and _prefill_idx >= len(state_indices_tensor):
|
||||
break
|
||||
_start = attn_metadata.query_start_loc[req_offset + _prefill_idx]
|
||||
_end = attn_metadata.query_start_loc[req_offset + _prefill_idx + 1]
|
||||
if prefill_state_indices is not None:
|
||||
slot_id = prefill_state_indices[_prefill_idx]
|
||||
else:
|
||||
slot_id = state_indices_tensor[req_offset + _prefill_idx]
|
||||
qs = q[_start:_end].transpose(0, 1).contiguous()
|
||||
ks = k[_start:_end].transpose(0, 1).contiguous()
|
||||
vs = v[_start:_end].transpose(0, 1).contiguous()
|
||||
slice_layer_cache = kv_cache[slot_id, ...]
|
||||
out_slice = prefix_fn(
|
||||
qs,
|
||||
ks,
|
||||
vs,
|
||||
slice_layer_cache,
|
||||
slope_rate,
|
||||
block_size,
|
||||
layer_idx=layer_idx,
|
||||
)
|
||||
hidden.append(out_slice.contiguous())
|
||||
|
||||
if attn_metadata.num_decode_tokens > 0:
|
||||
hidden_decode = decode_fn(
|
||||
q, k, v, kv_cache, state_indices_tensor, attn_metadata
|
||||
)
|
||||
hidden.insert(0, hidden_decode)
|
||||
|
||||
if not hidden:
|
||||
return torch.empty((0, q.size(1) * q.size(2)), device=q.device, dtype=q.dtype)
|
||||
|
||||
hidden = torch.concat(hidden, dim=0).contiguous()
|
||||
return hidden
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _bailing_linear_attn_decode_spec_step_kernel(
|
||||
q_ptr,
|
||||
k_ptr,
|
||||
v_ptr,
|
||||
kv_cache_ptr,
|
||||
slope_rate_ptr,
|
||||
state_indices_ptr,
|
||||
query_start_loc_ptr,
|
||||
num_accepted_tokens_ptr,
|
||||
output_ptr,
|
||||
q_start: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
q_b_stride,
|
||||
q_h_stride,
|
||||
q_d_stride,
|
||||
k_b_stride,
|
||||
k_h_stride,
|
||||
k_d_stride,
|
||||
v_b_stride,
|
||||
v_h_stride,
|
||||
v_d_stride,
|
||||
cache_b_stride,
|
||||
cache_h_stride,
|
||||
cache_d0_stride,
|
||||
cache_d1_stride,
|
||||
state_indices_b_stride,
|
||||
state_indices_t_stride,
|
||||
output_b_stride,
|
||||
output_d_stride,
|
||||
DRAFT_IDX: tl.constexpr,
|
||||
STATE_WIDTH: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
req_id = tl.program_id(0)
|
||||
head_id = tl.program_id(1)
|
||||
block_id = tl.program_id(2)
|
||||
|
||||
req_start = tl.load(query_start_loc_ptr + req_id).to(tl.int64)
|
||||
req_end = tl.load(query_start_loc_ptr + req_id + 1).to(tl.int64)
|
||||
query_len = req_end - req_start
|
||||
if query_len <= DRAFT_IDX:
|
||||
return
|
||||
|
||||
dst_slot = tl.load(
|
||||
state_indices_ptr
|
||||
+ req_id * state_indices_b_stride
|
||||
+ DRAFT_IDX * state_indices_t_stride
|
||||
).to(tl.int64)
|
||||
if dst_slot == -1:
|
||||
return
|
||||
|
||||
if DRAFT_IDX == 0:
|
||||
accepted_offset = tl.load(num_accepted_tokens_ptr + req_id).to(tl.int64) - 1
|
||||
accepted_offset = tl.maximum(accepted_offset, 0)
|
||||
accepted_offset = tl.minimum(accepted_offset, STATE_WIDTH - 1)
|
||||
src_slot = tl.load(
|
||||
state_indices_ptr
|
||||
+ req_id * state_indices_b_stride
|
||||
+ accepted_offset * state_indices_t_stride
|
||||
).to(tl.int64)
|
||||
else:
|
||||
src_slot = tl.load(
|
||||
state_indices_ptr
|
||||
+ req_id * state_indices_b_stride
|
||||
+ (DRAFT_IDX - 1) * state_indices_t_stride
|
||||
).to(tl.int64)
|
||||
if src_slot == -1:
|
||||
return
|
||||
|
||||
token_idx = req_start - q_start + DRAFT_IDX
|
||||
qk_offsets = tl.arange(0, D)
|
||||
v_offsets = tl.arange(0, BLOCK_SIZE) + block_id * BLOCK_SIZE
|
||||
qk_mask = qk_offsets < D
|
||||
v_mask = v_offsets < D
|
||||
kv_mask = qk_mask[:, None] & v_mask[None, :]
|
||||
|
||||
q = tl.load(
|
||||
q_ptr + token_idx * q_b_stride + head_id * q_h_stride + qk_offsets * q_d_stride,
|
||||
mask=qk_mask,
|
||||
other=0.0,
|
||||
)
|
||||
k = tl.load(
|
||||
k_ptr + token_idx * k_b_stride + head_id * k_h_stride + qk_offsets * k_d_stride,
|
||||
mask=qk_mask,
|
||||
other=0.0,
|
||||
)
|
||||
v = tl.load(
|
||||
v_ptr + token_idx * v_b_stride + head_id * v_h_stride + v_offsets * v_d_stride,
|
||||
mask=v_mask,
|
||||
other=0.0,
|
||||
)
|
||||
|
||||
cache_offsets = (
|
||||
qk_offsets[:, None] * cache_d0_stride + v_offsets[None, :] * cache_d1_stride
|
||||
)
|
||||
src_cache_ptr = (
|
||||
kv_cache_ptr
|
||||
+ src_slot * cache_b_stride
|
||||
+ head_id * cache_h_stride
|
||||
+ cache_offsets
|
||||
)
|
||||
dst_cache_ptr = (
|
||||
kv_cache_ptr
|
||||
+ dst_slot * cache_b_stride
|
||||
+ head_id * cache_h_stride
|
||||
+ cache_offsets
|
||||
)
|
||||
|
||||
slope = tl.load(slope_rate_ptr + head_id)
|
||||
decay = tl.exp(-slope)
|
||||
kv_old = tl.load(src_cache_ptr, mask=kv_mask, other=0.0)
|
||||
kv_new = k[:, None] * v[None, :] + decay * kv_old
|
||||
|
||||
output = tl.sum(q[:, None].to(tl.float32) * kv_new, axis=0)
|
||||
tl.store(dst_cache_ptr, kv_new, mask=kv_mask)
|
||||
tl.store(
|
||||
output_ptr
|
||||
+ token_idx * output_b_stride
|
||||
+ (head_id * D + v_offsets) * output_d_stride,
|
||||
output,
|
||||
mask=v_mask,
|
||||
)
|
||||
|
||||
|
||||
def bailing_linear_attention_decode_spec(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slope_rate: torch.Tensor,
|
||||
state_indices_tensor: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
num_accepted_tokens: torch.Tensor,
|
||||
q_start: int,
|
||||
q_end: int | None,
|
||||
slot_start: int,
|
||||
slot_end: int | None,
|
||||
block_size: int,
|
||||
) -> torch.Tensor:
|
||||
q_decode = q[q_start:q_end]
|
||||
k_decode = k[q_start:q_end]
|
||||
v_decode = v[q_start:q_end]
|
||||
hidden = torch.empty(
|
||||
(q_decode.shape[0], q.shape[1] * q.shape[2]),
|
||||
device=q.device,
|
||||
dtype=q.dtype,
|
||||
)
|
||||
hidden.zero_()
|
||||
|
||||
state_indices_tensor = state_indices_tensor[slot_start:slot_end]
|
||||
query_start_loc = query_start_loc.to(device=q.device)
|
||||
|
||||
batch_size = state_indices_tensor.shape[0]
|
||||
num_heads = q_decode.shape[1]
|
||||
head_dim = q_decode.shape[2]
|
||||
assert k_decode.shape == (q_decode.shape[0], num_heads, head_dim)
|
||||
assert v_decode.shape == (q_decode.shape[0], num_heads, head_dim)
|
||||
state_width = state_indices_tensor.shape[1]
|
||||
|
||||
grid = (batch_size, num_heads, triton.cdiv(head_dim, block_size))
|
||||
for draft_idx in range(state_width):
|
||||
_bailing_linear_attn_decode_spec_step_kernel[grid](
|
||||
q_decode,
|
||||
k_decode,
|
||||
v_decode,
|
||||
kv_cache,
|
||||
slope_rate,
|
||||
state_indices_tensor,
|
||||
query_start_loc,
|
||||
num_accepted_tokens[:batch_size],
|
||||
hidden,
|
||||
q_start,
|
||||
head_dim,
|
||||
q_decode.stride(0),
|
||||
q_decode.stride(1),
|
||||
q_decode.stride(2),
|
||||
k_decode.stride(0),
|
||||
k_decode.stride(1),
|
||||
k_decode.stride(2),
|
||||
v_decode.stride(0),
|
||||
v_decode.stride(1),
|
||||
v_decode.stride(2),
|
||||
kv_cache.stride(0),
|
||||
kv_cache.stride(1),
|
||||
kv_cache.stride(2),
|
||||
kv_cache.stride(3),
|
||||
state_indices_tensor.stride(0),
|
||||
state_indices_tensor.stride(1),
|
||||
hidden.stride(0),
|
||||
hidden.stride(1),
|
||||
DRAFT_IDX=draft_idx,
|
||||
STATE_WIDTH=state_width,
|
||||
BLOCK_SIZE=block_size,
|
||||
)
|
||||
|
||||
return hidden
|
||||
|
||||
|
||||
class BailingGroupRMSNormGate(RMSNormGated):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -208,6 +491,13 @@ class BailingMoELinearAttention(LinearAttention):
|
||||
raise ValueError(f"Duplicate layer name: {prefix}")
|
||||
compilation_config.static_forward_context[prefix] = self
|
||||
|
||||
def get_attn_backend(self):
|
||||
from vllm.v1.attention.backends.linear_attn import (
|
||||
BailingLinearAttentionBackend,
|
||||
)
|
||||
|
||||
return BailingLinearAttentionBackend
|
||||
|
||||
@staticmethod
|
||||
def weight_direct_load(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
|
||||
"""Load weight for linear attention layers.
|
||||
@@ -368,13 +658,42 @@ class BailingMoELinearAttention(LinearAttention):
|
||||
|
||||
def _decode_infer(self, q, k, v, kv_cache, state_indices_tensor, attn_metadata):
|
||||
"""Handle decode (single token per sequence)."""
|
||||
decode_state_indices = getattr(attn_metadata, "state_indices_tensor_d", None)
|
||||
num_accepted_tokens = getattr(attn_metadata, "num_accepted_tokens", None)
|
||||
query_start_loc = getattr(attn_metadata, "query_start_loc_d", None)
|
||||
if (
|
||||
decode_state_indices is not None
|
||||
and decode_state_indices.dim() > 1
|
||||
and num_accepted_tokens is not None
|
||||
and query_start_loc is not None
|
||||
):
|
||||
return bailing_linear_attention_decode_spec(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
kv_cache,
|
||||
self.tp_slope,
|
||||
decode_state_indices,
|
||||
query_start_loc,
|
||||
num_accepted_tokens,
|
||||
q_start=0,
|
||||
q_end=attn_metadata.num_decode_tokens,
|
||||
slot_start=0,
|
||||
slot_end=attn_metadata.num_decodes,
|
||||
block_size=32,
|
||||
)
|
||||
decode_state_indices = (
|
||||
state_indices_tensor
|
||||
if decode_state_indices is None
|
||||
else decode_state_indices
|
||||
)
|
||||
hidden = linear_attention_decode(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
kv_cache,
|
||||
self.tp_slope,
|
||||
state_indices_tensor,
|
||||
decode_state_indices,
|
||||
q_start=0,
|
||||
q_end=attn_metadata.num_decode_tokens,
|
||||
slot_start=0,
|
||||
|
||||
@@ -533,6 +533,10 @@ class BailingMoeV25Model(nn.Module):
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.word_embeddings(input_ids)
|
||||
|
||||
@property
|
||||
def embed_tokens(self) -> nn.Module:
|
||||
return self.word_embeddings
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-only Bailing MoE v2.5 MTP model."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.fused_moe import (
|
||||
fused_moe_make_expert_params_mapping,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
default_weight_loader,
|
||||
maybe_remap_kv_scale_name,
|
||||
)
|
||||
from vllm.model_executor.models.bailing_moe_linear import (
|
||||
BailingMoeV25,
|
||||
BailingMoeV25MLAAttention,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from .utils import PPMissingLayer, is_pp_missing_parameter, maybe_prefix
|
||||
|
||||
|
||||
def _get_draft_hf_config(vllm_config: VllmConfig) -> PretrainedConfig:
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is not None:
|
||||
draft_model_config = speculative_config.draft_model_config
|
||||
if draft_model_config is not None:
|
||||
return draft_model_config.hf_config
|
||||
return vllm_config.model_config.hf_config
|
||||
|
||||
|
||||
class BailingMTPSharedHead(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config: PretrainedConfig,
|
||||
prefix: str,
|
||||
vllm_config: VllmConfig,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
quant_config=vllm_config.quant_config,
|
||||
prefix=maybe_prefix(prefix, "head"),
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return hidden_states
|
||||
|
||||
|
||||
class BailingMoeV25MultiTokenPredictorLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
prefix: str,
|
||||
layer_id: int,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
config = _get_draft_hf_config(vllm_config)
|
||||
self.config = config
|
||||
self.layer_id = layer_id
|
||||
self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
|
||||
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.self_attn = BailingMoeV25MLAAttention(
|
||||
config,
|
||||
quant_config=vllm_config.quant_config,
|
||||
layer_id=layer_id,
|
||||
prefix=maybe_prefix(prefix, "self_attn"),
|
||||
cache_config=vllm_config.cache_config,
|
||||
)
|
||||
self.post_attention_layernorm = RMSNorm(
|
||||
config.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
self.mlp = BailingMoeV25(
|
||||
config,
|
||||
quant_config=vllm_config.quant_config,
|
||||
layer_id=layer_id,
|
||||
prefix=maybe_prefix(prefix, "mlp"),
|
||||
)
|
||||
self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.shared_head = BailingMTPSharedHead(
|
||||
config,
|
||||
maybe_prefix(prefix, "shared_head"),
|
||||
vllm_config,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
previous_hidden_states: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_index: int = 0,
|
||||
) -> torch.Tensor:
|
||||
assert inputs_embeds is not None
|
||||
inputs_embeds = torch.where(positions.unsqueeze(-1) == 0, 0, inputs_embeds)
|
||||
inputs_embeds = self.enorm(inputs_embeds)
|
||||
previous_hidden_states = self.hnorm(previous_hidden_states)
|
||||
|
||||
hidden_states = self.eh_proj(
|
||||
torch.cat([inputs_embeds, previous_hidden_states], dim=-1)
|
||||
)
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
hidden_states = self.self_attn(hidden_states, positions)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states.to(residual.device)
|
||||
return self.final_layernorm(hidden_states)
|
||||
|
||||
|
||||
class BailingMoeV25MultiTokenPredictor(nn.Module):
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
config = _get_draft_hf_config(vllm_config)
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
self.num_mtp_layers = config.num_nextn_predict_layers
|
||||
self.layers = nn.ModuleDict(
|
||||
{
|
||||
str(idx): BailingMoeV25MultiTokenPredictorLayer(
|
||||
vllm_config,
|
||||
f"{prefix}.layers.{idx}",
|
||||
idx,
|
||||
)
|
||||
for idx in range(
|
||||
self.mtp_start_layer_idx,
|
||||
self.mtp_start_layer_idx + self.num_mtp_layers,
|
||||
)
|
||||
}
|
||||
)
|
||||
if get_pp_group().is_first_rank:
|
||||
self.embed_tokens = VocabParallelEmbedding(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
org_num_embeddings=config.vocab_size,
|
||||
prefix=maybe_prefix(prefix, "embed_tokens"),
|
||||
)
|
||||
else:
|
||||
self.embed_tokens = PPMissingLayer()
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
previous_hidden_states: torch.Tensor,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor:
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
return self.layers[str(self.mtp_start_layer_idx + current_step_idx)](
|
||||
input_ids,
|
||||
positions,
|
||||
previous_hidden_states,
|
||||
inputs_embeds,
|
||||
current_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
spec_step_idx: int = 0,
|
||||
lm_head: nn.Module | None = None,
|
||||
) -> torch.Tensor:
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
mtp_layer = self.layers[str(self.mtp_start_layer_idx + current_step_idx)]
|
||||
head = lm_head if lm_head is not None else mtp_layer.shared_head.head
|
||||
return self.logits_processor(
|
||||
head,
|
||||
mtp_layer.shared_head(hidden_states),
|
||||
)
|
||||
|
||||
|
||||
@support_torch_compile
|
||||
class BailingMoeV25MTPModel(nn.Module):
|
||||
packed_modules_mapping = {
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
"fused_qkv_a_proj": ["q_a_proj", "kv_a_proj_with_mqa"],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
self.config = _get_draft_hf_config(vllm_config)
|
||||
self.lm_head: nn.Module | None = None
|
||||
self.model = BailingMoeV25MultiTokenPredictor(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "model"),
|
||||
)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.embed_input_ids(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor:
|
||||
return self.model(
|
||||
input_ids,
|
||||
positions,
|
||||
hidden_states,
|
||||
inputs_embeds,
|
||||
spec_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor:
|
||||
return self.model.compute_logits(hidden_states, spec_step_idx, self.lm_head)
|
||||
|
||||
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
|
||||
return fused_moe_make_expert_params_mapping(
|
||||
self,
|
||||
ckpt_gate_proj_name="gate_proj",
|
||||
ckpt_down_proj_name="down_proj",
|
||||
ckpt_up_proj_name="up_proj",
|
||||
num_experts=self.config.num_experts,
|
||||
num_redundant_experts=0,
|
||||
)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
stacked_params_mapping = [
|
||||
(".fused_qkv_a_proj", ".q_a_proj", 0),
|
||||
(".fused_qkv_a_proj", ".kv_a_proj_with_mqa", 1),
|
||||
(".gate_up_proj", ".gate_proj", 0),
|
||||
(".gate_up_proj", ".up_proj", 1),
|
||||
]
|
||||
expert_params_mapping = list(self.get_expert_mapping())
|
||||
params_dict = dict(self.named_parameters(remove_duplicate=False))
|
||||
loaded_params: set[str] = set()
|
||||
loaded_mtp_layers: set[int] = set()
|
||||
|
||||
def load_param(
|
||||
name: str,
|
||||
loaded_weight: torch.Tensor,
|
||||
shard_id=None,
|
||||
) -> bool:
|
||||
name = maybe_remap_kv_scale_name(name, params_dict)
|
||||
if name is None:
|
||||
return False
|
||||
if name not in params_dict or is_pp_missing_parameter(name, self):
|
||||
return False
|
||||
|
||||
param = params_dict[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
if shard_id is None:
|
||||
weight_loader(param, loaded_weight)
|
||||
elif isinstance(shard_id, int):
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
else:
|
||||
weight_loader(
|
||||
param,
|
||||
loaded_weight,
|
||||
name,
|
||||
expert_id=shard_id[0],
|
||||
shard_id=shard_id[1],
|
||||
)
|
||||
loaded_params.add(name)
|
||||
return True
|
||||
|
||||
def get_spec_layer_idx(name: str) -> int | None:
|
||||
if not name.startswith("model.layers."):
|
||||
return None
|
||||
try:
|
||||
layer_idx = int(name.split("model.layers.", 1)[1].split(".", 1)[0])
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
mtp_idx = layer_idx - self.config.num_hidden_layers
|
||||
if 0 <= mtp_idx < self.config.num_nextn_predict_layers:
|
||||
return layer_idx
|
||||
return None
|
||||
|
||||
def normalize_name(name: str) -> str:
|
||||
name = name.replace(".attention.dense", ".self_attn.o_proj")
|
||||
name = name.replace(".attention.", ".self_attn.")
|
||||
return name.replace(
|
||||
"mlp.gate.e_score_correction_bias",
|
||||
"mlp.gate.expert_bias",
|
||||
)
|
||||
|
||||
def load_lm_head(loaded_weight: torch.Tensor) -> None:
|
||||
for layer_idx in range(
|
||||
self.model.mtp_start_layer_idx,
|
||||
self.model.mtp_start_layer_idx + self.model.num_mtp_layers,
|
||||
):
|
||||
name = f"model.layers.{layer_idx}.shared_head.head.weight"
|
||||
load_param(name, loaded_weight)
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
if "rotary_emb.inv_freq" in name:
|
||||
continue
|
||||
|
||||
if name == "model.word_embeddings.weight":
|
||||
load_param("model.embed_tokens.weight", loaded_weight)
|
||||
continue
|
||||
if name == "lm_head.weight":
|
||||
load_lm_head(loaded_weight)
|
||||
continue
|
||||
|
||||
spec_layer = get_spec_layer_idx(name)
|
||||
if spec_layer is None:
|
||||
continue
|
||||
name = normalize_name(name)
|
||||
|
||||
loaded = False
|
||||
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||
if weight_name not in name:
|
||||
continue
|
||||
if "mlp.experts." in name and name not in params_dict:
|
||||
continue
|
||||
mapped_name = name.replace(weight_name, param_name)
|
||||
if load_param(mapped_name, loaded_weight, shard_id):
|
||||
loaded = True
|
||||
break
|
||||
if loaded:
|
||||
loaded_mtp_layers.add(spec_layer)
|
||||
continue
|
||||
|
||||
if "mlp.experts" in name:
|
||||
for mapping in expert_params_mapping:
|
||||
param_name, weight_name, expert_id, shard_id = mapping
|
||||
if weight_name not in name:
|
||||
continue
|
||||
mapped_name = name.replace(weight_name, param_name)
|
||||
if load_param(
|
||||
mapped_name,
|
||||
loaded_weight,
|
||||
(expert_id, shard_id),
|
||||
):
|
||||
loaded = True
|
||||
break
|
||||
if loaded:
|
||||
loaded_mtp_layers.add(spec_layer)
|
||||
continue
|
||||
|
||||
if load_param(name, loaded_weight):
|
||||
loaded_mtp_layers.add(spec_layer)
|
||||
|
||||
for layer_idx in range(
|
||||
self.model.mtp_start_layer_idx,
|
||||
self.model.mtp_start_layer_idx + self.model.num_mtp_layers,
|
||||
):
|
||||
if layer_idx not in loaded_mtp_layers:
|
||||
raise ValueError(
|
||||
f"Bailing MTP speculative decoding layer {layer_idx} "
|
||||
"weights are missing from checkpoint. Use a checkpoint "
|
||||
"that includes MTP layer weights, or disable speculative "
|
||||
"decoding."
|
||||
)
|
||||
return loaded_params
|
||||
@@ -612,6 +612,7 @@ _SPECULATIVE_DECODING_MODELS = {
|
||||
"DeepSeekMTPModel": ("deepseek_mtp", "DeepSeekMTP"),
|
||||
"DeepSeekV4MTPModel": ("vllm.models.deepseek_v4", "DeepSeekV4MTP"),
|
||||
"MiniMaxM3MTP": ("vllm.models.minimax_m3", "MiniMaxM3MTP"),
|
||||
"BailingMoeV25MTPModel": ("bailing_moe_mtp", "BailingMoeV25MTPModel"),
|
||||
"Gemma4MTPModel": ("gemma4_mtp", "Gemma4MTP"),
|
||||
"ErnieMTPModel": ("ernie_mtp", "ErnieMTP"),
|
||||
"ExaoneMoeMTP": ("exaone_moe_mtp", "ExaoneMoeMTP"),
|
||||
|
||||
Reference in New Issue
Block a user