Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -37,6 +37,7 @@ from vllm.model_executor.models.interfaces import (
|
||||
IsHybrid,
|
||||
MixtureOfExperts,
|
||||
MultiModalEmbeddings,
|
||||
SupportsHCSP,
|
||||
SupportsLoRA,
|
||||
SupportsMRoPE,
|
||||
SupportsPP,
|
||||
@@ -67,6 +68,7 @@ from vllm.model_executor.models.utils import (
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.models.common.ops.sequence_parallel import sp_all_gather
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import MultiModalFeatureSpec
|
||||
from vllm.sequence import IntermediateTensors
|
||||
@@ -74,9 +76,11 @@ from vllm.tokenizers.registry import cached_tokenizer_from_config
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
from ..common.hyperconnection import is_hc_sequence_parallel_enabled
|
||||
from ..common.mtp import make_mtp_hidden_buffer
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .ops.sequence_parallel import sp_reduce_scatter, sp_shard
|
||||
from .ple_layer import Qwen4ExpPLELayer
|
||||
from .qsa import Qwen4ExpQSAAttention
|
||||
|
||||
@@ -162,13 +166,19 @@ _EXTRA_WEIGHTS_MAPPER = WeightsMapper(
|
||||
class Qwen4ExpSparseMoeBlock(Qwen3NextSparseMoeBlock):
|
||||
"""Qwen3Next MoE with Qwen4Exp HC validation."""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
parallel_config = vllm_config.parallel_config
|
||||
if parallel_config.use_sequence_parallel_moe:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp HC does not support sequence-parallel MoE"
|
||||
)
|
||||
super().__init__(vllm_config=vllm_config, prefix=prefix)
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
prefix: str = "",
|
||||
reduce_results: bool = True,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
vllm_config=vllm_config, prefix=prefix, reduce_results=reduce_results
|
||||
)
|
||||
if self.replicate_shared_expert and not self.is_sequence_parallel:
|
||||
# Reduce routed outputs before adding replicated shared outputs.
|
||||
# SP then slices the result to avoid summing shared outputs again via RS.
|
||||
self.experts.moe_config.skip_final_all_reduce = False
|
||||
config = vllm_config.model_config.hf_text_config
|
||||
self.n_shared_experts = int(config.shared_expert_intermediate_size > 0)
|
||||
|
||||
@@ -186,11 +196,12 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
|
||||
self.config = config
|
||||
self.layer_type = layer_type
|
||||
# MoE SP also enables HC SP, while HC SP can be enabled independently.
|
||||
self.use_hc_sequence_parallel = is_hc_sequence_parallel_enabled(vllm_config)
|
||||
self.layer_idx = extract_layer_index(prefix)
|
||||
if vllm_config.parallel_config.use_sequence_parallel_moe:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp HC does not support sequence-parallel MoE"
|
||||
)
|
||||
self.use_sequence_parallel = (
|
||||
vllm_config.parallel_config.use_sequence_parallel_moe
|
||||
)
|
||||
self.ple: Qwen4ExpPLELayer | None = None
|
||||
ple_layer_ids = config.ple_layer_ids
|
||||
if (self.layer_idx + 1) in ple_layer_ids:
|
||||
@@ -205,6 +216,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
layer_idx=self.layer_idx,
|
||||
ple_dense_layer_id=ple_dense_layer_id,
|
||||
prefix=f"{prefix}.ple",
|
||||
use_sequence_parallel=self.use_hc_sequence_parallel,
|
||||
)
|
||||
|
||||
if layer_type == "linear_attention":
|
||||
@@ -213,6 +225,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
vllm_config=vllm_config,
|
||||
prefix=f"{prefix}.linear_attn",
|
||||
gqa_interleaved_layout=False,
|
||||
reduce_results=not self.use_hc_sequence_parallel,
|
||||
)
|
||||
elif layer_type in _QSA_LAYER_TYPES:
|
||||
use_qsa = getattr(config, "indexer_n_heads", None) is not None
|
||||
@@ -223,6 +236,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
cache_config=vllm_config.cache_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.self_attn",
|
||||
reduce_results=not self.use_hc_sequence_parallel,
|
||||
)
|
||||
else:
|
||||
self.self_attn = Qwen4ExpQSAAttention(
|
||||
@@ -231,12 +245,15 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
layer_id=self.layer_idx,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.self_attn",
|
||||
reduce_results=not self.use_hc_sequence_parallel,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid layer_type {layer_type}")
|
||||
|
||||
self.mlp = Qwen4ExpSparseMoeBlock(
|
||||
vllm_config=vllm_config, prefix=f"{prefix}.mlp"
|
||||
vllm_config=vllm_config,
|
||||
prefix=f"{prefix}.mlp",
|
||||
reduce_results=not self.use_hc_sequence_parallel,
|
||||
)
|
||||
|
||||
hc_config = HyperConnectionConfig(
|
||||
@@ -294,6 +311,9 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
else:
|
||||
hidden_states, block_input, injection = attn_hc.mix(hidden_states)
|
||||
|
||||
if self.use_hc_sequence_parallel:
|
||||
# Positions retain the full token axis for both text and MRoPE inputs.
|
||||
block_input = sp_all_gather(block_input)[: positions.shape[-1]]
|
||||
if self.layer_type == "linear_attention":
|
||||
attn_out = self.linear_attn(hidden_states=block_input)
|
||||
elif self.layer_type in _QSA_LAYER_TYPES:
|
||||
@@ -305,10 +325,25 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
raise ValueError("Invalid layer_type")
|
||||
|
||||
mlp_hc = self.mlp_hyper_connection
|
||||
if self.use_hc_sequence_parallel:
|
||||
attn_out = sp_reduce_scatter(attn_out)
|
||||
hidden_states, block_input, injection = mlp_hc.combine_and_mix(
|
||||
hidden_states, attn_out, injection
|
||||
)
|
||||
mlp_out = self.mlp(block_input)
|
||||
if self.use_sequence_parallel:
|
||||
# MoE consumes local tokens and returns complete local outputs.
|
||||
mlp_out = self.mlp(block_input, already_sequence_parallel=True)
|
||||
else:
|
||||
if self.use_hc_sequence_parallel:
|
||||
block_input = sp_all_gather(block_input)[: positions.shape[-1]]
|
||||
mlp_out = self.mlp(block_input)
|
||||
if self.use_hc_sequence_parallel:
|
||||
assert isinstance(self.mlp, Qwen4ExpSparseMoeBlock)
|
||||
reduce_output = self.mlp.experts.moe_config.skip_final_all_reduce
|
||||
# Only sum partial outputs. Reduced outputs already include all ranks.
|
||||
mlp_out = (
|
||||
sp_reduce_scatter(mlp_out) if reduce_output else sp_shard(mlp_out)
|
||||
)
|
||||
return hidden_states, mlp_out, injection
|
||||
|
||||
|
||||
@@ -383,6 +418,8 @@ class Qwen4ExpModel(nn.Module):
|
||||
self.num_redundant_experts = (
|
||||
vllm_config.parallel_config.eplb_config.num_redundant_experts
|
||||
)
|
||||
# MoE SP also enables HC SP, while HC SP can be enabled independently.
|
||||
self.use_hc_sequence_parallel = is_hc_sequence_parallel_enabled(vllm_config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self._qsa_layer_ids = frozenset(
|
||||
layer_idx
|
||||
@@ -457,12 +494,18 @@ class Qwen4ExpModel(nn.Module):
|
||||
if input_ids is None:
|
||||
raise ValueError("input_ids or inputs_embeds is required")
|
||||
hidden_states = self.embed_input_ids(input_ids)
|
||||
if self.use_hc_sequence_parallel:
|
||||
# The MoE padding mask stays unsharded: under torch.compile its
|
||||
# update would land only after the graph has run.
|
||||
hidden_states = sp_shard(hidden_states)
|
||||
# Expand only the local token rows when SP is enabled.
|
||||
hidden_states = hidden_states.repeat(1, self.config.hc_count)
|
||||
else:
|
||||
if intermediate_tensors is None:
|
||||
raise ValueError("pipeline stage requires intermediate tensors")
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
full_num_tokens = positions.shape[-1]
|
||||
block_output = None
|
||||
injection = None
|
||||
last_layer = None
|
||||
@@ -485,6 +528,8 @@ class Qwen4ExpModel(nn.Module):
|
||||
deepstack_embed = deepstack_input_embeds[
|
||||
f"deepstack_input_embeds_{layer_idx}"
|
||||
]
|
||||
if self.use_hc_sequence_parallel:
|
||||
deepstack_embed = sp_shard(deepstack_embed)
|
||||
deepstack_embed = (
|
||||
deepstack_embed.unsqueeze(-2)
|
||||
.expand(
|
||||
@@ -519,6 +564,24 @@ class Qwen4ExpModel(nn.Module):
|
||||
multi_hidden, sample_hidden_states, _ = final_mixer.combine_and_mix(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
if self.use_hc_sequence_parallel:
|
||||
if self._mtp_hidden_buffer is not None:
|
||||
# Gather LM-head and MTP states together when both are needed.
|
||||
hidden_size = self.config.hidden_size
|
||||
packed_hidden_states = torch.cat(
|
||||
[sample_hidden_states, multi_hidden], dim=-1
|
||||
)
|
||||
packed_hidden_states = sp_all_gather(packed_hidden_states)[
|
||||
:full_num_tokens
|
||||
]
|
||||
sample_hidden_states, multi_hidden = packed_hidden_states.split(
|
||||
[hidden_size, self.config.hc_count * hidden_size], dim=-1
|
||||
)
|
||||
sample_hidden_states = sample_hidden_states.contiguous()
|
||||
else:
|
||||
sample_hidden_states = sp_all_gather(sample_hidden_states)[
|
||||
:full_num_tokens
|
||||
]
|
||||
if self._mtp_hidden_buffer is not None:
|
||||
# Capture the pre-final-mixer multi-stream hidden state
|
||||
# [T, hc_count*H] for the MTP drafter (zero extra compute:
|
||||
@@ -574,6 +637,7 @@ class Qwen4ExpModel(nn.Module):
|
||||
class Qwen4ExpForCausalLM(
|
||||
nn.Module,
|
||||
HasInnerState,
|
||||
SupportsHCSP,
|
||||
SupportsLoRA,
|
||||
SupportsMRoPE,
|
||||
SupportsPP,
|
||||
@@ -806,6 +870,7 @@ class Qwen4ExpProcessingInfo(Qwen3VLProcessingInfo):
|
||||
class Qwen4ExpForConditionalGeneration(
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
HasInnerState,
|
||||
SupportsHCSP,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
):
|
||||
"""Qwen3-VL vision tower backed by the Qwen4Exp language model."""
|
||||
|
||||
@@ -34,7 +34,11 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.utils import configure_quant_config
|
||||
from vllm.model_executor.models.interfaces import LocalArgmaxMixin, SupportsPP
|
||||
from vllm.model_executor.models.interfaces import (
|
||||
LocalArgmaxMixin,
|
||||
SupportsHCSP,
|
||||
SupportsPP,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5Model
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
@@ -45,8 +49,10 @@ from vllm.model_executor.models.utils import (
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.models.common.ops.sequence_parallel import sp_all_gather, sp_shard
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from ..common.hyperconnection import is_hc_sequence_parallel_enabled
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
@@ -181,6 +187,8 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
config: Qwen4ExpTextConfig = model_config.hf_text_config
|
||||
|
||||
self.config = config
|
||||
# MoE SP also enables HC SP, while HC SP can be enabled independently.
|
||||
self.use_hc_sequence_parallel = is_hc_sequence_parallel_enabled(vllm_config)
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
@@ -321,6 +329,9 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
full_num_tokens = positions.shape[-1]
|
||||
if self.use_hc_sequence_parallel:
|
||||
hidden_states = sp_shard(hidden_states)
|
||||
layer = self.layers[current_step_idx]
|
||||
hidden_states, block_output, injection = layer(
|
||||
hidden_states=hidden_states,
|
||||
@@ -348,6 +359,17 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
)
|
||||
if self.use_hc_sequence_parallel:
|
||||
# Gather both outputs together, then restore their contiguous layouts.
|
||||
packed_hidden_states = torch.cat(
|
||||
[sample_hidden_states, multi_hidden], dim=-1
|
||||
)
|
||||
packed_hidden_states = sp_all_gather(packed_hidden_states)[:full_num_tokens]
|
||||
sample_hidden_states, multi_hidden = packed_hidden_states.split(
|
||||
[hidden_size, hc_count * hidden_size], dim=-1
|
||||
)
|
||||
sample_hidden_states = sample_hidden_states.contiguous()
|
||||
multi_hidden = multi_hidden.contiguous()
|
||||
return sample_hidden_states, multi_hidden
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
@@ -377,7 +399,13 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMTP(LocalArgmaxMixin, nn.Module, SupportsPP, Qwen4ExpMixtureOfExperts):
|
||||
class Qwen4ExpMTP(
|
||||
LocalArgmaxMixin,
|
||||
nn.Module,
|
||||
SupportsHCSP,
|
||||
SupportsPP,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.models.common.ops import sequence_parallel as common_sp
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
|
||||
def _sp_shard_op(x: torch.Tensor) -> torch.Tensor:
|
||||
output = common_sp.sp_shard(x)
|
||||
# A functional custom op must not return a view of its input.
|
||||
unpadded = x.shape[0] % get_tensor_model_parallel_world_size() == 0
|
||||
return output.clone() if unpadded else output
|
||||
|
||||
|
||||
def _sp_local_fake(x: torch.Tensor) -> torch.Tensor:
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
return x.new_empty((cdiv(x.shape[0], tp_size), *x.shape[1:]))
|
||||
|
||||
|
||||
# Dynamo would specialize the padding branch on the traced token count, and
|
||||
# vLLM drops the resulting guards. Keep the branch opaque when compiling.
|
||||
direct_register_custom_op(
|
||||
op_name="sp_reduce_scatter",
|
||||
op_func=common_sp.sp_reduce_scatter,
|
||||
fake_impl=_sp_local_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="sp_shard",
|
||||
op_func=_sp_shard_op,
|
||||
fake_impl=_sp_local_fake,
|
||||
)
|
||||
|
||||
|
||||
def sp_reduce_scatter(x: torch.Tensor) -> torch.Tensor:
|
||||
if torch.compiler.is_compiling():
|
||||
return torch.ops.vllm.sp_reduce_scatter(x)
|
||||
return common_sp.sp_reduce_scatter(x)
|
||||
|
||||
|
||||
def sp_shard(x: torch.Tensor) -> torch.Tensor:
|
||||
if torch.compiler.is_compiling():
|
||||
return torch.ops.vllm.sp_shard(x)
|
||||
return common_sp.sp_shard(x)
|
||||
@@ -9,6 +9,7 @@ from torch import nn
|
||||
from transformers import Qwen4ExpTextConfig
|
||||
|
||||
from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config
|
||||
from vllm.distributed import get_etp_group, get_tp_group
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
|
||||
@@ -21,7 +22,13 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import is_fp8
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm.models.common.ops.sequence_parallel import (
|
||||
sp_all_gather,
|
||||
sp_reduce_scatter,
|
||||
sp_shard,
|
||||
)
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.attention.backends.short_conv_attn import (
|
||||
@@ -182,8 +189,10 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
data_parallel_rank: int = 0,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
params_dtype: torch.dtype | None = None,
|
||||
use_sequence_parallel: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.use_sequence_parallel = use_sequence_parallel
|
||||
self.embedding_dim = embedding_dim
|
||||
self.layer_name = layer_name
|
||||
self.ngram_size = int(config.ngram_size)
|
||||
@@ -253,6 +262,11 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
if engram_config is not None and engram_config.cpu_offload
|
||||
else Qwen4ExpPLEDeviceEmbedding
|
||||
)
|
||||
# A TP reduce-scatter covers all vocabulary owners only when ETP=TP.
|
||||
self.use_reduce_scatter = (
|
||||
self.use_sequence_parallel
|
||||
and get_etp_group().world_size == get_tp_group().world_size
|
||||
)
|
||||
self.ngram_embedding = embedding_cls(
|
||||
padded_vocab_size,
|
||||
self.head_dim,
|
||||
@@ -263,6 +277,7 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
num_ngram_heads=self.ngram_heads,
|
||||
max_total_tokens=max_total_tokens,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
reduce_results=not self.use_reduce_scatter,
|
||||
)
|
||||
logger.info(
|
||||
"Initialized AMD PLE embedding %s: quantization_method=%s, "
|
||||
@@ -274,12 +289,25 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
self.ngram_embedding.weight.is_pinned(),
|
||||
)
|
||||
|
||||
def _sp_shard_embeddings(self, embeddings: torch.Tensor) -> torch.Tensor:
|
||||
"""Shard embedding token rows, optionally reducing vocabulary contributions."""
|
||||
# Each embedding element has one vocabulary owner, including FP8 bytes.
|
||||
output_dtype = embeddings.dtype
|
||||
if is_fp8(embeddings):
|
||||
embeddings = embeddings.view(torch.int8)
|
||||
if self.use_reduce_scatter:
|
||||
embeddings = sp_reduce_scatter(embeddings)
|
||||
else:
|
||||
embeddings = sp_shard(embeddings)
|
||||
return embeddings.view(output_dtype)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
ngram_context: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Return full embeddings or a token shard after combining vocabulary owners."""
|
||||
input_ids = input_ids.reshape(-1)
|
||||
ngram_ids = input_ids.new_empty(
|
||||
(input_ids.shape[0], self.ngram_heads), dtype=torch.int64
|
||||
@@ -302,17 +330,19 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
output,
|
||||
self.layer_name,
|
||||
)
|
||||
else:
|
||||
output = ngram_ids.new_empty(
|
||||
(ngram_ids.shape[0], self.embedding_dim),
|
||||
dtype=embedding.params_dtype,
|
||||
)
|
||||
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding(
|
||||
ngram_ids,
|
||||
output,
|
||||
self.layer_name,
|
||||
)
|
||||
if not self.use_sequence_parallel:
|
||||
return output
|
||||
output = ngram_ids.new_empty(
|
||||
(ngram_ids.shape[0], self.embedding_dim),
|
||||
dtype=embedding.params_dtype,
|
||||
)
|
||||
torch.ops.vllm.qwen4_exp_amd_ple_ngram_embedding(
|
||||
ngram_ids,
|
||||
output,
|
||||
self.layer_name,
|
||||
)
|
||||
return output
|
||||
return self._sp_shard_embeddings(output)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load hash buffers and checkpoint-split embedding rows."""
|
||||
@@ -388,8 +418,10 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
layer_idx: int = 0,
|
||||
ple_dense_layer_id: int | None = None,
|
||||
prefix: str = "",
|
||||
use_sequence_parallel: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.use_sequence_parallel = use_sequence_parallel
|
||||
model_config = vllm_config.model_config
|
||||
cache_config = vllm_config.cache_config
|
||||
quant_config = vllm_config.quant_config
|
||||
@@ -420,8 +452,9 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
data_parallel_rank=vllm_config.parallel_config.data_parallel_rank,
|
||||
quant_config=quant_config,
|
||||
params_dtype=model_config.dtype,
|
||||
use_sequence_parallel=self.use_sequence_parallel,
|
||||
)
|
||||
# The PLE cache is TP-replicated, so this merged projection is too.
|
||||
# Projection weights stay replicated even when their token rows are sharded.
|
||||
self.kv_proj = MergedColumnParallelLinear(
|
||||
int(config.ple_embed_dim),
|
||||
[self.hc_hidden_size, self.hidden_size],
|
||||
@@ -486,7 +519,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
self,
|
||||
inputs: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor | None,
|
||||
metadata: PleShortConvAttentionMetadata,
|
||||
conv_state: torch.Tensor,
|
||||
conv_weights: torch.Tensor,
|
||||
@@ -501,7 +534,8 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
has_non_spec = has_prefill or has_decode
|
||||
inputs = inputs[: metadata.num_actual_tokens]
|
||||
residual = residual[: metadata.num_actual_tokens]
|
||||
outer_residual = outer_residual[: metadata.num_actual_tokens]
|
||||
if outer_residual is not None:
|
||||
outer_residual = outer_residual[: metadata.num_actual_tokens]
|
||||
|
||||
spec_token_indices = None
|
||||
non_spec_token_indices = None
|
||||
@@ -553,11 +587,14 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
residual_d, residual_p = torch.split(
|
||||
residual, [num_decode_tokens, num_prefill_tokens], dim=0
|
||||
)
|
||||
outer_residual_d, outer_residual_p = torch.split(
|
||||
outer_residual,
|
||||
[num_decode_tokens, num_prefill_tokens],
|
||||
dim=0,
|
||||
)
|
||||
outer_residual_d: torch.Tensor | None = None
|
||||
outer_residual_p: torch.Tensor | None = None
|
||||
if outer_residual is not None:
|
||||
outer_residual_d, outer_residual_p = torch.split(
|
||||
outer_residual,
|
||||
[num_decode_tokens, num_prefill_tokens],
|
||||
dim=0,
|
||||
)
|
||||
token_indices_d = None
|
||||
token_indices_p = None
|
||||
else:
|
||||
@@ -628,14 +665,16 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
self,
|
||||
inputs: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor | None,
|
||||
) -> None:
|
||||
"""Update convolution state, optionally fusing both residual additions."""
|
||||
forward_context = get_forward_context()
|
||||
attn_metadata = forward_context.attn_metadata
|
||||
# Profiling omits all metadata or this Mamba entry. Short convolution
|
||||
# is a no-op there, but preserve the outer residual addition.
|
||||
if attn_metadata is None:
|
||||
residual.add_(outer_residual)
|
||||
if outer_residual is not None:
|
||||
residual.add_(outer_residual)
|
||||
return
|
||||
|
||||
if not isinstance(attn_metadata, dict):
|
||||
@@ -646,7 +685,8 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
|
||||
layer_attn_metadata = attn_metadata.get(self.prefix)
|
||||
if layer_attn_metadata is None:
|
||||
residual.add_(outer_residual)
|
||||
if outer_residual is not None:
|
||||
residual.add_(outer_residual)
|
||||
return
|
||||
if not isinstance(layer_attn_metadata, PleShortConvAttentionMetadata):
|
||||
raise TypeError(
|
||||
@@ -687,7 +727,10 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
ngram_context: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
input_ids = input_ids.reshape(-1)
|
||||
if input_ids.shape[0] != hidden_states.shape[0]:
|
||||
if (
|
||||
not self.use_sequence_parallel
|
||||
and input_ids.shape[0] != hidden_states.shape[0]
|
||||
):
|
||||
raise ValueError(
|
||||
"PLE expects input_ids and hidden_states to have the same "
|
||||
f"token length, got {input_ids.shape[0]} and "
|
||||
@@ -711,12 +754,23 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
# The short-conv op is a piecewise-graph splitting op: state routing
|
||||
# reads runtime request metadata. It accumulates the convolution and
|
||||
# the outer residual into gated_output.
|
||||
torch.ops.vllm.qwen4_exp_ple_short_conv(
|
||||
conv_input,
|
||||
gated_output,
|
||||
hidden_states,
|
||||
self.prefix,
|
||||
)
|
||||
if self.use_sequence_parallel:
|
||||
# Only convolution needs full tokens. Add residuals on local shards.
|
||||
conv_input = sp_all_gather(conv_input)[: input_ids.shape[0]]
|
||||
# Metadata may omit padding tokens or all tokens during profiling.
|
||||
conv_output = torch.zeros_like(conv_input)
|
||||
torch.ops.vllm.qwen4_exp_ple_short_conv(
|
||||
conv_input, conv_output, None, self.prefix
|
||||
)
|
||||
gated_output.add_(sp_shard(conv_output))
|
||||
gated_output.add_(hidden_states)
|
||||
else:
|
||||
torch.ops.vllm.qwen4_exp_ple_short_conv(
|
||||
conv_input,
|
||||
gated_output,
|
||||
hidden_states,
|
||||
self.prefix,
|
||||
)
|
||||
return gated_output
|
||||
|
||||
|
||||
@@ -787,7 +841,7 @@ def qwen4_exp_amd_ple_ngram_embedding_pinned(
|
||||
def qwen4_exp_ple_short_conv(
|
||||
inputs: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor,
|
||||
outer_residual: torch.Tensor | None,
|
||||
layer_name: str,
|
||||
) -> None:
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
|
||||
@@ -35,6 +35,16 @@ import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
|
||||
def is_hc_sequence_parallel_enabled(vllm_config: VllmConfig) -> bool:
|
||||
"""Enable GR/PLE SP explicitly or automatically with sequence-parallel MoE."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
return parallel_config.tensor_parallel_size > 1 and (
|
||||
parallel_config.enable_hc_sp or parallel_config.use_sequence_parallel_moe
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
"""Shared MTP drafter state for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
from transformers import Qwen4ExpTextConfig
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.transformers_utils.configs.qwen4_exp import Qwen4ExpTextConfig
|
||||
|
||||
|
||||
def make_mtp_hidden_buffer(
|
||||
|
||||
@@ -719,7 +719,11 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
|
||||
slot_size, slot_offset = self._get_dp_gather_slot(ngram_ids.shape[0])
|
||||
gathered_ids = self._gather_dp_ids(ngram_ids, slot_size)
|
||||
embeddings = self._lookup(gathered_ids)
|
||||
embeddings = self._reduce_etp_embeddings(embeddings)
|
||||
if self.reduce_results:
|
||||
embeddings = self._reduce_etp_embeddings(embeddings)
|
||||
else:
|
||||
# The outer TP reduce-scatter requires ETP=TP.
|
||||
assert self.etp_data_parallel_size == 1
|
||||
return self._select_embeddings(
|
||||
embeddings,
|
||||
ngram_ids.shape[0],
|
||||
|
||||
@@ -84,6 +84,7 @@ from vllm.tokenizers.registry import cached_tokenizer_from_config
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
from ..common.hyperconnection import is_hc_sequence_parallel_enabled
|
||||
from ..common.mtp import make_mtp_hidden_buffer
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
@@ -96,14 +97,6 @@ from .qsa import Qwen4ExpQSAAttention
|
||||
_QSA_LAYER_TYPES = ("qwen_sparse_attention", "indexed_attention")
|
||||
|
||||
|
||||
def is_hc_sequence_parallel_enabled(vllm_config: VllmConfig) -> bool:
|
||||
"""Enable GR/PLE SP explicitly or automatically with sequence-parallel MoE."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
return parallel_config.tensor_parallel_size > 1 and (
|
||||
parallel_config.enable_hc_sp or parallel_config.use_sequence_parallel_moe
|
||||
)
|
||||
|
||||
|
||||
def without_modelopt_fp4(
|
||||
quant_config: QuantizationConfig | None,
|
||||
) -> QuantizationConfig | None:
|
||||
|
||||
@@ -58,6 +58,7 @@ from vllm.models.common.ops.sequence_parallel import (
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from ..common.hyperconnection import is_hc_sequence_parallel_enabled
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
@@ -66,7 +67,6 @@ from .model import (
|
||||
Qwen4ExpDecoderLayer,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
is_hc_sequence_parallel_enabled,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user