Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
+7 -1
View File
@@ -251,6 +251,12 @@ class DeepseekV32MTP(nn.Module, DeepseekV2MixtureOfExperts, SupportsPP):
name = name.replace(f"model.layers.{spec_layer}.", "model.")
return name
def is_unused_checkpoint_weight(self, name: str) -> bool:
return (
get_spec_layer_idx_from_weight_name(self.config, name) is None
and "embed_tokens" not in name
)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
("gate_up_proj", "gate_proj", 0),
@@ -278,7 +284,7 @@ class DeepseekV32MTP(nn.Module, DeepseekV2MixtureOfExperts, SupportsPP):
loaded_params: set[str] = set()
_pending_wk_fp8: dict = {}
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
if "rotary_emb.inv_freq" in name or self.is_unused_checkpoint_weight(name):
continue
spec_layer = get_spec_layer_idx_from_weight_name(self.config, name)
if spec_layer is None:
+7 -1
View File
@@ -356,6 +356,12 @@ class DeepseekV32MTP(nn.Module, DeepseekV2MixtureOfExperts, SupportsPP):
name = name.replace(f"model.layers.{spec_layer}.", "model.")
return name
def is_unused_checkpoint_weight(self, name: str) -> bool:
return (
get_spec_layer_idx_from_weight_name(self.config, name) is None
and "embed_tokens" not in name
)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
("gate_up_proj", "gate_proj", 0),
@@ -378,7 +384,7 @@ class DeepseekV32MTP(nn.Module, DeepseekV2MixtureOfExperts, SupportsPP):
loaded_params: set[str] = set()
_pending_wk_fp8: dict = {}
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
if "rotary_emb.inv_freq" in name or self.is_unused_checkpoint_weight(name):
continue
spec_layer = get_spec_layer_idx_from_weight_name(self.config, name)
if spec_layer is None:
+9 -5
View File
@@ -11,9 +11,8 @@ ROCm port of ``nvidia/dspark.py``. Follows the same nvidia->amd recipe used for
tilelang / triton / torch) instead of calling the tilelang kernels directly,
and gate the trailing ``mhc_post`` on ``use_fused_mhc`` (True when AITER
or TileLang fused MHC is available; False only on the torch fallback);
* drop the mega-MoE weight path (``make_deepseek_v4_expert_params_mapping``,
``use_native_mega_moe`` and ``finalize_mega_moe_weights`` do not exist in
amd/model.py).
* use the AITER MegaMoE path (``aiter_mega_moe``) instead of the DeepGEMM
mega-MoE path.
Everything else — the semi-autoregressive drafting hooks, the Markov head, the
sliding-window context-KV insert, and the checkpoint ``mtp.*`` weight remap — is
@@ -50,6 +49,7 @@ from vllm.model_executor.models.qwen3_dspark import (
)
from vllm.model_executor.models.utils import maybe_prefix
from .mega_moe import finalize_mega_moe_weights
from .model import (
DeepseekV4DecoderLayer,
)
@@ -385,14 +385,15 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
Non-mtp weights (embed/head/main layers) belong to the target model and
are skipped here. ``embed_tokens``/``lm_head`` are aliased from the target.
"""
# AMD DeepseekV4MoE has no mega-MoE path; always use the standard
# per-expert fused-MoE mapping (mirrors amd/mtp.py).
expert_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="w1",
ckpt_down_proj_name="w2",
ckpt_up_proj_name="w3",
num_experts=self.config.n_routed_experts,
routed_experts_prefix=(
"" if self.model.layers[0].ffn.use_mega_moe else "routed_experts"
),
)
expert_scale_suffix = (
".weight_scale"
@@ -496,6 +497,9 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
logger.info_once("DSpark draft model loaded: %d params", len(loaded_params))
return loaded_params
def process_weights_after_loading(self) -> None:
finalize_mega_moe_weights(self)
def _remap_dspark_name(self, name: str) -> str | None:
"""Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path.
+154
View File
@@ -0,0 +1,154 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""AITER MegaMoE experts (fused dispatch, MXFP4 GEMMs, combine) for DeepSeek V4."""
from typing import Any
import torch
import torch.nn as nn
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig
from vllm.distributed import get_ep_group
from vllm.model_executor.utils import set_weight_attrs
from vllm.utils.math_utils import next_power_of_2
class DeepseekV4AiterMegaMoEExperts(nn.Module):
# MegaMoEV2 owns large symmetric-heap buffers, so every layer shares one
# instance and passes its own weights per call.
_runtime_cache: dict[tuple, Any] = {}
def __init__(
self,
vllm_config: VllmConfig,
*,
num_experts: int,
top_k: int,
hidden_size: int,
intermediate_size: int,
swiglu_limit: float | None,
prefix: str = "",
):
super().__init__()
ep_group = get_ep_group()
self.ep_rank = ep_group.rank_in_group
self.ep_size = ep_group.world_size
self.num_experts = num_experts
self.num_local_experts = num_experts // self.ep_size
self.experts_start_idx = self.ep_rank * self.num_local_experts
self.top_k = top_k
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.swiglu_limit = swiglu_limit or 0.0
self.max_num_tokens = next_power_of_2(
vllm_config.scheduler_config.max_num_batched_tokens
)
self.prefix = prefix
def make_param(rows: int, cols: int) -> nn.Parameter:
param = nn.Parameter(
torch.zeros(self.num_local_experts, rows, cols, dtype=torch.uint8),
requires_grad=False,
)
set_weight_attrs(param, {"weight_loader": self.weight_loader})
return param
self.w13_weight = make_param(2 * intermediate_size, hidden_size // 2)
self.w13_weight_scale = make_param(2 * intermediate_size, hidden_size // 32)
self.w2_weight = make_param(hidden_size, intermediate_size // 2)
self.w2_weight_scale = make_param(hidden_size, intermediate_size // 32)
self._runtime: Any = None
def weight_loader(
self,
param: nn.Parameter,
loaded_weight: torch.Tensor,
weight_name: str,
shard_id: str,
expert_id: int,
return_success: bool = False,
) -> bool | None:
local_expert_id = expert_id - self.experts_start_idx
if not 0 <= local_expert_id < self.num_local_experts:
return False if return_success else None
expert_data = param.data[local_expert_id]
if shard_id in ("w1", "w3"):
shard_offset = 0 if shard_id == "w1" else self.intermediate_size
expert_data = expert_data.narrow(0, shard_offset, self.intermediate_size)
elif shard_id != "w2":
raise ValueError(f"Unsupported expert shard id: {shard_id}")
expert_data.copy_(loaded_weight.view(torch.uint8))
return True if return_success else None
def finalize_weights(self) -> None:
if self._runtime is not None:
return
n = self.num_local_experts
self.w13_weight.data = rocm_aiter_ops.shuffle_weight_a16w4(
self.w13_weight.data, 16, True
)
self.w13_weight_scale.data = rocm_aiter_ops.shuffle_scale_a16w4(
self.w13_weight_scale.data.view(-1, self.hidden_size // 32), n, True
)
self.w2_weight.data = rocm_aiter_ops.shuffle_weight_a16w4(
self.w2_weight.data, 16, False
)
self.w2_weight_scale.data = rocm_aiter_ops.shuffle_scale_a16w4(
self.w2_weight_scale.data.view(-1, self.intermediate_size // 32), n, False
)
key = (
id(get_ep_group().cpu_group),
torch.accelerator.current_device_index(),
self.num_experts,
self.top_k,
self.hidden_size,
self.intermediate_size,
self.max_num_tokens,
self.swiglu_limit,
)
runtime = self._runtime_cache.get(key)
if runtime is None:
from aiter.ops.flydsl.kernels.mega_moe import MegaMoEV2
runtime = MegaMoEV2(
rank=self.ep_rank,
world_size=self.ep_size,
model_dim=self.hidden_size,
inter_dim=self.intermediate_size,
experts=self.num_experts,
topk=self.top_k,
quant="a8w4",
w1=self.w13_weight,
w1_scale=self.w13_weight_scale,
w2=self.w2_weight,
w2_scale=self.w2_weight_scale,
max_tok_per_rank=self.max_num_tokens,
swiglu_limit=self.swiglu_limit,
)
self._runtime_cache[key] = runtime
self._runtime = runtime
def forward(
self,
hidden_states: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
) -> torch.Tensor:
runtime = self._runtime
assert runtime is not None
# MegaMoEV2 reads these per launch; rebind to this layer's experts.
runtime._s1_w1 = self.w13_weight
runtime._s1_w1_scale = self.w13_weight_scale
runtime.w2 = self.w2_weight
runtime.w2_scale = self.w2_weight_scale
return runtime.forward(hidden_states.contiguous(), topk_weights, topk_ids)
DeepseekV4AiterMegaMoEExperts.weight_loader.supports_moe_loading = True # type: ignore[attr-defined]
def finalize_mega_moe_weights(model: nn.Module) -> None:
for module in model.modules():
if isinstance(module, DeepseekV4AiterMegaMoEExperts):
module.finalize_weights()
+81
View File
@@ -30,6 +30,9 @@ from vllm.model_executor.layers.fused_moe import (
from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import (
rocm_aiter_fused_experts,
)
from vllm.model_executor.layers.fused_moe.router.fused_topk_bias_router import (
fused_topk_bias,
)
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
@@ -71,6 +74,7 @@ from vllm.model_executor.models.utils import (
make_layers,
maybe_prefix,
)
from vllm.models.deepseek_v4.amd.mega_moe import DeepseekV4AiterMegaMoEExperts
from vllm.models.deepseek_v4.amd.rocm import DeepseekV4ROCMAiterMLAAttention
from vllm.platforms import current_platform
from vllm.platforms.rocm import on_gfx950
@@ -529,6 +533,39 @@ def _fuse_shared_experts_enabled(config, parallel_config: ParallelConfig) -> boo
)
def _validate_aiter_mega_moe_config(vllm_config: VllmConfig) -> None:
parallel_config = vllm_config.parallel_config
if not rocm_aiter_ops.is_fused_moe_enabled():
raise ValueError(
"--moe-backend aiter_mega_moe requires VLLM_ROCM_USE_AITER=1 "
" and VLLM_ROCM_USE_AITER_MOE=1."
)
if not on_gfx950():
raise NotImplementedError("AITER MegaMoE requires gfx950.")
if (
not parallel_config.enable_expert_parallel
or parallel_config.tensor_parallel_size != 1
or parallel_config.pipeline_parallel_size != 1
):
raise NotImplementedError(
"AITER MegaMoE requires data parallel attention with expert "
"parallel MoE: --data-parallel-size N --enable-expert-parallel "
"with TP=1 and PP=1."
)
if parallel_config.all2all_backend not in (
"mori_high_throughput",
"mori_low_latency",
):
raise ValueError(
"AITER MegaMoE runs on MoRI shmem; add "
"--all2all-backend mori_high_throughput."
)
if parallel_config.enable_eplb:
raise NotImplementedError("AITER MegaMoE does not support EPLB.")
if getattr(vllm_config.model_config.hf_config, "expert_dtype", "fp4") != "fp4":
raise NotImplementedError("AITER MegaMoE only supports fp4 experts.")
class DeepseekV4MoE(nn.Module):
def __init__(
self,
@@ -643,6 +680,20 @@ class DeepseekV4MoE(nn.Module):
self.experts_start_idx = self.tp_rank * self.n_local_experts
self.experts_end_idx = self.experts_start_idx + self.n_local_experts
self.use_mega_moe = vllm_config.kernel_config.moe_backend == "aiter_mega_moe"
if self.use_mega_moe:
_validate_aiter_mega_moe_config(vllm_config)
self.experts = DeepseekV4AiterMegaMoEExperts(
vllm_config,
num_experts=config.n_routed_experts,
top_k=config.num_experts_per_tok,
hidden_size=config.hidden_size,
intermediate_size=config.moe_intermediate_size,
swiglu_limit=self.swiglu_limit,
prefix=f"{prefix}.experts",
)
return
fuse_shared_into_routed = (
self.is_fused_shared_expert_enabled or self.fuse_heterogeneous_shared_expert
)
@@ -692,6 +743,8 @@ class DeepseekV4MoE(nn.Module):
raise ValueError("DeepSeek V4 vision MoE routing requires input_ids.")
org_shape = hidden_states.shape
if self.use_mega_moe:
return self._forward_mega_moe(hidden_states, input_ids).view(org_shape)
final_hidden_states = self.experts(
hidden_states=hidden_states,
router_logits=hidden_states,
@@ -700,6 +753,30 @@ class DeepseekV4MoE(nn.Module):
return final_hidden_states.view(org_shape)
def _forward_mega_moe(
self, hidden_states: torch.Tensor, input_ids: torch.Tensor | None
) -> torch.Tensor:
router_logits, _ = self.gate(hidden_states)
topk_weights, topk_ids = fused_topk_bias(
hidden_states=hidden_states,
gating_output=router_logits,
scoring_func=self.scoring_func,
e_score_correction_bias=self.gate.e_score_correction_bias,
topk=self.n_activated_experts,
renormalize=self.renormalize,
input_tokens=input_ids,
hash_indices_table=self.gate.tid2eid,
routed_scaling_factor=self.routed_scaling_factor,
bias_vl=self.gate.bias_vl,
image_sentinel_lo=self.image_sentinel_lo,
)
final_hidden_states = self.experts(hidden_states, topk_weights, topk_ids)
if self.shared_experts is not None:
final_hidden_states = final_hidden_states + self.shared_experts(
hidden_states
)
return final_hidden_states
# Hidden sizes supported by AITER mhc_pre_big_fuse_rmsnorm.
_AITER_MHC_FUSED_RMSNORM_SIZES = frozenset({1280, 2560, 4096, 7168})
@@ -993,6 +1070,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
self.fuse_heterogeneous_shared_expert = _heterogeneous_shared_expert_enabled(
vllm_config
)
self.use_mega_moe = vllm_config.kernel_config.moe_backend == "aiter_mega_moe"
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: DeepseekV4DecoderLayer(
@@ -1315,6 +1393,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
ckpt_down_proj_name="w2",
ckpt_up_proj_name="w3",
num_experts=num_experts,
routed_experts_prefix="" if self.use_mega_moe else "routed_experts",
)
@@ -1453,6 +1532,8 @@ class DeepseekV4ForCausalLM(nn.Module, SupportsPP, SupportsEagle3):
module.prepare_attn_preshuffle()
elif isinstance(module, DeepseekV4MLP):
module.prepare_gateup_preshuffle()
elif isinstance(module, DeepseekV4AiterMegaMoEExperts):
module.finalize_weights()
if fused_compressor_layers:
logger.info(
"Fused the C4 compressor GEMMs in %d DeepSeek V4 layers",
+8
View File
@@ -46,6 +46,7 @@ from vllm.models.deepseek_v4.common.ops.fused_mtp_input_rmsnorm import (
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from .mega_moe import finalize_mega_moe_weights
from .model import DeepseekV4DecoderLayer
logger = init_logger(__name__)
@@ -392,12 +393,16 @@ class DeepSeekV4MTP(nn.Module):
head_rank_end = n_local_head * (tp_rank + 1)
# Pre-compute expert mapping ONCE.
first_layer = next(iter(self.model.layers.values()))
expert_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="w1",
ckpt_down_proj_name="w2",
ckpt_up_proj_name="w3",
num_experts=self.config.n_routed_experts,
routed_experts_prefix=(
"" if first_layer.mtp_block.ffn.use_mega_moe else "routed_experts"
),
)
# FP8 experts register ``..._weight_scale_inv`` (block_quant) while
@@ -526,6 +531,9 @@ class DeepSeekV4MTP(nn.Module):
logger.info_once("MTP draft model loaded: %d params", len(loaded_params))
return loaded_params
def process_weights_after_loading(self) -> None:
finalize_mega_moe_weights(self)
def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
"""Rewrite the weight name to match the format of the original model.
Add .mtp_block for modules in transformer layer block for spec layer
@@ -22,13 +22,12 @@ reference's out-of-vocab scheme.
import math
from collections.abc import Mapping, Sequence
from typing import Any
from typing import Any, assert_never
import numpy as np
import torch
from PIL import Image, ImageOps
from transformers import BatchFeature
from typing_extensions import assert_never
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
@@ -305,6 +305,7 @@ class FusedIndexerQRopeQuantTritonKernel(
FP8_MAX=fp8_max,
USE_FNUZ=use_fnuz,
USE_EXPLICIT_FMA=current_platform.is_rocm(),
enable_fp_fusion=True,
num_warps=1,
)
@@ -540,6 +541,7 @@ class FusedIndexerQRopeMxFp4TritonKernel(
MXFP4_BLOCK=MXFP4_BLOCK_SIZE,
index_weights_stride=index_weights.stride(0),
index_weights_out_stride=index_weights_out.stride(0),
enable_fp_fusion=True,
num_warps=1,
)
+94 -211
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import typing
from collections.abc import Callable, Iterable
from inspect import signature
from itertools import islice
import regex as re
@@ -33,6 +32,11 @@ from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.deep_gemm_mega_moe import (
DeepGemmMegaMoEBackend,
get_deep_gemm_mega_moe_backend,
ue8m0_uint8_to_float,
)
from vllm.model_executor.layers.fused_moe.router.base_router import (
eplb_map_to_physical_and_record,
)
@@ -205,7 +209,9 @@ def make_deepseek_v4_expert_params_mapping(
class DeepseekV4MegaMoEExperts(nn.Module):
_symm_buffer_cache: dict[tuple[int, int, int, int, int, int, int, int], object] = {}
_symm_buffer_cache: dict[
tuple[int, int, int, int, int, int, int, int, str], object
] = {}
def __init__(
self,
@@ -296,6 +302,8 @@ class DeepseekV4MegaMoEExperts(nn.Module):
tuple[torch.Tensor, torch.Tensor] | None
) = None
self._backend: DeepGemmMegaMoEBackend | None = None
# Register in the static forward context so the custom-op wrapper
# can look up this module by name from within a torch.compile graph.
compilation_config = vllm_config.compilation_config
@@ -357,209 +365,71 @@ class DeepseekV4MegaMoEExperts(nn.Module):
@staticmethod
def _ue8m0_uint8_to_float(sf: torch.Tensor) -> torch.Tensor:
return (sf.to(torch.int32) << 23).view(torch.float32)
return ue8m0_uint8_to_float(sf)
def _ensure_backend(self) -> DeepGemmMegaMoEBackend:
"""Lazily resolve the MegaMoE backend.
The backend is looked up via :func:`get_deep_gemm_mega_moe_backend`, which
performs all runtime capability checks. Failure propagates directly
to the caller. This must be called before :meth:`finalize_weights`
releases the loader-side parameters.
"""
if self._backend is not None:
return self._backend
assert self.w13_weight is not None, (
"_ensure_backend() must be called before finalize_weights() "
"releases the loader-side parameters."
)
self._backend = get_deep_gemm_mega_moe_backend(
self.w13_weight.device,
self.hidden_size,
self.intermediate_size,
)
return self._backend
def _check_runtime_supported(self) -> None:
device = self.w13_weight.device
if torch.cuda.get_device_capability(device)[0] != 10:
raise NotImplementedError("DeepGEMM MegaMoE requires SM100 GPUs.")
if self.hidden_size % 128 != 0 or self.intermediate_size % 128 != 0:
raise ValueError(
"DeepGEMM MegaMoE requires hidden and intermediate sizes "
"to be multiples of 128."
)
"""Preserved for API compatibility; delegates to the backend check."""
self._ensure_backend()
@staticmethod
def _deep_gemm_supports_shared_experts(deep_gemm) -> bool:
"""Check the Python API before touching a symmetric-memory group.
def _finalize_shared_expert_weights(self, shared_experts: DeepseekV4MLP) -> None:
"""Delegate shared-expert weight transform to the backend and update state.
This also gives users of an older precompiled vLLM wheel a safe serial
fallback instead of failing halfway through multi-rank buffer setup.
On success, populates ``self._transformed_shared_l{1,2}_weights``. If
the backend cannot fuse shared experts (returns ``None``), disables
native fusion by setting ``self.num_shared_experts = 0``.
"""
try:
buffer_params = signature(deep_gemm.get_symm_buffer_for_mega_moe).parameters
kernel_params = signature(deep_gemm.fp8_fp4_mega_moe).parameters
except (TypeError, ValueError):
return False
return (
hasattr(deep_gemm, "get_block_m_for_mega_moe")
and hasattr(deep_gemm, "transform_weights_for_mega_moe")
and "num_shared_experts" in buffer_params
and "shared_l1_weights" in kernel_params
and "shared_l2_weights" in kernel_params
backend = self._ensure_backend()
result = backend.transform_shared_expert_weights(
shared_experts=shared_experts,
num_shared_experts=self.num_shared_experts,
hidden_size=self.hidden_size,
intermediate_size=self.intermediate_size,
prefix=self.prefix,
)
def _finalize_shared_expert_weights(
self, deep_gemm, shared_experts: DeepseekV4MLP
) -> None:
gate_up = shared_experts.gate_up_proj
down = shared_experts.down_proj
gate_up_weight = gate_up.weight.data
gate_up_scale = (
gate_up.weight_scale
if hasattr(gate_up, "weight_scale")
else gate_up.weight_scale_inv
).data
down_weight = down.weight.data
down_scale = (
down.weight_scale
if hasattr(down, "weight_scale")
else down.weight_scale_inv
).data
# MegaMoE's shared FP8 MMA consumes a 1x32 scale for every weight row,
# while the checkpoint uses coarser block-FP8 scales (usually
# 128x128). Build a dedicated, numerically equivalent scale view before
# the generic linear post-load hook replaces the raw checkpoint scales
# with its 128x128 DeepGEMM layout.
checkpoint_scale_dtypes = (torch.float8_e8m0fnu, torch.uint8)
if (
gate_up_scale.dtype in checkpoint_scale_dtypes
and down_scale.dtype in checkpoint_scale_dtypes
):
gate_up_scale = self._prepare_shared_expert_scale(
deep_gemm,
gate_up,
gate_up_scale,
gate_up_weight.shape[0],
gate_up_weight.shape[1],
)
down_scale = self._prepare_shared_expert_scale(
deep_gemm,
down,
down_scale,
down_weight.shape[0],
down_weight.shape[1],
)
if gate_up_scale is None or down_scale is None:
if result is None:
self.num_shared_experts = 0
return
shared_intermediate_size = self.intermediate_size * self.num_shared_experts
expected_gate_up_shape = (
2 * shared_intermediate_size,
self.hidden_size,
)
expected_down_shape = (self.hidden_size, shared_intermediate_size)
if (
gate_up_weight.dtype != torch.float8_e4m3fn
or down_weight.dtype != torch.float8_e4m3fn
or gate_up_scale.dtype != torch.int32
or down_scale.dtype != torch.int32
or tuple(gate_up_weight.shape) != expected_gate_up_shape
or tuple(down_weight.shape) != expected_down_shape
):
logger.warning(
"Disabling native MegaMoE shared-expert fusion for %s: expected "
"replicated block-FP8 weights with gate_up=%s, down=%s, and "
"DeepGEMM int32 scales; got gate_up=%s/%s/%s and down=%s/%s/%s.",
self.prefix,
expected_gate_up_shape,
expected_down_shape,
tuple(gate_up_weight.shape),
gate_up_weight.dtype,
gate_up_scale.dtype,
tuple(down_weight.shape),
down_weight.dtype,
down_scale.dtype,
)
self.num_shared_experts = 0
return
transformed_l1, transformed_l2 = deep_gemm.transform_weights_for_mega_moe(
(gate_up_weight, gate_up_scale),
(down_weight, down_scale),
)
# L1 interleaving allocates a full copy. Re-home the loader Parameter on
# that storage so the original 2*intermediate*hidden FP8 tensor can be
# released instead of adding roughly 0.7 GiB per rank on DSV4-Flash.
# The generic linear post-load hook may still repack the serial scales,
# but this shared MLP is never called after native fusion is enabled.
gate_up.weight.data = transformed_l1[0]
self._transformed_shared_l1_weights = (
gate_up.weight.data,
transformed_l1[1],
)
self._transformed_shared_l2_weights = transformed_l2
def _prepare_shared_expert_scale(
self,
deep_gemm,
linear: nn.Module,
scale: torch.Tensor,
mn: int,
k: int,
) -> torch.Tensor | None:
block_size = getattr(linear, "weight_block_size", None)
if block_size is None or len(block_size) != 2:
logger.warning(
"Disabling native MegaMoE shared-expert fusion for %s: "
"shared FP8 weight block size is unavailable.",
self.prefix,
)
return None
block_m, block_k = block_size
expected_shape = (
(mn + block_m - 1) // block_m,
(k + block_k - 1) // block_k,
)
if block_k % 32 != 0 or tuple(scale.shape) != expected_shape:
logger.warning(
"Disabling native MegaMoE shared-expert fusion for %s: "
"cannot convert shared scale shape %s with block size %s "
"to MegaMoE's 1x32 layout for weight (%d, %d).",
self.prefix,
tuple(scale.shape),
tuple(block_size),
mn,
k,
)
return None
scale_fp32 = self._ue8m0_uint8_to_float(scale.view(torch.uint8))
scale_1x32 = (
scale_fp32.repeat_interleave(block_m, dim=0)
.repeat_interleave(block_k // 32, dim=1)[:mn, : k // 32]
.contiguous()
)
# The grouped API is used with a singleton dimension to request the
# MN-major, TMA-aligned packed-UE8M0 strides, then squeezed back to the
# 2D layout required for a shared expert.
return deep_gemm.transform_sf_into_required_layout(
scale_1x32.unsqueeze(0),
mn,
k,
(1, 32),
1,
).squeeze(0)
(
self._transformed_shared_l1_weights,
self._transformed_shared_l2_weights,
) = result
def finalize_weights(self, shared_experts: DeepseekV4MLP | None = None) -> None:
backend = self._ensure_backend()
from vllm.utils.deep_gemm import _import_deep_gemm
deep_gemm = _import_deep_gemm()
if self._transformed_l1_weights is None:
self._check_runtime_supported()
w13_scale = deep_gemm.transform_sf_into_required_layout(
self._ue8m0_uint8_to_float(self.w13_weight_scale.data).contiguous(),
2 * self.intermediate_size,
self.hidden_size,
(1, 32),
self.num_local_experts,
)
w2_scale = deep_gemm.transform_sf_into_required_layout(
self._ue8m0_uint8_to_float(self.w2_weight_scale.data).contiguous(),
self.hidden_size,
self.intermediate_size,
(1, 32),
self.num_local_experts,
)
self._transformed_l1_weights, self._transformed_l2_weights = (
deep_gemm.transform_weights_for_mega_moe(
(self.w13_weight.data.view(torch.int8).contiguous(), w13_scale),
(self.w2_weight.data.view(torch.int8).contiguous(), w2_scale),
backend.transform_weights(
w13_weight=self.w13_weight.data,
w13_weight_scale=self.w13_weight_scale.data,
w2_weight=self.w2_weight.data,
w2_weight_scale=self.w2_weight_scale.data,
num_local_experts=self.num_local_experts,
hidden_size=self.hidden_size,
intermediate_size=self.intermediate_size,
)
)
# Drop the original loader-side parameters: the MegaMoE kernels only
@@ -578,7 +448,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
return
if self._transformed_shared_l1_weights is not None:
return
if not self._deep_gemm_supports_shared_experts(deep_gemm):
if not backend.supports_shared_experts(deep_gemm):
logger.warning_once(
"Disabling native MegaMoE shared-expert fusion because the "
"installed DeepGEMM Python API is older than the vLLM "
@@ -586,7 +456,8 @@ class DeepseekV4MegaMoEExperts(nn.Module):
)
self.num_shared_experts = 0
return
self._finalize_shared_expert_weights(deep_gemm, shared_experts)
self._finalize_shared_expert_weights(shared_experts)
@property
def has_fused_shared_experts(self) -> bool:
@@ -597,6 +468,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
deep_gemm = _import_deep_gemm()
backend = self._ensure_backend()
group = get_ep_group().device_group
device = torch.accelerator.current_device_index()
key = (
@@ -608,6 +480,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
self.hidden_size,
self.intermediate_size,
self.num_shared_experts if self.has_fused_shared_experts else 0,
backend.mma_type,
)
symm_buffer = self._symm_buffer_cache.get(key)
if symm_buffer is None:
@@ -621,6 +494,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
num_shared_experts=(
self.num_shared_experts if self.has_fused_shared_experts else 0
),
mma_type=backend.mma_type,
)
self._symm_buffer_cache[key] = symm_buffer
return symm_buffer
@@ -695,7 +569,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
deep_gemm = _import_deep_gemm()
symm_buffer = self.get_symm_buffer()
num_tokens = hidden_states.shape[0]
is_padding = None
if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available():
@@ -727,6 +600,8 @@ class DeepseekV4MegaMoEExperts(nn.Module):
else None,
)
backend = self._ensure_backend()
symm_buffer = self.get_symm_buffer()
shared_x_sf = None
shared_block_m = None
if self.has_fused_shared_experts:
@@ -737,7 +612,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
symm_buffer.num_max_tokens_per_rank,
num_tokens,
self.top_k,
"fp8xfp4",
backend.mma_type,
)
prepare_megamoe_inputs(
@@ -751,27 +626,28 @@ class DeepseekV4MegaMoEExperts(nn.Module):
is_padding=is_padding,
shared_x_sf=shared_x_sf,
shared_block_m=shared_block_m,
hidden_quant=backend.hidden_quant,
)
assert self._transformed_l1_weights is not None
assert self._transformed_l2_weights is not None
if self.has_fused_shared_experts:
deep_gemm.fp8_fp4_mega_moe(
y,
self._transformed_l1_weights,
self._transformed_l2_weights,
symm_buffer,
backend.run_mega_moe(
y=y,
l1_weights=self._transformed_l1_weights,
l2_weights=self._transformed_l2_weights,
symm_buffer=symm_buffer,
shared_l1_weights=self._transformed_shared_l1_weights,
shared_l2_weights=self._transformed_shared_l2_weights,
activation_clamp=activation_clamp,
fast_math=fast_math,
)
else:
deep_gemm.fp8_fp4_mega_moe(
y,
self._transformed_l1_weights,
self._transformed_l2_weights,
symm_buffer,
backend.run_mega_moe(
y=y,
l1_weights=self._transformed_l1_weights,
l2_weights=self._transformed_l2_weights,
symm_buffer=symm_buffer,
activation_clamp=activation_clamp,
fast_math=fast_math,
)
@@ -1034,9 +910,18 @@ class DeepseekV4MoE(nn.Module):
return self._forward_fused_moe(hidden_states, input_ids)
org_shape = hidden_states.shape
# The MegaMoE experts module owns the backend; resolve and assert it.
self.experts._ensure_backend()
assert self.experts._backend is not None, (
"MegaMoE backend must be resolved before routing."
)
mega_backend = self.experts._backend
# Small local padded batches favor GateLinear; 128-expert gates cross earlier.
gate_threshold = 1 if self.gate.weight.shape[0] == 128 else 16
if hidden_states.shape[0] <= gate_threshold:
if (
not mega_backend.supports_bf16_mega_gate()
or hidden_states.shape[0] <= gate_threshold
):
router_logits, _ = self.gate(hidden_states)
topk_weights, topk_ids = fused_topk_bias(
hidden_states=hidden_states,
@@ -1055,8 +940,6 @@ class DeepseekV4MoE(nn.Module):
image_sentinel_lo=self.image_sentinel_lo if bias_vl is not None else 0,
)
else:
from vllm.utils.deep_gemm import bf16_mega_gate
if mega_gate_metadata is None:
raise RuntimeError(
"MegaMoE routing metadata must be prepared once by the model."
@@ -1074,10 +957,10 @@ class DeepseekV4MoE(nn.Module):
]
fix_routing_mask = mega_gate_metadata.hash_token_mask
topk_weights, topk_ids = bf16_mega_gate(
hidden_states,
self.gate.weight,
self.n_activated_experts,
topk_weights, topk_ids = mega_backend.bf16_mega_gate(
x=hidden_states,
weight=self.gate.weight,
num_topk=self.n_activated_experts,
scoring_func=self.scoring_func,
routed_scaling_factor=self.routed_scaling_factor,
ep_rank=self.ep_rank,
+21 -19
View File
@@ -340,6 +340,26 @@ class DeepSeekV4MTP(nn.Module):
) -> torch.Tensor | None:
return self.model.compute_logits(hidden_states, spec_step_idx)
def _to_spec_layer_name(self, name: str) -> str:
"""Remap V4 `mtp.{i}.*` names to `model.layers.{num_hidden_layers + i}.*`
so that get_spec_layer_idx_from_weight_name can identify them."""
mtp_layer_idx = 0
for subname in name.split("."):
try:
# we use the first encountered integer
mtp_layer_idx = int(subname)
break
except ValueError:
continue
return name.replace(
f"mtp.{mtp_layer_idx}.",
f"model.layers.{self.config.num_hidden_layers + mtp_layer_idx}.",
)
def is_unused_checkpoint_weight(self, name: str) -> bool:
name = self._to_spec_layer_name(name)
return get_spec_layer_idx_from_weight_name(self.config, name) is None
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# Weight name remapping for checkpoint compatibility.
# Maps checkpoint weight paths to model parameter paths.
@@ -356,16 +376,6 @@ class DeepSeekV4MTP(nn.Module):
name = name.replace(old_pattern, new_pattern)
return name
def _find_mtp_layer_idx(name: str) -> int:
subnames = name.split(".")
for subname in subnames:
try:
# we return the first encountered integer
return int(subname)
except ValueError:
continue
return 0
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
("gate_up_proj", "w1", 0),
@@ -409,15 +419,7 @@ class DeepSeekV4MTP(nn.Module):
)
for name, loaded_weight in weights:
mtp_layer_idx = _find_mtp_layer_idx(name)
# V4 checkpoints store MTP weights as `mtp.{i}.*`; remap to
# `model.layers.{num_hidden_layers + i}.*` so that
# get_spec_layer_idx_from_weight_name can identify them.
name = name.replace(
f"mtp.{mtp_layer_idx}.",
f"model.layers.{self.config.num_hidden_layers + mtp_layer_idx}.",
)
name = self._to_spec_layer_name(name)
spec_layer = get_spec_layer_idx_from_weight_name(self.config, name)
if spec_layer is None:
continue
@@ -9,8 +9,15 @@ MegaMoE kernels consume.
import torch
from vllm.model_executor.layers.quantization.utils.quant_utils import (
FP8_DTYPE,
QuantKey,
kMxfp8Dynamic,
)
from vllm.triton_utils import tl, triton
_E8M0_SCALE_DTYPES = (torch.uint8, torch.float8_e8m0fnu)
@triton.jit(do_not_specialize=["num_tokens"])
def _prepare_megamoe_inputs_kernel(
@@ -48,6 +55,7 @@ def _prepare_megamoe_inputs_kernel(
GROUP_K: tl.constexpr,
BLOCK_TOPK: tl.constexpr,
SHARED_BLOCK_M: tl.constexpr,
USE_UE8M0: tl.constexpr,
) -> None:
token_id = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)
token_mask = token_id < num_tokens
@@ -69,15 +77,18 @@ def _prepare_megamoe_inputs_kernel(
amax = tl.maximum(amax, 1.0e-4)
scale = amax / 448.0
scale_bits = scale.to(tl.uint32, bitcast=True)
scale_exp = ((scale_bits >> 23) & 0xFF) + ((scale_bits & 0x7FFFFF) != 0).to(
tl.uint32
)
scale_exp = tl.minimum(tl.maximum(scale_exp, 1), 254)
rounded_scale = (scale_exp << 23).to(tl.float32, bitcast=True)
if USE_UE8M0:
scale_bits = scale.to(tl.uint32, bitcast=True)
scale_exp = ((scale_bits >> 23) & 0xFF) + ((scale_bits & 0x7FFFFF) != 0).to(
tl.uint32
)
scale_exp = tl.minimum(tl.maximum(scale_exp, 1), 254)
quant_scale = (scale_exp << 23).to(tl.float32, bitcast=True)
else:
quant_scale = scale
hidden_groups = tl.reshape(hidden, [BLOCK_M, num_groups, GROUP_K])
scaled = hidden_groups * (1.0 / rounded_scale)[:, :, None]
scaled = hidden_groups * (1.0 / quant_scale)[:, :, None]
scaled = tl.reshape(scaled, [BLOCK_M, BLOCK_K])
fp8 = scaled.to(tl.float8e4nv)
tl.store(
@@ -86,21 +97,32 @@ def _prepare_megamoe_inputs_kernel(
mask=k_mask,
)
scale_offsets = tl.arange(0, num_groups)
packed_scale = tl.sum(scale_exp << (scale_offsets[None, :] * 8), axis=1).to(
tl.int32
)
tl.store(
x_sf + token_id * x_sf_stride_m + k_block_id * x_sf_stride_k,
packed_scale,
mask=token_mask,
)
if USE_UE8M0:
scale_offsets = tl.arange(0, num_groups)
packed_scale = tl.sum(scale_exp << (scale_offsets[None, :] * 8), axis=1).to(
tl.int32
)
tl.store(
x_sf + token_id * x_sf_stride_m + k_block_id * x_sf_stride_k,
packed_scale,
mask=token_mask,
)
else:
sf_offset = tl.arange(0, num_groups)
tl.store(
x_sf
+ token_id[:, None] * x_sf_stride_m
+ k_block_id * x_sf_stride_k
+ sf_offset[None, :],
quant_scale,
mask=token_mask[:, None],
)
# DeepGEMM's SM100 shared-expert TMA loads require the activation scales
# in an MN-major layout whose row permutation depends on the MegaMoE
# scheduler's runtime BLOCK_M. Write that view while the packed UE8M0 scale
# is already resident, avoiding another kernel and temporary tensor.
if shared_x_sf is not None:
if USE_UE8M0 and shared_x_sf is not None:
m_block_id = token_id // SHARED_BLOCK_M
m_in_block = token_id % SHARED_BLOCK_M
aligned_block_m: tl.constexpr = triton.cdiv(SHARED_BLOCK_M, 128) * 128
@@ -160,6 +182,27 @@ def _prepare_megamoe_inputs_kernel(
)
def _resolve_hidden_quant(hidden_quant: QuantKey, block_k: int) -> tuple[int, bool]:
"""Map a hidden-state ``QuantKey`` to the kernel's ``(GROUP_K, USE_UE8M0)``."""
scale = hidden_quant.scale
group_shape = scale.group_shape
if (
hidden_quant.dtype != FP8_DTYPE
or not hidden_quant.symmetric
or hidden_quant.scale2 is not None
or scale.static
or not group_shape.is_per_group()
or block_k % group_shape.col != 0
or scale.dtype not in (*_E8M0_SCALE_DTYPES, torch.float32)
):
raise ValueError(
"DeepSeek V4 MegaMoE input staging requires symmetric dynamic fp8 "
f"per-group quantization with a group size dividing {block_k} and "
f"E8M0 or fp32 scales, got {hidden_quant}."
)
return group_shape.col, scale.dtype in _E8M0_SCALE_DTYPES
def prepare_megamoe_inputs(
hidden_states: torch.Tensor,
topk_weights: torch.Tensor,
@@ -171,7 +214,26 @@ def prepare_megamoe_inputs(
is_padding: torch.Tensor | None = None,
shared_x_sf: torch.Tensor | None = None,
shared_block_m: int | None = None,
hidden_quant: QuantKey = kMxfp8Dynamic,
) -> None:
"""Quantize hidden states and repack top-k routing for DeepGEMM MegaMoE.
Args:
hidden_states: Input activations of shape ``[num_tokens, hidden_dim]``.
topk_weights: Router top-k weights of shape ``[num_tokens, top_k]``.
topk_ids: Router top-k expert ids of shape ``[num_tokens, top_k]``.
x_fp8: Output buffer for the fp8-quantized hidden states.
x_sf: Output buffer for the hidden-state scale factors.
topk_idx_out: Output buffer for the repacked top-k expert ids.
topk_weights_out: Output buffer for the repacked top-k weights.
is_padding: Optional per-token mask; padded tokens are not routed.
shared_x_sf: Optional output buffer for shared-expert scale factors.
Must be given together with ``shared_block_m``.
shared_block_m: Block M used to lay out ``shared_x_sf``.
hidden_quant: Hidden-state quantization scheme. E8M0 scales are packed
four per int32 into ``x_sf``; fp32 scales are stored directly.
"""
num_tokens, hidden_size = hidden_states.shape
if num_tokens == 0:
return
@@ -180,6 +242,8 @@ def prepare_megamoe_inputs(
"DeepSeek V4 MegaMoE input staging requires hidden_size to be "
"a multiple of 128."
)
block_k = 128
group_k, use_ue8m0 = _resolve_hidden_quant(hidden_quant, block_k)
top_k = topk_ids.shape[1]
if topk_weights.shape != topk_ids.shape:
raise ValueError(
@@ -191,6 +255,11 @@ def prepare_megamoe_inputs(
"DeepSeek V4 MegaMoE shared input staging requires both "
"shared_x_sf and shared_block_m."
)
if shared_x_sf is not None and not use_ue8m0:
raise ValueError(
"DeepSeek V4 MegaMoE shared input staging currently requires "
"UE8M0-packed hidden scales."
)
if shared_x_sf is not None:
assert shared_block_m is not None
if shared_block_m <= 0:
@@ -209,7 +278,6 @@ def prepare_megamoe_inputs(
f"{required_rows}, got {shared_x_sf.shape[0]}."
)
block_k = 128
# On GB200, eight-row tiles win from 64 tokens; keep smaller batches untiled.
block_m = 8 if num_tokens >= 64 else 1
grid = (triton.cdiv(num_tokens, block_m), triton.cdiv(hidden_size, block_k))
@@ -247,8 +315,9 @@ def prepare_megamoe_inputs(
top_k,
BLOCK_M=block_m,
BLOCK_K=block_k,
GROUP_K=32,
GROUP_K=group_k,
BLOCK_TOPK=block_topk,
SHARED_BLOCK_M=shared_block_m or 1,
USE_UE8M0=use_ue8m0,
num_warps=4,
)
+5
View File
@@ -110,6 +110,11 @@ class DeepseekV4FP8Config(Fp8Config):
kv_cache_quant_algo=None,
exclude_modules=[],
group_size=16,
quantization_args=(
self.online_quantization_config.args
if self.online_quantization_config is not None
else None
),
)
return self._nvfp4_config
+9 -160
View File
@@ -26,7 +26,10 @@ from vllm.models.deepseek_v41.attention import (
DeepseekV4IndexerCache,
_replace_layer_index,
)
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
from vllm.models.deepseek_v41.common.ops import (
combine_topk_swa_indices,
dequantize_and_gather_k_cache,
)
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLAMetadata,
DeepseekV4SparseMLABackend,
@@ -129,165 +132,6 @@ def apply_pre_quantized_block_scaled_mm(
return out.to(dtype=kernel.config.out_dtype)
# ROCm sparse prefill keeps this dense combine local so AMD-specific SWA changes
# do not touch the shared DeepSeek V4 cache utilities.
_SPARSE_PREFILL_TOPK_ALIGNMENT = 128
@triton.jit
def _combine_topk_swa_indices_kernel(
combined_indices_ptr,
combined_indices_stride,
combined_lens_ptr,
topk_indices_ptr,
topk_indices_stride,
query_start_loc_ptr,
seq_lens_ptr,
gather_lens_ptr,
M,
N,
TOP_K: tl.constexpr,
COMPRESS_RATIO: tl.constexpr,
WINDOW_SIZE: tl.constexpr,
TOPK_WIDTH: tl.constexpr,
PADDED_TOP_K: tl.constexpr,
):
batch_idx = tl.program_id(0)
worker_id = tl.program_id(1)
num_workers = tl.num_programs(1)
base = tl.load(query_start_loc_ptr)
query_start = tl.load(query_start_loc_ptr + batch_idx) - base
query_end = tl.load(query_start_loc_ptr + batch_idx + 1) - base
query_len = query_end - query_start
seq_len = tl.load(seq_lens_ptr + batch_idx)
gather_len = tl.load(gather_lens_ptr + batch_idx)
start_pos = seq_len - query_len
gather_start = seq_len - gather_len
for token_idx in range(query_start + worker_id, query_end, num_workers):
token_idx_in_query = token_idx - query_start
pos = start_pos + token_idx_in_query
topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K)
swa_len = tl.minimum(pos + 1, WINDOW_SIZE)
topk_offset = tl.arange(0, PADDED_TOP_K)
topk_mask = topk_offset < topk_len
safe_topk_offset = tl.where(topk_offset < TOPK_WIDTH, topk_offset, 0)
topk_indices = tl.load(
topk_indices_ptr + token_idx * topk_indices_stride + safe_topk_offset,
mask=topk_mask,
other=-1,
)
valid_topk = (topk_indices >= 0) & (topk_indices < N)
topk_indices = tl.where(valid_topk, topk_indices + M * batch_idx, -1)
tl.store(
combined_indices_ptr + token_idx * combined_indices_stride + topk_offset,
topk_indices,
mask=topk_mask,
)
swa_offset = tl.arange(0, WINDOW_SIZE)
tl.store(
combined_indices_ptr
+ token_idx * combined_indices_stride
+ topk_len
+ swa_offset,
M * batch_idx + N + swa_offset + pos - swa_len + 1 - gather_start,
mask=swa_offset < swa_len,
)
tl.store(combined_lens_ptr + token_idx, topk_len + swa_len)
def combine_topk_swa_indices(
topk_indices: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
gather_lens: torch.Tensor,
window_size: int,
compress_ratio: int,
topk: int,
M: int,
N: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Combine compressed-attention and sliding-window indices with Torch.
The Triton implementation inherited from DeepSeek V4 launches a
two-dimensional grid with 128 workers per request. On gfx950 it can issue
an out-of-bounds access for V4.1's mixed prefill metadata (including the
synthetic mixed-token warmup). This path is prefill-only and the tensors
are small, so use ordinary Torch indexing until a gfx950-safe fused kernel
is available.
"""
topk_indices = topk_indices.reshape(topk_indices.shape[0], -1).contiguous()
num_tokens = topk_indices.shape[0]
combined_topk = (
(topk + window_size + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1)
// _SPARSE_PREFILL_TOPK_ALIGNMENT
* _SPARSE_PREFILL_TOPK_ALIGNMENT
)
combined_indices = torch.full(
(num_tokens, combined_topk),
fill_value=-1,
dtype=torch.int32,
device=topk_indices.device,
)
combined_lens = torch.empty(
num_tokens, dtype=torch.int32, device=topk_indices.device
)
# query_start_loc may have a non-zero base for a narrowed mixed batch.
query_lens = query_start_loc[1:] - query_start_loc[:-1]
req_ids = torch.repeat_interleave(
torch.arange(seq_lens.shape[0], device=seq_lens.device), query_lens
)
query_starts = query_start_loc[:-1] - query_start_loc[0]
token_offsets = torch.arange(num_tokens, device=seq_lens.device) - (
torch.repeat_interleave(query_starts, query_lens)
)
positions = seq_lens[req_ids] - query_lens[req_ids] + token_offsets
logical_topk_width = min(topk, topk_indices.shape[1])
topk_lens = torch.minimum(
(positions + 1) // compress_ratio,
torch.full_like(positions, logical_topk_width),
).clamp_min(0)
topk_offsets = torch.arange(logical_topk_width, device=seq_lens.device)
topk_mask = topk_offsets[None, :] < topk_lens[:, None]
topk_values = topk_indices[:, :logical_topk_width].to(torch.int32)
topk_valid = topk_mask & (topk_values >= 0) & (topk_values < N)
combined_indices[:, :logical_topk_width] = torch.where(
topk_valid,
topk_values + (M * req_ids).to(torch.int32)[:, None],
-1,
)
swa_lens = torch.minimum(
positions + 1, torch.full_like(positions, window_size)
).clamp_min(0)
swa_offsets = torch.arange(window_size, device=seq_lens.device)
swa_mask = swa_offsets[None, :] < swa_lens[:, None]
swa_columns = topk_lens[:, None] + swa_offsets[None, :]
gather_starts = seq_lens - gather_lens
swa_values = (
M * req_ids[:, None]
+ N
+ swa_offsets[None, :]
+ positions[:, None]
- swa_lens[:, None]
+ 1
- gather_starts[req_ids, None]
).to(torch.int32)
rows = torch.arange(num_tokens, device=seq_lens.device)[:, None].expand_as(
swa_columns
)
flat_dst = rows[swa_mask] * combined_topk + swa_columns[swa_mask]
combined_indices.view(-1).index_copy_(0, flat_dst, swa_values[swa_mask])
combined_lens.copy_((topk_lens + swa_lens).to(torch.int32))
return combined_indices, combined_lens
@triton.jit
def _compute_topk_lens_kernel(
topk_lens_ptr,
@@ -1387,6 +1231,9 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
gather_lens = swa_metadata.prefill_gather_lens
assert seq_lens is not None
assert gather_lens is not None
# CPU copy, so sizing the gather grid from it does not sync.
seq_lens_cpu = swa_metadata.prefill_seq_lens_cpu
assert seq_lens_cpu is not None
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
query_start_loc = swa_metadata.query_start_loc
@@ -1438,6 +1285,8 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
block_size=attn_metadata.block_size // self.compress_ratio,
offset=0,
use_fnuz=False,
max_gather_len=int(seq_lens_cpu[chunk_start:chunk_end].max())
// self.compress_ratio,
)
swa_block_table = swa_metadata.block_table[num_decodes:]
+28
View File
@@ -686,6 +686,34 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
)
return self._o_proj(attn_out, positions)
def forward_kv(self, positions: torch.Tensor, hidden_states: torch.Tensor) -> None:
"""Write only the KV ``forward`` writes (SWA KV, compressed KV, index K),
skipping wq_b, the indexer's top-k and attention."""
attn_metadata = get_forward_context().attn_metadata
qr_kv, kv_score, _ = self._run_parallel_input_projections(hidden_states)
_, _, kv = self._split_qkv_and_norm(qr_kv)
if isinstance(attn_metadata, dict):
# The KV half of _fused_qnorm_rope_kv_insert, bit for bit, without
# the unused query; same as dspark's _insert_context_kv.
cache = self.swa_cache_layer.kv_cache
torch.ops._C.fused_deepseek_v4_kv_rope_insert(
kv,
cache,
cast(Any, attn_metadata[self.swa_cache_layer.prefix]).slot_mapping,
positions,
self.rotary_emb.cos_sin_cache,
self.swa_cache_layer.block_size,
self._flashinfer_fp8_kv_scale
if cache.dtype == torch.float8_e4m3fn
else None,
self.kv_mxfp8,
)
if self.compressor is not None:
latent = self.compressor(kv_score, positions)
self.compressor.insert_cache(latent, positions, self.rotary_emb)
if self.indexer is not None and self.indexer.owns_k:
self.indexer._produce_k(latent, positions, self.indexer_rotary_emb)
def bind_gemm_rs(self) -> None:
"""Fuse ``wo_b`` with the sequence-parallel TP reduce-scatter.
+214 -11
View File
@@ -62,9 +62,16 @@ from vllm.distributed.device_communicators.shm_broadcast import (
from vllm.distributed.parallel_state import GroupCoordinator
from vllm.forward_context import get_forward_context, is_forward_context_available
from vllm.logger import init_logger
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
from vllm.model_executor.utils import set_weight_attrs
from vllm.models.deepseek_v41.common.ops.query_quant import (
can_fuse_query_quant,
mxfp8_scale_bytes,
mxfp8_scale_offset,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.platform_utils import is_uva_available
@@ -72,6 +79,10 @@ from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
logger = init_logger(__name__)
# Per-rank token slot from which the Engram DP exchange switches from peer
# reads to all-to-all.
ENGRAM_A2A_MIN_SLOT = 128
# Cache value for tokens that take no part in an n-gram (image spans).
DEAD_ID = -1
@@ -644,8 +655,10 @@ def _engram_lookup_kernel(
BLOCK_R: tl.constexpr,
GRID,
SORTED: tl.constexpr if _SORTED_IS_CONSTEXPR else None, # type: ignore[valid-type]
PACKED: tl.constexpr,
OUT_STRIDE: tl.constexpr,
):
"""Gather fp8 rows, apply their ue8m0 block scales, write bf16.
"""Gather FP8 rows as packed values/scales or dequantized BF16.
Only this rank's heads are read; padded heads write zeros for all-gather.
`weight`/`scales` may address pinned host memory through UVA. If SORTED,
@@ -684,13 +697,28 @@ def _engram_lookup_kernel(
mask=owned[:, None],
other=0,
)
# ue8m0 is a power of two, so its byte *is* the fp32 exponent field.
scale = (scale.to(tl.int32) << 23).to(tl.float32, bitcast=True)
tl.store(
out + dst[:, None] * DIM + cols[None, :],
(values.to(tl.float32) * scale).to(tl.bfloat16),
mask=valid[:, None],
)
if PACKED:
width: tl.constexpr = DIM + DIM // QUANT_BLOCK
dst = dst.to(tl.int64)
dst = dst // LOCAL_HEADS * OUT_STRIDE + dst % LOCAL_HEADS * width
tl.store(
out + dst[:, None] + cols[None, :],
values.to(tl.uint8, bitcast=True),
mask=valid[:, None],
)
tl.store(
out + dst[:, None] + DIM + scale_cols[None, :],
scale,
mask=valid[:, None] & (cols[None, :] % QUANT_BLOCK == 0),
)
else:
# ue8m0 is a power of two, so its byte *is* the fp32 exponent field.
scale = (scale.to(tl.int32) << 23).to(tl.float32, bitcast=True)
tl.store(
out + dst[:, None] * DIM + cols[None, :],
(values.to(tl.float32) * scale).to(tl.bfloat16),
mask=valid[:, None],
)
def engram_head_shard_rank() -> int:
@@ -1082,7 +1110,7 @@ class ParallelEngramEmbedding(nn.Module):
def lookup(
self, indices: torch.Tensor, out: torch.Tensor, background: bool = False
) -> None:
"""Look up local heads of [T, heads] into [T, local_heads, dim] bf16.
"""Look up local heads into BF16, or packed FP8 bytes followed by scales.
`background` limits the grid to leave SMs for concurrent work.
"""
@@ -1131,6 +1159,8 @@ class ParallelEngramEmbedding(nn.Module):
BLOCK_R=16,
GRID=grid,
SORTED=sort,
PACKED=out.dtype == torch.uint8,
OUT_STRIDE=out.stride(0),
)
def forward(self, indices: torch.Tensor) -> torch.Tensor:
@@ -1275,7 +1305,7 @@ def _engram_select_rows(
) -> None:
"""Copy one token window out of a rank-major gathered buffer.
Both gathers land rank-major ([rank][token][local width]); this walks the
Both gathers land rank-major (`[rank][token][local width]`); this walks the
window the rank keeps and lays its ranks out side by side as width.
"""
if output.numel() == 0:
@@ -1311,6 +1341,175 @@ def _gather_engram_rows(staged: torch.Tensor, num_tokens: int) -> torch.Tensor:
return rows
@triton.jit(do_not_specialize=["num_tokens"])
def _engram_unpack_fp8_kernel(
packed,
values,
scales,
num_tokens,
values_stride,
scales_stride,
HEADS: tl.constexpr,
LOCAL_HEADS: tl.constexpr,
LAYERS: tl.constexpr,
RANK: tl.constexpr,
DIM: tl.constexpr,
BLOCK: tl.constexpr,
PEER: tl.constexpr,
):
"""Split `[rank][token][layer][local head]` packed rows into MXFP8 values and
F8_128x4 scales, one layer per grid column; `packed` holds per-rank
pointers if PEER. Scales past `num_tokens` zero-pad the 128-row tile.
"""
row = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
layer = tl.program_id(1).to(tl.int64)
token, head = row // HEADS, row % HEADS
if PEER:
src = tl.load(packed + head // LOCAL_HEADS)
src = tl.multiple_of(src, DIM // 32).to(tl.pointer_type(tl.uint8))
source = RANK * num_tokens + token
else:
src = packed
source = head // LOCAL_HEADS * num_tokens + token
source = (source * LAYERS + layer) * LOCAL_HEADS + head % LOCAL_HEADS
# Packed rows are only scale-width aligned.
src += tl.multiple_of(source * (DIM + DIM // 32), DIM // 32)
valid = token < num_tokens
cols = tl.arange(0, DIM)
data = tl.load(src[:, None] + cols[None, :], mask=valid[:, None], other=0)
values += layer * values_stride + row * DIM
tl.store(values[:, None] + cols[None, :], data, mask=valid[:, None])
scale_cols = tl.arange(0, DIM // 32)
scale = tl.load(
src[:, None] + DIM + scale_cols[None, :], mask=valid[:, None], other=0
)
group = head[:, None] * (DIM // 32) + scale_cols[None, :]
offset = mxfp8_scale_offset(token[:, None], group, HEADS * DIM // 32)
tl.store(scales + layer * scales_stride + offset, scale)
class EngramBatch(nn.Module):
"""Stage every Engram layer's WKV input as MXFP8 with one exchange.
A module so the model owns the peer exchange's pointer buffers.
"""
def __init__(self, layers: list["Engram"], max_tokens: int) -> None:
super().__init__()
first = layers[0].layer_hash_index
hash_indices = [layer.layer_hash_index for layer in layers]
assert hash_indices == list(range(first, first + len(layers)))
self.layers = layers
table = layers[0].embed_tokens
device = layers[0].staged_rows.device
self.packed_rows = torch.empty(
max_tokens * table.dp_size,
len(layers),
table.part_n_hash_cols,
table.dim + table.dim // 32,
dtype=torch.uint8,
device=device,
)
width = table.n_hash_cols * table.dim
self.fp8_values = torch.empty(
len(layers), max_tokens, width, dtype=torch.uint8, device=device
)
self.fp8_scales = torch.empty(
len(layers),
mxfp8_scale_bytes(max_tokens, width),
dtype=torch.uint8,
device=device,
)
max_peer_slot = min(max_tokens, ENGRAM_A2A_MIN_SLOT - 1)
self.peer_exchange = None
if table.cpu_offload:
from vllm.models.deepseek_v41.nvidia.ops.engram_peer import (
EngramPeerExchange,
)
self.peer_exchange = EngramPeerExchange.create(layers, max_peer_slot)
for layer in layers:
# Owned by the model; keep it out of each layer's submodules.
object.__setattr__(layer, "_batch", self)
# The layers read this batch's staging instead of their BF16 rows.
layer.staged_rows = layer.staged_rows.new_empty(
(0, *layer.staged_rows.shape[1:])
)
@classmethod
def create(cls, layers: list["Engram"], max_tokens: int) -> "EngramBatch | None":
"""Batch DP-sharded tables whose WKV takes FlashInfer MXFP8 input."""
if not layers:
return None
table = layers[0].embed_tokens
if (
table.dp_size == 1
or table.tp_size > 1
or table.dim % 128
or get_current_vllm_config().lora_config is not None
or not can_fuse_query_quant([layer.wkv for layer in layers])
):
return None
return cls(layers, max_tokens)
def prepare_embeddings(self, hashes: torch.Tensor) -> None:
"""Stage every layer's WKV input before the decoder layers.
DP-sharded tables decide on the group's slot, so every rank agrees.
"""
slot = engram_gathered_num_tokens()
peer = self.peer_exchange is not None and slot < ENGRAM_A2A_MIN_SLOT
self._stage(hashes if peer else gather_engram_hashes(hashes), slot, peer)
@eager_break_during_capture
def _stage(self, hashes: torch.Tensor, slot: int, peer: bool) -> None:
if slot == 0:
return
if peer:
assert self.peer_exchange is not None
rows = self.peer_exchange.exchange(hashes, slot)
rank = self.peer_exchange.dp_rank
else:
rows, rank = self.packed_rows[: hashes.shape[0]], 0
for index, layer in enumerate(self.layers):
layer.embed_tokens.lookup(
hashes[:, layer.layer_hash_index], rows[:, index]
)
group = get_engram_dp_group()
assert group is not None
sent, rows = rows, torch.empty_like(rows)
torch.distributed.all_to_all_single(rows, sent, group=group.device_group)
table = self.layers[0].embed_tokens
heads = table.n_hash_cols
grid = (triton.cdiv(slot, 128) * 128 * heads // 16, len(self.layers))
_engram_unpack_fp8_kernel[grid](
rows,
self.fp8_values,
self.fp8_scales,
slot,
self.fp8_values.stride(0),
self.fp8_scales.stride(0),
HEADS=heads,
LOCAL_HEADS=table.part_n_hash_cols,
LAYERS=len(self.layers),
RANK=rank,
DIM=table.dim,
BLOCK=16,
PEER=peer,
)
def wkv_input(self, layer: "Engram", num_tokens: int) -> QuantizedActivation:
index = layer.layer_hash_index - self.layers[0].layer_hash_index
values = self.fp8_values[index, :num_tokens].view(torch.float8_e4m3fn)
return QuantizedActivation(
values,
self.fp8_scales[index, : mxfp8_scale_bytes(num_tokens, values.shape[1])],
torch.bfloat16,
values.shape,
kMxfp8Dynamic,
)
class Engram(nn.Module):
"""Writes an n-gram lookup into the residual stream, gated by how well it
matches that stream.
@@ -1323,6 +1522,7 @@ class Engram(nn.Module):
_prefetch_stream: torch.cuda.Stream | None = None
_prefetch_done: torch.cuda.Event | None = None
_batch: EngramBatch | None = None
def __init__(
self,
@@ -1482,7 +1682,10 @@ class Engram(nn.Module):
"""hidden_states: [T, hc_mult, dim]; hash_ids: [T, n_hash_cols] (all
tokens, pre sequence-parallel shard); token_mask: [T], False shuts
the gate so those positions pass through untouched."""
kv = self.wkv(self.embed(hash_ids).flatten(-2))
if self._batch is not None:
kv = self.wkv(self._batch.wkv_input(self, hash_ids.shape[0]))
else:
kv = self.wkv(self.embed(hash_ids).flatten(-2))
num_kv_tokens = hash_ids.shape[0]
assert token_mask is None or token_mask.shape == (num_kv_tokens,)
if self.use_sequence_parallel:
@@ -33,7 +33,7 @@ from vllm.model_executor.warmup.jit_warmup_triton_helper import (
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.import_utils import has_cutedsl
from vllm.utils.math_utils import next_power_of_2
from vllm.utils.math_utils import cdiv, next_power_of_2
# Per-token byte width of the two paged fp8 records. Both put a page's whole
# data region ahead of its whole scale region, so ``k_cache.shape[-1]`` -- the
@@ -436,6 +436,95 @@ def _dequantize_and_gather_k_kernel(
tl.store(output_row_ptr + bf16_output_offset + chunk_offsets, bf16_vals)
@triton.jit
def _dequantize_and_gather_k_one_pass_kernel(
out_ptr,
out_stride0,
out_stride1,
k_cache_ptr,
seq_lens_ptr,
block_table_ptr,
offset,
gather_lens_ptr,
# Constants
max_blocks_per_seq: tl.constexpr,
fp8_dim: tl.constexpr, # 448
bf16_dim: tl.constexpr, # 64
scale_dim: tl.constexpr, # 8
quant_block: tl.constexpr, # 64 (quantization block size)
cache_block_size: tl.constexpr, # 64 or 128 (paged cache block size)
token_data_size: tl.constexpr, # 576 bytes per token data
block_stride: tl.constexpr, # total bytes per block (padded) int32
output_dim: tl.constexpr, # 512
fp8_max: tl.constexpr,
n_quant_blocks: tl.constexpr, # 7 real blocks; the per-block form only
use_fnuz: tl.constexpr = False,
):
"""``_dequantize_and_gather_k_kernel`` with the token read in one tile.
The seven quantization blocks tile the fp8 region exactly, so the per-block
form's bounds never bite and its twenty-two memory operations per token
reduce to four. Selected on ROCm; CUDA keeps the per-block kernel.
"""
batch_idx = tl.program_id(0)
worker_id = tl.program_id(1)
num_workers = tl.num_programs(1)
seq_len = tl.load(seq_lens_ptr + batch_idx)
if gather_lens_ptr is not None: # noqa: SIM108
gather_len = tl.load(gather_lens_ptr + batch_idx)
else:
gather_len = seq_len
start_pos = seq_len - gather_len
for i in range(worker_id, gather_len, num_workers):
pos = start_pos + i
block_in_seq = pos // cache_block_size
pos_in_block = pos % cache_block_size
block_table_row_ptr = block_table_ptr + batch_idx * max_blocks_per_seq
physical_block_idx = tl.load(block_table_row_ptr + block_in_seq)
cache_block_ptr = k_cache_ptr + physical_block_idx.to(tl.int64) * block_stride
token_fp8_ptr = cache_block_ptr + pos_in_block * token_data_size
token_bf16_ptr = token_fp8_ptr + fp8_dim
token_scale_ptr = (
cache_block_ptr
+ cache_block_size * token_data_size
+ pos_in_block * scale_dim
)
output_row_ptr = out_ptr + batch_idx * out_stride0 + (offset + i) * out_stride1
# The tile is scale_dim * quant_block = 512 against an fp8 region of
# 448: the tail reads the token's own bf16 bytes, is scaled by a scale
# nothing reads, and is dropped by the store mask.
tile_dim: tl.constexpr = scale_dim * quant_block
tl.static_assert(tile_dim <= token_data_size, "tile outruns the token")
fp8_offsets = tl.arange(0, tile_dim)
x_uint8 = tl.load(token_fp8_ptr + fp8_offsets)
if use_fnuz:
x_fp8 = x_uint8.to(tl.float8e4b8, bitcast=True)
else:
x_fp8 = x_uint8.to(tl.float8e4nv, bitcast=True)
encoded_scale = tl.load(token_scale_ptr + tl.arange(0, scale_dim))
scale = tl.exp2(encoded_scale.to(tl.float32) - 127.0) # UE8M0
tiles = tl.reshape(x_fp8.to(tl.float32), (scale_dim, quant_block))
x_dequant = tl.reshape(tiles * tl.reshape(scale, (scale_dim, 1)), (tile_dim,))
tl.store(
output_row_ptr + fp8_offsets,
x_dequant.to(tl.bfloat16),
mask=fp8_offsets < fp8_dim,
)
bf16_cache_ptr = token_bf16_ptr.to(tl.pointer_type(tl.bfloat16))
bf16_offsets = tl.arange(0, bf16_dim)
tl.store(
output_row_ptr + fp8_dim + bf16_offsets,
tl.load(bf16_cache_ptr + bf16_offsets),
)
@triton.jit
def _dequantize_and_gather_k_mxfp8_kernel(
out_ptr,
@@ -566,6 +655,22 @@ def _dequantize_and_gather_k_nvfp4_kernel(
tl.store(output_row_ptr + d, dequant.to(tl.bfloat16))
# The per-token loop is a chain of dependent loads, so the grid has to hold
# enough chains in flight to cover the latency. The cap binds above 64k tokens,
# where a worker takes more than the eight steps this aims for.
_GATHER_STEPS_PER_WORKER = 8
_GATHER_MIN_WORKERS = 128
_GATHER_MAX_WORKERS = 8192
def gather_num_workers(max_gather_len: int | None) -> int:
"""Grid width for a gather of at most ``max_gather_len`` tokens."""
if max_gather_len is None:
return _GATHER_MIN_WORKERS
workers = cdiv(max_gather_len, _GATHER_STEPS_PER_WORKER)
return max(_GATHER_MIN_WORKERS, min(_GATHER_MAX_WORKERS, workers))
def dequantize_and_gather_k_cache_triton(
# [num_reqs, max_num_tokens, head_size]
out: torch.Tensor,
@@ -580,6 +685,7 @@ def dequantize_and_gather_k_cache_triton(
block_size: int,
offset: int,
use_fnuz: bool = False,
max_gather_len: int | None = None,
) -> None:
num_reqs = seq_lens.shape[0]
NUM_WORKERS = 128
@@ -633,7 +739,13 @@ def dequantize_and_gather_k_cache_triton(
FP8_MAX = 448.0
TOKEN_DATA_SIZE = TOKEN_FP8_DIM + TOKEN_BF16_DIM * 2
_dequantize_and_gather_k_kernel[(num_reqs, NUM_WORKERS)](
gather_workers = gather_num_workers(max_gather_len)
kernel = (
_dequantize_and_gather_k_one_pass_kernel
if current_platform.is_rocm()
else _dequantize_and_gather_k_kernel
)
kernel[(num_reqs, gather_workers)](
out,
out.stride(0),
out.stride(1),
@@ -671,6 +783,7 @@ def dequantize_and_gather_k_cache(
block_size: int,
offset: int,
use_fnuz: bool = False,
max_gather_len: int | None = None,
) -> None:
"""Dequantize and gather a paged DSv4 K cache.
@@ -711,6 +824,7 @@ def dequantize_and_gather_k_cache(
block_table,
block_size,
offset,
max_gather_len=max_gather_len,
use_fnuz=use_fnuz,
)
@@ -975,7 +1089,8 @@ class CombineTopkSwaIndicesKernel(
token_idx_in_query = token_idx - query_start
pos = start_pos + token_idx_in_query
if COMPRESS_RATIO > 0:
topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K)
# Warmup batches can put pos below zero; keep the length >= 0.
topk_len = tl.maximum(tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K), 0)
else:
# SWA-only layers pass TOP_K=0; skip the division entirely
# (integer div by constexpr 0 is UB and yields garbage, which
@@ -986,7 +1101,7 @@ class CombineTopkSwaIndicesKernel(
# start (SWA bounded replay), so the window cannot start before
# the gathered buffer does.
swa_start = tl.maximum(swa_start, gather_start)
swa_len = pos - swa_start + 1
swa_len = tl.maximum(pos - swa_start + 1, 0)
offset = tl.arange(0, PADDED_TOP_K)
mask = offset < topk_len
@@ -994,9 +1109,12 @@ class CombineTopkSwaIndicesKernel(
topk_indices_ptr + token_idx * topk_indices_stride + offset,
mask=mask,
)
# A failed (-1) or out-of-pool candidate stays -1 instead of landing
# in the previous request's rows or this request's SWA rows.
valid = (topk_indices >= 0) & (topk_indices < N)
tl.store(
combined_indices_ptr + token_idx * combined_indices_stride + offset,
topk_indices + M * batch_idx,
tl.where(valid, topk_indices + M * batch_idx, -1),
mask=mask,
)
# Index into gathered buffer: N + (position - gather_start)
@@ -12,6 +12,8 @@ per-step shuffle.
import torch
from vllm.model_executor.model_loader.weight_utils import composed_weight_loader
HEAD_DIM = 512
Q_CHUNK = 16
O_CHUNK = 32
@@ -60,27 +62,13 @@ def _bytes_view(t: torch.Tensor) -> torch.Tensor:
return t.view(torch.uint8) if t.element_size() == 1 else t
def permute_wq_b_(
weight: torch.Tensor, weight_scale: torch.Tensor, num_local_heads: int
) -> None:
"""Permute an MXFP8 ``wq_b`` shard's rows and per-row scales, in place."""
head_dim = weight.shape[0] // num_local_heads
perm = q_fused_permutation(num_local_heads, head_dim).to(weight.device)
for t in (weight, weight_scale):
b = _bytes_view(t)
b.copy_(b[perm])
def permute_on_load(param: torch.Tensor, perm: torch.Tensor, dim: int) -> None:
"""Make ``param``'s weight loader gather the loaded shard by ``perm``."""
def gather(t: torch.Tensor) -> torch.Tensor:
return _bytes_view(t).index_select(dim, perm.to(t.device)).view(t.dtype)
def permute_wo_a_(
weight: torch.Tensor,
weight_scale: torch.Tensor,
heads_per_group: int = WV_GROUP_SIZE,
) -> None:
"""Permute an MXFP8 ``wo_a`` shard's input columns and scales, in place."""
head_dim = weight.shape[1] // heads_per_group
perm = o_fused_permutation(heads_per_group, head_dim).to(weight.device)
w = _bytes_view(weight)
w.copy_(w[:, perm])
chunk_perm = o_fused_chunk_permutation(heads_per_group, head_dim)
s = _bytes_view(weight_scale)
s.copy_(s[:, chunk_perm.to(weight.device)])
param.weight_loader = composed_weight_loader( # type: ignore[attr-defined]
param.weight_loader, # type: ignore[attr-defined]
gather,
)
@@ -21,6 +21,18 @@ def _norm_row(x, weight, row, stride, eps, SIZE: tl.constexpr, BLOCK: tl.constex
return values * rrms * w
@triton.jit
def mxfp8_scale_offset(row, group, GROUPS: tl.constexpr):
"""F8_128x4: [row/128, group/4, row%32, row%128/32, group%4]."""
offset = (row // 128 * triton.cdiv(GROUPS, 4) + group // 4) * 512
return offset + row % 32 * 16 + row % 128 // 32 * 4 + group % 4
def mxfp8_scale_bytes(tokens: int, width: int) -> int:
"""Bytes of F8_128x4 scales for `tokens` rows of `width` MXFP8 values."""
return triton.cdiv(tokens, 128) * 128 * triton.cdiv(width // 32, 4) * 4
@triton.jit(do_not_specialize=["num_tokens"])
def _q_kv_norm_quant_kernel(
q,
@@ -68,14 +80,7 @@ def _q_kv_norm_quant_kernel(
sf = tl.full((BLOCK // 32,), 0, tl.uint32)
padded_groups: tl.constexpr = triton.cdiv(Q_SIZE // 32, 4) * 4
sf = tl.where(groups < Q_SIZE // 32, sf, 0)
# F8_128x4: [row/128, group/4, row%32, row%128/32, group%4].
offsets = (
row // 128 * (128 * padded_groups)
+ groups // 4 * 512
+ row % 32 * 16
+ row % 128 // 32 * 4
+ groups % 4
)
offsets = mxfp8_scale_offset(row, groups, Q_SIZE // 32)
tl.store(scales + offsets, sf, groups < padded_groups)
elif row < num_tokens:
y = _norm_row(kv, kvw, row, kv_stride, eps, KV_SIZE, BLOCK)
@@ -99,9 +104,8 @@ def fused_q_kv_rmsnorm_quant(
qo = torch.empty(qr.shape, dtype=torch.float8_e4m3fn, device=qr.device)
kvo = torch.empty(kv.shape, dtype=kv.dtype, device=kv.device)
padded_tokens = triton.cdiv(tokens, 128) * 128
padded_groups = triton.cdiv(q_size // 32, 4) * 4
scales = torch.empty(
padded_tokens * padded_groups, dtype=torch.uint8, device=qr.device
mxfp8_scale_bytes(tokens, q_size), dtype=torch.uint8, device=qr.device
)
if tokens:
block = triton.next_power_of_2(max(q_size, kv_size))
@@ -94,8 +94,6 @@ class DeepseekV4VLEncoderCudaGraphMixin:
grid = grid.tolist()
return [[int(v) for v in row] for row in grid]
_encoder_cg_pad_totals: dict[int, int] = {}
# -- SupportsEncoderCudaGraph protocol --
def get_encoder_cudagraph_config(self) -> EncoderCudaGraphConfig:
@@ -129,24 +127,13 @@ class DeepseekV4VLEncoderCudaGraphMixin:
"cudagraph_mm_encoder."
)
pad_totals = self._encoder_cg_pad_totals
def pad_cu_seqlens(dst: torch.Tensor, src: torch.Tensor) -> None:
# Varlen attention requires cu_seqlens[-1] to equal the number of
# rows actually passed in. The captured buffers are sized for the
# full token budget, so a smaller real batch is completed with one
# trailing padding sequence; declaring fewer rows than the buffer
# holds is undefined behaviour and returns NaN on FlashAttn.
total = pad_totals.get(dst.data_ptr())
if total is None:
raise RuntimeError(
"cu_seqlens replay buffer was not registered at capture "
"time; the manager must replay into the capture-time "
"buffers."
)
# Zero-length padding (same as Qwen): tail slots repeat the last
# real offset, so FlashAttn schedules no work for padding rows.
n = min(src.shape[0], dst.shape[0])
dst[:n].copy_(src[:n])
dst[n:] = total
if n < dst.shape[0]:
dst[n:] = src[-1] if n else 0
return EncoderCudaGraphConfig(
modalities=["image"],
@@ -268,8 +255,8 @@ class DeepseekV4VLEncoderCudaGraphMixin:
max_seqlen_override=total_patches,
cached=False,
)
# Spare cu_seqlens slots let replay append a padding sequence that
# covers the rows a smaller real batch does not fill.
# Spare cu_seqlens slots: replay pads smaller real batches with
# zero-length sequences (tail slots repeat the last real offset).
real_cu = metadata.pop("cu_seqlens")
cu_seqlens = torch.full(
(max_batch_size + 2,), total_patches, dtype=torch.int32, device=device
@@ -278,8 +265,6 @@ class DeepseekV4VLEncoderCudaGraphMixin:
merge = build_packed_merge_metadata(grids, r, device=device, dtype=dtype)
self._encoder_cg_pad_totals[cu_seqlens.data_ptr()] = total_patches
return EncoderCudaGraphCaptureInputs(
values={
"patches": patches,
@@ -303,7 +288,7 @@ class DeepseekV4VLEncoderCudaGraphMixin:
patches = patches.to(dtype)
# Unpadded: the manager zero-pads patches/cos/sin/merge buffers, and
# pad_cu_seqlens appends the padding sequence covering the tail rows.
# pad_cu_seqlens pads the tail with zero-length sequences.
metadata = build_packed_vit_metadata(
vit_grid,
rope_dim=self.vision.rope_dim,
@@ -2,63 +2,126 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Decoder-side SWA bounded replay: running the replay layers on their batch.
The layers past the last KV-source layer own nothing but sliding-window KV, so
in eager prefill steps they run on each request's last ``window`` rows only.
Once the last KV-source layer has written every row's KV, it and the layers past
it (which own only SWA KV) run on each request's last ``window`` rows only.
``DeepseekV41ModelState`` prepares those rows as a sub-batch with attention
metadata and a forward context of its own, like a microbatch;
``DecoderReplayLayers`` gathers the layer inputs by its rows, runs the layers
under that context and scatters the outputs back to batch rows. Steps that run
in a CUDA graph keep the layers on the whole batch, inside the graph.
under that context and scatters the outputs back to batch rows. FULL graphs and
small PIECEWISE ones keep the layers on the whole batch; larger PIECEWISE graphs
break out to the replay batch, which may run in a graph of its own
(decoder_replay_cudagraph.py).
"""
from collections.abc import Callable
from dataclasses import dataclass
import torch
from vllm.forward_context import ForwardContext, override_forward_context
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.forward_context import (
ForwardContext,
get_forward_context,
in_piecewise_cudagraph,
override_forward_context,
)
from vllm.model_executor.layers.fused_moe.moe_output import MoEOutput
@dataclass
class ReplayBatch:
"""One forward's replay batch; ``run_graph`` is set when it runs in a graph."""
rows: torch.Tensor
forward_context: ForwardContext
run_graph: Callable[..., tuple[torch.Tensor, ...]] | None = None
class DecoderReplayLayers:
"""Runs the replay layers on the step's replay batch.
``run_layers`` takes a batch's layer inputs and returns its per-row
outputs. ``row_buffers`` hold per-row results the source layer's indexer
publishes for the layers after it; they are compacted to the replay rows
in place.
``run_layers`` takes a batch's layer inputs and returns its per-row outputs;
``write_batch_kv`` takes them too and writes the first replay layer's KV for
every row. ``metadata_prefixes`` are the attention metadata keys the layers
read, so the replay batch builds only those. ``first_swa_prefix`` keys the
first replay layer's SWA metadata, built with the batch's window starts.
"""
def __init__(
self,
window: int,
run_layers: Callable[..., tuple[torch.Tensor, ...]],
row_buffers: list[torch.Tensor],
write_batch_kv: Callable[..., None],
metadata_prefixes: set[str],
first_swa_prefix: str,
) -> None:
self.window = window
self.run_layers = run_layers
self.row_buffers = row_buffers
# The replay batch, set by the model state every step: its rows of the
# batch and its forward context. None runs the layers on the batch.
self.rows: torch.Tensor | None = None
self.forward_context: ForwardContext | None = None
self.write_batch_kv = write_batch_kv
self.metadata_prefixes = metadata_prefixes
self.first_swa_prefix = first_swa_prefix
# Set by the model state every step; None runs the layers on the batch.
self.replay_batch: ReplayBatch | None = None
# Set by the model state with replay graphs: PIECEWISE model graphs of
# this many tokens or more break out to the replay batch.
self.trim_threshold: int | None = None
self._break_outputs: list[torch.Tensor] | None = None
def __call__(
self, hidden_states: torch.Tensor | MoEOutput, *states: torch.Tensor | None
) -> tuple[torch.Tensor, ...]:
rows = self.rows
if rows is None:
if self.uses_replay_batch():
# Outside the break, so a PIECEWISE graph captures it.
self.write_batch_kv(hidden_states, *states)
if in_piecewise_cudagraph():
return self._run_in_graph_break(hidden_states, *states)
return self._run(hidden_states, *states)
def uses_replay_batch(self) -> bool:
"""Whether this forward uses the replay batch: in a PIECEWISE graph by its
size, fixed at capture (no replay batch is set then); else if one is set."""
if in_piecewise_cudagraph():
batch_descriptor = get_forward_context().batch_descriptor
assert batch_descriptor is not None
return self.graph_uses_replay_batch(batch_descriptor.num_tokens)
return self.replay_batch is not None
def graph_uses_replay_batch(self, num_tokens: int) -> bool:
"""Whether a PIECEWISE graph of ``num_tokens`` breaks out to the replay
batch; capture and the model state's runtime replay batch share it."""
return self.trim_threshold is not None and num_tokens >= self.trim_threshold
@eager_break_during_capture
def _run_in_graph_break(
self, hidden_states: torch.Tensor | MoEOutput, *states: torch.Tensor | None
) -> tuple[torch.Tensor, ...]:
"""A graph break: the outputs land in fixed buffers the next segment reads."""
outputs = self._run(hidden_states, *states)
if self._break_outputs is None:
# Sized by the first call: the largest model graph is captured first.
self._break_outputs = [torch.empty_like(out) for out in outputs]
return tuple(
buf[: out.shape[0]].copy_(out)
for buf, out in zip(self._break_outputs, outputs)
)
def _run(
self, hidden_states: torch.Tensor | MoEOutput, *states: torch.Tensor | None
) -> tuple[torch.Tensor, ...]:
replay_batch = self.replay_batch
if replay_batch is None:
return self.run_layers(hidden_states, *states)
# A trimming step holds a prefill longer than the window, more tokens
# than any step whose MoE leaves its finalize to the next layer.
# Replay batch steps hold more than `window` tokens: no deferred MoE finalize.
assert isinstance(hidden_states, torch.Tensor)
num_rows = rows.shape[0]
for buf in self.row_buffers:
buf[:num_rows].copy_(buf.index_select(0, rows))
with override_forward_context(self.forward_context):
row_outputs = self.run_layers(
hidden_states.index_select(0, rows),
*(None if t is None else t.index_select(0, rows) for t in states),
)
rows = replay_batch.rows
inputs = (hidden_states, *states)
with override_forward_context(replay_batch.forward_context):
if replay_batch.run_graph is not None:
row_outputs = replay_batch.run_graph(rows, inputs)
else:
row_outputs = self.run_layers(
*(None if t is None else t.index_select(0, rows) for t in inputs)
)
# The trimmed rows' outputs stay zero; nothing reads them.
num_tokens = hidden_states.shape[0]
return tuple(
@@ -0,0 +1,102 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CUDA graphs of the decoder replay layers on a step's replay batch."""
from collections.abc import Callable
from copy import copy
from dataclasses import replace
import torch
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
from vllm.config import CUDAGraphMode, VllmConfig
from vllm.config.kernel import MEGA_MOE_BACKENDS
from vllm.forward_context import get_forward_context, override_forward_context
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.v1.worker.gpu.cudagraph_utils import (
BatchExecutionDescriptor,
CudaGraphManager,
)
class DecoderReplayCudaGraphManager(CudaGraphManager):
"""Breakable PIECEWISE graphs of the replay layers keyed by the replay batch's
padded size. They read the layer inputs from static buffers."""
def __init__(self, vllm_config: VllmConfig, device, layers: DecoderReplayLayers):
compilation = copy(vllm_config.compilation_config)
scheduler = vllm_config.scheduler_config
sizes = compilation.decoder_replay_cudagraph_capture_sizes
if not sizes:
bound = min(
compilation.max_cudagraph_capture_size,
scheduler.max_num_seqs * layers.window,
)
# Replay batches hold at least `window` rows: step by window, or by 1/8
# of the power-of-two interval once wider (256 in [2048, 4096)).
sizes, s = [bound], layers.window
while s < bound:
sizes.append(s)
s += max(layers.window, 1 << max(s.bit_length() - 4, 0))
sizes = sorted(set(sizes))
if max(sizes) > scheduler.max_num_batched_tokens:
raise ValueError(
"decoder_replay_cudagraph_capture_sizes must not exceed "
"max_num_batched_tokens"
)
compilation.cudagraph_capture_sizes = sizes
compilation.max_cudagraph_capture_size = max(sizes)
replay_config = copy(vllm_config)
replay_config.compilation_config = compilation
super().__init__(replay_config, device, CUDAGraphMode.PIECEWISE, 1)
self.layers = layers
self.breakable_cg_runner: BreakableCUDAGraphWrapper = BreakableCUDAGraphWrapper(
layers.run_layers, replay_config
)
config, act = vllm_config.model_config.hf_config, vllm_config.model_config.dtype
assert isinstance(act, torch.dtype)
hc, h, f32 = config.hc_mult, config.hidden_size, torch.float32
mega_moe = vllm_config.kernel_config.moe_backend in MEGA_MOE_BACKENDS
ids = torch.int64 if mega_moe else torch.int32
# hidden_states, positions, input_ids, pre_mix, post_mix, res_mix, residual
shapes = [(h,), (), (), (hc,), (hc, 1), (hc, hc), (hc, h)]
dtypes = [act, torch.int64, ids, f32, f32, f32, act]
n = compilation.max_cudagraph_capture_size
self.input_buffers = [
torch.zeros(n, *s, dtype=d, device=device) for s, d in zip(shapes, dtypes)
]
def capture_replay_graphs(
self, prepare: Callable[[BatchExecutionDescriptor], None]
) -> None:
"""Capture each size on the replay batch ``prepare`` sets on the layers."""
def create_forward_fn(desc: BatchExecutionDescriptor, warmup: bool):
prepare(desc)
assert self.layers.replay_batch is not None
context = self.layers.replay_batch.forward_context
inputs = [buf[: desc.num_tokens] for buf in self.input_buffers]
def forward_fn(cg_mode: CUDAGraphMode) -> None:
with override_forward_context(
replace(context, cudagraph_runtime_mode=cg_mode)
):
self.breakable_cg_runner(*inputs)
return forward_fn
self.capture(create_forward_fn, "Capturing decoder replay CUDA graphs")
self.layers.replay_batch = None
def run(self, rows: torch.Tensor, inputs: tuple) -> tuple[torch.Tensor, ...]:
"""Replay the forward context's graph on ``rows`` of ``inputs``."""
num_rows = rows.shape[0]
for buf, t in zip(self.input_buffers, inputs):
torch.index_select(t, 0, rows, out=buf[:num_rows])
batch_descriptor = get_forward_context().batch_descriptor
assert batch_descriptor is not None
num_tokens = batch_descriptor.num_tokens
outputs = self.breakable_cg_runner(
*(buf[:num_tokens] for buf in self.input_buffers)
)
return tuple(out[:num_rows] for out in outputs)
-14
View File
@@ -500,22 +500,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
for layer in self.model.layers:
layer.ffn.finalize_mega_moe_weights()
def _finalize_attn(self) -> None:
"""Run the attention backend's post-load weight step on the draft layers.
They are ordinary DeepseekV4DecoderLayers, so they take the engine-wide
attention backend and owe it whatever the target model owes it -- mega
attention permutes wq_b / wo_a here and refuses to run without it.
Idempotent, like the target's.
"""
for layer in self.model.layers:
finalize = getattr(layer.attn, "finalize_loaded_weights", None)
if finalize is not None:
finalize()
def process_weights_after_loading(self) -> None:
self._finalize_moe()
self._finalize_attn()
def _remap_dspark_name(self, name: str) -> str | None:
"""Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path.
@@ -32,8 +32,10 @@ from vllm.models.deepseek_v41.common.ops import (
)
from vllm.models.deepseek_v41.common.ops.fused_layout import (
WV_GROUP_SIZE,
permute_wo_a_,
permute_wq_b_,
o_fused_chunk_permutation,
o_fused_permutation,
permute_on_load,
q_fused_permutation,
)
from vllm.models.deepseek_v41.nvidia.flashmla import DeepseekV4FlashMLAAttention
from vllm.models.deepseek_v41.sparse_mla import (
@@ -182,7 +184,13 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
"wo_a group."
)
self.n_wv_group = self.padded_heads // WV_GROUP_SIZE
self._fused_layouts_ready = False
q_perm = q_fused_permutation(self.n_local_heads, self.head_dim)
permute_on_load(self.wq_b.weight, q_perm, dim=0)
permute_on_load(self.wq_b.weight_scale, q_perm, dim=0)
o_perm = o_fused_permutation(WV_GROUP_SIZE, self.head_dim)
permute_on_load(self.wo_a.weight, o_perm, dim=1)
o_chunk_perm = o_fused_chunk_permutation(WV_GROUP_SIZE, self.head_dim)
permute_on_load(self.wo_a.weight_scale, o_chunk_perm, dim=1)
# ---- interface contract ------------------------------------------------
@@ -227,25 +235,6 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
)
return self._wo_b_proj(z.flatten(1))
# ---- weights -----------------------------------------------------------
def finalize_loaded_weights(self) -> None:
"""Permute wq_b rows / wo_a columns into the kernel's layouts.
Idempotent: a second post-load pass must not permute twice.
"""
if self._fused_layouts_ready:
return
permute_wq_b_(
self.wq_b.weight.data, self.wq_b.weight_scale.data, self.n_local_heads
)
permute_wo_a_(
self.wo_a.weight.data,
self.wo_a.weight_scale.data,
self.n_local_heads // self.n_local_groups,
)
self._fused_layouts_ready = True
# ---- forward -----------------------------------------------------------
def forward_mqa(
@@ -255,11 +244,6 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
positions: torch.Tensor,
output: QuantizedActivation,
) -> None:
if not self._fused_layouts_ready:
raise RuntimeError(
f"{self.prefix}: wq_b / wo_a were never permuted for the mega "
"attention kernel; refusing to run with mismatched layouts."
)
attn_metadata = get_forward_context().attn_metadata
if attn_metadata is None:
# Warmup dummy run: reserve the prefill workspace, produce zeros.
+78 -34
View File
@@ -100,6 +100,7 @@ from vllm.v1.worker.ubatching import dbo_current_ubatch_id
from ..common.engram import (
Engram,
EngramBatch,
EngramLayout,
NgramHashState,
can_share_engram_tables,
@@ -623,6 +624,40 @@ class DeepseekV4DecoderLayer(nn.Module):
torch.cuda.current_stream().wait_stream(mhc_stream)
return x, residual, post_mix, res_mix, ffn_pre, previous_aux
def write_kv(
self,
x: torch.Tensor | MoEOutput,
positions: torch.Tensor,
input_ids: torch.Tensor | None,
pre_mix: torch.Tensor,
post_mix: torch.Tensor,
res_mix: torch.Tensor,
residual: torch.Tensor,
) -> None:
"""Write the KV ``forward`` would for the replay layers' inputs, skipping
the rest of the layer; the replay batch then reruns its rows."""
# The replay batch rules out Engram and sequence parallel here.
assert self.engram is None and not self.use_sequence_parallel
*_, x, _, _ = mhc_shifted_post_pre(
x,
residual,
post_mix,
res_mix,
self.hc_attn_fn,
self.hc_attn_scale,
self.hc_attn_base,
self.rms_norm_eps,
self.hc_eps,
self.hc_eps,
self.hc_post_alpha,
self.hc_sinkhorn_iters,
pre_mix=pre_mix,
norm_weight=self.attn_norm.weight,
norm_eps=self.attn_norm.variance_epsilon,
reduce_results=self.fuse_mhc_all_reduce,
)
self.attn.forward_kv(positions, x)
class DeepseekV4Model(nn.Module, EagleModelMixin):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
@@ -743,6 +778,14 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
),
prefix=f"{prefix}.layers",
)
self.engram_batch = EngramBatch.create(
[
layer.engram
for layer in islice(self.layers, self.start_layer, self.end_layer)
if getattr(layer, "engram", None) is not None
],
vllm_config.scheduler_config.max_num_batched_tokens,
)
if self.fuse_mhc_all_reduce:
# A MoE's top-k finalize folds into the next layer's first mHC
# boundary, which the last local layer lacks and an engram layer
@@ -765,19 +808,30 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
and self._decoder_replay_supported(vllm_config, cut)
and self.layers[cut].attn.swa_cache_layer.bounded_replay
):
self.decoder_replay_start = cut + 1
assert self.layers[cut].attn.compress_ratio <= 1
# The last KV source writes every row's KV, then replays.
self.decoder_replay_start = cut
# The attention metadata keys the replay layers read.
metadata_prefixes = set()
for layer in islice(self.layers, cut, self.end_layer):
attn = typing.cast(DeepseekV4DecoderLayer, layer).attn
metadata_prefixes.add(attn.swa_cache_layer.prefix)
if attn.compressed_cache_prefix is not None:
metadata_prefixes.add(attn.compressed_cache_prefix)
if attn.indexer is not None:
metadata_prefixes.add(attn.indexer.k_cache.prefix)
self.decoder_replay_layers = DecoderReplayLayers(
config.sliding_window,
self._run_replay_layers,
[
buf
for buf in (self.topk_indices_buffer, self.candidate_block_buffer)
if buf is not None
],
self.layers[cut].write_kv,
metadata_prefixes,
self.layers[cut].attn.swa_cache_layer.prefix,
)
logger.info_once(
"Decoder SWA bounded replay: in eager prefill steps, layers "
"Decoder SWA bounded replay: in eager prefill steps, layer %d "
"writes its KV for every token, and the rest of it and layers "
"%d-%d run on each request's last %d tokens only.",
cut,
cut + 1,
self.end_layer - 1,
config.sliding_window,
@@ -926,15 +980,18 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
if engram_hashes is not None:
# Gather all Engram rows before entering the decoder layers.
# One gather feeds every layer sharing the DP-split table.
gathered_hashes = gather_engram_hashes(
engram_hashes, dp_shared_memory=self.engram_dp_shared_memory
)
for layer in islice(self.layers, self.start_layer, self.end_layer):
engram = getattr(layer, "engram", None)
if engram is not None:
engram.prepare_embeddings(
gathered_hashes[:, engram.layer_hash_index]
)
if self.engram_batch is not None:
self.engram_batch.prepare_embeddings(engram_hashes)
else:
gathered_hashes = gather_engram_hashes(
engram_hashes, dp_shared_memory=self.engram_dp_shared_memory
)
for layer in islice(self.layers, self.start_layer, self.end_layer):
engram = getattr(layer, "engram", None)
if engram is not None:
engram.prepare_embeddings(
gathered_hashes[:, engram.layer_hash_index]
)
full_num_tokens = positions.shape[0]
if self.use_sequence_parallel:
@@ -1110,9 +1167,8 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
res_mix: torch.Tensor,
residual: torch.Tensor,
) -> tuple[torch.Tensor, ...]:
"""The layers past the last KV source, on whatever rows they are given;
returns their output, the last FFN's pre-mix and the aux hidden states
they capture."""
"""Layers ``decoder_replay_start``.. on the given rows; returns their output,
the last FFN's pre-mix and the aux hidden states they capture."""
aux_hidden_by_layer: dict[int, torch.Tensor] = {}
hidden_states, residual, post_mix, res_mix, pre_mix = self._run_layers(
range(self.decoder_replay_start, self.end_layer),
@@ -1144,7 +1200,7 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
)
def _decoder_replay_supported(self, vllm_config: VllmConfig, cut: int) -> bool:
"""Whether this rank may trim the layers after ``cut``; warns when not."""
"""Whether this rank may replay from layer ``cut`` on; warns when not."""
parallel_config = vllm_config.parallel_config
spec_config = vllm_config.speculative_config
draft_config = spec_config.draft_model_config if spec_config else None
@@ -1166,8 +1222,8 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
"the replay-layer batch shrinks per rank, which sequence and "
"prefill-context parallelism and microbatching cannot follow"
)
elif any(i > cut for i in getattr(self.config, "engram_layer_ids", ())):
reason = "an Engram layer sits after the last KV source layer"
elif any(i >= cut for i in getattr(self.config, "engram_layer_ids", ())):
reason = "an Engram layer sits at or after the last KV source layer"
elif draft_config is not None and (
draft_window is None
or draft_window > window
@@ -1354,17 +1410,6 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
for layer in islice(self.layers, self.start_layer, self.end_layer):
layer.ffn.finalize_mega_moe_weights()
def finalize_mega_attn_weights(self) -> None:
"""Permute wq_b / wo_a into FlashMLA's mega-attention layouts.
A no-op for every other attention layer, and idempotent, so a second
post-load pass cannot permute twice.
"""
for layer in islice(self.layers, self.start_layer, self.end_layer):
finalize = getattr(layer.attn, "finalize_loaded_weights", None)
if finalize is not None:
finalize()
def finalize_mhc_broadcast_weights(self) -> None:
if not get_pp_group().is_first_rank or self.start_layer >= self.end_layer:
return
@@ -1637,7 +1682,6 @@ class DeepseekV41LLMForCausalLM(
def process_weights_after_loading(self) -> None:
self.model.finalize_mega_moe_weights()
self.model.finalize_mhc_broadcast_weights()
self.model.finalize_mega_attn_weights()
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
return self.model.get_expert_mapping()
+170 -52
View File
@@ -8,10 +8,17 @@ import torch
import torch.distributed as dist
import torch.nn as nn
from vllm.compilation.breakable_cudagraph import is_breakable_cudagraph_enabled
from vllm.config import CUDAGraphMode, VllmConfig
from vllm.distributed.parallel_state import get_dp_group
from vllm.forward_context import DPMetadata, create_forward_context
from vllm.models.deepseek_v41.decoder_replay_layers import DecoderReplayLayers
from vllm.distributed.parallel_state import get_dp_group, get_pp_group
from vllm.forward_context import BatchDescriptor, DPMetadata, create_forward_context
from vllm.models.deepseek_v41.decoder_replay_layers import (
DecoderReplayLayers,
ReplayBatch,
)
from vllm.models.deepseek_v41.nvidia.decoder_replay_cudagraph import (
DecoderReplayCudaGraphManager,
)
from vllm.triton_utils import tl, triton
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadataBuilder
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
@@ -19,8 +26,10 @@ from vllm.v1.core.sched.output import NewRequestData
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.dp_utils import should_skip_dp_coordination
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.buffer_utils import UvaBufferPool
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
from vllm.v1.worker.gpu.model_states.interface import ModelSpecificAttnMetadata
@@ -229,7 +238,33 @@ class DeepseekV41ModelState(DefaultModelState):
self._kept_kv_start = torch.zeros(
self.max_num_reqs, dtype=torch.int32, device=device
)
self._replay_attn_groups: list[list[AttentionGroup]] | None = None
# The replay layers' and the first one's SWA attention groups.
self._replay_attn_groups: (
tuple[list[list[AttentionGroup]], list[list[AttentionGroup]]] | None
) = None
layers = self.decoder_replay_layers
compilation_config = vllm_config.compilation_config
self.replay_cudagraphs: DecoderReplayCudaGraphManager | None = None
if (
layers is not None
and compilation_config.cudagraph_decoder_replay
and compilation_config.cudagraph_mode.has_piecewise_cudagraphs()
and is_breakable_cudagraph_enabled()
and get_pp_group().is_first_rank
# The graphs' fixed inputs hold no LoRA mapping and no None input ids.
and vllm_config.lora_config is None
and not vllm_config.model_config.enable_prompt_embeds
):
threshold = compilation_config.decoder_replay_trim_threshold
if threshold <= layers.window:
raise ValueError(
"decoder_replay_trim_threshold must exceed the replay window "
f"of {layers.window} tokens: smaller graphs have nothing to trim"
)
self.replay_cudagraphs = DecoderReplayCudaGraphManager(
vllm_config, device, layers
)
layers.trim_threshold = threshold
def add_request(self, req_index: int, new_req_data: NewRequestData) -> None:
super().add_request(req_index, new_req_data)
@@ -409,15 +444,20 @@ class DeepseekV41ModelState(DefaultModelState):
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
replay_start: torch.Tensor,
capture_desc: BatchExecutionDescriptor | None = None,
) -> None:
"""Set the replay layers' batch for this forward, or none when nothing
trims. Only eager steps trim: a CUDA graph keeps the layers on the whole
batch, and ranks share the graph mode. Under data parallelism every rank
replays if any does."""
"""Set the replay layers' batch for this forward, or none. Eager steps trim;
captures and PIECEWISE graphs at the trim threshold or above break out to a
replay batch, trimmed or not; FULL and smaller PIECEWISE graphs keep the
whole batch. Under DP every rank replays if any does."""
layers = self.decoder_replay_layers
assert layers is not None
layers.rows = layers.forward_context = None
if cudagraph_mode != CUDAGraphMode.NONE:
layers.replay_batch = None
force_replay_batch = capture_desc is not None or (
cudagraph_mode == CUDAGraphMode.PIECEWISE
and layers.graph_uses_replay_batch(input_batch.num_tokens_after_padding)
)
if cudagraph_mode != CUDAGraphMode.NONE and not force_replay_batch:
return
num_reqs = input_batch.num_reqs
@@ -427,48 +467,126 @@ class DeepseekV41ModelState(DefaultModelState):
query_lens,
np.minimum(query_lens, layers.window),
)
# A batch of context-free non-prefill rows is a dummy (an idle DP rank's):
# nothing reads it and its idx_mapping hits stale slots, so keep one row.
seq_lens = input_batch.seq_lens_cpu_upper_bound[:num_reqs].numpy()
is_dummy = not input_batch.is_prefilling_np[:num_reqs].any() and bool(
(seq_lens == query_lens).all()
)
if is_dummy and capture_desc is None:
kept_lens = np.zeros_like(kept_lens)
kept_lens[0] = 1
# Dummy batches (captures, an idle DP rank's) are not prefills: they
# keep their rows unless a rank trims.
trims = bool(
needs_replay_batch = force_replay_batch or bool(
(kept_lens < query_lens)[input_batch.is_prefilling_np[:num_reqs]].any()
)
num_tokens = int(kept_lens.sum())
dp_metadata = None
dp_tokens = None
if self.vllm_config.parallel_config.data_parallel_size > 1:
trims, dp_metadata = self._agree_across_dp(trims, num_tokens)
if not trims:
needs_replay_batch, dp_tokens = self._agree_across_dp(
needs_replay_batch, num_tokens
)
if not needs_replay_batch:
return
cudagraphs, run_graph = self.replay_cudagraphs, None
num_padded, cg_mode = num_tokens, CUDAGraphMode.NONE
if cudagraphs is not None:
# Every rank runs the graph that fits the largest rank's batch.
dp_max_tokens = num_tokens if dp_tokens is None else int(dp_tokens.max())
desc = capture_desc or cudagraphs.dispatch(num_reqs, dp_max_tokens, None, 0)
if desc.cg_mode == CUDAGraphMode.PIECEWISE:
num_padded, cg_mode = desc.num_tokens, desc.cg_mode
run_graph = cudagraphs.run
if dp_tokens is not None:
dp_tokens.fill_(num_padded)
dp_metadata = None
if dp_tokens is not None:
dp_metadata = DPMetadata.make(
self.vllm_config.parallel_config, num_padded, dp_tokens
)
kept_batch, kept_slot_mappings = self._kept_input_batch(
input_batch, slot_mappings, replay_start, kept_lens
input_batch, slot_mappings, replay_start, kept_lens, num_padded
)
if self._replay_attn_groups is None:
self._replay_attn_groups = (
self._copy_attn_groups(attn_groups, layers.metadata_prefixes),
self._copy_attn_groups(attn_groups, {layers.first_swa_prefix}),
)
replay_groups, first_swa_groups = self._replay_attn_groups
attn_metadata = super().prepare_attn(
kept_batch,
CUDAGraphMode.NONE,
block_tables,
kept_slot_mappings,
self._replay_groups(attn_groups),
replay_groups,
kv_cache_config,
model_specific_attn_metadata=ReplayAttnMetadata(
self._kept_kv_start[:num_reqs]
),
)
layers.rows = self._kept_rows[:num_tokens]
layers.forward_context = create_forward_context(
attn_metadata,
self.vllm_config,
dp_metadata=dp_metadata,
slot_mapping=build_slot_mappings_by_layer(
kept_slot_mappings, kv_cache_config
# The first replay layer wrote every row's window KV: its window starts
# are the batch's.
first_swa = layers.first_swa_prefix
attn_metadata[first_swa] = super().prepare_attn(
kept_batch,
CUDAGraphMode.NONE,
block_tables,
kept_slot_mappings,
first_swa_groups,
kv_cache_config,
model_specific_attn_metadata=ReplayAttnMetadata(replay_start),
)[first_swa]
layers.replay_batch = ReplayBatch(
self._kept_rows[:num_tokens],
create_forward_context(
attn_metadata,
self.vllm_config,
dp_metadata=dp_metadata,
cudagraph_runtime_mode=cg_mode,
batch_descriptor=BatchDescriptor(num_tokens=num_padded),
slot_mapping=build_slot_mappings_by_layer(
kept_slot_mappings, kv_cache_config
),
),
run_graph,
)
def capture_inner_cudagraphs(
self,
input_buffers: InputBuffers,
block_tables: BlockTables,
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
) -> None:
def prepare(desc: BatchExecutionDescriptor) -> None:
# Capture reuses the runtime path on a dummy batch, so the graph reads
# the buffers a real step fills.
num_reqs = min(desc.num_tokens, self.max_num_reqs)
self._prepare_replay_batch(
InputBatch.make_dummy(num_reqs, desc.num_tokens, input_buffers),
CUDAGraphMode.NONE,
block_tables.get_dummy_block_tables(num_reqs),
block_tables.get_dummy_slot_mappings(desc.num_tokens),
attn_groups,
kv_cache_config,
self._replay_start[:num_reqs].zero_(),
capture_desc=desc,
)
if self.replay_cudagraphs is not None:
# profile_only captures use pre-KV-cache groups: drop the cache.
self._replay_attn_groups = None
self.replay_cudagraphs.capture_replay_graphs(prepare)
def _kept_input_batch(
self,
input_batch: InputBatch,
slot_mappings: torch.Tensor,
replay_start: torch.Tensor,
kept_lens: np.ndarray,
num_padded: int,
) -> tuple[InputBatch, torch.Tensor]:
"""Build the sub-``InputBatch`` of each request's last ``kept_lens``
rows, and its slot mappings.
@@ -486,7 +604,8 @@ class DeepseekV41ModelState(DefaultModelState):
input_batch.query_start_loc_np[: num_reqs + 1] - kept_query_start_loc_np
)
assert self._kept_slot_mappings is not None
kept_slot_mappings = self._kept_slot_mappings[:, :num_tokens]
kept_slot_mappings = self._kept_slot_mappings[:, :num_padded]
kept_slot_mappings[:, num_tokens:].fill_(PAD_SLOT_ID)
_gather_replay_batch_kernel[(num_reqs,)](
input_batch.query_start_loc,
dropped_before,
@@ -511,48 +630,47 @@ class DeepseekV41ModelState(DefaultModelState):
kept_batch = replace(
input_batch,
num_tokens=num_tokens,
num_tokens_after_padding=num_tokens,
num_tokens_after_padding=num_padded,
query_start_loc=self._kept_query_start_loc[: num_reqs + 1],
query_start_loc_np=kept_query_start_loc_np,
max_query_len=max_query_len,
positions=self._kept_positions[:num_tokens],
positions=self._kept_positions[:num_padded],
fast_prefill=None,
)
return kept_batch, kept_slot_mappings
def _agree_across_dp(
self, trims: bool, num_tokens: int
) -> tuple[bool, DPMetadata | None]:
"""Whether any rank trims and, then, the replay layers' DP metadata from
every rank's replay token count."""
self, needs_replay_batch: bool, num_tokens: int
) -> tuple[bool, torch.Tensor | None]:
"""Whether any rank needs a replay batch and, if so, each rank's token count."""
parallel_config = self.vllm_config.parallel_config
agreed = torch.zeros(2, parallel_config.data_parallel_size, dtype=torch.int32)
agreed[:, parallel_config.data_parallel_rank] = torch.tensor(
[trims, num_tokens]
[needs_replay_batch, num_tokens]
)
if not should_skip_dp_coordination():
dist.all_reduce(agreed, group=get_dp_group().cpu_group)
if not agreed[0].any():
return False, None
return True, DPMetadata.make(parallel_config, num_tokens, agreed[1])
return True, agreed[1]
def _replay_groups(
self, attn_groups: list[list[AttentionGroup]]
def _copy_attn_groups(
self, attn_groups: list[list[AttentionGroup]], prefixes: set[str]
) -> list[list[AttentionGroup]]:
"""The attention groups with metadata builders of their own, like each
microbatch's: a builder keeps the metadata it built, and the runner's
hold the batch's."""
if self._replay_attn_groups is None:
self._replay_attn_groups = []
for groups in attn_groups:
replay_groups = []
for group in groups:
replay_group = replace(group, metadata_builders=[])
replay_group.create_metadata_builders(
self.vllm_config,
self.device,
group.metadata_builders[0].kernel_block_size,
)
replay_groups.append(replay_group)
self._replay_attn_groups.append(replay_groups)
return self._replay_attn_groups
"""Copies of the groups holding any of ``prefixes``, with builders of their
own like a microbatch's: a builder keeps the metadata it built."""
own_groups = []
for groups in attn_groups:
copies = []
for group in groups:
if prefixes.isdisjoint(group.layer_names):
continue
copy = replace(group, metadata_builders=[])
copy.create_metadata_builders(
self.vllm_config,
self.device,
group.metadata_builders[0].kernel_block_size,
)
copies.append(copy)
own_groups.append(copies)
return own_groups
@@ -0,0 +1,173 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Symmetric-memory Engram exchange for slots below ENGRAM_A2A_MIN_SLOT."""
from typing import TYPE_CHECKING
import torch
import torch.distributed as dist
from torch import nn
from vllm.distributed import get_engram_dp_group
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
if TYPE_CHECKING:
from vllm.models.deepseek_v41.common.engram import Engram
@triton.jit(do_not_specialize=["num_tokens"])
def _peer_lookup_kernel(
metadata,
id_ptrs,
output,
num_tokens,
HEADS: tl.constexpr,
LAYERS: tl.constexpr,
DP: tl.constexpr,
RANK: tl.constexpr,
DIM: tl.constexpr,
BLOCK: tl.constexpr,
):
"""Look up this rank's heads for every peer's tokens into packed rows."""
row = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
local_heads: tl.constexpr = HEADS // DP
valid = row < num_tokens * LAYERS * HEADS
token = row // (LAYERS * local_heads)
layer, head = row // local_heads % LAYERS, row % local_heads
ids = tl.load(id_ptrs + token // num_tokens, valid, other=0).to(
tl.pointer_type(tl.int32)
)
index = tl.load(
ids + (token % num_tokens * LAYERS + layer) * HEADS + RANK * local_heads + head,
valid,
other=-1,
).to(tl.int64)
# Per-layer metadata: weight pointer, scale pointer, vocab start, vocab end.
table = metadata + layer * 4
start, end = tl.load(table + 2), tl.load(table + 3)
owned = valid & (index >= start) & (index < end)
local = tl.where(owned, index - start, 0)
weight = tl.multiple_of(tl.load(table), DIM).to(tl.pointer_type(tl.uint8))
scales = tl.load(table + 1)
scales = tl.multiple_of(scales, DIM // 32).to(tl.pointer_type(tl.uint8))
col = tl.arange(0, DIM)
value = tl.load(
weight[:, None] + local[:, None] * DIM + col[None, :], owned[:, None], other=0
)
dst = row.to(tl.int64) * (DIM + DIM // 32)
tl.store(output + dst[:, None] + col[None, :], value, valid[:, None])
scale_cols = tl.arange(0, DIM // 32)
scale = tl.load(
scales[:, None] + local[:, None] * (DIM // 32) + scale_cols[None, :],
owned[:, None],
other=0,
)
tl.store(output + dst[:, None] + DIM + scale_cols[None, :], scale, valid[:, None])
class EngramPeerExchange(nn.Module):
"""Two phase barriers fence reuse of each other's buffers across forwards.
Pointer tables are buffers so level-2 sleep restores them on wake-up.
"""
def __init__(self, layers: list["Engram"], max_tokens: int):
import torch.distributed._symmetric_memory as symm_mem
super().__init__()
group = get_engram_dp_group()
assert group is not None
self.dp_size, self.dp_rank = group.world_size, group.rank_in_group
device = layers[0].staged_rows.device
self.num_layers = len(layers)
self.hash_start = layers[0].layer_hash_index
table = layers[0].embed_tokens
self.heads, self.dim = table.n_hash_cols, table.dim
self.ids = symm_mem.empty(
(max_tokens, self.num_layers, self.heads),
dtype=torch.int32,
device=device,
)
self.rows = symm_mem.empty(
(
max_tokens * self.dp_size,
self.num_layers,
self.heads // self.dp_size,
self.dim + self.dim // 32,
),
dtype=torch.uint8,
device=device,
)
self.id_handle = symm_mem.rendezvous(self.ids, group.device_group)
self.row_handle = symm_mem.rendezvous(self.rows, group.device_group)
metadata = []
for layer in layers:
table = layer.embed_tokens
weight, scale = table._storage()
metadata.append(
(
weight.data_ptr(),
scale.data_ptr(),
table.vocab_start_idx,
table.vocab_end_idx,
)
)
for name, data in (
("metadata", metadata),
("id_ptrs", self.id_handle.buffer_ptrs),
("row_ptrs", self.row_handle.buffer_ptrs),
):
self.register_buffer(
name,
torch.tensor(data, dtype=torch.int64, device=device),
persistent=False,
)
@classmethod
def create(
cls, layers: list["Engram"], max_tokens: int
) -> "EngramPeerExchange | None":
# The Engram DP group is node-local and every rank agrees on these.
group = get_engram_dp_group()
assert group is not None
if not (
current_platform.is_device_capability_family(100)
and group.world_size in (2, 4, 8)
and layers[0].embed_tokens.n_hash_cols % group.world_size == 0
):
return None
physical_id = current_platform.visible_device_id_to_physical_device_id(
torch.accelerator.current_device_index()
)
physical_ids = [None] * group.world_size
dist.all_gather_object(physical_ids, physical_id, group=group.cpu_group)
if not current_platform.is_fully_connected(physical_ids):
return None
return cls(layers, max_tokens)
def exchange(self, hashes: torch.Tensor, slot: int) -> torch.Tensor:
"""Look up this rank's heads for every peer; return per-rank row pointers."""
tokens = hashes.shape[0]
assert 0 < slot <= self.ids.shape[0] and tokens <= slot
hash_end = self.hash_start + self.num_layers
self.ids[:tokens].copy_(hashes[:, self.hash_start : hash_end])
if tokens < slot:
self.ids[tokens:slot].fill_(-1)
# The preceding rows barrier completed every peer's hash reads. This
# barrier completes their previous output reads before rows are reused.
self.id_handle.barrier()
_peer_lookup_kernel[(triton.cdiv(slot * self.num_layers * self.heads, 16),)](
self.metadata,
self.id_ptrs,
self.rows,
slot,
HEADS=self.heads,
LAYERS=self.num_layers,
DP=self.dp_size,
RANK=self.dp_rank,
DIM=self.dim,
BLOCK=16,
)
self.row_handle.barrier()
return self.row_ptrs
+35 -2
View File
@@ -4,8 +4,11 @@
from __future__ import annotations
import fnmatch
from typing import TYPE_CHECKING, cast
import regex as re
from vllm.config import get_current_vllm_config
from vllm.config.quantization import QuantSpec
from vllm.model_executor.layers.fused_moe import (
@@ -23,6 +26,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
)
_DEEPSEEK_V4_EXPERT_DTYPES = ("fp4", "fp8")
_EXPERTS_LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)\.ffn\.experts$")
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.modelopt import (
@@ -54,6 +58,7 @@ class DeepseekV4FP8Config(Fp8Config):
super().__init__(*args, **kwargs)
self._resolved_expert_dtype: str | None = None
self._resolved_moe_quant_algo: str | None = None
self._modelopt_ignore: tuple[str, ...] = ()
self._nvfp4_config: ModelOptNvFp4Config | None = None
# ``is_scale_e8m0`` is a property that resolves on first read,
# by which time the current vllm_config has been set.
@@ -103,6 +108,21 @@ class DeepseekV4FP8Config(Fp8Config):
self._resolve_moe_overrides()
return self._resolved_moe_quant_algo or ""
def _is_nvfp4_expert_layer(self, prefix: str) -> bool:
if self.moe_quant_algo != "NVFP4":
return False
match = _EXPERTS_LAYER_RE.search(prefix)
if match is None or not self._modelopt_ignore:
return True
# MTP/draft layers are built as layers.{num_hidden_layers + k} but are
# named mtp.{k} in some checkpoints.
model_config = get_current_vllm_config().model_config
num_layers = model_config.hf_text_config.num_hidden_layers
idx = int(match.group(1))
layer = f"mtp.{idx - num_layers}" if idx >= num_layers else f"layers.{idx}"
name = f"{layer}.ffn.experts"
return not any(fnmatch.fnmatchcase(name, p) for p in self._modelopt_ignore)
def _get_nvfp4_config(self) -> ModelOptNvFp4Config:
if self._nvfp4_config is None:
from vllm.model_executor.layers.quantization.modelopt import (
@@ -114,6 +134,11 @@ class DeepseekV4FP8Config(Fp8Config):
kv_cache_quant_algo=None,
exclude_modules=[],
group_size=16,
quantization_args=(
self.online_quantization_config.args
if self.online_quantization_config is not None
else None
),
)
return self._nvfp4_config
@@ -168,6 +193,9 @@ class DeepseekV4FP8Config(Fp8Config):
@classmethod
def from_config(cls, config: dict) -> DeepseekV4FP8Config:
# ModelOpt NVFP4 exports keep the experts they ``ignore`` in the native
# MXFP4 format, e.g. the bundled MTP/DSpark layers (``mtp.*``).
ignore = config.get("ignore")
# Reroute AMD-Quark fused shared expert MXFP4 checkpoints onto the fp8
# path: the runtime layout matches the DeepSeek-native fp8 checkpoint,
# so translate the schema into format Fp8Config.from_config expects.
@@ -183,7 +211,12 @@ class DeepseekV4FP8Config(Fp8Config):
name for name in quark_exclude if isinstance(name, str)
],
}
return cast("DeepseekV4FP8Config", super().from_config(config))
quant_config = cast("DeepseekV4FP8Config", super().from_config(config))
if isinstance(ignore, list):
quant_config._modelopt_ignore = tuple(
p for p in ignore if isinstance(p, str)
)
return quant_config
def get_quant_method(self, layer, prefix):
if (
@@ -216,7 +249,7 @@ class DeepseekV4FP8Config(Fp8Config):
):
return UnquantizedFusedMoEMethod(layer.moe_config)
if self.expert_dtype == "fp4":
if self.moe_quant_algo == "NVFP4":
if self._is_nvfp4_expert_layer(prefix):
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptNvFp4FusedMoE,
)
@@ -733,6 +733,10 @@ class SparseAttnIndexerKpool(CustomOp):
self.topk_backend = (
cfg.kernel_config.sparse_indexer_topk_backend if cfg is not None else "auto"
)
if cfg is not None and cfg.parallel_config.decode_context_parallel_size > 1:
raise NotImplementedError(
"SparseAttnIndexerKpool on ROCm does not support DCP."
)
def forward_hip(
self,
+3
View File
@@ -209,6 +209,9 @@ class Glm5NextTailCache(DeepseekV32IndexerCache):
head_size_v=0,
dtype=torch.bfloat16,
sliding_window=ring,
# Tiny per-request ring; every DCP rank keeps the full tail so the
# rank owning a pool can compress it.
dcp_sharded=False,
)
def get_attn_backend(self):
+130 -7
View File
@@ -23,6 +23,10 @@ from vllm.model_executor.layers.fused_moe import (
GateLinear,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
resolve_layer_fused_shared_expert,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
@@ -62,9 +66,11 @@ from vllm.model_executor.models.glm4_1v import (
Glm4vForConditionalGeneration,
)
from vllm.model_executor.models.interfaces import (
EagleModelMixin,
HasInnerState,
IsHybrid,
MixtureOfExperts,
SupportsEagle3,
SupportsPP,
)
from vllm.model_executor.models.utils import (
@@ -258,7 +264,12 @@ class Glm5NextMoE(nn.Module):
)
swiglu_limit = config.swiglu_limit
if config.n_shared_experts is None:
self.is_fused_shared_expert_enabled = False
if config.n_shared_experts is not None:
self.is_fused_shared_expert_enabled = resolve_layer_fused_shared_expert(
quant_config, prefix
) and _fused_shared_experts_tuned(parallel_config)
if config.n_shared_experts is None or self.is_fused_shared_expert_enabled:
self.shared_experts = None
else:
intermediate_size = config.moe_intermediate_size * config.n_shared_experts
@@ -294,7 +305,11 @@ class Glm5NextMoE(nn.Module):
enable_eplb=self.enable_eplb,
num_redundant_experts=self.n_redundant_experts,
is_sequence_parallel=self.is_sequence_parallel,
n_shared_experts=None,
n_shared_experts=config.n_shared_experts
if self.is_fused_shared_expert_enabled
else None,
fuse_shared_experts=self.is_fused_shared_expert_enabled,
shared_expert_prefix=f"{prefix}.shared_experts",
router_logits_dtype=self.gate.out_dtype,
swiglu_limit=swiglu_limit,
)
@@ -672,7 +687,7 @@ class Glm5NextDecoderLayer(nn.Module):
)
class Glm5NextModel(nn.Module):
class Glm5NextModel(nn.Module, EagleModelMixin):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -730,9 +745,13 @@ class Glm5NextModel(nn.Module):
get_layer,
prefix=f"{prefix}.layers",
)
self._aux_post_op = MHCPostOp()
# The active slice is fixed after construction; cache it so forward
# doesn't rebuild the slice (a fresh list) every step.
self._active_layers = self.layers[self.start_layer : self.end_layer]
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
self.layers, Glm5NextMoE, "mlp"
)
if get_pp_group().is_last_rank:
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -751,6 +770,26 @@ class Glm5NextModel(nn.Module):
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
def _aux_hidden_state(
self,
hidden_states: torch.Tensor,
residual: torch.Tensor | None,
post: torch.Tensor | None,
comb: torch.Tensor | None,
) -> torch.Tensor:
"""Completed residual stream entering a layer, as one hidden vector.
mHC layers defer their final ``hc_post`` into the next layer's fused
pre-op, so ``hidden_states`` holds the raw layer output while the
widened stream is completed here and contracted back to
``hidden_size``. Non-mHC layers already return the summed stream.
"""
if post is None:
return hidden_states
assert residual is not None and comb is not None
completed = self._aux_post_op(hidden_states, residual, post, comb)
return hc_contract(completed, self.config.hc_mult)
def forward(
self,
input_ids: torch.Tensor | None,
@@ -780,7 +819,15 @@ class Glm5NextModel(nn.Module):
if self.is_sequence_parallel:
hidden_states = sp_shard(hidden_states)
for layer in self._active_layers:
aux_hidden_states: list[torch.Tensor] = []
for idx, layer in enumerate(self._active_layers, start=self.start_layer):
if idx in self.aux_hidden_state_layers:
aux_hidden_state = self._aux_hidden_state(
hidden_states, residual, post, comb
)
if self.is_sequence_parallel:
aux_hidden_state = sp_all_gather(aux_hidden_state)[:full_num_tokens]
aux_hidden_states.append(aux_hidden_state)
hidden_states, residual, post, comb = layer(
positions, hidden_states, residual, post, comb
)
@@ -795,10 +842,18 @@ class Glm5NextModel(nn.Module):
{"hidden_states": hidden_states, "residual": residual}
)
if self.end_layer in self.aux_hidden_state_layers:
final_aux = self._aux_hidden_state(hidden_states, residual, post, comb)
if self.is_sequence_parallel:
final_aux = sp_all_gather(final_aux)[:full_num_tokens]
aux_hidden_states.append(final_aux)
if self.is_sequence_parallel:
hidden_states = sp_all_gather(hidden_states)[:full_num_tokens]
hidden_states = self.norm(hidden_states)
if aux_hidden_states:
return hidden_states, aux_hidden_states
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
@@ -834,12 +889,15 @@ class Glm5NextModel(nn.Module):
),
0,
)
num_fused_shared = _num_fused_shared_experts(
self.config.n_shared_experts, self.is_fused_shared_expert_enabled
)
expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.n_routed_experts,
num_experts=self.config.n_routed_experts + num_fused_shared,
num_redundant_experts=num_redundant_experts,
)
else:
@@ -868,6 +926,8 @@ class Glm5NextModel(nn.Module):
# Models trained using ColossalAI may include these tensors in
# the checkpoint. Skip them.
continue
if self.is_fused_shared_expert_enabled:
name = _fused_shared_expert_name(name, self.config.n_routed_experts)
# Handle FP8 indexer WK: dequantize to BF16 for fusion with
# weights_proj into wk_weights_proj.
@@ -985,7 +1045,7 @@ class Glm5NextModel(nn.Module):
class Glm5NextForCausalLM(
nn.Module, HasInnerState, SupportsPP, MixtureOfExperts, IsHybrid
nn.Module, HasInnerState, SupportsPP, MixtureOfExperts, IsHybrid, SupportsEagle3
):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
@@ -1081,7 +1141,11 @@ class Glm5NextForCausalLM(
dummy_inputs=Glm4vDummyInputsBuilder,
)
class Glm5NextForConditionalGeneration(
Glm4vForConditionalGeneration, HasInnerState, IsHybrid, MixtureOfExperts
Glm4vForConditionalGeneration,
HasInnerState,
IsHybrid,
MixtureOfExperts,
SupportsEagle3,
):
# The text model (KDA + dense-MLA + MoE) is a hybrid mamba model. The
# multimodal wrapper must declare the same interfaces so vLLM treats it as
@@ -1228,6 +1292,65 @@ def get_spec_layer_idx_from_weight_name(
return None
def _fused_shared_experts_tuned(parallel_config: ParallelConfig) -> bool:
"""AITER has fused-MoE configs tuned for the fused shared-expert shape
(one more expert and one more top-k slot than the routed MoE) only on
gfx950, with every expert on each rank and its weights split by TP4 or
TP8. Data, prefill context and expert parallelism change that split, so
any other GPU or parallel layout would run untuned fallback kernels."""
from vllm.platforms.rocm import on_gfx950
reasons: list[str] = []
if not on_gfx950():
reasons.append("the GPU is not gfx950")
if parallel_config.tensor_parallel_size not in (4, 8):
reasons.append(
f"tensor_parallel_size is {parallel_config.tensor_parallel_size}"
)
if parallel_config.data_parallel_size != 1:
reasons.append(f"data_parallel_size is {parallel_config.data_parallel_size}")
if parallel_config.prefill_context_parallel_size != 1:
reasons.append(
"prefill_context_parallel_size is "
f"{parallel_config.prefill_context_parallel_size}"
)
if parallel_config.enable_expert_parallel:
reasons.append("expert parallelism is enabled")
if not reasons:
return True
logger.warning_once(
"VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS is ignored for GLM-5.3-Flash: "
"%s. AITER has tuned configs for its fused shared-expert MoE only on "
"gfx950 at TP4 and TP8, without data, prefill context or expert "
"parallelism. Running the shared experts as a separate MLP.",
"; ".join(reasons),
)
return False
def _num_fused_shared_experts(n_shared_experts: int | None, enabled: bool) -> int:
"""Expert slots the fused MoE appends for the shared expert; must match the
``num_fused_shared_experts`` that ``FusedMoE`` allocates."""
if not enabled or n_shared_experts is None:
return 0
if n_shared_experts > 1:
raise NotImplementedError(
"Fused shared-expert loading supports only 1 shared expert per "
f"layer, but config.n_shared_experts is {n_shared_experts}. Set "
"VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=0 to run the shared "
"experts as a separate MLP."
)
return n_shared_experts
def _fused_shared_expert_name(name: str, n_routed_experts: int) -> str:
"""Point a checkpoint ``mlp.shared_experts.*`` tensor at the fused MoE's
shared-expert slot, which follows the routed experts; other names are
returned unchanged."""
return name.replace("mlp.shared_experts.", f"mlp.experts.{n_routed_experts}.", 1)
def _try_load_fp8_indexer_wk(name, tensor, buf, params_dict, loaded_params):
if "indexer.wk." not in name or "wk_weights" in name:
return False
+14 -1
View File
@@ -10,6 +10,9 @@ from vllm.config import VllmConfig
from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.vocab_parallel_embedding import (
@@ -30,6 +33,8 @@ from .model import (
Glm5NextDecoderLayer,
Glm5NextMLAAttention,
Glm5NextMoE,
_fused_shared_expert_name,
_num_fused_shared_experts,
_try_load_fp8_attn_proj,
_try_load_fp8_indexer_wk,
get_spec_layer_idx_from_weight_name,
@@ -217,6 +222,9 @@ class Glm5NextMTP(nn.Module, DeepseekV2MixtureOfExperts):
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
self.set_moe_parameters()
self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
self.model.layers.values(), Glm5NextMoE, "mtp_block.mlp"
)
def set_moe_parameters(self):
self.num_moe_layers = self.config.num_nextn_predict_layers
@@ -298,12 +306,15 @@ class Glm5NextMTP(nn.Module, DeepseekV2MixtureOfExperts):
("wk_weights_proj", "wk", 0),
("wk_weights_proj", "weights_proj", 1),
]
num_fused_shared = _num_fused_shared_experts(
self.config.n_shared_experts, self.is_fused_shared_expert_enabled
)
expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=self.config.n_routed_experts,
num_experts=self.config.n_routed_experts + num_fused_shared,
num_redundant_experts=self.num_redundant_experts,
)
@@ -328,6 +339,8 @@ class Glm5NextMTP(nn.Module, DeepseekV2MixtureOfExperts):
if spec_layer is None:
continue
name = self._rewrite_spec_layer_name(spec_layer, name)
if self.is_fused_shared_expert_enabled:
name = _fused_shared_expert_name(name, self.config.n_routed_experts)
if _try_load_fp8_indexer_wk(
name,
@@ -87,7 +87,7 @@ def fused_recurrent_gated_delta_rule_fwd_kernel(
SAFE_GATE: tl.constexpr, # bounded gate variant (only branch implemented)
LOWER_BOUND: tl.constexpr,
):
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_nh, i_v, i_k = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_n, i_hv = i_nh // HV, i_nh % HV
i_h = i_hv // (HV // H)
if IS_VARLEN:
@@ -260,7 +260,9 @@ def fused_recurrent_gated_delta_rule_fwd(
else:
stride_indices_seq, stride_indices_tok = ssm_state_indices.stride()
grid = (NK, NV, N * HV)
# N * HV goes in gridDim.x: gridDim.z is capped at 65535 and batch x heads exceeds it
# (e.g. GLM-5.3-Flash at TP=1: 1024 x 64 = 65536 -> "invalid argument" at CUDA-graph capture).
grid = (N * HV, NV, NK)
fused_recurrent_gated_delta_rule_fwd_kernel[grid](
q=q,
k=k,
+3 -1
View File
@@ -95,7 +95,9 @@ def fused_recurrent_kda_fwd(
else:
stride_indices_seq, stride_indices_tok = ssm_state_indices.stride()
grid = (NK, NV, N * HV)
# N * HV goes in gridDim.x: gridDim.z is capped at 65535 and batch x heads exceeds it
# (e.g. GLM-5.3-Flash at TP=1: 1024 x 64 = 65536 -> "invalid argument" at CUDA-graph capture).
grid = (N * HV, NV, NK)
fused_recurrent_gated_delta_rule_fwd_kernel[grid](
q=q,
k=k,
+95 -27
View File
@@ -7,10 +7,12 @@ import torch
import vllm.envs as envs
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import get_current_vllm_config_or_none
from vllm.distributed import get_dcp_group
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.custom_op import CustomOp
from vllm.model_executor.layers.indexer_topk import get_indexer_topk
from vllm.model_executor.layers.sparse_attn_indexer import _merge_dcp_topk_global
from vllm.models.glm5next.common.sparse_indexer import (
RADIX_TOPK_WORKSPACE_SIZE,
_build_decode_scatter_indices,
@@ -24,6 +26,7 @@ from vllm.models.glm5next.common.sparse_indexer import (
from vllm.models.glm5next.nvidia.ops import kpool_compress as kpool_ops
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import has_deep_gemm
from vllm.utils.import_utils import has_cutedsl
from vllm.utils.torch_utils import (
LayerNameType,
_resolve_layer_name,
@@ -121,6 +124,9 @@ def sparse_attn_indexer_kpool(
tail_kv_cache: torch.Tensor | None = None,
tail_prefix: str | None = None,
topk_backend: str = "auto",
dcp_rank: int = 0,
dcp_world_size: int = 1,
cp_kv_cache_interleave_size: int = 1,
) -> torch.Tensor:
# careful! this will be None in dummy run
attn_metadata = get_forward_context().attn_metadata
@@ -170,6 +176,12 @@ def sparse_attn_indexer_kpool(
has_decode = attn_metadata_narrowed.num_decodes > 0
has_prefill = attn_metadata_narrowed.num_prefills > 0
num_decode_tokens = attn_metadata_narrowed.num_decode_tokens
# Pools are the DCP sharding unit of the index K cache.
pool_cp_interleave = (
cp_kv_cache_interleave_size // max(index_kpool, 1)
if dcp_world_size > 1
else cp_kv_cache_interleave_size
)
# q_scale is required iff the FP4 cache path is enabled; the FP8 path
# folds the Q scale into `weights` inside fused_indexer_q_rope_quant.
@@ -284,16 +296,18 @@ def sparse_attn_indexer_kpool(
scales_spec,
)
for chunk in prefill_metadata.chunks if not short_prefill else ():
k_quant = k_quant_full[: chunk.total_seq_lens]
k_scale = k_scale_full[: chunk.total_seq_lens]
# Under DCP this rank only gathers the pools it owns.
assert chunk.local_cu_seq_lens is not None
k_quant = k_quant_full[: chunk.max_local_total_seq_lens]
k_scale = k_scale_full[: chunk.max_local_total_seq_lens]
if not chunk.skip_kv_gather:
if not chunk.skip_kv_gather and chunk.local_total_seq_lens > 0:
ops.cp_gather_indexer_k_quant_cache(
kv_cache,
k_quant,
k_scale,
chunk.block_table,
chunk.cu_seq_lens,
chunk.local_cu_seq_lens,
)
q_slice = q_quant[chunk.token_start : chunk.token_end]
@@ -314,15 +328,18 @@ def sparse_attn_indexer_kpool(
k_scale_cast = k_scale.view(torch.float32).squeeze(-1)
from vllm.utils.deep_gemm import fp8_fp4_mqa_logits
logits = fp8_fp4_mqa_logits(
(q_slice_cast, q_scale_slice),
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
clean_logits=False,
)
num_rows = logits.shape[0]
num_rows = q_slice.shape[0]
if chunk.local_total_seq_lens == 0:
logits = q_slice.new_empty((num_rows, 0), dtype=torch.float32)
else:
logits = fp8_fp4_mqa_logits(
(q_slice_cast, q_scale_slice),
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
clean_logits=False,
)
# kpool: logits are pool-granular (compress_ratio == index_kpool),
# so topk selects pools. We pick topk_tokens // kpool pools then
@@ -338,15 +355,28 @@ def sparse_attn_indexer_kpool(
chunk.token_start : chunk.token_end, :topk_tokens
]
torch.ops._C.top_k_per_row_prefill(
if logits.shape[1] == 0:
topk_dst.fill_(-1)
else:
torch.ops._C.top_k_per_row_prefill(
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
# Local pool ids -> request-relative global pool ids.
_merge_dcp_topk_global(
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
dcp_rank,
dcp_world_size,
pool_cp_interleave,
row_starts=chunk.cu_seqlen_ks,
)
if index_kpool > 1:
@@ -584,6 +614,14 @@ def sparse_attn_indexer_kpool(
select_k,
attn_metadata_narrowed.max_seq_len,
)
_merge_dcp_topk_global(
logits,
topk_dst,
select_k,
dcp_rank,
dcp_world_size,
pool_cp_interleave,
)
# Resolve to token-level indices in the output buffer.
if index_kpool > 1:
@@ -669,14 +707,41 @@ class SparseAttnIndexerKpool(CustomOp):
else "auto"
)
_parallel = _cfg.parallel_config if _cfg is not None else None
if (
_parallel is not None
and _parallel.prefill_context_parallel_size > 1
and _parallel.decode_context_parallel_size > 1
):
raise NotImplementedError(
"SparseAttnIndexerKpool does not support PCP+DCP."
)
self._parallel_config = _parallel
self._cp_kv_cache_interleave_size: int | None = None
self.dcp_world_size = 1
self.dcp_rank = 0
if _parallel is not None and _parallel.decode_context_parallel_size > 1:
if _parallel.prefill_context_parallel_size > 1:
raise NotImplementedError(
"SparseAttnIndexerKpool does not support PCP+DCP."
)
self.dcp_world_size = _parallel.decode_context_parallel_size
self.dcp_rank = get_dcp_group().rank_in_group
if current_platform.is_cuda() and has_cutedsl():
from vllm.model_executor.kernels.attention.dsa.dcp_indexer_cutedsl import ( # noqa: E501
_PACK_DCP_TOPK_CANDIDATES_KERNEL,
_STABLE_TOPK_FROM_GATHERED_CANDIDATES_KERNEL,
)
_PACK_DCP_TOPK_CANDIDATES_KERNEL.register_warmup()
_STABLE_TOPK_FROM_GATHERED_CANDIDATES_KERNEL.register_warmup()
@property
def cp_kv_cache_interleave_size(self) -> int:
"""Resolved lazily like ``SparseAttnIndexer``: NIXL P/D can adjust it
after the model is built, and the indexer metadata builder sees the
adjusted value.
"""
if self.dcp_world_size == 1:
return 1
if self._cp_kv_cache_interleave_size is None:
assert self._parallel_config is not None
value = self._parallel_config.cp_kv_cache_interleave_size
if isinstance(get_forward_context().attn_metadata, dict):
self._cp_kv_cache_interleave_size = value
return value
return self._cp_kv_cache_interleave_size
def forward_native(
self,
@@ -743,4 +808,7 @@ class SparseAttnIndexerKpool(CustomOp):
self.tail_cache.kv_cache if self.tail_cache is not None else None,
self.tail_cache.prefix if self.tail_cache is not None else None,
self.topk_backend,
self.dcp_rank,
self.dcp_world_size,
self.cp_kv_cache_interleave_size,
)
+3 -3
View File
@@ -228,9 +228,9 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
-1, 1, kv_c_and_k_pe_cache.shape[-1]
)
# NOTE(Chen): kernel requires num_local_head to be a multiple of
# 64 on hopper and 128 on blackwell. Pad from q's head count, not
# self.num_heads: under DCP the heads are all-gathered before this.
# NOTE(Chen): kernel requires num_local_head to be a multiple of 64.
# Pad from q's head count, not self.num_heads: under DCP the heads are
# all-gathered before this.
if actual_num_heads is None:
actual_num_heads = q.shape[1]
padded_num_heads = (
+12 -4
View File
@@ -13,6 +13,10 @@ from vllm.config import VllmConfig
from vllm.distributed import divide
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.fusion.quant_activation import (
QuantizedActivation,
get_input_quant_key,
)
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
RowParallelLinear,
@@ -37,6 +41,7 @@ from vllm.model_executor.layers.mamba.ops.causal_conv1d import (
causal_conv1d_fn,
causal_conv1d_update,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
from vllm.model_executor.model_loader.weight_utils import sharded_weight_loader
from vllm.model_executor.utils import set_weight_attrs
from vllm.models.kimi_k3.amd.kda_metadata import KimiK3ROCmKDABackend
@@ -300,13 +305,16 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
qkv = qkv.permute(1, 0, 2, 3).contiguous().unsqueeze(1)
return qkv.unbind(0)
def get_input_quant_key(self) -> QuantKey | None:
return get_input_quant_key(self.in_proj_qkvgfab)
def forward(
self,
hidden_states: torch.Tensor,
hidden_states: torch.Tensor | QuantizedActivation,
positions: torch.Tensor,
) -> torch.Tensor:
num_tokens = hidden_states.size(0)
projected_qkvgfab = self.in_proj_qkvgfab(hidden_states)[0]
num_tokens = projected_qkvgfab.shape[0]
split_sizes = [
3 * self.local_projection_size,
@@ -326,8 +334,8 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
core_attn_out = torch.empty(
(1, num_tokens, self.local_num_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
dtype=projected_qkvgfab.dtype,
device=projected_qkvgfab.device,
)
self._forward(
+13 -3
View File
@@ -36,18 +36,23 @@ class ROCmLatentMoERunner(MoERunner):
up_proj = getattr(transform, "up_proj", None)
tp_size = get_tensor_model_parallel_world_size()
self._up_proj_preshard = bool(getattr(transform, "row_sharded", False))
self._up_proj_shard_size = 0
self._tail_shardable = (
up_proj is not None
and tp_size > 1
and up_proj.weight.shape[0] % tp_size == 0
and (self._up_proj_preshard or up_proj.weight.shape[0] % tp_size == 0)
and self._shared_experts is not None
and not self.moe_config.is_sequence_parallel
and self.routed_scaling_factor == 1.0
)
if self._tail_shardable:
assert up_proj is not None
self._up_proj_shard_size = up_proj.weight.shape[0] // tp_size
self._up_proj_shard_size = (
up_proj.weight.shape[0]
if self._up_proj_preshard
else up_proj.weight.shape[0] // tp_size
)
else:
logger.warning_once(
"K3 latent-MoE tail is not shardable under this config, "
@@ -80,7 +85,12 @@ class ROCmLatentMoERunner(MoERunner):
shard_size = self._up_proj_shard_size
shard_start = get_tensor_model_parallel_rank() * shard_size
up_proj_shard = transform.up_proj.weight.narrow(0, shard_start, shard_size)
weight = transform.up_proj.weight
up_proj_shard = (
weight
if self._up_proj_preshard
else weight.narrow(0, shard_start, shard_size)
)
hidden_shard = shared_output.narrow(-1, shard_start, shard_size)
# hidden_shard += latent @ up_proj_shard.T, accumulated in the GEMM's
+76 -14
View File
@@ -2,11 +2,12 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable
from typing import Any
from typing import Any, cast
import torch
from torch import nn
from vllm import envs
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import (
get_pp_group,
@@ -19,6 +20,10 @@ from vllm.model_executor.layers.fused_moe import (
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
from vllm.model_executor.layers.fusion.quant_activation import (
QuantizedActivation,
get_input_quant_key,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
@@ -38,6 +43,10 @@ from vllm.model_executor.layers.mamba.mamba_utils import (
)
from vllm.model_executor.layers.mla import MLAModules
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kFp8DynamicTokenSym,
)
from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
VocabParallelEmbedding,
@@ -114,6 +123,9 @@ class KimiMLP(nn.Module):
"Only silu and situ are supported."
)
def get_input_quant_key(self) -> QuantKey | None:
return get_input_quant_key(self.gate_up_proj)
def forward(self, x):
gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
@@ -125,11 +137,13 @@ class KimiRoutedOutputTransform(nn.Module):
def __init__(
self,
norm: RMSNorm | None,
up_proj: ReplicatedLinear,
up_proj: ReplicatedLinear | ColumnParallelLinear,
row_sharded: bool = False,
) -> None:
super().__init__()
self.norm = norm
self.up_proj = up_proj
self.row_sharded = row_sharded
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
if self.norm is not None:
@@ -148,8 +162,10 @@ def _apply_attn_res(
delta: torch.Tensor | None = None,
output_norm: RMSNorm | None = None,
block_write_idx: int = -1,
) -> torch.Tensor:
return attn_res(
quant_key: QuantKey | None = None,
) -> torch.Tensor | QuantizedActivation:
fuse_quant = quant_key == kFp8DynamicTokenSym and not envs.VLLM_BATCH_INVARIANT
result = attn_res(
prefix_sum,
delta,
block_residual,
@@ -160,7 +176,18 @@ def _apply_attn_res(
block_write_idx,
norm.variance_epsilon,
0.0 if output_norm is None else output_norm.variance_epsilon,
quant_dtype=cast(torch.dtype, kFp8DynamicTokenSym.dtype)
if fuse_quant
else None,
)
if fuse_quant:
assert isinstance(result, tuple)
data, scale = result
return QuantizedActivation(
data, scale, prefix_sum.dtype, prefix_sum.shape, kFp8DynamicTokenSym
)
assert isinstance(result, torch.Tensor)
return result
class KimiMoE(nn.Module):
@@ -240,7 +267,7 @@ class KimiMoE(nn.Module):
self.routed_expert_down_proj: ReplicatedLinear | None
self.routed_expert_norm: RMSNorm | None
self.routed_expert_up_proj: ReplicatedLinear | None
self.routed_expert_up_proj: ReplicatedLinear | ColumnParallelLinear | None
self.routed_output_transform: KimiRoutedOutputTransform | None
if self.use_latent_moe:
self.routed_expert_down_proj = ReplicatedLinear(
@@ -255,15 +282,36 @@ class KimiMoE(nn.Module):
if self.latent_moe_use_norm
else None
)
self.routed_expert_up_proj = ReplicatedLinear(
self.moe_hidden_size,
hidden_size,
bias=False,
quant_config=None,
prefix=f"{prefix}.routed_expert_up_proj",
shard_up_proj = (
self.tp_size > 1
and hidden_size % self.tp_size == 0
and self.num_shared_experts is not None
and self.routed_scaling_factor == 1.0
)
if shard_up_proj:
# gather_output is a fallback restoring the full hidden dim for
# the unfused tail. The fused tail reads from .weight directly
# so it is not triggered
self.routed_expert_up_proj = ColumnParallelLinear(
self.moe_hidden_size,
hidden_size,
bias=False,
gather_output=True,
quant_config=None,
prefix=f"{prefix}.routed_expert_up_proj",
)
else:
self.routed_expert_up_proj = ReplicatedLinear(
self.moe_hidden_size,
hidden_size,
bias=False,
quant_config=None,
prefix=f"{prefix}.routed_expert_up_proj",
)
self.routed_output_transform = KimiRoutedOutputTransform(
self.routed_expert_norm, self.routed_expert_up_proj
self.routed_expert_norm,
self.routed_expert_up_proj,
row_sharded=shard_up_proj,
)
else:
self.routed_expert_down_proj = None
@@ -452,10 +500,13 @@ class KimiMLAAttention(nn.Module):
prefix,
)
def get_input_quant_key(self) -> QuantKey | None:
return self.mla_attn.get_input_quant_key()
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
hidden_states: torch.Tensor | QuantizedActivation,
) -> torch.Tensor:
return self.mla_attn(positions, hidden_states)
@@ -579,7 +630,7 @@ class KimiDecoderLayer(nn.Module):
def _run_self_attn(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
hidden_states: torch.Tensor | QuantizedActivation,
) -> torch.Tensor:
return self.self_attn(
hidden_states=hidden_states,
@@ -626,6 +677,11 @@ class KimiDecoderLayer(nn.Module):
prefix_delta: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
prefix_sum = hidden_states
attention_quant_key = (
self.self_attn.get_input_quant_key()
if isinstance(self.self_attn, (KimiK3DeltaAttention, KimiMLAAttention))
else None
)
hidden_states = _apply_attn_res(
prefix_sum,
block_residual,
@@ -635,6 +691,7 @@ class KimiDecoderLayer(nn.Module):
delta=prefix_delta,
output_norm=self.input_layernorm,
block_write_idx=(self.block_write_idx if self.is_block_write_layer else -1),
quant_key=attention_quant_key,
)
if self.is_block_write_layer:
@@ -659,6 +716,11 @@ class KimiDecoderLayer(nn.Module):
mlp_valid_blocks,
delta=prefix_delta,
output_norm=self.post_attention_layernorm,
quant_key=(
self.mlp.get_input_quant_key()
if isinstance(self.mlp, KimiMLP)
else None
),
)
hidden_states = self.mlp(hidden_states)
+27 -2
View File
@@ -8,8 +8,13 @@ import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.attention.attention import get_attention_context
from vllm.model_executor.layers.fusion.quant_activation import (
QuantizedActivation,
get_input_quant_key,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.mla import MultiHeadLatentAttentionWrapper
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
from vllm.platforms import current_platform
_OPT_KV_LORA_RANK = 512
@@ -49,6 +54,21 @@ class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
not attn.is_aiter_triton_fp8_bmm_enabled and attn.W_UK_T is not None
)
def get_input_quant_key(self) -> QuantKey | None:
if self.indexer is not None:
return None
consumers = (
[self.fused_qkv_a_proj]
if self.q_lora_rank is not None
else [self.kv_a_proj_with_mqa, self.q_proj]
)
if self.g_proj is not None:
consumers.append(self.g_proj)
if any(layer is None for layer in consumers):
return None
keys = [get_input_quant_key(layer) for layer in consumers if layer is not None]
return keys[0] if all(key == keys[0] for key in keys) else None
def _normalize_q_kv(
self,
q_c: torch.Tensor,
@@ -173,10 +193,15 @@ class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
hidden_states: torch.Tensor | QuantizedActivation,
llama_4_scaling: torch.Tensor | None = None,
) -> torch.Tensor:
q_c = None
num_tokens = (
hidden_states.orig_shape[0]
if isinstance(hidden_states, QuantizedActivation)
else hidden_states.shape[0]
)
if self.q_lora_rank is not None:
assert self.fused_qkv_a_proj is not None, (
@@ -238,7 +263,7 @@ class KimiK3MultiHeadLatentAttentionWrapper(MultiHeadLatentAttentionWrapper):
if self.dcp_q_replicate:
q_dcp_replicated, q = q, q_proj_layer._local_view(q)
output_shape = (hidden_states.shape[0], self.num_heads * self.v_head_dim)
output_shape = (num_tokens, self.num_heads * self.v_head_dim)
# The fused decode path covers only the MQA slice, so it is taken for
# decode-only batches; anything else falls through to MLAAttention.
+4 -2
View File
@@ -9,6 +9,7 @@ import torch
from torch import nn
from vllm.config import VllmConfig
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.quantization.compressed_tensors import (
compressed_tensors,
@@ -65,6 +66,7 @@ class KimiK3ForConditionalGeneration(
"""Kimi-K3 model with Kimi-K2.5 vision and KimiLinear text."""
supports_encoder_tp_data = True
supports_mm_device_do_normalize = True
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
@@ -103,6 +105,7 @@ class KimiK3ForConditionalGeneration(
self.vision_tower = MoonViT3dPretrainedModel(
config.vision_config,
quant_config=self._maybe_ignore_quant_config(quant_config),
input_norm=build_mm_input_norm(vllm_config.model_config),
prefix=maybe_prefix(prefix, "vision_tower"),
)
if self._maybe_ignore_quant_config(quant_config) is not None:
@@ -114,6 +117,7 @@ class KimiK3ForConditionalGeneration(
self.mm_projector = KimiK25MultiModalProjector(
config=config.vision_config,
out_hidden_size=config.text_config.hidden_size,
use_data_parallel=self.use_data_parallel,
quant_config=self._maybe_ignore_quant_config(quant_config),
prefix=maybe_prefix(prefix, "mm_projector"),
@@ -163,8 +167,6 @@ class KimiK3ForConditionalGeneration(
pixel_values.shape[0] * pixel_values.shape[1], *pixel_values.shape[2:]
)
target_dtype = next(self.vision_tower.parameters()).dtype
pixel_values = pixel_values.to(target_dtype)
assert isinstance(grid_thws, torch.Tensor), (
f"expect grid_thws to be a tensor, got {type(grid_thws)}"
)
+28 -4
View File
@@ -10,6 +10,7 @@
import torch
from vllm.model_executor.layers.quantization.utils.quant_utils import get_fp8_min_max
from vllm.triton_utils import tl, triton
@@ -22,6 +23,7 @@ def _attn_res_kernel(
qk_weight_ptr,
output_norm_weight_ptr,
output_ptr,
output_scale_ptr,
stride_prefix_m: tl.constexpr,
stride_delta_m: tl.constexpr,
stride_block_m: tl.constexpr,
@@ -35,6 +37,7 @@ def _attn_res_kernel(
HAS_DELTA: tl.constexpr,
WRITE_BLOCK: tl.constexpr,
APPLY_OUTPUT_NORM: tl.constexpr,
QUANT_MAX: tl.constexpr,
BLOCK_L: tl.constexpr,
BLOCK_D: tl.constexpr,
):
@@ -129,6 +132,14 @@ def _attn_res_kernel(
output_norm_weight_ptr + d_offsets, mask=d_mask, other=0.0
).to(tl.float32)
output = mixed * output_reciprocal_std * output_norm_weight
if QUANT_MAX > 0:
# Preserve the rounding of the original BF16 output before quantizing.
output = output.to(prefix_ptr.dtype.element_ty).to(tl.float32)
amax = tl.max(tl.where(d_mask, tl.abs(output), 0.0), axis=0)
scale = tl.maximum(amax, 1e-10) * (1.0 / QUANT_MAX)
inv_scale = 1.0 / scale
output = tl.minimum(tl.maximum(output * inv_scale, -QUANT_MAX), QUANT_MAX)
tl.store(output_scale_ptr + row_idx, scale)
tl.store(
output_ptr + row_idx * stride_output_m + d_offsets,
output,
@@ -147,7 +158,9 @@ def attn_res(
block_write_idx: int,
eps: float,
output_norm_eps: float,
) -> torch.Tensor:
*,
quant_dtype: torch.dtype | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
num_tokens, hidden_size = prefix.shape
assert prefix.stride(-1) == 1
assert delta is None or delta.stride(-1) == 1
@@ -155,9 +168,18 @@ def attn_res(
assert norm_weight.stride(-1) == 1
assert qk_weight.stride(-1) == 1
assert output_norm_weight is None or output_norm_weight.stride(-1) == 1
output = prefix.new_empty(prefix.shape)
if quant_dtype is not None:
assert quant_dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz)
output = torch.empty_like(
prefix, dtype=quant_dtype or prefix.dtype, memory_format=torch.contiguous_format
)
scale = (
torch.empty((num_tokens, 1), device=prefix.device, dtype=torch.float32)
if quant_dtype is not None
else None
)
if num_tokens == 0:
return output
return output if scale is None else (output, scale)
# Source tiling helps decode, while one-source tiles scale better for prefill.
if num_tokens >= 256 or num_blocks <= 1:
@@ -172,6 +194,7 @@ def attn_res(
qk_weight,
output_norm_weight,
output,
scale,
prefix.stride(0),
0 if delta is None else delta.stride(0),
blocks.stride(0),
@@ -185,9 +208,10 @@ def attn_res(
HAS_DELTA=delta is not None,
WRITE_BLOCK=block_write_idx >= 0,
APPLY_OUTPUT_NORM=output_norm_weight is not None,
QUANT_MAX=0.0 if quant_dtype is None else get_fp8_min_max()[1],
BLOCK_L=block_l,
BLOCK_D=triton.next_power_of_2(hidden_size),
num_warps=num_warps,
num_stages=2,
)
return output
return output if scale is None else (output, scale)
+1 -1
View File
@@ -349,7 +349,7 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
for num_warps in [1, 2, 4, 8]
for num_stages in [2, 3, 4]
],
key=["BK", "NC", "BT", "HV"],
key=["BK", "BT", "HV"],
)
@triton.jit(do_not_specialize=["B", "T"])
def chunk_kda_fwd_kernel_intra_sub_chunk(
@@ -30,6 +30,9 @@ from vllm.multimodal.processing import (
from vllm.transformers_utils.configs.kimi_k3 import KimiK3Config
from vllm.transformers_utils.processor import cached_get_image_processor
from vllm.transformers_utils.processors.kimi_k3 import KimiK3Processor
from vllm.transformers_utils.processors.kimi_k25_vision_fused import (
KimiK25FusedVisionProcessor,
)
logger = init_logger(__name__)
@@ -106,6 +109,7 @@ class KimiK3ProcessingInfo(BaseProcessingInfo):
self.ctx.model_config.model,
revision=self.ctx.model_config.revision,
trust_remote_code=self.ctx.model_config.trust_remote_code,
processor_cls_overrides=KimiK25FusedVisionProcessor,
)
# Resolve token ID from the tokenizer because transformers v5
+5 -13
View File
@@ -409,20 +409,12 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
spec_sequence_masks_cpu &= (
query_start_loc_cpu.diff() <= self.num_spec + 1
)
# Native KDA can use its regular decode path when no draft token
# was scheduled. RecoverSSM must preserve its extended conv window.
if (
not self.use_recoverssm
and num_decode_draft_tokens_cpu[spec_sequence_masks_cpu].sum().item()
== 0
):
# A batch whose rows all drafted nothing still has to run the
# speculative path: that is the only path that applies each row's
# accepted-token offset to the recurrent state.
num_spec_decodes = spec_sequence_masks_cpu.sum().item()
if num_spec_decodes == 0:
spec_sequence_masks_cpu = None
num_spec_decodes = 0
active_non_spec_mask_cpu = None
else:
num_spec_decodes = spec_sequence_masks_cpu.sum().item()
if num_spec_decodes == 0:
spec_sequence_masks_cpu = None
spec_request_indices = None
spec_token_start = None
+13 -2
View File
@@ -422,6 +422,7 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
return MLAAttentionSpec( # type: ignore[call-arg]
block_size=vllm_config.cache_config.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.head_size,
dtype=kv_cache_dtype,
cache_dtype_str=self.kv_cache_dtype,
@@ -785,6 +786,15 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
cos_sin_cache=cos_sin_cache,
)
def _fused_mla_kv_concat(
self, kv_nope: torch.Tensor, k_pe: torch.Tensor, use_fp8_prefill: bool
) -> tuple[torch.Tensor, torch.Tensor]:
"""Pack one DCP context chunk's ``(k, v)`` with the fused kernels."""
k_nope, v = kv_nope.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
if use_fp8_prefill:
return fused_mla_kv_concat_quant_fp8(k_nope, k_pe, v)
return fused_mla_kv_concat(k_nope, k_pe), v
def _compute_prefill_context(
self,
q: torch.Tensor,
@@ -814,8 +824,8 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
copied per chunk.
Decode context parallelism keeps using
``impl._context_parallel_compute_prefill_context``; its extra allgather
and reorg are not fused here.
``impl._context_parallel_compute_prefill_context`` for its allgather and
reorg, with this layer's ``_fused_mla_kv_concat`` as its per-chunk pack.
"""
prefill = attn_metadata.prefill
assert prefill is not None
@@ -1074,6 +1084,7 @@ class MultiHeadLatentAttention(nn.Module, AttentionLayerBase):
attn_metadata,
k_scale=self._k_scale,
dcp_world_size=self.dcp_world_size,
fused_mla_kv_concat_fn=self._fused_mla_kv_concat,
)
)
else:
+49 -42
View File
@@ -30,6 +30,7 @@ from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
from vllm.model_executor.layers.fused_moe.router.grouped_topk_router import (
fused_grouped_topk,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
@@ -155,6 +156,20 @@ def shard_sequence_parallel_mlp(
)
def can_shard_sequence_parallel_shared_expert(vllm_config: VllmConfig) -> bool:
"""Whether the active MoE backend preserves the SP shared-expert contract.
MegaMoE invokes the shared expert directly. DeepEP v2 invokes it through
``MoERunner``, but its EP combine returns the routed output in the local
sequence-sharded layout, so the shared expert can use the same
all-gather/partial-GEMM/reduce-scatter implementation.
"""
return (
vllm_config.kernel_config.moe_backend == "deep_gemm_mega_moe"
or vllm_config.parallel_config.all2all_backend == "deepep_v2"
)
def maybe_init_gemm_rs_ar(vllm_config: VllmConfig, use_sequence_parallel: bool) -> bool:
# Both feature flags may be enabled; the worker's static SP topology binds
# its singleton to exactly one mode.
@@ -364,27 +379,16 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
return
self._check_runtime_supported()
from vllm.utils.deep_gemm import _import_deep_gemm
deep_gemm = _import_deep_gemm()
w13_scale = deep_gemm.transform_sf_into_required_layout(
self._ue8m0_uint8_to_float(self.w13_weight_scale.data).contiguous(),
2 * self.intermediate_size,
self.hidden_size,
(1, 32),
self.num_local_experts,
)
w2_scale = deep_gemm.transform_sf_into_required_layout(
self._ue8m0_uint8_to_float(self.w2_weight_scale.data).contiguous(),
self.hidden_size,
self.intermediate_size,
(1, 32),
self.num_local_experts,
)
backend = self._ensure_backend()
self._transformed_l1_weights, self._transformed_l2_weights = (
deep_gemm.transform_weights_for_mega_moe(
(self.w13_weight.data.view(torch.int8).contiguous(), w13_scale),
(self.w2_weight.data.view(torch.int8).contiguous(), w2_scale),
backend.transform_weights(
w13_weight=self.w13_weight.data,
w13_weight_scale=self.w13_weight_scale.data,
w2_weight=self.w2_weight.data,
w2_weight_scale=self.w2_weight_scale.data,
num_local_experts=self.num_local_experts,
hidden_size=self.hidden_size,
intermediate_size=self.intermediate_size,
activation=self.activation,
)
)
@@ -406,6 +410,7 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
from vllm.utils.deep_gemm import _import_deep_gemm
deep_gemm = _import_deep_gemm()
backend = self._ensure_backend()
group = get_ep_group().device_group
device = torch.accelerator.current_device_index()
key = (
@@ -417,6 +422,7 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
self.hidden_size,
self.intermediate_size,
self.activation,
backend.mma_type,
)
symm_buffer = self._kimi_symm_buffer_cache.get(key)
if symm_buffer is None:
@@ -428,6 +434,7 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
self.hidden_size,
self.intermediate_size,
activation=self.activation,
mma_type=backend.mma_type,
)
self._kimi_symm_buffer_cache[key] = symm_buffer
return symm_buffer
@@ -448,10 +455,6 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
f"but its symmetric buffer supports {self.max_num_tokens}."
)
y = torch.empty_like(hidden_states, dtype=torch.bfloat16)
from vllm.utils.deep_gemm import _import_deep_gemm
deep_gemm = _import_deep_gemm()
symm_buffer = self.get_symm_buffer()
num_tokens = hidden_states.shape[0]
is_padding = None
if envs.VLLM_MOE_SKIP_PADDING and is_forward_context_available():
@@ -482,6 +485,8 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
else None,
)
backend = self._ensure_backend()
symm_buffer = self.get_symm_buffer()
prepare_megamoe_inputs(
hidden_states,
topk_weights,
@@ -491,22 +496,23 @@ class KimiK3MegaMoEExperts(DeepseekV4MegaMoEExperts):
symm_buffer.topk_idx[:num_tokens],
symm_buffer.topk_weights[:num_tokens],
is_padding=is_padding,
hidden_quant=backend.hidden_quant,
)
self.finalize_weights()
assert self._transformed_l1_weights is not None
assert self._transformed_l2_weights is not None
deep_gemm.fp8_fp4_mega_moe(
y,
self._transformed_l1_weights,
self._transformed_l2_weights,
symm_buffer,
backend.run_mega_moe(
y=y,
l1_weights=self._transformed_l1_weights,
l2_weights=self._transformed_l2_weights,
symm_buffer=symm_buffer,
activation_clamp=activation_clamp,
activation=self.activation,
fast_math=fast_math,
# DeepGEMM names the SiTU gate tanh scale `activation_alpha` and the
# linear/up tanh scale `activation_beta`; beta=0 leaves up untouched.
activation=self.activation,
activation_alpha=self.activation_beta or 1.0,
activation_beta=self.activation_linear_beta or 0.0,
fast_math=fast_math,
)
return y
@@ -625,10 +631,12 @@ class KimiMoE(nn.Module):
quant_config=quant_config,
reduce_results=False,
use_sequence_parallel=use_sequence_parallel,
# Only the MegaMoE path calls the shared experts directly; the
# FusedMoE path below hands them to the runner, which fuses
# their reduction and assumes the replicated layout.
can_shard_sequence_parallel=self.use_mega_moe,
# MegaMoE calls the shared expert directly. DeepEP v2 hands it
# to MoERunner, but preserves the local SP output layout needed
# by the sharded shared-expert path.
can_shard_sequence_parallel=can_shard_sequence_parallel_shared_expert(
vllm_config
),
run_gemm_rs_ar=run_gemm_rs_ar,
prefix=f"{prefix}.shared_experts",
activation_situ_beta=activation_situ_beta,
@@ -1736,6 +1744,7 @@ class KimiK3ForConditionalGeneration(
"""Kimi-K3 model with Kimi-K2.5 vision and KimiLinear text."""
supports_encoder_tp_data = True
supports_mm_device_do_normalize = True
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
@@ -1775,6 +1784,7 @@ class KimiK3ForConditionalGeneration(
self.vision_tower = MoonViT3dPretrainedModel(
config.vision_config,
quant_config=self._maybe_ignore_quant_config(quant_config),
input_norm=build_mm_input_norm(vllm_config.model_config),
prefix=maybe_prefix(prefix, "vision_tower"),
)
if is_meta_module(self.vision_tower):
@@ -1815,6 +1825,7 @@ class KimiK3ForConditionalGeneration(
self.mm_projector = KimiK25MultiModalProjector(
config=config.vision_config,
out_hidden_size=config.text_config.hidden_size,
use_data_parallel=self.use_data_parallel,
quant_config=self._maybe_ignore_quant_config(quant_config),
prefix=maybe_prefix(prefix, "mm_projector"),
@@ -1964,13 +1975,13 @@ class KimiK3ForConditionalGeneration(
if isinstance(patch_size, int):
patch_size = (patch_size, patch_size)
total_patches = sum(t * h * w for t, h, w in grid_thws)
pixel_values = torch.randn(
pixel_values = torch.zeros(
total_patches,
3,
patch_size[0],
patch_size[1],
device=device,
dtype=dtype,
dtype=self.vision_tower.patch_embed.input_norm.input_dtype or dtype,
)
metadata = self.vision_tower.prepare_encoder_cudagraph_metadata(
grid_thws,
@@ -2028,9 +2039,7 @@ class KimiK3ForConditionalGeneration(
path: str = "default",
) -> torch.Tensor:
image_features = self.vision_tower(
self._get_pixel_values(mm_kwargs).to(
next(self.vision_tower.parameters()).dtype
),
self._get_pixel_values(mm_kwargs),
self._get_grid_thws(mm_kwargs),
)
return self._project_encoder_features(torch.cat(image_features))
@@ -2063,8 +2072,6 @@ class KimiK3ForConditionalGeneration(
pixel_values.shape[0] * pixel_values.shape[1], *pixel_values.shape[2:]
)
target_dtype = next(self.vision_tower.parameters()).dtype
pixel_values = pixel_values.to(target_dtype)
assert isinstance(grid_thws, torch.Tensor), (
f"expect grid_thws to be a tensor, got {type(grid_thws)}"
)
@@ -451,7 +451,7 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
for num_warps in [1, 2, 4, 8]
for num_stages in [2, 3, 4]
],
key=["BK", "NC", "BT", "HV"],
key=["BK", "BT", "HV"],
)
@triton.jit(do_not_specialize=["B", "T"])
def chunk_kda_fwd_kernel_intra_sub_chunk(
+1
View File
@@ -465,6 +465,7 @@ class MiniMaxM3MoE(nn.Module):
self.n_shared_experts if self.is_fused_shared_expert_enabled else None
),
fuse_shared_experts=self.is_fused_shared_expert_enabled,
shared_expert_prefix=f"{prefix}.shared_experts",
quant_config=quant_config,
prefix=f"{prefix}.experts",
)
+8 -7
View File
@@ -229,15 +229,16 @@ def _index_block_score_kernel(
if BLOCK_SIZE_Q * pid_q >= q_len:
return
q_ptrs = tl.make_block_ptr(
q_desc = tl.make_tensor_descriptor(
base=q_ptr + seq_start * stride_q_n + pid_h * stride_q_h,
shape=(q_len, head_dim),
strides=(stride_q_n, stride_q_d),
offsets=(pid_q * BLOCK_SIZE_Q, 0),
block_shape=(BLOCK_SIZE_Q, head_dim),
order=(1, 0),
shape=[q_len, head_dim],
strides=[stride_q_n, stride_q_d],
block_shape=[BLOCK_SIZE_Q, head_dim],
padding_option="zero",
)
q = tl.load(q_ptrs, boundary_check=(0,), padding_option="zero")
# 2. Perform the load by providing the multi-dimensional offset directly
q = q_desc.load([pid_q * BLOCK_SIZE_Q, 0])
q_start = prefix_len + pid_q * BLOCK_SIZE_Q
off_q = tl.arange(0, BLOCK_SIZE_Q) + pid_q * BLOCK_SIZE_Q + prefix_len
+16 -14
View File
@@ -139,15 +139,15 @@ def _gqa_sparse_fwd_kernel(
off_t = tl.arange(0, BLOCK_SIZE_T)
topk_idx = tl.load(t_ptr_j + off_t * stride_tk, mask=off_t < max_topk, other=-1)
real_topk = tl.sum((topk_idx >= 0).to(tl.int32), axis=0)
q_ptrs = tl.make_block_ptr(
q_desc = tl.make_tensor_descriptor(
base=q_ptr + q_start * stride_qn + pid_h * stride_qh,
shape=(q_len, gqa_group_size, head_dim),
strides=(stride_qn, stride_qh, stride_qd),
offsets=(pid_q_j * BLOCK_SIZE_Q, 0, 0),
block_shape=(BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(2, 1, 0),
shape=[q_len, gqa_group_size, head_dim],
strides=[stride_qn, stride_qh, stride_qd],
block_shape=[BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D],
padding_option="zero",
)
q = tl.load(q_ptrs, boundary_check=(0, 1, 2), padding_option="zero")
q = q_desc.load([pid_q_j * BLOCK_SIZE_Q, 0, 0])
m_i = tl.full((BLOCK_SIZE_QH,), float("-inf"), dtype=tl.float32)
lse_i = tl.full((BLOCK_SIZE_QH,), float("-inf"), dtype=tl.float32)
acc_o = tl.zeros((BLOCK_SIZE_QH, BLOCK_SIZE_D), dtype=tl.float32)
@@ -228,15 +228,17 @@ def _gqa_sparse_fwd_kernel(
lse_i = m_ij + tl.log2(tl.exp2(lse_i - m_ij) + l_ij)
acc_o = acc_o * tl.exp2(m_i - lse_i)[:, None]
acc_o = tl.reshape(acc_o, BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D)
o_ptrs = tl.make_block_ptr(
o_desc = tl.make_tensor_descriptor(
base=o_ptr + q_start * stride_on + pid_h * stride_oh,
shape=(q_len, gqa_group_size, head_dim),
strides=(stride_on, stride_oh, stride_od),
offsets=(pid_q_j * BLOCK_SIZE_Q, 0, 0),
block_shape=(BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(2, 1, 0),
shape=[q_len, gqa_group_size, head_dim],
strides=[stride_on, stride_oh, stride_od],
block_shape=[BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D],
)
o_desc.store(
offsets=[pid_q_j * BLOCK_SIZE_Q, 0, 0],
value=acc_o.to(o_ptr.dtype.element_ty),
)
tl.store(o_ptrs, acc_o.to(o_ptr.dtype.element_ty), boundary_check=(0, 1, 2))
@torch.no_grad()
@@ -110,7 +110,9 @@ def _gqa_sparse_fwd_kernel(
bt_row = block_table_ptr + pid_b * stride_bt_b
off_n = tl.arange(0, BLOCK_SIZE_K)
off_d = tl.arange(0, BLOCK_SIZE_D)
off_h = tl.arange(0, BLOCK_SIZE_H)
d_mask = off_d < head_dim
h_mask = off_h < gqa_group_size
for j in range(real_q_loop):
pid_q_j = pid_q * num_q_loop + j
t_ptr_j = t_ptr + (q_block_start + pid_q_j) * stride_tn + pid_kh * stride_th
@@ -118,15 +120,20 @@ def _gqa_sparse_fwd_kernel(
q_abs = prefix_len + pid_q_j * BLOCK_SIZE_Q
valid_blocks = (q_abs + BLOCK_SIZE_K) // BLOCK_SIZE_K
real_topk = tl.minimum(max_topk, valid_blocks)
q_ptrs = tl.make_block_ptr(
base=q_ptr + q_start * stride_qn + pid_h * stride_qh,
shape=(q_len, gqa_group_size, head_dim),
strides=(stride_qn, stride_qh, stride_qd),
offsets=(pid_q_j * BLOCK_SIZE_Q, 0, 0),
block_shape=(BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(2, 1, 0),
off_qi = pid_q_j * BLOCK_SIZE_Q + tl.arange(0, BLOCK_SIZE_Q)
qo_mask = (
(off_qi < q_len)[:, None, None]
& h_mask[None, :, None]
& d_mask[None, None, :]
)
q = tl.load(
q_ptr
+ (q_start + off_qi)[:, None, None] * stride_qn
+ (pid_h + off_h)[None, :, None] * stride_qh
+ off_d[None, None, :] * stride_qd,
mask=qo_mask,
other=0.0,
)
q = tl.load(q_ptrs, boundary_check=(0, 1, 2), padding_option="zero")
off_q = (
tl.arange(0, BLOCK_SIZE_Q)[:, None]
+ pid_q_j * BLOCK_SIZE_Q
@@ -203,15 +210,14 @@ def _gqa_sparse_fwd_kernel(
lse_i = m_ij + tl.log2(tl.exp2(lse_i - m_ij) + l_ij)
acc_o = acc_o * tl.exp2(m_i - lse_i)[:, None]
acc_o = tl.reshape(acc_o, BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D)
o_ptrs = tl.make_block_ptr(
base=o_ptr + q_start * stride_on + pid_h * stride_oh,
shape=(q_len, gqa_group_size, head_dim),
strides=(stride_on, stride_oh, stride_od),
offsets=(pid_q_j * BLOCK_SIZE_Q, 0, 0),
block_shape=(BLOCK_SIZE_Q, BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(2, 1, 0),
tl.store(
o_ptr
+ (q_start + off_qi)[:, None, None] * stride_on
+ (pid_h + off_h)[None, :, None] * stride_oh
+ off_d[None, None, :] * stride_od,
acc_o.to(o_ptr.dtype.element_ty),
mask=qo_mask,
)
tl.store(o_ptrs, acc_o.to(o_ptr.dtype.element_ty), boundary_check=(0, 1, 2))
# ---------------------------------------------------------------------------
@@ -298,7 +304,7 @@ def _gqa_sparse_decode_kernel(
# attention range instead of letting padded rows produce negative lengths.
kv_len = tl.maximum(query_pos + 1, 0)
# Valid block count from seq_len (no sentinel): min(topk, cdiv(kv_len, blk)).
# Upper bound on top-k entries from causal length; entries may be sentinels.
idx_base = t_ptr + pid_kh * stride_th + pid_b * stride_tn
num_blocks = (kv_len + BLOCK_SIZE_K - 1) // BLOCK_SIZE_K
real_topk = tl.minimum(max_topk, num_blocks)
@@ -306,30 +312,37 @@ def _gqa_sparse_decode_kernel(
off_n = tl.arange(0, BLOCK_SIZE_K)
off_d = tl.arange(0, BLOCK_SIZE_D)
off_h = tl.arange(0, BLOCK_SIZE_H)
d_mask = off_d < head_dim
h_mask = off_h < gqa_group_size
hd_mask = h_mask[:, None] & d_mask[None, :]
bt_row = block_table_ptr + req_id * stride_bt_b
m_i = tl.full((BLOCK_SIZE_H,), float("-inf"), dtype=tl.float32)
lse_i = tl.full((BLOCK_SIZE_H,), float("-inf"), dtype=tl.float32)
acc_o = tl.zeros((BLOCK_SIZE_H, BLOCK_SIZE_D), dtype=tl.float32)
q_ptrs = tl.make_block_ptr(
base=q_ptr + pid_b * stride_qn + pid_h * stride_qh,
shape=(gqa_group_size, head_dim),
strides=(stride_qh, stride_qd),
offsets=(0, 0),
block_shape=(BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(1, 0),
q = tl.load(
q_ptr
+ pid_b * stride_qn
+ (pid_h + off_h)[:, None] * stride_qh
+ off_d[None, :] * stride_qd,
mask=hd_mask,
other=0.0,
)
q = tl.load(q_ptrs, boundary_check=(0, 1), padding_option="zero")
cur_idx_ptr = idx_base + chunk_start_topk * stride_tk
for _ in tl.range(chunk_start_topk, chunk_end_topk):
blk = tl.load(cur_idx_ptr).to(tl.int32)
cur_idx_ptr = cur_idx_ptr + stride_tk
c = blk * BLOCK_SIZE_K
page = tl.load(bt_row + blk).to(tl.int64)
# topk_idx uses -1 for unused entries. Select a safe logical block
# before dereferencing the block table; invalid and future blocks then
# contribute a neutral online-softmax update without control flow.
valid_blk = (blk >= 0) & (blk < num_blocks)
safe_blk = tl.where(valid_blk, blk, 0)
c = safe_blk * BLOCK_SIZE_K
page = tl.load(bt_row + safe_blk).to(tl.int64)
pos = c + off_n
pos_mask = pos < kv_len
pos_mask = (pos < kv_len) & valid_blk
k = tl.load(
kv_cache_ptr
+ page * stride_kv_blk
@@ -356,9 +369,11 @@ def _gqa_sparse_decode_kernel(
qk += tl.where(pos_mask[None, :], 0, float("-inf"))
qk += tl.dot(q, k) * sm_scale_log2e
m_ij = tl.maximum(m_i, tl.max(qk, axis=1))
p = tl.exp2(qk - m_ij[:, None])
m_safe = tl.where(valid_blk, m_ij, 0.0)
p = tl.where(pos_mask[None, :], tl.exp2(qk - m_safe[:, None]), 0.0)
l_ij = tl.sum(p, axis=1)
acc_o = acc_o * tl.exp2(m_i - m_ij)[:, None]
alpha = tl.where(valid_blk, tl.exp2(m_i - m_safe), 1.0)
acc_o = acc_o * alpha[:, None]
v = tl.load(
kv_cache_ptr
+ page * stride_kv_blk
@@ -382,8 +397,9 @@ def _gqa_sparse_decode_kernel(
)
v = (v * v_scale[:, None]).to(q.dtype)
acc_o += tl.dot(p.to(v.dtype), v)
m_i = m_ij
lse_i = m_ij + tl.log2(tl.exp2(lse_i - m_ij) + l_ij)
lse_ij = m_safe + tl.log2(tl.exp2(lse_i - m_safe) + l_ij)
m_i = tl.where(valid_blk, m_safe, m_i)
lse_i = tl.where(valid_blk, lse_ij, lse_i)
if USE_PDL:
tl.extra.cuda.gdc_launch_dependents()
@@ -392,24 +408,23 @@ def _gqa_sparse_decode_kernel(
# can hit 0 * NaN. All-empty padded rows may still produce NaNs in merge.
scale = tl.where(lse_i > float("-inf"), tl.exp2(m_i - lse_i), tl.zeros_like(lse_i))
acc_o = acc_o * scale[:, None]
o_ptrs = tl.make_block_ptr(
base=o_ptr + pid_c * stride_o_c + pid_b * stride_o_b + pid_h * stride_o_h,
shape=(gqa_group_size, head_dim),
strides=(stride_o_h, stride_o_d),
offsets=(0, 0),
block_shape=(BLOCK_SIZE_H, BLOCK_SIZE_D),
order=(1, 0),
tl.store(
o_ptr
+ pid_c * stride_o_c
+ pid_b * stride_o_b
+ (pid_h + off_h)[:, None] * stride_o_h
+ off_d[None, :] * stride_o_d,
acc_o.to(o_ptr.dtype.element_ty),
mask=hd_mask,
)
tl.store(o_ptrs, acc_o.to(o_ptr.dtype.element_ty), boundary_check=(0, 1))
lse_ptrs = tl.make_block_ptr(
base=lse_ptr + pid_c * stride_l_c + pid_b * stride_l_b + pid_h * stride_l_h,
shape=(gqa_group_size,),
strides=(stride_l_h,),
offsets=(0,),
block_shape=(BLOCK_SIZE_H,),
order=(0,),
tl.store(
lse_ptr
+ pid_c * stride_l_c
+ pid_b * stride_l_b
+ (pid_h + off_h) * stride_l_h,
lse_i.to(lse_ptr.dtype.element_ty),
mask=h_mask,
)
tl.store(lse_ptrs, lse_i.to(lse_ptr.dtype.element_ty), boundary_check=(0,))
@triton.heuristics(
@@ -444,16 +459,16 @@ def _merge_topk_attn_out_kernel(
off_c = tl.arange(0, NUM_TOPK_CHUNKS)
off_d = tl.arange(0, BLOCK_SIZE_D)
o_ptrs = tl.make_block_ptr(
base=o_ptr + pid_b * stride_o_b + pid_h * stride_o_h,
shape=(NUM_TOPK_CHUNKS, head_dim),
strides=(stride_o_c, stride_o_d),
offsets=(0, 0),
block_shape=(NUM_TOPK_CHUNKS, BLOCK_SIZE_D),
order=(1, 0),
d_mask = off_d < head_dim
o_ptrs = (
o_ptr
+ pid_b * stride_o_b
+ pid_h * stride_o_h
+ off_c[:, None] * stride_o_c
+ off_d[None, :] * stride_o_d
)
lse_ptrs = lse_ptr + pid_b * stride_l_b + pid_h * stride_l_h + off_c * stride_l_c
o = tl.load(o_ptrs, boundary_check=(0, 1), padding_option="zero")
o = tl.load(o_ptrs, mask=d_mask[None, :], other=0.0)
lse = tl.load(lse_ptrs) # empty chunks contribute -inf -> weight 0
lse_max = tl.max(lse, axis=0)
weights = tl.exp2(lse - lse_max)
@@ -462,7 +477,7 @@ def _merge_topk_attn_out_kernel(
out_ptrs = (
out_ptr + pid_b * stride_out_n + pid_h * stride_out_h + off_d * stride_out_d
)
tl.store(out_ptrs, o_merged.to(out_ptr.dtype.element_ty), mask=off_d < head_dim)
tl.store(out_ptrs, o_merged.to(out_ptr.dtype.element_ty), mask=d_mask)
# ---------------------------------------------------------------------------
@@ -287,6 +287,8 @@ class IndexDecodeScoreKernel:
cute.arch.barrier(barrier_id=self.BAR_MMA, number_of_threads=128)
for q in cutlass.range_constexpr(Q_TILES):
cute.copy(ldsm_atom, sQ_ldsm[None, (q, None)], rQ[None, None, q])
# Order ldmatrix reads before the producer refills this stage with TMA.
cute.arch.fence_proxy("async.shared", space="cta")
cute.arch.mbarrier_arrive(tma_empty_mbar)
tma_stage = 1 % self.num_stages
@@ -342,6 +344,7 @@ class IndexDecodeScoreKernel:
rC[None, m, n],
)
cute.arch.fence_proxy("async.shared", space="cta")
cute.arch.mbarrier_arrive(tma_empty_mbar + tma_stage)
k_start = block_id * BLOCK_K + warp_id * 32
+127 -21
View File
@@ -4,7 +4,7 @@
from __future__ import annotations
from typing import cast
from typing import TYPE_CHECKING, cast
import torch
from torch import nn
@@ -23,6 +23,10 @@ from ..common.qsa_cache import (
QSAKeyStateCache,
canonical_qsa_rope_positions,
)
from .ops.qsa_prepare import qsa_prepare, supports_fused_pre_indexer
if TYPE_CHECKING:
from .qsa import Qwen4ExpQSAAttention
def apply_qsa_rope(
@@ -98,6 +102,12 @@ class QSAIndexer(nn.Module):
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.
@@ -143,20 +153,27 @@ class QSAIndexer(nn.Module):
def output_width(self) -> int:
return self.token_topk + self.compress_ratio - 1
def project_qk(
def project(
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Project replicated Q/K, normalize+rotate Q, and preserve raw K."""
"""Project replicated Q/K and split, leaving both operands unrotated."""
qk, _ = self.index_qk_proj(hidden_states)
q_raw, token_k = qk.split(
return qk.split(
(
self.index_n_heads * self.index_head_dim,
self.index_kv_heads * self.index_head_dim,
),
dim=-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."""
q_raw, token_k = self.project(hidden_states)
q = q_raw.reshape(-1, self.index_n_heads, self.index_head_dim)
q = apply_qsa_rmsnorm(
self.q_layernorm,
@@ -251,6 +268,66 @@ class QSAIndexer(nn.Module):
position_rows,
)
def _fused_prepare(
self,
projected_q: torch.Tensor,
raw_keys: torch.Tensor,
positions: torch.Tensor,
raw_metadata: QSAForwardMetadata,
compressed_metadata: QSAForwardMetadata,
attn: Qwen4ExpQSAAttention,
qkv: torch.Tensor,
slot_mapping: torch.Tensor,
gate_out: torch.Tensor | None,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
"""Prepare the indexer and ``attn``'s main attention in one launch.
Normalizes and rotates the index Q, compresses K and writes both side
caches, which replaces ``project_qk``'s norm/RoPE half and the whole of
``_update_and_compress``. The same launch applies ``attn``'s QK-norm and
RoPE, copies its gate and writes its K/V into ``attn.kv_cache``,
replacing ``_project_qkv_gate`` and ``do_kv_cache_update``. Both halves
must stay numerically interchangeable with what they replace.
"""
num_tokens = raw_metadata.num_actual_tokens
raw_key_cache = self.raw_key_cache
q = projected_q.new_empty(num_tokens, self.index_n_heads, self.index_head_dim)
main_outputs = qsa_prepare(
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_cache.kv_cache,
raw_metadata.slot_mapping,
raw_metadata.block_table,
raw_metadata.query_start_loc,
raw_metadata.logical_positions,
self.compressed_key_cache.kv_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_cache.rope_position_offset
if raw_key_cache.cache_rope_positions
else None
),
main_qkv=qkv[:num_tokens],
main_q_norm_weight=attn.q_norm.weight,
main_k_norm_weight=attn.k_norm.weight,
main_eps=attn.q_norm.variance_epsilon,
main_kv_cache=attn.kv_cache.transpose(1, 2),
main_slot_mapping=slot_mapping[:num_tokens],
main_k_scale=attn._k_scale_float,
main_v_scale=attn._v_scale_float,
main_gate_out=None if gate_out is None else gate_out[:num_tokens],
)
return q, main_outputs
def _select(
self,
q: torch.Tensor,
@@ -276,13 +353,25 @@ class QSAIndexer(nn.Module):
hidden_states: torch.Tensor,
positions: torch.Tensor,
out: torch.Tensor | None = None,
) -> torch.Tensor:
"""Return fixed-width request-relative token indices padded with ``-1``."""
*,
attn: Qwen4ExpQSAAttention,
qkv: torch.Tensor | None = None,
slot_mapping: torch.Tensor | None = None,
gate_out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
"""Return fixed-width request-relative token indices padded with ``-1``.
With ``attn.use_fused_qsa_prepare``, the same launch also writes
``attn``'s K/V into ``attn.kv_cache`` at ``slot_mapping`` and prepares
its Q and gate from ``qkv``, returned as the second element (None
otherwise). The gate is written into ``gate_out`` when given. ``qkv``,
``slot_mapping`` and ``gate_out`` are only read in that mode.
"""
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
return out, None
result = torch.full(
(hidden_states.shape[0], self.output_width),
-1,
@@ -291,24 +380,41 @@ class QSAIndexer(nn.Module):
)
if out is not None:
out.copy_(result)
return out
return result
return out, None
return result, None
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,
)
hidden_states = hidden_states[:num_tokens]
positions = positions[..., :num_tokens]
main_outputs: tuple[torch.Tensor, torch.Tensor] | None = None
if attn.use_fused_qsa_prepare:
if qkv is None or slot_mapping is None:
raise ValueError("fused QSA prepare requires qkv and slot_mapping")
projected_q, raw_keys = self.project(hidden_states)
q, main_outputs = self._fused_prepare(
projected_q,
raw_keys,
positions,
raw_metadata,
compressed_metadata,
attn,
qkv,
slot_mapping,
gate_out,
)
else:
q, token_k = self.project_qk(hidden_states, positions)
self._update_and_compress(
token_k,
positions,
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)
return out, main_outputs
return self._select(q, compressed_metadata, out), main_outputs
__all__ = ["QSAIndexer", "apply_qsa_rope"]
+10 -8
View File
@@ -141,9 +141,9 @@ _QWEN4_EXP_IGNORED_MISSING_SUFFIXES = [
"_input_scale",
]
# The checkpoint keeps down and injection projections separate; runtime packs
# them into adjacent logical shards of one MergedColumnParallelLinear.
_HC_WEIGHTS_MAPPER = WeightsMapper(
# The checkpoint stores these projections separately; runtime packs each group
# into adjacent logical shards of a MergedColumnParallelLinear.
_EXTRA_WEIGHTS_MAPPER = WeightsMapper(
orig_to_new_stacked={
"hyper_connection.input_mix_weight_down.weight": (
"hyper_connection.input_mix_weight_down_block_inject.weight",
@@ -153,6 +153,8 @@ _HC_WEIGHTS_MAPPER = WeightsMapper(
"hyper_connection.input_mix_weight_down_block_inject.weight",
1,
),
"ple.key_proj": ("ple.kv_proj", 0),
"ple.value_proj": ("ple.kv_proj", 1),
}
)
@@ -277,7 +279,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
if input_ids is None or query_start_loc is None or ngram_context is None:
raise RuntimeError("PLE inputs were not prepared")
hidden_states = hidden_states + self.ple(
hidden_states = self.ple(
hidden_states,
input_ids,
query_start_loc,
@@ -372,7 +374,7 @@ class Qwen4ExpMixtureOfExperts(MixtureOfExperts):
}
)
class Qwen4ExpModel(nn.Module):
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _EXTRA_WEIGHTS_MAPPER
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
super().__init__()
@@ -581,6 +583,7 @@ class Qwen4ExpForCausalLM(
packed_modules_mapping = {
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
"gate_up_proj": ["gate_proj", "up_proj"],
"kv_proj": ["key_proj", "value_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": [
@@ -631,8 +634,6 @@ class Qwen4ExpForCausalLM(
inputs_embeds: torch.Tensor | None = None,
**kwargs: object,
) -> torch.Tensor | IntermediateTensors:
# Forward kwargs unchanged so the runner's _maybe_add_ngram_kwargs
# path (query_start_loc / ngram_context) reaches Qwen4ExpModel.
return self.model(
input_ids,
positions,
@@ -812,11 +813,12 @@ class Qwen4ExpForConditionalGeneration(
requires_raw_input_tokens = True
packed_modules_mapping = Qwen3_5ForConditionalGeneration.packed_modules_mapping | {
"kv_proj": ["key_proj", "value_proj"],
"input_mix_weight_down_block_inject": [
"input_mix_weight_down",
"block_inject_weight",
"_input_mix_padding",
]
],
}
@staticmethod
+2 -2
View File
@@ -50,7 +50,7 @@ from vllm.sequence import IntermediateTensors
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
from .model import (
_HC_WEIGHTS_MAPPER,
_EXTRA_WEIGHTS_MAPPER,
_QWEN4_EXP_IGNORED_MISSING_SUFFIXES,
Qwen4ExpDecoderLayer,
Qwen4ExpMixtureOfExperts,
@@ -172,7 +172,7 @@ def _make_draft_vllm_config(
}
)
class Qwen4ExpMultiTokenPredictor(nn.Module):
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _HC_WEIGHTS_MAPPER
hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper | _EXTRA_WEIGHTS_MAPPER
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
super().__init__()
@@ -0,0 +1,703 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused QSA prepare kernel for the AMD Qwen4Exp path.
Started as a copy of the NVIDIA kernel (``nvidia/ops/qsa_prepare.py``) and is
kept separate so either vendor can change its own copy without re-validating
the other. The state source select is two masked loads rather than a pointer
select, which ROCm Triton rejects.
"""
import torch
from torch import nn
from vllm.triton_utils import tl, triton
def supports_fused_pre_indexer(
rotary_emb: nn.Module,
head_dim: int,
num_kv_heads: int,
compress_ratio: int,
) -> bool:
"""Report whether this indexer's shapes match the fused kernel's assumptions.
The kernel hard-codes the rotary layout and the single-KV-head group
compression it was written for; everything it rejects has a working unfused
path.
"""
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
)
@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
def _to_dst_dtype(x, dst, scale):
"""Round to BF16 like the unfused path, then scale for an FP8 destination."""
out_ty = dst.dtype.element_ty
x = x.to(tl.bfloat16)
if out_ty == tl.float8e4nv:
x = x.to(tl.float32) / scale
return x.to(out_ty)
@triton.jit
def _store_rotated(dst, y, o1, o2, scale):
"""Store a normalized head whose first ``2 * len(o1)`` dims are rotated."""
HALF: tl.constexpr = o1.shape[0]
dims = tl.arange(0, y.shape[0])
rot = tl.arange(0, HALF)
tl.store(dst + dims, _to_dst_dtype(y, dst, scale), mask=dims >= 2 * HALF)
tl.store(dst + rot, _to_dst_dtype(o1, dst, scale))
tl.store(dst + HALF + rot, _to_dst_dtype(o2, dst, scale))
@triton.jit(
do_not_specialize=[
"num_tokens",
"num_state_blocks",
"num_compressed_blocks",
"num_k_work",
]
)
def _qsa_prepare_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,
main_qkv_ptr,
main_q_norm_weight_ptr,
main_k_norm_weight_ptr,
main_eps,
main_q_out_ptr,
main_gate_out_ptr,
main_cache_ptr,
main_cache_stride_block,
main_cache_stride_token,
main_cache_stride_head,
main_slots_ptr,
main_k_scale,
main_v_scale,
MAIN_HQ: tl.constexpr,
MAIN_HK: tl.constexpr,
MAIN_D: tl.constexpr,
MAIN_PAGE_SIZE: tl.constexpr,
):
pid = tl.program_id(0)
num_index_work = num_k_work + tl.cdiv(num_tokens, TILE_T_Q) * tl.cdiv(HQ, TILE_H_Q)
if pid >= num_index_work:
# Main attention: one program per (token, Q or KV head) after the
# indexer work. RoPE covers the first D // 2 dims, the width of the
# shared cos/sin table.
main_pid = pid - num_index_work
token = (main_pid // (MAIN_HQ + MAIN_HK)).to(tl.int64)
head = main_pid % (MAIN_HQ + MAIN_HK)
HALF: tl.constexpr = D // 4
dims = tl.arange(0, MAIN_D)
rot = tl.arange(0, HALF)
row = main_qkv_ptr + token * (2 * (MAIN_HQ + MAIN_HK) * MAIN_D)
is_k = head >= MAIN_HQ
kv_head = head - MAIN_HQ
if is_k:
src = row + (2 * MAIN_HQ + kv_head) * MAIN_D
weight_ptr = main_k_norm_weight_ptr
else:
src = row + 2 * head * MAIN_D
weight_ptr = main_q_norm_weight_ptr
x = tl.load(src + dims).to(tl.float32)
inv_rms = tl.rsqrt(tl.sum(x * x, axis=0) / MAIN_D + main_eps)
w = tl.load(weight_ptr + dims).to(tl.float32) + 1.0
y = x * inv_rms * w
x1 = tl.load(src + rot).to(tl.float32)
x2 = tl.load(src + HALF + rot).to(tl.float32)
w1 = tl.load(weight_ptr + rot).to(tl.float32) + 1.0
w2 = tl.load(weight_ptr + HALF + rot).to(tl.float32) + 1.0
x1 = (x1 * inv_rms * w1).to(tl.bfloat16).to(tl.float32)
x2 = (x2 * inv_rms * w2).to(tl.bfloat16).to(tl.float32)
pos = tl.load(pos_ptr + token * pos_stride_token).to(tl.int64)
if IS_2D_POSITIONS:
pos_h = tl.load(pos_ptr + pos_stride_axis + token * pos_stride_token)
pos_w = tl.load(pos_ptr + 2 * pos_stride_axis + token * pos_stride_token)
is_h = (rot % 3 == 1) & (rot < 3 * MROPE_H)
is_w = (rot % 3 == 2) & (rot < 3 * MROPE_W)
pos = tl.where(
is_h, pos_h.to(tl.int64), tl.where(is_w, pos_w.to(tl.int64), pos)
)
cos = tl.load(cos_sin_ptr + pos * (D // 2) + rot).to(tl.float32)
sin = tl.load(cos_sin_ptr + pos * (D // 2) + HALF + rot).to(tl.float32)
o1 = x1 * cos - x2 * sin
o2 = x2 * cos + x1 * sin
if is_k:
slot = tl.load(main_slots_ptr + token).to(tl.int64)
if slot >= 0:
dst = (
main_cache_ptr
+ (slot // MAIN_PAGE_SIZE) * main_cache_stride_block
+ (slot % MAIN_PAGE_SIZE) * main_cache_stride_token
+ kv_head * main_cache_stride_head
)
_store_rotated(dst, y, o1, o2, main_k_scale)
v = tl.load(src + MAIN_HK * MAIN_D + dims)
tl.store(dst + MAIN_D + dims, _to_dst_dtype(v, dst, main_v_scale))
else:
out = (token * MAIN_HQ + head) * MAIN_D
_store_rotated(main_q_out_ptr + out, y, o1, o2, None)
gate = tl.load(src + MAIN_D + dims)
tl.store(main_gate_out_ptr + out + dims, gate)
return
# 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)).to(tl.int64)
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_in_cache = 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).to(tl.int64)[:, 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, so
# every row comes from exactly one of the two sources. Selecting
# between the base pointers would need a pointer-typed tl.where,
# which ROCm's Triton rejects ("'tt.addptr' op failed to verify
# that result type matches ptr type"), so select the loaded values
# instead. The two masks are complementary, so no lane fetches from
# both and memory traffic is unchanged.
#
# Both bases still need the alignment stated explicitly. Without it
# Triton vectorizes these loads differently, which reorders the
# pooling reduction below; float addition is not associative, so the
# compressed rows stop matching the unfused path bit for bit and an
# FP8 cache rounds a near-zero pooled value to the wrong code.
current_base = tl.multiple_of(current_base, (8, 8))
cached_base = tl.multiple_of(cached_base, (8, 8))
from_chunk = valid & source_in_chunk[:, None] & source_tokens_valid[:, None]
from_cache = valid & source_in_cache[:, None] & state_block_valid
current = tl.load(current_base + dims[None, :], mask=from_chunk, other=0.0)
cached = tl.load(cached_base + dims[None, :], mask=from_cache, other=0.0)
source = tl.where(source_in_chunk[:, None], current, cached).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).to(tl.int64)
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_prepare(
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,
main_qkv: torch.Tensor,
main_q_norm_weight: torch.Tensor,
main_k_norm_weight: torch.Tensor,
main_eps: float,
main_kv_cache: torch.Tensor,
main_slot_mapping: torch.Tensor,
main_k_scale: float,
main_v_scale: float,
main_gate_out: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Normalize Q, compress K, then update the circular raw state.
Also prepares the main attention (QK-norm/RoPE, gate copy, K/V cache write)
and returns its Q and gate. ``main_gate_out`` lets the gate land in a
caller-owned buffer, e.g. one that outlives an opaque custom op.
"""
num_tokens = q.shape[0]
main_head_dim = main_kv_cache.shape[-1] // 2
num_main_kv_heads = main_kv_cache.shape[2]
num_main_q_heads = main_qkv.shape[1] // (2 * main_head_dim) - num_main_kv_heads
main_q_out = main_qkv.new_empty(num_tokens, num_main_q_heads, main_head_dim)
if main_gate_out is None:
main_gate_out = torch.empty_like(main_q_out)
else:
assert main_gate_out.shape == main_q_out.shape
assert main_gate_out.is_contiguous()
if num_tokens == 0:
return main_q_out, main_gate_out
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
qkv_width = 2 * (num_main_q_heads + num_main_kv_heads) * main_head_dim
assert main_qkv.shape == (num_tokens, qkv_width) and main_qkv.is_contiguous()
assert main_slot_mapping.shape == (num_tokens,)
# Swept on MI355X (64-lane wavefronts) over TILE_T_Q 1-16, TILE_H_Q 1-4 and
# num_warps 1/2/4, from 4 to 16384 tokens: no config beat these by more
# than noise, and 2 or 4 warps were slower everywhere.
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)
num_main_work = num_tokens * (num_main_q_heads + num_main_kv_heads)
_qsa_prepare_kernel[(num_k_work + num_q_work + num_main_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],
main_qkv_ptr=main_qkv,
main_q_norm_weight_ptr=main_q_norm_weight,
main_k_norm_weight_ptr=main_k_norm_weight,
main_eps=main_eps,
main_q_out_ptr=main_q_out,
main_gate_out_ptr=main_gate_out,
main_cache_ptr=main_kv_cache,
main_cache_stride_block=main_kv_cache.stride(0),
main_cache_stride_token=main_kv_cache.stride(1),
main_cache_stride_head=main_kv_cache.stride(2),
main_slots_ptr=main_slot_mapping,
main_k_scale=main_k_scale,
main_v_scale=main_v_scale,
MAIN_HQ=num_main_q_heads,
MAIN_HK=num_main_kv_heads,
MAIN_D=main_head_dim,
MAIN_PAGE_SIZE=main_kv_cache.shape[1],
num_warps=1,
)
return main_q_out, main_gate_out
__all__ = ["qsa_prepare", "supports_fused_pre_indexer"]
+206 -574
View File
@@ -2,18 +2,16 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GPU-resident Qwen4Exp position-learning enhancement layers."""
import math
from collections.abc import Iterable, Sequence
import torch
import torch.nn.functional as F
from torch import nn
from transformers import Qwen4ExpTextConfig
from vllm.config import CacheConfig, ModelConfig, VllmConfig, get_current_vllm_config
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
from vllm.model_executor.layers.mamba.abstract import MambaBase
from vllm.model_executor.layers.mamba.mamba_utils import (
MambaStateDtypeCalculator,
@@ -30,13 +28,13 @@ from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionBackend,
PleShortConvAttentionMetadata,
)
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from ..common.ngram_embedding import (
Qwen4ExpPLEDeviceEmbedding,
Qwen4ExpPLEEmbeddingMethod,
Qwen4ExpPLEPinnedHostEmbedding,
)
from ..common.ops.ple import ple_conv, ple_gate, ple_ngram_ids
logger = init_logger(__name__)
@@ -177,7 +175,6 @@ class Qwen4ExpNGramEmbedding(nn.Module):
embedding_dim: int,
ple_dense_layer_id: int,
max_total_tokens: int,
max_num_reqs: int,
prefix: str,
layer_name: str,
*,
@@ -270,55 +267,6 @@ class Qwen4ExpNGramEmbedding(nn.Module):
self.ngram_embedding.weight.device,
self.ngram_embedding.weight.is_pinned(),
)
self.register_buffer(
"positions_buffer",
torch.arange(max_total_tokens, dtype=torch.int64),
persistent=False,
)
self.register_buffer(
"padded_buffer",
torch.full(
(max_num_reqs, max_total_tokens),
self.eos_token_id,
dtype=torch.int64,
),
persistent=False,
)
@staticmethod
def _shift_precompute(
tokens: torch.Tensor, eos_token_id: int
) -> tuple[torch.Tensor, torch.Tensor]:
if tokens.dim() != 2:
raise ValueError("tokens must be a 2D tensor")
batch_size, seq_len = tokens.shape
positions = torch.arange(seq_len, device=tokens.device, dtype=torch.int64)
eos_positions = torch.where(tokens == eos_token_id, positions, -1)
previous_eos_inclusive = torch.cummax(eos_positions, dim=1).values
previous_eos = torch.cat(
[
eos_positions.new_full((batch_size, 1), -1),
previous_eos_inclusive[:, :-1],
],
dim=1,
)
return positions, positions.unsqueeze(0) - previous_eos - 1
@staticmethod
def _shift_apply(
tokens: torch.Tensor,
positions: torch.Tensor,
position_in_segment: torch.Tensor,
shift: int,
eos_token_id: int,
) -> torch.Tensor:
if shift == 0:
return tokens
source = positions - shift
gather_indices = source.clamp_min(0).unsqueeze(0).expand(tokens.shape[0], -1)
shifted = tokens.gather(1, gather_indices)
valid = (source.unsqueeze(0) >= 0) & (position_in_segment >= shift)
return torch.where(valid, shifted, tokens.new_full((), eos_token_id))
def forward(
self,
@@ -326,64 +274,17 @@ class Qwen4ExpNGramEmbedding(nn.Module):
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
) -> torch.Tensor:
input_ids = input_ids.reshape(-1).long()
query_start_loc = query_start_loc.long()
num_reqs = query_start_loc.numel() - 1
num_tokens = input_ids.shape[0]
if num_tokens > self.positions_buffer.numel():
raise ValueError(
f"PLE received {num_tokens} tokens, but its workspace supports "
f"at most {self.positions_buffer.numel()}"
)
if num_reqs > self.padded_buffer.shape[0]:
raise ValueError(
f"PLE received {num_reqs} requests, but its workspace supports "
f"at most {self.padded_buffer.shape[0]}"
)
positions = self.positions_buffer[:num_tokens]
packed = self.padded_buffer[:num_reqs]
packed.fill_(self.eos_token_id)
request_indices = torch.searchsorted(query_start_loc, positions, right=True) - 1
request_indices.clamp_(max=num_reqs - 1)
columns = (positions - query_start_loc[request_indices]).clamp(
0, packed.shape[1] - 1
input_ids = input_ids.reshape(-1)
ngram_ids = input_ids.new_empty(
(input_ids.shape[0], self.ngram_heads), dtype=torch.int64
)
packed[request_indices, columns] = input_ids
ngram_context = ngram_context[:num_reqs].to(
device=input_ids.device, dtype=torch.long
torch.ops.vllm.qwen4_exp_amd_ple_ngram_ids(
input_ids,
query_start_loc,
ngram_context,
ngram_ids,
self.layer_name,
)
context = torch.cat([ngram_context, packed], dim=-1)
positions_2d, position_in_segment = self._shift_precompute(
context, self.eos_token_id
)
shifted = [context]
for shift in range(1, self.ngram_size):
shifted.append(
self._shift_apply(
context,
positions_2d,
position_in_segment,
shift,
self.eos_token_id,
)
)
adjusted_columns = columns + self.ngram_size - 1
id_blocks = []
for ngram in range(2, self.ngram_size + 1):
start = (ngram - 2) * self.heads_per_ngram
end = start + self.heads_per_ngram
mixed = shifted[0] * self.layer_multipliers[0]
for index in range(1, ngram):
mixed = torch.bitwise_xor(
mixed, shifted[index] * self.layer_multipliers[index]
)
sizes = self.ngram_heads_vocab_sizes[start:end]
offsets = self.ngram_heads_offsets[start:end]
ids = torch.remainder(mixed.unsqueeze(-1), sizes) + offsets
id_blocks.append(ids[request_indices, adjusted_columns])
ngram_ids = torch.cat(id_blocks, dim=-1)
embedding = self.ngram_embedding
if embedding.supports_prefetch:
output = ngram_ids.new_empty(
@@ -508,26 +409,21 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
int(config.ple_embed_dim),
self.ple_dense_layer_id,
vllm_config.scheduler_config.max_num_batched_tokens,
vllm_config.scheduler_config.max_num_seqs,
f"{prefix}.ple_embedding",
prefix,
data_parallel_rank=vllm_config.parallel_config.data_parallel_rank,
quant_config=quant_config,
params_dtype=model_config.dtype,
)
self.key_proj = ReplicatedLinear(
# The PLE cache is TP-replicated, so this merged projection is too.
self.kv_proj = MergedColumnParallelLinear(
int(config.ple_embed_dim),
self.hc_hidden_size,
[self.hc_hidden_size, self.hidden_size],
bias=False,
params_dtype=model_config.dtype,
quant_config=quant_config,
prefix=f"{prefix}.key_proj",
)
self.value_proj = ReplicatedLinear(
int(config.ple_embed_dim),
self.hidden_size,
bias=False,
quant_config=quant_config,
prefix=f"{prefix}.value_proj",
prefix=f"{prefix}.kv_proj",
disable_tp=True,
)
norm_args = (
self.hc_hidden_size,
@@ -580,355 +476,15 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
num_spec=self.num_spec_tokens,
)
def _apply_norm(
self, norm: Qwen4ExpPLEGroupedNorm, hidden_states: torch.Tensor
) -> torch.Tensor:
shape = hidden_states.shape
return norm(hidden_states.flatten(-2)).reshape(shape)
def _short_conv_fallback(self, inputs: torch.Tensor) -> torch.Tensor:
# Profiling / CUDA graph capture only; conv state is not updated.
inputs_t = inputs.transpose(0, 1).unsqueeze(0)
output = self.conv1d(inputs_t)[..., : inputs_t.size(-1)]
return F.silu(output).squeeze(0).transpose(0, 1)
def _short_conv_dilated_decode_batched(
self,
x_d: torch.Tensor,
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
state_indices_tensor_d: torch.Tensor,
has_initial_states_d: torch.Tensor | None,
) -> torch.Tensor:
state_indices = state_indices_tensor_d.to(
device=conv_state.device, dtype=torch.int64
)
# FULL cudagraph padded decode rows use NULL_BLOCK_ID. Remap them to
# slot 0 for a safe gather, then zero output and skip write-back.
valid_state = state_indices != NULL_BLOCK_ID
state_indices = torch.where(
valid_state, state_indices, torch.zeros_like(state_indices)
)
if has_initial_states_d is None:
has_initial_state = valid_state
else:
if has_initial_states_d.numel() < state_indices_tensor_d.numel():
raise ValueError(
"has_initial_states_d size mismatch: "
f"got {has_initial_states_d.numel()}, "
f"need >= {state_indices_tensor_d.numel()}."
)
has_initial_state = has_initial_states_d[
: state_indices_tensor_d.numel()
].to(device=conv_state.device, dtype=torch.bool)
has_initial_state = has_initial_state & valid_state
cached_state = conv_state.index_select(0, state_indices)
state = cached_state[..., : self.conv_state_len].to(x_d.dtype)
if self.conv_state_len > 0:
initial_state = torch.where(
has_initial_state.view(-1, 1, 1),
state,
torch.zeros_like(state),
)
history = torch.cat((initial_state, x_d.unsqueeze(-1)), dim=-1)
else:
history = x_d.unsqueeze(-1)
conv_output = F.conv1d(
history,
conv_weights.unsqueeze(1).contiguous(),
groups=history.size(1),
dilation=self.short_conv_dilation,
).squeeze(-1)
output = F.silu(conv_output)
output = output * valid_state.view(-1, 1).to(output.dtype)
if self.conv_state_len > 0:
next_state = history[..., -self.conv_state_len :]
# Padded rows are remapped to the reserved null slot. Preserve its
# existing value while writing the new states for valid rows.
existing_base_state = cached_state[..., : self.conv_state_len]
safe_next_state = torch.where(
valid_state.view(-1, 1, 1),
next_state.to(conv_state.dtype),
existing_base_state,
)
cached_state[..., : self.conv_state_len] = safe_next_state
conv_state.index_copy_(0, state_indices, cached_state)
return output
def _short_conv_dilated_prefill_batched(
self,
x_p: torch.Tensor,
metadata: PleShortConvAttentionMetadata,
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
state_indices_tensor_p: torch.Tensor,
num_prefills: int,
num_decode_tokens: int,
num_prefill_tokens: int,
) -> torch.Tensor:
query_start_loc_p = metadata.query_start_loc_p
if query_start_loc_p is None:
raise ValueError("query_start_loc is required for prefill short-conv")
# The metadata builder guarantees that the prefill query offsets start
# at 0 and end at num_prefill_tokens. Avoid reading those values here,
# since doing so would force a device-to-host synchronization.
has_initial_states_p = metadata.has_initial_states_p
if has_initial_states_p is None:
raise ValueError("has_initial_states_p is required for prefill short-conv")
output = torch.empty_like(x_p)
q_starts = query_start_loc_p.to(torch.int64)
if state_indices_tensor_p.numel() < num_prefills:
raise ValueError(
"state_indices_tensor_p size mismatch: "
f"got {state_indices_tensor_p.numel()}, "
f"need >= {num_prefills}."
)
if has_initial_states_p.numel() < num_prefills:
raise ValueError(
"has_initial_states_p size mismatch: "
f"got {has_initial_states_p.numel()}, "
f"need >= {num_prefills}."
)
if num_prefills == 0 or x_p.numel() == 0:
return output
lengths = q_starts[1:] - q_starts[:-1]
# Use the CPU-computed packing width from the metadata builder instead
# of synchronizing on lengths.max().
max_len = metadata.max_prefill_query_len
if max_len <= 0:
return output
hidden_size = x_p.shape[1]
positions = torch.arange(
num_prefill_tokens, device=x_p.device, dtype=torch.int64
)
req_indices = torch.searchsorted(q_starts[1:], positions, right=True)
col_indices = positions - q_starts[req_indices]
packed_tokens = x_p.new_zeros((num_prefills, max_len, hidden_size))
packed_tokens[req_indices, col_indices] = x_p
packed_tokens = packed_tokens.transpose(1, 2).contiguous()
state_indices = state_indices_tensor_p[:num_prefills].to(
device=conv_state.device, dtype=torch.int64
)
valid_state = state_indices != NULL_BLOCK_ID
state_indices = torch.where(
valid_state, state_indices, torch.zeros_like(state_indices)
)
has_initial = has_initial_states_p[:num_prefills].to(
device=conv_state.device, dtype=torch.bool
)
if self.conv_state_len > 0:
if conv_state.shape[0] == 0:
state = conv_state.new_zeros(
(num_prefills, hidden_size, self.conv_state_len),
dtype=x_p.dtype,
)
else:
state = conv_state.index_select(0, state_indices)[
..., : self.conv_state_len
].to(x_p.dtype)
use_initial_mask = (valid_state & has_initial).view(num_prefills, 1, 1)
initial_state = torch.where(
use_initial_mask,
state,
torch.zeros_like(state),
)
history = torch.cat((initial_state, packed_tokens), dim=-1)
else:
history = packed_tokens
conv_output = F.conv1d(
history,
conv_weights.unsqueeze(1).contiguous(),
groups=history.size(1),
dilation=self.short_conv_dilation,
)
conv_output = F.silu(conv_output).transpose(1, 2).contiguous()
token_positions = torch.arange(max_len, device=x_p.device, dtype=torch.int64)
valid_tokens = token_positions.view(1, max_len) < lengths.view(num_prefills, 1)
valid_output_mask = valid_tokens & valid_state.to(device=x_p.device).view(
num_prefills, 1
)
conv_output.masked_fill_(~valid_output_mask.unsqueeze(-1), 0)
output.copy_(conv_output[req_indices, col_indices])
if self.conv_state_len > 0 and conv_state.shape[0] > 0:
state_starts = lengths.to(device=history.device, dtype=torch.int64).view(
num_prefills, 1, 1
)
state_offsets = torch.arange(
self.conv_state_len, device=history.device, dtype=torch.int64
).view(1, 1, self.conv_state_len)
next_state = history.gather(
dim=2,
index=(state_starts + state_offsets).expand(-1, history.size(1), -1),
)
# Write back without a host synchronization. Valid, non-empty rows
# receive their new state; padding and zero-length rows keep the
# current cache value.
existing_state = conv_state.index_select(0, state_indices)
existing_base_state = existing_state[..., : self.conv_state_len]
update_mask = valid_state & (lengths.to(device=conv_state.device) > 0)
safe_next_state = torch.where(
update_mask.view(num_prefills, 1, 1),
next_state.to(conv_state.dtype),
existing_base_state,
)
existing_state[..., : self.conv_state_len] = safe_next_state
conv_state.index_copy_(0, state_indices, existing_state)
return output
def _short_conv_dilated_spec_batched(
self,
x_spec: torch.Tensor,
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
spec_state_indices_tensor: torch.Tensor,
spec_query_start_loc: torch.Tensor,
num_accepted_tokens: torch.Tensor,
spec_query_len: int,
) -> torch.Tensor:
"""Dilated short-conv for speculative-decode (MTP) requests.
Each spec request feeds multiple (draft + 1) query tokens. The conv
outputs are computed causally after rolling back the previous draft
state by ``num_accepted_tokens - 1``. The current candidate inputs stay
in the extended cache for the next forward, matching
``causal_conv1d_update``.
``spec_query_len`` (== num_speculative_tokens + 1) is the maximum query
length and is a Python int, so no host synchronization is needed; this
keeps the path safe for full CUDA-graph capture/replay where the buffers
are padded at the request level.
"""
num_reqs = spec_state_indices_tensor.numel()
hidden_size = x_spec.size(-1)
# Use a fixed packing width instead of synchronizing on lengths.max().
max_len = spec_query_len
# Full CUDA graphs can pad these buffers. Only the first num_reqs
# accepted-token counts belong to actual speculative requests.
num_accepted_tokens = num_accepted_tokens[:num_reqs]
q_starts = spec_query_start_loc[: num_reqs + 1].to(torch.int64)
# Keep the number of real speculative tokens on the device.
total_real_tokens = q_starts[num_reqs]
state_indices = spec_state_indices_tensor.to(
device=conv_state.device, dtype=torch.int64
)
valid_state = state_indices != NULL_BLOCK_ID
state_indices = torch.where(
valid_state, state_indices, torch.zeros_like(state_indices)
)
positions = torch.arange(
x_spec.size(0), device=x_spec.device, dtype=torch.int64
)
# Route graph-padded token rows to the discarded dummy request so that
# they cannot overwrite real packed data.
req_indices = torch.searchsorted(q_starts[1:], positions, right=True)
valid_tokens = (positions < total_real_tokens) & (req_indices < num_reqs)
clamped_req_indices = req_indices.clamp_max(max(num_reqs - 1, 0))
col_indices = (positions - q_starts[clamped_req_indices]).clamp_(0, max_len - 1)
pack_req_indices = torch.where(
valid_tokens,
clamped_req_indices,
torch.full_like(req_indices, num_reqs),
)
pack_col_indices = torch.where(
valid_tokens, col_indices, torch.zeros_like(col_indices)
)
# The last request row is the dummy sink for graph padding.
packed = x_spec.new_zeros((num_reqs + 1, max_len, hidden_size))
packed[pack_req_indices, pack_col_indices] = x_spec
packed = packed.transpose(1, 2).contiguous()
if self.conv_state_len > 0:
cached_state = conv_state.index_select(0, state_indices)
rollback_offsets = num_accepted_tokens.to(
device=conv_state.device, dtype=torch.int64
).sub(1)
rollback_offsets = torch.where(
valid_state,
rollback_offsets.clamp_(0, max_len - 1),
torch.zeros_like(rollback_offsets),
)
state_offsets = torch.arange(
self.conv_state_len, device=conv_state.device, dtype=torch.int64
).view(1, 1, self.conv_state_len)
rollback_indices = rollback_offsets.view(-1, 1, 1) + state_offsets
state = cached_state.gather(
2, rollback_indices.expand(-1, hidden_size, -1)
).to(x_spec.dtype)
state = torch.where(
valid_state.view(num_reqs, 1, 1),
state,
torch.zeros_like(state),
)
# Append a zeroed dummy-row state to match the [num_reqs + 1] pack.
dummy_state = state.new_zeros((1, hidden_size, self.conv_state_len))
state_full = torch.cat((state, dummy_state), dim=0)
history = torch.cat((state_full, packed), dim=-1)
else:
history = packed
conv_output = F.conv1d(
history,
conv_weights.unsqueeze(1).contiguous(),
groups=history.size(1),
dilation=self.short_conv_dilation,
)
conv_output = F.silu(conv_output).transpose(1, 2).contiguous()
output = conv_output[pack_req_indices, pack_col_indices]
output = output * valid_tokens.view(-1, 1).to(output.dtype)
# Keep all current candidate inputs in the extended state. On the next
# target forward, ``num_accepted_tokens - 1`` selects the rollback
# window before processing the newly scheduled tokens.
if self.conv_state_len > 0:
state_capacity = self.conv_state_len + max_len - 1
if conv_state.size(-1) < state_capacity:
raise RuntimeError(
"PLE short-conv cache cannot retain speculative tokens: "
f"got {conv_state.size(-1)}, need {state_capacity}."
)
candidate_state = history[:num_reqs, :, 1 : state_capacity + 1]
query_lengths = q_starts[1:] - q_starts[:-1]
state_positions = torch.arange(
state_capacity, device=history.device, dtype=torch.int64
).view(1, 1, state_capacity)
update_lengths = (self.conv_state_len + query_lengths - 1).view(
num_reqs, 1, 1
)
update_mask = valid_state.view(num_reqs, 1, 1) & (
state_positions < update_lengths
)
existing_state = cached_state[..., :state_capacity]
next_state = torch.where(
update_mask,
candidate_state.to(conv_state.dtype),
existing_state,
)
cached_state[..., :state_capacity] = next_state
conv_state.index_copy_(0, state_indices, cached_state)
return output
def _short_conv_dilated_dispatch(
self,
inputs: torch.Tensor,
residual: torch.Tensor,
outer_residual: torch.Tensor,
metadata: PleShortConvAttentionMetadata,
conv_state: torch.Tensor,
conv_weights: torch.Tensor,
) -> torch.Tensor:
) -> None:
num_prefills = metadata.num_prefills
num_decodes = metadata.num_decodes
num_decode_tokens = metadata.num_decode_tokens
@@ -936,110 +492,145 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
has_prefill = num_prefills > 0
has_decode = num_decodes > 0
has_spec = metadata.spec_sequence_masks is not None
x = inputs[: metadata.num_actual_tokens]
has_non_spec = has_prefill or has_decode
inputs = inputs[: metadata.num_actual_tokens]
residual = residual[: metadata.num_actual_tokens]
outer_residual = outer_residual[: metadata.num_actual_tokens]
# Split spec / non-spec tokens.
if has_spec:
if has_prefill or has_decode:
assert metadata.spec_token_indx is not None
assert metadata.non_spec_token_indx is not None
x_spec = x.index_select(0, metadata.spec_token_indx.long())
x_non_spec = x.index_select(0, metadata.non_spec_token_indx.long())
else:
x_spec = x
x_non_spec = None
else:
x_spec = None
x_non_spec = x
spec_token_indices = None
non_spec_token_indices = None
if has_spec and has_non_spec:
assert metadata.spec_token_indx is not None
assert metadata.non_spec_token_indx is not None
spec_token_indices = metadata.spec_token_indx
non_spec_token_indices = metadata.non_spec_token_indx
spec_output = None
# 1. Run the multi-query speculative-decode part.
if has_spec:
assert metadata.spec_state_indices_tensor is not None
assert metadata.spec_query_start_loc is not None
assert metadata.num_accepted_tokens is not None
spec_output = self._short_conv_dilated_spec_batched(
x_spec=x_spec,
query_start_loc = metadata.spec_query_start_loc
num_accepted_tokens = metadata.num_accepted_tokens
assert query_start_loc is not None
assert num_accepted_tokens is not None
spec_state_indices = metadata.spec_state_indices_tensor[
: metadata.num_spec_decodes
]
# Mixed batches stay in their original row order; the kernels map
# logical spec/non-spec rows instead of materializing both groups.
ple_conv(
inputs=inputs,
residual=residual,
conv_state=conv_state,
conv_weights=conv_weights,
spec_state_indices_tensor=metadata.spec_state_indices_tensor[
: metadata.num_spec_decodes
],
spec_query_start_loc=metadata.spec_query_start_loc,
num_accepted_tokens=metadata.num_accepted_tokens,
state_indices=spec_state_indices,
outer_residual=outer_residual,
mode="spec",
dilation=self.short_conv_dilation,
query_start_loc=query_start_loc,
num_accepted_tokens=num_accepted_tokens,
spec_query_len=metadata.spec_query_len,
token_indices=spec_token_indices,
)
# 2. Run regular decode and prefill requests.
conv_out_non_spec = None
state_indices_tensor = metadata.state_indices_tensor
if x_non_spec is not None:
assert state_indices_tensor is not None
if has_prefill:
state_indices_tensor_d, state_indices_tensor_p = torch.split(
state_indices_tensor,
[num_decodes, num_prefills],
dim=0,
if not has_non_spec:
return
state_indices = metadata.state_indices_tensor
assert state_indices is not None
if has_prefill:
state_indices_d, state_indices_p = torch.split(
state_indices, [num_decodes, num_prefills], dim=0
)
if non_spec_token_indices is None:
inputs_d, inputs_p = torch.split(
inputs, [num_decode_tokens, num_prefill_tokens], dim=0
)
x_d, x_p = torch.split(
x_non_spec,
residual_d, residual_p = torch.split(
residual, [num_decode_tokens, num_prefill_tokens], dim=0
)
outer_residual_d, outer_residual_p = torch.split(
outer_residual,
[num_decode_tokens, num_prefill_tokens],
dim=0,
)
non_spec_parts: list[torch.Tensor] = []
if has_decode:
non_spec_parts.append(
self._short_conv_dilated_decode_batched(
x_d=x_d,
conv_state=conv_state,
conv_weights=conv_weights,
state_indices_tensor_d=state_indices_tensor_d,
has_initial_states_d=metadata.has_initial_states_d,
)
)
non_spec_parts.append(
self._short_conv_dilated_prefill_batched(
x_p=x_p,
metadata=metadata,
conv_state=conv_state,
conv_weights=conv_weights,
state_indices_tensor_p=state_indices_tensor_p,
num_prefills=num_prefills,
num_decode_tokens=num_decode_tokens,
num_prefill_tokens=num_prefill_tokens,
)
)
conv_out_non_spec = torch.vstack(non_spec_parts)
token_indices_d = None
token_indices_p = None
else:
conv_out_non_spec = self._short_conv_dilated_decode_batched(
x_d=x_non_spec,
inputs_d = inputs_p = inputs
residual_d = residual_p = residual
outer_residual_d = outer_residual_p = outer_residual
token_indices_d, token_indices_p = torch.split(
non_spec_token_indices,
[num_decode_tokens, num_prefill_tokens],
dim=0,
)
if has_decode:
ple_conv(
inputs=inputs_d,
residual=residual_d,
conv_state=conv_state,
conv_weights=conv_weights,
state_indices_tensor_d=state_indices_tensor[: x_non_spec.size(0)],
has_initial_states_d=metadata.has_initial_states_d,
state_indices=state_indices_d,
outer_residual=outer_residual_d,
mode="decode",
dilation=self.short_conv_dilation,
has_initial_states=metadata.has_initial_states_d,
token_indices=token_indices_d,
)
# 3. Merge both parts back into the original token order.
if has_spec and conv_out_non_spec is not None:
assert metadata.spec_token_indx is not None
assert metadata.non_spec_token_indx is not None
assert spec_output is not None
output = x.new_empty((metadata.num_actual_tokens, x.size(-1)))
output.index_copy_(0, metadata.spec_token_indx, spec_output)
output.index_copy_(0, metadata.non_spec_token_indx, conv_out_non_spec)
return output
elif has_spec:
assert spec_output is not None
return spec_output
if conv_out_non_spec is None:
return x
return conv_out_non_spec
query_start_loc = metadata.query_start_loc_p
if query_start_loc is None:
raise ValueError("query_start_loc is required for prefill short-conv")
has_initial_states = metadata.has_initial_states_p
if has_initial_states is None:
raise ValueError(
"has_initial_states_p is required for prefill short-conv"
)
ple_conv(
inputs=inputs_p,
residual=residual_p,
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=state_indices_p,
outer_residual=outer_residual_p,
mode="prefill",
dilation=self.short_conv_dilation,
query_start_loc=query_start_loc,
has_initial_states=has_initial_states,
token_indices=token_indices_p,
)
else:
num_decode_rows = (
non_spec_token_indices.numel()
if non_spec_token_indices is not None
else inputs.size(0)
)
ple_conv(
inputs=inputs,
residual=residual,
conv_state=conv_state,
conv_weights=conv_weights,
state_indices=state_indices[:num_decode_rows],
outer_residual=outer_residual,
mode="decode",
dilation=self.short_conv_dilation,
has_initial_states=metadata.has_initial_states_d,
token_indices=non_spec_token_indices,
)
def _short_conv(self, inputs: torch.Tensor) -> torch.Tensor:
def _short_conv(
self,
inputs: torch.Tensor,
residual: torch.Tensor,
outer_residual: torch.Tensor,
) -> None:
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
# Profiling omits all metadata or this Mamba entry. Short convolution
# is a no-op there, but preserve the outer residual addition.
if attn_metadata is None:
return self._short_conv_fallback(inputs)
residual.add_(outer_residual)
return
if not isinstance(attn_metadata, dict):
raise RuntimeError(
@@ -1049,8 +640,8 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
layer_attn_metadata = attn_metadata.get(self.prefix)
if layer_attn_metadata is None:
# MRV2 omits Mamba-family metadata during profile warmup.
return self._short_conv_fallback(inputs)
residual.add_(outer_residual)
return
if not isinstance(layer_attn_metadata, PleShortConvAttentionMetadata):
raise TypeError(
"Expected PleShortConvAttentionMetadata for layer "
@@ -1059,6 +650,7 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
)
conv_state = self.kv_cache[0]
# Canonicalize both backend cache layouts to [slot, channel, window].
if not is_conv_state_dim_first():
conv_state = conv_state.transpose(-1, -2)
conv_weights = self.conv1d.weight.squeeze(1)
@@ -1072,11 +664,13 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
f"expect at least {state_capacity}."
)
conv_state = conv_state[..., -state_capacity:]
return self._short_conv_dilated_dispatch(
inputs,
layer_attn_metadata,
conv_state,
conv_weights.to(dtype=inputs.dtype),
self._short_conv_dilated_dispatch(
inputs=inputs,
residual=residual,
outer_residual=outer_residual,
metadata=layer_attn_metadata,
conv_state=conv_state,
conv_weights=conv_weights.to(dtype=inputs.dtype),
)
def forward(
@@ -1095,27 +689,58 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
)
embeddings = self.ple_embedding(input_ids, query_start_loc, ngram_context)
embeddings = self.ple_embedding.ngram_embedding.dequantize(
embeddings,
self.ple_embedding.ngram_embedding.params_dtype,
embeddings, hidden_states.dtype
)
key, _ = self.key_proj(embeddings)
value, _ = self.value_proj(embeddings)
token_count = hidden_states.shape[0]
key = key.reshape(token_count, self.hc_count, self.hidden_size)
query = hidden_states.reshape(token_count, self.hc_count, self.hidden_size)
key = self._apply_norm(self.norm_key, key)
query = self._apply_norm(self.norm_query, query)
gate = (key * query).sum(dim=-1, keepdim=True) / math.sqrt(self.hidden_size)
gate = torch.sigmoid(gate.sign() * gate.abs().clamp_min(1e-6).sqrt())
gated_value = gate * value.unsqueeze(-2)
normalized = self._apply_norm(self.norm_conv, gated_value).flatten(-2)
conv_output = torch.zeros_like(normalized)
kv, _ = self.kv_proj(embeddings)
key, value = kv.split(self.kv_proj.output_sizes, dim=-1)
gated_output, conv_input = ple_gate(
key,
value,
hidden_states,
self.norm_key.weight,
self.norm_query.weight,
self.norm_conv.weight,
self.norm_key.eps,
)
# The short-conv op is a piecewise-graph splitting op: state routing
# reads runtime request metadata. It accumulates the convolution and
# the outer residual into gated_output.
torch.ops.vllm.qwen4_exp_ple_short_conv(
normalized,
conv_output,
conv_input,
gated_output,
hidden_states,
self.prefix,
)
return gated_value.flatten(-2) + conv_output
return gated_output
def qwen4_exp_amd_ple_ngram_ids(
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
output: torch.Tensor,
layer_name: str,
) -> None:
"""Hash the current request layout into n-gram embedding indices.
The launch sizes its request binary search from the request count, which
is symbolic under Dynamo, so it runs outside Inductor's FX graph.
"""
layer = get_forward_context().no_compile_layers[layer_name]
if not isinstance(layer, Qwen4ExpPLELayer):
raise TypeError(f"{layer_name} is not a Qwen4Exp PLE owner")
embedding = layer.ple_embedding
ple_ngram_ids(
input_ids=input_ids,
query_start_loc=query_start_loc,
ngram_context=ngram_context,
layer_multipliers=embedding.layer_multipliers,
ngram_heads_vocab_sizes=embedding.ngram_heads_vocab_sizes,
ngram_heads_offsets=embedding.ngram_heads_offsets,
eos_token_id=embedding.eos_token_id,
heads_per_ngram=embedding.heads_per_ngram,
output=output,
)
def qwen4_exp_amd_ple_ngram_embedding(
@@ -1155,12 +780,19 @@ def qwen4_exp_amd_ple_ngram_embedding_pinned(
def qwen4_exp_ple_short_conv(
inputs: torch.Tensor,
output: torch.Tensor,
residual: torch.Tensor,
outer_residual: torch.Tensor,
layer_name: str,
) -> None:
layer = get_forward_context().no_compile_layers[layer_name]
result = layer._short_conv(inputs)
output[: result.shape[0]].copy_(result)
layer._short_conv(inputs, residual, outer_residual)
direct_register_custom_op(
op_name="qwen4_exp_amd_ple_ngram_ids",
op_func=qwen4_exp_amd_ple_ngram_ids,
mutates_args=["output"],
)
direct_register_custom_op(
@@ -1180,7 +812,7 @@ direct_register_custom_op(
direct_register_custom_op(
op_name="qwen4_exp_ple_short_conv",
op_func=qwen4_exp_ple_short_conv,
mutates_args=["output"],
mutates_args=["residual"],
)
+100 -16
View File
@@ -116,8 +116,8 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
self,
layer: torch.nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
key: torch.Tensor | None,
value: torch.Tensor | None,
kv_cache: torch.Tensor,
attn_metadata: FlashAttentionMetadata,
output: torch.Tensor,
@@ -214,7 +214,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
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.head_dim = int(config.head_dim or self.hidden_size // self.total_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
@@ -294,6 +294,11 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
quant_config=quant_config,
prefix=f"{prefix}.indexer",
)
self.use_fused_qsa_prepare = (
self.attn_output_gate
and self.indexer.use_fused_pre_indexer
and self.head_dim & (self.head_dim - 1) == 0
)
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
self.register_buffer(
"topk_indices_buffer",
@@ -327,16 +332,22 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
query: torch.Tensor | None,
key: torch.Tensor | None,
value: torch.Tensor | None,
output: torch.Tensor,
qkv: torch.Tensor | None = None,
gate: torch.Tensor | None = None,
) -> None:
# query/key/value are None when the fused prepare runs inside the
# indexer launch, which then writes the gate into ``gate``.
metadata = get_forward_context().attn_metadata
if isinstance(metadata, list):
metadata = metadata[0]
if not isinstance(metadata, dict):
output.zero_()
if gate is not None:
gate.zero_()
return
main_metadata = cast(FlashAttentionMetadata, metadata[self.layer_name])
if self.kv_cache.numel() == 0:
@@ -349,10 +360,14 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
)
if side_metadata.num_actual_tokens != num_tokens:
raise RuntimeError("QSA main and side metadata token counts disagree")
selected = self.indexer(
selected, main_outputs = self.indexer(
hidden_states,
positions,
self.topk_indices_buffer[:num_tokens],
attn=self,
qkv=qkv,
slot_mapping=main_metadata.slot_mapping,
gate_out=gate,
)
if selected.shape != (
num_tokens,
@@ -360,13 +375,22 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
):
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,
)
if main_outputs is None:
assert key is not None and value is not None
impl.do_kv_cache_update(
self,
key,
value,
self.kv_cache,
main_metadata.slot_mapping,
)
else:
query, _ = main_outputs
# The gate is applied to every row outside this op; padded rows
# must stay finite so they keep the zero output forward_qsa gives.
assert gate is not None
gate[num_tokens:].zero_()
assert query is not None
impl.forward_qsa(
self,
query,
@@ -384,13 +408,40 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
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]
encoded_layer_name = _encode_layer_name(self.layer_name)
if self.use_fused_qsa_prepare:
# Norm/RoPE/gate and the K/V cache write happen inside the op.
attn_output = qkv.new_empty(num_tokens, self.num_heads, self.head_dim)
gate = torch.empty_like(attn_output)
if current_platform.opaque_attention_op():
torch.ops.vllm.qwen4_exp_qsa_prepare_with_output(
hidden_states,
positions,
qkv,
attn_output,
gate,
encoded_layer_name,
)
else:
qwen4_exp_qsa_prepare_with_output(
hidden_states,
positions,
qkv,
attn_output,
gate,
encoded_layer_name,
)
flat_output = attn_output.view(num_tokens, -1)
flat_output = flat_output * torch.sigmoid(gate.view(num_tokens, -1))
output, _ = self.o_proj(flat_output)
return output
q, k, v, gate = self._project_qkv_gate(qkv, positions)
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,
@@ -449,10 +500,43 @@ direct_register_custom_op(
)
def qwen4_exp_qsa_prepare_with_output(
hidden_states: torch.Tensor,
positions: torch.Tensor,
qkv: torch.Tensor,
output: torch.Tensor,
gate: torch.Tensor,
layer_name: LayerNameType,
) -> None:
"""Run the QSA transaction with the main QK-norm/RoPE/gate fused in."""
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,
None,
None,
None,
output,
qkv=qkv,
gate=gate,
)
direct_register_custom_op(
op_name="qwen4_exp_qsa_prepare_with_output",
op_func=qwen4_exp_qsa_prepare_with_output,
mutates_args=["output", "gate"],
)
__all__ = [
"QSAIndexer",
"Qwen4ExpQSAAttention",
"Qwen4ExpQSAFlashAttentionBackend",
"Qwen4ExpQSAFlashAttentionImpl",
"qwen4_exp_qsa_prepare_with_output",
"qwen4_exp_qsa_with_output",
]
+22 -20
View File
@@ -32,6 +32,7 @@ from vllm.model_executor.layers.quantization.modelopt import (
ModelOptMixedPrecisionConfig,
ModelOptQuantConfigBase,
)
from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
create_fp8_scale_parameter,
)
@@ -196,6 +197,9 @@ class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
and not quant_config.config_parser.resolve(None, prefix).quantized
):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
# Quark quantizes only Linear and MoE layers; PLE tables stay BF16.
if isinstance(quant_config, QuarkConfig):
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
if not isinstance(quant_config, Fp8Config):
raise NotImplementedError(
"Qwen4Exp PLE embedding does not support quantization config "
@@ -376,29 +380,33 @@ class Qwen4ExpPLEDeviceEmbedding(Qwen4ExpPLEEmbedding):
@triton.jit
def _lookup_ple_embedding_from_pinned_kernel(
weight_ptr,
weight_ptr: tl.pointer_type(tl.uint8), # type: ignore[valid-type]
ids_ptr,
output_ptr,
embedding_dim,
output_ptr: tl.pointer_type(tl.uint8), # type: ignore[valid-type]
row_bytes,
tp_vocab_start,
tp_vocab_end,
BLOCK_D: tl.constexpr,
):
"""Look up TP-owned PLE rows through a CUDA view of pinned host memory."""
row_id = tl.program_id(0)
"""Copy TP-owned PLE rows as raw bytes from a CUDA view of pinned host memory.
Byte pointers keep the storage dtype out of the kernel signature, so
dtypes Triton cannot lower on the GPU (FP8 E4M3FN before SM89) still work.
"""
row_id = tl.program_id(0).to(tl.int64)
global_idx = tl.load(ids_ptr + row_id)
in_range = (global_idx >= tp_vocab_start) & (global_idx < tp_vocab_end)
local_idx = tl.where(in_range, global_idx - tp_vocab_start, 0)
offsets = tl.arange(0, BLOCK_D)
store_mask = offsets < embedding_dim
store_mask = offsets < row_bytes
load_mask = store_mask & in_range
values = tl.load(
weight_ptr + local_idx * embedding_dim + offsets,
weight_ptr + local_idx * row_bytes + offsets,
mask=load_mask,
other=0.0,
other=0,
)
tl.store(
output_ptr + row_id * embedding_dim + offsets,
output_ptr + row_id * row_bytes + offsets,
values,
mask=store_mask,
)
@@ -436,7 +444,8 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
data_parallel_rank=data_parallel_rank,
)
self._uva_weight = get_accelerator_view_from_cpu_tensor(self.weight)
self._block_d = triton.next_power_of_2(self.embedding_dim)
self._row_bytes = self.embedding_dim * self.weight.element_size()
self._block_d = triton.next_power_of_2(self._row_bytes)
self._prefetch_stream: torch.cuda.Stream | None = None
self._prefetch_buffer: torch.Tensor | None = None
self._prefetch_alloc_lock = threading.Lock()
@@ -484,18 +493,11 @@ class Qwen4ExpPLEPinnedHostEmbedding(Qwen4ExpPLEEmbedding):
flat_ids = input_ids.reshape(-1).long()
if flat_ids.numel():
if self.weight.dtype == torch.float8_e4m3fn:
uva_weight_view = self._uva_weight.view(torch.int8)
output_view = output.view(torch.int8)
else:
uva_weight_view = self._uva_weight
output_view = output
_lookup_ple_embedding_from_pinned_kernel[(flat_ids.numel(),)](
uva_weight_view,
self._uva_weight,
flat_ids,
output_view,
self.embedding_dim,
output,
self._row_bytes,
self.shard_indices.org_vocab_start_index,
self.shard_indices.org_vocab_end_index,
BLOCK_D=self._block_d,
@@ -0,0 +1,4 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen4Exp kernels shared by the NVIDIA and AMD backends; import leaf modules
directly."""
+5 -2
View File
@@ -127,7 +127,9 @@ def circular_qsa_slot_mapping(
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
# Dummy and padding requests own no ring and sit on the null block,
# which must never be written.
valid &= physical_blocks > 0
slots = physical_blocks * compressor_state_size + positions.remainder(
compressor_state_size
)
@@ -288,7 +290,8 @@ def _build_qsa_metadata_kernel(
mask=valid,
other=-1,
)
valid &= physical_block >= 0
# Dummy and padding requests own no ring and sit on the null block.
valid &= physical_block > 0
slot = physical_block * circular_buffer_size + (
logical_position % circular_buffer_size
)
@@ -13,6 +13,7 @@ from torch import nn
import vllm.envs as envs
from vllm.model_executor.kernels.linear.cute_dsl.skinny_gemm import (
SkinnyGemmConfig,
row_stride_ok,
shape_dynamic_skinny_gemm,
)
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
@@ -78,7 +79,7 @@ QWEN4_EXP_SM90_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
(4224, 2560): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=6, vector_width=2, static_k=2560),
2: SkinnyGemmConfig(2, 128, 2, k_unroll=3, vector_width=2, static_k=2560),
4: SkinnyGemmConfig(4, 64, 4, k_unroll=2, vector_width=4),
4: SkinnyGemmConfig(4, 64, 4, k_unroll=1, vector_width=8),
},
# GDN and QSA output projections, TP=4.
(2560, 1536): {
@@ -167,7 +168,7 @@ QWEN4_EXP_SM100_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
}
# DGX Spark (GB10) plans, TP=1 unless noted.
# DGX Spark (GB10) plans for TP=1 and TP=2 local shapes.
QWEN4_EXP_SM121_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] = {
# Shared-expert gate.
(1, 2560): {
@@ -177,6 +178,14 @@ QWEN4_EXP_SM121_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
16: SkinnyGemmConfig(16, 128, 1, vector_width=4, static_k=2560),
},
# GDN fused B/A projection, TP=2.
(48, 2560): {
1: SkinnyGemmConfig(1, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 2, k_unroll=4, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
8: SkinnyGemmConfig(8, 128, 1, k_unroll=4, vector_width=4, static_k=2560),
16: SkinnyGemmConfig(16, 128, 1, k_unroll=2, vector_width=4, static_k=2560),
},
# GDN fused B/A projection.
(96, 2560): {
1: SkinnyGemmConfig(1, 128, 4, k_unroll=2, vector_width=2, static_k=2560),
@@ -217,6 +226,12 @@ QWEN4_EXP_SM121_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
8: SkinnyGemmConfig(8, 32, 1, k_unroll=4, vector_width=4, static_k=640),
16: SkinnyGemmConfig(16, 32, 1, k_unroll=2, vector_width=4, static_k=640),
},
# GDN and QSA output projections, TP=2.
(2560, 3072): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=2, vector_width=4, static_k=3072),
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2, static_k=3072),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=2, static_k=3072),
},
# GDN and QSA output projections.
(2560, 6144): {
1: SkinnyGemmConfig(1, 64, 2, vector_width=4, static_k=6144),
@@ -225,6 +240,18 @@ QWEN4_EXP_SM121_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
8: SkinnyGemmConfig(8, 128, 1, vector_width=2, static_k=6144),
16: SkinnyGemmConfig(16, 32, 1, static_k=6144),
},
# QSA fused QKV/gate projection, TP=2.
(6656, 2560): {
1: SkinnyGemmConfig(1, 128, 4, k_unroll=2, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 128, 4, k_unroll=2, vector_width=4, static_k=2560),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=4, vector_width=4, static_k=2560),
},
# GDN fused QKVZ projection, TP=2.
(8192, 2560): {
1: SkinnyGemmConfig(1, 128, 2, vector_width=4, static_k=2560),
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2, static_k=2560),
4: SkinnyGemmConfig(4, 64, 2, k_unroll=4, vector_width=4, static_k=2560),
},
# HC up projection.
(10240, 320): {
1: SkinnyGemmConfig(1, 32, 1, k_unroll=2, vector_width=2, static_k=320),
@@ -248,6 +275,11 @@ QWEN4_EXP_SM121_GEMM_PLANS: dict[tuple[int, int], dict[int, SkinnyGemmConfig]] =
8: SkinnyGemmConfig(8, 64, 1, vector_width=2, static_k=2560),
16: SkinnyGemmConfig(16, 32, 1, k_unroll=2, vector_width=2, static_k=2560),
},
# LM head, TP=2.
(124160, 2560): {
1: SkinnyGemmConfig(1, 128, 2, k_unroll=4, vector_width=4),
2: SkinnyGemmConfig(2, 64, 2, k_unroll=2),
},
# LM head.
(248320, 2560): {
1: SkinnyGemmConfig(1, 128, 1, k_unroll=2, vector_width=4, static_k=2560),
@@ -273,10 +305,13 @@ 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:
def _runtime_ok(
x: torch.Tensor, weight: torch.Tensor, config: SkinnyGemmConfig
) -> bool:
return (
not envs.VLLM_BATCH_INVARIANT
and _is_packed_row_major(x)
and x.dim() == 2
and row_stride_ok(x, config)
and _is_packed_row_major(weight)
and x.dtype == torch.bfloat16
and weight.dtype == torch.bfloat16
@@ -317,7 +352,7 @@ def _qwen4_exp_low_latency_gemm(x: torch.Tensor, weight: torch.Tensor) -> torch.
config = None if plan is None else plan.get(x.shape[0])
if (
config is not None
and _runtime_ok(x, weight)
and _runtime_ok(x, weight, config)
and shape_dynamic_skinny_gemm.is_available()
):
return shape_dynamic_skinny_gemm(x, weight, config)
@@ -25,7 +25,7 @@ from ..common.ngram_embedding import (
Qwen4ExpPLEPinnedHostEmbedding,
Qwen4ExpPLEUnquantizedEmbeddingMethod,
)
from .ops.ple import ple_ngram_ids
from ..common.ops.ple import ple_ngram_ids
logger = init_logger(__name__)
+1 -1
View File
@@ -24,8 +24,8 @@ from vllm.v1.attention.backends.short_conv_attn import (
PleShortConvAttentionMetadata,
)
from ..common.ops.ple import ple_conv, ple_gate
from .ngram_embedding import Qwen4ExpNGramEmbedding
from .ops.ple import ple_conv, ple_gate
class Qwen4ExpPLEGroupedNorm(nn.Module):
+15 -4
View File
@@ -13,7 +13,7 @@ from transformers import Qwen4ExpTextConfig
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.config.cache import CacheConfig, 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 (
@@ -29,7 +29,11 @@ from vllm.model_executor.layers.linear import (
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.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
WeightsMapper,
extract_layer_index,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import (
@@ -125,6 +129,13 @@ class Qwen4ExpQSAQKVIndexerLinear(MergedColumnParallelLinear):
return super().load_weights(remap_shards())
def qsa_kv_cache_dtype(cache_config: CacheConfig, prefix: str) -> CacheDType:
"""The layer's KV cache dtype, honoring ``--kv-cache-dtype-skip-layers``."""
if str(extract_layer_index(prefix)) in cache_config.kv_cache_dtype_skip_layers:
return "auto"
return cache_config.cache_dtype
class Qwen4ExpQSAMetadataBuilder(FlashAttentionMetadataBuilder):
"""Flash metadata supporting uniform decode and target-verify graphs."""
@@ -382,7 +393,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
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.head_dim = int(config.head_dim or self.hidden_size // self.total_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
@@ -444,7 +455,7 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
self.layer_name = f"{prefix}.attn"
self.attn_type = AttentionType.DECODER
self.kv_cache_dtype = cache_config.cache_dtype
self.kv_cache_dtype = qsa_kv_cache_dtype(cache_config, prefix)
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
self.kv_cache_dtype, model_config
)