Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
+161
-88
@@ -13,7 +13,6 @@ from torch._ops import OpOverload
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import PlaceholderModule
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
rocm_aiter_sparse_attn_indexer,
|
||||
@@ -25,20 +24,27 @@ if TYPE_CHECKING:
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = PlaceholderModule("pandas")
|
||||
|
||||
# fp8_dtype is not cached.
|
||||
# on ROCm the fp8_dtype always calls is_fp8_fnuz
|
||||
# which is a host op, so we cache it once here.
|
||||
FP8_DTYPE = current_platform.fp8_dtype()
|
||||
_HIPB_MM_INITIALIZED_DEVICES: set[int] = set()
|
||||
_FP8_E4M3_DTYPES = {
|
||||
dtype
|
||||
for dtype in (
|
||||
getattr(torch, "float8_e4m3fn", None),
|
||||
getattr(torch, "float8_e4m3fnuz", None),
|
||||
)
|
||||
if dtype is not None
|
||||
}
|
||||
KB = 1024
|
||||
MB = 1024 * KB
|
||||
|
||||
|
||||
def _is_fp8_e4m3_tensor(t: torch.Tensor | None) -> bool:
|
||||
return t is not None and t.dtype in _FP8_E4M3_DTYPES
|
||||
|
||||
|
||||
def _get_or_create_aiter_qr_rmsnorm_comm(
|
||||
device_comm: Any,
|
||||
) -> tuple[int, int, bool] | None:
|
||||
@@ -231,27 +237,42 @@ def is_aiter_found_and_supported_on_rdna4() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@functools.cache
|
||||
def _load_gemm_tuned_configs(
|
||||
q_dtype_w: torch.dtype, csv_path: str
|
||||
) -> set[tuple[int, int, int]]:
|
||||
try:
|
||||
df = pd.read_csv(csv_path).drop_duplicates()
|
||||
df = df[df["q_dtype_w"] == str(q_dtype_w)]
|
||||
return set(zip(df["N"].astype(int), df["K"].astype(int), df["M"].astype(int)))
|
||||
except Exception:
|
||||
return set()
|
||||
def _triton_gemm_config_is_tuned(config_name: str, N: int, K: int) -> bool:
|
||||
from aiter.ops.triton.utils.gemm_config_utils import get_gemm_config
|
||||
|
||||
# any M shape under 1024 should be tuned
|
||||
M_TUNE_PROBE = 128
|
||||
|
||||
return get_gemm_config(config_name, M_TUNE_PROBE, N, K)[1]
|
||||
|
||||
|
||||
def _check_kernel_tuned(N: int, K: int, q_dtype_w: torch.dtype, csv_path: str) -> bool:
|
||||
configs = _load_gemm_tuned_configs(q_dtype_w, csv_path)
|
||||
def _ck_gemm_shape_is_tuned(
|
||||
N: int, K: int, q_dtype_w: torch.dtype, csv_attr: str
|
||||
) -> bool:
|
||||
l_m = (
|
||||
[1, 2, 4]
|
||||
+ list(range(8, 513, 8))
|
||||
+ [1024, 1536]
|
||||
+ [2**i for i in range(11, 19)]
|
||||
)
|
||||
return any((N, K, M) in configs for M in l_m)
|
||||
try:
|
||||
from aiter.ops.gemm_op_a8w8 import (
|
||||
AITER_CONFIGS,
|
||||
get_GEMM_config_with_quant_type,
|
||||
)
|
||||
|
||||
csv_path = getattr(AITER_CONFIGS, csv_attr)
|
||||
return any(
|
||||
get_GEMM_config_with_quant_type(M, N, K, q_dtype_w, csv_path) is not None
|
||||
for M in l_m
|
||||
)
|
||||
except (AttributeError, ImportError, OSError):
|
||||
logger.warning_once(
|
||||
"Could not read aiter CK GEMM configs from AITER_CONFIGS.%s; "
|
||||
"treating all shapes as untuned.",
|
||||
csv_attr,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def if_aiter_supported(func: Callable) -> Callable:
|
||||
@@ -2200,6 +2221,106 @@ class rocm_aiter_ops:
|
||||
def is_shuffle_kv_cache_enabled(cls) -> bool:
|
||||
return cls._SHUFFLE_KV_CACHE_ENABLED
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def fused_qknorm_idxrqknorm_enabled(
|
||||
cls,
|
||||
kv_cache_dtype: str,
|
||||
k_scale: torch.Tensor | None = None,
|
||||
v_scale: torch.Tensor | None = None,
|
||||
) -> bool:
|
||||
"""Whether MiniMax-M3 can use AITER's consolidated fused QK-norm.
|
||||
|
||||
Requires AITER to be installed and enabled. bf16 (``auto``) always
|
||||
qualifies; fp8 e4m3 also needs K/V scales. Other cache dtypes fall
|
||||
back to vLLM's fused kernel.
|
||||
"""
|
||||
if not cls._AITER_ENABLED:
|
||||
return False
|
||||
if kv_cache_dtype == "auto":
|
||||
return True
|
||||
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
||||
return k_scale is not None and v_scale is not None
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def fused_qknorm_idxrqknorm(
|
||||
cls,
|
||||
qkv: torch.Tensor,
|
||||
q_norm_weight: torch.Tensor,
|
||||
k_norm_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
num_heads: int,
|
||||
num_kv_heads: int,
|
||||
rotary_dim: int,
|
||||
eps: float,
|
||||
slot_mapping: torch.Tensor,
|
||||
kv_cache_k: torch.Tensor,
|
||||
kv_cache_v: torch.Tensor,
|
||||
q_out: torch.Tensor,
|
||||
kv_cache_dtype: str,
|
||||
k_scale: torch.Tensor | None = None,
|
||||
v_scale: torch.Tensor | None = None,
|
||||
index_q_norm_weight: torch.Tensor | None = None,
|
||||
index_k_norm_weight: torch.Tensor | None = None,
|
||||
num_index_heads: int = 0,
|
||||
index_cache: torch.Tensor | None = None,
|
||||
index_q_out: torch.Tensor | None = None,
|
||||
index_slot_mapping: torch.Tensor | None = None,
|
||||
skip_index_branch: bool = False,
|
||||
) -> None:
|
||||
"""Run consolidated MiniMax-M3 QK-norm fusion.
|
||||
|
||||
Callers must check ``fused_qknorm_idxrqknorm_enabled`` first. Runtime
|
||||
failures from the AITER op are deliberately propagated.
|
||||
"""
|
||||
if kv_cache_dtype == "auto":
|
||||
aiter_kv_cache_dtype = "auto"
|
||||
aiter_k_scale = None
|
||||
aiter_v_scale = None
|
||||
elif kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
||||
aiter_kv_cache_dtype = "fp8_e4m3_static"
|
||||
aiter_k_scale = k_scale
|
||||
aiter_v_scale = v_scale
|
||||
else:
|
||||
raise ValueError(
|
||||
"AITER fused QK-norm requires kv_cache_dtype 'auto', 'fp8', "
|
||||
f"or 'fp8_e4m3', got {kv_cache_dtype!r}"
|
||||
)
|
||||
aiter_index_cache_dtype = "fp8" if _is_fp8_e4m3_tensor(index_cache) else "auto"
|
||||
|
||||
from aiter import fused_qknorm_idxrqknorm
|
||||
|
||||
fused_qknorm_idxrqknorm(
|
||||
qkv,
|
||||
q_norm_weight,
|
||||
k_norm_weight,
|
||||
cos_sin_cache,
|
||||
positions,
|
||||
num_heads,
|
||||
num_kv_heads,
|
||||
rotary_dim,
|
||||
eps,
|
||||
index_q_norm_weight=index_q_norm_weight,
|
||||
index_k_norm_weight=index_k_norm_weight,
|
||||
num_index_heads=num_index_heads,
|
||||
slot_mapping=slot_mapping,
|
||||
kv_cache_k=kv_cache_k,
|
||||
kv_cache_v=kv_cache_v,
|
||||
index_cache=index_cache,
|
||||
block_size=16,
|
||||
q_out=q_out,
|
||||
index_q_out=index_q_out,
|
||||
index_slot_mapping=index_slot_mapping,
|
||||
kv_cache_dtype=aiter_kv_cache_dtype,
|
||||
index_cache_dtype=aiter_index_cache_dtype,
|
||||
k_scale=aiter_k_scale,
|
||||
v_scale=aiter_v_scale,
|
||||
asm_layout=True,
|
||||
skip_index_branch=skip_index_branch,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def is_triton_unified_attn_enabled(cls) -> bool:
|
||||
@@ -3346,89 +3467,41 @@ class rocm_aiter_ops:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@functools.cache
|
||||
def is_triton_gemm_w8a8_tuned(n: int, k: int) -> bool:
|
||||
if not current_platform.is_rocm():
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx950, on_rdna4
|
||||
|
||||
gfx950_tuned = {
|
||||
(1024, 8192),
|
||||
(2112, 7168),
|
||||
(3072, 1536),
|
||||
(32768, 8192),
|
||||
(4096, 7168),
|
||||
(4608, 7168),
|
||||
(512, 7168),
|
||||
(7168, 2048),
|
||||
(7168, 256),
|
||||
(8192, 1024),
|
||||
(8192, 32768),
|
||||
}
|
||||
rdna4_tuned = gfx950_tuned | {
|
||||
(2048, 2048),
|
||||
(2624, 6144),
|
||||
(3072, 6144),
|
||||
(3584, 512),
|
||||
(4096, 512),
|
||||
(6144, 1536),
|
||||
(6144, 2048),
|
||||
(7168, 2304),
|
||||
(7168, 16384),
|
||||
(7168, 18432),
|
||||
(8192, 8192),
|
||||
(16384, 1536),
|
||||
(24576, 1536),
|
||||
(32768, 512),
|
||||
(36864, 7168),
|
||||
}
|
||||
if on_rdna4():
|
||||
return (n, k) in rdna4_tuned
|
||||
if on_gfx950():
|
||||
return (n, k) in gfx950_tuned
|
||||
return False
|
||||
try:
|
||||
return _triton_gemm_config_is_tuned("GEMM-A8W8_BLOCKSCALE", n, k)
|
||||
except (AssertionError, ImportError):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def is_triton_gemm_afp4wfp4_presh_ws_tuned(n: int, k: int) -> bool:
|
||||
return (n, k) in [
|
||||
(8192, 4096),
|
||||
(1280, 8192),
|
||||
(16384, 53248),
|
||||
(106496, 16384),
|
||||
(57344, 8192),
|
||||
(8192, 2048),
|
||||
(2560, 8192),
|
||||
(10240, 8192),
|
||||
(16384, 16384),
|
||||
(8192, 28672),
|
||||
(28672, 8192),
|
||||
(18432, 16384),
|
||||
(8192, 1024),
|
||||
(7168, 8192),
|
||||
(5120, 8192),
|
||||
(8192, 8192),
|
||||
(8192, 7168),
|
||||
(14336, 8192),
|
||||
(8192, 14336),
|
||||
(8192, 3584),
|
||||
]
|
||||
@functools.cache
|
||||
def is_triton_gemm_afp4wfp4_presh_ws_tuned(n: int, k_bytes: int) -> bool:
|
||||
if not current_platform.is_rocm():
|
||||
return False
|
||||
# Input = weight.shape[1] (bytes); *4 for fp4 and aiter config 2*k
|
||||
try:
|
||||
return _triton_gemm_config_is_tuned(
|
||||
"GEMM-AFP4WFP4_PRESHUFFLED", n, 4 * k_bytes
|
||||
)
|
||||
except (AssertionError, ImportError):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
@functools.cache
|
||||
def is_shuffled_per_token_w8a8_gemm_tuned(
|
||||
N: int, K: int, q_dtype_w: torch.dtype
|
||||
) -> bool:
|
||||
import aiter.ops.gemm_op_a8w8 as aiter_gemm_a8w8_ops
|
||||
|
||||
csv_path = (
|
||||
aiter_gemm_a8w8_ops.AITER_CONFIGS.AITER_CONFIG_GEMM_A8W8_BPRESHUFFLE_FILE
|
||||
return _ck_gemm_shape_is_tuned(
|
||||
N, K, q_dtype_w, "AITER_CONFIG_GEMM_A8W8_BPRESHUFFLE_FILE"
|
||||
)
|
||||
return _check_kernel_tuned(N, K, q_dtype_w, csv_path)
|
||||
|
||||
@staticmethod
|
||||
@functools.cache
|
||||
def is_per_token_w8a8_gemm_tuned(N: int, K: int, q_dtype_w: torch.dtype) -> bool:
|
||||
import aiter.ops.gemm_op_a8w8 as aiter_gemm_a8w8_ops
|
||||
|
||||
csv_path = aiter_gemm_a8w8_ops.AITER_CONFIGS.AITER_CONFIG_GEMM_A8W8_FILE
|
||||
return _check_kernel_tuned(N, K, q_dtype_w, csv_path)
|
||||
return _ck_gemm_shape_is_tuned(N, K, q_dtype_w, "AITER_CONFIG_GEMM_A8W8_FILE")
|
||||
|
||||
@staticmethod
|
||||
def shuffle_weight(
|
||||
|
||||
@@ -2272,7 +2272,21 @@ def moe_align_block_size(
|
||||
experts_ids: torch.Tensor,
|
||||
num_tokens_post_pad: torch.Tensor,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
scatter_idx: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
if current_platform.is_xpu():
|
||||
if scatter_idx is not None:
|
||||
raise NotImplementedError("scatter_idx is not supported on XPU")
|
||||
torch.ops._moe_C.moe_align_block_size(
|
||||
topk_ids,
|
||||
num_experts,
|
||||
block_size,
|
||||
sorted_token_ids,
|
||||
experts_ids,
|
||||
num_tokens_post_pad,
|
||||
expert_map,
|
||||
)
|
||||
return
|
||||
torch.ops._moe_C.moe_align_block_size(
|
||||
topk_ids,
|
||||
num_experts,
|
||||
@@ -2281,6 +2295,7 @@ def moe_align_block_size(
|
||||
experts_ids,
|
||||
num_tokens_post_pad,
|
||||
expert_map,
|
||||
scatter_idx,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from ..vllm_inductor_pass import (
|
||||
VllmPatternReplacement,
|
||||
_fx_view_to_reshape,
|
||||
fold_consecutive_reshapes,
|
||||
remove_noop_reshapes,
|
||||
)
|
||||
from .matcher_utils import (
|
||||
MatcherQuantFP8,
|
||||
@@ -452,9 +453,9 @@ class AiterRMSNormGatedFp8GroupQuantPattern(AiterRMSNormQuantPattern):
|
||||
"""Matches decomposed RMSNormGated + reshape + group FP8 quant and replaces
|
||||
with rocm_aiter_fused_rms_gated_fp8_group_quant.
|
||||
|
||||
The norm operates per-head on (N*H, D) tensors. The compiler folds the
|
||||
reshape chain so after norm the result goes through reshape->merge->quant.
|
||||
The pattern reshapes from (N*H, D) to (N, H*D) before calling
|
||||
The norm operates per-head, on either (N*H, D) or (N, H, D). The compiler
|
||||
folds the reshape chain so after norm the result goes through
|
||||
reshape->merge->quant. The pattern reshapes to (N, H*D) before calling
|
||||
MatcherQuantFP8 so that _quantize_group_native sees the full hidden dim
|
||||
and computes the correct num_groups.
|
||||
"""
|
||||
@@ -482,6 +483,16 @@ class AiterRMSNormGatedFp8GroupQuantPattern(AiterRMSNormQuantPattern):
|
||||
self.head_dim = head_dim
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
self._register_layout(pm_pass, flatten_heads=True)
|
||||
# Both layouts reach the norm. With an opaque quant op they trace to
|
||||
# the same pattern; with a native quant they differ, because its group
|
||||
# reshape back to (N, H, D) is a no-op the compiler already dropped.
|
||||
if not self.quant_matcher.enabled:
|
||||
self._register_layout(pm_pass, flatten_heads=False)
|
||||
|
||||
def _register_layout(
|
||||
self, pm_pass: PatternMatcherPass, *, flatten_heads: bool
|
||||
) -> None:
|
||||
num_heads = self.num_heads
|
||||
head_dim = self.head_dim
|
||||
hidden_dim = num_heads * head_dim
|
||||
@@ -502,6 +513,11 @@ class AiterRMSNormGatedFp8GroupQuantPattern(AiterRMSNormQuantPattern):
|
||||
z: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# The pattern matches on op structure rather than rank, so either
|
||||
# per-head layout can land here. The fused op takes (M, D), and
|
||||
# both operands are contiguous, so collapsing the heads is a view.
|
||||
x = x.reshape(-1, head_dim)
|
||||
z = z.reshape(-1, head_dim)
|
||||
fused = self.FUSED_OP(
|
||||
x=x,
|
||||
weight=weight,
|
||||
@@ -519,14 +535,21 @@ class AiterRMSNormGatedFp8GroupQuantPattern(AiterRMSNormQuantPattern):
|
||||
return fp8_reshaped, scales_reshaped
|
||||
|
||||
n_tokens = 2
|
||||
x = self.empty(n_tokens * num_heads, head_dim)
|
||||
z = self.empty(n_tokens * num_heads, head_dim)
|
||||
shape = (
|
||||
(n_tokens * num_heads, head_dim)
|
||||
if flatten_heads
|
||||
else (n_tokens, num_heads, head_dim)
|
||||
)
|
||||
x = self.empty(*shape)
|
||||
z = self.empty(*shape)
|
||||
w = self.empty(head_dim)
|
||||
|
||||
def trace_fn(*args, **kwargs):
|
||||
gm = pm.fwd_only(*args, **kwargs)
|
||||
_fx_view_to_reshape(gm)
|
||||
fold_consecutive_reshapes(gm)
|
||||
if not flatten_heads:
|
||||
remove_noop_reshapes(gm)
|
||||
return gm
|
||||
|
||||
pm.register_replacement(
|
||||
|
||||
@@ -277,6 +277,27 @@ def fold_consecutive_reshapes(gm: fx.GraphModule) -> None:
|
||||
gm.graph.erase_node(inp)
|
||||
|
||||
|
||||
def remove_noop_reshapes(gm: fx.GraphModule) -> None:
|
||||
"""Drop reshape ops whose output shape equals their input shape.
|
||||
|
||||
Companion to :func:`fold_consecutive_reshapes`. ``make_fx`` records a
|
||||
reshape to the shape the input already has; the compiled graph has already
|
||||
dropped it, so the pattern only matches once we drop it too.
|
||||
"""
|
||||
aten_reshape = torch.ops.aten.reshape.default
|
||||
for node in list(gm.graph.nodes):
|
||||
if not is_func(node, aten_reshape):
|
||||
continue
|
||||
inp = node.args[0]
|
||||
if not isinstance(inp, fx.Node):
|
||||
continue
|
||||
val, inp_val = node.meta.get("val"), inp.meta.get("val")
|
||||
if val is None or inp_val is None or val.shape != inp_val.shape:
|
||||
continue
|
||||
node.replace_all_uses_with(inp)
|
||||
gm.graph.erase_node(node)
|
||||
|
||||
|
||||
def _remove_noop_permutes(gm: fx.GraphModule) -> None:
|
||||
for node in gm.graph.nodes:
|
||||
if not is_func(node, torch.ops.aten.permute.default):
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm.config.attention import AttentionConfig, HiSparseConfig
|
||||
from vllm.config.aux_output import AuxOutputConfig
|
||||
from vllm.config.cache import CacheConfig
|
||||
from vllm.config.compilation import (
|
||||
CompilationConfig,
|
||||
@@ -66,6 +67,8 @@ from vllm.config.weight_transfer import WeightTransferConfig
|
||||
# __all__ should only contain classes and functions.
|
||||
# Types and globals should be imported from their respective modules.
|
||||
__all__ = [
|
||||
# From vllm.config.aux_output
|
||||
"AuxOutputConfig",
|
||||
# From vllm.config.attention
|
||||
"AttentionConfig",
|
||||
"HiSparseConfig",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Configuration for execution auxiliary outputs."""
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from vllm.config.utils import config
|
||||
|
||||
|
||||
@config
|
||||
class AuxOutputConfig:
|
||||
"""Configuration for auxiliary-output delivery."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Capture and return routed-experts auxiliary outputs."""
|
||||
|
||||
max_bytes: int | None = Field(default=None, gt=0)
|
||||
"""LRU capacity, or ``None`` to derive it from the KV cache capacity."""
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
"""Whether any execution auxiliary output is enabled."""
|
||||
return self.enable_return_routed_experts
|
||||
|
||||
def compute_hash(self) -> str:
|
||||
"""Hash AuxOutput settings that alter the model forward graph."""
|
||||
from vllm.config.utils import hash_factors
|
||||
|
||||
return hash_factors(
|
||||
{"enable_return_routed_experts": self.enable_return_routed_experts}
|
||||
)
|
||||
+15
-3
@@ -107,7 +107,19 @@ class CacheConfig:
|
||||
per-instance limit, and only applies to the current vLLM instance. It does
|
||||
not matter if you have another vLLM instance running on the same GPU. For
|
||||
example, if you have two vLLM instances running on the same GPU, you can
|
||||
set the GPU memory utilization to 0.5 for each instance."""
|
||||
set the GPU memory utilization to 0.5 for each instance. On non-GPU
|
||||
installs, this value controls the corresponding device memory utilization.
|
||||
"""
|
||||
|
||||
@property
|
||||
def device_memory_utilization(self) -> float:
|
||||
"""Device-neutral alias for ``gpu_memory_utilization``."""
|
||||
return self.gpu_memory_utilization
|
||||
|
||||
@device_memory_utilization.setter
|
||||
def device_memory_utilization(self, value: float) -> None:
|
||||
self.gpu_memory_utilization = value
|
||||
|
||||
cache_dtype: CacheDType = "auto"
|
||||
"""Data type for kv cache storage. If "auto", will use model data type.
|
||||
CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. ROCm (AMD GPU) supports
|
||||
@@ -184,7 +196,7 @@ class CacheConfig:
|
||||
when the token is at position i * block_size. This is the default when prefix
|
||||
caching is enabled.
|
||||
"""
|
||||
enable_mamba_fine_grained_prefix_cache: bool = False
|
||||
enable_mamba_shared_prefix_checkpoint: bool = False
|
||||
"""Also register a Mamba "align" checkpoint at the shared-prefix junction --
|
||||
where an EAGLE/MTP sibling was observed to resume -- instead of only at the
|
||||
prompt tail. Off by default; only takes effect with `mamba_cache_mode`
|
||||
@@ -274,7 +286,7 @@ class CacheConfig:
|
||||
"prefix_cache_retention_interval",
|
||||
# Prefix-caching implementation detail (doesn't affect compiled graph).
|
||||
"prefix_match_unit",
|
||||
"enable_mamba_fine_grained_prefix_cache",
|
||||
"enable_mamba_shared_prefix_checkpoint",
|
||||
"mamba_page_size_padded",
|
||||
"skip_page_size_padded",
|
||||
"user_specified_block_size",
|
||||
|
||||
+17
-26
@@ -3,14 +3,12 @@
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.utils import config, get_hash_factors, hash_factors
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.config.model import ModelConfig
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
|
||||
@@ -23,10 +21,6 @@ _NGRAM_LAYER_FIELDS = {
|
||||
}
|
||||
|
||||
|
||||
def _default_cpu_offload() -> bool:
|
||||
return envs.VLLM_PLE_CPU_OFFLOAD
|
||||
|
||||
|
||||
def model_has_engram_layers(model_config: "ModelConfig | None") -> bool:
|
||||
"""Whether the model carries n-gram embedding layers."""
|
||||
if model_config is None:
|
||||
@@ -41,20 +35,20 @@ def model_has_engram_layers(model_config: "ModelConfig | None") -> bool:
|
||||
class EngramConfig:
|
||||
"""Configuration for Engram embedding storage and sharding."""
|
||||
|
||||
cpu_offload: bool = Field(default_factory=_default_cpu_offload)
|
||||
"""Store embedding weights in pinned CPU memory for UVA lookup.
|
||||
Defaults to VLLM_PLE_CPU_OFFLOAD, which is enabled by default. An explicit
|
||||
value takes precedence over the environment variable."""
|
||||
cpu_offload: bool = True
|
||||
"""Store embedding weights in pinned CPU memory for UVA lookup."""
|
||||
|
||||
embedding_across_dp: bool = False
|
||||
"""Shard embeddings across TP and all DP ranks when enabled.
|
||||
Otherwise, each DP rank has a separate TP-sharded embedding replica."""
|
||||
|
||||
dp_shared_memory: bool = False
|
||||
dp_shared_memory: bool | None = None
|
||||
"""Share CPU-offloaded embedding weights between co-located
|
||||
DP replicas. Each node stores one copy of every TP shard, reducing host
|
||||
memory without per-step Engram DP collectives. Requires sufficient
|
||||
/dev/shm capacity and a shared IPC namespace."""
|
||||
/dev/shm capacity and a shared IPC namespace. Defaults to enabled whenever
|
||||
the other settings allow it, falling back to per-replica tables when DP
|
||||
replicas are not co-located on one node or /dev/shm cannot hold them."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_shared_memory(self) -> Self:
|
||||
@@ -74,7 +68,7 @@ class EngramConfig:
|
||||
if (
|
||||
model_config is None
|
||||
or field is None
|
||||
or not current_platform.is_cuda()
|
||||
or not current_platform.is_cuda_alike()
|
||||
or not getattr(model_config.hf_text_config, field, None)
|
||||
):
|
||||
raise ValueError(
|
||||
@@ -82,6 +76,15 @@ class EngramConfig:
|
||||
"embeddings, non-empty n-gram layer ids, and CUDA."
|
||||
)
|
||||
|
||||
def resolve_dp_shared_memory(self, parallel_config: "ParallelConfig") -> None:
|
||||
"""Share host tables by default wherever the configuration permits."""
|
||||
if self.dp_shared_memory is None:
|
||||
self.dp_shared_memory = (
|
||||
self.cpu_offload
|
||||
and parallel_config.data_parallel_size > 1
|
||||
and not parallel_config.enable_elastic_ep
|
||||
)
|
||||
|
||||
def verify_parallel_config(self, parallel_config: "ParallelConfig") -> None:
|
||||
"""Reject unsupported embedding parallel topologies."""
|
||||
if self.dp_shared_memory:
|
||||
@@ -98,18 +101,6 @@ class EngramConfig:
|
||||
"Engram embedding_across_dp is not supported with elastic EP yet."
|
||||
)
|
||||
|
||||
def verify_load_config(self, load_config: "LoadConfig") -> None:
|
||||
"""Shared tables require a loader that invokes parameter weight callbacks."""
|
||||
if self.dp_shared_memory and load_config.load_format not in (
|
||||
"auto",
|
||||
"safetensors",
|
||||
"pt",
|
||||
):
|
||||
raise ValueError(
|
||||
"dp_shared_memory requires load_format 'auto', "
|
||||
f"'safetensors' or 'pt'; got {load_config.load_format!r}."
|
||||
)
|
||||
|
||||
def get_parallel_size(self, parallel_config: "ParallelConfig") -> int:
|
||||
"""Derive the embedding group size from the parallel configuration."""
|
||||
size = parallel_config.tensor_parallel_size
|
||||
|
||||
+83
-10
@@ -247,8 +247,6 @@ class ModelConfig:
|
||||
|
||||
NOTE: This disables both `torch.compile` and CUDA graphs, and is
|
||||
equivalent to setting `-cc.mode=none -cc.cudagraph_mode=none`."""
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Whether to return routed experts."""
|
||||
return_sampling_mask: bool = False
|
||||
"""Whether to return the post-processing token support for each sample."""
|
||||
max_logprobs: int = Field(default=20, ge=-1)
|
||||
@@ -342,6 +340,9 @@ class ModelConfig:
|
||||
enable_sleep_mode: bool = False
|
||||
"""Enable sleep mode for the engine (only cuda and
|
||||
hip platforms are supported)."""
|
||||
sleep_preserve_parameter_names: list[str] = field(default_factory=list)
|
||||
"""Parameter-name globs to preserve across level-2 sleep.
|
||||
The sender must omit these parameters; loaders must preserve their storage."""
|
||||
sleep_mode_backend: str = "cumem"
|
||||
"""Mechanism used to free and restore GPU state for sleep mode. ``"cumem"``
|
||||
(default) uses the built-in ``CuMemAllocator`` and is behavior-compatible
|
||||
@@ -867,6 +868,80 @@ class ModelConfig:
|
||||
self._verify_quantization()
|
||||
self._verify_cuda_graph()
|
||||
|
||||
def _supports_multimodal_inputs(self) -> bool:
|
||||
"""Checks if the model supports multimodal inputs.
|
||||
Returns True if the model is multimodal with any non-zero supported
|
||||
modalities, otherwise returns False, effectively running in
|
||||
text-only mode.
|
||||
"""
|
||||
if not self.is_multimodal_model:
|
||||
return False
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
mm_config = self.get_multimodal_config()
|
||||
try:
|
||||
info = MULTIMODAL_REGISTRY.get_processing_info(self)
|
||||
except ValueError:
|
||||
# Speculative drafters for multimodal targets (e.g. Qwen3_5MTP,
|
||||
# Exaone4_5_MTP, MiMoV2OmniMTP) declare `SupportsMultiModal` so
|
||||
# that they can consume the embeddings merged by the target model,
|
||||
# but they never run a multi-modal processor of their own. Running
|
||||
# in text-only mode is the expected outcome for them, not a
|
||||
# misconfiguration worth warning about.
|
||||
if self.runner_type != "draft":
|
||||
logger.warning_once(
|
||||
"Model %s is treated as multimodal but has no registered "
|
||||
"multimodal processor; running in text-only mode.",
|
||||
self.model,
|
||||
)
|
||||
return False
|
||||
|
||||
# Check if all supported modalities have limit == 0
|
||||
if all(
|
||||
mm_config.get_limit_per_prompt(modality) == 0
|
||||
for modality in info.supported_mm_limits
|
||||
):
|
||||
# If enable_mm_embeds is True, we still need MM infrastructure
|
||||
# to process pre-computed embeddings even though encoder won't run
|
||||
if mm_config.enable_mm_embeds:
|
||||
return True
|
||||
|
||||
logger.info_once(
|
||||
"All limits of multimodal modalities supported by the model "
|
||||
"are set to 0, running in text-only mode."
|
||||
)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _cached_supports_multimodal_inputs(self) -> bool:
|
||||
cache = getattr(self, "_supports_multimodal_inputs_cache", None)
|
||||
if cache is None:
|
||||
self._supports_multimodal_inputs_cache = cache = {}
|
||||
|
||||
mm_config = self.multimodal_config
|
||||
if mm_config is None:
|
||||
mm_cache_key = None
|
||||
else:
|
||||
limits_per_prompt = {
|
||||
modality: mm_config.get_limit_per_prompt(modality)
|
||||
for modality in mm_config.limit_per_prompt
|
||||
}
|
||||
mm_cache_key = (
|
||||
mm_config.language_model_only,
|
||||
tuple(limits_per_prompt.items()),
|
||||
mm_config.enable_mm_embeds,
|
||||
)
|
||||
|
||||
cache_key = (self.is_multimodal_model, self.runner_type, mm_cache_key)
|
||||
if cache_key in cache:
|
||||
return cache[cache_key]
|
||||
|
||||
supports_mm = self._supports_multimodal_inputs()
|
||||
cache[cache_key] = supports_mm
|
||||
return supports_mm
|
||||
|
||||
def _supports_multimodal_for_mm_prefix(self) -> bool:
|
||||
"""Whether multimodal inputs can still appear for this deployment.
|
||||
|
||||
@@ -883,24 +958,18 @@ class ModelConfig:
|
||||
vision modality is still enabled (e.g. ``image=0`` but video allowed).
|
||||
The deep-copied cache preserves the top-level decision instead.
|
||||
"""
|
||||
cached = getattr(self, "_supports_multimodal_inputs_cached", None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
if self.multimodal_config is None:
|
||||
# Early call before multimodal init — do not clear mm_prefix yet.
|
||||
return True
|
||||
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
|
||||
supports_mm = MULTIMODAL_REGISTRY.supports_multimodal_inputs(self)
|
||||
self._supports_multimodal_inputs_cached = supports_mm
|
||||
supports_mm = self._cached_supports_multimodal_inputs()
|
||||
if not supports_mm:
|
||||
logger.info_once(
|
||||
"Disabled mm_prefix attention mode because multimodal inputs "
|
||||
"are configuration-disabled. Attention backends without "
|
||||
"mm_prefix support may now be selected."
|
||||
)
|
||||
|
||||
return supports_mm
|
||||
|
||||
def get_model_arch_config(self) -> ModelArchitectureConfig:
|
||||
@@ -1861,6 +1930,10 @@ class ModelConfig:
|
||||
def is_multimodal_raw_input_only_model(self) -> bool:
|
||||
return self._model_info.supports_multimodal_raw_input_only
|
||||
|
||||
@property
|
||||
def supports_multimodal_inputs(self) -> bool:
|
||||
return self._cached_supports_multimodal_inputs()
|
||||
|
||||
@property
|
||||
def requires_raw_input_tokens(self) -> bool:
|
||||
return self._model_info.requires_raw_input_tokens
|
||||
|
||||
+19
-1
@@ -760,12 +760,30 @@ class ParallelConfig:
|
||||
|
||||
@property
|
||||
def nnodes_within_dp(self) -> int:
|
||||
"""Number of nodes one DP replica spans.
|
||||
|
||||
External LB pins ``data_parallel_size_local`` to 1, so the ratio
|
||||
rounds down to 0 once DP replicas outnumber nodes. A replica that
|
||||
does not span nodes still occupies exactly one.
|
||||
"""
|
||||
if self.nnodes == 1:
|
||||
return 1
|
||||
data_parallel_node_size = (
|
||||
self.data_parallel_size // self.data_parallel_size_local
|
||||
)
|
||||
return self.nnodes // data_parallel_node_size
|
||||
nnodes_within_dp = self.nnodes // data_parallel_node_size
|
||||
if self.data_parallel_external_lb:
|
||||
return max(nnodes_within_dp, 1)
|
||||
if self.nnodes % data_parallel_node_size != 0:
|
||||
raise ValueError(
|
||||
"Invalid data parallel configuration: "
|
||||
f"nnodes ({self.nnodes}) must be divisible by the number of "
|
||||
"data parallel node groups "
|
||||
f"({data_parallel_node_size} = data_parallel_size "
|
||||
f"{self.data_parallel_size} / data_parallel_size_local "
|
||||
f"{self.data_parallel_size_local})"
|
||||
)
|
||||
return nnodes_within_dp
|
||||
|
||||
@property
|
||||
def local_world_size(self) -> int:
|
||||
|
||||
+25
-1
@@ -14,6 +14,7 @@ from vllm.utils.hashing import safe_hash
|
||||
logger = init_logger(__name__)
|
||||
|
||||
ProfilerKind = Literal["torch", "cuda", "proton"]
|
||||
TorchProfilerActivity = Literal["CPU", "CUDA", "PrivateUse1", "XPU"]
|
||||
ProtonBackend = Literal["cupti"]
|
||||
ProtonContext = Literal["shadow", "python"]
|
||||
ProtonData = Literal["tree", "trace"]
|
||||
@@ -51,6 +52,12 @@ class ProfilerConfig:
|
||||
worker's traces (CPU & GPU) will be saved under this directory. Note that
|
||||
it must be an absolute path."""
|
||||
|
||||
torch_profiler_activities: list[TorchProfilerActivity] | None = Field(
|
||||
default=None, min_length=1
|
||||
)
|
||||
"""Activities recorded by workers using the torch profiler. When unset,
|
||||
each worker uses its platform default: CPU; CPU and CUDA; or CPU and XPU."""
|
||||
|
||||
proton_profiler_dir: str = ""
|
||||
"""Directory to save Triton Proton profiles. Each worker writes a
|
||||
separate rank-qualified file."""
|
||||
@@ -170,7 +177,24 @@ class ProfilerConfig:
|
||||
@model_validator(mode="after")
|
||||
def _validate_profiler_config(self) -> Self:
|
||||
has_delay_or_limit = self.delay_iterations > 0 or self.max_iterations > 0
|
||||
if self.profiler == "torch" and has_delay_or_limit and not self.ignore_frontend:
|
||||
activities = self.torch_profiler_activities
|
||||
if activities is not None:
|
||||
if self.profiler != "torch":
|
||||
raise ValueError(
|
||||
"torch_profiler_activities is only applicable when profiler "
|
||||
"is set to 'torch'"
|
||||
)
|
||||
if len(activities) != len(set(activities)):
|
||||
raise ValueError(
|
||||
"torch_profiler_activities must not contain duplicates"
|
||||
)
|
||||
records_cpu_activity = activities is None or "CPU" in activities
|
||||
if (
|
||||
self.profiler == "torch"
|
||||
and has_delay_or_limit
|
||||
and not self.ignore_frontend
|
||||
and records_cpu_activity
|
||||
):
|
||||
logger.warning_once(
|
||||
"Using 'torch' profiler with delay_iterations or max_iterations "
|
||||
"while ignore_frontend is False may result in high overhead."
|
||||
|
||||
@@ -79,7 +79,10 @@ class SchedulerConfig:
|
||||
|
||||
long_prefill_token_threshold: int = Field(default=0, ge=0)
|
||||
"""For chunked prefill, a request is considered long if the prompt is
|
||||
longer than this number of tokens. 0 disables the cap (default)."""
|
||||
longer than this number of tokens. 0 disables the cap (default).
|
||||
|
||||
The cap is not applied when the request is the only one in the batch,
|
||||
since there is no other request for it to starve."""
|
||||
|
||||
max_num_queued_reqs: int | None = Field(default=None, ge=0)
|
||||
"""Maximum number of requests that can be in-flight (waiting or running)
|
||||
|
||||
@@ -14,7 +14,7 @@ from vllm.config.cache import CacheDType
|
||||
from vllm.config.kernel import MoEBackend
|
||||
from vllm.config.model import HfOverrides, ModelConfig
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
from vllm.config.utils import config
|
||||
from vllm.config.utils import config, replace
|
||||
from vllm.logger import init_logger
|
||||
from vllm.transformers_utils.config import get_hf_text_config
|
||||
from vllm.utils.hashing import safe_hash
|
||||
@@ -25,8 +25,10 @@ if TYPE_CHECKING:
|
||||
from transformers import PretrainedConfig
|
||||
|
||||
import vllm.model_executor.layers.quantization as me_quant
|
||||
from vllm.config.vllm import VllmConfig
|
||||
else:
|
||||
PretrainedConfig = Any
|
||||
VllmConfig = Any
|
||||
|
||||
me_quant = LazyLoader(
|
||||
"model_executor", globals(), "vllm.model_executor.layers.quantization"
|
||||
@@ -371,6 +373,17 @@ def _validate_qwen3_omni_dspark(
|
||||
)
|
||||
|
||||
|
||||
# (SpeculativeConfig field, VllmConfig sub-config, overridden field)
|
||||
_DRAFT_VLLM_CONFIG_OVERRIDES = (
|
||||
# Otherwise the draft inherits the target's --moe-backend, which fails
|
||||
# when the draft is unquantized and that backend is not.
|
||||
("moe_backend", "kernel_config", "moe_backend"),
|
||||
# Only when set, so the draft keeps a KV cache layout the target shares.
|
||||
("attention_backend", "attention_config", "backend"),
|
||||
("kv_cache_dtype", "cache_config", "cache_dtype"),
|
||||
)
|
||||
|
||||
|
||||
@config
|
||||
class SpeculativeConfig:
|
||||
"""Configuration for speculative decoding."""
|
||||
@@ -1771,6 +1784,18 @@ class SpeculativeConfig:
|
||||
|
||||
return draft_parallel_config
|
||||
|
||||
def apply_draft_overrides(self, vllm_config: VllmConfig) -> VllmConfig:
|
||||
"""Overlay this config's kernel overrides onto a target VllmConfig.
|
||||
|
||||
Only non-None fields override, so an unset field keeps whatever the
|
||||
target resolved.
|
||||
"""
|
||||
for src, config_name, dst in _DRAFT_VLLM_CONFIG_OVERRIDES:
|
||||
if (value := getattr(self, src)) is not None:
|
||||
sub_config = replace(getattr(vllm_config, config_name), **{dst: value})
|
||||
vllm_config = replace(vllm_config, **{config_name: sub_config})
|
||||
return vllm_config
|
||||
|
||||
@field_validator("attention_backend", mode="before")
|
||||
@classmethod
|
||||
def _parse_attention_backend(cls, value: Any) -> Any:
|
||||
|
||||
+87
-37
@@ -28,6 +28,7 @@ from vllm.utils import random_uuid
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
from .attention import AttentionConfig, HiSparseConfig
|
||||
from .aux_output import AuxOutputConfig
|
||||
from .cache import CacheConfig
|
||||
from .compilation import CompilationConfig, CompilationMode, CUDAGraphMode
|
||||
from .device import DeviceConfig
|
||||
@@ -376,6 +377,8 @@ class VllmConfig:
|
||||
"""Model weight offloading configuration."""
|
||||
attention_config: AttentionConfig = Field(default_factory=AttentionConfig)
|
||||
"""Attention configuration."""
|
||||
aux_output_config: AuxOutputConfig = Field(default_factory=AuxOutputConfig)
|
||||
"""Execution auxiliary output configuration."""
|
||||
engram_config: EngramConfig | None = None
|
||||
"""N-gram embedding storage and sharding settings."""
|
||||
mamba_config: MambaConfig = Field(default_factory=MambaConfig)
|
||||
@@ -554,6 +557,7 @@ class VllmConfig:
|
||||
vllm_factors.append(self.ec_transfer_config.compute_hash())
|
||||
else:
|
||||
vllm_factors.append("None")
|
||||
vllm_factors.append(self.aux_output_config.compute_hash())
|
||||
if self.additional_config:
|
||||
if isinstance(additional_config := self.additional_config, dict):
|
||||
additional_config_hash = safe_hash(
|
||||
@@ -1084,6 +1088,58 @@ class VllmConfig:
|
||||
# This is the same for all backends
|
||||
self.kv_transfer_config.kv_role = "kv_both"
|
||||
|
||||
def _verify_aux_output_compatibility(self) -> None:
|
||||
"""Reject configurations unsupported by enabled auxiliary outputs."""
|
||||
if not self.aux_output_config.enabled:
|
||||
return
|
||||
if not self.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"AuxOutput Connector requires Model Runner V2; set "
|
||||
"VLLM_USE_V2_MODEL_RUNNER=1."
|
||||
)
|
||||
if self.model_config.runner_type != "generate":
|
||||
raise ValueError("AuxOutput Connector only supports generate runners.")
|
||||
if not self.model_config.is_moe:
|
||||
raise ValueError("AuxOutput Connector only supports MoE models.")
|
||||
if not self.cache_config.enable_prefix_caching:
|
||||
raise ValueError("AuxOutput Connector requires prefix caching.")
|
||||
if (
|
||||
self.speculative_config is not None
|
||||
and self.speculative_config.enable_adaptive_verification
|
||||
):
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with "
|
||||
"adaptive speculative verification."
|
||||
)
|
||||
if self.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with "
|
||||
"pipeline parallelism (PP > 1)."
|
||||
)
|
||||
if (
|
||||
self.parallel_config.decode_context_parallel_size > 1
|
||||
or self.parallel_config.prefill_context_parallel_size > 1
|
||||
):
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with "
|
||||
"context parallelism (DCP/PCP > 1)."
|
||||
)
|
||||
|
||||
kv_transfer_config = self.kv_transfer_config
|
||||
if kv_transfer_config is not None:
|
||||
for connector_name in (
|
||||
"NixlConnector",
|
||||
"NixlPullConnector",
|
||||
"NixlPushConnector",
|
||||
"MoRIIOConnector",
|
||||
"MooncakeConnector",
|
||||
):
|
||||
if kv_transfer_config.has_connector(connector_name):
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with "
|
||||
f"{connector_name}; PD auxiliary output is not supported."
|
||||
)
|
||||
|
||||
def _verify_kv_transfer_compat(self) -> None:
|
||||
"""Reject configurations that silently corrupt KV transfers."""
|
||||
if (
|
||||
@@ -1260,14 +1316,14 @@ class VllmConfig:
|
||||
"Disable --enable-dbo and set --ubatch-size to 0."
|
||||
)
|
||||
if self.engram_config is None:
|
||||
if not current_platform.is_cuda() or not model_has_engram_layers(
|
||||
if not current_platform.is_cuda_alike() or not model_has_engram_layers(
|
||||
model_config
|
||||
):
|
||||
return
|
||||
self.engram_config = EngramConfig()
|
||||
self.engram_config.verify_model_config(model_config)
|
||||
self.engram_config.resolve_dp_shared_memory(self.parallel_config)
|
||||
self.engram_config.verify_parallel_config(self.parallel_config)
|
||||
self.engram_config.verify_load_config(self.load_config)
|
||||
logger.info_once("Resolved Engram configuration: %s", str(self.engram_config))
|
||||
|
||||
def __post_init__(self):
|
||||
@@ -1294,38 +1350,6 @@ class VllmConfig:
|
||||
|
||||
self.parallel_config.is_moe_model = self.model_config.is_moe
|
||||
|
||||
if (
|
||||
self.model_config is not None
|
||||
and self.model_config.enable_return_routed_experts
|
||||
):
|
||||
if self.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with "
|
||||
"pipeline parallelism (PP > 1)."
|
||||
)
|
||||
if (
|
||||
self.parallel_config.decode_context_parallel_size > 1
|
||||
or self.parallel_config.prefill_context_parallel_size > 1
|
||||
):
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with context "
|
||||
"parallelism (DCP > 1 or PCP > 1)."
|
||||
)
|
||||
|
||||
# Incompatible with any KV connector — covers both PD disaggregation
|
||||
# (kv_producer/kv_consumer: routing captured on P can't reach D) and
|
||||
# single-instance KV offload/sharing (kv_both: slot_mapping semantics
|
||||
# change when KV blocks live outside local GPU memory, breaking the
|
||||
# slot-indexed routed_experts buffer).
|
||||
if (
|
||||
self.kv_transfer_config is not None
|
||||
and self.kv_transfer_config.is_kv_transfer_instance
|
||||
):
|
||||
raise ValueError(
|
||||
"--enable-return-routed-experts is incompatible with KV "
|
||||
"connectors (PD disaggregation, KV cache offload)."
|
||||
)
|
||||
|
||||
if (
|
||||
self.model_config is not None
|
||||
and self.model_config.multimodal_config is not None
|
||||
@@ -1438,11 +1462,12 @@ class VllmConfig:
|
||||
and self.speculative_config.method not in get_args(NgramGPUTypes)
|
||||
and self.speculative_config.method != "draft_model"
|
||||
and self.speculative_config.method != "dspark"
|
||||
and self.speculative_config.method != "dflash"
|
||||
):
|
||||
raise ValueError(
|
||||
"Currently, async scheduling is only supported "
|
||||
"with EAGLE/MTP/Draft Model/NGram GPU/DSpark kind of "
|
||||
"speculative decoding"
|
||||
"with EAGLE/MTP/Draft Model/NGram GPU/DSpark/DFlash "
|
||||
"kind of speculative decoding"
|
||||
)
|
||||
if self.speculative_config.disable_padded_drafter_batch:
|
||||
raise ValueError(
|
||||
@@ -1471,6 +1496,7 @@ class VllmConfig:
|
||||
and self.speculative_config.method not in get_args(NgramGPUTypes)
|
||||
and self.speculative_config.method != "draft_model"
|
||||
and self.speculative_config.method != "dspark"
|
||||
and self.speculative_config.method != "dflash"
|
||||
):
|
||||
logger.warning_once(
|
||||
"Async scheduling not supported with %s-based "
|
||||
@@ -1501,6 +1527,15 @@ class VllmConfig:
|
||||
"DP+EP generation accuracy."
|
||||
)
|
||||
self.scheduler_config.async_scheduling = False
|
||||
elif (
|
||||
self.parallel_config.pipeline_parallel_size > 1
|
||||
and not self.use_v2_model_runner
|
||||
):
|
||||
logger.warning_once(
|
||||
"Async scheduling is disabled because the V1 model runner "
|
||||
"does not support it with pipeline parallelism."
|
||||
)
|
||||
self.scheduler_config.async_scheduling = False
|
||||
else:
|
||||
self.scheduler_config.async_scheduling = True
|
||||
|
||||
@@ -2032,6 +2067,7 @@ class VllmConfig:
|
||||
# Resolve kv_offloading-derived connector name into kv_transfer_config
|
||||
# before the HMA check below, which inspects the connector class.
|
||||
self._post_init_kv_transfer_config()
|
||||
self._verify_aux_output_compatibility()
|
||||
|
||||
if self.is_mm_encoder_only and self.cache_config.enable_prefix_caching:
|
||||
# Such an instance publishes encoder embeddings and runs no language
|
||||
@@ -2689,7 +2725,7 @@ class VllmConfig:
|
||||
f"quantization={self.model_config.quantization}, "
|
||||
f"quantization_config={self.model_config.quantization_config}, " # noqa
|
||||
f"enforce_eager={self.model_config.enforce_eager}, "
|
||||
f"enable_return_routed_experts={self.model_config.enable_return_routed_experts}, " # noqa
|
||||
f"aux_output_config={self.aux_output_config!r}, "
|
||||
f"kv_cache_dtype={self.cache_config.cache_dtype}, "
|
||||
f"device_config={self.device_config.device}, "
|
||||
f"structured_outputs_config={self.structured_outputs_config!r}, "
|
||||
@@ -2940,6 +2976,20 @@ class VllmConfig:
|
||||
if self.parallel_config.prefill_context_parallel_size > 1:
|
||||
unsupported.append("prefill context parallel")
|
||||
|
||||
# Note(arpera):
|
||||
# MRV1 + PP>1 + async sched + structured output
|
||||
# does not work in vLLM. For more info see:
|
||||
# https://github.com/vllm-project/vllm/issues/45014
|
||||
# Since recently MRV1 has been deprecated then
|
||||
# there was decided not to fix the issue but instead
|
||||
# to disallow such configuration.
|
||||
# At the same time MRV2 works fine in this case.
|
||||
if (
|
||||
self.parallel_config.pipeline_parallel_size > 1
|
||||
and self.scheduler_config.async_scheduling
|
||||
):
|
||||
unsupported.append("pipeline parallelism with async scheduling")
|
||||
|
||||
# DSpark is implemented only by the V2 GPU model runner.
|
||||
if self.speculative_config:
|
||||
if self.speculative_config.method == "dspark":
|
||||
|
||||
@@ -78,6 +78,10 @@ def make_sdesc_128B_swizzle(LBO: int):
|
||||
return Uint64((LBO >> 4 << 16) | (SBO >> 4 << 32) | (1 << 46) | (2 << 61))
|
||||
|
||||
|
||||
def make_mxfp8_idesc(MMA_M: int, MMA_N: int):
|
||||
return Uint32((MMA_N >> 3 << 17) | (1 << 23) | (MMA_M >> 7 << 27))
|
||||
|
||||
|
||||
@dsl_user_op
|
||||
def mma_f16(
|
||||
d_tmem,
|
||||
@@ -130,6 +134,73 @@ def mma_ts_f16(
|
||||
)
|
||||
|
||||
|
||||
@dsl_user_op
|
||||
def mma_mxfp8(
|
||||
d_tmem,
|
||||
a_desc,
|
||||
b_desc,
|
||||
idesc,
|
||||
sfa_tmem,
|
||||
sfb_tmem,
|
||||
enable_input_d,
|
||||
cta_group: int = 1,
|
||||
*,
|
||||
loc=None,
|
||||
ip=None,
|
||||
) -> None:
|
||||
with cute.arch.elect_one():
|
||||
nvvm.tcgen05_mma_block_scale(
|
||||
nvvm.Tcgen05MMAKind.MXF8F6F4,
|
||||
NVVM_CTA_GROUP_MAP[cta_group],
|
||||
_make_tmem_llvm_ptr(d_tmem, loc=loc, ip=ip),
|
||||
Uint64(a_desc).ir_value(loc=loc, ip=ip),
|
||||
Uint64(b_desc).ir_value(loc=loc, ip=ip),
|
||||
Int32(idesc).ir_value(loc=loc, ip=ip),
|
||||
Boolean(enable_input_d).ir_value(loc=loc, ip=ip),
|
||||
_make_tmem_llvm_ptr(sfa_tmem, loc=loc, ip=ip),
|
||||
_make_tmem_llvm_ptr(sfb_tmem, loc=loc, ip=ip),
|
||||
scale_vec_size=nvvm.Tcgen05MMAScaleVecSize.X1,
|
||||
loc=loc,
|
||||
ip=ip,
|
||||
)
|
||||
|
||||
|
||||
@dsl_user_op
|
||||
def cp(
|
||||
tmem,
|
||||
sdesc,
|
||||
shape: str,
|
||||
mcast: str,
|
||||
cta_group: int = 1,
|
||||
*,
|
||||
loc=None,
|
||||
ip=None,
|
||||
) -> None:
|
||||
SHAPE_MAP = {
|
||||
"128x256b": nvvm.Tcgen05CpShape.SHAPE_128x256b,
|
||||
"4x256b": nvvm.Tcgen05CpShape.SHAPE_4x256b,
|
||||
"128x128b": nvvm.Tcgen05CpShape.SHAPE_128x128b,
|
||||
"64x128b": nvvm.Tcgen05CpShape.SHAPE_64x128b,
|
||||
"32x128b": nvvm.Tcgen05CpShape.SHAPE_32x128b,
|
||||
}
|
||||
MCAST_MAP = {
|
||||
"none": nvvm.Tcgen05CpMulticast.NONE,
|
||||
"warpx2::02_13": nvvm.Tcgen05CpMulticast.WARPX2_02_13,
|
||||
"warpx2::01_23": nvvm.Tcgen05CpMulticast.WARPX2_01_23,
|
||||
"warpx4": nvvm.Tcgen05CpMulticast.WARPX4,
|
||||
}
|
||||
with cute.arch.elect_one():
|
||||
nvvm.tcgen05_cp(
|
||||
SHAPE_MAP[shape],
|
||||
_make_tmem_llvm_ptr(tmem, loc=loc, ip=ip),
|
||||
Uint64(sdesc).ir_value(loc=loc, ip=ip),
|
||||
group=NVVM_CTA_GROUP_MAP[cta_group],
|
||||
multicast=MCAST_MAP[mcast],
|
||||
loc=loc,
|
||||
ip=ip,
|
||||
)
|
||||
|
||||
|
||||
@dsl_user_op
|
||||
def commit(mbar, cta_mask=None, cta_group: int = 1, *, loc=None, ip=None):
|
||||
mbar_llvm = mbar.to_llvm_ptr(loc=loc, ip=ip)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,157 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Scheduler-side control plane for execution auxiliary outputs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.request import Request
|
||||
|
||||
|
||||
@dataclass
|
||||
class PackedBlockHashes:
|
||||
"""Contiguous, self-contained block hashes for scheduler-worker IPC."""
|
||||
|
||||
data: bytes
|
||||
item_size: int
|
||||
|
||||
def __iter__(self) -> Iterator[bytes]:
|
||||
for start in range(0, len(self.data), self.item_size):
|
||||
yield self.data[start : start + self.item_size]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuxOutputConnectorMetadata:
|
||||
generation: int
|
||||
requests: dict[str, int]
|
||||
block_hashes: dict[str, PackedBlockHashes]
|
||||
finished_requests: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuxRequestOutput:
|
||||
token_start: int
|
||||
rows: np.ndarray
|
||||
|
||||
|
||||
class AuxOutputSchedulerConnector:
|
||||
"""Build worker metadata without owning auxiliary output payloads or stores."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# Number of hashes already sent to the worker for each active request.
|
||||
self._sent_hash_counts: dict[str, int] = {}
|
||||
# Terminal events are delivered with the next connector metadata.
|
||||
self._finished_requests: dict[str, PackedBlockHashes | None] = {}
|
||||
self._generation = 0
|
||||
|
||||
def build_connector_meta(
|
||||
self,
|
||||
scheduler_output: SchedulerOutput,
|
||||
requests: dict[str, Request],
|
||||
) -> AuxOutputConnectorMetadata:
|
||||
"""Build one step's incremental worker metadata."""
|
||||
scheduled_requests: dict[str, int] = {}
|
||||
block_hashes_by_request: dict[str, PackedBlockHashes] = {}
|
||||
for request_id in scheduler_output.num_scheduled_tokens:
|
||||
num_sent = self._sent_hash_counts.setdefault(request_id, 0)
|
||||
request = requests[request_id]
|
||||
packed = self._pack_new_hashes(request.block_hashes, num_sent)
|
||||
if packed is not None:
|
||||
block_hashes_by_request[request_id] = packed
|
||||
self._sent_hash_counts[request_id] = len(request.block_hashes)
|
||||
assert request.sampling_params is not None
|
||||
scheduled_requests[request_id] = max(
|
||||
request.sampling_params.routed_experts_prompt_start,
|
||||
0 if request.num_output_tokens == 0 else request.num_tokens - 1,
|
||||
)
|
||||
# A settled token can complete a hash block after the next async schedule
|
||||
# was built. Send a hash-only update if the request was not rescheduled.
|
||||
if len(self._sent_hash_counts) != len(scheduled_requests):
|
||||
for request_id, num_sent in self._sent_hash_counts.items():
|
||||
if request_id in scheduled_requests:
|
||||
continue
|
||||
request = requests[request_id]
|
||||
packed = self._pack_new_hashes(request.block_hashes, num_sent)
|
||||
if packed is None:
|
||||
continue
|
||||
block_hashes_by_request[request_id] = packed
|
||||
self._sent_hash_counts[request_id] = len(request.block_hashes)
|
||||
# Sending transfers ownership of these one-shot events.
|
||||
finished_requests = tuple(self._finished_requests)
|
||||
block_hashes_by_request.update(
|
||||
(request_id, block_hashes)
|
||||
for request_id, block_hashes in self._finished_requests.items()
|
||||
if block_hashes is not None
|
||||
)
|
||||
self._finished_requests = {}
|
||||
return AuxOutputConnectorMetadata(
|
||||
self._generation,
|
||||
scheduled_requests,
|
||||
block_hashes_by_request,
|
||||
finished_requests,
|
||||
)
|
||||
|
||||
def take_output(
|
||||
self,
|
||||
request: Request,
|
||||
output: dict[str, AuxRequestOutput] | None,
|
||||
) -> np.ndarray | None:
|
||||
"""Return the accepted R3 rows for one scheduled request."""
|
||||
request_id = request.request_id
|
||||
assert output is not None and request_id in output, (
|
||||
f"auxiliary output worker output is missing {request_id}"
|
||||
)
|
||||
request_output = output[request_id]
|
||||
token_end = request.num_tokens - 1
|
||||
local_end = token_end - request_output.token_start
|
||||
if local_end < 0:
|
||||
assert not request.is_finished(), (
|
||||
"finished auxiliary output output has no accepted token range: "
|
||||
f"request={request_id}, token_end={token_end}, "
|
||||
f"output_start={request_output.token_start}, "
|
||||
"output_end="
|
||||
f"{request_output.token_start + len(request_output.rows)}"
|
||||
)
|
||||
return None
|
||||
assert local_end <= len(request_output.rows), (
|
||||
"auxiliary output worker output has an invalid token range: "
|
||||
f"request={request_id}, token_end={token_end}, "
|
||||
f"output_start={request_output.token_start}, "
|
||||
f"output_end={request_output.token_start + len(request_output.rows)}"
|
||||
)
|
||||
return request_output.rows[:local_end]
|
||||
|
||||
def request_finished(self, request: Request) -> None:
|
||||
"""Queue a request's terminal event and final block hashes."""
|
||||
request_id = request.request_id
|
||||
num_sent = self._sent_hash_counts.pop(request_id, None)
|
||||
if num_sent is None:
|
||||
return
|
||||
# The next metadata delivers this terminal event to the worker.
|
||||
self._finished_requests[request_id] = self._pack_new_hashes(
|
||||
request.block_hashes, num_sent
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _pack_new_hashes(
|
||||
block_hashes: Sequence[bytes], num_sent: int
|
||||
) -> PackedBlockHashes | None:
|
||||
assert num_sent <= len(block_hashes), "KV block-hash history shrank"
|
||||
new_hashes = block_hashes[num_sent:]
|
||||
if not new_hashes:
|
||||
return None
|
||||
return PackedBlockHashes(b"".join(new_hashes), len(new_hashes[0]))
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Start a new auxiliary output namespace after a prefix-cache reset."""
|
||||
# The worker drops temporary state on generation changes; resend hashes.
|
||||
self._sent_hash_counts.clear()
|
||||
self._finished_requests.clear()
|
||||
self._generation += 1
|
||||
@@ -0,0 +1,219 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Routed-experts auxiliary output keys, publication, and materialization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Hashable, Iterable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.distributed.aux_output_connector.store import (
|
||||
BackgroundBlockObjectStore,
|
||||
BlockObject,
|
||||
BlockObjectStore,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RequestTail:
|
||||
slot: int
|
||||
block_start: int
|
||||
length: int = 0
|
||||
|
||||
|
||||
class RoutedExpertsBuffer:
|
||||
"""Own incomplete and unkeyed full routed-experts blocks."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dtype: np.dtype[Any],
|
||||
shape_per_token: tuple[int, ...],
|
||||
block_size: int,
|
||||
max_num_seqs: int,
|
||||
max_num_batched_tokens: int,
|
||||
max_concurrent_batches: int,
|
||||
) -> None:
|
||||
self.dtype = dtype
|
||||
self.shape_per_token = shape_per_token
|
||||
self.block_size = block_size
|
||||
max_step_blocks = (
|
||||
max_num_batched_tokens + block_size - 1
|
||||
) // block_size + max_num_seqs
|
||||
# In-flight full blocks plus one incomplete tail per active request.
|
||||
max_blocks = max_concurrent_batches * max_step_blocks + max_num_seqs
|
||||
self._rows: np.ndarray = np.empty(
|
||||
(max_blocks, block_size, *shape_per_token), dtype=dtype
|
||||
)
|
||||
self._free_slots = list(range(len(self._rows) - 1, -1, -1))
|
||||
self._owned_slots: dict[int, int] = {}
|
||||
self._requests: dict[Hashable, _RequestTail] = {}
|
||||
|
||||
def _tail(self, request_id: Hashable, block_start: int) -> _RequestTail:
|
||||
tail = self._requests.get(request_id)
|
||||
if tail is not None:
|
||||
assert tail.block_start == block_start, (
|
||||
"auxiliary output capture skipped an incomplete block: "
|
||||
f"request={request_id}, expected={tail.block_start}, "
|
||||
f"actual={block_start}"
|
||||
)
|
||||
return tail
|
||||
assert self._free_slots, "auxiliary output block pool is exhausted"
|
||||
tail = _RequestTail(self._free_slots.pop(), block_start)
|
||||
self._requests[request_id] = tail
|
||||
return tail
|
||||
|
||||
def capture(
|
||||
self, request_id: Hashable, token_start: int, rows: np.ndarray
|
||||
) -> list[tuple[int, np.ndarray]]:
|
||||
"""Stage rows and return completed blocks without retaining them."""
|
||||
rows = np.asarray(rows)
|
||||
assert rows.shape[1:] == self.shape_per_token and rows.dtype == self.dtype, (
|
||||
"routed-experts capture profile changed"
|
||||
)
|
||||
if token_start < 0:
|
||||
raise ValueError("auxiliary output token start must be non-negative")
|
||||
|
||||
completed: list[tuple[int, np.ndarray]] = []
|
||||
offset = 0
|
||||
while offset < len(rows):
|
||||
position = token_start + offset
|
||||
block_start = position // self.block_size * self.block_size
|
||||
local_start = position - block_start
|
||||
|
||||
# Full aligned input blocks do not need tail staging.
|
||||
if (
|
||||
request_id not in self._requests
|
||||
and local_start == 0
|
||||
and len(rows) - offset >= self.block_size
|
||||
):
|
||||
completed.append((block_start, rows[offset : offset + self.block_size]))
|
||||
offset += self.block_size
|
||||
continue
|
||||
|
||||
tail = self._tail(request_id, block_start)
|
||||
assert local_start == tail.length, (
|
||||
"auxiliary output capture is not contiguous: "
|
||||
f"request={request_id}, expected={block_start + tail.length}, "
|
||||
f"actual={position}"
|
||||
)
|
||||
count = min(self.block_size - local_start, len(rows) - offset)
|
||||
if count == 1:
|
||||
self._rows[tail.slot, local_start] = rows[offset]
|
||||
else:
|
||||
self._rows[tail.slot, local_start : local_start + count] = rows[
|
||||
offset : offset + count
|
||||
]
|
||||
tail.length += count
|
||||
offset += count
|
||||
if tail.length == self.block_size:
|
||||
block = self._rows[tail.slot]
|
||||
del self._requests[request_id]
|
||||
self._owned_slots[id(block)] = tail.slot
|
||||
completed.append((block_start, block))
|
||||
|
||||
return completed
|
||||
|
||||
def read(
|
||||
self, request_id: Hashable, token_start: int, token_end: int
|
||||
) -> np.ndarray:
|
||||
tail = self._requests.get(request_id)
|
||||
assert tail is not None, (
|
||||
f"auxiliary output buffer is missing request {request_id}"
|
||||
)
|
||||
local_start = token_start - tail.block_start
|
||||
local_end = token_end - tail.block_start
|
||||
assert 0 <= local_start < local_end <= tail.length, (
|
||||
"auxiliary output range is unavailable: "
|
||||
f"request={request_id}, range=[{token_start}, {token_end}), "
|
||||
f"available=[{tail.block_start}, {tail.block_start + tail.length})"
|
||||
)
|
||||
return self._rows[tail.slot, local_start:local_end].copy()
|
||||
|
||||
def retain_block(self, rows: np.ndarray) -> np.ndarray:
|
||||
"""Retain one unkeyed block after the current capture call."""
|
||||
if id(rows) in self._owned_slots:
|
||||
return rows
|
||||
assert self._free_slots, "auxiliary output block pool is exhausted"
|
||||
slot = self._free_slots.pop()
|
||||
retained = self._rows[slot]
|
||||
retained[...] = rows
|
||||
self._owned_slots[id(retained)] = slot
|
||||
return retained
|
||||
|
||||
def release_block(self, rows: np.ndarray) -> None:
|
||||
slot = self._owned_slots.pop(id(rows), None)
|
||||
if slot is not None:
|
||||
self._free_slots.append(slot)
|
||||
|
||||
def discard(self, request_id: Hashable) -> None:
|
||||
tail = self._requests.pop(request_id, None)
|
||||
if tail is not None:
|
||||
self._free_slots.append(tail.slot)
|
||||
|
||||
def reset(self) -> None:
|
||||
self._requests.clear()
|
||||
self._owned_slots.clear()
|
||||
self._free_slots[:] = range(len(self._rows) - 1, -1, -1)
|
||||
|
||||
|
||||
def routed_experts_keys(
|
||||
block_hashes: Iterable[bytes], aux_output_namespace: str
|
||||
) -> list[str]:
|
||||
prefix = f"vllm-artifact/{aux_output_namespace}/"
|
||||
return [prefix + block_hash.hex() for block_hash in block_hashes]
|
||||
|
||||
|
||||
def materialize_routed_experts(
|
||||
store: BackgroundBlockObjectStore | BlockObjectStore,
|
||||
aux_output_keys: list[str],
|
||||
*,
|
||||
shape_per_token: tuple[int, ...],
|
||||
dtype: np.dtype[Any],
|
||||
) -> np.ndarray:
|
||||
if not aux_output_keys:
|
||||
raise ValueError("routed-experts auxiliary output key list must not be empty")
|
||||
payload = store.get_concatenated(aux_output_keys)
|
||||
return np.frombuffer(payload, dtype=dtype).reshape((-1, *shape_per_token))
|
||||
|
||||
|
||||
def publish_routed_experts(
|
||||
store: BackgroundBlockObjectStore | BlockObjectStore,
|
||||
*,
|
||||
batches: Sequence[tuple[Sequence[str], list[tuple[int, np.ndarray]]]],
|
||||
block_size: int,
|
||||
retain_keys: Sequence[str] = (),
|
||||
release_keys: Sequence[str] = (),
|
||||
) -> None:
|
||||
"""Publish immutable full R3 blocks."""
|
||||
objects = []
|
||||
for aux_output_keys, blocks in batches:
|
||||
for block_start, array in blocks:
|
||||
if block_start < 0 or block_start % block_size:
|
||||
raise ValueError(
|
||||
"auxiliary output block start is not hash-block aligned"
|
||||
)
|
||||
block_index = block_start // block_size
|
||||
if block_index >= len(aux_output_keys):
|
||||
raise ValueError(
|
||||
"auxiliary output block has no corresponding key: "
|
||||
f"start={block_start}, index={block_index}, "
|
||||
f"keys={len(aux_output_keys)}, block_size={block_size}"
|
||||
)
|
||||
if len(array) != block_size:
|
||||
raise ValueError(
|
||||
"auxiliary output block length does not match hash block size"
|
||||
)
|
||||
objects.append(
|
||||
BlockObject(
|
||||
key=aux_output_keys[block_index],
|
||||
payload=array.tobytes(order="C"),
|
||||
)
|
||||
)
|
||||
store.put(
|
||||
objects,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
@@ -0,0 +1,234 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""In-process auxiliary-output storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import mmap
|
||||
import queue
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BlockObject:
|
||||
"""One immutable auxiliary output object."""
|
||||
|
||||
key: str
|
||||
payload: bytes
|
||||
|
||||
|
||||
class BlockObjectStoreError(RuntimeError):
|
||||
"""AuxOutput storage or retrieval failed."""
|
||||
|
||||
|
||||
class BackgroundBlockObjectStore:
|
||||
"""Serialize store mutations on a background thread."""
|
||||
|
||||
def __init__(self, store: BlockObjectStore, *, max_pending_batches: int) -> None:
|
||||
self._store = store
|
||||
self._queue: queue.Queue[
|
||||
tuple[list[BlockObject], tuple[str, ...], tuple[str, ...]] | None
|
||||
] = queue.Queue(maxsize=max_pending_batches)
|
||||
self._error: BaseException | None = None
|
||||
self._closed = False
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
daemon=True,
|
||||
name="vllm-aux-output-writer",
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
update = self._queue.get()
|
||||
try:
|
||||
if update is None:
|
||||
return
|
||||
if self._error is None:
|
||||
objects, retain_keys, release_keys = update
|
||||
self._store.put(
|
||||
objects,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
except BaseException as error:
|
||||
self._error = error
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
def _raise_if_failed(self) -> None:
|
||||
if self._error is not None:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output publication failed"
|
||||
) from self._error
|
||||
|
||||
def put(
|
||||
self,
|
||||
objects: list[BlockObject],
|
||||
*,
|
||||
retain_keys: Iterable[str] = (),
|
||||
release_keys: Iterable[str] = (),
|
||||
) -> None:
|
||||
retains = tuple(retain_keys)
|
||||
releases = tuple(release_keys)
|
||||
if not objects and not retains and not releases:
|
||||
return
|
||||
if self._closed:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
self._queue.put((objects, retains, releases))
|
||||
self._raise_if_failed()
|
||||
|
||||
def get_concatenated(self, keys: list[str]) -> bytes:
|
||||
self._queue.join()
|
||||
self._raise_if_failed()
|
||||
return self._store.get_concatenated(keys)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._queue.join()
|
||||
self._queue.put(None)
|
||||
self._thread.join()
|
||||
self._store.close()
|
||||
self._raise_if_failed()
|
||||
|
||||
|
||||
class BlockObjectStore:
|
||||
"""Single-owner bounded store that fails closed after an eviction."""
|
||||
|
||||
_UNALLOCATED_SLOT = -1
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
max_bytes: int,
|
||||
object_nbytes: int,
|
||||
) -> None:
|
||||
if object_nbytes <= 0:
|
||||
raise ValueError("auxiliary output object size must be positive")
|
||||
if max_bytes < object_nbytes:
|
||||
raise ValueError("auxiliary output store must fit at least one object")
|
||||
self.object_nbytes = object_nbytes
|
||||
self.num_slots = max_bytes // object_nbytes
|
||||
self._lru: OrderedDict[str, int] = OrderedDict()
|
||||
self._references: dict[str, int] = {}
|
||||
self._free_slots: list[int] = []
|
||||
self._next_slot = 0
|
||||
self._arena: mmap.mmap | None = mmap.mmap(
|
||||
-1, self.num_slots * self.object_nbytes
|
||||
)
|
||||
|
||||
def _evict_to_fit(self, protected: set[str]) -> None:
|
||||
excess = len(self._lru) - self.num_slots
|
||||
if excess <= 0:
|
||||
return
|
||||
victims = []
|
||||
for key in self._lru:
|
||||
if key not in self._references and key not in protected:
|
||||
victims.append(key)
|
||||
if len(victims) == excess:
|
||||
break
|
||||
if len(victims) != excess:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output store cannot retain the requested batch: "
|
||||
f"limit={self.num_slots} objects"
|
||||
)
|
||||
for victim in victims:
|
||||
slot = self._lru.pop(victim)
|
||||
if slot != self._UNALLOCATED_SLOT:
|
||||
self._free_slots.append(slot)
|
||||
|
||||
def _allocate_slot(self) -> int:
|
||||
if self._free_slots:
|
||||
return self._free_slots.pop()
|
||||
slot = self._next_slot
|
||||
self._next_slot += 1
|
||||
return slot
|
||||
|
||||
def put(
|
||||
self,
|
||||
objects: list[BlockObject],
|
||||
*,
|
||||
retain_keys: Iterable[str] = (),
|
||||
release_keys: Iterable[str] = (),
|
||||
) -> None:
|
||||
arena = self._arena
|
||||
if arena is None:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
unique = {obj.key: obj for obj in objects}
|
||||
self._retain(retain_keys)
|
||||
terminal_order = self._release(release_keys)
|
||||
for key in unique:
|
||||
self._lru.setdefault(key, self._UNALLOCATED_SLOT)
|
||||
self._lru.move_to_end(key)
|
||||
for key in terminal_order:
|
||||
if key in self._lru:
|
||||
self._lru.move_to_end(key)
|
||||
try:
|
||||
self._evict_to_fit(set(unique) - set(terminal_order))
|
||||
except BlockObjectStoreError:
|
||||
for key in unique:
|
||||
if self._lru.get(key) == self._UNALLOCATED_SLOT:
|
||||
del self._lru[key]
|
||||
raise
|
||||
for object_id, obj in unique.items():
|
||||
slot = self._lru.get(object_id)
|
||||
if slot is None:
|
||||
continue
|
||||
if slot != self._UNALLOCATED_SLOT:
|
||||
continue
|
||||
slot = self._allocate_slot()
|
||||
offset = slot * self.object_nbytes
|
||||
arena[offset : offset + self.object_nbytes] = obj.payload
|
||||
self._lru[object_id] = slot
|
||||
|
||||
def _retain(self, keys: Iterable[str]) -> None:
|
||||
for key in keys:
|
||||
references = self._references.get(key, 0)
|
||||
self._references[key] = references + 1
|
||||
|
||||
def _release(self, keys: Iterable[str]) -> list[str]:
|
||||
terminal_order = []
|
||||
for key in keys:
|
||||
references = self._references[key] - 1
|
||||
if references:
|
||||
self._references[key] = references
|
||||
continue
|
||||
del self._references[key]
|
||||
terminal_order.append(key)
|
||||
return terminal_order
|
||||
|
||||
def get_concatenated(self, keys: list[str]) -> bytes:
|
||||
arena_obj = self._arena
|
||||
if arena_obj is None:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
try:
|
||||
entries = [self._lru[key] for key in keys]
|
||||
except KeyError as error:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output object does not exist; the object may have been "
|
||||
f"evicted (used={len(self._lru)}, "
|
||||
f"limit={self.num_slots} objects). Increase "
|
||||
"aux_output_config.max_bytes when a KV cache hit requires it."
|
||||
) from error
|
||||
arena = memoryview(arena_obj)
|
||||
try:
|
||||
payload = b"".join(
|
||||
arena[slot * self.object_nbytes : (slot + 1) * self.object_nbytes]
|
||||
for slot in entries
|
||||
)
|
||||
finally:
|
||||
arena.release()
|
||||
for key in keys:
|
||||
self._lru.move_to_end(key)
|
||||
return payload
|
||||
|
||||
def close(self) -> None:
|
||||
arena = self._arena
|
||||
if arena is not None:
|
||||
self._arena = None
|
||||
arena.close()
|
||||
@@ -0,0 +1,412 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Worker-side auxiliary-output data plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.aux_output_connector.connector import (
|
||||
AuxOutputConnectorMetadata,
|
||||
AuxRequestOutput,
|
||||
)
|
||||
from vllm.distributed.aux_output_connector.routed_experts import (
|
||||
RoutedExpertsBuffer,
|
||||
materialize_routed_experts,
|
||||
publish_routed_experts,
|
||||
routed_experts_keys,
|
||||
)
|
||||
from vllm.distributed.aux_output_connector.store import (
|
||||
BackgroundBlockObjectStore,
|
||||
BlockObjectStore,
|
||||
)
|
||||
from vllm.distributed.parallel_state import get_tp_group
|
||||
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
|
||||
RoutedExpertsCapturer,
|
||||
bind_routed_experts_capturer,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import resolve_kv_cache_block_sizes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WorkerRequestState:
|
||||
aux_output_keys: list[str] = field(default_factory=list)
|
||||
pending_blocks: list[tuple[int, np.ndarray]] = field(default_factory=list)
|
||||
capture_cursor: int | None = None
|
||||
scheduled_cursor: int = 0
|
||||
emit_cursor: int = 0
|
||||
pending_outputs: int = 0
|
||||
# Terminal event received; teardown waits for in-flight step outputs.
|
||||
finished: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class PendingAuxOutput:
|
||||
"""Own one step's R3 snapshot until its asynchronous copy is consumed."""
|
||||
|
||||
connector: AuxOutputWorkerConnector
|
||||
request_ids: list[str]
|
||||
token_starts: np.ndarray
|
||||
query_start_loc: np.ndarray
|
||||
# GPU snapshot taken on the main stream.
|
||||
routed_experts_gpu: torch.Tensor
|
||||
# Filled by enqueue_cpu_copy on the output copy stream.
|
||||
routed_experts: np.ndarray | None = None
|
||||
num_sampled: np.ndarray | None = None
|
||||
num_rejected: np.ndarray | None = None
|
||||
|
||||
def enqueue_cpu_copy(
|
||||
self, num_sampled: np.ndarray, num_rejected: np.ndarray
|
||||
) -> None:
|
||||
"""Enqueue asynchronous D2H copies; call on the output copy stream."""
|
||||
self.num_sampled = num_sampled
|
||||
self.num_rejected = num_rejected
|
||||
self.routed_experts = self.routed_experts_gpu.to(
|
||||
"cpu", non_blocking=True
|
||||
).numpy()
|
||||
|
||||
def process_output(self) -> dict[str, AuxRequestOutput]:
|
||||
return self.connector.process_output(self)
|
||||
|
||||
|
||||
class AuxOutputWorkerConnector:
|
||||
"""Own capture, request tails, and backend resources on the output worker."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
model: torch.nn.Module,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
) -> None:
|
||||
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
capturer = RoutedExpertsCapturer(
|
||||
max_num_batched_tokens=max_num_batched_tokens, vllm_config=vllm_config
|
||||
)
|
||||
bind_routed_experts_capturer(model, capturer)
|
||||
self._capturer = capturer
|
||||
self._store: BackgroundBlockObjectStore | None = None
|
||||
self._buffer: RoutedExpertsBuffer | None = None
|
||||
self._requests: dict[str, _WorkerRequestState] = {}
|
||||
self._generation = 0
|
||||
self._step_metadata: AuxOutputConnectorMetadata | None = None
|
||||
# Steps whose asynchronous copy has not been consumed yet. The engine
|
||||
# consumes step outputs in order, so at most max_concurrent_batches
|
||||
# are outstanding; guarded by _lock against the output thread.
|
||||
self._pending_outputs: list[PendingAuxOutput] = []
|
||||
self._lock = Lock()
|
||||
self._max_concurrent_batches = vllm_config.max_concurrent_batches
|
||||
# Every TP rank participates in capture collectives, but only the
|
||||
# executor output rank owns the auxiliary output data plane.
|
||||
if not get_tp_group().is_first_rank:
|
||||
return
|
||||
|
||||
shape_per_token = self._capturer.shape_per_token
|
||||
dtype: np.dtype[Any] = np.dtype(self._capturer.output_dtype_name)
|
||||
scheduler_block_size, hash_block_size = resolve_kv_cache_block_sizes(
|
||||
kv_cache_config, vllm_config
|
||||
)
|
||||
hashes_per_kv_block = scheduler_block_size // hash_block_size
|
||||
block_nbytes = hash_block_size * int(np.prod(shape_per_token)) * dtype.itemsize
|
||||
max_bytes = vllm_config.aux_output_config.max_bytes
|
||||
if max_bytes is None:
|
||||
max_bytes = kv_cache_config.num_blocks * hashes_per_kv_block * block_nbytes
|
||||
self._store = BackgroundBlockObjectStore(
|
||||
BlockObjectStore(max_bytes=max_bytes, object_nbytes=block_nbytes),
|
||||
max_pending_batches=2 * vllm_config.scheduler_config.max_num_seqs,
|
||||
)
|
||||
self._buffer = RoutedExpertsBuffer(
|
||||
dtype,
|
||||
shape_per_token,
|
||||
hash_block_size,
|
||||
vllm_config.scheduler_config.max_num_seqs,
|
||||
max_num_batched_tokens,
|
||||
vllm_config.max_concurrent_batches,
|
||||
)
|
||||
|
||||
def prepare_output(self, input_batch: InputBatch) -> PendingAuxOutput | None:
|
||||
"""Snapshot one step's R3 tensor for asynchronous CPU transfer."""
|
||||
if self._buffer is None or self._step_metadata is None:
|
||||
return None
|
||||
|
||||
request_ids = list(input_batch.req_ids)
|
||||
query_start_loc = input_batch.query_start_loc_np[: len(request_ids) + 1]
|
||||
num_rows = int(query_start_loc[-1])
|
||||
pending_output = PendingAuxOutput(
|
||||
connector=self,
|
||||
request_ids=request_ids,
|
||||
token_starts=input_batch.num_computed_tokens_np,
|
||||
query_start_loc=query_start_loc,
|
||||
routed_experts_gpu=self._capturer.snapshot_routing_data(num_rows),
|
||||
)
|
||||
with self._lock:
|
||||
assert len(self._pending_outputs) < self._max_concurrent_batches, (
|
||||
"auxiliary output step outputs are not consumed in order"
|
||||
)
|
||||
self._pending_outputs.append(pending_output)
|
||||
for request_id in pending_output.request_ids:
|
||||
self._requests[request_id].pending_outputs += 1
|
||||
return pending_output
|
||||
|
||||
def process_output(self, pending: PendingAuxOutput) -> dict[str, AuxRequestOutput]:
|
||||
"""Commit one consumed R3 snapshot and build request outputs.
|
||||
|
||||
Request teardown deferred by begin_step is completed here once no
|
||||
in-flight step covers the request.
|
||||
"""
|
||||
with self._lock:
|
||||
teardown = []
|
||||
release_keys: list[str] = []
|
||||
try:
|
||||
outputs = self._commit_output(pending)
|
||||
finally:
|
||||
self._pending_outputs.remove(pending)
|
||||
for request_id in pending.request_ids:
|
||||
state = self._requests[request_id]
|
||||
state.pending_outputs -= 1
|
||||
if state.pending_outputs == 0 and state.finished:
|
||||
teardown.append(request_id)
|
||||
release_keys.extend(reversed(state.aux_output_keys))
|
||||
if teardown:
|
||||
self._publish_blocks([], release_keys=release_keys)
|
||||
self._teardown(teardown)
|
||||
return outputs
|
||||
|
||||
def _commit_output(self, pending: PendingAuxOutput) -> dict[str, AuxRequestOutput]:
|
||||
buffer = self._buffer
|
||||
store = self._store
|
||||
assert buffer is not None and store is not None
|
||||
block_size = buffer.block_size
|
||||
|
||||
routed_experts = pending.routed_experts
|
||||
num_sampled = pending.num_sampled
|
||||
num_rejected = pending.num_rejected
|
||||
assert (
|
||||
routed_experts is not None
|
||||
and num_sampled is not None
|
||||
and num_rejected is not None
|
||||
), "auxiliary output CPU copy was not enqueued"
|
||||
|
||||
# Publish the whole batch before materializing any consumer output.
|
||||
materialize_outputs: list[tuple[str, int, int]] = []
|
||||
block_batches = []
|
||||
outputs: dict[str, AuxRequestOutput] = {}
|
||||
|
||||
# Use the ModelRunner's actual batch boundaries rather than rebuilding them.
|
||||
for request_id, token_start, start, end, sampled, rejected in zip(
|
||||
pending.request_ids,
|
||||
pending.token_starts,
|
||||
pending.query_start_loc[:-1],
|
||||
pending.query_start_loc[1:],
|
||||
num_sampled,
|
||||
num_rejected,
|
||||
strict=True,
|
||||
):
|
||||
request_num_tokens = end - start
|
||||
assert request_num_tokens > 0, (
|
||||
"auxiliary output request token count must be positive"
|
||||
)
|
||||
state = self._requests[request_id]
|
||||
|
||||
# Capture precedes speculative acceptance, so discard the rejected
|
||||
# suffix. Batch boundaries still span the full executed range.
|
||||
rejected = int(rejected)
|
||||
assert 0 <= rejected <= request_num_tokens, (
|
||||
"auxiliary output rejected-token count is invalid"
|
||||
)
|
||||
rows = routed_experts[start : end - rejected]
|
||||
|
||||
capture_start = token_start
|
||||
capture_cursor = state.capture_cursor
|
||||
if capture_cursor is None:
|
||||
capture_cursor = capture_start
|
||||
|
||||
assert capture_start >= capture_cursor, (
|
||||
"auxiliary output capture moved backwards"
|
||||
)
|
||||
if capture_start > capture_cursor:
|
||||
# Reattach after an optimistically scheduled suffix was rejected.
|
||||
assert capture_cursor < state.scheduled_cursor, (
|
||||
"auxiliary output capture has an unbacked token gap"
|
||||
)
|
||||
capture_start = capture_cursor
|
||||
|
||||
emit_start = state.emit_cursor
|
||||
# Complete blocks without keys remain pending until a hash update.
|
||||
completed = buffer.capture(request_id, capture_start, rows)
|
||||
token_end = capture_start + len(rows)
|
||||
state.capture_cursor = token_end
|
||||
state.scheduled_cursor = token_start + request_num_tokens
|
||||
block_batches.append((state, completed))
|
||||
|
||||
if sampled > 0 and emit_start <= token_end:
|
||||
if emit_start >= capture_start:
|
||||
outputs[request_id] = AuxRequestOutput(
|
||||
emit_start, rows[emit_start - capture_start :]
|
||||
)
|
||||
state.emit_cursor = token_end
|
||||
else:
|
||||
materialize_outputs.append((request_id, emit_start, token_end))
|
||||
|
||||
# A consumer may reuse a block produced earlier in the same batch.
|
||||
self._publish_blocks(block_batches)
|
||||
|
||||
for request_id, emit_start, token_end in materialize_outputs:
|
||||
state = self._requests[request_id]
|
||||
stored_end = (
|
||||
min(token_end // block_size, len(state.aux_output_keys)) * block_size
|
||||
)
|
||||
if emit_start < stored_end:
|
||||
first_block = emit_start // block_size
|
||||
stored = materialize_routed_experts(
|
||||
store,
|
||||
state.aux_output_keys[first_block : stored_end // block_size],
|
||||
shape_per_token=buffer.shape_per_token,
|
||||
dtype=buffer.dtype,
|
||||
)
|
||||
local_start = emit_start % block_size
|
||||
rows = stored[local_start : local_start + stored_end - emit_start]
|
||||
if stored_end < token_end:
|
||||
rows = np.concatenate(
|
||||
(rows, buffer.read(request_id, stored_end, token_end))
|
||||
)
|
||||
else:
|
||||
rows = buffer.read(request_id, emit_start, token_end)
|
||||
outputs[request_id] = AuxRequestOutput(emit_start, rows)
|
||||
state.emit_cursor = token_end
|
||||
return outputs
|
||||
|
||||
def _publish_blocks(
|
||||
self,
|
||||
batches: list[tuple[_WorkerRequestState, list[tuple[int, np.ndarray]]]],
|
||||
retain_keys: Sequence[str] = (),
|
||||
release_keys: Sequence[str] = (),
|
||||
) -> None:
|
||||
store = self._store
|
||||
buffer = self._buffer
|
||||
assert store is not None and buffer is not None
|
||||
ready_batches = []
|
||||
for state, completed in batches:
|
||||
blocks = state.pending_blocks + completed
|
||||
keyed_end = len(state.aux_output_keys) * buffer.block_size
|
||||
ready = [(start, rows) for start, rows in blocks if start < keyed_end]
|
||||
state.pending_blocks = [
|
||||
(start, buffer.retain_block(rows))
|
||||
for start, rows in blocks
|
||||
if start >= keyed_end
|
||||
]
|
||||
if ready:
|
||||
ready_batches.append((state.aux_output_keys, ready))
|
||||
if ready_batches or retain_keys or release_keys:
|
||||
publish_routed_experts(
|
||||
store,
|
||||
batches=ready_batches,
|
||||
block_size=buffer.block_size,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
for _, blocks in ready_batches:
|
||||
for _, rows in blocks:
|
||||
buffer.release_block(rows)
|
||||
|
||||
def _teardown(self, request_ids: Iterable[str]) -> None:
|
||||
"""Drop finished requests' temporary state after publishing key releases."""
|
||||
buffer = self._buffer
|
||||
assert buffer is not None
|
||||
for request_id in request_ids:
|
||||
state = self._requests.pop(request_id)
|
||||
for _, rows in state.pending_blocks:
|
||||
buffer.release_block(rows)
|
||||
buffer.discard(request_id)
|
||||
|
||||
def begin_step(self, metadata: AuxOutputConnectorMetadata | None) -> None:
|
||||
"""Apply one scheduler step's request and block-hash updates.
|
||||
|
||||
While an unconsumed step covers a finished request, its teardown is
|
||||
deferred to that step's process_output.
|
||||
"""
|
||||
self._step_metadata = metadata
|
||||
if self._buffer is None or metadata is None:
|
||||
return
|
||||
assert not metadata.requests.keys() & metadata.finished_requests, (
|
||||
"auxiliary output request cannot run and finish in one step"
|
||||
)
|
||||
assert metadata.generation >= self._generation, (
|
||||
"auxiliary output metadata generation moved backwards"
|
||||
)
|
||||
with self._lock:
|
||||
release_keys: list[str] = []
|
||||
if metadata.generation > self._generation:
|
||||
# A generation change follows a prefix-cache reset, which the
|
||||
# scheduler only performs once all model output is consumed.
|
||||
assert not self._pending_outputs, (
|
||||
"auxiliary output generation changed with output in flight"
|
||||
)
|
||||
release_keys.extend(
|
||||
key
|
||||
for state in self._requests.values()
|
||||
for key in reversed(state.aux_output_keys)
|
||||
)
|
||||
self._buffer.reset()
|
||||
self._requests.clear()
|
||||
self._generation = metadata.generation
|
||||
for request_id, emit_start in metadata.requests.items():
|
||||
state = self._requests.setdefault(
|
||||
request_id, _WorkerRequestState(emit_cursor=emit_start)
|
||||
)
|
||||
if state.pending_outputs == 0:
|
||||
# In-flight steps leave the worker cursor behind the
|
||||
# scheduler's optimistic view; only check settled requests.
|
||||
assert emit_start <= state.emit_cursor, (
|
||||
"auxiliary output Scheduler emit cursor moved ahead"
|
||||
)
|
||||
block_batches: list[
|
||||
tuple[_WorkerRequestState, list[tuple[int, np.ndarray]]]
|
||||
] = []
|
||||
retained_keys: list[str] = []
|
||||
for request_id, block_hashes in metadata.block_hashes.items():
|
||||
state = self._requests[request_id]
|
||||
keys = routed_experts_keys(block_hashes, str(self._generation))
|
||||
state.aux_output_keys.extend(keys)
|
||||
retained_keys.extend(keys)
|
||||
block_batches.append((state, []))
|
||||
finished_now: list[str] = []
|
||||
for request_id in metadata.finished_requests:
|
||||
state = self._requests[request_id]
|
||||
state.finished = True
|
||||
if state.pending_outputs:
|
||||
continue
|
||||
finished_now.append(request_id)
|
||||
release_keys.extend(reversed(state.aux_output_keys))
|
||||
self._publish_blocks(block_batches, retained_keys, release_keys)
|
||||
self._teardown(finished_now)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._pending_outputs.clear()
|
||||
if self._store is not None:
|
||||
try:
|
||||
self._store.close()
|
||||
finally:
|
||||
self._store = None
|
||||
|
||||
|
||||
def get_aux_output_connector(
|
||||
model: torch.nn.Module, vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
) -> AuxOutputWorkerConnector:
|
||||
return AuxOutputWorkerConnector(
|
||||
model=model,
|
||||
kv_cache_config=kv_cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
@@ -6,6 +6,7 @@ import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .base_device_communicator import DeviceCommunicatorBase
|
||||
@@ -45,7 +46,25 @@ class XpuCommunicator(DeviceCommunicatorBase):
|
||||
self.all2all_manager = AgRsAll2AllManager(self.cpu_group)
|
||||
logger.info("Using AgRs manager on XPU device.")
|
||||
|
||||
def _fixed_rank_sum(self, input_: torch.Tensor) -> torch.Tensor:
|
||||
flat_input = input_.reshape(-1)
|
||||
gathered = torch.empty(
|
||||
(self.world_size, flat_input.numel()),
|
||||
dtype=input_.dtype,
|
||||
device=input_.device,
|
||||
)
|
||||
dist.all_gather_single(gathered.view(-1), flat_input, group=self.device_group)
|
||||
output = gathered[0].clone()
|
||||
for rank in range(1, self.world_size):
|
||||
output.add_(gathered[rank])
|
||||
return output.view(input_.shape)
|
||||
|
||||
def all_reduce(self, input_: torch.Tensor) -> torch.Tensor:
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
# XCCL changes its reduction order with message size. Gather first
|
||||
# and accumulate in rank order, independent of the token batch.
|
||||
return self._fixed_rank_sum(input_)
|
||||
|
||||
output = input_.clone()
|
||||
dist.all_reduce(output, group=self.device_group)
|
||||
return output
|
||||
@@ -69,7 +88,12 @@ class XpuCommunicator(DeviceCommunicatorBase):
|
||||
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
|
||||
)
|
||||
|
||||
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
reduced = self._fixed_rank_sum(input_tensor)
|
||||
start = self.rank_in_group * chunk_size
|
||||
output.copy_(reduced.narrow(0, start, chunk_size))
|
||||
else:
|
||||
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
|
||||
|
||||
# Reshape before returning
|
||||
return output.movedim(0, dim).contiguous()
|
||||
@@ -99,12 +123,32 @@ class XpuCommunicator(DeviceCommunicatorBase):
|
||||
output = torch.empty(
|
||||
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
|
||||
)
|
||||
if sizes is not None and sizes.count(sizes[0]) != len(sizes):
|
||||
# if inputs shape in different ranks is not the same using reduce_scatter
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
reduced = self._fixed_rank_sum(input_tensor)
|
||||
start = (
|
||||
self.rank_in_group * chunk_size
|
||||
if sizes is None
|
||||
else sum(sizes[: self.rank_in_group])
|
||||
)
|
||||
output.copy_(reduced.narrow(0, start, chunk_size))
|
||||
elif sizes is None or sizes.count(sizes[0]) == len(sizes):
|
||||
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
|
||||
elif torch.xpu.device_count() < self.world_size:
|
||||
# uneven reduce_scatter is not supported when the
|
||||
# process cannot see every device in the group (
|
||||
# e.g. external-LBDP).
|
||||
max_size = max(sizes)
|
||||
padded = input_tensor.new_zeros(
|
||||
(world_size * max_size,) + input_tensor.shape[1:]
|
||||
)
|
||||
for rank, split in enumerate(input_tensor.split(sizes, dim=0)):
|
||||
padded[rank * max_size : rank * max_size + sizes[rank]] = split
|
||||
padded_output = input_tensor.new_empty((max_size,) + input_tensor.shape[1:])
|
||||
dist.reduce_scatter_tensor(padded_output, padded, group=self.device_group)
|
||||
output = padded_output[:chunk_size]
|
||||
else:
|
||||
input_splits = list(input_tensor.split(sizes, dim=0))
|
||||
dist.reduce_scatter(output, input_splits, group=self.device_group)
|
||||
else:
|
||||
dist.reduce_scatter_tensor(output, input_tensor, group=self.device_group)
|
||||
# Reshape before returning
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
@@ -179,7 +223,7 @@ class XpuCommunicator(DeviceCommunicatorBase):
|
||||
(self.world_size,) + input_size, dtype=input_.dtype, device=input_.device
|
||||
)
|
||||
# All-gather.
|
||||
dist.all_gather_into_tensor(output_tensor, input_, group=self.device_group)
|
||||
dist.all_gather_single(output_tensor, input_, group=self.device_group)
|
||||
if self.rank_in_group == dst:
|
||||
# Reshape
|
||||
output_tensor = output_tensor.movedim(0, dim)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
@@ -45,6 +46,13 @@ TransferId = str
|
||||
TransferOffsetsKey = tuple[str, tuple[int, ...], tuple[int, ...], torch.dtype]
|
||||
|
||||
|
||||
def _positive_finite_timeout(name: str, value: Any) -> float:
|
||||
timeout = float(value)
|
||||
if not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError(f"{name} must be finite and greater than zero")
|
||||
return timeout
|
||||
|
||||
|
||||
class MoRIIOTransferAck(NamedTuple):
|
||||
transfer_id: TransferId
|
||||
consumer_tp_size: int = 1
|
||||
@@ -160,6 +168,20 @@ class MoRIIOMode(Enum):
|
||||
WRITE = "write"
|
||||
|
||||
|
||||
class TransferBatchState(Enum):
|
||||
"""Verdict for a group of transfer statuses that belong to one request.
|
||||
|
||||
A request's KV transfer is spread over one status per layer (two for a KDA
|
||||
layer), so a single status never decides the request: PENDING means at
|
||||
least one is still in flight and none has failed, FAILED means at least
|
||||
one failed, DONE means all succeeded.
|
||||
"""
|
||||
|
||||
DONE = "done"
|
||||
FAILED = "failed"
|
||||
PENDING = "pending"
|
||||
|
||||
|
||||
class MoRIIOError(Exception):
|
||||
"""Base exception for MoRIIO operations."""
|
||||
|
||||
@@ -260,6 +282,7 @@ class MoRIIOConfig:
|
||||
tp_size: int
|
||||
transfer_timeout: float
|
||||
defer_timeout: float
|
||||
recv_abort_timeout: float
|
||||
read_mode: bool = False
|
||||
qp_per_transfer: int = 1
|
||||
post_batch_size: int = -1
|
||||
@@ -284,6 +307,8 @@ class MoRIIOConfig:
|
||||
# raising TransferError (sec).
|
||||
# defer_timeout -> Timeout before a deferred send with no finished_sending
|
||||
# notification is reaped and its blocks force-freed (sec).
|
||||
# recv_abort_timeout -> Timeout before an in-flight recv whose RDMA
|
||||
# completion never arrived is aborted (sec).
|
||||
|
||||
# Knobs for RDMA transfers, ignored if on xgmi backend
|
||||
# qp_per_transfer -> Number of RDMA Queue Pairs per KV transfer.
|
||||
@@ -315,13 +340,29 @@ class MoRIIOConfig:
|
||||
"must be one of 'rdma' or 'xgmi'."
|
||||
)
|
||||
|
||||
transfer_timeout = float(
|
||||
transfer_timeout = _positive_finite_timeout(
|
||||
"kv_connector_extra_config.transfer_timeout",
|
||||
extra_config.get(
|
||||
"transfer_timeout", MoRIIOConstants.DEFAULT_TRANSFER_TIMEOUT
|
||||
)
|
||||
),
|
||||
)
|
||||
defer_timeout = float(
|
||||
extra_config.get("defer_timeout", MoRIIOConstants.DEFAULT_DEFER_TIMEOUT)
|
||||
defer_timeout = _positive_finite_timeout(
|
||||
"kv_connector_extra_config.defer_timeout",
|
||||
extra_config.get("defer_timeout", MoRIIOConstants.DEFAULT_DEFER_TIMEOUT),
|
||||
)
|
||||
legacy_recv_abort_timeout = os.environ.get("VLLM_MORIIO_TRANSFER_TIMEOUT_S")
|
||||
if legacy_recv_abort_timeout is not None:
|
||||
logger.warning_once(
|
||||
"The environment variable VLLM_MORIIO_TRANSFER_TIMEOUT_S is "
|
||||
"deprecated. Set 'recv_abort_timeout' inside "
|
||||
"kv_transfer_config.kv_connector_extra_config instead."
|
||||
)
|
||||
recv_abort_timeout = _positive_finite_timeout(
|
||||
"kv_connector_extra_config.recv_abort_timeout",
|
||||
extra_config.get(
|
||||
"recv_abort_timeout",
|
||||
legacy_recv_abort_timeout or MoRIIOConstants.DEFAULT_RECV_ABORT_TIMEOUT,
|
||||
),
|
||||
)
|
||||
|
||||
return cls(
|
||||
@@ -347,6 +388,7 @@ class MoRIIOConfig:
|
||||
backend=backend,
|
||||
transfer_timeout=transfer_timeout,
|
||||
defer_timeout=defer_timeout,
|
||||
recv_abort_timeout=recv_abort_timeout,
|
||||
)
|
||||
|
||||
|
||||
@@ -374,6 +416,10 @@ class MoRIIOConstants:
|
||||
# notification is reaped and its blocks force-freed.
|
||||
# Overridable via kv_connector_extra_config["defer_timeout"].
|
||||
DEFAULT_DEFER_TIMEOUT = 60.0
|
||||
# Timeout (seconds) before an in-flight recv whose RDMA completion was lost
|
||||
# is aborted, so the decode worker does not hang on it forever.
|
||||
# Overridable via kv_connector_extra_config["recv_abort_timeout"].
|
||||
DEFAULT_RECV_ABORT_TIMEOUT = 120.0
|
||||
|
||||
|
||||
# The router embeds both zmq_addresses in the request_id:
|
||||
@@ -567,9 +613,12 @@ class MoRIIOConnectorMetadata(KVConnectorMetadata):
|
||||
remote_handshake_port=int(remote_handshake_port),
|
||||
remote_notify_port=int(remote_notify_port),
|
||||
# Remote peer TP degree (used as remote_tp_size downstream). The
|
||||
# proxy advertises it under "remote_tp_size"; #46332 read "tp_size"
|
||||
# which is absent on WRITE producer requests -> defaulted to 1 ->
|
||||
# rank collapse. Read the right key; 0 == unknown (== homogeneous).
|
||||
# decode side must know the prefiller's TP degree to map producer
|
||||
# ranks onto the correct decode rank (and vice versa). The old plain
|
||||
# "tp_size" key (#46332) is absent on WRITE producer requests and
|
||||
# defaulted to 1, collapsing every producer rank onto decode rank 0
|
||||
# and corrupting the transfer; prefer "remote_tp_size". 0 == unknown
|
||||
# (treated as homogeneous downstream).
|
||||
tp_size=int(
|
||||
kv_transfer_params.get("remote_tp_size")
|
||||
or kv_transfer_params.get("tp_size")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
MoRIIOError,
|
||||
MoRIIOTransferAck,
|
||||
RemoteAllocInfo,
|
||||
TransferBatchState,
|
||||
TransferError,
|
||||
TransferId,
|
||||
WriteTask,
|
||||
@@ -58,7 +59,6 @@ try:
|
||||
except ImportError:
|
||||
logger.error("MoRIIO is not available")
|
||||
|
||||
|
||||
"""Write task execution logic for MoRIIO connector."""
|
||||
|
||||
|
||||
@@ -395,9 +395,9 @@ class MoRIIOWriter:
|
||||
)
|
||||
request_info.transfer_offsets[key] = offsets
|
||||
|
||||
# Get session index
|
||||
layer_names = list(self.worker.layer_name_to_local_kv_cache_metadata.keys())
|
||||
sess_idx = layer_names.index(task.layer_name)
|
||||
# One session per registered region; attention layers map to a single
|
||||
# index (see MoRIIOConnectorWorker._region_session_indices).
|
||||
sess_idx = self.worker._region_session_indices(task.layer_name)[0]
|
||||
|
||||
local_off, remote_off, sizes = offsets
|
||||
|
||||
@@ -662,6 +662,25 @@ class MoRIIOWrapper:
|
||||
)
|
||||
return transfer_status
|
||||
|
||||
def poll_transfer_batch(self, transfer_statuses: list[Any]) -> TransferBatchState:
|
||||
"""Non-blocking verdict over every status of one request.
|
||||
|
||||
Judging a request by its newest status alone calls it done while an
|
||||
earlier layer is unfinished or already failed; failures do land on
|
||||
layers other than the last, because _post_read_with_backoff returns a
|
||||
failed status when the send queue never drains.
|
||||
|
||||
This stays a Python scan so it does not drive the backend's progress
|
||||
callback from the engine thread alongside MoRIIO's own poller.
|
||||
"""
|
||||
state = TransferBatchState.DONE
|
||||
for status in transfer_statuses:
|
||||
if status.Failed():
|
||||
return TransferBatchState.FAILED
|
||||
if not status.Succeeded():
|
||||
state = TransferBatchState.PENDING
|
||||
return state
|
||||
|
||||
def waiting_for_transfer_complete(self, transfer_statuses: list[Any] | None = None):
|
||||
if transfer_statuses is None:
|
||||
with self.lock:
|
||||
@@ -673,6 +692,15 @@ class MoRIIOWrapper:
|
||||
if not transfers_to_wait:
|
||||
return
|
||||
|
||||
self._poll_transfers_until_done(transfers_to_wait)
|
||||
|
||||
def _poll_transfers_until_done(self, transfers_to_wait: list[Any]) -> None:
|
||||
"""Fallback for mori builds without the batched wait.
|
||||
|
||||
Gives failure precedence over pending: once any status has failed the
|
||||
request is lost, so waiting out the remaining ones would only delay the
|
||||
barrier by up to transfer_timeout.
|
||||
"""
|
||||
timeout = self._transfer_timeout
|
||||
deadline = time.monotonic() + timeout
|
||||
remaining = list(transfers_to_wait)
|
||||
@@ -698,6 +726,8 @@ class MoRIIOWrapper:
|
||||
)
|
||||
else:
|
||||
still_waiting.append(status)
|
||||
if errors:
|
||||
break
|
||||
remaining = still_waiting
|
||||
if remaining:
|
||||
time.sleep(0.001)
|
||||
|
||||
@@ -2,14 +2,18 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import NamedTuple
|
||||
from typing import NamedTuple, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.ssm_conv_transfer_utils import (
|
||||
MambaConvSplitInfo,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
@@ -29,6 +33,85 @@ class LayerTransferGeometry(NamedTuple):
|
||||
split_kv_regions: bool
|
||||
|
||||
|
||||
class MambaTransferGeometry(NamedTuple):
|
||||
"""Geometry of a hybrid (mamba/KDA) layer's recurrent state.
|
||||
|
||||
A KDA layer's packed page is exposed as ``conv_state`` and ``ssm_state``
|
||||
views. Each is slot-strided, so a slot's bytes live at
|
||||
``slot * slot_stride * element_size`` and span ``slot_bytes``. The two
|
||||
tensors are registered as two separate MoRIIO regions per layer.
|
||||
"""
|
||||
|
||||
conv_slot_stride: int
|
||||
ssm_slot_stride: int
|
||||
ssm_slot_bytes: int
|
||||
conv_element_size: int
|
||||
ssm_element_size: int
|
||||
conv_region_len: int
|
||||
ssm_region_len: int
|
||||
|
||||
|
||||
def get_mamba_transfer_geometry(
|
||||
conv: torch.Tensor,
|
||||
ssm: torch.Tensor,
|
||||
) -> MambaTransferGeometry:
|
||||
"""Derive the slot-strided geometry of a KDA layer's conv + ssm state.
|
||||
|
||||
``conv``/``ssm`` are zero-copy views over the layer's packed page. Slot byte
|
||||
offset is ``slot * slot_stride * element_size`` and each
|
||||
slot spans ``subtensor[0].numel() * element_size`` bytes; the whole tensor
|
||||
is registered as one region (``*_region_len`` bytes).
|
||||
"""
|
||||
if conv.ndim == 0 or ssm.ndim == 0 or conv.shape[0] == 0 or ssm.shape[0] == 0:
|
||||
raise ValueError("KDA conv/ssm caches must contain at least one slot")
|
||||
if conv.shape[0] != ssm.shape[0]:
|
||||
raise ValueError(
|
||||
f"KDA conv/ssm slot count mismatch: {conv.shape[0]} != {ssm.shape[0]}"
|
||||
)
|
||||
conv_slot_bytes = conv[0].numel() * conv.element_size()
|
||||
ssm_slot_bytes = ssm[0].numel() * ssm.element_size()
|
||||
conv_available_bytes = (
|
||||
conv.untyped_storage().nbytes() - conv.storage_offset() * conv.element_size()
|
||||
)
|
||||
ssm_available_bytes = (
|
||||
ssm.untyped_storage().nbytes() - ssm.storage_offset() * ssm.element_size()
|
||||
)
|
||||
if conv.shape[0]:
|
||||
conv_required_bytes = (conv.shape[0] - 1) * conv.stride(
|
||||
0
|
||||
) * conv.element_size() + conv_slot_bytes
|
||||
ssm_required_bytes = (ssm.shape[0] - 1) * ssm.stride(
|
||||
0
|
||||
) * ssm.element_size() + ssm_slot_bytes
|
||||
if conv_required_bytes > conv_available_bytes:
|
||||
raise ValueError("KDA conv slots exceed the registered storage extent")
|
||||
if ssm_required_bytes > ssm_available_bytes:
|
||||
raise ValueError("KDA ssm slots exceed the registered storage extent")
|
||||
|
||||
return MambaTransferGeometry(
|
||||
conv_slot_stride=conv.stride(0),
|
||||
ssm_slot_stride=ssm.stride(0),
|
||||
ssm_slot_bytes=ssm_slot_bytes,
|
||||
conv_element_size=conv.element_size(),
|
||||
ssm_element_size=ssm.element_size(),
|
||||
# Registered region must span the full slot-strided extent: stride(0)
|
||||
# may exceed the per-slot element count, so numel() would under-size the
|
||||
# region and truncate the highest-slot transfers. shape[0]*stride(0)
|
||||
# covers every byte a ``slot * slot_stride * elem`` offset can address.
|
||||
# Cap at the bytes remaining from each view's storage offset. A packed
|
||||
# conv+ssm page places ssm at a non-zero intra-buffer offset,
|
||||
# so do not register past the end of the shared backing allocation.
|
||||
conv_region_len=min(
|
||||
conv.shape[0] * conv.stride(0) * conv.element_size(),
|
||||
conv_available_bytes,
|
||||
),
|
||||
ssm_region_len=min(
|
||||
ssm.shape[0] * ssm.stride(0) * ssm.element_size(),
|
||||
ssm_available_bytes,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def build_layer_to_spec(kv_cache_config: KVCacheConfig) -> dict[str, KVCacheSpec]:
|
||||
layer_to_spec: dict[str, KVCacheSpec] = {}
|
||||
for group in kv_cache_config.kv_cache_groups:
|
||||
@@ -99,10 +182,10 @@ def get_layer_transfer_geometry(
|
||||
layer_to_spec: Mapping[str, KVCacheSpec],
|
||||
remote_num_blocks: int | None = None,
|
||||
) -> LayerTransferGeometry:
|
||||
spec = layer_to_spec[layer_name]
|
||||
shape = kv_cache.shape
|
||||
stride = kv_cache.stride()
|
||||
element_size = kv_cache.element_size()
|
||||
spec = layer_to_spec[layer_name]
|
||||
is_mla_cache = is_mla_cache_layer(layer_to_spec, layer_name)
|
||||
|
||||
if not is_mla_cache and len(shape) == 5 and shape[0] == 2:
|
||||
@@ -238,12 +321,60 @@ def get_layer_transfer_geometry(
|
||||
)
|
||||
|
||||
|
||||
def kda_conv_ssm(
|
||||
kv_cache: torch.Tensor,
|
||||
spec: MambaSpec,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Return zero-copy conv and SSM views over a packed two-state page."""
|
||||
from math import prod
|
||||
|
||||
from vllm.utils.torch_utils import get_dtype_size
|
||||
|
||||
if len(spec.shapes) != 2 or len(spec.dtypes) != 2:
|
||||
raise ValueError(
|
||||
"MoRIIO KDA transfer requires exactly two states (conv and SSM)"
|
||||
)
|
||||
if kv_cache.element_size() != 1:
|
||||
raise ValueError("MoRIIO KDA packed cache must use a byte-sized dtype")
|
||||
if kv_cache.ndim != 4 or kv_cache.shape[1:3] != (1, 1) or kv_cache.stride(3) != 1:
|
||||
raise ValueError(
|
||||
"MoRIIO KDA packed cache must have shape [B, 1, 1, C] with "
|
||||
"a contiguous byte dimension"
|
||||
)
|
||||
# Mirror MambaBase.bind_kv_cache: blocks may be strided within a shared
|
||||
# multi-layer allocation, while every individual byte page is contiguous.
|
||||
pages = kv_cache.squeeze(dim=(1, 2))
|
||||
states: list[torch.Tensor] = []
|
||||
offset = 0
|
||||
for shp, dt in zip(spec.shapes, spec.dtypes, strict=True):
|
||||
nbytes = prod(shp) * get_dtype_size(dt)
|
||||
if offset + nbytes > pages.shape[1]:
|
||||
raise ValueError(
|
||||
"MoRIIO KDA state layout exceeds the packed cache page size"
|
||||
)
|
||||
state = pages[:, offset : offset + nbytes].view(dt)
|
||||
states.append(state.view(-1, *shp))
|
||||
offset += nbytes
|
||||
return states[0], states[1]
|
||||
|
||||
|
||||
def iter_layer_registration_regions(
|
||||
layer_name: str,
|
||||
kv_cache: torch.Tensor,
|
||||
layer_to_spec: Mapping[str, KVCacheSpec],
|
||||
) -> list[tuple[torch.Tensor, int]]:
|
||||
geometry = get_layer_transfer_geometry(layer_name, kv_cache, layer_to_spec)
|
||||
spec = layer_to_spec[layer_name]
|
||||
if isinstance(spec, MambaSpec):
|
||||
# KDA layer: register the conv and ssm tensors as two whole-tensor
|
||||
# regions (the conv 3-subprojection split is expressed as transfer
|
||||
# offset triples, not extra registrations).
|
||||
conv, ssm = kda_conv_ssm(kv_cache, spec)
|
||||
geom = get_mamba_transfer_geometry(conv, ssm)
|
||||
return [(conv, geom.conv_region_len), (ssm, geom.ssm_region_len)]
|
||||
geometry = cast(
|
||||
LayerTransferGeometry,
|
||||
get_layer_transfer_geometry(layer_name, kv_cache, layer_to_spec),
|
||||
)
|
||||
region_len = geometry.num_blocks * geometry.regions_per_block * geometry.block_len
|
||||
if geometry.regions_per_block == 1:
|
||||
# With padded or interleaved pages the block stride exceeds the
|
||||
@@ -311,9 +442,36 @@ def compute_block_transfer_offsets(
|
||||
"local_block_ids longer than remote_block_ids: "
|
||||
f"{len(local_block_ids)} > {len(remote_block_ids)}"
|
||||
)
|
||||
geometry = get_layer_transfer_geometry(
|
||||
layer_name, kv_cache, layer_to_spec, remote_num_blocks
|
||||
geometry = cast(
|
||||
LayerTransferGeometry,
|
||||
get_layer_transfer_geometry(
|
||||
layer_name, kv_cache, layer_to_spec, remote_num_blocks
|
||||
),
|
||||
)
|
||||
invalid_local = next(
|
||||
(
|
||||
block_id
|
||||
for block_id in local_block_ids
|
||||
if not 0 <= block_id < geometry.num_blocks
|
||||
),
|
||||
None,
|
||||
)
|
||||
if invalid_local is not None:
|
||||
raise ValueError(
|
||||
f"local block id {invalid_local} is outside [0, {geometry.num_blocks})"
|
||||
)
|
||||
invalid_remote = next(
|
||||
(
|
||||
block_id
|
||||
for block_id in remote_block_ids
|
||||
if not 0 <= block_id < remote_num_blocks
|
||||
),
|
||||
None,
|
||||
)
|
||||
if invalid_remote is not None:
|
||||
raise ValueError(
|
||||
f"remote block id {invalid_remote} is outside [0, {remote_num_blocks})"
|
||||
)
|
||||
element_size = kv_cache.element_size()
|
||||
transfer_size_byte = geometry.block_len
|
||||
per_block = geometry.transfers_per_block
|
||||
@@ -339,3 +497,125 @@ def compute_block_transfer_offsets(
|
||||
w += 1
|
||||
|
||||
return merge_fn(offset_local, offset_remote, sizes)
|
||||
|
||||
|
||||
class MambaOffsetTemplate(NamedTuple):
|
||||
"""Slot-independent conv+ssm offset decomposition for a KDA layer.
|
||||
|
||||
Homogeneous-TP geometry (conv/ssm slot strides, conv sub-projection
|
||||
offsets, ssm per-slot size) is identical across requests and across the
|
||||
homogeneous GDN layers, so it is computed once and reused; only the
|
||||
per-request slot bases vary (see ``apply_mamba_offset_template``).
|
||||
"""
|
||||
|
||||
num_slots: int
|
||||
conv_slot_stride_bytes: int
|
||||
ssm_slot_stride_bytes: int
|
||||
ssm_read_bytes: int
|
||||
conv_subprojs: tuple[tuple[int, int, int], ...]
|
||||
|
||||
|
||||
def build_mamba_offset_template(
|
||||
conv: torch.Tensor,
|
||||
ssm: torch.Tensor,
|
||||
split_info: MambaConvSplitInfo,
|
||||
tp_ratio: int,
|
||||
) -> MambaOffsetTemplate:
|
||||
"""Precompute the slot-independent conv+ssm offset decomposition.
|
||||
|
||||
Only homogeneous TP (``tp_ratio == 1``) is supported; heterogeneous TP is
|
||||
gated with ``NotImplementedError`` (see the design doc). The returned
|
||||
template is a pure function of the layer geometry and ``split_info``, so it
|
||||
can be cached and reused across requests without recomputation.
|
||||
"""
|
||||
if tp_ratio != 1:
|
||||
# Heterogeneous-TP recurrent-state transfer needs the remote page's
|
||||
# slot stride (which differs from the local page) and, for
|
||||
# P_TP > D_TP, a multi-rank gather of conv/ssm slices. Both are
|
||||
# follow-ups. The mamba path bypasses the attention KV-head validator,
|
||||
# so fail loudly here instead of silently transferring wrong bytes.
|
||||
raise NotImplementedError(
|
||||
"heterogeneous-TP mamba/KDA transfer is not supported yet "
|
||||
f"(tp_ratio={tp_ratio}); use equal prefill/decode TP for "
|
||||
"hybrid models"
|
||||
)
|
||||
geom = get_mamba_transfer_geometry(conv, ssm)
|
||||
conv_local_offsets = split_info.local_conv_offsets
|
||||
conv_remote_offsets = split_info.remote_conv_offsets(0, 1)
|
||||
ssm_read_bytes = geom.ssm_slot_bytes
|
||||
conv_subprojs = tuple(
|
||||
(loff, roff, rsz)
|
||||
for (loff, _lsz), (roff, rsz) in zip(conv_local_offsets, conv_remote_offsets)
|
||||
)
|
||||
return MambaOffsetTemplate(
|
||||
num_slots=conv.shape[0],
|
||||
conv_slot_stride_bytes=geom.conv_slot_stride * geom.conv_element_size,
|
||||
ssm_slot_stride_bytes=geom.ssm_slot_stride * geom.ssm_element_size,
|
||||
ssm_read_bytes=ssm_read_bytes,
|
||||
conv_subprojs=conv_subprojs,
|
||||
)
|
||||
|
||||
|
||||
def apply_mamba_offset_template(
|
||||
template: MambaOffsetTemplate,
|
||||
local_slots: list[int],
|
||||
remote_slots: list[int],
|
||||
) -> tuple[list[int], list[int], list[int]]:
|
||||
"""Apply per-request slot bases to a cached ``MambaOffsetTemplate``.
|
||||
|
||||
Conv sub-projection entries (all slots) come first, followed by one ssm
|
||||
entry per slot.
|
||||
"""
|
||||
if len(local_slots) != len(remote_slots):
|
||||
raise ValueError(
|
||||
"local and remote mamba slot counts must match: "
|
||||
f"{len(local_slots)} != {len(remote_slots)}"
|
||||
)
|
||||
invalid_local = next(
|
||||
(slot for slot in local_slots if not 0 <= slot < template.num_slots), None
|
||||
)
|
||||
if invalid_local is not None:
|
||||
raise ValueError(
|
||||
f"local mamba slot {invalid_local} is outside [0, {template.num_slots})"
|
||||
)
|
||||
invalid_remote = next((slot for slot in remote_slots if slot < 0), None)
|
||||
if invalid_remote is not None:
|
||||
raise ValueError(f"remote mamba slot {invalid_remote} must be non-negative")
|
||||
# The peer's KDA slot count is not part of MoRIIOAgentMetadata yet. Do not
|
||||
# compare remote slot IDs against the local pool size: two otherwise
|
||||
# compatible engines may reserve different numbers of slots.
|
||||
local_offs: list[int] = []
|
||||
remote_offs: list[int] = []
|
||||
sizes: list[int] = []
|
||||
|
||||
# Conv sub-projections (region 0), all slots first.
|
||||
conv_slot_stride_bytes = template.conv_slot_stride_bytes
|
||||
for ls, rs in zip(local_slots, remote_slots):
|
||||
lbase = ls * conv_slot_stride_bytes
|
||||
rbase = rs * conv_slot_stride_bytes
|
||||
for loff, roff, rsz in template.conv_subprojs:
|
||||
local_offs.append(lbase + loff)
|
||||
remote_offs.append(rbase + roff)
|
||||
sizes.append(rsz)
|
||||
|
||||
# SSM temporal state (region 1), one entry per slot.
|
||||
ssm_slot_stride_bytes = template.ssm_slot_stride_bytes
|
||||
ssm_read_bytes = template.ssm_read_bytes
|
||||
for ls, rs in zip(local_slots, remote_slots):
|
||||
local_offs.append(ls * ssm_slot_stride_bytes)
|
||||
remote_offs.append(rs * ssm_slot_stride_bytes)
|
||||
sizes.append(ssm_read_bytes)
|
||||
|
||||
return local_offs, remote_offs, sizes
|
||||
|
||||
|
||||
def compute_mamba_conv_split_count(
|
||||
local_slots: list[int],
|
||||
split_info: MambaConvSplitInfo,
|
||||
) -> int:
|
||||
"""Number of leading conv entries in a KDA layer transfer plan.
|
||||
|
||||
Entries ``[:count]`` are conv sub-projections (conv region/session);
|
||||
entries ``[count:]`` are the per-slot ssm state (ssm region/session).
|
||||
"""
|
||||
return len(local_slots) * len(split_info.local_conv_offsets)
|
||||
|
||||
@@ -75,6 +75,7 @@ from vllm.distributed.parallel_state import (
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.network_utils import make_zmq_path
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
@@ -2430,6 +2431,18 @@ class NixlBaseConnectorWorker:
|
||||
remote_physical_per_logical = (
|
||||
nixl_agent_meta.physical_blocks_per_logical_kv_block
|
||||
)
|
||||
if (
|
||||
(self.dcp_size > 1 or remote_dcp_size > 1)
|
||||
and self.region_group_ids
|
||||
and self.region_group_ids != self.dst_region_group_ids[remote_engine_id]
|
||||
and (
|
||||
self._physical_blocks_per_logical_kv_block != 1
|
||||
or remote_physical_per_logical != 1
|
||||
)
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"DCP region pulls require matching logical and physical block sizes"
|
||||
)
|
||||
if (
|
||||
self._has_mamba
|
||||
and remote_physical_per_logical
|
||||
@@ -3234,11 +3247,14 @@ class NixlBaseConnectorWorker:
|
||||
local_dcp_rank: int,
|
||||
remote_dcp_size: int,
|
||||
local_num_computed_blocks: int,
|
||||
num_remote_blocks: int | None = None,
|
||||
) -> tuple[list[int], list[int]]:
|
||||
"""Match local and remote block IDs by global DCP position.
|
||||
|
||||
``local_ids`` excludes blocks already satisfied by the local prefix
|
||||
cache, while ``remote_ids`` contains the full transferable remote list.
|
||||
``num_remote_blocks``, when provided, is the global block count before
|
||||
DCP partitioning and excludes allocation padding.
|
||||
|
||||
Example:
|
||||
local DCP size 2, rank 0 owns *global positions*=[0, 2, 4, 6]
|
||||
@@ -3254,6 +3270,9 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
"""
|
||||
local_size, remote_size = local_dcp_size, remote_dcp_size
|
||||
if num_remote_blocks is not None:
|
||||
num_local = cdiv(num_remote_blocks - local_dcp_rank, local_size)
|
||||
local_ids = local_ids[: max(0, num_local - local_num_computed_blocks)]
|
||||
|
||||
if local_size == remote_size:
|
||||
local_slice = local_ids
|
||||
@@ -3274,6 +3293,8 @@ class NixlBaseConnectorWorker:
|
||||
remote_slice = remote_ids[start_remote::k]
|
||||
|
||||
matched_blocks = min(len(local_slice), len(remote_slice))
|
||||
if num_remote_blocks is not None and matched_blocks < len(local_slice):
|
||||
raise ValueError("Remote KV pages do not cover the requested range")
|
||||
return local_slice[:matched_blocks], remote_slice[:matched_blocks]
|
||||
|
||||
@staticmethod
|
||||
@@ -3290,13 +3311,15 @@ class NixlBaseConnectorWorker:
|
||||
block_ids_by_region.append(list(block_ids[group_id]))
|
||||
return block_ids_by_region
|
||||
|
||||
@staticmethod
|
||||
def _apply_prefix_caching_by_region(
|
||||
self,
|
||||
decode_block_ids: BlockIds,
|
||||
prefill_block_ids: BlockIds,
|
||||
*,
|
||||
num_computed_blocks: list[int] | None = None,
|
||||
num_remote_blocks: int | None = None,
|
||||
remote_rank: int = 0,
|
||||
remote_dcp_size: int = 1,
|
||||
) -> tuple[BlockIds, BlockIds]:
|
||||
"""Pair an uncached decode suffix with the same prefill regions."""
|
||||
assert len(decode_block_ids) == len(prefill_block_ids)
|
||||
@@ -3310,13 +3333,18 @@ class NixlBaseConnectorWorker:
|
||||
for decode_region, prefill_region, start in zip(
|
||||
decode_block_ids, prefill_block_ids, num_computed_blocks, strict=True
|
||||
):
|
||||
count = min(len(decode_region), max(num_remote_blocks - start, 0))
|
||||
if start + count > len(prefill_region):
|
||||
raise ValueError("Remote KV pages do not cover the requested range")
|
||||
# An extra producer page can be allocation padding, not a
|
||||
# cached prefix. Select by token position instead of list length.
|
||||
matched_decode.append(list(decode_region[:count]))
|
||||
matched_prefill.append(list(prefill_region[start : start + count]))
|
||||
local, remote = self._apply_dcp_prefix_caching(
|
||||
decode_region,
|
||||
prefill_region,
|
||||
remote_rank,
|
||||
self.dcp_size,
|
||||
self.dcp_rank,
|
||||
remote_dcp_size,
|
||||
start,
|
||||
num_remote_blocks=num_remote_blocks,
|
||||
)
|
||||
matched_decode.append(local)
|
||||
matched_prefill.append(remote)
|
||||
return matched_decode, matched_prefill
|
||||
|
||||
trimmed_prefill: list[list[int]] = []
|
||||
|
||||
@@ -191,7 +191,6 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
"Different NIXL cache-group layouts are only supported for "
|
||||
"pure MLA models"
|
||||
)
|
||||
assert len(plan.all_source_ranks) == 1
|
||||
if self.block_size != remote_info.remote_block_size:
|
||||
raise NotImplementedError(
|
||||
"Region-mapped NIXL transfers require matching physical block sizes"
|
||||
@@ -213,7 +212,6 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
and meta.local_num_computed_blocks
|
||||
and all(group >= 0 for group in local_region_groups)
|
||||
and all(group >= 0 for group in remote_region_groups)
|
||||
and not dcp_active
|
||||
):
|
||||
transfer_groups = self.kv_cache_config.transfer_group_ids
|
||||
num_computed_blocks = [
|
||||
@@ -224,32 +222,34 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
num_remote_blocks = cdiv(
|
||||
meta.remote.num_tokens, remote_info.remote_block_size
|
||||
)
|
||||
elif (
|
||||
remote_info.remote_physical_blocks_per_logical
|
||||
elif any(local_by_region) and (
|
||||
dcp_active
|
||||
or remote_info.remote_physical_blocks_per_logical
|
||||
!= self._physical_blocks_per_logical_kv_block
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Region-mapped pulls with different logical block sizes require "
|
||||
"remote_num_tokens, per-group prefix counts, unshared regions "
|
||||
"and DCP=1"
|
||||
"Region-mapped pulls with DCP or different logical block sizes "
|
||||
"require remote_num_tokens, per-group prefix counts "
|
||||
"and unshared regions"
|
||||
)
|
||||
matched_local, matched_remote = self._apply_prefix_caching_by_region(
|
||||
local_by_region,
|
||||
remote_by_region,
|
||||
num_computed_blocks=num_computed_blocks,
|
||||
num_remote_blocks=num_remote_blocks,
|
||||
)
|
||||
meta.region_blocks_to_zero = [
|
||||
list(blocks[len(matched) :])
|
||||
for blocks, matched in zip(local_by_region, matched_local, strict=True)
|
||||
]
|
||||
read_specs = [
|
||||
ReadSpec(
|
||||
remote_rank=plan.all_source_ranks[0],
|
||||
local_block_ids=matched_local,
|
||||
remote_block_ids=matched_remote,
|
||||
rank,
|
||||
*self._apply_prefix_caching_by_region(
|
||||
local_by_region,
|
||||
remote_by_region,
|
||||
num_computed_blocks=num_computed_blocks,
|
||||
num_remote_blocks=num_remote_blocks,
|
||||
remote_rank=rank,
|
||||
remote_dcp_size=remote_info.remote_dcp_size,
|
||||
),
|
||||
block_ids_by_region=True,
|
||||
)
|
||||
for rank in plan.all_source_ranks
|
||||
]
|
||||
meta.region_blocks_to_zero = [
|
||||
list(blocks[sum(len(spec.local_block_ids[r]) for spec in read_specs) :])
|
||||
for r, blocks in enumerate(local_by_region)
|
||||
]
|
||||
else:
|
||||
remote_logical_block_ids = meta.remote.block_ids
|
||||
|
||||
@@ -553,6 +553,7 @@ def _create_req_context(req: Request) -> ReqContext:
|
||||
return ReqContext(
|
||||
req_id=req.request_id,
|
||||
kv_transfer_params=params,
|
||||
kv_hints=req.kv_hints,
|
||||
load_tier_filter=load_filter,
|
||||
)
|
||||
|
||||
|
||||
+49
-16
@@ -35,6 +35,7 @@ from typing_extensions import TypeIs
|
||||
import vllm.envs as envs
|
||||
from vllm.config import (
|
||||
AttentionConfig,
|
||||
AuxOutputConfig,
|
||||
CacheConfig,
|
||||
CompilationConfig,
|
||||
ConfigType,
|
||||
@@ -447,7 +448,9 @@ class EngineArgs:
|
||||
"""Arguments for vLLM engine."""
|
||||
|
||||
model: str = ModelConfig.model
|
||||
enable_return_routed_experts: bool = ModelConfig.enable_return_routed_experts
|
||||
# Public compatibility argument. Canonical runtime state lives in
|
||||
# AuxOutputConfig.
|
||||
enable_return_routed_experts: bool = False
|
||||
return_sampling_mask: bool = ModelConfig.return_sampling_mask
|
||||
model_weights: str = ModelConfig.model_weights
|
||||
served_model_name: str | list[str] | None = ModelConfig.served_model_name
|
||||
@@ -674,6 +677,7 @@ class EngineArgs:
|
||||
structured_outputs_config: StructuredOutputsConfig = get_field(
|
||||
VllmConfig, "structured_outputs_config"
|
||||
)
|
||||
aux_output_config: AuxOutputConfig = get_field(VllmConfig, "aux_output_config")
|
||||
reasoning_parser: str = StructuredOutputsConfig.reasoning_parser
|
||||
reasoning_parser_plugin: str | None = None
|
||||
|
||||
@@ -737,6 +741,9 @@ class EngineArgs:
|
||||
|
||||
generation_config: str = ModelConfig.generation_config
|
||||
enable_sleep_mode: bool = ModelConfig.enable_sleep_mode
|
||||
sleep_preserve_parameter_names: list[str] = get_field(
|
||||
ModelConfig, "sleep_preserve_parameter_names"
|
||||
)
|
||||
enable_cumem_allocator: bool = ModelConfig.enable_cumem_allocator
|
||||
enable_nccl_comm_suspend: bool = ModelConfig.enable_nccl_comm_suspend
|
||||
override_generation_config: dict[str, Any] = get_field(
|
||||
@@ -753,8 +760,8 @@ class EngineArgs:
|
||||
mamba_block_size: int | None = get_field(CacheConfig, "mamba_block_size")
|
||||
prefix_match_unit: int | None = get_field(CacheConfig, "prefix_match_unit")
|
||||
mamba_cache_mode: MambaCacheMode = CacheConfig.mamba_cache_mode
|
||||
enable_mamba_fine_grained_prefix_cache: bool = (
|
||||
CacheConfig.enable_mamba_fine_grained_prefix_cache
|
||||
enable_mamba_shared_prefix_checkpoint: bool = (
|
||||
CacheConfig.enable_mamba_shared_prefix_checkpoint
|
||||
)
|
||||
replayssm_buffer_len: int = CacheConfig.replayssm_buffer_len
|
||||
use_replayssm: bool = CacheConfig.use_replayssm
|
||||
@@ -816,6 +823,10 @@ class EngineArgs:
|
||||
self.compilation_config = CompilationConfig(**self.compilation_config)
|
||||
if isinstance(self.attention_config, dict):
|
||||
self.attention_config = AttentionConfig(**self.attention_config)
|
||||
if isinstance(self.aux_output_config, dict):
|
||||
self.aux_output_config = AuxOutputConfig(**self.aux_output_config)
|
||||
if self.enable_return_routed_experts:
|
||||
self.aux_output_config.enable_return_routed_experts = True
|
||||
if isinstance(self.engram_config, dict):
|
||||
self.engram_config = EngramConfig(**self.engram_config)
|
||||
if isinstance(self.mamba_config, dict):
|
||||
@@ -884,6 +895,7 @@ class EngineArgs:
|
||||
"""Shared CLI arguments for vLLM engine."""
|
||||
# Model arguments
|
||||
model_kwargs = get_kwargs(ModelConfig)
|
||||
aux_output_kwargs = get_kwargs(AuxOutputConfig)
|
||||
model_group = parser.add_argument_group(
|
||||
title="ModelConfig",
|
||||
description=ModelConfig.__doc__,
|
||||
@@ -923,7 +935,7 @@ class EngineArgs:
|
||||
model_group.add_argument("--enforce-eager", **model_kwargs["enforce_eager"])
|
||||
model_group.add_argument(
|
||||
"--enable-return-routed-experts",
|
||||
**model_kwargs["enable_return_routed_experts"],
|
||||
**aux_output_kwargs["enable_return_routed_experts"],
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--return-sampling-mask",
|
||||
@@ -966,6 +978,10 @@ class EngineArgs:
|
||||
model_group.add_argument(
|
||||
"--enable-sleep-mode", **model_kwargs["enable_sleep_mode"]
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--sleep-preserve-parameter-names",
|
||||
**model_kwargs["sleep_preserve_parameter_names"],
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--enable-cumem-allocator", **model_kwargs["enable_cumem_allocator"]
|
||||
)
|
||||
@@ -1282,7 +1298,10 @@ class EngineArgs:
|
||||
)
|
||||
cache_group.add_argument("--block-size", **cache_kwargs["block_size"])
|
||||
cache_group.add_argument(
|
||||
"--gpu-memory-utilization", **cache_kwargs["gpu_memory_utilization"]
|
||||
"--gpu-memory-utilization",
|
||||
"--device-memory-utilization",
|
||||
dest="gpu_memory_utilization",
|
||||
**cache_kwargs["gpu_memory_utilization"],
|
||||
)
|
||||
cache_group.add_argument(
|
||||
"--kv-cache-memory-bytes", **cache_kwargs["kv_cache_memory_bytes"]
|
||||
@@ -1330,8 +1349,8 @@ class EngineArgs:
|
||||
"--mamba-cache-mode", **cache_kwargs["mamba_cache_mode"]
|
||||
)
|
||||
cache_group.add_argument(
|
||||
"--enable-mamba-fine-grained-prefix-cache",
|
||||
**cache_kwargs["enable_mamba_fine_grained_prefix_cache"],
|
||||
"--enable-mamba-shared-prefix-checkpoint",
|
||||
**cache_kwargs["enable_mamba_shared_prefix_checkpoint"],
|
||||
)
|
||||
cache_group.add_argument(
|
||||
"--replayssm-buffer-len", **cache_kwargs["replayssm_buffer_len"]
|
||||
@@ -1749,6 +1768,9 @@ class EngineArgs:
|
||||
vllm_group.add_argument(
|
||||
"--structured-outputs-config", **vllm_kwargs["structured_outputs_config"]
|
||||
)
|
||||
vllm_group.add_argument(
|
||||
"--aux-output-config", **vllm_kwargs["aux_output_config"]
|
||||
)
|
||||
vllm_group.add_argument("--profiler-config", **vllm_kwargs["profiler_config"])
|
||||
vllm_group.add_argument(
|
||||
"--optimization-level", **vllm_kwargs["optimization_level"]
|
||||
@@ -1856,7 +1878,6 @@ class EngineArgs:
|
||||
quantization_config=self.quantization_config,
|
||||
allow_deprecated_quantization=self.allow_deprecated_quantization,
|
||||
enforce_eager=self.enforce_eager,
|
||||
enable_return_routed_experts=self.enable_return_routed_experts,
|
||||
return_sampling_mask=self.return_sampling_mask,
|
||||
max_logprobs=self.max_logprobs,
|
||||
logprobs_mode=self.logprobs_mode,
|
||||
@@ -1890,6 +1911,7 @@ class EngineArgs:
|
||||
generation_config=self.generation_config,
|
||||
override_generation_config=self.override_generation_config,
|
||||
enable_sleep_mode=self.enable_sleep_mode,
|
||||
sleep_preserve_parameter_names=self.sleep_preserve_parameter_names,
|
||||
enable_cumem_allocator=self.enable_cumem_allocator,
|
||||
enable_nccl_comm_suspend=self.enable_nccl_comm_suspend,
|
||||
model_impl=self.model_impl,
|
||||
@@ -2128,8 +2150,8 @@ class EngineArgs:
|
||||
mamba_block_size=self.mamba_block_size,
|
||||
prefix_match_unit=self.prefix_match_unit,
|
||||
mamba_cache_mode=self.mamba_cache_mode,
|
||||
enable_mamba_fine_grained_prefix_cache=(
|
||||
self.enable_mamba_fine_grained_prefix_cache
|
||||
enable_mamba_shared_prefix_checkpoint=(
|
||||
self.enable_mamba_shared_prefix_checkpoint
|
||||
),
|
||||
replayssm_buffer_len=self.replayssm_buffer_len,
|
||||
use_replayssm=self.use_replayssm,
|
||||
@@ -2221,12 +2243,22 @@ class EngineArgs:
|
||||
self.node_rank * local_world_size
|
||||
) // world_size_within_dp
|
||||
if self.data_parallel_size > 1 and self.data_parallel_external_lb:
|
||||
self.data_parallel_rank = inferred_data_parallel_rank
|
||||
logger.info(
|
||||
"Inferred data_parallel_rank %d from node_rank %d for external lb",
|
||||
self.data_parallel_rank,
|
||||
self.node_rank,
|
||||
)
|
||||
if self.data_parallel_rank is None:
|
||||
if self.nnodes % self.data_parallel_size != 0:
|
||||
raise ValueError(
|
||||
"Invalid data-parallel launch options: "
|
||||
"`--node-rank` cannot unambiguously identify external "
|
||||
"data-parallel ranks when `--nnodes` is not divisible "
|
||||
"by `--data-parallel-size`. Set a unique "
|
||||
"`--data-parallel-rank` for each external-LB process."
|
||||
)
|
||||
self.data_parallel_rank = inferred_data_parallel_rank
|
||||
logger.info(
|
||||
"Inferred data_parallel_rank %d from node_rank %d "
|
||||
"for external lb",
|
||||
self.data_parallel_rank,
|
||||
self.node_rank,
|
||||
)
|
||||
elif self.data_parallel_size_local is None:
|
||||
# Infer data parallel size local for internal dplb:
|
||||
self.data_parallel_size_local = max(
|
||||
@@ -2669,6 +2701,7 @@ class EngineArgs:
|
||||
load_config=load_config,
|
||||
offload_config=offload_config,
|
||||
attention_config=attention_config,
|
||||
aux_output_config=self.aux_output_config,
|
||||
engram_config=self.engram_config,
|
||||
mamba_config=mamba_config,
|
||||
kernel_config=kernel_config,
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.tasks import SupportedTask
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
from vllm.v1.fault_tolerance.utils import FaultToleranceRequest, FaultToleranceResult
|
||||
from vllm.v1.kv_hints import KvHintsEnvelope
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import PauseMode
|
||||
@@ -102,6 +103,7 @@ class EngineClient(ABC):
|
||||
priority: int = 0,
|
||||
data_parallel_rank: int | None = None,
|
||||
session_id: str | None = None,
|
||||
kv_hints: KvHintsEnvelope | None = None,
|
||||
reasoning_ended: bool | None = None,
|
||||
reasoning_parser_kwargs: dict[str, Any] | None = None,
|
||||
) -> AsyncGenerator[RequestOutput, None]:
|
||||
|
||||
@@ -46,6 +46,7 @@ def main():
|
||||
import vllm.entrypoints.cli.openai
|
||||
import vllm.entrypoints.cli.run_batch
|
||||
import vllm.entrypoints.cli.serve
|
||||
import vllm.entrypoints.cli.snapshot
|
||||
from vllm.entrypoints.serve.utils.api_utils import (
|
||||
VLLM_SUBCMD_PARSER_EPILOG,
|
||||
cli_env_setup,
|
||||
@@ -59,9 +60,11 @@ def main():
|
||||
vllm.entrypoints.cli.benchmark.main,
|
||||
vllm.entrypoints.cli.collect_env,
|
||||
vllm.entrypoints.cli.run_batch,
|
||||
vllm.entrypoints.cli.snapshot,
|
||||
]
|
||||
|
||||
cli_env_setup()
|
||||
if sys.argv[1:2] != ["snapshot"]:
|
||||
cli_env_setup()
|
||||
|
||||
vllm.entrypoints.cli.benchmark.main.maybe_exec_rust_bench()
|
||||
|
||||
@@ -94,7 +97,12 @@ def main():
|
||||
subparsers = parser.add_subparsers(required=False, dest="subparser")
|
||||
cmds = {}
|
||||
for cmd_module in CMD_MODULES:
|
||||
new_cmds = cmd_module.cmd_init()
|
||||
if cmd_module is vllm.entrypoints.cli.snapshot:
|
||||
new_cmds = cmd_module.cmd_init(
|
||||
create_requested=sys.argv[1:3] == ["snapshot", "create"]
|
||||
)
|
||||
else:
|
||||
new_cmds = cmd_module.cmd_init()
|
||||
for cmd in new_cmds:
|
||||
cmd.subparser_init(subparsers).set_defaults(dispatch_function=cmd.cmd)
|
||||
cmds[cmd.name] = cmd
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import typing
|
||||
from pathlib import Path
|
||||
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
else:
|
||||
FlexibleArgumentParser = argparse.ArgumentParser
|
||||
|
||||
|
||||
def validate_create_args(args: argparse.Namespace) -> None:
|
||||
model = str(getattr(args, "model_tag", None) or args.model)
|
||||
revision = str(getattr(args, "revision", None) or "")
|
||||
if (
|
||||
Path(model).exists()
|
||||
or len(revision) != 40
|
||||
or any(character not in "0123456789abcdefABCDEF" for character in revision)
|
||||
):
|
||||
raise ValueError(
|
||||
"snapshot create requires an immutable remote model and "
|
||||
"40-character --revision"
|
||||
)
|
||||
parallel_sizes = (
|
||||
("tensor parallel", args.tensor_parallel_size),
|
||||
("pipeline parallel", args.pipeline_parallel_size),
|
||||
("data parallel", args.data_parallel_size),
|
||||
("prefill context parallel", args.prefill_context_parallel_size),
|
||||
)
|
||||
for name, size in parallel_sizes:
|
||||
if size != 1:
|
||||
raise ValueError(f"snapshot create currently requires {name} size 1")
|
||||
unsupported_frontend = (
|
||||
args.api_server_count not in (None, 1)
|
||||
or args.grpc
|
||||
or args.headless
|
||||
or args.api_key
|
||||
or os.environ.get("VLLM_API_KEY")
|
||||
or args.uds
|
||||
or args.middleware
|
||||
)
|
||||
if unsupported_frontend or any(
|
||||
(
|
||||
args.ssl_keyfile,
|
||||
args.ssl_certfile,
|
||||
args.ssl_ca_certs,
|
||||
args.enable_ssl_refresh,
|
||||
args.ssl_ciphers,
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
"snapshot create requires one unauthenticated plaintext HTTP server"
|
||||
)
|
||||
if args.logprobs_mode in {"raw_logits", "processed_logits"}:
|
||||
raise ValueError("snapshot canary requires a log-probability mode")
|
||||
if any(
|
||||
getattr(args, name, None) is not None
|
||||
for name in ("speculative_config", "spec_method", "spec_model", "spec_tokens")
|
||||
):
|
||||
raise ValueError("snapshot create does not support speculative decoding")
|
||||
if platform.system() != "Linux" or platform.machine() != "x86_64":
|
||||
raise ValueError("snapshot create requires Linux x86_64")
|
||||
|
||||
|
||||
def run_create(args: argparse.Namespace) -> None:
|
||||
validate_create_args(args)
|
||||
from vllm.snapshot.controller import create_snapshot
|
||||
|
||||
create_snapshot(args)
|
||||
|
||||
|
||||
def run_inspect(args: argparse.Namespace) -> None:
|
||||
from vllm.snapshot.manifest import inspect_snapshot
|
||||
|
||||
print(json.dumps(inspect_snapshot(Path(args.snapshot_dir)), indent=2))
|
||||
|
||||
|
||||
def run_restore(args: argparse.Namespace) -> None:
|
||||
from vllm.snapshot.controller import restore_snapshot
|
||||
|
||||
restore_snapshot(args)
|
||||
|
||||
|
||||
class SnapshotSubcommand(CLISubcommand):
|
||||
"""The `snapshot` subcommand for the vLLM CLI."""
|
||||
|
||||
name = "snapshot"
|
||||
|
||||
def __init__(self, *, create_requested: bool = False) -> None:
|
||||
self.create_requested = create_requested
|
||||
|
||||
@staticmethod
|
||||
def cmd(args: argparse.Namespace) -> None:
|
||||
args.snapshot_dispatch(args)
|
||||
|
||||
def subparser_init(
|
||||
self, subparsers: argparse._SubParsersAction
|
||||
) -> FlexibleArgumentParser:
|
||||
parser = subparsers.add_parser(
|
||||
self.name,
|
||||
help="Create, inspect, or restore an initialized vLLM snapshot.",
|
||||
usage="vllm snapshot <create|inspect|restore> [options]",
|
||||
)
|
||||
actions = parser.add_subparsers(required=True, dest="snapshot_action")
|
||||
|
||||
create_parser = actions.add_parser(
|
||||
"create", help="Create a snapshot from an initialized TP1 engine."
|
||||
)
|
||||
if self.create_requested:
|
||||
from vllm.entrypoints.launchers.cli_args import make_arg_parser
|
||||
|
||||
create_parser = make_arg_parser(create_parser)
|
||||
else:
|
||||
create_parser.add_argument("model_tag", nargs="?")
|
||||
create_parser.add_argument("--snapshot-dir", required=True)
|
||||
create_parser.set_defaults(snapshot_dispatch=run_create)
|
||||
|
||||
inspect_parser = actions.add_parser(
|
||||
"inspect", help="Inspect a snapshot without restoring it."
|
||||
)
|
||||
inspect_parser.add_argument("snapshot_dir")
|
||||
inspect_parser.set_defaults(snapshot_dispatch=run_inspect)
|
||||
|
||||
restore_parser = actions.add_parser(
|
||||
"restore", help="Restore a same-host TP1 snapshot."
|
||||
)
|
||||
restore_parser.add_argument("snapshot_dir")
|
||||
restore_parser.add_argument("--host", default=None)
|
||||
restore_parser.add_argument("--port", type=int, default=8000)
|
||||
restore_parser.set_defaults(snapshot_dispatch=run_restore)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def cmd_init(*, create_requested: bool = False) -> list[CLISubcommand]:
|
||||
return [SnapshotSubcommand(create_requested=create_requested)]
|
||||
@@ -53,8 +53,7 @@ from vllm.entrypoints.serve.engine.protocol import (
|
||||
)
|
||||
from vllm.entrypoints.speech_to_text.transcription.protocol import (
|
||||
TranscriptionRequest,
|
||||
TranscriptionResponse,
|
||||
TranscriptionResponseVerbose,
|
||||
TranscriptionResponseVariant,
|
||||
)
|
||||
from vllm.entrypoints.speech_to_text.translation.protocol import (
|
||||
TranslationRequest,
|
||||
@@ -203,8 +202,7 @@ AllResponse: TypeAlias = (
|
||||
| EmbeddingResponse
|
||||
| ScoreResponse
|
||||
| RerankResponse
|
||||
| TranscriptionResponse
|
||||
| TranscriptionResponseVerbose
|
||||
| TranscriptionResponseVariant
|
||||
| TranslationResponse
|
||||
| TranslationResponseVerbose
|
||||
)
|
||||
@@ -660,8 +658,7 @@ def make_transcription_wrapper(
|
||||
async def transcription_wrapper(
|
||||
batch_request_body: (BatchTranscriptionRequest | BatchTranslationRequest),
|
||||
) -> (
|
||||
TranscriptionResponse
|
||||
| TranscriptionResponseVerbose
|
||||
TranscriptionResponseVariant
|
||||
| TranslationResponse
|
||||
| TranslationResponseVerbose
|
||||
| ErrorResponse
|
||||
|
||||
@@ -57,6 +57,8 @@ logger = init_logger(__name__)
|
||||
class _ChunkedPromptAggregator:
|
||||
weighted_sum: torch.Tensor | None = None
|
||||
total_weight: int = 0
|
||||
num_chunks: int = 0
|
||||
all_chunks_l2_normalized: bool = True
|
||||
|
||||
|
||||
class EmbedIOProcessor(PoolingIOProcessor):
|
||||
@@ -204,7 +206,17 @@ class EmbedIOProcessor(PoolingIOProcessor):
|
||||
|
||||
weight = len(result.prompt_token_ids)
|
||||
embedding_data = result.outputs.data
|
||||
weighted_embedding = embedding_data.to(dtype=torch.float32) * weight
|
||||
float_embedding = embedding_data.to(dtype=torch.float32)
|
||||
if ctx.pooling_params.use_activation:
|
||||
# Custom activations need not L2-normalize; allow BF16 rounding.
|
||||
embedding_norm = torch.linalg.vector_norm(float_embedding)
|
||||
aggregator.all_chunks_l2_normalized &= torch.allclose(
|
||||
embedding_norm,
|
||||
torch.ones_like(embedding_norm),
|
||||
rtol=1e-2,
|
||||
atol=1e-5,
|
||||
)
|
||||
weighted_embedding = float_embedding * weight
|
||||
|
||||
if aggregator.weighted_sum is None:
|
||||
# First chunk
|
||||
@@ -214,6 +226,7 @@ class EmbedIOProcessor(PoolingIOProcessor):
|
||||
aggregator.weighted_sum += weighted_embedding
|
||||
|
||||
aggregator.total_weight += weight
|
||||
aggregator.num_chunks += 1
|
||||
|
||||
if ctx.original_engine_inputs is None:
|
||||
raise ValueError("Original engine inputs not available")
|
||||
@@ -239,6 +252,14 @@ class EmbedIOProcessor(PoolingIOProcessor):
|
||||
):
|
||||
# Compute final mean embedding
|
||||
final_embedding = weighted_sum / total_weight
|
||||
if (
|
||||
ctx.pooling_params.use_activation
|
||||
and aggregator.num_chunks > 1
|
||||
and aggregator.all_chunks_l2_normalized
|
||||
):
|
||||
final_embedding = torch.nn.functional.normalize(
|
||||
final_embedding, dim=-1
|
||||
)
|
||||
|
||||
# Create a PoolingRequestOutput
|
||||
# for the aggregated result
|
||||
|
||||
@@ -602,6 +602,7 @@ class DerenderChatStreamRequest(BaseModel):
|
||||
the client carried ``stream_state``.
|
||||
"""
|
||||
|
||||
# --8<-- [start:derender-chat-stream-request]
|
||||
stream: Literal[True]
|
||||
|
||||
model: str | None = None
|
||||
@@ -629,6 +630,7 @@ class DerenderChatStreamRequest(BaseModel):
|
||||
|
||||
chat_request: ChatCompletionRequest | None = None
|
||||
"""The original (post adjust_request) ChatCompletionRequest from /render."""
|
||||
# --8<-- [end:derender-chat-stream-request]
|
||||
|
||||
|
||||
class DerenderCompletionStreamRequest(BaseModel):
|
||||
@@ -639,6 +641,7 @@ class DerenderCompletionStreamRequest(BaseModel):
|
||||
returns the derendered chunk plus updated state.
|
||||
"""
|
||||
|
||||
# --8<-- [start:derender-completion-stream-request]
|
||||
stream: Literal[True]
|
||||
|
||||
model: str | None = None
|
||||
@@ -653,6 +656,7 @@ class DerenderCompletionStreamRequest(BaseModel):
|
||||
|
||||
completion_request: CompletionRequest | None = None
|
||||
"""The original (post adjust_request) CompletionRequest from /render."""
|
||||
# --8<-- [end:derender-completion-stream-request]
|
||||
|
||||
|
||||
class DerenderChatStreamResponse(BaseModel):
|
||||
|
||||
+16
-8
@@ -131,6 +131,7 @@ if TYPE_CHECKING:
|
||||
VLLM_GDN_DECODE_KERNEL: Literal["cuda", "triton"] = "cuda"
|
||||
VLLM_DISABLE_PYNCCL: bool = False
|
||||
VLLM_USE_OINK_OPS: bool = False
|
||||
VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD: bool = False
|
||||
VLLM_MXFP8_EMULATION_DEQUANT_AT_LOAD: bool = True
|
||||
VLLM_ROCM_USE_AITER: bool = False
|
||||
VLLM_ROCM_USE_AITER_CUSTOM_AR: bool = True
|
||||
@@ -156,7 +157,6 @@ if TYPE_CHECKING:
|
||||
VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT: bool = False
|
||||
VLLM_ENABLE_V1_MULTIPROCESSING: bool = True
|
||||
VLLM_LOG_BATCHSIZE_INTERVAL: float = -1
|
||||
VLLM_PLE_CPU_OFFLOAD: bool = True
|
||||
VLLM_DISABLE_COMPILE_CACHE: bool = False
|
||||
VLLM_REPLICATE_EMBED: bool = False
|
||||
VLLM_USE_LAYERNAME: bool = True
|
||||
@@ -213,7 +213,7 @@ if TYPE_CHECKING:
|
||||
VLLM_KIMI_K3_SHARD_SP_SHARED_EXPERT: bool = False
|
||||
VLLM_KIMI_K3_AUX_ATTN_RES_STREAM: bool = False
|
||||
VLLM_KIMI_K3_GEMM_AR: bool = True
|
||||
VLLM_KIMI_K3_GEMM_RS: bool = False
|
||||
VLLM_ENABLE_GEMM_RS: bool = False
|
||||
VLLM_BLOCKSCALE_FP8_GEMM_FLASHINFER: bool = True
|
||||
VLLM_USE_FLASHINFER_MOE_INT4: bool = False
|
||||
VLLM_FLASHINFER_AUTOTUNE_CACHE_DIR: str | None = None
|
||||
@@ -1230,6 +1230,13 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
),
|
||||
# Disable aiter ops unless specifically enabled.
|
||||
# Acts as a parent switch to enable the rest of the other operations.
|
||||
# Set to 1 to dequantize MXFP4 weights to BF16 once at load time and run as
|
||||
# a BF16 checkpoint (no per-step weight dequant). This improves emulation
|
||||
# latency at the cost of additional device memory. Default off.
|
||||
"VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD": lambda: (
|
||||
os.getenv("VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD", "False").lower()
|
||||
in ("true", "1")
|
||||
),
|
||||
# On hardware without a native MXFP8 kernel (e.g. ROCm gfx942 / MI300), the
|
||||
# MXFP8 emulation path dequantizes weights MXFP8->BF16 once at load time and
|
||||
# runs as a BF16 checkpoint (no per-step dequant). Set to 0 to fall back to
|
||||
@@ -1524,7 +1531,8 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_HUMMING_ONLINE_QUANT_CONFIG": lambda: maybe_convert_json_str_or_file(
|
||||
os.environ.get("VLLM_HUMMING_ONLINE_QUANT_CONFIG", None)
|
||||
),
|
||||
# The activation dtype config for humming kernel
|
||||
# The activation dtype config for humming kernel. Explicit schemas disable
|
||||
# fallback unless the config includes "allow_fallback": true.
|
||||
"VLLM_HUMMING_INPUT_QUANT_CONFIG": lambda: maybe_convert_json_str_or_file(
|
||||
os.environ.get("VLLM_HUMMING_INPUT_QUANT_CONFIG", None)
|
||||
),
|
||||
@@ -1621,9 +1629,11 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
# Use the SM100 BF16 GEMM-AR kernel for eligible Kimi-K3 row-parallel
|
||||
# attention projections. All TP ranks must belong to one NVLink domain.
|
||||
"VLLM_KIMI_K3_GEMM_AR": lambda: bool(int(os.getenv("VLLM_KIMI_K3_GEMM_AR", "1"))),
|
||||
# Use the SM100 BF16 GEMM-RS kernel for eligible Kimi-K3 sequence-parallel
|
||||
# row-parallel projections. All TP ranks must belong to one NVLink domain.
|
||||
"VLLM_KIMI_K3_GEMM_RS": lambda: bool(int(os.getenv("VLLM_KIMI_K3_GEMM_RS", "0"))),
|
||||
# Fuse eligible sequence-parallel row-parallel projections with their TP
|
||||
# reduce-scatter using the SM100 BF16/MXFP8 GEMM-RS kernel (Kimi-K3
|
||||
# attention/shared-expert projections, DeepSeek-V4.1 ``wo_b``). All TP
|
||||
# ranks must belong to one NVLink domain.
|
||||
"VLLM_ENABLE_GEMM_RS": lambda: bool(int(os.getenv("VLLM_ENABLE_GEMM_RS", "0"))),
|
||||
# Allow use of FlashInfer FP8 block-scale GEMM for linear layers.
|
||||
# This uses TensorRT-LLM kernels and requires SM90+ (Hopper).
|
||||
"VLLM_BLOCKSCALE_FP8_GEMM_FLASHINFER": lambda: bool(
|
||||
@@ -2065,8 +2075,6 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_LOG_MODEL_INSPECTION": lambda: bool(
|
||||
int(os.getenv("VLLM_LOG_MODEL_INSPECTION", "0"))
|
||||
),
|
||||
# Store n-gram embedding tables in pinned CPU memory for UVA lookup.
|
||||
"VLLM_PLE_CPU_OFFLOAD": lambda: bool(int(os.getenv("VLLM_PLE_CPU_OFFLOAD", "1"))),
|
||||
# Debug logging for --enable-mfu-metrics
|
||||
"VLLM_DEBUG_MFU_METRICS": lambda: bool(
|
||||
int(os.getenv("VLLM_DEBUG_MFU_METRICS", "0"))
|
||||
|
||||
@@ -1104,7 +1104,10 @@ def enable_batch_invariant_mode():
|
||||
|
||||
_fp16_block_size_n = 128
|
||||
|
||||
# Softmax, log_softmax, mean, and bmm are already batch-invariant on XPU
|
||||
# Native mean can change reduction order with the row count on XPU too.
|
||||
_batch_invariant_LIB.impl("aten::mean.dim", mean_batch_invariant, key)
|
||||
|
||||
# Softmax, log_softmax, and bmm are already batch-invariant on XPU
|
||||
# (oneDNN backend produces bitwise-identical results regardless of batch
|
||||
# context). Only register these overrides on CUDA where they are needed.
|
||||
if not current_platform.is_xpu():
|
||||
@@ -1113,7 +1116,6 @@ def enable_batch_invariant_mode():
|
||||
)
|
||||
_batch_invariant_LIB.impl("aten::softmax", softmax_batch_invariant, key)
|
||||
_batch_invariant_LIB.impl("aten::_softmax", softmax_batch_invariant, key)
|
||||
_batch_invariant_LIB.impl("aten::mean.dim", mean_batch_invariant, key)
|
||||
# torch 2.12+ registers a built-in Triton bmm kernel for CUDA
|
||||
# (torch._native.ops.bmm_outer_product), so we need allow_override
|
||||
# to replace it at the dispatcher level.
|
||||
|
||||
@@ -101,6 +101,7 @@ from vllm.model_executor.kernels.linear.mxfp6 import (
|
||||
from vllm.model_executor.kernels.linear.mxfp6.emulation import (
|
||||
EmulationMxfp6LinearKernel,
|
||||
)
|
||||
from vllm.model_executor.kernels.linear.mxfp6.humming import HummingMxFp6LinearKernel
|
||||
from vllm.model_executor.kernels.linear.mxfp8 import (
|
||||
Mxfp8LinearKernel,
|
||||
Mxfp8LinearLayerConfig,
|
||||
@@ -295,6 +296,7 @@ _LINEAR_BACKEND_KERNEL_MAP: dict[str, set[type]] = {
|
||||
HummingLinearKernel,
|
||||
HummingMxfp8LinearKernel,
|
||||
HummingMxFp4LinearKernel,
|
||||
HummingMxFp6LinearKernel,
|
||||
HummingNvFp4LinearKernel,
|
||||
},
|
||||
"marlin": {
|
||||
@@ -574,6 +576,7 @@ _POSSIBLE_NVFP4_KERNELS: dict[PlatformEnum, list[type[NvFp4LinearKernel]]] = {
|
||||
|
||||
_POSSIBLE_MXFP6_KERNELS: dict[PlatformEnum, list[type[MxFp6LinearKernel]]] = {
|
||||
PlatformEnum.CUDA: [
|
||||
HummingMxFp6LinearKernel,
|
||||
EmulationMxfp6LinearKernel,
|
||||
],
|
||||
PlatformEnum.ROCM: [
|
||||
@@ -1294,6 +1297,7 @@ __all__ = [
|
||||
"MxFp6LinearLayerConfig",
|
||||
"init_mxfp6_linear_kernel",
|
||||
"EmulationMxfp6LinearKernel",
|
||||
"HummingMxFp6LinearKernel",
|
||||
"AiterMxfp4LinearKernel",
|
||||
"EmulationMxfp4LinearKernel",
|
||||
"FlashInferMxFp4LinearKernel",
|
||||
|
||||
+341
-58
@@ -1,18 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""SM100 BF16 GEMM with fused tensor-parallel reduce-scatter/all-reduce."""
|
||||
"""SM100 BF16/MXFP8 GEMM with fused tensor-parallel reduce-scatter/all-reduce.
|
||||
|
||||
Model-neutral: any row-parallel projection whose output is reduced across TP
|
||||
(Kimi-K3 ``o_proj``/``down_proj``, DeepSeek-V4.1 ``wo_b``) can bind to the
|
||||
process-wide workspace through ``maybe_init_gemm_rs_ar`` + ``GemmRsAr.apply``.
|
||||
"""
|
||||
|
||||
# Based on CUTLASS's Blackwell distributed GEMM-RS example at dcf215a.
|
||||
# See https://github.com/NVIDIA/cutlass/issues/3117 for memory semantics.
|
||||
# The MXFP8 path follows the block-scaled SM100 GEMM template from
|
||||
# https://github.com/gau-nernst/gn-kernels (sm100_mm_mxfp8.py).
|
||||
|
||||
from functools import cache
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import cutlass
|
||||
import torch
|
||||
import torch.distributed._symmetric_memory as symm_mem
|
||||
from cuda.bindings.driver import CUstream
|
||||
from cutlass import BFloat16, Int32, Int64, Uint16, cute, utils
|
||||
from cutlass import (
|
||||
BFloat16,
|
||||
Float8E4M3FN,
|
||||
Float8E8M0FNU,
|
||||
Int32,
|
||||
Int64,
|
||||
Uint16,
|
||||
Uint64,
|
||||
cute,
|
||||
utils,
|
||||
)
|
||||
from cutlass._mlir import ir
|
||||
from cutlass._mlir.dialects import llvm, nvvm, vector
|
||||
from cutlass.cute.nvgpu import cpasync, tcgen05
|
||||
@@ -24,6 +42,10 @@ from vllm.cute_utils import _tcgen05, mbarrier, simple_tma_copy, to_cta0_smem
|
||||
from vllm.distributed import get_tp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import LinearBase, UnquantizedLinearMethod
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -88,24 +110,31 @@ def multimem_st_16B(dst: cute.Tensor, value: cute.Tensor, *, loc=None, ip=None)
|
||||
)
|
||||
|
||||
|
||||
class Sm100GemmRsArBF16:
|
||||
class Sm100GemmRsAr:
|
||||
def __init__(
|
||||
self,
|
||||
rank: int,
|
||||
num_ranks: int,
|
||||
BN: int = 128,
|
||||
cta_group: int = 1,
|
||||
all_reduce: bool = False,
|
||||
dtype: str = "bf16",
|
||||
) -> None:
|
||||
assert dtype in ("bf16", "mxfp8")
|
||||
self.rank = rank
|
||||
self.num_ranks = num_ranks
|
||||
BM, BK = 128, 64
|
||||
BM = 128
|
||||
BN = 128
|
||||
BK = {"bf16": 64, "mxfp8": 128}[dtype] # 128B
|
||||
self.cta_tile = (BM, BN, BK)
|
||||
self.cta_group = cta_group
|
||||
self.all_reduce = all_reduce
|
||||
self.dtype = dtype
|
||||
|
||||
smem_bytes = get_smem_capacity_in_bytes()
|
||||
self.stage_size = (BM + (BN // cta_group)) * BK * 2
|
||||
if dtype == "bf16":
|
||||
self.stage_size = (BM + (BN // cta_group)) * BK * 2
|
||||
elif dtype == "mxfp8":
|
||||
self.stage_size = (BM + (BN // cta_group)) * BK + (BM + BN) * (BK // 32)
|
||||
self.num_stages = smem_bytes // self.stage_size
|
||||
|
||||
@cute.jit
|
||||
@@ -124,11 +153,36 @@ class Sm100GemmRsArBF16:
|
||||
layout = cute.make_composed_layout(swizzle_128b, 0, layout)
|
||||
return cpasync.make_tiled_tma_atom(tma_op, tensor, layout, (BM, BK))
|
||||
|
||||
@cute.jit
|
||||
def prepare_sf_tma(
|
||||
self,
|
||||
SF: cute.Tensor,
|
||||
R: Int32,
|
||||
Ksf: Int32,
|
||||
BR: cutlass.Constexpr,
|
||||
BKsf: cutlass.Constexpr,
|
||||
) -> cpasync.TmaInfo:
|
||||
tma_group = (
|
||||
tcgen05.CtaGroup.TWO if self.cta_group == 2 else tcgen05.CtaGroup.ONE
|
||||
)
|
||||
tma_op = cpasync.CopyBulkTensorTileG2SOp(cta_group=tma_group)
|
||||
# NVIDIA SF gmem layout: an [R, Ksf] scale grid padded to R % 128 == 0
|
||||
# and permuted as [R/128, Ksf/4, 32, 4, 4]. The trailing [32, 4, 4]
|
||||
# atom is the opaque 512B block tcgen05 expects, so treat it as bytes.
|
||||
# The Int64 recast keeps the TMA boxDim <= 256.
|
||||
g_layout = cute.make_layout((Ksf * 128, cute.ceil_div(R, 128)))
|
||||
SF_i64 = cute.recast_tensor(cute.make_tensor(SF.iterator, g_layout), Int64)
|
||||
tiler = (128 * BKsf // 8, BR // 128)
|
||||
layout = cute.make_layout((*tiler, self.num_stages))
|
||||
return cpasync.make_tiled_tma_atom(tma_op, SF_i64, layout, tiler)
|
||||
|
||||
@cute.jit
|
||||
def __call__(
|
||||
self,
|
||||
A: cute.Tensor,
|
||||
B: cute.Tensor,
|
||||
SFA: cute.Tensor,
|
||||
SFB: cute.Tensor,
|
||||
partial_uc: cute.Tensor,
|
||||
partial_mc_ptr: cute.Pointer,
|
||||
output: cute.Tensor,
|
||||
@@ -138,10 +192,17 @@ class Sm100GemmRsArBF16:
|
||||
grid_size: Int32,
|
||||
stream: CUstream,
|
||||
) -> None:
|
||||
M, K = A.shape
|
||||
N = B.shape[0]
|
||||
BM, BN, BK = self.cta_tile
|
||||
A_tma = self.prepare_tma(A, BM, BK)
|
||||
B_tma = self.prepare_tma(B, BN // self.cta_group, BK)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
SFA_tma = self.prepare_sf_tma(SFA, M, K // 32, BM, BK // 32)
|
||||
SFB_tma = self.prepare_sf_tma(SFB, N, K // 32, BN, BK // 32)
|
||||
else:
|
||||
SFA_tma = None
|
||||
SFB_tma = None
|
||||
padded_M = partial_uc.shape[0]
|
||||
partial_mc = cute.make_tensor(
|
||||
partial_mc_ptr,
|
||||
@@ -158,6 +219,8 @@ class Sm100GemmRsArBF16:
|
||||
self.kernel(
|
||||
A_tma,
|
||||
B_tma,
|
||||
SFA_tma,
|
||||
SFB_tma,
|
||||
partial_uc,
|
||||
partial_mc,
|
||||
output,
|
||||
@@ -171,6 +234,8 @@ class Sm100GemmRsArBF16:
|
||||
self,
|
||||
A_tma: cpasync.TmaInfo,
|
||||
B_tma: cpasync.TmaInfo,
|
||||
SFA_tma: cpasync.TmaInfo,
|
||||
SFB_tma: cpasync.TmaInfo,
|
||||
partial_uc: cute.Tensor,
|
||||
partial_mc: cute.Tensor,
|
||||
output: cute.Tensor,
|
||||
@@ -190,25 +255,33 @@ class Sm100GemmRsArBF16:
|
||||
|
||||
is_2cta = cta_group == 2
|
||||
cta_rank = raw_bid % self.cta_group
|
||||
num_tmem_stages = 512 // BN
|
||||
|
||||
# MXFP8 reserves the last 16 tmem columns (496-512) for the A/B scale
|
||||
# factors.
|
||||
num_tmem_stages = (496 if self.dtype == "mxfp8" else 512) // BN
|
||||
|
||||
smem = utils.SmemAllocator()
|
||||
sA = smem.allocate_tensor(
|
||||
BFloat16,
|
||||
A_tma.atom.value_type,
|
||||
A_tma.smem_layout.outer,
|
||||
byte_alignment=128,
|
||||
swizzle=A_tma.smem_layout.inner,
|
||||
)
|
||||
sB = smem.allocate_tensor(
|
||||
BFloat16,
|
||||
B_tma.atom.value_type,
|
||||
B_tma.smem_layout.outer,
|
||||
byte_alignment=128,
|
||||
swizzle=B_tma.smem_layout.inner,
|
||||
)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
sSFA = smem.allocate_tensor(Int64, SFA_tma.smem_layout, byte_alignment=128)
|
||||
sSFB = smem.allocate_tensor(Int64, SFB_tma.smem_layout, byte_alignment=128)
|
||||
|
||||
tma_full_mbar = smem.allocate_array(Int64, num_stages)
|
||||
tma_empty_mbar = smem.allocate_array(Int64, num_stages)
|
||||
tmem_full_mbar = smem.allocate_array(Int64, num_tmem_stages)
|
||||
tmem_empty_mbar = smem.allocate_array(Int64, num_tmem_stages)
|
||||
|
||||
taddr = smem.allocate(Int32, 4)
|
||||
|
||||
# Named barriers
|
||||
@@ -238,6 +311,9 @@ class Sm100GemmRsArBF16:
|
||||
elif warp_id == 1:
|
||||
cpasync.prefetch_descriptor(A_tma.atom)
|
||||
cpasync.prefetch_descriptor(B_tma.atom)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
cpasync.prefetch_descriptor(SFA_tma.atom)
|
||||
cpasync.prefetch_descriptor(SFB_tma.atom)
|
||||
|
||||
if cutlass.const_expr(is_2cta):
|
||||
cute.arch.cluster_arrive_relaxed()
|
||||
@@ -261,12 +337,22 @@ class Sm100GemmRsArBF16:
|
||||
# [(BM, BK), (M/BM, K/BK)]
|
||||
gA_tiles = cute.zipped_divide(A_tma.tma_tensor, (BM, BK))
|
||||
gB_tiles = cute.zipped_divide(B_tma.tma_tensor, (BN // cta_group, BK))
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
BKsf = BK // 32
|
||||
gSFA_tiles = cute.zipped_divide(
|
||||
SFA_tma.tma_tensor, (128 * BKsf // 8, BM // 128)
|
||||
)
|
||||
gSFB_tiles = cute.zipped_divide(
|
||||
SFB_tma.tma_tensor, (128 * BKsf // 8, BN // 128)
|
||||
)
|
||||
|
||||
for bid in range(raw_bid, total_tiles, num_bids):
|
||||
bid_m = bid % grid_m
|
||||
bid_n = bid // grid_m
|
||||
if cutlass.const_expr(cta_group == 2):
|
||||
bid_n = bid_n * cta_group + cta_rank
|
||||
bid_n_b = bid_n * cta_group + cta_rank
|
||||
else:
|
||||
bid_n_b = bid_n
|
||||
|
||||
for iter_k in cutlass.range(cute.ceil_div(K, BK), unroll=1):
|
||||
mbar = tma_full_mbar_ + tma_stage
|
||||
@@ -282,10 +368,23 @@ class Sm100GemmRsArBF16:
|
||||
)
|
||||
simple_tma_copy(
|
||||
B_tma.atom,
|
||||
gB_tiles[None, (bid_n, iter_k)],
|
||||
gB_tiles[None, (bid_n_b, iter_k)],
|
||||
sB[None, None, tma_stage],
|
||||
mbar,
|
||||
)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
simple_tma_copy(
|
||||
SFA_tma.atom,
|
||||
gSFA_tiles[None, (iter_k, bid_m)],
|
||||
sSFA[None, None, tma_stage],
|
||||
mbar,
|
||||
)
|
||||
simple_tma_copy(
|
||||
SFB_tma.atom,
|
||||
gSFB_tiles[None, (iter_k, bid_n)],
|
||||
sSFB[None, None, tma_stage],
|
||||
mbar,
|
||||
)
|
||||
|
||||
tma_stage = (tma_stage + 1) % num_stages
|
||||
if tma_stage == 0:
|
||||
@@ -303,8 +402,15 @@ class Sm100GemmRsArBF16:
|
||||
|
||||
MMA_M = BM * cta_group
|
||||
MMA_N = BN
|
||||
idesc = _tcgen05.make_bf16_idesc(MMA_M, MMA_N)
|
||||
sdesc = _tcgen05.make_sdesc_128B_swizzle(0)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
# SF smem descriptor: no swizzle, SBO = 8 * 16 bytes.
|
||||
sdesc_sf = Uint64((8 << 32) | (1 << 46))
|
||||
sfa_tmem = 496
|
||||
sfb_tmem = sfa_tmem + 4
|
||||
idesc = _tcgen05.make_mxfp8_idesc(MMA_M, MMA_N)
|
||||
else:
|
||||
idesc = _tcgen05.make_bf16_idesc(MMA_M, MMA_N)
|
||||
multicast_mask = Uint16((1 << self.cta_group) - 1)
|
||||
|
||||
for bid in range(raw_bid, total_tiles, num_bids):
|
||||
@@ -319,17 +425,54 @@ class Sm100GemmRsArBF16:
|
||||
b_addr = sB[None, None, tma_stage].iterator.toint()
|
||||
a_desc = sdesc | (a_addr >> 4)
|
||||
b_desc = sdesc | (b_addr >> 4)
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
sfa_desc = sdesc_sf | (
|
||||
sSFA[None, None, tma_stage].iterator.toint() >> 4
|
||||
)
|
||||
sfb_desc = sdesc_sf | (
|
||||
sSFB[None, None, tma_stage].iterator.toint() >> 4
|
||||
)
|
||||
|
||||
cute.arch.mbarrier_wait(
|
||||
tma_full_mbar + tma_stage, tma_full_parity
|
||||
)
|
||||
_tcgen05.fence_after_thread_sync()
|
||||
|
||||
for mma_k in cutlass.range_constexpr(BK // 16):
|
||||
enable_d = iter_k > 0 or mma_k > 0
|
||||
_tcgen05.mma_f16(
|
||||
d_tmem, a_desc, b_desc, idesc, enable_d, cta_group
|
||||
# load SF from smem->tmem
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
_tcgen05.cp(
|
||||
sfa_tmem, sfa_desc, "32x128b", "warpx4", cta_group
|
||||
)
|
||||
for j in cutlass.range_constexpr(BN // 128):
|
||||
_tcgen05.cp(
|
||||
sfb_tmem + j * 4,
|
||||
sfb_desc,
|
||||
"32x128b",
|
||||
"warpx4",
|
||||
cta_group,
|
||||
)
|
||||
sfb_desc += (128 * 4) >> 4
|
||||
|
||||
# 4 = 128B / 32B
|
||||
for mma_k in cutlass.range_constexpr(4):
|
||||
enable_d = iter_k > 0 or mma_k > 0
|
||||
if cutlass.const_expr(self.dtype == "mxfp8"):
|
||||
# select SF IDs
|
||||
idesc_k = idesc + ((mma_k << 4) | (mma_k << 29))
|
||||
_tcgen05.mma_mxfp8(
|
||||
d_tmem,
|
||||
a_desc,
|
||||
b_desc,
|
||||
idesc_k,
|
||||
sfa_tmem,
|
||||
sfb_tmem,
|
||||
enable_d,
|
||||
cta_group,
|
||||
)
|
||||
else:
|
||||
_tcgen05.mma_f16(
|
||||
d_tmem, a_desc, b_desc, idesc, enable_d, cta_group
|
||||
)
|
||||
a_desc += 32 >> 4
|
||||
b_desc += 32 >> 4
|
||||
_tcgen05.commit(
|
||||
@@ -638,9 +781,9 @@ class Sm100GemmRsArBF16:
|
||||
def compile(
|
||||
rank: int,
|
||||
num_ranks: int,
|
||||
BN: int,
|
||||
cta_group: int,
|
||||
all_reduce: bool = False,
|
||||
dtype: str = "bf16",
|
||||
):
|
||||
M = cute.sym_int()
|
||||
padded_M = cute.sym_int()
|
||||
@@ -649,12 +792,37 @@ class Sm100GemmRsArBF16:
|
||||
local_M = cute.sym_int()
|
||||
num_flags = cute.sym_int()
|
||||
|
||||
ab_dtype = Float8E4M3FN if dtype == "mxfp8" else BFloat16
|
||||
# Row stride must keep rows 16B-aligned: 8 BF16 or 16 FP8 elements.
|
||||
row_div = 16 if dtype == "mxfp8" else 8
|
||||
A = make_fake_tensor(
|
||||
BFloat16, (M, K), (cute.sym_int64(divisibility=8), 1), assumed_align=16
|
||||
ab_dtype,
|
||||
(M, K),
|
||||
(cute.sym_int64(divisibility=row_div), 1),
|
||||
assumed_align=16,
|
||||
)
|
||||
B = make_fake_tensor(
|
||||
BFloat16, (N, K), (cute.sym_int64(divisibility=8), 1), assumed_align=16
|
||||
ab_dtype,
|
||||
(N, K),
|
||||
(cute.sym_int64(divisibility=row_div), 1),
|
||||
assumed_align=16,
|
||||
)
|
||||
if dtype == "mxfp8":
|
||||
SFA = make_fake_tensor(
|
||||
Float8E8M0FNU,
|
||||
(cute.sym_int(divisibility=512),),
|
||||
(1,),
|
||||
assumed_align=16,
|
||||
)
|
||||
SFB = make_fake_tensor(
|
||||
Float8E8M0FNU,
|
||||
(cute.sym_int(divisibility=512),),
|
||||
(1,),
|
||||
assumed_align=16,
|
||||
)
|
||||
else:
|
||||
SFA = None
|
||||
SFB = None
|
||||
partial = make_fake_tensor(
|
||||
BFloat16,
|
||||
(padded_M, N),
|
||||
@@ -677,13 +845,15 @@ class Sm100GemmRsArBF16:
|
||||
peer_flag_ptr = nullptr(Int64, cute.AddressSpace.gmem, assumed_align=8)
|
||||
|
||||
stream = make_fake_stream(use_tvm_ffi_env_stream=True)
|
||||
kernel = Sm100GemmRsArBF16(
|
||||
rank, num_ranks, BN, cta_group, all_reduce=all_reduce
|
||||
kernel = Sm100GemmRsAr(
|
||||
rank, num_ranks, cta_group, all_reduce=all_reduce, dtype=dtype
|
||||
)
|
||||
return cute.compile(
|
||||
kernel,
|
||||
A,
|
||||
B,
|
||||
SFA,
|
||||
SFB,
|
||||
partial,
|
||||
partial_mc_ptr,
|
||||
output,
|
||||
@@ -697,7 +867,7 @@ class Sm100GemmRsArBF16:
|
||||
|
||||
|
||||
class GemmRsAr:
|
||||
"""Own the symmetric workspace for Kimi-K3 GEMM-RS/AR launches.
|
||||
"""Own the symmetric workspace for GEMM-RS/AR launches.
|
||||
|
||||
All TP ranks must belong to one NVLink domain for multimem instructions.
|
||||
|
||||
@@ -727,6 +897,7 @@ class GemmRsAr:
|
||||
self.N = N
|
||||
self.device = device
|
||||
self.all_reduce = all_reduce
|
||||
self.dtypes: set[str] = set()
|
||||
|
||||
self.partial = symm_mem.empty((max_M, N), dtype=torch.bfloat16, device=device)
|
||||
self.partial_handle = symm_mem.rendezvous(self.partial, group)
|
||||
@@ -766,22 +937,41 @@ class GemmRsAr:
|
||||
tp_group.barrier()
|
||||
|
||||
def can_run(self, linear: LinearBase) -> bool:
|
||||
# Validate projection-invariant requirements once during model init.
|
||||
# only supports BF16 for now
|
||||
if not isinstance(linear.quant_method, UnquantizedLinearMethod):
|
||||
return False
|
||||
w = linear.weight
|
||||
if w.ndim != 2:
|
||||
return False
|
||||
K = w.shape[1]
|
||||
return (
|
||||
w.shape == (self.N, K)
|
||||
and K % 64 == 0
|
||||
and w.dtype == torch.bfloat16
|
||||
and w.device == self.device
|
||||
and w.is_contiguous()
|
||||
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
FlashInferCutlassMxfp8LinearKernel,
|
||||
)
|
||||
|
||||
# Called before weight loading; online quantization starts on meta.
|
||||
if isinstance(linear.quant_method, UnquantizedLinearMethod):
|
||||
dtype, k_alignment = "bf16", 64
|
||||
if linear.weight.dtype != torch.bfloat16:
|
||||
return False
|
||||
else:
|
||||
method = getattr(linear, "scheme", linear.quant_method)
|
||||
kernel = getattr(method, "kernel", None)
|
||||
if not isinstance(
|
||||
kernel,
|
||||
(
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
FlashInferCutlassMxfp8LinearKernel,
|
||||
),
|
||||
):
|
||||
return False
|
||||
dtype, k_alignment = "mxfp8", 128
|
||||
|
||||
w = linear.weight
|
||||
if (
|
||||
w.ndim != 2
|
||||
or w.shape[0] != self.N
|
||||
or w.shape[1] % k_alignment != 0
|
||||
or (w.device != self.device and not w.is_meta)
|
||||
or not w.is_contiguous()
|
||||
):
|
||||
return False
|
||||
self.dtypes.add(dtype)
|
||||
return True
|
||||
|
||||
def warn_incompatible_projection(self) -> None:
|
||||
logger.warning_once(
|
||||
"Some projections are incompatible with GEMM-RS/AR; using the "
|
||||
@@ -794,18 +984,51 @@ class GemmRsAr:
|
||||
# supported but faster on the existing LL path.
|
||||
return x.shape[0] >= 128
|
||||
|
||||
def __call__(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
|
||||
def apply(self, x: torch.Tensor, linear: LinearBase) -> torch.Tensor:
|
||||
from vllm.model_executor.kernels.linear.mxfp8.flashinfer import (
|
||||
FlashInferCutedslMxfp8LinearKernel,
|
||||
)
|
||||
|
||||
method = getattr(linear, "scheme", linear.quant_method)
|
||||
w = linear.weight
|
||||
if isinstance(
|
||||
getattr(method, "kernel", None), FlashInferCutedslMxfp8LinearKernel
|
||||
):
|
||||
# This backend stores a column-major [K, N] view after loading.
|
||||
w = w.t()
|
||||
w_sf = getattr(linear, "weight_scale", None)
|
||||
|
||||
assert x.ndim == 2
|
||||
M, K = x.shape
|
||||
assert 0 < M <= self.max_M
|
||||
assert w.shape == (self.N, K) and K % 64 == 0
|
||||
assert w.dtype == torch.bfloat16
|
||||
assert w.device == self.device
|
||||
assert w.is_contiguous()
|
||||
assert x.dtype == torch.bfloat16
|
||||
assert x.device == self.device
|
||||
assert x.is_contiguous()
|
||||
N = w.shape[0]
|
||||
assert w.device == self.device
|
||||
N = self.N
|
||||
dtype = "mxfp8" if w.dtype == torch.float8_e4m3fn else "bf16"
|
||||
x_sf = None
|
||||
if dtype == "mxfp8":
|
||||
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
|
||||
mxfp8_e4m3_quantize,
|
||||
)
|
||||
|
||||
assert w_sf is not None
|
||||
assert w_sf.dtype == torch.uint8 and w_sf.device == self.device
|
||||
assert w_sf.ndim == 1 and w_sf.is_contiguous()
|
||||
assert w_sf.numel() == N * (K // 32)
|
||||
assert w.shape == (N, K) and K % 128 == 0
|
||||
assert w.is_contiguous()
|
||||
x, x_sf = mxfp8_e4m3_quantize(x, is_sf_swizzled_layout=True)
|
||||
# The kernel declares the scales as E8M0; the stored/quantized
|
||||
# tensors carry the same bits as uint8.
|
||||
x_sf = x_sf.view(torch.float8_e8m0fnu)
|
||||
w_sf = w_sf.view(torch.float8_e8m0fnu)
|
||||
else:
|
||||
assert w_sf is None
|
||||
assert w.shape == (N, K) and K % 64 == 0
|
||||
assert w.dtype == torch.bfloat16
|
||||
assert w.is_contiguous()
|
||||
padded_M = (M + self.world_size - 1) // self.world_size
|
||||
padded_M *= self.world_size
|
||||
local_M = padded_M // self.world_size
|
||||
@@ -814,10 +1037,8 @@ class GemmRsAr:
|
||||
# Avoid padding small odd grids; 2-CTA wins consistently for M >= 1024.
|
||||
cta_group = 2 if M >= 1024 or grid_m % 2 == 0 else 1
|
||||
grid_m = (grid_m + cta_group - 1) // cta_group * cta_group
|
||||
BN = 256 if M * K >= 24 * 1024 * 1024 else 128
|
||||
assert N % BN == 0
|
||||
|
||||
num_tiles = grid_m * (N // BN)
|
||||
num_tiles = grid_m * (N // 128)
|
||||
num_ctas = min(num_tiles, self.num_sms)
|
||||
num_ctas = num_ctas // cta_group * cta_group
|
||||
assert self.flags.numel() >= num_tiles + num_ctas
|
||||
@@ -825,16 +1046,26 @@ class GemmRsAr:
|
||||
output = None
|
||||
if not self.all_reduce:
|
||||
output = torch.empty((local_M, N), dtype=torch.bfloat16, device=self.device)
|
||||
compiled = Sm100GemmRsArBF16.compile(
|
||||
# The kernel never touches rows at or beyond M. Callers that hand
|
||||
# in an unpadded M (DeepSeek-V4.1 slices the SP all-gather back to
|
||||
# the real token count) expect the same zero padding rows that
|
||||
# ``sp_reduce_scatter`` produces, so clear them here. This is a
|
||||
# no-op whenever M is already a multiple of the TP size.
|
||||
valid_rows = min(max(M - self.rank * local_M, 0), local_M)
|
||||
if valid_rows < local_M:
|
||||
output[valid_rows:].zero_()
|
||||
compiled = Sm100GemmRsAr.compile(
|
||||
self.rank,
|
||||
self.world_size,
|
||||
BN,
|
||||
cta_group,
|
||||
self.all_reduce,
|
||||
dtype=dtype,
|
||||
)
|
||||
compiled(
|
||||
x,
|
||||
w,
|
||||
x_sf,
|
||||
w_sf,
|
||||
self.partial[:padded_M],
|
||||
self.partial_mc_ptr,
|
||||
output,
|
||||
@@ -871,22 +1102,74 @@ def init_gemm_rs_ar(max_M: int, N: int, *, all_reduce: bool = False) -> None:
|
||||
_gemm_rs_ar = GemmRsAr(max_M=max_M, N=N, all_reduce=all_reduce)
|
||||
|
||||
|
||||
def maybe_init_gemm_rs_ar(
|
||||
vllm_config: "VllmConfig", *, N: int, all_reduce: bool
|
||||
) -> bool:
|
||||
"""Collectively initialize the mode-bound GEMM-RS/AR state if supported.
|
||||
|
||||
Callers gate on their own feature flag first; this checks the worker
|
||||
topology (SM100-family CUDA, BF16 model dtype, no ubatching, a TP size in
|
||||
2-16 that divides 128) and the NVLink multicast rendezvous. Returns whether
|
||||
projections may bind to the kernel through ``get_gemm_rs_ar().can_run``.
|
||||
"""
|
||||
mode = "GEMM-AR" if all_reduce else "GEMM-RS"
|
||||
parallel_config = vllm_config.parallel_config
|
||||
tp_size = parallel_config.tensor_parallel_size
|
||||
if parallel_config.use_ubatching:
|
||||
reason = "ubatching is enabled"
|
||||
elif vllm_config.model_config.dtype != torch.bfloat16:
|
||||
reason = "the model dtype is not BF16"
|
||||
elif not current_platform.is_cuda():
|
||||
reason = "the device is not CUDA"
|
||||
elif not current_platform.is_device_capability_family(100):
|
||||
reason = "the device is not SM100-family"
|
||||
elif not 1 < tp_size <= 16:
|
||||
reason = "TP size is not in the supported range 2-16"
|
||||
elif 128 % tp_size != 0:
|
||||
reason = "TP size does not divide 128"
|
||||
elif N % 128 != 0:
|
||||
reason = f"the output width {N} is not a multiple of 128"
|
||||
else:
|
||||
reason = None
|
||||
|
||||
if reason is not None:
|
||||
logger.warning_once("%s is disabled because %s.", mode, reason)
|
||||
return False
|
||||
|
||||
try:
|
||||
init_gemm_rs_ar(
|
||||
max_M=vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
N=N,
|
||||
all_reduce=all_reduce,
|
||||
)
|
||||
except RuntimeError as e:
|
||||
logger.warning_once(
|
||||
"%s is disabled because initialization failed: %s. This may mean "
|
||||
"the TP ranks do not share one NVLink domain.",
|
||||
mode,
|
||||
e,
|
||||
)
|
||||
return False
|
||||
logger.info_once("%s is enabled.", mode)
|
||||
return True
|
||||
|
||||
|
||||
def warmup_gemm_rs_ar() -> int:
|
||||
"""Compile every reachable dispatch for the initialized GEMM-RS/AR mode."""
|
||||
# Initialization can be disabled or fail when multicast is unavailable.
|
||||
if _gemm_rs_ar is None:
|
||||
return 0
|
||||
# Keep these profiles in sync with the dispatch in GemmRsAr.__call__.
|
||||
profiles = ((128, 1), (128, 2), (256, 2))
|
||||
for BN, cta_group in profiles:
|
||||
Sm100GemmRsArBF16.compile(
|
||||
_gemm_rs_ar.rank,
|
||||
_gemm_rs_ar.world_size,
|
||||
BN,
|
||||
cta_group,
|
||||
_gemm_rs_ar.all_reduce,
|
||||
)
|
||||
return len(profiles)
|
||||
|
||||
for dtype in sorted(_gemm_rs_ar.dtypes):
|
||||
for cta_group in (1, 2):
|
||||
Sm100GemmRsAr.compile(
|
||||
_gemm_rs_ar.rank,
|
||||
_gemm_rs_ar.world_size,
|
||||
cta_group,
|
||||
_gemm_rs_ar.all_reduce,
|
||||
dtype=dtype,
|
||||
)
|
||||
return 2 * len(_gemm_rs_ar.dtypes)
|
||||
|
||||
|
||||
def get_gemm_rs_ar() -> GemmRsAr:
|
||||
@@ -24,7 +24,7 @@ class HummingLinearKernel(MPLinearKernel):
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
@@ -57,13 +57,14 @@ class HummingLinearKernel(MPLinearKernel):
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
)
|
||||
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.nn.parameter import Parameter
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import (
|
||||
dequant_mxfp4,
|
||||
@@ -97,7 +98,16 @@ class EmulationMxfp4LinearKernel(MxFp4LinearKernel):
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
layer.weight_scale = Parameter(layer.weight_scale.data, requires_grad=False)
|
||||
weight_scale = Parameter(layer.weight_scale.data, requires_grad=False)
|
||||
|
||||
# Match the MXFP8 emulation path when explicitly enabled: dequantize
|
||||
# once at load time so inference uses a plain high-precision linear.
|
||||
# Otherwise retain packed weights and dequantize per invocation.
|
||||
if envs.VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD:
|
||||
weight = dequant_mxfp4(layer.weight, weight_scale, torch.bfloat16)
|
||||
layer.weight = Parameter(weight.contiguous(), requires_grad=False)
|
||||
|
||||
layer.weight_scale = weight_scale
|
||||
|
||||
def apply_weights(
|
||||
self,
|
||||
@@ -105,6 +115,12 @@ class EmulationMxfp4LinearKernel(MxFp4LinearKernel):
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
dq_w = dequant_mxfp4(layer.weight, layer.weight_scale, x.dtype)
|
||||
qdq_x = self.quant_dequant_func(x)
|
||||
|
||||
# Packed MXFP4 weights use one byte for two values. A weight with
|
||||
# elements wider than one byte was already dequantized at load time.
|
||||
if layer.weight.element_size() >= 2:
|
||||
return F.linear(qdq_x, layer.weight.to(x.dtype), bias)
|
||||
|
||||
dq_w = dequant_mxfp4(layer.weight, layer.weight_scale, x.dtype)
|
||||
return F.linear(qdq_x, dq_w, bias)
|
||||
|
||||
@@ -3,21 +3,18 @@
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
quant_key_to_input_schema,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp4Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
from .base import MxFp4LinearKernel, MxFp4LinearLayerConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class HummingMxFp4LinearKernel(MxFp4LinearKernel):
|
||||
"""Humming GEMM Kernel for MXFP4."""
|
||||
@@ -39,14 +36,10 @@ class HummingMxFp4LinearKernel(MxFp4LinearKernel):
|
||||
|
||||
@classmethod
|
||||
def can_implement(cls, config: MxFp4LinearLayerConfig) -> tuple[bool, str | None]:
|
||||
if config.activation_quant_key not in (None, kMxfp4Dynamic):
|
||||
return False, "only supports MXFP4 dynamic or unquantized activations"
|
||||
if config.activation_quant_key is not None:
|
||||
logger.warning_once(
|
||||
"HummingMxFp4LinearKernel is a weight-only (A16) kernel; "
|
||||
"the requested activation quantization (%s) is ignored.",
|
||||
config.activation_quant_key,
|
||||
)
|
||||
try:
|
||||
quant_key_to_input_schema(config.activation_quant_key)
|
||||
except ValueError as error:
|
||||
return False, str(error)
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
@@ -62,7 +55,10 @@ class HummingMxFp4LinearKernel(MxFp4LinearKernel):
|
||||
}
|
||||
|
||||
convert_linear_layer_to_humming_standard(layer=layer, name_map=name_map)
|
||||
self.layer_config = prepare_humming_linear_layer_config(layer, quant_config)
|
||||
input_schema = quant_key_to_input_schema(self.config.activation_quant_key)
|
||||
self.layer_config = prepare_humming_linear_layer_config(
|
||||
layer, quant_config, input_schema=input_schema
|
||||
)
|
||||
self.compute_config = get_humming_linear_compute_config()
|
||||
self.locks = torch.zeros(1024, dtype=torch.int32, device=layer.weight.device)
|
||||
|
||||
@@ -75,6 +71,7 @@ class HummingMxFp4LinearKernel(MxFp4LinearKernel):
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
|
||||
@@ -13,8 +13,8 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
|
||||
class MxFp6LinearLayerConfig:
|
||||
"""Configuration for an MXFP6 linear layer.
|
||||
|
||||
All MXFP6 layers share the same structure: packed uint8 weights (2 FP4 values per
|
||||
byte) and per-block weight scales (group size 32).
|
||||
All MXFP6 layers share the same structure: packed uint8 weights (4 FP6 values
|
||||
per 3 bytes) and per-block weight scales (group size 32).
|
||||
|
||||
Attributes:
|
||||
weight_quant_key: Identifies the weight quantization format. Can be
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
quant_key_to_input_schema,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp6E2M3Static
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
from .base import MxFp6LinearKernel, MxFp6LinearLayerConfig
|
||||
|
||||
|
||||
class HummingMxFp6LinearKernel(MxFp6LinearKernel):
|
||||
"""Humming GEMM for packed MXFP6 E2M3 and E3M2 weights."""
|
||||
|
||||
@classmethod
|
||||
def is_supported(
|
||||
cls, compute_capability: int | None = None
|
||||
) -> tuple[bool, str | None]:
|
||||
if not current_platform.is_cuda():
|
||||
return False, "Humming only supported on CUDA"
|
||||
|
||||
if not has_humming():
|
||||
return False, "Humming is not installed"
|
||||
|
||||
if not current_platform.has_device_capability(75):
|
||||
return False, "Humming only supported on SM75+"
|
||||
|
||||
return True, None
|
||||
|
||||
@classmethod
|
||||
def can_implement(cls, config: MxFp6LinearLayerConfig) -> tuple[bool, str | None]:
|
||||
try:
|
||||
quant_key_to_input_schema(config.activation_quant_key)
|
||||
except ValueError as error:
|
||||
return False, str(error)
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
weight_dtype = "float6e3m2"
|
||||
if self.config.weight_quant_key == kMxfp6E2M3Static:
|
||||
weight_dtype = "float6e2m3"
|
||||
|
||||
quant_config = {
|
||||
"quant_method": "humming",
|
||||
"dtype": weight_dtype,
|
||||
"scale_dtype": "float8e8m0",
|
||||
"group_size": 32,
|
||||
"weight_scale_type": "group",
|
||||
}
|
||||
layer.weight_scale.data = layer.weight_scale.data.view(torch.float8_e8m0fnu)
|
||||
|
||||
convert_linear_layer_to_humming_standard(
|
||||
layer=layer,
|
||||
name_map={"weight": "weight", "weight_scale": "weight_scale"},
|
||||
)
|
||||
input_schema = quant_key_to_input_schema(self.config.activation_quant_key)
|
||||
self.layer_config = prepare_humming_linear_layer_config(
|
||||
layer, quant_config, input_schema=input_schema
|
||||
)
|
||||
self.compute_config = get_humming_linear_compute_config()
|
||||
self.locks = torch.zeros(1024, dtype=torch.int32, device=layer.weight.device)
|
||||
|
||||
def apply_weights(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
)
|
||||
@@ -3,12 +3,14 @@
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
quant_key_to_input_schema,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
@@ -50,7 +52,10 @@ class HummingMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
}
|
||||
|
||||
convert_linear_layer_to_humming_standard(layer=layer, name_map=name_map)
|
||||
self.layer_config = prepare_humming_linear_layer_config(layer, quant_config)
|
||||
input_schema = quant_key_to_input_schema(kMxfp8Dynamic)
|
||||
self.layer_config = prepare_humming_linear_layer_config(
|
||||
layer, quant_config, input_schema=input_schema
|
||||
)
|
||||
self.compute_config = get_humming_linear_compute_config()
|
||||
self.locks = torch.zeros(1024, dtype=torch.int32, device=layer.weight.device)
|
||||
|
||||
@@ -63,6 +68,7 @@ class HummingMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
quant_key_to_input_schema,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kNvfp4Dynamic
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
@@ -40,9 +42,7 @@ class HummingNvFp4LinearKernel(NvFp4LinearKernel):
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
# Route through humming's compressed-tensors nvfp4 loader (same path as
|
||||
# the MoE oracle); the native group_tensor schema mishandles a scalar
|
||||
# global scale.
|
||||
# Reuse the CT loader for packed FP4 weights and tensor scales.
|
||||
quant_config = {
|
||||
"quant_method": "compressed-tensors",
|
||||
"format": "nvfp4-pack-quantized",
|
||||
@@ -60,7 +60,16 @@ class HummingNvFp4LinearKernel(NvFp4LinearKernel):
|
||||
layer.weight_global_scale = torch.nn.Parameter(
|
||||
1.0 / layer.weight_global_scale, requires_grad=False
|
||||
)
|
||||
self.layer_config = prepare_humming_linear_layer_config(layer, quant_config)
|
||||
input_quant_key = None
|
||||
if hasattr(layer, "input_global_scale"):
|
||||
layer.input_scale_2 = torch.nn.Parameter(
|
||||
layer.input_global_scale.reshape(-1), requires_grad=False
|
||||
)
|
||||
input_quant_key = kNvfp4Dynamic
|
||||
input_schema = quant_key_to_input_schema(input_quant_key)
|
||||
self.layer_config = prepare_humming_linear_layer_config(
|
||||
layer, quant_config, input_schema=input_schema
|
||||
)
|
||||
self.compute_config = get_humming_linear_compute_config()
|
||||
self.locks = torch.zeros(1024, dtype=torch.int32, device=layer.weight.device)
|
||||
|
||||
@@ -73,6 +82,7 @@ class HummingNvFp4LinearKernel(NvFp4LinearKernel):
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
apply_humming_linear,
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
@@ -92,6 +92,7 @@ class HummingFP8ScaledMMLinearKernel(FP8ScaledMMLinearKernel):
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
@@ -158,6 +159,7 @@ class HummingInt8ScaledMMLinearKernel(Int8ScaledMMLinearKernel):
|
||||
return apply_humming_linear(
|
||||
layer,
|
||||
x,
|
||||
skip_bias_add=bias is None,
|
||||
layer_config=self.layer_config,
|
||||
compute_config=self.compute_config,
|
||||
locks=self.locks,
|
||||
|
||||
@@ -305,8 +305,12 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
use_pre_mix_in: bool = False,
|
||||
save_pre_mix: bool = False,
|
||||
rms_numel: int = 0,
|
||||
split_mode: str = "fused",
|
||||
write_aux: bool = False,
|
||||
):
|
||||
# Split modes require shifted mHC: input collapse uses a carried pre-mix.
|
||||
assert split_mode in ("fused", "stats", "input")
|
||||
assert split_mode == "fused" or save_pre_mix
|
||||
num_tokens = T.dynamic("num_tokens")
|
||||
hc_mult3 = hc_mult * (2 + hc_mult)
|
||||
if gemm_last_dim < 0:
|
||||
@@ -330,26 +334,26 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
aux_out: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type]
|
||||
|
||||
with T.Kernel(num_tokens, threads=96) as i:
|
||||
rms = T.alloc_fragment(1, T.float32)
|
||||
mixes = T.alloc_fragment(hc_mult3, T.float32)
|
||||
T.clear(mixes)
|
||||
rms[0] = 0
|
||||
|
||||
if ENABLE_PDL:
|
||||
T.pdl_sync()
|
||||
|
||||
for i_split in T.serial(n_splits):
|
||||
rms[0] += gemm_out_sqrsum[i_split, i]
|
||||
rms[0] = T.rsqrt(rms[0] / rms_numel + rms_eps)
|
||||
for j in T.Parallel(hc_mult3):
|
||||
mixes[j] = 0
|
||||
for i_split in T.serial(n_splits):
|
||||
mixes[j] += gemm_out_mul[i_split, i, j]
|
||||
mixes[j] *= rms[0]
|
||||
mixes_shared = T.alloc_shared(hc_mult3, T.float32)
|
||||
T.copy(mixes, mixes_shared)
|
||||
if split_mode != "input":
|
||||
rms = T.alloc_fragment(1, T.float32)
|
||||
mixes = T.alloc_fragment(hc_mult3, T.float32)
|
||||
T.clear(mixes)
|
||||
rms[0] = 0
|
||||
|
||||
if T.get_thread_binding() < 32:
|
||||
for i_split in T.serial(n_splits):
|
||||
rms[0] += gemm_out_sqrsum[i_split, i]
|
||||
rms[0] = T.rsqrt(rms[0] / rms_numel + rms_eps)
|
||||
for j in T.Parallel(hc_mult3):
|
||||
mixes[j] = 0
|
||||
for i_split in T.serial(n_splits):
|
||||
mixes[j] += gemm_out_mul[i_split, i, j]
|
||||
mixes[j] *= rms[0]
|
||||
T.copy(mixes, mixes_shared)
|
||||
|
||||
if split_mode != "input" and T.get_thread_binding() < 32:
|
||||
cm = T.alloc_fragment((hc_mult, hc_mult), T.float32)
|
||||
for j in T.Parallel(hc_mult):
|
||||
if save_pre_mix:
|
||||
@@ -395,7 +399,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
|
||||
for j, k in T.Parallel(hc_mult, hc_mult):
|
||||
comb_mix[i, j * hc_mult + k] = cm[j, k]
|
||||
else:
|
||||
elif split_mode != "stats" and T.get_thread_binding() >= 32:
|
||||
pre_mix_shared = T.alloc_shared(hc_mult, T.float32)
|
||||
for j in T.Parallel(hc_mult):
|
||||
if use_pre_mix_in:
|
||||
|
||||
@@ -36,6 +36,7 @@ class MHCPreNormKernel(VllmJitKernel["MHCPreNormKernel.CompileKey"]):
|
||||
use_pre_mix_in: bool
|
||||
rms_numel: int
|
||||
save_pre_mix: bool = True
|
||||
split_mode: str = "fused"
|
||||
write_aux: bool = False
|
||||
|
||||
kernel: Any = staticmethod(mhc_pre_big_fuse_with_norm_tilelang)
|
||||
|
||||
@@ -1553,7 +1553,10 @@ class _DecodeConcatQuantFP8(QuantFP8):
|
||||
scale: torch.Tensor,
|
||||
scale_ub: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
decode_q0 = torch.cat((decode_ql_nope, decode_q_pe), dim=-1)
|
||||
if decode_q_pe.shape[-1] == 0 and decode_ql_nope.is_contiguous():
|
||||
decode_q0 = decode_ql_nope
|
||||
else:
|
||||
decode_q0 = torch.cat((decode_ql_nope, decode_q_pe), dim=-1)
|
||||
decode_q_flat = decode_q0.reshape(decode_q0.shape[0], -1)
|
||||
decode_q, _ = quant_fn(self, decode_q_flat, scale, scale_ub)
|
||||
return decode_q.view(decode_q0.shape)
|
||||
|
||||
@@ -1282,6 +1282,7 @@ class FusedMoEConfig:
|
||||
elastic_ep_max_dp_size: int | None = None
|
||||
has_bias: bool = False
|
||||
is_lora_enabled: bool = False
|
||||
has_hash_routing: bool = False
|
||||
|
||||
# When True, the MoE skips its final cross-rank all-reduce (and the separate
|
||||
# shared-expert reduce), returning the partial per-rank sum. The caller is
|
||||
|
||||
@@ -321,7 +321,7 @@ class AiterW4A16ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
|
||||
moe_parallel_config: FusedMoEParallelConfig,
|
||||
) -> bool:
|
||||
return (
|
||||
not moe_parallel_config.use_all2all_kernels
|
||||
not moe_parallel_config.use_ep
|
||||
and not moe_parallel_config.enable_eplb
|
||||
and moe_parallel_config.dp_size <= 1
|
||||
)
|
||||
|
||||
@@ -246,7 +246,7 @@ class AiterW4A8ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
|
||||
moe_parallel_config: FusedMoEParallelConfig,
|
||||
) -> bool:
|
||||
return (
|
||||
not moe_parallel_config.use_all2all_kernels
|
||||
not moe_parallel_config.use_ep
|
||||
and not moe_parallel_config.enable_eplb
|
||||
and moe_parallel_config.dp_size <= 1
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
@@ -30,6 +31,7 @@ from vllm.model_executor.layers.fused_moe.moe_permute_unpermute import (
|
||||
get_moe_permute_scratch,
|
||||
moe_permute,
|
||||
moe_permute_unpermute_supported,
|
||||
moe_prepare_scatter,
|
||||
moe_unpermute,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
@@ -57,14 +59,16 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kMxfp8Static,
|
||||
kNvfp4Dynamic,
|
||||
kNvfp4Static,
|
||||
kStaticTensorScale,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.scalar_type import ScalarType
|
||||
from vllm.utils.import_utils import has_humming
|
||||
from vllm.utils.platform_utils import num_compute_units
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
HummingMoEQuantConfig,
|
||||
)
|
||||
from vllm.utils.humming import (
|
||||
@@ -118,38 +122,9 @@ def get_humming_moe_gemm_type(moe_config: FusedMoEConfig | None = None) -> str:
|
||||
return gemm_type
|
||||
|
||||
|
||||
def _fixup_moe_tuning_config(tuning_config: list, max_k_block: int = 128) -> None:
|
||||
"""Fix up each MoE tile in place: cap the K-block and widen warp-N.
|
||||
|
||||
- block_shape[2] (K-block) > ``max_k_block``: the driver rejects the TMA
|
||||
descriptor at launch (CUDA_ERROR_MISALIGNED_ADDRESS). Cap at 128, which
|
||||
Humming already uses for larger M.
|
||||
- warp_shape[1] (warp-N) < 32: block-FP8 (group-128) activations route the
|
||||
w13 (gate/up) GEMM to a tuning table that pins warp-N to 16, under-filling
|
||||
the Hopper WGMMA N dimension and corrupting the GEMM output (gsm8k
|
||||
0.94 -> 0.89). Widen to 32 whenever block_n % 32 == 0 -- on every tile,
|
||||
not just the K-capped ones. w2 (down) already uses warp_n=32.
|
||||
"""
|
||||
logger.info_once("Attempting to override humming GEMM config")
|
||||
for entry in tuning_config:
|
||||
config = entry[2]
|
||||
block_shape = config.get("block_shape")
|
||||
if not (block_shape and len(block_shape) == 3):
|
||||
continue
|
||||
block_m, block_n, block_k = block_shape
|
||||
|
||||
logger.info_once(f"Overriding humming GEMM config. Previous config\n: {config}")
|
||||
if block_k > max_k_block:
|
||||
config["block_shape"] = [block_m, block_n, max_k_block]
|
||||
|
||||
warp_shape = config.get("warp_shape")
|
||||
if warp_shape and warp_shape[1] < 32 and block_n % 32 == 0:
|
||||
config["warp_shape"] = [warp_shape[0], 32, warp_shape[2]]
|
||||
|
||||
logger.info_once(f"Overridden humming GEMM config. Current config\n: {config}")
|
||||
|
||||
|
||||
class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
quant_config: "HummingMoEQuantConfig"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
moe_config: FusedMoEConfig,
|
||||
@@ -165,7 +140,7 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
self.locks = torch.zeros(1024, dtype=torch.int32, device=moe_config.device)
|
||||
self.num_experts = moe_config.num_local_experts
|
||||
self.global_num_experts = moe_config.num_experts
|
||||
self.quant_config = quant_config
|
||||
self.quant_config = humming_quant_config
|
||||
self.init_humming_moe()
|
||||
|
||||
if self.is_batched():
|
||||
@@ -199,31 +174,61 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
gemm_type=self.humming_gemm_type(),
|
||||
)
|
||||
self.compute_config_str = json.dumps(self.compute_config)
|
||||
# Fix up the heuristic-chosen tiles before freezing to JSON -- see
|
||||
# _fixup_moe_tuning_config.
|
||||
_fixup_moe_tuning_config(self.w13_tuning_config)
|
||||
_fixup_moe_tuning_config(self.w2_tuning_config)
|
||||
self.w13_tuning_config_str = json.dumps(self.w13_tuning_config)
|
||||
self.w2_tuning_config_str = json.dumps(self.w2_tuning_config)
|
||||
|
||||
def quantize_input(
|
||||
def process_input(
|
||||
self,
|
||||
sublayer_name: str,
|
||||
inputs: torch.Tensor,
|
||||
quanted_input: torch.Tensor | None,
|
||||
input_scale: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
from vllm.utils.humming import may_quant_input
|
||||
|
||||
# input_scale is set for block-FP8 (group-128) activations that were
|
||||
# quantized before the EP dispatch: may_quant_input then skips the
|
||||
# redundant w13 quantization and forwards the pre-computed scale.
|
||||
return may_quant_input(
|
||||
self.humming_configs[sublayer_name],
|
||||
inputs=inputs,
|
||||
input_scale=input_scale,
|
||||
quanted_input=quanted_input,
|
||||
expert_tokens: torch.Tensor | None = None,
|
||||
activation: MoEActivation | None = None,
|
||||
scatter_idx: torch.Tensor | None = None,
|
||||
num_valid_tokens: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
||||
from vllm.model_executor.layers.quantization.utils.humming.activation import (
|
||||
get_humming_activation,
|
||||
)
|
||||
from vllm.utils.humming import may_process_input
|
||||
|
||||
quant_config = self.quant_config
|
||||
config = self.humming_configs[sublayer_name]
|
||||
if input_scale is not None:
|
||||
assert scatter_idx is None
|
||||
if activation is not None:
|
||||
raise ValueError("Cannot apply activation to prequantized input")
|
||||
return inputs, input_scale, None
|
||||
|
||||
activation_kwargs = {}
|
||||
if activation is not None:
|
||||
activation_config = self.activation_config
|
||||
activation_kwargs = get_humming_activation(activation, activation_config)
|
||||
|
||||
prefix = "w1" if sublayer_name == "w13" else "w2"
|
||||
scale = getattr(quant_config, f"{prefix}_input_scale")
|
||||
scale2 = getattr(quant_config, f"{prefix}_input_scale_2")
|
||||
mode = config.input_quant_mode
|
||||
layout = "grouped_mask" if self.is_batched() else "normal"
|
||||
if scatter_idx is not None:
|
||||
layout = "scatter"
|
||||
|
||||
inputs, group_scales, token_scales = may_process_input(
|
||||
config,
|
||||
inputs=inputs,
|
||||
outputs=quanted_input,
|
||||
token_scales=scale2 if mode.has_secondary_scale else scale,
|
||||
hadamard_block_size=getattr(quant_config, f"{prefix}_hadamard_block_size"),
|
||||
layout=layout,
|
||||
expert_tokens=expert_tokens if layout == "grouped_mask" else None,
|
||||
scatter_idx=scatter_idx,
|
||||
num_valid_tokens=num_valid_tokens,
|
||||
**activation_kwargs,
|
||||
)
|
||||
input_scale = group_scales if mode.has_group_scale else token_scales
|
||||
input_scale_2 = token_scales if mode.has_secondary_scale else None
|
||||
return inputs, input_scale, input_scale_2
|
||||
|
||||
def humming_forward(
|
||||
self,
|
||||
@@ -232,30 +237,30 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
weight: torch.Tensor,
|
||||
input_scale: torch.Tensor | None,
|
||||
outputs: torch.Tensor,
|
||||
input_scale_2: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> torch.Tensor:
|
||||
from vllm.utils.humming import humming_forward
|
||||
|
||||
is_w13 = sublayer_name == "w13"
|
||||
index = 1 if sublayer_name == "w13" else 2
|
||||
return humming_forward(
|
||||
self.humming_configs[sublayer_name],
|
||||
inputs=inputs,
|
||||
weight=weight,
|
||||
weight_scale=(
|
||||
self.quant_config.w1_scale if is_w13 else self.quant_config.w2_scale
|
||||
),
|
||||
zero_point=(self.quant_config.w1_zp if is_w13 else self.quant_config.w2_zp),
|
||||
bias=(self.quant_config.w1_bias if is_w13 else self.quant_config.w2_bias),
|
||||
weight_scale_2=(
|
||||
self.quant_config.g1_alphas if is_w13 else self.quant_config.g2_alphas
|
||||
),
|
||||
weight_scale=getattr(self.quant_config, f"w{index}_scale"),
|
||||
zero_point=getattr(self.quant_config, f"w{index}_zp"),
|
||||
bias=getattr(self.quant_config, f"w{index}_bias"),
|
||||
weight_scale_2=getattr(self.quant_config, f"g{index}_alphas"),
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=outputs,
|
||||
locks=self.locks,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _get_permute_scratch(self, topk: int) -> MoEPermuteScratch | None:
|
||||
def _get_permute_scratch(
|
||||
self, topk: int, indices_only: bool = False
|
||||
) -> MoEPermuteScratch | None:
|
||||
if not moe_permute_unpermute_supported():
|
||||
return None
|
||||
|
||||
@@ -270,8 +275,8 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
num_experts=self.moe_config.num_experts,
|
||||
num_local_experts=self.moe_config.num_local_experts,
|
||||
device=torch.device(self.moe_config.device),
|
||||
hidden_size=self.moe_config.hidden_dim,
|
||||
hidden_dtype=self.moe_config.in_dtype,
|
||||
hidden_size=None if indices_only else self.moe_config.hidden_dim,
|
||||
hidden_dtype=None if indices_only else self.moe_config.in_dtype,
|
||||
)
|
||||
|
||||
def get_global_valid_shape_m(self, topk_ids: torch.Tensor):
|
||||
@@ -302,6 +307,16 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
weight_key: QuantKey | None,
|
||||
activation_key: QuantKey | None,
|
||||
) -> bool:
|
||||
if (
|
||||
activation_key is not None
|
||||
and activation_key.scale == kNvfp4Dynamic.scale
|
||||
and activation_key.dtype == kNvfp4Dynamic.dtype
|
||||
and activation_key.scale2 is not None
|
||||
and not activation_key.scale2.static
|
||||
and activation_key.scale2.group_shape == GroupShape.PER_TOKEN
|
||||
and activation_key.scale2.dtype == torch.float32
|
||||
):
|
||||
activation_key = replace(activation_key, scale2=kStaticTensorScale)
|
||||
SUPPORTED_W_A = [
|
||||
(kMxfp4Static, None),
|
||||
(kMxfp4Static, kMxfp4Dynamic),
|
||||
@@ -343,7 +358,7 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
(kMxfp8Static, kMxfp8Dynamic),
|
||||
]
|
||||
return (weight_key, activation_key) in SUPPORTED_W_A or (
|
||||
activation_key in (None, kFp8DynamicTokenSym)
|
||||
activation_key in (None, kFp8DynamicTokenSym, kInt8DynamicTokenSym)
|
||||
and _is_supported_wna16_weight_key(weight_key)
|
||||
)
|
||||
|
||||
@@ -355,7 +370,7 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
to FP8 before dispatch sends FP8 rather than BF16 over the interconnect,
|
||||
and Humming then consumes the pre-quantized FP8 + scale directly (see
|
||||
the apply() methods, which forward the dispatch scale into
|
||||
HummingMethod.may_quant_input, and may_quant_input itself, which is a
|
||||
HummingExpertsBase.process_input, which is a
|
||||
no-op when an input scale is already supplied). The scale layout
|
||||
produced by vLLM's block-FP8 quantization ([M, K // 128] float32,
|
||||
row-major) matches what the Humming WGMMA grouped GEMM expects.
|
||||
@@ -373,7 +388,7 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
inputs).
|
||||
|
||||
Humming normally quantizes inputs internally via
|
||||
HummingMethod.may_quant_input() in apply(), so we defer quantization
|
||||
HummingExpertsBase.process_input() in apply(), so we defer quantization
|
||||
(return True) to avoid quantizing twice -- once in prepare and once in
|
||||
Humming's apply().
|
||||
|
||||
@@ -398,8 +413,6 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
|
||||
@staticmethod
|
||||
def _supports_activation(activation: MoEActivation) -> bool:
|
||||
# Humming uses apply_moe_activation() callback for activation,
|
||||
# so any activation supported there can be used here.
|
||||
return apply_moe_activation_supported(activation)
|
||||
|
||||
@staticmethod
|
||||
@@ -456,10 +469,9 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
assert intermediate_dim == self.adjust_N_for_activation(gate_up_dim, activation)
|
||||
|
||||
# hidden_states
|
||||
# (-> quanted_gate_up_input) (if not BF16/FP16 activation)
|
||||
# -> quanted_gate_up_input (Hadamard + optional quantization)
|
||||
# -> gate_up_output
|
||||
# -> activation_output
|
||||
# (-> quanted_down_input) (if not BF16/FP16 activation)
|
||||
# -> quanted_down_input (activation + Hadamard + optional quantization)
|
||||
# -> down_output
|
||||
# (-> output) (if not is_batched)
|
||||
# Neighboring nodes are required to utilize distinct workspaces.
|
||||
@@ -471,8 +483,8 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
max_num_tokens = self.max_num_tokens
|
||||
num_dispatchers = self.num_dispatchers
|
||||
assert max_num_tokens is not None and num_dispatchers is not None
|
||||
input_shape_m = num_experts * max_num_tokens
|
||||
real_shape_m = num_experts * max_num_tokens * num_dispatchers
|
||||
input_shape_m = real_shape_m
|
||||
output_shape = (num_experts, max_num_tokens * num_dispatchers, K)
|
||||
else:
|
||||
input_shape_m = M
|
||||
@@ -483,15 +495,18 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
|
||||
a_dtype = self.humming_configs["w13"].a_dtype
|
||||
c_dtype = self.humming_configs["w13"].c_dtype
|
||||
num_bits = a_dtype.num_bits
|
||||
down_a_dtype = w2_config.a_dtype
|
||||
torch_dtype_map = {
|
||||
dtypes.float16: torch.float16,
|
||||
dtypes.bfloat16: torch.bfloat16,
|
||||
dtypes.float32: torch.float32,
|
||||
dtypes.float8e3m4: torch.uint8,
|
||||
dtypes.float8e4m3: torch.float8_e4m3fn,
|
||||
dtypes.float8e5m2: torch.float8_e5m2,
|
||||
dtypes.int8: torch.int8,
|
||||
dtypes.int4: torch.uint8,
|
||||
dtypes.float4e0m3: torch.uint8,
|
||||
dtypes.float4e2m1: torch.uint8,
|
||||
}
|
||||
|
||||
buffer_metas = {
|
||||
@@ -503,13 +518,9 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
"shape": (real_shape_m, gate_up_dim),
|
||||
"dtype": torch_dtype_map[c_dtype],
|
||||
},
|
||||
"activation_output": {
|
||||
"shape": (real_shape_m, intermediate_dim),
|
||||
"dtype": torch_dtype_map[c_dtype],
|
||||
},
|
||||
"quanted_down_input": {
|
||||
"shape": (real_shape_m, intermediate_dim),
|
||||
"dtype": torch_dtype_map[a_dtype],
|
||||
"dtype": torch_dtype_map[down_a_dtype],
|
||||
},
|
||||
"down_output": {
|
||||
"shape": output_shape if self.is_batched() else (real_shape_m, K),
|
||||
@@ -523,7 +534,8 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
|
||||
for key in buffer_metas:
|
||||
meta = buffer_metas[key]
|
||||
if "quanted" in key and a_dtype.num_bits == 4:
|
||||
input_dtype = down_a_dtype if key == "quanted_down_input" else a_dtype
|
||||
if "quanted" in key and input_dtype.num_bits == 4:
|
||||
last_dim = meta["shape"][-1]
|
||||
if last_dim % 2 != 0:
|
||||
raise ValueError(
|
||||
@@ -532,25 +544,12 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
)
|
||||
meta["shape"] = meta["shape"][:-1] + (last_dim // 2,)
|
||||
|
||||
if num_bits == 16:
|
||||
required_buffers = ["gate_up_output", "activation_output", "down_output"]
|
||||
else:
|
||||
required_buffers = [
|
||||
"quanted_gate_up_input",
|
||||
"gate_up_output",
|
||||
"activation_output",
|
||||
"quanted_down_input",
|
||||
"down_output",
|
||||
]
|
||||
|
||||
# Note: The fused SITU+FP8 quant goes gate_up_output ->
|
||||
# quanted_down_input directly, never materializing
|
||||
# activation_output. Dropping activation_output from the chain
|
||||
# flips the even/odd workspace 2-coloring below so
|
||||
# gate_up_output and quanted_down_input land
|
||||
# on DIFFERENT workspaces.
|
||||
if self.fused_situ_quant_enabled(activation):
|
||||
required_buffers.remove("activation_output")
|
||||
required_buffers = [
|
||||
"quanted_gate_up_input",
|
||||
"gate_up_output",
|
||||
"quanted_down_input",
|
||||
"down_output",
|
||||
]
|
||||
|
||||
# batched moe use down_output as output
|
||||
if not self.is_batched():
|
||||
@@ -673,81 +672,6 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
activation_kwargs["valid_token_counts"] = valid_token_counts
|
||||
self.activation(**activation_kwargs)
|
||||
|
||||
def fused_situ_quant_enabled(self, activation: MoEActivation) -> bool:
|
||||
"""Whether the SITU activation + w2 quant can be fused into one kernel.
|
||||
|
||||
Fused only for k-major block-FP8 group-128 e4m3 with float32 scales --
|
||||
the sole layout situ_and_mul_quant supports. A float32 as_dtype rules out
|
||||
MXMMA (which uses e8m0 m-major scales), so a group-128 scale is
|
||||
guaranteed k-major. Everything else (m-major MXFP8, other group sizes,
|
||||
16-bit passthrough, non-SITU) falls back to the separate
|
||||
situ_and_mul + quantize_input path.
|
||||
"""
|
||||
if activation != MoEActivation.SITU:
|
||||
return False
|
||||
w2cfg = self.humming_configs["w2"]
|
||||
# Report the specific blocker once so a silent fallback to the unfused
|
||||
# situ_and_mul + quant pair is never a mystery in a trace.
|
||||
reason: str | None = None
|
||||
if not (w2cfg.a_dtype.num_bits == 8 and str(w2cfg.a_dtype) == "float8e4m3"):
|
||||
reason = f"w2 a_dtype is {w2cfg.a_dtype} (need float8e4m3)"
|
||||
elif w2cfg.input_scale_group_size != 128:
|
||||
reason = (
|
||||
f"w2 input_scale_group_size is {w2cfg.input_scale_group_size} "
|
||||
"(need 128)"
|
||||
)
|
||||
elif not (w2cfg.as_dtype is not None and str(w2cfg.as_dtype) == "float32"):
|
||||
reason = f"w2 as_dtype is {w2cfg.as_dtype} (need float32, k-major)"
|
||||
if reason is not None:
|
||||
logger.warning_once(
|
||||
"Humming fused SITU+FP8 quant disabled, using unfused "
|
||||
"situ_and_mul + quant: %s",
|
||||
reason,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def fused_situ_quant(
|
||||
self,
|
||||
gate_up_output: torch.Tensor,
|
||||
quanted_down_input: torch.Tensor,
|
||||
num_valid_tokens: torch.Tensor | None,
|
||||
topk: int = 1,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Run the fused SITU activation + FP8 quant for the w2 input.
|
||||
|
||||
Returns ``(quanted_down_input, input_scale)`` in the same layout the
|
||||
unfused ``apply_activation`` + ``quantize_input("w2")`` pair produces: an
|
||||
fp8 [M, d] tensor plus a k-major block-FP8 float32 [M, d // 128] group
|
||||
scale. Only reached when ``fused_situ_quant_enabled`` (group_size 128).
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.activation import (
|
||||
situ_and_mul_quant,
|
||||
)
|
||||
|
||||
cfg = self.activation_config
|
||||
assert cfg.activation_situ_beta is not None, (
|
||||
"SITU requires activation_situ_beta from FusedMoEConfig"
|
||||
)
|
||||
group_size = self.humming_configs["w2"].input_scale_group_size
|
||||
m, d = quanted_down_input.size(0), quanted_down_input.size(1)
|
||||
input_scale = torch.empty(
|
||||
(m, d // group_size),
|
||||
dtype=torch.float32,
|
||||
device=quanted_down_input.device,
|
||||
)
|
||||
situ_and_mul_quant(
|
||||
quanted_down_input,
|
||||
input_scale,
|
||||
gate_up_output,
|
||||
beta=cfg.activation_situ_beta,
|
||||
linear_beta=cfg.activation_situ_linear_beta,
|
||||
group_size=group_size,
|
||||
num_valid_tokens=num_valid_tokens,
|
||||
topk=topk,
|
||||
)
|
||||
return quanted_down_input, input_scale
|
||||
|
||||
|
||||
class HummingIndexedExperts(HummingExpertsBase):
|
||||
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
|
||||
@@ -768,7 +692,7 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
topk_ids: torch.Tensor,
|
||||
expert_map: torch.Tensor | None,
|
||||
expert_tokens_meta: mk.ExpertTokensMetadata | None,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
) -> tuple[dict[str, Any], dict[str, Any], torch.Tensor | None]:
|
||||
valid_shape_m = self.estimate_local_valid_shape_m(topk_ids)
|
||||
|
||||
moe_block_size = None
|
||||
@@ -784,13 +708,21 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
)
|
||||
moe_block_size = 64
|
||||
|
||||
sorted_ids, expert_ids, num_tokens_padded = moe_align_block_size(
|
||||
use_scatter = False
|
||||
if expert_map is not None:
|
||||
num_sms = num_compute_units(topk_ids.get_device())
|
||||
use_scatter = topk_ids.numel() > 2 * num_sms
|
||||
|
||||
alignment = moe_align_block_size(
|
||||
topk_ids=topk_ids,
|
||||
block_size=moe_block_size,
|
||||
num_experts=self.global_num_experts,
|
||||
expert_map=expert_map,
|
||||
ignore_invalid_experts=True,
|
||||
return_scatter_idx=use_scatter,
|
||||
)
|
||||
sorted_ids, expert_ids, num_tokens_padded = alignment[:3]
|
||||
scatter_idx = alignment[3] if len(alignment) == 4 else None
|
||||
|
||||
moe_common_kwargs = {
|
||||
"sorted_ids": sorted_ids,
|
||||
@@ -806,7 +738,26 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
moe_kwargs1.update(moe_common_kwargs)
|
||||
moe_kwargs2.update(moe_common_kwargs)
|
||||
|
||||
return moe_kwargs1, moe_kwargs2
|
||||
w2_block_size = 64
|
||||
for lower, upper, config in self.w2_tuning_config:
|
||||
if lower < valid_shape_m <= upper:
|
||||
w2_block_size = config["block_shape"][0]
|
||||
break
|
||||
if w2_block_size != moe_block_size:
|
||||
sorted_ids2, expert_ids2, num_tokens_padded2 = moe_align_block_size(
|
||||
topk_ids=topk_ids,
|
||||
block_size=w2_block_size,
|
||||
num_experts=self.global_num_experts,
|
||||
expert_map=expert_map,
|
||||
ignore_invalid_experts=True,
|
||||
)
|
||||
moe_kwargs2.update(
|
||||
sorted_ids=sorted_ids2,
|
||||
expert_ids=expert_ids2,
|
||||
num_tokens_padded=num_tokens_padded2,
|
||||
)
|
||||
|
||||
return moe_kwargs1, moe_kwargs2, scatter_idx
|
||||
|
||||
def apply(
|
||||
self,
|
||||
@@ -832,7 +783,7 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
object, so w1, w2, a2_scale are unused. a1q_scale is None on the usual
|
||||
path (Humming quantizes the w13 input itself); for block-FP8 activations
|
||||
it carries the scale computed before dispatch, which is forwarded to
|
||||
may_quant_input so Humming skips the redundant w13 quantization. The
|
||||
process_input so Humming skips the redundant w13 quantization. The
|
||||
output is written into workspace13 via the buffer management.
|
||||
"""
|
||||
assert not apply_router_weight_on_input
|
||||
@@ -847,13 +798,13 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
)
|
||||
buffers["output"] = output
|
||||
|
||||
moe_kwargs1, moe_kwargs2 = self.prepare_humming_moe_kwargs(
|
||||
moe_kwargs1, moe_kwargs2, scatter_idx = self.prepare_humming_moe_kwargs(
|
||||
topk_ids=topk_ids,
|
||||
expert_map=expert_map,
|
||||
expert_tokens_meta=expert_tokens_meta,
|
||||
)
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w13",
|
||||
inputs=hidden_states,
|
||||
input_scale=a1q_scale,
|
||||
@@ -865,52 +816,25 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
inputs=inputs,
|
||||
weight=w1,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=buffers["gate_up_output"],
|
||||
**moe_kwargs1,
|
||||
)
|
||||
|
||||
# psum[-1:] is the DeepEP valid *token* count as a zero-cost int32 view.
|
||||
# The fused path and mul_sum consume tokens directly. The unfused
|
||||
# activation consumes the expanded row count (tokens * topk).
|
||||
valid_tokens = None
|
||||
topk = topk_ids.size(1)
|
||||
if (
|
||||
expert_tokens_meta is not None
|
||||
and expert_tokens_meta.psum_recv_per_rank is not None
|
||||
):
|
||||
valid_tokens = expert_tokens_meta.psum_recv_per_rank[-1:]
|
||||
|
||||
if self.fused_situ_quant_enabled(activation):
|
||||
# Fused SITU + FP8 quant (per-token or block-FP8 group-128) straight
|
||||
# into the w2 input, skipping the bf16 activation_output round-trip.
|
||||
inputs, input_scale = self.fused_situ_quant(
|
||||
gate_up_output=buffers["gate_up_output"],
|
||||
quanted_down_input=buffers["quanted_down_input"],
|
||||
num_valid_tokens=valid_tokens,
|
||||
topk=topk,
|
||||
)
|
||||
else:
|
||||
valid_token_counts = (
|
||||
valid_tokens * topk if valid_tokens is not None else None
|
||||
)
|
||||
self.apply_activation(
|
||||
activation=activation,
|
||||
input=buffers["gate_up_output"],
|
||||
output=buffers["activation_output"],
|
||||
valid_token_counts=valid_token_counts,
|
||||
)
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
"w2",
|
||||
inputs=buffers["activation_output"],
|
||||
quanted_input=buffers.get("quanted_down_input", None),
|
||||
)
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w2",
|
||||
inputs=buffers["gate_up_output"],
|
||||
quanted_input=buffers["quanted_down_input"],
|
||||
activation=activation,
|
||||
scatter_idx=scatter_idx,
|
||||
)
|
||||
|
||||
self.humming_forward(
|
||||
"w2",
|
||||
inputs=inputs,
|
||||
weight=w2,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=buffers["down_output"].view(-1, hidden_states.size(-1)),
|
||||
**moe_kwargs2,
|
||||
)
|
||||
@@ -918,6 +842,10 @@ class HummingIndexedExperts(HummingExpertsBase):
|
||||
# expert_map masks any non-local id; num_valid_tokens bounds the
|
||||
# persistent kernel to the real token rows [0, num_recv) so the padding
|
||||
# tail is never iterated (CUDA-graph-safe device scalar).
|
||||
valid_tokens = None
|
||||
if expert_tokens_meta and expert_tokens_meta.psum_recv_per_rank is not None:
|
||||
valid_tokens = expert_tokens_meta.psum_recv_per_rank[-1:]
|
||||
|
||||
moe_fused_mul_sum(
|
||||
inputs=buffers["down_output"].view(*topk_ids.shape, -1),
|
||||
topk_weights=topk_weights,
|
||||
@@ -983,21 +911,33 @@ class HummingGroupedExperts(HummingExpertsBase):
|
||||
)
|
||||
buffers["output"] = output
|
||||
|
||||
hidden_states, a1q_scale, expert_first_token_offset, inv_perm, _ = moe_permute(
|
||||
hidden_states=hidden_states,
|
||||
a1q_scale=a1q_scale,
|
||||
topk_ids=topk_ids,
|
||||
n_expert=global_num_experts,
|
||||
n_local_expert=self.num_experts,
|
||||
expert_map=expert_map,
|
||||
scratch=self._get_permute_scratch(topk_ids.size(1)),
|
||||
)
|
||||
if a1q_scale is None:
|
||||
scratch = self._get_permute_scratch(topk_ids.size(1), indices_only=True)
|
||||
assert scratch is not None
|
||||
scatter_metadata = moe_prepare_scatter(topk_ids, expert_map, scratch)
|
||||
expert_offsets, scatter_idx = scatter_metadata
|
||||
inv_perm = scatter_idx.flatten()
|
||||
num_valid_tokens = expert_offsets[-1:] if expert_map is not None else None
|
||||
else:
|
||||
hidden_states, a1q_scale, expert_offsets, inv_perm, _ = moe_permute(
|
||||
hidden_states=hidden_states,
|
||||
a1q_scale=a1q_scale,
|
||||
topk_ids=topk_ids,
|
||||
n_expert=global_num_experts,
|
||||
n_local_expert=self.num_experts,
|
||||
expert_map=expert_map,
|
||||
scratch=self._get_permute_scratch(topk_ids.size(1)),
|
||||
)
|
||||
scatter_idx = None
|
||||
num_valid_tokens = None
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w13",
|
||||
inputs=hidden_states,
|
||||
input_scale=a1q_scale,
|
||||
quanted_input=buffers.get("quanted_gate_up_input", None),
|
||||
scatter_idx=scatter_idx,
|
||||
num_valid_tokens=num_valid_tokens,
|
||||
)
|
||||
|
||||
self.humming_forward(
|
||||
@@ -1005,28 +945,20 @@ class HummingGroupedExperts(HummingExpertsBase):
|
||||
inputs=inputs,
|
||||
weight=w1,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=buffers["gate_up_output"],
|
||||
valid_shape_m=valid_shape_m,
|
||||
expert_layout=expert_first_token_offset,
|
||||
expert_layout=expert_offsets,
|
||||
compute_config=self.compute_config_str,
|
||||
tuning_config=self.w13_tuning_config_str,
|
||||
)
|
||||
|
||||
self.apply_activation(
|
||||
activation=activation,
|
||||
input=buffers["gate_up_output"],
|
||||
output=buffers["activation_output"],
|
||||
valid_token_counts=(
|
||||
expert_first_token_offset[-1:].to(torch.int32)
|
||||
if expert_tokens_meta is None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w2",
|
||||
inputs=buffers["activation_output"],
|
||||
quanted_input=buffers.get("quanted_down_input", None),
|
||||
inputs=buffers["gate_up_output"],
|
||||
quanted_input=buffers["quanted_down_input"],
|
||||
activation=activation,
|
||||
num_valid_tokens=expert_offsets[-1:],
|
||||
)
|
||||
|
||||
self.humming_forward(
|
||||
@@ -1034,9 +966,10 @@ class HummingGroupedExperts(HummingExpertsBase):
|
||||
inputs=inputs,
|
||||
weight=w2,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=buffers["down_output"],
|
||||
valid_shape_m=valid_shape_m,
|
||||
expert_layout=expert_first_token_offset,
|
||||
expert_layout=expert_offsets,
|
||||
compute_config=self.compute_config_str,
|
||||
tuning_config=self.w2_tuning_config_str,
|
||||
)
|
||||
@@ -1046,7 +979,7 @@ class HummingGroupedExperts(HummingExpertsBase):
|
||||
permuted_hidden_states=buffers["down_output"].view(*topk_ids.shape, -1),
|
||||
topk_weights=topk_weights,
|
||||
inv_permuted_idx=inv_perm,
|
||||
expert_first_token_offset=expert_first_token_offset,
|
||||
expert_first_token_offset=expert_offsets,
|
||||
)
|
||||
|
||||
|
||||
@@ -1088,7 +1021,7 @@ class BatchedHummingGroupedExperts(HummingExpertsBase):
|
||||
object, so w1, w2, a2_scale are unused. a1q_scale is None on the usual
|
||||
path (Humming quantizes the w13 input itself); for block-FP8 activations
|
||||
it carries the scale computed before dispatch, which is forwarded to
|
||||
may_quant_input so Humming skips the redundant w13 quantization. The
|
||||
process_input so Humming skips the redundant w13 quantization. The
|
||||
output is written into workspace13 via the buffer management.
|
||||
"""
|
||||
assert not apply_router_weight_on_input
|
||||
@@ -1111,11 +1044,12 @@ class BatchedHummingGroupedExperts(HummingExpertsBase):
|
||||
)
|
||||
buffers["down_output"] = output
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w13",
|
||||
inputs=hidden_states,
|
||||
input_scale=a1q_scale,
|
||||
quanted_input=buffers.get("quanted_gate_up_input", None),
|
||||
expert_tokens=expert_num_tokens,
|
||||
)
|
||||
|
||||
self.humming_forward(
|
||||
@@ -1123,6 +1057,7 @@ class BatchedHummingGroupedExperts(HummingExpertsBase):
|
||||
inputs=inputs,
|
||||
weight=w1,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=buffers["gate_up_output"],
|
||||
valid_shape_m=valid_shape_m,
|
||||
expert_layout=expert_num_tokens,
|
||||
@@ -1130,16 +1065,12 @@ class BatchedHummingGroupedExperts(HummingExpertsBase):
|
||||
tuning_config=self.w13_tuning_config_str,
|
||||
)
|
||||
|
||||
self.apply_activation(
|
||||
activation=activation,
|
||||
input=buffers["gate_up_output"],
|
||||
output=buffers["activation_output"],
|
||||
)
|
||||
|
||||
inputs, input_scale = self.quantize_input(
|
||||
inputs, input_scale, input_scale_2 = self.process_input(
|
||||
"w2",
|
||||
inputs=buffers["activation_output"],
|
||||
quanted_input=buffers.get("quanted_down_input", None),
|
||||
inputs=buffers["gate_up_output"],
|
||||
quanted_input=buffers["quanted_down_input"],
|
||||
expert_tokens=expert_num_tokens,
|
||||
activation=activation,
|
||||
)
|
||||
|
||||
self.humming_forward(
|
||||
@@ -1147,6 +1078,7 @@ class BatchedHummingGroupedExperts(HummingExpertsBase):
|
||||
inputs=inputs,
|
||||
weight=w2,
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
outputs=output.view(-1, hidden_states.size(-1)),
|
||||
valid_shape_m=valid_shape_m,
|
||||
expert_layout=expert_num_tokens,
|
||||
|
||||
@@ -479,8 +479,11 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
|
||||
# Fuse SiLU+Mul + FP8 block quantize into a single kernel
|
||||
# when conditions permit (gated SiLU, fp8 block quant with
|
||||
# group_size=128, no LoRA requiring the BF16 intermediate).
|
||||
# The fused kernel has no clamp parameter, so a configured
|
||||
# SwiGLU clamp limit falls through to the unfused path.
|
||||
if (
|
||||
activation == MoEActivation.SILU
|
||||
and self.activation_config.clamp_limit is None
|
||||
and self.quant_config.use_fp8_w8a8
|
||||
and self.block_shape == [128, 128]
|
||||
and lora_context is None
|
||||
|
||||
@@ -363,6 +363,7 @@ def FusedMoEFactory(
|
||||
activation=moe_activation,
|
||||
device=vllm_config.device_config.device,
|
||||
routing_method=router.routing_method_type, # Not ideal
|
||||
has_hash_routing=hash_indices_table is not None,
|
||||
swiglu_limit=swiglu_limit,
|
||||
swiglu_alpha=swiglu_alpha,
|
||||
swiglu_beta=swiglu_beta,
|
||||
|
||||
@@ -544,6 +544,8 @@ class FusedMoEExperts(ABC):
|
||||
return False, _make_reason(
|
||||
f"parallel config {moe_config.moe_parallel_config}"
|
||||
)
|
||||
elif moe_config.has_hash_routing and cls.is_monolithic():
|
||||
return False, _make_reason("hash routing")
|
||||
elif not cls._supports_routing_method(
|
||||
moe_config.routing_method, weight_key, activation_key
|
||||
):
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Literal, overload
|
||||
|
||||
import torch
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
@@ -8,6 +10,48 @@ from vllm.triton_utils import triton
|
||||
from vllm.utils.math_utils import round_up
|
||||
|
||||
|
||||
@overload
|
||||
def moe_align_block_size(
|
||||
topk_ids: torch.Tensor,
|
||||
block_size: int,
|
||||
num_experts: int,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
pad_sorted_ids: bool = False,
|
||||
ignore_invalid_experts: bool = False,
|
||||
*,
|
||||
return_scatter_idx: Literal[False] = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def moe_align_block_size(
|
||||
topk_ids: torch.Tensor,
|
||||
block_size: int,
|
||||
num_experts: int,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
pad_sorted_ids: bool = False,
|
||||
ignore_invalid_experts: bool = False,
|
||||
*,
|
||||
return_scatter_idx: Literal[True],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def moe_align_block_size(
|
||||
topk_ids: torch.Tensor,
|
||||
block_size: int,
|
||||
num_experts: int,
|
||||
expert_map: torch.Tensor | None = None,
|
||||
pad_sorted_ids: bool = False,
|
||||
ignore_invalid_experts: bool = False,
|
||||
*,
|
||||
return_scatter_idx: bool,
|
||||
) -> (
|
||||
tuple[torch.Tensor, torch.Tensor, torch.Tensor]
|
||||
| tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
|
||||
): ...
|
||||
|
||||
|
||||
def moe_align_block_size(
|
||||
topk_ids: torch.Tensor,
|
||||
block_size: int,
|
||||
@@ -15,7 +59,11 @@ def moe_align_block_size(
|
||||
expert_map: torch.Tensor | None = None,
|
||||
pad_sorted_ids: bool = False,
|
||||
ignore_invalid_experts: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return_scatter_idx: bool = False,
|
||||
) -> (
|
||||
tuple[torch.Tensor, torch.Tensor, torch.Tensor]
|
||||
| tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
|
||||
):
|
||||
"""Aligns the token distribution across experts to be compatible with block
|
||||
size for matrix multiplication.
|
||||
|
||||
@@ -42,6 +90,8 @@ def moe_align_block_size(
|
||||
as -1. When True, all invalid expert_ids in topk_ids will be ignored
|
||||
and will not participate in counting or ranking, and there will be no
|
||||
-1 in expert_ids.
|
||||
return_scatter_idx: Whether to additionally return a masked identity
|
||||
mapping for the original routed rows.
|
||||
|
||||
Returns:
|
||||
- sorted_token_ids: A tensor containing the sorted token indices according
|
||||
@@ -49,6 +99,10 @@ def moe_align_block_size(
|
||||
- expert_ids: A tensor indicating the assigned expert index for each block.
|
||||
- num_tokens_post_padded: The total number of tokens after padding,
|
||||
ensuring divisibility by block_size.
|
||||
- scatter_idx: Only returned when return_scatter_idx=True. An int32 tensor
|
||||
shaped [topk_ids.numel(), 1], containing the original routed row index
|
||||
for valid routes and -1 otherwise. With expert_map, this requires
|
||||
ignore_invalid_experts=True.
|
||||
|
||||
This function pads the number of tokens that each expert needs to process
|
||||
so that it is divisible by block_size.
|
||||
@@ -71,6 +125,15 @@ def moe_align_block_size(
|
||||
by block_size for proper block matrix operations.
|
||||
|
||||
"""
|
||||
if return_scatter_idx and expert_map is not None and not ignore_invalid_experts:
|
||||
raise ValueError("scatter_idx with expert_map requires ignore_invalid_experts")
|
||||
scatter_idx = None
|
||||
if return_scatter_idx:
|
||||
scatter_idx = torch.empty(
|
||||
(topk_ids.numel(), 1),
|
||||
dtype=torch.int32,
|
||||
device=topk_ids.device,
|
||||
)
|
||||
max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
|
||||
if pad_sorted_ids:
|
||||
max_num_tokens_padded = round_up(max_num_tokens_padded, block_size)
|
||||
@@ -95,11 +158,14 @@ def moe_align_block_size(
|
||||
expert_ids,
|
||||
num_tokens_post_pad,
|
||||
expert_map if ignore_invalid_experts else None,
|
||||
scatter_idx,
|
||||
)
|
||||
|
||||
if expert_map is not None and not ignore_invalid_experts:
|
||||
expert_ids = expert_map[expert_ids]
|
||||
|
||||
if scatter_idx is not None:
|
||||
return sorted_ids, expert_ids, num_tokens_post_pad, scatter_idx
|
||||
return sorted_ids, expert_ids, num_tokens_post_pad
|
||||
|
||||
|
||||
|
||||
@@ -107,6 +107,37 @@ class MoEPermuteScratch:
|
||||
return topk_ids_int32
|
||||
|
||||
|
||||
def moe_prepare_scatter(
|
||||
topk_ids: torch.Tensor,
|
||||
expert_map: torch.Tensor | None,
|
||||
scratch: MoEPermuteScratch,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Generate expert offsets and shared scatter/unpermute destination indices."""
|
||||
assert topk_ids.device == scratch.device
|
||||
assert topk_ids.size(0) <= scratch.max_num_tokens
|
||||
assert topk_ids.size(1) == scratch.topk
|
||||
n_token, topk = topk_ids.shape
|
||||
expanded_rows = topk_ids.numel()
|
||||
inverse = scratch.inv_permuted_idx[:expanded_rows].view(n_token, topk)
|
||||
if expanded_rows == 0:
|
||||
scratch.expert_first_token_offset.zero_()
|
||||
return scratch.expert_first_token_offset, inverse
|
||||
torch.ops._moe_C.moe_prepare_scatter(
|
||||
scratch.prepare_topk_ids(topk_ids),
|
||||
scratch.token_expert_indices_view(n_token),
|
||||
expert_map,
|
||||
scratch.num_experts,
|
||||
scratch.num_local_experts,
|
||||
scratch.expert_first_token_offset,
|
||||
inverse,
|
||||
scratch.sort_workspace,
|
||||
scratch.permuted_experts_id[:expanded_rows].view(n_token, topk),
|
||||
scratch.sorted_row_idx[:expanded_rows].view(n_token, topk),
|
||||
scratch.topk_ids_for_sort[:expanded_rows].view(n_token, topk),
|
||||
)
|
||||
return scratch.expert_first_token_offset, inverse
|
||||
|
||||
|
||||
def get_moe_permute_scratch(
|
||||
*,
|
||||
max_num_tokens: int,
|
||||
|
||||
@@ -603,7 +603,7 @@ def convert_to_fp8_moe_kernel_format(
|
||||
w13.is_shuffled = True
|
||||
w2.is_shuffled = True
|
||||
elif fp8_backend == Fp8MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
@@ -739,7 +739,7 @@ def make_fp8_moe_quant_config(
|
||||
)
|
||||
elif fp8_backend == Fp8MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.fused_moe import RoutedExperts
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -193,7 +193,7 @@ def make_int8_moe_quant_config(
|
||||
|
||||
if int8_backend == Int8MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.fused_moe import RoutedExperts
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
@@ -254,7 +254,7 @@ def convert_to_int8_moe_kernel_format(
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Convert INT8 MoE weights to backend-specific kernel format."""
|
||||
if int8_backend == Int8MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
|
||||
@@ -1456,7 +1456,7 @@ def convert_to_wna16_moe_kernel_format(
|
||||
"""
|
||||
if backend == WNA16MoEBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.moe_wna16 import MoeWNA16Config
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
|
||||
@@ -844,7 +844,7 @@ def convert_gpt_oss_weight_to_mxfp4_moe_kernel_format(
|
||||
sf_block_size = 32 # mxfp4 block size
|
||||
|
||||
if mxfp4_backend == Mxfp4MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
@@ -1428,7 +1428,7 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
)
|
||||
|
||||
if mxfp4_backend == Mxfp4MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
@@ -1966,7 +1966,7 @@ def make_mxfp4_moe_quant_config(
|
||||
gemm1_clamp_limit=swiglu_limit,
|
||||
)
|
||||
elif mxfp4_backend == Mxfp4MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -409,7 +409,7 @@ def convert_to_nvfp4_moe_kernel_format(
|
||||
is_act_and_mul=is_act_and_mul,
|
||||
)
|
||||
elif nvfp4_backend == NvFp4MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
convert_to_humming_moe_kernel_format,
|
||||
)
|
||||
|
||||
@@ -523,7 +523,7 @@ def make_nvfp4_moe_quant_config(
|
||||
use_a16 = _use_a16(backend, use_a16)
|
||||
if backend == NvFp4MoeBackend.HUMMING:
|
||||
from vllm.model_executor.layers.fused_moe import RoutedExperts
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -94,7 +94,13 @@ def _get_priority_backends(moe_config: FusedMoEConfig) -> list[UnquantizedMoeBac
|
||||
_move_to_back(_AVAILABLE_BACKENDS, UnquantizedMoeBackend.FLASHINFER_CUTLASS)
|
||||
|
||||
elif current_platform.is_xpu():
|
||||
_AVAILABLE_BACKENDS = [UnquantizedMoeBackend.XPU]
|
||||
# XPUExperts does not support batch invariance; TRITON is kept as a
|
||||
# fallback so VLLM_BATCH_INVARIANT=1 still resolves to a valid
|
||||
# (batch-invariant) backend on XPU.
|
||||
_AVAILABLE_BACKENDS = [
|
||||
UnquantizedMoeBackend.XPU,
|
||||
UnquantizedMoeBackend.TRITON,
|
||||
]
|
||||
elif current_platform.is_cpu():
|
||||
_AVAILABLE_BACKENDS = [UnquantizedMoeBackend.CPU]
|
||||
return _AVAILABLE_BACKENDS
|
||||
|
||||
@@ -10,15 +10,12 @@ from collections.abc import Callable
|
||||
from functools import partial
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.parallel_state import get_tp_group
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, is_full_attention_spec
|
||||
from vllm.v1.outputs import RoutedExpertsTensors
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -46,37 +43,29 @@ def _get_routed_experts_shape(vllm_config: VllmConfig) -> tuple[int, int, int]:
|
||||
class RoutedExpertsCapturer:
|
||||
"""Worker-side capturer for routed experts, lives on GPU.
|
||||
|
||||
Layer-level hooks call :meth:`capture` from inside the forward pass
|
||||
with the per-layer ``topk_ids`` tensor. The tensor is sliced to the
|
||||
tokens owned by this DP rank and written into a preallocated device
|
||||
buffer. At the end of the step, :class:`GPUModelRunner` reads the
|
||||
device buffer, issues a D2H copy into a pinned CPU buffer, and hands
|
||||
the result to the scheduler via :class:`RoutedExpertsLists`.
|
||||
Layer-level hooks call :meth:`capture` inside the forward pass. Routing
|
||||
rows owned by this DP rank are written into a preallocated device buffer.
|
||||
|
||||
The device / pinned-CPU transit buffers use ``torch.int32`` (not a
|
||||
narrow ``uint8``/``uint16`` sized by ``num_experts``). This keeps the
|
||||
SP all-gather path free of dtype casts, matches the router's native
|
||||
``topk_ids`` indices dtype more closely, and costs only a few MB per
|
||||
worker (``max_num_batched_tokens * num_layers * top_k * 4`` bytes).
|
||||
The scheduler-side slot buffer
|
||||
(``RoutedExpertsManager.routed_experts_by_slot``) still uses the
|
||||
narrow dtype -- numpy fancy-index assignment in ``store_batch``
|
||||
narrows the data on the way in.
|
||||
The device buffer uses ``int32``. Stable snapshots use the narrowest dtype
|
||||
that can represent every logical expert ID.
|
||||
|
||||
Invariants:
|
||||
- One instance per worker; shape is fixed at init and covers the
|
||||
worst-case step (``max_num_batched_tokens`` tokens).
|
||||
- Every routed layer overwrites the current step's token rows.
|
||||
- ``device_buffer.dtype`` is ``torch.int32``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
max_num_batched_tokens: int,
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
) -> None:
|
||||
num_layers, _, num_experts_per_tok = _get_routed_experts_shape(vllm_config)
|
||||
num_layers, num_experts, num_experts_per_tok = _get_routed_experts_shape(
|
||||
vllm_config
|
||||
)
|
||||
self.shape_per_token = (num_layers, num_experts_per_tok)
|
||||
self.output_dtype_name = "uint8" if num_experts <= 256 else "uint16"
|
||||
self.output_dtype = getattr(torch, self.output_dtype_name)
|
||||
logger.info(
|
||||
"RoutedExpertsCapturer: allocating buffer with "
|
||||
"max_tokens=%d, num_layers=%d, num_experts_per_tok=%d "
|
||||
@@ -87,23 +76,12 @@ class RoutedExpertsCapturer:
|
||||
vllm_config.model_config.hf_text_config.model_type,
|
||||
)
|
||||
self.device_buffer = torch.zeros(
|
||||
(
|
||||
max_num_batched_tokens,
|
||||
num_layers,
|
||||
num_experts_per_tok,
|
||||
),
|
||||
# Use int32 for the device / host transit buffers: it
|
||||
# matches the router's native topk_ids dtype, is universally
|
||||
# supported by NCCL (uint8/uint16 are version-dependent),
|
||||
# and the extra bytes are small (few MB per worker). The
|
||||
# big scheduler-side slot buffer stays narrow.
|
||||
(max_num_batched_tokens, *self.shape_per_token),
|
||||
dtype=torch.int32,
|
||||
device=current_platform.device_type,
|
||||
)
|
||||
self.dp_rank = vllm_config.parallel_config.data_parallel_rank
|
||||
self.tp_size = vllm_config.parallel_config.tensor_parallel_size
|
||||
# KV cache group whose slot layout the routing data is keyed by.
|
||||
self.attn_gid = get_routed_experts_attn_gid(kv_cache_config)
|
||||
|
||||
def capture(self, layer_id: int, topk_ids: torch.Tensor) -> None:
|
||||
"""Capture expert routing decisions for a specific layer.
|
||||
@@ -139,31 +117,21 @@ class RoutedExpertsCapturer:
|
||||
|
||||
"""
|
||||
ctx = get_forward_context()
|
||||
if ctx.dp_metadata is None: # single dp
|
||||
start_loc = 0
|
||||
end_loc = topk_ids.shape[0]
|
||||
token_num_per_dp = topk_ids.shape[0]
|
||||
else: # multi dp
|
||||
if ctx.dp_metadata is None:
|
||||
local_topk_ids = topk_ids
|
||||
else:
|
||||
num_tokens_dp = ctx.dp_metadata.num_tokens_across_dp_cpu
|
||||
token_num_per_dp = int(num_tokens_dp[self.dp_rank].item())
|
||||
num_local_tokens = int(num_tokens_dp[self.dp_rank].item())
|
||||
total = int(num_tokens_dp.sum().item())
|
||||
n = topk_ids.shape[0]
|
||||
shard_sizes = getattr(ctx.dp_metadata, "local_sizes", None)
|
||||
gathered_size = sum(shard_sizes) if shard_sizes is not None else -1
|
||||
|
||||
if n == total:
|
||||
# Naive dispatch: all DP ranks' tokens concatenated
|
||||
# before routing. This rank owns tokens
|
||||
# [end_loc - token_num_per_dp, end_loc).
|
||||
cumsum = torch.cumsum(num_tokens_dp, dim=0)
|
||||
end_loc = int(cumsum[self.dp_rank].item())
|
||||
start_loc = end_loc - token_num_per_dp
|
||||
elif n == token_num_per_dp:
|
||||
# Modular-kernel path: DP combine happens inside
|
||||
# quant_method.apply; select_experts only sees this
|
||||
# rank's tokens, take the whole tensor.
|
||||
start_loc = 0
|
||||
end_loc = token_num_per_dp
|
||||
end = int(num_tokens_dp[: self.dp_rank + 1].sum().item())
|
||||
local_topk_ids = topk_ids[end - num_local_tokens : end]
|
||||
elif n == num_local_tokens:
|
||||
local_topk_ids = topk_ids
|
||||
elif shard_sizes is not None and n == gathered_size:
|
||||
# Naive DP+EP dispatch gathers the sequence-parallel shards in
|
||||
# flattened DP-then-TP order. ``local_sizes`` is the exact
|
||||
@@ -173,12 +141,11 @@ class RoutedExpertsCapturer:
|
||||
assert len(shard_sizes) % num_dp_ranks == 0
|
||||
shards_per_dp_rank = len(shard_sizes) // num_dp_ranks
|
||||
first_shard = self.dp_rank * shards_per_dp_rank
|
||||
start_loc = sum(shard_sizes[:first_shard])
|
||||
end_loc = start_loc + token_num_per_dp
|
||||
start = sum(shard_sizes[:first_shard])
|
||||
local_topk_ids = topk_ids[start : start + num_local_tokens]
|
||||
elif (
|
||||
self.tp_size > 1
|
||||
and n != token_num_per_dp
|
||||
and n == (token_num_per_dp + self.tp_size - 1) // self.tp_size
|
||||
and n == (num_local_tokens + self.tp_size - 1) // self.tp_size
|
||||
):
|
||||
# SP + modular-kernel path. All-gather across the TP
|
||||
# group along dim=0 to reconstruct the full per-DP-rank
|
||||
@@ -193,60 +160,30 @@ class RoutedExpertsCapturer:
|
||||
#
|
||||
# ``topk_ids`` is already whatever the router produced
|
||||
# (typically int32/int64, both supported by NCCL); the
|
||||
# downstream ``device_buffer[...] = topk_ids[...]``
|
||||
# setitem narrows into int32 automatically.
|
||||
topk_ids = get_tp_group().all_gather(topk_ids, dim=0)
|
||||
start_loc = 0
|
||||
end_loc = token_num_per_dp
|
||||
# downstream buffer assignment narrows to the capture dtype.
|
||||
local_topk_ids = get_tp_group().all_gather(topk_ids, dim=0)[
|
||||
:num_local_tokens
|
||||
]
|
||||
else:
|
||||
sp_expected = (
|
||||
(token_num_per_dp + self.tp_size - 1) // self.tp_size
|
||||
if self.tp_size > 0
|
||||
else -1
|
||||
)
|
||||
sp_expected = (num_local_tokens + self.tp_size - 1) // self.tp_size
|
||||
raise AssertionError(
|
||||
"RoutedExpertsCapturer: unexpected topk_ids batch "
|
||||
f"dim {n} (expected {total}, {token_num_per_dp}, "
|
||||
f"dim {n} (expected {total}, {num_local_tokens}, "
|
||||
f"{gathered_size}, or {sp_expected} for "
|
||||
f"dp_rank={self.dp_rank}, tp_size={self.tp_size})"
|
||||
)
|
||||
|
||||
if layer_id >= self.device_buffer.shape[1]:
|
||||
if not 0 <= layer_id < self.device_buffer.shape[1]:
|
||||
raise IndexError(
|
||||
f"routed-experts layer {layer_id} exceeds capture buffer "
|
||||
f"layer count {self.device_buffer.shape[1]}"
|
||||
)
|
||||
|
||||
self.device_buffer[:token_num_per_dp, layer_id, :] = topk_ids[
|
||||
start_loc:end_loc, :
|
||||
]
|
||||
self.device_buffer[: len(local_topk_ids), layer_id] = local_topk_ids
|
||||
|
||||
def get_device_buffer(self) -> torch.Tensor:
|
||||
"""Return the underlying device buffer so the model runner can
|
||||
issue the D2H copy. The tensor is shared; callers must either
|
||||
clone or fully drain it before the next forward pass overwrites it.
|
||||
"""
|
||||
return self.device_buffer
|
||||
|
||||
def get_routed_experts(
|
||||
self, slot_mappings: torch.Tensor, num_tokens: int
|
||||
) -> RoutedExpertsTensors:
|
||||
"""Snapshot this step's routing data and its attention slot mapping.
|
||||
|
||||
Both tensors are cloned since the capture buffer and the shared
|
||||
``slot_mappings`` are overwritten by the next step, which may race
|
||||
with an in-flight D2H copy.
|
||||
|
||||
Args:
|
||||
slot_mappings: Per-KV-cache-group slot mappings for this step,
|
||||
shape ``(num_kv_cache_groups, max_num_batched_tokens)``.
|
||||
num_tokens: Total number of tokens scheduled in this step.
|
||||
|
||||
"""
|
||||
return RoutedExpertsTensors(
|
||||
routing_data=self.device_buffer[:num_tokens].clone(),
|
||||
slot_mapping=slot_mappings[self.attn_gid, :num_tokens].clone(),
|
||||
)
|
||||
def snapshot_routing_data(self, num_tokens: int) -> torch.Tensor:
|
||||
"""Return a stable snapshot of the current routing data."""
|
||||
return self.device_buffer[:num_tokens].to(self.output_dtype)
|
||||
|
||||
|
||||
def bind_routed_experts_capturer(
|
||||
@@ -268,20 +205,12 @@ def bind_routed_experts_capturer(
|
||||
continue
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
layer_id = module.layer_id
|
||||
|
||||
def capture_fn(
|
||||
topk_ids: torch.Tensor,
|
||||
layer_id: int = layer_id,
|
||||
capturer: RoutedExpertsCapturer = capturer,
|
||||
) -> None:
|
||||
capturer.capture(layer_id, topk_ids)
|
||||
|
||||
capture_fn = partial(capturer.capture, module.layer_id)
|
||||
quant_method = module._quant_method
|
||||
moe_kernel = getattr(quant_method, "moe_kernel", None)
|
||||
impl = getattr(moe_kernel, "impl", None)
|
||||
fused_experts = getattr(impl, "fused_experts", None)
|
||||
if quant_method.is_monolithic:
|
||||
moe_kernel = getattr(quant_method, "moe_kernel", None)
|
||||
impl = getattr(moe_kernel, "impl", None)
|
||||
fused_experts = getattr(impl, "fused_experts", None)
|
||||
if not (
|
||||
isinstance(fused_experts, FusedMoEExpertsMonolithic)
|
||||
and fused_experts.supports_routing_replay_capture()
|
||||
@@ -303,132 +232,3 @@ def bind_routed_experts_capturer(
|
||||
|
||||
if num_bound == 0:
|
||||
raise ValueError("No supported MoE router found for routed-experts capture.")
|
||||
|
||||
|
||||
def get_routed_experts_attn_gid(kv_cache_config: KVCacheConfig) -> int:
|
||||
"""Return the full-attention KV cache group used for routed experts."""
|
||||
for gid, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
if is_full_attention_spec(group.kv_cache_spec):
|
||||
return gid
|
||||
raise ValueError("Routed-experts capture requires a full-attention KV cache group.")
|
||||
|
||||
|
||||
class RoutedExpertsManager:
|
||||
"""Scheduler-side slot-indexed buffer for routed experts.
|
||||
|
||||
Lives on CPU in the scheduler process. Each slot corresponds to
|
||||
``block_id * block_size + offset_in_block`` where ``block_id`` is
|
||||
drawn from the physical KV-cache block pool, so routing data is
|
||||
tied to physical blocks and naturally survives preemption for
|
||||
prefix-cached blocks (prefix hits re-expose the same slots).
|
||||
|
||||
Data flow per step:
|
||||
1. Worker D2Hs its device capture buffer into
|
||||
:class:`RoutedExpertsLists` and returns it via
|
||||
:class:`ModelRunnerOutput`.
|
||||
2. Scheduler calls :meth:`store_batch` with that step's
|
||||
``(routing_data, slot_mapping)`` — a single CPU->CPU
|
||||
fancy-index assign, ~few MB per step.
|
||||
3. On request completion / abort / preemption, the scheduler
|
||||
calls :meth:`get` with the request's block IDs to recover
|
||||
the full per-token routing.
|
||||
|
||||
Memory: ``routed_experts_by_slot`` is sized for the whole block
|
||||
pool (``num_blocks * block_size`` slots). For large block pools
|
||||
this can reach multiple GB; see the init log for the exact size.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
) -> None:
|
||||
# Hybrid models also have KV groups whose slot layout differs.
|
||||
self.attn_gid = get_routed_experts_attn_gid(kv_cache_config)
|
||||
attn_group = kv_cache_config.kv_cache_groups[self.attn_gid]
|
||||
self.block_size = attn_group.kv_cache_spec.block_size
|
||||
|
||||
# All kv_cache_groups share the same physical block pool, so
|
||||
# block IDs span [0, num_blocks) regardless of how many groups
|
||||
# exist. Sizing to the full pool avoids index-out-of-range
|
||||
# when different groups happen to land on the same block.
|
||||
num_layers, num_experts, num_experts_per_tok = _get_routed_experts_shape(
|
||||
vllm_config
|
||||
)
|
||||
max_num_slots = kv_cache_config.num_blocks * self.block_size
|
||||
# Expert IDs are 0..num_experts-1; uint8 fits 256 distinct
|
||||
# values so the boundary is ``<= 256`` (NOT ``< 256``). Keeping
|
||||
# this narrow matters because the slot buffer is sized for the
|
||||
# whole block pool and can reach multiple GB.
|
||||
expert_id_dtype = np.uint8 if num_experts <= 256 else np.uint16
|
||||
self.routed_experts_by_slot = np.zeros(
|
||||
(
|
||||
max_num_slots,
|
||||
num_layers,
|
||||
num_experts_per_tok,
|
||||
),
|
||||
dtype=expert_id_dtype,
|
||||
)
|
||||
logger.info(
|
||||
"RoutedExpertsManager CPU buffer: %.2f GB "
|
||||
"(slots=%d, layers=%d, top_k=%d, dtype=%s)",
|
||||
self.routed_experts_by_slot.nbytes / 1e9,
|
||||
max_num_slots,
|
||||
num_layers,
|
||||
num_experts_per_tok,
|
||||
self.routed_experts_by_slot.dtype.name,
|
||||
)
|
||||
|
||||
def store_batch(self, data: np.ndarray, slot_mapping: np.ndarray) -> None:
|
||||
"""Persist one step's routed experts into the slot buffer.
|
||||
|
||||
Equivalent to ``slot_buffer[slot_mapping] = data``; numpy fancy
|
||||
indexing handles repeated / out-of-order indices. Called once
|
||||
per scheduler step in ``update_from_output``.
|
||||
"""
|
||||
self.routed_experts_by_slot[slot_mapping] = data
|
||||
|
||||
def get(
|
||||
self,
|
||||
block_ids: list[int],
|
||||
num_tokens: int,
|
||||
token_start: int = 0,
|
||||
) -> np.ndarray:
|
||||
"""Read routed experts data for a completed / preempted request.
|
||||
|
||||
Reconstructs a per-token slot_mapping from the request's block
|
||||
IDs and returns the routing slice. Because numpy fancy indexing
|
||||
returns a **copy** (not a view), the returned ndarray is safe
|
||||
to hold across subsequent :meth:`store_batch` calls — do not
|
||||
replace the fancy index with a slice without re-verifying.
|
||||
|
||||
Args:
|
||||
block_ids: Block IDs from the attention KV-cache group.
|
||||
num_tokens: Number of tokens that have gone through a forward
|
||||
pass and therefore have routing data written to their
|
||||
slots (typically ``request.num_tokens - 1``; the last
|
||||
sampled token has not been forwarded yet). Slots beyond
|
||||
``request.num_computed_tokens`` are zero-initialized.
|
||||
token_start: Skip the first ``token_start`` tokens from the
|
||||
result. The slot_mapping is sliced before the fancy-index
|
||||
read, so only the requested slots are fetched — no large
|
||||
intermediate array is allocated. Clamped to
|
||||
``[0, num_tokens]`` automatically.
|
||||
|
||||
Returns:
|
||||
Array of shape (num_tokens - token_start, num_layers,
|
||||
num_experts_per_tok).
|
||||
|
||||
"""
|
||||
bs = self.block_size
|
||||
block_ids_array = np.array(block_ids, dtype=np.int32)
|
||||
block_offsets = np.arange(bs)
|
||||
# slot = block_id * block_size + offset_in_block; flatten the
|
||||
# (num_blocks, block_size) grid and trim to num_tokens, then
|
||||
# skip the first token_start entries so only the requested
|
||||
# range is fetched in a single fancy-index read.
|
||||
slot_mapping = (
|
||||
block_ids_array.reshape(-1, 1) * bs + block_offsets.reshape(1, -1)
|
||||
).flatten()[:num_tokens]
|
||||
slot_mapping = slot_mapping[token_start:]
|
||||
return self.routed_experts_by_slot[slot_mapping]
|
||||
|
||||
@@ -45,6 +45,7 @@ from vllm.model_executor.layers.fused_moe.runner.shared_experts import (
|
||||
SharedExperts,
|
||||
SharedExpertsOrder,
|
||||
)
|
||||
from vllm.model_executor.layers.utils import dispatch_unquantized_gemm
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import (
|
||||
_USE_LAYERNAME,
|
||||
@@ -273,7 +274,7 @@ class MoERunner(MoERunnerInterface):
|
||||
|
||||
# When both gates are present and FSE is enabled, fuse their
|
||||
# weight matrices into [num_experts + num_shared, hidden] so one
|
||||
# F.linear produces combined logits. The topk kernel can then
|
||||
# GEMM produces combined logits. The topk kernel can then
|
||||
# apply routing softmax and shared expert activation (sigmoid)
|
||||
# in a single launch.
|
||||
self._fse_fuse_gate = gate is not None and shared_expert_gate is not None
|
||||
@@ -898,7 +899,9 @@ class MoERunner(MoERunnerInterface):
|
||||
if self.gate is not None:
|
||||
if self._fse_fuse_gate:
|
||||
self._maybe_fuse_gate_weights()
|
||||
router_logits = F.linear(hidden_states, self._combined_gate_weight)
|
||||
router_logits = dispatch_unquantized_gemm()(
|
||||
self, hidden_states, self._combined_gate_weight, None
|
||||
)
|
||||
else:
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
|
||||
|
||||
@@ -119,6 +119,14 @@ class RMSNorm(CustomOp):
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
if envs.VLLM_BATCH_INVARIANT and residual is not None:
|
||||
assert self.variance_size_override is None, (
|
||||
"Batch invariance is not supported for variance_size_override"
|
||||
)
|
||||
weight = self.weight.data if self.pass_weight_add else None
|
||||
return ir.ops.fused_add_rms_norm.impls["native"].impl_fn(
|
||||
x, residual, weight, self.variance_epsilon
|
||||
)
|
||||
return self.forward_cuda(x, residual)
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
@@ -171,6 +179,15 @@ class GemmaRMSNorm(CustomOp):
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
if residual is None:
|
||||
return self.forward_cuda(x, residual)
|
||||
return ir.ops.fused_add_rms_norm.impls["native"].impl_fn(
|
||||
x,
|
||||
residual,
|
||||
self.weight.float() + 1.0,
|
||||
self.variance_epsilon,
|
||||
)
|
||||
import vllm._xpu_ops # noqa: F401 registers torch.ops.vllm.xpu_gemma_rms_norm
|
||||
|
||||
# Fall back to the native path if the fused gemma kernels are not
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
MambaSpec,
|
||||
get_mamba_prefill_checkpoint_position,
|
||||
is_mamba_prefill_checkpoint_valid,
|
||||
)
|
||||
|
||||
|
||||
def compute_mamba_prefill_checkpoints(
|
||||
seq_lens: list[int],
|
||||
query_lens: list[int],
|
||||
hash_block_size: int,
|
||||
mamba_block_size: int,
|
||||
checkpoint_alignment: int | None,
|
||||
drop_eagle_block: bool,
|
||||
) -> tuple[list[int], list[int]]:
|
||||
"""Per-row internal prefill checkpoint offsets and cache block columns.
|
||||
|
||||
Backends call this instead of re-deriving the rules, so they decline in
|
||||
lockstep with the scheduler and ``MambaManager``: allocating a checkpoint
|
||||
block without writing it leaves the prefix cache serving uninitialized
|
||||
state.
|
||||
|
||||
Returns:
|
||||
``(offsets, cols)``: the checkpoint's offset into each row's query and
|
||||
its block-table column. ``0`` and ``-1`` mean the row has none.
|
||||
|
||||
"""
|
||||
offsets: list[int] = []
|
||||
cols: list[int] = []
|
||||
for seq_len, query_len in zip(seq_lens, query_lens):
|
||||
query_start = seq_len - query_len
|
||||
position = get_mamba_prefill_checkpoint_position(
|
||||
seq_len, hash_block_size, drop_eagle_block=drop_eagle_block
|
||||
)
|
||||
valid = is_mamba_prefill_checkpoint_valid(
|
||||
query_start=query_start,
|
||||
query_end=seq_len,
|
||||
checkpoint_position=position,
|
||||
hash_block_size=hash_block_size,
|
||||
mamba_block_size=mamba_block_size,
|
||||
checkpoint_alignment=checkpoint_alignment,
|
||||
)
|
||||
offsets.append(position - query_start if valid else 0)
|
||||
cols.append(cdiv(seq_len, mamba_block_size) - 2 if valid else -1)
|
||||
return offsets, cols
|
||||
|
||||
|
||||
@dataclass
|
||||
class MambaPrefillCheckpointMetadata:
|
||||
checkpoint_offsets: torch.Tensor
|
||||
state_indices: torch.Tensor
|
||||
|
||||
|
||||
class MambaPrefillCheckpointBuilder:
|
||||
"""Build backend-neutral prefill checkpoint locations."""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, kv_cache_spec: MambaSpec) -> None:
|
||||
self.vllm_config = vllm_config
|
||||
self.kv_cache_spec = kv_cache_spec
|
||||
|
||||
def build(
|
||||
self,
|
||||
m: CommonAttentionMetadata,
|
||||
request_rows: list[int],
|
||||
) -> MambaPrefillCheckpointMetadata | None:
|
||||
if self.kv_cache_spec.num_prefill_checkpoint_blocks == 0:
|
||||
return None
|
||||
assert m.seq_lens_cpu_upper_bound is not None
|
||||
all_query_lens = m.query_start_loc_cpu.diff().tolist()
|
||||
query_lens = [all_query_lens[row] for row in request_rows]
|
||||
seq_lens = m.seq_lens_cpu_upper_bound.tolist()
|
||||
block_size = self.kv_cache_spec.block_size
|
||||
hash_block_size = self.vllm_config.cache_config.prefix_match_unit or block_size
|
||||
speculative_config = self.vllm_config.speculative_config
|
||||
drop_eagle_block = (
|
||||
speculative_config is not None and speculative_config.use_eagle_block_drop()
|
||||
)
|
||||
checkpoint_offsets, checkpoint_cols = compute_mamba_prefill_checkpoints(
|
||||
[seq_lens[row] for row in request_rows],
|
||||
query_lens,
|
||||
hash_block_size=hash_block_size,
|
||||
mamba_block_size=block_size,
|
||||
checkpoint_alignment=self.kv_cache_spec.prefill_checkpoint_alignment,
|
||||
drop_eagle_block=drop_eagle_block,
|
||||
)
|
||||
if not any(checkpoint_offsets):
|
||||
return None
|
||||
checkpoint_offsets_tensor = async_tensor_h2d(
|
||||
checkpoint_offsets,
|
||||
dtype=torch.int32,
|
||||
device=m.query_start_loc.device,
|
||||
)
|
||||
request_rows_tensor = async_tensor_h2d(
|
||||
request_rows, dtype=torch.int64, device=m.query_start_loc.device
|
||||
)
|
||||
checkpoint_cols_tensor = async_tensor_h2d(
|
||||
checkpoint_cols, dtype=torch.int64, device=m.query_start_loc.device
|
||||
)
|
||||
checkpoint_state_indices = m.block_table_tensor[
|
||||
request_rows_tensor, checkpoint_cols_tensor
|
||||
]
|
||||
checkpoint_state_indices = torch.where(
|
||||
checkpoint_cols_tensor >= 0,
|
||||
checkpoint_state_indices,
|
||||
NULL_BLOCK_ID,
|
||||
)
|
||||
return MambaPrefillCheckpointMetadata(
|
||||
checkpoint_offsets_tensor,
|
||||
checkpoint_state_indices,
|
||||
)
|
||||
|
||||
|
||||
class MambaPrefillCheckpointExporter(ABC):
|
||||
"""Export a mid-prefill checkpoint into backend-specific paged states."""
|
||||
|
||||
@abstractmethod
|
||||
def export(
|
||||
self,
|
||||
checkpoint: MambaPrefillCheckpointMetadata,
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Write checkpoint state into the paged cache."""
|
||||
raise NotImplementedError
|
||||
@@ -329,8 +329,7 @@ class KimiGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
) -> torch.Tensor:
|
||||
num_tokens = hidden_states.size(0)
|
||||
projected_qkvgfab = self.in_proj_qkvgfab(hidden_states)[0]
|
||||
if self.use_full_rank_gate:
|
||||
@@ -375,7 +374,7 @@ class KimiGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
core_attn_out=core_attn_out,
|
||||
)
|
||||
core_attn_out = rearrange(core_attn_out, "1 n h d -> n (h d)")
|
||||
output[:] = self.o_proj(core_attn_out)[0]
|
||||
return self.o_proj(core_attn_out)[0]
|
||||
|
||||
@eager_break_during_capture
|
||||
def _forward(
|
||||
|
||||
@@ -852,13 +852,8 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
The RMSNormGated + quant sequence is eligible for fusion
|
||||
by the compilation pass when fuse_norm_quant is enabled.
|
||||
"""
|
||||
z_shape_og = z.shape
|
||||
core_attn_out = core_attn_out.reshape(-1, core_attn_out.shape[-1])
|
||||
z = z.reshape(-1, z.shape[-1])
|
||||
core_attn_out = self.norm(core_attn_out, z)
|
||||
core_attn_out = core_attn_out.reshape(z_shape_og)
|
||||
core_attn_out = core_attn_out.flatten(-2) # ... h d -> ... (h d)
|
||||
output, _ = self.out_proj(core_attn_out)
|
||||
output, _ = self.out_proj(core_attn_out.flatten(-2))
|
||||
return output
|
||||
|
||||
def forward_hip(
|
||||
@@ -1012,15 +1007,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
# ============================================================
|
||||
# Part 3: Output Projection
|
||||
# ============================================================
|
||||
z_shape_og = z.shape
|
||||
# Reshape input data into 2D tensor
|
||||
core_attn_out = core_attn_out.reshape(-1, core_attn_out.shape[-1])
|
||||
z = z.reshape(-1, z.shape[-1])
|
||||
core_attn_out = self.norm(core_attn_out, z)
|
||||
core_attn_out = core_attn_out.reshape(z_shape_og)
|
||||
core_attn_out = core_attn_out.flatten(-2) # ... h d -> ... (h d)
|
||||
out, _ = self.out_proj(core_attn_out)
|
||||
return out
|
||||
return self._output_projection(core_attn_out, z)
|
||||
|
||||
def forward_cpu(
|
||||
self,
|
||||
@@ -1063,14 +1050,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
_encode_layer_name(self.prefix),
|
||||
)
|
||||
|
||||
z_shape_og = z.shape
|
||||
core_attn_out = core_attn_out.reshape(-1, core_attn_out.shape[-1])
|
||||
z = z.reshape(-1, z.shape[-1])
|
||||
core_attn_out = self.norm(core_attn_out, z)
|
||||
core_attn_out = core_attn_out.reshape(z_shape_og)
|
||||
core_attn_out = core_attn_out.flatten(-2) # ... h d -> ... (h d)
|
||||
out, _ = self.out_proj(core_attn_out)
|
||||
return out
|
||||
return self._output_projection(core_attn_out, z)
|
||||
|
||||
def _warmup_prefill_kernels(self, qkv_or_qkvz: torch.Tensor, v_dim: int) -> None:
|
||||
"""Warm up GDN prefill kernels during V1 profiling.
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.mamba.checkpoint import (
|
||||
MambaPrefillCheckpointExporter,
|
||||
MambaPrefillCheckpointMetadata,
|
||||
)
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
|
||||
|
||||
def kda_prefill_checkpoint_alignment(backend: str) -> int | None:
|
||||
return 16 if backend == "flashkda" else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FlashKDAPrefillCheckpointExporter(MambaPrefillCheckpointExporter):
|
||||
"""Store FlashKDA recurrent and convolution checkpoint states."""
|
||||
|
||||
state_len: int | None = None
|
||||
|
||||
def export(
|
||||
self,
|
||||
checkpoint: MambaPrefillCheckpointMetadata,
|
||||
*,
|
||||
raw_qkv: torch.Tensor,
|
||||
conv_state: torch.Tensor,
|
||||
recurrent_checkpoint: torch.Tensor,
|
||||
recurrent_state: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor,
|
||||
) -> None:
|
||||
state_len = (
|
||||
self.state_len if self.state_len is not None else conv_state.shape[-1]
|
||||
)
|
||||
width = raw_qkv.shape[-1]
|
||||
recurrent_row_size = recurrent_checkpoint[0].numel()
|
||||
block_size = 256
|
||||
store_cache_checkpoints_kernel[
|
||||
(
|
||||
checkpoint.checkpoint_offsets.numel(),
|
||||
triton.cdiv(max(width * state_len, recurrent_row_size), block_size),
|
||||
)
|
||||
](
|
||||
raw_qkv,
|
||||
conv_state,
|
||||
recurrent_checkpoint,
|
||||
recurrent_state,
|
||||
cu_seqlens,
|
||||
checkpoint.checkpoint_offsets,
|
||||
checkpoint.state_indices,
|
||||
raw_qkv.stride(0),
|
||||
raw_qkv.stride(1),
|
||||
conv_state.stride(0),
|
||||
conv_state.stride(1),
|
||||
conv_state.stride(2),
|
||||
recurrent_checkpoint.stride(0),
|
||||
recurrent_state.stride(0),
|
||||
checkpoint.checkpoint_offsets.stride(0),
|
||||
state_len,
|
||||
width,
|
||||
recurrent_row_size,
|
||||
NULL_BLOCK_ID,
|
||||
block_size,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def store_cache_checkpoints_kernel(
|
||||
x_ptr,
|
||||
conv_state_ptr,
|
||||
recurrent_checkpoint_ptr,
|
||||
recurrent_state_ptr,
|
||||
query_start_loc_ptr,
|
||||
checkpoint_offsets_ptr,
|
||||
checkpoint_state_indices_ptr,
|
||||
x_stride_0: tl.constexpr,
|
||||
x_stride_1: tl.constexpr,
|
||||
state_stride_0: tl.constexpr,
|
||||
state_stride_1: tl.constexpr,
|
||||
state_stride_2: tl.constexpr,
|
||||
checkpoint_stride_0: tl.constexpr,
|
||||
recurrent_state_stride_0: tl.constexpr,
|
||||
checkpoint_offset_stride: tl.constexpr,
|
||||
STATE_LEN: tl.constexpr,
|
||||
WIDTH: tl.constexpr,
|
||||
RECURRENT_ROW_SIZE: tl.constexpr,
|
||||
NULL_STATE_IDX: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
seq_idx = tl.program_id(0)
|
||||
cols = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
state_idx = tl.load(checkpoint_state_indices_ptr + seq_idx).to(tl.int64)
|
||||
checkpoint_offset = tl.load(
|
||||
checkpoint_offsets_ptr + seq_idx * checkpoint_offset_stride
|
||||
)
|
||||
valid_checkpoint = (state_idx != NULL_STATE_IDX) & (checkpoint_offset > 0)
|
||||
valid_conv = (
|
||||
(cols < WIDTH * STATE_LEN) & valid_checkpoint & (checkpoint_offset >= STATE_LEN)
|
||||
)
|
||||
width_idx = cols // STATE_LEN
|
||||
history_idx = cols % STATE_LEN
|
||||
checkpoint_end = tl.load(query_start_loc_ptr + seq_idx) + checkpoint_offset
|
||||
token_idx = checkpoint_end - STATE_LEN + history_idx
|
||||
values = tl.load(
|
||||
x_ptr + token_idx * x_stride_0 + width_idx * x_stride_1,
|
||||
mask=valid_conv,
|
||||
)
|
||||
tl.store(
|
||||
conv_state_ptr
|
||||
+ state_idx * state_stride_0
|
||||
+ width_idx * state_stride_1
|
||||
+ history_idx * state_stride_2,
|
||||
values,
|
||||
mask=valid_conv,
|
||||
)
|
||||
|
||||
valid_recurrent = (cols < RECURRENT_ROW_SIZE) & valid_checkpoint
|
||||
recurrent = tl.load(
|
||||
recurrent_checkpoint_ptr + seq_idx * checkpoint_stride_0 + cols,
|
||||
mask=valid_recurrent,
|
||||
)
|
||||
tl.store(
|
||||
recurrent_state_ptr + state_idx * recurrent_state_stride_0 + cols,
|
||||
recurrent,
|
||||
mask=valid_recurrent,
|
||||
)
|
||||
@@ -713,7 +713,7 @@ class AutoAWQMoEMethod(FusedMoEMethodBase):
|
||||
|
||||
def get_fused_moe_quant_config(self, layer: RoutedExperts) -> FusedMoEQuantConfig:
|
||||
if self.wna16_moe_backend == WNA16MoEBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -689,7 +689,7 @@ class AutoGPTQMoEMethod(FusedMoEMethodBase):
|
||||
|
||||
def get_fused_moe_quant_config(self, layer: RoutedExperts) -> FusedMoEQuantConfig:
|
||||
if self.wna16_moe_backend == WNA16MoEBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
+1
-1
@@ -474,7 +474,7 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
|
||||
self, layer: torch.nn.Module
|
||||
) -> FusedMoEQuantConfig | None:
|
||||
if self.wna16_backend == WNA16MoEBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Callable
|
||||
from math import gcd
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import regex as re
|
||||
@@ -28,12 +29,15 @@ from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
QuantizeMethodBase,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
check_and_fallback_input_schema,
|
||||
convert_to_humming_moe_kernel_format,
|
||||
get_humming_linear_compute_config,
|
||||
get_humming_moe_quant_config,
|
||||
humming_update_schema_hadamard_block_size,
|
||||
input_schema_to_quant_key,
|
||||
make_humming_moe_kernel,
|
||||
resolve_humming_layer_config,
|
||||
select_humming_moe_experts,
|
||||
weight_schema_to_quant_key,
|
||||
)
|
||||
@@ -227,23 +231,13 @@ class HummingConfig(QuantizationConfig):
|
||||
return None
|
||||
config = group_config
|
||||
|
||||
layer_config = config
|
||||
layer_dynamic = config.get("dynamic", {})
|
||||
if not isinstance(layer_dynamic, dict):
|
||||
layer_dynamic = {}
|
||||
for regex, override_config in layer_dynamic.items():
|
||||
if regex[:1] != "+":
|
||||
continue
|
||||
if re.match(regex[2:], prefix):
|
||||
layer_config = config.copy()
|
||||
layer_config.update(override_config)
|
||||
break
|
||||
layer_config = resolve_humming_layer_config(config, prefix)
|
||||
|
||||
if "quant_method" in layer_config:
|
||||
return _hm.BaseWeightSchema.from_config(layer_config)
|
||||
return None
|
||||
|
||||
def get_layer_input_schema(self, config: dict[str, Any], prefix: str):
|
||||
def get_layer_input_config(self, config: dict[str, Any], prefix: str):
|
||||
if self.is_layer_skipped(config, prefix):
|
||||
return None
|
||||
if config["quant_method"] in ["compressed-tensors", "modelopt"]:
|
||||
@@ -252,10 +246,15 @@ class HummingConfig(QuantizationConfig):
|
||||
return None
|
||||
config = group_config
|
||||
|
||||
config = resolve_humming_layer_config(config, prefix)
|
||||
if config.get("quant_method", None) in _hm.BaseInputSchema.INPUT_SCHEMA_MAP:
|
||||
return _hm.BaseInputSchema.from_config(config)
|
||||
return config
|
||||
return None
|
||||
|
||||
def get_layer_input_schema(self, config: dict[str, Any], prefix: str):
|
||||
config = self.get_layer_input_config(config, prefix)
|
||||
return None if config is None else _hm.BaseInputSchema.from_config(config)
|
||||
|
||||
def get_quant_config_for_layer(
|
||||
self, prefix: str, layer_type: str
|
||||
) -> "HummingLayerQuantizationConfig | None":
|
||||
@@ -279,14 +278,25 @@ class HummingConfig(QuantizationConfig):
|
||||
if weight_schema is not None:
|
||||
input_schema = None
|
||||
force_input_schema = None
|
||||
allow_input_schema_fallback = True
|
||||
|
||||
if self.full_config:
|
||||
input_schema = self.get_layer_input_schema(self.full_config, prefix)
|
||||
input_config = self.get_layer_input_config(self.full_config, prefix)
|
||||
if input_config is not None:
|
||||
allow_input_schema_fallback = input_config.pop(
|
||||
"allow_fallback", True
|
||||
)
|
||||
input_schema = _hm.BaseInputSchema.from_config(input_config)
|
||||
|
||||
if envs.VLLM_HUMMING_INPUT_QUANT_CONFIG:
|
||||
quant_config = envs.VLLM_HUMMING_INPUT_QUANT_CONFIG.copy()
|
||||
quant_config["quant_method"] = "humming"
|
||||
force_input_schema = self.get_layer_input_schema(quant_config, prefix)
|
||||
input_config = self.get_layer_input_config(quant_config, prefix)
|
||||
if input_config is not None:
|
||||
allow_input_schema_fallback = input_config.pop(
|
||||
"allow_fallback", False
|
||||
)
|
||||
force_input_schema = _hm.BaseInputSchema.from_config(input_config)
|
||||
if input_schema is None:
|
||||
input_schema = force_input_schema
|
||||
|
||||
@@ -299,6 +309,7 @@ class HummingConfig(QuantizationConfig):
|
||||
force_weight_schema=force_weight_schema,
|
||||
force_input_schema=force_input_schema,
|
||||
is_online_quant=is_online_quant,
|
||||
allow_input_schema_fallback=allow_input_schema_fallback,
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -318,6 +329,11 @@ class HummingConfig(QuantizationConfig):
|
||||
elif isinstance(layer, LinearBase):
|
||||
return UnquantizedLinearMethod()
|
||||
elif isinstance(layer, LinearBase):
|
||||
input_size = layer.input_size
|
||||
partition_size = getattr(layer, "input_size_per_partition", input_size)
|
||||
is_online_quant = quant_config.is_online_quant
|
||||
if is_online_quant and (input_size % 32 != 0 or partition_size % 32 != 0):
|
||||
return UnquantizedLinearMethod()
|
||||
return HummingLinearMethod(quant_config)
|
||||
elif isinstance(layer, RoutedExperts):
|
||||
return HummingMoEMethod(quant_config, layer.moe_config)
|
||||
@@ -332,6 +348,7 @@ class HummingLayerQuantizationConfig(HummingConfig):
|
||||
force_weight_schema: "HummingWeightSchema | None" = None,
|
||||
force_input_schema: "HummingInputSchema | None" = None,
|
||||
is_online_quant: bool = False,
|
||||
allow_input_schema_fallback: bool = True,
|
||||
):
|
||||
self.weight_schema = weight_schema
|
||||
if input_schema is None:
|
||||
@@ -340,6 +357,7 @@ class HummingLayerQuantizationConfig(HummingConfig):
|
||||
self.force_weight_schema = force_weight_schema
|
||||
self.force_input_schema = force_input_schema
|
||||
self.is_online_quant = is_online_quant
|
||||
self.allow_input_schema_fallback = allow_input_schema_fallback
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config):
|
||||
@@ -373,21 +391,13 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
if is_unquantized and self.is_online_quant:
|
||||
# online quant (fp16/bf16 -> quant_type)
|
||||
assert isinstance(self.weight_schema, _hm.HummingWeightSchema)
|
||||
f16_dtype = _hm.DataType.from_torch_dtype(layer.param_dtype)
|
||||
has_global_scale = "TENSOR" in str(self.weight_schema.weight_scale_type)
|
||||
tensor_list = _hm.quantize_weight(
|
||||
weight=loaded_weight,
|
||||
dtype=self.weight_schema.b_dtype,
|
||||
scale_dtype=self.weight_schema.bs_dtype or f16_dtype,
|
||||
group_size=self.weight_schema.weight_scale_group_size,
|
||||
has_zero_point=self.weight_schema.has_zero_point,
|
||||
has_global_scale=has_global_scale,
|
||||
is_fp_zero_point=self.weight_schema.is_fp_zero_point,
|
||||
pack=True,
|
||||
tensors = self.weight_schema.quant_tensor(
|
||||
loaded_weight.to(param.device),
|
||||
self.weight_schema,
|
||||
layer.param_dtype,
|
||||
)
|
||||
|
||||
key_list = ["weight", "weight_scale", "zero_point", "global_scale"]
|
||||
for key, tensor in zip(key_list, tensor_list):
|
||||
for key, tensor in tensors.items():
|
||||
if tensor is None or tensor.nelement() == 0:
|
||||
continue
|
||||
param = getattr(layer, key)
|
||||
@@ -459,6 +469,18 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
layer.output_partition_sizes = output_partition_sizes
|
||||
layer.extra_weight_attrs = extra_weight_attrs.copy()
|
||||
|
||||
input_schema = self.force_input_schema or self.input_schema
|
||||
input_schema = input_schema.to_humming_schema(params_dtype)
|
||||
for name in ("weight_schema", "force_weight_schema"):
|
||||
schema = getattr(self, name)
|
||||
if getattr(schema, "hadamard_block_size", None) == -1:
|
||||
schema = humming_update_schema_hadamard_block_size(
|
||||
weight_schema=schema,
|
||||
input_schema=input_schema,
|
||||
shape_k=input_size_per_partition,
|
||||
)
|
||||
setattr(self, name, schema)
|
||||
|
||||
weight_loader = extra_weight_attrs.get("weight_loader", default_weight_loader)
|
||||
new_weight_loader = self.prepare_weight_loader(layer, weight_loader)
|
||||
extra_weight_attrs["weight_loader"] = new_weight_loader
|
||||
@@ -502,7 +524,10 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
return None
|
||||
|
||||
# convert from checkpoint format to humming format
|
||||
if not isinstance(self.weight_schema, _hm.HummingWeightSchema):
|
||||
is_humming_weight = isinstance(self.weight_schema, _hm.HummingWeightSchema)
|
||||
is_humming_input = isinstance(self.input_schema, _hm.HummingInputSchema)
|
||||
|
||||
if not is_humming_weight or not is_humming_input:
|
||||
self.weight_schema, tensors = self.weight_schema.convert_humming(
|
||||
tensors=layer.state_dict(),
|
||||
shape_n_stacks=layer.output_partition_sizes,
|
||||
@@ -510,12 +535,13 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
param_dtype=layer.param_dtype,
|
||||
)
|
||||
|
||||
self.input_schema, _ = self.input_schema.convert_humming(
|
||||
self.input_schema, input_tensors = self.input_schema.convert_humming(
|
||||
tensors=layer.state_dict(),
|
||||
shape_n_stacks=layer.output_partition_sizes,
|
||||
shape_k_stacks=[layer.input_size_per_partition],
|
||||
param_dtype=layer.param_dtype,
|
||||
)
|
||||
tensors.update(input_tensors)
|
||||
|
||||
for name, _ in list(layer.named_parameters()):
|
||||
delattr(layer, name)
|
||||
@@ -530,11 +556,15 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
assert isinstance(self.weight_schema, _hm.HummingWeightSchema)
|
||||
force_requant = self.force_weight_schema is not None
|
||||
if force_requant and self.weight_schema != self.force_weight_schema:
|
||||
source_tensors = layer.state_dict()
|
||||
tensors = self.weight_schema.requant_tensors(
|
||||
tensors=layer.state_dict(),
|
||||
tensors=source_tensors,
|
||||
target_weight_schema=self.force_weight_schema,
|
||||
param_dtype=layer.param_dtype,
|
||||
)
|
||||
name = self.input_schema.static_tensor_scale_name
|
||||
if name is not None:
|
||||
tensors[name] = source_tensors[name]
|
||||
|
||||
self.weight_schema = self.force_weight_schema
|
||||
|
||||
@@ -548,6 +578,12 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
|
||||
del tensors
|
||||
|
||||
self.input_schema = check_and_fallback_input_schema(
|
||||
weight_schema=self.weight_schema,
|
||||
input_schema=self.input_schema,
|
||||
param_dtype=layer.param_dtype,
|
||||
allow_fallback=self.quant_config.allow_input_schema_fallback,
|
||||
)
|
||||
self.layer_config = _hm.prepare_layer_config(
|
||||
shape_n=layer.output_partition_sizes_sum,
|
||||
shape_k=layer.input_size_per_partition,
|
||||
@@ -557,10 +593,16 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
pad_k_to_multiple=128,
|
||||
has_bias=layer.has_bias,
|
||||
torch_dtype=layer.param_dtype,
|
||||
device=layer.weight.device,
|
||||
)
|
||||
tensors = _hm.transform_humming_tensors(
|
||||
self.layer_config, dict(layer.named_parameters())
|
||||
)
|
||||
source_tensors = dict(layer.named_parameters())
|
||||
tensors = _hm.transform_humming_tensors(self.layer_config, source_tensors)
|
||||
name = self.input_schema.static_tensor_scale_name
|
||||
if name is not None:
|
||||
tensors[name] = source_tensors[name]
|
||||
if "bias" in tensors:
|
||||
zero_bias = torch.zeros_like(tensors["bias"])
|
||||
layer.register_buffer("zero_bias", zero_bias)
|
||||
for name, _ in list(layer.named_parameters()):
|
||||
delattr(layer, name)
|
||||
for name, tensor in tensors.items():
|
||||
@@ -583,8 +625,11 @@ class HummingLinearMethod(LinearMethodBase):
|
||||
weight=layer.weight,
|
||||
weight_scale=getattr(layer, "weight_scale", None),
|
||||
zero_point=getattr(layer, "zero_point", None),
|
||||
bias=getattr(layer, "bias", None),
|
||||
bias=getattr(layer, "bias" if bias is not None else "zero_bias", None),
|
||||
weight_scale_2=getattr(layer, "weight_scale_2", None),
|
||||
input_scale=getattr(layer, "input_scale", None),
|
||||
input_scale_2=getattr(layer, "input_scale_2", None),
|
||||
hadamard_block_size=self.weight_schema.hadamard_block_size,
|
||||
locks=self.locks,
|
||||
compute_config=self.compute_config,
|
||||
)
|
||||
@@ -606,11 +651,15 @@ class HummingMoEMethod(FusedMoEMethodBase):
|
||||
# Derive QuantKeys from humming schemas.
|
||||
# Prefer force schemas (the final format after requant) over base.
|
||||
weight_key = weight_schema_to_quant_key(
|
||||
self.force_weight_schema or self.weight_schema
|
||||
self.force_weight_schema or self.weight_schema, moe.in_dtype
|
||||
)
|
||||
activation_key = input_schema_to_quant_key(
|
||||
self.force_input_schema or self.input_schema
|
||||
runtime_input_schema = check_and_fallback_input_schema(
|
||||
weight_schema=self.force_weight_schema or self.weight_schema,
|
||||
input_schema=self.force_input_schema or self.input_schema,
|
||||
param_dtype=moe.in_dtype,
|
||||
allow_fallback=quant_config.allow_input_schema_fallback,
|
||||
)
|
||||
activation_key = input_schema_to_quant_key(runtime_input_schema, moe.in_dtype)
|
||||
|
||||
# Select Humming MoE experts
|
||||
self.experts_cls = select_humming_moe_experts(
|
||||
@@ -634,22 +683,14 @@ class HummingMoEMethod(FusedMoEMethodBase):
|
||||
# online quant (fp16/bf16 -> quant_type)
|
||||
if is_unquantized:
|
||||
assert isinstance(self.weight_schema, _hm.HummingWeightSchema)
|
||||
f16_dtype = _hm.DataType.from_torch_dtype(layer.param_dtype)
|
||||
has_global_scale = "TENSOR" in str(self.weight_schema.weight_scale_type)
|
||||
tensor_list = _hm.quantize_weight(
|
||||
weight=loaded_weight,
|
||||
dtype=self.weight_schema.b_dtype,
|
||||
scale_dtype=self.weight_schema.bs_dtype or f16_dtype,
|
||||
group_size=self.weight_schema.weight_scale_group_size,
|
||||
has_zero_point=self.weight_schema.has_zero_point,
|
||||
has_global_scale=has_global_scale,
|
||||
is_fp_zero_point=self.weight_schema.is_fp_zero_point,
|
||||
pack=True,
|
||||
tensors = self.weight_schema.quant_tensor(
|
||||
loaded_weight.to(param.device),
|
||||
self.weight_schema,
|
||||
layer.param_dtype,
|
||||
)
|
||||
|
||||
key_list = ["weight", "weight_scale", "zero_point", "global_scale"]
|
||||
success = True
|
||||
for key, tensor in zip(key_list, tensor_list):
|
||||
for key, tensor in tensors.items():
|
||||
if tensor is None or tensor.nelement() == 0:
|
||||
continue
|
||||
sublayer_name = "w2" if shard_id == "w2" else "w13"
|
||||
@@ -695,6 +736,18 @@ class HummingMoEMethod(FusedMoEMethodBase):
|
||||
layer.num_experts = num_experts
|
||||
layer.param_dtype = params_dtype
|
||||
layer.intermediate_size = intermediate_size_per_partition
|
||||
input_schema = self.force_input_schema or self.input_schema
|
||||
input_schema = input_schema.to_humming_schema(params_dtype)
|
||||
shape_k = gcd(hidden_size, intermediate_size_per_partition)
|
||||
for name in ("weight_schema", "force_weight_schema"):
|
||||
schema = getattr(self, name)
|
||||
if getattr(schema, "hadamard_block_size", None) == -1:
|
||||
schema = humming_update_schema_hadamard_block_size(
|
||||
weight_schema=schema,
|
||||
input_schema=input_schema,
|
||||
shape_k=shape_k,
|
||||
)
|
||||
setattr(self, name, schema)
|
||||
weight_loader = extra_weight_attrs.get("weight_loader", default_weight_loader)
|
||||
weight_loader = self.prepare_weight_loader(layer, weight_loader)
|
||||
extra_weight_attrs["weight_loader"] = weight_loader
|
||||
@@ -761,6 +814,7 @@ class HummingMoEMethod(FusedMoEMethodBase):
|
||||
weight_schema=self.weight_schema,
|
||||
input_schema=self.input_schema,
|
||||
force_weight_schema=self.force_weight_schema,
|
||||
allow_input_schema_fallback=self.quant_config.allow_input_schema_fallback,
|
||||
)
|
||||
|
||||
# Build the MoE kernel
|
||||
|
||||
@@ -389,7 +389,7 @@ class MoeWNA16Method(FusedMoEMethodBase):
|
||||
self, layer: RoutedExperts
|
||||
) -> FusedMoEQuantConfig | None:
|
||||
if self.wna16_backend == WNA16MoEBackend.HUMMING:
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.humming import (
|
||||
get_humming_moe_quant_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Humming quantization integration."""
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.humming.activation import (
|
||||
get_humming_activation,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.humming.linear import (
|
||||
apply_humming_linear,
|
||||
convert_linear_layer_to_humming_standard,
|
||||
get_humming_linear_compute_config,
|
||||
prepare_humming_linear_layer_config,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.humming.moe import (
|
||||
HummingMoEQuantConfig,
|
||||
convert_to_humming_moe_kernel_format,
|
||||
get_humming_moe_quant_config,
|
||||
make_humming_moe_kernel,
|
||||
make_humming_moe_quant_config,
|
||||
select_humming_moe_experts,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.humming.schema import (
|
||||
check_and_fallback_input_schema,
|
||||
humming_is_layer_skipped,
|
||||
humming_update_schema_hadamard_block_size,
|
||||
input_schema_to_quant_key,
|
||||
quant_key_to_input_schema,
|
||||
resolve_humming_layer_config,
|
||||
weight_schema_to_quant_key,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"check_and_fallback_input_schema",
|
||||
"get_humming_activation",
|
||||
"HummingMoEQuantConfig",
|
||||
"get_humming_moe_quant_config",
|
||||
"humming_is_layer_skipped",
|
||||
"humming_update_schema_hadamard_block_size",
|
||||
"make_humming_moe_quant_config",
|
||||
"apply_humming_linear",
|
||||
"convert_linear_layer_to_humming_standard",
|
||||
"get_humming_linear_compute_config",
|
||||
"prepare_humming_linear_layer_config",
|
||||
"make_humming_moe_kernel",
|
||||
"select_humming_moe_experts",
|
||||
"input_schema_to_quant_key",
|
||||
"quant_key_to_input_schema",
|
||||
"resolve_humming_layer_config",
|
||||
"weight_schema_to_quant_key",
|
||||
"convert_to_humming_moe_kernel_format",
|
||||
]
|
||||
@@ -0,0 +1,126 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""MoE activation expressions for Humming input processing."""
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from vllm.model_executor.layers.fused_moe.activation import (
|
||||
ApplyMoEActivationConfig,
|
||||
MoEActivation,
|
||||
)
|
||||
|
||||
_SILU_IMPL = "a / (1.f + expf(-a))"
|
||||
_GELU_IMPL = "0.5f * a * (1.f + erff(a * 0.7071067811865476f))"
|
||||
_RELU2_IMPL = "fmaxf(a, 0.f) * fmaxf(a, 0.f)"
|
||||
_GELU_TANH_IMPL = """[](float a) {
|
||||
const float cubic = 0.044715f * a * a * a;
|
||||
const float inner = 0.7978845608028654f * (a + cubic);
|
||||
return 0.5f * a * (1.f + tanhf(inner));
|
||||
}(a)"""
|
||||
_CLAMPED_SILU_IMPL = """[](float a, float b) {{
|
||||
const float gate = fminf(a, {limit});
|
||||
const float up = fmaxf(fminf(b, {limit}), -{limit});
|
||||
const float activated_gate = gate / (1.f + expf(-{alpha} * gate));
|
||||
return activated_gate * (up + {beta});
|
||||
}}(a, b)"""
|
||||
|
||||
# Parameterized expressions are resolved by get_humming_activation().
|
||||
_HUMMING_ACTIVATIONS: dict[MoEActivation, dict[str, str]] = {
|
||||
MoEActivation.SILU: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": f"({_SILU_IMPL}) * b",
|
||||
},
|
||||
MoEActivation.GELU: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": f"({_GELU_IMPL}) * b",
|
||||
},
|
||||
MoEActivation.GELU_TANH: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": f"({_GELU_TANH_IMPL}) * b",
|
||||
},
|
||||
MoEActivation.RELU2: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": f"({_RELU2_IMPL}) * b",
|
||||
},
|
||||
MoEActivation.SWIGLUOAI: {
|
||||
"activation_type": "binary_interleaved",
|
||||
"activation_impl": _CLAMPED_SILU_IMPL,
|
||||
},
|
||||
MoEActivation.SITU: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": """[](float a, float b) {{
|
||||
const float gate = {situ_beta} * tanhf(a / {situ_beta});
|
||||
const float activated_gate = gate / (1.f + expf(-a));
|
||||
const float up = {situ_up};
|
||||
return activated_gate * up;
|
||||
}}(a, b)""",
|
||||
},
|
||||
MoEActivation.SWIGLUOAI_UNINTERLEAVE: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": _CLAMPED_SILU_IMPL,
|
||||
},
|
||||
MoEActivation.SWIGLUSTEP: {
|
||||
"activation_type": "binary_split",
|
||||
"activation_impl": """[](float a, float b) {
|
||||
const float activated_gate = a / (1.f + expf(-a));
|
||||
const float gate = fminf(activated_gate, 7.f);
|
||||
const float up = fmaxf(fminf(b, 7.f), -7.f);
|
||||
return gate * up;
|
||||
}(a, b)""",
|
||||
},
|
||||
MoEActivation.SILU_NO_MUL: {
|
||||
"activation_type": "unary",
|
||||
"activation_impl": _SILU_IMPL,
|
||||
},
|
||||
MoEActivation.GELU_NO_MUL: {
|
||||
"activation_type": "unary",
|
||||
"activation_impl": _GELU_IMPL,
|
||||
},
|
||||
MoEActivation.GELU_TANH_NO_MUL: {
|
||||
"activation_type": "unary",
|
||||
"activation_impl": _GELU_TANH_IMPL,
|
||||
},
|
||||
MoEActivation.RELU2_NO_MUL: {
|
||||
"activation_type": "unary",
|
||||
"activation_impl": _RELU2_IMPL,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_humming_activation(
|
||||
activation: MoEActivation,
|
||||
config: ApplyMoEActivationConfig | None = None,
|
||||
) -> dict[str, str]:
|
||||
config = config or ApplyMoEActivationConfig()
|
||||
use_clamped_silu = False
|
||||
if activation == MoEActivation.SWIGLUOAI:
|
||||
config = ApplyMoEActivationConfig(clamp_limit=7.0, alpha=1.702, beta=1.0)
|
||||
use_clamped_silu = True
|
||||
elif activation == MoEActivation.SILU and config.clamp_limit is not None:
|
||||
config = replace(config, alpha=1.0, beta=0.0)
|
||||
use_clamped_silu = True
|
||||
elif activation == MoEActivation.SWIGLUOAI_UNINTERLEAVE:
|
||||
if config.clamp_limit is None:
|
||||
raise ValueError("SWIGLUOAI_UNINTERLEAVE requires clamp_limit")
|
||||
use_clamped_silu = True
|
||||
|
||||
definition = _HUMMING_ACTIVATIONS[activation].copy()
|
||||
if activation == MoEActivation.SITU:
|
||||
if config.activation_situ_beta is None:
|
||||
raise ValueError("SITU requires activation_situ_beta")
|
||||
linear_beta = config.activation_situ_linear_beta
|
||||
situ_up = "b"
|
||||
if linear_beta is not None and linear_beta > 0:
|
||||
situ_up = f"({float(linear_beta)}f) * tanhf(b / ({float(linear_beta)}f))"
|
||||
situ_beta = f"({float(config.activation_situ_beta)}f)"
|
||||
activation_impl = definition["activation_impl"]
|
||||
activation_impl = activation_impl.format(situ_beta=situ_beta, situ_up=situ_up)
|
||||
definition["activation_impl"] = activation_impl
|
||||
elif use_clamped_silu:
|
||||
assert config.clamp_limit is not None
|
||||
limit = f"({float(config.clamp_limit)}f)"
|
||||
alpha = f"({float(config.alpha)}f)"
|
||||
beta = f"({float(config.beta)}f)"
|
||||
activation_impl = _CLAMPED_SILU_IMPL.format(limit=limit, alpha=alpha, beta=beta)
|
||||
definition["activation_impl"] = activation_impl
|
||||
return definition
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Prepare and execute Humming linear layers."""
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.humming.schema import (
|
||||
check_and_fallback_input_schema,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.utils.humming import BaseInputSchema, LayerConfig
|
||||
|
||||
|
||||
def convert_linear_layer_to_humming_standard(
|
||||
layer: LinearBase, name_map: dict[str, str]
|
||||
):
|
||||
"""Rename/reshape a linear layer's quantized params (the canonical MPLinear
|
||||
layout: ``weight_packed`` int32 + ``weight_scale``) into the parameter names
|
||||
and layout humming's weight schema expects (``weight`` / ``weight_scale``)."""
|
||||
for name, checkpoint_name in name_map.items():
|
||||
tensor = getattr(layer, checkpoint_name)
|
||||
delattr(layer, checkpoint_name)
|
||||
|
||||
if name == "weight":
|
||||
input_dim = getattr(tensor, "input_dim", 1)
|
||||
output_dim = getattr(tensor, "output_dim", 0)
|
||||
|
||||
if input_dim == 0 and output_dim == 1:
|
||||
tensor = tensor.transpose(1, 0).contiguous()
|
||||
else:
|
||||
assert output_dim == 0 and input_dim == 1
|
||||
|
||||
tensor = tensor.view(tensor.size(0), -1).view(torch.int32)
|
||||
elif name in ["weight_scale", "zero_point"]:
|
||||
if getattr(tensor, "output_dim", 0) == 1:
|
||||
tensor = tensor.transpose(0, 1).contiguous()
|
||||
if tensor.ndim == 1:
|
||||
tensor = tensor.unsqueeze(1)
|
||||
|
||||
tensor = tensor.view(torch.int32) if name == "zero_point" else tensor
|
||||
|
||||
if isinstance(tensor, torch.nn.Parameter):
|
||||
param = tensor
|
||||
else:
|
||||
param = torch.nn.Parameter(tensor, requires_grad=False)
|
||||
|
||||
setattr(layer, name, param)
|
||||
|
||||
|
||||
def prepare_humming_linear_layer_config(
|
||||
layer: LinearBase,
|
||||
quant_config: dict,
|
||||
input_quant_config: dict | None = None,
|
||||
*,
|
||||
input_schema: "BaseInputSchema | None" = None,
|
||||
) -> "LayerConfig":
|
||||
from vllm.utils.humming import (
|
||||
BaseInputSchema,
|
||||
BaseWeightSchema,
|
||||
HummingInputSchema,
|
||||
prepare_layer_config,
|
||||
transform_humming_tensors,
|
||||
)
|
||||
|
||||
weight_schema = BaseWeightSchema.from_config(quant_config)
|
||||
if input_schema is None:
|
||||
if input_quant_config is not None:
|
||||
input_schema = BaseInputSchema.from_config(input_quant_config)
|
||||
else:
|
||||
input_schema = HummingInputSchema()
|
||||
|
||||
# ReplicatedLinear has no TP partitioning and so does not set
|
||||
# input_size_per_partition; for it that is just input_size. Use hasattr
|
||||
# rather than getattr's default arg, which is evaluated eagerly and would
|
||||
# raise on layers lacking input_size (e.g. ParallelLMHead).
|
||||
if hasattr(layer, "input_size_per_partition"):
|
||||
input_size_per_partition = layer.input_size_per_partition
|
||||
else:
|
||||
input_size_per_partition = layer.input_size
|
||||
shape_k_stacks = [input_size_per_partition]
|
||||
shape_n_stacks = layer.output_partition_sizes
|
||||
|
||||
# Step 1: convert weight and input schemas to humming standard format
|
||||
source_tensors = dict(layer.named_parameters())
|
||||
weight_schema, tensors = weight_schema.convert_humming(
|
||||
tensors=source_tensors,
|
||||
shape_n_stacks=shape_n_stacks,
|
||||
shape_k_stacks=shape_k_stacks,
|
||||
param_dtype=layer.params_dtype,
|
||||
)
|
||||
input_schema, input_tensors = input_schema.convert_humming(
|
||||
tensors=source_tensors,
|
||||
shape_n_stacks=shape_n_stacks,
|
||||
shape_k_stacks=shape_k_stacks,
|
||||
param_dtype=layer.params_dtype,
|
||||
)
|
||||
|
||||
tensors.update(input_tensors)
|
||||
layer.weight_schema = weight_schema
|
||||
input_schema = check_and_fallback_input_schema(
|
||||
weight_schema=weight_schema,
|
||||
input_schema=input_schema,
|
||||
param_dtype=layer.params_dtype,
|
||||
)
|
||||
for name in ("input_scale", "input_scale_2"):
|
||||
if name != input_schema.static_tensor_scale_name:
|
||||
tensors.pop(name, None)
|
||||
input_tensors.pop(name, None)
|
||||
|
||||
# Step 2: transform weight (humming standard format) for forwarding.
|
||||
config = prepare_layer_config(
|
||||
shape_n=sum(layer.output_partition_sizes),
|
||||
shape_k=input_size_per_partition,
|
||||
weight_schema=weight_schema,
|
||||
input_schema=input_schema,
|
||||
pad_n_to_multiple=256,
|
||||
pad_k_to_multiple=128,
|
||||
has_bias=layer.has_bias,
|
||||
torch_dtype=layer.params_dtype,
|
||||
device=tensors["weight"].device,
|
||||
)
|
||||
tensors = transform_humming_tensors(config, tensors)
|
||||
tensors.update(input_tensors)
|
||||
if "bias" in tensors:
|
||||
zero_bias = torch.zeros_like(tensors["bias"])
|
||||
layer.register_buffer("zero_bias", zero_bias)
|
||||
for name, _ in list(layer.named_parameters()):
|
||||
delattr(layer, name)
|
||||
for name, tensor in tensors.items():
|
||||
param = torch.nn.Parameter(tensor, requires_grad=False)
|
||||
setattr(layer, name, param)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def get_humming_linear_compute_config() -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"use_batch_invariant": envs.VLLM_BATCH_INVARIANT,
|
||||
"use_f16_accum": envs.VLLM_HUMMING_USE_F16_ACCUM,
|
||||
"gemm_type": "dense",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def apply_humming_linear(
|
||||
layer: LinearBase,
|
||||
x: torch.Tensor,
|
||||
*,
|
||||
skip_bias_add: bool = False,
|
||||
layer_config: "LayerConfig",
|
||||
compute_config: str,
|
||||
locks: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
from vllm.utils.humming import humming_forward
|
||||
|
||||
mode = layer_config.input_quant_mode
|
||||
input_scale = getattr(layer, "input_scale", None) if mode.should_quantize else None
|
||||
input_scale_2 = (
|
||||
getattr(layer, "input_scale_2", None) if mode.has_secondary_scale else None
|
||||
)
|
||||
flatten_inputs = x.reshape(-1, x.size(-1))
|
||||
output = humming_forward(
|
||||
layer_config,
|
||||
inputs=flatten_inputs,
|
||||
weight=layer.weight,
|
||||
weight_scale=getattr(layer, "weight_scale", None),
|
||||
zero_point=getattr(layer, "zero_point", None),
|
||||
bias=getattr(layer, "zero_bias" if skip_bias_add else "bias", None),
|
||||
weight_scale_2=getattr(layer, "weight_scale_2", None),
|
||||
input_scale=input_scale,
|
||||
input_scale_2=input_scale_2,
|
||||
hadamard_block_size=layer.weight_schema.hadamard_block_size,
|
||||
locks=locks,
|
||||
compute_config=compute_config,
|
||||
)
|
||||
return output.view(*x.shape[:-1], output.size(-1))
|
||||
+65
-539
@@ -1,13 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import json
|
||||
"""Configure, prepare weights for, and assemble Humming MoE kernels."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
import vllm.model_executor.layers.quantization.utils.humming.schema as humming_schema
|
||||
from vllm import envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.all2all_utils import (
|
||||
@@ -23,34 +24,19 @@ from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
|
||||
HummingGroupedExperts,
|
||||
HummingIndexedExperts,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.humming.schema import (
|
||||
humming_is_layer_skipped,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
FP4_DTYPE,
|
||||
FP8_DTYPE,
|
||||
INT4_DTYPE,
|
||||
INT8_DTYPE,
|
||||
MXFP_SCALE_DTYPE,
|
||||
GroupShape,
|
||||
QuantKey,
|
||||
ScaleDesc,
|
||||
)
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
|
||||
from vllm.utils.humming import (
|
||||
AWQWeightSchema,
|
||||
BaseInputSchema,
|
||||
BaseWeightSchema,
|
||||
CompressedTensorsInputSchema,
|
||||
CompressedTensorsWeightSchema,
|
||||
Fp8WeightSchema,
|
||||
GPTQWeightSchema,
|
||||
HummingInputSchema,
|
||||
HummingWeightSchema,
|
||||
LayerConfig,
|
||||
)
|
||||
from vllm.utils.humming import dtypes as humming_dtypes
|
||||
from vllm.utils.humming import LayerConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -59,504 +45,12 @@ logger = init_logger(__name__)
|
||||
class HummingMoEQuantConfig(FusedMoEQuantConfig):
|
||||
w1_humming_config: "LayerConfig"
|
||||
w2_humming_config: "LayerConfig"
|
||||
|
||||
|
||||
if has_humming():
|
||||
from vllm.utils.humming import dtypes as humming_dtypes
|
||||
|
||||
_HUMMING_TO_QUANT_DTYPE: dict[humming_dtypes.DataType, Any] = {
|
||||
humming_dtypes.float4e2m1: FP4_DTYPE,
|
||||
humming_dtypes.float8e4m3: FP8_DTYPE,
|
||||
humming_dtypes.float8e5m2: torch.float8_e5m2,
|
||||
humming_dtypes.int8: torch.int8,
|
||||
humming_dtypes.uint4: INT4_DTYPE,
|
||||
humming_dtypes.uint8: INT8_DTYPE,
|
||||
humming_dtypes.uint2: torch.uint8,
|
||||
humming_dtypes.uint3: torch.uint8,
|
||||
humming_dtypes.uint5: torch.uint8,
|
||||
humming_dtypes.uint6: torch.uint8,
|
||||
humming_dtypes.uint7: torch.uint8,
|
||||
}
|
||||
|
||||
_HUMMING_TO_SCALE_DTYPE: dict[humming_dtypes.DataType, torch.dtype] = {
|
||||
humming_dtypes.float8e8m0: MXFP_SCALE_DTYPE,
|
||||
humming_dtypes.float8e4m3: FP8_DTYPE,
|
||||
humming_dtypes.float16: torch.float16,
|
||||
humming_dtypes.bfloat16: torch.bfloat16,
|
||||
humming_dtypes.float32: torch.float32,
|
||||
}
|
||||
|
||||
|
||||
def _group_shape(group_size: int, group_size_n: int = 0) -> GroupShape:
|
||||
"""Map humming group sizes to QuantKey GroupShape.
|
||||
|
||||
group_size: elements per group along K (col); 0 means full dimension.
|
||||
group_size_n: elements per group along N (row); 0 means 1 (per-row).
|
||||
|
||||
GroupShape convention: row = N dim, col = K dim.
|
||||
"""
|
||||
if group_size == 0 and group_size_n == 0:
|
||||
return GroupShape.PER_CHANNEL
|
||||
|
||||
row = group_size_n if group_size_n > 0 else 1
|
||||
col = group_size if group_size > 0 else -1
|
||||
return GroupShape(row=row, col=col)
|
||||
|
||||
|
||||
# ---- HummingWeightSchema (post-conversion) --------------------------------
|
||||
|
||||
|
||||
def _humming_weight_schema_to_quant_key(
|
||||
schema: "HummingWeightSchema",
|
||||
) -> QuantKey:
|
||||
from vllm.utils.humming import WeightScaleType
|
||||
|
||||
"""Convert a HummingWeightSchema to a QuantKey."""
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[schema.b_dtype]
|
||||
|
||||
if schema.bs_dtype is not None:
|
||||
scale_dtype = _HUMMING_TO_SCALE_DTYPE[schema.bs_dtype]
|
||||
else:
|
||||
scale_dtype = torch.float32
|
||||
|
||||
group_shape = _group_shape(
|
||||
schema.weight_scale_group_size,
|
||||
schema.weight_scale_group_size_n,
|
||||
)
|
||||
|
||||
scale = ScaleDesc(dtype=scale_dtype, static=True, group_shape=group_shape)
|
||||
|
||||
scale2 = None
|
||||
if schema.weight_scale_type == WeightScaleType.GROUP_TENSOR:
|
||||
scale2 = ScaleDesc(
|
||||
dtype=torch.float32,
|
||||
static=True,
|
||||
group_shape=GroupShape.PER_TENSOR,
|
||||
)
|
||||
|
||||
return QuantKey(
|
||||
dtype=dtype,
|
||||
scale=scale,
|
||||
scale2=scale2,
|
||||
symmetric=not schema.has_zero_point,
|
||||
)
|
||||
|
||||
|
||||
# ---- Checkpoint-format weight schemas (pre-conversion) --------------------
|
||||
|
||||
|
||||
def _fp8_weight_schema_to_quant_key(schema: "Fp8WeightSchema") -> QuantKey:
|
||||
if schema.weight_block_size is not None:
|
||||
gs_n, gs_k = schema.weight_block_size
|
||||
group_shape = GroupShape(row=gs_n, col=gs_k)
|
||||
else:
|
||||
group_shape = GroupShape.PER_CHANNEL
|
||||
|
||||
scale = ScaleDesc(dtype=torch.float32, static=True, group_shape=group_shape)
|
||||
return QuantKey(dtype=FP8_DTYPE, scale=scale, symmetric=True)
|
||||
|
||||
|
||||
def _awq_weight_schema_to_quant_key(schema: "AWQWeightSchema") -> QuantKey:
|
||||
group_shape = _group_shape(schema.group_size)
|
||||
scale = ScaleDesc(
|
||||
dtype=torch.float16,
|
||||
static=True,
|
||||
group_shape=group_shape,
|
||||
)
|
||||
return QuantKey(
|
||||
dtype=INT4_DTYPE,
|
||||
scale=scale,
|
||||
symmetric=not schema.zero_point,
|
||||
)
|
||||
|
||||
|
||||
def _gptq_weight_schema_to_quant_key(schema: "GPTQWeightSchema") -> QuantKey:
|
||||
group_shape = _group_shape(schema.group_size)
|
||||
scale = ScaleDesc(
|
||||
dtype=torch.float16,
|
||||
static=True,
|
||||
group_shape=group_shape,
|
||||
)
|
||||
return QuantKey(dtype=INT4_DTYPE, scale=scale, symmetric=schema.sym)
|
||||
|
||||
|
||||
def _compressed_tensors_weight_schema_to_quant_key(
|
||||
schema: "CompressedTensorsWeightSchema",
|
||||
) -> QuantKey:
|
||||
# Determine dtype from format/type/num_bits
|
||||
fmt = schema.format
|
||||
if fmt in ("int-quantized", "float-quantized", "naive-quantized"):
|
||||
dtype = INT8_DTYPE if schema.type == "int" else FP8_DTYPE
|
||||
elif "nvfp4" in fmt or "mxfp4" in fmt:
|
||||
dtype = FP4_DTYPE
|
||||
else:
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[
|
||||
humming_dtypes.DataType.from_str(f"uint{schema.num_bits}")
|
||||
]
|
||||
|
||||
# Determine group shape from strategy
|
||||
if schema.strategy in ("group", "tensor_group"):
|
||||
group_shape = _group_shape(schema.group_size or 0)
|
||||
elif schema.strategy == "block" and schema.block_structure is not None:
|
||||
group_shape = GroupShape(
|
||||
row=schema.block_structure[0],
|
||||
col=schema.block_structure[1],
|
||||
)
|
||||
else:
|
||||
group_shape = GroupShape.PER_CHANNEL
|
||||
|
||||
# Determine scale dtype
|
||||
if "mxfp" in fmt:
|
||||
scale_dtype = MXFP_SCALE_DTYPE
|
||||
elif "nvfp4" in fmt:
|
||||
scale_dtype = FP8_DTYPE
|
||||
else:
|
||||
scale_dtype = torch.float32
|
||||
|
||||
scale = ScaleDesc(dtype=scale_dtype, static=True, group_shape=group_shape)
|
||||
|
||||
scale2 = None
|
||||
if "nvfp4" in fmt or schema.strategy == "tensor_group":
|
||||
scale2 = ScaleDesc(
|
||||
dtype=torch.float32,
|
||||
static=True,
|
||||
group_shape=GroupShape.PER_TENSOR,
|
||||
)
|
||||
|
||||
return QuantKey(
|
||||
dtype=dtype,
|
||||
scale=scale,
|
||||
scale2=scale2,
|
||||
symmetric=schema.symmetric,
|
||||
)
|
||||
|
||||
|
||||
# ---- Dispatch for any BaseWeightSchema ------------------------------------
|
||||
|
||||
|
||||
def weight_schema_to_quant_key(
|
||||
schema: "BaseWeightSchema",
|
||||
) -> QuantKey:
|
||||
from vllm.utils.humming import (
|
||||
AWQWeightSchema,
|
||||
BitnetWeightSchema,
|
||||
CompressedTensorsWeightSchema,
|
||||
Fp8WeightSchema,
|
||||
GptOssMxfp4WeightSchema,
|
||||
GPTQWeightSchema,
|
||||
HummingWeightSchema,
|
||||
ModeloptMxfp8WeightSchema,
|
||||
ModeloptNvfp4WeightSchema,
|
||||
Mxfp4WeightSchema,
|
||||
)
|
||||
|
||||
"""Convert any BaseWeightSchema to a QuantKey."""
|
||||
if isinstance(schema, HummingWeightSchema):
|
||||
return _humming_weight_schema_to_quant_key(schema)
|
||||
|
||||
# Schemas with fixed QuantKeys
|
||||
if isinstance(schema, (Mxfp4WeightSchema, GptOssMxfp4WeightSchema)):
|
||||
return QuantKey(
|
||||
dtype=FP4_DTYPE,
|
||||
scale=ScaleDesc(MXFP_SCALE_DTYPE, True, GroupShape(1, 32)),
|
||||
)
|
||||
if isinstance(schema, ModeloptMxfp8WeightSchema):
|
||||
return QuantKey(
|
||||
dtype=FP8_DTYPE,
|
||||
scale=ScaleDesc(MXFP_SCALE_DTYPE, True, GroupShape(1, 32)),
|
||||
)
|
||||
if isinstance(schema, ModeloptNvfp4WeightSchema):
|
||||
return QuantKey(
|
||||
dtype=FP4_DTYPE,
|
||||
scale=ScaleDesc(FP8_DTYPE, True, GroupShape(1, 16)),
|
||||
scale2=ScaleDesc(torch.float32, True, GroupShape.PER_TENSOR),
|
||||
)
|
||||
if isinstance(schema, BitnetWeightSchema):
|
||||
return QuantKey(
|
||||
dtype=torch.uint8,
|
||||
scale=ScaleDesc(torch.float32, True, GroupShape.PER_CHANNEL),
|
||||
)
|
||||
|
||||
# Schemas requiring config inspection
|
||||
if isinstance(schema, Fp8WeightSchema):
|
||||
return _fp8_weight_schema_to_quant_key(schema)
|
||||
if isinstance(schema, AWQWeightSchema):
|
||||
return _awq_weight_schema_to_quant_key(schema)
|
||||
if isinstance(schema, GPTQWeightSchema):
|
||||
return _gptq_weight_schema_to_quant_key(schema)
|
||||
if isinstance(schema, CompressedTensorsWeightSchema):
|
||||
return _compressed_tensors_weight_schema_to_quant_key(schema)
|
||||
|
||||
raise TypeError(f"Unsupported weight schema type: {type(schema)}")
|
||||
|
||||
|
||||
# ---- HummingInputSchema (post-conversion) ----------------------------------
|
||||
|
||||
|
||||
def _humming_input_schema_to_quant_key(
|
||||
schema: "HummingInputSchema",
|
||||
) -> QuantKey | None:
|
||||
"""Convert a HummingInputSchema to a QuantKey. Returns None if
|
||||
the schema represents unquantized (bf16/fp16) inputs."""
|
||||
if schema.a_dtype is None or schema.a_dtype.num_bits >= 16:
|
||||
return None
|
||||
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[schema.a_dtype]
|
||||
|
||||
gs = schema.input_scale_group_size
|
||||
group_shape = GroupShape(row=1, col=gs) if gs > 0 else GroupShape.PER_TOKEN
|
||||
|
||||
# Pick the scale dtype the Humming kernel actually consumes. An explicit
|
||||
# input_scale_dtype always wins. Otherwise infer from the grouping: MX
|
||||
# microscale activations (group size 32, e.g. MXFP8) carry an e8m0 (uint8)
|
||||
# scale, while block-FP8 (group size 128) and per-token FP8/int8 carry a
|
||||
# float32 scale. Getting this right lets a grouped FP8 activation match
|
||||
# kFp8Dynamic128Sym instead of an unmatchable uint8-scaled key.
|
||||
if schema.input_scale_dtype is not None:
|
||||
scale_dtype = _HUMMING_TO_SCALE_DTYPE[schema.input_scale_dtype]
|
||||
elif gs == 32:
|
||||
scale_dtype = MXFP_SCALE_DTYPE
|
||||
else:
|
||||
scale_dtype = torch.float32
|
||||
|
||||
scale = ScaleDesc(dtype=scale_dtype, static=False, group_shape=group_shape)
|
||||
|
||||
return QuantKey(dtype=dtype, scale=scale, symmetric=True)
|
||||
|
||||
|
||||
# ---- Checkpoint-format input schemas (pre-conversion) ----------------------
|
||||
|
||||
|
||||
def _resolve_input_quant_key(
|
||||
origin_a_dtype: "humming_dtypes.DataType",
|
||||
group_size: int,
|
||||
) -> QuantKey | None:
|
||||
from vllm.utils.humming import HummingInputSchema
|
||||
|
||||
"""Resolve the actual activation QuantKey after platform fallback."""
|
||||
a_dtype = HummingInputSchema().get_fallback_input_dtype(origin_a_dtype)
|
||||
if a_dtype is None or a_dtype.num_bits >= 16:
|
||||
return None
|
||||
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[a_dtype]
|
||||
gs = group_size if a_dtype == humming_dtypes.float4e2m1 else 0
|
||||
group_shape = GroupShape(row=1, col=gs) if gs > 0 else GroupShape.PER_TOKEN
|
||||
scale_dtype = MXFP_SCALE_DTYPE if gs > 0 else torch.float32
|
||||
|
||||
scale = ScaleDesc(dtype=scale_dtype, static=False, group_shape=group_shape)
|
||||
return QuantKey(dtype=dtype, scale=scale, symmetric=True)
|
||||
|
||||
|
||||
def _compressed_tensors_input_schema_to_quant_key(
|
||||
schema: "CompressedTensorsInputSchema",
|
||||
) -> QuantKey | None:
|
||||
type_bits_to_dtype = {
|
||||
("float", 8): humming_dtypes.float8e4m3,
|
||||
("float", 4): humming_dtypes.float4e2m1,
|
||||
("int", 8): humming_dtypes.int8,
|
||||
("int", 4): humming_dtypes.int4,
|
||||
}
|
||||
origin = type_bits_to_dtype.get((schema.type, schema.num_bits))
|
||||
if origin is None:
|
||||
return None
|
||||
return _resolve_input_quant_key(origin, schema.group_size)
|
||||
|
||||
|
||||
# ---- Dispatch for any BaseInputSchema -------------------------------------
|
||||
|
||||
|
||||
def input_schema_to_quant_key(
|
||||
schema: "BaseInputSchema",
|
||||
) -> QuantKey | None:
|
||||
from vllm.utils.humming import (
|
||||
CompressedTensorsInputSchema,
|
||||
Fp8InputSchema,
|
||||
HummingInputSchema,
|
||||
ModeloptNvfp4InputSchema,
|
||||
)
|
||||
|
||||
"""Convert any BaseInputSchema to a QuantKey. Returns None if
|
||||
the schema represents unquantized (bf16/fp16) inputs."""
|
||||
if isinstance(schema, HummingInputSchema):
|
||||
return _humming_input_schema_to_quant_key(schema)
|
||||
|
||||
if isinstance(schema, Fp8InputSchema):
|
||||
return _resolve_input_quant_key(humming_dtypes.float8e4m3, 0)
|
||||
|
||||
if isinstance(schema, ModeloptNvfp4InputSchema):
|
||||
return _resolve_input_quant_key(
|
||||
humming_dtypes.float8e4m3,
|
||||
schema.group_size,
|
||||
)
|
||||
|
||||
if isinstance(schema, CompressedTensorsInputSchema):
|
||||
return _compressed_tensors_input_schema_to_quant_key(schema)
|
||||
|
||||
raise TypeError(f"Unsupported input schema type: {type(schema)}")
|
||||
|
||||
|
||||
def humming_is_layer_skipped(config: dict[str, Any], prefix: str):
|
||||
if not config:
|
||||
return True
|
||||
|
||||
keys = ["ignored_layers", "ignore", "modules_to_not_convert"]
|
||||
ignored_layers: list[str] = []
|
||||
for key in keys:
|
||||
candidate = config.get(key, []) or []
|
||||
if candidate:
|
||||
ignored_layers = candidate
|
||||
break
|
||||
|
||||
if any(module_name in prefix for module_name in ignored_layers):
|
||||
return True
|
||||
if "lm_head" in prefix:
|
||||
return True
|
||||
|
||||
for regex in config.get("dynamic", {}):
|
||||
if regex[:1] != "-":
|
||||
continue
|
||||
if re.match(regex[2:], prefix):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def convert_linear_layer_to_humming_standard(
|
||||
layer: LinearBase, name_map: dict[str, str]
|
||||
):
|
||||
"""Rename/reshape a linear layer's quantized params (the canonical MPLinear
|
||||
layout: ``weight_packed`` int32 + ``weight_scale``) into the parameter names
|
||||
and layout humming's weight schema expects (``weight`` / ``weight_scale``)."""
|
||||
for name, checkpoint_name in name_map.items():
|
||||
tensor = getattr(layer, checkpoint_name)
|
||||
delattr(layer, checkpoint_name)
|
||||
|
||||
if name == "weight":
|
||||
input_dim = getattr(tensor, "input_dim", 1)
|
||||
output_dim = getattr(tensor, "output_dim", 0)
|
||||
|
||||
if input_dim == 0 and output_dim == 1:
|
||||
tensor = tensor.transpose(1, 0).contiguous()
|
||||
else:
|
||||
assert output_dim == 0 and input_dim == 1
|
||||
|
||||
tensor = tensor.view(tensor.size(0), -1).view(torch.int32)
|
||||
elif name in ["weight_scale", "zero_point"]:
|
||||
if getattr(tensor, "output_dim", 0) == 1:
|
||||
tensor = tensor.transpose(0, 1).contiguous()
|
||||
if tensor.ndim == 1:
|
||||
tensor = tensor.unsqueeze(1)
|
||||
|
||||
tensor = tensor.view(torch.int32) if name == "zero_point" else tensor
|
||||
|
||||
if isinstance(tensor, torch.nn.Parameter):
|
||||
param = tensor
|
||||
else:
|
||||
param = torch.nn.Parameter(tensor, requires_grad=False)
|
||||
|
||||
setattr(layer, name, param)
|
||||
|
||||
|
||||
def prepare_humming_linear_layer_config(
|
||||
layer: LinearBase,
|
||||
quant_config: dict,
|
||||
input_quant_config: dict | None = None,
|
||||
) -> "LayerConfig":
|
||||
from vllm.utils.humming import (
|
||||
BaseInputSchema,
|
||||
BaseWeightSchema,
|
||||
HummingInputSchema,
|
||||
prepare_layer_config,
|
||||
transform_humming_tensors,
|
||||
)
|
||||
|
||||
weight_schema = BaseWeightSchema.from_config(quant_config)
|
||||
if input_quant_config is not None:
|
||||
input_schema = BaseInputSchema.from_config(input_quant_config)
|
||||
else:
|
||||
input_schema = HummingInputSchema()
|
||||
|
||||
# ReplicatedLinear has no TP partitioning and so does not set
|
||||
# input_size_per_partition; for it that is just input_size. Use hasattr
|
||||
# rather than getattr's default arg, which is evaluated eagerly and would
|
||||
# raise on layers lacking input_size (e.g. ParallelLMHead).
|
||||
if hasattr(layer, "input_size_per_partition"):
|
||||
input_size_per_partition = layer.input_size_per_partition
|
||||
else:
|
||||
input_size_per_partition = layer.input_size
|
||||
shape_k_stacks = [input_size_per_partition]
|
||||
shape_n_stacks = layer.output_partition_sizes
|
||||
|
||||
# Step 1: convert weight and input schemas to humming standard format
|
||||
weight_schema, tensors = weight_schema.convert_humming(
|
||||
tensors=dict(layer.named_parameters()),
|
||||
shape_n_stacks=shape_n_stacks,
|
||||
shape_k_stacks=shape_k_stacks,
|
||||
param_dtype=layer.params_dtype,
|
||||
)
|
||||
input_schema, _ = input_schema.convert_humming(
|
||||
tensors={},
|
||||
shape_n_stacks=shape_n_stacks,
|
||||
shape_k_stacks=shape_k_stacks,
|
||||
param_dtype=layer.params_dtype,
|
||||
)
|
||||
|
||||
layer.weight_schema = weight_schema
|
||||
|
||||
# Step 2: transform weight (humming standard format) for forwarding.
|
||||
config = prepare_layer_config(
|
||||
shape_n=sum(layer.output_partition_sizes),
|
||||
shape_k=input_size_per_partition,
|
||||
weight_schema=weight_schema,
|
||||
input_schema=input_schema,
|
||||
pad_n_to_multiple=256,
|
||||
pad_k_to_multiple=128,
|
||||
has_bias=layer.has_bias,
|
||||
torch_dtype=layer.params_dtype,
|
||||
)
|
||||
tensors = transform_humming_tensors(config, tensors)
|
||||
for name, _ in list(layer.named_parameters()):
|
||||
delattr(layer, name)
|
||||
for name, tensor in tensors.items():
|
||||
param = torch.nn.Parameter(tensor, requires_grad=False)
|
||||
setattr(layer, name, param)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def get_humming_linear_compute_config() -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"use_batch_invariant": envs.VLLM_BATCH_INVARIANT,
|
||||
"use_f16_accum": envs.VLLM_HUMMING_USE_F16_ACCUM,
|
||||
"gemm_type": "dense",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def apply_humming_linear(
|
||||
layer: LinearBase,
|
||||
x: torch.Tensor,
|
||||
*,
|
||||
layer_config: "LayerConfig",
|
||||
compute_config: str,
|
||||
locks: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
from vllm.utils.humming import humming_forward
|
||||
|
||||
flatten_inputs = x.reshape(-1, x.size(-1))
|
||||
output = humming_forward(
|
||||
layer_config,
|
||||
inputs=flatten_inputs,
|
||||
weight=layer.weight,
|
||||
weight_scale=getattr(layer, "weight_scale", None),
|
||||
zero_point=getattr(layer, "zero_point", None),
|
||||
bias=getattr(layer, "bias", None),
|
||||
weight_scale_2=getattr(layer, "weight_scale_2", None),
|
||||
locks=locks,
|
||||
compute_config=compute_config,
|
||||
)
|
||||
return output.view(*x.shape[:-1], output.size(-1))
|
||||
w1_hadamard_block_size: int = 1
|
||||
w2_hadamard_block_size: int = 1
|
||||
w1_input_scale: torch.Tensor | None = None
|
||||
w2_input_scale: torch.Tensor | None = None
|
||||
w1_input_scale_2: torch.Tensor | None = None
|
||||
w2_input_scale_2: torch.Tensor | None = None
|
||||
|
||||
|
||||
def make_humming_moe_quant_config(
|
||||
@@ -648,8 +142,12 @@ def get_humming_moe_quant_config(
|
||||
q_dtype is not None
|
||||
and q_dtype.startswith("float8")
|
||||
and input_scale_group_size == 128
|
||||
and weight_schema.hadamard_block_size <= 1
|
||||
and input_schema.input_quant_mode in (None, "dynamic_group")
|
||||
):
|
||||
q_dtype = _HUMMING_TO_QUANT_DTYPE.get(input_schema.a_dtype, FP8_DTYPE)
|
||||
q_dtype = humming_schema._HUMMING_TO_QUANT_DTYPE.get(
|
||||
input_schema.a_dtype, FP8_DTYPE
|
||||
)
|
||||
activation_group_shape = GroupShape(row=1, col=input_scale_group_size)
|
||||
|
||||
weight_scale_group_size = weight_schema.weight_scale_group_size
|
||||
@@ -665,7 +163,7 @@ def get_humming_moe_quant_config(
|
||||
else:
|
||||
weight_group_shape = GroupShape(row=weight_scale_group_size, col=1)
|
||||
|
||||
return make_humming_moe_quant_config(
|
||||
config = make_humming_moe_quant_config(
|
||||
quant_dtype=q_dtype,
|
||||
weight_dtype=str(weight_schema.b_dtype),
|
||||
weight_group_shape=weight_group_shape,
|
||||
@@ -683,6 +181,17 @@ def get_humming_moe_quant_config(
|
||||
gemm1_clamp_limit=gemm1_clamp_limit,
|
||||
humming_configs=humming_configs,
|
||||
)
|
||||
for prefix, sublayer in (("w1", "w13"), ("w2", "w2")):
|
||||
setattr(
|
||||
config,
|
||||
f"{prefix}_hadamard_block_size",
|
||||
layer.weight_schemas[sublayer].hadamard_block_size,
|
||||
)
|
||||
for name in ("input_scale", "input_scale_2"):
|
||||
key = f"{prefix}_{name}"
|
||||
value = getattr(layer, f"{sublayer}_{name}", None)
|
||||
setattr(config, key, value)
|
||||
return config
|
||||
|
||||
|
||||
def select_humming_moe_experts(
|
||||
@@ -846,12 +355,6 @@ def _convert_sublayer_to_humming(
|
||||
Tuple of (converted_weight_schema, converted_input_schema)
|
||||
|
||||
"""
|
||||
from vllm.utils.humming import HummingWeightSchema
|
||||
|
||||
if isinstance(weight_schema, HummingWeightSchema):
|
||||
# Already in Humming format
|
||||
return weight_schema, input_schema
|
||||
|
||||
tensors = _extract_sublayer_tensors(layer, sublayer_name)
|
||||
|
||||
shape_k_stacks = [shape_k]
|
||||
@@ -867,13 +370,14 @@ def _convert_sublayer_to_humming(
|
||||
num_experts=num_experts,
|
||||
)
|
||||
|
||||
converted_input_schema, _ = input_schema.convert_humming(
|
||||
tensors=converted_tensors,
|
||||
converted_input_schema, input_tensors = input_schema.convert_humming(
|
||||
tensors=tensors,
|
||||
shape_n_stacks=shape_n_stacks,
|
||||
shape_k_stacks=shape_k_stacks,
|
||||
param_dtype=param_dtype,
|
||||
num_experts=num_experts,
|
||||
)
|
||||
converted_tensors.update(input_tensors)
|
||||
|
||||
_replace_layer_parameters(layer, sublayer_name, converted_tensors)
|
||||
|
||||
@@ -907,11 +411,16 @@ def _prepare_and_transform_sublayer(
|
||||
has_bias=has_bias,
|
||||
num_experts=num_experts,
|
||||
torch_dtype=param_dtype,
|
||||
device=getattr(layer, f"{sublayer_name}_weight").device,
|
||||
)
|
||||
tensors = transform_humming_tensors(
|
||||
config,
|
||||
_extract_sublayer_tensors(layer, sublayer_name),
|
||||
)
|
||||
source_tensors = _extract_sublayer_tensors(layer, sublayer_name)
|
||||
for name in ("input_scale", "input_scale_2"):
|
||||
if name != input_schema.static_tensor_scale_name:
|
||||
source_tensors.pop(name, None)
|
||||
tensors = transform_humming_tensors(config, source_tensors)
|
||||
for name in ("input_scale", "input_scale_2"):
|
||||
if name in source_tensors:
|
||||
tensors[name] = source_tensors[name]
|
||||
_replace_layer_parameters(layer, sublayer_name, tensors)
|
||||
return config
|
||||
|
||||
@@ -927,6 +436,7 @@ def _process_single_sublayer(
|
||||
num_experts: int,
|
||||
param_dtype: torch.dtype,
|
||||
force_weight_schema: Any | None = None,
|
||||
allow_input_schema_fallback: bool = True,
|
||||
) -> tuple[Any, Any, "LayerConfig"]:
|
||||
"""Process a single sublayer: convert, optionally requant, prepare, and transform.
|
||||
|
||||
@@ -944,6 +454,7 @@ def _process_single_sublayer(
|
||||
num_experts: Number of experts
|
||||
param_dtype: Parameter data type
|
||||
force_weight_schema: Optional schema to force requantization to
|
||||
allow_input_schema_fallback: Whether incompatible input schemas may be replaced.
|
||||
|
||||
Returns:
|
||||
Tuple of the final weight schema, input schema, and Humming layer config.
|
||||
@@ -966,19 +477,28 @@ def _process_single_sublayer(
|
||||
# Step 2: Force requant if needed
|
||||
assert isinstance(current_weight_schema, HummingWeightSchema)
|
||||
if force_weight_schema is not None and current_weight_schema != force_weight_schema:
|
||||
tensors = _extract_sublayer_tensors(layer, sublayer_name)
|
||||
source_tensors = _extract_sublayer_tensors(layer, sublayer_name)
|
||||
|
||||
tensors = current_weight_schema.requant_tensors(
|
||||
tensors=tensors,
|
||||
tensors=source_tensors,
|
||||
target_weight_schema=force_weight_schema,
|
||||
param_dtype=param_dtype,
|
||||
)
|
||||
name = current_input_schema.static_tensor_scale_name
|
||||
if name is not None:
|
||||
tensors[name] = source_tensors[name]
|
||||
|
||||
current_weight_schema = force_weight_schema
|
||||
_replace_layer_parameters(layer, sublayer_name, tensors, preserve_bias=True)
|
||||
del tensors
|
||||
|
||||
# Step 3: Prepare layer metadata and transform weights
|
||||
current_input_schema = humming_schema.check_and_fallback_input_schema(
|
||||
weight_schema=current_weight_schema,
|
||||
input_schema=current_input_schema,
|
||||
param_dtype=param_dtype,
|
||||
allow_fallback=allow_input_schema_fallback,
|
||||
)
|
||||
config = _prepare_and_transform_sublayer(
|
||||
layer=layer,
|
||||
sublayer_name=sublayer_name,
|
||||
@@ -1001,6 +521,7 @@ def convert_to_humming_moe_kernel_format(
|
||||
weight_schema: Any | None = None,
|
||||
input_schema: Any | None = None,
|
||||
force_weight_schema: Any | None = None,
|
||||
allow_input_schema_fallback: bool = True,
|
||||
) -> dict[str, "LayerConfig"]:
|
||||
"""Convert MoE weights from checkpoint format to Humming kernel format.
|
||||
|
||||
@@ -1023,6 +544,7 @@ def convert_to_humming_moe_kernel_format(
|
||||
input_schema: Optional initial input quantization schema.
|
||||
If None, built from quant_config or env vars.
|
||||
force_weight_schema: Optional schema to force requantization to
|
||||
allow_input_schema_fallback: Whether incompatible input schemas may be replaced.
|
||||
|
||||
Side effects:
|
||||
- Modifies layer parameters in place
|
||||
@@ -1041,20 +563,23 @@ def convert_to_humming_moe_kernel_format(
|
||||
"Must provide either weight_schema/input_schema or quant_config"
|
||||
)
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.humming_utils import (
|
||||
humming_is_layer_skipped,
|
||||
)
|
||||
from vllm.utils.humming import BaseWeightSchema, HummingInputSchema
|
||||
|
||||
if weight_schema is None:
|
||||
weight_schema = BaseWeightSchema.from_config(quant_config)
|
||||
|
||||
if input_schema is None:
|
||||
input_quant_config = envs.VLLM_HUMMING_INPUT_QUANT_CONFIG or {}
|
||||
input_quant_config = (envs.VLLM_HUMMING_INPUT_QUANT_CONFIG or {}).copy()
|
||||
if humming_is_layer_skipped(input_quant_config, layer.layer_name):
|
||||
input_schema = HummingInputSchema()
|
||||
else:
|
||||
# TODO: read input_quant_config from quant_config
|
||||
input_quant_config = humming_schema.resolve_humming_layer_config(
|
||||
input_quant_config, layer.layer_name
|
||||
)
|
||||
allow_input_schema_fallback = input_quant_config.pop(
|
||||
"allow_fallback", False
|
||||
)
|
||||
input_schema = HummingInputSchema.from_config(input_quant_config)
|
||||
|
||||
# Build sublayer configs from layer properties if not provided
|
||||
@@ -1089,6 +614,7 @@ def convert_to_humming_moe_kernel_format(
|
||||
num_experts=num_experts,
|
||||
param_dtype=param_dtype,
|
||||
force_weight_schema=force_weight_schema,
|
||||
allow_input_schema_fallback=allow_input_schema_fallback,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Map Humming schemas and handle shared checkpoint quantization settings."""
|
||||
|
||||
import dataclasses
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
FP4_DTYPE,
|
||||
FP8_DTYPE,
|
||||
INT4_DTYPE,
|
||||
INT8_DTYPE,
|
||||
MXFP_SCALE_DTYPE,
|
||||
GroupShape,
|
||||
QuantKey,
|
||||
ScaleDesc,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.scalar_type import scalar_types
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.utils.humming import (
|
||||
BaseInputSchema,
|
||||
BaseWeightSchema,
|
||||
HummingInputSchema,
|
||||
HummingWeightSchema,
|
||||
)
|
||||
from vllm.utils.humming import dtypes as humming_dtypes
|
||||
|
||||
|
||||
def humming_update_schema_hadamard_block_size(
|
||||
weight_schema: "HummingWeightSchema",
|
||||
input_schema: "HummingInputSchema",
|
||||
shape_k: int,
|
||||
) -> "HummingWeightSchema":
|
||||
assert shape_k > 0
|
||||
block_size = 32
|
||||
weight_group_size = weight_schema.weight_scale_group_size
|
||||
input_group_size = input_schema.input_scale_group_size
|
||||
for group_size in (weight_group_size, input_group_size):
|
||||
if group_size is not None and group_size > 0:
|
||||
block_size = min(block_size, group_size)
|
||||
block_size = 1 << (block_size.bit_length() - 1)
|
||||
while shape_k % block_size:
|
||||
block_size //= 2
|
||||
return dataclasses.replace(weight_schema, hadamard_block_size=block_size)
|
||||
|
||||
|
||||
if has_humming():
|
||||
from vllm.utils.humming import dtypes as humming_dtypes
|
||||
|
||||
_HUMMING_TO_QUANT_DTYPE: dict[humming_dtypes.DataType, Any] = {
|
||||
humming_dtypes.float4e0m3: FP4_DTYPE,
|
||||
humming_dtypes.float4e2m1: FP4_DTYPE,
|
||||
humming_dtypes.float6e2m3: scalar_types.float6_e2m3f,
|
||||
humming_dtypes.float6e3m2: scalar_types.float6_e3m2f,
|
||||
humming_dtypes.float8e3m4: FP8_DTYPE,
|
||||
humming_dtypes.float8e4m3: FP8_DTYPE,
|
||||
humming_dtypes.float8e5m2: torch.float8_e5m2,
|
||||
humming_dtypes.int8: torch.int8,
|
||||
humming_dtypes.uint4: INT4_DTYPE,
|
||||
humming_dtypes.uint8: INT8_DTYPE,
|
||||
humming_dtypes.uint2: torch.uint8,
|
||||
humming_dtypes.uint3: torch.uint8,
|
||||
humming_dtypes.uint5: torch.uint8,
|
||||
humming_dtypes.uint6: torch.uint8,
|
||||
humming_dtypes.uint7: torch.uint8,
|
||||
}
|
||||
|
||||
_HUMMING_TO_SCALE_DTYPE: dict[humming_dtypes.DataType, torch.dtype] = {
|
||||
humming_dtypes.float8e8m0: MXFP_SCALE_DTYPE,
|
||||
humming_dtypes.float8e4m3: FP8_DTYPE,
|
||||
humming_dtypes.float16: torch.float16,
|
||||
humming_dtypes.bfloat16: torch.bfloat16,
|
||||
humming_dtypes.float32: torch.float32,
|
||||
}
|
||||
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _group_shape(group_size: int, group_size_n: int = 0) -> GroupShape:
|
||||
"""Map humming group sizes to QuantKey GroupShape.
|
||||
|
||||
group_size: elements per group along K (col); 0 means full dimension.
|
||||
group_size_n: elements per group along N (row); 0 means 1 (per-row).
|
||||
|
||||
GroupShape convention: row = N dim, col = K dim.
|
||||
"""
|
||||
if group_size == 0 and group_size_n == 0:
|
||||
return GroupShape.PER_CHANNEL
|
||||
|
||||
row = group_size_n if group_size_n > 0 else 1
|
||||
col = group_size if group_size > 0 else -1
|
||||
return GroupShape(row=row, col=col)
|
||||
|
||||
|
||||
def weight_schema_to_quant_key(
|
||||
schema: "BaseWeightSchema",
|
||||
param_dtype: torch.dtype | None = None,
|
||||
) -> QuantKey:
|
||||
from vllm.utils.humming import WeightScale2Type, WeightScaleType
|
||||
|
||||
if param_dtype is None:
|
||||
param_dtype = torch.get_default_dtype()
|
||||
if param_dtype not in [torch.float16, torch.bfloat16]:
|
||||
param_dtype = torch.bfloat16
|
||||
if not current_platform.has_device_capability(80):
|
||||
param_dtype = torch.float16
|
||||
|
||||
schema = schema.to_humming_schema(param_dtype)
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[schema.b_dtype]
|
||||
|
||||
if schema.bs_dtype is not None:
|
||||
scale_dtype = _HUMMING_TO_SCALE_DTYPE[schema.bs_dtype]
|
||||
else:
|
||||
scale_dtype = torch.float32
|
||||
|
||||
group_shape = _group_shape(
|
||||
schema.weight_scale_group_size,
|
||||
schema.weight_scale_group_size_n,
|
||||
)
|
||||
if schema.weight_scale_type == WeightScaleType.TENSOR:
|
||||
group_shape = GroupShape.PER_TENSOR
|
||||
|
||||
scale = ScaleDesc(dtype=scale_dtype, static=True, group_shape=group_shape)
|
||||
|
||||
scale2 = None
|
||||
if schema.weight_scale_2_type == WeightScale2Type.TENSOR:
|
||||
scale2 = ScaleDesc(
|
||||
dtype=torch.float32,
|
||||
static=True,
|
||||
group_shape=GroupShape.PER_TENSOR,
|
||||
)
|
||||
|
||||
return QuantKey(
|
||||
dtype=dtype,
|
||||
scale=scale,
|
||||
scale2=scale2,
|
||||
symmetric=not schema.has_zero_point,
|
||||
)
|
||||
|
||||
|
||||
def input_schema_to_quant_key(
|
||||
schema: "BaseInputSchema",
|
||||
param_dtype: torch.dtype | None = None,
|
||||
) -> QuantKey | None:
|
||||
from vllm.utils.humming import InputQuantizationMode
|
||||
|
||||
if param_dtype is None:
|
||||
param_dtype = torch.get_default_dtype()
|
||||
if param_dtype not in [torch.float16, torch.bfloat16]:
|
||||
param_dtype = torch.bfloat16
|
||||
if not current_platform.has_device_capability(80):
|
||||
param_dtype = torch.float16
|
||||
|
||||
schema = schema.to_humming_schema(param_dtype)
|
||||
if schema.a_dtype is None or schema.a_dtype.num_bits >= 16:
|
||||
return None
|
||||
|
||||
mode = schema.input_quant_mode
|
||||
if mode == InputQuantizationMode.Disabled:
|
||||
return None
|
||||
dtype = _HUMMING_TO_QUANT_DTYPE[schema.a_dtype]
|
||||
|
||||
gs = schema.input_scale_group_size
|
||||
group_shape = GroupShape(row=1, col=gs) if gs > 0 else GroupShape.PER_TOKEN
|
||||
|
||||
# Pick the scale dtype the Humming kernel actually consumes. An explicit
|
||||
# input_scale_dtype always wins. Otherwise infer from the grouping: MX
|
||||
# microscale activations (group size 32, e.g. MXFP8) carry an e8m0 (uint8)
|
||||
# scale, while block-FP8 (group size 128) and per-token FP8/int8 carry a
|
||||
# float32 scale. Getting this right lets a grouped FP8 activation match
|
||||
# kFp8Dynamic128Sym instead of an unmatchable uint8-scaled key.
|
||||
if schema.input_scale_dtype is not None:
|
||||
scale_dtype = _HUMMING_TO_SCALE_DTYPE[schema.input_scale_dtype]
|
||||
elif gs == 16:
|
||||
scale_dtype = FP8_DTYPE
|
||||
elif gs == 32:
|
||||
scale_dtype = MXFP_SCALE_DTYPE
|
||||
else:
|
||||
scale_dtype = torch.float32
|
||||
|
||||
if mode == InputQuantizationMode.StaticTensor:
|
||||
group_shape = GroupShape.PER_TENSOR
|
||||
scale = ScaleDesc(
|
||||
dtype=scale_dtype,
|
||||
static=mode == InputQuantizationMode.StaticTensor,
|
||||
group_shape=group_shape,
|
||||
)
|
||||
scale2 = None
|
||||
has_scale2 = (
|
||||
InputQuantizationMode.StaticTensorDynamicGroup,
|
||||
InputQuantizationMode.DynamicGroupToken,
|
||||
)
|
||||
if mode in has_scale2:
|
||||
static = mode == InputQuantizationMode.StaticTensorDynamicGroup
|
||||
scale2 = ScaleDesc(
|
||||
torch.float32,
|
||||
static,
|
||||
GroupShape.PER_TENSOR if static else GroupShape.PER_TOKEN,
|
||||
)
|
||||
|
||||
return QuantKey(dtype=dtype, scale=scale, scale2=scale2, symmetric=True)
|
||||
|
||||
|
||||
def quant_key_to_input_schema(key: QuantKey | None) -> "HummingInputSchema":
|
||||
from vllm.utils.humming import HummingInputSchema, InputQuantizationMode
|
||||
|
||||
if key is None:
|
||||
return HummingInputSchema(input_quant_mode=InputQuantizationMode.Disabled)
|
||||
|
||||
if not key.symmetric:
|
||||
raise ValueError("Humming input quantization must be symmetric")
|
||||
|
||||
quant_dtypes = {value: dtype for dtype, value in _HUMMING_TO_QUANT_DTYPE.items()}
|
||||
quant_dtypes[FP4_DTYPE] = humming_dtypes.float4e2m1
|
||||
quant_dtypes[FP8_DTYPE] = humming_dtypes.float8e4m3
|
||||
scale_dtypes = {value: dtype for dtype, value in _HUMMING_TO_SCALE_DTYPE.items()}
|
||||
if key.dtype not in quant_dtypes or key.scale.dtype not in scale_dtypes:
|
||||
raise ValueError(f"Unsupported Humming input or scale dtype: {key}")
|
||||
|
||||
scale = key.scale
|
||||
group_size = 0
|
||||
if scale.static and scale.group_shape.is_per_tensor() and key.scale2 is None:
|
||||
mode = InputQuantizationMode.StaticTensor
|
||||
elif not scale.static and scale.group_shape.is_per_token() and key.scale2 is None:
|
||||
mode = InputQuantizationMode.DynamicToken
|
||||
elif not scale.static and scale.group_shape.is_per_group():
|
||||
group_size = scale.group_shape.col
|
||||
scale2 = key.scale2
|
||||
if scale2 is None:
|
||||
mode = InputQuantizationMode.DynamicGroup
|
||||
elif scale2.dtype != torch.float32:
|
||||
raise ValueError("Humming secondary input scales must be float32")
|
||||
elif scale2.static and scale2.group_shape.is_per_tensor():
|
||||
mode = InputQuantizationMode.StaticTensorDynamicGroup
|
||||
elif not scale2.static and scale2.group_shape.is_per_token():
|
||||
mode = InputQuantizationMode.DynamicGroupToken
|
||||
else:
|
||||
raise ValueError(f"Unsupported Humming secondary input scale: {scale2}")
|
||||
else:
|
||||
raise ValueError(f"Unsupported Humming input scale: {key}")
|
||||
|
||||
if group_size == 0 and scale.dtype != torch.float32:
|
||||
raise ValueError("Humming tensor and token input scales must be float32")
|
||||
|
||||
return HummingInputSchema(
|
||||
a_dtype=quant_dtypes[key.dtype],
|
||||
input_scale_group_size=group_size,
|
||||
input_scale_dtype=scale_dtypes[scale.dtype],
|
||||
input_quant_mode=mode,
|
||||
)
|
||||
|
||||
|
||||
def check_and_fallback_input_schema(
|
||||
weight_schema: "BaseWeightSchema",
|
||||
input_schema: "BaseInputSchema",
|
||||
param_dtype: torch.dtype | None = None,
|
||||
allow_fallback: bool = True,
|
||||
) -> "HummingInputSchema":
|
||||
from vllm.utils.humming import HummingInputSchema, InputQuantizationMode
|
||||
|
||||
capability = current_platform.get_device_capability()
|
||||
assert capability is not None
|
||||
sm_version = capability.to_int()
|
||||
if param_dtype is None:
|
||||
param_dtype = torch.get_default_dtype()
|
||||
if param_dtype not in (torch.float16, torch.bfloat16):
|
||||
param_dtype = torch.bfloat16 if sm_version >= 80 else torch.float16
|
||||
assert param_dtype in (torch.float16, torch.bfloat16)
|
||||
|
||||
dtype_fallback_order_map = {
|
||||
humming_dtypes.float8e5m2: (
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.float8e3m4,
|
||||
humming_dtypes.int8,
|
||||
),
|
||||
humming_dtypes.float8e4m3: (
|
||||
humming_dtypes.float8e3m4,
|
||||
humming_dtypes.int8,
|
||||
),
|
||||
humming_dtypes.float8e3m4: (
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.int8,
|
||||
),
|
||||
humming_dtypes.float4e2m1: (
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.float8e3m4,
|
||||
humming_dtypes.int8,
|
||||
),
|
||||
humming_dtypes.float4e0m3: (
|
||||
humming_dtypes.int4,
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.float8e3m4,
|
||||
humming_dtypes.int8,
|
||||
),
|
||||
humming_dtypes.int8: (
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.float8e3m4,
|
||||
),
|
||||
humming_dtypes.int4: (
|
||||
humming_dtypes.int8,
|
||||
humming_dtypes.float8e4m3,
|
||||
humming_dtypes.float8e3m4,
|
||||
),
|
||||
}
|
||||
|
||||
weight_schema = weight_schema.to_humming_schema(param_dtype)
|
||||
input_schema = input_schema.to_humming_schema(param_dtype)
|
||||
fp6_dtypes = (humming_dtypes.float6e2m3, humming_dtypes.float6e3m2)
|
||||
if input_schema.a_dtype in fp6_dtypes:
|
||||
input_schema.a_dtype = humming_dtypes.float8e4m3
|
||||
a_dtype = input_schema.a_dtype
|
||||
input_bits = a_dtype.num_bits if a_dtype is not None else 16
|
||||
weight_group_size = weight_schema.weight_scale_group_size
|
||||
input_group_size = input_schema.input_scale_group_size
|
||||
input_scale_dtype = input_schema.input_scale_dtype
|
||||
|
||||
def is_deprecated(dtype: "humming_dtypes.DataType | None") -> bool:
|
||||
if dtype is None or dtype.num_bits == 16:
|
||||
return False
|
||||
is_int4_deprecated = dtype == humming_dtypes.int4 and sm_version >= 90
|
||||
is_int8_deprecated = dtype == humming_dtypes.int8 and 103 <= sm_version < 110
|
||||
# Humming has not yet implemented high-performance FP8 computation
|
||||
# on SM10X and SM11X. Therefore, it is temporarily considered deprecated.
|
||||
# TODO: removed this after Humming has high-performance FP8 computation
|
||||
is_fp8_deprecated = dtype.num_bits < 16 and 100 <= sm_version < 120
|
||||
return is_int4_deprecated or is_int8_deprecated or is_fp8_deprecated
|
||||
|
||||
if input_schema.is_compatible_with(weight_schema, param_dtype):
|
||||
if not allow_fallback:
|
||||
if is_deprecated(a_dtype):
|
||||
msg = f"Humming {a_dtype} activation is slow on SM{sm_version} now."
|
||||
logger.warning_once(msg)
|
||||
return input_schema
|
||||
|
||||
if a_dtype is None or a_dtype.num_bits == 16:
|
||||
return input_schema
|
||||
|
||||
if not is_deprecated(a_dtype):
|
||||
is_mxfp8 = (
|
||||
a_dtype.is_floating_point_type
|
||||
and a_dtype.num_bits == 8
|
||||
and input_group_size == 32
|
||||
and input_scale_dtype == humming_dtypes.float8e8m0
|
||||
and sm_version >= 120
|
||||
)
|
||||
is_groupwise = input_group_size > 0 or weight_group_size > 0
|
||||
if input_bits == 8 and is_groupwise and not is_mxfp8:
|
||||
# prefer wna16 for groupwise weight or groupwise input
|
||||
return HummingInputSchema()
|
||||
|
||||
return input_schema
|
||||
|
||||
if allow_fallback:
|
||||
fallback_dtypes = (
|
||||
a_dtype,
|
||||
*dtype_fallback_order_map.get(a_dtype, ()),
|
||||
humming_dtypes.DataType.from_any(param_dtype),
|
||||
)
|
||||
for dtype in fallback_dtypes:
|
||||
if dtype is None or is_deprecated(dtype):
|
||||
continue
|
||||
|
||||
group_size = 0
|
||||
scale_dtype = humming_dtypes.float32
|
||||
quant_mode = InputQuantizationMode.DynamicToken
|
||||
if dtype.num_bits == 16:
|
||||
scale_dtype = None
|
||||
quant_mode = InputQuantizationMode.Disabled
|
||||
elif dtype in (humming_dtypes.float8e4m3, humming_dtypes.float8e3m4):
|
||||
is_channelwise_weight = weight_schema.weight_scale_group_size == 0
|
||||
weight_group_size = weight_schema.weight_scale_group_size
|
||||
is_e8m0_scale = weight_schema.bs_dtype == humming_dtypes.float8e8m0
|
||||
is_mx_weight = weight_group_size == 32 and is_e8m0_scale
|
||||
if sm_version >= 120 and (is_channelwise_weight or is_mx_weight):
|
||||
group_size = 32
|
||||
scale_dtype = humming_dtypes.float8e8m0
|
||||
quant_mode = InputQuantizationMode.DynamicGroup
|
||||
|
||||
candidate = HummingInputSchema(
|
||||
a_dtype=dtype,
|
||||
input_scale_group_size=group_size,
|
||||
input_scale_dtype=scale_dtype,
|
||||
input_quant_mode=quant_mode,
|
||||
)
|
||||
if candidate.is_compatible_with(weight_schema, param_dtype):
|
||||
return candidate
|
||||
|
||||
raise ValueError(
|
||||
f"No compatible Humming input schema for {input_schema} with "
|
||||
f"weight schema {weight_schema} on SM{sm_version} "
|
||||
f"({allow_fallback=})"
|
||||
)
|
||||
|
||||
|
||||
def resolve_humming_layer_config(config: dict[str, Any], prefix: str) -> dict[str, Any]:
|
||||
layer_config = config.copy()
|
||||
dynamic = config.get("dynamic", {})
|
||||
if isinstance(dynamic, dict):
|
||||
for pattern, overrides in dynamic.items():
|
||||
if pattern.startswith("+") and re.match(pattern[2:], prefix):
|
||||
layer_config.update(overrides)
|
||||
break
|
||||
return layer_config
|
||||
|
||||
|
||||
def humming_is_layer_skipped(config: dict[str, Any], prefix: str):
|
||||
if not config:
|
||||
return True
|
||||
|
||||
keys = ["ignored_layers", "ignore", "modules_to_not_convert"]
|
||||
ignored_layers: list[str] = []
|
||||
for key in keys:
|
||||
candidate = config.get(key, []) or []
|
||||
if candidate:
|
||||
ignored_layers = candidate
|
||||
break
|
||||
|
||||
if any(module_name in prefix for module_name in ignored_layers):
|
||||
return True
|
||||
if "lm_head" in prefix:
|
||||
return True
|
||||
|
||||
for regex in config.get("dynamic", {}):
|
||||
if regex[:1] != "-":
|
||||
continue
|
||||
if re.match(regex[2:], prefix):
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -12,7 +12,13 @@ from torch import nn
|
||||
from typing_extensions import assert_never
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import ModelConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.config import (
|
||||
LoadConfig,
|
||||
ModelConfig,
|
||||
VllmConfig,
|
||||
replace,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.attention import is_deferred_attention_layer
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
@@ -23,6 +29,9 @@ from vllm.model_executor.model_loader.reload import (
|
||||
record_metadata_for_reloading,
|
||||
set_torchao_reload_attrs,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_cache.utils import (
|
||||
is_draft_model_cacheable,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_tying import maybe_retie_word_embeddings
|
||||
from vllm.model_executor.models.interfaces import SupportsQuant
|
||||
from vllm.model_executor.utils import is_weights_pre_processed
|
||||
@@ -34,6 +43,33 @@ from vllm.utils.torch_utils import get_accelerator_view_from_cpu_tensor
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def get_draft_load_config(vllm_config: VllmConfig) -> LoadConfig:
|
||||
"""Get load config for the speculative draft model."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
if (
|
||||
speculative_config is not None
|
||||
and speculative_config.draft_load_config is not None
|
||||
):
|
||||
return speculative_config.draft_load_config
|
||||
load_config = vllm_config.load_config
|
||||
if load_config is not None and load_config.load_format != "ipc_cache":
|
||||
return load_config
|
||||
kwargs = (
|
||||
# Route the draft to the daemon's draft group.
|
||||
{
|
||||
"model_loader_extra_config": {
|
||||
**load_config.model_loader_extra_config,
|
||||
"is_draft": True,
|
||||
}
|
||||
}
|
||||
if is_draft_model_cacheable(speculative_config)
|
||||
# No daemon draft group for this method; load from disk instead of
|
||||
# hitting the target daemon with a mismatching fingerprint.
|
||||
else {"load_format": "auto", "model_loader_extra_config": {}}
|
||||
)
|
||||
return replace(load_config, **kwargs)
|
||||
|
||||
|
||||
@instrument(span_name="Initialize model")
|
||||
def initialize_model(
|
||||
vllm_config: VllmConfig,
|
||||
|
||||
@@ -1,26 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm.model_executor.model_loader.weight_cache.ipc_loader import IpcModelLoader
|
||||
from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
CacheConfigMismatchError,
|
||||
TensorEntry,
|
||||
UnsupportedPlatformForIPCError,
|
||||
UnsupportedQuantForIPCError,
|
||||
WeightCacheKey,
|
||||
WeightCacheUnavailableError,
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CacheConfigMismatchError",
|
||||
"IpcModelLoader",
|
||||
"TensorEntry",
|
||||
"UnsupportedPlatformForIPCError",
|
||||
"UnsupportedQuantForIPCError",
|
||||
"WeightCacheKey",
|
||||
"WeightCacheUnavailableError",
|
||||
"check_ipc_platform_support",
|
||||
"check_ipc_quant_support",
|
||||
]
|
||||
|
||||
@@ -41,6 +41,13 @@ The global TP rank of local GPU ``i`` on node ``r`` is
|
||||
``r * (tp_size // nnodes) + i``, matching vLLM's contiguous per-node rank
|
||||
assignment, so each engine worker maps its shard from the daemon on its own
|
||||
node.
|
||||
|
||||
With MTP, EAGLE or EAGLE3 speculative decoding the launcher additionally
|
||||
starts a draft daemon group that caches the draft model. It uses its own cache
|
||||
key, Unix sockets (``*_draft.sock``) and rendezvous port
|
||||
(``--weight-cache-draft-master-port``, default ``--weight-cache-master-port +
|
||||
1``), so each process serves exactly one model role. Other draft types are not
|
||||
cached and keep loading from disk in the engine.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
@@ -52,10 +59,15 @@ import signal
|
||||
import socket
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from itertools import product
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import ParallelConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.config import (
|
||||
ParallelConfig,
|
||||
VllmConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.distributed import (
|
||||
ensure_model_parallel_initialized,
|
||||
init_distributed_environment,
|
||||
@@ -77,6 +89,11 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
send_msg,
|
||||
verify_peer_is_owner,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_cache.utils import (
|
||||
export_model_attrs,
|
||||
format_daemon_role,
|
||||
is_draft_model_cacheable,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
@@ -130,30 +147,6 @@ def export_entries(
|
||||
return entries, aliases
|
||||
|
||||
|
||||
def get_daemon_model(vllm_config: VllmConfig) -> torch.nn.Module:
|
||||
"""Load the daemon's model, composed from the configured loader.
|
||||
|
||||
Runs the quantization check after model creation but before the slow
|
||||
weight load, so an unsupported method fails fast. Online quantization
|
||||
always fails the check, so load_model's finalize step for it is
|
||||
unnecessary here.
|
||||
"""
|
||||
model_config = vllm_config.model_config
|
||||
load_config = vllm_config.load_config
|
||||
loader = get_model_loader(load_config)
|
||||
device_config = vllm_config.device_config
|
||||
target_device = torch.device(
|
||||
device_config.device if load_config.device is None else load_config.device
|
||||
)
|
||||
with set_default_torch_dtype(model_config.dtype):
|
||||
with target_device:
|
||||
model = loader.create_model(vllm_config, model_config)
|
||||
check_ipc_quant_support(model)
|
||||
loader.load_weights(model, model_config)
|
||||
process_weights_after_loading(model, model_config, target_device)
|
||||
return model.eval()
|
||||
|
||||
|
||||
class WeightCacheDaemon:
|
||||
"""Per-GPU process that loads one TP shard and serves CUDA IPC handles."""
|
||||
|
||||
@@ -164,19 +157,31 @@ class WeightCacheDaemon:
|
||||
local_rank: int,
|
||||
distributed_init_method: str,
|
||||
socket_dir: str | None = None,
|
||||
is_draft: bool = False,
|
||||
):
|
||||
self.vllm_config = vllm_config
|
||||
# A draft daemon builds the draft with the target's VllmConfig, like
|
||||
# the engine does; only the ModelConfig differs.
|
||||
if is_draft:
|
||||
spec = vllm_config.speculative_config
|
||||
assert spec is not None and spec.draft_model_config is not None
|
||||
self.model_config = spec.draft_model_config
|
||||
else:
|
||||
self.model_config = vllm_config.model_config
|
||||
self.tp_rank = tp_rank
|
||||
self.local_rank = local_rank
|
||||
self.distributed_init_method = distributed_init_method
|
||||
self.socket_dir = socket_dir
|
||||
self.is_draft = is_draft
|
||||
self.role = format_daemon_role(is_draft)
|
||||
self.model: torch.nn.Module | None = None
|
||||
# Fingerprint before loading: process_weights_after_loading may
|
||||
# mutate hf_config.quantization_config.
|
||||
self.cache_config = WeightCacheKey.from_model_config(
|
||||
vllm_config.model_config,
|
||||
self.model_config,
|
||||
tp_size=vllm_config.parallel_config.tensor_parallel_size,
|
||||
tp_rank=tp_rank,
|
||||
is_draft=is_draft,
|
||||
)
|
||||
|
||||
def load_model(self) -> None:
|
||||
@@ -191,12 +196,37 @@ class WeightCacheDaemon:
|
||||
)
|
||||
with set_current_vllm_config(self.vllm_config):
|
||||
ensure_model_parallel_initialized(tp_size, 1)
|
||||
self.model = get_daemon_model(self.vllm_config)
|
||||
self.model = self.get_model()
|
||||
logger.info(
|
||||
"Weight cache daemon rank %d loaded model",
|
||||
"Weight cache %s daemon rank %d loaded model",
|
||||
self.role,
|
||||
self.tp_rank,
|
||||
)
|
||||
|
||||
def get_model(self) -> torch.nn.Module:
|
||||
"""Load the daemon's model, composed from the configured loader.
|
||||
|
||||
Runs the quantization check after model creation but before the slow
|
||||
weight load, so an unsupported method fails fast. Online quantization
|
||||
always fails the check, so load_model's finalize step for it is
|
||||
unnecessary here.
|
||||
"""
|
||||
vllm_config = self.vllm_config
|
||||
model_config = self.model_config
|
||||
load_config = vllm_config.load_config
|
||||
loader = get_model_loader(load_config)
|
||||
device_config = vllm_config.device_config
|
||||
target_device = torch.device(
|
||||
device_config.device if load_config.device is None else load_config.device
|
||||
)
|
||||
with set_default_torch_dtype(model_config.dtype):
|
||||
with target_device:
|
||||
model = loader.create_model(vllm_config, model_config)
|
||||
check_ipc_quant_support(model)
|
||||
loader.load_weights(model, model_config)
|
||||
process_weights_after_loading(model, model_config, target_device)
|
||||
return model.eval()
|
||||
|
||||
def serve_forever(self, ready_callback: Callable[[], None] | None = None) -> None:
|
||||
"""Serve requests until terminated.
|
||||
|
||||
@@ -223,7 +253,10 @@ class WeightCacheDaemon:
|
||||
os.chmod(socket_path, 0o600)
|
||||
server.listen()
|
||||
logger.info(
|
||||
"Weight cache daemon rank %d serving on %s", self.tp_rank, socket_path
|
||||
"Weight cache %s daemon rank %d serving on %s",
|
||||
self.role,
|
||||
self.tp_rank,
|
||||
socket_path,
|
||||
)
|
||||
if ready_callback is not None:
|
||||
ready_callback()
|
||||
@@ -270,7 +303,11 @@ class WeightCacheDaemon:
|
||||
|
||||
@property
|
||||
def _socket_path(self) -> str:
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
return get_socket_path(
|
||||
get_current_device_uuid(),
|
||||
self.socket_dir,
|
||||
is_draft=self.is_draft,
|
||||
)
|
||||
|
||||
def _handle_connection(self, conn: socket.socket) -> None:
|
||||
request = recv_msg(conn)
|
||||
@@ -303,11 +340,13 @@ class WeightCacheDaemon:
|
||||
"status": "ok",
|
||||
"entries": entries,
|
||||
"aliases": aliases,
|
||||
"attrs": export_model_attrs(self.model),
|
||||
"gpu_uuid": gpu_uuid,
|
||||
},
|
||||
)
|
||||
logger.info_once(
|
||||
"Weight cache daemon rank %d sent %d tensors (+%d aliases) to engine",
|
||||
"Weight cache %s daemon rank %d sent %d tensors (+%d aliases) to engine",
|
||||
self.role,
|
||||
self.tp_rank,
|
||||
len(entries),
|
||||
len(aliases),
|
||||
@@ -316,7 +355,11 @@ class WeightCacheDaemon:
|
||||
def _handle_release(self, conn: socket.socket) -> None:
|
||||
self.model = None
|
||||
torch.accelerator.empty_cache()
|
||||
logger.info("Weight cache daemon rank %d released cached weights", self.tp_rank)
|
||||
logger.info(
|
||||
"Weight cache %s daemon rank %d released cached weights",
|
||||
self.role,
|
||||
self.tp_rank,
|
||||
)
|
||||
send_msg(conn, {"status": "ok"})
|
||||
|
||||
|
||||
@@ -326,13 +369,27 @@ def _run_daemon(
|
||||
vllm_config: VllmConfig,
|
||||
distributed_init_method: str,
|
||||
socket_dir: str | None,
|
||||
ready_queue: "multiprocessing.Queue[int]",
|
||||
ready_queue: "multiprocessing.Queue[tuple[str, int]]",
|
||||
is_draft: bool = False,
|
||||
) -> None:
|
||||
daemon = WeightCacheDaemon(
|
||||
vllm_config, tp_rank, local_rank, distributed_init_method, socket_dir
|
||||
vllm_config,
|
||||
tp_rank,
|
||||
local_rank,
|
||||
distributed_init_method,
|
||||
socket_dir,
|
||||
is_draft,
|
||||
)
|
||||
daemon.load_model()
|
||||
daemon.serve_forever(ready_callback=lambda: ready_queue.put(tp_rank))
|
||||
daemon.serve_forever(ready_callback=lambda: ready_queue.put((daemon.role, tp_rank)))
|
||||
|
||||
|
||||
def get_draft_daemon_config(vllm_config: VllmConfig) -> VllmConfig | None:
|
||||
"""VllmConfig for the draft daemon group"""
|
||||
if not is_draft_model_cacheable(vllm_config.speculative_config):
|
||||
return None
|
||||
assert vllm_config.speculative_config is not None
|
||||
return vllm_config.speculative_config.apply_draft_overrides(vllm_config)
|
||||
|
||||
|
||||
def _reject_unsupported_parallelism(parallel_config: ParallelConfig) -> None:
|
||||
@@ -369,6 +426,14 @@ def main() -> None:
|
||||
"serving) and match across nodes. Required when --nnodes > 1; defaults "
|
||||
"to a free port for single-node.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--weight-cache-draft-master-port",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Rendezvous port for the MTP draft daemon group. Defaults to "
|
||||
"--weight-cache-master-port + 1 for multi-node, or a free port for "
|
||||
"single-node.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
engine_args = EngineArgs.from_cli_args(args)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
@@ -398,27 +463,56 @@ def main() -> None:
|
||||
master_port = args.weight_cache_master_port or get_open_port()
|
||||
distributed_init_method = get_distributed_init_method(master_addr, master_port)
|
||||
|
||||
# (is_draft, vllm_config, rendezvous) per daemon group.
|
||||
groups: list[tuple[bool, VllmConfig, str]] = [
|
||||
(False, vllm_config, distributed_init_method)
|
||||
]
|
||||
draft_vllm_config = get_draft_daemon_config(vllm_config)
|
||||
if draft_vllm_config is not None:
|
||||
draft_master_port = args.weight_cache_draft_master_port or (
|
||||
master_port + 1 if nnodes > 1 else get_open_port()
|
||||
)
|
||||
if draft_master_port == master_port:
|
||||
raise ValueError(
|
||||
"--weight-cache-draft-master-port must differ from "
|
||||
"--weight-cache-master-port"
|
||||
)
|
||||
groups.append(
|
||||
(
|
||||
True,
|
||||
draft_vllm_config,
|
||||
get_distributed_init_method(master_addr, draft_master_port),
|
||||
)
|
||||
)
|
||||
|
||||
ctx = multiprocessing.get_context("spawn")
|
||||
ready_queue: multiprocessing.Queue[int] = ctx.Queue()
|
||||
ready_queue: multiprocessing.Queue[tuple[str, int]] = ctx.Queue()
|
||||
# Global TP rank of local GPU i on this node; local index == device index.
|
||||
global_ranks = [
|
||||
node_rank * local_world_size + local_rank
|
||||
for local_rank in range(local_world_size)
|
||||
]
|
||||
expected_ready = {
|
||||
(format_daemon_role(is_draft), global_rank)
|
||||
for (is_draft, _, _), global_rank in product(groups, global_ranks)
|
||||
}
|
||||
procs = [
|
||||
ctx.Process(
|
||||
target=_run_daemon,
|
||||
args=(
|
||||
global_rank,
|
||||
local_rank,
|
||||
vllm_config,
|
||||
distributed_init_method,
|
||||
config,
|
||||
init_method,
|
||||
args.weight_cache_socket_dir,
|
||||
ready_queue,
|
||||
is_draft,
|
||||
),
|
||||
name=f"vllm-weight-cache-daemon-{global_rank}",
|
||||
name=f"vllm-weight-cache-{format_daemon_role(is_draft)}-{global_rank}",
|
||||
)
|
||||
for (is_draft, config, init_method), (local_rank, global_rank) in product(
|
||||
groups, enumerate(global_ranks)
|
||||
)
|
||||
for local_rank, global_rank in enumerate(global_ranks)
|
||||
]
|
||||
for proc in procs:
|
||||
proc.start()
|
||||
@@ -430,10 +524,10 @@ def main() -> None:
|
||||
signal.signal(signal.SIGINT, _shutdown)
|
||||
signal.signal(signal.SIGTERM, _shutdown)
|
||||
|
||||
ready_ranks: set[int] = set()
|
||||
while len(ready_ranks) < local_world_size:
|
||||
ready: set[tuple[str, int]] = set()
|
||||
while len(ready) < len(expected_ready):
|
||||
try:
|
||||
ready_ranks.add(ready_queue.get(timeout=1.0))
|
||||
ready.add(ready_queue.get(timeout=1.0))
|
||||
except queue.Empty:
|
||||
dead = [p for p in procs if p.exitcode is not None]
|
||||
if dead:
|
||||
@@ -450,10 +544,11 @@ def main() -> None:
|
||||
socket_dir_msg = args.weight_cache_socket_dir or "the default socket dir"
|
||||
logger.info_once(
|
||||
"===== Weight cache daemon READY: node %d/%d serving %d local rank(s) "
|
||||
"in %s =====",
|
||||
"x %d role(s) in %s =====",
|
||||
node_rank,
|
||||
nnodes,
|
||||
local_world_size,
|
||||
len(groups),
|
||||
socket_dir_msg,
|
||||
)
|
||||
|
||||
|
||||
@@ -25,9 +25,9 @@ from vllm.model_executor.model_loader.utils import (
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
CacheConfigMismatchError,
|
||||
TensorEntry,
|
||||
UnsupportedQuantForIPCError,
|
||||
WeightCacheKey,
|
||||
WeightCacheState,
|
||||
WeightCacheUnavailableError,
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
@@ -60,7 +60,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
Extra config keys (via --model-loader-extra-config):
|
||||
|
||||
- socket_path: explicit daemon socket path. Defaults to a per-GPU path
|
||||
derived from the physical GPU uuid.
|
||||
derived from the physical GPU uuid and the cache role (target/draft).
|
||||
- socket_dir: directory containing the daemon sockets.
|
||||
- mode: "zero_copy" (default) or "copy".
|
||||
- fallback: fall back to disk loading when the daemon is unavailable or
|
||||
@@ -78,6 +78,15 @@ class IpcModelLoader(BaseModelLoader):
|
||||
extra_config = copy(load_config.model_loader_extra_config or {})
|
||||
self.socket_path: str | None = extra_config.pop("socket_path", None)
|
||||
self.socket_dir: str | None = extra_config.pop("socket_dir", None)
|
||||
# Internal: set by the engine when routing a speculative draft to the
|
||||
# daemon's draft group.
|
||||
self.is_draft = bool(extra_config.pop("is_draft", False))
|
||||
if self.is_draft and self.socket_path is not None:
|
||||
raise ValueError(
|
||||
"socket_path cannot be combined with the draft weight cache role; "
|
||||
"use socket_dir so the target and draft sockets are derived "
|
||||
"independently"
|
||||
)
|
||||
self.mode: str = extra_config.pop("mode", "zero_copy")
|
||||
self.fallback: bool = extra_config.pop("fallback", True)
|
||||
self.connect_timeout_s: float = float(
|
||||
@@ -108,7 +117,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
loaded through this loader).
|
||||
"""
|
||||
device_index = torch.accelerator.current_device_index()
|
||||
entries, _ = self._fetch_entries(model_config)
|
||||
entries = self._fetch_entries(model_config).entries
|
||||
params = dict(model.named_parameters())
|
||||
buffers = dict(model.named_buffers())
|
||||
for name, entry in entries.items():
|
||||
@@ -128,11 +137,22 @@ class IpcModelLoader(BaseModelLoader):
|
||||
check_ipc_platform_support()
|
||||
state_fetched = False
|
||||
try:
|
||||
entries, aliases = self._fetch_entries(model_config)
|
||||
# Cross-check the routing flag against the identity of the model
|
||||
# being loaded: a draft load that lost its flag (or a target load
|
||||
# that got one) would hit the wrong daemon group and
|
||||
# fingerprint-mismatch.
|
||||
spec = vllm_config.speculative_config
|
||||
inferred = spec is not None and model_config is spec.draft_model_config
|
||||
if inferred != self.is_draft:
|
||||
raise CacheConfigMismatchError(
|
||||
f"Weight cache role mismatch: loading "
|
||||
f"{'draft' if inferred else 'target'} model but the loader "
|
||||
f"was configured for the "
|
||||
f"{'draft' if self.is_draft else 'target'} group"
|
||||
)
|
||||
state = self._fetch_entries(model_config)
|
||||
state_fetched = True
|
||||
return self._build_model(
|
||||
vllm_config, model_config, prefix, entries, aliases
|
||||
)
|
||||
return self._build_model(vllm_config, model_config, prefix, state)
|
||||
except (WeightCacheUnavailableError, CacheConfigMismatchError) as e:
|
||||
if not self.fallback:
|
||||
raise
|
||||
@@ -163,8 +183,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
vllm_config: VllmConfig,
|
||||
model_config: ModelConfig,
|
||||
prefix: str,
|
||||
entries: dict[str, TensorEntry],
|
||||
aliases: dict[str, str],
|
||||
state: WeightCacheState,
|
||||
) -> nn.Module:
|
||||
device_config = vllm_config.device_config
|
||||
load_device = (
|
||||
@@ -186,7 +205,11 @@ class IpcModelLoader(BaseModelLoader):
|
||||
prefix=prefix,
|
||||
)
|
||||
check_ipc_quant_support(model)
|
||||
self._apply_entries(model, entries, aliases, device_index)
|
||||
self._apply_entries(model, state, device_index)
|
||||
# Flags that load_weights would have set (e.g. EAGLE ownership of
|
||||
# embed_tokens / lm_head); the daemon ran it, this process did not.
|
||||
for name, value in state.attrs.items():
|
||||
setattr(model, name, value)
|
||||
# The daemon exports tensors that already went through
|
||||
# process_weights_after_loading; re-run it in pre-processed mode
|
||||
# so quant methods only rebuild Python-side state (e.g. the MoE
|
||||
@@ -202,7 +225,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
self._send_release()
|
||||
logger.info(
|
||||
"Mapped %d tensors from the weight cache daemon (%s mode)",
|
||||
len(entries),
|
||||
len(state.entries),
|
||||
self.mode,
|
||||
)
|
||||
return model.eval()
|
||||
@@ -210,8 +233,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _apply_entries(
|
||||
self,
|
||||
model: nn.Module,
|
||||
entries: dict[str, TensorEntry],
|
||||
aliases: dict[str, str],
|
||||
state: WeightCacheState,
|
||||
device_index: int,
|
||||
) -> None:
|
||||
# remove_duplicate=False keeps tied module aliases reachable by name:
|
||||
@@ -242,7 +264,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
module.register_buffer(leaf, obj)
|
||||
registered[name] = obj
|
||||
|
||||
for name, entry in entries.items():
|
||||
for name, entry in state.entries.items():
|
||||
tensor = entry.rebuild(device_index)
|
||||
if self.mode == "copy":
|
||||
tensor = tensor.clone()
|
||||
@@ -251,7 +273,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
# Re-establish tied-weight aliases by registering the *same* object the
|
||||
# canonical name resolved to, so parameter identity (and the tie) is
|
||||
# preserved instead of allocating uninitialized memory.
|
||||
for alias_name, canonical_name in aliases.items():
|
||||
for alias_name, canonical_name in state.aliases.items():
|
||||
obj = registered.get(canonical_name)
|
||||
if obj is None:
|
||||
logger.warning(
|
||||
@@ -262,19 +284,16 @@ class IpcModelLoader(BaseModelLoader):
|
||||
continue
|
||||
_register(alias_name, obj, isinstance(obj, nn.Parameter))
|
||||
|
||||
def _fetch_entries(
|
||||
self, model_config: ModelConfig
|
||||
) -> tuple[dict[str, TensorEntry], dict[str, str]]:
|
||||
def _fetch_entries(self, model_config: ModelConfig) -> WeightCacheState:
|
||||
cache_config = WeightCacheKey.from_model_config(
|
||||
model_config,
|
||||
tp_size=get_tensor_model_parallel_world_size(),
|
||||
tp_rank=get_tensor_model_parallel_rank(),
|
||||
is_draft=self.is_draft,
|
||||
)
|
||||
return self._request_state(cache_config)
|
||||
|
||||
def _request_state(
|
||||
self, cache_config: WeightCacheKey
|
||||
) -> tuple[dict[str, TensorEntry], dict[str, str]]:
|
||||
def _request_state(self, cache_config: WeightCacheKey) -> WeightCacheState:
|
||||
with self._connect(self.state_timeout_s) as conn:
|
||||
send_msg(conn, {"cmd": "get_state", "cache_config": cache_config})
|
||||
response = recv_msg(conn)
|
||||
@@ -288,7 +307,11 @@ class IpcModelLoader(BaseModelLoader):
|
||||
f"Weight cache daemon error: {response.get('message')}"
|
||||
)
|
||||
self._check_gpu_uuid(response.get("gpu_uuid"))
|
||||
return response["entries"], response.get("aliases", {})
|
||||
return WeightCacheState(
|
||||
entries=response["entries"],
|
||||
aliases=response.get("aliases", {}),
|
||||
attrs=response.get("attrs", {}),
|
||||
)
|
||||
|
||||
def _connect(self, timeout: float) -> socket.socket:
|
||||
socket_path = self._resolve_socket_path()
|
||||
@@ -316,7 +339,11 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _resolve_socket_path(self) -> str:
|
||||
if self.socket_path is not None:
|
||||
return self.socket_path
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
return get_socket_path(
|
||||
get_current_device_uuid(),
|
||||
self.socket_dir,
|
||||
is_draft=self.is_draft,
|
||||
)
|
||||
|
||||
def _check_gpu_uuid(self, daemon_uuid: str | None) -> None:
|
||||
if daemon_uuid is None:
|
||||
@@ -340,7 +367,9 @@ class IpcModelLoader(BaseModelLoader):
|
||||
# DefaultModelLoader must not see load_format="ipc_cache" or the ipc
|
||||
# extra config keys.
|
||||
return dataclasses.replace(
|
||||
self.load_config, load_format="auto", model_loader_extra_config={}
|
||||
self.load_config,
|
||||
load_format="auto",
|
||||
model_loader_extra_config={},
|
||||
)
|
||||
|
||||
def _fallback_load(
|
||||
|
||||
@@ -20,7 +20,7 @@ import stat
|
||||
import struct
|
||||
import tempfile
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
import torch
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor, reduce_tensor
|
||||
@@ -29,13 +29,16 @@ from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
|
||||
import vllm.version
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
|
||||
from vllm.model_executor.model_loader.weight_cache.utils import (
|
||||
format_socket_role_suffix,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
filter_duplicate_safetensors_files,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_{gpu_uuid}.sock"
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_{gpu_uuid}{role}.sock"
|
||||
SOCKET_DIR_TEMPLATE = "vllm_weight_cache_{uid}"
|
||||
|
||||
_LEN_STRUCT = struct.Struct("!Q")
|
||||
@@ -128,9 +131,23 @@ def get_socket_dir(socket_dir: str | None = None) -> str:
|
||||
)
|
||||
|
||||
|
||||
def get_socket_path(gpu_uuid: str, socket_dir: str | None = None) -> str:
|
||||
directory = get_socket_dir(socket_dir)
|
||||
return os.path.join(directory, SOCKET_NAME_TEMPLATE.format(gpu_uuid=gpu_uuid))
|
||||
def get_socket_path(
|
||||
gpu_uuid: str,
|
||||
socket_dir: str | None = None,
|
||||
*,
|
||||
is_draft: bool = False,
|
||||
) -> str:
|
||||
"""Socket path of a daemon group; ``is_draft=False`` is the target.
|
||||
|
||||
The GPU uuid is hashed to keep the name well under the AF_UNIX path
|
||||
limit (~108 bytes) even with the draft role suffix.
|
||||
"""
|
||||
gpu_id = safe_hash(gpu_uuid.encode()).hexdigest()
|
||||
name = SOCKET_NAME_TEMPLATE.format(
|
||||
gpu_uuid=gpu_id,
|
||||
role=format_socket_role_suffix(is_draft),
|
||||
)
|
||||
return os.path.join(get_socket_dir(socket_dir), name)
|
||||
|
||||
|
||||
def ensure_private_socket_dir(directory: str, strict_perms: bool = True) -> None:
|
||||
@@ -272,10 +289,17 @@ class WeightCacheKey:
|
||||
quant_config_hash: str
|
||||
revision: str | None
|
||||
vllm_version: str
|
||||
is_draft: bool = False
|
||||
"""Daemon group the weights come from; False is the target model."""
|
||||
|
||||
@classmethod
|
||||
def from_model_config(
|
||||
cls, model_config: ModelConfig, tp_size: int, tp_rank: int
|
||||
cls,
|
||||
model_config: ModelConfig,
|
||||
tp_size: int,
|
||||
tp_rank: int,
|
||||
*,
|
||||
is_draft: bool = False,
|
||||
) -> "WeightCacheKey":
|
||||
"""Build the fingerprint for a model configuration.
|
||||
|
||||
@@ -302,6 +326,7 @@ class WeightCacheKey:
|
||||
quant_config_hash=_hash_quant_config(quant_config),
|
||||
revision=model_config.revision,
|
||||
vllm_version=vllm.version.__version__,
|
||||
is_draft=is_draft,
|
||||
)
|
||||
|
||||
def mismatched_fields(self, other: "WeightCacheKey") -> list[str]:
|
||||
@@ -345,6 +370,17 @@ class TensorEntry:
|
||||
return rebuild_cuda_tensor(*args)
|
||||
|
||||
|
||||
class WeightCacheState(NamedTuple):
|
||||
"""Client-side decode of a daemon's get_state response payload."""
|
||||
|
||||
entries: dict[str, TensorEntry]
|
||||
"""Model tensors, exported as CUDA IPC handles or shipped by value."""
|
||||
aliases: dict[str, str]
|
||||
"""Duplicate (tied) weight names aliased to their canonical entry."""
|
||||
attrs: dict[str, bool]
|
||||
"""Python-side flags set by load_weights, e.g. EAGLE ownership flags."""
|
||||
|
||||
|
||||
def send_msg(sock: socket.socket, obj: Any) -> None:
|
||||
payload = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
||||
sock.sendall(_LEN_STRUCT.pack(len(payload)))
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Helpers shared by the weight cache daemon, the IPC loader and the engine.
|
||||
|
||||
These live outside ``protocol`` so callers that only need to know whether a
|
||||
draft is cached, or how a daemon group is named, do not have to import the
|
||||
wire format.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm.config import SpeculativeConfig
|
||||
from vllm.model_executor.models.interfaces import SupportsEagleBase
|
||||
|
||||
# Speculative methods whose draft model the daemon caches in its own group.
|
||||
# Other drafts keep loading from disk in the engine.
|
||||
WEIGHT_CACHE_DRAFT_METHODS = frozenset({"mtp", "eagle", "eagle3"})
|
||||
|
||||
# Python-side flags that weight loading sets on EAGLE-style drafts; the engine
|
||||
# never runs load_weights for cached models, so the daemon ships them.
|
||||
EXPORTED_MODEL_ATTRS = tuple(SupportsEagleBase.__annotations__)
|
||||
|
||||
|
||||
def export_model_attrs(model: Any) -> dict[str, bool]:
|
||||
return {
|
||||
name: bool(getattr(model, name))
|
||||
for name in EXPORTED_MODEL_ATTRS
|
||||
if hasattr(model, name)
|
||||
}
|
||||
|
||||
|
||||
def is_draft_model_cacheable(speculative_config: SpeculativeConfig | None) -> bool:
|
||||
"""Whether the daemon serves the speculative draft as a separate role."""
|
||||
return (
|
||||
speculative_config is not None
|
||||
and speculative_config.method in WEIGHT_CACHE_DRAFT_METHODS
|
||||
and speculative_config.draft_model_config is not None
|
||||
)
|
||||
|
||||
|
||||
def format_daemon_role(is_draft: bool) -> str:
|
||||
"""Name of a daemon group: the target model or the draft."""
|
||||
return "draft" if is_draft else "target"
|
||||
|
||||
|
||||
def format_socket_role_suffix(is_draft: bool) -> str:
|
||||
"""Socket-name suffix keeping the draft group distinct from the target."""
|
||||
return "_draft" if is_draft else ""
|
||||
@@ -197,6 +197,11 @@ class DiffusionGemmaForConditionalGeneration(
|
||||
text_config.attention_k_eq_v = True
|
||||
|
||||
# ---- Vision tower ----
|
||||
# Gemma4's image path, borrowed below, reads this flag.
|
||||
lora_config = vllm_config.lora_config
|
||||
self._enable_mm_lora = bool(
|
||||
lora_config is not None and lora_config.enable_tower_connector_lora
|
||||
)
|
||||
vision_config = getattr(config, "vision_config", None)
|
||||
self.embed_vision: Gemma4MultimodalEmbedder | None
|
||||
if vision_config is not None:
|
||||
|
||||
@@ -189,38 +189,6 @@ class HCXVisionV2DummyInputsBuilder(BaseDummyInputsBuilder[HCXVisionV2Processing
|
||||
num_videos = mm_counts.get("video", 0)
|
||||
return V2_IMAGE_TOKEN * num_images + V2_VIDEO_TOKEN * num_videos
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions | None = None,
|
||||
mm_processor_kwargs: Mapping[str, object] | None = None,
|
||||
) -> ProcessorInputs:
|
||||
"""Build dummy processor inputs for memory profiling."""
|
||||
num_images = mm_counts.get("image", 0)
|
||||
num_videos = mm_counts.get("video", 0)
|
||||
prompt_text = V2_IMAGE_TOKEN * num_images + V2_VIDEO_TOKEN * num_videos
|
||||
|
||||
dummy_mm_data = self.get_dummy_mm_data(
|
||||
seq_len,
|
||||
mm_counts,
|
||||
mm_options,
|
||||
mm_processor_kwargs=mm_processor_kwargs,
|
||||
)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data, validate=False)
|
||||
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
prompt = tokenizer.encode(
|
||||
prompt_text,
|
||||
**self.info.default_tok_params.get_encode_kwargs(),
|
||||
)
|
||||
|
||||
return ProcessorInputs(
|
||||
prompt=prompt,
|
||||
mm_data_items=dummy_mm_items,
|
||||
hf_processor_mm_kwargs=mm_processor_kwargs or {},
|
||||
)
|
||||
|
||||
def get_dummy_mm_data(
|
||||
self,
|
||||
seq_len: int,
|
||||
@@ -255,6 +223,28 @@ class HCXVisionV2MultiModalProcessor(
|
||||
):
|
||||
"""Multimodal processor for HyperCLOVAX V2 (32B Think model)."""
|
||||
|
||||
def get_dummy_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> ProcessorInputs:
|
||||
num_images = mm_counts.get("image", 0)
|
||||
num_videos = mm_counts.get("video", 0)
|
||||
prompt_text = V2_IMAGE_TOKEN * num_images + V2_VIDEO_TOKEN * num_videos
|
||||
|
||||
builder = self.dummy_inputs
|
||||
dummy_mm_data = builder.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data, validate=False)
|
||||
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
prompt = tokenizer.encode(
|
||||
prompt_text,
|
||||
**self.info.default_tok_params.get_encode_kwargs(),
|
||||
)
|
||||
|
||||
return ProcessorInputs(prompt=prompt, mm_data_items=dummy_mm_items)
|
||||
|
||||
def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
|
||||
@@ -267,7 +257,7 @@ class HCXVisionV2MultiModalProcessor(
|
||||
hf_config = self.info.get_hf_config()
|
||||
|
||||
# Use token IDs directly from config.
|
||||
# This matches what get_dummy_processor_inputs uses, ensuring consistency.
|
||||
# This matches what get_dummy_inputs uses, ensuring consistency.
|
||||
placeholder: dict[str, int] = {
|
||||
"image": hf_config.image_token_id, # 128060 for <|IMAGE_PAD|>
|
||||
"video": hf_config.video_token_id, # 128061 for <|VIDEO_PAD|>
|
||||
|
||||
@@ -176,29 +176,6 @@ class KimiAudioDummyInputsBuilder(BaseDummyInputsBuilder[KimiAudioProcessingInfo
|
||||
),
|
||||
}
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> ProcessorInputs:
|
||||
dummy_mm_data = self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
|
||||
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
dummy_tokens = (
|
||||
[198]
|
||||
if num_audios == 0
|
||||
else [
|
||||
KimiAudioProcessor.KIMIA_MEDIA_BEGIN,
|
||||
KimiAudioProcessor.KIMIA_TEXT_BLANK,
|
||||
KimiAudioProcessor.KIMIA_MEDIA_END,
|
||||
]
|
||||
* num_audios
|
||||
)
|
||||
|
||||
return ProcessorInputs(prompt=dummy_tokens, mm_data_items=dummy_mm_items)
|
||||
|
||||
|
||||
# Field config for Kimi-Audio multimodal data
|
||||
_KIMIAUDIO_FIELD_CONFIG = {
|
||||
@@ -228,6 +205,30 @@ class KimiAudioMultiModalDataParser(MultiModalDataParser):
|
||||
class KimiAudioMultiModalProcessor(BaseMultiModalProcessor[KimiAudioProcessingInfo]):
|
||||
"""vLLM multi-modal processor wrapper for Kimi-Audio."""
|
||||
|
||||
def get_dummy_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> ProcessorInputs:
|
||||
builder = self.dummy_inputs
|
||||
dummy_mm_data = builder.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
|
||||
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
dummy_tokens = (
|
||||
[198]
|
||||
if num_audios == 0
|
||||
else [
|
||||
KimiAudioProcessor.KIMIA_MEDIA_BEGIN,
|
||||
KimiAudioProcessor.KIMIA_TEXT_BLANK,
|
||||
KimiAudioProcessor.KIMIA_MEDIA_END,
|
||||
]
|
||||
* num_audios
|
||||
)
|
||||
|
||||
return ProcessorInputs(prompt=dummy_tokens, mm_data_items=dummy_mm_items)
|
||||
|
||||
def _get_hf_mm_inputs(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
|
||||
@@ -192,18 +192,13 @@ class Mistral3HFEncoderInfo(PixtralHFEncoderInfo):
|
||||
image_width = math.floor(image_width / ratio)
|
||||
image_height = math.floor(image_height / ratio)
|
||||
|
||||
patch_size = self.vision_config.patch_size
|
||||
assert isinstance(self.hf_config, Mistral3Config)
|
||||
spatial_merge_size = self.hf_config.spatial_merge_size
|
||||
merged_patch_size = (
|
||||
self.vision_config.patch_size * self.hf_config.spatial_merge_size
|
||||
)
|
||||
|
||||
# The HF processor rounds each dimension up to the vision patch size
|
||||
# before the projector drops incomplete spatial-merge groups. This is
|
||||
# not equivalent to rounding directly to the merged patch size.
|
||||
num_width_patches = (image_width - 1) // patch_size + 1
|
||||
num_height_patches = (image_height - 1) // patch_size + 1
|
||||
|
||||
ncols = num_width_patches // spatial_merge_size
|
||||
nrows = num_height_patches // spatial_merge_size
|
||||
ncols = (image_width - 1) // merged_patch_size + 1
|
||||
nrows = (image_height - 1) // merged_patch_size + 1
|
||||
return ncols, nrows
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from PIL import ImageOps
|
||||
from PIL.Image import Image
|
||||
from transformers import (
|
||||
BaseImageProcessor,
|
||||
@@ -54,6 +53,7 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
)
|
||||
from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.image import normalize_image
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItems,
|
||||
@@ -1299,7 +1299,7 @@ def exif_transpose(
|
||||
exif_transpose(img) if isinstance(img, Image) else img for img in images
|
||||
]
|
||||
elif images is not None and isinstance(images, Image):
|
||||
images = ImageOps.exif_transpose(images)
|
||||
images = normalize_image(images)
|
||||
return images
|
||||
|
||||
|
||||
|
||||
@@ -438,31 +438,38 @@ class MossTranscribeDiarizeDummyInputsBuilder(
|
||||
)
|
||||
}
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
|
||||
class MossTranscribeDiarizeMultiModalProcessor(
|
||||
BaseMultiModalProcessor[MossTranscribeDiarizeProcessingInfo]
|
||||
):
|
||||
def get_dummy_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
) -> ProcessorInputs:
|
||||
dummy_mm_data = self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
builder = self.dummy_inputs
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
prompt = cached_encode(
|
||||
tokenizer,
|
||||
AUDIO_PLACEHOLDER * num_audios,
|
||||
add_special_tokens=False,
|
||||
) or cached_encode(
|
||||
tokenizer,
|
||||
"\n",
|
||||
add_special_tokens=False,
|
||||
)
|
||||
|
||||
dummy_mm_data = builder.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
|
||||
|
||||
num_audios = mm_counts.get("audio", 0)
|
||||
if num_audios > 0:
|
||||
prompt = cached_encode(
|
||||
tokenizer,
|
||||
AUDIO_PLACEHOLDER * num_audios,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
else:
|
||||
prompt = cached_encode(
|
||||
tokenizer,
|
||||
"\n",
|
||||
add_special_tokens=False,
|
||||
)
|
||||
|
||||
return ProcessorInputs(prompt=prompt, mm_data_items=dummy_mm_items)
|
||||
|
||||
|
||||
class MossTranscribeDiarizeMultiModalProcessor(
|
||||
BaseMultiModalProcessor[MossTranscribeDiarizeProcessingInfo]
|
||||
):
|
||||
def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
|
||||
|
||||
@@ -221,18 +221,22 @@ class PixtralDummyInputsBuilder(BaseDummyInputsBuilder[PixtralProcessingInfo]):
|
||||
)
|
||||
}
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
|
||||
class PixtralMultiModalProcessor(BaseMultiModalProcessor[PixtralProcessingInfo]):
|
||||
def get_dummy_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
# For test_common.py only
|
||||
mm_data: MultiModalDataDict | None = None,
|
||||
) -> ProcessorInputs:
|
||||
builder = self.dummy_inputs
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
|
||||
dummy_text = self.get_dummy_text(mm_counts)
|
||||
dummy_text = builder.get_dummy_text(mm_counts)
|
||||
dummy_mm_data = (
|
||||
self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
builder.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
if mm_data is None
|
||||
else mm_data
|
||||
)
|
||||
@@ -256,8 +260,6 @@ class PixtralDummyInputsBuilder(BaseDummyInputsBuilder[PixtralProcessingInfo]):
|
||||
|
||||
return ProcessorInputs(prompt=dummy_tokens, mm_data_items=dummy_mm_items)
|
||||
|
||||
|
||||
class PixtralMultiModalProcessor(BaseMultiModalProcessor[PixtralProcessingInfo]):
|
||||
# The tokens are already inserted by the chat template,
|
||||
# so we just double check that they exist
|
||||
def _maybe_apply_prompt_updates(
|
||||
|
||||
@@ -41,12 +41,14 @@ from transformers.models.qwen2_5_vl.configuration_qwen2_5_vl import (
|
||||
Qwen2_5_VLConfig,
|
||||
Qwen2_5_VLVisionConfig,
|
||||
)
|
||||
from transformers.video_utils import VideoMetadata
|
||||
|
||||
from vllm.compilation.decorators import (
|
||||
should_torch_compile_mm_encoder,
|
||||
support_torch_compile,
|
||||
)
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import VideoDummyOptions
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.distributed import utils as dist_utils
|
||||
from vllm.logger import init_logger
|
||||
@@ -72,9 +74,11 @@ from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems
|
||||
from vllm.multimodal.processing import PromptReplacement, PromptUpdate
|
||||
from vllm.multimodal.processing.processor import HFMultiModalInputs
|
||||
from vllm.multimodal.video_prune.evs import (
|
||||
compute_mrope_for_media,
|
||||
compute_retained_tokens_count,
|
||||
@@ -102,8 +106,9 @@ from .interfaces import (
|
||||
SupportsPP,
|
||||
SupportsQuant,
|
||||
)
|
||||
from .qwen2_vl import Qwen2VLDummyInputsBuilder as Qwen2_5_VLDummyInputsBuilder
|
||||
from .qwen2_vl import (
|
||||
Qwen2VLDummyInputsBuilder,
|
||||
Qwen2VLMultiModalDataParser,
|
||||
Qwen2VLMultiModalProcessor,
|
||||
Qwen2VLProcessingInfo,
|
||||
)
|
||||
@@ -1137,6 +1142,40 @@ class Qwen2_5_VisionTransformer(nn.Module):
|
||||
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
|
||||
|
||||
|
||||
class Qwen2_5_VLDummyInputsBuilder(Qwen2VLDummyInputsBuilder):
|
||||
def _get_dummy_videos(
|
||||
self,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
num_frames: int,
|
||||
num_videos: int,
|
||||
overrides: VideoDummyOptions | None = None,
|
||||
) -> list[VideoItem]:
|
||||
videos = super()._get_dummy_videos(
|
||||
width=width,
|
||||
height=height,
|
||||
num_frames=num_frames,
|
||||
num_videos=num_videos,
|
||||
overrides=overrides,
|
||||
)
|
||||
videos = [v.copy() for v in videos]
|
||||
|
||||
video_items = []
|
||||
for video in videos:
|
||||
video_num_frames = video.shape[0]
|
||||
video_metadata = {
|
||||
"fps": 2.0,
|
||||
"duration": video_num_frames / 2.0,
|
||||
"total_num_frames": video_num_frames,
|
||||
"frames_indices": list(range(video_num_frames)),
|
||||
"video_backend": "opencv",
|
||||
"do_sample_frames": False,
|
||||
}
|
||||
video_items.append((video, video_metadata))
|
||||
return video_items
|
||||
|
||||
|
||||
class Qwen2_5_VLProcessingInfo(Qwen2VLProcessingInfo):
|
||||
def get_hf_config(self):
|
||||
return self.ctx.get_hf_config(Qwen2_5_VLConfig)
|
||||
@@ -1148,6 +1187,14 @@ class Qwen2_5_VLProcessingInfo(Qwen2VLProcessingInfo):
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def get_data_parser(self):
|
||||
return Qwen2VLMultiModalDataParser(
|
||||
self.get_hf_config().vision_config.spatial_merge_size,
|
||||
video_needs_metadata=True,
|
||||
expected_hidden_size=self._get_expected_hidden_size(),
|
||||
allow_missing_mm_embeddings=self.allow_missing_mm_embeddings,
|
||||
)
|
||||
|
||||
|
||||
class Qwen2_5_VLMultiModalProcessor(Qwen2VLMultiModalProcessor):
|
||||
def _get_mm_fields_config(
|
||||
@@ -1160,6 +1207,25 @@ class Qwen2_5_VLMultiModalProcessor(Qwen2VLMultiModalProcessor):
|
||||
second_per_grid_ts=MultiModalFieldConfig.batched("video", keep_on_cpu=True),
|
||||
)
|
||||
|
||||
def _get_hf_mm_inputs(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> HFMultiModalInputs:
|
||||
hf_inputs = super()._get_hf_mm_inputs(mm_items, hf_kwargs)
|
||||
hf_data = hf_inputs.hf_data
|
||||
|
||||
if videos := hf_data.get("videos"):
|
||||
# HF expects video metadata as a separate argument.
|
||||
hf_data["videos"] = [video for video, _ in videos]
|
||||
hf_data["video_metadata"] = [
|
||||
VideoMetadata(
|
||||
**{k: metadata[k] for k in metadata if k != "do_sample_frames"}
|
||||
)
|
||||
for _, metadata in videos
|
||||
]
|
||||
return hf_inputs
|
||||
|
||||
def _get_prompt_updates(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
|
||||
@@ -149,19 +149,23 @@ class VoxtralDummyInputsBuilder(BaseDummyInputsBuilder[VoxtralProcessingInfo]):
|
||||
)
|
||||
}
|
||||
|
||||
def get_dummy_processor_inputs(
|
||||
|
||||
class VoxtralMultiModalProcessor(BaseMultiModalProcessor[VoxtralProcessingInfo]):
|
||||
def get_dummy_inputs(
|
||||
self,
|
||||
seq_len: int,
|
||||
mm_counts: Mapping[str, int],
|
||||
mm_options: MultiModalDummyOptions,
|
||||
# For test_common.py only
|
||||
mm_data: MultiModalDataDict | None = None,
|
||||
) -> ProcessorInputs:
|
||||
builder = self.dummy_inputs
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
feature_extractor = self.info.get_feature_extractor()
|
||||
|
||||
dummy_text = self.get_dummy_text(mm_counts)
|
||||
dummy_text = builder.get_dummy_text(mm_counts)
|
||||
dummy_mm_data = (
|
||||
self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
builder.get_dummy_mm_data(seq_len, mm_counts, mm_options)
|
||||
if mm_data is None
|
||||
else mm_data
|
||||
)
|
||||
@@ -197,8 +201,6 @@ class VoxtralDummyInputsBuilder(BaseDummyInputsBuilder[VoxtralProcessingInfo]):
|
||||
|
||||
return ProcessorInputs(prompt=dummy_tokens, mm_data_items=dummy_mm_items)
|
||||
|
||||
|
||||
class VoxtralMultiModalProcessor(BaseMultiModalProcessor[VoxtralProcessingInfo]):
|
||||
# The tokens are already inserted by the chat template,
|
||||
# so we just double check that they exist
|
||||
def _maybe_apply_prompt_updates(
|
||||
|
||||
@@ -767,6 +767,7 @@ class WhisperMultiModalProcessor(EncDecMultiModalProcessor[WhisperProcessingInfo
|
||||
hf_kwargs=dict(
|
||||
hf_inputs.hf_kwargs,
|
||||
sampling_rate=feature_extractor.sampling_rate,
|
||||
truncation=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -136,16 +136,17 @@ def _warmup_bf16x3_router_gemm(
|
||||
logger.info_once("Warmed up BF16x3 router GEMM configs: %s.", configs)
|
||||
|
||||
|
||||
def _warmup_kimi_k3_gemm_rs_ar() -> None:
|
||||
# Kimi-K3 model construction imports this module only when GEMM-RS/AR is
|
||||
# enabled and initializes its singleton before kernel_warmup runs. Avoid
|
||||
# importing it here so other models do not compile the RS/AR variants.
|
||||
module = sys.modules.get("vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar")
|
||||
def _warmup_gemm_rs_ar() -> None:
|
||||
# Model construction (Kimi-K3, DeepSeek-V4.1) imports this module only
|
||||
# when GEMM-RS/AR is enabled and initializes its singleton before
|
||||
# kernel_warmup runs. Avoid importing it here so other models do not
|
||||
# compile the RS/AR variants.
|
||||
module = sys.modules.get("vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar")
|
||||
if module is None:
|
||||
return
|
||||
compiled = module.warmup_gemm_rs_ar()
|
||||
if compiled:
|
||||
logger.info_once("Warmed up %d Kimi-K3 GEMM-RS/AR variants.", compiled)
|
||||
logger.info_once("Warmed up %d GEMM-RS/AR variants.", compiled)
|
||||
|
||||
|
||||
def _autotune_kimi_k3_kda_qkvg(model: torch.nn.Module) -> None:
|
||||
@@ -208,7 +209,7 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False):
|
||||
if current_platform.has_device_capability(90):
|
||||
_warmup_ll_bf16_router_gemm(worker.get_model())
|
||||
|
||||
_warmup_kimi_k3_gemm_rs_ar()
|
||||
_warmup_gemm_rs_ar()
|
||||
|
||||
if worker.vllm_config.kernel_config.enable_cutedsl_warmup:
|
||||
# TODO(roberto): Remove after registered CuTeDSL warmups are migrated
|
||||
|
||||
@@ -44,6 +44,7 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.qwen3_dspark import (
|
||||
DSparkConfidenceHead,
|
||||
DSparkMarkovHead,
|
||||
)
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
@@ -102,7 +103,7 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
]
|
||||
)
|
||||
|
||||
# Heads: final norm + hc_head, and the Markov head
|
||||
# Heads: final norm + hc_head, and the Markov + confidence heads
|
||||
# Loaded from the "final" MTP layer weights (mtp.*) in the target checkpoint
|
||||
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
hc_dim = self.hc_mult * config.hidden_size
|
||||
@@ -125,6 +126,12 @@ class DSparkDeepseekV4Model(nn.Module):
|
||||
config.dspark_markov_rank,
|
||||
prefix=maybe_prefix(prefix, "markov_head"),
|
||||
)
|
||||
self.confidence_head: DSparkConfidenceHead | None = None
|
||||
if getattr(config, "enable_confidence_head", True):
|
||||
self.confidence_head = DSparkConfidenceHead(
|
||||
config.hidden_size + config.dspark_markov_rank,
|
||||
prefix=maybe_prefix(prefix, "confidence_head"),
|
||||
)
|
||||
|
||||
# MHC head CustomOp dispatcher (aiter / tilelang / triton / torch),
|
||||
# replacing the direct nvidia tilelang kernel call.
|
||||
@@ -358,6 +365,17 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
def markov_bias(self, markov_embed: torch.Tensor) -> torch.Tensor:
|
||||
return self.model.markov_head.bias(markov_embed, self.logits_processor)
|
||||
|
||||
def compute_confidence(
|
||||
self, head_hidden: torch.Tensor, markov_embed: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Per-position acceptance probability for each drafted token."""
|
||||
if self.model.confidence_head is None:
|
||||
raise RuntimeError(
|
||||
"compute_confidence() requires a confidence head, but the "
|
||||
"checkpoint did not provide confidence_head weights."
|
||||
)
|
||||
return torch.sigmoid(self.model.confidence_head(head_hidden, markov_embed))
|
||||
|
||||
# --- Weight loading ----------------------------------------------------
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
@@ -391,6 +409,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
loaded_confidence_head = False
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
tp_rank = get_tensor_model_parallel_rank()
|
||||
@@ -403,6 +422,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
if mapped is None:
|
||||
continue
|
||||
name = mapped
|
||||
if "confidence_head." in name:
|
||||
loaded_confidence_head = True
|
||||
|
||||
# ``.scale`` -> per-method scale suffix.
|
||||
if name.endswith(".scale"):
|
||||
@@ -439,8 +460,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
continue
|
||||
|
||||
# Stacked rules only apply to decoder-layer weights. Head-stack params
|
||||
# (main_proj/norm/hc_head/markov_head) load directly — otherwise e.g.
|
||||
# "markov_w1" would collide with the "w1" shard rule.
|
||||
# (main_proj/norm/hc_head/markov_head/confidence_head) load directly —
|
||||
# otherwise e.g. "markov_w1" would collide with the "w1" shard rule.
|
||||
is_layer_param = name.startswith("model.layers.")
|
||||
for param_name, weight_name, stacked_shard_id in stacked_params_mapping:
|
||||
if not is_layer_param or weight_name not in name:
|
||||
@@ -469,6 +490,8 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded_params.add(name)
|
||||
|
||||
if self.model.confidence_head is not None and not loaded_confidence_head:
|
||||
self.model.confidence_head = None
|
||||
logger.info_once("DSpark draft model loaded: %d params", len(loaded_params))
|
||||
return loaded_params
|
||||
|
||||
@@ -482,8 +505,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
return None
|
||||
stage = int(m.group(1))
|
||||
rest = m.group(2)
|
||||
# The confidence head is not wired into inference yet; drop its weights.
|
||||
if rest.startswith("confidence_head."):
|
||||
if rest.startswith("confidence_head.") and self.model.confidence_head is None:
|
||||
return None
|
||||
# Head-stack params live at model level (mtp.last), context combiner at
|
||||
# model level (mtp.0); everything else is a per-layer decoder block.
|
||||
@@ -493,6 +515,7 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
|
||||
"hc_head_base",
|
||||
"hc_head_scale",
|
||||
"markov_head.",
|
||||
"confidence_head.",
|
||||
)
|
||||
if rest.startswith(("main_proj.", "main_norm.")) or rest.startswith(
|
||||
head_prefixes
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user