[Model] Support Qwen3.8-Flash-Next (#53896)
Signed-off-by: huanghaoyan.hhy <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: andyluo7 <andy.luo@amd.com> Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Signed-off-by: Harry Huang <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: Thien Tran <gau.nernst@yahoo.com.sg> Signed-off-by: Isotr0py <Isotr0py@outlook.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Signed-off-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: KungYork <firelikest@163.com> Co-authored-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: andyluo7 <43718156+andyluo7@users.noreply.github.com> Co-authored-by: Isotr0py <mozf@inferact.ai> Co-authored-by: andyluo7 <andy.luo@amd.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: Vadim Gimpelson <156319763+vadiklyutiy@users.noreply.github.com> Co-authored-by: Isotr0py <Isotr0py@outlook.com> Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
zjy0516
KungYork
Thien Tran
Yifan Qiao
andyluo7
Isotr0py
andyluo7
OpenAI Codex
lishunyang12
Vadim Gimpelson
Isotr0py
Lucas Wilkinson
Claude Opus 5
OpenAI Codex
parent
687db59744
commit
e126687a9a
@@ -2817,6 +2817,7 @@ def fused_gdn_decode_post_conv_mtp(
|
||||
out: torch.Tensor | None = None,
|
||||
scale: float = 128**-0.5,
|
||||
norm_eps: float = 1e-5,
|
||||
output_gate_activation: str = "silu",
|
||||
) -> torch.Tensor:
|
||||
if out is None:
|
||||
out = torch.empty_like(output_gate)
|
||||
@@ -2835,6 +2836,7 @@ def fused_gdn_decode_post_conv_mtp(
|
||||
out,
|
||||
scale,
|
||||
norm_eps,
|
||||
output_gate_activation,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@@ -768,6 +768,9 @@ class CompilationConfig:
|
||||
"vllm::mamba_mixer2",
|
||||
"vllm::mamba_mixer",
|
||||
"vllm::short_conv",
|
||||
"vllm::qwen4_exp_compute_ple_ngram_ids",
|
||||
"vllm::qwen4_exp_ple_short_conv",
|
||||
"vllm::qwen4_exp_qsa_with_output",
|
||||
"vllm::linear_attention",
|
||||
"vllm::qwen_gdn_attention_core",
|
||||
"vllm::qwen_gdn_attention_core_fused_norm_packed",
|
||||
|
||||
@@ -215,6 +215,10 @@ class SchedulerConfig:
|
||||
# https://github.com/vllm-project/vllm/issues/29585
|
||||
factors.append(self.max_num_batched_tokens)
|
||||
|
||||
# PLE and other model components allocate static per-request buffers.
|
||||
# Their shapes are captured in compiled graphs.
|
||||
factors.append(self.max_num_seqs)
|
||||
|
||||
hash_str = safe_hash(str(factors).encode(), usedforsecurity=False).hexdigest()
|
||||
return hash_str
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ MTPModelTypes = Literal[
|
||||
"exaone_moe_mtp",
|
||||
"exaone4_5_mtp",
|
||||
"qwen3_next_mtp",
|
||||
"qwen4_exp_mtp",
|
||||
"qwen3_5_mtp",
|
||||
"longcat_flash_mtp",
|
||||
"bailing_hybrid_v3_mtp",
|
||||
@@ -425,6 +426,9 @@ class SpeculativeConfig:
|
||||
"""The specific revision to use for the draft model code on Hugging Face
|
||||
Hub. It can be a branch name, a tag name, or a commit id. If unspecified,
|
||||
will use the default version."""
|
||||
index_share_for_mtp_iteration: bool | None = None
|
||||
"""Override whether MTP iterations reuse the first step's sparse indices.
|
||||
If `None`, use the value from the draft model's Hugging Face config."""
|
||||
|
||||
# Advanced control
|
||||
disable_padded_drafter_batch: bool = False
|
||||
@@ -623,6 +627,15 @@ class SpeculativeConfig:
|
||||
# Convert to tuple to make it hashable
|
||||
factors.append(tuple(layer_ids))
|
||||
|
||||
if self.method == "mtp" and self.draft_model_config is not None:
|
||||
factors.append(
|
||||
getattr(
|
||||
self.draft_model_config.hf_config,
|
||||
"index_share_for_mtp_iteration",
|
||||
False,
|
||||
)
|
||||
)
|
||||
|
||||
hash_str = safe_hash(str(factors).encode(), usedforsecurity=False).hexdigest()
|
||||
return hash_str
|
||||
|
||||
@@ -805,6 +818,27 @@ class SpeculativeConfig:
|
||||
hf_config.update(
|
||||
{"n_predict": n_predict, "architectures": ["Qwen3NextMTP"]}
|
||||
)
|
||||
if hf_config.model_type in {"qwen4_exp", "qwen4_exp_text"}:
|
||||
hf_config.model_type = "qwen4_exp_mtp"
|
||||
if hf_config.model_type == "qwen4_exp_mtp":
|
||||
text_config = get_hf_text_config(hf_config)
|
||||
n_predict = getattr(
|
||||
text_config,
|
||||
"mtp_num_hidden_layers",
|
||||
getattr(text_config, "num_nextn_predict_layers", None),
|
||||
)
|
||||
share_mtp_indices = getattr(
|
||||
text_config, "index_share_for_mtp_iteration", False
|
||||
)
|
||||
hf_config.update(
|
||||
{
|
||||
# hc_count is the HC stream multiplier for Qwen MTP feedback.
|
||||
"hc_mult": int(text_config.hc_count),
|
||||
"n_predict": n_predict,
|
||||
"architectures": ["Qwen4ExpMTP"],
|
||||
"index_share_for_mtp_iteration": share_mtp_indices,
|
||||
}
|
||||
)
|
||||
|
||||
architectures = getattr(hf_config, "architectures", []) or []
|
||||
if initial_architecture == "BailingMoeV3ForCausalLM":
|
||||
@@ -1461,6 +1495,15 @@ class SpeculativeConfig:
|
||||
)
|
||||
)
|
||||
|
||||
if self.index_share_for_mtp_iteration is not None:
|
||||
if self.method != "mtp" or self.draft_model_config is None:
|
||||
raise ValueError(
|
||||
"index_share_for_mtp_iteration is only supported with method='mtp'"
|
||||
)
|
||||
self.draft_model_config.hf_config.index_share_for_mtp_iteration = (
|
||||
self.index_share_for_mtp_iteration
|
||||
)
|
||||
|
||||
if self.method != "dspark" and self.enable_adaptive_verification:
|
||||
raise ValueError("Adaptive verification only supported with DSpark")
|
||||
|
||||
|
||||
@@ -405,6 +405,8 @@ class CustomAllreduce:
|
||||
def should_custom_ar(self, inp: torch.Tensor):
|
||||
if self.disabled or self.world_size > 8:
|
||||
return False
|
||||
if inp.dtype not in (torch.float32, torch.float16, torch.bfloat16):
|
||||
return False
|
||||
inp_size = inp.numel() * inp.element_size()
|
||||
# custom allreduce requires input byte size to be multiples of 16
|
||||
if inp_size % 16 != 0:
|
||||
|
||||
@@ -72,12 +72,15 @@ from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.utils.network_utils import make_zmq_path
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
iter_layer_specs,
|
||||
)
|
||||
from vllm.v1.worker.block_table import BlockTable
|
||||
from vllm.v1.worker.utils import select_common_block_size
|
||||
@@ -118,7 +121,12 @@ class NixlBaseConnectorWorker:
|
||||
# NIXL regions per SSM layer = conv sub-projections + 1 SSM temporal
|
||||
# (Mamba2/GDN: 3+1=4; Mamba1: 1+1=2).
|
||||
ssm_regions_per_layer = len(self._conv_decomp.local_conv_offsets) + 1
|
||||
num_ssm_regions = len(self.block_len_per_layer) * ssm_regions_per_layer
|
||||
# Count only the regions that actually hold SSM state; must match
|
||||
# the descriptors emitted by _build_mamba_local.
|
||||
num_ssm_regions = (
|
||||
len(self._ssm_region_indices or self.block_len_per_layer)
|
||||
* ssm_regions_per_layer
|
||||
)
|
||||
|
||||
num_blocks = dst_num_blocks
|
||||
if block_size_ratio is not None:
|
||||
@@ -146,12 +154,19 @@ class NixlBaseConnectorWorker:
|
||||
all_descs: list[np.ndarray] = []
|
||||
for i, group in enumerate(block_ids):
|
||||
group_arr = np.asarray(group)
|
||||
if _is_attention_spec(self._group_spec_types[i]):
|
||||
fa_region_ids = np.arange(self.num_regions)[:, None]
|
||||
spec_type = self._group_spec_types[i]
|
||||
if _is_attention_spec(spec_type):
|
||||
# A scratch cache lives only in its own regions; every other
|
||||
# attention group spans all of them.
|
||||
fa_region_ids = (
|
||||
np.asarray(self._scratch_region_indices, dtype=np.int64)
|
||||
if spec_type is CircularBufferSpec
|
||||
else np.arange(self.num_regions)
|
||||
)[:, None]
|
||||
all_descs.append(
|
||||
(fa_region_ids * num_blocks + group_arr[None, :]).flatten()
|
||||
)
|
||||
elif _is_ssm_spec(self._group_spec_types[i]):
|
||||
elif _is_ssm_spec(spec_type):
|
||||
# NOTE (NickLucche) SSM and Attention block regions can
|
||||
# be exchanged arbitrarily by manager. Therefore, descs
|
||||
# are laid out as:
|
||||
@@ -159,7 +174,11 @@ class NixlBaseConnectorWorker:
|
||||
# num_fa_descs offset must be computed per-engine since
|
||||
# P and D can have different num_blocks (and thus
|
||||
# different FA desc counts).
|
||||
ssm_region_ids = np.arange(num_ssm_regions)[:, None]
|
||||
ssm_region_ids = (
|
||||
np.arange(num_ssm_regions, num_ssm_regions + 1)
|
||||
if i == self._ple_group_index
|
||||
else np.arange(num_ssm_regions)
|
||||
)[:, None]
|
||||
all_descs.append(
|
||||
(
|
||||
ssm_region_ids * logical_blocks
|
||||
@@ -206,6 +225,10 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
# Per-FA-descriptor replicate flag, in _build_fa_local emission order.
|
||||
fa_desc_replicated = self._fa_desc_replicated(num_fa_descs)
|
||||
sharded_desc_end = len(src_blocks_data) - (
|
||||
self._logical_num_blocks if self._ple_region_index is not None else 0
|
||||
)
|
||||
assert num_fa_descs <= sharded_desc_end
|
||||
|
||||
assert block_size_ratio == 1 or fa_num_splits == 1 or all(fa_desc_replicated), (
|
||||
"Head-sharded attention reads with P_TP > D_TP and heterogeneous "
|
||||
@@ -226,9 +249,11 @@ class NixlBaseConnectorWorker:
|
||||
# SPLIT (full-attn): this rank's head slice.
|
||||
chunk = local_len // fa_num_splits
|
||||
handle.append((addr + fa_slot * chunk, chunk, dev))
|
||||
else:
|
||||
elif j < sharded_desc_end:
|
||||
chunk = local_len // ssm_num_splits
|
||||
handle.append((addr + p_idx * chunk, chunk, dev))
|
||||
else:
|
||||
handle.append((addr, local_len, dev))
|
||||
yield handle
|
||||
|
||||
def _needs_split_local_xfer_handles(self, tp_ratio: int, plan: TPMapping) -> bool:
|
||||
@@ -307,19 +332,22 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
)
|
||||
|
||||
self.kv_cache_config = kv_cache_config
|
||||
# Per-layer specs, unwrapping UniformTypeKVCacheSpecs group wrappers.
|
||||
self._layer_specs: dict[str, KVCacheSpec] = {}
|
||||
for group in kv_cache_config.transfer_groups:
|
||||
group_spec = group.kv_cache_spec
|
||||
if isinstance(group_spec, UniformTypeKVCacheSpecs):
|
||||
self._layer_specs.update(group_spec.kv_cache_specs)
|
||||
else:
|
||||
self._layer_specs.update(dict.fromkeys(group.layer_names, group_spec))
|
||||
self._is_hma_required = (
|
||||
not vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
and any(
|
||||
not isinstance(g.kv_cache_spec, FullAttentionSpec)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
not isinstance(spec, FullAttentionSpec)
|
||||
for spec in self._layer_specs.values()
|
||||
)
|
||||
)
|
||||
self.kv_cache_config = kv_cache_config
|
||||
self._layer_specs = {
|
||||
layer: group.kv_cache_spec
|
||||
for group in kv_cache_config.transfer_groups
|
||||
for layer in group.layer_names
|
||||
}
|
||||
|
||||
# ---- Model state (derived from model config) ----
|
||||
mamba_ssm_size = (0, 0)
|
||||
@@ -328,9 +356,29 @@ class NixlBaseConnectorWorker:
|
||||
# conv sub-projections are contiguous in memory.
|
||||
self._conv_decomp: MambaConvSplitInfo | None = None
|
||||
self._has_mamba = any(
|
||||
isinstance(g.kv_cache_spec, MambaSpec)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
isinstance(spec, MambaSpec) for spec in self._layer_specs.values()
|
||||
)
|
||||
self._is_csa_linear = any(
|
||||
get_representative_spec_type(group.kv_cache_spec) is CircularBufferSpec
|
||||
for group in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
self._ple_group_index: int | None = None
|
||||
if self._is_csa_linear:
|
||||
ple_groups = [
|
||||
(index, group)
|
||||
for index, group in enumerate(kv_cache_config.kv_cache_groups)
|
||||
if group.layer_names
|
||||
and all(
|
||||
isinstance(spec, MambaSpec) and spec.tp_replicated
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
]
|
||||
if len(ple_groups) != 1 or len(ple_groups[0][1].layer_names) != 1:
|
||||
raise ValueError(
|
||||
"CSA-linear NIXL requires exactly one PLE cache owner."
|
||||
)
|
||||
self._ple_group_index = ple_groups[0][0]
|
||||
|
||||
if self._has_mamba:
|
||||
assert self._is_hma_required
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
@@ -345,6 +393,7 @@ class NixlBaseConnectorWorker:
|
||||
spec
|
||||
for spec in self._layer_specs.values()
|
||||
if isinstance(spec, MambaSpec)
|
||||
and (not self._is_csa_linear or not spec.tp_replicated)
|
||||
)
|
||||
self._conv_decomp = derive_mamba_conv_split(
|
||||
mamba_spec,
|
||||
@@ -579,6 +628,12 @@ class NixlBaseConnectorWorker:
|
||||
# (MLA), False -> SPLIT (head-sharded full-attn). Mixed only for models
|
||||
# combining both (e.g. GQA main + MLA Eagle-3 draft).
|
||||
self._region_is_mla = list[bool]()
|
||||
self._ssm_region_indices = list[int]()
|
||||
# Regions holding a scratch cache (the CSA compressor circular buffer).
|
||||
# Tracked explicitly because a scratch page shares its address with the
|
||||
# page it overlays, so its regions cannot be recovered from spec type.
|
||||
self._scratch_region_indices = list[int]()
|
||||
self._ple_region_index: int | None = None
|
||||
|
||||
# Enable different block lengths for different layers *only* when MLA is used.
|
||||
# This is not used for SSM layers, which use the counterpart `mamba_ssm_size`.
|
||||
@@ -632,6 +687,24 @@ class NixlBaseConnectorWorker:
|
||||
self.block_size = kernel_block_size
|
||||
self.num_blocks *= self._physical_blocks_per_logical_kv_block
|
||||
|
||||
def _validate_csa_linear_tp_layout(self, remote_tp_size: int) -> None:
|
||||
"""Reject P/D pairs whose main-KV pages have different head layouts.
|
||||
|
||||
A rank at TP < total KV heads holds several heads per page, while a
|
||||
rank at TP >= total KV heads holds exactly one (replicated beyond
|
||||
that). CSA-linear pages are shared tensors that transfer as whole
|
||||
block units, so endpoints on opposite sides of that boundary lay
|
||||
them out differently and cannot exchange them.
|
||||
"""
|
||||
assert self.transfer_topo is not None
|
||||
total_kv_heads = self.transfer_topo.total_num_kv_heads
|
||||
if (self.world_size < total_kv_heads) != (remote_tp_size < total_kv_heads):
|
||||
raise ValueError(
|
||||
"CSA-linear NIXL requires both endpoints on the same side of "
|
||||
f"the KV-head sharding boundary ({total_kv_heads} KV heads): "
|
||||
f"got local TP {self.world_size}, remote TP {remote_tp_size}."
|
||||
)
|
||||
|
||||
def _nixl_handshake(
|
||||
self,
|
||||
host: str,
|
||||
@@ -643,6 +716,8 @@ class NixlBaseConnectorWorker:
|
||||
notif_agents_only: bool = False,
|
||||
) -> tuple[dict[tuple[int, int], str], float]:
|
||||
"""Do a NIXL handshake with a remote instance."""
|
||||
if self._is_csa_linear:
|
||||
self._validate_csa_linear_tp_layout(remote_tp_size)
|
||||
|
||||
# the first time we connect to a remote agent.
|
||||
# be careful, the handshake happens in a background thread.
|
||||
@@ -1034,6 +1109,11 @@ class NixlBaseConnectorWorker:
|
||||
transfer_mode=self._TRANSFER_MODE,
|
||||
)
|
||||
|
||||
if self._is_csa_linear and self.use_host_buffer:
|
||||
raise NotImplementedError(
|
||||
"NIXL host staging does not preserve CSA-linear shared tensors."
|
||||
)
|
||||
|
||||
if self.use_host_buffer:
|
||||
self.initialize_host_xfer_buffer(kv_caches=kv_caches)
|
||||
assert len(self.host_xfer_buffers) == len(kv_caches), (
|
||||
@@ -1059,8 +1139,14 @@ class NixlBaseConnectorWorker:
|
||||
caches_data = []
|
||||
seen_storage_addresses: set[int] = set()
|
||||
seen_base_addresses: list[int] = []
|
||||
self._ssm_region_indices = []
|
||||
self._scratch_region_indices = []
|
||||
self._ple_region_index = None
|
||||
|
||||
packed_storage = _share_storage_and_block_stride(list(xfer_buffers.values()))
|
||||
# CSA-linear needs separate logical regions for attention and state
|
||||
# aliases even though every view shares one block-major allocation.
|
||||
packed_storage = packed_storage and not self._is_csa_linear
|
||||
|
||||
# K and V are packed into the content dim, so each attention layer is a
|
||||
# single NIXL region whose block transfers as one unit. Mamba layers instead
|
||||
@@ -1112,14 +1198,16 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
|
||||
if isinstance(layer_spec, MambaSpec):
|
||||
physical_ratio = self._physical_blocks_per_logical_kv_block
|
||||
block_len = physical_page_size // physical_ratio
|
||||
block_stride = physical_page_size
|
||||
if self._is_csa_linear and cache.ndim != 1:
|
||||
# CSA-linear packs multiple cache owners in each block, so
|
||||
# state views advance by the packed block stride.
|
||||
block_stride = cache.stride(0) * cache.element_size()
|
||||
assert block_stride % physical_ratio == 0
|
||||
region_specs = [
|
||||
(
|
||||
cache.data_ptr(),
|
||||
physical_page_size
|
||||
// self._physical_blocks_per_logical_kv_block,
|
||||
physical_page_size
|
||||
// self._physical_blocks_per_logical_kv_block,
|
||||
)
|
||||
(cache.data_ptr(), block_len, block_stride // physical_ratio)
|
||||
]
|
||||
else:
|
||||
if cache.ndim == 1:
|
||||
@@ -1131,19 +1219,18 @@ class NixlBaseConnectorWorker:
|
||||
block_stride = cache.stride(0) * cache.element_size()
|
||||
storage_is_block_major = num_blocks * block_stride == storage.nbytes()
|
||||
# A layer whose [H, N, C] interior is dense addresses its own page
|
||||
# as one chunk, so it can own a region. When it does not, or when
|
||||
# every layer is packed into this one storage, the block's whole
|
||||
# row is the only contiguous unit.
|
||||
# as one chunk. Otherwise the block's whole row is the only
|
||||
# contiguous transfer unit.
|
||||
hnc_contiguous = (
|
||||
cache.ndim == 4
|
||||
and cache.stride(2) == cache.shape[3]
|
||||
and cache.stride(1) == cache.shape[2] * cache.shape[3]
|
||||
)
|
||||
if storage_is_block_major and (
|
||||
(packed_storage and is_mla_region) or not hnc_contiguous
|
||||
(packed_storage and is_mla_region)
|
||||
or (not hnc_contiguous and not self._is_csa_linear)
|
||||
):
|
||||
# TODO(Lucas): handle TP slicing for packed_storage; for now
|
||||
# restrict to MLA (DSv4) where kv is replicated.
|
||||
# Packed MLA layouts transfer the complete storage row.
|
||||
storage_block_len = storage.nbytes() // num_blocks
|
||||
region_specs = [
|
||||
(storage_addr, storage_block_len, storage_block_len)
|
||||
@@ -1170,17 +1257,27 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
for base_addr, block_len, block_stride in region_specs:
|
||||
if base_addr in seen_base_addresses:
|
||||
if is_mla_region:
|
||||
# Dual-purpose HMA tensor: an MLA layer shares a region
|
||||
# that a non-MLA layer registered first. MLA is not
|
||||
# head-sharded, so the region must be flagged MLA.
|
||||
idx = seen_base_addresses.index(base_addr)
|
||||
self._region_is_mla[idx] = True
|
||||
continue
|
||||
seen_base_addresses.append(base_addr)
|
||||
self.block_len_per_layer.append(block_len)
|
||||
self.block_stride_per_layer.append(block_stride)
|
||||
self._region_is_mla.append(is_mla_region)
|
||||
region_index = seen_base_addresses.index(base_addr)
|
||||
self._region_is_mla[region_index] |= is_mla_region
|
||||
else:
|
||||
region_index = len(seen_base_addresses)
|
||||
seen_base_addresses.append(base_addr)
|
||||
self.block_len_per_layer.append(block_len)
|
||||
self.block_stride_per_layer.append(block_stride)
|
||||
self._region_is_mla.append(is_mla_region)
|
||||
|
||||
if isinstance(layer_spec, MambaSpec):
|
||||
if layer_spec.tp_replicated:
|
||||
assert self._is_csa_linear
|
||||
assert self._ple_region_index in (None, region_index)
|
||||
self._ple_region_index = region_index
|
||||
elif region_index not in self._ssm_region_indices:
|
||||
self._ssm_region_indices.append(region_index)
|
||||
elif (
|
||||
isinstance(layer_spec, CircularBufferSpec)
|
||||
and region_index not in self._scratch_region_indices
|
||||
):
|
||||
self._scratch_region_indices.append(region_index)
|
||||
|
||||
# When there's a mismatch between kbs<>bs, we rely on HMA to ensure
|
||||
# caches are either [NB, PS] or [NB*r, PS/r] where r is bs/kbs.
|
||||
@@ -1210,6 +1307,8 @@ class NixlBaseConnectorWorker:
|
||||
== len(self._region_is_mla)
|
||||
== len(self.block_stride_per_layer)
|
||||
)
|
||||
# Descriptor ids must be region-ordered, matching the remote side.
|
||||
self._scratch_region_indices.sort()
|
||||
|
||||
self.kv_caches_base_addr[self.engine_id][self.tp_rank] = seen_base_addresses
|
||||
self.num_regions = len(seen_base_addresses)
|
||||
@@ -1324,17 +1423,26 @@ class NixlBaseConnectorWorker:
|
||||
physical_per_logical = self._physical_blocks_per_logical_kv_block
|
||||
device_id = self.device_id
|
||||
block_arange = np.arange(num_blocks, dtype=np.uint64)
|
||||
|
||||
parts: list[np.ndarray] = []
|
||||
for i, base_addr in enumerate(base_addresses):
|
||||
# Jump one page_size, but ssm page_size may be bigger when kernel
|
||||
# locks block size to a specific value (physical_per_logical scale).
|
||||
page_stride = self.block_len_per_layer[i] * physical_per_logical
|
||||
blk_addrs = base_addr + block_arange * page_stride
|
||||
|
||||
region_indices = self._ssm_region_indices or range(len(base_addresses))
|
||||
for i in region_indices:
|
||||
base_addr = base_addresses[i]
|
||||
block_stride = self.block_stride_per_layer[i] * physical_per_logical
|
||||
blk_addrs = base_addr + block_arange * block_stride
|
||||
for off, sz in conv_offsets:
|
||||
parts.append(self._stack_descs(blk_addrs + off, sz, device_id))
|
||||
# SSM temporal state follows the conv state.
|
||||
parts.append(self._stack_descs(blk_addrs + conv_size, ssm_size, device_id))
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
block_len = self.block_len_per_layer[region_index] * physical_per_logical
|
||||
block_stride = (
|
||||
self.block_stride_per_layer[region_index] * physical_per_logical
|
||||
)
|
||||
block_addrs = base_addresses[region_index] + block_arange * block_stride
|
||||
parts.append(self._stack_descs(block_addrs, block_len, self.device_id))
|
||||
|
||||
return np.concatenate(parts)
|
||||
|
||||
def _build_mamba_remote(
|
||||
@@ -1370,14 +1478,44 @@ class NixlBaseConnectorWorker:
|
||||
parts: list[np.ndarray] = []
|
||||
# NOTE (ZhanqiuHu): use per-layer block_lens[i], not [0], in case
|
||||
# block lengths vary across layers (e.g. MLA).
|
||||
for i, base_addr in enumerate(nixl_agent_meta.kv_caches_base_addr):
|
||||
page_stride = nixl_agent_meta.block_lens[i] * remote_physical_per_logical
|
||||
blk_addrs = base_addr + block_arange * page_stride
|
||||
region_indices = self._ssm_region_indices or range(
|
||||
len(nixl_agent_meta.kv_caches_base_addr)
|
||||
)
|
||||
for i in region_indices:
|
||||
base_addr = nixl_agent_meta.kv_caches_base_addr[i]
|
||||
block_stride = (
|
||||
nixl_agent_meta.block_strides[i] * remote_physical_per_logical
|
||||
)
|
||||
blk_addrs = base_addr + block_arange * block_stride
|
||||
for off, sz in conv_offsets:
|
||||
parts.append(self._stack_descs(blk_addrs + off, sz, device_id))
|
||||
# SSM temporal state is also TP-sharded on the heads dimension.
|
||||
ssm_addrs = blk_addrs + conv_size_remote + local_offset * ssm_read_size
|
||||
parts.append(self._stack_descs(ssm_addrs, ssm_read_size, device_id))
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
local_block_len = (
|
||||
self.block_len_per_layer[region_index]
|
||||
* self._physical_blocks_per_logical_kv_block
|
||||
)
|
||||
remote_block_len = (
|
||||
nixl_agent_meta.block_lens[region_index] * remote_physical_per_logical
|
||||
)
|
||||
if local_block_len != remote_block_len:
|
||||
raise ValueError(
|
||||
"PLE pages require identical P/D geometry: "
|
||||
f"local={local_block_len}, remote={remote_block_len}."
|
||||
)
|
||||
remote_block_stride = (
|
||||
nixl_agent_meta.block_strides[region_index]
|
||||
* remote_physical_per_logical
|
||||
)
|
||||
block_addrs = (
|
||||
nixl_agent_meta.kv_caches_base_addr[region_index]
|
||||
+ block_arange * remote_block_stride
|
||||
)
|
||||
parts.append(self._stack_descs(block_addrs, remote_block_len, device_id))
|
||||
|
||||
return np.concatenate(parts)
|
||||
|
||||
@staticmethod
|
||||
@@ -2410,8 +2548,7 @@ class NixlBaseConnectorWorker:
|
||||
group_specs = self.kv_cache_config.transfer_groups
|
||||
physical_block_ids = []
|
||||
for i, group in enumerate(block_ids):
|
||||
spec = group_specs[i].kv_cache_spec
|
||||
if isinstance(spec, MambaSpec):
|
||||
if _is_ssm_spec(get_representative_spec_type(group_specs[i].kv_cache_spec)):
|
||||
physical_block_ids.append(group)
|
||||
else:
|
||||
physical_block_ids.append(
|
||||
|
||||
@@ -536,7 +536,8 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
def group_ids(block_ids: BlockIds, rank: int) -> BlockIds:
|
||||
return [
|
||||
list(block_ids[g])
|
||||
if (replicate_attn and _is_attention_spec(self._group_spec_types[g]))
|
||||
if (self._is_csa_linear and tp_ratio < 0)
|
||||
or (replicate_attn and _is_attention_spec(self._group_spec_types[g]))
|
||||
or rank in plan.source_ranks_per_group[g]
|
||||
else []
|
||||
for g in range(num_groups)
|
||||
|
||||
@@ -39,6 +39,7 @@ from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
is_deep_gemm_e8m0_used,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
FP8_DTYPE,
|
||||
QuantKey,
|
||||
kFp8Dynamic128Sym,
|
||||
kFp8DynamicTensorSym,
|
||||
@@ -153,6 +154,19 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
|
||||
(kFp8StaticTensorSym, kFp8StaticTensorSym),
|
||||
(kFp8StaticTensorSym, kFp8DynamicTensorSym),
|
||||
]
|
||||
# Block-quantized FP8 with arbitrary block shape: the Triton
|
||||
# kernels take the block shape as a runtime argument.
|
||||
if (
|
||||
weight_key is not None
|
||||
and activation_key == kFp8Dynamic128Sym
|
||||
and weight_key.dtype == FP8_DTYPE
|
||||
and weight_key.symmetric
|
||||
and weight_key.scale.static
|
||||
and weight_key.scale.dtype == torch.float32
|
||||
and weight_key.scale.group_shape.row > 1
|
||||
and weight_key.scale.group_shape.col > 1
|
||||
):
|
||||
return True
|
||||
return (weight_key, activation_key) in supported
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import math
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
@@ -268,6 +269,39 @@ def map_fp8_backend(runner_backend: MoEBackend) -> Fp8MoeBackend:
|
||||
)
|
||||
|
||||
|
||||
def refine_fp8_moe_block_shape(
|
||||
config: FusedMoEConfig,
|
||||
weight_block_size: list[int],
|
||||
) -> list[int] | None:
|
||||
"""
|
||||
Compute a refined block shape for block-quantized FP8 MoE weights whose
|
||||
checkpoint blocks cannot be sharded exactly across TP ranks.
|
||||
|
||||
TP shards the intermediate dim of the expert weights, so a per-shard size
|
||||
that is not a multiple of the checkpoint's block size makes the
|
||||
checkpoint's block scales impossible to shard exactly. When a finer block
|
||||
size (>= 32) divides both the checkpoint blocks and all involved dims,
|
||||
the weight scales can be refined to that granularity at load time (a
|
||||
lossless upsampling, since the refined block divides the checkpoint
|
||||
block). Only Triton-based kernels can consume the refined block shape:
|
||||
they take it as a runtime argument, while the other backends require the
|
||||
native 128x128 blocks. The refined shape is encoded in the QuantKey used
|
||||
for backend selection, so backends that only support 128x128 blocks are
|
||||
rejected by the oracle automatically.
|
||||
|
||||
Returns the refined [block_n, block_k] shape, or None if no refinement
|
||||
is needed or possible.
|
||||
"""
|
||||
block_n, block_k = weight_block_size
|
||||
ispp = config.intermediate_size_per_partition
|
||||
if ispp % block_n == 0 and (config.tp_size == 1 or ispp % block_k == 0):
|
||||
return None
|
||||
refine = math.gcd(block_n, block_k, ispp, config.hidden_dim)
|
||||
if refine < 32:
|
||||
return None
|
||||
return [refine, refine]
|
||||
|
||||
|
||||
def select_fp8_moe_backend(
|
||||
config: FusedMoEConfig,
|
||||
weight_key: QuantKey | None,
|
||||
|
||||
@@ -474,6 +474,39 @@ def _get_requested_backends(
|
||||
return _filter_by_activation(backends, requested_activation_key)
|
||||
|
||||
|
||||
def _requires_qwen38_tep8_emulation(
|
||||
config: FusedMoEConfig,
|
||||
activation_key: QuantKey | None,
|
||||
) -> bool:
|
||||
"""Avoid the inaccurate native gfx950 kernel for Qwen3.8 TEP8.
|
||||
|
||||
Qwen3.8 Flash Next's routed experts use the distinctive
|
||||
``E=512, H=2560, N=640`` W4A4 shape. With eight-way expert parallelism,
|
||||
AITER operates on 64 local experts and pads ``N`` to 768. That native path
|
||||
is not numerically reliable on gfx950, while OCP MX emulation preserves
|
||||
model accuracy. Keep this guard exact so other MXFP4 shapes and smaller EP
|
||||
configurations retain the native backend.
|
||||
"""
|
||||
parallel = config.moe_parallel_config
|
||||
if not (
|
||||
activation_key == kMxfp4Dynamic
|
||||
and parallel.use_ep
|
||||
and parallel.ep_size == 8
|
||||
and config.num_experts == 512
|
||||
and config.num_local_experts == 64
|
||||
and config.hidden_dim == 2560
|
||||
and config.intermediate_size == 640
|
||||
):
|
||||
return False
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
return False
|
||||
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
return on_gfx950()
|
||||
|
||||
|
||||
def select_mxfp4_moe_backend(
|
||||
config: FusedMoEConfig,
|
||||
activation_key: QuantKey | None = None,
|
||||
@@ -532,6 +565,21 @@ def select_mxfp4_moe_backend(
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
|
||||
if _requires_qwen38_tep8_emulation(config, requested_activation_key):
|
||||
backend = Mxfp4MoeBackend.EMULATION
|
||||
logger.warning_once(
|
||||
"Using OCP MX emulation for the Qwen3.8 Flash Next TEP8 routed "
|
||||
"experts on gfx950 because the native AITER W4A4 kernel is not "
|
||||
"numerically reliable for this shape. Performance will be lower."
|
||||
)
|
||||
return _return_or_raise(
|
||||
backend,
|
||||
config,
|
||||
kMxfp4Static,
|
||||
requested_activation_key,
|
||||
activation_format,
|
||||
)
|
||||
|
||||
# Select kernels in order of backend.
|
||||
AVAILABLE_BACKENDS = _filter_by_activation(
|
||||
_get_priority_backends_for_gpt_oss(), requested_activation_key
|
||||
|
||||
@@ -345,14 +345,13 @@ def convert_to_unquantized_kernel_format(
|
||||
|
||||
elif unquantized_backend == UnquantizedMoeBackend.FLASHINFER_TRTLLM:
|
||||
is_act_and_mul = moe_config.is_act_and_mul
|
||||
if not is_act_and_mul:
|
||||
# Kernel requires intermediate_size_per_partition % 128 == 0 (BlockMajorK
|
||||
# weight layout uses block_k=128). Pad along the intermediate dim when
|
||||
# the model + TP split don't satisfy the constraint.
|
||||
w13_weight, w2_weight, padded_intermediate = align_moe_weights_for_fi(
|
||||
w13_weight, w2_weight, is_act_and_mul, min_alignment=128
|
||||
)
|
||||
moe_config.intermediate_size_per_partition = padded_intermediate
|
||||
# Kernel requires intermediate_size_per_partition % 128 == 0 (BlockMajorK
|
||||
# weight layout uses block_k=128). Pad along the intermediate dim when
|
||||
# the model + TP split don't satisfy the constraint.
|
||||
w13_weight, w2_weight, padded_intermediate = align_moe_weights_for_fi(
|
||||
w13_weight, w2_weight, is_act_and_mul, min_alignment=128
|
||||
)
|
||||
moe_config.intermediate_size_per_partition = padded_intermediate
|
||||
|
||||
_cache_permute_indices: dict[torch.Size, torch.Tensor] = {}
|
||||
w13_weight, w2_weight = convert_moe_weights_to_flashinfer_trtllm_block_layout(
|
||||
|
||||
@@ -832,6 +832,20 @@ class RoutedExperts(PluggableLayer):
|
||||
FusedMoeWeightScaleSupported.GROUP.value,
|
||||
FusedMoeWeightScaleSupported.BLOCK.value,
|
||||
]:
|
||||
scale_refine = getattr(self.quant_method, "weight_scale_refine", None)
|
||||
if (
|
||||
quant_method == FusedMoeWeightScaleSupported.BLOCK.value
|
||||
and scale_refine is not None
|
||||
):
|
||||
# FP8 block scales are stored per (block_n, block_k) tile
|
||||
# of the unsharded weight, while the TP-sharded parameters
|
||||
# use a refined block grid (see Fp8MoEMethod). Upsample the
|
||||
# scales to the refined grid (lossless: the refined block
|
||||
# divides the checkpoint block) so per-rank slicing stays
|
||||
# exact. Dim -2 is the weight's N dim, dim -1 is K.
|
||||
loaded_weight = loaded_weight.repeat_interleave(
|
||||
scale_refine[0], dim=-2
|
||||
).repeat_interleave(scale_refine[1], dim=-1)
|
||||
self._load_model_weight_or_group_weight_scale(
|
||||
shard_id=shard_id,
|
||||
shard_dim=shard_dim,
|
||||
|
||||
@@ -56,6 +56,10 @@ class MambaBase(AttentionLayerBase):
|
||||
def mamba_type(self) -> MambaAttentionBackendEnum:
|
||||
pass
|
||||
|
||||
@property
|
||||
def is_kv_cache_tp_replicated(self) -> bool:
|
||||
return False
|
||||
|
||||
@abstractmethod
|
||||
def get_state_dtype(self) -> tuple[torch.dtype, ...]:
|
||||
pass
|
||||
@@ -70,6 +74,7 @@ class MambaBase(AttentionLayerBase):
|
||||
block_size=mamba_block_size,
|
||||
page_size_padded=page_size_padded,
|
||||
mamba_type=self.mamba_type,
|
||||
tp_replicated=self.is_kv_cache_tp_replicated,
|
||||
mamba_cache_mode=vllm_config.cache_config.mamba_cache_mode,
|
||||
# RecoverSSM verifies the whole window off one checkpoint, so it
|
||||
# never writes the baseline's per-draft-token state slots.
|
||||
|
||||
@@ -519,7 +519,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
self.gqa_interleaved_layout
|
||||
or self.head_k_dim != 128
|
||||
or self.head_v_dim != 128
|
||||
or self.norm.activation != "silu"
|
||||
or self.norm.activation not in ("silu", "sigmoid")
|
||||
or vllm_config.model_config.dtype != torch.bfloat16
|
||||
or conv_state_dtype != torch.bfloat16
|
||||
or recurrent_state_dtype not in FUSED_GDN_STATE_DTYPES
|
||||
@@ -527,9 +527,9 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
):
|
||||
return (
|
||||
"the fused CUDA kernel requires a BF16 GDN model with "
|
||||
"K=V=128, SiLU gating, non-interleaved GQA layout, BF16 "
|
||||
"convolution cache, BF16 or FP32 recurrent state, and a "
|
||||
"GPU with compute capability 8.0+"
|
||||
"K=V=128, SiLU or sigmoid gating, non-interleaved GQA "
|
||||
"layout, BF16 convolution cache, BF16 or FP32 recurrent "
|
||||
"state, and a GPU with compute capability 8.0+"
|
||||
)
|
||||
if not hasattr(torch.ops._C, "fused_gdn_decode_post_conv_mtp"):
|
||||
return "torch.ops._C.fused_gdn_decode_post_conv_mtp is not built"
|
||||
@@ -1766,6 +1766,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
out=core_attn_out,
|
||||
scale=self.head_k_dim**-0.5,
|
||||
norm_eps=self.layer_norm_epsilon,
|
||||
output_gate_activation=self.norm.activation,
|
||||
)
|
||||
|
||||
def _forward_core_fused_norm_packed(
|
||||
|
||||
@@ -17,6 +17,7 @@ from vllm.utils.torch_utils import (
|
||||
STR_DTYPE_TO_TORCH_DTYPE,
|
||||
get_kv_cache_torch_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -352,6 +353,10 @@ Parameters:
|
||||
num_accepted_tokens: int - number of accepted tokens used to compute the copy offset.
|
||||
Range: 1 .. 1 + num_speculative_tokens (inclusive).
|
||||
"""
|
||||
MambaStateCopyFuncs: TypeAlias = tuple[MambaStateCopyFunc, ...]
|
||||
MambaStateCopyFuncsByType: TypeAlias = dict[
|
||||
MambaAttentionBackendEnum, MambaStateCopyFuncs
|
||||
]
|
||||
|
||||
|
||||
def get_conv_copy_spec(
|
||||
|
||||
@@ -31,6 +31,7 @@ from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
|
||||
convert_to_fp8_moe_kernel_format,
|
||||
make_fp8_moe_kernel,
|
||||
make_fp8_moe_quant_config,
|
||||
refine_fp8_moe_block_shape,
|
||||
select_fp8_moe_backend,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import (
|
||||
@@ -63,7 +64,6 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8Dynamic128Sym,
|
||||
kFp8DynamicTensorSym,
|
||||
kFp8DynamicTokenSym,
|
||||
kFp8Static128BlockSym,
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
|
||||
@@ -481,9 +481,41 @@ class Fp8MoEMethod(FusedMoEMethodBase):
|
||||
"weight_scale_inv" if self.block_quant else "weight_scale"
|
||||
)
|
||||
|
||||
self.weight_scale_refine: tuple[int, int] | None = None
|
||||
self.moe_block_shape = self.weight_block_size
|
||||
|
||||
# Set weight key and activation key for kernel compatibility
|
||||
if self.block_quant:
|
||||
weight_key = kFp8Static128BlockSym
|
||||
assert self.weight_block_size is not None
|
||||
# TP shards the intermediate dim of the expert weights, so a
|
||||
# per-shard size that is not a multiple of the checkpoint's block
|
||||
# size makes the checkpoint's block scales impossible to shard
|
||||
# exactly. When a finer block size (>= 32) divides both the
|
||||
# checkpoint blocks and all involved dims, the weight scales are
|
||||
# refined to that granularity at load time (a lossless upsampling,
|
||||
# since the refined block divides the checkpoint block). The
|
||||
# refined block shape is encoded in the weight key, so the oracle
|
||||
# only selects kernels that support it (e.g. Triton, which takes
|
||||
# the block shape as a runtime argument).
|
||||
refined_shape = refine_fp8_moe_block_shape(self.moe, self.weight_block_size)
|
||||
if refined_shape is not None:
|
||||
block_n, block_k = self.weight_block_size
|
||||
self.weight_scale_refine = (
|
||||
block_n // refined_shape[0],
|
||||
block_k // refined_shape[1],
|
||||
)
|
||||
self.moe_block_shape = refined_shape
|
||||
logger.info_once(
|
||||
"FP8 MoE block scales refined from %s to %s to fit "
|
||||
"the TP-sharded intermediate size %d.",
|
||||
str(self.weight_block_size),
|
||||
str(refined_shape),
|
||||
self.moe.intermediate_size_per_partition,
|
||||
)
|
||||
assert self.moe_block_shape is not None
|
||||
weight_key = create_fp8_quant_key(
|
||||
static=True, group_shape=GroupShape(*self.moe_block_shape)
|
||||
)
|
||||
activation_key = kFp8Dynamic128Sym
|
||||
else:
|
||||
weight_key = kFp8StaticTensorSym
|
||||
@@ -519,6 +551,8 @@ class Fp8MoEMethod(FusedMoEMethodBase):
|
||||
|
||||
if self.block_quant:
|
||||
assert self.weight_block_size is not None
|
||||
assert self.moe_block_shape is not None
|
||||
moe_block_shape = self.moe_block_shape
|
||||
layer.weight_block_size = self.weight_block_size
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
block_n, block_k = (
|
||||
@@ -530,18 +564,24 @@ class Fp8MoEMethod(FusedMoEMethodBase):
|
||||
# layers must be divisible by block_n.
|
||||
# Required by column parallel or enabling merged weights
|
||||
if intermediate_size_per_partition % block_n != 0:
|
||||
raise ValueError(
|
||||
f"The output_size of gate's and up's weight = "
|
||||
f"{intermediate_size_per_partition} is not divisible by "
|
||||
f"weight quantization block_n = {block_n}."
|
||||
)
|
||||
if self.weight_scale_refine is None:
|
||||
raise ValueError(
|
||||
f"The output_size of gate's and up's weight = "
|
||||
f"{intermediate_size_per_partition} is not divisible by "
|
||||
f"weight quantization block_n = {block_n}."
|
||||
)
|
||||
# Use the refined block grid for the scale parameters; the
|
||||
# loader upsamples the checkpoint scales accordingly.
|
||||
block_n, block_k = moe_block_shape
|
||||
if tp_size > 1 and intermediate_size_per_partition % block_k != 0:
|
||||
# Required by row parallel
|
||||
raise ValueError(
|
||||
f"The input_size of down's weight = "
|
||||
f"{intermediate_size_per_partition} is not divisible by "
|
||||
f"weight quantization block_k = {block_k}."
|
||||
)
|
||||
if self.weight_scale_refine is None:
|
||||
raise ValueError(
|
||||
f"The input_size of down's weight = "
|
||||
f"{intermediate_size_per_partition} is not divisible by "
|
||||
f"weight quantization block_k = {block_k}."
|
||||
)
|
||||
block_n, block_k = moe_block_shape
|
||||
|
||||
# WEIGHTS
|
||||
w13_weight = torch.nn.Parameter(
|
||||
@@ -747,7 +787,7 @@ class Fp8MoEMethod(FusedMoEMethodBase):
|
||||
w2_scale=w2_scale,
|
||||
a1_scale=a1_scale,
|
||||
a2_scale=a2_scale,
|
||||
block_shape=self.weight_block_size,
|
||||
block_shape=self.moe_block_shape,
|
||||
swiglu_limit=getattr(layer, "swiglu_limit", None),
|
||||
gemm1_alpha=getattr(layer, "swiglu_alpha", None),
|
||||
gemm1_beta=getattr(layer, "swiglu_beta", None),
|
||||
|
||||
@@ -161,6 +161,16 @@ class QuarkOCP_MX(QuarkScheme):
|
||||
weight_loader: Callable,
|
||||
**kwargs,
|
||||
):
|
||||
if input_size_per_partition % OCP_MX_BLOCK_SIZE != 0:
|
||||
layer_name = getattr(layer, "prefix", "") or type(layer).__name__
|
||||
raise ValueError(
|
||||
f"OCP MX linear layer {layer_name!r} has an input size per "
|
||||
f"partition of {input_size_per_partition}, which must be "
|
||||
f"divisible by the OCP MX group size {OCP_MX_BLOCK_SIZE}. "
|
||||
"Choose a compatible tensor-parallel size or avoid "
|
||||
"tensor-parallel sharding for this layer."
|
||||
)
|
||||
|
||||
if self.dynamic_mxfp4_quant:
|
||||
weight = ModelWeightParameter(
|
||||
data=torch.empty(
|
||||
|
||||
@@ -9,6 +9,41 @@ if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
|
||||
def get_quark_ocp_mx_group_size(
|
||||
quant_config: "QuantizationConfig | None",
|
||||
layer_name: str,
|
||||
) -> int | None:
|
||||
"""Return the OCP MX group size for a quantized Quark linear layer."""
|
||||
if quant_config is None:
|
||||
return None
|
||||
|
||||
from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig
|
||||
from vllm.model_executor.layers.quantization.quark.utils import should_ignore_layer
|
||||
|
||||
if not isinstance(quant_config, QuarkConfig):
|
||||
return None
|
||||
|
||||
if should_ignore_layer(
|
||||
layer_name,
|
||||
ignore=quant_config.quant_config.get("exclude") or [],
|
||||
fused_mapping=quant_config.packed_modules_mapping,
|
||||
):
|
||||
return None
|
||||
|
||||
layer_quant_config = (
|
||||
quant_config.get_layer_quant_config_from_name(layer_name)
|
||||
or quant_config.quant_config.get("global_quant_config")
|
||||
or {}
|
||||
)
|
||||
weight_quant = layer_quant_config.get("weight")
|
||||
input_quant = layer_quant_config.get("input_tensors")
|
||||
if not quant_config._is_w_ocp_mx_a_x(weight_quant, input_quant):
|
||||
return None
|
||||
|
||||
assert weight_quant is not None
|
||||
return int(weight_quant["group_size"])
|
||||
|
||||
|
||||
def is_shared_expert_quant_fse_compatible(
|
||||
quant_config: "QuantizationConfig | None",
|
||||
expert_prefix: str,
|
||||
|
||||
@@ -232,7 +232,16 @@ def align_fp4_moe_weights_for_fi(
|
||||
|
||||
# Pad w13 and w2 along its intermediate dimension.
|
||||
padded_w13 = w13.new_zeros((num_experts, padded_gate_up_dim, hidden_size // 2))
|
||||
padded_w13[:, : w13.shape[1], :] = w13
|
||||
if is_act_and_mul:
|
||||
# Keep the two logical projections independently aligned. Copying the
|
||||
# fused [gate, up] tensor contiguously would move the up projection into
|
||||
# the padded tail of gate when intermediate is rounded up.
|
||||
padded_w13[:, :intermediate, :] = w13[:, :intermediate, :]
|
||||
padded_w13[:, padded_intermediate : padded_intermediate + intermediate, :] = (
|
||||
w13[:, intermediate:, :]
|
||||
)
|
||||
else:
|
||||
padded_w13[:, : w13.shape[1], :] = w13
|
||||
|
||||
padded_w2 = w2.new_zeros((num_experts, hidden_size, padded_intermediate // 2))
|
||||
padded_w2[:, :, : w2.shape[2]] = w2
|
||||
@@ -240,7 +249,13 @@ def align_fp4_moe_weights_for_fi(
|
||||
padded_w13_scale = w13_scale.new_zeros(
|
||||
(num_experts, padded_gate_up_dim, hidden_size // 16)
|
||||
)
|
||||
padded_w13_scale[:, : w13_scale.shape[1], :] = w13_scale
|
||||
if is_act_and_mul:
|
||||
padded_w13_scale[:, :intermediate, :] = w13_scale[:, :intermediate, :]
|
||||
padded_w13_scale[
|
||||
:, padded_intermediate : padded_intermediate + intermediate, :
|
||||
] = w13_scale[:, intermediate:, :]
|
||||
else:
|
||||
padded_w13_scale[:, : w13_scale.shape[1], :] = w13_scale
|
||||
|
||||
padded_w2_scale = w2_scale.new_zeros(
|
||||
(num_experts, hidden_size, padded_intermediate // 16)
|
||||
@@ -322,7 +337,13 @@ def align_moe_weights_for_fi(
|
||||
|
||||
# Pad w13 and w2 along its intermediate dimension.
|
||||
padded_w13 = w13.new_zeros((num_experts, padded_gate_up_dim, hidden_size))
|
||||
padded_w13[:, : w13.shape[1], :] = w13
|
||||
if is_act_and_mul:
|
||||
padded_w13[:, :intermediate, :] = w13[:, :intermediate, :]
|
||||
padded_w13[:, padded_intermediate : padded_intermediate + intermediate, :] = (
|
||||
w13[:, intermediate:, :]
|
||||
)
|
||||
else:
|
||||
padded_w13[:, :intermediate, :] = w13
|
||||
|
||||
padded_w2 = w2.new_zeros((num_experts, hidden_size, padded_intermediate))
|
||||
padded_w2[:, :, :intermediate] = w2
|
||||
|
||||
@@ -233,6 +233,7 @@ class VocabParallelEmbedding(PluggableLayer):
|
||||
quant_config: quant config for the layer
|
||||
prefix: full name of the layer in the state dict
|
||||
disable_tp: If true, tensor parallelism will be disabled for this layer.
|
||||
quant_method: Preselected quantization method for model-specific layers.
|
||||
""" # noqa: E501
|
||||
|
||||
# --8<-- [end:vocab_parallel_embedding]
|
||||
@@ -248,6 +249,7 @@ class VocabParallelEmbedding(PluggableLayer):
|
||||
prefix: str = "",
|
||||
*,
|
||||
disable_tp: bool = False,
|
||||
quant_method: QuantizeMethodBase | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -281,8 +283,9 @@ class VocabParallelEmbedding(PluggableLayer):
|
||||
)
|
||||
self.embedding_dim = embedding_dim
|
||||
|
||||
quant_method = None
|
||||
if quant_config is not None:
|
||||
# Avoid overriding a preselected model-specific method with generic
|
||||
# config-based dispatch.
|
||||
if quant_method is None and quant_config is not None:
|
||||
quant_method = quant_config.get_quant_method(self, prefix=prefix)
|
||||
if quant_method is None:
|
||||
quant_method = UnquantizedEmbeddingMethod()
|
||||
@@ -501,8 +504,16 @@ class VocabParallelEmbedding(PluggableLayer):
|
||||
output_parallel = self.quant_method.embedding(self, masked_input.long())
|
||||
# Mask the output embedding.
|
||||
if self.tp_size > 1:
|
||||
if output_parallel.dtype in (
|
||||
torch.float8_e4m3fn,
|
||||
torch.float8_e5m2,
|
||||
):
|
||||
# Each vocab token has one owner, so FP8 bytes can use int8 SUM.
|
||||
comm_output = output_parallel.view(torch.int8)
|
||||
comm_output.masked_fill_(input_mask.unsqueeze(-1), 0)
|
||||
output = tensor_model_parallel_all_reduce(comm_output)
|
||||
return output.view(output_parallel.dtype)
|
||||
output_parallel.masked_fill_(input_mask.unsqueeze(-1), 0)
|
||||
# Reduce across all the model parallel GPUs.
|
||||
return tensor_model_parallel_all_reduce(output_parallel)
|
||||
return output_parallel
|
||||
|
||||
|
||||
@@ -289,12 +289,17 @@ def get_quant_config(
|
||||
# if hf_quant_config is None, we will try to get config from
|
||||
# hf_overrides
|
||||
hf_overrides = model_config.hf_overrides
|
||||
if callable(hf_overrides):
|
||||
# A callable hf_overrides is a config-to-config transform (e.g. the
|
||||
# one SpeculativeConfig installs on draft model configs); it cannot
|
||||
# carry quantization config entries, so treat it as no overrides.
|
||||
hf_overrides = {}
|
||||
if not isinstance(hf_overrides, dict):
|
||||
raise ValueError(
|
||||
"hf_overrides must be a dict for get_quant_config "
|
||||
"to get the quantization config from it."
|
||||
)
|
||||
quantization_config_file = hf_overrides.get("quantization_config_file", None)
|
||||
quantization_config_file = hf_overrides.get("quantization_config_file")
|
||||
if quantization_config_file is not None:
|
||||
if hasattr(quant_cls, "from_config_file"):
|
||||
return quant_cls.from_config_file(quantization_config_file)
|
||||
@@ -304,7 +309,7 @@ def get_quant_config(
|
||||
"but quant_cls.from_config_file is not implemented in "
|
||||
f"{quant_cls}"
|
||||
)
|
||||
quantization_config_json = hf_overrides.get("quantization_config_dict_json", None)
|
||||
quantization_config_json = hf_overrides.get("quantization_config_dict_json")
|
||||
if quantization_config_json is not None:
|
||||
if hasattr(quant_cls, "from_config_dict_json"):
|
||||
return quant_cls.from_config_dict_json(quantization_config_json)
|
||||
|
||||
@@ -839,6 +839,83 @@ class Qwen3_5ForCausalLMConfig(Qwen3_5ForConditionalGenerationConfig):
|
||||
rope_parameters.pop("mrope_interleaved", None)
|
||||
|
||||
|
||||
def _strip_qwen4_exp_mrope(model_config: "ModelConfig") -> None:
|
||||
configs = {
|
||||
id(config): config
|
||||
for config in (
|
||||
getattr(model_config, "hf_config", None),
|
||||
model_config.hf_text_config,
|
||||
)
|
||||
if config is not None
|
||||
}
|
||||
for config in configs.values():
|
||||
rope_parameters = getattr(config, "rope_parameters", None)
|
||||
if rope_parameters is not None:
|
||||
rope_parameters.pop("mrope_section", None)
|
||||
rope_parameters.pop("mrope_interleaved", None)
|
||||
|
||||
|
||||
class Qwen4ExpForConditionalGenerationConfig(Qwen3_5ForConditionalGenerationConfig):
|
||||
"""Apply the Qwen3.5 hybrid-cache contract to Qwen4Exp."""
|
||||
|
||||
@staticmethod
|
||||
def verify_and_update_config(vllm_config: "VllmConfig") -> None:
|
||||
Qwen3_5ForConditionalGenerationConfig.verify_and_update_config(vllm_config)
|
||||
text_config = vllm_config.model_config.hf_text_config
|
||||
if text_config.hc_count <= 1:
|
||||
raise ValueError("Qwen4Exp requires hc_count > 1")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
uses_ple_or_qsa = bool(text_config.ple_layer_ids) or (
|
||||
getattr(text_config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
if uses_ple_or_qsa and (
|
||||
parallel_config.enable_dbo or parallel_config.ubatch_size > 1
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp PLE/QSA does not support dual-batch overlap or microbatching"
|
||||
)
|
||||
# Checked again in Qwen4ExpModelState; rejecting it here keeps the
|
||||
# engine from loading weights first.
|
||||
if text_config.ple_layer_ids and parallel_config.pipeline_parallel_size > 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp N-gram PLE embedding requires pipeline_parallel_size=1 "
|
||||
"because non-first pipeline ranks do not receive the raw input_ids "
|
||||
"it needs. Please run with PP=1."
|
||||
)
|
||||
multimodal_config = vllm_config.model_config.multimodal_config
|
||||
if multimodal_config is not None and multimodal_config.language_model_only:
|
||||
_strip_qwen4_exp_mrope(vllm_config.model_config)
|
||||
spec_config = vllm_config.speculative_config
|
||||
if spec_config is not None and spec_config.method not in {
|
||||
"mtp",
|
||||
"ngram",
|
||||
"ngram_gpu",
|
||||
}:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp speculative decoding supports only its native MTP "
|
||||
"checkpoint and linear n-gram proposers"
|
||||
)
|
||||
|
||||
|
||||
class Qwen4ExpForCausalLMConfig(Qwen4ExpForConditionalGenerationConfig):
|
||||
@staticmethod
|
||||
def verify_and_update_config(vllm_config: "VllmConfig") -> None:
|
||||
Qwen4ExpForConditionalGenerationConfig.verify_and_update_config(vllm_config)
|
||||
|
||||
_strip_qwen4_exp_mrope(vllm_config.model_config)
|
||||
|
||||
|
||||
class Qwen4ExpMTPConfig(Qwen4ExpForConditionalGenerationConfig):
|
||||
"""Preserve MRoPE for a VL target and use 1D RoPE for a text target."""
|
||||
|
||||
@staticmethod
|
||||
def verify_and_update_config(vllm_config: "VllmConfig") -> None:
|
||||
Qwen4ExpForConditionalGenerationConfig.verify_and_update_config(vllm_config)
|
||||
if hasattr(vllm_config.model_config.hf_config, "vision_config"):
|
||||
return
|
||||
_strip_qwen4_exp_mrope(vllm_config.model_config)
|
||||
|
||||
|
||||
class ColQwen3_5Config(Qwen3_5ForConditionalGenerationConfig):
|
||||
"""Apply the attention contract declared by a ColQwen3.5 checkpoint."""
|
||||
|
||||
@@ -963,6 +1040,9 @@ MODELS_CONFIG_MAP: dict[str, type[VerifyAndUpdateConfig]] = {
|
||||
"Qwen3_5ForConditionalGeneration": Qwen3_5ForConditionalGenerationConfig,
|
||||
"Qwen3_5MoeForCausalLM": Qwen3_5ForCausalLMConfig,
|
||||
"Qwen3_5MoeForConditionalGeneration": Qwen3_5ForConditionalGenerationConfig,
|
||||
"Qwen4ExpForCausalLM": Qwen4ExpForCausalLMConfig,
|
||||
"Qwen4ExpForConditionalGeneration": (Qwen4ExpForConditionalGenerationConfig),
|
||||
"Qwen4ExpMTP": Qwen4ExpMTPConfig,
|
||||
"UnlimitedOCRForCausalLM": UnlimitedOCRForCausalLMConfig,
|
||||
"VoyageQwen3BidirectionalEmbedModel": VoyageQwen3BidirectionalEmbedModelConfig,
|
||||
"XLMRobertaModel": JinaRobertaModelConfig,
|
||||
|
||||
@@ -49,13 +49,17 @@ if TYPE_CHECKING:
|
||||
from vllm.lora.model_manager import LoRAModelManager
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateCopyFunc
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
MambaStateCopyFunc,
|
||||
MambaStateCopyFuncsByType,
|
||||
)
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
from vllm.multimodal.inputs import MultiModalFeatureSpec, MultiModalKwargsItem
|
||||
from vllm.multimodal.registry import _ProcessorFactories
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.tasks import ScoreType
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
EncoderCudaGraphCaptureInputs,
|
||||
EncoderCudaGraphConfig,
|
||||
@@ -970,6 +974,14 @@ class IsHybrid(Protocol):
|
||||
"""
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_copy_funcs(
|
||||
cls,
|
||||
mamba_types: set["MambaAttentionBackendEnum"],
|
||||
) -> "MambaStateCopyFuncsByType":
|
||||
copy_funcs = cls.get_mamba_state_copy_func()
|
||||
return {mamba_type: copy_funcs for mamba_type in mamba_types}
|
||||
|
||||
|
||||
@overload
|
||||
def is_hybrid(model: type[object]) -> TypeIs[type[IsHybrid]]: ...
|
||||
@@ -1131,6 +1143,20 @@ class SupportsMambaPrefixCaching(Protocol):
|
||||
|
||||
supports_mamba_prefix_caching: ClassVar[Literal[True]] = True
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_copy_func(cls) -> tuple["MambaStateCopyFunc", ...]:
|
||||
"""Return copy functions for the model's Mamba states."""
|
||||
...
|
||||
|
||||
@classmethod
|
||||
def get_mamba_state_copy_funcs(
|
||||
cls,
|
||||
mamba_types: set["MambaAttentionBackendEnum"],
|
||||
) -> "MambaStateCopyFuncsByType":
|
||||
"""Map legacy copy functions to each requested Mamba backend."""
|
||||
copy_funcs = cls.get_mamba_state_copy_func()
|
||||
return {mamba_type: copy_funcs for mamba_type in mamba_types}
|
||||
|
||||
|
||||
@overload
|
||||
def supports_mamba_prefix_caching(
|
||||
|
||||
@@ -80,15 +80,17 @@ class Qwen2MoeMLP(nn.Module):
|
||||
reduce_results: bool = True,
|
||||
expert_gate: torch.nn.Linear | None = None,
|
||||
is_sequence_parallel: bool = False,
|
||||
disable_tp: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
disable_tp = disable_tp or is_sequence_parallel
|
||||
self.gate_up_proj = MergedColumnParallelLinear(
|
||||
hidden_size,
|
||||
[intermediate_size] * 2,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
disable_tp=is_sequence_parallel,
|
||||
disable_tp=disable_tp,
|
||||
prefix=f"{prefix}.gate_up_proj",
|
||||
)
|
||||
self.down_proj = RowParallelLinear(
|
||||
@@ -97,7 +99,7 @@ class Qwen2MoeMLP(nn.Module):
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
reduce_results=reduce_results,
|
||||
disable_tp=is_sequence_parallel,
|
||||
disable_tp=disable_tp,
|
||||
prefix=f"{prefix}.down_proj",
|
||||
)
|
||||
if hidden_act != "silu":
|
||||
|
||||
@@ -43,6 +43,9 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
MambaStateShapeCalculator,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.quantization.utils.config_utils import (
|
||||
get_quark_ocp_mx_group_size,
|
||||
)
|
||||
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding, get_rope
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
@@ -90,6 +93,38 @@ def _should_use_sequence_parallel(vllm_config: VllmConfig) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _should_replicate_misaligned_shared_expert(
|
||||
intermediate_size: int,
|
||||
tp_size: int,
|
||||
group_size: int | None,
|
||||
enable_expert_parallel: bool,
|
||||
is_sequence_parallel: bool,
|
||||
) -> bool:
|
||||
if intermediate_size <= 0 or group_size is None:
|
||||
return False
|
||||
|
||||
partition_size, remainder = divmod(intermediate_size, tp_size)
|
||||
if remainder == 0 and partition_size % group_size == 0:
|
||||
return False
|
||||
|
||||
if enable_expert_parallel or is_sequence_parallel:
|
||||
return True
|
||||
|
||||
if remainder != 0:
|
||||
raise ValueError(
|
||||
f"Shared-expert intermediate size {intermediate_size} must be "
|
||||
f"divisible by tensor-parallel size {tp_size}."
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
"The Quark OCP MX shared expert cannot be tensor-parallelized: "
|
||||
f"intermediate size {intermediate_size} with TP size {tp_size} "
|
||||
f"produces a partition of {partition_size}, which is not divisible by "
|
||||
f"the OCP MX group size {group_size}. Choose a compatible "
|
||||
"tensor-parallel size or enable expert parallelism."
|
||||
)
|
||||
|
||||
|
||||
class Qwen3NextSparseMoeBlock(nn.Module):
|
||||
def __init__(self, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
@@ -106,6 +141,17 @@ class Qwen3NextSparseMoeBlock(nn.Module):
|
||||
|
||||
self.is_sequence_parallel = parallel_config.use_sequence_parallel_moe
|
||||
|
||||
shared_expert_group_size = get_quark_ocp_mx_group_size(
|
||||
quant_config,
|
||||
f"{prefix}.shared_expert.down_proj",
|
||||
)
|
||||
self.replicate_shared_expert = _should_replicate_misaligned_shared_expert(
|
||||
config.shared_expert_intermediate_size,
|
||||
self.tp_size,
|
||||
shared_expert_group_size,
|
||||
parallel_config.enable_expert_parallel,
|
||||
self.is_sequence_parallel,
|
||||
)
|
||||
if self.tp_size > config.num_experts:
|
||||
raise ValueError(
|
||||
f"Tensor parallel size {self.tp_size} is greater than "
|
||||
@@ -138,7 +184,10 @@ class Qwen3NextSparseMoeBlock(nn.Module):
|
||||
)
|
||||
|
||||
self.is_fused_shared_expert_enabled = False
|
||||
if config.shared_expert_intermediate_size > 0:
|
||||
if (
|
||||
config.shared_expert_intermediate_size > 0
|
||||
and not self.replicate_shared_expert
|
||||
):
|
||||
self.is_fused_shared_expert_enabled = resolve_layer_fused_shared_expert(
|
||||
quant_config,
|
||||
prefix,
|
||||
@@ -159,11 +208,14 @@ class Qwen3NextSparseMoeBlock(nn.Module):
|
||||
reduce_results=False,
|
||||
expert_gate=self.shared_expert_gate,
|
||||
is_sequence_parallel=self.is_sequence_parallel,
|
||||
disable_tp=self.replicate_shared_expert,
|
||||
prefix=f"{prefix}.shared_expert",
|
||||
)
|
||||
|
||||
self.experts = FusedMoEFactory(
|
||||
shared_experts=self.shared_expert,
|
||||
shared_experts=(
|
||||
None if self.replicate_shared_expert else self.shared_expert
|
||||
),
|
||||
gate=self.gate,
|
||||
num_experts=self.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
@@ -195,9 +247,16 @@ class Qwen3NextSparseMoeBlock(nn.Module):
|
||||
if self.is_sequence_parallel and not already_sequence_parallel:
|
||||
hidden_states = sequence_parallel_chunk(hidden_states)
|
||||
|
||||
replicated_shared_output = (
|
||||
self.shared_expert(hidden_states)
|
||||
if self.replicate_shared_expert and self.shared_expert is not None
|
||||
else None
|
||||
)
|
||||
final_hidden_states = self.experts(
|
||||
hidden_states=hidden_states, router_logits=hidden_states
|
||||
)
|
||||
if replicated_shared_output is not None:
|
||||
final_hidden_states += replicated_shared_output
|
||||
|
||||
if self.is_sequence_parallel and not already_sequence_parallel:
|
||||
final_hidden_states = tensor_model_parallel_all_gather(
|
||||
@@ -488,7 +547,7 @@ class Qwen3NextDecoderLayer(nn.Module):
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor | None,
|
||||
positions: torch.Tensor = None,
|
||||
positions: torch.Tensor,
|
||||
**kwargs: object,
|
||||
):
|
||||
full_num_tokens = positions.shape[-1]
|
||||
|
||||
@@ -111,6 +111,10 @@ _TEXT_GENERATION_MODELS = {
|
||||
"Gemma3nForCausalLM": ("gemma3n", "Gemma3nForCausalLM"),
|
||||
"Gemma4ForCausalLM": ("gemma4", "Gemma4ForCausalLM"),
|
||||
"Qwen3NextForCausalLM": ("qwen3_next", "Qwen3NextForCausalLM"),
|
||||
"Qwen4ExpForCausalLM": (
|
||||
"vllm.models.qwen4_exp",
|
||||
"Qwen4ExpForCausalLM",
|
||||
),
|
||||
"GlmForCausalLM": ("glm", "GlmForCausalLM"),
|
||||
"Glm4ForCausalLM": ("glm4", "Glm4ForCausalLM"),
|
||||
"Glm4MoeForCausalLM": ("glm4_moe", "Glm4MoeForCausalLM"),
|
||||
@@ -573,6 +577,10 @@ _MULTIMODAL_MODELS = {
|
||||
"qwen3_5",
|
||||
"Qwen3_5MoeForConditionalGeneration",
|
||||
),
|
||||
"Qwen4ExpForConditionalGeneration": (
|
||||
"vllm.models.qwen4_exp",
|
||||
"Qwen4ExpForConditionalGeneration",
|
||||
),
|
||||
"RForConditionalGeneration": ("rvl", "RForConditionalGeneration"),
|
||||
"SkyworkR1VChatModel": ("skyworkr1v", "SkyworkR1VChatModel"),
|
||||
"SmolVLMForConditionalGeneration": ("smolvlm", "SmolVLMForConditionalGeneration"),
|
||||
@@ -659,6 +667,7 @@ _SPECULATIVE_DECODING_MODELS = {
|
||||
"MedusaModel": ("medusa", "Medusa"),
|
||||
"OpenPanguMTPModel": ("openpangu_mtp", "OpenPanguMTP"),
|
||||
"Qwen3NextMTP": ("qwen3_next_mtp", "Qwen3NextMTP"),
|
||||
"Qwen4ExpMTP": ("vllm.models.qwen4_exp", "Qwen4ExpMTP"),
|
||||
"Step3p5MTP": ("step3p5_mtp", "Step3p5MTP"),
|
||||
"Qwen3_5MTP": ("qwen3_5_mtp", "Qwen3_5MTP"),
|
||||
"Qwen3_5MoeMTP": ("qwen3_5_mtp", "Qwen3_5MoeMTP"),
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp model package."""
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .common.hyperconnection import (
|
||||
GatedResidual,
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionBase,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .nvidia.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .nvidia.mtp import Qwen4ExpMTP
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name in {
|
||||
"Qwen4ExpForCausalLM",
|
||||
"Qwen4ExpForConditionalGeneration",
|
||||
"Qwen4ExpMTP",
|
||||
}:
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_xpu() or current_platform.is_tpu():
|
||||
raise NotImplementedError("Qwen4Exp currently supports CUDA and ROCm only")
|
||||
if current_platform.is_rocm():
|
||||
from .amd.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .amd.mtp import Qwen4ExpMTP
|
||||
else:
|
||||
from .nvidia.model import (
|
||||
Qwen4ExpForCausalLM,
|
||||
Qwen4ExpForConditionalGeneration,
|
||||
)
|
||||
from .nvidia.mtp import Qwen4ExpMTP
|
||||
|
||||
return {
|
||||
"Qwen4ExpForCausalLM": Qwen4ExpForCausalLM,
|
||||
"Qwen4ExpForConditionalGeneration": (Qwen4ExpForConditionalGeneration),
|
||||
"Qwen4ExpMTP": Qwen4ExpMTP,
|
||||
}[name]
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
"Qwen4ExpForCausalLM",
|
||||
"Qwen4ExpForConditionalGeneration",
|
||||
"Qwen4ExpMTP",
|
||||
]
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,205 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities for the AMD model variant.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606). This AMD variant
|
||||
delays each HC combine to the following HC mix boundary. HC glue kernels,
|
||||
including fused combine+RMSNorm, live in ``ops/hc.py``; projections remain
|
||||
standard vLLM Linear modules.
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout).
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config)
|
||||
|
||||
hidden_states, block_input, injection = self.attn_hc.mix(hidden_states)
|
||||
attention_output = attention(block_input)
|
||||
hidden_states, block_input, injection = self.mlp_hc.combine_and_mix(
|
||||
hidden_states, attention_output, injection
|
||||
)
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
|
||||
from ..common.hyperconnection import (
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
from .ops.hc import (
|
||||
grouped_gemma_rmsnorm,
|
||||
hc_combine,
|
||||
hc_combine_norm,
|
||||
hc_gate_mix,
|
||||
hc_silu,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(nn.Module):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``combine_and_mix()`` runs the pre pipeline (grouped GemmaRMSNorm -> merged
|
||||
low-rank down+inject GEMM -> silu -> up GEMM -> sigmoid -> gated mean
|
||||
over the HC streams). When passed a pending block output and an injection,
|
||||
it fuses their residual combine with the RMSNorm. Final mixers use
|
||||
``use_combine=False`` and do not produce a new injection.
|
||||
|
||||
Weights: the norm owns the grouped GemmaRMSNorm affine; the projections
|
||||
are vLLM Linear modules (merged replicated linear for down+inject), so
|
||||
GEMM dispatch (e.g. the low-latency skinny GEMM) applies through the
|
||||
standard quant_method mechanism.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
use_combine: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.lora_rank = config.hc_lowrank
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.use_combine = use_combine
|
||||
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- vLLM Linear weights --------------------------------------------
|
||||
# The merged skinny-GEMM shape is physically padded to 16 rows for
|
||||
# alignment and efficient backend dispatch.
|
||||
self.pad_size = (-(self.lora_rank + self.hc_count)) % 16 if use_combine else 0
|
||||
if use_combine:
|
||||
self.input_mix_weight_down_block_inject = MergedColumnParallelLinear(
|
||||
self.hyper_hidden_size,
|
||||
[self.lora_rank, self.hc_count]
|
||||
+ ([self.pad_size] if self.pad_size else []),
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down_block_inject"),
|
||||
return_bias=False,
|
||||
disable_tp=True,
|
||||
)
|
||||
else:
|
||||
self.input_mix_weight_down = ReplicatedLinear(
|
||||
self.hyper_hidden_size,
|
||||
self.lora_rank,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down"),
|
||||
return_bias=False,
|
||||
)
|
||||
self.input_mix_weight_up = ReplicatedLinear(
|
||||
self.lora_rank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_up"),
|
||||
return_bias=False,
|
||||
)
|
||||
|
||||
def mix(
|
||||
self, hidden_states: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
xn = grouped_gemma_rmsnorm(
|
||||
hidden_states,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine_and_mix(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prev_block_output: torch.Tensor,
|
||||
prev_injection: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""Consume a pending combine, then prepare the next block input.
|
||||
|
||||
``hidden_states`` is the multi-stream state from before the pending
|
||||
block's mix. Its combine with ``block_output`` is fused with this
|
||||
module's input RMSNorm.
|
||||
"""
|
||||
hidden_states, xn = hc_combine_norm(
|
||||
hidden_states,
|
||||
prev_block_output,
|
||||
prev_injection,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return hc_combine(hidden_states, block_output, injection, self.hc_count)
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,321 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp weight-free QSA indexer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import (
|
||||
QSACompressedKeyCache,
|
||||
QSAForwardMetadata,
|
||||
QSAKeyStateCache,
|
||||
canonical_qsa_rope_positions,
|
||||
)
|
||||
|
||||
|
||||
def apply_qsa_rope(
|
||||
rotary_emb: nn.Module,
|
||||
positions: torch.Tensor,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
cos_sin = cache[positions]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if positions.ndim == 2:
|
||||
shape = tensor.shape
|
||||
tensor, _ = triton_mrope(
|
||||
tensor.reshape(num_tokens, -1),
|
||||
tensor.new_empty((num_tokens, head_dim)),
|
||||
cos,
|
||||
sin,
|
||||
rotary_emb.mrope_section,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
rotary_emb.mrope_interleaved,
|
||||
rotary_emb.is_neox_style,
|
||||
)
|
||||
return tensor.reshape(shape)
|
||||
|
||||
rotated = rotary_emb.apply_rotary_emb(
|
||||
tensor[..., :rotary_dim],
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
return torch.cat((rotated, tensor[..., rotary_dim:]), dim=-1)
|
||||
|
||||
|
||||
def apply_qsa_rmsnorm(
|
||||
norm: GemmaRMSNorm,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Use vLLM's portable RMSNorm implementation on ROCm."""
|
||||
|
||||
return cast(torch.Tensor, norm(tensor))
|
||||
|
||||
|
||||
class QSAIndexer(nn.Module):
|
||||
"""Replicated Q/K projection plus paged, weight-free QSA selection.
|
||||
|
||||
``prefix`` must be the checkpoint's indexer prefix, normally
|
||||
``model.layers.N.self_attn.indexer``. Consequently the trainable names are
|
||||
``index_qk_proj``, ``q_layernorm`` and ``k_layernorm`` under that prefix.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
rotary_emb: nn.Module,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if vllm_config.cache_config is None:
|
||||
raise ValueError("QSA requires a paged KV cache")
|
||||
if vllm_config.model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
|
||||
self.layer_id = int(layer_id)
|
||||
self.index_n_heads = int(config.indexer_n_heads)
|
||||
self.index_kv_heads = int(config.indexer_kv_heads)
|
||||
self.index_head_dim = int(config.indexer_head_dim)
|
||||
self.token_topk = int(config.indexer_budget)
|
||||
self.compress_ratio = int(config.indexer_compress_ratio)
|
||||
self.rotary_emb = rotary_emb
|
||||
self.prefix = prefix
|
||||
# MTP step 0 selects the target-aligned rows; later steps reuse them
|
||||
# while continuing to update the QSA side cache.
|
||||
self.skip_topk = False
|
||||
|
||||
self.index_qk_proj = ReplicatedLinear(
|
||||
int(config.hidden_size),
|
||||
(self.index_n_heads + self.index_kv_heads) * self.index_head_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.index_qk_proj" if prefix else "index_qk_proj",
|
||||
)
|
||||
self.q_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
self.k_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
|
||||
cache_config = vllm_config.cache_config
|
||||
cache_prefix = f"{prefix}." if prefix else ""
|
||||
self.raw_key_cache = QSAKeyStateCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
cache_rope_positions=vllm_config.model_config.uses_mrope,
|
||||
prefix=f"{cache_prefix}raw_key_cache",
|
||||
cache_config=cache_config,
|
||||
compress_ratio=self.compress_ratio,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
self.compressed_key_cache = QSACompressedKeyCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
compress_ratio=self.compress_ratio,
|
||||
prefix=f"{cache_prefix}compressed_key_cache",
|
||||
cache_config=cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
@property
|
||||
def output_width(self) -> int:
|
||||
return self.token_topk + self.compress_ratio - 1
|
||||
|
||||
def project_qk(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Project replicated Q/K, normalize+rotate Q, and preserve raw K."""
|
||||
|
||||
qk, _ = self.index_qk_proj(hidden_states)
|
||||
q_raw, token_k = qk.split(
|
||||
(
|
||||
self.index_n_heads * self.index_head_dim,
|
||||
self.index_kv_heads * self.index_head_dim,
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
q = q_raw.reshape(-1, self.index_n_heads, self.index_head_dim)
|
||||
q = apply_qsa_rmsnorm(
|
||||
self.q_layernorm,
|
||||
q.reshape(-1, self.index_head_dim),
|
||||
).reshape_as(q)
|
||||
q = apply_qsa_rope(self.rotary_emb, positions, q)
|
||||
return q, token_k.reshape(-1, 1, self.index_head_dim)
|
||||
|
||||
def normalize_compressed_keys(
|
||||
self,
|
||||
compressed_keys: torch.Tensor,
|
||||
first_rope_positions: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Normalize pooled K and apply the first token's exact group position."""
|
||||
|
||||
keys = compressed_keys.reshape(-1, self.index_head_dim)
|
||||
keys = apply_qsa_rmsnorm(self.k_layernorm, keys).reshape(
|
||||
-1, 1, self.index_head_dim
|
||||
)
|
||||
if getattr(self.rotary_emb, "mrope_section", None):
|
||||
positions = first_rope_positions.transpose(0, 1)
|
||||
else:
|
||||
positions = first_rope_positions[:, 0]
|
||||
return apply_qsa_rope(self.rotary_emb, positions, keys)
|
||||
|
||||
def _metadata(
|
||||
self,
|
||||
) -> tuple[QSAForwardMetadata, QSAForwardMetadata] | None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
return None
|
||||
raw = cast(QSAForwardMetadata, metadata[self.raw_key_cache.prefix])
|
||||
compressed = cast(
|
||||
QSAForwardMetadata, metadata[self.compressed_key_cache.prefix]
|
||||
)
|
||||
if raw.num_actual_tokens != compressed.num_actual_tokens:
|
||||
raise RuntimeError("QSA side-cache metadata token counts disagree")
|
||||
if not raw.logical_positions.is_cuda and (
|
||||
not torch.equal(raw.logical_positions, compressed.logical_positions)
|
||||
):
|
||||
raise RuntimeError("QSA side-cache metadata positions disagree")
|
||||
return raw, compressed
|
||||
|
||||
def _update_and_compress(
|
||||
self,
|
||||
token_k: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
raw_metadata: QSAForwardMetadata,
|
||||
compressed_metadata: QSAForwardMetadata,
|
||||
) -> None:
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
raw_key_cache = self.raw_key_cache.key_cache
|
||||
rope_position_cache = self.raw_key_cache.rope_position_cache
|
||||
from .ops.qsa import qsa_compress_groups_with_ratio, qsa_store_cache_rows
|
||||
|
||||
if rope_position_cache is None:
|
||||
position_rows = raw_metadata.logical_positions.view(-1, 1, 1).expand(
|
||||
-1, 1, 3
|
||||
)
|
||||
else:
|
||||
position_rows = canonical_qsa_rope_positions(positions)[:num_tokens].to(
|
||||
device=raw_key_cache.device
|
||||
)
|
||||
pooled, first_positions = qsa_compress_groups_with_ratio(
|
||||
token_k[:num_tokens],
|
||||
position_rows,
|
||||
raw_key_cache,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.token_to_req,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_metadata.slot_mapping,
|
||||
self.compress_ratio,
|
||||
rope_position_cache,
|
||||
)
|
||||
normalized = self.normalize_compressed_keys(pooled, first_positions)
|
||||
qsa_store_cache_rows(
|
||||
self.compressed_key_cache.kv_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
normalized,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
raw_key_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
token_k[:num_tokens],
|
||||
)
|
||||
if rope_position_cache is not None:
|
||||
qsa_store_cache_rows(
|
||||
rope_position_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
position_rows,
|
||||
)
|
||||
|
||||
def _select(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
metadata: QSAForwardMetadata,
|
||||
out: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
from .ops.qsa import qsa_select_paged_tokens
|
||||
|
||||
return qsa_select_paged_tokens(
|
||||
q,
|
||||
self.compressed_key_cache.kv_cache,
|
||||
metadata.block_table,
|
||||
metadata.token_to_req,
|
||||
metadata.logical_positions,
|
||||
metadata.seq_lens,
|
||||
self.token_topk,
|
||||
self.compress_ratio,
|
||||
out,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Return fixed-width request-relative token indices padded with ``-1``."""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
if self.skip_topk and out is not None:
|
||||
return out
|
||||
result = torch.full(
|
||||
(hidden_states.shape[0], self.output_width),
|
||||
-1,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
if out is not None:
|
||||
out.copy_(result)
|
||||
return out
|
||||
return result
|
||||
raw_metadata, compressed_metadata = metadata
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
q, token_k = self.project_qk(
|
||||
hidden_states[:num_tokens], positions[..., :num_tokens]
|
||||
)
|
||||
self._update_and_compress(
|
||||
token_k,
|
||||
positions[..., :num_tokens],
|
||||
raw_metadata,
|
||||
compressed_metadata,
|
||||
)
|
||||
if self.skip_topk:
|
||||
if out is None:
|
||||
raise RuntimeError("QSA top-k reuse requires an output buffer")
|
||||
return out
|
||||
return self._select(q, compressed_metadata, out)
|
||||
|
||||
|
||||
__all__ = ["QSAIndexer", "apply_qsa_rope"]
|
||||
@@ -0,0 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp low-latency GEMM hook for AMD ROCm."""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
|
||||
def enable_qwen4_exp_low_latency_gemm(
|
||||
module: nn.Module,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
"""Keep the standard vLLM linear methods on AMD ROCm."""
|
||||
|
||||
del module, dtype
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Model-runner state for Qwen4Exp PLE inputs."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
class Qwen4ExpModelState(MambaHybridModelState):
|
||||
"""Add rollback-safe PLE n-gram context to the model inputs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
model: nn.Module,
|
||||
encoder_cache: EncoderCache | None,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(vllm_config, model, encoder_cache, device)
|
||||
config = self.model_config.hf_text_config
|
||||
self.uses_ngram_embedding = bool(config.ple_layer_ids)
|
||||
if not self.uses_ngram_embedding:
|
||||
self.ngram_context_len = 0
|
||||
self.ngram_eos_token_id = 0
|
||||
return
|
||||
|
||||
if vllm_config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise RuntimeError(
|
||||
"N-gram PLE embedding currently requires "
|
||||
"pipeline_parallel_size=1 because non-first pipeline ranks do "
|
||||
"not receive the raw input_ids required by PLE. Please run "
|
||||
"with PP=1."
|
||||
)
|
||||
|
||||
self.ngram_context_len = int(config.ngram_size) - 1
|
||||
if self.ngram_context_len <= 0:
|
||||
raise ValueError("N-gram embedding requires context length >= 1.")
|
||||
self.ngram_eos_token_id = int(config.eos_token_id)
|
||||
self.ngram_context = torch.full(
|
||||
(self.max_num_reqs, self.ngram_context_len),
|
||||
self.ngram_eos_token_id,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.ngram_context_offsets = torch.arange(
|
||||
-self.ngram_context_len,
|
||||
0,
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
self.ple_query_start_loc = torch.zeros(
|
||||
self.max_num_reqs + 1,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
def _prepare_ngram_context(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> torch.Tensor:
|
||||
num_reqs = input_batch.num_reqs
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
context = self.ngram_context[:num_reqs_padded]
|
||||
context.fill_(self.ngram_eos_token_id)
|
||||
if num_reqs == 0:
|
||||
return context
|
||||
|
||||
request_indices = input_batch.idx_mapping[:num_reqs].long()
|
||||
context_end = req_states.num_computed_tokens.gpu[request_indices].long()
|
||||
token_indices = context_end.unsqueeze(1) + self.ngram_context_offsets
|
||||
valid_tokens = token_indices >= 0
|
||||
token_indices.clamp_min_(0)
|
||||
context_tokens = req_states.all_token_ids.gpu[
|
||||
request_indices.unsqueeze(1), token_indices
|
||||
]
|
||||
context[:num_reqs].copy_(
|
||||
torch.where(
|
||||
valid_tokens,
|
||||
context_tokens,
|
||||
context_tokens.new_full((), self.ngram_eos_token_id),
|
||||
)
|
||||
)
|
||||
return context
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_inputs(input_batch, req_states)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs_padded + 1]
|
||||
query_start_loc.copy_(input_batch.query_start_loc[: num_reqs_padded + 1])
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=self._prepare_ngram_context(input_batch, req_states),
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
def prepare_dummy_inputs(
|
||||
self,
|
||||
num_reqs: int,
|
||||
num_tokens: int,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs + 1]
|
||||
query_start_loc[0] = 0
|
||||
tokens_per_req, num_extra_tokens = divmod(num_tokens, num_reqs)
|
||||
query_lens = torch.full(
|
||||
(num_reqs,),
|
||||
tokens_per_req,
|
||||
dtype=query_start_loc.dtype,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
if num_extra_tokens > 0:
|
||||
query_lens[-num_extra_tokens:] += 1
|
||||
torch.cumsum(query_lens, dim=0, out=query_start_loc[1:])
|
||||
|
||||
ngram_context = self.ngram_context[:num_reqs]
|
||||
ngram_context.fill_(self.ngram_eos_token_id)
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=ngram_context,
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpModelState"]
|
||||
@@ -0,0 +1,462 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-only Qwen4Exp MTP (Multi-Token Predictor) model.
|
||||
|
||||
The MTP draft model reuses the Qwen4Exp backbone (PLE/HC/MoE) but:
|
||||
- drops all multi-modal handling (text-only),
|
||||
- forces PLE off while keeping the main model's HC stream count,
|
||||
- fuses the backbone hidden and the new-token embedding via
|
||||
``residual_linear_shared`` (fc_embedding + shared fc_hidden) instead of
|
||||
the ``Linear(2H, H)`` + repeat used by other MTP variants,
|
||||
- emits TWO hidden streams per step (scheme A): a single stream [T, H]
|
||||
(final-mixer collapsed, fed to the LM head) and a pre-final-mixer
|
||||
multi stream [T, hc_count*H] (fed to the next draft step).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import VllmConfig, replace, set_current_vllm_config
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
is_model_fused_shared_expert_compatible,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
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.utils import configure_quant_config
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5Model
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
PPMissingLayer,
|
||||
WeightsMapper,
|
||||
get_draft_quant_config,
|
||||
make_empty_intermediate_tensors_factory,
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
_HC_WEIGHTS_MAPPER,
|
||||
_QWEN4_EXP_IGNORED_MISSING_SUFFIXES,
|
||||
Qwen4ExpDecoderLayer,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
)
|
||||
|
||||
|
||||
def _remap_ignored_layers(
|
||||
ignored_layers: list[str],
|
||||
mtp_start_layer_idx: int,
|
||||
) -> list[str]:
|
||||
remapped: list[str] = []
|
||||
for name in ignored_layers:
|
||||
if name.startswith("mtp."):
|
||||
new_name = re.sub(
|
||||
r"(?<=\.layers\.)\d+",
|
||||
lambda m: str(mtp_start_layer_idx + int(m.group(0))),
|
||||
name,
|
||||
)
|
||||
remapped.append(new_name)
|
||||
else:
|
||||
remapped.append(name)
|
||||
return remapped
|
||||
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
):
|
||||
if name.startswith(checkpoint_prefix):
|
||||
name = name.removeprefix(checkpoint_prefix)
|
||||
break
|
||||
|
||||
if name.startswith("embed_tokens."):
|
||||
name = f"model.{name}"
|
||||
if name.startswith("model.mtp."):
|
||||
name = name.removeprefix("model.")
|
||||
if name.startswith("mtp.shared_head.head."):
|
||||
return name.replace("mtp.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.shared_head.head."):
|
||||
return name.replace("model.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("shared_head.head."):
|
||||
return name.replace("shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.lm_head."):
|
||||
return name.removeprefix("model.")
|
||||
if name.startswith("mtp."):
|
||||
return name.replace("mtp.", "model.", 1)
|
||||
if name.startswith("model.embed_tokens.") or name.startswith("lm_head."):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _make_draft_vllm_config(
|
||||
vllm_config: VllmConfig,
|
||||
mtp_start_layer_idx: int,
|
||||
) -> VllmConfig:
|
||||
"""Ensure that the draft model config is set in the vLLM config."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is None or speculative_config.draft_model_config is None:
|
||||
raise ValueError("speculative_config.draft_model_config must be set")
|
||||
|
||||
draft_quant_config = get_draft_quant_config(vllm_config)
|
||||
|
||||
# inject packed and ignored modules to the quantization config of draft model
|
||||
if draft_quant_config is not None:
|
||||
configure_quant_config(draft_quant_config, Qwen4ExpMTP)
|
||||
ignored_layers = getattr(draft_quant_config, "ignored_layers", None)
|
||||
if ignored_layers:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"ignored_layers",
|
||||
_remap_ignored_layers(ignored_layers, mtp_start_layer_idx),
|
||||
)
|
||||
exclude_modules = getattr(draft_quant_config, "exclude_modules", None)
|
||||
if exclude_modules:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"exclude_modules",
|
||||
_remap_ignored_layers(exclude_modules, mtp_start_layer_idx),
|
||||
)
|
||||
|
||||
draft_vllm_config = replace(
|
||||
vllm_config,
|
||||
model_config=speculative_config.draft_model_config,
|
||||
)
|
||||
# VllmConfig post-init derives the target quant config, so restore the
|
||||
# independently resolved draft quant config after replacement.
|
||||
draft_vllm_config.quant_config = draft_quant_config
|
||||
return draft_vllm_config
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
|
||||
model_config = vllm_config.model_config
|
||||
config: Qwen4ExpTextConfig = model_config.hf_text_config
|
||||
|
||||
self.config = config
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
self.num_mtp_layers = getattr(config, "mtp_num_hidden_layers", 1)
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.hc_count = config.hc_count
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, self.hidden_size)
|
||||
draft_vllm_config = _make_draft_vllm_config(
|
||||
vllm_config,
|
||||
self.mtp_start_layer_idx,
|
||||
)
|
||||
with set_current_vllm_config(draft_vllm_config, prefix=prefix):
|
||||
# residual_linear_shared fusion: fc_embedding projects the token
|
||||
# embedding, fc_hidden (shared across HC branches) projects the
|
||||
# backbone hidden; the embedding is added as a residual to every
|
||||
# branch (see mtp_residual_linear_shared.md).
|
||||
self.fc_embedding = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_embedding",
|
||||
)
|
||||
self.fc_hidden = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_hidden",
|
||||
)
|
||||
self.layers = nn.ModuleList(
|
||||
Qwen4ExpDecoderLayer(
|
||||
draft_vllm_config,
|
||||
layer_type="full_attention",
|
||||
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
|
||||
)
|
||||
for idx in range(self.num_mtp_layers)
|
||||
)
|
||||
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
|
||||
self.layers,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
"mlp",
|
||||
)
|
||||
|
||||
self.pre_fc_norm_embedding = GemmaRMSNorm(
|
||||
self.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
self.pre_fc_norm_hidden = GemmaRMSNorm(
|
||||
self.hidden_size * self.hc_count, eps=config.rms_norm_eps
|
||||
)
|
||||
# HC final mixer collapses the multi stream into [T, H] for the LM head.
|
||||
hc_config = HyperConnectionConfig(
|
||||
hc_count=config.hc_count,
|
||||
hidden_size=config.hidden_size,
|
||||
params_dtype=torch.bfloat16,
|
||||
hc_lowrank=config.hc_lowrank,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
hc_per_branch_norm=True,
|
||||
)
|
||||
self.hyper_connection_mixer = GatedResidual(
|
||||
hc_config,
|
||||
use_combine=False,
|
||||
prefix=maybe_prefix(prefix, "hyper_connection_mixer"),
|
||||
)
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states"], self.hidden_size * self.hc_count
|
||||
)
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
attention is not None
|
||||
and getattr(attention, "indexer", None) is not None
|
||||
):
|
||||
yield attention
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
selected = buffer.index_select(0, row_indices)
|
||||
buffer[:num_rows].copy_(selected)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
hc_count = self.hc_count
|
||||
hidden_size = self.hidden_size
|
||||
|
||||
if get_pp_group().is_first_rank:
|
||||
assert hidden_states is not None
|
||||
if inputs_embeds is None:
|
||||
assert input_ids is not None
|
||||
inputs_embeds = self.embed_input_ids(input_ids)
|
||||
# Embedding branch: pre-norm -> fc_embedding -> [T, H].
|
||||
inputs_embeds = self.pre_fc_norm_embedding(inputs_embeds)
|
||||
inputs_embeds = self.fc_embedding(inputs_embeds)
|
||||
|
||||
# Backbone hidden is multi-stream [T, hc_count*H] (scheme A:
|
||||
# the main model truly emits the pre-final-mixer multi stream
|
||||
# on the first step; subsequent steps reuse the prior draft
|
||||
# step's multi stream).
|
||||
num_tokens = hidden_states.shape[0]
|
||||
hidden_states = hidden_states.view(num_tokens, hc_count, hidden_size)
|
||||
hidden_states = self.pre_fc_norm_hidden(hidden_states.flatten(-2)).view(
|
||||
num_tokens, hc_count, hidden_size
|
||||
)
|
||||
hidden_states = self.fc_hidden(hidden_states)
|
||||
# Add the embedding residual to every branch, then fold back
|
||||
# to [T, hc_count*H] (HC outer, HS inner) for the HC decoder.
|
||||
hidden_states = inputs_embeds.unsqueeze(-2) + hidden_states
|
||||
hidden_states = hidden_states.flatten(-2)
|
||||
else:
|
||||
assert intermediate_tensors is not None
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
layer = self.layers[current_step_idx]
|
||||
hidden_states, block_output, injection = layer(
|
||||
hidden_states=hidden_states,
|
||||
prev_block_output=None,
|
||||
prev_injection=None,
|
||||
positions=positions,
|
||||
input_ids=None,
|
||||
query_start_loc=None,
|
||||
ngram_context=None,
|
||||
)
|
||||
if not get_pp_group().is_last_rank:
|
||||
# As in the target model, PP carries a materialized tensor rather
|
||||
# than the delayed hidden/output/injection tuple.
|
||||
hidden_states = layer.mlp_hyper_connection.combine(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
return IntermediateTensors({"hidden_states": hidden_states})
|
||||
|
||||
# Last PP rank finalize. Keep both:
|
||||
# (A) sample_hidden_states [T, H] -> single stream for the LM head
|
||||
# (B) multi_hidden [T, hc_count*H] -> pre-final-mixer multi stream
|
||||
# for the next draft step (zero extra compute, just kept).
|
||||
multi_hidden, sample_hidden_states, _ = (
|
||||
self.hyper_connection_mixer.combine_and_mix(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
)
|
||||
return sample_hidden_states, multi_hidden
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
weights = maybe_fuse_shared_experts(
|
||||
weights,
|
||||
enabled=self.is_fused_shared_expert_enabled,
|
||||
n_routed_experts=getattr(self.config, "num_experts", 0) or 0,
|
||||
n_shared_experts=1,
|
||||
ckpt_prefix="mlp.shared_expert",
|
||||
)
|
||||
mapper = self.hf_to_vllm_mapper | WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(weights, mapper=mapper)
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMTP(nn.Module, SupportsPP, Qwen4ExpMixtureOfExperts):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
"in_proj_qkvz": ["in_proj_qkv", "in_proj_z"],
|
||||
"in_proj_ba": ["in_proj_b", "in_proj_a"],
|
||||
"input_mix_weight_down_block_inject": [
|
||||
"input_mix_weight_down",
|
||||
"block_inject_weight",
|
||||
"_input_mix_padding",
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
|
||||
self.vllm_config = vllm_config
|
||||
cache_config = vllm_config.cache_config
|
||||
if cache_config.mamba_cache_mode == "all":
|
||||
raise NotImplementedError(
|
||||
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
|
||||
"please use '--mamba-cache-mode=align' instead"
|
||||
)
|
||||
|
||||
self.quant_config = vllm_config.quant_config
|
||||
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.model = Qwen4ExpMultiTokenPredictor(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "mtp"),
|
||||
)
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head = self.model.embed_tokens
|
||||
else:
|
||||
self.lm_head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
else:
|
||||
self.lm_head = PPMissingLayer()
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
self.make_empty_intermediate_tensors = (
|
||||
self.model.make_empty_intermediate_tensors
|
||||
)
|
||||
self.set_moe_parameters(self.model.layers)
|
||||
enable_qwen4_exp_low_latency_gemm(self, vllm_config.model_config.dtype)
|
||||
|
||||
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 | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
return self.model(
|
||||
input_ids,
|
||||
positions,
|
||||
hidden_states,
|
||||
intermediate_tensors,
|
||||
inputs_embeds,
|
||||
spec_step_idx=spec_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int = 0
|
||||
) -> torch.Tensor | None:
|
||||
return self.logits_processor(self.lm_head, hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
def remap_weight_names():
|
||||
for name, weight in weights:
|
||||
remapped_name = _remap_mtp_weight_name(name)
|
||||
if remapped_name is not None:
|
||||
yield remapped_name, weight
|
||||
|
||||
mapper = WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(remap_weight_names(), mapper=mapper)
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpMTP", "Qwen4ExpMultiTokenPredictor"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm Qwen4Exp kernels; import leaf modules directly."""
|
||||
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm HyperConnection kernels for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_gemma_rmsnorm_kernel(
|
||||
x_ptr,
|
||||
w_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
NUM_GROUPS: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
GROUP_DIM: tl.constexpr = DIM // NUM_GROUPS
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(GROUP_DIM)
|
||||
|
||||
pid = tl.program_id(0)
|
||||
group_id = pid % NUM_GROUPS
|
||||
row = pid // NUM_GROUPS
|
||||
|
||||
offs_g = tl.arange(0, BLOCK_SIZE)
|
||||
offsets = group_id * GROUP_DIM + offs_g
|
||||
mask = offs_g < GROUP_DIM
|
||||
# A [GROUP_DIM] affine is shared; a [DIM] affine follows the grouped
|
||||
# checkpoint layout.
|
||||
w_offs = offs_g if W_SHARED else offsets
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0).to(tl.float32)
|
||||
w = tl.load(w_ptr + w_offs, mask, other=0.0)
|
||||
|
||||
rrms = tl.rsqrt(tl.sum(x * x) / GROUP_DIM + EPS)
|
||||
# Gemma's (1 + w) affine is written this way to lower to an FMA.
|
||||
y = x * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offsets, y, mask)
|
||||
|
||||
|
||||
def _grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
N, DIM = x.shape
|
||||
assert x.stride(1) == 1, "grouped Gemma RMSNorm requires unit inner stride"
|
||||
assert weight.is_contiguous(), "grouped Gemma RMSNorm weight must be contiguous"
|
||||
assert DIM % num_groups == 0
|
||||
group_dim = DIM // num_groups
|
||||
assert weight.numel() in (group_dim, DIM)
|
||||
|
||||
y = x.new_empty(x.shape)
|
||||
_grouped_gemma_rmsnorm_kernel[(N * num_groups,)](
|
||||
x,
|
||||
weight,
|
||||
y,
|
||||
x.stride(0),
|
||||
y.stride(0),
|
||||
DIM,
|
||||
num_groups,
|
||||
W_SHARED=weight.numel() == group_dim,
|
||||
EPS=eps,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return y
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_silu_kernel(
|
||||
x_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(DIM)
|
||||
|
||||
row = tl.program_id(0)
|
||||
offs = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs < DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offs, mask).to(tl.float32) / HC
|
||||
y = x * tl.sigmoid(x)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask)
|
||||
|
||||
|
||||
def _hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
num_tokens, DIM = x.shape
|
||||
assert x.stride(1) == 1
|
||||
|
||||
output = x.new_empty(x.shape)
|
||||
_hc_silu_kernel[(num_tokens,)](
|
||||
x,
|
||||
output,
|
||||
x.stride(0),
|
||||
output.stride(0),
|
||||
DIM=DIM,
|
||||
HC=hc_count,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_gate_mix_kernel(
|
||||
x_ptr,
|
||||
g_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_DIM: tl.constexpr = DIM // HC
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs_inner < HC_DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# The constexpr loop is unrolled and keeps one stream live at a time.
|
||||
# Materializing [HC, BLOCK_SIZE] more than doubles latency at large M.
|
||||
acc = tl.zeros([BLOCK_SIZE], dtype=tl.float32)
|
||||
for stream in tl.static_range(HC):
|
||||
offsets = stream * HC_DIM + offs_inner
|
||||
g = tl.load(g_ptr + row * stride_g + offsets, mask, other=0.0)
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0)
|
||||
acc += tl.sigmoid(g.to(tl.float32)) * x.to(tl.float32)
|
||||
acc /= HC
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs_inner, acc, mask)
|
||||
|
||||
|
||||
def _hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
N, DIM = gate.shape
|
||||
assert x.shape == gate.shape
|
||||
assert DIM % hc_count == 0
|
||||
assert x.stride(1) == 1
|
||||
assert gate.stride(1) == 1
|
||||
|
||||
HC_DIM = DIM // hc_count
|
||||
out = x.new_empty(N, HC_DIM)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_gate_mix_kernel[(N, triton.cdiv(HC_DIM, BLOCK_SIZE))](
|
||||
x,
|
||||
gate,
|
||||
out,
|
||||
x.stride(0),
|
||||
gate.stride(0),
|
||||
out.stride(0),
|
||||
DIM,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
out_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
offs = offs_hc[:, None] * HC_DIM + offs_inner[None, :]
|
||||
mask = mask_hc[:, None] & mask_inner[None, :]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask, other=0.0)
|
||||
|
||||
# Keeping HC as a broadcast dimension is faster here than four separate
|
||||
# residual load/store sequences.
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
out = res.to(tl.float32) + block.to(tl.float32)[None, :] * inj[:, None]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask)
|
||||
|
||||
|
||||
def _hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_kernel[(N, triton.cdiv(hc_dim, BLOCK_SIZE))](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
out,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_norm_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
w_ptr,
|
||||
out_ptr,
|
||||
y_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
stride_y,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
NUM_TILES: tl.constexpr = triton.cdiv(HC_DIM, BLOCK_SIZE)
|
||||
NUM_TILES_PAD: tl.constexpr = triton.next_power_of_2(NUM_TILES)
|
||||
|
||||
row = tl.program_id(0)
|
||||
stream = tl.program_id(1)
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
tile_ids = tl.arange(0, NUM_TILES_PAD)
|
||||
offs_inner = tile_ids[:, None] * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)[None, :]
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs = stream * HC_DIM + offs_inner
|
||||
# Shared norm weights repeat across streams; per-branch weights use the
|
||||
# same flattened HC layout as the residual.
|
||||
w_offs = offs_inner if W_SHARED else offs
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# Start the uncached residual load first, then issue the other combine
|
||||
# loads before consuming any of them.
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask_inner, other=0.0)
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
inj = tl.sum(tl.where(offs_hc == stream, inj, 0.0))
|
||||
# Round the materialized combine result before normalization. This matches
|
||||
# the unfused combine -> RMSNorm boundary.
|
||||
out = (res.to(tl.float32) + block.to(tl.float32) * inj).to(out_ptr.dtype.element_ty)
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask_inner)
|
||||
|
||||
out = out.to(tl.float32)
|
||||
# Keep the two-axis reduction: flattening the padded tile is ~40% slower
|
||||
# at decode sizes.
|
||||
sum_sq = tl.sum(tl.sum(out * out, axis=1), axis=0)
|
||||
rrms = tl.rsqrt(sum_sq / HC_DIM + EPS)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
# Loading the weight earlier helps decode but keeps the tile live across
|
||||
# the reduction and regresses larger batches, so defer it to the norm.
|
||||
w = tl.load(w_ptr + w_offs, mask_inner, other=0.0)
|
||||
y = out * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask_inner)
|
||||
|
||||
|
||||
def _hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
assert norm_weight.is_contiguous()
|
||||
assert norm_weight.numel() in (hc_dim, DIM)
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
y = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_norm_kernel[(N, hc_count)](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
out,
|
||||
y,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
y.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
W_SHARED=norm_weight.numel() == hc_dim,
|
||||
EPS=eps,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out, y
|
||||
|
||||
|
||||
def _same_shape_fake(x: torch.Tensor, *args) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _hc_gate_mix_fake(
|
||||
x: torch.Tensor, gate: torch.Tensor, hc_count: int
|
||||
) -> torch.Tensor:
|
||||
del gate
|
||||
return x.new_empty((x.shape[0], x.shape[1] // hc_count))
|
||||
|
||||
|
||||
def _hc_combine_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
del block_output, injection_logits, hc_count
|
||||
return residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
def _hc_combine_norm_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del block_output, injection_logits, norm_weight, eps, hc_count
|
||||
return residual.new_empty(residual.shape), residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_grouped_gemma_rmsnorm",
|
||||
op_func=_grouped_gemma_rmsnorm,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_silu",
|
||||
op_func=_hc_silu,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_gate_mix",
|
||||
op_func=_hc_gate_mix,
|
||||
fake_impl=_hc_gate_mix_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine",
|
||||
op_func=_hc_combine,
|
||||
fake_impl=_hc_combine_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine_norm",
|
||||
op_func=_hc_combine_norm,
|
||||
fake_impl=_hc_combine_norm_fake,
|
||||
)
|
||||
|
||||
|
||||
def grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_grouped_gemma_rmsnorm(x, weight, eps, num_groups)
|
||||
|
||||
|
||||
def hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_silu(x, hc_count)
|
||||
|
||||
|
||||
def hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_gate_mix(x, gate, hc_count)
|
||||
|
||||
|
||||
def hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine(
|
||||
residual, block_output, injection_logits, hc_count
|
||||
)
|
||||
|
||||
|
||||
def hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine_norm(
|
||||
residual,
|
||||
block_output,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
eps,
|
||||
hc_count,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"grouped_gemma_rmsnorm",
|
||||
"hc_combine",
|
||||
"hc_combine_norm",
|
||||
"hc_gate_mix",
|
||||
"hc_silu",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,474 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""AMD ROCm QSA owner with Triton kernels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.attention.attention import (
|
||||
set_default_quant_scales,
|
||||
)
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding import get_rope
|
||||
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
canonicalize_singleton_dim_strides,
|
||||
direct_register_custom_op,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionType,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.fa_utils import is_flash_attn_varlen_func_available
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionBackend,
|
||||
FlashAttentionImpl,
|
||||
FlashAttentionMetadata,
|
||||
FlashAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheSpec,
|
||||
get_kv_quant_mode,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import QSAForwardMetadata
|
||||
from . import model
|
||||
from .indexer_qsa import QSAIndexer
|
||||
|
||||
|
||||
class Qwen4ExpQSAMetadataBuilder(FlashAttentionMetadataBuilder):
|
||||
"""Flash metadata supporting uniform decode and target-verify graphs."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
|
||||
"""FullAttentionSpec backend used by the merged QSA owner."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_QSA_TRITON"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
# QSA consumes manager pages directly and does not use FA4 paged attention.
|
||||
return [MultipleOf(16)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[Qwen4ExpQSAFlashAttentionImpl]:
|
||||
return Qwen4ExpQSAFlashAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[Qwen4ExpQSAMetadataBuilder]:
|
||||
return Qwen4ExpQSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_kv_connector(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
"""Run paged sparse GQA with the QSA Triton kernel."""
|
||||
|
||||
supports_dcp: bool = False
|
||||
supports_pcp: bool = False
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if not is_flash_attn_varlen_func_available():
|
||||
raise NotImplementedError("Qwen4Exp QSA requires FlashAttention")
|
||||
if self.dcp_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support decode context parallelism"
|
||||
)
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
self.supports_quant_query_input = False
|
||||
|
||||
def forward_qsa(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
attn_metadata: FlashAttentionMetadata,
|
||||
output: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
output_block_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
del key, value
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError("QSA does not support fused output quantization")
|
||||
if self.alibi_slopes is not None or self.sinks is not None:
|
||||
raise NotImplementedError("QSA does not support ALiBi or attention sinks")
|
||||
if self.sliding_window != (-1, -1):
|
||||
raise NotImplementedError("QSA does not support sliding-window attention")
|
||||
|
||||
num_tokens = attn_metadata.num_actual_tokens
|
||||
output.zero_()
|
||||
if num_tokens == 0:
|
||||
return output
|
||||
|
||||
topk_buffer = getattr(layer, "topk_indices_buffer", None)
|
||||
if topk_buffer is None:
|
||||
raise RuntimeError("QSA owner did not provide its top-k buffer")
|
||||
logical_indices = topk_buffer[:num_tokens]
|
||||
token_to_req = token_to_req[:num_tokens]
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
|
||||
key_cache = canonicalize_singleton_dim_strides(key_cache)
|
||||
value_cache = canonicalize_singleton_dim_strides(value_cache)
|
||||
if key_cache.dtype != torch.bfloat16 or query.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 Q/K/V")
|
||||
|
||||
from .ops.qsa import qsa_sparse_paged_attention
|
||||
|
||||
qsa_sparse_paged_attention(
|
||||
query[:num_tokens],
|
||||
key_cache,
|
||||
value_cache,
|
||||
logical_indices,
|
||||
attn_metadata.block_table,
|
||||
token_to_req,
|
||||
output[:num_tokens],
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
"""Merged Qwen full-attention owner with a QSA index side branch."""
|
||||
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
reduce_results: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
nn.Module.__init__(self)
|
||||
cache_config = vllm_config.cache_config
|
||||
model_config = vllm_config.model_config
|
||||
if cache_config is None:
|
||||
raise ValueError("Qwen4Exp QSA requires a paged KV cache")
|
||||
if model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
if cache_config.cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if getattr(quant_config, "kv_cache_scheme", None) is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support KV quantization")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
if (
|
||||
parallel_config.prefill_context_parallel_size > 1
|
||||
or parallel_config.decode_context_parallel_size > 1
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support context parallelism"
|
||||
)
|
||||
if not getattr(config, "is_causal", True):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires causal decoder attention")
|
||||
|
||||
self.config = config
|
||||
self.hidden_size = int(config.hidden_size)
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.total_num_heads = int(config.num_attention_heads)
|
||||
if self.total_num_heads % tp_size:
|
||||
raise ValueError("QSA attention heads must be divisible by TP size")
|
||||
self.num_heads = self.total_num_heads // tp_size
|
||||
self.total_num_kv_heads = int(config.num_key_value_heads)
|
||||
if self.total_num_kv_heads >= tp_size:
|
||||
if self.total_num_kv_heads % tp_size:
|
||||
raise ValueError("QSA KV heads must be divisible by TP size")
|
||||
elif tp_size % self.total_num_kv_heads:
|
||||
raise ValueError("TP size must be divisible by replicated QSA KV heads")
|
||||
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
||||
self.head_dim = int(config.head_dim or self.hidden_size // self.num_heads)
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.dual_chunk_attention_config = getattr(
|
||||
config, "dual_chunk_attention_config", None
|
||||
)
|
||||
if self.dual_chunk_attention_config is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support dual-chunk RoPE")
|
||||
# Qwen4Exp full-attention checkpoints always pack a sigmoid output
|
||||
# gate next to Q, even when an inherited config default says otherwise.
|
||||
self.attn_output_gate = True
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
self.hidden_size,
|
||||
self.head_dim,
|
||||
self.total_num_heads * (1 + self.attn_output_gate),
|
||||
self.total_num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=model.without_modelopt_fp4(quant_config),
|
||||
prefix=f"{prefix}.qkv_proj",
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
self.total_num_heads * self.head_dim,
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
reduce_results=reduce_results,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o_proj",
|
||||
)
|
||||
self.rotary_emb = get_rope(
|
||||
head_size=self.head_dim,
|
||||
max_position=config.max_position_embeddings,
|
||||
rope_parameters=config.rope_parameters,
|
||||
)
|
||||
self.q_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
mm_config = model_config.multimodal_config
|
||||
text_only = mm_config is None or mm_config.language_model_only
|
||||
self.use_fused_qk_norm_rope_gate = (
|
||||
self.attn_output_gate
|
||||
and getattr(self.rotary_emb, "is_neox_style", False)
|
||||
and current_platform.is_cuda()
|
||||
and text_only
|
||||
)
|
||||
|
||||
self.layer_name = f"{prefix}.attn"
|
||||
self.attn_type = AttentionType.DECODER
|
||||
self.kv_cache_dtype = cache_config.cache_dtype
|
||||
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
|
||||
self.kv_cache_dtype, model_config
|
||||
)
|
||||
if self.kv_cache_torch_dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 cache storage")
|
||||
self.kv_sharing_target_layer_name = None
|
||||
self.kv_cache = torch.tensor([])
|
||||
set_default_quant_scales(self, register_buffer=True)
|
||||
|
||||
self.attn_backend = Qwen4ExpQSAFlashAttentionBackend
|
||||
self.impl = Qwen4ExpQSAFlashAttentionImpl(
|
||||
self.num_heads,
|
||||
self.head_dim,
|
||||
self.scaling,
|
||||
self.num_kv_heads,
|
||||
None,
|
||||
None,
|
||||
self.kv_cache_dtype,
|
||||
None,
|
||||
AttentionType.DECODER,
|
||||
None,
|
||||
)
|
||||
self.indexer = QSAIndexer(
|
||||
vllm_config=vllm_config,
|
||||
config=config,
|
||||
layer_id=layer_id,
|
||||
rotary_emb=self.rotary_emb,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.indexer",
|
||||
)
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.register_buffer(
|
||||
"topk_indices_buffer",
|
||||
torch.empty(
|
||||
max_tokens,
|
||||
self.indexer.output_width,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if self.layer_name in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {self.layer_name}")
|
||||
static_context[self.layer_name] = self
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return self.attn_backend
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
return FullAttentionSpec(
|
||||
block_size=vllm_config.cache_config.block_size,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
head_size=self.head_dim,
|
||||
head_size_v=self.head_dim,
|
||||
dtype=self.kv_cache_torch_dtype,
|
||||
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
|
||||
)
|
||||
|
||||
def _run_qsa(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
output.zero_()
|
||||
return
|
||||
main_metadata = cast(FlashAttentionMetadata, metadata[self.layer_name])
|
||||
if self.kv_cache.numel() == 0:
|
||||
raise RuntimeError("QSA main K/V cache is not bound")
|
||||
|
||||
num_tokens = main_metadata.num_actual_tokens
|
||||
side_metadata = cast(
|
||||
QSAForwardMetadata,
|
||||
metadata[self.indexer.raw_key_cache.prefix],
|
||||
)
|
||||
if side_metadata.num_actual_tokens != num_tokens:
|
||||
raise RuntimeError("QSA main and side metadata token counts disagree")
|
||||
selected = self.indexer(
|
||||
hidden_states,
|
||||
positions,
|
||||
self.topk_indices_buffer[:num_tokens],
|
||||
)
|
||||
if selected.shape != (
|
||||
num_tokens,
|
||||
self.indexer.output_width,
|
||||
):
|
||||
raise RuntimeError("QSA indexer returned an invalid selection shape")
|
||||
impl = cast(Qwen4ExpQSAFlashAttentionImpl, self.impl)
|
||||
impl.do_kv_cache_update(
|
||||
self,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata.slot_mapping,
|
||||
)
|
||||
impl.forward_qsa(
|
||||
self,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata,
|
||||
output,
|
||||
token_to_req=side_metadata.token_to_req,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q, k, v, gate = self._project_qkv_gate(qkv, positions)
|
||||
num_tokens = hidden_states.shape[0]
|
||||
query = q.view(num_tokens, self.num_heads, self.head_dim)
|
||||
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
attn_output = torch.empty_like(query)
|
||||
encoded_layer_name = _encode_layer_name(self.layer_name)
|
||||
if current_platform.opaque_attention_op():
|
||||
torch.ops.vllm.qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
else:
|
||||
qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
flat_output = attn_output.view(num_tokens, -1)
|
||||
if gate is not None:
|
||||
flat_output = flat_output * torch.sigmoid(gate)
|
||||
output, _ = self.o_proj(flat_output)
|
||||
return output
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Run the complete QSA state/update/attend transaction."""
|
||||
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
if not isinstance(layer, Qwen4ExpQSAAttention):
|
||||
raise TypeError(f"{layer_name} is not a Qwen4Exp QSA owner")
|
||||
layer._run_qsa(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
output,
|
||||
)
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
del hidden_states, positions, query, key, value, output, layer_name
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_qsa_with_output",
|
||||
op_func=qwen4_exp_qsa_with_output,
|
||||
mutates_args=["output"],
|
||||
fake_impl=qwen4_exp_qsa_with_output_fake,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSAIndexer",
|
||||
"Qwen4ExpQSAAttention",
|
||||
"Qwen4ExpQSAFlashAttentionBackend",
|
||||
"Qwen4ExpQSAFlashAttentionImpl",
|
||||
"qwen4_exp_qsa_with_output",
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Common Qwen4Exp model components."""
|
||||
|
||||
from .hyperconnection import (
|
||||
GatedResidual,
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionBase,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,250 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606).
|
||||
|
||||
The two concrete variants are:
|
||||
- ``HyperConnectionBase`` - simple average pooling across hc_count parallel
|
||||
streams (equivalent to hyperconnection_average).
|
||||
- ``GatedResidual`` - learnable low-rank gated mixing and injection
|
||||
(gated_residual).
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout). The local torch
|
||||
implementation consumes the hyper input viewed as ``[..., HC, HS]``.
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config, role="attn")
|
||||
self.mlp_hc = GatedResidual(hc_config, role="mlp")
|
||||
|
||||
hidden_states, residual = self.attn_hc.mix(hidden_states)
|
||||
hidden_states = attention(hidden_states)
|
||||
hidden_states = self.attn_hc.combine(hidden_states, residual)
|
||||
|
||||
hidden_states, residual = self.mlp_hc.mix(hidden_states)
|
||||
hidden_states = mlp(hidden_states)
|
||||
hidden_states = self.mlp_hc.combine(hidden_states, residual)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config
|
||||
# ---------------------------------------------------------------------------
|
||||
@dataclass
|
||||
class HyperConnectionConfig:
|
||||
"""Configuration shared by all HyperConnection variants."""
|
||||
|
||||
hc_count: int = 4
|
||||
hidden_size: int = 64
|
||||
params_dtype: torch.dtype = torch.bfloat16
|
||||
mtp_hc: bool = False
|
||||
hc_lowrank: int = 16
|
||||
rms_norm_eps: float = 1e-6
|
||||
hc_per_branch_norm: bool = False
|
||||
|
||||
|
||||
class GroupedGemmaRMSNorm(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
eps: float,
|
||||
group_size: int | None,
|
||||
dtype: torch.dtype | None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if group_size is not None and hidden_size % group_size:
|
||||
raise ValueError(
|
||||
f"hidden_size ({hidden_size}) must be divisible by "
|
||||
f"group_size ({group_size})"
|
||||
)
|
||||
self.variance_epsilon = eps
|
||||
self.group_size = group_size
|
||||
self.weight = nn.Parameter(torch.zeros(hidden_size, dtype=dtype))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.float()
|
||||
if self.group_size is None:
|
||||
variance = hidden_states.square().mean(dim=-1, keepdim=True)
|
||||
normalized = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
else:
|
||||
grouped = hidden_states.unflatten(
|
||||
-1, (hidden_states.shape[-1] // self.group_size, self.group_size)
|
||||
)
|
||||
variance = grouped.square().mean(dim=-1, keepdim=True)
|
||||
normalized = (
|
||||
grouped * torch.rsqrt(variance + self.variance_epsilon)
|
||||
).flatten(-2)
|
||||
return (normalized * (1.0 + self.weight.float())).to(input_dtype)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Average-pooling variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class HyperConnectionBase(nn.Module):
|
||||
"""Average-pooling HyperConnection (``hyperconnection_average``).
|
||||
|
||||
Splits the incoming ``[..., HC*HS]`` tensor (HC outer, HS inner) into
|
||||
``HC`` parallel streams, averages them for the block input, and
|
||||
broadcasts the block output back to every stream.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
layer_idx: int | None = None,
|
||||
role: str | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_idx = layer_idx
|
||||
self.role = role
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
def mix(self, hyper_input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Average the HC streams into a single block input."""
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
# [*, HC, HS] — mean over HC (dim=-2).
|
||||
unflat = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
mixed_input = unflat.mean(dim=-2)
|
||||
return mixed_input, hyper_input
|
||||
|
||||
def combine(
|
||||
self, block_output: torch.Tensor, residual: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Broadcast the block output back to every stream."""
|
||||
assert residual.shape[-1] == self.hc_count * self.hidden_size
|
||||
assert block_output.shape[-1] == self.hidden_size
|
||||
residual_reshaped = residual.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
combined = residual_reshaped + block_output.unsqueeze(-2)
|
||||
return combined.flatten(-2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(HyperConnectionBase):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``mix()`` applies GemmaRMSNorm per HC stream and projects through a
|
||||
low-rank sigmoid gate to produce a single block input. ``combine()``
|
||||
injects the block output back into each stream through a learned
|
||||
per-stream injection weight.
|
||||
|
||||
This implementation uses only PyTorch operators. Tensor-parallel
|
||||
collectives are supplied by its caller.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
layer_idx: int | None = None,
|
||||
role: str | None = None,
|
||||
use_mix: bool = True,
|
||||
use_combine: bool = True,
|
||||
) -> None:
|
||||
super().__init__(config, layer_idx, role)
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- raw Linear weights (checkpoint-compatible) ----------------------
|
||||
if use_mix:
|
||||
self.input_mix_weight_down = nn.Linear(
|
||||
self.hyper_hidden_size,
|
||||
config.hc_lowrank,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
self.input_mix_weight_up = nn.Linear(
|
||||
config.hc_lowrank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
if use_combine:
|
||||
self.block_inject_weight = nn.Linear(
|
||||
self.hyper_hidden_size,
|
||||
self.hc_count,
|
||||
bias=False,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
def _normalize(self, hyper_input: torch.Tensor) -> torch.Tensor:
|
||||
if self.config.hc_per_branch_norm:
|
||||
return self.hc_norm(hyper_input)
|
||||
return self.hc_norm(
|
||||
hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
).flatten(-2)
|
||||
|
||||
def mix(
|
||||
self, hyper_input: torch.Tensor
|
||||
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
|
||||
"""Mix: RMSNorm -> low-rank gate -> gated mean."""
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
if not hasattr(self, "input_mix_weight_down"):
|
||||
raise RuntimeError("mix was disabled for this hyper-connection")
|
||||
hyper_input_normed = self._normalize(hyper_input)
|
||||
# Gate — original mix order: linear+silu then linear+sigmoid.
|
||||
gate = F.silu(
|
||||
F.linear(hyper_input_normed, self.input_mix_weight_down.weight)
|
||||
/ self.hc_count
|
||||
)
|
||||
gate = torch.sigmoid(F.linear(gate, self.input_mix_weight_up.weight)).unflatten(
|
||||
-1, (self.hc_count, self.hidden_size)
|
||||
)
|
||||
mixed_input = (
|
||||
gate * hyper_input_normed.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
).mean(dim=-2)
|
||||
return mixed_input.to(hyper_input.dtype), (hyper_input, hyper_input_normed)
|
||||
|
||||
def combine(
|
||||
self,
|
||||
block_output: torch.Tensor,
|
||||
residuals: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
if not hasattr(self, "block_inject_weight"):
|
||||
raise RuntimeError("combine was disabled for this hyper-connection")
|
||||
hyper_input, hyper_input_normed = residuals
|
||||
assert hyper_input.shape[-1] == self.hc_count * self.hidden_size
|
||||
assert block_output.shape[-1] == self.hidden_size
|
||||
residual = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
|
||||
# The paired mix keeps its normalized hyper input so combine uses the
|
||||
# same HC module's injection weight.
|
||||
injection_weight = 2.0 * torch.sigmoid(
|
||||
F.linear(hyper_input_normed, self.block_inject_weight.weight)
|
||||
/ self.hc_count
|
||||
)
|
||||
output = residual + block_output.unsqueeze(-2) * injection_weight.unsqueeze(-1)
|
||||
return output.flatten(-2).to(hyper_input.dtype)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionBase",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Common Qwen4Exp PLE helpers."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PLEShardOverlap:
|
||||
"""Source and destination slices for one checkpoint embedding shard."""
|
||||
|
||||
source_start: int
|
||||
destination_start: int
|
||||
row_count: int
|
||||
|
||||
|
||||
def compute_ple_shard_overlap(
|
||||
*,
|
||||
checkpoint_start: int,
|
||||
checkpoint_rows: int,
|
||||
tp_start: int,
|
||||
tp_end: int,
|
||||
) -> PLEShardOverlap | None:
|
||||
"""Compute the overlap of a checkpoint shard and one TP vocabulary range."""
|
||||
|
||||
if checkpoint_start < 0 or checkpoint_rows < 0:
|
||||
raise ValueError("checkpoint shard bounds must be non-negative")
|
||||
if tp_start < 0 or tp_end < tp_start:
|
||||
raise ValueError("invalid TP vocabulary range")
|
||||
checkpoint_end = checkpoint_start + checkpoint_rows
|
||||
overlap_start = max(checkpoint_start, tp_start)
|
||||
overlap_end = min(checkpoint_end, tp_end)
|
||||
if overlap_start >= overlap_end:
|
||||
return None
|
||||
return PLEShardOverlap(
|
||||
source_start=overlap_start - checkpoint_start,
|
||||
destination_start=overlap_start - tp_start,
|
||||
row_count=overlap_end - overlap_start,
|
||||
)
|
||||
|
||||
|
||||
def copy_ple_embedding_shard_(
|
||||
destination: torch.Tensor,
|
||||
loaded_weight: torch.Tensor,
|
||||
*,
|
||||
checkpoint_start: int,
|
||||
tp_start: int,
|
||||
tp_end: int,
|
||||
) -> int:
|
||||
"""Copy the overlapping rows of a PLE checkpoint shard into a TP table."""
|
||||
|
||||
if destination.ndim == 0 or loaded_weight.ndim != destination.ndim:
|
||||
raise ValueError("destination and loaded weight must have matching ranks")
|
||||
if destination.shape[1:] != loaded_weight.shape[1:]:
|
||||
raise ValueError(
|
||||
"embedding shard dimensions do not match: "
|
||||
f"{tuple(destination.shape[1:])} != {tuple(loaded_weight.shape[1:])}"
|
||||
)
|
||||
if destination.shape[0] < tp_end - tp_start:
|
||||
raise ValueError("destination does not cover the requested TP range")
|
||||
overlap = compute_ple_shard_overlap(
|
||||
checkpoint_start=checkpoint_start,
|
||||
checkpoint_rows=loaded_weight.shape[0],
|
||||
tp_start=tp_start,
|
||||
tp_end=tp_end,
|
||||
)
|
||||
if overlap is None:
|
||||
return 0
|
||||
source = loaded_weight.narrow(0, overlap.source_start, overlap.row_count)
|
||||
target = destination.narrow(0, overlap.destination_start, overlap.row_count)
|
||||
with torch.no_grad():
|
||||
target.copy_(source.to(device=target.device, dtype=target.dtype))
|
||||
return overlap.row_count
|
||||
|
||||
|
||||
class PLEVocabParallelEmbedding(VocabParallelEmbedding):
|
||||
"""Vocab-parallel embedding that accepts checkpoint row shards."""
|
||||
|
||||
def weight_loader(
|
||||
self,
|
||||
param: torch.Tensor,
|
||||
loaded_weight: torch.Tensor,
|
||||
checkpoint_start: int | None = None,
|
||||
) -> None:
|
||||
if checkpoint_start is None:
|
||||
super().weight_loader(param, loaded_weight)
|
||||
return
|
||||
copy_ple_embedding_shard_(
|
||||
param,
|
||||
loaded_weight,
|
||||
checkpoint_start=checkpoint_start,
|
||||
tp_start=self.shard_indices.org_vocab_start_index,
|
||||
tp_end=self.shard_indices.org_vocab_end_index,
|
||||
)
|
||||
@@ -0,0 +1,807 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Paged side-cache ownership and metadata for Qwen4Exp QSA.
|
||||
|
||||
Each QSA layer keeps a fixed circular buffer of raw index keys (the
|
||||
compressor state) and one compressed key. MRoPE models pack exact three-axis
|
||||
positions beside the raw keys; text models derive group positions from
|
||||
logical positions. The compressor state uses one block per request, while
|
||||
the compressed owner uses ``MLAAttentionSpec.tokens_per_state`` so its block
|
||||
table follows the main KV-cache lifecycle. Their physical tensor storage is
|
||||
shared by the generic cache-layout planner.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from typing import ClassVar
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import CacheConfig, VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionMetadata,
|
||||
AttentionMetadataBuilder,
|
||||
CommonAttentionMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
CircularBufferSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MLAAttentionSpec,
|
||||
)
|
||||
|
||||
|
||||
def canonical_qsa_rope_positions(positions: torch.Tensor) -> torch.Tensor:
|
||||
"""Return exact per-token positions as ``[tokens, 1, 3]`` int64 rows."""
|
||||
|
||||
if positions.ndim == 1:
|
||||
positions = positions.unsqueeze(0).expand(3, -1)
|
||||
elif positions.ndim != 2 or positions.shape[0] not in (1, 3):
|
||||
raise ValueError("QSA RoPE positions must be [tokens] or [1|3, tokens]")
|
||||
if positions.shape[0] == 1:
|
||||
positions = positions.expand(3, -1)
|
||||
return positions.transpose(0, 1).unsqueeze(1).to(torch.int64)
|
||||
|
||||
|
||||
def _logical_positions(
|
||||
query_start_loc: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
num_tokens: int,
|
||||
) -> torch.Tensor:
|
||||
if num_tokens == 0:
|
||||
return seq_lens.new_empty((0,), dtype=torch.int64)
|
||||
arange = torch.arange(num_tokens, device=query_start_loc.device)
|
||||
requests = token_to_req[:num_tokens].long()
|
||||
query_lens = torch.diff(query_start_loc)
|
||||
within_query = arange - query_start_loc.index_select(0, requests)
|
||||
return (
|
||||
seq_lens.index_select(0, requests).long()
|
||||
- query_lens.index_select(0, requests).long()
|
||||
+ within_query.long()
|
||||
)
|
||||
|
||||
|
||||
def _logical_to_physical_qsa_slots(
|
||||
block_table: torch.Tensor,
|
||||
request_indices: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
block_size: int,
|
||||
) -> torch.Tensor:
|
||||
if block_size <= 0:
|
||||
raise ValueError("QSA cache block size must be positive")
|
||||
if block_table.ndim != 2:
|
||||
raise ValueError("QSA block table must be two-dimensional")
|
||||
if request_indices.shape != logical_positions.shape:
|
||||
request_indices = torch.broadcast_to(request_indices, logical_positions.shape)
|
||||
|
||||
requests = request_indices.to(device=block_table.device, dtype=torch.long)
|
||||
positions = logical_positions.to(device=block_table.device, dtype=torch.long)
|
||||
valid = (requests >= 0) & (requests < block_table.shape[0]) & (positions >= 0)
|
||||
logical_blocks = torch.div(
|
||||
positions.clamp_min(0), block_size, rounding_mode="floor"
|
||||
)
|
||||
valid &= logical_blocks < block_table.shape[1]
|
||||
safe_requests = requests.clamp(0, max(block_table.shape[0] - 1, 0))
|
||||
safe_blocks = logical_blocks.clamp(0, max(block_table.shape[1] - 1, 0))
|
||||
if not all(block_table.shape):
|
||||
return torch.full_like(positions, PAD_SLOT_ID)
|
||||
physical_blocks = block_table[safe_requests, safe_blocks].long()
|
||||
valid &= physical_blocks >= 0
|
||||
slots = physical_blocks * block_size + positions.remainder(block_size)
|
||||
return torch.where(valid, slots, PAD_SLOT_ID)
|
||||
|
||||
|
||||
def circular_qsa_slot_mapping(
|
||||
block_table: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
compressor_state_size: int,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Map each request to its fixed physical block as a circular token ring."""
|
||||
|
||||
if compressor_state_size <= 0:
|
||||
raise ValueError("QSA circular buffer size must be positive")
|
||||
if block_table.ndim != 2:
|
||||
raise ValueError("QSA block table must be two-dimensional")
|
||||
|
||||
requests = token_to_req.to(device=block_table.device, dtype=torch.long)
|
||||
positions = logical_positions.to(device=block_table.device, dtype=torch.long)
|
||||
if not all(block_table.shape):
|
||||
slots = torch.full_like(positions, PAD_SLOT_ID)
|
||||
else:
|
||||
valid = (requests >= 0) & (requests < block_table.shape[0]) & (positions >= 0)
|
||||
safe_requests = requests.clamp(0, block_table.shape[0] - 1)
|
||||
physical_blocks = block_table[safe_requests, 0].long()
|
||||
valid &= physical_blocks >= 0
|
||||
slots = physical_blocks * compressor_state_size + positions.remainder(
|
||||
compressor_state_size
|
||||
)
|
||||
slots = torch.where(valid, slots, PAD_SLOT_ID)
|
||||
|
||||
if query_start_loc is not None:
|
||||
if query_start_loc.ndim != 1 or query_start_loc.shape[0] < 2:
|
||||
raise ValueError("QSA query starts must contain a terminal offset")
|
||||
query_start_loc = query_start_loc.to(block_table.device)
|
||||
num_requests = query_start_loc.shape[0] - 1
|
||||
safe_requests = requests.clamp(0, num_requests - 1)
|
||||
request_ends = query_start_loc.index_select(0, safe_requests + 1)
|
||||
rows = torch.arange(slots.numel(), device=slots.device)
|
||||
keep = (
|
||||
(requests >= 0)
|
||||
& (requests < num_requests)
|
||||
& (rows + compressor_state_size >= request_ends)
|
||||
)
|
||||
slots = torch.where(keep, slots, PAD_SLOT_ID)
|
||||
|
||||
slots = slots.to(torch.int64)
|
||||
if out is not None:
|
||||
out.fill_(PAD_SLOT_ID)
|
||||
out[: slots.numel()].copy_(slots)
|
||||
return out[: slots.numel()]
|
||||
return slots
|
||||
|
||||
|
||||
def compressed_qsa_slot_mapping(
|
||||
block_table: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Build boundary-only slots for an ``MLAAttentionSpec`` QSA cache."""
|
||||
|
||||
if storage_block_size <= 0 or compress_ratio <= 0:
|
||||
raise ValueError("QSA block size and compression ratio must be positive")
|
||||
compressed_positions = torch.div(
|
||||
logical_positions.clamp_min(0), compress_ratio, rounding_mode="floor"
|
||||
)
|
||||
slots = _logical_to_physical_qsa_slots(
|
||||
block_table,
|
||||
token_to_req,
|
||||
compressed_positions,
|
||||
storage_block_size,
|
||||
)
|
||||
valid = (logical_positions >= 0) & (
|
||||
(logical_positions + 1).remainder(compress_ratio) == 0
|
||||
)
|
||||
slots = torch.where(valid, slots, PAD_SLOT_ID).to(torch.int64)
|
||||
if out is not None:
|
||||
out.fill_(PAD_SLOT_ID)
|
||||
out[: slots.numel()].copy_(slots)
|
||||
return out[: slots.numel()]
|
||||
return slots
|
||||
|
||||
|
||||
@cache
|
||||
def _metadata_launch_pdl() -> bool:
|
||||
return current_platform.is_arch_support_pdl()
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=[
|
||||
"num_reqs",
|
||||
"num_mapped_tokens",
|
||||
"num_tokens",
|
||||
"max_num_work",
|
||||
"num_search_steps",
|
||||
"work_search_steps",
|
||||
]
|
||||
)
|
||||
def _build_qsa_metadata_kernel(
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
common_slot_mapping_ptr,
|
||||
block_table_ptr,
|
||||
token_to_req_ptr,
|
||||
logical_positions_ptr,
|
||||
slot_mapping_ptr,
|
||||
k_work_metadata_ptr,
|
||||
block_table_stride_0: tl.constexpr,
|
||||
block_table_stride_1: tl.constexpr,
|
||||
num_reqs,
|
||||
num_mapped_tokens,
|
||||
num_tokens,
|
||||
max_num_work,
|
||||
num_search_steps,
|
||||
work_search_steps,
|
||||
storage_block_size: tl.constexpr,
|
||||
compress_ratio: tl.constexpr,
|
||||
circular_buffer_size: tl.constexpr,
|
||||
num_block_table_columns: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
TOKEN_BLOCK_SIZE: tl.constexpr,
|
||||
REQUEST_SCAN_SIZE: tl.constexpr,
|
||||
WORK_BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
pid = tl.program_id(0)
|
||||
token_idx = pid * TOKEN_BLOCK_SIZE + tl.arange(0, TOKEN_BLOCK_SIZE)
|
||||
store_mask = token_idx < num_tokens
|
||||
mapped = token_idx < num_mapped_tokens
|
||||
search_token_idx = tl.minimum(token_idx, num_mapped_tokens - 1)
|
||||
request_idx = tl.zeros((TOKEN_BLOCK_SIZE,), tl.int32)
|
||||
# Find the last query start at or before each token. The dynamic loop avoids
|
||||
# compiling a kernel variant for every ceil(log2(num_reqs)).
|
||||
for step in tl.range(0, num_search_steps):
|
||||
candidate = request_idx + (1 << (num_search_steps - step - 1))
|
||||
valid_candidate = candidate < num_reqs
|
||||
candidate_start = tl.load(
|
||||
query_start_loc_ptr + candidate,
|
||||
mask=valid_candidate,
|
||||
other=num_mapped_tokens + 1,
|
||||
)
|
||||
advance = valid_candidate & (candidate_start <= search_token_idx)
|
||||
request_idx = tl.where(advance, candidate, request_idx)
|
||||
query_start = tl.load(query_start_loc_ptr + request_idx, mask=mapped, other=0)
|
||||
query_end = tl.load(query_start_loc_ptr + request_idx + 1, mask=mapped, other=0)
|
||||
seq_len = tl.load(seq_lens_ptr + request_idx, mask=mapped, other=0)
|
||||
logical_position = seq_len - (query_end - query_start) + token_idx - query_start
|
||||
logical_position = tl.where(mapped, logical_position, -1)
|
||||
tl.store(
|
||||
token_to_req_ptr + token_idx,
|
||||
tl.where(mapped, request_idx, 0),
|
||||
mask=store_mask,
|
||||
)
|
||||
tl.store(
|
||||
logical_positions_ptr + token_idx,
|
||||
logical_position,
|
||||
mask=store_mask,
|
||||
)
|
||||
|
||||
# circular_buffer_size is constexpr, so each builder instance compiles out
|
||||
# the other QSA cache owner's slot-mapping rule.
|
||||
if circular_buffer_size > 0:
|
||||
valid = (
|
||||
mapped
|
||||
& (logical_position >= 0)
|
||||
& (token_idx + circular_buffer_size >= query_end)
|
||||
& (num_block_table_columns > 0)
|
||||
)
|
||||
physical_block = tl.load(
|
||||
block_table_ptr + request_idx * block_table_stride_0,
|
||||
mask=valid,
|
||||
other=-1,
|
||||
)
|
||||
valid &= physical_block >= 0
|
||||
slot = physical_block * circular_buffer_size + (
|
||||
logical_position % circular_buffer_size
|
||||
)
|
||||
elif compress_ratio != 1:
|
||||
compressed_position = tl.maximum(logical_position, 0) // compress_ratio
|
||||
logical_block = compressed_position // storage_block_size
|
||||
valid = (
|
||||
mapped
|
||||
& (logical_position >= 0)
|
||||
& ((logical_position + 1) % compress_ratio == 0)
|
||||
& (logical_block < num_block_table_columns)
|
||||
)
|
||||
physical_block = tl.load(
|
||||
block_table_ptr
|
||||
+ request_idx * block_table_stride_0
|
||||
+ logical_block * block_table_stride_1,
|
||||
mask=valid,
|
||||
other=-1,
|
||||
)
|
||||
valid &= physical_block >= 0
|
||||
valid &= (
|
||||
tl.load(common_slot_mapping_ptr + token_idx, mask=mapped, other=-1) >= 0
|
||||
)
|
||||
slot = physical_block * storage_block_size + (
|
||||
compressed_position % storage_block_size
|
||||
)
|
||||
if (circular_buffer_size > 0) or (compress_ratio != 1):
|
||||
tl.store(
|
||||
slot_mapping_ptr + token_idx,
|
||||
tl.where(valid, slot, -1),
|
||||
mask=store_mask,
|
||||
)
|
||||
work_tile_start = pid * WORK_BLOCK_SIZE
|
||||
has_work_tile = work_tile_start < max_num_work
|
||||
if k_work_metadata_ptr is not None and has_work_tile:
|
||||
# Every work CTA builds the request prefix in registers. Recomputing this
|
||||
# small vector lets CTAs write disjoint work tiles without a grid barrier.
|
||||
requests = tl.arange(0, REQUEST_SCAN_SIZE)
|
||||
valid_request = requests < num_reqs
|
||||
request_query_start = tl.load(
|
||||
query_start_loc_ptr + requests, mask=valid_request, other=0
|
||||
)
|
||||
request_query_end = tl.load(
|
||||
query_start_loc_ptr + requests + 1, mask=valid_request, other=0
|
||||
)
|
||||
request_seq_len = tl.load(seq_lens_ptr + requests, mask=valid_request, other=0)
|
||||
request_query_len = request_query_end - request_query_start
|
||||
chunk_start = request_seq_len - request_query_len
|
||||
num_groups = request_seq_len // compress_ratio - chunk_start // compress_ratio
|
||||
# Nonempty requests need one item even without a completed compression
|
||||
# group because work item zero also commits the current raw-K suffix.
|
||||
work_counts = tl.where(request_query_len > 0, tl.maximum(num_groups, 1), 0)
|
||||
work_ends = tl.cumsum(tl.where(valid_request, work_counts, 0), axis=0)
|
||||
total_work = tl.sum(tl.where(valid_request, work_counts, 0), axis=0)
|
||||
work_offsets = tl.arange(0, WORK_BLOCK_SIZE)
|
||||
work = work_tile_start + work_offsets
|
||||
in_bounds = work < max_num_work
|
||||
active = in_bounds & (work < total_work)
|
||||
request = tl.zeros((WORK_BLOCK_SIZE,), dtype=tl.int32)
|
||||
# Request zero starts at zero for every active work item. Descending
|
||||
# steps find the last request starting at or before this item.
|
||||
for step_idx in tl.range(0, work_search_steps):
|
||||
step = 1 << (work_search_steps - step_idx - 1)
|
||||
candidate = request + step
|
||||
valid_candidate = candidate < num_reqs
|
||||
candidate_start = tl.gather(work_ends, candidate - 1, 0)
|
||||
advance = active & valid_candidate & (candidate_start <= work)
|
||||
request = tl.where(advance, candidate, request)
|
||||
|
||||
if launch_pdl:
|
||||
# Let the dependent grid start launch setup while these CTAs finish
|
||||
# stores; its gdc_wait still orders access to the completed metadata.
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
owner_work_start = tl.gather(work_ends, tl.maximum(request - 1, 0), 0)
|
||||
owner_work_start = tl.where(request == 0, 0, owner_work_start)
|
||||
work_in_request = work - owner_work_start
|
||||
tl.store(
|
||||
k_work_metadata_ptr + work * 2,
|
||||
tl.where(active, request, -1),
|
||||
mask=in_bounds,
|
||||
)
|
||||
tl.store(
|
||||
k_work_metadata_ptr + work * 2 + 1,
|
||||
tl.where(active, work_in_request, -1),
|
||||
mask=in_bounds,
|
||||
)
|
||||
|
||||
else:
|
||||
if launch_pdl:
|
||||
# A dependent grid launches only after every CTA has signaled.
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
|
||||
def build_qsa_metadata_triton(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
token_to_req_buffer: torch.Tensor,
|
||||
logical_positions_buffer: torch.Tensor,
|
||||
slot_mapping_buffer: torch.Tensor,
|
||||
*,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
circular_buffer_size: int = 0,
|
||||
k_work_metadata_buffer: torch.Tensor | None = None,
|
||||
request_capacity: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Build QSA side-cache and optional pre-indexer work metadata."""
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
num_mapped_tokens = int(common_attn_metadata.query_start_loc_cpu[-1])
|
||||
token_to_req = token_to_req_buffer[:num_tokens]
|
||||
logical_positions = logical_positions_buffer[:num_tokens]
|
||||
slot_mapping = slot_mapping_buffer[:num_tokens]
|
||||
num_reqs = common_attn_metadata.query_start_loc.shape[0] - 1
|
||||
assert num_reqs > 0
|
||||
|
||||
if k_work_metadata_buffer is not None:
|
||||
if request_capacity is None:
|
||||
request_capacity = num_reqs
|
||||
assert request_capacity >= num_reqs
|
||||
# Pad for tl.arange while keeping the scan width stable across live batches.
|
||||
request_scan_size = 1 << int(math.ceil(math.log2(request_capacity)))
|
||||
max_num_work = k_work_metadata_buffer.shape[0]
|
||||
else:
|
||||
request_scan_size = 1
|
||||
max_num_work = 0
|
||||
|
||||
if num_tokens == 0 and k_work_metadata_buffer is None:
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
block_table = common_attn_metadata.block_table_tensor
|
||||
num_search_steps = int(math.ceil(math.log2(num_reqs)))
|
||||
work_search_steps = int(math.ceil(math.log2(num_reqs)))
|
||||
# The same grid covers token tiles and, for the compressed cache, work tiles.
|
||||
num_token_blocks = cdiv(num_tokens, 128)
|
||||
num_work_blocks = (
|
||||
cdiv(max_num_work, 256) if k_work_metadata_buffer is not None else 0
|
||||
)
|
||||
_build_qsa_metadata_kernel[(max(num_token_blocks, num_work_blocks, 1),)](
|
||||
common_attn_metadata.query_start_loc,
|
||||
common_attn_metadata.seq_lens,
|
||||
common_attn_metadata.slot_mapping,
|
||||
block_table,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
slot_mapping,
|
||||
k_work_metadata_buffer,
|
||||
block_table.stride(0),
|
||||
block_table.stride(1),
|
||||
num_reqs,
|
||||
num_mapped_tokens,
|
||||
num_tokens,
|
||||
max_num_work,
|
||||
num_search_steps,
|
||||
work_search_steps,
|
||||
storage_block_size,
|
||||
compress_ratio,
|
||||
circular_buffer_size,
|
||||
block_table.shape[1],
|
||||
launch_pdl=_metadata_launch_pdl(),
|
||||
TOKEN_BLOCK_SIZE=128,
|
||||
REQUEST_SCAN_SIZE=request_scan_size,
|
||||
WORK_BLOCK_SIZE=256,
|
||||
num_warps=4,
|
||||
)
|
||||
if circular_buffer_size == 0 and compress_ratio == 1:
|
||||
slot_mapping = common_attn_metadata.slot_mapping[:num_tokens]
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
|
||||
def _build_qsa_metadata_torch(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
token_to_req_buffer: torch.Tensor,
|
||||
logical_positions_buffer: torch.Tensor,
|
||||
slot_mapping_buffer: torch.Tensor,
|
||||
*,
|
||||
storage_block_size: int,
|
||||
compress_ratio: int,
|
||||
circular_buffer_size: int = 0,
|
||||
k_work_metadata_buffer: torch.Tensor | None = None,
|
||||
request_capacity: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
del request_capacity
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
num_mapped_tokens = int(common_attn_metadata.query_start_loc_cpu[-1])
|
||||
logical_positions = logical_positions_buffer[:num_tokens]
|
||||
|
||||
token_to_req = common_attn_metadata.token_to_req_indices(token_to_req_buffer)[
|
||||
:num_tokens
|
||||
]
|
||||
logical_positions[:num_mapped_tokens].copy_(
|
||||
_logical_positions(
|
||||
common_attn_metadata.query_start_loc,
|
||||
common_attn_metadata.seq_lens,
|
||||
token_to_req[:num_mapped_tokens],
|
||||
num_mapped_tokens,
|
||||
)
|
||||
)
|
||||
if num_mapped_tokens < num_tokens:
|
||||
logical_positions[num_mapped_tokens:].fill_(-1)
|
||||
if circular_buffer_size > 0:
|
||||
slot_mapping = circular_qsa_slot_mapping(
|
||||
common_attn_metadata.block_table_tensor,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
circular_buffer_size,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
out=slot_mapping_buffer,
|
||||
)
|
||||
elif compress_ratio == 1:
|
||||
slot_mapping = common_attn_metadata.slot_mapping[:num_tokens]
|
||||
else:
|
||||
slot_mapping = compressed_qsa_slot_mapping(
|
||||
common_attn_metadata.block_table_tensor,
|
||||
token_to_req,
|
||||
logical_positions,
|
||||
storage_block_size,
|
||||
compress_ratio,
|
||||
slot_mapping_buffer,
|
||||
)
|
||||
slot_mapping.masked_fill_(
|
||||
common_attn_metadata.slot_mapping[:num_tokens] < 0, -1
|
||||
)
|
||||
if k_work_metadata_buffer is not None:
|
||||
query_lens = (
|
||||
common_attn_metadata.query_start_loc[1:]
|
||||
- common_attn_metadata.query_start_loc[:-1]
|
||||
)
|
||||
chunk_starts = common_attn_metadata.seq_lens - query_lens
|
||||
num_work_per_request = (
|
||||
common_attn_metadata.seq_lens // compress_ratio
|
||||
- chunk_starts // compress_ratio
|
||||
)
|
||||
num_work_per_request = torch.where(
|
||||
query_lens > 0, num_work_per_request.clamp_min(1), 0
|
||||
)
|
||||
k_start_loc = torch.empty(
|
||||
query_lens.shape[0] + 1,
|
||||
dtype=torch.int32,
|
||||
device=query_lens.device,
|
||||
)
|
||||
k_start_loc[0] = 0
|
||||
torch.cumsum(num_work_per_request, 0, out=k_start_loc[1:])
|
||||
work = torch.arange(
|
||||
k_work_metadata_buffer.shape[0],
|
||||
device=k_work_metadata_buffer.device,
|
||||
)
|
||||
requests = torch.searchsorted(k_start_loc[1:], work, right=True)
|
||||
active = work < k_start_loc[-1]
|
||||
work_in_request = (
|
||||
work - k_start_loc[requests.clamp_max(query_lens.shape[0] - 1)]
|
||||
)
|
||||
k_work_metadata_buffer[:, 0].copy_(
|
||||
torch.where(active, requests, -1).to(torch.int32)
|
||||
)
|
||||
k_work_metadata_buffer[:, 1].copy_(
|
||||
torch.where(active, work_in_request, -1).to(torch.int32)
|
||||
)
|
||||
return token_to_req, logical_positions, slot_mapping
|
||||
|
||||
|
||||
# Resolve the fallback outside the per-step metadata hot path.
|
||||
build_qsa_metadata = (
|
||||
build_qsa_metadata_triton if HAS_TRITON else _build_qsa_metadata_torch
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class QSAForwardMetadata(AttentionMetadata):
|
||||
"""Common per-forward metadata for one QSA side cache."""
|
||||
|
||||
block_table: torch.Tensor
|
||||
slot_mapping: torch.Tensor
|
||||
seq_lens: torch.Tensor
|
||||
query_start_loc: torch.Tensor
|
||||
token_to_req: torch.Tensor
|
||||
logical_positions: torch.Tensor
|
||||
k_work_metadata: torch.Tensor
|
||||
num_actual_tokens: int
|
||||
storage_block_size: int
|
||||
compress_ratio: int
|
||||
|
||||
|
||||
class QSAMetadataBuilder(AttentionMetadataBuilder[QSAForwardMetadata]):
|
||||
"""Build QSA metadata from vLLM's cache-group-specific common metadata."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
self.is_circular_buffer = isinstance(kv_cache_spec, CircularBufferSpec)
|
||||
if isinstance(kv_cache_spec, MLAAttentionSpec):
|
||||
compress_ratio = kv_cache_spec.tokens_per_state
|
||||
assert isinstance(compress_ratio, int), (
|
||||
"QSA compression requires an integer tokens_per_state"
|
||||
)
|
||||
self.compress_ratio = compress_ratio
|
||||
else:
|
||||
self.compress_ratio = 1
|
||||
self.storage_block_size = kv_cache_spec.num_states
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.token_to_req_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int32, device=device
|
||||
)
|
||||
self.slot_mapping_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
self.logical_positions_buffer = torch.empty(
|
||||
max_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
max_requests = vllm_config.scheduler_config.max_num_seqs
|
||||
self.request_capacity = max_requests
|
||||
if not self.is_circular_buffer and self.compress_ratio != 1:
|
||||
max_k_work = (
|
||||
max_tokens + (self.compress_ratio - 1) * max_requests
|
||||
) // self.compress_ratio
|
||||
self.k_work_metadata_buffer = torch.empty(
|
||||
max_k_work, 2, dtype=torch.int32, device=device
|
||||
)
|
||||
else:
|
||||
self.k_work_metadata_buffer = torch.empty(
|
||||
0, 2, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> QSAForwardMetadata:
|
||||
del common_prefix_len, fast_build
|
||||
num_tokens = common_attn_metadata.num_actual_tokens
|
||||
build_k_work = not self.is_circular_buffer and self.compress_ratio != 1
|
||||
k_work_metadata = self.k_work_metadata_buffer
|
||||
request_capacity = None
|
||||
if build_k_work:
|
||||
num_requests = common_attn_metadata.query_start_loc.shape[0] - 1
|
||||
request_capacity = self.request_capacity
|
||||
max_num_work = (
|
||||
num_tokens + (self.compress_ratio - 1) * num_requests
|
||||
) // self.compress_ratio
|
||||
k_work_metadata = self.k_work_metadata_buffer[:max_num_work]
|
||||
token_to_req, logical_positions, slot_mapping = build_qsa_metadata(
|
||||
common_attn_metadata,
|
||||
self.token_to_req_buffer,
|
||||
self.logical_positions_buffer,
|
||||
self.slot_mapping_buffer,
|
||||
storage_block_size=self.storage_block_size,
|
||||
compress_ratio=self.compress_ratio,
|
||||
circular_buffer_size=(
|
||||
self.kv_cache_spec.block_size if self.is_circular_buffer else 0
|
||||
),
|
||||
k_work_metadata_buffer=k_work_metadata if build_k_work else None,
|
||||
request_capacity=request_capacity,
|
||||
)
|
||||
return QSAForwardMetadata(
|
||||
block_table=common_attn_metadata.block_table_tensor,
|
||||
slot_mapping=slot_mapping,
|
||||
seq_lens=common_attn_metadata.seq_lens,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
token_to_req=token_to_req,
|
||||
logical_positions=logical_positions,
|
||||
k_work_metadata=k_work_metadata,
|
||||
num_actual_tokens=num_tokens,
|
||||
storage_block_size=self.storage_block_size,
|
||||
compress_ratio=self.compress_ratio,
|
||||
)
|
||||
|
||||
|
||||
class QSAStateBackend(AttentionBackend):
|
||||
"""Key-only dummy backend for out-of-band BF16 QSA side-cache operations."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_EXP_QSA_STATE"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls():
|
||||
raise NotImplementedError(
|
||||
"QSA state caches run out-of-band and have no attention impl"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[QSAMetadataBuilder]:
|
||||
return QSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
|
||||
# QSA pages are packed beside the main KV pages within each block.
|
||||
return (KVCacheLayout.BLNHC, KVCacheLayout.BLHNC)
|
||||
|
||||
|
||||
class _QSAStateCache(nn.Module, AttentionLayerBase):
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
cache_config: CacheConfig,
|
||||
prefix: str,
|
||||
vllm_config: VllmConfig,
|
||||
compress_ratio: int = 1,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if head_size <= 0:
|
||||
raise ValueError("QSA cache head size must be positive")
|
||||
if compress_ratio <= 0:
|
||||
raise ValueError("QSA compression ratio must be positive")
|
||||
if cache_config.block_size % compress_ratio:
|
||||
raise ValueError(
|
||||
"QSA cache block size must be divisible by the compression ratio"
|
||||
)
|
||||
self.head_size = head_size
|
||||
self.dtype = dtype
|
||||
self.cache_config = cache_config
|
||||
self.prefix = prefix
|
||||
self.compress_ratio = compress_ratio
|
||||
self.kv_cache = torch.tensor([])
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if prefix in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {prefix}")
|
||||
static_context[prefix] = self
|
||||
|
||||
def forward(self) -> None: ...
|
||||
|
||||
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
|
||||
"""Adapt the unified [B, H, N, C] view to QSA's [B, N, H, C]."""
|
||||
if kv_cache.ndim != 4 or kv_cache.shape[1] != 1:
|
||||
raise ValueError("QSA state cache must be [blocks, 1, states, width]")
|
||||
if kv_cache.dtype != torch.bfloat16 or kv_cache.shape[3] != self.head_size:
|
||||
raise ValueError("QSA state cache does not match its packed BF16 spec")
|
||||
super().bind_kv_cache(kv_cache.transpose(1, 2))
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return QSAStateBackend
|
||||
|
||||
|
||||
class QSAKeyStateCache(_QSAStateCache):
|
||||
"""Raw BF16 key, optionally followed by exact int64 MRoPE positions."""
|
||||
|
||||
_BF16_PER_INT64 = 4
|
||||
_NUM_ROPE_AXES = 3
|
||||
|
||||
def __init__(self, *, cache_rope_positions: bool = False, **kwargs) -> None:
|
||||
key_head_size = int(kwargs.pop("head_size"))
|
||||
self.key_head_size = key_head_size
|
||||
self.cache_rope_positions = bool(cache_rope_positions)
|
||||
self.rope_position_offset = (
|
||||
(key_head_size + self._BF16_PER_INT64 - 1) // self._BF16_PER_INT64
|
||||
) * self._BF16_PER_INT64
|
||||
storage_head_size = key_head_size
|
||||
if self.cache_rope_positions:
|
||||
storage_head_size = self.rope_position_offset + (
|
||||
self._NUM_ROPE_AXES * self._BF16_PER_INT64
|
||||
)
|
||||
super().__init__(head_size=storage_head_size, **kwargs)
|
||||
|
||||
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
|
||||
super().bind_kv_cache(kv_cache)
|
||||
qsa_cache = self.kv_cache
|
||||
self.key_cache = qsa_cache[..., : self.key_head_size]
|
||||
if self.cache_rope_positions:
|
||||
position_tail = qsa_cache[..., self.rope_position_offset :]
|
||||
self.rope_position_cache = position_tail.view(torch.int64)
|
||||
else:
|
||||
self.rope_position_cache = None
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
# Hold the open group's committed keys plus every row a speculative
|
||||
# step stores before acceptance is known, rounded up to whole groups so
|
||||
# the ring divides the attention block size (it joins the LCM that sets
|
||||
# the scheduler block size). Anything narrower lets a rejected draft row
|
||||
# overwrite a committed key the next step needs to close the group.
|
||||
span = self.compress_ratio + vllm_config.num_speculative_tokens
|
||||
capacity = self.compress_ratio * cdiv(span, self.compress_ratio)
|
||||
assert self.cache_config.block_size % capacity == 0, (
|
||||
f"QSA ring capacity {capacity} must divide the attention block "
|
||||
f"size {self.cache_config.block_size}"
|
||||
)
|
||||
return CircularBufferSpec(
|
||||
block_size=capacity,
|
||||
num_kv_heads=1,
|
||||
head_size=self.head_size,
|
||||
head_size_v=0,
|
||||
dtype=self.dtype,
|
||||
)
|
||||
|
||||
|
||||
class QSACompressedKeyCache(_QSAStateCache):
|
||||
"""Normalized, group-first-RoPE BF16 key at one row per complete group."""
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
del vllm_config
|
||||
return MLAAttentionSpec(
|
||||
block_size=self.cache_config.block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=self.head_size,
|
||||
dtype=self.dtype,
|
||||
tokens_per_state=self.compress_ratio,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSACompressedKeyCache",
|
||||
"QSAForwardMetadata",
|
||||
"QSAKeyStateCache",
|
||||
"QSAMetadataBuilder",
|
||||
"QSAStateBackend",
|
||||
"canonical_qsa_rope_positions",
|
||||
"circular_qsa_slot_mapping",
|
||||
"compressed_qsa_slot_mapping",
|
||||
]
|
||||
@@ -0,0 +1,252 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp model configuration."""
|
||||
|
||||
from typing import Any, ClassVar, cast
|
||||
|
||||
from transformers import PretrainedConfig
|
||||
from transformers.models.qwen3_vl.configuration_qwen3_vl import (
|
||||
Qwen3VLVisionConfig,
|
||||
)
|
||||
|
||||
from vllm.transformers_utils.configs.qwen3_next import Qwen3NextConfig
|
||||
|
||||
_QSA_CONFIG_FIELDS = (
|
||||
"indexer_n_heads",
|
||||
"indexer_kv_heads",
|
||||
"indexer_head_dim",
|
||||
"indexer_budget",
|
||||
"indexer_compress_ratio",
|
||||
)
|
||||
|
||||
|
||||
class Qwen4ExpVisionConfig(Qwen3VLVisionConfig):
|
||||
model_type = "qwen4_exp"
|
||||
base_config_key = "vision_config"
|
||||
|
||||
|
||||
class Qwen4ExpTextConfig(Qwen3NextConfig):
|
||||
model_type = "qwen4_exp_text"
|
||||
base_config_key = "text_config"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hc_count: int = 4,
|
||||
hc_lowrank: int = 320,
|
||||
ple_layer_ids: list[int] | None = None,
|
||||
ple_embed_dim: int | None = None,
|
||||
ple_conv_kernel_size: int = 4,
|
||||
ngram_size: int = 3,
|
||||
heads_per_ngram: int = 8,
|
||||
ngram_vocab_size_base: int = 20_000_000,
|
||||
make_ngram_vocab_size_divisible_by: int = 128,
|
||||
output_gate_type: str = "sigmoid",
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
layer_types: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
if hc_count <= 1:
|
||||
raise ValueError(f"Qwen4Exp requires hc_count > 1, got {hc_count}.")
|
||||
|
||||
if rope_parameters is not None:
|
||||
if kwargs.get("rope_scaling") is None:
|
||||
kwargs["rope_scaling"] = rope_parameters
|
||||
if kwargs.get("rope_theta") is None and "rope_theta" in rope_parameters:
|
||||
kwargs["rope_theta"] = rope_parameters["rope_theta"]
|
||||
if (
|
||||
kwargs.get("partial_rotary_factor") is None
|
||||
and "partial_rotary_factor" in rope_parameters
|
||||
):
|
||||
kwargs["partial_rotary_factor"] = rope_parameters[
|
||||
"partial_rotary_factor"
|
||||
]
|
||||
|
||||
rope_scaling = kwargs.get("rope_scaling")
|
||||
rope_theta = kwargs.get("rope_theta", 10_000.0)
|
||||
super().__init__(layer_types=layer_types, **kwargs)
|
||||
|
||||
normalized_rope_parameters = self.rope_parameters
|
||||
self.rope_scaling = (
|
||||
rope_scaling or rope_parameters or normalized_rope_parameters
|
||||
)
|
||||
self.rope_parameters = rope_parameters or normalized_rope_parameters
|
||||
self.rope_theta = rope_theta
|
||||
|
||||
self.hc_count = hc_count
|
||||
self.hc_lowrank = hc_lowrank
|
||||
self.ple_layer_ids = ple_layer_ids or []
|
||||
self.ple_embed_dim = (
|
||||
self.hidden_size if ple_embed_dim is None else ple_embed_dim
|
||||
)
|
||||
self.ple_conv_kernel_size = ple_conv_kernel_size
|
||||
self.ngram_size = ngram_size
|
||||
self.heads_per_ngram = heads_per_ngram
|
||||
self.ngram_vocab_size_base = ngram_vocab_size_base
|
||||
self.make_ngram_vocab_size_divisible_by = make_ngram_vocab_size_divisible_by
|
||||
self.output_gate_type = output_gate_type
|
||||
|
||||
self._validate_ple_config()
|
||||
self._validate_ple_layer_ids()
|
||||
self._validate_qsa_config()
|
||||
|
||||
def _validate_ple_config(self) -> None:
|
||||
if self.hc_lowrank <= 0:
|
||||
raise ValueError(f"hc_lowrank must be positive, got {self.hc_lowrank}")
|
||||
if self.ngram_size < 2:
|
||||
raise ValueError(f"ngram_size must be >= 2, got {self.ngram_size}")
|
||||
if self.heads_per_ngram <= 0:
|
||||
raise ValueError(
|
||||
f"heads_per_ngram must be positive, got {self.heads_per_ngram}"
|
||||
)
|
||||
if self.ple_embed_dim <= 0:
|
||||
raise ValueError(
|
||||
f"ple_embed_dim must be positive, got {self.ple_embed_dim}"
|
||||
)
|
||||
ngram_heads = (self.ngram_size - 1) * self.heads_per_ngram
|
||||
if self.ple_embed_dim % ngram_heads:
|
||||
raise ValueError(
|
||||
"ple_embed_dim must be divisible by total ngram heads: "
|
||||
f"{self.ple_embed_dim} % {ngram_heads} != 0"
|
||||
)
|
||||
if self.ple_conv_kernel_size <= 0:
|
||||
raise ValueError(
|
||||
"ple_conv_kernel_size must be positive, got "
|
||||
f"{self.ple_conv_kernel_size}"
|
||||
)
|
||||
if self.ngram_vocab_size_base <= 0:
|
||||
raise ValueError("ngram_vocab_size_base must be positive")
|
||||
if self.make_ngram_vocab_size_divisible_by <= 0:
|
||||
raise ValueError("make_ngram_vocab_size_divisible_by must be positive")
|
||||
|
||||
def _validate_ple_layer_ids(self) -> None:
|
||||
invalid = [
|
||||
layer_id
|
||||
for layer_id in self.ple_layer_ids
|
||||
if not 1 <= int(layer_id) <= self.num_hidden_layers
|
||||
]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
"ple_layer_ids are 1-based and must refer to an existing layer; "
|
||||
f"got {invalid} for {self.num_hidden_layers} layers"
|
||||
)
|
||||
|
||||
def _validate_qsa_config(self) -> None:
|
||||
configured = {name: getattr(self, name, None) for name in _QSA_CONFIG_FIELDS}
|
||||
if all(value is None for value in configured.values()):
|
||||
return
|
||||
|
||||
missing = [name for name, value in configured.items() if value is None]
|
||||
if missing:
|
||||
raise ValueError(f"QSA config is missing required fields: {missing}")
|
||||
|
||||
values = {name: int(cast(int, value)) for name, value in configured.items()}
|
||||
if any(value <= 0 for value in values.values()):
|
||||
raise ValueError(f"QSA config values must be positive: {values}")
|
||||
if values["indexer_kv_heads"] != 1:
|
||||
raise ValueError("the QSA MQA operators require indexer_kv_heads=1")
|
||||
if values["indexer_budget"] % values["indexer_compress_ratio"] != 0:
|
||||
raise ValueError(
|
||||
"indexer_budget must be divisible by indexer_compress_ratio"
|
||||
)
|
||||
block_topk = values["indexer_budget"] // values["indexer_compress_ratio"]
|
||||
if block_topk not in (512, 2048):
|
||||
raise ValueError(
|
||||
"QSA requires indexer_budget / indexer_compress_ratio "
|
||||
f"to be 512 or 2048, got {block_topk}"
|
||||
)
|
||||
rotary_dim = int(self.head_dim * self.partial_rotary_factor)
|
||||
if rotary_dim > values["indexer_head_dim"]:
|
||||
raise ValueError(
|
||||
"QSA indexer_head_dim must cover the attention rotary "
|
||||
f"dimension, got {values['indexer_head_dim']} < {rotary_dim}"
|
||||
)
|
||||
|
||||
@property
|
||||
def layers_block_type(self) -> list[str]:
|
||||
return [
|
||||
"attention" if layer_type == "full_attention" else layer_type
|
||||
for layer_type in self.layer_types
|
||||
]
|
||||
|
||||
@property
|
||||
def short_conv_layer_ids(self) -> list[int]:
|
||||
if not self.ple_layer_ids:
|
||||
return []
|
||||
return sorted({int(layer_id) - 1 for layer_id in self.ple_layer_ids})
|
||||
|
||||
@property
|
||||
def short_conv_state_shape(self) -> tuple[int, int] | None:
|
||||
if not self.short_conv_layer_ids:
|
||||
return None
|
||||
ple_state_len = (self.ple_conv_kernel_size - 1) * self.ngram_size
|
||||
ple_channels = self.hidden_size * self.hc_count
|
||||
return ple_channels, ple_state_len
|
||||
|
||||
@property
|
||||
def ngram_context_len(self) -> int:
|
||||
if not self.ple_layer_ids:
|
||||
return 0
|
||||
return max(int(self.ngram_size) - 1, 0)
|
||||
|
||||
|
||||
class Qwen4ExpConfig(PretrainedConfig):
|
||||
model_type = "qwen4_exp"
|
||||
sub_configs: ClassVar[dict[str, type[PretrainedConfig]]] = {
|
||||
"vision_config": Qwen4ExpVisionConfig,
|
||||
"text_config": Qwen4ExpTextConfig,
|
||||
}
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
text_config: Qwen4ExpTextConfig | dict[str, Any] | None = None,
|
||||
vision_config: Qwen4ExpVisionConfig | dict[str, Any] | None = None,
|
||||
image_token_id: int = 248056,
|
||||
video_token_id: int = 248057,
|
||||
vision_start_token_id: int = 248053,
|
||||
vision_end_token_id: int = 248054,
|
||||
tie_word_embeddings: bool = False,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
if text_config is not None:
|
||||
kwargs.pop("split_ngram_parts", None)
|
||||
|
||||
text_kwargs = (
|
||||
dict(kwargs)
|
||||
if text_config is None
|
||||
and "hidden_size" in kwargs
|
||||
and "num_hidden_layers" in kwargs
|
||||
else {}
|
||||
)
|
||||
|
||||
if isinstance(vision_config, dict):
|
||||
self.vision_config = self.sub_configs["vision_config"](**vision_config)
|
||||
elif vision_config is None:
|
||||
self.vision_config = self.sub_configs["vision_config"]()
|
||||
else:
|
||||
self.vision_config = vision_config
|
||||
|
||||
if isinstance(text_config, dict):
|
||||
self.text_config = self.sub_configs["text_config"](**text_config)
|
||||
elif text_config is None:
|
||||
self.text_config = self.sub_configs["text_config"](**text_kwargs)
|
||||
else:
|
||||
self.text_config = text_config
|
||||
|
||||
self.image_token_id = image_token_id
|
||||
self.video_token_id = video_token_id
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
self.rope_parameters = rope_parameters or getattr(
|
||||
self.text_config, "rope_parameters", {}
|
||||
)
|
||||
super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Qwen4ExpConfig",
|
||||
"Qwen4ExpTextConfig",
|
||||
"Qwen4ExpVisionConfig",
|
||||
]
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,205 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HyperConnection (Gated Residual) utilities — NVIDIA model variant.
|
||||
|
||||
Implements the HyperConnection residual scheme proposed in
|
||||
"HyperConnections" (https://arxiv.org/abs/2409.19606). This NVIDIA variant
|
||||
delays each HC combine to the following HC mix boundary. HC glue kernels,
|
||||
including fused combine+RMSNorm, live in ``ops/hc.py``; projections remain
|
||||
standard vLLM Linear modules.
|
||||
|
||||
Hidden states between layers have shape ``[..., HC*HS]`` with HS inner
|
||||
(HC outer, HS inner — checkpoint-native layout).
|
||||
|
||||
Typical usage inside a transformer decoder layer::
|
||||
|
||||
self.attn_hc = GatedResidual(hc_config)
|
||||
|
||||
hidden_states, block_input, injection = self.attn_hc.mix(hidden_states)
|
||||
attention_output = attention(block_input)
|
||||
hidden_states, block_input, injection = self.mlp_hc.combine_and_mix(
|
||||
hidden_states, attention_output, injection
|
||||
)
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
|
||||
from ..common.hyperconnection import (
|
||||
GroupedGemmaRMSNorm,
|
||||
HyperConnectionConfig,
|
||||
)
|
||||
from .ops.hc import (
|
||||
grouped_gemma_rmsnorm,
|
||||
hc_combine,
|
||||
hc_combine_norm,
|
||||
hc_gate_mix,
|
||||
hc_silu,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gated-residual variant
|
||||
# ---------------------------------------------------------------------------
|
||||
class GatedResidual(nn.Module):
|
||||
"""Gated HyperConnection with learnable low-rank mixing and injection.
|
||||
|
||||
``combine_and_mix()`` runs the pre pipeline (grouped GemmaRMSNorm -> merged
|
||||
low-rank down+inject GEMM -> silu -> up GEMM -> sigmoid -> gated mean
|
||||
over the HC streams). When passed a pending block output and an injection,
|
||||
it fuses their residual combine with the RMSNorm. Final mixers use
|
||||
``use_combine=False`` and do not produce a new injection.
|
||||
|
||||
Weights: the norm owns the grouped GemmaRMSNorm affine; the projections
|
||||
are vLLM Linear modules (merged replicated linear for down+inject), so
|
||||
GEMM dispatch (e.g. the low-latency skinny GEMM) applies through the
|
||||
standard quant_method mechanism.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: HyperConnectionConfig,
|
||||
use_combine: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.lora_rank = config.hc_lowrank
|
||||
self.hc_count = config.hc_count
|
||||
self.hidden_size = config.hidden_size
|
||||
self.use_combine = use_combine
|
||||
|
||||
norm_size = (
|
||||
self.hyper_hidden_size if config.hc_per_branch_norm else config.hidden_size
|
||||
)
|
||||
group_size = config.hidden_size if config.hc_per_branch_norm else None
|
||||
# Normalize each H-sized HC stream independently while retaining a
|
||||
# separate affine weight for every element of the HC*H layout.
|
||||
self.hc_norm = GroupedGemmaRMSNorm(
|
||||
norm_size,
|
||||
eps=config.rms_norm_eps,
|
||||
group_size=group_size,
|
||||
dtype=config.params_dtype,
|
||||
)
|
||||
|
||||
# -- vLLM Linear weights --------------------------------------------
|
||||
# The merged skinny-GEMM shape is physically padded to 16 rows to ensure
|
||||
# good alignment and performant implementation chosen by CuBLAS heuristics.
|
||||
self.pad_size = (-(self.lora_rank + self.hc_count)) % 16 if use_combine else 0
|
||||
if use_combine:
|
||||
self.input_mix_weight_down_block_inject = MergedColumnParallelLinear(
|
||||
self.hyper_hidden_size,
|
||||
[self.lora_rank, self.hc_count]
|
||||
+ ([self.pad_size] if self.pad_size else []),
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down_block_inject"),
|
||||
return_bias=False,
|
||||
disable_tp=True,
|
||||
)
|
||||
else:
|
||||
self.input_mix_weight_down = ReplicatedLinear(
|
||||
self.hyper_hidden_size,
|
||||
self.lora_rank,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_down"),
|
||||
return_bias=False,
|
||||
)
|
||||
self.input_mix_weight_up = ReplicatedLinear(
|
||||
self.lora_rank,
|
||||
self.hyper_hidden_size,
|
||||
bias=False,
|
||||
params_dtype=config.params_dtype,
|
||||
quant_config=None,
|
||||
prefix=maybe_prefix(prefix, "input_mix_weight_up"),
|
||||
return_bias=False,
|
||||
)
|
||||
|
||||
def mix(
|
||||
self, hidden_states: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
xn = grouped_gemma_rmsnorm(
|
||||
hidden_states,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine_and_mix(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prev_block_output: torch.Tensor,
|
||||
prev_injection: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""Consume a pending combine, then prepare the next block input.
|
||||
|
||||
``hidden_states`` is the multi-stream state from before the pending
|
||||
block's mix. Its combine with ``block_output`` is fused with this
|
||||
module's input RMSNorm.
|
||||
"""
|
||||
hidden_states, xn = hc_combine_norm(
|
||||
hidden_states,
|
||||
prev_block_output,
|
||||
prev_injection,
|
||||
self.hc_norm.weight,
|
||||
self.config.rms_norm_eps,
|
||||
self.hc_count,
|
||||
)
|
||||
|
||||
if self.use_combine:
|
||||
# produce injection logits for combine
|
||||
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
|
||||
down_and_injection = self.input_mix_weight_down_block_inject(xn)
|
||||
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
|
||||
else:
|
||||
lora = self.input_mix_weight_down(xn)
|
||||
injection = None
|
||||
|
||||
lora = hc_silu(lora, self.hc_count)
|
||||
gate = self.input_mix_weight_up(lora) # [M, D]
|
||||
block_input = hc_gate_mix(xn, gate, self.hc_count)
|
||||
|
||||
return hidden_states, block_input, injection
|
||||
|
||||
def combine(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return hc_combine(hidden_states, block_output, injection, self.hc_count)
|
||||
|
||||
@property
|
||||
def hyper_hidden_size(self) -> int:
|
||||
return self.hc_count * self.hidden_size
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GatedResidual",
|
||||
"GroupedGemmaRMSNorm",
|
||||
"HyperConnectionConfig",
|
||||
]
|
||||
@@ -0,0 +1,356 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp weight-free QSA indexer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import (
|
||||
QSACompressedKeyCache,
|
||||
QSAForwardMetadata,
|
||||
QSAKeyStateCache,
|
||||
canonical_qsa_rope_positions,
|
||||
)
|
||||
from .ops.qsa_pre_indexer import qsa_pre_indexer
|
||||
|
||||
|
||||
def apply_qsa_rope(
|
||||
rotary_emb: nn.Module,
|
||||
positions: torch.Tensor,
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
cos_sin = cache[positions]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if positions.ndim == 2:
|
||||
shape = tensor.shape
|
||||
tensor, _ = triton_mrope(
|
||||
tensor.reshape(num_tokens, -1),
|
||||
tensor.new_empty((num_tokens, head_dim)),
|
||||
cos,
|
||||
sin,
|
||||
rotary_emb.mrope_section,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
rotary_emb.mrope_interleaved,
|
||||
rotary_emb.is_neox_style,
|
||||
)
|
||||
return tensor.reshape(shape)
|
||||
|
||||
rotated = rotary_emb.apply_rotary_emb.forward_cuda(
|
||||
tensor[..., :rotary_dim],
|
||||
cos,
|
||||
sin,
|
||||
)
|
||||
return torch.cat((rotated, tensor[..., rotary_dim:]), dim=-1)
|
||||
|
||||
|
||||
def _supports_fused_pre_indexer(
|
||||
rotary_emb: nn.Module,
|
||||
head_dim: int,
|
||||
num_kv_heads: int,
|
||||
compress_ratio: int,
|
||||
) -> bool:
|
||||
rotary_dim = int(rotary_emb.rotary_dim)
|
||||
mrope_section = getattr(rotary_emb, "mrope_section", None)
|
||||
return (
|
||||
bool(getattr(rotary_emb, "is_neox_style", False))
|
||||
and (
|
||||
not mrope_section
|
||||
or (
|
||||
len(mrope_section) == 3
|
||||
and sum(mrope_section) == rotary_dim // 2
|
||||
and bool(getattr(rotary_emb, "mrope_interleaved", False))
|
||||
)
|
||||
)
|
||||
and head_dim == 128
|
||||
and rotary_dim == 64
|
||||
and num_kv_heads == 1
|
||||
and compress_ratio > 1
|
||||
and compress_ratio & (compress_ratio - 1) == 0
|
||||
)
|
||||
|
||||
|
||||
class QSAIndexer(nn.Module):
|
||||
"""Replicated Q/K projection plus paged, weight-free QSA selection.
|
||||
|
||||
``prefix`` must be the checkpoint's indexer prefix, normally
|
||||
``model.layers.N.self_attn.indexer``. Consequently the trainable names are
|
||||
``index_qk_proj``, ``q_layernorm`` and ``k_layernorm`` under that prefix.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
rotary_emb: nn.Module,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if vllm_config.cache_config is None:
|
||||
raise ValueError("QSA requires a paged KV cache")
|
||||
if vllm_config.model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
|
||||
self.layer_id = int(layer_id)
|
||||
self.index_n_heads = int(config.indexer_n_heads)
|
||||
self.index_kv_heads = int(config.indexer_kv_heads)
|
||||
self.index_head_dim = int(config.indexer_head_dim)
|
||||
self.token_topk = int(config.indexer_budget)
|
||||
self.compress_ratio = int(config.indexer_compress_ratio)
|
||||
self.rotary_emb = rotary_emb
|
||||
self.use_fused_pre_indexer = _supports_fused_pre_indexer(
|
||||
rotary_emb,
|
||||
self.index_head_dim,
|
||||
self.index_kv_heads,
|
||||
self.compress_ratio,
|
||||
)
|
||||
self.prefix = prefix
|
||||
# MTP step 0 selects the target-aligned rows; later steps reuse them
|
||||
# while continuing to update the QSA side cache.
|
||||
self.skip_topk = False
|
||||
|
||||
self.index_qk_proj = ReplicatedLinear(
|
||||
int(config.hidden_size),
|
||||
(self.index_n_heads + self.index_kv_heads) * self.index_head_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.index_qk_proj" if prefix else "index_qk_proj",
|
||||
)
|
||||
self.q_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
self.k_layernorm = GemmaRMSNorm(
|
||||
self.index_head_dim,
|
||||
eps=float(getattr(config, "rms_norm_eps", 1e-6)),
|
||||
)
|
||||
|
||||
cache_config = vllm_config.cache_config
|
||||
cache_prefix = f"{prefix}." if prefix else ""
|
||||
self.raw_key_cache = QSAKeyStateCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
cache_rope_positions=vllm_config.model_config.uses_mrope,
|
||||
prefix=f"{cache_prefix}raw_key_cache",
|
||||
cache_config=cache_config,
|
||||
compress_ratio=self.compress_ratio,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
self.compressed_key_cache = QSACompressedKeyCache(
|
||||
head_size=self.index_head_dim,
|
||||
dtype=torch.bfloat16,
|
||||
compress_ratio=self.compress_ratio,
|
||||
prefix=f"{cache_prefix}compressed_key_cache",
|
||||
cache_config=cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
@property
|
||||
def output_width(self) -> int:
|
||||
return self.token_topk + self.compress_ratio - 1
|
||||
|
||||
def _metadata(
|
||||
self,
|
||||
) -> tuple[QSAForwardMetadata, QSAForwardMetadata] | None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
return None
|
||||
raw = cast(QSAForwardMetadata, metadata[self.raw_key_cache.prefix])
|
||||
compressed = cast(
|
||||
QSAForwardMetadata, metadata[self.compressed_key_cache.prefix]
|
||||
)
|
||||
if raw.num_actual_tokens != compressed.num_actual_tokens:
|
||||
raise RuntimeError("QSA side-cache metadata token counts disagree")
|
||||
if not raw.logical_positions.is_cuda and (
|
||||
not torch.equal(raw.logical_positions, compressed.logical_positions)
|
||||
):
|
||||
raise RuntimeError("QSA side-cache metadata positions disagree")
|
||||
return raw, compressed
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Return fixed-width request-relative token indices padded with ``-1``."""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
if self.skip_topk and out is not None:
|
||||
return out
|
||||
result = torch.full(
|
||||
(hidden_states.shape[0], self.output_width),
|
||||
-1,
|
||||
dtype=torch.int32,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
if out is not None:
|
||||
out.copy_(result)
|
||||
return out
|
||||
return result
|
||||
|
||||
from .ops.qsa import (
|
||||
qsa_compress_groups_with_ratio,
|
||||
qsa_select_paged_tokens,
|
||||
qsa_store_cache_rows,
|
||||
)
|
||||
|
||||
raw_metadata, compressed_metadata = metadata
|
||||
num_tokens = raw_metadata.num_actual_tokens
|
||||
hidden_states = hidden_states[:num_tokens]
|
||||
positions = positions[..., :num_tokens]
|
||||
|
||||
# Q/K projection
|
||||
projected_qk, _ = self.index_qk_proj(hidden_states)
|
||||
projected_q, raw_keys = projected_qk.split(
|
||||
(
|
||||
self.index_n_heads * self.index_head_dim,
|
||||
self.index_kv_heads * self.index_head_dim,
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
raw_key_state_cache = self.raw_key_cache
|
||||
compressed_key_cache = self.compressed_key_cache.kv_cache
|
||||
|
||||
if self.use_fused_pre_indexer:
|
||||
q = projected_q.new_empty(
|
||||
num_tokens,
|
||||
self.index_n_heads,
|
||||
self.index_head_dim,
|
||||
)
|
||||
qsa_pre_indexer(
|
||||
projected_q,
|
||||
raw_keys,
|
||||
positions,
|
||||
self.rotary_emb.cos_sin_cache,
|
||||
self.q_layernorm.weight,
|
||||
self.k_layernorm.weight,
|
||||
self.q_layernorm.variance_epsilon,
|
||||
q,
|
||||
raw_key_state_cache.kv_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_key_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
compressed_metadata.k_work_metadata,
|
||||
compress_ratio=self.compress_ratio,
|
||||
mrope_section=getattr(self.rotary_emb, "mrope_section", None),
|
||||
rope_pos_offset=(
|
||||
raw_key_state_cache.rope_position_offset
|
||||
if raw_key_state_cache.rope_position_cache is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
else:
|
||||
# Unfused reference path
|
||||
from flashinfer.norm import gemma_rmsnorm
|
||||
|
||||
q = projected_q.reshape(-1, self.index_n_heads, self.index_head_dim)
|
||||
q = gemma_rmsnorm(
|
||||
q.reshape(-1, self.index_head_dim),
|
||||
self.q_layernorm.weight,
|
||||
self.q_layernorm.variance_epsilon,
|
||||
).reshape_as(q)
|
||||
q = apply_qsa_rope(self.rotary_emb, positions, q)
|
||||
|
||||
raw_key_cache = raw_key_state_cache.key_cache
|
||||
rope_position_cache = raw_key_state_cache.rope_position_cache
|
||||
if rope_position_cache is None:
|
||||
position_rows = raw_metadata.logical_positions.view(-1, 1, 1).expand(
|
||||
-1, 1, 3
|
||||
)
|
||||
else:
|
||||
position_rows = canonical_qsa_rope_positions(positions).to(
|
||||
device=raw_key_cache.device
|
||||
)
|
||||
pooled, first_positions = qsa_compress_groups_with_ratio(
|
||||
raw_keys.reshape(-1, 1, self.index_head_dim),
|
||||
position_rows,
|
||||
raw_key_cache,
|
||||
raw_metadata.block_table,
|
||||
raw_metadata.token_to_req,
|
||||
raw_metadata.query_start_loc,
|
||||
raw_metadata.logical_positions,
|
||||
compressed_metadata.slot_mapping,
|
||||
self.compress_ratio,
|
||||
rope_position_cache,
|
||||
)
|
||||
compressed_keys = gemma_rmsnorm(
|
||||
pooled.reshape(-1, self.index_head_dim),
|
||||
self.k_layernorm.weight,
|
||||
self.k_layernorm.variance_epsilon,
|
||||
).reshape(-1, 1, self.index_head_dim)
|
||||
if getattr(self.rotary_emb, "mrope_section", None):
|
||||
first_positions = first_positions.transpose(0, 1)
|
||||
else:
|
||||
first_positions = first_positions[:, 0]
|
||||
compressed_keys = apply_qsa_rope(
|
||||
self.rotary_emb,
|
||||
first_positions,
|
||||
compressed_keys,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
compressed_key_cache,
|
||||
compressed_metadata.slot_mapping,
|
||||
compressed_keys,
|
||||
)
|
||||
qsa_store_cache_rows(
|
||||
raw_key_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
raw_keys,
|
||||
)
|
||||
if rope_position_cache is not None:
|
||||
qsa_store_cache_rows(
|
||||
rope_position_cache,
|
||||
raw_metadata.slot_mapping,
|
||||
position_rows,
|
||||
)
|
||||
|
||||
if self.skip_topk:
|
||||
if out is None:
|
||||
raise RuntimeError("QSA top-k reuse requires an output buffer")
|
||||
return out
|
||||
|
||||
# Score compressed keys, select blocks, then expand them to token indices.
|
||||
return qsa_select_paged_tokens(
|
||||
q,
|
||||
compressed_key_cache,
|
||||
compressed_metadata.block_table,
|
||||
compressed_metadata.token_to_req,
|
||||
compressed_metadata.logical_positions,
|
||||
compressed_metadata.seq_lens,
|
||||
self.token_topk,
|
||||
self.compress_ratio,
|
||||
out,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["QSAIndexer", "apply_qsa_rope"]
|
||||
@@ -0,0 +1,185 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Qwen4Exp decode GEMM selection on Blackwell.
|
||||
|
||||
Dispatch follows Kimi-K3 and uses the local ``(N, K)`` shape and token count.
|
||||
Plans contain measured CUDA graph capture sizes; other token counts use the
|
||||
standard linear implementation.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.model_executor.kernels.linear.cute_dsl.skinny_gemm import (
|
||||
SkinnyGemmConfig,
|
||||
shape_dynamic_skinny_gemm,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
UnquantizedEmbeddingMethod,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
QWEN4_EXP_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] = {
|
||||
# GDN fused QKVZ projection, TP=4.
|
||||
(4096, 2560): {
|
||||
1: SkinnyGemmConfig(1, 64, 4, k_unroll=4),
|
||||
2: SkinnyGemmConfig(2, 64, 4, k_unroll=4),
|
||||
},
|
||||
# GDN and QSA output projections, TP=4.
|
||||
(2560, 1536): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=2, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=2, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2),
|
||||
},
|
||||
# GDN fused B/A projection, TP=4.
|
||||
(24, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 2, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4),
|
||||
16: SkinnyGemmConfig(16, 128, 1, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# QSA fused QKV/gate projection, TP=4.
|
||||
(3584, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 4, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2),
|
||||
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2),
|
||||
},
|
||||
# QSA indexer Q/K projection, replicated in a TP=4 deployment.
|
||||
(640, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 1, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 1, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 1, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# Shared-expert fused gate/up projection, TP=4.
|
||||
(320, 2560): {
|
||||
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
|
||||
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4),
|
||||
4: SkinnyGemmConfig(4, 128, 2, k_unroll=4, vector_width=4),
|
||||
8: SkinnyGemmConfig(8, 64, 1, k_unroll=4),
|
||||
16: SkinnyGemmConfig(16, 128, 2, k_unroll=4, vector_width=4),
|
||||
},
|
||||
# LM head, TP=4.
|
||||
(62080, 2560): {
|
||||
1: SkinnyGemmConfig(1, 64, 4, k_unroll=2),
|
||||
2: SkinnyGemmConfig(2, 32, 4, k_unroll=2),
|
||||
},
|
||||
# HC merged down/injection projection, replicated in a TP=4 deployment.
|
||||
(336, 10240): {
|
||||
1: SkinnyGemmConfig(1, 128, 1, static_k=10240),
|
||||
2: SkinnyGemmConfig(2, 128, 1, static_k=10240),
|
||||
4: SkinnyGemmConfig(4, 128, 2, static_k=10240),
|
||||
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _is_sm103() -> bool:
|
||||
return current_platform.is_device_capability((10, 3))
|
||||
|
||||
|
||||
def _is_packed_row_major(tensor: torch.Tensor) -> bool:
|
||||
return tensor.dim() == 2 and tensor.stride() == (tensor.shape[1], 1)
|
||||
|
||||
|
||||
def _runtime_ok(x: torch.Tensor, weight: torch.Tensor) -> bool:
|
||||
return (
|
||||
not envs.VLLM_BATCH_INVARIANT
|
||||
and _is_packed_row_major(x)
|
||||
and _is_packed_row_major(weight)
|
||||
and x.dtype == torch.bfloat16
|
||||
and weight.dtype == torch.bfloat16
|
||||
and x.is_cuda
|
||||
and weight.is_cuda
|
||||
and x.device == weight.device
|
||||
and x.shape[1] == weight.shape[1]
|
||||
)
|
||||
|
||||
|
||||
class _Qwen4ExpLowLatencyApply:
|
||||
def apply(
|
||||
self,
|
||||
layer: nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if bias is None and not envs.VLLM_BATCH_INVARIANT:
|
||||
return torch.ops.vllm.qwen4_exp_low_latency_gemm(x, layer.weight)
|
||||
return super().apply(layer, x, bias) # type: ignore[misc]
|
||||
|
||||
|
||||
class Qwen4ExpLowLatencyLinearMethod(_Qwen4ExpLowLatencyApply, UnquantizedLinearMethod):
|
||||
pass
|
||||
|
||||
|
||||
class Qwen4ExpLowLatencyEmbeddingMethod(
|
||||
_Qwen4ExpLowLatencyApply, UnquantizedEmbeddingMethod
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def _qwen4_exp_low_latency_gemm(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
|
||||
plan = QWEN4_EXP_GEMM_PLANS.get((weight.shape[0], weight.shape[1]))
|
||||
config = None if plan is None else plan.get(x.shape[0])
|
||||
if (
|
||||
config is not None
|
||||
and _runtime_ok(x, weight)
|
||||
and shape_dynamic_skinny_gemm.is_available()
|
||||
):
|
||||
return shape_dynamic_skinny_gemm(x, weight, config)
|
||||
return torch.nn.functional.linear(x, weight)
|
||||
|
||||
|
||||
def _qwen4_exp_low_latency_gemm_fake(
|
||||
x: torch.Tensor, weight: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
return x.new_empty((*x.shape[:-1], weight.shape[0]))
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_low_latency_gemm",
|
||||
op_func=_qwen4_exp_low_latency_gemm,
|
||||
fake_impl=_qwen4_exp_low_latency_gemm_fake,
|
||||
)
|
||||
|
||||
|
||||
def enable_qwen4_exp_low_latency_gemm(
|
||||
module: nn.Module,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
if dtype != torch.bfloat16 or not _is_sm103():
|
||||
return
|
||||
if not shape_dynamic_skinny_gemm.is_available():
|
||||
return
|
||||
|
||||
warmup_configs: set[SkinnyGemmConfig] = set()
|
||||
for child in module.modules():
|
||||
is_linear = (
|
||||
isinstance(child, LinearBase)
|
||||
and type(child.quant_method) is UnquantizedLinearMethod
|
||||
)
|
||||
is_head = (
|
||||
isinstance(child, ParallelLMHead)
|
||||
and type(child.quant_method) is UnquantizedEmbeddingMethod
|
||||
)
|
||||
if not (is_linear or is_head):
|
||||
continue
|
||||
weight = getattr(child, "weight", None)
|
||||
if weight is None or weight.dim() != 2:
|
||||
continue
|
||||
plan = QWEN4_EXP_GEMM_PLANS.get((weight.shape[0], weight.shape[1]))
|
||||
if plan is None:
|
||||
continue
|
||||
if is_linear:
|
||||
child.quant_method = Qwen4ExpLowLatencyLinearMethod()
|
||||
else:
|
||||
child.quant_method = Qwen4ExpLowLatencyEmbeddingMethod()
|
||||
warmup_configs.update(plan.values())
|
||||
|
||||
if warmup_configs:
|
||||
shape_dynamic_skinny_gemm.request_warmup_configs(dtype, warmup_configs)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,143 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Model-runner state for Qwen4Exp PLE inputs."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
class Qwen4ExpModelState(MambaHybridModelState):
|
||||
"""Add rollback-safe PLE n-gram context to the model inputs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
model: nn.Module,
|
||||
encoder_cache: EncoderCache | None,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(vllm_config, model, encoder_cache, device)
|
||||
config = self.model_config.hf_text_config
|
||||
self.uses_ngram_embedding = bool(config.ple_layer_ids)
|
||||
if not self.uses_ngram_embedding:
|
||||
self.ngram_context_len = 0
|
||||
self.ngram_eos_token_id = 0
|
||||
return
|
||||
|
||||
if vllm_config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise RuntimeError(
|
||||
"N-gram PLE embedding currently requires "
|
||||
"pipeline_parallel_size=1 because non-first pipeline ranks do "
|
||||
"not receive the raw input_ids required by PLE. Please run "
|
||||
"with PP=1."
|
||||
)
|
||||
|
||||
self.ngram_context_len = int(config.ngram_size) - 1
|
||||
if self.ngram_context_len <= 0:
|
||||
raise ValueError("N-gram embedding requires context length >= 1.")
|
||||
self.ngram_eos_token_id = int(config.eos_token_id)
|
||||
self.ngram_context = torch.full(
|
||||
(self.max_num_reqs, self.ngram_context_len),
|
||||
self.ngram_eos_token_id,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
self.ngram_context_offsets = torch.arange(
|
||||
-self.ngram_context_len,
|
||||
0,
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
self.ple_query_start_loc = torch.zeros(
|
||||
self.max_num_reqs + 1,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
def _prepare_ngram_context(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> torch.Tensor:
|
||||
num_reqs = input_batch.num_reqs
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
context = self.ngram_context[:num_reqs_padded]
|
||||
context.fill_(self.ngram_eos_token_id)
|
||||
if num_reqs == 0:
|
||||
return context
|
||||
|
||||
request_indices = input_batch.idx_mapping[:num_reqs].long()
|
||||
context_end = req_states.num_computed_tokens.gpu[request_indices].long()
|
||||
token_indices = context_end.unsqueeze(1) + self.ngram_context_offsets
|
||||
valid_tokens = token_indices >= 0
|
||||
token_indices.clamp_min_(0)
|
||||
context_tokens = req_states.all_token_ids.gpu[
|
||||
request_indices.unsqueeze(1), token_indices
|
||||
]
|
||||
context[:num_reqs].copy_(
|
||||
torch.where(
|
||||
valid_tokens,
|
||||
context_tokens,
|
||||
context_tokens.new_full((), self.ngram_eos_token_id),
|
||||
)
|
||||
)
|
||||
return context
|
||||
|
||||
def prepare_inputs(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
req_states: RequestState,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_inputs(input_batch, req_states)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
num_reqs_padded = input_batch.num_reqs_after_padding
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs_padded + 1]
|
||||
query_start_loc.copy_(input_batch.query_start_loc[: num_reqs_padded + 1])
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=self._prepare_ngram_context(input_batch, req_states),
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
def prepare_dummy_inputs(
|
||||
self,
|
||||
num_reqs: int,
|
||||
num_tokens: int,
|
||||
) -> dict[str, Any]:
|
||||
model_inputs = super().prepare_dummy_inputs(num_reqs, num_tokens)
|
||||
if not self.uses_ngram_embedding:
|
||||
return model_inputs
|
||||
|
||||
query_start_loc = self.ple_query_start_loc[: num_reqs + 1]
|
||||
query_start_loc[0] = 0
|
||||
tokens_per_req, num_extra_tokens = divmod(num_tokens, num_reqs)
|
||||
query_lens = torch.full(
|
||||
(num_reqs,),
|
||||
tokens_per_req,
|
||||
dtype=query_start_loc.dtype,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
if num_extra_tokens > 0:
|
||||
query_lens[-num_extra_tokens:] += 1
|
||||
torch.cumsum(query_lens, dim=0, out=query_start_loc[1:])
|
||||
|
||||
ngram_context = self.ngram_context[:num_reqs]
|
||||
ngram_context.fill_(self.ngram_eos_token_id)
|
||||
model_inputs.update(
|
||||
query_start_loc=query_start_loc,
|
||||
ngram_context=ngram_context,
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpModelState"]
|
||||
@@ -0,0 +1,462 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-only Qwen4Exp MTP (Multi-Token Predictor) model.
|
||||
|
||||
The MTP draft model reuses the Qwen4Exp backbone (PLE/HC/MoE) but:
|
||||
- drops all multi-modal handling (text-only),
|
||||
- forces PLE off while keeping the main model's HC stream count,
|
||||
- fuses the backbone hidden and the new-token embedding via
|
||||
``residual_linear_shared`` (fc_embedding + shared fc_hidden) instead of
|
||||
the ``Linear(2H, H)`` + repeat used by other MTP variants,
|
||||
- emits TWO hidden streams per step (scheme A): a single stream [T, H]
|
||||
(final-mixer collapsed, fed to the LM head) and a pre-final-mixer
|
||||
multi stream [T, hc_count*H] (fed to the next draft step).
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import VllmConfig, replace, set_current_vllm_config
|
||||
from vllm.distributed import get_pp_group
|
||||
from vllm.model_executor.layers.fused_moe.utils import (
|
||||
is_model_fused_shared_expert_compatible,
|
||||
)
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
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.utils import configure_quant_config
|
||||
from vllm.model_executor.models.interfaces import SupportsPP
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5Model
|
||||
from vllm.model_executor.models.utils import (
|
||||
AutoWeightsLoader,
|
||||
PPMissingLayer,
|
||||
WeightsMapper,
|
||||
get_draft_quant_config,
|
||||
make_empty_intermediate_tensors_factory,
|
||||
maybe_fuse_shared_experts,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .model import (
|
||||
_HC_WEIGHTS_MAPPER,
|
||||
_QWEN4_EXP_IGNORED_MISSING_SUFFIXES,
|
||||
Qwen4ExpDecoderLayer,
|
||||
Qwen4ExpMixtureOfExperts,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
)
|
||||
|
||||
|
||||
def _remap_ignored_layers(
|
||||
ignored_layers: list[str],
|
||||
mtp_start_layer_idx: int,
|
||||
) -> list[str]:
|
||||
remapped: list[str] = []
|
||||
for name in ignored_layers:
|
||||
if name.startswith("mtp."):
|
||||
new_name = re.sub(
|
||||
r"(?<=\.layers\.)\d+",
|
||||
lambda m: str(mtp_start_layer_idx + int(m.group(0))),
|
||||
name,
|
||||
)
|
||||
remapped.append(new_name)
|
||||
else:
|
||||
remapped.append(name)
|
||||
return remapped
|
||||
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
):
|
||||
if name.startswith(checkpoint_prefix):
|
||||
name = name.removeprefix(checkpoint_prefix)
|
||||
break
|
||||
|
||||
if name.startswith("embed_tokens."):
|
||||
name = f"model.{name}"
|
||||
if name.startswith("model.mtp."):
|
||||
name = name.removeprefix("model.")
|
||||
if name.startswith("mtp.shared_head.head."):
|
||||
return name.replace("mtp.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.shared_head.head."):
|
||||
return name.replace("model.shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("shared_head.head."):
|
||||
return name.replace("shared_head.head.", "lm_head.", 1)
|
||||
if name.startswith("model.lm_head."):
|
||||
return name.removeprefix("model.")
|
||||
if name.startswith("mtp."):
|
||||
return name.replace("mtp.", "model.", 1)
|
||||
if name.startswith("model.embed_tokens.") or name.startswith("lm_head."):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def _make_draft_vllm_config(
|
||||
vllm_config: VllmConfig,
|
||||
mtp_start_layer_idx: int,
|
||||
) -> VllmConfig:
|
||||
"""Ensure that the draft model config is set in the vLLM config."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if speculative_config is None or speculative_config.draft_model_config is None:
|
||||
raise ValueError("speculative_config.draft_model_config must be set")
|
||||
|
||||
draft_quant_config = get_draft_quant_config(vllm_config)
|
||||
|
||||
# inject packed and ignored modules to the quantization config of draft model
|
||||
if draft_quant_config is not None:
|
||||
configure_quant_config(draft_quant_config, Qwen4ExpMTP)
|
||||
ignored_layers = getattr(draft_quant_config, "ignored_layers", None)
|
||||
if ignored_layers:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"ignored_layers",
|
||||
_remap_ignored_layers(ignored_layers, mtp_start_layer_idx),
|
||||
)
|
||||
exclude_modules = getattr(draft_quant_config, "exclude_modules", None)
|
||||
if exclude_modules:
|
||||
setattr( # noqa: B010
|
||||
draft_quant_config,
|
||||
"exclude_modules",
|
||||
_remap_ignored_layers(exclude_modules, mtp_start_layer_idx),
|
||||
)
|
||||
|
||||
draft_vllm_config = replace(
|
||||
vllm_config,
|
||||
model_config=speculative_config.draft_model_config,
|
||||
)
|
||||
# VllmConfig post-init derives the target quant config, so restore the
|
||||
# independently resolved draft quant config after replacement.
|
||||
draft_vllm_config.quant_config = draft_quant_config
|
||||
return draft_vllm_config
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
super().__init__()
|
||||
|
||||
model_config = vllm_config.model_config
|
||||
config: Qwen4ExpTextConfig = model_config.hf_text_config
|
||||
|
||||
self.config = config
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers
|
||||
self.num_mtp_layers = getattr(config, "mtp_num_hidden_layers", 1)
|
||||
|
||||
self.hidden_size = config.hidden_size
|
||||
self.hc_count = config.hc_count
|
||||
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, self.hidden_size)
|
||||
draft_vllm_config = _make_draft_vllm_config(
|
||||
vllm_config,
|
||||
self.mtp_start_layer_idx,
|
||||
)
|
||||
with set_current_vllm_config(draft_vllm_config, prefix=prefix):
|
||||
# residual_linear_shared fusion: fc_embedding projects the token
|
||||
# embedding, fc_hidden (shared across HC branches) projects the
|
||||
# backbone hidden; the embedding is added as a residual to every
|
||||
# branch (see mtp_residual_linear_shared.md).
|
||||
self.fc_embedding = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_embedding",
|
||||
)
|
||||
self.fc_hidden = ColumnParallelLinear(
|
||||
self.hidden_size,
|
||||
self.hidden_size,
|
||||
gather_output=True,
|
||||
bias=False,
|
||||
return_bias=False,
|
||||
quant_config=draft_vllm_config.quant_config,
|
||||
prefix=f"{prefix}.fc_hidden",
|
||||
)
|
||||
self.layers = nn.ModuleList(
|
||||
Qwen4ExpDecoderLayer(
|
||||
draft_vllm_config,
|
||||
layer_type="full_attention",
|
||||
prefix=f"{prefix}.layers.{self.mtp_start_layer_idx + idx}",
|
||||
)
|
||||
for idx in range(self.num_mtp_layers)
|
||||
)
|
||||
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
|
||||
self.layers,
|
||||
Qwen4ExpSparseMoeBlock,
|
||||
"mlp",
|
||||
)
|
||||
|
||||
self.pre_fc_norm_embedding = GemmaRMSNorm(
|
||||
self.hidden_size, eps=config.rms_norm_eps
|
||||
)
|
||||
self.pre_fc_norm_hidden = GemmaRMSNorm(
|
||||
self.hidden_size * self.hc_count, eps=config.rms_norm_eps
|
||||
)
|
||||
# HC final mixer collapses the multi stream into [T, H] for the LM head.
|
||||
hc_config = HyperConnectionConfig(
|
||||
hc_count=config.hc_count,
|
||||
hidden_size=config.hidden_size,
|
||||
params_dtype=torch.bfloat16,
|
||||
hc_lowrank=config.hc_lowrank,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
hc_per_branch_norm=True,
|
||||
)
|
||||
self.hyper_connection_mixer = GatedResidual(
|
||||
hc_config,
|
||||
use_combine=False,
|
||||
prefix=maybe_prefix(prefix, "hyper_connection_mixer"),
|
||||
)
|
||||
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
|
||||
["hidden_states"], self.hidden_size * self.hc_count
|
||||
)
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
attention is not None
|
||||
and getattr(attention, "indexer", None) is not None
|
||||
):
|
||||
yield attention
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
selected = buffer.index_select(0, row_indices)
|
||||
buffer[:num_rows].copy_(selected)
|
||||
|
||||
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
|
||||
return self.embed_tokens(input_ids)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor | None,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
hc_count = self.hc_count
|
||||
hidden_size = self.hidden_size
|
||||
|
||||
if get_pp_group().is_first_rank:
|
||||
assert hidden_states is not None
|
||||
if inputs_embeds is None:
|
||||
assert input_ids is not None
|
||||
inputs_embeds = self.embed_input_ids(input_ids)
|
||||
# Embedding branch: pre-norm -> fc_embedding -> [T, H].
|
||||
inputs_embeds = self.pre_fc_norm_embedding(inputs_embeds)
|
||||
inputs_embeds = self.fc_embedding(inputs_embeds)
|
||||
|
||||
# Backbone hidden is multi-stream [T, hc_count*H] (scheme A:
|
||||
# the main model truly emits the pre-final-mixer multi stream
|
||||
# on the first step; subsequent steps reuse the prior draft
|
||||
# step's multi stream).
|
||||
num_tokens = hidden_states.shape[0]
|
||||
hidden_states = hidden_states.view(num_tokens, hc_count, hidden_size)
|
||||
hidden_states = self.pre_fc_norm_hidden(hidden_states.flatten(-2)).view(
|
||||
num_tokens, hc_count, hidden_size
|
||||
)
|
||||
hidden_states = self.fc_hidden(hidden_states)
|
||||
# Add the embedding residual to every branch, then fold back
|
||||
# to [T, hc_count*H] (HC outer, HS inner) for the HC decoder.
|
||||
hidden_states = inputs_embeds.unsqueeze(-2) + hidden_states
|
||||
hidden_states = hidden_states.flatten(-2)
|
||||
else:
|
||||
assert intermediate_tensors is not None
|
||||
hidden_states = intermediate_tensors["hidden_states"]
|
||||
|
||||
current_step_idx = spec_step_idx % self.num_mtp_layers
|
||||
layer = self.layers[current_step_idx]
|
||||
hidden_states, block_output, injection = layer(
|
||||
hidden_states=hidden_states,
|
||||
prev_block_output=None,
|
||||
prev_injection=None,
|
||||
positions=positions,
|
||||
input_ids=None,
|
||||
query_start_loc=None,
|
||||
ngram_context=None,
|
||||
)
|
||||
if not get_pp_group().is_last_rank:
|
||||
# As in the target model, PP carries a materialized tensor rather
|
||||
# than the delayed hidden/output/injection tuple.
|
||||
hidden_states = layer.mlp_hyper_connection.combine(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
return IntermediateTensors({"hidden_states": hidden_states})
|
||||
|
||||
# Last PP rank finalize. Keep both:
|
||||
# (A) sample_hidden_states [T, H] -> single stream for the LM head
|
||||
# (B) multi_hidden [T, hc_count*H] -> pre-final-mixer multi stream
|
||||
# for the next draft step (zero extra compute, just kept).
|
||||
multi_hidden, sample_hidden_states, _ = (
|
||||
self.hyper_connection_mixer.combine_and_mix(
|
||||
hidden_states, block_output, injection
|
||||
)
|
||||
)
|
||||
return sample_hidden_states, multi_hidden
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
weights = maybe_fuse_shared_experts(
|
||||
weights,
|
||||
enabled=self.is_fused_shared_expert_enabled,
|
||||
n_routed_experts=getattr(self.config, "num_experts", 0) or 0,
|
||||
n_shared_experts=1,
|
||||
ckpt_prefix="mlp.shared_expert",
|
||||
)
|
||||
mapper = self.hf_to_vllm_mapper | WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(weights, mapper=mapper)
|
||||
|
||||
|
||||
@support_torch_compile(
|
||||
dynamic_arg_dims={
|
||||
"input_ids": 0,
|
||||
"positions": -1,
|
||||
"intermediate_tensors": 0,
|
||||
"inputs_embeds": 0,
|
||||
"hidden_states": 0,
|
||||
}
|
||||
)
|
||||
class Qwen4ExpMTP(nn.Module, SupportsPP, Qwen4ExpMixtureOfExperts):
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
"in_proj_qkvz": ["in_proj_qkv", "in_proj_z"],
|
||||
"in_proj_ba": ["in_proj_b", "in_proj_a"],
|
||||
"input_mix_weight_down_block_inject": [
|
||||
"input_mix_weight_down",
|
||||
"block_inject_weight",
|
||||
"_input_mix_padding",
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
config: Qwen4ExpTextConfig = vllm_config.model_config.hf_text_config
|
||||
self.vllm_config = vllm_config
|
||||
cache_config = vllm_config.cache_config
|
||||
if cache_config.mamba_cache_mode == "all":
|
||||
raise NotImplementedError(
|
||||
"Qwen4ExpMTP currently does not support 'all' prefix caching, "
|
||||
"please use '--mamba-cache-mode=align' instead"
|
||||
)
|
||||
|
||||
self.quant_config = vllm_config.quant_config
|
||||
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.model = Qwen4ExpMultiTokenPredictor(
|
||||
vllm_config=vllm_config,
|
||||
prefix=maybe_prefix(prefix, "mtp"),
|
||||
)
|
||||
|
||||
if get_pp_group().is_last_rank:
|
||||
if config.tie_word_embeddings:
|
||||
self.lm_head = self.model.embed_tokens
|
||||
else:
|
||||
self.lm_head = ParallelLMHead(
|
||||
config.vocab_size,
|
||||
config.hidden_size,
|
||||
prefix=maybe_prefix(prefix, "lm_head"),
|
||||
)
|
||||
else:
|
||||
self.lm_head = PPMissingLayer()
|
||||
|
||||
self.logits_processor = LogitsProcessor(config.vocab_size)
|
||||
self.make_empty_intermediate_tensors = (
|
||||
self.model.make_empty_intermediate_tensors
|
||||
)
|
||||
self.set_moe_parameters(self.model.layers)
|
||||
enable_qwen4_exp_low_latency_gemm(self, vllm_config.model_config.dtype)
|
||||
|
||||
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 | None = None,
|
||||
intermediate_tensors: IntermediateTensors | None = None,
|
||||
inputs_embeds: torch.Tensor | None = None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor] | IntermediateTensors:
|
||||
return self.model(
|
||||
input_ids,
|
||||
positions,
|
||||
hidden_states,
|
||||
intermediate_tensors,
|
||||
inputs_embeds,
|
||||
spec_step_idx=spec_step_idx,
|
||||
)
|
||||
|
||||
def compute_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int = 0
|
||||
) -> torch.Tensor | None:
|
||||
return self.logits_processor(self.lm_head, hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
def remap_weight_names():
|
||||
for name, weight in weights:
|
||||
remapped_name = _remap_mtp_weight_name(name)
|
||||
if remapped_name is not None:
|
||||
yield remapped_name, weight
|
||||
|
||||
mapper = WeightsMapper(
|
||||
orig_to_new_substr={"hyper_connection_mixer.block_inject_weight": None}
|
||||
)
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
ignore_unexpected_suffixes=_QWEN4_EXP_IGNORED_MISSING_SUFFIXES.copy(),
|
||||
)
|
||||
return loader.load_weights(remap_weight_names(), mapper=mapper)
|
||||
|
||||
|
||||
__all__ = ["Qwen4ExpMTP", "Qwen4ExpMultiTokenPredictor"]
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA-only Qwen4Exp kernels; import leaf modules directly."""
|
||||
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA HyperConnection kernels for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_gemma_rmsnorm_kernel(
|
||||
x_ptr,
|
||||
w_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
NUM_GROUPS: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
GROUP_DIM: tl.constexpr = DIM // NUM_GROUPS
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(GROUP_DIM)
|
||||
|
||||
pid = tl.program_id(0)
|
||||
group_id = pid % NUM_GROUPS
|
||||
row = pid // NUM_GROUPS
|
||||
|
||||
offs_g = tl.arange(0, BLOCK_SIZE)
|
||||
offsets = group_id * GROUP_DIM + offs_g
|
||||
mask = offs_g < GROUP_DIM
|
||||
# A [GROUP_DIM] affine is shared; a [DIM] affine follows the grouped
|
||||
# checkpoint layout.
|
||||
w_offs = offs_g if W_SHARED else offsets
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0).to(tl.float32)
|
||||
w = tl.load(w_ptr + w_offs, mask, other=0.0)
|
||||
|
||||
rrms = tl.rsqrt(tl.sum(x * x) / GROUP_DIM + EPS)
|
||||
# Gemma's (1 + w) affine is written this way to lower to an FMA.
|
||||
y = x * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offsets, y, mask)
|
||||
|
||||
|
||||
def _grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
N, DIM = x.shape
|
||||
assert x.stride(1) == 1, "grouped Gemma RMSNorm requires unit inner stride"
|
||||
assert weight.is_contiguous(), "grouped Gemma RMSNorm weight must be contiguous"
|
||||
assert DIM % num_groups == 0
|
||||
group_dim = DIM // num_groups
|
||||
assert weight.numel() in (group_dim, DIM)
|
||||
|
||||
y = x.new_empty(x.shape)
|
||||
_grouped_gemma_rmsnorm_kernel[(N * num_groups,)](
|
||||
x,
|
||||
weight,
|
||||
y,
|
||||
x.stride(0),
|
||||
y.stride(0),
|
||||
DIM,
|
||||
num_groups,
|
||||
W_SHARED=weight.numel() == group_dim,
|
||||
EPS=eps,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return y
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_silu_kernel(
|
||||
x_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
BLOCK_SIZE: tl.constexpr = triton.next_power_of_2(DIM)
|
||||
|
||||
row = tl.program_id(0)
|
||||
offs = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs < DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x + offs, mask).to(tl.float32) / HC
|
||||
y = x * tl.sigmoid(x)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask)
|
||||
|
||||
|
||||
def _hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
num_tokens, DIM = x.shape
|
||||
assert x.stride(1) == 1
|
||||
|
||||
output = x.new_empty(x.shape)
|
||||
_hc_silu_kernel[(num_tokens,)](
|
||||
x,
|
||||
output,
|
||||
x.stride(0),
|
||||
output.stride(0),
|
||||
DIM=DIM,
|
||||
HC=hc_count,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_gate_mix_kernel(
|
||||
x_ptr,
|
||||
g_ptr,
|
||||
y_ptr,
|
||||
stride_x,
|
||||
stride_g,
|
||||
stride_y,
|
||||
DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_DIM: tl.constexpr = DIM // HC
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offs_inner < HC_DIM
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# The constexpr loop is unrolled and keeps one stream live at a time.
|
||||
# Materializing [HC, BLOCK_SIZE] more than doubles latency at large M.
|
||||
acc = tl.zeros([BLOCK_SIZE], dtype=tl.float32)
|
||||
for stream in tl.static_range(HC):
|
||||
offsets = stream * HC_DIM + offs_inner
|
||||
g = tl.load(g_ptr + row * stride_g + offsets, mask, other=0.0)
|
||||
x = tl.load(x_ptr + row * stride_x + offsets, mask, other=0.0)
|
||||
acc += tl.sigmoid(g.to(tl.float32)) * x.to(tl.float32)
|
||||
acc /= HC
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(y_ptr + row * stride_y + offs_inner, acc, mask)
|
||||
|
||||
|
||||
def _hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
N, DIM = gate.shape
|
||||
assert x.shape == gate.shape
|
||||
assert DIM % hc_count == 0
|
||||
assert x.stride(1) == 1
|
||||
assert gate.stride(1) == 1
|
||||
|
||||
HC_DIM = DIM // hc_count
|
||||
out = x.new_empty(N, HC_DIM)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_gate_mix_kernel[(N, triton.cdiv(HC_DIM, BLOCK_SIZE))](
|
||||
x,
|
||||
gate,
|
||||
out,
|
||||
x.stride(0),
|
||||
gate.stride(0),
|
||||
out.stride(0),
|
||||
DIM,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
out_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
|
||||
row = tl.program_id(0)
|
||||
tile_id = tl.program_id(1)
|
||||
|
||||
offs_inner = tile_id * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
offs = offs_hc[:, None] * HC_DIM + offs_inner[None, :]
|
||||
mask = mask_hc[:, None] & mask_inner[None, :]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask, other=0.0)
|
||||
|
||||
# Keeping HC as a broadcast dimension is faster here than four separate
|
||||
# residual load/store sequences.
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
out = res.to(tl.float32) + block.to(tl.float32)[None, :] * inj[:, None]
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask)
|
||||
|
||||
|
||||
def _hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_kernel[(N, triton.cdiv(hc_dim, BLOCK_SIZE))](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
out,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _hc_combine_norm_kernel(
|
||||
block_ptr,
|
||||
res_ptr,
|
||||
inj_ptr,
|
||||
w_ptr,
|
||||
out_ptr,
|
||||
y_ptr,
|
||||
stride_block,
|
||||
stride_res,
|
||||
stride_inj,
|
||||
stride_out,
|
||||
stride_y,
|
||||
HC_DIM: tl.constexpr,
|
||||
HC: tl.constexpr,
|
||||
W_SHARED: tl.constexpr,
|
||||
EPS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
) -> None:
|
||||
HC_PAD: tl.constexpr = triton.next_power_of_2(HC)
|
||||
NUM_TILES: tl.constexpr = triton.cdiv(HC_DIM, BLOCK_SIZE)
|
||||
NUM_TILES_PAD: tl.constexpr = triton.next_power_of_2(NUM_TILES)
|
||||
|
||||
row = tl.program_id(0)
|
||||
stream = tl.program_id(1)
|
||||
offs_hc = tl.arange(0, HC_PAD)
|
||||
mask_hc = offs_hc < HC
|
||||
tile_ids = tl.arange(0, NUM_TILES_PAD)
|
||||
offs_inner = tile_ids[:, None] * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)[None, :]
|
||||
mask_inner = offs_inner < HC_DIM
|
||||
offs = stream * HC_DIM + offs_inner
|
||||
# Shared norm weights repeat across streams; per-branch weights use the
|
||||
# same flattened HC layout as the residual.
|
||||
w_offs = offs_inner if W_SHARED else offs
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
|
||||
# Start the uncached residual load first, then issue the other combine
|
||||
# loads before consuming any of them.
|
||||
res = tl.load(res_ptr + row * stride_res + offs, mask_inner, other=0.0)
|
||||
inj = tl.load(inj_ptr + row * stride_inj + offs_hc, mask_hc, other=0.0)
|
||||
block = tl.load(block_ptr + row * stride_block + offs_inner, mask_inner, other=0.0)
|
||||
inj = 2.0 * tl.sigmoid(inj.to(tl.float32) / HC)
|
||||
inj = tl.sum(tl.where(offs_hc == stream, inj, 0.0))
|
||||
# Round the materialized combine result before normalization. This matches
|
||||
# the unfused combine -> RMSNorm boundary.
|
||||
out = (res.to(tl.float32) + block.to(tl.float32) * inj).to(out_ptr.dtype.element_ty)
|
||||
tl.store(out_ptr + row * stride_out + offs, out, mask=mask_inner)
|
||||
|
||||
out = out.to(tl.float32)
|
||||
# Keep the two-axis reduction: flattening the padded tile is ~40% slower
|
||||
# at decode sizes.
|
||||
sum_sq = tl.sum(tl.sum(out * out, axis=1), axis=0)
|
||||
rrms = tl.rsqrt(sum_sq / HC_DIM + EPS)
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
# Loading the weight earlier helps decode but keeps the tile live across
|
||||
# the reduction and regresses larger batches, so defer it to the norm.
|
||||
w = tl.load(w_ptr + w_offs, mask_inner, other=0.0)
|
||||
y = out * rrms
|
||||
y += y * w.to(tl.float32)
|
||||
tl.store(y_ptr + row * stride_y + offs, y, mask_inner)
|
||||
|
||||
|
||||
def _hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
N, DIM = residual.shape
|
||||
assert DIM % hc_count == 0
|
||||
hc_dim = DIM // hc_count
|
||||
assert block_output.shape == (N, hc_dim)
|
||||
assert injection_logits.shape == (N, hc_count)
|
||||
assert residual.stride(1) == 1
|
||||
assert block_output.stride(1) == 1
|
||||
assert injection_logits.stride(1) == 1
|
||||
assert norm_weight.is_contiguous()
|
||||
assert norm_weight.numel() in (hc_dim, DIM)
|
||||
|
||||
out = residual.new_empty(residual.shape)
|
||||
y = residual.new_empty(residual.shape)
|
||||
BLOCK_SIZE = 512
|
||||
_hc_combine_norm_kernel[(N, hc_count)](
|
||||
block_output,
|
||||
residual,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
out,
|
||||
y,
|
||||
block_output.stride(0),
|
||||
residual.stride(0),
|
||||
injection_logits.stride(0),
|
||||
out.stride(0),
|
||||
y.stride(0),
|
||||
hc_dim,
|
||||
hc_count,
|
||||
W_SHARED=norm_weight.numel() == hc_dim,
|
||||
EPS=eps,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
return out, y
|
||||
|
||||
|
||||
def _same_shape_fake(x: torch.Tensor, *args) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _hc_gate_mix_fake(
|
||||
x: torch.Tensor, gate: torch.Tensor, hc_count: int
|
||||
) -> torch.Tensor:
|
||||
del gate
|
||||
return x.new_empty((x.shape[0], x.shape[1] // hc_count))
|
||||
|
||||
|
||||
def _hc_combine_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
del block_output, injection_logits, hc_count
|
||||
return residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
def _hc_combine_norm_fake(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del block_output, injection_logits, norm_weight, eps, hc_count
|
||||
return residual.new_empty(residual.shape), residual.new_empty(residual.shape)
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_grouped_gemma_rmsnorm",
|
||||
op_func=_grouped_gemma_rmsnorm,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_silu",
|
||||
op_func=_hc_silu,
|
||||
fake_impl=_same_shape_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_gate_mix",
|
||||
op_func=_hc_gate_mix,
|
||||
fake_impl=_hc_gate_mix_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine",
|
||||
op_func=_hc_combine,
|
||||
fake_impl=_hc_combine_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_hc_combine_norm",
|
||||
op_func=_hc_combine_norm,
|
||||
fake_impl=_hc_combine_norm_fake,
|
||||
)
|
||||
|
||||
|
||||
def grouped_gemma_rmsnorm(
|
||||
x: torch.Tensor, weight: torch.Tensor, eps: float, num_groups: int
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_grouped_gemma_rmsnorm(x, weight, eps, num_groups)
|
||||
|
||||
|
||||
def hc_silu(x: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_silu(x, hc_count)
|
||||
|
||||
|
||||
def hc_gate_mix(x: torch.Tensor, gate: torch.Tensor, hc_count: int) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_gate_mix(x, gate, hc_count)
|
||||
|
||||
|
||||
def hc_combine(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
hc_count: int,
|
||||
) -> torch.Tensor:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine(
|
||||
residual, block_output, injection_logits, hc_count
|
||||
)
|
||||
|
||||
|
||||
def hc_combine_norm(
|
||||
residual: torch.Tensor,
|
||||
block_output: torch.Tensor,
|
||||
injection_logits: torch.Tensor,
|
||||
norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
hc_count: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.qwen4_exp_hc_combine_norm(
|
||||
residual,
|
||||
block_output,
|
||||
injection_logits,
|
||||
norm_weight,
|
||||
eps,
|
||||
hc_count,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"grouped_gemma_rmsnorm",
|
||||
"hc_combine",
|
||||
"hc_combine_norm",
|
||||
"hc_gate_mix",
|
||||
"hc_silu",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,508 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Fused QSA pre-indexer kernel for Qwen4Exp."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _norm_rope(
|
||||
x,
|
||||
pos_t,
|
||||
pos_h,
|
||||
pos_w,
|
||||
cos_sin_ptr,
|
||||
cos_sin_stride,
|
||||
norm_weight_ptr,
|
||||
eps,
|
||||
IS_MROPE: tl.constexpr,
|
||||
MROPE_H: tl.constexpr,
|
||||
MROPE_W: tl.constexpr,
|
||||
):
|
||||
"""Apply Gemma RMSNorm and selected-axis NeoX RoPE to register rows."""
|
||||
TILE_T: tl.constexpr = x.shape[0]
|
||||
TILE_H: tl.constexpr = x.shape[1]
|
||||
D: tl.constexpr = x.shape[2]
|
||||
ROWS: tl.constexpr = TILE_T * TILE_H
|
||||
HALF: tl.constexpr = D // 2
|
||||
QUARTER: tl.constexpr = D // 4
|
||||
pairs = tl.arange(0, QUARTER)
|
||||
if IS_MROPE:
|
||||
# Qwen interleaves temporal, height, and width rotary pairs. Each axis
|
||||
# still indexes the same position-major cos/sin table.
|
||||
h_mask = ((pairs % 3) == 1) & (pairs <= 3 * MROPE_H)
|
||||
w_mask = ((pairs % 3) == 2) & (pairs <= 3 * MROPE_W)
|
||||
t_mask = ~(h_mask | w_mask)
|
||||
base = cos_sin_ptr + pairs[None, :]
|
||||
pos_rows = (pos_t, pos_h, pos_w)
|
||||
axis_masks = (t_mask, h_mask, w_mask)
|
||||
cos = tl.zeros((TILE_T, QUARTER), dtype=cos_sin_ptr.dtype.element_ty)
|
||||
sin = tl.zeros((TILE_T, QUARTER), dtype=cos_sin_ptr.dtype.element_ty)
|
||||
for axis in tl.static_range(3):
|
||||
cos += tl.load(
|
||||
base + pos_rows[axis][:, None] * cos_sin_stride,
|
||||
mask=axis_masks[axis][None, :],
|
||||
other=0,
|
||||
)
|
||||
sin += tl.load(
|
||||
base + pos_rows[axis][:, None] * cos_sin_stride + QUARTER,
|
||||
mask=axis_masks[axis][None, :],
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
cos = tl.load(cos_sin_ptr + pos_t[:, None] * cos_sin_stride + pairs[None, :])
|
||||
sin = tl.load(
|
||||
cos_sin_ptr + pos_t[:, None] * cos_sin_stride + QUARTER + pairs[None, :]
|
||||
)
|
||||
|
||||
cos = tl.reshape(
|
||||
tl.broadcast_to(cos[:, None, :], (TILE_T, TILE_H, QUARTER)),
|
||||
(ROWS, QUARTER),
|
||||
)
|
||||
sin = tl.reshape(
|
||||
tl.broadcast_to(sin[:, None, :], (TILE_T, TILE_H, QUARTER)),
|
||||
(ROWS, QUARTER),
|
||||
)
|
||||
x = tl.reshape(x, (ROWS, D)).to(tl.float32)
|
||||
weight = tl.load(norm_weight_ptr + tl.arange(0, D)).to(tl.float32) + 1.0
|
||||
rrms = tl.rsqrt(tl.sum(x * x, axis=1) / D + eps)
|
||||
y = (x * rrms[:, None] * weight[None, :]).to(cos.dtype)
|
||||
rotated, passthrough = tl.split(
|
||||
tl.permute(tl.reshape(y, (ROWS, 2, HALF)), (0, 2, 1))
|
||||
)
|
||||
r0, r1 = tl.split(tl.permute(tl.reshape(rotated, (ROWS, 2, QUARTER)), (0, 2, 1)))
|
||||
out0 = r0 * cos - r1 * sin
|
||||
out1 = r1 * cos + r0 * sin
|
||||
rotated = tl.reshape(tl.permute(tl.join(out0, out1), (0, 2, 1)), (ROWS, HALF))
|
||||
result = tl.reshape(tl.permute(tl.join(rotated, passthrough), (0, 2, 1)), (ROWS, D))
|
||||
return tl.reshape(result, (TILE_T, TILE_H, D))
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=[
|
||||
"num_tokens",
|
||||
"num_state_blocks",
|
||||
"num_compressed_blocks",
|
||||
"num_k_work",
|
||||
]
|
||||
)
|
||||
def _qsa_pre_indexer_kernel(
|
||||
q_ptr,
|
||||
q_stride_token,
|
||||
k_ptr,
|
||||
k_stride_token,
|
||||
pos_ptr,
|
||||
pos_stride_axis,
|
||||
pos_stride_token,
|
||||
cos_sin_ptr,
|
||||
q_norm_weight_ptr,
|
||||
k_norm_weight_ptr,
|
||||
eps,
|
||||
q_out_ptr,
|
||||
q_out_stride_token,
|
||||
q_out_stride_head,
|
||||
state_cache_ptr,
|
||||
state_cache_stride_block,
|
||||
state_cache_stride_token,
|
||||
state_slots_ptr,
|
||||
state_table_ptr,
|
||||
state_table_stride_req,
|
||||
query_start_loc_ptr,
|
||||
logical_positions_ptr,
|
||||
compressed_slots_ptr,
|
||||
k_work_metadata_ptr,
|
||||
compressed_cache_ptr,
|
||||
compressed_cache_stride_block,
|
||||
compressed_cache_stride_token,
|
||||
num_tokens,
|
||||
num_state_blocks,
|
||||
num_compressed_blocks,
|
||||
num_k_work,
|
||||
HQ: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
TILE_T_Q: tl.constexpr,
|
||||
TILE_H_Q: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
STATE_SIZE: tl.constexpr,
|
||||
COMP_PAGE_SIZE: tl.constexpr,
|
||||
IS_2D_POSITIONS: tl.constexpr,
|
||||
IS_K_MROPE: tl.constexpr,
|
||||
CACHE_HAS_ROPE_POS: tl.constexpr,
|
||||
MROPE_H: tl.constexpr,
|
||||
MROPE_W: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
# K work occupies the first programs; the remaining programs tile Q. This
|
||||
# keeps both paths in one launch while leaving their register shapes
|
||||
# independent.
|
||||
if pid >= num_k_work:
|
||||
q_pid = pid - num_k_work
|
||||
num_head_tiles: tl.constexpr = tl.cdiv(HQ, TILE_H_Q)
|
||||
token_tile = q_pid // num_head_tiles
|
||||
head_tile = q_pid % num_head_tiles
|
||||
tokens = token_tile * TILE_T_Q + tl.arange(0, TILE_T_Q)
|
||||
heads = head_tile * TILE_H_Q + tl.arange(0, TILE_H_Q)
|
||||
valid_tokens = tokens < num_tokens
|
||||
valid_heads = heads < HQ
|
||||
dims = tl.arange(0, D)
|
||||
mask = valid_tokens[:, None, None] & valid_heads[None, :, None]
|
||||
x = tl.load(
|
||||
q_ptr
|
||||
+ tokens[:, None, None] * q_stride_token
|
||||
+ heads[None, :, None] * D
|
||||
+ dims[None, None, :],
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
)
|
||||
pos_t = tl.load(pos_ptr + tokens * pos_stride_token, mask=valid_tokens, other=0)
|
||||
if IS_2D_POSITIONS:
|
||||
pos_h = tl.load(
|
||||
pos_ptr + pos_stride_axis + tokens * pos_stride_token,
|
||||
mask=valid_tokens,
|
||||
other=0,
|
||||
)
|
||||
pos_w = tl.load(
|
||||
pos_ptr + 2 * pos_stride_axis + tokens * pos_stride_token,
|
||||
mask=valid_tokens,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
pos_h = pos_t
|
||||
pos_w = pos_t
|
||||
y = _norm_rope(
|
||||
x,
|
||||
pos_t,
|
||||
pos_h,
|
||||
pos_w,
|
||||
cos_sin_ptr,
|
||||
D // 2,
|
||||
q_norm_weight_ptr,
|
||||
eps,
|
||||
IS_2D_POSITIONS,
|
||||
MROPE_H,
|
||||
MROPE_W,
|
||||
)
|
||||
tl.store(
|
||||
q_out_ptr
|
||||
+ tokens[:, None, None] * q_out_stride_token
|
||||
+ heads[None, :, None] * q_out_stride_head
|
||||
+ dims[None, None, :],
|
||||
y,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
if pid < num_k_work:
|
||||
# One work item owns one completed compression group. Work item zero
|
||||
# additionally commits the request's current raw-K suffix below.
|
||||
work_metadata = tl.load(k_work_metadata_ptr + pid * 2 + tl.arange(0, 2))
|
||||
request, work_in_request = tl.split(work_metadata)
|
||||
if request < 0:
|
||||
return
|
||||
|
||||
query_start = tl.load(query_start_loc_ptr + request)
|
||||
query_end = tl.load(query_start_loc_ptr + request + 1)
|
||||
query_len = query_end - query_start
|
||||
chunk_end = tl.load(logical_positions_ptr + query_end - 1)
|
||||
chunk_start = chunk_end - query_len + 1
|
||||
num_groups = (chunk_end + 1) // COMPRESS_RATIO - chunk_start // COMPRESS_RATIO
|
||||
dims = tl.arange(0, D)
|
||||
|
||||
if work_in_request < num_groups:
|
||||
first_boundary = (
|
||||
(chunk_start + COMPRESS_RATIO) // COMPRESS_RATIO
|
||||
) * COMPRESS_RATIO - 1
|
||||
end_position = first_boundary + work_in_request * COMPRESS_RATIO
|
||||
boundary_token = query_start + end_position - chunk_start
|
||||
valid_token = (
|
||||
(boundary_token >= query_start)
|
||||
& (boundary_token < query_end)
|
||||
& (boundary_token < num_tokens)
|
||||
)
|
||||
compressed_slot = tl.load(
|
||||
compressed_slots_ptr + boundary_token,
|
||||
mask=valid_token,
|
||||
other=-1,
|
||||
)
|
||||
valid = (
|
||||
valid_token
|
||||
& (compressed_slot >= 0)
|
||||
& (compressed_slot < num_compressed_blocks * COMP_PAGE_SIZE)
|
||||
)
|
||||
state_block = tl.load(state_table_ptr + request * state_table_stride_req)
|
||||
state_block_valid = (state_block >= 0) & (state_block < num_state_blocks)
|
||||
safe_state_block = tl.maximum(state_block, 0).to(tl.int64)
|
||||
group_offsets = tl.arange(0, COMPRESS_RATIO)
|
||||
source_positions = end_position - (COMPRESS_RATIO - 1) + group_offsets
|
||||
source_in_chunk = source_positions >= chunk_start
|
||||
source_tokens = query_start + source_positions - chunk_start
|
||||
source_tokens_valid = (
|
||||
(source_tokens >= query_start)
|
||||
& (source_tokens < query_end)
|
||||
& (source_tokens < num_tokens)
|
||||
)
|
||||
current_base = (
|
||||
k_ptr + tl.maximum(source_tokens, 0)[:, None] * k_stride_token
|
||||
)
|
||||
cached_base = (
|
||||
state_cache_ptr
|
||||
+ safe_state_block * state_cache_stride_block
|
||||
+ (source_positions % STATE_SIZE)[:, None] * state_cache_stride_token
|
||||
)
|
||||
# Only the first completed group can cross the chunk boundary. Select
|
||||
# historical rows from the ring without issuing two masked loads.
|
||||
source_base = tl.where(source_in_chunk[:, None], current_base, cached_base)
|
||||
# Pointer selection obscures alignment from Triton's analysis.
|
||||
source_base = tl.multiple_of(source_base, (8, 8))
|
||||
source_valid = tl.where(
|
||||
source_in_chunk, source_tokens_valid, state_block_valid
|
||||
)
|
||||
source = tl.load(
|
||||
source_base + dims[None, :],
|
||||
mask=valid & source_valid[:, None],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
# Match the unfused path's BF16 pooled tensor before RMSNorm.
|
||||
pooled = (
|
||||
(tl.sum(source, axis=0) / COMPRESS_RATIO).to(tl.bfloat16).to(tl.float32)
|
||||
)
|
||||
|
||||
first_position = end_position - (COMPRESS_RATIO - 1)
|
||||
if CACHE_HAS_ROPE_POS:
|
||||
# RoPE uses the first token in the pooled group. Its exact MRoPE
|
||||
# coordinates may live in this chunk or the raw-state ring.
|
||||
first_in_chunk = first_position >= chunk_start
|
||||
first_token = query_start + first_position - chunk_start
|
||||
first_token_valid = (
|
||||
(first_token >= query_start)
|
||||
& (first_token < query_end)
|
||||
& (first_token < num_tokens)
|
||||
)
|
||||
safe_first_token = tl.maximum(first_token, 0)
|
||||
load_current_position = first_in_chunk & first_token_valid
|
||||
first_pos_t = tl.load(
|
||||
pos_ptr + safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
if IS_2D_POSITIONS:
|
||||
first_pos_h = tl.load(
|
||||
pos_ptr + pos_stride_axis + safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
first_pos_w = tl.load(
|
||||
pos_ptr
|
||||
+ 2 * pos_stride_axis
|
||||
+ safe_first_token * pos_stride_token,
|
||||
mask=load_current_position,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
first_pos_h = first_pos_t
|
||||
first_pos_w = first_pos_t
|
||||
tail = (
|
||||
state_cache_ptr
|
||||
+ safe_state_block * state_cache_stride_block
|
||||
+ (first_position % STATE_SIZE) * state_cache_stride_token
|
||||
+ D
|
||||
).to(tl.pointer_type(tl.int64))
|
||||
load_cached_position = ~first_in_chunk & state_block_valid
|
||||
cached_pos_t = tl.load(tail, mask=load_cached_position, other=0)
|
||||
cached_pos_h = tl.load(tail + 1, mask=load_cached_position, other=0)
|
||||
cached_pos_w = tl.load(tail + 2, mask=load_cached_position, other=0)
|
||||
pos_t = tl.where(first_in_chunk, first_pos_t.to(tl.int64), cached_pos_t)
|
||||
pos_h = tl.where(first_in_chunk, first_pos_h.to(tl.int64), cached_pos_h)
|
||||
pos_w = tl.where(first_in_chunk, first_pos_w.to(tl.int64), cached_pos_w)
|
||||
else:
|
||||
pos_t = first_position
|
||||
pos_h = first_position
|
||||
pos_w = first_position
|
||||
y = _norm_rope(
|
||||
tl.reshape(pooled, (1, 1, D)),
|
||||
pos_t + tl.arange(0, 1),
|
||||
pos_h + tl.arange(0, 1),
|
||||
pos_w + tl.arange(0, 1),
|
||||
cos_sin_ptr,
|
||||
D // 2,
|
||||
k_norm_weight_ptr,
|
||||
eps,
|
||||
IS_K_MROPE,
|
||||
MROPE_H,
|
||||
MROPE_W,
|
||||
)
|
||||
compressed_block = (compressed_slot // COMP_PAGE_SIZE).to(tl.int64)
|
||||
compressed_row = compressed_slot % COMP_PAGE_SIZE
|
||||
tl.store(
|
||||
compressed_cache_ptr
|
||||
+ compressed_block * compressed_cache_stride_block
|
||||
+ compressed_row * compressed_cache_stride_token
|
||||
+ dims,
|
||||
tl.reshape(y, (D,)),
|
||||
mask=valid,
|
||||
)
|
||||
|
||||
if work_in_request == 0:
|
||||
# This CTA may have just read historical rows from the circular buffer.
|
||||
# Keep every lane past those loads before overwriting the same ring.
|
||||
tl.debug_barrier()
|
||||
# One CTA per request commits only the suffix retained by the ring.
|
||||
num_state_rows = tl.minimum(query_len, STATE_SIZE)
|
||||
for state_offset in tl.range(0, num_state_rows):
|
||||
token = query_end - num_state_rows + state_offset
|
||||
valid_token = (
|
||||
(token >= query_start) & (token < query_end) & (token < num_tokens)
|
||||
)
|
||||
slot = tl.load(state_slots_ptr + token, mask=valid_token, other=-1)
|
||||
valid_slot = (
|
||||
valid_token & (slot >= 0) & (slot < num_state_blocks * STATE_SIZE)
|
||||
)
|
||||
safe_slot = tl.maximum(slot, 0)
|
||||
state_row = (
|
||||
state_cache_ptr
|
||||
+ (safe_slot // STATE_SIZE).to(tl.int64) * state_cache_stride_block
|
||||
+ (safe_slot % STATE_SIZE) * state_cache_stride_token
|
||||
)
|
||||
k = tl.load(
|
||||
k_ptr + tl.maximum(token, 0) * k_stride_token + dims,
|
||||
mask=valid_slot,
|
||||
other=0.0,
|
||||
)
|
||||
tl.store(state_row + dims, k, mask=valid_slot)
|
||||
if CACHE_HAS_ROPE_POS:
|
||||
pos_t = tl.load(
|
||||
pos_ptr + tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
if IS_2D_POSITIONS:
|
||||
pos_h = tl.load(
|
||||
pos_ptr
|
||||
+ pos_stride_axis
|
||||
+ tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
pos_w = tl.load(
|
||||
pos_ptr
|
||||
+ 2 * pos_stride_axis
|
||||
+ tl.maximum(token, 0) * pos_stride_token,
|
||||
mask=valid_slot,
|
||||
other=0,
|
||||
)
|
||||
else:
|
||||
pos_h = pos_t
|
||||
pos_w = pos_t
|
||||
tail = (state_row + D).to(tl.pointer_type(tl.int64))
|
||||
tl.store(tail, pos_t.to(tl.int64), mask=valid_slot)
|
||||
tl.store(tail + 1, pos_h.to(tl.int64), mask=valid_slot)
|
||||
tl.store(tail + 2, pos_w.to(tl.int64), mask=valid_slot)
|
||||
|
||||
|
||||
def qsa_pre_indexer(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
q_norm_weight: torch.Tensor,
|
||||
k_norm_weight: torch.Tensor,
|
||||
eps: float,
|
||||
q_out: torch.Tensor,
|
||||
state_cache: torch.Tensor,
|
||||
state_slots: torch.Tensor,
|
||||
state_block_table: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
logical_positions: torch.Tensor,
|
||||
compressed_cache: torch.Tensor,
|
||||
compressed_slots: torch.Tensor,
|
||||
k_work_metadata: torch.Tensor,
|
||||
*,
|
||||
compress_ratio: int,
|
||||
mrope_section: tuple[int, int, int] | None,
|
||||
rope_pos_offset: int | None,
|
||||
) -> None:
|
||||
"""Normalize Q, compress K, then update the circular raw state."""
|
||||
num_tokens = q.shape[0]
|
||||
if num_tokens == 0:
|
||||
return
|
||||
num_q_heads, head_dim = q_out.shape[1:]
|
||||
assert cos_sin_cache.shape[-1] * 2 == head_dim
|
||||
assert q.shape == (num_tokens, num_q_heads * head_dim)
|
||||
assert k.shape == (num_tokens, head_dim)
|
||||
assert q.stride(-1) == 1
|
||||
assert k.stride(-1) == 1
|
||||
assert q_out.stride(-1) == 1
|
||||
assert cos_sin_cache.is_contiguous()
|
||||
assert state_cache.stride(-1) == 1
|
||||
assert compressed_cache.stride(-1) == 1
|
||||
assert k_work_metadata.ndim == 2 and k_work_metadata.shape[1] == 2
|
||||
is_2d_positions = positions.ndim == 2
|
||||
is_k_mrope = bool(mrope_section)
|
||||
cache_has_rope_pos = rope_pos_offset is not None
|
||||
assert rope_pos_offset is None or rope_pos_offset == head_dim
|
||||
if is_2d_positions:
|
||||
assert positions.shape == (3, num_tokens)
|
||||
assert is_k_mrope
|
||||
pos_stride_axis, pos_stride_token = positions.stride()
|
||||
else:
|
||||
assert positions.shape == (num_tokens,)
|
||||
pos_stride_axis, pos_stride_token = 0, positions.stride(0)
|
||||
section = mrope_section if mrope_section is not None else (0, 0, 0)
|
||||
assert len(section) == 3
|
||||
|
||||
if num_tokens <= 4096:
|
||||
TILE_T_Q, TILE_H_Q = 2, 2
|
||||
else:
|
||||
TILE_T_Q, TILE_H_Q = 2, 4
|
||||
num_k_work = k_work_metadata.shape[0]
|
||||
num_q_work = triton.cdiv(num_tokens, TILE_T_Q) * triton.cdiv(num_q_heads, TILE_H_Q)
|
||||
_qsa_pre_indexer_kernel[(num_k_work + num_q_work,)](
|
||||
q,
|
||||
q.stride(0),
|
||||
k,
|
||||
k.stride(0),
|
||||
positions,
|
||||
pos_stride_axis,
|
||||
pos_stride_token,
|
||||
cos_sin_cache,
|
||||
q_norm_weight,
|
||||
k_norm_weight,
|
||||
eps,
|
||||
q_out,
|
||||
q_out.stride(0),
|
||||
q_out.stride(1),
|
||||
state_cache,
|
||||
state_cache.stride(0),
|
||||
state_cache.stride(1),
|
||||
state_slots,
|
||||
state_block_table,
|
||||
state_block_table.stride(0),
|
||||
query_start_loc,
|
||||
logical_positions,
|
||||
compressed_slots,
|
||||
k_work_metadata,
|
||||
compressed_cache,
|
||||
compressed_cache.stride(0),
|
||||
compressed_cache.stride(1),
|
||||
num_tokens,
|
||||
state_cache.shape[0],
|
||||
compressed_cache.shape[0],
|
||||
num_k_work,
|
||||
HQ=num_q_heads,
|
||||
D=head_dim,
|
||||
TILE_T_Q=TILE_T_Q,
|
||||
TILE_H_Q=TILE_H_Q,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
STATE_SIZE=state_cache.shape[1],
|
||||
COMP_PAGE_SIZE=compressed_cache.shape[1],
|
||||
IS_2D_POSITIONS=is_2d_positions,
|
||||
IS_K_MROPE=is_k_mrope,
|
||||
CACHE_HAS_ROPE_POS=cache_has_rope_pos,
|
||||
MROPE_H=section[1],
|
||||
MROPE_W=section[2],
|
||||
num_warps=1,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["qsa_pre_indexer"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,487 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NVIDIA QSA owner with Triton kernels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.layers.attention.attention import (
|
||||
set_default_quant_scales,
|
||||
)
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
|
||||
from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding, get_rope
|
||||
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
canonicalize_singleton_dim_strides,
|
||||
direct_register_custom_op,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
AttentionType,
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.fa_utils import is_flash_attn_varlen_func_available
|
||||
from vllm.v1.attention.backends.flash_attn import (
|
||||
FlashAttentionBackend,
|
||||
FlashAttentionImpl,
|
||||
FlashAttentionMetadata,
|
||||
FlashAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheSpec,
|
||||
get_kv_quant_mode,
|
||||
)
|
||||
|
||||
from ..common.qsa_cache import QSAForwardMetadata
|
||||
from . import model
|
||||
from .indexer_qsa import QSAIndexer
|
||||
|
||||
|
||||
class Qwen4ExpQSAMetadataBuilder(FlashAttentionMetadataBuilder):
|
||||
"""Flash metadata supporting uniform decode and target-verify graphs."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
|
||||
"""FullAttentionSpec backend used by the merged QSA owner."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "QWEN4_EXP_QSA_TRITON"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
|
||||
# QSA consumes manager pages directly and does not use FA4 paged attention.
|
||||
return [MultipleOf(16)]
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type[Qwen4ExpQSAFlashAttentionImpl]:
|
||||
return Qwen4ExpQSAFlashAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type[Qwen4ExpQSAMetadataBuilder]:
|
||||
return Qwen4ExpQSAMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def is_sparse(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_kv_connector(cls) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
"""Run paged sparse GQA with the QSA Triton kernel."""
|
||||
|
||||
supports_dcp: bool = False
|
||||
supports_pcp: bool = False
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if not is_flash_attn_varlen_func_available():
|
||||
raise NotImplementedError("Qwen4Exp QSA requires FlashAttention")
|
||||
if self.dcp_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support decode context parallelism"
|
||||
)
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
self.supports_quant_query_input = False
|
||||
|
||||
def forward_qsa(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
attn_metadata: FlashAttentionMetadata,
|
||||
output: torch.Tensor,
|
||||
token_to_req: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
output_block_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
del key, value
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError("QSA does not support fused output quantization")
|
||||
if self.alibi_slopes is not None or self.sinks is not None:
|
||||
raise NotImplementedError("QSA does not support ALiBi or attention sinks")
|
||||
if self.sliding_window != (-1, -1):
|
||||
raise NotImplementedError("QSA does not support sliding-window attention")
|
||||
|
||||
num_tokens = attn_metadata.num_actual_tokens
|
||||
output.zero_()
|
||||
if num_tokens == 0:
|
||||
return output
|
||||
|
||||
topk_buffer = getattr(layer, "topk_indices_buffer", None)
|
||||
if topk_buffer is None:
|
||||
raise RuntimeError("QSA owner did not provide its top-k buffer")
|
||||
logical_indices = topk_buffer[:num_tokens]
|
||||
token_to_req = token_to_req[:num_tokens]
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
|
||||
key_cache = canonicalize_singleton_dim_strides(key_cache)
|
||||
value_cache = canonicalize_singleton_dim_strides(value_cache)
|
||||
if key_cache.dtype != torch.bfloat16 or query.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 Q/K/V")
|
||||
|
||||
from .ops.qsa import qsa_sparse_paged_attention
|
||||
|
||||
qsa_sparse_paged_attention(
|
||||
query[:num_tokens],
|
||||
key_cache,
|
||||
value_cache,
|
||||
logical_indices,
|
||||
attn_metadata.block_table,
|
||||
token_to_req,
|
||||
output[:num_tokens],
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
"""Merged Qwen full-attention owner with a QSA index side branch."""
|
||||
|
||||
supports_dcp = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
config: Qwen4ExpTextConfig,
|
||||
layer_id: int,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
reduce_results: bool = True,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
nn.Module.__init__(self)
|
||||
cache_config = vllm_config.cache_config
|
||||
model_config = vllm_config.model_config
|
||||
if cache_config is None:
|
||||
raise ValueError("Qwen4Exp QSA requires a paged KV cache")
|
||||
if model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
if cache_config.cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if getattr(quant_config, "kv_cache_scheme", None) is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support KV quantization")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
if (
|
||||
parallel_config.prefill_context_parallel_size > 1
|
||||
or parallel_config.decode_context_parallel_size > 1
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support context parallelism"
|
||||
)
|
||||
if not getattr(config, "is_causal", True):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires causal decoder attention")
|
||||
|
||||
self.config = config
|
||||
self.hidden_size = int(config.hidden_size)
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.total_num_heads = int(config.num_attention_heads)
|
||||
if self.total_num_heads % tp_size:
|
||||
raise ValueError("QSA attention heads must be divisible by TP size")
|
||||
self.num_heads = self.total_num_heads // tp_size
|
||||
self.total_num_kv_heads = int(config.num_key_value_heads)
|
||||
if self.total_num_kv_heads >= tp_size:
|
||||
if self.total_num_kv_heads % tp_size:
|
||||
raise ValueError("QSA KV heads must be divisible by TP size")
|
||||
elif tp_size % self.total_num_kv_heads:
|
||||
raise ValueError("TP size must be divisible by replicated QSA KV heads")
|
||||
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
||||
self.head_dim = int(config.head_dim or self.hidden_size // self.num_heads)
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.dual_chunk_attention_config = getattr(
|
||||
config, "dual_chunk_attention_config", None
|
||||
)
|
||||
if self.dual_chunk_attention_config is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support dual-chunk RoPE")
|
||||
# Qwen4Exp full-attention checkpoints always pack a sigmoid output
|
||||
# gate next to Q, even when an inherited config default says otherwise.
|
||||
self.attn_output_gate = True
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
self.hidden_size,
|
||||
self.head_dim,
|
||||
self.total_num_heads * (1 + self.attn_output_gate),
|
||||
self.total_num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=model.without_modelopt_fp4(quant_config),
|
||||
prefix=f"{prefix}.qkv_proj",
|
||||
)
|
||||
self.o_proj = RowParallelLinear(
|
||||
self.total_num_heads * self.head_dim,
|
||||
self.hidden_size,
|
||||
bias=False,
|
||||
reduce_results=reduce_results,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o_proj",
|
||||
)
|
||||
self.rotary_emb = get_rope(
|
||||
head_size=self.head_dim,
|
||||
max_position=config.max_position_embeddings,
|
||||
rope_parameters=config.rope_parameters,
|
||||
)
|
||||
self.q_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = GemmaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
mm_config = model_config.multimodal_config
|
||||
text_only = mm_config is None or mm_config.language_model_only
|
||||
mrope_section = getattr(self.rotary_emb, "mrope_section", None)
|
||||
supports_mrope = bool(
|
||||
type(self.rotary_emb) is MRotaryEmbedding
|
||||
and mrope_section
|
||||
and len(mrope_section) == 3
|
||||
and sum(mrope_section) == self.rotary_emb.rotary_dim // 2
|
||||
and getattr(self.rotary_emb, "mrope_interleaved", False)
|
||||
)
|
||||
supports_dtype = getattr(self.rotary_emb, "dtype", None) in (
|
||||
torch.float16,
|
||||
torch.bfloat16,
|
||||
)
|
||||
self.use_fused_qk_norm_rope_gate = (
|
||||
self.attn_output_gate
|
||||
and getattr(self.rotary_emb, "is_neox_style", False)
|
||||
and current_platform.is_cuda()
|
||||
and supports_dtype
|
||||
and (text_only or supports_mrope)
|
||||
)
|
||||
|
||||
self.layer_name = f"{prefix}.attn"
|
||||
self.attn_type = AttentionType.DECODER
|
||||
self.kv_cache_dtype = cache_config.cache_dtype
|
||||
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
|
||||
self.kv_cache_dtype, model_config
|
||||
)
|
||||
if self.kv_cache_torch_dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 cache storage")
|
||||
self.kv_sharing_target_layer_name = None
|
||||
self.kv_cache = torch.tensor([])
|
||||
set_default_quant_scales(self, register_buffer=True)
|
||||
|
||||
self.attn_backend = Qwen4ExpQSAFlashAttentionBackend
|
||||
self.impl = Qwen4ExpQSAFlashAttentionImpl(
|
||||
self.num_heads,
|
||||
self.head_dim,
|
||||
self.scaling,
|
||||
self.num_kv_heads,
|
||||
None,
|
||||
None,
|
||||
self.kv_cache_dtype,
|
||||
None,
|
||||
AttentionType.DECODER,
|
||||
None,
|
||||
)
|
||||
self.indexer = QSAIndexer(
|
||||
vllm_config=vllm_config,
|
||||
config=config,
|
||||
layer_id=layer_id,
|
||||
rotary_emb=self.rotary_emb,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.indexer",
|
||||
)
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.register_buffer(
|
||||
"topk_indices_buffer",
|
||||
torch.empty(
|
||||
max_tokens,
|
||||
self.indexer.output_width,
|
||||
dtype=torch.int32,
|
||||
),
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
static_context = vllm_config.compilation_config.static_forward_context
|
||||
if self.layer_name in static_context:
|
||||
raise ValueError(f"Duplicate layer name: {self.layer_name}")
|
||||
static_context[self.layer_name] = self
|
||||
|
||||
def get_attn_backend(self) -> type[AttentionBackend]:
|
||||
return self.attn_backend
|
||||
|
||||
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
|
||||
return FullAttentionSpec(
|
||||
block_size=vllm_config.cache_config.block_size,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
head_size=self.head_dim,
|
||||
head_size_v=self.head_dim,
|
||||
dtype=self.kv_cache_torch_dtype,
|
||||
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
|
||||
)
|
||||
|
||||
def _run_qsa(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
metadata = get_forward_context().attn_metadata
|
||||
if isinstance(metadata, list):
|
||||
metadata = metadata[0]
|
||||
if not isinstance(metadata, dict):
|
||||
output.zero_()
|
||||
return
|
||||
main_metadata = cast(FlashAttentionMetadata, metadata[self.layer_name])
|
||||
if self.kv_cache.numel() == 0:
|
||||
raise RuntimeError("QSA main K/V cache is not bound")
|
||||
|
||||
num_tokens = main_metadata.num_actual_tokens
|
||||
side_metadata = cast(
|
||||
QSAForwardMetadata,
|
||||
metadata[self.indexer.raw_key_cache.prefix],
|
||||
)
|
||||
if side_metadata.num_actual_tokens != num_tokens:
|
||||
raise RuntimeError("QSA main and side metadata token counts disagree")
|
||||
selected = self.indexer(
|
||||
hidden_states,
|
||||
positions,
|
||||
self.topk_indices_buffer[:num_tokens],
|
||||
)
|
||||
if selected.shape != (
|
||||
num_tokens,
|
||||
self.indexer.output_width,
|
||||
):
|
||||
raise RuntimeError("QSA indexer returned an invalid selection shape")
|
||||
impl = cast(Qwen4ExpQSAFlashAttentionImpl, self.impl)
|
||||
impl.do_kv_cache_update(
|
||||
self,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata.slot_mapping,
|
||||
)
|
||||
impl.forward_qsa(
|
||||
self,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
self.kv_cache,
|
||||
main_metadata,
|
||||
output,
|
||||
token_to_req=side_metadata.token_to_req,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
qkv, _ = self.qkv_proj(hidden_states)
|
||||
q, k, v, gate = self._project_qkv_gate(qkv, positions)
|
||||
num_tokens = hidden_states.shape[0]
|
||||
query = q.view(num_tokens, self.num_heads, self.head_dim)
|
||||
key = k.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
value = v.view(num_tokens, self.num_kv_heads, self.head_dim)
|
||||
attn_output = torch.empty_like(query)
|
||||
encoded_layer_name = _encode_layer_name(self.layer_name)
|
||||
if current_platform.opaque_attention_op():
|
||||
torch.ops.vllm.qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
else:
|
||||
qwen4_exp_qsa_with_output(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_output,
|
||||
encoded_layer_name,
|
||||
)
|
||||
flat_output = attn_output.view(num_tokens, -1)
|
||||
if gate is not None:
|
||||
flat_output = flat_output * torch.sigmoid(gate)
|
||||
output, _ = self.o_proj(flat_output)
|
||||
return output
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Run the complete QSA state/update/attend transaction."""
|
||||
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
if not isinstance(layer, Qwen4ExpQSAAttention):
|
||||
raise TypeError(f"{layer_name} is not a Qwen4Exp QSA owner")
|
||||
layer._run_qsa(
|
||||
hidden_states,
|
||||
positions,
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
output,
|
||||
)
|
||||
|
||||
|
||||
def qwen4_exp_qsa_with_output_fake(
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
del hidden_states, positions, query, key, value, output, layer_name
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="qwen4_exp_qsa_with_output",
|
||||
op_func=qwen4_exp_qsa_with_output,
|
||||
mutates_args=["output"],
|
||||
fake_impl=qwen4_exp_qsa_with_output_fake,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"QSAIndexer",
|
||||
"Qwen4ExpQSAAttention",
|
||||
"Qwen4ExpQSAFlashAttentionBackend",
|
||||
"Qwen4ExpQSAFlashAttentionImpl",
|
||||
"qwen4_exp_qsa_with_output",
|
||||
]
|
||||
@@ -855,11 +855,18 @@ class Platform:
|
||||
model_config.architecture,
|
||||
model_config=model_config,
|
||||
)
|
||||
mamba_page_size = MambaSpec(
|
||||
shapes=model_cls.get_mamba_state_shape_from_config(vllm_config),
|
||||
dtypes=model_cls.get_mamba_state_dtype_from_config(vllm_config),
|
||||
block_size=-1,
|
||||
).page_size_bytes
|
||||
# Qwen4Exp has multiple Mamba state layouts with different sizes.
|
||||
if hasattr(model_cls, "get_mamba_specs_from_config"):
|
||||
mamba_page_size = max(
|
||||
spec.page_size_bytes
|
||||
for spec in model_cls.get_mamba_specs_from_config(vllm_config)
|
||||
)
|
||||
else:
|
||||
mamba_page_size = MambaSpec(
|
||||
shapes=model_cls.get_mamba_state_shape_from_config(vllm_config),
|
||||
dtypes=model_cls.get_mamba_state_dtype_from_config(vllm_config),
|
||||
block_size=-1,
|
||||
).page_size_bytes
|
||||
|
||||
if mamba_page_size == 0:
|
||||
return
|
||||
|
||||
@@ -125,6 +125,8 @@ _CONFIG_REGISTRY: dict[str, type[PretrainedConfig]] = LazyConfigDict(
|
||||
qianfan_ocr="QianfanOCRConfig",
|
||||
qwen3_asr="Qwen3ASRConfig",
|
||||
qwen3_next="Qwen3NextConfig",
|
||||
qwen4_exp="Qwen4ExpConfig",
|
||||
qwen4_exp_text="Qwen4ExpTextConfig",
|
||||
qwen3_5="Qwen3_5Config",
|
||||
qwen3_5_text="Qwen3_5TextConfig",
|
||||
qwen3_5_moe="Qwen3_5MoeConfig",
|
||||
|
||||
@@ -91,6 +91,9 @@ _CLASS_TO_MODULE: dict[str, str] = {
|
||||
"QianfanOCRVisionConfig": "vllm.transformers_utils.configs.qianfan_ocr",
|
||||
"Qwen3ASRConfig": "vllm.transformers_utils.configs.qwen3_asr",
|
||||
"Qwen3NextConfig": "vllm.transformers_utils.configs.qwen3_next",
|
||||
"Qwen4ExpConfig": "vllm.transformers_utils.configs.qwen4_exp",
|
||||
"Qwen4ExpTextConfig": "vllm.transformers_utils.configs.qwen4_exp",
|
||||
"Qwen4ExpVisionConfig": "vllm.transformers_utils.configs.qwen4_exp",
|
||||
"Qwen3_5Config": "vllm.transformers_utils.configs.qwen3_5",
|
||||
"Qwen3_5TextConfig": "vllm.transformers_utils.configs.qwen3_5",
|
||||
"Qwen3_5MoeConfig": "vllm.transformers_utils.configs.qwen3_5_moe",
|
||||
@@ -176,6 +179,9 @@ __all__ = [
|
||||
"QianfanOCRVisionConfig",
|
||||
"Qwen3ASRConfig",
|
||||
"Qwen3NextConfig",
|
||||
"Qwen4ExpConfig",
|
||||
"Qwen4ExpTextConfig",
|
||||
"Qwen4ExpVisionConfig",
|
||||
"Qwen3_5Config",
|
||||
"Qwen3_5TextConfig",
|
||||
"Qwen3_5MoeConfig",
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Exports for the package-owned Qwen4Exp configs."""
|
||||
|
||||
from vllm.models.qwen4_exp.config import (
|
||||
Qwen4ExpConfig,
|
||||
Qwen4ExpTextConfig,
|
||||
Qwen4ExpVisionConfig,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Qwen4ExpConfig",
|
||||
"Qwen4ExpTextConfig",
|
||||
"Qwen4ExpVisionConfig",
|
||||
]
|
||||
@@ -642,6 +642,15 @@ class Qwen3NextMTPModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
return getattr(self.hf_text_config, "num_nextn_predict_layers", 0)
|
||||
|
||||
|
||||
class Qwen4ExpMTPModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
def get_num_hidden_layers(self) -> int:
|
||||
return getattr(
|
||||
self.hf_text_config,
|
||||
"mtp_num_hidden_layers",
|
||||
getattr(self.hf_text_config, "num_nextn_predict_layers", 0),
|
||||
)
|
||||
|
||||
|
||||
class BailingHybridMTPModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
def get_num_hidden_layers(self) -> int:
|
||||
return getattr(self.hf_text_config, "num_nextn_predict_layers", 0)
|
||||
@@ -791,6 +800,7 @@ MODEL_ARCH_CONFIG_CONVERTORS = {
|
||||
"pangu_ultra_moe_mtp": PanguUltraMoeMTPModelArchConfigConvertor,
|
||||
"qwen3_5_mtp": Qwen3_5MTPModelArchConfigConvertor,
|
||||
"qwen3_next_mtp": Qwen3NextMTPModelArchConfigConvertor,
|
||||
"qwen4_exp_mtp": Qwen4ExpMTPModelArchConfigConvertor,
|
||||
"RefinedWeb": FalconModelArchConfigConvertor,
|
||||
"RefinedWebModel": FalconModelArchConfigConvertor,
|
||||
"step3p5_mtp": Step3p5MTPModelArchConfigConvertor,
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
from vllm.v1.attention.backend import AttentionBackend
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
AttentionCGSupport,
|
||||
CommonAttentionMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.mamba_attn import (
|
||||
BaseMambaAttentionMetadata,
|
||||
BaseMambaAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import (
|
||||
NULL_BLOCK_ID,
|
||||
compute_causal_conv1d_metadata,
|
||||
mamba_get_block_table_tensor,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
|
||||
class ShortConvAttentionBackend(AttentionBackend):
|
||||
@@ -32,3 +47,513 @@ class ShortConvAttentionMetadataBuilder(
|
||||
BaseMambaAttentionMetadataBuilder[ShortConvAttentionMetadata]
|
||||
):
|
||||
metadata_cls = ShortConvAttentionMetadata
|
||||
|
||||
|
||||
@dataclass
|
||||
class PleShortConvAttentionMetadata(ShortConvAttentionMetadata):
|
||||
# Number of speculative-decode (multi-query / MTP) requests and the total
|
||||
# number of tokens they contribute. These are 0 when spec-decode is off.
|
||||
num_spec_decodes: int = 0
|
||||
num_spec_decode_tokens: int = 0
|
||||
num_actual_tokens: int = 0
|
||||
|
||||
# Max query length among spec-decode requests (== num_speculative_tokens + 1).
|
||||
# Used as ``max_query_len`` for the varlen spec causal_conv1d_update.
|
||||
spec_query_len: int = 1
|
||||
|
||||
# Max query length among the non-spec *prefill* requests, precomputed
|
||||
# CPU-side in the builder. The dilated PLE short-conv uses it to size its
|
||||
# packing buffer without a device->host sync (``lengths.max().item()``).
|
||||
# 0 when there are no prefill requests.
|
||||
max_prefill_query_len: int = 0
|
||||
query_start_loc: torch.Tensor | None = None
|
||||
|
||||
# ``state_indices_tensor`` keeps the historical (non-spec) layout used by
|
||||
# all existing short-conv consumers: the conv-state slot for each regular
|
||||
# decode followed by each prefill request. When spec-decode is active this
|
||||
# only covers the non-spec requests.
|
||||
state_indices_tensor: torch.Tensor | None = None
|
||||
has_initial_states_d: torch.Tensor | None = None
|
||||
|
||||
# ``non_spec_query_start_loc`` is the varlen cumulative token offset over
|
||||
# the non-spec requests only (decodes then prefills). It equals
|
||||
# ``query_start_loc`` when there are no spec-decode requests.
|
||||
non_spec_query_start_loc: torch.Tensor | None = None
|
||||
|
||||
# Speculative-decode (MTP) conv metadata. Only column 0 of the block table
|
||||
# is needed for the convolution state, so these tensors are 1-D over the
|
||||
# spec-decode requests.
|
||||
spec_query_start_loc: torch.Tensor | None = None # [num_spec_decodes + 1]
|
||||
spec_state_indices_tensor: torch.Tensor | None = None # [num_spec_decodes]
|
||||
spec_sequence_masks: torch.Tensor | None = None # [batch]
|
||||
spec_token_indx: torch.Tensor | None = None
|
||||
non_spec_token_indx: torch.Tensor | None = None
|
||||
num_decode_draft_tokens_cpu: torch.Tensor | None = None
|
||||
|
||||
|
||||
class PleShortConvAttentionBackend(ShortConvAttentionBackend):
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "PLE_SHORT_CONV_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["PleShortConvAttentionMetadataBuilder"]:
|
||||
return PleShortConvAttentionMetadataBuilder
|
||||
|
||||
|
||||
class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
metadata_cls = PleShortConvAttentionMetadata
|
||||
# Spec-decode requires a uniform (multi-token) decode batch for full
|
||||
# CUDA graph capture, matching the GDN backend.
|
||||
_cudagraph_support = AttentionCGSupport.UNIFORM_BATCH
|
||||
reorder_batch_threshold: int = 1
|
||||
supports_update_block_table = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: MambaSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
self.num_spec = self.num_spec_tokens
|
||||
self.use_full_cuda_graph = (
|
||||
self.compilation_config.cudagraph_mode.has_full_cudagraphs()
|
||||
)
|
||||
|
||||
max_num_seqs = vllm_config.scheduler_config.max_num_seqs
|
||||
max_capture_size = self.compilation_config.max_cudagraph_capture_size
|
||||
self.decode_cudagraph_max_bs = max_num_seqs
|
||||
self.decode_cudagraph_max_tokens = max_num_seqs * (self.num_spec + 1)
|
||||
if max_capture_size is not None:
|
||||
self.decode_cudagraph_max_bs = min(
|
||||
self.decode_cudagraph_max_bs, max_capture_size
|
||||
)
|
||||
self.decode_cudagraph_max_tokens = min(
|
||||
self.decode_cudagraph_max_tokens, max_capture_size
|
||||
)
|
||||
|
||||
# Persistent buffers reused during full CUDA graph capture and replay.
|
||||
self.spec_state_indices_tensor = torch.empty(
|
||||
(self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device
|
||||
)
|
||||
self.spec_sequence_masks = torch.empty(
|
||||
(self.decode_cudagraph_max_bs,), dtype=torch.bool, device=device
|
||||
)
|
||||
self.spec_token_indx = torch.empty(
|
||||
(self.decode_cudagraph_max_tokens,), dtype=torch.int32, device=device
|
||||
)
|
||||
self.non_spec_token_indx = torch.empty(
|
||||
(self.decode_cudagraph_max_tokens,), dtype=torch.int32, device=device
|
||||
)
|
||||
self.spec_query_start_loc = torch.empty(
|
||||
(self.decode_cudagraph_max_bs + 1,), dtype=torch.int32, device=device
|
||||
)
|
||||
self.num_accepted_tokens = torch.empty(
|
||||
(self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device
|
||||
)
|
||||
self.has_initial_states_d = torch.empty(
|
||||
(self.decode_cudagraph_max_bs,), dtype=torch.bool, device=device
|
||||
)
|
||||
|
||||
def _build_non_spec_metadata(
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool,
|
||||
num_decode_draft_tokens_cpu: torch.Tensor | None,
|
||||
**kwargs: Any,
|
||||
) -> PleShortConvAttentionMetadata:
|
||||
metadata = super().build(
|
||||
common_prefix_len,
|
||||
common_attn_metadata,
|
||||
fast_build,
|
||||
num_accepted_tokens=None,
|
||||
**kwargs,
|
||||
)
|
||||
assert isinstance(metadata, PleShortConvAttentionMetadata)
|
||||
|
||||
state_indices_d = metadata.state_indices_tensor_d
|
||||
if state_indices_d is not None and state_indices_d.dim() > 1:
|
||||
state_indices_d = state_indices_d[:, 0]
|
||||
state_indices_p = metadata.state_indices_tensor_p
|
||||
if metadata.num_prefills == 0:
|
||||
assert state_indices_d is not None
|
||||
# BaseMambaAttentionMetadataBuilder pads decode state indices into
|
||||
# a persistent tensor for full CUDA graphs. Keep those rows so the
|
||||
# PLE decode receives one cache slot per graph-padded token.
|
||||
state_indices_tensor = state_indices_d
|
||||
elif metadata.num_decodes == 0:
|
||||
assert state_indices_p is not None
|
||||
state_indices_tensor = state_indices_p[: metadata.num_prefills]
|
||||
else:
|
||||
assert state_indices_d is not None
|
||||
assert state_indices_p is not None
|
||||
state_indices_tensor = torch.cat(
|
||||
(state_indices_d, state_indices_p[: metadata.num_prefills])
|
||||
)
|
||||
|
||||
has_initial_states_d = None
|
||||
if metadata.num_decodes > 0:
|
||||
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
|
||||
has_initial_states_d = num_computed_tokens[: metadata.num_decodes] > 0
|
||||
if (
|
||||
self.use_full_cuda_graph
|
||||
and metadata.num_prefills == 0
|
||||
and metadata.num_decodes <= self.decode_cudagraph_max_bs
|
||||
):
|
||||
assert state_indices_d is not None
|
||||
# Prepare tensors for CUDA graph replay. Padded rows have no
|
||||
# initial state and use NULL_BLOCK_ID in state_indices_d.
|
||||
num_decode_rows = state_indices_d.numel()
|
||||
self.has_initial_states_d[: metadata.num_decodes].copy_(
|
||||
has_initial_states_d, non_blocking=True
|
||||
)
|
||||
self.has_initial_states_d[metadata.num_decodes : num_decode_rows].fill_(
|
||||
False
|
||||
)
|
||||
has_initial_states_d = self.has_initial_states_d[:num_decode_rows]
|
||||
|
||||
max_prefill_query_len = 0
|
||||
if metadata.num_prefills > 0:
|
||||
query_lens_cpu = torch.diff(common_attn_metadata.query_start_loc_cpu)
|
||||
max_prefill_query_len = int(
|
||||
query_lens_cpu[
|
||||
metadata.num_decodes : (
|
||||
metadata.num_decodes + metadata.num_prefills
|
||||
)
|
||||
]
|
||||
.max()
|
||||
.item()
|
||||
)
|
||||
|
||||
return replace(
|
||||
metadata,
|
||||
num_actual_tokens=common_attn_metadata.num_actual_tokens,
|
||||
spec_query_len=self.num_spec + 1,
|
||||
max_prefill_query_len=max_prefill_query_len,
|
||||
query_start_loc=common_attn_metadata.query_start_loc,
|
||||
state_indices_tensor=state_indices_tensor,
|
||||
has_initial_states_d=has_initial_states_d,
|
||||
non_spec_query_start_loc=common_attn_metadata.query_start_loc,
|
||||
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
|
||||
)
|
||||
|
||||
def build( # type: ignore[override]
|
||||
self,
|
||||
common_prefix_len: int,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
*,
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> PleShortConvAttentionMetadata:
|
||||
m = common_attn_metadata
|
||||
spec_sequence_masks_cpu: torch.Tensor | None = None
|
||||
# Detect speculative-decode requests. We use -1 to mark prefill and
|
||||
# plain-decode requests, so any value >= 0 is a (multi-query)
|
||||
# spec-decode request.
|
||||
if self.use_spec_decode and num_decode_draft_tokens_cpu is not None:
|
||||
candidate_mask = num_decode_draft_tokens_cpu[: m.num_reqs] >= 0
|
||||
if bool(candidate_mask.any().item()):
|
||||
spec_sequence_masks_cpu = candidate_mask
|
||||
|
||||
if spec_sequence_masks_cpu is None:
|
||||
return self._build_non_spec_metadata(
|
||||
common_prefix_len,
|
||||
common_attn_metadata,
|
||||
fast_build,
|
||||
num_decode_draft_tokens_cpu,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
del common_prefix_len, fast_build, kwargs
|
||||
query_start_loc = m.query_start_loc
|
||||
query_start_loc_cpu = m.query_start_loc_cpu
|
||||
query_lens_cpu = torch.diff(query_start_loc_cpu)
|
||||
block_table_tensor = mamba_get_block_table_tensor(
|
||||
m.block_table_tensor,
|
||||
m.seq_lens,
|
||||
self.kv_cache_spec,
|
||||
self.vllm_config.cache_config.mamba_cache_mode,
|
||||
)
|
||||
|
||||
if query_start_loc.device.type == "cpu":
|
||||
spec_sequence_masks = spec_sequence_masks_cpu
|
||||
else:
|
||||
spec_sequence_masks = async_tensor_h2d(
|
||||
spec_sequence_masks_cpu, device=query_start_loc.device
|
||||
)
|
||||
|
||||
# For causal_conv1d (non-spec prefill Triton kernel metadata).
|
||||
nums_dict = None
|
||||
batch_ptr = None
|
||||
token_chunk_offset_ptr = None
|
||||
has_initial_states_p = None
|
||||
has_initial_states_d = None
|
||||
num_computed_tokens_p = None
|
||||
# Original request indices of the non-spec requests, ordered
|
||||
# [decodes, prefills]. Used to gather per-request data consistently.
|
||||
non_spec_req_idx_cpu: torch.Tensor | None = None
|
||||
|
||||
query_lens = torch.diff(query_start_loc)
|
||||
# Per-request classification by mask, NOT by position. With
|
||||
# spec-decode, the front decode group can contain both spec-decode
|
||||
# requests and plain non-spec single-token decodes. Spec requests are
|
||||
# therefore not guaranteed to occupy the first num_spec_decodes slots.
|
||||
non_spec_mask_cpu = ~spec_sequence_masks_cpu
|
||||
decode_mask_cpu = non_spec_mask_cpu & (query_lens_cpu == 1)
|
||||
prefill_mask_cpu = non_spec_mask_cpu & (query_lens_cpu > 1)
|
||||
|
||||
num_spec_decodes = int(spec_sequence_masks_cpu.sum().item())
|
||||
num_decodes = int(decode_mask_cpu.sum().item())
|
||||
num_prefills = int(prefill_mask_cpu.sum().item())
|
||||
num_decode_tokens = num_decodes
|
||||
num_prefill_tokens = int(query_lens_cpu[prefill_mask_cpu].sum().item())
|
||||
num_spec_decode_tokens = int(
|
||||
query_lens_cpu[spec_sequence_masks_cpu].sum().item()
|
||||
)
|
||||
# Max prefill query length, CPU-side (no device-to-host sync) for the
|
||||
# PLE dilated short-conv packing buffer.
|
||||
max_prefill_query_len = (
|
||||
int(query_lens_cpu[prefill_mask_cpu].max().item())
|
||||
if num_prefills > 0
|
||||
else 0
|
||||
)
|
||||
|
||||
# Original request indices grouped as
|
||||
# [spec | non-spec decode | non-spec prefill]; each group keeps the
|
||||
# original (already reordered) relative order via a stable nonzero.
|
||||
spec_req_idx_cpu = spec_sequence_masks_cpu.nonzero(as_tuple=True)[0]
|
||||
decode_req_idx_cpu = decode_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
prefill_req_idx_cpu = prefill_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
non_spec_req_idx_cpu = torch.cat((decode_req_idx_cpu, prefill_req_idx_cpu))
|
||||
spec_req_idx = spec_req_idx_cpu.to(query_start_loc.device)
|
||||
non_spec_req_idx = non_spec_req_idx_cpu.to(query_start_loc.device)
|
||||
|
||||
if num_decodes == 0 and num_prefills == 0:
|
||||
# Pure speculative-decode batch: all real tokens are spec tokens.
|
||||
spec_token_indx = torch.arange(
|
||||
num_spec_decode_tokens,
|
||||
dtype=torch.int32,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
non_spec_token_indx = torch.empty(
|
||||
0, dtype=torch.int32, device=query_start_loc.device
|
||||
)
|
||||
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
|
||||
non_spec_state_indices_tensor = None
|
||||
spec_query_start_loc = query_start_loc[: num_spec_decodes + 1]
|
||||
non_spec_query_start_loc = None
|
||||
non_spec_query_start_loc_cpu = None
|
||||
else:
|
||||
# Mixed batch: build a per-token group key consistent with the
|
||||
# request grouping above (spec=0 | decode=1 | prefill=2) and a
|
||||
# stable sort, so tokens of each request stay contiguous and in
|
||||
# request order. This yields spec tokens first, then the non-spec
|
||||
# [decode, prefill] tokens.
|
||||
req_group = torch.full(
|
||||
(m.num_reqs,),
|
||||
2,
|
||||
dtype=torch.int64,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
req_group[spec_req_idx] = 0
|
||||
req_group[decode_req_idx_cpu.to(query_start_loc.device)] = 1
|
||||
token_group = torch.repeat_interleave(req_group, query_lens)
|
||||
token_perm = torch.argsort(token_group, stable=True)
|
||||
spec_token_indx = token_perm[:num_spec_decode_tokens]
|
||||
non_spec_token_indx = token_perm[num_spec_decode_tokens:]
|
||||
|
||||
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
|
||||
non_spec_state_indices_tensor = block_table_tensor[non_spec_req_idx, 0]
|
||||
spec_query_start_loc = torch.zeros(
|
||||
num_spec_decodes + 1,
|
||||
dtype=torch.int32,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
torch.cumsum(query_lens[spec_req_idx], dim=0, out=spec_query_start_loc[1:])
|
||||
non_spec_query_start_loc = torch.zeros(
|
||||
num_decodes + num_prefills + 1,
|
||||
dtype=torch.int32,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
torch.cumsum(
|
||||
query_lens[non_spec_req_idx],
|
||||
dim=0,
|
||||
out=non_spec_query_start_loc[1:],
|
||||
)
|
||||
non_spec_query_start_loc_cpu = torch.zeros(
|
||||
num_decodes + num_prefills + 1, dtype=torch.int32
|
||||
)
|
||||
torch.cumsum(
|
||||
query_lens_cpu[non_spec_req_idx_cpu],
|
||||
dim=0,
|
||||
out=non_spec_query_start_loc_cpu[1:],
|
||||
)
|
||||
|
||||
assert num_accepted_tokens is not None
|
||||
# Accepted-token counts must follow the same request order as the
|
||||
# speculative state indices.
|
||||
num_accepted_tokens = num_accepted_tokens[
|
||||
spec_req_idx_cpu.to(num_accepted_tokens.device)
|
||||
]
|
||||
|
||||
# Compute the conv-state slots for the non-spec decode/prefill split,
|
||||
# plus the initial-state masks and Triton causal_conv1d metadata.
|
||||
if non_spec_state_indices_tensor is None:
|
||||
state_indices_tensor = block_table_tensor[:0, 0]
|
||||
else:
|
||||
state_indices_tensor = non_spec_state_indices_tensor
|
||||
|
||||
# Build the regular decode/prefill state metadata inherited from the
|
||||
# generic short-conv metadata contract.
|
||||
query_start_loc_p = None
|
||||
query_start_loc_d = None
|
||||
state_indices_tensor_p = None
|
||||
state_indices_tensor_d = None
|
||||
if num_decodes > 0 or num_prefills > 0:
|
||||
num_computed_tokens = m.compute_num_computed_tokens()
|
||||
if non_spec_req_idx_cpu is not None:
|
||||
non_spec_req_idx = non_spec_req_idx_cpu.to(num_computed_tokens.device)
|
||||
num_computed_tokens = num_computed_tokens[non_spec_req_idx]
|
||||
|
||||
state_indices_tensor_d = state_indices_tensor[:num_decodes]
|
||||
state_indices_tensor_p = state_indices_tensor[
|
||||
num_decodes : num_decodes + num_prefills
|
||||
]
|
||||
if num_decodes > 0:
|
||||
has_initial_states_d = num_computed_tokens[:num_decodes] > 0
|
||||
assert non_spec_query_start_loc is not None
|
||||
query_start_loc_d = non_spec_query_start_loc[: num_decodes + 1]
|
||||
if num_prefills > 0:
|
||||
num_computed_tokens_p = num_computed_tokens[
|
||||
num_decodes : num_decodes + num_prefills
|
||||
]
|
||||
has_initial_states_p = num_computed_tokens_p > 0
|
||||
assert non_spec_query_start_loc is not None
|
||||
assert non_spec_query_start_loc_cpu is not None
|
||||
query_start_loc_p = (
|
||||
non_spec_query_start_loc[num_decodes:] - num_decode_tokens
|
||||
)
|
||||
query_start_loc_p_cpu = (
|
||||
non_spec_query_start_loc_cpu[num_decodes:] - num_decode_tokens
|
||||
)
|
||||
if query_start_loc.device.type != "cpu":
|
||||
nums_dict, batch_ptr, token_chunk_offset_ptr = (
|
||||
compute_causal_conv1d_metadata(
|
||||
query_start_loc_p_cpu,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
)
|
||||
|
||||
# Prepare persistent tensors for CUDA graph capture and replay.
|
||||
# ``m.num_actual_tokens`` is already padded by the model runner.
|
||||
# Request-level buffers use ``m.num_reqs`` while token-level buffers
|
||||
# use their independently bounded token count.
|
||||
batch_size = m.num_reqs
|
||||
if (
|
||||
self.use_full_cuda_graph
|
||||
and num_prefills == 0
|
||||
and num_decodes == 0
|
||||
and spec_sequence_masks is not None
|
||||
and num_spec_decodes <= self.decode_cudagraph_max_bs
|
||||
and num_spec_decode_tokens <= self.decode_cudagraph_max_tokens
|
||||
):
|
||||
assert spec_state_indices_tensor is not None
|
||||
self.spec_state_indices_tensor[:num_spec_decodes].copy_(
|
||||
spec_state_indices_tensor, non_blocking=True
|
||||
)
|
||||
spec_state_indices_tensor = self.spec_state_indices_tensor[:batch_size]
|
||||
spec_state_indices_tensor[num_spec_decodes:].fill_(NULL_BLOCK_ID)
|
||||
|
||||
self.spec_sequence_masks[:batch_size].copy_(
|
||||
spec_sequence_masks[:batch_size], non_blocking=True
|
||||
)
|
||||
spec_sequence_masks = self.spec_sequence_masks[:batch_size]
|
||||
|
||||
assert spec_query_start_loc is not None
|
||||
self.spec_query_start_loc[: num_spec_decodes + 1].copy_(
|
||||
spec_query_start_loc, non_blocking=True
|
||||
)
|
||||
spec_num_query_tokens = spec_query_start_loc[-1]
|
||||
spec_query_start_loc = self.spec_query_start_loc[: batch_size + 1]
|
||||
spec_query_start_loc[num_spec_decodes + 1 :].fill_(spec_num_query_tokens)
|
||||
|
||||
assert num_accepted_tokens is not None
|
||||
self.num_accepted_tokens[:num_spec_decodes].copy_(
|
||||
num_accepted_tokens, non_blocking=True
|
||||
)
|
||||
num_accepted_tokens = self.num_accepted_tokens[:batch_size]
|
||||
num_accepted_tokens[num_spec_decodes:].fill_(1)
|
||||
|
||||
return PleShortConvAttentionMetadata(
|
||||
num_prefills=num_prefills,
|
||||
num_prefill_tokens=num_prefill_tokens,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
num_reqs=m.num_reqs,
|
||||
num_spec_decodes=num_spec_decodes,
|
||||
num_spec_decode_tokens=num_spec_decode_tokens,
|
||||
num_actual_tokens=m.num_actual_tokens,
|
||||
spec_query_len=self.num_spec + 1,
|
||||
max_prefill_query_len=max_prefill_query_len,
|
||||
query_start_loc=query_start_loc,
|
||||
state_indices_tensor=state_indices_tensor,
|
||||
has_initial_states_p=has_initial_states_p,
|
||||
has_initial_states_d=has_initial_states_d,
|
||||
non_spec_query_start_loc=non_spec_query_start_loc,
|
||||
spec_query_start_loc=spec_query_start_loc,
|
||||
spec_state_indices_tensor=spec_state_indices_tensor,
|
||||
spec_sequence_masks=spec_sequence_masks,
|
||||
spec_token_indx=spec_token_indx,
|
||||
non_spec_token_indx=non_spec_token_indx,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
|
||||
nums_dict=nums_dict,
|
||||
batch_ptr=batch_ptr,
|
||||
token_chunk_offset_ptr=token_chunk_offset_ptr,
|
||||
query_start_loc_p=query_start_loc_p,
|
||||
query_start_loc_d=query_start_loc_d,
|
||||
state_indices_tensor_p=state_indices_tensor_p,
|
||||
state_indices_tensor_d=state_indices_tensor_d,
|
||||
num_computed_tokens_p=num_computed_tokens_p,
|
||||
block_idx_last_scheduled_token=None,
|
||||
block_idx_first_scheduled_token_p=None,
|
||||
block_idx_last_computed_token=None,
|
||||
block_idx_last_scheduled_token_prev_step=None,
|
||||
seq_lens=m.seq_lens,
|
||||
)
|
||||
|
||||
def build_for_cudagraph_capture(
|
||||
self, common_attn_metadata: CommonAttentionMetadata
|
||||
) -> PleShortConvAttentionMetadata:
|
||||
"""Build metadata for full CUDA graph capture.
|
||||
|
||||
Currently, only decode is supported for full CUDA graphs with
|
||||
short-conv.
|
||||
"""
|
||||
m = common_attn_metadata
|
||||
assert (
|
||||
m.num_reqs <= self.decode_cudagraph_max_bs
|
||||
and m.num_actual_tokens <= self.decode_cudagraph_max_tokens
|
||||
), (
|
||||
"ShortConv only supports decode-only full CUDAGraph capture. "
|
||||
f"Make sure batch size ({m.num_reqs}) <= "
|
||||
f"cudagraph capture size ({self.decode_cudagraph_max_bs}) and "
|
||||
f"number of tokens ({m.num_actual_tokens}) <= "
|
||||
f"token capture size ({self.decode_cudagraph_max_tokens})."
|
||||
)
|
||||
|
||||
if self.use_spec_decode:
|
||||
num_accepted_tokens = torch.diff(m.query_start_loc)
|
||||
num_decode_draft_tokens_cpu = (num_accepted_tokens - 1).cpu()
|
||||
return self.build(
|
||||
0,
|
||||
m,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
|
||||
)
|
||||
return self.build(0, m)
|
||||
|
||||
@@ -599,7 +599,11 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
self.hash_block_size = hash_block_size
|
||||
self.dcp_world_size = dcp_world_size
|
||||
group_block_sizes = [
|
||||
manager.block_size for manager in self.single_type_managers
|
||||
manager.block_size
|
||||
for manager, group in zip(
|
||||
self.single_type_managers, kv_cache_config.kv_cache_groups
|
||||
)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
]
|
||||
assert all(
|
||||
block_size % hash_block_size == 0 for block_size in group_block_sizes
|
||||
@@ -638,8 +642,11 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
if self.enable_partial_hash_hits:
|
||||
unsupported_partial_hit_managers = {
|
||||
type(manager).__name__
|
||||
for manager in self.single_type_managers
|
||||
if not manager.supports_fine_grained_hash_lookup
|
||||
for manager, group in zip(
|
||||
self.single_type_managers, kv_cache_config.kv_cache_groups
|
||||
)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
and not manager.supports_fine_grained_hash_lookup
|
||||
and manager.block_size != hash_block_size
|
||||
}
|
||||
if unsupported_partial_hit_managers:
|
||||
@@ -668,6 +675,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
"""
|
||||
self.attention_groups: list[SpecGroup] = []
|
||||
for i, g in enumerate(self.kv_cache_config.kv_cache_groups):
|
||||
if not g.kv_cache_spec.prefix_cacheable:
|
||||
continue
|
||||
manager_cls = self.single_type_managers[i].__class__
|
||||
spec = g.kv_cache_spec
|
||||
use_eagle = i in self.eagle_group_ids
|
||||
@@ -687,8 +696,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
SpecGroup(spec, [i], manager_cls, use_eagle)
|
||||
)
|
||||
|
||||
assert len(self.attention_groups) > 1, (
|
||||
"HybridKVCacheCoordinator requires at least two attention groups."
|
||||
assert self.attention_groups, (
|
||||
"HybridKVCacheCoordinator requires at least one cacheable group."
|
||||
)
|
||||
|
||||
# Put full attention first: its efficient left-to-right scan provides
|
||||
|
||||
@@ -779,6 +779,14 @@ class KVCacheManager:
|
||||
self.kv_cache_config.kv_cache_groups,
|
||||
strict=True,
|
||||
):
|
||||
if not group.kv_cache_spec.prefix_cacheable:
|
||||
# Scratch groups (e.g. the CSA compressor ring) hold a fixed
|
||||
# block covering no token range, so a lookup result never
|
||||
# carries computed blocks for them and their block size does
|
||||
# not divide the endpoint.
|
||||
assert not group_blocks
|
||||
truncated.append([])
|
||||
continue
|
||||
assert num_computed_tokens % manager.block_size == 0
|
||||
num_blocks = num_computed_tokens // manager.block_size
|
||||
if isinstance(group.kv_cache_spec, MambaSpec):
|
||||
|
||||
+193
-156
@@ -16,7 +16,7 @@ from vllm import envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.hashing import xxhash, xxhash_cbor
|
||||
from vllm.utils.math_utils import cdiv, round_up
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.mem_utils import format_gib
|
||||
from vllm.utils.torch_utils import get_dtype_size
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
@@ -717,21 +717,52 @@ def resolve_kv_cache_block_sizes(
|
||||
# scheduler block size. Read the mode from the resolved group spec because
|
||||
# its block size may have been updated independently of cache_config.
|
||||
if any(
|
||||
isinstance(g.kv_cache_spec, MambaSpec)
|
||||
and g.kv_cache_spec.mamba_cache_mode != "align"
|
||||
for g in groups
|
||||
isinstance(spec, MambaSpec) and spec.mamba_cache_mode != "align"
|
||||
for group in groups
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
):
|
||||
return scheduler_block_size, scheduler_block_size
|
||||
|
||||
hashing_sizes = [
|
||||
block_size
|
||||
for group, block_size in zip(groups, group_block_sizes)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
] or group_block_sizes
|
||||
requested = cache_config.prefix_match_unit
|
||||
hash_block_size = (
|
||||
requested if requested is not None else math.gcd(*group_block_sizes)
|
||||
)
|
||||
if any(bs % hash_block_size != 0 for bs in group_block_sizes):
|
||||
hash_block_size = requested if requested is not None else math.gcd(*hashing_sizes)
|
||||
if any(bs % hash_block_size != 0 for bs in hashing_sizes):
|
||||
raise ValueError(
|
||||
f"Invalid prefix_match_unit={hash_block_size}; all KV cache group "
|
||||
f"block sizes must be divisible by prefix_match_unit. "
|
||||
f"Got group block sizes={group_block_sizes}."
|
||||
f"Invalid prefix_match_unit={hash_block_size}; prefix-cacheable "
|
||||
"KV cache group block sizes must be divisible by prefix_match_unit. "
|
||||
f"Got group block sizes={group_block_sizes}, "
|
||||
f"prefix-cacheable={hashing_sizes}."
|
||||
)
|
||||
prefix_alignments = {
|
||||
spec.tokens_per_state
|
||||
for group in groups
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
if spec.prefix_cacheable
|
||||
and isinstance(spec.tokens_per_state, int)
|
||||
and spec.tokens_per_state > 1
|
||||
}
|
||||
has_partial_mamba_group = any(
|
||||
isinstance(spec, MambaSpec)
|
||||
and spec.mamba_cache_mode == "align"
|
||||
and (
|
||||
(dcp == 1 and block_size > hash_block_size)
|
||||
or (dcp > 1 and block_size >= hash_block_size)
|
||||
)
|
||||
for group, block_size in zip(groups, group_block_sizes)
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
cache_hit_alignment = (
|
||||
hash_block_size if has_partial_mamba_group else scheduler_block_size
|
||||
)
|
||||
if any(cache_hit_alignment % alignment for alignment in prefix_alignments):
|
||||
raise ValueError(
|
||||
f"Invalid prefix_match_unit={hash_block_size}; prefix-cache boundaries "
|
||||
"must align with each spec's per-state compression. "
|
||||
f"Got alignments={sorted(prefix_alignments)}."
|
||||
)
|
||||
return scheduler_block_size, hash_block_size
|
||||
|
||||
@@ -1577,49 +1608,6 @@ def unify_hybrid_kv_cache_specs(kv_cache_spec: dict[str, KVCacheSpec]):
|
||||
kv_cache_spec.update(_promote_local_kv_cache_specs(kv_cache_spec))
|
||||
|
||||
|
||||
def group_and_unify_kv_cache_specs(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[UniformTypeKVCacheSpecs] | None:
|
||||
"""
|
||||
Group the KV cache specs and unify each group into one UniformTypeKVCacheSpecs.
|
||||
Currently, this is only used for DeepseekV4.
|
||||
"""
|
||||
if not any(
|
||||
isinstance(spec, SlidingWindowMLASpec) for spec in kv_cache_spec.values()
|
||||
):
|
||||
return None
|
||||
|
||||
# SlidingWindowMLASpec models with uniform page sizes don't need tuple packing.
|
||||
page_sizes = {spec.page_size_bytes for spec in kv_cache_spec.values()}
|
||||
if len(page_sizes) <= 1:
|
||||
return None
|
||||
|
||||
mla_specs: dict[str, KVCacheSpec] = {}
|
||||
grouped_swa_mla_specs: dict[tuple[int, int], dict[str, KVCacheSpec]] = defaultdict(
|
||||
dict
|
||||
)
|
||||
# NOTE: Here we group SWA layers by (block_size, sliding_window), which separates
|
||||
# SWA layers, C4I+C4A layers, and C128A layers into three different groups. It can
|
||||
# be fragile with only block_size and sliding_window as keys, but fine for now.
|
||||
for name, spec in kv_cache_spec.items():
|
||||
if isinstance(spec, SlidingWindowMLASpec):
|
||||
grouped_swa_mla_specs[(spec.block_size, spec.sliding_window)][name] = spec
|
||||
elif isinstance(spec, MLAAttentionSpec):
|
||||
mla_specs[name] = spec
|
||||
|
||||
assert len(mla_specs) > 0
|
||||
mla_uniform_spec = UniformTypeKVCacheSpecs.from_specs(mla_specs)
|
||||
assert mla_uniform_spec is not None
|
||||
|
||||
swa_uniform_specs: list[UniformTypeKVCacheSpecs] = []
|
||||
for spec_dict in grouped_swa_mla_specs.values():
|
||||
uniform_spec = UniformTypeKVCacheSpecs.from_specs(spec_dict)
|
||||
assert uniform_spec is not None
|
||||
swa_uniform_specs.append(uniform_spec)
|
||||
|
||||
return [mla_uniform_spec, *swa_uniform_specs]
|
||||
|
||||
|
||||
def _approximate_gcd(values: Sequence[int], *, lower_bound: int | None = None) -> int:
|
||||
"""Pick a chunk size that minimizes total upward padding.
|
||||
|
||||
@@ -1655,91 +1643,145 @@ def _approximate_gcd(values: Sequence[int], *, lower_bound: int | None = None) -
|
||||
return best_d
|
||||
|
||||
|
||||
def _get_kv_cache_groups_uniform_groups(
|
||||
grouped_specs: list[UniformTypeKVCacheSpecs],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
def _get_packed_kv_cache_groups(
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec] | None:
|
||||
"""Group mixed-page-size layers for contiguous block-outermost packing.
|
||||
|
||||
Greedily buckets layers into uniform-type specs. Buckets with equal layer
|
||||
counts per page size are treated as a repeating layer pattern (one layer
|
||||
per page size) and split into groups covering the same number of pattern
|
||||
repeats (picked by ``_approximate_gcd`` to minimize padding), so all
|
||||
groups pack into the same per-block layout. Mamba buckets are additionally
|
||||
split to fit the block the attention buckets already need.
|
||||
Returns None when the layout is not block-outermost or all layers already
|
||||
share one page size.
|
||||
"""
|
||||
Generate the KV cache groups from the grouped specs.
|
||||
"""
|
||||
assert len(grouped_specs) > 0 and all(
|
||||
isinstance(spec, UniformTypeKVCacheSpecs) for spec in grouped_specs
|
||||
layout = vllm_config.cache_config.get_resolved_kv_cache_layout()
|
||||
page_sizes = {spec.page_size_bytes for spec in kv_cache_spec.values()}
|
||||
if not layout.is_block_outermost or len(page_sizes) <= 1:
|
||||
return None
|
||||
|
||||
buckets: list[dict[str, KVCacheSpec]] = []
|
||||
for name, spec in kv_cache_spec.items():
|
||||
for bucket in buckets:
|
||||
candidate = {**bucket, name: spec}
|
||||
if UniformTypeKVCacheSpecs.is_uniform_type(candidate):
|
||||
bucket[name] = spec
|
||||
break
|
||||
else:
|
||||
buckets.append({name: spec})
|
||||
|
||||
bucketed = []
|
||||
for bucket in buckets:
|
||||
uniform_spec = UniformTypeKVCacheSpecs.from_specs(bucket)
|
||||
assert uniform_spec is not None
|
||||
page_size_layers: dict[int, list[str]] = defaultdict(list)
|
||||
for layer_name, layer_spec in bucket.items():
|
||||
page_size_layers[layer_spec.page_size_bytes].append(layer_name)
|
||||
# Only 1:1 patterns (one layer of each page size per repeat) are
|
||||
# supported; counts sharing a gcd > 1 (e.g. 2:1) could in principle
|
||||
# repeat too, but such buckets are emitted whole instead.
|
||||
balanced = len(set(map(len, page_size_layers.values()))) == 1
|
||||
bucketed.append((uniform_spec, page_size_layers, balanced))
|
||||
|
||||
# Balanced buckets that mix page sizes must stay whole, so the largest one
|
||||
# sets a floor on the repeats per group; larger single-size buckets are
|
||||
# split down toward it. No such bucket means nothing needs packing.
|
||||
min_repeats_per_group = max(
|
||||
(
|
||||
spec.get_max_layers_per_page_size()
|
||||
for spec, page_size_layers, balanced in bucketed
|
||||
if balanced and len(page_size_layers) > 1
|
||||
),
|
||||
default=0,
|
||||
)
|
||||
# For now, we restrict the first grouped_spec to be UniformTypeKVCacheSpecs
|
||||
# containing only MLAAttentionSpec.
|
||||
full_mla_spec = grouped_specs[0]
|
||||
assert all(
|
||||
isinstance(spec, MLAAttentionSpec)
|
||||
for spec in full_mla_spec.kv_cache_specs.values()
|
||||
)
|
||||
full_mla_group = KVCacheGroupSpec(
|
||||
layer_names=list(full_mla_spec.kv_cache_specs.keys()),
|
||||
kv_cache_spec=full_mla_spec,
|
||||
repeats_per_group = (
|
||||
_approximate_gcd(
|
||||
[
|
||||
spec.get_max_layers_per_page_size()
|
||||
for spec, _, balanced in bucketed
|
||||
if balanced
|
||||
],
|
||||
lower_bound=min_repeats_per_group,
|
||||
)
|
||||
if min_repeats_per_group
|
||||
else None
|
||||
)
|
||||
|
||||
# We define a layer tuple as a group of layers with different page sizes, and
|
||||
# one UniformTypeKVCacheSpecs contains a list of layer tuples.
|
||||
# For example, if we have 11 C4 layers and 10 C128 layers, we can define a layer
|
||||
# tuple as [C4I, C4A, C128], and the full_mla_group will contain "11" layer tuples.
|
||||
# The other uniform KV cache specs will be similarly partitioned into layer tuples.
|
||||
# Say we have 21 SWA layers, all with the same page size, then we will have "21"
|
||||
# layer tuples.
|
||||
num_layer_tuples_per_group: list[int] = [
|
||||
g_spec.get_num_layer_tuples() for g_spec in grouped_specs
|
||||
]
|
||||
# Choose `num_layer_tuples` to minimize total padding across groups.
|
||||
num_layer_tuples = _approximate_gcd(
|
||||
num_layer_tuples_per_group, lower_bound=num_layer_tuples_per_group[0]
|
||||
)
|
||||
# Round up to the nearest multiple of `num_layer_tuples` (i.e., padding)
|
||||
num_layer_tuples_per_group = [
|
||||
round_up(x, num_layer_tuples) for x in num_layer_tuples_per_group
|
||||
]
|
||||
def num_groups_for(spec: UniformTypeKVCacheSpecs, balanced: bool) -> int:
|
||||
if balanced and repeats_per_group is not None:
|
||||
return cdiv(spec.get_max_layers_per_page_size(), repeats_per_group)
|
||||
return 1
|
||||
|
||||
swa_mla_specs = grouped_specs[1:]
|
||||
assert all(
|
||||
isinstance(spec, SlidingWindowMLASpec)
|
||||
for group in swa_mla_specs
|
||||
for spec in group.kv_cache_specs.values()
|
||||
def widest_group_bytes(page_size_layers: dict[int, list[str]], n: int) -> int:
|
||||
"""Page bytes of the largest of the n groups a bucket splits into."""
|
||||
return sum(
|
||||
cdiv(len(names), n) * page for page, names in page_size_layers.items()
|
||||
)
|
||||
|
||||
# Bytes a block must hold however the mamba buckets end up split: a mamba
|
||||
# bucket can go down to one state per group, every other bucket's split is
|
||||
# already fixed by the repeat pattern.
|
||||
anchor_bytes = max(
|
||||
(
|
||||
widest_group_bytes(
|
||||
page_size_layers,
|
||||
len(spec.kv_cache_specs)
|
||||
if isinstance(spec.first_spec, MambaSpec)
|
||||
else num_groups_for(spec, balanced),
|
||||
)
|
||||
for spec, page_size_layers, balanced in bucketed
|
||||
),
|
||||
default=0,
|
||||
)
|
||||
|
||||
# Split each SWA UniformKV group into smaller groups to align their
|
||||
# numbers of layer tuples. The packed block planner overlays groups, so
|
||||
# their page sizes do not need to match.
|
||||
swa_mla_groups = []
|
||||
for sm_spec in swa_mla_specs:
|
||||
layers_per_size: dict[int, list[str]] = defaultdict(list)
|
||||
groups = []
|
||||
for spec, page_size_layers, balanced in bucketed:
|
||||
num_groups = num_groups_for(spec, balanced)
|
||||
# `_align_hybrid_block_size` pads a mamba state up to one attention
|
||||
# page, so cap a mamba group at the states a block already fits rather
|
||||
# than let it widen the block.
|
||||
if anchor_bytes and isinstance(spec.first_spec, MambaSpec):
|
||||
states_per_block = max(anchor_bytes // spec.first_spec.page_size_bytes, 1)
|
||||
num_groups = max(
|
||||
num_groups, cdiv(len(spec.kv_cache_specs), states_per_block)
|
||||
)
|
||||
if num_groups == 1:
|
||||
groups.append(KVCacheGroupSpec(list(spec.kv_cache_specs), spec))
|
||||
continue
|
||||
|
||||
for layer_name, layer_spec in sm_spec.kv_cache_specs.items():
|
||||
layers_per_size[layer_spec.page_size_bytes].append(layer_name)
|
||||
# NOTE(yifan): for now, inside a UniformKV group, each page_size should
|
||||
# have the same number of layers. This also means we don't need to pad layers
|
||||
# inside a partial-full layer tuple.
|
||||
assert len(set(len(layers) for layers in layers_per_size.values())) == 1
|
||||
num_layers_per_size = len(next(iter(layers_per_size.values())))
|
||||
|
||||
# Split layers inside each UniformKV group for aligned #(layers).
|
||||
# See `_get_kv_cache_groups_uniform_page_size` for more details.
|
||||
num_tuple_groups = cdiv(num_layers_per_size, num_layer_tuples)
|
||||
layer_tuples = list(zip(*layers_per_size.values()))
|
||||
for i in range(num_tuple_groups):
|
||||
group_layer_tuples = layer_tuples[i::num_tuple_groups]
|
||||
# Flatten tuples and build dict for from_specs
|
||||
pattern_repeats = list(zip(*page_size_layers.values()))
|
||||
for i in range(num_groups):
|
||||
group_layer_names = [
|
||||
name for layer_tuple in group_layer_tuples for name in layer_tuple
|
||||
name for repeat in pattern_repeats[i::num_groups] for name in repeat
|
||||
]
|
||||
group_layer_specs = {
|
||||
name: sm_spec.kv_cache_specs[name] for name in group_layer_names
|
||||
name: spec.kv_cache_specs[name] for name in group_layer_names
|
||||
}
|
||||
sub_sm_spec = UniformTypeKVCacheSpecs.from_specs(group_layer_specs)
|
||||
assert sub_sm_spec is not None
|
||||
swa_mla_groups.append(
|
||||
KVCacheGroupSpec(
|
||||
layer_names=group_layer_names,
|
||||
kv_cache_spec=sub_sm_spec,
|
||||
)
|
||||
)
|
||||
group_spec = UniformTypeKVCacheSpecs.from_specs(group_layer_specs)
|
||||
assert group_spec is not None
|
||||
groups.append(KVCacheGroupSpec(group_layer_names, group_spec))
|
||||
|
||||
return [full_mla_group, *swa_mla_groups]
|
||||
_annotate_eagle_groups(
|
||||
vllm_config,
|
||||
kv_cache_spec,
|
||||
groups,
|
||||
use_deepseek_v4_fallback=_is_deepseek_v4_eagle(vllm_config),
|
||||
)
|
||||
_warn_if_unannotated_eagle_mamba(vllm_config, groups)
|
||||
return groups
|
||||
|
||||
|
||||
def _is_deepseek_v4_eagle(vllm_config: VllmConfig) -> bool:
|
||||
spec_config = vllm_config.speculative_config
|
||||
if spec_config is None or not spec_config.use_eagle():
|
||||
return False
|
||||
model_config = vllm_config.model_config
|
||||
return (
|
||||
model_config is not None and model_config.hf_config.model_type == "deepseek_v4"
|
||||
)
|
||||
|
||||
|
||||
def _annotate_eagle_groups(
|
||||
@@ -1763,9 +1805,10 @@ def _annotate_eagle_groups(
|
||||
the target's own decoder layer and so carries no spec marker. Its draft
|
||||
attention layer is always the last registered layer, so flag whichever
|
||||
group holds it. This rule is only valid where the groups partition
|
||||
exactly the layers of ``kv_cache_spec``, which is true on the
|
||||
group_and_unify path and not in general; other callers must leave
|
||||
``use_deepseek_v4_fallback`` False.
|
||||
exactly the layers of ``kv_cache_spec``, which is true on the packed
|
||||
grouping path and not in general; other callers must leave
|
||||
``use_deepseek_v4_fallback`` False. The caller gates this fallback on
|
||||
the configured model type.
|
||||
FIXME(yifan): avoid/generalize this hacky check.
|
||||
|
||||
Args:
|
||||
@@ -1773,25 +1816,21 @@ def _annotate_eagle_groups(
|
||||
kv_cache_spec: The kv cache spec of each attention layer, in layer
|
||||
registration order. Only read by rule 2.
|
||||
kv_cache_groups: Groups to annotate in place.
|
||||
use_deepseek_v4_fallback: Enable rule 2. Only the group_and_unify path
|
||||
may set this.
|
||||
use_deepseek_v4_fallback: Enable rule 2 for a DeepseekV4 packed group.
|
||||
"""
|
||||
spec_config = vllm_config.speculative_config
|
||||
if spec_config is None or not spec_config.use_eagle():
|
||||
return
|
||||
|
||||
for group in kv_cache_groups:
|
||||
if getattr(group.kv_cache_spec, "non_causal_multi_token_decode", False):
|
||||
if any(
|
||||
getattr(spec, "non_causal_multi_token_decode", False)
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
):
|
||||
group.is_eagle_group = True
|
||||
|
||||
if not use_deepseek_v4_fallback:
|
||||
return
|
||||
# Detection uses the merged MLA spec's model_version.
|
||||
if not any(
|
||||
getattr(spec, "model_version", None) == "deepseek_v4"
|
||||
for spec in kv_cache_spec.values()
|
||||
):
|
||||
return
|
||||
last_layer = next(reversed(kv_cache_spec))
|
||||
for group in kv_cache_groups:
|
||||
if last_layer in group.layer_names:
|
||||
@@ -1822,7 +1861,10 @@ def _warn_if_unannotated_eagle_mamba(
|
||||
mamba_groups = [
|
||||
idx
|
||||
for idx, group in enumerate(kv_cache_groups)
|
||||
if isinstance(group.kv_cache_spec, MambaSpec)
|
||||
if any(
|
||||
isinstance(spec, MambaSpec)
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
]
|
||||
if not mamba_groups:
|
||||
return
|
||||
@@ -1846,7 +1888,8 @@ def _largest_divisor_at_most(value: int, limit: int) -> int:
|
||||
|
||||
|
||||
def get_kv_cache_groups(
|
||||
vllm_config: VllmConfig, kv_cache_spec: dict[str, KVCacheSpec]
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Split the layers in the model into groups with the same KV cache spec.
|
||||
@@ -1876,22 +1919,8 @@ def get_kv_cache_groups(
|
||||
# full attention, or all layers are sliding window attention with the
|
||||
# same window size). Put all layers into one group.
|
||||
return _get_kv_cache_groups_uniform_type(uniform_spec)
|
||||
elif grouped_specs := group_and_unify_kv_cache_specs(kv_cache_spec):
|
||||
# DeepseekV4 case: All layers need the same number of token slots,
|
||||
# yet some layers are full attention while others are sliding window
|
||||
# attention in different sizes. Need to group layers into multiple
|
||||
# UniformTypeKVCacheSpecs.
|
||||
kv_cache_groups = _get_kv_cache_groups_uniform_groups(grouped_specs)
|
||||
_annotate_eagle_groups(
|
||||
vllm_config,
|
||||
kv_cache_spec,
|
||||
kv_cache_groups,
|
||||
use_deepseek_v4_fallback=True,
|
||||
)
|
||||
return kv_cache_groups
|
||||
|
||||
# Pull HiddenStateCacheSpec layers out before the general multi-group
|
||||
# path so they don't affect page-size unification or grouping.
|
||||
# Hidden-state layers use their own block table and must not be absorbed
|
||||
# into a compatible attention bucket.
|
||||
hidden_specs = {
|
||||
k: v for k, v in kv_cache_spec.items() if isinstance(v, HiddenStateCacheSpec)
|
||||
}
|
||||
@@ -1901,6 +1930,14 @@ def get_kv_cache_groups(
|
||||
if not isinstance(v, HiddenStateCacheSpec)
|
||||
}
|
||||
|
||||
if packed_groups := _get_packed_kv_cache_groups(vllm_config, filtered_spec):
|
||||
# Block-outermost blocks are strided by the widest group, so hidden
|
||||
# groups need no page alignment.
|
||||
packed_groups += [
|
||||
KVCacheGroupSpec([name], spec) for name, spec in hidden_specs.items()
|
||||
]
|
||||
return packed_groups
|
||||
|
||||
# Prefer preserving each layer's cache semantics. If physical pages cannot
|
||||
# be unified, try a supported allocation-only fallback before failing.
|
||||
try:
|
||||
|
||||
@@ -1008,6 +1008,18 @@ class Scheduler(SchedulerInterface):
|
||||
)
|
||||
if num_new_tokens == 0:
|
||||
break
|
||||
if (
|
||||
pad_spec_decode
|
||||
and num_new_tokens != 1 + self.num_spec_tokens
|
||||
):
|
||||
# Alignment clipped the placeholder rows. The split
|
||||
# aligns prefill chunks, but the padded tail rows are
|
||||
# speculative positions, not prefill tokens. A padded
|
||||
# request must keep all 1 + num_spec rows or the
|
||||
# sampler's row count stops matching its query rows,
|
||||
# so drop the padding instead of shortening it.
|
||||
num_new_tokens = 1
|
||||
pad_spec_decode = False
|
||||
|
||||
# Schedule encoder inputs.
|
||||
if request.has_encoder_inputs:
|
||||
@@ -1170,6 +1182,7 @@ class Scheduler(SchedulerInterface):
|
||||
request.status = RequestStatus.RUNNING
|
||||
request.num_computed_tokens = num_computed_tokens
|
||||
if pad_spec_decode:
|
||||
assert num_new_tokens == 1 + self.num_spec_tokens
|
||||
scheduled_spec_decode_tokens[request_id] = [
|
||||
-1
|
||||
] * self.num_spec_tokens
|
||||
|
||||
@@ -18,6 +18,7 @@ from vllm.v1.core.kv_cache_utils import (
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
ChunkedLocalAttentionSpec,
|
||||
CircularBufferSpec,
|
||||
CrossAttentionSpec,
|
||||
FullAttentionSpec,
|
||||
HiddenStateCacheSpec,
|
||||
@@ -83,8 +84,10 @@ class SingleTypeKVCacheManager(ABC):
|
||||
self._max_admission_blocks_per_request = max_admission_blocks_per_request
|
||||
# Record newly allocated block ids only when worker-side zeroing will
|
||||
# consume them and this manager holds a spec type that gets zeroed.
|
||||
self._record_new_block_ids = needs_kv_cache_zeroing and isinstance(
|
||||
kv_cache_spec, AttentionSpec
|
||||
self._record_new_block_ids = (
|
||||
needs_kv_cache_zeroing
|
||||
and isinstance(kv_cache_spec, AttentionSpec)
|
||||
and not isinstance(kv_cache_spec, CircularBufferSpec)
|
||||
)
|
||||
self.new_block_ids: list[int] = []
|
||||
|
||||
@@ -1109,6 +1112,93 @@ class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
return 0
|
||||
|
||||
|
||||
class CircularBufferManager(FullAttentionManager):
|
||||
"""Claims the ring's single block per request; prefix caching disabled."""
|
||||
|
||||
supports_fine_grained_hash_lookup: ClassVar[bool] = False
|
||||
|
||||
def _claim_ring_block(self, request_id: str) -> list[KVCacheBlock]:
|
||||
req_blocks = self.req_to_blocks[request_id]
|
||||
if req_blocks:
|
||||
return []
|
||||
new_blocks = self.block_pool.get_new_blocks(1)
|
||||
req_blocks.extend(new_blocks)
|
||||
if self._record_new_block_ids:
|
||||
self.new_block_ids.extend(block.block_id for block in new_blocks)
|
||||
return new_blocks
|
||||
|
||||
def get_num_blocks_to_allocate(
|
||||
self,
|
||||
request_id: str,
|
||||
num_tokens: int,
|
||||
new_computed_blocks: Sequence[KVCacheBlock],
|
||||
total_computed_tokens: int,
|
||||
num_local_computed_tokens: int,
|
||||
num_tokens_main_model: int,
|
||||
apply_admission_cap: bool = False,
|
||||
) -> int:
|
||||
return 0 if self.req_to_blocks.get(request_id) else 1
|
||||
|
||||
def allocate_new_blocks(
|
||||
self, request_id: str, num_tokens: int, num_tokens_main_model: int
|
||||
) -> list[KVCacheBlock]:
|
||||
return self._claim_ring_block(request_id)
|
||||
|
||||
def allocate_external_computed_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
num_local_computed_tokens: int,
|
||||
num_external_computed_tokens: int,
|
||||
) -> None:
|
||||
self._claim_ring_block(request_id)
|
||||
|
||||
@classmethod
|
||||
def find_longest_cache_hit(
|
||||
cls,
|
||||
block_hashes: BlockHashList,
|
||||
max_length: int,
|
||||
kv_cache_group_ids: list[int],
|
||||
block_pool: BlockPool,
|
||||
kv_cache_spec: KVCacheSpec,
|
||||
drop_eagle_block: bool,
|
||||
alignment_tokens: int,
|
||||
dcp_world_size: int = 1,
|
||||
pcp_world_size: int = 1,
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int]:
|
||||
return tuple([] for _ in kv_cache_group_ids), 0
|
||||
|
||||
def cache_blocks(
|
||||
self,
|
||||
request: Request,
|
||||
num_tokens: int,
|
||||
retention_interval: int | None = None,
|
||||
) -> None:
|
||||
return
|
||||
|
||||
def add_local_computed_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
new_computed_blocks: Sequence[KVCacheBlock],
|
||||
num_local_computed_tokens: int,
|
||||
num_external_computed_tokens: int,
|
||||
) -> None:
|
||||
return
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
processed_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
return
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
return 0
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
def __init__(self, kv_cache_spec: ChunkedLocalAttentionSpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
@@ -1953,6 +2043,11 @@ def register_all_kvcache_specs(vllm_config):
|
||||
SlidingWindowManager,
|
||||
uniform_type_base_spec=SlidingWindowSpec,
|
||||
)
|
||||
KVCacheSpecRegistry.register(
|
||||
CircularBufferSpec,
|
||||
CircularBufferManager,
|
||||
uniform_type_base_spec=CircularBufferSpec,
|
||||
)
|
||||
KVCacheSpecRegistry.register(
|
||||
SlidingWindowMLASpec,
|
||||
SlidingWindowManager,
|
||||
|
||||
@@ -150,6 +150,10 @@ class KVCacheSpec:
|
||||
# number of tokens in a block
|
||||
block_size: int
|
||||
|
||||
@property
|
||||
def prefix_cacheable(self) -> bool:
|
||||
return True
|
||||
|
||||
@property
|
||||
def num_heads(self) -> int:
|
||||
raise NotImplementedError
|
||||
@@ -745,6 +749,38 @@ class SlidingWindowSpec(AttentionSpec):
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class CircularBufferSpec(AttentionSpec):
|
||||
"""One block per request holding the raw keys of the token group that
|
||||
is still being compressed.
|
||||
|
||||
``block_size`` is the ring capacity. It must exceed the compression ratio
|
||||
by the speculative lookahead: a speculative step stores all of its rows,
|
||||
drafts included, before acceptance is known, while the next step still
|
||||
reads the open group's committed keys from the ring.
|
||||
"""
|
||||
|
||||
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
|
||||
# The ring occupies one block per request for its whole lifetime.
|
||||
del vllm_config
|
||||
return self.page_size_bytes
|
||||
|
||||
def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int:
|
||||
del vllm_config, max_len
|
||||
return 1
|
||||
|
||||
def is_uniform_with_collection(
|
||||
self, kv_cache_specs: dict[str, KVCacheSpec]
|
||||
) -> bool:
|
||||
return all(
|
||||
isinstance(spec, CircularBufferSpec) for spec in kv_cache_specs.values()
|
||||
)
|
||||
|
||||
@property
|
||||
def prefix_cacheable(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class SlidingWindowMLASpec(SlidingWindowSpec):
|
||||
"""Sliding window attention with MLA cache format."""
|
||||
@@ -814,7 +850,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
|
||||
@dataclass(frozen=True)
|
||||
class MambaSpec(KVCacheSpec):
|
||||
shapes: tuple[tuple[int, ...], ...]
|
||||
dtypes: tuple[torch.dtype]
|
||||
dtypes: tuple[torch.dtype, ...]
|
||||
page_size_padded: int | None = None
|
||||
mamba_type: MambaAttentionBackendEnum = MambaAttentionBackendEnum.MAMBA2
|
||||
mamba_cache_mode: str = "none"
|
||||
@@ -822,6 +858,9 @@ class MambaSpec(KVCacheSpec):
|
||||
num_prefill_checkpoint_blocks: int = 0
|
||||
num_heads: int = 1
|
||||
tokens_per_state: int = -1
|
||||
# False: the state is sharded across TP ranks (e.g. GDN). True: every TP
|
||||
# rank holds the full state (e.g. the replicated PLE conv state).
|
||||
tp_replicated: bool = False
|
||||
|
||||
@property
|
||||
def state_content_size_bytes(self) -> int:
|
||||
@@ -873,6 +912,8 @@ class MambaSpec(KVCacheSpec):
|
||||
isinstance(spec, MambaSpec)
|
||||
and spec.num_speculative_blocks == self.num_speculative_blocks
|
||||
and spec.num_prefill_checkpoint_blocks == self.num_prefill_checkpoint_blocks
|
||||
and spec.page_size_bytes == self.page_size_bytes
|
||||
and spec.tp_replicated == self.tp_replicated
|
||||
for spec in kv_cache_specs.values()
|
||||
)
|
||||
|
||||
@@ -963,6 +1004,15 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
|
||||
kv_cache_specs: dict[str, KVCacheSpec]
|
||||
|
||||
@property
|
||||
def prefix_cacheable(self) -> bool:
|
||||
return all(spec.prefix_cacheable for spec in self.kv_cache_specs.values())
|
||||
|
||||
@property
|
||||
def first_spec(self) -> KVCacheSpec:
|
||||
"""Return the first spec in the group."""
|
||||
return next(iter(self.kv_cache_specs.values()))
|
||||
|
||||
@property
|
||||
def page_size_bytes(self) -> int:
|
||||
return sum(spec.page_size_bytes for spec in self.kv_cache_specs.values())
|
||||
@@ -1015,8 +1065,9 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
else:
|
||||
return None
|
||||
|
||||
# NOTE: below util functions are only used by DeepseekV4 for now.
|
||||
def get_num_layer_tuples(self) -> int:
|
||||
def get_max_layers_per_page_size(self) -> int:
|
||||
"""Max number of layers sharing a page size. For a balanced bucket
|
||||
this equals the number of repetitions of the layer pattern."""
|
||||
return Counter(
|
||||
spec.page_size_bytes for spec in self.kv_cache_specs.values()
|
||||
).most_common(1)[0][1]
|
||||
@@ -1212,7 +1263,11 @@ class KVCacheConfig:
|
||||
|
||||
@property
|
||||
def has_mamba_layers(self) -> bool:
|
||||
return any(isinstance(g.kv_cache_spec, MambaSpec) for g in self.kv_cache_groups)
|
||||
return any(
|
||||
isinstance(spec, MambaSpec)
|
||||
for group in self.kv_cache_groups
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
|
||||
@property
|
||||
def has_mixed_precision_kv_cache(self) -> bool:
|
||||
|
||||
@@ -26,6 +26,7 @@ class BlockTables:
|
||||
cp_size: int = 1,
|
||||
cp_rank: int = 0,
|
||||
cp_interleave: int = 1,
|
||||
slot_mapping_enabled: list[bool] | None = None,
|
||||
):
|
||||
self.block_sizes = block_sizes
|
||||
self.kernel_block_sizes = kernel_block_sizes
|
||||
@@ -39,6 +40,10 @@ class BlockTables:
|
||||
|
||||
self.num_kv_cache_groups = len(self.block_sizes)
|
||||
assert len(max_num_blocks_per_group) == self.num_kv_cache_groups
|
||||
if slot_mapping_enabled is None:
|
||||
slot_mapping_enabled = [True] * self.num_kv_cache_groups
|
||||
assert len(slot_mapping_enabled) == self.num_kv_cache_groups
|
||||
self._slot_mapping_enabled = slot_mapping_enabled
|
||||
|
||||
self.blocks_per_kv_block = [
|
||||
bs // kbs for bs, kbs in zip(block_sizes, kernel_block_sizes)
|
||||
@@ -100,6 +105,9 @@ class BlockTables:
|
||||
self.kernel_block_sizes_tensor = torch.tensor(
|
||||
self.kernel_block_sizes, dtype=torch.int32, device=self.device
|
||||
)
|
||||
self.slot_mapping_enabled = torch.tensor(
|
||||
self._slot_mapping_enabled, dtype=torch.bool, device=self.device
|
||||
)
|
||||
self.input_block_table_ptrs = self._make_ptr_tensor(self.input_block_tables)
|
||||
|
||||
def append_block_ids(
|
||||
@@ -202,6 +210,7 @@ class BlockTables:
|
||||
self.block_table_strides,
|
||||
self.block_sizes_tensor,
|
||||
self.kernel_block_sizes_tensor,
|
||||
self.slot_mapping_enabled,
|
||||
slot_mappings,
|
||||
slot_mappings.stride(0),
|
||||
self.cp_rank,
|
||||
@@ -274,6 +283,7 @@ def _compute_slot_mappings_kernel(
|
||||
block_table_strides, # [num_kv_cache_groups]
|
||||
block_sizes, # [num_kv_cache_groups]
|
||||
kernel_block_sizes, # [num_kv_cache_groups]
|
||||
slot_mapping_enabled, # [num_kv_cache_groups]
|
||||
slot_mappings_ptr, # [num_kv_cache_groups, max_num_tokens]
|
||||
slot_mappings_stride,
|
||||
cp_rank,
|
||||
@@ -302,6 +312,7 @@ def _compute_slot_mappings_kernel(
|
||||
block_table_stride = tl.load(block_table_strides + group_id)
|
||||
kv_block_size = tl.load(block_sizes + group_id)
|
||||
kernel_block_size = tl.load(kernel_block_sizes + group_id)
|
||||
mapping_enabled = tl.load(slot_mapping_enabled + group_id)
|
||||
|
||||
req_state_idx = tl.load(idx_mapping + batch_idx)
|
||||
start_idx = tl.load(query_start_loc + batch_idx)
|
||||
@@ -325,7 +336,9 @@ def _compute_slot_mappings_kernel(
|
||||
local_offsets = rounds * CP_INTERLEAVE + remainder
|
||||
local_positions = virtual_block_indices * kv_block_size + local_offsets
|
||||
|
||||
block_indices = local_positions // kernel_block_size
|
||||
block_indices = tl.where(
|
||||
mapping_enabled, local_positions // kernel_block_size, 0
|
||||
)
|
||||
block_offsets = local_positions % kernel_block_size
|
||||
block_numbers = tl.load(
|
||||
block_table_ptr + req_state_idx * block_table_stride + block_indices,
|
||||
@@ -336,4 +349,5 @@ def _compute_slot_mappings_kernel(
|
||||
if CP_SIZE != 1:
|
||||
slot_ids = tl.where(is_local, slot_ids, PAD_ID)
|
||||
|
||||
slot_ids = tl.where(mapping_enabled, slot_ids, PAD_ID)
|
||||
tl.store(slot_mapping_ptr + offset, slot_ids, mask=offset < end_idx)
|
||||
|
||||
@@ -64,7 +64,12 @@ from vllm.tasks import SupportedTask
|
||||
from vllm.utils.mem_utils import DeviceMemoryProfiler, format_gib
|
||||
from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE
|
||||
from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
KVCacheConfig,
|
||||
MambaSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.outputs import (
|
||||
DraftTokenIds,
|
||||
ECConnectorOutput,
|
||||
@@ -548,9 +553,14 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
|
||||
block_sizes = []
|
||||
max_num_blocks_per_group = []
|
||||
slot_mapping_enabled = []
|
||||
for kv_cache_group in kv_cache_config.kv_cache_groups:
|
||||
spec = kv_cache_group.kv_cache_spec
|
||||
block_sizes.append(spec.block_size)
|
||||
layer_spec = (
|
||||
spec.first_spec if isinstance(spec, UniformTypeKVCacheSpecs) else spec
|
||||
)
|
||||
slot_mapping_enabled.append(not isinstance(layer_spec, CircularBufferSpec))
|
||||
# Let each cache type account for CP. Attention KV is DCP-sharded,
|
||||
# while Mamba/GDN recurrent state is replicated across DCP ranks.
|
||||
max_num_blocks = spec.max_num_blocks_per_req(
|
||||
@@ -558,7 +568,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
)
|
||||
# Preserve each cache type's alignment requirements after applying
|
||||
# its topology-aware block-table width.
|
||||
if isinstance(spec, MambaSpec):
|
||||
if isinstance(layer_spec, (MambaSpec, CircularBufferSpec)):
|
||||
max_num_blocks = get_block_table_width(
|
||||
max_num_blocks, spec.block_size, token_alignment=None
|
||||
)
|
||||
@@ -605,6 +615,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
max_num_blocks_per_group=max_num_blocks_per_group,
|
||||
device=self.device,
|
||||
kernel_block_sizes=self.kernel_block_sizes,
|
||||
slot_mapping_enabled=slot_mapping_enabled,
|
||||
cp_size=self.dcp_size,
|
||||
cp_rank=self.dcp_rank,
|
||||
cp_interleave=self.cp_interleave,
|
||||
@@ -1192,6 +1203,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
total_num_draft_tokens = int(num_draft_tokens_per_req.sum())
|
||||
total_num_logits = num_reqs * num_bonus_tokens + total_num_draft_tokens
|
||||
num_logits = num_draft_tokens_per_req + num_bonus_tokens
|
||||
# combine_sampled_and_draft_tokens places a request's logits rows
|
||||
# at [query_end - num_logits, query_end). Fewer query rows than
|
||||
# that would silently select the preceding request's hidden states.
|
||||
assert (num_scheduled_tokens_np >= num_logits).all()
|
||||
cu_num_logits_np = np.empty(num_reqs + 1, dtype=np.int32)
|
||||
cu_num_logits_np[0] = 0
|
||||
np.cumsum(num_logits, out=cu_num_logits_np[1:])
|
||||
|
||||
@@ -9,10 +9,14 @@ import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateCopyFuncsByType
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadataBuilder
|
||||
from vllm.v1.attention.backends.mamba2_attn import Mamba2AttentionMetadataBuilder
|
||||
from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionMetadataBuilder
|
||||
from vllm.v1.attention.backends.short_conv_attn import (
|
||||
PleShortConvAttentionMetadataBuilder,
|
||||
ShortConvAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.core.sched.output import NewRequestData
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
|
||||
from vllm.v1.utils import CpuGpuBuffer
|
||||
@@ -24,7 +28,10 @@ from vllm.v1.worker.gpu.model_states.interface import ModelSpecificAttnMetadata
|
||||
from vllm.v1.worker.gpu.model_states.recoverssm import RecoverSSMState
|
||||
from vllm.v1.worker.mamba_utils import (
|
||||
MambaSpecDecodeGPUContext,
|
||||
get_mamba_group_ids,
|
||||
get_mamba_groups,
|
||||
preprocess_mamba_align_fused_kernel,
|
||||
validate_mamba_state_copy_funcs,
|
||||
)
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
@@ -53,6 +60,7 @@ class MambaHybridAttnMetadata(ModelSpecificAttnMetadata):
|
||||
Mamba2AttentionMetadataBuilder,
|
||||
GDNAttentionMetadataBuilder,
|
||||
ShortConvAttentionMetadataBuilder,
|
||||
PleShortConvAttentionMetadataBuilder,
|
||||
),
|
||||
):
|
||||
return {}
|
||||
@@ -102,6 +110,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
self._mamba_ctx: MambaSpecDecodeGPUContext | None = None
|
||||
self._mamba_group_ids: list[int] = []
|
||||
self._mamba_spec: MambaSpec | None = None
|
||||
self._mamba_state_copy_funcs: MambaStateCopyFuncsByType | None = None
|
||||
|
||||
def add_request(self, req_index: int, new_req_data: NewRequestData) -> None:
|
||||
super().add_request(req_index, new_req_data)
|
||||
@@ -117,17 +126,16 @@ class MambaHybridModelState(DefaultModelState):
|
||||
self, kv_cache_config: KVCacheConfig
|
||||
) -> tuple[list[int], MambaSpec]:
|
||||
if self._mamba_spec is None:
|
||||
group_ids: list[int] = []
|
||||
specs: list[MambaSpec] = []
|
||||
for i, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
spec = group.kv_cache_spec
|
||||
if isinstance(spec, MambaSpec):
|
||||
group_ids.append(i)
|
||||
specs.append(spec)
|
||||
assert specs, "no mamba layers in the model"
|
||||
assert all(specs[0] == s for s in specs)
|
||||
self._mamba_group_ids = group_ids
|
||||
self._mamba_spec = specs[0]
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_spec = next(iter(mamba_groups))
|
||||
assert all(
|
||||
spec.block_size == mamba_spec.block_size
|
||||
and spec.num_speculative_blocks == mamba_spec.num_speculative_blocks
|
||||
and spec.mamba_cache_mode == mamba_spec.mamba_cache_mode
|
||||
for spec in mamba_groups
|
||||
), "all mamba groups must share cache scheduling parameters"
|
||||
self._mamba_group_ids = get_mamba_group_ids(mamba_groups)
|
||||
self._mamba_spec = mamba_spec
|
||||
return self._mamba_group_ids, self._mamba_spec
|
||||
|
||||
def _ensure_align_ctx(
|
||||
@@ -136,8 +144,14 @@ class MambaHybridModelState(DefaultModelState):
|
||||
mamba_group_ids: list[int],
|
||||
block_tables: tuple[torch.Tensor, ...],
|
||||
) -> MambaSpecDecodeGPUContext:
|
||||
if self._mamba_state_copy_funcs is None:
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_types = {spec.mamba_type for spec in mamba_groups}
|
||||
copy_funcs = self.model.get_mamba_state_copy_funcs(mamba_types)
|
||||
validate_mamba_state_copy_funcs(mamba_groups, copy_funcs)
|
||||
self._mamba_state_copy_funcs = copy_funcs
|
||||
copy_funcs = self._mamba_state_copy_funcs
|
||||
if self._mamba_ctx is None:
|
||||
copy_funcs = self.model.get_mamba_state_copy_func()
|
||||
# Both SD and DS conv layouts support a >0 spec-decode shift: the
|
||||
# fused pre-copy kernel (``_copy_mamba_state_block``) applies the
|
||||
# ``token_bias = num_accepted - 1`` window shift per conv layout
|
||||
@@ -146,7 +160,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
self._mamba_ctx = MambaSpecDecodeGPUContext.create(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
num_state_types=len(copy_funcs),
|
||||
copy_funcs=copy_funcs,
|
||||
device=self.device,
|
||||
make_buffer=lambda n, dtype: CpuGpuBuffer(
|
||||
n, dtype=dtype, device=self.device
|
||||
@@ -161,7 +175,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
ctx.initialize_from_forward_context(
|
||||
kv_cache_config,
|
||||
forward_context,
|
||||
self.model.get_mamba_state_copy_func(),
|
||||
copy_funcs,
|
||||
[block_tables[gid] for gid in mamba_group_ids],
|
||||
)
|
||||
return ctx
|
||||
|
||||
@@ -18,7 +18,13 @@ from vllm.v1.core.sched.output import (
|
||||
NewRequestData,
|
||||
SchedulerOutput,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import CrossAttentionSpec, KVCacheSpec, MambaSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
CrossAttentionSpec,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.request import Request
|
||||
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
|
||||
|
||||
@@ -39,6 +45,11 @@ def _reserved_block_count(
|
||||
`KVCacheManager.allocate_slots` reserves: the token range plus
|
||||
`num_lookahead_tokens`, where the speculator writes the KV of its drafts.
|
||||
"""
|
||||
if isinstance(kvcache_spec, UniformTypeKVCacheSpecs):
|
||||
kvcache_spec = kvcache_spec.first_spec
|
||||
if isinstance(kvcache_spec, CircularBufferSpec):
|
||||
# Circular caches keep one physical ring block for the request lifetime.
|
||||
return 1
|
||||
if isinstance(kvcache_spec, CrossAttentionSpec):
|
||||
# Cross-attention blocks cover the encoder sequence only.
|
||||
return cdiv(max_encoder_len, kvcache_spec.block_size)
|
||||
|
||||
@@ -66,6 +66,7 @@ from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
|
||||
RoutedExpertsCapturer,
|
||||
bind_routed_experts_capturer,
|
||||
)
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateCopyFuncsByType
|
||||
from vllm.model_executor.layers.mamba.ops.ssu_dispatch import (
|
||||
initialize_mamba_ssu_backend,
|
||||
)
|
||||
@@ -997,6 +998,7 @@ class GPUModelRunner(
|
||||
self.kv_connector_output: KVConnectorOutput | None = None
|
||||
self.mamba_state_idx: dict[str, int] = {}
|
||||
self._mamba_bufs: mamba_utils.MambaBuffers | None = None
|
||||
self._mamba_state_copy_funcs: MambaStateCopyFuncsByType | None = None
|
||||
self.mamba_prev_last_scheduled_idx: CpuGpuBuffer | None = None
|
||||
if self.cache_config.mamba_cache_mode == "all" and self.num_spec_tokens > 0:
|
||||
self.mamba_prev_last_scheduled_idx = self._make_buffer(
|
||||
@@ -1053,6 +1055,15 @@ class GPUModelRunner(
|
||||
with_numpy=numpy,
|
||||
)
|
||||
|
||||
def _get_mamba_state_copy_funcs(self) -> MambaStateCopyFuncsByType:
|
||||
if self._mamba_state_copy_funcs is None:
|
||||
mamba_groups = mamba_utils.get_mamba_groups(self.kv_cache_config)
|
||||
mamba_types = {spec.mamba_type for spec in mamba_groups}
|
||||
copy_funcs = self.model.get_mamba_state_copy_funcs(mamba_types)
|
||||
mamba_utils.validate_mamba_state_copy_funcs(mamba_groups, copy_funcs)
|
||||
self._mamba_state_copy_funcs = copy_funcs
|
||||
return self._mamba_state_copy_funcs
|
||||
|
||||
def _get_mamba_bufs(self) -> mamba_utils.MambaBuffers:
|
||||
# Only reachable on the ``mamba_cache_mode == "align"`` path.
|
||||
# The postprocess sub-object is additionally gated on spec
|
||||
@@ -1062,7 +1073,7 @@ class GPUModelRunner(
|
||||
self._mamba_bufs = mamba_utils.MambaBuffers.create(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
copy_funcs=self.model.get_mamba_state_copy_func(),
|
||||
copy_funcs=self._get_mamba_state_copy_funcs(),
|
||||
make_buffer=self._make_buffer,
|
||||
device=self.device,
|
||||
with_postprocess_align=(
|
||||
@@ -1599,7 +1610,7 @@ class GPUModelRunner(
|
||||
input_batch=self.input_batch,
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
forward_context=self.compilation_config.static_forward_context,
|
||||
mamba_state_copy_funcs=self.model.get_mamba_state_copy_func(),
|
||||
mamba_state_copy_funcs=self._get_mamba_state_copy_funcs(),
|
||||
)
|
||||
|
||||
assert self.num_accepted_tokens_event is not None
|
||||
@@ -4404,7 +4415,7 @@ class GPUModelRunner(
|
||||
self.input_batch,
|
||||
self.requests,
|
||||
self.compilation_config.static_forward_context,
|
||||
self.model.get_mamba_state_copy_func(),
|
||||
self._get_mamba_state_copy_funcs(),
|
||||
mamba_bufs.preprocess,
|
||||
align_ctx=mamba_bufs.postprocess_align,
|
||||
)
|
||||
@@ -7488,6 +7499,7 @@ class GPUModelRunner(
|
||||
kv_cache_config = deepcopy(kv_cache_config)
|
||||
self.kv_cache_config = kv_cache_config
|
||||
self._mamba_bufs = None
|
||||
self._mamba_state_copy_funcs = None
|
||||
self.may_add_encoder_only_layers_to_kv_cache_config()
|
||||
self.maybe_add_kv_sharing_layers_to_kv_cache_groups(kv_cache_config)
|
||||
self.initialize_attn_backend(kv_cache_config, is_profiling=is_profiling)
|
||||
|
||||
+142
-57
@@ -10,7 +10,7 @@ import torch
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
MambaStateCopyFunc,
|
||||
MambaStateCopyFuncsByType,
|
||||
get_conv_copy_spec,
|
||||
get_temporal_copy_spec,
|
||||
is_conv_state_dim_first,
|
||||
@@ -19,7 +19,12 @@ from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
MambaSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.utils import CpuGpuBuffer
|
||||
from vllm.v1.worker.gpu_input_batch import CachedRequestState
|
||||
from vllm.v1.worker.lora_model_runner_mixin import GPUInputBatch
|
||||
@@ -374,8 +379,8 @@ def postprocess_mamba_fused_kernel(
|
||||
# block table.
|
||||
block_table_ptrs_ptr,
|
||||
block_table_stride_req: tl.int64, # stride between requests (in elements)
|
||||
# Mamba state metadata (per-layer, per-state-type)
|
||||
# These are 1D arrays indexed by (layer_idx * num_state_types + state_type_idx)
|
||||
# Mamba state metadata, flattened across all layer/state tensors. Different
|
||||
# Mamba groups may contribute different numbers of state tensors.
|
||||
state_base_addrs_ptr, # base address of each state tensor
|
||||
state_block_strides_ptr, # bytes per block for each state
|
||||
state_elem_sizes_ptr, # element size for each state
|
||||
@@ -415,14 +420,13 @@ def postprocess_mamba_fused_kernel(
|
||||
Fused GPU kernel for postprocess_mamba that computes decisions AND performs
|
||||
mamba state copies without any CPU-GPU synchronization.
|
||||
|
||||
Grid: (num_reqs, num_layers * num_state_types [, TEMPORAL_TILES])
|
||||
Grid: (num_reqs, num_states [, TEMPORAL_TILES])
|
||||
- program_id(0) = request/batch index
|
||||
- program_id(1) = state_idx (flattened index into layer/state_type metadata)
|
||||
- program_id(2) = temporal-copy tile index (0 when TEMPORAL_TILES == 1)
|
||||
|
||||
Note: num_layers and num_state_types are not passed as kernel parameters
|
||||
because the kernel indexes directly into pre-flattened metadata arrays
|
||||
using program_id(1). The grid dimensions encode the total state count.
|
||||
The kernel indexes directly into pre-flattened metadata arrays using
|
||||
program_id(1). The grid dimensions encode the total state count.
|
||||
"""
|
||||
batch_idx = tl.program_id(0)
|
||||
state_idx = tl.program_id(1)
|
||||
@@ -581,8 +585,8 @@ def precopy_mamba_align_fused_kernel(
|
||||
copy specs), but driven by the GPU-resident src columns so it needs no
|
||||
CPU-GPU sync (async-scheduling safe).
|
||||
|
||||
Grid: (num_reqs, num_layers * num_state_types [, TEMPORAL_TILES]). V2 passes
|
||||
a batch-to-state idx_mapping; V1 already stores the staged arrays in batch
|
||||
Grid: (num_reqs, num_states [, TEMPORAL_TILES]). V2 passes a
|
||||
batch-to-state idx_mapping; V1 already stores the staged arrays in batch
|
||||
order and uses HAS_IDX_MAPPING=False.
|
||||
"""
|
||||
batch_idx = tl.program_id(0)
|
||||
@@ -663,17 +667,56 @@ def batch_memcpy(src_ptrs, dst_ptrs, sizes):
|
||||
batch_memcpy_kernel[grid](src_ptrs, dst_ptrs, sizes, BLOCK_SIZE=BLOCK_SIZE)
|
||||
|
||||
|
||||
def get_mamba_groups(kv_cache_config: KVCacheConfig) -> tuple[list[int], MambaSpec]:
|
||||
mamba_group_ids: list[int] = []
|
||||
mamba_specs: list[MambaSpec] = []
|
||||
for i in range(len(kv_cache_config.kv_cache_groups)):
|
||||
kv_cache_spec = kv_cache_config.kv_cache_groups[i].kv_cache_spec
|
||||
if isinstance(kv_cache_spec, MambaSpec):
|
||||
mamba_group_ids.append(i)
|
||||
mamba_specs.append(kv_cache_spec)
|
||||
assert len(mamba_group_ids) > 0, "no mamba layers in the model"
|
||||
assert all(mamba_specs[0] == spec for spec in mamba_specs)
|
||||
return mamba_group_ids, mamba_specs[0]
|
||||
def _get_mamba_spec_for_layer(
|
||||
kv_cache_group: KVCacheGroupSpec, layer_name: str
|
||||
) -> MambaSpec:
|
||||
kv_cache_spec = kv_cache_group.kv_cache_spec
|
||||
if isinstance(kv_cache_spec, UniformTypeKVCacheSpecs):
|
||||
kv_cache_spec = kv_cache_spec.kv_cache_specs[layer_name]
|
||||
assert isinstance(kv_cache_spec, MambaSpec)
|
||||
return kv_cache_spec
|
||||
|
||||
|
||||
def get_mamba_group_ids(mamba_groups: dict[MambaSpec, list[int]]) -> list[int]:
|
||||
"""Return the sorted group ids of all mamba groups, without duplicates.
|
||||
|
||||
A group whose layers use different ``MambaSpec``s is listed under one key
|
||||
per spec, so the same group id can appear more than once.
|
||||
"""
|
||||
return sorted(
|
||||
{group_id for group_ids in mamba_groups.values() for group_id in group_ids}
|
||||
)
|
||||
|
||||
|
||||
def get_mamba_groups(kv_cache_config: KVCacheConfig) -> dict[MambaSpec, list[int]]:
|
||||
"""Return a mapping from each distinct MambaSpec to its sorted group_ids."""
|
||||
mamba_groups: dict[MambaSpec, set[int]] = {}
|
||||
for i, kv_cache_group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
kv_cache_spec = kv_cache_group.kv_cache_spec
|
||||
if isinstance(kv_cache_spec, UniformTypeKVCacheSpecs):
|
||||
kv_cache_spec = kv_cache_spec.first_spec
|
||||
if not isinstance(kv_cache_spec, MambaSpec):
|
||||
continue
|
||||
for layer_name in kv_cache_group.layer_names:
|
||||
mamba_spec = _get_mamba_spec_for_layer(kv_cache_group, layer_name)
|
||||
mamba_groups.setdefault(mamba_spec, set()).add(i)
|
||||
assert len(mamba_groups) > 0, "no mamba layers in the model"
|
||||
return {spec: sorted(ids) for spec, ids in mamba_groups.items()}
|
||||
|
||||
|
||||
def validate_mamba_state_copy_funcs(
|
||||
mamba_groups: dict[MambaSpec, list[int]],
|
||||
copy_funcs: MambaStateCopyFuncsByType,
|
||||
) -> None:
|
||||
for mamba_spec in mamba_groups:
|
||||
assert mamba_spec.mamba_type in copy_funcs, (
|
||||
f"missing state copy funcs for {mamba_spec.mamba_type}"
|
||||
)
|
||||
state_copy_funcs = copy_funcs[mamba_spec.mamba_type]
|
||||
assert len(state_copy_funcs) == len(mamba_spec.shapes), (
|
||||
f"{mamba_spec.mamba_type} declares {len(mamba_spec.shapes)} states, "
|
||||
f"but provides {len(state_copy_funcs)} state copy funcs"
|
||||
)
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
@@ -690,14 +733,29 @@ class MambaCopyBuffers:
|
||||
cls,
|
||||
max_num_reqs: int,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
copy_funcs: MambaStateCopyFuncsByType,
|
||||
make_buffer: Callable[..., CpuGpuBuffer],
|
||||
) -> "MambaCopyBuffers":
|
||||
mamba_group_ids, mamba_spec = get_mamba_groups(kv_cache_config)
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_spec = next(iter(mamba_groups))
|
||||
assert all(
|
||||
spec.block_size == mamba_spec.block_size
|
||||
and spec.num_speculative_blocks == mamba_spec.num_speculative_blocks
|
||||
and spec.mamba_cache_mode == mamba_spec.mamba_cache_mode
|
||||
for spec in mamba_groups
|
||||
), "all mamba groups must share cache scheduling parameters"
|
||||
mamba_group_ids = get_mamba_group_ids(mamba_groups)
|
||||
entries_per_req = sum(
|
||||
len(kv_cache_config.kv_cache_groups[gid].layer_names)
|
||||
len(
|
||||
copy_funcs[
|
||||
_get_mamba_spec_for_layer(
|
||||
kv_cache_config.kv_cache_groups[gid], layer_name
|
||||
).mamba_type
|
||||
]
|
||||
)
|
||||
for gid in mamba_group_ids
|
||||
) * len(copy_funcs)
|
||||
for layer_name in kv_cache_config.kv_cache_groups[gid].layer_names
|
||||
)
|
||||
n = max_num_reqs * entries_per_req
|
||||
|
||||
return cls(
|
||||
@@ -725,7 +783,9 @@ class MambaSpecDecodeGPUContext:
|
||||
window with offset-based copies), 0 for temporal states (full block copies).
|
||||
"""
|
||||
|
||||
# Per-state metadata tensors (shape: [num_layers * num_state_types])
|
||||
# Per-state metadata tensors (shape: [num_states]). Mamba groups may have
|
||||
# different numbers of state types (for example, GDN has two while PLE
|
||||
# short-conv has one).
|
||||
# These are populated from forward_context during the first forward pass
|
||||
state_base_addrs: torch.Tensor # int64: base address of each state tensor
|
||||
state_block_strides: torch.Tensor # int64: bytes per block
|
||||
@@ -739,8 +799,7 @@ class MambaSpecDecodeGPUContext:
|
||||
|
||||
# Configuration
|
||||
block_size: int
|
||||
num_layers: int
|
||||
num_state_types: int
|
||||
num_states: int
|
||||
mamba_group_ids: list[int]
|
||||
num_groups: int
|
||||
|
||||
@@ -776,19 +835,37 @@ class MambaSpecDecodeGPUContext:
|
||||
cls,
|
||||
max_num_reqs: int,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
num_state_types: int,
|
||||
copy_funcs: MambaStateCopyFuncsByType,
|
||||
device: torch.device,
|
||||
make_buffer: Callable[..., CpuGpuBuffer],
|
||||
) -> "MambaSpecDecodeGPUContext":
|
||||
"""Create context with allocated buffers (metadata populated later)."""
|
||||
mamba_group_ids, mamba_spec = get_mamba_groups(kv_cache_config)
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_group_ids = get_mamba_group_ids(mamba_groups)
|
||||
mamba_spec = next(iter(mamba_groups))
|
||||
assert all(
|
||||
spec.block_size == mamba_spec.block_size
|
||||
and spec.num_speculative_blocks == mamba_spec.num_speculative_blocks
|
||||
and spec.mamba_cache_mode == mamba_spec.mamba_cache_mode
|
||||
for spec in mamba_groups
|
||||
), "all mamba groups must share cache scheduling parameters"
|
||||
copy_funcs_by_spec = {
|
||||
spec: copy_funcs[spec.mamba_type] for spec in mamba_groups
|
||||
}
|
||||
|
||||
# Count total layers across all mamba groups
|
||||
num_layers = sum(
|
||||
len(kv_cache_config.kv_cache_groups[gid].layer_names)
|
||||
# Count physical state tensors across all Mamba groups. Different
|
||||
# groups may expose different state specs.
|
||||
total_states = sum(
|
||||
len(
|
||||
copy_funcs_by_spec[
|
||||
_get_mamba_spec_for_layer(
|
||||
kv_cache_config.kv_cache_groups[gid], layer_name
|
||||
)
|
||||
]
|
||||
)
|
||||
for gid in mamba_group_ids
|
||||
for layer_name in kv_cache_config.kv_cache_groups[gid].layer_names
|
||||
)
|
||||
total_states = num_layers * num_state_types
|
||||
|
||||
return cls(
|
||||
state_base_addrs=torch.zeros(
|
||||
@@ -816,8 +893,7 @@ class MambaSpecDecodeGPUContext:
|
||||
total_states, dtype=torch.int64, device=device
|
||||
),
|
||||
block_size=mamba_spec.block_size,
|
||||
num_layers=num_layers,
|
||||
num_state_types=num_state_types,
|
||||
num_states=total_states,
|
||||
mamba_group_ids=mamba_group_ids,
|
||||
num_groups=len(mamba_group_ids),
|
||||
num_accepted_tokens_out=torch.zeros(
|
||||
@@ -848,7 +924,7 @@ class MambaSpecDecodeGPUContext:
|
||||
self,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
forward_context: dict[str, Any],
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
block_tables: list[torch.Tensor],
|
||||
) -> None:
|
||||
"""
|
||||
@@ -879,8 +955,8 @@ class MambaSpecDecodeGPUContext:
|
||||
forward_context: Dictionary mapping layer names to attention objects,
|
||||
populated after the model is loaded. Each attention object must
|
||||
have a `kv_cache` attribute containing the list of state tensors.
|
||||
mamba_state_copy_funcs: Tuple of copy functions (one per state type)
|
||||
used to determine whether each state is a conv or temporal state.
|
||||
mamba_state_copy_funcs: Mapping from MambaAttentionBackendEnum to
|
||||
copy functions.
|
||||
block_tables: per-mamba-group persistent block-table tensors, in
|
||||
the same order as `mamba_group_ids`. Their `data_ptr()` /
|
||||
`stride(0)` are captured once for the kernel to index into.
|
||||
@@ -900,22 +976,24 @@ class MambaSpecDecodeGPUContext:
|
||||
self,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
forward_context: dict[str, Any],
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
block_tables: list[torch.Tensor],
|
||||
) -> None:
|
||||
idx = 0
|
||||
for group_local_idx, mamba_group_id in enumerate(self.mamba_group_ids):
|
||||
layer_names = kv_cache_config.kv_cache_groups[mamba_group_id].layer_names
|
||||
kv_cache_group = kv_cache_config.kv_cache_groups[mamba_group_id]
|
||||
layer_names = kv_cache_group.layer_names
|
||||
for layer_name in layer_names:
|
||||
mamba_spec = _get_mamba_spec_for_layer(kv_cache_group, layer_name)
|
||||
state_copy_funcs = mamba_state_copy_funcs[mamba_spec.mamba_type]
|
||||
attention = forward_context[layer_name]
|
||||
kv_caches: list[torch.Tensor] = attention.kv_cache
|
||||
|
||||
if len(kv_caches) < self.num_state_types:
|
||||
if len(kv_caches) < len(state_copy_funcs):
|
||||
raise ValueError(
|
||||
f"Expected at least {self.num_state_types} Mamba state "
|
||||
f"Expected at least {len(state_copy_funcs)} Mamba state "
|
||||
f"tensors, got {len(kv_caches)}"
|
||||
)
|
||||
for state_type_idx, copy_func in enumerate(mamba_state_copy_funcs):
|
||||
for state_type_idx, copy_func in enumerate(state_copy_funcs):
|
||||
state = kv_caches[state_type_idx]
|
||||
# Base address
|
||||
self.state_base_addrs[idx] = _reinterpret_u64_as_i64(
|
||||
@@ -994,6 +1072,8 @@ class MambaSpecDecodeGPUContext:
|
||||
self.state_group_indices[idx] = group_local_idx
|
||||
idx += 1
|
||||
|
||||
assert idx == self.num_states
|
||||
|
||||
# Cache per-group block-table base addresses and per-request stride.
|
||||
# `block_tables[i]` is the persistent 2D int32 block-table tensor for
|
||||
# `mamba_group_ids[i]`; `data_ptr()` / `stride(0)` are stable for the
|
||||
@@ -1079,7 +1159,7 @@ class MambaSpecDecodeGPUContext:
|
||||
num_accepted_tokens_gpu[:num_reqs]
|
||||
)
|
||||
|
||||
total_states = self.num_layers * self.num_state_types
|
||||
total_states = self.num_states
|
||||
grid = (num_reqs, total_states, _TEMPORAL_TILES)
|
||||
|
||||
postprocess_mamba_fused_kernel[grid](
|
||||
@@ -1128,7 +1208,7 @@ class MambaSpecDecodeGPUContext:
|
||||
"""
|
||||
if num_reqs == 0 or not self.is_initialized:
|
||||
return
|
||||
total_states = self.num_layers * self.num_state_types
|
||||
total_states = self.num_states
|
||||
grid = (num_reqs, total_states, _TEMPORAL_TILES)
|
||||
precopy_mamba_align_fused_kernel[grid](
|
||||
state_idx_gpu,
|
||||
@@ -1178,7 +1258,7 @@ class MambaSpecDecodeGPUContext:
|
||||
num_accepted_tokens_snapshot = self.num_accepted_tokens_out
|
||||
num_accepted_tokens_snapshot.copy_(num_accepted_tokens_gpu)
|
||||
|
||||
total_states = self.num_layers * self.num_state_types
|
||||
total_states = self.num_states
|
||||
grid = (num_reqs, total_states, _TEMPORAL_TILES)
|
||||
postprocess_mamba_fused_kernel[grid](
|
||||
num_accepted_tokens_snapshot,
|
||||
@@ -1226,7 +1306,7 @@ class MambaBuffers:
|
||||
cls,
|
||||
max_num_reqs: int,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
copy_funcs: MambaStateCopyFuncsByType,
|
||||
make_buffer: Callable[..., CpuGpuBuffer],
|
||||
device: torch.device,
|
||||
with_postprocess_align: bool,
|
||||
@@ -1239,7 +1319,7 @@ class MambaBuffers:
|
||||
MambaSpecDecodeGPUContext.create(
|
||||
max_num_reqs=max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
num_state_types=len(copy_funcs),
|
||||
copy_funcs=copy_funcs,
|
||||
device=device,
|
||||
make_buffer=make_buffer,
|
||||
)
|
||||
@@ -1252,7 +1332,7 @@ class MambaBuffers:
|
||||
def collect_mamba_copy_meta(
|
||||
copy_bufs: MambaCopyBuffers,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
mamba_group_ids: list[int],
|
||||
src_block_idx: int,
|
||||
dest_block_idx: int,
|
||||
@@ -1271,11 +1351,14 @@ def collect_mamba_copy_meta(
|
||||
for mamba_group_id in mamba_group_ids:
|
||||
block_ids = req_state.block_ids[mamba_group_id]
|
||||
dest_block_id = block_ids[dest_block_idx]
|
||||
layer_names = kv_cache_config.kv_cache_groups[mamba_group_id].layer_names
|
||||
kv_cache_group = kv_cache_config.kv_cache_groups[mamba_group_id]
|
||||
layer_names = kv_cache_group.layer_names
|
||||
for layer_name in layer_names:
|
||||
mamba_spec = _get_mamba_spec_for_layer(kv_cache_group, layer_name)
|
||||
state_copy_funcs = mamba_state_copy_funcs[mamba_spec.mamba_type]
|
||||
attention = forward_context[layer_name]
|
||||
kv_caches: list[torch.Tensor] = attention.kv_cache
|
||||
for state, state_copy_func in zip(kv_caches, mamba_state_copy_funcs):
|
||||
for state, state_copy_func in zip(kv_caches, state_copy_funcs):
|
||||
copy_spec = state_copy_func(
|
||||
state, block_ids, src_block_idx, accept_token_bias + 1
|
||||
)
|
||||
@@ -1355,7 +1438,7 @@ def preprocess_mamba(
|
||||
input_batch: GPUInputBatch,
|
||||
requests: dict[str, CachedRequestState],
|
||||
forward_context: dict[str, Any],
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
copy_bufs: MambaCopyBuffers,
|
||||
align_ctx: MambaSpecDecodeGPUContext | None = None,
|
||||
):
|
||||
@@ -1470,8 +1553,10 @@ def postprocess_mamba_all(
|
||||
"""
|
||||
if num_spec_tokens <= 0:
|
||||
return
|
||||
_, mamba_spec = get_mamba_groups(kv_cache_config)
|
||||
block_size = mamba_spec.block_size
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
block_sizes = {mamba_spec.block_size for mamba_spec in mamba_groups}
|
||||
assert len(block_sizes) == 1, "all mamba groups must share block_size"
|
||||
block_size = next(iter(block_sizes))
|
||||
full_decode_len = 1 + num_spec_tokens
|
||||
scheduled = scheduler_output.num_scheduled_tokens
|
||||
for req_id in input_batch.req_ids[:num_reqs]:
|
||||
@@ -1508,7 +1593,7 @@ def postprocess_mamba_align_gpu(
|
||||
input_batch: GPUInputBatch,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
forward_context: dict[str, Any],
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
) -> None:
|
||||
"""GPU-side mamba postprocess for spec decode + hybrid + align mode.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user