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:
+162
-24
@@ -1870,28 +1870,39 @@ def _mhc_delayed_pre_tail(
|
||||
_OPS_REGISTERED = False
|
||||
|
||||
|
||||
_AITER_SITUV2_ACT_ENV = {
|
||||
"a8w4": "AITER_SITUV2_A8W4",
|
||||
"a4w4": "AITER_SITUV2_A4W4",
|
||||
}
|
||||
|
||||
|
||||
def _resolve_situv2_activation() -> str:
|
||||
"""VLLM_ROCM_USE_AITER_MOE_SITUV2 -> a4w4 | a8w4 | a16w4.
|
||||
|
||||
auto (default) and the legacy 1 mean a4w4; legacy 0 means a16w4.
|
||||
"""
|
||||
value = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2.lower()
|
||||
if value in ("auto", "1"):
|
||||
return "a4w4"
|
||||
if value == "0":
|
||||
return "a16w4"
|
||||
return value
|
||||
|
||||
|
||||
def _sync_aiter_situv2_moe_env() -> None:
|
||||
"""Mirror the SiTUv2 MoE toggle into AITER's a4w4 dispatch env.
|
||||
"""Set the AITER_SITUV2_* env matching VLLM_ROCM_USE_AITER_MOE_SITUV2.
|
||||
|
||||
AITER selects afp8 vs afp4 activation kernels via AITER_SITUV2_A8W4 /
|
||||
AITER_SITUV2_A4W4 (see ROCm/aiter fused_moe.py, A8W4 checked first).
|
||||
When VLLM_ROCM_USE_AITER_MOE_SITUV2 is enabled we route to a4w4
|
||||
(afp4_wfp4_fp4 kernels) and clear any legacy AITER_SITUV2_A8W4 override.
|
||||
|
||||
Requires AITER with ROCm/aiter#4463 (first tagged in v0.1.20): a4w4
|
||||
dispatch plus kimik3_a4w4_{un,}tuned_fmoe.csv. Older AITER still runs
|
||||
afp4 FlyDSL but falls back to heuristic configs, which is not the
|
||||
tuned a4w4 path this recipe is meant to use.
|
||||
AITER reads AITER_SITUV2_A8W4 / AITER_SITUV2_A4W4 and defaults to a16w4,
|
||||
so exactly one is set for a8w4/a4w4 and both are cleared for a16w4.
|
||||
"""
|
||||
import os
|
||||
|
||||
import vllm.envs as envs
|
||||
|
||||
if envs.VLLM_ROCM_USE_AITER_MOE_SITUV2:
|
||||
os.environ["AITER_SITUV2_A4W4"] = "1"
|
||||
os.environ.pop("AITER_SITUV2_A8W4", None)
|
||||
else:
|
||||
os.environ.pop("AITER_SITUV2_A4W4", None)
|
||||
selected = _AITER_SITUV2_ACT_ENV.get(_resolve_situv2_activation())
|
||||
for name in _AITER_SITUV2_ACT_ENV.values():
|
||||
if name == selected:
|
||||
os.environ[name] = "1"
|
||||
else:
|
||||
os.environ.pop(name, None)
|
||||
|
||||
|
||||
class rocm_aiter_ops:
|
||||
@@ -1917,7 +1928,8 @@ class rocm_aiter_ops:
|
||||
VLLM_ROCM_USE_AITER_FP4_ASM_GEMM: Controls FP4 assembly GEMM.
|
||||
VLLM_ROCM_USE_AITER_TRITON_ROPE: Controls Triton rotary embeddings.
|
||||
VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS: Controls shared expert fusion.
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: Controls SiTUv2 FlyDSL MoE (a4w4).
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: SiTUv2 FlyDSL MoE activation
|
||||
dtype (a16w4 | a8w4 | a4w4).
|
||||
VLLM_ROCM_USE_AITER_TRITON_GEMM: Controls Triton unquantized GEMM.
|
||||
|
||||
Note:
|
||||
@@ -1987,7 +1999,7 @@ class rocm_aiter_ops:
|
||||
# TODO: Consolidate under VLLM_ROCM_USE_AITER_ROPE
|
||||
_TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
|
||||
_MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
|
||||
_MOE_SITUV2 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2
|
||||
_MOE_SITUV2 = _resolve_situv2_activation()
|
||||
# TODO: Consolidate under _LINEAR_ENABLED
|
||||
_TRITON_UNQUANT_GEMM = envs.VLLM_ROCM_USE_AITER_TRITON_GEMM
|
||||
# Lazily probed: whether aiter.topk_softmax supports the
|
||||
@@ -2016,9 +2028,10 @@ class rocm_aiter_ops:
|
||||
cls._FP4_GEMM_DYNAMIC_QUANT_ASM = envs.VLLM_ROCM_USE_AITER_FP4_ASM_GEMM
|
||||
cls._TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
|
||||
cls._MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
|
||||
cls._MOE_SITUV2 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2
|
||||
cls._MOE_SITUV2 = _resolve_situv2_activation()
|
||||
_sync_aiter_situv2_moe_env()
|
||||
cls._TRITON_UNQUANT_GEMM = envs.VLLM_ROCM_USE_AITER_TRITON_GEMM
|
||||
cls._MOE_DISPATCH_POLICY = envs.VLLM_ROCM_AITER_MOE_DISPATCH_POLICY
|
||||
|
||||
@staticmethod
|
||||
def get_aiter_activation_type(activation_str: str) -> "ActivationType | None":
|
||||
@@ -2131,9 +2144,25 @@ class rocm_aiter_ops:
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def is_fused_moe_situv2_enabled(cls) -> bool:
|
||||
# _MOE_SITUV2 is a variant of aiter fused moe, so aiter
|
||||
# fused moe must be enabled as well.
|
||||
return cls.is_fused_moe_enabled() and cls._MOE_SITUV2
|
||||
"""True when a low-precision (a8w4/a4w4) SiTUv2 activation is selected."""
|
||||
return cls.is_fused_moe_enabled() and cls._MOE_SITUV2 != "a16w4"
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def get_fused_moe_situv2_activation(cls) -> str:
|
||||
"""SiTUv2 activation dtype name: a16w4, a8w4 or a4w4."""
|
||||
return cls._MOE_SITUV2
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def is_fused_moe_situv2_gate_up_interleaved(cls) -> bool:
|
||||
"""Whether the SiTUv2 kernels expect gate/up-interleaved w13.
|
||||
|
||||
The a8w4 FlyDSL stage-1 kernels (_gui_) are interleaved; a16w4 and
|
||||
a4w4 are separated. Weight shuffle (oracle/mxfp4.py) and gate_mode
|
||||
(experts/rocm_aiter_moe.py) must both use this.
|
||||
"""
|
||||
return cls._MOE_SITUV2 == "a8w4"
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
@@ -3362,6 +3391,115 @@ class rocm_aiter_ops:
|
||||
rotary_dim=kernel_rotary_dim,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def fused_qk_norm_mrope_and_cache(
|
||||
qkv: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
num_heads_q: int,
|
||||
num_heads_k: int,
|
||||
head_dim: int,
|
||||
is_neox: bool,
|
||||
mrope_section: list[int],
|
||||
is_interleaved: bool,
|
||||
rms_norm_eps: float,
|
||||
q_out: torch.Tensor,
|
||||
k_cache: torch.Tensor,
|
||||
v_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
k_scale: torch.Tensor,
|
||||
v_scale: torch.Tensor,
|
||||
block_size: int,
|
||||
x: int,
|
||||
rotary_dim: int = 0,
|
||||
) -> None:
|
||||
from aiter.ops.fused_qk_norm_mrope_cache_quant import (
|
||||
fused_qk_norm_mrope_3d_cache_pts_quant_shuffle,
|
||||
)
|
||||
|
||||
fused_qk_norm_mrope_3d_cache_pts_quant_shuffle(
|
||||
qkv,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
positions,
|
||||
qkv.size(0),
|
||||
num_heads_q,
|
||||
num_heads_k,
|
||||
num_heads_k,
|
||||
head_dim,
|
||||
is_neox,
|
||||
mrope_section,
|
||||
is_interleaved,
|
||||
rms_norm_eps,
|
||||
q_out,
|
||||
k_cache,
|
||||
v_cache,
|
||||
slot_mapping,
|
||||
k_scale,
|
||||
v_scale,
|
||||
None,
|
||||
None,
|
||||
False,
|
||||
False,
|
||||
block_size,
|
||||
x,
|
||||
rotary_dim,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def do_qk_norm_mrope_kvcache_update(
|
||||
qkv: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
num_heads_q: int,
|
||||
num_heads_k: int,
|
||||
head_dim: int,
|
||||
is_neox: bool,
|
||||
mrope_section: list[int],
|
||||
is_interleaved: bool,
|
||||
rms_norm_eps: float,
|
||||
q_out: torch.Tensor,
|
||||
key_cache: torch.Tensor,
|
||||
value_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
k_scale: torch.Tensor,
|
||||
v_scale: torch.Tensor,
|
||||
kv_cache_dtype: str,
|
||||
rotary_dim: int = 0,
|
||||
) -> None:
|
||||
if kv_cache_dtype.startswith("fp8"):
|
||||
key_cache = key_cache.view(current_platform.fp8_dtype())
|
||||
value_cache = value_cache.view(current_platform.fp8_dtype())
|
||||
|
||||
rocm_aiter_ops.fused_qk_norm_mrope_and_cache(
|
||||
qkv=qkv,
|
||||
q_weight=q_weight,
|
||||
k_weight=k_weight,
|
||||
cos_sin_cache=cos_sin_cache,
|
||||
positions=positions,
|
||||
num_heads_q=num_heads_q,
|
||||
num_heads_k=num_heads_k,
|
||||
head_dim=head_dim,
|
||||
is_neox=is_neox,
|
||||
mrope_section=mrope_section,
|
||||
is_interleaved=is_interleaved,
|
||||
rms_norm_eps=rms_norm_eps,
|
||||
q_out=q_out,
|
||||
k_cache=key_cache,
|
||||
v_cache=value_cache,
|
||||
slot_mapping=slot_mapping,
|
||||
k_scale=k_scale,
|
||||
v_scale=v_scale,
|
||||
block_size=key_cache.shape[1],
|
||||
x=16 // key_cache.element_size(),
|
||||
rotary_dim=rotary_dim,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def triton_rope_and_cache(
|
||||
query: torch.Tensor,
|
||||
@@ -3406,7 +3544,7 @@ class rocm_aiter_ops:
|
||||
X: torch.Tensor,
|
||||
W: torch.Tensor,
|
||||
w_scale: torch.Tensor,
|
||||
Y: torch.Tensor,
|
||||
Y: torch.Tensor | None = None,
|
||||
transpose_bm: bool | None = False,
|
||||
prequant: bool | None = False,
|
||||
y_scale: torch.Tensor | None = None,
|
||||
|
||||
+20
-104
@@ -732,26 +732,6 @@ def moe_gptq_gemm_rdna3(
|
||||
)
|
||||
|
||||
|
||||
if hasattr(torch.ops._C, "allspark_w8a16_gemm"):
|
||||
|
||||
@register_fake("_C::allspark_w8a16_gemm")
|
||||
def _allspark_w8a16_gemm_fake(
|
||||
a: torch.Tensor,
|
||||
b_qweight: torch.Tensor,
|
||||
b_scales: torch.Tensor,
|
||||
b_qzeros: torch.Tensor | None,
|
||||
n: torch.SymInt,
|
||||
group_size: torch.SymInt,
|
||||
sm_count: torch.SymInt,
|
||||
sm_version: torch.SymInt,
|
||||
CUBLAS_M_THRESHOLD: torch.SymInt,
|
||||
has_zp: bool,
|
||||
n32k16_reorder: bool,
|
||||
) -> torch.Tensor:
|
||||
m = a.size(0)
|
||||
return torch.empty((m, n), device=a.device, dtype=a.dtype)
|
||||
|
||||
|
||||
# cutlass
|
||||
def cutlass_scaled_mm_supports_fp4(cuda_device_capability: int) -> bool:
|
||||
return torch.ops._C.cutlass_scaled_mm_supports_fp4(cuda_device_capability)
|
||||
@@ -1911,90 +1891,6 @@ def scaled_fp8_quant(
|
||||
return output, scale
|
||||
|
||||
|
||||
# gptq allspark
|
||||
def allspark_repack_weight(
|
||||
qweight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
zero_point: torch.Tensor | None = None,
|
||||
has_zp: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Rearrange qweight, scale, and zero_point(if asymmetric) to n32k16 format
|
||||
for Ampere W8A16 Fused Gemm kernel
|
||||
|
||||
Args:
|
||||
qweight: uint8 weight tensor, original k x n format.
|
||||
scale: fp16/bf16 weight scale tensor, 1 x n format.
|
||||
zero_point: fp16/bf16 weight zero_point tensor, 1 x n format.
|
||||
Must be provided for asymmetric quantization.
|
||||
has_zp: if use symmetric quantization, has_zp = False.
|
||||
if use asymmetric quantization, has_zp = True.
|
||||
|
||||
Returns:
|
||||
tuple[torch.Tensor, torch.Tensor, torch.Tensor | None] :
|
||||
rearranged weight, scale, and optionally zero_point.
|
||||
|
||||
"""
|
||||
K = qweight.shape[0]
|
||||
N = qweight.shape[1]
|
||||
N_32align = (N + 32 - 1) // 32 * 32
|
||||
|
||||
qweight_reorder = torch.empty(
|
||||
(N_32align, K), device=qweight.device, dtype=qweight.dtype
|
||||
)
|
||||
scale_reorder = torch.empty((1, N_32align), device=scale.device, dtype=scale.dtype)
|
||||
zero_point_reorder = None
|
||||
if has_zp:
|
||||
assert zero_point is not None, (
|
||||
"zero_point must be provided for asymmetric quantization."
|
||||
)
|
||||
zero_point_reorder = torch.empty(
|
||||
(1, N_32align), device=zero_point.device, dtype=zero_point.dtype
|
||||
)
|
||||
|
||||
torch.ops._C.rearrange_kn_weight_as_n32k16_order(
|
||||
qweight,
|
||||
scale,
|
||||
zero_point,
|
||||
has_zp,
|
||||
qweight_reorder,
|
||||
scale_reorder,
|
||||
zero_point_reorder,
|
||||
K,
|
||||
N,
|
||||
N_32align,
|
||||
)
|
||||
|
||||
return qweight_reorder, scale_reorder, zero_point_reorder
|
||||
|
||||
|
||||
def allspark_w8a16_gemm(
|
||||
a: torch.Tensor,
|
||||
b_qweight: torch.Tensor,
|
||||
b_scales: torch.Tensor,
|
||||
b_qzeros: torch.Tensor | None,
|
||||
n: int,
|
||||
group_size: int,
|
||||
sm_count: int,
|
||||
sm_version: int,
|
||||
CUBLAS_M_THRESHOLD: int,
|
||||
has_zp: bool,
|
||||
n32k16_reorder: bool,
|
||||
) -> torch.Tensor:
|
||||
return torch.ops._C.allspark_w8a16_gemm(
|
||||
a,
|
||||
b_qweight,
|
||||
b_scales,
|
||||
b_qzeros,
|
||||
n,
|
||||
group_size,
|
||||
sm_count,
|
||||
sm_version,
|
||||
CUBLAS_M_THRESHOLD,
|
||||
has_zp,
|
||||
n32k16_reorder,
|
||||
)
|
||||
|
||||
|
||||
# int8
|
||||
def scaled_int8_quant(
|
||||
input: torch.Tensor,
|
||||
@@ -3263,6 +3159,26 @@ def mnnvl_lamport_reduce_scatter(
|
||||
)
|
||||
|
||||
|
||||
def mnnvl_multimem_reduce_scatter(
|
||||
fa: int,
|
||||
inp: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
local_buffer: int,
|
||||
multicast_buffer: int,
|
||||
stage_sz_bytes: int,
|
||||
block_limit: int,
|
||||
) -> None:
|
||||
torch.ops._C_custom_ar.mnnvl_multimem_reduce_scatter(
|
||||
fa,
|
||||
inp,
|
||||
out,
|
||||
local_buffer,
|
||||
multicast_buffer,
|
||||
stage_sz_bytes,
|
||||
block_limit,
|
||||
)
|
||||
|
||||
|
||||
def dispose(fa: int) -> None:
|
||||
torch.ops._C_custom_ar.dispose(fa)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
from vllm_xpu_kernels.flash_attn_interface import flash_attn_varlen_func
|
||||
from vllm_xpu_kernels.rotary import apply_rotary_emb
|
||||
|
||||
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
|
||||
from vllm.logger import init_logger
|
||||
@@ -249,6 +250,24 @@ def _xpu_ops_deepseek_scaling_rope_fake(
|
||||
return query, key
|
||||
|
||||
|
||||
def _xpu_apply_rotary_emb_impl(
|
||||
x: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
is_neox_style: bool,
|
||||
) -> torch.Tensor:
|
||||
return apply_rotary_emb(x, cos, sin, is_neox_style)
|
||||
|
||||
|
||||
def _xpu_apply_rotary_emb_fake(
|
||||
x: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
is_neox_style: bool,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty_like(x)
|
||||
|
||||
|
||||
def _xpu_fp8_bmm_impl(
|
||||
a: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
@@ -1257,6 +1276,12 @@ class xpu_ops:
|
||||
dispatch_key=current_platform.dispatch_key,
|
||||
)
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="xpu_apply_rotary_emb",
|
||||
op_func=_xpu_apply_rotary_emb_impl,
|
||||
fake_impl=_xpu_apply_rotary_emb_fake,
|
||||
)
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="xpu_mxfp8_quantize",
|
||||
op_func=_xpu_mxfp8_quantize_impl,
|
||||
|
||||
@@ -169,6 +169,7 @@ def main(args: argparse.Namespace):
|
||||
# Output JSON results if specified
|
||||
if args.output_json:
|
||||
results = {
|
||||
"model_id": args.model,
|
||||
"avg_latency": np.mean(latencies),
|
||||
"latencies": latencies.tolist(),
|
||||
"percentiles": dict(zip(percentages, percentiles.tolist())),
|
||||
|
||||
@@ -1695,7 +1695,6 @@ def add_cli_args(parser: FlexibleArgumentParser):
|
||||
- "auto" will use the tokenizer from `mistral_common` for Mistral models
|
||||
if available, otherwise it will use the "hf" tokenizer.\n
|
||||
- "hf" will use the fast tokenizer if available.\n
|
||||
- "slow" will always use the slow tokenizer.\n
|
||||
- "mistral" will always use the tokenizer from `mistral_common`.\n
|
||||
- "deepseek_v32" will always use the tokenizer from `deepseek_v32`.\n
|
||||
- Other custom values can be supported via plugins.""",
|
||||
|
||||
@@ -1141,6 +1141,7 @@ def main(args: argparse.Namespace):
|
||||
# Output JSON results if specified
|
||||
if args.output_json:
|
||||
results = {
|
||||
"model_id": args.model,
|
||||
"elapsed_time": elapsed_time,
|
||||
"num_requests": len(requests),
|
||||
"total_num_tokens": total_num_tokens,
|
||||
|
||||
@@ -25,6 +25,7 @@ from __future__ import annotations
|
||||
import dataclasses
|
||||
import functools
|
||||
import gc
|
||||
import logging
|
||||
import threading
|
||||
import weakref
|
||||
from collections.abc import Callable
|
||||
@@ -285,7 +286,7 @@ class BreakableCUDAGraphWrapper:
|
||||
self.runtime_mode = runtime_mode
|
||||
self.compilation_config = vllm_config.compilation_config
|
||||
self.graph_pool = current_platform.get_global_graph_pool()
|
||||
self.is_debugging_mode = envs.VLLM_LOGGING_LEVEL == "DEBUG"
|
||||
self.is_debugging_mode = logger.isEnabledFor(logging.DEBUG)
|
||||
|
||||
self.entries: dict[BatchDescriptor, _BreakableEntry] = {}
|
||||
BreakableCUDAGraphWrapper._all_instances.add(self)
|
||||
|
||||
@@ -23,6 +23,8 @@ from vllm.utils.torch_utils import is_torch_equal_or_newer
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_last_inductor_triton_cache_dir: str | None = None
|
||||
|
||||
|
||||
class CompilerInterface:
|
||||
"""The interface for a compiler that can be used by vLLM."""
|
||||
@@ -453,19 +455,22 @@ class InductorAdaptor(CompilerInterface):
|
||||
def initialize_cache(
|
||||
self, cache_dir: str, disable_cache: bool = False, prefix: str = ""
|
||||
) -> None:
|
||||
global _last_inductor_triton_cache_dir
|
||||
self.cache_dir = cache_dir
|
||||
self.prefix = prefix
|
||||
self.base_cache_dir = cache_dir[: -len(prefix)] if prefix else cache_dir
|
||||
if disable_cache:
|
||||
return
|
||||
# redirect the cache directory to a subdirectory
|
||||
# set flags so that Inductor and Triton store their cache
|
||||
# in the cache_dir, then users only need to copy the cache_dir
|
||||
# to another machine to reuse the cache.
|
||||
# Keep artifacts together unless the caller supplies a Triton cache.
|
||||
inductor_cache = os.path.join(self.base_cache_dir, "inductor_cache")
|
||||
os.makedirs(inductor_cache, exist_ok=True)
|
||||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = inductor_cache
|
||||
triton_cache = os.path.join(self.base_cache_dir, "triton_cache")
|
||||
triton_cache = os.environ.get("TRITON_CACHE_DIR")
|
||||
# A directory assigned by an earlier adaptor is still a model-local
|
||||
# default, rather than a caller override for subsequent models.
|
||||
if triton_cache is None or triton_cache == _last_inductor_triton_cache_dir:
|
||||
triton_cache = os.path.join(self.base_cache_dir, "triton_cache")
|
||||
_last_inductor_triton_cache_dir = triton_cache
|
||||
os.makedirs(triton_cache, exist_ok=True)
|
||||
os.environ["TRITON_CACHE_DIR"] = triton_cache
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import dataclasses
|
||||
import logging
|
||||
import weakref
|
||||
from collections import Counter
|
||||
from collections.abc import Callable
|
||||
@@ -11,7 +12,6 @@ from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.compilation.counter import compilation_counter
|
||||
from vllm.compilation.monitor import validate_cudagraph_capturing_enabled
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
@@ -164,7 +164,7 @@ class CUDAGraphWrapper:
|
||||
assumption on the dynamic shape (batch size) of the runtime inputs, as a
|
||||
trade-off for staying orthogonal to compilation logic. Nevertheless,
|
||||
tracing and checking the input addresses to be consistent during replay is
|
||||
guaranteed when VLLM_LOGGING_LEVEL == "DEBUG".
|
||||
guaranteed when vLLM debug logging is enabled.
|
||||
"""
|
||||
|
||||
_all_instances: ClassVar[weakref.WeakSet["CUDAGraphWrapper"]] = weakref.WeakSet()
|
||||
@@ -188,7 +188,7 @@ class CUDAGraphWrapper:
|
||||
self.compilation_config = vllm_config.compilation_config
|
||||
|
||||
self.first_run_finished = False
|
||||
self.is_debugging_mode = envs.VLLM_LOGGING_LEVEL == "DEBUG"
|
||||
self.is_debugging_mode = logger.isEnabledFor(logging.DEBUG)
|
||||
self._runnable_str = str(runnable) if self.is_debugging_mode else None
|
||||
|
||||
# assert runtime_mode is not NONE(no cudagraph), otherwise, we don't
|
||||
|
||||
@@ -7,6 +7,7 @@ from collections.abc import Callable
|
||||
import torch
|
||||
from torch._higher_order_ops.auto_functionalize import auto_functionalized
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import VllmConfig, get_layers_from_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.attention import Attention
|
||||
@@ -35,7 +36,9 @@ RESHAPE_OP = torch.ops.aten.reshape.default
|
||||
_FP8_QUANT_KEY = QuantKey(dtype=FP8_DTYPE, scale=kStaticTensorScale, symmetric=True)
|
||||
|
||||
|
||||
class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
class AttnFp8StaticQuantPattern(
|
||||
VllmPatternReplacement[..., torch.Tensor | tuple[torch.Tensor, torch.Tensor]]
|
||||
):
|
||||
"""Fusion for Attention+Fp8StaticQuant.
|
||||
|
||||
Only triggers when the attention implementation returns True in
|
||||
@@ -51,8 +54,20 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
self._dtype = dtype
|
||||
self._quant_matcher = MatcherQuantFP8(_FP8_QUANT_KEY)
|
||||
|
||||
def _quantize(
|
||||
self, value: torch.Tensor, scale: torch.Tensor
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
return self._quant_matcher(value, scale)[0]
|
||||
|
||||
def _output(
|
||||
self, value: torch.Tensor, scale: torch.Tensor
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
return value
|
||||
|
||||
@property
|
||||
def pattern(self) -> Callable[..., torch.Tensor]:
|
||||
def pattern(
|
||||
self,
|
||||
) -> Callable[..., torch.Tensor | tuple[torch.Tensor, torch.Tensor]]:
|
||||
# When _USE_LAYERNAME is enabled (torch >= 2.11), layer_name is
|
||||
# passed as an explicit pattern input so the pattern matcher
|
||||
# treats it as a wildcard matching hoisted LayerName placeholders.
|
||||
@@ -78,7 +93,7 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
attn_out_view = RESHAPE_OP(
|
||||
at1[1], [q.shape[0], self._num_heads * self._head_size]
|
||||
)
|
||||
return self._quant_matcher(attn_out_view, scale)[0]
|
||||
return self._quantize(attn_out_view, scale)
|
||||
|
||||
return _pattern_with_ln
|
||||
|
||||
@@ -97,12 +112,14 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
attn_out_view = RESHAPE_OP(
|
||||
at1[1], [q.shape[0], self._num_heads * self._head_size]
|
||||
)
|
||||
return self._quant_matcher(attn_out_view, scale)[0]
|
||||
return self._quantize(attn_out_view, scale)
|
||||
|
||||
return _pattern
|
||||
|
||||
@property
|
||||
def replacement(self) -> Callable[..., torch.Tensor]:
|
||||
def replacement(
|
||||
self,
|
||||
) -> Callable[..., torch.Tensor | tuple[torch.Tensor, torch.Tensor]]:
|
||||
_ln = _encode_layer_name(self._layer_name)
|
||||
|
||||
if _USE_LAYERNAME:
|
||||
@@ -126,7 +143,9 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
output_block_scale=None,
|
||||
kv_cache_dummy_dep=kv_cache_dummy_dep,
|
||||
)
|
||||
return RESHAPE_OP(at1[1], [-1, self._num_heads * self._head_size])
|
||||
return self._output(
|
||||
RESHAPE_OP(at1[1], [-1, self._num_heads * self._head_size]), scale
|
||||
)
|
||||
|
||||
return _replacement_with_ln
|
||||
|
||||
@@ -147,7 +166,9 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
output_block_scale=None,
|
||||
kv_cache_dummy_dep=kv_cache_dummy_dep,
|
||||
)
|
||||
return RESHAPE_OP(at1[1], [-1, self._num_heads * self._head_size])
|
||||
return self._output(
|
||||
RESHAPE_OP(at1[1], [-1, self._num_heads * self._head_size]), scale
|
||||
)
|
||||
|
||||
return _replacement
|
||||
|
||||
@@ -168,6 +189,30 @@ class AttnFp8StaticQuantPattern(VllmPatternReplacement[..., torch.Tensor]):
|
||||
return inputs
|
||||
|
||||
|
||||
class RocmAttnFp8StaticQuantPattern(AttnFp8StaticQuantPattern):
|
||||
"""Fuse AITER static quantization while preserving its scale output."""
|
||||
|
||||
def _quantize(
|
||||
self, value: torch.Tensor, scale: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
out = torch.empty_like(value, dtype=FP8_DTYPE)
|
||||
_, out, scale = auto_functionalized(
|
||||
torch.ops.vllm.rocm_aiter_per_tensor_quant.default,
|
||||
out=out,
|
||||
x=value,
|
||||
scale=scale,
|
||||
is_dynamic=False,
|
||||
)
|
||||
# The shared AITER op declares scale mutable for its dynamic variant.
|
||||
# Static quant preserves it; keep this graph output when replacing it.
|
||||
return out, scale
|
||||
|
||||
def _output(
|
||||
self, value: torch.Tensor, scale: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return value, scale
|
||||
|
||||
|
||||
class AttnNvfp4QuantPattern(
|
||||
VllmPatternReplacement[..., tuple[torch.Tensor, torch.Tensor]]
|
||||
):
|
||||
@@ -387,6 +432,8 @@ class AttnQuantFusionPass(VllmFusionPatternMatcherPass):
|
||||
for layer in layers:
|
||||
if layer.impl.fused_output_quant_supported(_FP8_QUANT_KEY):
|
||||
self.register(AttnFp8StaticQuantPattern(layer, dtype))
|
||||
if current_platform.is_rocm() and rocm_aiter_ops.is_enabled():
|
||||
self.register(RocmAttnFp8StaticQuantPattern(layer, dtype))
|
||||
if _USE_LAYERNAME:
|
||||
break
|
||||
|
||||
|
||||
@@ -339,6 +339,8 @@ class BasePattern:
|
||||
|
||||
|
||||
class GEMMReduceScatterPattern(BasePattern):
|
||||
rocm_gemm = False
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
mul = torch.empty([16, 4], device=self.device, dtype=self.dtype)
|
||||
mm_weight = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
@@ -346,7 +348,10 @@ class GEMMReduceScatterPattern(BasePattern):
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(mul: torch.Tensor, mm_weight: torch.Tensor) -> torch.Tensor:
|
||||
mm = torch.ops.aten.mm.default(mul, mm_weight)
|
||||
if self.rocm_gemm:
|
||||
mm = torch.ops.vllm.rocm_unquantized_gemm(mul, mm_weight, None)
|
||||
else:
|
||||
mm = torch.ops.aten.mm.default(mul, mm_weight)
|
||||
reduce_scatter = torch.ops.vllm.reduce_scatter.default(
|
||||
mm,
|
||||
dim=0,
|
||||
@@ -358,7 +363,7 @@ class GEMMReduceScatterPattern(BasePattern):
|
||||
def replacement(mul: torch.Tensor, mm_weight: torch.Tensor) -> torch.Tensor:
|
||||
gemm_rs = torch.ops.symm_mem.fused_matmul_reduce_scatter(
|
||||
mul,
|
||||
mm_weight,
|
||||
mm_weight.t() if self.rocm_gemm else mm_weight,
|
||||
"sum",
|
||||
scatter_dim=0,
|
||||
group_name=self.tp.device_group.group_name,
|
||||
@@ -371,7 +376,13 @@ class GEMMReduceScatterPattern(BasePattern):
|
||||
)
|
||||
|
||||
|
||||
class RocmGEMMReduceScatterPattern(GEMMReduceScatterPattern):
|
||||
rocm_gemm = True
|
||||
|
||||
|
||||
class AllGatherGEMMPattern(BasePattern):
|
||||
rocm_gemm = False
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
x = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
weight = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
@@ -390,12 +401,14 @@ class AllGatherGEMMPattern(BasePattern):
|
||||
group_name=self.tp.unique_name,
|
||||
)
|
||||
|
||||
if self.rocm_gemm:
|
||||
return torch.ops.vllm.rocm_unquantized_gemm(all_gather, weight, None)
|
||||
return torch.ops.aten.mm.default(all_gather, weight)
|
||||
|
||||
def replacement(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
|
||||
ag_output, mm_outputs = torch.ops.symm_mem.fused_all_gather_matmul(
|
||||
x,
|
||||
[weight],
|
||||
[weight.t() if self.rocm_gemm else weight],
|
||||
gather_dim=0,
|
||||
group_name=self.tp.device_group.group_name,
|
||||
)
|
||||
@@ -406,6 +419,10 @@ class AllGatherGEMMPattern(BasePattern):
|
||||
)
|
||||
|
||||
|
||||
class RocmAllGatherGEMMPattern(AllGatherGEMMPattern):
|
||||
rocm_gemm = True
|
||||
|
||||
|
||||
class ScaledMMReduceScatterPattern(BasePattern):
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
input = torch.empty([16, 16], device=self.device, dtype=FP8_DTYPE)
|
||||
@@ -906,6 +923,13 @@ class AsyncTPPass(VllmFusionPatternMatcherPass):
|
||||
GEMMReduceScatterPattern(self.model_dtype, self.device).register(self.pm_pass)
|
||||
|
||||
AllGatherGEMMPattern(self.model_dtype, self.device).register(self.pm_pass)
|
||||
if current_platform.is_rocm() and self.model_dtype == torch.bfloat16:
|
||||
RocmGEMMReduceScatterPattern(self.model_dtype, self.device).register(
|
||||
self.pm_pass
|
||||
)
|
||||
RocmAllGatherGEMMPattern(self.model_dtype, self.device).register(
|
||||
self.pm_pass
|
||||
)
|
||||
|
||||
# These fusions are enabled only for bfloat16 models because
|
||||
# `scaled_mm` or `cutlass_scaled_mm` with per-token (row-wise) scaling
|
||||
|
||||
@@ -31,6 +31,7 @@ from vllm.platforms import current_platform
|
||||
|
||||
ROTARY_OP = torch.ops._C.rotary_embedding.default
|
||||
FLASHINFER_ROTARY_OP = torch.ops.vllm.flashinfer_rotary_embedding.default
|
||||
MROPE_OP = torch.ops.vllm.mrope.default
|
||||
|
||||
QUANT_OPS: dict[QuantKey, OpOverload] = {
|
||||
kFp8StaticTensorSym: torch.ops._C.static_scaled_fp8_quant.default, # noqa: E501
|
||||
@@ -162,6 +163,74 @@ class MatcherRotaryEmbedding(MatcherCustomOp):
|
||||
return result
|
||||
|
||||
|
||||
class MatcherMRotaryEmbedding(MatcherCustomOp):
|
||||
def __init__(
|
||||
self,
|
||||
is_neox: bool,
|
||||
head_size: int,
|
||||
rotary_dim: int,
|
||||
num_heads: int,
|
||||
num_kv_heads: int,
|
||||
mrope_section: tuple[int, int, int],
|
||||
mrope_interleaved: bool,
|
||||
enabled: bool | None = None,
|
||||
) -> None:
|
||||
if enabled is None:
|
||||
enabled = RotaryEmbedding.enabled()
|
||||
|
||||
super().__init__(enabled)
|
||||
self.is_neox = is_neox
|
||||
self.head_size = head_size
|
||||
self.rotary_dim = rotary_dim
|
||||
self.num_heads = num_heads
|
||||
self.num_kv_heads = num_kv_heads
|
||||
self.q_size = self.num_heads * self.head_size
|
||||
self.kv_size = self.num_kv_heads * self.head_size
|
||||
self.mrope_section = mrope_section
|
||||
self.mrope_interleaved = mrope_interleaved
|
||||
|
||||
def inputs(self) -> list[torch.Tensor]:
|
||||
positions = self.empty_int64(3, 5)
|
||||
query = self.empty(5, self.q_size)
|
||||
key = self.empty(5, self.kv_size)
|
||||
cos_sin_cache = self.empty(4096, self.rotary_dim)
|
||||
return [positions, query, key, cos_sin_cache]
|
||||
|
||||
def forward_custom(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
result = auto_functionalized(
|
||||
MROPE_OP,
|
||||
positions=positions,
|
||||
query=query,
|
||||
key=key,
|
||||
cos_sin_cache=cos_sin_cache,
|
||||
head_size=self.head_size,
|
||||
rotary_dim=self.rotary_dim,
|
||||
mrope_section_t=self.mrope_section[0],
|
||||
mrope_section_h=self.mrope_section[1],
|
||||
mrope_section_w=self.mrope_section[2],
|
||||
mrope_interleaved=self.mrope_interleaved,
|
||||
is_neox_style=self.is_neox,
|
||||
)
|
||||
return result[1], result[2]
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
raise NotImplementedError(
|
||||
"MRoPE fusion requires the rotary_embedding custom op"
|
||||
)
|
||||
|
||||
|
||||
class MatcherRMSNormGated(MatcherCustomOp):
|
||||
"""Matches RMSNormGated with norm_before_gate=True and group_size=None."""
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import inspect
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import ParamSpec
|
||||
|
||||
import torch
|
||||
@@ -19,12 +19,19 @@ from vllm.model_executor.layers.attention.attention import (
|
||||
Attention,
|
||||
get_attention_context,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
from vllm.utils.torch_utils import (
|
||||
_USE_LAYERNAME,
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
direct_register_custom_op,
|
||||
)
|
||||
|
||||
from ..inductor_pass import enable_fake_mode
|
||||
from ..vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
|
||||
from .matcher_utils import MatcherRotaryEmbedding
|
||||
from .matcher_utils import MROPE_OP, MatcherMRotaryEmbedding, MatcherRotaryEmbedding
|
||||
from .rms_quant_fusion import empty_bf16, empty_fp32, empty_i64
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -51,8 +58,9 @@ def fused_qk_norm_rope_and_unified_kv_cache_update_impl(
|
||||
rms_norm_eps: float,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
is_neox: bool,
|
||||
layer_name: str = "",
|
||||
layer_name: LayerNameType,
|
||||
) -> torch.Tensor:
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
_, attn_layer, kv_cache, layer_slot_mapping = get_attention_context(layer_name)
|
||||
if layer_slot_mapping is not None:
|
||||
attn_layer.impl.do_qk_norm_rope_kvcache_update(
|
||||
@@ -87,7 +95,7 @@ def fused_qk_norm_rope_and_unified_kv_cache_update_fake(
|
||||
rms_norm_eps: float,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
is_neox: bool,
|
||||
layer_name: str = "",
|
||||
layer_name: LayerNameType,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty(0, device=qkv.device, dtype=qkv.dtype)
|
||||
|
||||
@@ -100,6 +108,76 @@ direct_register_custom_op(
|
||||
)
|
||||
|
||||
|
||||
def fused_qk_norm_mrope_and_unified_kv_cache_update_impl(
|
||||
q_out: torch.Tensor,
|
||||
qkv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
is_neox: bool,
|
||||
mrope_section_t: int,
|
||||
mrope_section_h: int,
|
||||
mrope_section_w: int,
|
||||
is_interleaved: bool,
|
||||
rotary_dim: int,
|
||||
layer_name: LayerNameType,
|
||||
) -> torch.Tensor:
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
_, attn_layer, kv_cache, layer_slot_mapping = get_attention_context(layer_name)
|
||||
if layer_slot_mapping is not None:
|
||||
if positions.ndim == 1:
|
||||
positions = positions.unsqueeze(0).expand(3, -1).contiguous()
|
||||
attn_layer.impl.do_qk_norm_mrope_kvcache_update(
|
||||
attn_layer,
|
||||
qkv,
|
||||
q_out,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
rms_norm_eps,
|
||||
cos_sin_cache,
|
||||
is_neox,
|
||||
(mrope_section_t, mrope_section_h, mrope_section_w),
|
||||
is_interleaved,
|
||||
rotary_dim,
|
||||
kv_cache,
|
||||
layer_slot_mapping,
|
||||
)
|
||||
else:
|
||||
q_out.zero_()
|
||||
|
||||
return torch.empty(0, device=qkv.device, dtype=qkv.dtype)
|
||||
|
||||
|
||||
def fused_qk_norm_mrope_and_unified_kv_cache_update_fake(
|
||||
q_out: torch.Tensor,
|
||||
qkv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
rms_norm_eps: float,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
is_neox: bool,
|
||||
mrope_section_t: int,
|
||||
mrope_section_h: int,
|
||||
mrope_section_w: int,
|
||||
is_interleaved: bool,
|
||||
rotary_dim: int,
|
||||
layer_name: LayerNameType,
|
||||
) -> torch.Tensor:
|
||||
return torch.empty(0, device=qkv.device, dtype=qkv.dtype)
|
||||
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="fused_qk_norm_mrope_and_unified_kv_cache_update",
|
||||
op_func=fused_qk_norm_mrope_and_unified_kv_cache_update_impl,
|
||||
mutates_args=["q_out"],
|
||||
fake_impl=fused_qk_norm_mrope_and_unified_kv_cache_update_fake,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pattern: QK-norm + RoPE + unified_kv_cache_update
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -142,19 +220,27 @@ class QkNormRopeKvCachePattern:
|
||||
self.eps = eps
|
||||
self.is_neox = is_neox
|
||||
self.quant_query = quant_query
|
||||
self.encoded_layer_name = _encode_layer_name(self.layer_name)
|
||||
self.query_quant_group_shape = (
|
||||
layer.query_quant.group_shape
|
||||
if layer.query_quant is not None
|
||||
else GroupShape.PER_TENSOR
|
||||
)
|
||||
|
||||
self.q_size = self.num_heads * self.head_size
|
||||
self.k_size = self.num_kv_heads * self.head_size
|
||||
self.v_size = self.num_kv_heads * self.head_size_v
|
||||
|
||||
self.rope_matcher = MatcherRotaryEmbedding(
|
||||
is_neox=is_neox,
|
||||
head_size=self.head_size,
|
||||
num_heads=self.num_heads,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
self.rope_matcher: MatcherRotaryEmbedding | MatcherMRotaryEmbedding = (
|
||||
MatcherRotaryEmbedding(
|
||||
is_neox=is_neox,
|
||||
head_size=self.head_size,
|
||||
num_heads=self.num_heads,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
)
|
||||
)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
def get_inputs(self) -> list:
|
||||
T = 5
|
||||
L = 4096
|
||||
qkv = empty_bf16(T, self.q_size + self.k_size + self.v_size)
|
||||
@@ -166,8 +252,13 @@ class QkNormRopeKvCachePattern:
|
||||
if self.quant_query:
|
||||
q_scale = empty_fp32(1)
|
||||
inputs += [q_scale]
|
||||
if _USE_LAYERNAME:
|
||||
inputs.append(self.encoded_layer_name)
|
||||
return inputs
|
||||
|
||||
def _get_layer_name(self, layer_name: LayerNameType | None) -> LayerNameType:
|
||||
return self.encoded_layer_name if layer_name is None else layer_name
|
||||
|
||||
def pattern_non_fp8_quant_query(
|
||||
self,
|
||||
qkv: torch.Tensor,
|
||||
@@ -175,6 +266,7 @@ class QkNormRopeKvCachePattern:
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q, k, v = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1)
|
||||
q_by_head = q.view(-1, self.q_size // self.head_size, self.head_size)
|
||||
@@ -190,7 +282,9 @@ class QkNormRopeKvCachePattern:
|
||||
q_rope = q_rope.view(-1, self.num_heads, self.head_size)
|
||||
k_rope = k_rope.view(-1, self.num_kv_heads, self.head_size)
|
||||
v = v.view(-1, self.num_kv_heads, self.head_size_v)
|
||||
dummy = torch.ops.vllm.unified_kv_cache_update(k_rope, v, self.layer_name)
|
||||
dummy = torch.ops.vllm.unified_kv_cache_update(
|
||||
k_rope, v, self._get_layer_name(layer_name)
|
||||
)
|
||||
return dummy, q_rope, k_rope, v
|
||||
|
||||
def replacement_non_fp8_quant_query(
|
||||
@@ -200,6 +294,7 @@ class QkNormRopeKvCachePattern:
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_out = torch.empty(
|
||||
qkv.shape[0],
|
||||
@@ -228,10 +323,49 @@ class QkNormRopeKvCachePattern:
|
||||
rms_norm_eps=self.eps,
|
||||
cos_sin_cache=cos_sin_cache,
|
||||
is_neox=self.is_neox,
|
||||
layer_name=self.layer_name,
|
||||
layer_name=self._get_layer_name(layer_name),
|
||||
)
|
||||
return results[0], results[1], results[2], v
|
||||
|
||||
def _quantize_query(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
if self.query_quant_group_shape.is_per_tensor():
|
||||
q_out = torch.empty_like(query, dtype=current_platform.fp8_dtype())
|
||||
q_quant = auto_functionalized(
|
||||
torch.ops.vllm.rocm_aiter_per_tensor_quant.default,
|
||||
out=q_out,
|
||||
x=query,
|
||||
scale=q_scale,
|
||||
is_dynamic=False,
|
||||
)
|
||||
# The AITER op's schema marks scale mutable, so preserve its
|
||||
# functionalized write-back as an output of the matched region.
|
||||
return q_quant[1], q_quant[2]
|
||||
|
||||
# QuantFP8.forward_hip falls back to the generic static op for the
|
||||
# historical per-head shape (-1, block_size). This also covers the
|
||||
# degenerate one-local-KV-head case where a scalar scale is represented
|
||||
# as (-1, q_size), rather than changing Attention's classification.
|
||||
q_out = torch.empty(
|
||||
query.shape,
|
||||
device=query.device,
|
||||
dtype=current_platform.fp8_dtype(),
|
||||
)
|
||||
q_quant = auto_functionalized(
|
||||
torch.ops._C.static_scaled_fp8_quant.default,
|
||||
result=q_out,
|
||||
input=query,
|
||||
scale=q_scale,
|
||||
group_shape=[
|
||||
self.query_quant_group_shape.row,
|
||||
self.query_quant_group_shape.col,
|
||||
],
|
||||
)
|
||||
return q_quant[1], None
|
||||
|
||||
def pattern_fp8_quant_query(
|
||||
self,
|
||||
qkv: torch.Tensor,
|
||||
@@ -240,7 +374,8 @@ class QkNormRopeKvCachePattern:
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
q, k, v = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1)
|
||||
q_by_head = q.view(-1, self.q_size // self.head_size, self.head_size)
|
||||
q_normed = vllm.ir.ops.rms_norm(q_by_head, q_weight, self.eps)
|
||||
@@ -251,24 +386,15 @@ class QkNormRopeKvCachePattern:
|
||||
k_flat = k_normed.view(-1, self.k_size)
|
||||
|
||||
q_rope, k_rope = self.rope_matcher(positions, q_flat, k_flat, cos_sin_cache)
|
||||
# Match the quant-query op Attention.forward inserts (fp8 KV + UNIFIED).
|
||||
# Explicit auto_functionalized (out=[1]) keeps the quant node in the pattern.
|
||||
q_out = torch.empty_like(q_rope, dtype=current_platform.fp8_dtype())
|
||||
q_quant = auto_functionalized(
|
||||
torch.ops.vllm.rocm_aiter_per_tensor_quant.default,
|
||||
out=q_out,
|
||||
x=q_rope,
|
||||
scale=q_scale,
|
||||
is_dynamic=False,
|
||||
)
|
||||
# `scale` is mutable: its copy_ write-back to _q_scale bumps the mutation
|
||||
# region, so keep q flat (a reshape lands past the barrier and won't match).
|
||||
q_rope_fp8 = q_quant[1]
|
||||
q_scale_out = q_quant[2]
|
||||
q_rope_fp8, q_scale_out = self._quantize_query(q_rope, q_scale)
|
||||
|
||||
k_rope = k_rope.view(-1, self.num_kv_heads, self.head_size)
|
||||
v = v.view(-1, self.num_kv_heads, self.head_size_v)
|
||||
dummy = torch.ops.vllm.unified_kv_cache_update(k_rope, v, self.layer_name)
|
||||
dummy = torch.ops.vllm.unified_kv_cache_update(
|
||||
k_rope, v, self._get_layer_name(layer_name)
|
||||
)
|
||||
if q_scale_out is None:
|
||||
return dummy, q_rope_fp8, k_rope, v
|
||||
return dummy, q_rope_fp8, k_rope, v, q_scale_out
|
||||
|
||||
def replacement_fp8_quant_query(
|
||||
@@ -279,7 +405,8 @@ class QkNormRopeKvCachePattern:
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
q_out = torch.empty(
|
||||
qkv.shape[0],
|
||||
self.num_heads,
|
||||
@@ -307,22 +434,14 @@ class QkNormRopeKvCachePattern:
|
||||
rms_norm_eps=self.eps,
|
||||
cos_sin_cache=cos_sin_cache,
|
||||
is_neox=self.is_neox,
|
||||
layer_name=self.layer_name,
|
||||
layer_name=self._get_layer_name(layer_name),
|
||||
)
|
||||
# Re-apply the quant on the kernel's bf16 q_out; fused op does not quant q.
|
||||
# Same explicit auto_functionalized form as the pattern: [1] = quantized
|
||||
# q, [2] = scale (returned so the buffer-writeback use is preserved).
|
||||
# Re-apply the same quant form on the kernel's bf16 q_out; the fused
|
||||
# operation does not quantize Q.
|
||||
q_fp8_flat = results[1].view(-1, self.q_size)
|
||||
q_fp8_out = torch.empty_like(q_fp8_flat, dtype=current_platform.fp8_dtype())
|
||||
q_requant = auto_functionalized(
|
||||
torch.ops.vllm.rocm_aiter_per_tensor_quant.default,
|
||||
out=q_fp8_out,
|
||||
x=q_fp8_flat,
|
||||
scale=q_scale,
|
||||
is_dynamic=False,
|
||||
)
|
||||
q_fp8 = q_requant[1] # flat to mirror the pattern (see note above)
|
||||
q_scale_out = q_requant[2]
|
||||
q_fp8, q_scale_out = self._quantize_query(q_fp8_flat, q_scale)
|
||||
if q_scale_out is None:
|
||||
return results[0], q_fp8, results[2], v
|
||||
return results[0], q_fp8, results[2], v, q_scale_out
|
||||
|
||||
@staticmethod
|
||||
@@ -345,6 +464,9 @@ class QkNormRopeKvCachePattern:
|
||||
|
||||
view_to_reshape(gm)
|
||||
|
||||
def _extra_check(self, match: pm.Match) -> bool:
|
||||
return True
|
||||
|
||||
def _register(self, pattern, replacement, pm_pass) -> None:
|
||||
trace_fn = QkNormRopeKvCachePattern.wrap_trace_fn(
|
||||
pm.fwd_only,
|
||||
@@ -370,40 +492,338 @@ class QkNormRopeKvCachePattern:
|
||||
inputs,
|
||||
trace_fn,
|
||||
pm_pass,
|
||||
extra_check=self._extra_check,
|
||||
search_fn_pattern=search_fn_pattern,
|
||||
)
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
# make_fx counts `self` in bound-method code params; wrap as plain fns.
|
||||
# Distinct names per branch so mypy doesn't see one name, two signatures.
|
||||
if self.quant_query:
|
||||
if _USE_LAYERNAME:
|
||||
|
||||
def pattern_q(qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale):
|
||||
return self.pattern_fp8_quant_query(
|
||||
def pattern_q_with_layer(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
q_scale,
|
||||
layer_name,
|
||||
):
|
||||
return self.pattern_fp8_quant_query(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
q_scale,
|
||||
layer_name,
|
||||
)
|
||||
|
||||
def replacement_q_with_layer(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
q_scale,
|
||||
layer_name,
|
||||
):
|
||||
return self.replacement_fp8_quant_query(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
q_scale,
|
||||
layer_name,
|
||||
)
|
||||
|
||||
self._register(pattern_q_with_layer, replacement_q_with_layer, pm_pass)
|
||||
else:
|
||||
|
||||
def pattern_q_without_layer(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale
|
||||
)
|
||||
):
|
||||
return self.pattern_fp8_quant_query(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale
|
||||
)
|
||||
|
||||
def replacement_q(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale
|
||||
):
|
||||
return self.replacement_fp8_quant_query(
|
||||
def replacement_q_without_layer(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale
|
||||
)
|
||||
):
|
||||
return self.replacement_fp8_quant_query(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, q_scale
|
||||
)
|
||||
|
||||
self._register(pattern_q, replacement_q, pm_pass)
|
||||
self._register(
|
||||
pattern_q_without_layer, replacement_q_without_layer, pm_pass
|
||||
)
|
||||
else:
|
||||
if _USE_LAYERNAME:
|
||||
|
||||
def pattern_noq(qkv, positions, q_weight, k_weight, cos_sin_cache):
|
||||
return self.pattern_non_fp8_quant_query(
|
||||
def pattern_noq_with_layer(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
layer_name,
|
||||
):
|
||||
return self.pattern_non_fp8_quant_query(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
layer_name,
|
||||
)
|
||||
|
||||
def replacement_noq_with_layer(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
layer_name,
|
||||
):
|
||||
return self.replacement_non_fp8_quant_query(
|
||||
qkv,
|
||||
positions,
|
||||
q_weight,
|
||||
k_weight,
|
||||
cos_sin_cache,
|
||||
layer_name,
|
||||
)
|
||||
|
||||
self._register(
|
||||
pattern_noq_with_layer, replacement_noq_with_layer, pm_pass
|
||||
)
|
||||
else:
|
||||
|
||||
def pattern_noq_without_layer(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache
|
||||
):
|
||||
return self.pattern_non_fp8_quant_query(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache
|
||||
)
|
||||
|
||||
def replacement_noq_without_layer(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache
|
||||
):
|
||||
return self.replacement_non_fp8_quant_query(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache
|
||||
)
|
||||
|
||||
self._register(
|
||||
pattern_noq_without_layer,
|
||||
replacement_noq_without_layer,
|
||||
pm_pass,
|
||||
)
|
||||
|
||||
def replacement_noq(qkv, positions, q_weight, k_weight, cos_sin_cache):
|
||||
return self.replacement_non_fp8_quant_query(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache
|
||||
)
|
||||
|
||||
self._register(pattern_noq, replacement_noq, pm_pass)
|
||||
class QkNormMRopeKvCachePattern(QkNormRopeKvCachePattern):
|
||||
FUSED_OP = torch.ops.vllm.fused_qk_norm_mrope_and_unified_kv_cache_update.default
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
layer: Attention,
|
||||
eps: float,
|
||||
is_neox: bool,
|
||||
quant_query: bool,
|
||||
rotary_dim: int,
|
||||
mrope_section: tuple[int, int, int],
|
||||
is_interleaved: bool,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
layer=layer,
|
||||
eps=eps,
|
||||
is_neox=is_neox,
|
||||
quant_query=quant_query,
|
||||
)
|
||||
self.rotary_dim = rotary_dim
|
||||
self.mrope_section = mrope_section
|
||||
self.is_interleaved = is_interleaved
|
||||
self.rope_matcher = MatcherMRotaryEmbedding(
|
||||
is_neox=is_neox,
|
||||
head_size=self.head_size,
|
||||
rotary_dim=rotary_dim,
|
||||
num_heads=self.num_heads,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
mrope_section=mrope_section,
|
||||
mrope_interleaved=is_interleaved,
|
||||
)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
T = 5
|
||||
L = 4096
|
||||
qkv = empty_bf16(T, self.q_size + self.k_size + self.v_size)
|
||||
positions = empty_i64(3, T)
|
||||
q_weight = empty_bf16(1, self.head_size)
|
||||
k_weight = empty_bf16(1, self.head_size)
|
||||
cos_sin_cache = empty_bf16(L, self.rotary_dim)
|
||||
inputs = [qkv, positions, q_weight, k_weight, cos_sin_cache]
|
||||
if self.quant_query:
|
||||
inputs.append(empty_fp32(1))
|
||||
if _USE_LAYERNAME:
|
||||
inputs.append(self.encoded_layer_name)
|
||||
return inputs
|
||||
|
||||
def _unfused_kv_views(self, qkv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# The supported backend reads K/V from the cache after the fused write.
|
||||
# Keep view-compatible placeholders for the attention custom-op ABI.
|
||||
_, k, v = qkv.split([self.q_size, self.k_size, self.v_size], dim=-1)
|
||||
k = k.view(qkv.shape[0], self.num_kv_heads, self.head_size)
|
||||
v = v.view(qkv.shape[0], self.num_kv_heads, self.head_size_v)
|
||||
return k, v
|
||||
|
||||
def _fused_results(
|
||||
self,
|
||||
qkv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
layer_name: LayerNameType | None,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
q_out = torch.empty(
|
||||
qkv.shape[0],
|
||||
self.num_heads,
|
||||
self.head_size,
|
||||
device=qkv.device,
|
||||
dtype=qkv.dtype,
|
||||
)
|
||||
return auto_functionalized(
|
||||
self.FUSED_OP,
|
||||
q_out=q_out,
|
||||
qkv=qkv,
|
||||
positions=positions,
|
||||
q_weight=q_weight,
|
||||
k_weight=k_weight,
|
||||
rms_norm_eps=self.eps,
|
||||
cos_sin_cache=cos_sin_cache,
|
||||
is_neox=self.is_neox,
|
||||
mrope_section_t=self.mrope_section[0],
|
||||
mrope_section_h=self.mrope_section[1],
|
||||
mrope_section_w=self.mrope_section[2],
|
||||
is_interleaved=self.is_interleaved,
|
||||
rotary_dim=self.rotary_dim,
|
||||
layer_name=self._get_layer_name(layer_name),
|
||||
)
|
||||
|
||||
def replacement_non_fp8_quant_query(
|
||||
self,
|
||||
qkv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
k, v = self._unfused_kv_views(qkv)
|
||||
results = self._fused_results(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, layer_name
|
||||
)
|
||||
return results[0], results[1], k, v
|
||||
|
||||
def replacement_fp8_quant_query(
|
||||
self,
|
||||
qkv: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
layer_name: LayerNameType | None = None,
|
||||
) -> tuple[torch.Tensor, ...]:
|
||||
k, v = self._unfused_kv_views(qkv)
|
||||
results = self._fused_results(
|
||||
qkv, positions, q_weight, k_weight, cos_sin_cache, layer_name
|
||||
)
|
||||
q_flat = results[1].view(-1, self.q_size)
|
||||
q_fp8, q_scale_out = self._quantize_query(q_flat, q_scale)
|
||||
if q_scale_out is None:
|
||||
return results[0], q_fp8, k, v
|
||||
return results[0], q_fp8, k, v, q_scale_out
|
||||
|
||||
def _extra_check(self, match: pm.Match) -> bool:
|
||||
expected = {
|
||||
"head_size": self.head_size,
|
||||
"rotary_dim": self.rotary_dim,
|
||||
"mrope_section_t": self.mrope_section[0],
|
||||
"mrope_section_h": self.mrope_section[1],
|
||||
"mrope_section_w": self.mrope_section[2],
|
||||
"mrope_interleaved": self.is_interleaved,
|
||||
"is_neox_style": self.is_neox,
|
||||
}
|
||||
mrope_node = next(
|
||||
(node for node in match.nodes if node.args and node.args[0] == MROPE_OP),
|
||||
None,
|
||||
)
|
||||
if mrope_node is None or any(
|
||||
mrope_node.kwargs.get(name) != value for name, value in expected.items()
|
||||
):
|
||||
return False
|
||||
|
||||
# The fused AITER MRoPE entrypoint writes rotated K directly to the
|
||||
# cache and does not expose a BF16 K result. Returning the raw K view is
|
||||
# valid only for decoder unified attention, whose backend consumes K
|
||||
# from that cache. Reject graphs that observe K in any other way.
|
||||
output_nodes = match.output_nodes()
|
||||
if len(output_nodes) < 3 or output_nodes[2] is None:
|
||||
return False
|
||||
matched_nodes = set(match.nodes)
|
||||
attention_op = torch.ops.vllm.unified_attention_with_output.default
|
||||
|
||||
def is_unified_attention_user(user: fx.Node) -> bool:
|
||||
return user.op == "call_function" and (
|
||||
user.target == attention_op
|
||||
or (user.args and user.args[0] == attention_op)
|
||||
)
|
||||
|
||||
return all(
|
||||
user in matched_nodes or is_unified_attention_user(user)
|
||||
for user in output_nodes[2].users
|
||||
)
|
||||
|
||||
|
||||
def _discover_mrope_configs(
|
||||
config: VllmConfig,
|
||||
) -> tuple[tuple[tuple[int, int, int], bool], ...]:
|
||||
model_config = config.model_config
|
||||
hf_configs = (
|
||||
getattr(model_config, "hf_text_config", None),
|
||||
getattr(model_config, "hf_config", None),
|
||||
)
|
||||
configs: set[tuple[tuple[int, int, int], bool]] = set()
|
||||
for hf_config in hf_configs:
|
||||
if hf_config is None:
|
||||
continue
|
||||
rope_parameters = getattr(hf_config, "rope_parameters", None)
|
||||
if rope_parameters is None:
|
||||
rope_parameters = getattr(hf_config, "rope_scaling", None)
|
||||
if not isinstance(rope_parameters, Mapping):
|
||||
continue
|
||||
section = rope_parameters.get("mrope_section")
|
||||
if not isinstance(section, (list, tuple)) or len(section) != 3:
|
||||
continue
|
||||
try:
|
||||
parsed_section = (
|
||||
int(section[0]),
|
||||
int(section[1]),
|
||||
int(section[2]),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if any(value <= 0 for value in parsed_section):
|
||||
continue
|
||||
configs.add(
|
||||
(
|
||||
parsed_section,
|
||||
bool(rope_parameters.get("mrope_interleaved", False)),
|
||||
)
|
||||
)
|
||||
return tuple(sorted(configs))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -412,7 +832,7 @@ class QkNormRopeKvCachePattern:
|
||||
|
||||
|
||||
class QkNormRopeKvCacheFusionPass(VllmPatternMatcherPass):
|
||||
"""Fuse QK-norm + RoPE + KV cache update into a single AITER HIP kernel.
|
||||
"""Fuse QK-norm + RoPE/MRoPE + KV cache update into an AITER HIP kernel.
|
||||
|
||||
Supersedes both QKNormRoPEFusionPass and RopeKVCacheFusionPass for
|
||||
attention layers that support the combined operation, eliminating two
|
||||
@@ -429,22 +849,33 @@ class QkNormRopeKvCacheFusionPass(VllmPatternMatcherPass):
|
||||
|
||||
cc = config.compilation_config
|
||||
self.max_token_num = cc.pass_config.rope_kvcache_fusion_max_token_num
|
||||
self.mrope_configs = (
|
||||
_discover_mrope_configs(config)
|
||||
if cc.is_custom_op_enabled("rotary_embedding")
|
||||
else ()
|
||||
)
|
||||
|
||||
dtype = config.model_config.dtype
|
||||
if dtype not in (torch.bfloat16, torch.float16):
|
||||
logger.warning_once(
|
||||
"QK Norm+RoPE+KVCache fusion not enabled: unsupported dtype %s", dtype
|
||||
"QK Norm+RoPE/MRoPE+KVCache fusion not enabled: unsupported dtype %s",
|
||||
dtype,
|
||||
)
|
||||
return
|
||||
|
||||
attn_layers = get_layers_from_vllm_config(config, Attention)
|
||||
|
||||
for _, layer in attn_layers.items():
|
||||
if not layer.impl.fused_qk_norm_rope_kvcache_supported():
|
||||
supports_rope = layer.impl.fused_qk_norm_rope_kvcache_supported()
|
||||
supports_mrope = (
|
||||
bool(self.mrope_configs)
|
||||
and layer.impl.fused_qk_norm_mrope_kvcache_supported()
|
||||
)
|
||||
if not supports_rope and not supports_mrope:
|
||||
continue
|
||||
if layer.head_size not in SUPPORTED_FUSED_QK_NORM_ROPE_KVCACHE_HEAD_DIMS:
|
||||
logger.warning_once(
|
||||
"QK Norm+RoPE+KVCache fusion not enabled for a layer: "
|
||||
"QK Norm+RoPE/MRoPE+KVCache fusion not enabled for a layer: "
|
||||
"head_size=%d is not supported by the "
|
||||
"fused_qk_norm_rope_cache_pts_quant_shuffle kernel "
|
||||
"(supported: %s). Falling back to the unfused path.",
|
||||
@@ -455,22 +886,71 @@ class QkNormRopeKvCacheFusionPass(VllmPatternMatcherPass):
|
||||
if layer.head_size_v != layer.head_size:
|
||||
# The fused kernel uses a single head_dim for q/k/v.
|
||||
logger.warning_once(
|
||||
"QK Norm+RoPE+KVCache fusion not enabled for a layer: "
|
||||
"QK Norm+RoPE/MRoPE+KVCache fusion not enabled for a layer: "
|
||||
"head_size_v=%d differs from head_size=%d, which the fused "
|
||||
"kernel does not support. Falling back to the unfused path.",
|
||||
layer.head_size_v,
|
||||
layer.head_size,
|
||||
)
|
||||
continue
|
||||
for epsilon in [1e-5, 1e-6]:
|
||||
for neox in [True, False]:
|
||||
for quant_q in [False, True]:
|
||||
QkNormRopeKvCachePattern(
|
||||
layer=layer,
|
||||
eps=epsilon,
|
||||
is_neox=neox,
|
||||
quant_query=quant_q,
|
||||
).register(self.patterns)
|
||||
if supports_rope:
|
||||
for epsilon in [1e-5, 1e-6]:
|
||||
for neox in [True, False]:
|
||||
for quant_q in [False, True]:
|
||||
QkNormRopeKvCachePattern(
|
||||
layer=layer,
|
||||
eps=epsilon,
|
||||
is_neox=neox,
|
||||
quant_query=quant_q,
|
||||
).register(self.patterns)
|
||||
|
||||
if supports_mrope:
|
||||
for section, is_interleaved in self.mrope_configs:
|
||||
rotary_dim = 2 * sum(section)
|
||||
if rotary_dim > layer.head_size:
|
||||
logger.warning_once(
|
||||
"QK Norm+MRoPE+KVCache fusion not enabled for a "
|
||||
"layer: rotary_dim=%d exceeds head_size=%d.",
|
||||
rotary_dim,
|
||||
layer.head_size,
|
||||
)
|
||||
continue
|
||||
vector_width = layer.head_size // 32
|
||||
for epsilon in [1e-5, 1e-6]:
|
||||
for neox in [True, False]:
|
||||
# Each warp lane processes `vector_width` adjacent
|
||||
# values. NeoX additionally exchanges vectors
|
||||
# across the half-rotary boundary.
|
||||
rotary_alignment = vector_width * (2 if neox else 1)
|
||||
if rotary_dim % rotary_alignment != 0:
|
||||
logger.warning_once(
|
||||
"QK Norm+MRoPE+KVCache fusion not enabled "
|
||||
"for a layer/style: rotary_dim=%d must be "
|
||||
"divisible by %d for head_size=%d and "
|
||||
"is_neox=%s.",
|
||||
rotary_dim,
|
||||
rotary_alignment,
|
||||
layer.head_size,
|
||||
neox,
|
||||
)
|
||||
continue
|
||||
for quant_q in [False, True]:
|
||||
QkNormMRopeKvCachePattern(
|
||||
layer=layer,
|
||||
eps=epsilon,
|
||||
is_neox=neox,
|
||||
quant_query=quant_q,
|
||||
rotary_dim=rotary_dim,
|
||||
mrope_section=section,
|
||||
is_interleaved=is_interleaved,
|
||||
).register(self.patterns)
|
||||
|
||||
# Opaque LayerName is a pattern wildcard on torch >= 2.11, so
|
||||
# homogeneous attention layers produce duplicate search patterns.
|
||||
# As in the other LayerName-aware fusion passes, one supported
|
||||
# layer registers all shape/style variants for the model.
|
||||
if _USE_LAYERNAME:
|
||||
break
|
||||
|
||||
self.dump_patterns(config, self.patterns)
|
||||
|
||||
@@ -478,8 +958,8 @@ class QkNormRopeKvCacheFusionPass(VllmPatternMatcherPass):
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
self.matched_count = self.patterns.apply(graph)
|
||||
logger.info(
|
||||
"QK-Norm+RoPE+KVCache fusion: replaced %s pattern(s) "
|
||||
"with AITER fused_qk_norm_rope_cache_pts_quant_shuffle",
|
||||
"QK-Norm+RoPE/MRoPE+KVCache fusion: replaced %s pattern(s) "
|
||||
"with an AITER fused attention-prologue kernel",
|
||||
self.matched_count,
|
||||
)
|
||||
|
||||
@@ -487,4 +967,10 @@ class QkNormRopeKvCacheFusionPass(VllmPatternMatcherPass):
|
||||
return compile_range.end <= self.max_token_num
|
||||
|
||||
def uuid(self) -> str:
|
||||
return VllmInductorPass.hash_source(self, QkNormRopeKvCachePattern)
|
||||
return VllmInductorPass.hash_source(
|
||||
self,
|
||||
QkNormRopeKvCachePattern,
|
||||
QkNormMRopeKvCachePattern,
|
||||
_discover_mrope_configs,
|
||||
repr(self.mrope_configs),
|
||||
)
|
||||
|
||||
@@ -41,6 +41,7 @@ if current_platform.is_cuda_alike() or current_platform.is_xpu():
|
||||
if current_platform.is_cuda_alike():
|
||||
from .fusion.act_quant_fusion import ActivationQuantFusionPass
|
||||
from .fusion.attn_quant_fusion import AttnQuantFusionPass
|
||||
from .fusion.collective_fusion import AsyncTPPass
|
||||
from .fusion.mla_attn_quant_fusion import MLAAttnQuantFusionPass
|
||||
from .fusion.mla_rope_kvcache_cat_fusion import MLARoPEKVCacheCatFusionPass
|
||||
from .fusion.qk_norm_rope_kvcache_fusion import QkNormRopeKvCacheFusionPass
|
||||
@@ -50,7 +51,6 @@ if current_platform.is_cuda_alike():
|
||||
|
||||
if current_platform.is_cuda():
|
||||
from .fusion.allreduce_rms_fusion import AllReduceFusionPass
|
||||
from .fusion.collective_fusion import AsyncTPPass
|
||||
|
||||
if current_platform.is_xpu():
|
||||
from .fusion.act_quant_fusion import ActivationQuantFusionPass
|
||||
|
||||
@@ -20,6 +20,7 @@ from vllm.config.kernel import KernelConfig
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.config.kv_transfer import KVTransferConfig
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.config.logging import LoggingConfig
|
||||
from vllm.config.lora import LoRAConfig
|
||||
from vllm.config.mamba import MambaConfig
|
||||
from vllm.config.model import (
|
||||
@@ -97,6 +98,8 @@ __all__ = [
|
||||
"KVTransferConfig",
|
||||
# From vllm.config.load
|
||||
"LoadConfig",
|
||||
# From vllm.config.logging
|
||||
"LoggingConfig",
|
||||
# From vllm.config.lora
|
||||
"LoRAConfig",
|
||||
# From vllm.config.mamba
|
||||
|
||||
@@ -154,15 +154,15 @@ class PassConfig:
|
||||
fuse_rope_kvcache: bool = None # type: ignore[assignment]
|
||||
"""Fuse the QK rope + KV cache ops."""
|
||||
fuse_qk_norm_rope_kvcache: bool = Field(default=None) # type: ignore[assignment]
|
||||
"""Fuse QK RMSNorm + RoPE + KV cache update into a single AITER HIP
|
||||
"""Fuse QK RMSNorm + RoPE/MRoPE + KV cache update into an AITER HIP
|
||||
kernel. Supersedes both enable_qk_norm_rope_fusion and fuse_rope_kvcache
|
||||
for layers that support it. Auto-enabled at O1+ on ROCm for models
|
||||
with QK-norm (e.g. Qwen3-MoE)."""
|
||||
for layers that support it. Auto-enabled at O2+ on ROCm for models
|
||||
with QK-norm (e.g. Qwen3-MoE and Qwen3-VL-class architectures)."""
|
||||
|
||||
rope_kvcache_fusion_max_token_num: int = 256
|
||||
"""The threshold for ROCm AITER RoPE+KVCache fusion e.g. for small batch decode.
|
||||
Larger batch sizes e.g. during prefill will use the unfused kernels.
|
||||
Also applies to the fused QK-Norm+RoPE+KVCache pass.
|
||||
Also applies to the fused QK-Norm+RoPE/MRoPE+KVCache pass.
|
||||
"""
|
||||
|
||||
fi_allreduce_fusion_max_size_mb: float | None = None
|
||||
|
||||
+11
-1
@@ -50,10 +50,19 @@ class EngramConfig:
|
||||
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."""
|
||||
|
||||
use_thp: bool = False
|
||||
"""Back private CPU-offloaded tables with transparent huge pages (best
|
||||
effort, falls back to ordinary pinned pages). Prefaulting the tables at
|
||||
startup takes longer. Requires cpu_offload without dp_shared_memory."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_shared_memory(self) -> Self:
|
||||
if self.dp_shared_memory and not self.cpu_offload:
|
||||
raise ValueError("dp_shared_memory requires cpu_offload=True")
|
||||
if self.use_thp and (not self.cpu_offload or self.dp_shared_memory):
|
||||
raise ValueError(
|
||||
"use_thp requires cpu_offload=True and dp_shared_memory=False"
|
||||
)
|
||||
return self
|
||||
|
||||
def verify_model_config(self, model_config: "ModelConfig | None") -> None:
|
||||
@@ -73,7 +82,8 @@ class EngramConfig:
|
||||
):
|
||||
raise ValueError(
|
||||
"EngramConfig requires a model with supported Engram "
|
||||
"embeddings, non-empty n-gram layer ids, and CUDA."
|
||||
"embeddings, non-empty n-gram layer ids, and a CUDA-alike "
|
||||
"device (CUDA or ROCm)."
|
||||
)
|
||||
|
||||
def resolve_dp_shared_memory(self, parallel_config: "ParallelConfig") -> None:
|
||||
|
||||
+2
-3
@@ -39,9 +39,8 @@ class LoadConfig:
|
||||
InstantTensor, which enables distributed loading with pipelined prefetching
|
||||
and fast direct I/O.
|
||||
- "ipc_cache" will map post-quantized weights from a local weight cache
|
||||
daemon via CUDA IPC for fast engine restarts. See
|
||||
`vllm/model_executor/model_loader/weight_cache/daemon.py` for how to
|
||||
launch the daemon.
|
||||
daemon via CUDA IPC for fast engine restarts. Launch the daemon with
|
||||
`vllm preload` first.
|
||||
- "npcache" will load the weights in pytorch format and store a numpy cache
|
||||
to speed up the loading.
|
||||
- "dummy" will initialize the weights with random values, which is mainly
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Literal, cast
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.utils import config
|
||||
|
||||
LogLevel = Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"]
|
||||
|
||||
|
||||
@config
|
||||
class LoggingConfig:
|
||||
"""vLLM logging. Default ``dictConfig`` adds a formatted stream handler.
|
||||
|
||||
Supply a JSON object with ``--logging-config`` or individual fields with
|
||||
dotted arguments such as ``--logging-config.log_level DEBUG`` and
|
||||
``--logging-config.pylogging_config_file logging.json``. ``--log-level``
|
||||
and legacy ``--log-config-file`` override their matching fields. Set
|
||||
``configure_logging`` to false to skip applying a ``dictConfig``.
|
||||
"""
|
||||
|
||||
log_level: LogLevel = Field(
|
||||
default_factory=lambda: cast(LogLevel, envs.VLLM_LOGGING_LEVEL)
|
||||
)
|
||||
"""Log level used when no custom logging configuration is provided."""
|
||||
|
||||
configure_logging: bool = Field(default_factory=lambda: envs.VLLM_CONFIGURE_LOGGING)
|
||||
"""Whether to apply a Python logging configuration.
|
||||
|
||||
With no ``pylogging_config_file``, the default config adds a formatted
|
||||
stream handler to the ``vllm`` logger. A custom Python logging configuration
|
||||
file also requires this to be enabled.
|
||||
"""
|
||||
|
||||
pylogging_config_file: str | None = Field(
|
||||
default_factory=lambda: envs.VLLM_LOGGING_CONFIG_PATH
|
||||
)
|
||||
"""Path to a Python logging JSON file using
|
||||
[``dictConfig`` schema](https://docs.python.org/3/library/logging.config.html#configuration-file-format).
|
||||
|
||||
A custom ``dictConfig`` is authoritative over ``log_level`` for logger,
|
||||
handler, and formatter settings.
|
||||
"""
|
||||
+40
-28
@@ -55,7 +55,7 @@ from vllm.utils.import_utils import LazyLoader
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from transformers import PretrainedConfig
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
import vllm.model_executor.layers.quantization as me_quant
|
||||
import vllm.model_executor.models as me_models
|
||||
@@ -64,7 +64,7 @@ if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization import QuantizationMethods
|
||||
from vllm.v1.sample.logits_processor import LogitsProcessor
|
||||
else:
|
||||
PretrainedConfig = Any
|
||||
PreTrainedConfig = Any
|
||||
|
||||
me_quant = LazyLoader(
|
||||
"model_executor", globals(), "vllm.model_executor.layers.quantization"
|
||||
@@ -89,7 +89,6 @@ ConvertOption = Literal["auto", ConvertType]
|
||||
TokenizerMode = Literal[
|
||||
"auto",
|
||||
"hf",
|
||||
"slow",
|
||||
"mistral",
|
||||
"deepseek_v32",
|
||||
"deepseek_v4",
|
||||
@@ -105,7 +104,7 @@ PROCESSED_LOGPROBS_MODES: tuple[LogprobsMode, ...] = (
|
||||
"processed_logits",
|
||||
"processed_logprobs",
|
||||
)
|
||||
HfOverrides = dict[str, Any] | Callable[[PretrainedConfig], PretrainedConfig]
|
||||
HfOverrides = dict[str, Any] | Callable[[PreTrainedConfig], PreTrainedConfig]
|
||||
ModelImpl = Literal["auto", "vllm", "transformers", "terratorch"]
|
||||
LayerBlockType = Literal["attention", "linear_attention", "mamba"]
|
||||
|
||||
@@ -148,7 +147,6 @@ class ModelConfig:
|
||||
- "auto" will use the tokenizer from `mistral_common` for Mistral models
|
||||
if available, otherwise it will use the "hf" tokenizer.
|
||||
- "hf" will use the fast tokenizer if available.
|
||||
- "slow" will always use the slow tokenizer.
|
||||
- "mistral" will always use the tokenizer from `mistral_common`.
|
||||
- "deepseek_v32" will always use the tokenizer from `deepseek_v32`.
|
||||
- "deepseek_v4" will always use the tokenizer from `deepseek_v4`.
|
||||
@@ -183,10 +181,14 @@ class ModelConfig:
|
||||
We must set the global seed because otherwise,
|
||||
different tensor parallel workers would sample different tokens,
|
||||
leading to inconsistent results."""
|
||||
hf_config: PretrainedConfig = field(init=False)
|
||||
hf_config: PreTrainedConfig = field(init=False)
|
||||
"""The Hugging Face config of the model."""
|
||||
hf_text_config: PretrainedConfig = field(init=False)
|
||||
hf_text_config: PreTrainedConfig = field(init=False)
|
||||
"""The Hugging Face config of the text model (same as hf_config for text models)."""
|
||||
is_submodel_config: bool = field(default=False, init=False)
|
||||
"""Whether this is a submodule view derived by `VllmConfig.with_hf_config`
|
||||
(e.g. a multimodal model's text stack). Its architecture list is empty, so
|
||||
deployment-level validation must not run against it."""
|
||||
word_embeddings_untied_by_checkpoint: bool = field(default=False, init=False)
|
||||
"""Whether `tie_word_embeddings` was overridden to `False` because the checkpoint
|
||||
contains an `lm_head` of its own. The two may still turn out to be identical, in
|
||||
@@ -479,7 +481,7 @@ class ModelConfig:
|
||||
|
||||
def _update_nested(
|
||||
self,
|
||||
target: PretrainedConfig | dict[str, Any],
|
||||
target: PreTrainedConfig | dict[str, Any],
|
||||
updates: dict[str, Any],
|
||||
) -> None:
|
||||
"""Recursively updates a config or dict with nested updates."""
|
||||
@@ -507,15 +509,15 @@ class ModelConfig:
|
||||
|
||||
def _apply_dict_overrides(
|
||||
self,
|
||||
config: PretrainedConfig,
|
||||
config: PreTrainedConfig,
|
||||
overrides: dict[str, Any],
|
||||
) -> None:
|
||||
"""Apply dict overrides, handling both nested configs and dict values."""
|
||||
from transformers import PretrainedConfig
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
for key, value in overrides.items():
|
||||
attr = getattr(config, key, None)
|
||||
if attr is not None and isinstance(attr, PretrainedConfig):
|
||||
if attr is not None and isinstance(attr, PreTrainedConfig):
|
||||
# It's a nested config - recursively update it
|
||||
self._update_nested(attr, value)
|
||||
else:
|
||||
@@ -585,22 +587,27 @@ class ModelConfig:
|
||||
self.maybe_pull_model_tokenizer_for_runai(self.model, self.tokenizer)
|
||||
|
||||
# If loading model/tokenizer from HF Hub, resolve the revision once
|
||||
# to prevent resolving it multiple times downstream.
|
||||
# If the weights come from a different repo, we cannot eagerly resolve revision
|
||||
weights_from_model = not self.model_weights or self.model_weights == self.model
|
||||
# If the config comes from a different repo, we cannot eagerly resolve revision
|
||||
config_from_model = not self.hf_config_path or self.hf_config_path == self.model
|
||||
can_resolve_model_revision = config_from_model and weights_from_model
|
||||
if can_resolve_model_revision:
|
||||
self.revision = resolve_revision(
|
||||
self.model,
|
||||
# to prevent resolving it multiple times downstream. A resolved revision
|
||||
# only pins the repo it was resolved for, so each repo needs its own call.
|
||||
self.revision = resolve_revision(
|
||||
self.model,
|
||||
self.revision,
|
||||
self.hf_token,
|
||||
)
|
||||
|
||||
# The config can live in another repo, which `self.revision` does not pin.
|
||||
# It stays `None` if the config comes from `self.model`, so that call sites
|
||||
# fall back to `self.revision` the same way they fall back to `self.model`.
|
||||
self._hf_config_revision = None
|
||||
if self.hf_config_path and self.hf_config_path != self.model:
|
||||
self._hf_config_revision = resolve_revision(
|
||||
self.hf_config_path,
|
||||
self.revision,
|
||||
self.hf_token,
|
||||
)
|
||||
|
||||
if (
|
||||
can_resolve_model_revision
|
||||
and self.tokenizer == self.model
|
||||
self.tokenizer == self.model
|
||||
and self.tokenizer_revision == requested_revision
|
||||
):
|
||||
self.tokenizer_revision = self.revision
|
||||
@@ -628,7 +635,7 @@ class ModelConfig:
|
||||
hf_config = get_config(
|
||||
self.hf_config_path or self.model,
|
||||
self.trust_remote_code,
|
||||
self.revision,
|
||||
self._hf_config_revision or self.revision,
|
||||
self.code_revision,
|
||||
self.config_format,
|
||||
hf_overrides_kw=hf_overrides_kw,
|
||||
@@ -1082,7 +1089,10 @@ class ModelConfig:
|
||||
# Check if the architecture we're wrapping has defaults
|
||||
runner = None
|
||||
task = None
|
||||
if defaults := try_match_architecture_defaults(self.architectures[0]):
|
||||
# architectures is empty for with_hf_config() submodel views.
|
||||
if self.architectures and (
|
||||
defaults := try_match_architecture_defaults(self.architectures[0])
|
||||
):
|
||||
_, (runner, task) = defaults
|
||||
# User specified value take precedence
|
||||
if self.runner != "auto":
|
||||
@@ -1772,7 +1782,7 @@ class ModelConfig:
|
||||
config = try_get_generation_config(
|
||||
self.hf_config_path or self.model,
|
||||
trust_remote_code=self.trust_remote_code,
|
||||
revision=self.revision,
|
||||
revision=self._hf_config_revision or self.revision,
|
||||
code_revision=self.code_revision,
|
||||
config_format=self.config_format,
|
||||
hf_token=self.hf_token,
|
||||
@@ -1815,6 +1825,8 @@ class ModelConfig:
|
||||
|
||||
available_params = [
|
||||
"repetition_penalty",
|
||||
"presence_penalty",
|
||||
"frequency_penalty",
|
||||
"temperature",
|
||||
"top_k",
|
||||
"top_p",
|
||||
@@ -2386,7 +2398,7 @@ def _resolve_auto_dtype(
|
||||
|
||||
def _get_and_verify_dtype(
|
||||
model_id: str,
|
||||
config: PretrainedConfig,
|
||||
config: PreTrainedConfig,
|
||||
dtype: str | torch.dtype,
|
||||
*,
|
||||
is_pooling_model: bool,
|
||||
@@ -2433,7 +2445,7 @@ def _get_and_verify_dtype(
|
||||
|
||||
|
||||
def _get_head_dtype(
|
||||
config: PretrainedConfig, dtype: torch.dtype, runner_type: str
|
||||
config: PreTrainedConfig, dtype: torch.dtype, runner_type: str
|
||||
) -> torch.dtype:
|
||||
head_dtype: str | torch.dtype | None = getattr(config, "head_dtype", None)
|
||||
|
||||
@@ -2457,7 +2469,7 @@ def _get_head_dtype(
|
||||
|
||||
|
||||
def _get_and_verify_max_len(
|
||||
hf_config: PretrainedConfig,
|
||||
hf_config: PreTrainedConfig,
|
||||
model_arch_config: ModelArchitectureConfig,
|
||||
tokenizer_config: dict | None,
|
||||
max_model_len: int | None,
|
||||
|
||||
@@ -534,11 +534,19 @@ class MultiModalConfig:
|
||||
"""Get the keyword arguments to pass to the multi-modal processor
|
||||
according to the extra arguments passed during inference.
|
||||
"""
|
||||
kwargs = self.mm_processor_kwargs or {}
|
||||
merged = dict(self.mm_processor_kwargs or {}) | dict(inference_kwargs)
|
||||
if self.mm_device_do_normalize:
|
||||
kwargs["do_normalize"] = False
|
||||
kwargs["do_rescale"] = False
|
||||
return kwargs | dict(inference_kwargs)
|
||||
# The model expects raw pixels and normalises on device;
|
||||
# overriding these per request would silently double-normalise.
|
||||
for key in ("do_normalize", "do_rescale"):
|
||||
if key in inference_kwargs:
|
||||
logger.warning_once(
|
||||
"mm_device_do_normalize is enabled; ignoring "
|
||||
"per-request mm_processor_kwargs[%r].",
|
||||
key,
|
||||
)
|
||||
merged[key] = False
|
||||
return merged
|
||||
|
||||
def use_gpu_video_backend(self) -> bool:
|
||||
"""Return whether the configured video loader or codec uses the GPU."""
|
||||
|
||||
@@ -84,6 +84,12 @@ class SchedulerConfig:
|
||||
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."""
|
||||
|
||||
long_prefill_token_threshold_adaptive: bool = Field(default=False)
|
||||
"""Floor the effective long prefill token threshold at a fair share of
|
||||
the token budget: max_num_batched_tokens divided by the number of
|
||||
queued and running requests. Only applies when
|
||||
long_prefill_token_threshold is nonzero."""
|
||||
|
||||
max_num_queued_reqs: int | None = Field(default=None, ge=0)
|
||||
"""Maximum number of requests that can be in-flight (waiting or running)
|
||||
at the same time, or None for no limit. When the limit is reached, new
|
||||
@@ -232,13 +238,17 @@ class SchedulerConfig:
|
||||
|
||||
# The first half of this warning can be removed once the Scheduler interface is
|
||||
# finalized and we can maintain support for scheduler classes that implement it
|
||||
logger.warning_once(
|
||||
"Using custom scheduler class %s. This scheduler interface is not public "
|
||||
"and compatibility may not be maintained. If you have subclassed Scheduler "
|
||||
"instead of AsyncScheduler, you will see degraded performance due to async "
|
||||
"scheduling being disabled.",
|
||||
self.scheduler_cls, # type: ignore[arg-type]
|
||||
)
|
||||
if not (
|
||||
isinstance(self.scheduler_cls, str)
|
||||
and self.scheduler_cls.startswith("vllm.")
|
||||
):
|
||||
logger.warning_once(
|
||||
"Using custom scheduler class %s. This scheduler interface is not "
|
||||
"public and compatibility may not be maintained. If you have "
|
||||
"subclassed Scheduler instead of AsyncScheduler, you will see "
|
||||
"degraded performance due to async scheduling being disabled.",
|
||||
self.scheduler_cls, # type: ignore[arg-type]
|
||||
)
|
||||
if not isinstance(self.scheduler_cls, str):
|
||||
return cast(type["SchedulerInterface"], self.scheduler_cls)
|
||||
return resolve_obj_by_qualname(self.scheduler_cls)
|
||||
|
||||
+22
-25
@@ -22,12 +22,12 @@ from vllm.utils.import_utils import LazyLoader, has_arctic_inference
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from transformers import PretrainedConfig
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
import vllm.model_executor.layers.quantization as me_quant
|
||||
from vllm.config.vllm import VllmConfig
|
||||
else:
|
||||
PretrainedConfig = Any
|
||||
PreTrainedConfig = Any
|
||||
VllmConfig = Any
|
||||
|
||||
me_quant = LazyLoader(
|
||||
@@ -631,6 +631,8 @@ class SpeculativeConfig:
|
||||
"dspark",
|
||||
)
|
||||
factors.append(uses_aux_hidden_states)
|
||||
if self.method == "dspark":
|
||||
factors.append(self.enable_adaptive_verification)
|
||||
|
||||
if self.draft_model_config is not None:
|
||||
factors.append(self.draft_model_config.compute_hash())
|
||||
@@ -657,7 +659,7 @@ class SpeculativeConfig:
|
||||
return hash_str
|
||||
|
||||
@staticmethod
|
||||
def hf_config_override(hf_config: PretrainedConfig) -> PretrainedConfig:
|
||||
def hf_config_override(hf_config: PreTrainedConfig) -> PreTrainedConfig:
|
||||
initial_architecture = hf_config.architectures[0]
|
||||
use_v32_mtp = hf_config.model_type in ("deepseek_v32", "glm_moe_dsa")
|
||||
if hf_config.model_type == "dots3_note":
|
||||
@@ -694,8 +696,8 @@ class SpeculativeConfig:
|
||||
if hf_config.model_type in ("deepseek_v4", "deepseek_v41"):
|
||||
# V4.1 has no classic-MTP draft: its checkpoints ship DSpark stages
|
||||
# under ``mtp.*``, so only V4 gets an MTP architecture here. The
|
||||
# DSpark path rewrites ``architectures`` itself and needs only
|
||||
# ``n_predict``; ``method="mtp"`` on V4.1 is rejected below.
|
||||
# DSpark path rewrites ``architectures`` itself;
|
||||
# ``method="mtp"`` on V4.1 is rejected below.
|
||||
is_v41 = hf_config.model_type == "deepseek_v41"
|
||||
hf_config.model_type = "deepseek_mtp"
|
||||
n_predict = getattr(hf_config, "num_nextn_predict_layers", None)
|
||||
@@ -1066,16 +1068,16 @@ class SpeculativeConfig:
|
||||
|
||||
@staticmethod
|
||||
def _apply_composed_hf_override(
|
||||
target_hf_overrides: Callable[[PretrainedConfig], PretrainedConfig],
|
||||
hf_config: PretrainedConfig,
|
||||
) -> PretrainedConfig:
|
||||
target_hf_overrides: Callable[[PreTrainedConfig], PreTrainedConfig],
|
||||
hf_config: PreTrainedConfig,
|
||||
) -> PreTrainedConfig:
|
||||
hf_config = SpeculativeConfig.hf_config_override(hf_config)
|
||||
return target_hf_overrides(hf_config)
|
||||
|
||||
@staticmethod
|
||||
def compose_draft_hf_overrides(
|
||||
target_hf_overrides: HfOverrides | None,
|
||||
) -> Callable[[PretrainedConfig], PretrainedConfig]:
|
||||
) -> Callable[[PreTrainedConfig], PreTrainedConfig]:
|
||||
"""Build the ``hf_overrides`` for the draft ``ModelConfig``.
|
||||
|
||||
Callable overrides on the target are config-to-config transforms
|
||||
@@ -1440,14 +1442,6 @@ class SpeculativeConfig:
|
||||
draft_hf_config.architectures = [
|
||||
"DSparkV41DraftModel" if is_v41 else "DSparkDraftModel"
|
||||
]
|
||||
if is_v41:
|
||||
# hf_config_override set n_predict to the number of
|
||||
# MTP stages (3), but one DSpark round drafts
|
||||
# dspark_block_size tokens; num_speculative_tokens
|
||||
# divisibility is checked against n_predict below.
|
||||
draft_hf_config.n_predict = getattr(
|
||||
draft_hf_config, "dspark_block_size", None
|
||||
) or getattr(draft_hf_config, "n_predict", None)
|
||||
self.draft_model_config.quantization = (
|
||||
self.target_model_config.quantization
|
||||
)
|
||||
@@ -1464,11 +1458,6 @@ class SpeculativeConfig:
|
||||
and getattr(hf, "target_layer_ids", None) is not None
|
||||
):
|
||||
hf.dspark_target_layer_ids = hf.target_layer_ids
|
||||
if (
|
||||
getattr(hf, "n_predict", None) is None
|
||||
and getattr(hf, "block_size", None) is not None
|
||||
):
|
||||
hf.n_predict = hf.block_size
|
||||
|
||||
if self.method in ("dflash", "dspark"):
|
||||
self.parallel_drafting = True
|
||||
@@ -1483,7 +1472,15 @@ class SpeculativeConfig:
|
||||
n_predict = getattr(
|
||||
self.draft_model_config.hf_config, "n_predict", None
|
||||
)
|
||||
if n_predict is not None:
|
||||
if self.use_dspark():
|
||||
if self.num_speculative_tokens is None:
|
||||
# DSpark's parallel width is independent of MTP stages.
|
||||
hf_config = self.draft_model_config.hf_config
|
||||
block_size = getattr(hf_config, "block_size", None)
|
||||
if block_size is None:
|
||||
block_size = getattr(hf_config, "dspark_block_size", None)
|
||||
self.num_speculative_tokens = block_size
|
||||
elif n_predict is not None:
|
||||
if self.num_speculative_tokens is None:
|
||||
# Default to max value defined in draft model config.
|
||||
self.num_speculative_tokens = n_predict
|
||||
@@ -1672,7 +1669,7 @@ class SpeculativeConfig:
|
||||
|
||||
@staticmethod
|
||||
def _maybe_override_draft_max_position_embeddings(
|
||||
draft_hf_config: PretrainedConfig,
|
||||
draft_hf_config: PreTrainedConfig,
|
||||
target_max_model_len: int,
|
||||
) -> None:
|
||||
"""Raise an EAGLE draft's max_position_embeddings up to the target's.
|
||||
@@ -1709,7 +1706,7 @@ class SpeculativeConfig:
|
||||
def _verify_and_get_draft_tp(
|
||||
target_parallel_config: ParallelConfig,
|
||||
speculative_draft_tensor_parallel_size: int | None,
|
||||
draft_hf_config: PretrainedConfig,
|
||||
draft_hf_config: PreTrainedConfig,
|
||||
) -> int:
|
||||
"""Verifies and adjusts the tensor parallel size for a draft model
|
||||
specified using speculative_draft_tensor_parallel_size.
|
||||
|
||||
@@ -138,7 +138,7 @@ def getattr_iter(
|
||||
) -> Any:
|
||||
"""A helper function that retrieves an attribute from an object which may
|
||||
have multiple possible names. This is useful when fetching attributes from
|
||||
arbitrary `transformers.PretrainedConfig` instances.
|
||||
arbitrary `transformers.PreTrainedConfig` instances.
|
||||
|
||||
In the case where the first name in `names` is the preferred name, and
|
||||
any other names are deprecated aliases, setting `warn=True` will log a
|
||||
@@ -314,7 +314,7 @@ def normalize_value(x):
|
||||
except Exception:
|
||||
return str(x)
|
||||
|
||||
# PretrainedConfig (must be before dataclass branch as these are now dataclasses)
|
||||
# PreTrainedConfig (must be before dataclass branch as these are now dataclasses)
|
||||
if hasattr(x, "to_json_string") and callable(x.to_json_string):
|
||||
try:
|
||||
return x.to_json_string()
|
||||
|
||||
+154
-27
@@ -40,6 +40,7 @@ from .kernel import KernelConfig
|
||||
from .kv_events import KVEventsConfig
|
||||
from .kv_transfer import KVTransferConfig
|
||||
from .load import LoadConfig
|
||||
from .logging import LoggingConfig
|
||||
from .lora import LoRAConfig
|
||||
from .mamba import MambaBackendEnum, MambaConfig
|
||||
from .model import ModelConfig
|
||||
@@ -56,12 +57,12 @@ from .watermarking import WatermarkConfig
|
||||
from .weight_transfer import WeightTransferConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from transformers import PretrainedConfig
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
else:
|
||||
PretrainedConfig = Any
|
||||
PreTrainedConfig = Any
|
||||
|
||||
QuantizationConfig = Any
|
||||
|
||||
@@ -242,7 +243,7 @@ def enable_mla_dual_rms_norm_fusion(cfg: "VllmConfig") -> bool:
|
||||
|
||||
|
||||
def enable_qk_norm_rope_kvcache(cfg: "VllmConfig") -> bool:
|
||||
"""Enable fused QK-norm + RoPE + KV cache update on ROCm with AITER."""
|
||||
"""Enable fused QK-norm + RoPE/MRoPE + KV cache update with AITER."""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
if not rocm_aiter_ops.is_enabled():
|
||||
@@ -402,6 +403,8 @@ class VllmConfig:
|
||||
default_factory=ObservabilityConfig
|
||||
)
|
||||
"""Observability configuration."""
|
||||
logging_config: LoggingConfig = Field(default_factory=LoggingConfig)
|
||||
"""Logging configuration."""
|
||||
quant_config: QuantizationConfig | None = None
|
||||
"""Quantization configuration."""
|
||||
compilation_config: CompilationConfig = Field(default_factory=CompilationConfig)
|
||||
@@ -722,11 +725,23 @@ class VllmConfig:
|
||||
if model_config is not None and current_platform.is_rocm():
|
||||
architectures = getattr(model_config, "architectures", ())
|
||||
if any(arch in ROCM_DEFAULT_MRV1_ARCHITECTURES for arch in architectures):
|
||||
# This default is a speed preference, not a claim that V1 can
|
||||
# serve the config, so it yields where V1 cannot. It yields by
|
||||
# falling through to the checks below, not by selecting V2.
|
||||
v1_unsupported = self._get_v1_model_runner_unsupported_features()
|
||||
if not v1_unsupported:
|
||||
logger.warning_once(
|
||||
"Defaulting to V1 model runner on ROCm for model "
|
||||
"architectures: %s",
|
||||
", ".join(architectures),
|
||||
)
|
||||
return False
|
||||
logger.warning_once(
|
||||
"Defaulting to V1 model runner on ROCm for model architectures: %s",
|
||||
"Skipping the ROCm V1 model runner default for %s: V1 does "
|
||||
"not support %s.",
|
||||
", ".join(architectures),
|
||||
", ".join(v1_unsupported),
|
||||
)
|
||||
return False
|
||||
|
||||
if not HAS_TRITON:
|
||||
logger.warning_once(
|
||||
@@ -745,8 +760,8 @@ class VllmConfig:
|
||||
|
||||
return True
|
||||
|
||||
def _is_dflash2_draft(self) -> bool:
|
||||
"""Whether the DFlash draft is a DFlash2 one, by the architecture the
|
||||
def _is_dflash_candidate_draft(self) -> bool:
|
||||
"""Whether the DFlash draft has a candidate head, by the architecture the
|
||||
speculator selects on (v1/worker/gpu/spec_decode/__init__.py)."""
|
||||
spec = self.speculative_config
|
||||
if spec is None or spec.method != "dflash":
|
||||
@@ -754,7 +769,11 @@ class VllmConfig:
|
||||
draft_config = getattr(spec, "draft_model_config", None)
|
||||
if draft_config is None:
|
||||
return False
|
||||
return "DFlash2DraftModel" in (draft_config.architectures or [])
|
||||
return bool(
|
||||
{"DFlash2DraftModel", "LiLiCorrDraftModel"}.intersection(
|
||||
draft_config.architectures or []
|
||||
)
|
||||
)
|
||||
|
||||
def _dflash_needs_multi_kv_group(self) -> bool:
|
||||
"""Whether a DFlash draft mixes sliding-window and full attention."""
|
||||
@@ -776,6 +795,45 @@ class VllmConfig:
|
||||
architectures = set(model_config.architectures)
|
||||
return bool(architectures & default_breakable_cudagraph_architectures())
|
||||
|
||||
def _uses_breakable_cudagraph_for_batch_invariance(self) -> bool:
|
||||
"""Avoid freezing runtime-M tile lookup in compiled forward (#54243).
|
||||
Breakable graphs look up tuned bf16, unquantized qkv/o/gate_up/down tiles
|
||||
at capture; lm_head runs outside compiled forward and does not benefit."""
|
||||
from vllm.model_executor.determinism import batch_invariant_configs as bi
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
model = self.model_config
|
||||
if (
|
||||
not envs.VLLM_BATCH_INVARIANT
|
||||
or model is None
|
||||
or model.enforce_eager
|
||||
or model.dtype != torch.bfloat16
|
||||
or model.quantization is not None
|
||||
or not current_platform.is_cuda()
|
||||
# Sequence parallelism / async TP are torch.compile passes.
|
||||
or self.compilation_config.pass_config.enable_sp
|
||||
or self.compilation_config.pass_config.fuse_gemm_comms
|
||||
):
|
||||
return False
|
||||
family = bi._get_tuned_matmul_arch_family(
|
||||
current_platform.get_device_capability()
|
||||
)
|
||||
if family is None or family not in bi._BATCH_INVARIANT_MATMUL_TUNED_CONFIGS:
|
||||
return False
|
||||
table = bi._BATCH_INVARIANT_MATMUL_TUNED_CONFIGS[family]
|
||||
parallel = self.parallel_config
|
||||
tp = parallel.tensor_parallel_size
|
||||
hidden = model.get_hidden_size()
|
||||
head = model.get_head_size()
|
||||
heads = model.get_num_attention_heads(parallel)
|
||||
kv_heads = model.get_num_kv_heads(parallel)
|
||||
shapes = [((heads + 2 * kv_heads) * head, hidden), (hidden, heads * head)]
|
||||
intermediate = getattr(model.hf_text_config, "intermediate_size", None)
|
||||
# Per-layer sizes (e.g. Gemma3n) are not modeled.
|
||||
if isinstance(intermediate, int):
|
||||
shapes += [(2 * intermediate // tp, hidden), (hidden, intermediate // tp)]
|
||||
return any(shape in table for shape in shapes)
|
||||
|
||||
def _maybe_enable_breakable_cudagraph(self) -> bool:
|
||||
if (
|
||||
"VLLM_USE_BREAKABLE_CUDAGRAPH" not in os.environ
|
||||
@@ -786,6 +844,16 @@ class VllmConfig:
|
||||
"Auto-enabling VLLM_USE_BREAKABLE_CUDAGRAPH=1. "
|
||||
"Set VLLM_USE_BREAKABLE_CUDAGRAPH=0 to opt out."
|
||||
)
|
||||
elif (
|
||||
"VLLM_USE_BREAKABLE_CUDAGRAPH" not in os.environ
|
||||
and envs.VLLM_BATCH_INVARIANT
|
||||
and self._uses_breakable_cudagraph_for_batch_invariance()
|
||||
):
|
||||
os.environ["VLLM_USE_BREAKABLE_CUDAGRAPH"] = "1"
|
||||
logger.info_once(
|
||||
"VLLM_BATCH_INVARIANT=1: auto-enabling VLLM_USE_BREAKABLE_CUDAGRAPH=1. "
|
||||
"Set VLLM_USE_BREAKABLE_CUDAGRAPH=0 to opt out."
|
||||
)
|
||||
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
is_breakable_cudagraph_enabled,
|
||||
@@ -890,7 +958,7 @@ class VllmConfig:
|
||||
|
||||
def with_hf_config(
|
||||
self,
|
||||
hf_config: PretrainedConfig,
|
||||
hf_config: PreTrainedConfig,
|
||||
architectures: list[str] | None = None,
|
||||
) -> "VllmConfig":
|
||||
if architectures is not None:
|
||||
@@ -943,6 +1011,7 @@ class VllmConfig:
|
||||
|
||||
model_config.hf_config = hf_config
|
||||
model_config.model_arch_config = model_config.get_model_arch_config()
|
||||
model_config.is_submodel_config = True
|
||||
|
||||
return replace(self, model_config=model_config)
|
||||
|
||||
@@ -1092,7 +1161,14 @@ class VllmConfig:
|
||||
"""Reject configurations unsupported by enabled auxiliary outputs."""
|
||||
if not self.aux_output_config.enabled:
|
||||
return
|
||||
if not self.use_v2_model_runner:
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# In-tree platforms only wire AuxOutput to MRV2. TPU and out-of-tree
|
||||
# platforms bring their own model runners and validate AuxOutput
|
||||
# support themselves.
|
||||
if not self.use_v2_model_runner and not (
|
||||
current_platform.is_tpu() or current_platform.is_out_of_tree()
|
||||
):
|
||||
raise ValueError(
|
||||
"AuxOutput Connector requires Model Runner V2; set "
|
||||
"VLLM_USE_V2_MODEL_RUNNER=1."
|
||||
@@ -1331,8 +1407,27 @@ class VllmConfig:
|
||||
# To give each torch profile run a unique instance name.
|
||||
self.instance_id = f"{time.time_ns()}"
|
||||
|
||||
if self.model_config is not None and self.model_config.is_submodel_config:
|
||||
# with_hf_config() view: the parent config was already validated,
|
||||
# and this view's empty architecture list makes the model-dependent checks
|
||||
# below unsafe (e.g. use_mla resolves the architecture registry).
|
||||
return
|
||||
|
||||
self._resolve_mm_encoder_only()
|
||||
|
||||
if self.is_mm_encoder_only and self.cache_config.enable_prefix_caching:
|
||||
# Such an instance publishes encoder embeddings and runs no language
|
||||
# model, so it holds no KV cache for prefix caching to reuse and its
|
||||
# coordinator would have no group to manage. Disable before
|
||||
# `try_verify_and_update_config` so model config hooks (e.g. the
|
||||
# hybrid mamba hook setting `mamba_block_size`) already see prefix
|
||||
# caching as disabled.
|
||||
logger.info(
|
||||
"Disabling prefix caching: this instance runs the "
|
||||
"multi-modal encoder only."
|
||||
)
|
||||
self.cache_config.enable_prefix_caching = False
|
||||
|
||||
if self.performance_mode != "balanced":
|
||||
logger.info_once("Performance mode set to '%s'.", self.performance_mode)
|
||||
|
||||
@@ -1597,12 +1692,24 @@ class VllmConfig:
|
||||
)
|
||||
|
||||
if self.model_config is not None and self.model_config.enforce_eager:
|
||||
logger.warning_once(
|
||||
"Enforce eager set, disabling torch.compile and CUDAGraphs. "
|
||||
"This is equivalent to setting -cc.mode=none -cc.cudagraph_mode=none"
|
||||
)
|
||||
self.compilation_config.mode = CompilationMode.NONE
|
||||
self.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
if self.parallel_config.enable_fault_tolerance:
|
||||
# Keep JIT warmup: in-inference Triton compilation latency
|
||||
# spikes can delay peer-fault detection past its deadline.
|
||||
logger.warning_once(
|
||||
"Enforce eager set, disabling torch.compile and CUDAGraphs. "
|
||||
"This is equivalent to setting -cc.mode=none "
|
||||
"-cc.cudagraph_mode=none"
|
||||
)
|
||||
else:
|
||||
logger.warning_once(
|
||||
"Enforce eager set, disabling torch.compile, CUDAGraphs, and "
|
||||
"JIT kernel warmup. This is equivalent to setting "
|
||||
"-cc.mode=none -cc.cudagraph_mode=none and "
|
||||
"--kernel_config.enable_jit_warmup=False"
|
||||
)
|
||||
self.kernel_config.enable_jit_warmup = False
|
||||
|
||||
if os.environ.get("TORCH_COMPILE_DISABLE") == "1":
|
||||
logger.warning_once(
|
||||
@@ -1611,6 +1718,26 @@ class VllmConfig:
|
||||
)
|
||||
self.compilation_config.mode = CompilationMode.NONE
|
||||
|
||||
# TODO: This is a stopgap that turns sequence parallelism / async TP
|
||||
# off under batch invariance. Make the sequence-parallel reduce-scatter
|
||||
# path batch-invariant instead so they can stay enabled (#56370).
|
||||
# Sequence parallelism / async TP rewrite all_reduce + rms_norm into a
|
||||
# reduce-scatter whose reduction order depends on the batch, so they
|
||||
# are not batch-invariant. Decide this before the breakable-CUDA-graph
|
||||
# default below, which declines to auto-enable when they are on.
|
||||
pass_config = self.compilation_config.pass_config
|
||||
if envs.VLLM_BATCH_INVARIANT and (
|
||||
pass_config.enable_sp or pass_config.fuse_gemm_comms
|
||||
):
|
||||
logger.warning_once(
|
||||
"Disabling sequence parallelism and async TP "
|
||||
"(pass_config.enable_sp / fuse_gemm_comms) when "
|
||||
"VLLM_BATCH_INVARIANT is enabled: the reduce-scatter path "
|
||||
"is not batch-invariant (see vllm-project/vllm#56370)."
|
||||
)
|
||||
pass_config.enable_sp = False
|
||||
pass_config.fuse_gemm_comms = False
|
||||
|
||||
breakable_cudagraph_enabled = self._maybe_enable_breakable_cudagraph()
|
||||
|
||||
if not breakable_cudagraph_enabled and (
|
||||
@@ -1894,6 +2021,16 @@ class VllmConfig:
|
||||
)
|
||||
current_platform.check_and_update_config(self)
|
||||
|
||||
# After the platform hook, which has the last word on async scheduling.
|
||||
if (
|
||||
self.diffusion_config is not None
|
||||
and self.scheduler_config.async_scheduling
|
||||
and self.scheduler_config.scheduler_cls is None
|
||||
):
|
||||
self.scheduler_config.scheduler_cls = (
|
||||
"vllm.v1.core.sched.diffusion_scheduler.DiffusionAsyncScheduler"
|
||||
)
|
||||
|
||||
self._normalize_piecewise_cudagraph_mode(
|
||||
breakable_cudagraph_enabled=breakable_cudagraph_enabled
|
||||
)
|
||||
@@ -2069,16 +2206,6 @@ class VllmConfig:
|
||||
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
|
||||
# model, so it holds no KV cache for prefix caching to reuse and its
|
||||
# coordinator would have no group to manage.
|
||||
logger.info(
|
||||
"Disabling prefix caching: this instance runs the "
|
||||
"multi-modal encoder only."
|
||||
)
|
||||
self.cache_config.enable_prefix_caching = False
|
||||
|
||||
# Hybrid KV cache manager (HMA) runtime rules:
|
||||
# - Explicit enable (--no-disable-kv-cache-manager): error if runtime
|
||||
# disables it
|
||||
@@ -3001,11 +3128,11 @@ class VllmConfig:
|
||||
if self._dflash_needs_multi_kv_group():
|
||||
unsupported.append("mixed sliding/full dflash drafts")
|
||||
|
||||
# The DFlash2 candidate selector exists only in the V2 speculator. On
|
||||
# DFlash candidate heads exist only in the V2 speculator. On
|
||||
# V1 the same checkpoint drafts through DFlashProposer, which never
|
||||
# calls it, so the draft would degrade to DFlash1 silently.
|
||||
if self._is_dflash2_draft():
|
||||
unsupported.append("dflash2 drafts")
|
||||
if self._is_dflash_candidate_draft():
|
||||
unsupported.append("DFlash candidate-head drafts")
|
||||
|
||||
if self.model_config is not None and self.model_config.is_diffusion:
|
||||
unsupported.append("diffusion models")
|
||||
|
||||
@@ -9,7 +9,9 @@ from vllm.config.utils import config
|
||||
class WeightTransferConfig:
|
||||
"""Configuration for weight transfer during RL training."""
|
||||
|
||||
backend: Literal["nccl", "ipc", "sparse_nccl", "sharded_rdt"] | str = "nccl"
|
||||
backend: Literal["nccl", "ipc", "sparse_nccl", "sharded_rdt", "nccl_m2n"] | str = (
|
||||
"nccl"
|
||||
)
|
||||
"""The backend to use for weight transfer. Validated against the
|
||||
`WeightTransferEngineFactory` registry at engine creation time.
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Helpers for reading and editing PyTorch's allocator configuration.
|
||||
|
||||
Torch's allocator config is parsed as a whole: ``parseArgs`` resets every
|
||||
option that is not explicitly present in the string it is handed. Writing a
|
||||
single field therefore silently drops the rest of the user's configuration,
|
||||
for the remainder of the process:
|
||||
|
||||
>>> # PYTORCH_ALLOC_CONF=expandable_segments:True,max_split_size_mb:512
|
||||
>>> torch._C._accelerator_setAllocatorSettings("expandable_segments:False")
|
||||
>>> # max_split_size is now SIZE_MAX, not 512 MiB -- and writing
|
||||
>>> # "expandable_segments:True" back does not bring it home either.
|
||||
|
||||
So anything that wants to toggle one option has to read the current config,
|
||||
flip just that field, and write the whole string back.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
# Checked in torch's own precedence order: the accelerator-agnostic variable
|
||||
# wins, then the CUDA one, then the HIP one (which is what ROCm users set).
|
||||
ALLOC_CONF_ENV_VARS = (
|
||||
"PYTORCH_ALLOC_CONF",
|
||||
"PYTORCH_CUDA_ALLOC_CONF",
|
||||
"PYTORCH_HIP_ALLOC_CONF",
|
||||
)
|
||||
|
||||
EXPANDABLE_SEGMENTS = "expandable_segments"
|
||||
|
||||
|
||||
def alloc_conf_from_env(
|
||||
environ: "os._Environ[str] | dict[str, str] | None" = None,
|
||||
) -> str:
|
||||
"""The allocator config string the process was started with, if any."""
|
||||
env = os.environ if environ is None else environ
|
||||
for name in ALLOC_CONF_ENV_VARS:
|
||||
conf = env.get(name)
|
||||
if conf:
|
||||
return conf
|
||||
return ""
|
||||
|
||||
|
||||
def live_alloc_conf() -> str | None:
|
||||
"""The allocator config string currently in effect, or ``None``.
|
||||
|
||||
Read from the live allocator rather than the environment, so that a
|
||||
*runtime* write by another component is visible.
|
||||
"""
|
||||
try:
|
||||
settings = torch.cuda.memory._snapshot().get("allocator_settings")
|
||||
if settings is not None:
|
||||
for name in ALLOC_CONF_ENV_VARS:
|
||||
conf = settings.get(name)
|
||||
if conf is not None:
|
||||
return conf
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def current_alloc_conf() -> str:
|
||||
"""The live allocator config, falling back to the environment."""
|
||||
live = live_alloc_conf()
|
||||
return live if live is not None else alloc_conf_from_env()
|
||||
|
||||
|
||||
def conf_flag_enabled(conf: str, key: str) -> bool:
|
||||
"""Parse ``<key>:<bool>`` out of an allocator config string."""
|
||||
for field in conf.split(","):
|
||||
name, _, value = field.partition(":")
|
||||
if name.strip() == key:
|
||||
return value.strip().lower() in ("true", "1")
|
||||
return False
|
||||
|
||||
|
||||
def with_conf_flag(conf: str, key: str, enabled: bool) -> str:
|
||||
"""Return ``conf`` with only ``key`` flipped, every other field verbatim."""
|
||||
want = f"{key}:{'True' if enabled else 'False'}"
|
||||
fields = [f for f in (f.strip() for f in conf.split(",")) if f]
|
||||
for i, field in enumerate(fields):
|
||||
if field.partition(":")[0].strip() == key:
|
||||
fields[i] = want
|
||||
return ",".join(fields)
|
||||
fields.append(want)
|
||||
return ",".join(fields)
|
||||
|
||||
|
||||
def expandable_segments_enabled_from_env(
|
||||
environ: "os._Environ[str] | dict[str, str] | None" = None,
|
||||
) -> bool:
|
||||
return conf_flag_enabled(alloc_conf_from_env(environ), EXPANDABLE_SEGMENTS)
|
||||
|
||||
|
||||
def expandable_segments_enabled() -> bool | None:
|
||||
"""Live ``expandable_segments`` state, or ``None`` if it cannot be read.
|
||||
|
||||
``None`` is deliberately distinct from ``False``: the environment can never
|
||||
reflect a runtime write, so a caller verifying a write it just issued must
|
||||
not read "cannot tell" as "the write did not take".
|
||||
"""
|
||||
try:
|
||||
settings = torch.cuda.memory._snapshot().get("allocator_settings")
|
||||
if settings is not None and EXPANDABLE_SEGMENTS in settings:
|
||||
return bool(settings[EXPANDABLE_SEGMENTS])
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def set_alloc_conf(conf: str) -> None:
|
||||
"""Write a complete allocator config string."""
|
||||
setter = getattr(torch._C, "_accelerator_setAllocatorSettings", None)
|
||||
if setter is not None:
|
||||
setter(conf)
|
||||
return
|
||||
torch.cuda.memory._set_allocator_settings(conf)
|
||||
@@ -10,7 +10,6 @@
|
||||
# the only successful approach is to call cuda driver API in C.
|
||||
import atexit
|
||||
import gc
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
@@ -18,6 +17,13 @@ from typing import Any
|
||||
import torch
|
||||
|
||||
from vllm.device_allocator import AllocationData, HandleType
|
||||
from vllm.device_allocator.alloc_conf import (
|
||||
EXPANDABLE_SEGMENTS,
|
||||
conf_flag_enabled,
|
||||
current_alloc_conf,
|
||||
set_alloc_conf,
|
||||
with_conf_flag,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.system_utils import find_loaded_library
|
||||
@@ -371,13 +377,17 @@ class CuMemAllocator:
|
||||
|
||||
# Expandable segments are incompatible with the memory pool used for
|
||||
# sleep mode (see https://github.com/pytorch/pytorch/issues/147851).
|
||||
# If the user has enabled expandable segments via
|
||||
# PYTORCH_CUDA_ALLOC_CONF, temporarily disable them for the duration
|
||||
# of the memory pool context and restore on exit.
|
||||
conf = os.environ.get("PYTORCH_CUDA_ALLOC_CONF", "")
|
||||
expandable_was_enabled = "expandable_segments:True" in conf
|
||||
# If the user has enabled expandable segments, temporarily disable
|
||||
# them for the duration of the memory pool context and restore on
|
||||
# exit. The whole config string is rewritten, not just this one
|
||||
# field: torch resets every option that is absent from the string it
|
||||
# is handed, so a bare "expandable_segments:False" would also drop
|
||||
# max_split_size_mb, garbage_collection_threshold and
|
||||
# roundup_power2_divisions for the rest of the process.
|
||||
prev_conf = current_alloc_conf()
|
||||
expandable_was_enabled = conf_flag_enabled(prev_conf, EXPANDABLE_SEGMENTS)
|
||||
if expandable_was_enabled:
|
||||
torch.cuda.memory._set_allocator_settings("expandable_segments:False")
|
||||
set_alloc_conf(with_conf_flag(prev_conf, EXPANDABLE_SEGMENTS, False))
|
||||
|
||||
old_tag = self.current_tag
|
||||
self.current_tag = tag
|
||||
@@ -411,7 +421,7 @@ class CuMemAllocator:
|
||||
finally:
|
||||
self.current_tag = old_tag
|
||||
if expandable_was_enabled:
|
||||
torch.cuda.memory._set_allocator_settings("expandable_segments:True")
|
||||
set_alloc_conf(prev_conf)
|
||||
|
||||
def get_current_usage(self) -> int:
|
||||
"""Get the total number of bytes allocated in the memory pool."""
|
||||
|
||||
@@ -56,11 +56,17 @@ class AgRsAll2AllManager(All2AllManagerBase):
|
||||
|
||||
def __init__(self, cpu_group, tcp_store_group=None):
|
||||
super().__init__(cpu_group, tcp_store_group)
|
||||
self.use_ep = get_current_vllm_config().parallel_config.enable_expert_parallel
|
||||
|
||||
def _get_comm_group(self, is_sequence_parallel: bool) -> Any:
|
||||
if is_sequence_parallel:
|
||||
return get_ep_group()
|
||||
if self.dp_world_size > 1:
|
||||
if self.use_ep and get_pcp_group().world_size > 1:
|
||||
assert self.tp_group.world_size == 1, (
|
||||
"DP+PCP with TP>1 requires sequence-parallel MoE inputs"
|
||||
)
|
||||
return get_ep_group()
|
||||
return get_dp_group()
|
||||
return get_pcp_group()
|
||||
|
||||
@@ -72,6 +78,7 @@ class AgRsAll2AllManager(All2AllManagerBase):
|
||||
assert dp_metadata is not None
|
||||
sizes = dp_metadata.get_chunk_sizes_across_dp_rank()
|
||||
assert sizes is not None
|
||||
assert len(sizes) == comm_group.world_size
|
||||
return sizes
|
||||
|
||||
def dispatch_router_logits(
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from contextlib import contextmanager
|
||||
from typing import cast
|
||||
from typing import Literal, cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -32,6 +32,9 @@ except ImportError:
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_ReduceScatterBackend = Literal["legacy", "mnnvl_lamport", "mnnvl_multimem"]
|
||||
_MNNVL_MULTIMEM_REDUCE_SCATTER_WORLD_SIZES = (2, 4, 8)
|
||||
|
||||
|
||||
def _has_local_multicast_support(device: torch.device) -> bool:
|
||||
"""Return whether this CUDA device can allocate multicast memory."""
|
||||
@@ -53,6 +56,12 @@ def _has_local_multicast_support(device: torch.device) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _all_ranks_true(group: ProcessGroup, local_value: bool) -> bool:
|
||||
group_value = torch.tensor(int(local_value), dtype=torch.int32, device="cpu")
|
||||
dist.all_reduce(group_value, op=dist.ReduceOp.MIN, group=group)
|
||||
return bool(group_value.item())
|
||||
|
||||
|
||||
def _group_can_attempt_mnnvl(
|
||||
group: ProcessGroup,
|
||||
device: torch.device,
|
||||
@@ -71,17 +80,7 @@ def _group_can_attempt_mnnvl(
|
||||
and current_platform.has_device_capability(100, device_index)
|
||||
and _has_local_multicast_support(device)
|
||||
)
|
||||
group_support = torch.tensor(
|
||||
int(local_support),
|
||||
dtype=torch.int32,
|
||||
device="cpu",
|
||||
)
|
||||
dist.all_reduce(
|
||||
group_support,
|
||||
op=dist.ReduceOp.MIN,
|
||||
group=group,
|
||||
)
|
||||
return bool(group_support.item())
|
||||
return _all_ranks_true(group, local_support)
|
||||
|
||||
|
||||
def _can_p2p(rank: int, world_size: int) -> bool:
|
||||
@@ -101,6 +100,20 @@ def _can_p2p(rank: int, world_size: int) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _supports_mnnvl_multimem_reduce_scatter(
|
||||
device: torch.device, world_size: int
|
||||
) -> bool:
|
||||
return (
|
||||
world_size in _MNNVL_MULTIMEM_REDUCE_SCATTER_WORLD_SIZES
|
||||
and device.index is not None
|
||||
and (
|
||||
current_platform.is_device_capability((10, 0), device.index)
|
||||
or current_platform.is_device_capability((10, 3), device.index)
|
||||
)
|
||||
and _has_local_multicast_support(device)
|
||||
)
|
||||
|
||||
|
||||
from vllm.distributed.utils import is_weak_contiguous # noqa: E402
|
||||
|
||||
|
||||
@@ -116,6 +129,8 @@ class CustomAllreduce:
|
||||
}
|
||||
_DEFAULT_REDUCE_SCATTER_MAX_SIZE = 16 * 1024 * 1024
|
||||
_DEFAULT_MNNVL_REDUCE_SCATTER_MAX_SIZE = 16 * 1024 * 1024
|
||||
_DEFAULT_MNNVL_MULTIMEM_REDUCE_SCATTER_MAX_SIZE = 64 * 1024 * 1024
|
||||
_MNNVL_MULTIMEM_REDUCE_SCATTER_BLOCKS = 8
|
||||
|
||||
# max_size: max supported allreduce size
|
||||
def __init__(
|
||||
@@ -127,6 +142,9 @@ class CustomAllreduce:
|
||||
max_mnnvl_all_gather_size=None,
|
||||
max_reduce_scatter_size=_DEFAULT_REDUCE_SCATTER_MAX_SIZE,
|
||||
max_mnnvl_reduce_scatter_size=_DEFAULT_MNNVL_REDUCE_SCATTER_MAX_SIZE,
|
||||
max_mnnvl_multimem_reduce_scatter_size=(
|
||||
_DEFAULT_MNNVL_MULTIMEM_REDUCE_SCATTER_MAX_SIZE
|
||||
),
|
||||
symm_mem_enabled=False,
|
||||
) -> None:
|
||||
"""Args:
|
||||
@@ -153,6 +171,13 @@ class CustomAllreduce:
|
||||
self.mnnvl_lamport_epochs = None
|
||||
self.mnnvl_lamport_ag_epoch_ptr = 0
|
||||
self.mnnvl_lamport_rs_epoch_ptr = 0
|
||||
self.mnnvl_multimem_rs_supported = False
|
||||
self.mnnvl_multimem_rs_initialized = False
|
||||
self.mnnvl_multimem_rs_buffer = None
|
||||
self.mnnvl_multimem_rs_handle = None
|
||||
self.mnnvl_multimem_rs_buffer_size = 0
|
||||
self.mnnvl_multimem_rs_local_ptr = 0
|
||||
self.mnnvl_multimem_rs_multicast_ptr = 0
|
||||
self.mnnvl_only = False
|
||||
|
||||
if not custom_ar:
|
||||
@@ -197,6 +222,9 @@ class CustomAllreduce:
|
||||
# now `device` is a `torch.device` object
|
||||
assert isinstance(device, torch.device)
|
||||
self.device = device
|
||||
mnnvl_multimem_rs_supported = _supports_mnnvl_multimem_reduce_scatter(
|
||||
device, world_size
|
||||
)
|
||||
if not same_node and not _group_can_attempt_mnnvl(group, device):
|
||||
logger.warning(
|
||||
"Custom collectives are disabled because this multi-node "
|
||||
@@ -294,6 +322,9 @@ class CustomAllreduce:
|
||||
self.max_mnnvl_all_gather_size = max_mnnvl_all_gather_size
|
||||
self.max_reduce_scatter_size = max_reduce_scatter_size
|
||||
self.max_mnnvl_reduce_scatter_size = max_mnnvl_reduce_scatter_size
|
||||
self.max_mnnvl_multimem_reduce_scatter_size = (
|
||||
max_mnnvl_multimem_reduce_scatter_size
|
||||
)
|
||||
self.rank = rank
|
||||
self.world_size = world_size
|
||||
self.fully_connected = fully_connected
|
||||
@@ -307,6 +338,11 @@ class CustomAllreduce:
|
||||
max_mnnvl_reduce_scatter_size,
|
||||
)
|
||||
)
|
||||
if world_size in _MNNVL_MULTIMEM_REDUCE_SCATTER_WORLD_SIZES:
|
||||
self.mnnvl_multimem_rs_supported = _all_ranks_true(
|
||||
self.group,
|
||||
mnnvl_multimem_rs_supported and bool(self.mnnvl_multicast_ptr),
|
||||
)
|
||||
if not same_node and not self.mnnvl_multicast_ptr:
|
||||
logger.warning(
|
||||
"Custom collectives are disabled because this multi-node "
|
||||
@@ -368,6 +404,59 @@ class CustomAllreduce:
|
||||
except RuntimeError as error:
|
||||
logger.debug("MNNVL AG/RS initialization failed: %s", error)
|
||||
|
||||
def _init_mnnvl_multimem_reduce_scatter_buffer(self) -> None:
|
||||
if self.mnnvl_multimem_rs_initialized:
|
||||
return
|
||||
self.mnnvl_multimem_rs_initialized = True
|
||||
if not self.mnnvl_multimem_rs_supported:
|
||||
return
|
||||
|
||||
assert torch_symm_mem is not None
|
||||
buffer = None
|
||||
signal_size = ops.meta_size()
|
||||
try:
|
||||
buffer = torch_symm_mem.empty(
|
||||
signal_size + self.max_mnnvl_multimem_reduce_scatter_size,
|
||||
dtype=torch.uint8,
|
||||
device=self.device,
|
||||
)
|
||||
except RuntimeError as error:
|
||||
logger.debug("MNNVL multimem RS allocation failed: %s", error)
|
||||
if not _all_ranks_true(self.group, buffer is not None):
|
||||
logger.warning_once(
|
||||
"MNNVL multimem reduce-scatter symmetric-memory allocation "
|
||||
"failed on at least one rank; falling back to NCCL.",
|
||||
scope="global",
|
||||
)
|
||||
return
|
||||
assert buffer is not None
|
||||
|
||||
handle = None
|
||||
try:
|
||||
handle = torch_symm_mem.rendezvous(buffer, self.group.group_name)
|
||||
if handle is not None:
|
||||
buffer[:signal_size].zero_()
|
||||
torch.accelerator.synchronize()
|
||||
except RuntimeError as error:
|
||||
logger.debug("MNNVL multimem RS rendezvous failed: %s", error)
|
||||
if not _all_ranks_true(
|
||||
self.group,
|
||||
handle is not None and bool(handle.multicast_ptr),
|
||||
):
|
||||
logger.warning_once(
|
||||
"MNNVL multimem reduce-scatter symmetric-memory rendezvous "
|
||||
"failed on at least one rank; falling back to NCCL.",
|
||||
scope="global",
|
||||
)
|
||||
return
|
||||
assert handle is not None
|
||||
|
||||
self.mnnvl_multimem_rs_buffer = buffer
|
||||
self.mnnvl_multimem_rs_handle = handle
|
||||
self.mnnvl_multimem_rs_buffer_size = self.max_mnnvl_multimem_reduce_scatter_size
|
||||
self.mnnvl_multimem_rs_local_ptr = buffer.data_ptr() + signal_size
|
||||
self.mnnvl_multimem_rs_multicast_ptr = handle.multicast_ptr + signal_size
|
||||
|
||||
@contextmanager
|
||||
def capture(self):
|
||||
"""The main responsibility of this context manager is the
|
||||
@@ -509,35 +598,77 @@ class CustomAllreduce:
|
||||
)
|
||||
return out
|
||||
|
||||
def should_custom_reduce_scatter(self, inp: torch.Tensor) -> bool:
|
||||
def _select_reduce_scatter_backend(
|
||||
self, inp: torch.Tensor
|
||||
) -> _ReduceScatterBackend | None:
|
||||
if self.disabled or not current_platform.is_cuda():
|
||||
return False
|
||||
return None
|
||||
if self.world_size == 16 and not self.mnnvl_only:
|
||||
return False
|
||||
return None
|
||||
inp_size = inp.nbytes
|
||||
if inp.dtype not in (torch.float32, torch.float16, torch.bfloat16):
|
||||
return False
|
||||
return None
|
||||
if inp.shape[0] % self.world_size != 0:
|
||||
return False
|
||||
return None
|
||||
output_size = inp_size // self.world_size
|
||||
max_size = (
|
||||
self.max_mnnvl_reduce_scatter_size
|
||||
if self.mnnvl_multicast_ptr
|
||||
else self.max_reduce_scatter_size
|
||||
)
|
||||
return (
|
||||
0 < inp_size <= max_size
|
||||
and output_size % 16 == 0
|
||||
and is_weak_contiguous(inp)
|
||||
and (self.fully_connected or bool(self.mnnvl_multicast_ptr))
|
||||
)
|
||||
if inp_size <= 0 or output_size % 16 != 0 or not is_weak_contiguous(inp):
|
||||
return None
|
||||
|
||||
if self.mnnvl_multicast_ptr:
|
||||
if inp_size <= self.max_mnnvl_reduce_scatter_size:
|
||||
return "mnnvl_lamport"
|
||||
if (
|
||||
(
|
||||
self.mnnvl_multimem_rs_multicast_ptr
|
||||
or (
|
||||
self.mnnvl_multimem_rs_supported
|
||||
and not self.mnnvl_multimem_rs_initialized
|
||||
)
|
||||
)
|
||||
and not envs.VLLM_BATCH_INVARIANT
|
||||
and inp_size <= self.max_mnnvl_multimem_reduce_scatter_size
|
||||
):
|
||||
return "mnnvl_multimem"
|
||||
return None
|
||||
|
||||
if self.fully_connected and inp_size <= self.max_reduce_scatter_size:
|
||||
return "legacy"
|
||||
return None
|
||||
|
||||
def should_custom_reduce_scatter(self, inp: torch.Tensor) -> bool:
|
||||
return self._select_reduce_scatter_backend(inp) is not None
|
||||
|
||||
def should_mnnvl_multimem_reduce_scatter(self, inp: torch.Tensor) -> bool:
|
||||
return self._select_reduce_scatter_backend(inp) == "mnnvl_multimem"
|
||||
|
||||
def custom_reduce_scatter(self, inp: torch.Tensor) -> torch.Tensor | None:
|
||||
if not self.should_custom_reduce_scatter(inp):
|
||||
backend = self._select_reduce_scatter_backend(inp)
|
||||
if backend is None:
|
||||
return None
|
||||
if backend == "mnnvl_multimem" and not self.mnnvl_multimem_rs_multicast_ptr:
|
||||
if self._IS_CAPTURING:
|
||||
return None
|
||||
self._init_mnnvl_multimem_reduce_scatter_buffer()
|
||||
if not self.mnnvl_multimem_rs_multicast_ptr:
|
||||
return None
|
||||
|
||||
out_shape = (inp.shape[0] // self.world_size,) + inp.shape[1:]
|
||||
out = torch.empty(out_shape, dtype=inp.dtype, device=inp.device)
|
||||
if self.mnnvl_multicast_ptr:
|
||||
if backend == "mnnvl_multimem":
|
||||
logger.info_once(
|
||||
"Using the low-SM MNNVL multimem reduce-scatter kernel.",
|
||||
scope="global",
|
||||
)
|
||||
ops.mnnvl_multimem_reduce_scatter(
|
||||
self._ptr,
|
||||
inp,
|
||||
out,
|
||||
self.mnnvl_multimem_rs_local_ptr,
|
||||
self.mnnvl_multimem_rs_multicast_ptr,
|
||||
self.mnnvl_multimem_rs_buffer_size,
|
||||
self._MNNVL_MULTIMEM_REDUCE_SCATTER_BLOCKS,
|
||||
)
|
||||
elif backend == "mnnvl_lamport":
|
||||
logger.info_once(
|
||||
"Using the MNNVL Lamport reduce-scatter kernel.",
|
||||
scope="global",
|
||||
@@ -571,6 +702,8 @@ class CustomAllreduce:
|
||||
self.mnnvl_handle = None
|
||||
self.mnnvl_buffer = None
|
||||
self.mnnvl_lamport_epochs = None
|
||||
self.mnnvl_multimem_rs_handle = None
|
||||
self.mnnvl_multimem_rs_buffer = None
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import atexit
|
||||
import contextlib
|
||||
import logging
|
||||
import tempfile
|
||||
from typing import Any
|
||||
|
||||
@@ -83,7 +84,7 @@ def compile_nccl_allocator():
|
||||
cpp_sources=nccl_allocator_source,
|
||||
with_cuda=True,
|
||||
extra_ldflags=ldflags,
|
||||
verbose=envs.VLLM_LOGGING_LEVEL == "DEBUG",
|
||||
verbose=logger.isEnabledFor(logging.DEBUG),
|
||||
is_python_module=False,
|
||||
build_directory=out_dir,
|
||||
extra_include_paths=nccl_include_paths,
|
||||
|
||||
@@ -60,24 +60,26 @@ def collect_ec_item_metadata(
|
||||
|
||||
Keyed by mm_hash, each entry carries a `metadata` dict with whatever
|
||||
placeholder fields `resolver` says this model needs published for its
|
||||
modality, so a consumer can skip the image transform. `item_indices`
|
||||
modality, so a consumer can skip media preprocessing. `item_indices`
|
||||
identifies every occurrence in `mm_features`, including repeated hashes.
|
||||
`data` is None for items served from the processor cache, so the metadata is
|
||||
unavailable here and the consumer has to fall back to processing the
|
||||
media itself. A connector that also has transfer coordinates to report
|
||||
Audio token counts come from the placeholder; other metadata requires
|
||||
`data` and falls back to raw media when it is unavailable on cache hits.
|
||||
A connector that also has transfer coordinates to report
|
||||
(e.g. NIXL peer_host/peer_port/size_bytes) merges those in alongside
|
||||
`metadata`, not into it.
|
||||
"""
|
||||
items: dict[str, dict[str, Any]] = {}
|
||||
for index, feature in enumerate(mm_features):
|
||||
metadata: dict[str, Any] = {}
|
||||
wanted = resolver.fields_for(feature.modality)
|
||||
if "audio_num_tokens" in wanted:
|
||||
metadata["audio_num_tokens"] = [feature.mm_position.get_num_embeds()]
|
||||
if feature.data is not None:
|
||||
wanted = resolver.fields_for(feature.modality)
|
||||
for key, value in feature.data.get_data().items():
|
||||
if key not in wanted:
|
||||
continue
|
||||
if isinstance(value, torch.Tensor):
|
||||
metadata[key] = value.tolist()
|
||||
metadata[key] = torch.atleast_1d(value).tolist()
|
||||
elif is_list_of(value, (int, float)):
|
||||
# Some metadata (e.g. Qwen3-VL video timestamps) is
|
||||
# produced as a plain list rather than a tensor.
|
||||
|
||||
@@ -550,10 +550,7 @@ class ElasticEPScalingExecutor:
|
||||
is_async_enabled = eplb_state.is_async
|
||||
run_async = async_op and is_async_enabled
|
||||
eplb_state.is_async = run_async
|
||||
if rank_mapping is None:
|
||||
eplb_state.rearrange()
|
||||
else:
|
||||
eplb_state.rearrange(rank_mapping=rank_mapping)
|
||||
eplb_state.rearrange(rank_mapping=rank_mapping, use_last_expert_load=True)
|
||||
if not run_async:
|
||||
# Wait for non-blocking expert resharding copies before continuing
|
||||
# the Elastic EP reconfiguration.
|
||||
|
||||
@@ -6,6 +6,7 @@ from vllm.distributed.device_communicators.pynccl import defer_comm_warmup_on_ro
|
||||
from vllm.distributed.parallel_state import (
|
||||
_init_stateless_group,
|
||||
_node_count,
|
||||
get_pcp_group,
|
||||
get_pp_group,
|
||||
get_tp_group,
|
||||
get_world_group,
|
||||
@@ -72,12 +73,13 @@ def create_standby_groups(
|
||||
_STANDBY_WORLD_NODE_COUNT = _node_count(_STANDBY_WORLD.tcp_store_group)
|
||||
|
||||
tp_size = get_tp_group().world_size
|
||||
pcp_size = get_pcp_group().world_size
|
||||
pp_size = get_pp_group().world_size
|
||||
|
||||
all_ranks = torch.arange(new_world_size_across_dp).reshape(
|
||||
-1, new_dp_size, pp_size, tp_size
|
||||
-1, new_dp_size, pp_size, pcp_size, tp_size
|
||||
)
|
||||
standby_dp_ranks = all_ranks.transpose(1, 3).reshape(-1, new_dp_size).unbind(0)
|
||||
standby_dp_ranks = all_ranks.transpose(1, 4).reshape(-1, new_dp_size).unbind(0)
|
||||
standby_dp_ranks = [x.tolist() for x in standby_dp_ranks]
|
||||
|
||||
# Deferred to commit so the warm-up runs while the engine is paused.
|
||||
@@ -87,7 +89,9 @@ def create_standby_groups(
|
||||
)
|
||||
|
||||
standby_ep_ranks = (
|
||||
all_ranks.transpose(1, 2).reshape(-1, new_dp_size * tp_size).unbind(0)
|
||||
all_ranks.transpose(1, 2)
|
||||
.reshape(-1, new_dp_size * pcp_size * tp_size)
|
||||
.unbind(0)
|
||||
)
|
||||
standby_ep_ranks = [x.tolist() for x in standby_ep_ranks]
|
||||
_STANDBY_EP = _init_stateless_group(
|
||||
|
||||
@@ -183,6 +183,8 @@ class EplbModelState:
|
||||
See:
|
||||
https://github.com/vllm-project/vllm/pull/22167#pullrequestreview-3086143856
|
||||
"""
|
||||
last_expert_load: torch.Tensor
|
||||
"""Global logical-expert totals from the last reshuffle; equal demand initially."""
|
||||
model_name: str
|
||||
model: MixtureOfExperts
|
||||
expert_buffer: list[torch.Tensor]
|
||||
@@ -499,6 +501,11 @@ class EplbState:
|
||||
expert_load_pass=expert_load_pass,
|
||||
expert_load_pass_buffer=expert_load_pass_buffer,
|
||||
expert_load_window=expert_load_window,
|
||||
last_expert_load=torch.ones(
|
||||
(model.num_moe_layers, model.num_logical_experts),
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
),
|
||||
model_name=model_config.model,
|
||||
model=model,
|
||||
expert_buffer=expert_buffer,
|
||||
@@ -744,6 +751,7 @@ class EplbState:
|
||||
self,
|
||||
is_profile: bool = False,
|
||||
rank_mapping: dict[int, int] | None = None,
|
||||
use_last_expert_load: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
"""Rearrange the experts according to the current load.
|
||||
|
||||
@@ -753,6 +761,7 @@ class EplbState:
|
||||
no memory movement will be performed. Default is False.
|
||||
rank_mapping (dict[int, int] | None): The rank mapping
|
||||
when scaling is done in EEP.
|
||||
use_last_expert_load: Use the last reshuffle's logical-expert totals.
|
||||
|
||||
"""
|
||||
ep_group = get_ep_group().device_group
|
||||
@@ -775,6 +784,13 @@ class EplbState:
|
||||
# Map the physical expert load to global logical experts
|
||||
global_expert_load_windows = []
|
||||
for eplb_model_state in self.model_states.values():
|
||||
if use_last_expert_load:
|
||||
# Distribute rank 0's saved counts through the existing all-reduce.
|
||||
saved_load = eplb_model_state.last_expert_load
|
||||
global_expert_load_windows.append(
|
||||
saved_load.clone() if is_main_rank else torch.zeros_like(saved_load)
|
||||
)
|
||||
continue
|
||||
expert_load_window = eplb_model_state.expert_load_window
|
||||
physical_to_logical = eplb_model_state.physical_to_logical_map
|
||||
invalid_idx = eplb_model_state.model.num_logical_experts
|
||||
@@ -835,6 +851,8 @@ class EplbState:
|
||||
for eplb_model_state, global_expert_load_window in zip(
|
||||
self.model_states.values(), global_expert_load_windows
|
||||
):
|
||||
if not is_profile:
|
||||
eplb_model_state.last_expert_load = global_expert_load_window
|
||||
if not self.is_async or is_profile:
|
||||
# Get new expert mappings for the model. The policy runs on the
|
||||
# host, so the load window and current map have to come back.
|
||||
|
||||
@@ -31,7 +31,7 @@ The class provides the following primitives:
|
||||
wait_for_layer_load() - blocks until layer i load is done
|
||||
|
||||
save_kv_layer() - starts saving KV for layer i (maybe async)
|
||||
wait_for_save() - blocks until all saves are done
|
||||
wait_for_save() - submits saves and performs required synchronization
|
||||
|
||||
get_transfer_results() - returns async send/receive completions and
|
||||
receive failures in one snapshot.
|
||||
@@ -42,6 +42,7 @@ The class provides the following primitives:
|
||||
import enum
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, Iterable
|
||||
from contextlib import AbstractContextManager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
@@ -227,6 +228,13 @@ class KVConnectorBase_V1(ABC):
|
||||
# Worker-side methods
|
||||
# ==============================
|
||||
|
||||
def get_mem_pool_context(self) -> AbstractContextManager | None:
|
||||
"""Return a custom KV cache allocation context, if configured.
|
||||
|
||||
Returning None uses the engine's default memory pool.
|
||||
"""
|
||||
return None
|
||||
|
||||
def bind_connector_metadata(self, connector_metadata: KVConnectorMetadata) -> None:
|
||||
"""Set the connector metadata from the scheduler.
|
||||
|
||||
@@ -356,11 +364,14 @@ class KVConnectorBase_V1(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def wait_for_save(self):
|
||||
"""Block until all the save operations is done. This is called
|
||||
as the forward context exits to ensure that the async saving
|
||||
from save_kv_layer is complete before finishing the forward.
|
||||
"""Submit saves and perform required synchronization.
|
||||
|
||||
This prevents overwrites of paged KV buffer before saving done.
|
||||
Called once per step, including empty steps, after any target and draft
|
||||
forwards. Metadata remains bound during this call. Do nothing if there
|
||||
is no save work.
|
||||
|
||||
Async saves must retain their source blocks until completion is reported
|
||||
to the scheduler. Otherwise, wait for saves to finish before returning.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@@ -28,6 +28,16 @@ Example:
|
||||
- fill_mean (float): Mean value for random normal fill (default: 0.015)
|
||||
- fill_std (float): Standard deviation for random fill (default: 0.0)
|
||||
Set to 0 for constant values, >0 for random sampling
|
||||
- startup_fill (bool): Fill the whole KV cache once at startup instead
|
||||
of filling each new request's blocks in the step that schedules it
|
||||
(default: False). Circular-buffer caches are still zeroed per
|
||||
request, and attention caches whose new blocks the engine zeroes
|
||||
before use (hybrid Mamba or mixed-precision KV caches) are still
|
||||
filled per request. The fill is not redone after sleep mode
|
||||
discards the KV cache.
|
||||
|
||||
The dummy KV cache is only meant for performance measurement; outputs are
|
||||
not meaningful for accuracy evaluation.
|
||||
|
||||
"""
|
||||
|
||||
@@ -45,13 +55,20 @@ from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
SupportsHMA,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
dcp_world_size_for_kv_cache_spec,
|
||||
resolve_dcp_kv_block_size,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import CircularBufferSpec, iter_layer_specs
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
CircularBufferSpec,
|
||||
KVCacheSpec,
|
||||
KVQuantMode,
|
||||
UniformTypeKVCacheSpecs,
|
||||
iter_layer_specs,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
@@ -64,6 +81,45 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _get_fp8_dtype(spec: KVCacheSpec, cache_dtype: str) -> torch.dtype | None:
|
||||
"""The fp8 dtype of a KV cache that stores plain fp8 values as uint8.
|
||||
|
||||
Returns None for other layouts, including packed ones that embed scales
|
||||
or other metadata in the uint8 page.
|
||||
"""
|
||||
if (
|
||||
not isinstance(spec, AttentionSpec)
|
||||
or spec.dtype != torch.uint8
|
||||
or spec.kv_quant_mode != KVQuantMode.FP8_PER_TENSOR
|
||||
or spec.state_content_bytes is not None
|
||||
):
|
||||
return None
|
||||
cache_dtype = getattr(spec, "cache_dtype_str", None) or cache_dtype
|
||||
if cache_dtype in ("fp8", "fp8_e4m3"):
|
||||
return current_platform.fp8_dtype()
|
||||
if cache_dtype == "fp8_e5m2":
|
||||
return torch.float8_e5m2
|
||||
return None
|
||||
|
||||
|
||||
def _get_startup_fill_group_ids(kv_cache_config: "KVCacheConfig") -> set[int]:
|
||||
"""KV cache groups that startup fill covers.
|
||||
|
||||
Circular buffers are zero-filled per request. Attention groups whose new
|
||||
blocks the engine zeroes before use are filled per request, since the
|
||||
zeroing would wipe the startup fill.
|
||||
"""
|
||||
group_ids = set()
|
||||
for group_idx, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
spec = group.kv_cache_spec
|
||||
if any(isinstance(s, CircularBufferSpec) for s in iter_layer_specs(spec)):
|
||||
continue
|
||||
if kv_cache_config.needs_kv_cache_zeroing and isinstance(spec, AttentionSpec):
|
||||
continue
|
||||
group_ids.add(group_idx)
|
||||
return group_ids
|
||||
|
||||
|
||||
@dataclass
|
||||
class DecodeBenchConnectorMetadata(KVConnectorMetadata):
|
||||
"""Metadata for DecodeBenchConnector.
|
||||
@@ -191,16 +247,18 @@ class DecodeBenchConnectorScheduler:
|
||||
"""Scheduler-side implementation for DecodeBenchConnector."""
|
||||
|
||||
def __init__(self, vllm_config: "VllmConfig", kv_cache_config: "KVCacheConfig"):
|
||||
kv_transfer_config = vllm_config.kv_transfer_config
|
||||
assert kv_transfer_config is not None
|
||||
self.startup_fill = kv_transfer_config.get_from_extra_config(
|
||||
"startup_fill", False
|
||||
)
|
||||
self._startup_fill_group_ids = (
|
||||
_get_startup_fill_group_ids(kv_cache_config) if self.startup_fill else set()
|
||||
)
|
||||
dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size
|
||||
self.kv_cache_groups = kv_cache_config.kv_cache_groups
|
||||
self.group_block_sizes = tuple(
|
||||
resolve_dcp_kv_block_size(
|
||||
group.kv_cache_spec,
|
||||
dcp_world_size_for_kv_cache_spec(
|
||||
group.kv_cache_spec,
|
||||
dcp_world_size,
|
||||
),
|
||||
)
|
||||
resolve_dcp_kv_block_size(group.kv_cache_spec, dcp_world_size)
|
||||
for group in self.kv_cache_groups
|
||||
)
|
||||
|
||||
@@ -275,6 +333,9 @@ class DecodeBenchConnectorScheduler:
|
||||
strict=True,
|
||||
)
|
||||
):
|
||||
if group_idx in self._startup_fill_group_ids:
|
||||
block_ids_per_group_list.append([])
|
||||
continue
|
||||
is_circular_buffer = all(
|
||||
isinstance(spec, CircularBufferSpec)
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
@@ -310,6 +371,9 @@ class DecodeBenchConnectorScheduler:
|
||||
)
|
||||
block_ids_per_group_list.append(block_ids)
|
||||
block_ids_per_group = tuple(block_ids_per_group_list)
|
||||
self._filled_requests.add(req_id)
|
||||
if self.startup_fill and not any(block_ids_per_group):
|
||||
return
|
||||
|
||||
# Store the blocks to fill for all group. _pending_fills doesn't need cleanup
|
||||
# as it's cleared after build_connector_meta
|
||||
@@ -317,7 +381,6 @@ class DecodeBenchConnectorScheduler:
|
||||
block_ids_per_group,
|
||||
num_external_tokens,
|
||||
)
|
||||
self._filled_requests.add(req_id)
|
||||
|
||||
block_counts = tuple(len(group) for group in block_ids_per_group)
|
||||
logger.debug(
|
||||
@@ -356,10 +419,27 @@ class DecodeBenchConnectorWorker:
|
||||
assert kv_transfer_config is not None
|
||||
self.fill_mean = kv_transfer_config.get_from_extra_config("fill_mean", 0.015)
|
||||
self.fill_std = kv_transfer_config.get_from_extra_config("fill_std", 0.0)
|
||||
self.startup_fill = kv_transfer_config.get_from_extra_config(
|
||||
"startup_fill", False
|
||||
)
|
||||
self._startup_fill_group_ids = (
|
||||
_get_startup_fill_group_ids(kv_cache_config) if self.startup_fill else set()
|
||||
)
|
||||
|
||||
# Will be populated via register_kv_caches
|
||||
self.kv_caches: dict[str, torch.Tensor] | None = None
|
||||
|
||||
# Layers whose uint8 KV cache stores plain fp8 values
|
||||
self._fp8_dtypes: dict[str, torch.dtype] = {}
|
||||
for group in kv_cache_config.kv_cache_groups:
|
||||
for layer_name in group.layer_names:
|
||||
spec = group.kv_cache_spec
|
||||
if isinstance(spec, UniformTypeKVCacheSpecs):
|
||||
spec = spec.kv_cache_specs[layer_name]
|
||||
fp8_dtype = _get_fp8_dtype(spec, vllm_config.cache_config.cache_dtype)
|
||||
if fp8_dtype is not None:
|
||||
self._fp8_dtypes[layer_name] = fp8_dtype
|
||||
|
||||
# Mapping from KV cache group index to list of layer names in that group
|
||||
self.group_to_layers = {
|
||||
group_idx: list(group.layer_names)
|
||||
@@ -373,6 +453,17 @@ class DecodeBenchConnectorWorker:
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
}
|
||||
num_zeroed_groups = len(
|
||||
self.group_to_layers.keys()
|
||||
- self._startup_fill_group_ids
|
||||
- self._zero_fill_group_ids
|
||||
)
|
||||
if self.startup_fill and num_zeroed_groups:
|
||||
logger.info(
|
||||
"DecodeBenchConnector: the engine zeroes new blocks of %d KV "
|
||||
"cache groups before use, so they are still filled per request.",
|
||||
num_zeroed_groups,
|
||||
)
|
||||
|
||||
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
|
||||
"""Store references to the KV cache tensors."""
|
||||
@@ -383,6 +474,48 @@ class DecodeBenchConnectorWorker:
|
||||
len(kv_caches),
|
||||
)
|
||||
|
||||
if self.startup_fill:
|
||||
self._fill_all_kv_caches()
|
||||
|
||||
def _fill_all_kv_caches(self):
|
||||
"""Fill the KV cache tensors of the startup-filled groups once, in
|
||||
place, with dummy values, so that no per-request fill is needed.
|
||||
"""
|
||||
assert self.kv_caches is not None
|
||||
|
||||
num_layers = 0
|
||||
for group_idx in sorted(self._startup_fill_group_ids):
|
||||
for layer_name in self.group_to_layers[group_idx]:
|
||||
kv_cache = self.kv_caches.get(layer_name)
|
||||
if isinstance(kv_cache, torch.Tensor):
|
||||
tensors = [kv_cache]
|
||||
elif isinstance(kv_cache, (list, tuple)) and all(
|
||||
isinstance(t, torch.Tensor) for t in kv_cache
|
||||
):
|
||||
tensors = list(kv_cache)
|
||||
else:
|
||||
logger.warning_once(
|
||||
"DecodeBenchConnector: skipping startup fill for layer "
|
||||
"%s whose KV cache is %s, not a tensor or a list/tuple "
|
||||
"of tensors.",
|
||||
layer_name,
|
||||
type(kv_cache).__name__,
|
||||
)
|
||||
continue
|
||||
for tensor in tensors:
|
||||
fill_dtype = self._fp8_dtypes.get(layer_name, tensor.dtype)
|
||||
self._fill_tensor(tensor, self.fill_mean, self.fill_std, fill_dtype)
|
||||
num_layers += 1
|
||||
|
||||
logger.info(
|
||||
"DecodeBenchConnector: Filled %d KV cache layers at startup with %s "
|
||||
"values (mean=%.3f, std=%.3f)",
|
||||
num_layers,
|
||||
"random" if self.fill_std > 0 else "constant",
|
||||
self.fill_mean,
|
||||
self.fill_std,
|
||||
)
|
||||
|
||||
def start_fill_kv(self, metadata: DecodeBenchConnectorMetadata):
|
||||
"""Fill the allocated KV cache blocks with dummy values.
|
||||
|
||||
@@ -455,12 +588,17 @@ class DecodeBenchConnectorWorker:
|
||||
# dimension — so fill each tensor in its entirety with the same
|
||||
# dummy values.
|
||||
if isinstance(kv_cache, torch.Tensor):
|
||||
self._fill_block_tensor(kv_cache, block_ids, fill_mean, fill_std)
|
||||
fill_dtype = self._fp8_dtypes.get(layer_name, kv_cache.dtype)
|
||||
self._fill_block_tensor(
|
||||
kv_cache, block_ids, fill_mean, fill_std, fill_dtype
|
||||
)
|
||||
elif isinstance(kv_cache, (list, tuple)) and all(
|
||||
isinstance(t, torch.Tensor) for t in kv_cache
|
||||
):
|
||||
for state_tensor in kv_cache:
|
||||
self._fill_state_tensor(state_tensor, fill_mean, fill_std)
|
||||
self._fill_tensor(
|
||||
state_tensor, fill_mean, fill_std, state_tensor.dtype
|
||||
)
|
||||
else:
|
||||
logger.warning_once(
|
||||
"DecodeBenchConnector: skipping fill for layer %s whose KV "
|
||||
@@ -486,6 +624,7 @@ class DecodeBenchConnectorWorker:
|
||||
block_ids: list[int],
|
||||
fill_mean: float,
|
||||
fill_std: float,
|
||||
fill_dtype: torch.dtype,
|
||||
):
|
||||
"""Fill the requested block rows of a block-indexed KV cache tensor.
|
||||
|
||||
@@ -495,6 +634,8 @@ class DecodeBenchConnectorWorker:
|
||||
tensor's first dim are ignored.
|
||||
fill_mean: Mean value for the fill.
|
||||
fill_std: Standard deviation for the fill.
|
||||
fill_dtype: Dtype the values are encoded as, e.g. the fp8 dtype
|
||||
of a uint8 fp8 cache.
|
||||
|
||||
"""
|
||||
# Convert block_ids to tensor on device
|
||||
@@ -509,46 +650,85 @@ class DecodeBenchConnectorWorker:
|
||||
if len(valid_block_ids) == 0:
|
||||
return
|
||||
|
||||
# Create fill values - either constant or random
|
||||
block_shape = kv_cache.shape[1:]
|
||||
if fill_std > 0:
|
||||
# Random normal sampling
|
||||
fill_values = torch.normal(
|
||||
mean=fill_mean,
|
||||
std=fill_std,
|
||||
size=(len(valid_block_ids),) + block_shape,
|
||||
dtype=kv_cache.dtype,
|
||||
device=kv_cache.device,
|
||||
)
|
||||
else:
|
||||
# Constant fill value
|
||||
fill_values = torch.full(
|
||||
(len(valid_block_ids),) + block_shape,
|
||||
fill_mean,
|
||||
dtype=kv_cache.dtype,
|
||||
device=kv_cache.device,
|
||||
)
|
||||
fill_values = self._make_fill_values(
|
||||
(len(valid_block_ids),) + kv_cache.shape[1:],
|
||||
kv_cache.device,
|
||||
fill_dtype,
|
||||
fill_mean,
|
||||
fill_std,
|
||||
)
|
||||
|
||||
# Batch fill operation
|
||||
kv_cache[valid_block_ids] = fill_values
|
||||
kv_cache[valid_block_ids] = fill_values.view(kv_cache.dtype)
|
||||
|
||||
def _fill_state_tensor(
|
||||
self, kv_cache: torch.Tensor, fill_mean: float, fill_std: float
|
||||
def _make_fill_values(
|
||||
self,
|
||||
size: tuple[int, ...],
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
fill_mean: float,
|
||||
fill_std: float,
|
||||
) -> torch.Tensor:
|
||||
"""Create constant or random fill values of ``dtype``, clamped to its
|
||||
finite range. Non-floating dtypes (packed layouts) are filled with
|
||||
zeros.
|
||||
"""
|
||||
if not dtype.is_floating_point:
|
||||
if fill_mean or fill_std:
|
||||
logger.warning_once(
|
||||
"DecodeBenchConnector: %s KV caches do not hold plain "
|
||||
"floating-point values; filling them with zeros.",
|
||||
dtype,
|
||||
)
|
||||
return torch.zeros(size, dtype=dtype, device=device)
|
||||
|
||||
finfo = torch.finfo(dtype)
|
||||
if fill_std > 0:
|
||||
sample_dtype = torch.float32
|
||||
if dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64):
|
||||
sample_dtype = dtype
|
||||
values = torch.normal(
|
||||
fill_mean, fill_std, size=size, device=device, dtype=sample_dtype
|
||||
)
|
||||
return values.clamp_(finfo.min, finfo.max).to(dtype)
|
||||
fill_mean = min(max(fill_mean, finfo.min), finfo.max)
|
||||
return torch.full(size, fill_mean, dtype=dtype, device=device)
|
||||
|
||||
def _fill_tensor(
|
||||
self,
|
||||
kv_cache: torch.Tensor,
|
||||
fill_mean: float,
|
||||
fill_std: float,
|
||||
fill_dtype: torch.dtype,
|
||||
):
|
||||
"""Fill an entire non-block-indexed state tensor with dummy values.
|
||||
"""Fill an entire tensor in place with dummy values.
|
||||
|
||||
Hybrid / linear-attention layers (e.g. Mamba, Kimi Delta Attention)
|
||||
store their per-layer state as tensors with no num_blocks dimension,
|
||||
so the whole tensor is filled with the same constant or random values
|
||||
used for block fills, rather than selected block rows.
|
||||
Used for startup fills, and for hybrid / linear-attention layers (e.g.
|
||||
Mamba, Kimi Delta Attention) whose per-layer state tensors are filled
|
||||
in their entirety with the same constant or random values used for
|
||||
block fills, rather than selected block rows.
|
||||
|
||||
Args:
|
||||
kv_cache: A state tensor to fill in its entirety.
|
||||
kv_cache: A tensor to fill in its entirety.
|
||||
fill_mean: Mean value for the fill.
|
||||
fill_std: Standard deviation for the fill.
|
||||
fill_dtype: Dtype the values are encoded as, e.g. the fp8 dtype
|
||||
of a uint8 fp8 cache.
|
||||
|
||||
"""
|
||||
if fill_std > 0:
|
||||
kv_cache.normal_(mean=fill_mean, std=fill_std)
|
||||
else:
|
||||
kv_cache.fill_(fill_mean)
|
||||
view = kv_cache.view(fill_dtype)
|
||||
if fill_std == 0 or not fill_dtype.is_floating_point:
|
||||
view.fill_(
|
||||
self._make_fill_values(
|
||||
(), torch.device("cpu"), fill_dtype, fill_mean, fill_std
|
||||
)
|
||||
)
|
||||
return
|
||||
# Sample in chunks to bound the temporary memory.
|
||||
rows = max(1, (1 << 24) // max(1, view[0].numel()))
|
||||
for chunk in view.split(rows):
|
||||
chunk.copy_(
|
||||
self._make_fill_values(
|
||||
chunk.shape, chunk.device, fill_dtype, fill_mean, fill_std
|
||||
)
|
||||
)
|
||||
|
||||
@@ -142,6 +142,7 @@ class LMCacheConnectorV1(KVConnectorBase_V1):
|
||||
engine.current_layer = 0
|
||||
if hasattr(engine, "layerwise_retrievers"):
|
||||
engine.layerwise_retrievers = []
|
||||
engine.layerwise_storers = []
|
||||
|
||||
def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None:
|
||||
"""Start loading the KV cache from the connector to vLLM's paged
|
||||
|
||||
@@ -606,6 +606,7 @@ class LMCacheConnectorV1Impl:
|
||||
|
||||
self.async_loading = config.enable_async_loading
|
||||
self.layerwise_retrievers: list[Generator[torch.Tensor | None, None, None]] = []
|
||||
self.layerwise_storers: list[Generator[Any, None, None]] = []
|
||||
self._stats_monitor = LMCStatsMonitor.GetOrCreate()
|
||||
if role == KVConnectorRole.SCHEDULER:
|
||||
# Create lookup client using factory
|
||||
@@ -798,6 +799,7 @@ class LMCacheConnectorV1Impl:
|
||||
"""
|
||||
self.current_layer = 0
|
||||
self.layerwise_retrievers = []
|
||||
self.layerwise_storers = []
|
||||
|
||||
@_lmcache_nvtx_annotate
|
||||
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
|
||||
|
||||
@@ -1051,15 +1051,9 @@ class MooncakeConnectorWorker:
|
||||
self.finished_recving_reqs: set[ReqId] = set()
|
||||
# Written from the receiver loop, drained from the worker thread.
|
||||
self._invalid_block_ids: queue.Queue[set[int]] = queue.Queue()
|
||||
self._is_hma_required = (
|
||||
not vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
and any(
|
||||
not isinstance(g.kv_cache_spec, FullAttentionSpec)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
)
|
||||
)
|
||||
# Block IDs are only unique within a group; with HMA the scheduler
|
||||
# tracks a single merged group, so failures are reported per request.
|
||||
self._is_hma_required = len(kv_cache_config.kv_cache_groups) > 1
|
||||
# Block IDs are only unique within a group, so with multiple groups
|
||||
# load failures are reported per request instead.
|
||||
self._failed_recv_reqs: queue.Queue[ReqId] = queue.Queue()
|
||||
|
||||
self.xfer_stats = MooncakeKVConnectorStats()
|
||||
|
||||
@@ -13,6 +13,7 @@ enabling prefix caching via hash-based deduplication.
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from contextlib import AbstractContextManager
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
@@ -322,6 +323,17 @@ class MooncakeStoreConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
# Worker-side methods
|
||||
# ============================================================
|
||||
|
||||
def get_mem_pool_context(self) -> AbstractContextManager | None:
|
||||
"""Return a context manager for the custom MemPool, or None.
|
||||
|
||||
Called by the Worker before ``initialize_kv_cache`` so that KV
|
||||
cache is allocated from the Mooncake-managed pool when
|
||||
``custom_mem_pool`` is set in ``kv_connector_extra_config``.
|
||||
"""
|
||||
if self.connector_worker is None:
|
||||
return None
|
||||
return self.connector_worker.get_mem_pool_context()
|
||||
|
||||
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
|
||||
assert self.connector_worker is not None
|
||||
self.connector_worker.register_kv_caches(kv_caches)
|
||||
|
||||
@@ -19,13 +19,14 @@ import threading
|
||||
import time
|
||||
from collections.abc import Callable, Sequence
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from contextlib import AbstractContextManager
|
||||
from typing import Any, TypeVar
|
||||
|
||||
import torch
|
||||
import zmq
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import ModelConfig, VllmConfig
|
||||
from vllm.distributed import (
|
||||
get_dcp_group,
|
||||
get_pcp_group,
|
||||
@@ -1414,6 +1415,41 @@ class KVCacheStoreRecvingThread(KVTransferThread):
|
||||
class MooncakeStoreWorker:
|
||||
"""Worker-side component for MooncakeStoreConnector."""
|
||||
|
||||
@staticmethod
|
||||
def _create_mem_pool(
|
||||
extra_config: dict[str, Any], model_config: ModelConfig
|
||||
) -> torch.cuda.MemPool | None:
|
||||
pool_type = str(extra_config.get("custom_mem_pool") or "").upper()
|
||||
if not pool_type:
|
||||
return None
|
||||
if pool_type not in ("NVLINK", "BAREX"):
|
||||
raise ValueError(
|
||||
f"Unsupported custom_mem_pool={pool_type!r}, "
|
||||
"expected 'NVLINK' or 'BAREX'"
|
||||
)
|
||||
if model_config.enable_sleep_mode or model_config.enable_cumem_allocator:
|
||||
raise ValueError(
|
||||
"custom_mem_pool is incompatible with enable_sleep_mode "
|
||||
"or enable_cumem_allocator; CuMemAllocator cannot manage "
|
||||
"allocations from the custom pool."
|
||||
)
|
||||
try:
|
||||
if pool_type == "NVLINK":
|
||||
from mooncake.allocator import NVLinkAllocator as allocator_cls
|
||||
else: # pool_type == "BAREX"
|
||||
from mooncake.allocator import BarexAllocator as allocator_cls
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
f"custom_mem_pool={pool_type!r} requires "
|
||||
"mooncake-transfer-engine>=0.3.8. Please upgrade Mooncake."
|
||||
) from e
|
||||
|
||||
device = torch.device("cuda", torch.accelerator.current_device_index())
|
||||
allocator = allocator_cls.get_allocator(device)
|
||||
mem_pool = torch.cuda.MemPool(allocator.allocator())
|
||||
logger.info("Using Mooncake custom memory pool: %s", pool_type)
|
||||
return mem_pool
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
@@ -1461,13 +1497,7 @@ class MooncakeStoreWorker:
|
||||
and not self.can_put
|
||||
)
|
||||
self.cache_config = vllm_config.cache_config
|
||||
self._is_hma_required = (
|
||||
not vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
and any(
|
||||
not isinstance(g.kv_cache_spec, FullAttentionSpec)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
)
|
||||
)
|
||||
self._is_hma_required = len(kv_cache_config.kv_cache_groups) > 1
|
||||
self.block_size, self.hash_block_size = resolve_kv_cache_block_sizes(
|
||||
kv_cache_config, vllm_config
|
||||
)
|
||||
@@ -1477,6 +1507,10 @@ class MooncakeStoreWorker:
|
||||
|
||||
# Initialize MooncakeDistributedStore with its own TransferEngine
|
||||
store_config = MooncakeStoreConfig.load_from_config()
|
||||
# Validate and create the custom memory pool before initializing the
|
||||
# store so failures cannot leak a partially initialized store handle.
|
||||
self._mem_pool = self._create_mem_pool(extra_config, model_config)
|
||||
|
||||
self.store = MooncakeDistributedStore()
|
||||
local_ip = get_ip()
|
||||
local_hostname = rdma_utils.get_requester_local_hostname(local_ip)
|
||||
@@ -1747,6 +1781,13 @@ class MooncakeStoreWorker:
|
||||
)
|
||||
return token_dbs
|
||||
|
||||
def get_mem_pool_context(self) -> AbstractContextManager | None:
|
||||
"""Return a context manager for the custom MemPool, or None if
|
||||
no custom pool is configured."""
|
||||
if self._mem_pool is None:
|
||||
return None
|
||||
return torch.cuda.use_mem_pool(self._mem_pool)
|
||||
|
||||
def _spec_tp_replication_factor(self, spec: KVCacheSpec) -> int:
|
||||
if self.dcp_size > 1:
|
||||
return 1
|
||||
|
||||
@@ -69,6 +69,8 @@ class WriteTask:
|
||||
event: torch.cuda.Event
|
||||
remote_notify_port: int
|
||||
remote_ip: str
|
||||
multi_pod_hosts: list[str] = field(default_factory=list)
|
||||
remote_dp_size_local: int = 0
|
||||
enqueue_time: float = field(default_factory=time.perf_counter)
|
||||
retried: int = 0
|
||||
|
||||
@@ -96,7 +98,7 @@ class RemoteAllocInfo:
|
||||
writes_expected: int | None = None
|
||||
decode_dp_rank: int = 0
|
||||
completion_request_id: str | None = None
|
||||
completion_remote_notify_port: int | None = None
|
||||
completion_notify_port: int | None = None
|
||||
completion_remote_ip: str | None = None
|
||||
completion_notified: bool = False
|
||||
transfer_statuses: list[Any] = field(default_factory=list)
|
||||
|
||||
@@ -1776,6 +1776,8 @@ class MoRIIOConnectorWorker:
|
||||
kv_layer: torch.Tensor,
|
||||
remote_notify_port: int,
|
||||
remote_ip: str,
|
||||
multi_pod_hosts: list[str],
|
||||
remote_dp_size_local: int,
|
||||
) -> None:
|
||||
"""Schedule a block write operation.
|
||||
|
||||
@@ -1789,6 +1791,8 @@ class MoRIIOConnectorWorker:
|
||||
kv_layer: KV cache tensor
|
||||
remote_notify_port: Port for completion notification
|
||||
remote_ip: IP address of remote node
|
||||
multi_pod_hosts: List of pod IPs for multi-pod Wide-EP
|
||||
remote_dp_size_local: Per-pod DP size for multi-pod
|
||||
|
||||
"""
|
||||
# synchronization to prevent dirty reads between
|
||||
@@ -1810,6 +1814,8 @@ class MoRIIOConnectorWorker:
|
||||
event=event,
|
||||
remote_notify_port=remote_notify_port,
|
||||
remote_ip=remote_ip,
|
||||
multi_pod_hosts=multi_pod_hosts,
|
||||
remote_dp_size_local=remote_dp_size_local,
|
||||
)
|
||||
self._writer.schedule_write(task)
|
||||
|
||||
@@ -3167,18 +3173,17 @@ class MoRIIOConnectorWorker:
|
||||
)
|
||||
|
||||
def _write_blocks_for_req(self, req_id: ReqId, meta: ReqMeta, layer_name, kv_layer):
|
||||
# Stash multi_pod_hosts + local DP size on the worker so
|
||||
# MoRIIOEngine._finalize_if_complete (which sees only the WriteTask,
|
||||
# not ReqMeta) can pick the per-rank pod IP for the completion notify.
|
||||
# Last-writer-wins is safe: all requests share the same topology.
|
||||
if meta.multi_pod_hosts:
|
||||
self.multi_pod_hosts = list(meta.multi_pod_hosts)
|
||||
else:
|
||||
self.multi_pod_hosts = [meta.remote_host]
|
||||
if meta.remote_dp_size_local:
|
||||
self.remote_dp_size_local = int(meta.remote_dp_size_local)
|
||||
else:
|
||||
self.remote_dp_size_local = int(meta.remote_dp_size)
|
||||
# Compute per-request values to pass through the task (no shared state).
|
||||
# This avoids race conditions when concurrent requests target different
|
||||
# decode pods - each WriteTask carries its own routing info.
|
||||
hosts = (
|
||||
list(meta.multi_pod_hosts) if meta.multi_pod_hosts else [meta.remote_host]
|
||||
)
|
||||
dp_local = (
|
||||
int(meta.remote_dp_size_local)
|
||||
if meta.remote_dp_size_local
|
||||
else int(meta.remote_dp_size)
|
||||
)
|
||||
# WRITE does not support HMA, so unwrap blocks into flat lists.
|
||||
# remote_block_ids can itself be empty so need to be careful when unwrapping.
|
||||
local_block_ids = meta.local_block_ids[0]
|
||||
@@ -3193,6 +3198,8 @@ class MoRIIOConnectorWorker:
|
||||
kv_layer=kv_layer,
|
||||
remote_notify_port=meta.remote_notify_port,
|
||||
remote_ip=meta.remote_host,
|
||||
multi_pod_hosts=hosts,
|
||||
remote_dp_size_local=dp_local,
|
||||
)
|
||||
|
||||
def merge_contiguous_blocks(
|
||||
|
||||
@@ -314,18 +314,27 @@ class MoRIIOWriter:
|
||||
request_info = self._get_remote_alloc_info(task.transfer_id)
|
||||
with self._write_state_lock:
|
||||
request_info.completion_request_id = task.request_id
|
||||
request_info.completion_remote_notify_port = task.remote_notify_port
|
||||
# Wide-EP multi-pod: task.remote_ip addresses only the first pod,
|
||||
# so resolve the per-rank host from multi_pod_hosts (falls back to
|
||||
# task.remote_ip for single-pod or on any indexing miss).
|
||||
_remote_ip = task.remote_ip
|
||||
_hosts = list(getattr(self.worker, "multi_pod_hosts", []) or [])
|
||||
_dp_local = int(getattr(self.worker, "remote_dp_size_local", 0) or 0)
|
||||
_hosts = task.multi_pod_hosts
|
||||
_dp_local = task.remote_dp_size_local
|
||||
if _hosts and _dp_local > 0:
|
||||
_pod_idx = int(request_info.decode_dp_rank) // _dp_local
|
||||
if 0 <= _pod_idx < len(_hosts):
|
||||
_remote_ip = _hosts[_pod_idx]
|
||||
request_info.completion_remote_ip = _remote_ip
|
||||
# Resolve the final notify port under the lock so finalize only
|
||||
# reads it. The offset uses the per-pod local rank (% dp_local),
|
||||
# since each pod binds notify sockets only for its local ranks;
|
||||
# single-pod is bit-identical (modulus is a no-op).
|
||||
_decode_dp_rank_for_port = int(request_info.decode_dp_rank)
|
||||
if _dp_local > 0:
|
||||
_decode_dp_rank_for_port = _decode_dp_rank_for_port % _dp_local
|
||||
request_info.completion_notify_port = task.remote_notify_port + (
|
||||
get_port_offset(_decode_dp_rank_for_port, self.worker.tp_rank)
|
||||
)
|
||||
if task.transfer_id in self._sealed_writes:
|
||||
request_info.writes_expected = self._sealed_writes[task.transfer_id]
|
||||
|
||||
@@ -461,9 +470,9 @@ class MoRIIOWriter:
|
||||
if request_info.completion_notified:
|
||||
return
|
||||
request_id = request_info.completion_request_id
|
||||
remote_notify_port = request_info.completion_remote_notify_port
|
||||
remote_port = request_info.completion_notify_port
|
||||
remote_ip = request_info.completion_remote_ip
|
||||
if request_id is None or remote_notify_port is None or remote_ip is None:
|
||||
if request_id is None or remote_port is None or remote_ip is None:
|
||||
return
|
||||
transfer_statuses = list(request_info.transfer_statuses)
|
||||
request_info.transfer_statuses.clear()
|
||||
@@ -472,16 +481,6 @@ class MoRIIOWriter:
|
||||
# Wait for this request's transfers to complete.
|
||||
self.worker.moriio_wrapper.waiting_for_transfer_complete(transfer_statuses)
|
||||
|
||||
# The notify port offset must use the per-pod local rank
|
||||
# (% dp_local), since each pod binds notify sockets only for its local
|
||||
# ranks. Single-pod is bit-identical (modulus is a no-op).
|
||||
_dp_local = int(getattr(self.worker, "remote_dp_size_local", 0) or 0)
|
||||
_decode_dp_rank_for_port = int(request_info.decode_dp_rank)
|
||||
if _dp_local > 0:
|
||||
_decode_dp_rank_for_port = _decode_dp_rank_for_port % _dp_local
|
||||
remote_port = remote_notify_port + get_port_offset(
|
||||
_decode_dp_rank_for_port, self.worker.tp_rank
|
||||
)
|
||||
# Consider using RDMA immediate data in decode side
|
||||
# to eliminate the need for this notification.
|
||||
# Consider including the first gen token from prefill in the notification
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import copy
|
||||
from collections.abc import Callable, Iterable
|
||||
from contextlib import AbstractContextManager
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
@@ -294,6 +295,26 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
# ==============================
|
||||
# Worker-side methods
|
||||
# ==============================
|
||||
def get_mem_pool_context(self) -> AbstractContextManager | None:
|
||||
"""Forward a custom KV cache memory pool from a child connector.
|
||||
|
||||
KV cache is allocated once and can only live in one pool, so at
|
||||
most one child may provide a context.
|
||||
"""
|
||||
found: list[tuple[str, AbstractContextManager]] = []
|
||||
for connector in self._connectors:
|
||||
if (ctx := connector.get_mem_pool_context()) is not None:
|
||||
found.append((type(connector).__name__, ctx))
|
||||
|
||||
if len(found) > 1:
|
||||
names = [name for name, _ in found]
|
||||
raise ValueError(
|
||||
f"Multiple connectors provide a KV cache memory pool {names}; "
|
||||
"KV cache is allocated once and can only live in one pool. "
|
||||
"Configure custom_mem_pool on at most one connector."
|
||||
)
|
||||
return found[0][1] if found else None
|
||||
|
||||
def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None:
|
||||
for c in self._connectors:
|
||||
c.start_load_kv(forward_context, **kwargs)
|
||||
|
||||
@@ -839,6 +839,8 @@ class NixlBaseConnectorWorker:
|
||||
self._engine_ttl: float = vllm_config.kv_transfer_config.get_from_extra_config(
|
||||
"engine_ttl", 3600.0
|
||||
)
|
||||
# Map of pull peer (host, port) -> engine_id currently serving it.
|
||||
self._engine_by_address: dict[tuple[str, int], EngineId] = {}
|
||||
|
||||
self.model_config = vllm_config.model_config
|
||||
|
||||
@@ -1300,6 +1302,7 @@ class NixlBaseConnectorWorker:
|
||||
self._remote_agents[eid] = remote_agents
|
||||
self._engine_clock_offset[eid] = clock_offset
|
||||
self._engine_last_active[eid] = time.perf_counter()
|
||||
self._track_remote_engine_replacement(eid, host, port)
|
||||
except Exception as e:
|
||||
self._log_failure(
|
||||
failure_type="handshake_setup_failed",
|
||||
@@ -1567,7 +1570,13 @@ class NixlBaseConnectorWorker:
|
||||
block_stride = physical_page_size
|
||||
else:
|
||||
block_stride = cache.stride(0) * cache.element_size()
|
||||
storage_is_block_major = num_blocks * block_stride == registration_len
|
||||
# A connector that registers the backing as one memory region
|
||||
# may need its length rounded up to a page boundary. Such a tail
|
||||
# is shorter than one block, so it cannot make the storage
|
||||
# segmented.
|
||||
storage_is_block_major = (
|
||||
0 <= registration_len - num_blocks * block_stride < block_stride
|
||||
)
|
||||
# A view with a contiguous page can own a strided region even
|
||||
# when sibling layers share the same backing allocation.
|
||||
page_contiguous = (
|
||||
@@ -1589,7 +1598,9 @@ class NixlBaseConnectorWorker:
|
||||
):
|
||||
# TODO(Lucas): handle TP slicing for packed_storage; for now
|
||||
# restrict to MLA (DSv4) where kv is replicated.
|
||||
storage_block_len = registration_len // num_blocks
|
||||
# The complete storage row is one block stride. Dividing the
|
||||
# registered length instead would fold the padding tail in.
|
||||
storage_block_len = block_stride
|
||||
region_specs = [
|
||||
(registration_base, storage_block_len, storage_block_len)
|
||||
]
|
||||
@@ -2943,25 +2954,9 @@ class NixlBaseConnectorWorker:
|
||||
self._sync_device_after_direct_recv(direct_device_recving)
|
||||
|
||||
# Handle timeout to avoid stranding blocks on remote.
|
||||
now = time.perf_counter()
|
||||
while self._reqs_to_send:
|
||||
req_id, expires = next(iter(self._reqs_to_send.items()))
|
||||
# Sorted dict, oldest requests are put first so we can exit early.
|
||||
if now < expires:
|
||||
break
|
||||
count = self.consumer_notification_counts_by_req.pop(req_id, 0)
|
||||
self.expected_consumer_notifications_by_req.pop(req_id, None)
|
||||
self.xfer_stats.record_kv_expired_req()
|
||||
logger.warning(
|
||||
"Releasing expired KV blocks for request %s which were "
|
||||
"retrieved by %d remote worker(s) before lease expired.",
|
||||
req_id,
|
||||
count,
|
||||
)
|
||||
self._reqs_to_process.remove(req_id)
|
||||
del self._reqs_to_send[req_id]
|
||||
done_sending.add(req_id)
|
||||
self._reap_expired_send_leases(done_sending)
|
||||
|
||||
self._cleanup_replaced_remote_engines()
|
||||
return KVConnectorTransferResults(
|
||||
finished_sending=done_sending,
|
||||
finished_recving=done_recving,
|
||||
@@ -2988,6 +2983,34 @@ class NixlBaseConnectorWorker:
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _reap_expired_send_leases(self, done_sending: set[str]) -> None:
|
||||
"""Reclaim expired send-side KV leases into ``done_sending``.
|
||||
|
||||
``_reqs_to_send`` is not ordered by expiry: heartbeats update the
|
||||
deadline in place, and mixed TTLs share the map, so a live head
|
||||
entry can sit in front of already-expired ones. Scan every entry
|
||||
rather than stopping at the first still-live request.
|
||||
"""
|
||||
if not self._reqs_to_send:
|
||||
return
|
||||
now = time.perf_counter()
|
||||
expired = [
|
||||
req_id for req_id, expires in self._reqs_to_send.items() if now >= expires
|
||||
]
|
||||
for req_id in expired:
|
||||
count = self.consumer_notification_counts_by_req.pop(req_id, 0)
|
||||
self.expected_consumer_notifications_by_req.pop(req_id, None)
|
||||
self.xfer_stats.record_kv_expired_req()
|
||||
logger.warning(
|
||||
"Releasing expired KV blocks for request %s which were "
|
||||
"retrieved by %d remote worker(s) before lease expired.",
|
||||
req_id,
|
||||
count,
|
||||
)
|
||||
self._reqs_to_process.remove(req_id)
|
||||
del self._reqs_to_send[req_id]
|
||||
done_sending.add(req_id)
|
||||
|
||||
def _handle_heartbeat(self, payload: str) -> None:
|
||||
"""Extend leases for requests referenced in a heartbeat.
|
||||
|
||||
@@ -3522,14 +3545,53 @@ class NixlBaseConnectorWorker:
|
||||
and meta.remote is not None
|
||||
}
|
||||
|
||||
def _track_remote_engine_replacement(
|
||||
self, engine_id: EngineId, host: str, port: int
|
||||
) -> None:
|
||||
"""Record the engine currently serving a pull peer address."""
|
||||
# TODO: Also handle push mode, which handshakes in both directions.
|
||||
if self._TRANSFER_MODE != "pull":
|
||||
return
|
||||
previous = self._engine_by_address.get((host, port))
|
||||
self._engine_by_address[(host, port)] = engine_id
|
||||
if previous is None or previous == engine_id:
|
||||
return
|
||||
logger.info(
|
||||
"Remote engine at %s:%d changed from %s to %s.",
|
||||
host,
|
||||
port,
|
||||
previous,
|
||||
engine_id,
|
||||
)
|
||||
|
||||
def _cleanup_replaced_remote_engines(self) -> None:
|
||||
"""Release replaced pull peers once requests and handshakes have drained."""
|
||||
if self._TRANSFER_MODE != "pull":
|
||||
return
|
||||
with self._handshake_lock:
|
||||
if self._handshake_futures:
|
||||
return
|
||||
replaced = self._remote_agents.keys() - self._engine_by_address.values()
|
||||
if not replaced:
|
||||
return
|
||||
# _recving_metadata is only accessed from this (main) thread.
|
||||
busy = {
|
||||
meta.remote.engine_id
|
||||
for meta in self._recving_metadata.values()
|
||||
if meta.remote is not None
|
||||
}
|
||||
for engine_id in replaced - busy:
|
||||
self._cleanup_remote_engine(engine_id, log_eviction=False)
|
||||
logger.info("Released NIXL state for replaced remote engine %s.", engine_id)
|
||||
|
||||
def _cleanup_remote_engine(
|
||||
self, engine_id: EngineId, *, log_eviction: bool = True
|
||||
) -> None:
|
||||
"""Remove all state for a single remote engine.
|
||||
|
||||
Releases NIXL resources (dlist handles, remote agents) and clears
|
||||
all per-engine data structures. Used by both TTL eviction and
|
||||
shutdown.
|
||||
all per-engine data structures. Used by TTL eviction, replaced peer
|
||||
cleanup and shutdown.
|
||||
"""
|
||||
assert engine_id in self._remote_agents
|
||||
|
||||
@@ -3539,6 +3601,9 @@ class NixlBaseConnectorWorker:
|
||||
# Pop under the handshake lock; NIXL teardown stays outside it.
|
||||
with self._handshake_lock:
|
||||
agents = self._remote_agents.pop(engine_id)
|
||||
for address, eid in list(self._engine_by_address.items()):
|
||||
if eid == engine_id:
|
||||
del self._engine_by_address[address]
|
||||
for agent_name in agents.values():
|
||||
self.nixl_wrapper.remove_remote_agent(agent_name)
|
||||
|
||||
|
||||
@@ -84,7 +84,14 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
|
||||
# Start transfers for requests whose handshakes have now finished.
|
||||
while not self._ready_requests.empty():
|
||||
self._read_blocks_for_req(*self._ready_requests.get_nowait())
|
||||
req_id, meta = self._ready_requests.get_nowait()
|
||||
assert meta.remote is not None
|
||||
if meta.remote.engine_id not in self._remote_agents:
|
||||
# The engine was released after its handshake completed, so
|
||||
# handshake again. This fails if the engine is gone.
|
||||
self._background_nixl_handshake(req_id, meta.remote.engine_id, meta)
|
||||
continue
|
||||
self._read_blocks_for_req(req_id, meta)
|
||||
|
||||
if self.pcp_rank > 0 and not self.pcp_dcp_sharded:
|
||||
# Replicated-KV PCP: only PCP rank 0 serves the KV, so this rank
|
||||
|
||||
@@ -103,6 +103,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
# (``_pop_done_transfers``); guarded by
|
||||
# ``_sending_transfers_lock``.
|
||||
self._sending_transfers = defaultdict[ReqId, list[TransferHandle]](list)
|
||||
self._send_failures: set[ReqId] = set()
|
||||
self._sending_transfers_lock = threading.Lock()
|
||||
|
||||
# Writer-thread owned matching state.
|
||||
@@ -162,6 +163,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
for handle in handles:
|
||||
self.nixl_wrapper.release_xfer_handle(handle)
|
||||
self._sending_transfers.clear()
|
||||
self._send_failures.clear()
|
||||
super().shutdown()
|
||||
|
||||
# --- Engine-main-thread entry point -------------------------------- #
|
||||
@@ -178,6 +180,12 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
)
|
||||
assert meta.remote is not None
|
||||
remote_engine_id = meta.remote.engine_id
|
||||
# Update last activity from this remote (same as pull), but only for
|
||||
# an already-connected engine so we never leave an _engine_last_active
|
||||
# entry without a _remote_agents entry (breaks _cleanup_remote_engine).
|
||||
if remote_engine_id in self._remote_agents:
|
||||
self._engine_last_active[remote_engine_id] = time.perf_counter()
|
||||
|
||||
logger.debug(
|
||||
"start_load_kv (push) for request %s from remote engine %s. "
|
||||
"Num local_block_ids: %s. Num remote_block_ids: %s. ",
|
||||
@@ -728,6 +736,8 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
# don't have a ``_recving_metadata`` entry to invalidate, so
|
||||
# we just release the handle and let the engine reschedule
|
||||
# via the lease / watchdog.
|
||||
with self._sending_transfers_lock:
|
||||
self._send_failures.add(request_id)
|
||||
if not self._handle_failed_transfer(request_id, handle):
|
||||
return handle
|
||||
return None
|
||||
@@ -811,13 +821,16 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
done_pushing, failed_pushing = self._pop_done_transfers(
|
||||
self._sending_transfers
|
||||
)
|
||||
# A failed send must never be reported as done: its blocks
|
||||
# are freed via the lease / watchdog instead.
|
||||
done_pushing = {
|
||||
req_id
|
||||
for req_id in done_pushing - failed_pushing
|
||||
if req_id in self._recving_metadata
|
||||
}
|
||||
# Remember failures until the final sibling WRITE completes.
|
||||
self._send_failures.update(failed_pushing)
|
||||
successful = {
|
||||
req_id
|
||||
for req_id in done_pushing - self._send_failures
|
||||
if req_id in self._reqs_to_send or req_id in self._reqs_to_process
|
||||
}
|
||||
self._send_failures.difference_update(done_pushing | done_sending)
|
||||
# Expired requests were already reported, even if their WRITEs finish later.
|
||||
done_pushing = successful
|
||||
for req_id in done_pushing:
|
||||
self._reqs_to_send.pop(req_id, None)
|
||||
self._reqs_to_process.discard(req_id)
|
||||
|
||||
@@ -247,12 +247,22 @@ class OffloadingEventsTracker:
|
||||
the underlying :class:`OffloadingEvent` stream.
|
||||
|
||||
"""
|
||||
removed_keys: set[OffloadKey] = set()
|
||||
for event in events:
|
||||
if event.removed:
|
||||
if self.self_describing_enabled:
|
||||
removed_keys.update(event.keys)
|
||||
yield from self._take_removed_event(event)
|
||||
else:
|
||||
yield from self._take_stored_event(event)
|
||||
|
||||
# A primary removal can precede a queued secondary store in this batch.
|
||||
# Keep its payload until all stores have registered their residencies.
|
||||
for key in removed_keys:
|
||||
meta = self._pending_event_metadata.get(key)
|
||||
if meta is not None and not meta.active_residencies:
|
||||
self._pending_event_metadata.pop(key)
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Drop all tracked state; pending payloads are stale after a
|
||||
manager cache reset."""
|
||||
@@ -407,8 +417,6 @@ class OffloadingEventsTracker:
|
||||
maybe_convert_block_hash(h) for h in meta.block_hashes
|
||||
)
|
||||
meta.active_residencies.discard((event.medium, event.ownership))
|
||||
if not meta.active_residencies:
|
||||
self._pending_event_metadata.pop(key)
|
||||
else:
|
||||
if self.self_describing_enabled:
|
||||
logger.warning_once(
|
||||
|
||||
@@ -131,19 +131,14 @@ class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
pass
|
||||
|
||||
def wait_for_save(self):
|
||||
# Store deferral is handled in get_finished(), which always runs even
|
||||
# when wait_for_save() is skipped (e.g. kv_connector_no_forward).
|
||||
pass
|
||||
assert self.connector_worker is not None
|
||||
assert isinstance(self._connector_metadata, OffloadingConnectorMetadata)
|
||||
# Defer store jobs to the next step's start_kv_transfers.
|
||||
self.connector_worker.prepare_store_kv(self._connector_metadata)
|
||||
|
||||
def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]:
|
||||
assert self.connector_worker is not None
|
||||
assert isinstance(self._connector_metadata, OffloadingConnectorMetadata)
|
||||
|
||||
# Defer store jobs to the next step's start_kv_transfers. Done here
|
||||
# (rather than wait_for_save) so stores are queued even on steps where
|
||||
# wait_for_save is skipped.
|
||||
self.connector_worker.prepare_store_kv(self._connector_metadata)
|
||||
|
||||
return self.connector_worker.get_finished(finished_req_ids)
|
||||
|
||||
def build_connector_worker_meta(self) -> OffloadingWorkerMetadata | None:
|
||||
|
||||
@@ -15,6 +15,12 @@ from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorRole,
|
||||
SupportsHMA,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
KVConnectorPromMetrics,
|
||||
KVConnectorStats,
|
||||
PromMetric,
|
||||
PromMetricT,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
@@ -25,6 +31,10 @@ from vllm.v1.simple_kv_offload.manager import (
|
||||
from vllm.v1.simple_kv_offload.metadata import (
|
||||
SimpleCPUOffloadMetadata,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.metrics import (
|
||||
SimpleCPUOffloadPromMetrics,
|
||||
SimpleCPUOffloadStats,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.worker import (
|
||||
SimpleCPUOffloadWorker,
|
||||
)
|
||||
@@ -162,6 +172,7 @@ class SimpleCPUOffloadConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
hash_block_size=hash_block_size,
|
||||
lazy_offload=lazy_offload,
|
||||
disk_capacity_bytes=disk_capacity_bytes if disk_mode else 0,
|
||||
use_page_cache=use_page_cache if disk_mode else False,
|
||||
)
|
||||
elif role == KVConnectorRole.WORKER:
|
||||
self.worker_handler = SimpleCPUOffloadWorker(
|
||||
@@ -307,6 +318,38 @@ class SimpleCPUOffloadConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
return self.scheduler_manager.get_boundary_store_stats()
|
||||
return None
|
||||
|
||||
def get_kv_connector_stats(self) -> KVConnectorStats | None:
|
||||
# Worker-side callers may invoke this hook on connectors constructed
|
||||
# via __new__ (as in test_worker.py), which lack scheduler_manager.
|
||||
scheduler_manager: SimpleCPUOffloadScheduler | None = getattr(
|
||||
self, "scheduler_manager", None
|
||||
)
|
||||
if scheduler_manager is not None:
|
||||
return scheduler_manager.get_stats()
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def build_kv_connector_stats(
|
||||
cls, data: dict[str, Any] | None = None
|
||||
) -> KVConnectorStats | None:
|
||||
return (
|
||||
SimpleCPUOffloadStats(data=data)
|
||||
if data is not None
|
||||
else SimpleCPUOffloadStats()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def build_prom_metrics(
|
||||
cls,
|
||||
vllm_config: VllmConfig,
|
||||
metric_types: dict[type[PromMetric], type[PromMetricT]],
|
||||
labelnames: list[str],
|
||||
per_engine_labelvalues: dict[int, list[object]],
|
||||
) -> KVConnectorPromMetrics:
|
||||
return SimpleCPUOffloadPromMetrics(
|
||||
vllm_config, metric_types, labelnames, per_engine_labelvalues
|
||||
)
|
||||
|
||||
def take_events(self) -> Iterable[KVCacheEvent]:
|
||||
if self.scheduler_manager is not None:
|
||||
return self.scheduler_manager.take_events()
|
||||
|
||||
@@ -1583,6 +1583,14 @@ def get_dcp_group() -> GroupCoordinator:
|
||||
return _DCP
|
||||
|
||||
|
||||
def get_dcp_world_size_and_rank(enabled: bool = True) -> tuple[int, int]:
|
||||
"""Return ``(world_size, rank)`` in the DCP group, or ``(1, 0)`` when disabled
|
||||
(e.g. a replicated draft cache) or the group is uninitialized (unit tests)."""
|
||||
if not enabled or _DCP is None:
|
||||
return 1, 0
|
||||
return _DCP.world_size, _DCP.rank_in_group
|
||||
|
||||
|
||||
_PP: GroupCoordinator | None = None
|
||||
|
||||
|
||||
|
||||
@@ -243,6 +243,12 @@ WeightTransferEngineFactory.register_engine(
|
||||
"ShardedRDTWeightTransferEngine",
|
||||
)
|
||||
|
||||
WeightTransferEngineFactory.register_engine(
|
||||
"nccl_m2n",
|
||||
"vllm.distributed.weight_transfer.m2n_engine",
|
||||
"M2NWeightTransferEngine",
|
||||
)
|
||||
|
||||
|
||||
# Trainer-side engines, parallel to the worker registry above.
|
||||
WeightTransferTrainerFactory.register_engine(
|
||||
@@ -268,3 +274,9 @@ WeightTransferTrainerFactory.register_engine(
|
||||
"vllm.distributed.weight_transfer.sharded_rdt_trainer",
|
||||
"ShardedRDTTrainerWeightTransferEngine",
|
||||
)
|
||||
|
||||
WeightTransferTrainerFactory.register_engine(
|
||||
"nccl_m2n",
|
||||
"vllm.distributed.weight_transfer.m2n_trainer",
|
||||
"M2NTrainerWeightTransferEngine",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared helpers for the NCCL M2N (`nccl_m2n`) weight transfer backend.
|
||||
|
||||
M2N reshards a tensor between two disjoint meshes of ranks that live in one
|
||||
communicator: the trainer occupies ranks `[0, T)` and the inference workers
|
||||
`[T, T + N)`. This module holds everything both sides need — the optional
|
||||
runtime import, layout descriptors, and the conversion to `nccl.m2n` types —
|
||||
so the engine module stays about the transfer itself.
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.weight_transfer.base import ParamMeta
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
|
||||
# Placement code for a mesh axis that replicates. Any other (non-negative) code
|
||||
# is the tensor dim that axis shards. Ints rather than `nccl.m2n` objects so
|
||||
# layouts survive the JSON init handshake without a custom encoder.
|
||||
REPLICATE = -1
|
||||
|
||||
# `NCCL_RESHARD_MAX_TENSOR_DIMS`; 4-D and higher are rejected by the library.
|
||||
MAX_TENSOR_DIMS = 3
|
||||
|
||||
MESH_NDIMS = 2
|
||||
|
||||
# Destination mesh convention. Keeping these roles named avoids scattering
|
||||
# positional axis assumptions through the worker-side planner.
|
||||
DESTINATION_REPLICA_AXIS = 0
|
||||
DESTINATION_SHARD_AXIS = 1
|
||||
|
||||
# m2n bounds how many source shards may feed one destination shard, and how many
|
||||
# destination shards one source shard may feed, with compile-time arrays in
|
||||
# `reshard_limits.h`. The bindings do not expose them, so they are mirrored
|
||||
# here; a build with larger arrays makes these conservative, never wrong.
|
||||
MAX_SOURCE_SHARDS = 16
|
||||
MAX_DEST_SHARDS = 64
|
||||
|
||||
# Wire dtypes `ncclReshard` accepts. Notably excludes fp4 and any packed
|
||||
# sub-byte type, so quantized checkpoints are out of scope for now.
|
||||
SUPPORTED_DTYPES: frozenset[torch.dtype] = frozenset(
|
||||
dtype
|
||||
for dtype in (
|
||||
getattr(torch, name, None)
|
||||
for name in (
|
||||
"int8",
|
||||
"uint8",
|
||||
"float8_e4m3fn",
|
||||
"float8_e5m2",
|
||||
"float16",
|
||||
"bfloat16",
|
||||
"int32",
|
||||
"uint32",
|
||||
"float32",
|
||||
"int64",
|
||||
"uint64",
|
||||
"float64",
|
||||
)
|
||||
)
|
||||
if dtype is not None
|
||||
)
|
||||
|
||||
_IMPORT_HINT = (
|
||||
"The nccl_m2n weight transfer backend requires the `nccl-extensions` "
|
||||
"package (and its `nccl4py` dependency), which is not installed by vLLM. "
|
||||
"See https://github.com/NVIDIA/nccl-extensions for build "
|
||||
"and install instructions. It needs NCCL 2.30.5 or newer, and "
|
||||
"VLLM_NCCL_SO_PATH must point at the same libnccl.so that libnccl_m2n.so "
|
||||
"was linked against."
|
||||
)
|
||||
|
||||
|
||||
def import_m2n() -> Any:
|
||||
"""Import `nccl.m2n` lazily, with an actionable error when it is missing.
|
||||
|
||||
Deferred so that importing vLLM — or any other weight transfer backend —
|
||||
never requires the m2n runtime to be present.
|
||||
"""
|
||||
try:
|
||||
import nccl.m2n as m2n
|
||||
except ImportError as e:
|
||||
raise ImportError(f"{_IMPORT_HINT} (import failed: {e})") from e
|
||||
return m2n
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class M2NMesh:
|
||||
"""One side's rank topology — pure topology, no tensor placement.
|
||||
|
||||
Mirrors `ncclMesh_t`: a 2-axis mesh owning the contiguous rank interval
|
||||
`[start_rank, start_rank + dims[0] * dims[1])`. There is no 1-D mesh; a
|
||||
single-axis topology is spelled with a second axis of size 1.
|
||||
|
||||
One mesh describes every tensor on its side, so it is exchanged once at the
|
||||
init handshake rather than per parameter.
|
||||
"""
|
||||
|
||||
dims: tuple[int, int]
|
||||
start_rank: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if len(self.dims) != MESH_NDIMS or any(d <= 0 for d in self.dims):
|
||||
raise ValueError(f"mesh dims must be {MESH_NDIMS} positive ints")
|
||||
if self.start_rank < 0:
|
||||
raise ValueError(
|
||||
f"mesh start_rank must be non-negative, got {self.start_rank}"
|
||||
)
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
return self.dims[0] * self.dims[1]
|
||||
|
||||
|
||||
# A tensor's placement over its side's mesh: one code per mesh axis
|
||||
# (`REPLICATE`, or the tensor dim that axis shards), or `REPLICATED` for a
|
||||
# tensor every rank holds in full.
|
||||
Placements = tuple[int, int]
|
||||
REPLICATED: Placements | None = None
|
||||
|
||||
|
||||
def check_placements(placements: Placements, context: str = "placements") -> None:
|
||||
"""Reject placement pairs m2n cannot express.
|
||||
|
||||
The header requires exactly one SHARD axis and one REPLICATE axis.
|
||||
`{REPLICATE, REPLICATE}` hits a degenerate prepare branch, which is why
|
||||
full replication is carried as `REPLICATED` and resolved separately;
|
||||
sharding both axes is not expressible at all.
|
||||
"""
|
||||
if len(placements) != MESH_NDIMS:
|
||||
raise ValueError(f"{context} must have {MESH_NDIMS} entries")
|
||||
invalid = [code for code in placements if code < REPLICATE]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
f"{context} contains invalid placement code {invalid[0]}; valid "
|
||||
f"codes are {REPLICATE} (Replicate) and non-negative tensor dimensions"
|
||||
)
|
||||
num_sharded = sum(code != REPLICATE for code in placements)
|
||||
if num_sharded == 0:
|
||||
raise ValueError(
|
||||
f"{context}: a fully replicated tensor is carried as REPLICATED, "
|
||||
"not as two "
|
||||
"REPLICATE axes"
|
||||
)
|
||||
if num_sharded == MESH_NDIMS:
|
||||
raise ValueError(
|
||||
f"{context}: nccl_m2n needs one REPLICATE mesh axis, but "
|
||||
f"{placements} shards both"
|
||||
)
|
||||
|
||||
|
||||
def resolve_layout(
|
||||
mesh: M2NMesh,
|
||||
placements: Placements | None,
|
||||
context: str = "placements",
|
||||
) -> tuple[M2NMesh, Placements]:
|
||||
"""Pair one tensor's placement with the mesh m2n should see for it.
|
||||
|
||||
A replicated tensor needs a size-1 mesh axis to carry a no-op shard, since
|
||||
m2n has no `{REPLICATE, REPLICATE}`. It is therefore described over the
|
||||
*same rank interval* re-factored as `(size, 1)`. That re-factoring is sound
|
||||
precisely because replication is order-independent — every rank holds the
|
||||
whole tensor, so it does not matter that `(a, b)` and `(size, 1)` walk the
|
||||
interval in a different order. A sharded tensor keeps its side's own
|
||||
factorization, where rank order decides who owns which shard.
|
||||
"""
|
||||
if placements is None:
|
||||
return M2NMesh((mesh.size, 1), mesh.start_rank), (REPLICATE, 0)
|
||||
check_placements(placements, context)
|
||||
return mesh, placements
|
||||
|
||||
|
||||
def shard_count(mesh: M2NMesh, placements: Placements) -> int:
|
||||
"""How many pieces this layout splits the tensor into."""
|
||||
return next(
|
||||
(mesh.dims[axis] for axis, code in enumerate(placements) if code != REPLICATE),
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
def check_plan_limits(
|
||||
src: tuple[M2NMesh, Placements],
|
||||
dst: tuple[M2NMesh, Placements],
|
||||
name: str,
|
||||
) -> None:
|
||||
"""Reject plans that exceed m2n's static per-shard fan-in / fan-out arrays.
|
||||
|
||||
Only the unambiguous cases are checked: when one side is a single shard it
|
||||
is fed by (or feeds) every shard on the other side, so the count is exactly
|
||||
the other side's shard count. In the general sharded-to-sharded case the
|
||||
overlap depends on the library's chunking, and reproducing that arithmetic
|
||||
here would duplicate internals that can change under us.
|
||||
|
||||
m2n re-checks authoritatively and, because the plan is derived from the
|
||||
shared descriptors, fails identically on every rank -- so this is about
|
||||
reporting at init with a message that names the parameter, not about
|
||||
avoiding a hang.
|
||||
"""
|
||||
src_shards = shard_count(*src)
|
||||
dst_shards = shard_count(*dst)
|
||||
if dst_shards == 1 and src_shards > MAX_SOURCE_SHARDS:
|
||||
raise ValueError(
|
||||
f"parameter '{name}' would feed {src_shards} source shards into one "
|
||||
f"replicated destination, over m2n's MAX_SOURCES={MAX_SOURCE_SHARDS}. "
|
||||
"Shard the destination, replicate the source, or rebuild m2n with "
|
||||
"larger arrays."
|
||||
)
|
||||
if src_shards == 1 and dst_shards > MAX_DEST_SHARDS:
|
||||
raise ValueError(
|
||||
f"parameter '{name}' would fan one source shard out to {dst_shards} "
|
||||
f"destination shards, over m2n's MAX_TARGETS={MAX_DEST_SHARDS}. "
|
||||
"Rebuild m2n with larger arrays to raise the bound."
|
||||
)
|
||||
|
||||
|
||||
def validate_layout(
|
||||
mesh: M2NMesh, placements: Placements, shape: Sequence[int], side: str
|
||||
) -> None:
|
||||
"""Check a resolved layout can describe `shape` before any collective runs.
|
||||
|
||||
Called on both sides at init so a bad plan surfaces as an error from the
|
||||
init RPC rather than as a hang inside the first reshard.
|
||||
"""
|
||||
for axis, code in enumerate(placements):
|
||||
if code == REPLICATE:
|
||||
continue
|
||||
if code >= len(shape):
|
||||
raise ValueError(
|
||||
f"{side} layout shards tensor dim {code}, but the tensor "
|
||||
f"has rank {len(shape)}"
|
||||
)
|
||||
factor = mesh.dims[axis]
|
||||
if shape[code] % factor:
|
||||
raise ValueError(
|
||||
f"{side} layout shards dim {code} (size {shape[code]}) over "
|
||||
f"{factor} ranks, which does not divide evenly"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class M2NParamMeta(ParamMeta):
|
||||
"""`ParamMeta` extended with how the trainer places this tensor.
|
||||
|
||||
The base class carries only name / dtype / full shape, which is not enough
|
||||
to plan a reshard. `placements` is relative to its side's `M2NMesh`, or
|
||||
`REPLICATED` when every rank holds the whole tensor.
|
||||
"""
|
||||
|
||||
placements: Placements | None
|
||||
|
||||
|
||||
def check_transferable(name: str, dtype: torch.dtype, shape: Sequence[int]) -> None:
|
||||
"""Reject tensors m2n cannot move at all, with the parameter named."""
|
||||
if dtype not in SUPPORTED_DTYPES:
|
||||
raise ValueError(
|
||||
f"parameter '{name}' has dtype {dtype}, which nccl_m2n does not "
|
||||
f"support. Supported: {sorted(str(d) for d in SUPPORTED_DTYPES)}"
|
||||
)
|
||||
if not 1 <= len(shape) <= MAX_TENSOR_DIMS:
|
||||
raise ValueError(
|
||||
f"parameter '{name}' has rank {len(shape)}; nccl_m2n supports "
|
||||
f"rank 1..{MAX_TENSOR_DIMS}"
|
||||
)
|
||||
|
||||
|
||||
def to_mesh(m2n: Any, mesh: M2NMesh) -> Any:
|
||||
return m2n.Mesh(mesh.dims, start_rank=mesh.start_rank)
|
||||
|
||||
|
||||
def to_placements(m2n: Any, placements: Placements) -> list[Any]:
|
||||
return [
|
||||
m2n.Replicate() if code == REPLICATE else m2n.Shard(code) for code in placements
|
||||
]
|
||||
|
||||
|
||||
def publish_destination_placements(
|
||||
comm: "PyNcclCommunicator",
|
||||
first_worker_rank: int,
|
||||
placements: "Sequence[Placements | None] | None",
|
||||
num_parameters: int,
|
||||
) -> list[Placements | None]:
|
||||
"""Share the worker-side destination plan with every rank in the group.
|
||||
|
||||
The trainer must issue each reshard with the same destination the workers
|
||||
use, but once destinations are per-parameter they depend on the inference
|
||||
model, which only the workers can see. The first worker publishes them here,
|
||||
over the shared NCCL communicator; trainer ranks pass `None` and receive
|
||||
them, and the other workers pass their own so a disagreement is caught
|
||||
rather than deadlocking later.
|
||||
|
||||
Only placements travel: the destination *mesh* is still derived from the
|
||||
rank split, identically on both sides. Use the NCCL communicator directly
|
||||
because unique-id rendezvous deliberately has no bootstrap process group.
|
||||
"""
|
||||
replicated_sentinel = REPLICATE - 1
|
||||
encoded = torch.full(
|
||||
(num_parameters, MESH_NDIMS),
|
||||
replicated_sentinel,
|
||||
dtype=torch.int8,
|
||||
device=comm.device,
|
||||
)
|
||||
if comm.rank == first_worker_rank:
|
||||
if placements is None or len(placements) != num_parameters:
|
||||
raise ValueError(
|
||||
f"publishing rank needs {num_parameters} destination placements"
|
||||
)
|
||||
rows = [
|
||||
[replicated_sentinel] * MESH_NDIMS if placement is REPLICATED else placement
|
||||
for placement in placements
|
||||
]
|
||||
if rows:
|
||||
encoded.copy_(torch.tensor(rows, dtype=torch.int8, device=comm.device))
|
||||
|
||||
comm.broadcast(encoded, src=first_worker_rank)
|
||||
return [
|
||||
REPLICATED
|
||||
if all(code == replicated_sentinel for code in row)
|
||||
else cast(Placements, tuple(row))
|
||||
for row in encoded.tolist()
|
||||
]
|
||||
|
||||
|
||||
def comm_ptr(comm: "PyNcclCommunicator") -> int:
|
||||
"""Raw `ncclComm_t` behind vLLM's `PyNcclCommunicator`.
|
||||
|
||||
m2n links its own NCCL, so the handle only means anything if vLLM loaded
|
||||
the same `libnccl.so` — set `VLLM_NCCL_SO_PATH` accordingly.
|
||||
"""
|
||||
handle = comm.comm
|
||||
ptr = getattr(handle, "value", handle)
|
||||
if not ptr:
|
||||
raise RuntimeError("PyNcclCommunicator has no live NCCL communicator")
|
||||
return int(ptr)
|
||||
@@ -0,0 +1,453 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Inference-side weight transfer engine built on NCCL M2N (`nccl_m2n`).
|
||||
|
||||
The trainer and the inference workers share one NCCL communicator: trainer ranks
|
||||
occupy `[0, T)`, workers `[T, T + N)`. Each parameter is moved with a single
|
||||
`nccl.m2n.reshard`, which redistributes it from the trainer's layout (FSDP / EP
|
||||
/ arbitrary DTensor sharding) to the inference layout — so the trainer sends its
|
||||
local shards and never all-gathers a full tensor, which is what the broadcast
|
||||
NCCL backend forces it to do.
|
||||
|
||||
When an incoming checkpoint parameter maps directly to a live vLLM parameter,
|
||||
M2N reshards into that worker's local model storage. Parameters whose names or
|
||||
layouts cannot be resolved receive a full tensor and fall back to
|
||||
`load_weights`, preserving the existing backend's loading behavior.
|
||||
|
||||
Both meshes participate in every reshard, in the same order, so this backend has
|
||||
the same concurrency shape as the broadcast NCCL backend: the worker must be
|
||||
inside `receive_weights` while the trainer is sending. Driving that from the
|
||||
trainer is the trainer engine's job.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config.weight_transfer import WeightTransferConfig
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
WeightTransferEngine,
|
||||
WeightTransferInitInfo,
|
||||
WeightTransferUpdateInfo,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.m2n_common import (
|
||||
DESTINATION_SHARD_AXIS,
|
||||
MESH_NDIMS,
|
||||
REPLICATED,
|
||||
M2NMesh,
|
||||
M2NParamMeta,
|
||||
Placements,
|
||||
check_plan_limits,
|
||||
check_transferable,
|
||||
comm_ptr,
|
||||
import_m2n,
|
||||
publish_destination_placements,
|
||||
resolve_layout,
|
||||
to_mesh,
|
||||
to_placements,
|
||||
validate_layout,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.m2n_layout import (
|
||||
M2NDestination,
|
||||
resolve_parameter_destinations,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.nccl_common import (
|
||||
NCCLWeightTransferInitInfo,
|
||||
decode_nccl_unique_id,
|
||||
worker_init_process_group,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
|
||||
__all__ = [
|
||||
"M2NWeightTransferInitInfo",
|
||||
"M2NWeightTransferUpdateInfo",
|
||||
"M2NWeightTransferEngine",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Wire types
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class M2NWeightTransferInitInfo(WeightTransferInitInfo):
|
||||
"""Worker-side init info: the rendezvous plus the full transfer plan.
|
||||
|
||||
Layouts are static for the whole run, so they ride the one-time init
|
||||
handshake and the per-round update info stays a list of names. Everything is
|
||||
plain JSON so the HTTP control plane carries it unchanged.
|
||||
"""
|
||||
|
||||
master_address: str | None = None
|
||||
master_port: int | None = None
|
||||
rank_offset: int
|
||||
"""First worker rank, i.e. the number of trainer ranks."""
|
||||
world_size: int
|
||||
"""Trainer ranks + all inference workers."""
|
||||
src_mesh_dims: list[int]
|
||||
"""The trainer's mesh, shared by every parameter (`start_rank` is 0: the
|
||||
trainer occupies the front of the communicator)."""
|
||||
dst_mesh_dims: list[int]
|
||||
"""The inference mesh, starting at `rank_offset`. Declared rather than
|
||||
derived so both sides describe the destination identically."""
|
||||
names: list[str]
|
||||
dtype_names: list[str]
|
||||
shapes: list[list[int]]
|
||||
src_placements: list[list[int] | None]
|
||||
"""Per parameter, relative to `src_mesh_dims`; `None` means replicated."""
|
||||
nccl_unique_id_b64: str | None = field(default=None, repr=False)
|
||||
max_cta: int | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_ = self.nccl_unique_id_bytes
|
||||
num_params = len(self.names)
|
||||
for label, values in (
|
||||
("dtype_names", self.dtype_names),
|
||||
("shapes", self.shapes),
|
||||
("src_placements", self.src_placements),
|
||||
):
|
||||
if len(values) != num_params:
|
||||
raise ValueError(
|
||||
f"`{label}` should be of the same size as `names`: "
|
||||
f"got {len(values)} and {num_params}"
|
||||
)
|
||||
if self.rank_offset < 1 or self.rank_offset >= self.world_size:
|
||||
raise ValueError(
|
||||
f"`rank_offset` ({self.rank_offset}) must leave at least one "
|
||||
f"trainer rank and one worker in world_size {self.world_size}"
|
||||
)
|
||||
num_workers = self.world_size - self.rank_offset
|
||||
dst = tuple(self.dst_mesh_dims)
|
||||
if len(dst) != MESH_NDIMS or dst[0] * dst[1] != num_workers:
|
||||
raise ValueError(
|
||||
f"`dst_mesh_dims` {dst} must be {MESH_NDIMS} dims covering the "
|
||||
f"{num_workers} inference workers"
|
||||
)
|
||||
|
||||
@property
|
||||
def nccl_unique_id_bytes(self) -> bytes | None:
|
||||
return decode_nccl_unique_id(
|
||||
master_address=self.master_address,
|
||||
master_port=self.master_port,
|
||||
nccl_unique_id_b64=self.nccl_unique_id_b64,
|
||||
ctx="M2NWeightTransferInitInfo",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class M2NWeightTransferUpdateInfo(WeightTransferUpdateInfo):
|
||||
"""Per-round update info: which parameters this chunk carries, in order.
|
||||
|
||||
Shapes, dtypes and layouts were fixed at init, so a round only needs to say
|
||||
what is coming and in what order — both sides must issue their reshards in
|
||||
exactly that order.
|
||||
"""
|
||||
|
||||
names: list[str]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Worker engine
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class M2NWeightTransferEngine(
|
||||
WeightTransferEngine[M2NWeightTransferInitInfo, M2NWeightTransferUpdateInfo]
|
||||
):
|
||||
"""Inference-side engine: receives each parameter with one reshard.
|
||||
|
||||
Resolvable parameters are resharded from the trainer layout directly into
|
||||
each worker's live local model storage. Unresolvable parameters receive a
|
||||
full tensor and use `load_weights`. In both cases, the trainer sends its
|
||||
local shards without materializing a full tensor.
|
||||
"""
|
||||
|
||||
init_info_cls = M2NWeightTransferInitInfo
|
||||
update_info_cls = M2NWeightTransferUpdateInfo
|
||||
# The destination plan is resolved against the model this engine was built
|
||||
# for, so it cannot be retargeted at a draft model mid-flight.
|
||||
supports_draft_weight_update = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: WeightTransferConfig,
|
||||
vllm_config: "VllmConfig",
|
||||
device: torch.device,
|
||||
model: torch.nn.Module,
|
||||
) -> None:
|
||||
super().__init__(config, vllm_config, device, model)
|
||||
self.model_update_group: PyNcclCommunicator | None = None
|
||||
self._m2n: Any = None
|
||||
self._handle: Any = None
|
||||
self._metas: list[M2NParamMeta] = []
|
||||
self._src_mesh: M2NMesh | None = None
|
||||
self._dst_mesh: M2NMesh | None = None
|
||||
self._parameter_destinations: list[M2NDestination] = []
|
||||
self._index: dict[str, int] = {}
|
||||
self._uses_load_weights = False
|
||||
|
||||
def init_transfer_engine(self, init_info: M2NWeightTransferInitInfo) -> None:
|
||||
"""Join the trainer's communicator and rebuild the transfer plan.
|
||||
|
||||
Every precondition (dtype, tensor rank, divisibility) is checked here so
|
||||
a bad plan fails the init RPC instead of hanging the first collective.
|
||||
"""
|
||||
self._m2n = import_m2n()
|
||||
self._metas = []
|
||||
|
||||
self._src_mesh = M2NMesh(
|
||||
cast(tuple[int, int], tuple(init_info.src_mesh_dims)), 0
|
||||
)
|
||||
if self._src_mesh.size != init_info.rank_offset:
|
||||
raise ValueError(
|
||||
f"source mesh covers {self._src_mesh.size} ranks, but there are "
|
||||
f"{init_info.rank_offset} trainer ranks"
|
||||
)
|
||||
# The inference topology, as declared by the trainer. This is the mesh
|
||||
# a sharded destination is placed over; a replicated one is described
|
||||
# by the alternate descriptor `resolve_layout` derives from it, which
|
||||
# covers the same ranks but is not this mesh.
|
||||
self._dst_mesh = M2NMesh(
|
||||
cast(tuple[int, int], tuple(init_info.dst_mesh_dims)),
|
||||
init_info.rank_offset,
|
||||
)
|
||||
|
||||
for name, name_dtype, shape, placements in zip(
|
||||
init_info.names,
|
||||
init_info.dtype_names,
|
||||
init_info.shapes,
|
||||
init_info.src_placements,
|
||||
):
|
||||
dtype = getattr(torch, name_dtype, None)
|
||||
if not isinstance(dtype, torch.dtype):
|
||||
raise ValueError(
|
||||
f"parameter '{name}' has invalid dtype name "
|
||||
f"'{name_dtype}'; expected the name of a torch.dtype"
|
||||
)
|
||||
check_transferable(name, dtype, shape)
|
||||
codes = (
|
||||
REPLICATED
|
||||
if placements is None
|
||||
else cast(Placements, tuple(placements))
|
||||
)
|
||||
src_mesh, src_placements = resolve_layout(
|
||||
self._src_mesh, codes, f"parameter '{name}' source placements"
|
||||
)
|
||||
validate_layout(src_mesh, src_placements, shape, "source")
|
||||
# Destination checks are deferred until loader-aware resolution;
|
||||
# assuming replication here can reject a valid sharded plan.
|
||||
self._metas.append(M2NParamMeta(name, dtype, tuple(shape), codes))
|
||||
|
||||
parallel_config = self.parallel_config
|
||||
shard_axis_size = self._dst_mesh.dims[DESTINATION_SHARD_AXIS]
|
||||
quantization = getattr(self.model_config, "quantization", None)
|
||||
# A quantized weight loader may dequantize / transpose / requantize, and
|
||||
# under PP a rank's local shape is not the checkpoint shape split over
|
||||
# the shard axis. Both break shape-derived resolution, so take the
|
||||
# fallback.
|
||||
allow_direct = (
|
||||
quantization is None and parallel_config.pipeline_parallel_size == 1
|
||||
)
|
||||
# Match every incoming checkpoint parameter to its rank-local target.
|
||||
# Resolvable parameters can be resharded directly into live model
|
||||
# storage; the rest receive a full tensor for `load_weights`.
|
||||
self._parameter_destinations = resolve_parameter_destinations(
|
||||
self.model,
|
||||
[m.name for m in self._metas],
|
||||
[m.dtype for m in self._metas],
|
||||
[m.shape for m in self._metas],
|
||||
num_workers=self._dst_mesh.size,
|
||||
shard_axis_size=shard_axis_size,
|
||||
allow_direct=allow_direct,
|
||||
)
|
||||
# Check the resolved layout rather than a provisional replicated one.
|
||||
# For example, 32 source shards feeding 4 destination shards may need
|
||||
# only 8 sources per destination, while a replicated plan needs all 32.
|
||||
for meta, destination in zip(self._metas, self._parameter_destinations):
|
||||
src_mesh, src_placements = resolve_layout(
|
||||
self._src_mesh,
|
||||
meta.placements,
|
||||
f"parameter '{meta.name}' source placements",
|
||||
)
|
||||
dst_mesh, dst_placements = resolve_layout(
|
||||
self._dst_mesh,
|
||||
destination.placements,
|
||||
f"parameter '{meta.name}' destination placements",
|
||||
)
|
||||
validate_layout(dst_mesh, dst_placements, meta.shape, "destination")
|
||||
check_plan_limits(
|
||||
(src_mesh, src_placements),
|
||||
(dst_mesh, dst_placements),
|
||||
meta.name,
|
||||
)
|
||||
|
||||
# Update requests carry names only, so cache their plan indices. Track
|
||||
# whether any fallback entry requires the `load_weights` lifecycle.
|
||||
self._index = {meta.name: i for i, meta in enumerate(self._metas)}
|
||||
self._uses_load_weights = any(
|
||||
not destination.direct for destination in self._parameter_destinations
|
||||
)
|
||||
|
||||
self.model_update_group = worker_init_process_group(
|
||||
NCCLWeightTransferInitInfo(
|
||||
master_address=init_info.master_address,
|
||||
master_port=init_info.master_port,
|
||||
nccl_unique_id_b64=init_info.nccl_unique_id_b64,
|
||||
rank_offset=init_info.rank_offset,
|
||||
world_size=init_info.world_size,
|
||||
),
|
||||
parallel_config,
|
||||
)
|
||||
# Destinations are per-parameter and depend on the inference model, so
|
||||
# the trainer cannot derive them. The first worker publishes the plan
|
||||
# and every other rank checks its own against it — a silent
|
||||
# disagreement between workers would mean mismatched collectives.
|
||||
mine = [destination.placements for destination in self._parameter_destinations]
|
||||
agreed = publish_destination_placements(
|
||||
self.model_update_group, init_info.rank_offset, mine, len(self._metas)
|
||||
)
|
||||
if agreed != mine:
|
||||
mismatched = next(
|
||||
meta.name for meta, a, b in zip(self._metas, mine, agreed) if a != b
|
||||
)
|
||||
raise RuntimeError(
|
||||
"inference workers resolved different nccl_m2n destinations "
|
||||
f"(first mismatch: '{mismatched}'); all workers must run the "
|
||||
"same model and parallel config"
|
||||
)
|
||||
|
||||
self._handle = self._m2n.Handle.create(
|
||||
self._m2n.Config(max_cta=init_info.max_cta)
|
||||
)
|
||||
|
||||
def start_weight_update(self) -> None:
|
||||
"""Set up layerwise reloading, but only if some parameter needs it.
|
||||
|
||||
Directly-resharded parameters are written in place and never go through
|
||||
`load_weights`, so a plan with no fallback entries has nothing to
|
||||
reload.
|
||||
"""
|
||||
if not self._uses_load_weights:
|
||||
return
|
||||
from vllm.model_executor.model_loader.reload import initialize_layerwise_reload
|
||||
|
||||
initialize_layerwise_reload(self.model)
|
||||
|
||||
def finish_weight_update(self) -> None:
|
||||
"""Finalize layerwise reloading when the plan uses fallback entries."""
|
||||
if not self._uses_load_weights:
|
||||
return
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload
|
||||
|
||||
finalize_layerwise_reload(self.model, self.model_config)
|
||||
|
||||
def receive_weights(self, update_info: M2NWeightTransferUpdateInfo) -> None:
|
||||
"""Receive each requested parameter using its initialization-time plan."""
|
||||
if self._handle is None or self.model_update_group is None:
|
||||
raise RuntimeError(
|
||||
"nccl_m2n weight transfer not initialized. "
|
||||
"Call init_transfer_engine() first."
|
||||
)
|
||||
|
||||
requested = []
|
||||
for name in update_info.names:
|
||||
index = self._index.get(name)
|
||||
if index is None:
|
||||
raise ValueError(
|
||||
f"parameter '{name}' was not declared at init; the "
|
||||
"trainer must send the same parameter set it announced"
|
||||
)
|
||||
requested.append((name, index))
|
||||
|
||||
from vllm.model_executor.model_loader.mtp_validation import (
|
||||
disable_mtp_completeness_check,
|
||||
)
|
||||
|
||||
comm = comm_ptr(self.model_update_group)
|
||||
stream = torch.cuda.current_stream()
|
||||
|
||||
# Reshard lazily so one `load_weights` invocation sees the complete
|
||||
# fallback sequence without staging every full tensor at once. Direct
|
||||
# destinations still execute in request order as the iterator advances.
|
||||
def reshard_requested_weights() -> Iterator[tuple[str, torch.Tensor]]:
|
||||
for name, index in requested:
|
||||
meta = self._metas[index]
|
||||
destination = self._parameter_destinations[index]
|
||||
buffer = destination.tensor
|
||||
if buffer is None:
|
||||
buffer = torch.empty(
|
||||
meta.shape, dtype=meta.dtype, device=self.device
|
||||
)
|
||||
|
||||
self._reshard(comm, stream, meta, destination.placements, buffer)
|
||||
|
||||
if destination.tensor is None:
|
||||
# `load_weights` reads on the host stream, so the transfer
|
||||
# has to have landed before it runs.
|
||||
stream.synchronize()
|
||||
yield name, buffer
|
||||
|
||||
has_fallback = any(
|
||||
self._parameter_destinations[index].tensor is None for _, index in requested
|
||||
)
|
||||
with disable_mtp_completeness_check():
|
||||
received_weights = reshard_requested_weights()
|
||||
if has_fallback:
|
||||
# Some model loaders keep invocation-local state to combine
|
||||
# related checkpoint tensors, so preserve one iterable scope.
|
||||
self.model.load_weights(received_weights)
|
||||
else:
|
||||
# The iterator performs the reshards. With nothing to yield to
|
||||
# `load_weights`, exhaust it here to execute direct transfers.
|
||||
for _ in received_weights:
|
||||
pass
|
||||
|
||||
def _reshard(
|
||||
self,
|
||||
comm: int,
|
||||
stream: torch.cuda.Stream,
|
||||
src_meta: M2NParamMeta,
|
||||
dst_placements: Placements | None,
|
||||
dst_buffer: torch.Tensor,
|
||||
) -> None:
|
||||
"""Reshard one parameter from its trainer layout into a worker buffer.
|
||||
|
||||
`dst_placements` describes the buffer's logical placement over the
|
||||
worker mesh; `dst_buffer` is this rank's physical storage.
|
||||
"""
|
||||
assert self._src_mesh is not None
|
||||
assert self._dst_mesh is not None
|
||||
m2n = self._m2n
|
||||
src_mesh, resolved_src_placements = resolve_layout(
|
||||
self._src_mesh, src_meta.placements
|
||||
)
|
||||
dst_mesh, resolved_dst_placements = resolve_layout(
|
||||
self._dst_mesh, dst_placements
|
||||
)
|
||||
m2n.reshard(
|
||||
None,
|
||||
dst_buffer,
|
||||
comm,
|
||||
stream,
|
||||
src_mesh=to_mesh(m2n, src_mesh),
|
||||
src_placements=to_placements(m2n, resolved_src_placements),
|
||||
dst_mesh=to_mesh(m2n, dst_mesh),
|
||||
dst_placements=to_placements(m2n, resolved_dst_placements),
|
||||
handle=self._handle,
|
||||
)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Finish pending GPU work and release M2N communication state."""
|
||||
if self._handle is not None:
|
||||
# M2N does not synchronize caller streams on finalize.
|
||||
torch.accelerator.synchronize()
|
||||
self._handle.destroy()
|
||||
self._handle = None
|
||||
self.model_update_group = None
|
||||
self._parameter_destinations = []
|
||||
@@ -0,0 +1,261 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Destination-layout resolution for the NCCL M2N weight transfer backend.
|
||||
|
||||
For every incoming checkpoint parameter the worker needs a destination buffer
|
||||
plus its placement over the inference mesh. Two outcomes are possible:
|
||||
|
||||
* **direct** — when the model is not quantized, the parameter maps 1:1 onto a
|
||||
live vLLM parameter and its loader is a small, known-safe copy or tensor-
|
||||
parallel loader. The loader's declared input/output dimension determines the
|
||||
placement; shapes are validation, not an inference mechanism. The reshard
|
||||
writes straight into the live parameter, so each rank receives only its own
|
||||
shard and nothing is copied afterwards.
|
||||
* **fallback** — anything else. The reshard delivers the whole tensor to every
|
||||
rank and `load_weights` does the sharding, exactly as the broadcast NCCL
|
||||
backend does. Fused parameters (`qkv_proj`, `gate_up_proj`, MoE `w13`/`w2`)
|
||||
take this path: the checkpoint name does not name a vLLM parameter, so there
|
||||
is nothing to resolve against.
|
||||
|
||||
Correctness never depends on a parameter resolving — the fallback is always
|
||||
available and is the same path the existing backend uses.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.weight_transfer.m2n_common import (
|
||||
DESTINATION_REPLICA_AXIS,
|
||||
DESTINATION_SHARD_AXIS,
|
||||
MESH_NDIMS,
|
||||
REPLICATE,
|
||||
REPLICATED,
|
||||
Placements,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_DIRECT_WEIGHT_LOADING_BLOCKLIST = {
|
||||
"vllm.model_executor.models.gpt2.GPT2Model",
|
||||
}
|
||||
|
||||
|
||||
def _module_type_name(module: torch.nn.Module) -> str:
|
||||
cls = type(module)
|
||||
return f"{cls.__module__}.{cls.__name__}"
|
||||
|
||||
|
||||
def _destination_placements(shard_dim: int) -> Placements:
|
||||
"""Place one tensor shard on the configured destination mesh axis."""
|
||||
placements = [REPLICATE] * MESH_NDIMS
|
||||
placements[DESTINATION_REPLICA_AXIS] = REPLICATE
|
||||
placements[DESTINATION_SHARD_AXIS] = shard_dim
|
||||
return cast(Placements, tuple(placements))
|
||||
|
||||
|
||||
@dataclass
|
||||
class M2NDestination:
|
||||
"""Where one checkpoint parameter lands on this worker."""
|
||||
|
||||
name: str
|
||||
placements: Placements | None
|
||||
"""Placement over the inference mesh, or `REPLICATED` for the fallback."""
|
||||
tensor: torch.Tensor | None
|
||||
"""The live parameter view to reshard into, or None for the fallback path
|
||||
(the engine allocates a full replica per round and calls `load_weights`)."""
|
||||
|
||||
@property
|
||||
def direct(self) -> bool:
|
||||
return self.tensor is not None
|
||||
|
||||
|
||||
def _base_loader_shard_dim(
|
||||
param: torch.nn.Parameter,
|
||||
shard_axis_size: int,
|
||||
) -> int | None:
|
||||
"""Return a known-safe loader's declared shard dim, or reject it.
|
||||
|
||||
Loader identity is deliberately fail-closed. A missing loader is not
|
||||
treated as ``default_weight_loader`` because a model-level ``load_weights``
|
||||
implementation may transform the tensor before it reaches that default.
|
||||
Wrappers and partials are also rejected: recognizing their wrapped callable
|
||||
would ignore behavior added by the wrapper.
|
||||
"""
|
||||
loader = getattr(param, "weight_loader", None)
|
||||
if loader is None or isinstance(loader, partial):
|
||||
return None
|
||||
|
||||
owner = loader.__self__ if inspect.ismethod(loader) else None
|
||||
loader_fn = loader.__func__ if inspect.ismethod(loader) else loader
|
||||
|
||||
# Lazy imports avoid making the weight-transfer registry import all model
|
||||
# executor layers during normal vLLM startup.
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
replicated_loaders = {
|
||||
default_weight_loader,
|
||||
ReplicatedLinear.weight_loader,
|
||||
}
|
||||
column_loaders = {
|
||||
ColumnParallelLinear.weight_loader,
|
||||
ColumnParallelLinear.weight_loader_v2,
|
||||
}
|
||||
row_loaders = {
|
||||
RowParallelLinear.weight_loader,
|
||||
RowParallelLinear.weight_loader_v2,
|
||||
}
|
||||
|
||||
# These attributes signal packing, a transform, or pre-sharded checkpoint
|
||||
# storage. Such semantics cannot be reproduced by a plain M2N placement.
|
||||
# Check them before accepting replicated loaders too: model-level loading
|
||||
# may transform a tensor before handing it to an otherwise plain copier.
|
||||
metadata_attrs = ("packed_dim", "packed_factor", "marlin_tile_size")
|
||||
flag_attrs = ("needs_scalar_to_array", "is_sharded_weight", "is_transposed")
|
||||
if any(getattr(param, attr, None) is not None for attr in metadata_attrs):
|
||||
return None
|
||||
if any(bool(getattr(param, attr, False)) for attr in flag_attrs):
|
||||
return None
|
||||
|
||||
if loader_fn in replicated_loaders:
|
||||
return REPLICATE
|
||||
if loader_fn not in column_loaders | row_loaders:
|
||||
return None
|
||||
|
||||
if owner is None or getattr(owner, "tp_size", None) != shard_axis_size:
|
||||
return None
|
||||
|
||||
attr = "output_dim" if loader_fn in column_loaders else "input_dim"
|
||||
dim = getattr(param, attr, None)
|
||||
return dim if isinstance(dim, int) and dim >= 0 else None
|
||||
|
||||
|
||||
def _validated_shard_dim(
|
||||
global_shape: Sequence[int],
|
||||
local_shape: Sequence[int],
|
||||
declared_dim: int,
|
||||
shard_axis_size: int,
|
||||
) -> int | None:
|
||||
"""Validate a loader-declared shard dimension against both shapes."""
|
||||
if len(global_shape) != len(local_shape):
|
||||
return None
|
||||
|
||||
if declared_dim == REPLICATE:
|
||||
return REPLICATE if tuple(global_shape) == tuple(local_shape) else None
|
||||
if declared_dim >= len(global_shape):
|
||||
return None
|
||||
for dim, (whole, local) in enumerate(zip(global_shape, local_shape)):
|
||||
expected = local * shard_axis_size if dim == declared_dim else local
|
||||
if whole != expected:
|
||||
return None
|
||||
return declared_dim
|
||||
|
||||
|
||||
def resolve_parameter_destinations(
|
||||
model: torch.nn.Module,
|
||||
names: Sequence[str],
|
||||
dtypes: Sequence[torch.dtype],
|
||||
shapes: Sequence[Sequence[int]],
|
||||
*,
|
||||
num_workers: int,
|
||||
shard_axis_size: int,
|
||||
allow_direct: bool,
|
||||
) -> list[M2NDestination]:
|
||||
"""Build this worker's destination plan, one entry per checkpoint parameter.
|
||||
|
||||
Placements are relative to the inference mesh: axis 0 replicates and axis 1
|
||||
shards. `allow_direct=False` forces every parameter onto the fallback path;
|
||||
the engine sets it for pipeline-parallel or quantized deployments, where a
|
||||
parameter's local shape is not simply the checkpoint shape split across the
|
||||
shard axis. Parameters below a model type with known model-level checkpoint
|
||||
preprocessing also fall back, since bypassing `load_weights` would skip the
|
||||
transformation.
|
||||
"""
|
||||
params = dict(model.named_parameters()) if allow_direct else {}
|
||||
blocked_param_ids = {
|
||||
id(param)
|
||||
for module in model.modules()
|
||||
if _module_type_name(module) in _DIRECT_WEIGHT_LOADING_BLOCKLIST
|
||||
for param in module.parameters()
|
||||
}
|
||||
|
||||
destinations: list[M2NDestination] = []
|
||||
for name, dtype, shape in zip(names, dtypes, shapes):
|
||||
param = params.get(name)
|
||||
dim = None
|
||||
if (
|
||||
param is not None
|
||||
and id(param) not in blocked_param_ids
|
||||
and param.dtype == dtype
|
||||
and param.data.is_contiguous()
|
||||
and num_workers % shard_axis_size == 0
|
||||
):
|
||||
declared_dim = _base_loader_shard_dim(param, shard_axis_size)
|
||||
if declared_dim is not None:
|
||||
dim = _validated_shard_dim(
|
||||
shape, param.shape, declared_dim, shard_axis_size
|
||||
)
|
||||
|
||||
if dim is None:
|
||||
# A replicated parameter is identical on every rank, so it needs no
|
||||
# placement of its own — REPLICATED lets resolve_layout spread it
|
||||
# over all the workers regardless of how the mesh is factored.
|
||||
destinations.append(M2NDestination(name, REPLICATED, None))
|
||||
elif dim == REPLICATE:
|
||||
assert param is not None
|
||||
destinations.append(M2NDestination(name, REPLICATED, param.data))
|
||||
else:
|
||||
assert param is not None
|
||||
destinations.append(
|
||||
M2NDestination(name, _destination_placements(dim), param.data)
|
||||
)
|
||||
|
||||
# Layerwise reload finalizes a module as a unit. Mixing direct and fallback
|
||||
# parameters within one module can copy stale storage over the direct load.
|
||||
fallback_modules = {
|
||||
name.rpartition(".")[0]
|
||||
for name, destination in zip(names, destinations)
|
||||
if not destination.direct and name in params
|
||||
}
|
||||
destinations = [
|
||||
M2NDestination(destination.name, REPLICATED, None)
|
||||
if destination.direct
|
||||
and destination.name.rpartition(".")[0] in fallback_modules
|
||||
else destination
|
||||
for destination in destinations
|
||||
]
|
||||
|
||||
num_direct = sum(d.direct for d in destinations)
|
||||
parameter_bytes = [
|
||||
math.prod(shape) * dtype.itemsize for dtype, shape in zip(dtypes, shapes)
|
||||
]
|
||||
total_bytes = sum(parameter_bytes)
|
||||
direct_bytes = sum(
|
||||
nbytes
|
||||
for destination, nbytes in zip(destinations, parameter_bytes)
|
||||
if destination.direct
|
||||
)
|
||||
direct_byte_percentage = 100 * direct_bytes / total_bytes if total_bytes else 0
|
||||
logger.info(
|
||||
"nccl_m2n destination plan: %d/%d parameters resharded directly into "
|
||||
"the model, %d via full-tensor fallback; direct byte coverage: "
|
||||
"%d/%d bytes (%.1f%%)",
|
||||
num_direct,
|
||||
len(destinations),
|
||||
len(destinations) - num_direct,
|
||||
direct_bytes,
|
||||
total_bytes,
|
||||
direct_byte_percentage,
|
||||
)
|
||||
return destinations
|
||||
@@ -0,0 +1,155 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Trainer-side weight sources for the NCCL M2N backend.
|
||||
|
||||
m2n plans a transfer from both sides' layouts, so the trainer has to say how it
|
||||
holds each parameter — which the base `WeightSource` / `ParamMeta` pair does not
|
||||
express. This module supplies the m2n flavor of both, and the DTensor-backed
|
||||
implementation that covers the common trainer.
|
||||
|
||||
A source declares its mesh once (`mesh()`) and a placement per parameter, since
|
||||
one topology describes every tensor on the side.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.weight_transfer.base import ParamMeta, WeightSource
|
||||
from vllm.distributed.weight_transfer.m2n_common import (
|
||||
REPLICATE,
|
||||
REPLICATED,
|
||||
M2NMesh,
|
||||
M2NParamMeta,
|
||||
Placements,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"M2NWeightSource",
|
||||
"DTensorModuleSource",
|
||||
"mesh_from_tensor",
|
||||
"placements_from_tensor",
|
||||
]
|
||||
|
||||
|
||||
class M2NWeightSource(WeightSource):
|
||||
"""A `WeightSource` that also describes how the trainer holds its weights.
|
||||
|
||||
Unlike `ModuleSource`, iteration yields each rank's **local shard**, not a
|
||||
materialized full tensor: gathering is exactly the cost m2n removes.
|
||||
"""
|
||||
|
||||
def mesh(self) -> M2NMesh:
|
||||
"""The trainer's rank topology, shared by every parameter."""
|
||||
raise NotImplementedError
|
||||
|
||||
def metadata(self) -> list[ParamMeta]:
|
||||
"""Name, dtype, full shape, and trainer placement for each parameter."""
|
||||
raise NotImplementedError
|
||||
|
||||
def __iter__(self) -> Iterator[tuple[str, torch.Tensor]]:
|
||||
"""Yield `(name, local shard)` pairs in the same order as `metadata()`."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def _placement_code(placement: Any) -> int:
|
||||
"""Map a `torch.distributed` placement onto an m2n placement code."""
|
||||
name = type(placement).__name__
|
||||
if name == "Replicate":
|
||||
return REPLICATE
|
||||
if name == "Shard":
|
||||
return int(placement.dim)
|
||||
raise ValueError(
|
||||
f"nccl_m2n cannot express the {name} placement; only Replicate and "
|
||||
"Shard are supported"
|
||||
)
|
||||
|
||||
|
||||
def mesh_from_tensor(tensor: torch.Tensor, num_trainer_ranks: int) -> M2NMesh:
|
||||
"""The mesh a parameter lives on, as an `M2NMesh`.
|
||||
|
||||
A plain tensor is identical on every trainer rank, so it spans all of them.
|
||||
"""
|
||||
device_mesh = getattr(tensor, "device_mesh", None)
|
||||
if device_mesh is None:
|
||||
return M2NMesh((num_trainer_ranks, 1), 0)
|
||||
|
||||
grid = device_mesh.mesh
|
||||
ranks = grid.flatten().tolist()
|
||||
if ranks != list(range(len(ranks))):
|
||||
raise ValueError(
|
||||
"nccl_m2n requires the trainer's device mesh to cover the "
|
||||
f"contiguous rank interval [0, {len(ranks)}); got {ranks}"
|
||||
)
|
||||
if grid.ndim > 2:
|
||||
raise ValueError(
|
||||
f"nccl_m2n supports 1-D and 2-D device meshes, got {grid.ndim}-D"
|
||||
)
|
||||
dims = tuple(grid.shape)
|
||||
return M2NMesh(dims if len(dims) == 2 else (dims[0], 1), 0)
|
||||
|
||||
|
||||
def placements_from_tensor(tensor: torch.Tensor) -> Placements | None:
|
||||
"""How a parameter is placed over its mesh, or `REPLICATED`.
|
||||
|
||||
`REPLICATED` is returned rather than a `(REPLICATE, REPLICATE)` pair: m2n
|
||||
cannot express that, and the size-1-axis encoding it needs instead is
|
||||
applied later by `resolve_layout`, which owns that workaround.
|
||||
"""
|
||||
placements = getattr(tensor, "placements", None)
|
||||
if placements is None:
|
||||
return REPLICATED
|
||||
codes = [_placement_code(p) for p in placements]
|
||||
if all(code == REPLICATE for code in codes):
|
||||
return REPLICATED
|
||||
if len(codes) == 1:
|
||||
return (codes[0], REPLICATE)
|
||||
return (codes[0], codes[1])
|
||||
|
||||
|
||||
class DTensorModuleSource(M2NWeightSource):
|
||||
"""`M2NWeightSource` over `module.named_parameters()`.
|
||||
|
||||
Covers both the FSDP/DTensor trainer (placement read off each parameter,
|
||||
local shard yielded via `to_local()`) and the plain replicated trainer, with
|
||||
no special casing. Trainers with a custom producer (a Megatron export, MoE
|
||||
re-fusing) subclass `M2NWeightSource` instead.
|
||||
"""
|
||||
|
||||
def __init__(self, module: torch.nn.Module, num_trainer_ranks: int) -> None:
|
||||
"""Wrap `module`; `num_trainer_ranks` sizes the mesh for plain tensors."""
|
||||
self._module = module
|
||||
self._num_trainer_ranks = num_trainer_ranks
|
||||
|
||||
def mesh(self) -> M2NMesh:
|
||||
"""The mesh every sharded parameter agrees on.
|
||||
|
||||
Replicated parameters span the trainer without a device mesh of their
|
||||
own, so they never decide this; a model whose *sharded* parameters
|
||||
disagree cannot be described by one side mesh and is rejected.
|
||||
"""
|
||||
meshes = {
|
||||
mesh_from_tensor(p, self._num_trainer_ranks)
|
||||
for _, p in self._module.named_parameters()
|
||||
if placements_from_tensor(p) is not REPLICATED
|
||||
}
|
||||
if len(meshes) > 1:
|
||||
raise ValueError(
|
||||
"nccl_m2n needs one mesh per side, but this module's sharded "
|
||||
f"parameters span several: {sorted(m.dims for m in meshes)}"
|
||||
)
|
||||
return meshes.pop() if meshes else M2NMesh((self._num_trainer_ranks, 1), 0)
|
||||
|
||||
def metadata(self) -> list[ParamMeta]:
|
||||
"""Read global shape/dtype and placements without gathering shards."""
|
||||
return [
|
||||
M2NParamMeta(name, p.dtype, tuple(p.shape), placements_from_tensor(p))
|
||||
for name, p in self._module.named_parameters()
|
||||
]
|
||||
|
||||
def __iter__(self) -> Iterator[tuple[str, torch.Tensor]]:
|
||||
"""Yield each parameter's local shard (`to_local()`), or the tensor itself."""
|
||||
for name, param in self._module.named_parameters():
|
||||
to_local = getattr(param, "to_local", None)
|
||||
yield name, (to_local() if callable(to_local) else param)
|
||||
@@ -0,0 +1,414 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Trainer-side weight transfer engine for the NCCL M2N backend.
|
||||
|
||||
Symmetric to `M2NWeightTransferEngine` but in the training process. Every
|
||||
trainer rank joins the shared communicator and runs every reshard, sending its
|
||||
own local shard; only rank 0 touches the inference control plane.
|
||||
|
||||
Workers join the communicator during init and run reshard from inside
|
||||
`update_weights`, so those two RPCs overlap with work on this side. Both run on
|
||||
a helper thread and are joined afterwards, which keeps that overlap inside the
|
||||
engine -- where the `TrainerWeightTransferEngine` contract puts it -- rather than
|
||||
in every caller.
|
||||
"""
|
||||
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
TrainerInitInfo,
|
||||
TrainerWeightTransferEngine,
|
||||
VLLMWeightSyncClient,
|
||||
WeightSource,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.m2n_common import (
|
||||
M2NMesh,
|
||||
M2NParamMeta,
|
||||
Placements,
|
||||
check_transferable,
|
||||
comm_ptr,
|
||||
import_m2n,
|
||||
publish_destination_placements,
|
||||
resolve_layout,
|
||||
to_mesh,
|
||||
to_placements,
|
||||
validate_layout,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.m2n_source import M2NWeightSource
|
||||
from vllm.distributed.weight_transfer.nccl_common import (
|
||||
decode_nccl_unique_id,
|
||||
trainer_init,
|
||||
uid_init_process_group,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
__all__ = ["M2NTrainerInitInfo", "M2NTrainerWeightTransferEngine"]
|
||||
|
||||
|
||||
def _dtype_name(dtype: torch.dtype) -> str:
|
||||
"""Short name for a dtype, e.g. `bfloat16`, for the worker-side init dict."""
|
||||
return str(dtype).split(".")[-1]
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class M2NTrainerInitInfo(TrainerInitInfo):
|
||||
"""Trainer-side init info for nccl_m2n.
|
||||
|
||||
`rank` (from `TrainerInitInfo`) is this trainer process's rank; it is also
|
||||
its rank in the shared communicator, since the trainer occupies
|
||||
`[0, num_trainer_ranks)`. Rank 0 drives the control plane.
|
||||
"""
|
||||
|
||||
backend: ClassVar[str] = "nccl_m2n"
|
||||
|
||||
master_address: str | None = None
|
||||
master_port: int | None = None
|
||||
world_size: int
|
||||
"""Trainer ranks + all inference workers."""
|
||||
num_trainer_ranks: int = 1
|
||||
dst_mesh_dims: tuple[int, int] | None = None
|
||||
"""How the inference ranks are laid out: axis 0 replicates and axis 1
|
||||
shards. The trainer declares it so both sides describe the destination
|
||||
identically; defaults to a flat `(num_workers, 1)`, which is all a
|
||||
replicated destination needs."""
|
||||
max_cta: int | None = None
|
||||
nccl_unique_id_b64: str | None = field(default=None, repr=False)
|
||||
|
||||
@property
|
||||
def destination_mesh_dims(self) -> tuple[int, int]:
|
||||
"""`dst_mesh_dims`, or a flat mesh over every inference worker."""
|
||||
if self.dst_mesh_dims is not None:
|
||||
return self.dst_mesh_dims
|
||||
return (self.world_size - self.num_trainer_ranks, 1)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Reject rank counts or destination meshes that cannot form a group."""
|
||||
_ = self.nccl_unique_id_bytes
|
||||
if not 0 < self.num_trainer_ranks < self.world_size:
|
||||
raise ValueError(
|
||||
f"`num_trainer_ranks` ({self.num_trainer_ranks}) must leave at "
|
||||
f"least one worker in world_size {self.world_size}"
|
||||
)
|
||||
num_workers = self.world_size - self.num_trainer_ranks
|
||||
if self.dst_mesh_dims is not None:
|
||||
dims = tuple(self.dst_mesh_dims)
|
||||
if len(dims) != 2 or dims[0] * dims[1] != num_workers:
|
||||
raise ValueError(
|
||||
f"`dst_mesh_dims` {dims} must be two dims covering the "
|
||||
f"{num_workers} inference workers"
|
||||
)
|
||||
if not 0 <= self.rank < self.num_trainer_ranks:
|
||||
raise ValueError(
|
||||
f"trainer `rank` ({self.rank}) must be below "
|
||||
f"`num_trainer_ranks` ({self.num_trainer_ranks})"
|
||||
)
|
||||
|
||||
@property
|
||||
def nccl_unique_id_bytes(self) -> bytes | None:
|
||||
return decode_nccl_unique_id(
|
||||
master_address=self.master_address,
|
||||
master_port=self.master_port,
|
||||
nccl_unique_id_b64=self.nccl_unique_id_b64,
|
||||
ctx="M2NTrainerInitInfo",
|
||||
)
|
||||
|
||||
|
||||
class M2NTrainerWeightTransferEngine(TrainerWeightTransferEngine[M2NTrainerInitInfo]):
|
||||
"""Trainer-side engine: sends every rank's local shard, once per parameter.
|
||||
|
||||
Called on every trainer rank. All ranks join the communicator and run every
|
||||
reshard; only rank 0 touches the control plane.
|
||||
"""
|
||||
|
||||
init_info_cls = M2NTrainerInitInfo
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
client: VLLMWeightSyncClient,
|
||||
source: M2NWeightSource,
|
||||
is_controller: bool,
|
||||
num_trainer_ranks: int,
|
||||
) -> None:
|
||||
"""Hold the client and source; `trainer_init` fills in the group."""
|
||||
super().__init__(client=client, source=source, is_sender=is_controller)
|
||||
self.source: M2NWeightSource = source
|
||||
self.is_controller = is_controller
|
||||
self.num_trainer_ranks = num_trainer_ranks
|
||||
self.group: PyNcclCommunicator | None = None
|
||||
self._m2n: Any = None
|
||||
self._handle: Any = None
|
||||
self._metas: list[M2NParamMeta] = []
|
||||
self._src_mesh: M2NMesh | None = None
|
||||
self._dst_mesh: M2NMesh | None = None
|
||||
self._dst_placements: list[Placements | None] = []
|
||||
self._executor: ThreadPoolExecutor | None = None
|
||||
|
||||
@classmethod
|
||||
def trainer_init(
|
||||
cls,
|
||||
init_info: M2NTrainerInitInfo,
|
||||
*,
|
||||
client: VLLMWeightSyncClient,
|
||||
source: WeightSource | None = None,
|
||||
) -> Self:
|
||||
"""Build the engine and rendezvous with the inference side.
|
||||
|
||||
Runs on *every* trainer rank. Rank 0 additionally ships the transfer
|
||||
plan to the workers and drives the control plane; the other ranks only
|
||||
build local state and join the communicator. Every rank participates
|
||||
in every reshard and sends its local shard.
|
||||
|
||||
The ordering here is not arbitrary -- see the comments inline. In
|
||||
short: validate before anything blocks; start the init RPC without
|
||||
waiting (workers join the communicator inside that RPC, so it cannot
|
||||
return until this side has joined too); then join the NCCL
|
||||
communicator; then create the M2N handle; and only then wait for the RPC
|
||||
to finish.
|
||||
"""
|
||||
# The base WeightSource carries name/dtype/shape but not layout, which
|
||||
# is not enough to plan a reshard. Fail here rather than at the first
|
||||
# missing attribute deep inside the send loop.
|
||||
if not isinstance(source, M2NWeightSource):
|
||||
raise TypeError(
|
||||
"nccl_m2n needs per-parameter layouts, so its source must be an "
|
||||
f"M2NWeightSource (e.g. DTensorModuleSource); got "
|
||||
f"{type(source).__name__}"
|
||||
)
|
||||
|
||||
# Trainer-side weight transfer engine for this rank. `__init__` only
|
||||
# holds the client and source; the communicator, meshes, and M2N handle
|
||||
# are filled in below.
|
||||
engine = cls(
|
||||
client=client,
|
||||
source=source,
|
||||
is_controller=init_info.rank == 0,
|
||||
num_trainer_ranks=init_info.num_trainer_ranks,
|
||||
)
|
||||
engine._m2n = import_m2n()
|
||||
|
||||
engine._src_mesh = source.mesh()
|
||||
if engine._src_mesh.size != init_info.num_trainer_ranks:
|
||||
raise ValueError(
|
||||
f"source mesh covers {engine._src_mesh.size} ranks, but there "
|
||||
f"are {init_info.num_trainer_ranks} trainer ranks"
|
||||
)
|
||||
|
||||
# Validate the whole plan before any rendezvous. A layout m2n cannot
|
||||
# express is a mismatched collective at send time, which hangs rather
|
||||
# than raises -- so every precondition is checked while an exception can
|
||||
# still propagate to the caller.
|
||||
engine._metas = cast(list[M2NParamMeta], source.metadata())
|
||||
for meta in engine._metas:
|
||||
check_transferable(meta.name, meta.dtype, meta.shape)
|
||||
mesh, placements = resolve_layout(engine._src_mesh, meta.placements)
|
||||
validate_layout(mesh, placements, meta.shape, "source")
|
||||
|
||||
rendezvous: Future | None = None
|
||||
if engine.is_controller:
|
||||
engine._executor = ThreadPoolExecutor(
|
||||
max_workers=1, thread_name_prefix="m2n-weight-sync"
|
||||
)
|
||||
# Only trainer rank 0 starts the control-plane RPC. Workers join
|
||||
# the communicator inside it, so submit it first, join below, and
|
||||
# wait for it at the end.
|
||||
rendezvous = engine._executor.submit(
|
||||
client.init_weight_transfer_engine,
|
||||
engine._worker_init_info(init_info),
|
||||
)
|
||||
|
||||
# Every trainer rank joins -- reshard is collective over the whole
|
||||
# communicator. Trainer ranks take
|
||||
# [0, num_trainer_ranks) and the workers follow, which is the
|
||||
# contiguous-interval layout m2n requires of both meshes.
|
||||
unique_id_bytes = init_info.nccl_unique_id_bytes
|
||||
if unique_id_bytes is not None:
|
||||
engine.group = uid_init_process_group(
|
||||
unique_id_bytes,
|
||||
rank=init_info.rank,
|
||||
world_size=init_info.world_size,
|
||||
device=torch.accelerator.current_device_index(),
|
||||
)
|
||||
else:
|
||||
assert init_info.master_address is not None
|
||||
assert init_info.master_port is not None
|
||||
engine.group = trainer_init(
|
||||
{
|
||||
"master_address": init_info.master_address,
|
||||
"master_port": init_info.master_port,
|
||||
"world_size": init_info.world_size,
|
||||
},
|
||||
rank=init_info.rank,
|
||||
)
|
||||
|
||||
# The trainer declares the inference topology; the worker uses exactly
|
||||
# this, so neither side has to infer the other's factorization.
|
||||
engine._dst_mesh = M2NMesh(
|
||||
init_info.destination_mesh_dims, init_info.num_trainer_ranks
|
||||
)
|
||||
engine._dst_placements = engine._receive_destination_plan(
|
||||
init_info.num_trainer_ranks
|
||||
)
|
||||
logger.info(
|
||||
"nccl_m2n trainer ready: %d parameters, trainer ranks [0, %d), "
|
||||
"inference ranks [%d, %d)",
|
||||
len(engine._metas),
|
||||
init_info.num_trainer_ranks,
|
||||
init_info.num_trainer_ranks,
|
||||
init_info.world_size,
|
||||
)
|
||||
|
||||
# Created after the group so a failed rendezvous does not leave a live
|
||||
# handle behind; shutdown() releases it once caller streams are synced.
|
||||
engine._handle = engine._m2n.Handle.create(
|
||||
engine._m2n.Config(max_cta=init_info.max_cta)
|
||||
)
|
||||
|
||||
# Now safe to collect: both sides have joined, so the RPC has returned
|
||||
# or raised. Doing this last means a worker-side init failure surfaces
|
||||
# here, as an exception from trainer_init, rather than at the first send.
|
||||
if rendezvous is not None:
|
||||
rendezvous.result()
|
||||
return engine
|
||||
|
||||
def _receive_destination_plan(
|
||||
self, first_worker_rank: int
|
||||
) -> list[Placements | None]:
|
||||
"""Receive and validate the inference-side per-parameter placements."""
|
||||
if self.group is None or self._dst_mesh is None:
|
||||
raise RuntimeError(
|
||||
"destination plan requires the communicator and destination mesh"
|
||||
)
|
||||
|
||||
# The first inference worker publishes one placement per parameter.
|
||||
# Every trainer rank receives the complete plan in this single,
|
||||
# initialization-time broadcast.
|
||||
placements = publish_destination_placements(
|
||||
self.group, first_worker_rank, None, len(self._metas)
|
||||
)
|
||||
# The send loop matches placements to metadata by position, so reject
|
||||
# an incomplete or oversized plan before entering any M2N collective.
|
||||
if len(placements) != len(self._metas):
|
||||
raise RuntimeError(
|
||||
f"inference side planned {len(placements)} parameters, but "
|
||||
f"this trainer announced {len(self._metas)}"
|
||||
)
|
||||
# Check every worker-selected destination against the corresponding
|
||||
# global parameter shape before the first transfer.
|
||||
for meta, placement in zip(self._metas, placements):
|
||||
mesh, resolved = resolve_layout(self._dst_mesh, placement)
|
||||
validate_layout(mesh, resolved, meta.shape, "destination")
|
||||
return placements
|
||||
|
||||
def _worker_init_info(self, init_info: M2NTrainerInitInfo) -> dict[str, Any]:
|
||||
"""Handshake payload: rendezvous, both meshes, and the transfer plan."""
|
||||
assert self._src_mesh is not None
|
||||
payload: dict[str, Any] = {
|
||||
"master_address": init_info.master_address,
|
||||
"master_port": init_info.master_port,
|
||||
"nccl_unique_id_b64": init_info.nccl_unique_id_b64,
|
||||
"rank_offset": init_info.num_trainer_ranks,
|
||||
"world_size": init_info.world_size,
|
||||
"src_mesh_dims": list(self._src_mesh.dims),
|
||||
"dst_mesh_dims": list(init_info.destination_mesh_dims),
|
||||
"names": [m.name for m in self._metas],
|
||||
"dtype_names": [_dtype_name(m.dtype) for m in self._metas],
|
||||
"shapes": [list(m.shape) for m in self._metas],
|
||||
"src_placements": [
|
||||
None if m.placements is None else list(m.placements)
|
||||
for m in self._metas
|
||||
],
|
||||
"max_cta": init_info.max_cta,
|
||||
}
|
||||
return {key: value for key, value in payload.items() if value is not None}
|
||||
|
||||
def send_weights(self) -> None:
|
||||
"""Drive one update round: start, reshard concurrently, then finish."""
|
||||
if self._handle is None or self.group is None:
|
||||
raise RuntimeError("nccl_m2n trainer engine is not initialized")
|
||||
|
||||
update: Future | None = None
|
||||
if self.is_controller:
|
||||
self.client.start_weight_update()
|
||||
# The workers reshard from inside `update_weights`, concurrently
|
||||
# with the sends below.
|
||||
assert self._executor is not None
|
||||
update = self._executor.submit(
|
||||
self.client.update_weights,
|
||||
{"names": [m.name for m in self._metas]},
|
||||
)
|
||||
|
||||
try:
|
||||
self._send()
|
||||
finally:
|
||||
if update is not None:
|
||||
update.result()
|
||||
|
||||
if self.is_controller:
|
||||
self.client.finish_weight_update()
|
||||
|
||||
def _send(self) -> None:
|
||||
"""Reshard each local shard into its worker-planned destination."""
|
||||
assert self.group is not None
|
||||
assert self._src_mesh is not None
|
||||
assert self._dst_mesh is not None
|
||||
m2n = self._m2n
|
||||
comm = comm_ptr(self.group)
|
||||
stream = torch.cuda.current_stream()
|
||||
|
||||
for index, (name, tensor) in enumerate(self.source):
|
||||
meta = self._metas[index]
|
||||
if name != meta.name:
|
||||
raise RuntimeError(
|
||||
f"weight source yielded '{name}' at position {index}, but "
|
||||
f"its metadata declared '{meta.name}'; the source must "
|
||||
"iterate in a stable order"
|
||||
)
|
||||
shard = tensor.detach().contiguous()
|
||||
src_mesh, src_placements = resolve_layout(self._src_mesh, meta.placements)
|
||||
dst_mesh, dst_placements = resolve_layout(
|
||||
self._dst_mesh, self._dst_placements[index]
|
||||
)
|
||||
m2n.reshard(
|
||||
shard,
|
||||
None,
|
||||
comm,
|
||||
stream,
|
||||
src_mesh=to_mesh(m2n, src_mesh),
|
||||
src_placements=to_placements(m2n, src_placements),
|
||||
dst_mesh=to_mesh(m2n, dst_mesh),
|
||||
dst_placements=to_placements(m2n, dst_placements),
|
||||
handle=self._handle,
|
||||
)
|
||||
# A custom source may yield temporary storage allocated on another
|
||||
# stream. M2N retains only its device pointer for asynchronous work,
|
||||
# so tell the allocator not to reuse that storage until this stream
|
||||
# has finished with it. For storage allocated on this stream,
|
||||
# record_stream is effectively a no-op.
|
||||
shard.record_stream(stream)
|
||||
|
||||
# As in the other weight-transfer backends, wait before returning
|
||||
# rather than relying on same-stream ordering. The caller may then
|
||||
# safely mutate parameters or continue work on another stream.
|
||||
stream.synchronize()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Destroy the m2n handle, join the helper thread, and drop the group."""
|
||||
if self._handle is not None:
|
||||
torch.accelerator.synchronize()
|
||||
self._handle.destroy()
|
||||
self._handle = None
|
||||
if self._executor is not None:
|
||||
self._executor.shutdown()
|
||||
self._executor = None
|
||||
self.group = None
|
||||
@@ -220,11 +220,11 @@ def worker_init_process_group(
|
||||
|
||||
def trainer_init(
|
||||
init_info: NCCLRendezvous | dict,
|
||||
rank: int = 0,
|
||||
) -> "PyNcclCommunicator":
|
||||
"""Initialize NCCL process group for trainer-side weight transfer.
|
||||
|
||||
The trainer is always rank 0 in the process group. Uses the current
|
||||
CUDA device (torch.accelerator.current_device_index()).
|
||||
Uses the current CUDA device (torch.accelerator.current_device_index()).
|
||||
|
||||
Args:
|
||||
init_info: Any object carrying the `NCCLRendezvous` fields (a trainer or
|
||||
@@ -232,6 +232,9 @@ def trainer_init(
|
||||
- master_address: str
|
||||
- master_port: int
|
||||
- world_size: int
|
||||
rank: This trainer process's rank in the group. The broadcast backends
|
||||
have a single trainer at rank 0; multi-rank trainers (m2n) occupy
|
||||
ranks `[0, num_trainer_ranks)` and the workers start after them.
|
||||
|
||||
Returns:
|
||||
PyNcclCommunicator for weight transfer.
|
||||
@@ -246,12 +249,11 @@ def trainer_init(
|
||||
master_port = init_info.master_port
|
||||
world_size = init_info.world_size
|
||||
|
||||
# Trainer is always rank 0
|
||||
device = torch.accelerator.current_device_index()
|
||||
return stateless_init_process_group(
|
||||
master_address,
|
||||
master_port,
|
||||
0,
|
||||
rank,
|
||||
world_size,
|
||||
device,
|
||||
)
|
||||
|
||||
@@ -8,6 +8,7 @@ import functools
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from dataclasses import MISSING, asdict, dataclass, fields, is_dataclass
|
||||
from types import UnionType
|
||||
@@ -50,6 +51,7 @@ from vllm.config import (
|
||||
KVEventsConfig,
|
||||
KVTransferConfig,
|
||||
LoadConfig,
|
||||
LoggingConfig,
|
||||
LoRAConfig,
|
||||
MambaConfig,
|
||||
ModelConfig,
|
||||
@@ -84,6 +86,7 @@ from vllm.config.kernel import (
|
||||
SparseIndexerTopkBackend,
|
||||
)
|
||||
from vllm.config.load import SafetensorsLoadStrategy
|
||||
from vllm.config.logging import LogLevel
|
||||
from vllm.config.lora import MaxLoRARanks
|
||||
from vllm.config.mamba import MambaBackendEnum, MambaSSUAlgorithm
|
||||
from vllm.config.model import (
|
||||
@@ -113,7 +116,7 @@ from vllm.config.scheduler import SchedulerPolicy
|
||||
from vllm.config.utils import get_field
|
||||
from vllm.config.vllm import OptimizationLevel, PerformanceMode
|
||||
from vllm.config.watermarking import WatermarkConfig
|
||||
from vllm.logger import init_logger, suppress_logging
|
||||
from vllm.logger import configure_logging_if_needed, init_logger, suppress_logging
|
||||
from vllm.platforms import CpuArchEnum, current_platform
|
||||
from vllm.plugins import load_general_plugins
|
||||
from vllm.ray.lazy_utils import is_in_ray_actor, is_ray_initialized
|
||||
@@ -443,6 +446,20 @@ def get_kwargs(cls: ConfigType) -> dict[str, dict[str, Any]]:
|
||||
return copy.deepcopy(_compute_kwargs(cls))
|
||||
|
||||
|
||||
_LOG_CONFIG_FILE_DEPRECATION_MESSAGE = (
|
||||
"--log-config-file is deprecated and will be removed in v0.33.0. "
|
||||
"Use --logging-config.pylogging_config_file instead."
|
||||
)
|
||||
|
||||
|
||||
class DeprecatedLogConfigFileAction(argparse.Action):
|
||||
"""Warn when the legacy ``--log-config-file`` option is used."""
|
||||
|
||||
def __call__(self, parser, namespace, values, option_string=None):
|
||||
warnings.warn(_LOG_CONFIG_FILE_DEPRECATION_MESSAGE, stacklevel=1)
|
||||
setattr(namespace, self.dest, values)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineArgs:
|
||||
"""Arguments for vLLM engine."""
|
||||
@@ -573,6 +590,9 @@ class EngineArgs:
|
||||
max_num_batched_tokens: int | None = None
|
||||
max_num_scheduled_tokens: int | None = None
|
||||
long_prefill_token_threshold: int = SchedulerConfig.long_prefill_token_threshold
|
||||
long_prefill_token_threshold_adaptive: bool = (
|
||||
SchedulerConfig.long_prefill_token_threshold_adaptive
|
||||
)
|
||||
max_num_seqs: int | None = None
|
||||
max_num_active_seqs: int | None = SchedulerConfig.max_num_active_seqs
|
||||
max_num_queued_reqs: int | None = None
|
||||
@@ -730,6 +750,10 @@ class EngineArgs:
|
||||
|
||||
profiler_config: ProfilerConfig = get_field(VllmConfig, "profiler_config")
|
||||
|
||||
logging_config: LoggingConfig | None = None
|
||||
log_level: LogLevel | None = None
|
||||
log_config_file: str | None = None
|
||||
|
||||
kv_transfer_config: KVTransferConfig | None = None
|
||||
kv_events_config: KVEventsConfig | None = None
|
||||
|
||||
@@ -1548,6 +1572,34 @@ class EngineArgs:
|
||||
**lora_kwargs["enable_moe_shared_loras"],
|
||||
)
|
||||
|
||||
# Logging arguments
|
||||
logging_group = parser.add_argument_group(
|
||||
title="LoggingConfig",
|
||||
description=LoggingConfig.__doc__,
|
||||
)
|
||||
logging_config_kwargs = get_kwargs(VllmConfig)["logging_config"]
|
||||
logging_config_kwargs["default"] = argparse.SUPPRESS
|
||||
logging_group.add_argument("--logging-config", **logging_config_kwargs)
|
||||
logging_group.add_argument(
|
||||
"--log-level",
|
||||
choices=get_args(LogLevel),
|
||||
default=argparse.SUPPRESS,
|
||||
help=(
|
||||
"Shortcut for --logging-config.log_level. "
|
||||
"Overrides that field if both are specified."
|
||||
),
|
||||
)
|
||||
logging_group.add_argument(
|
||||
"--log-config-file",
|
||||
dest="log_config_file",
|
||||
default=argparse.SUPPRESS,
|
||||
metavar="PYLOGGING_CONFIG_FILE",
|
||||
action=DeprecatedLogConfigFileAction,
|
||||
help=_LOG_CONFIG_FILE_DEPRECATION_MESSAGE,
|
||||
)
|
||||
# Retain the warning in v0.31.0 and v0.32.0. Remove this option and its
|
||||
# compatibility mapping in create_logging_config() in v0.33.0.
|
||||
|
||||
# Observability arguments
|
||||
observability_kwargs = get_kwargs(ObservabilityConfig)
|
||||
observability_group = parser.add_argument_group(
|
||||
@@ -1643,6 +1695,10 @@ class EngineArgs:
|
||||
"--long-prefill-token-threshold",
|
||||
**scheduler_kwargs["long_prefill_token_threshold"],
|
||||
)
|
||||
scheduler_group.add_argument(
|
||||
"--long-prefill-token-threshold-adaptive",
|
||||
**scheduler_kwargs["long_prefill_token_threshold_adaptive"],
|
||||
)
|
||||
# multi-step scheduling has been removed; corresponding arguments
|
||||
# are no longer supported.
|
||||
scheduler_group.add_argument(
|
||||
@@ -2074,6 +2130,16 @@ class EngineArgs:
|
||||
jit_monitor_verbose=self.jit_monitor_verbose,
|
||||
)
|
||||
|
||||
def create_logging_config(self) -> LoggingConfig:
|
||||
config = self.logging_config or LoggingConfig()
|
||||
if self.log_level is not None:
|
||||
config = dataclasses.replace(config, log_level=self.log_level)
|
||||
if self.log_config_file is not None:
|
||||
config = dataclasses.replace(
|
||||
config, pylogging_config_file=self.log_config_file
|
||||
)
|
||||
return config
|
||||
|
||||
def create_engine_config(
|
||||
self,
|
||||
usage_context: UsageContext | None = None,
|
||||
@@ -2083,6 +2149,9 @@ class EngineArgs:
|
||||
|
||||
NOTE: If VllmConfig is incompatible, we raise an error.
|
||||
"""
|
||||
logging_config = self.create_logging_config()
|
||||
configure_logging_if_needed(logging_config)
|
||||
|
||||
current_platform.pre_register_and_update()
|
||||
|
||||
device_config = DeviceConfig(device=cast(Device, current_platform.device_type))
|
||||
@@ -2489,6 +2558,9 @@ class EngineArgs:
|
||||
policy=self.scheduling_policy,
|
||||
scheduler_cls=self.scheduler_cls,
|
||||
long_prefill_token_threshold=self.long_prefill_token_threshold,
|
||||
long_prefill_token_threshold_adaptive=(
|
||||
self.long_prefill_token_threshold_adaptive
|
||||
),
|
||||
scheduler_reserve_full_isl=self.scheduler_reserve_full_isl,
|
||||
watermark=self.watermark,
|
||||
prefill_schedule_interval=self.prefill_schedule_interval,
|
||||
@@ -2711,6 +2783,7 @@ class EngineArgs:
|
||||
diffusion_config=diffusion_config,
|
||||
structured_outputs_config=self.structured_outputs_config,
|
||||
observability_config=observability_config,
|
||||
logging_config=logging_config,
|
||||
compilation_config=compilation_config,
|
||||
kv_transfer_config=self.kv_transfer_config,
|
||||
kv_events_config=self.kv_events_config,
|
||||
|
||||
@@ -111,13 +111,53 @@ class AnthropicJsonOutputFormat(BaseModel):
|
||||
type: Literal["json_schema"] = "json_schema"
|
||||
|
||||
|
||||
AnthropicEffort = Literal["low", "medium", "high", "xhigh", "max"]
|
||||
# reasoning_effort sent to the chat template for thinking.type=disabled.
|
||||
AnthropicDisabledThinkingEffort = Literal["none", AnthropicEffort]
|
||||
AnthropicDisabledThinkingEffortOption = Literal["auto", AnthropicDisabledThinkingEffort]
|
||||
AnthropicThinkingDisplay = Literal["summarized", "omitted", "updates"]
|
||||
|
||||
|
||||
class AnthropicOutputConfig(BaseModel):
|
||||
"""Configuration options for the model's output, such as the output format."""
|
||||
|
||||
effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
|
||||
effort: AnthropicEffort | None = None
|
||||
format: AnthropicJsonOutputFormat | None = None
|
||||
|
||||
|
||||
class AnthropicThinkingConfigEnabled(BaseModel):
|
||||
"""Extended thinking with a fixed token budget.
|
||||
|
||||
``display`` is accepted but ignored: reasoning is always returned.
|
||||
"""
|
||||
|
||||
type: Literal["enabled"]
|
||||
budget_tokens: int = Field(ge=1024)
|
||||
display: AnthropicThinkingDisplay | None = None
|
||||
|
||||
|
||||
class AnthropicThinkingConfigDisabled(BaseModel):
|
||||
type: Literal["disabled"]
|
||||
|
||||
|
||||
class AnthropicThinkingConfigAdaptive(BaseModel):
|
||||
"""Extended thinking whose depth the model chooses.
|
||||
|
||||
``display`` is accepted but ignored: reasoning is always returned.
|
||||
"""
|
||||
|
||||
type: Literal["adaptive"]
|
||||
display: AnthropicThinkingDisplay | None = None
|
||||
|
||||
|
||||
AnthropicThinkingConfig = Annotated[
|
||||
AnthropicThinkingConfigEnabled
|
||||
| AnthropicThinkingConfigDisabled
|
||||
| AnthropicThinkingConfigAdaptive,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class AnthropicMessagesRequest(BaseModel):
|
||||
"""Anthropic Messages API request."""
|
||||
|
||||
@@ -126,6 +166,7 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
max_tokens: int
|
||||
metadata: dict[str, Any] | None = None
|
||||
output_config: AnthropicOutputConfig | None = None
|
||||
thinking: AnthropicThinkingConfig | None = None
|
||||
stop_sequences: (
|
||||
Annotated[list[str], Field(max_length=envs.VLLM_MAX_STOP_STRINGS)] | None
|
||||
) = None
|
||||
@@ -190,6 +231,19 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
raise ValueError("max_tokens must be positive")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_thinking_budget(self) -> "AnthropicMessagesRequest":
|
||||
# P/D prefill legs are sent with max_tokens=1 and never decode; the
|
||||
# decode leg carries the client's max_tokens and is still checked.
|
||||
if self.kv_transfer_params and self.kv_transfer_params.get("do_remote_decode"):
|
||||
return self
|
||||
if (
|
||||
isinstance(self.thinking, AnthropicThinkingConfigEnabled)
|
||||
and self.thinking.budget_tokens >= self.max_tokens
|
||||
):
|
||||
raise ValueError("thinking.budget_tokens must be less than max_tokens")
|
||||
return self
|
||||
|
||||
|
||||
class AnthropicDelta(BaseModel):
|
||||
"""Delta for streaming responses."""
|
||||
|
||||
@@ -10,7 +10,7 @@ import logging
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
from typing import Any, get_args
|
||||
|
||||
import jinja2
|
||||
from fastapi import Request
|
||||
@@ -22,11 +22,15 @@ from vllm.entrypoints.anthropic.protocol import (
|
||||
AnthropicCountTokensRequest,
|
||||
AnthropicCountTokensResponse,
|
||||
AnthropicDelta,
|
||||
AnthropicDisabledThinkingEffort,
|
||||
AnthropicDisabledThinkingEffortOption,
|
||||
AnthropicEffort,
|
||||
AnthropicError,
|
||||
AnthropicMessagesRequest,
|
||||
AnthropicMessagesResponse,
|
||||
AnthropicOutputConfig,
|
||||
AnthropicStreamEvent,
|
||||
AnthropicThinkingConfig,
|
||||
AnthropicUsage,
|
||||
)
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
|
||||
@@ -47,9 +51,11 @@ from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse, UsageInfo
|
||||
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.logger import init_logger
|
||||
from vllm.renderers.hf import HfRenderer, resolve_chat_template
|
||||
from vllm.renderers.online_renderer import OnlineRenderer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _build_anthropic_usage(
|
||||
@@ -116,6 +122,7 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
enable_prompt_tokens_details: bool = False,
|
||||
enable_force_include_usage: bool = False,
|
||||
default_chat_template_kwargs: dict[str, Any] | None = None,
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffortOption = "auto",
|
||||
):
|
||||
super().__init__(
|
||||
engine_client=engine_client,
|
||||
@@ -139,7 +146,87 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
"length": "max_tokens",
|
||||
"tool_calls": "tool_use",
|
||||
}
|
||||
self._merge_inline_system = self._detect_merge_inline_system(chat_template)
|
||||
self._merge_inline_system = self._should_merge_inline_system(online_renderer)
|
||||
# Resolved lazily from the renderer when "auto".
|
||||
self._disabled_thinking_effort: AnthropicDisabledThinkingEffort | None = (
|
||||
None if disabled_thinking_effort == "auto" else disabled_thinking_effort
|
||||
)
|
||||
|
||||
async def _get_disabled_thinking_effort(self) -> AnthropicDisabledThinkingEffort:
|
||||
if self._disabled_thinking_effort is None:
|
||||
self._disabled_thinking_effort = (
|
||||
await self._probe_disabled_thinking_effort()
|
||||
)
|
||||
logger.info(
|
||||
"Anthropic thinking.type=disabled maps to reasoning_effort=%r",
|
||||
self._disabled_thinking_effort,
|
||||
)
|
||||
return self._disabled_thinking_effort
|
||||
|
||||
async def _probe_disabled_thinking_effort(self) -> AnthropicDisabledThinkingEffort:
|
||||
"""Use ``low`` if the renderer rejects or ignores ``none``.
|
||||
|
||||
``none`` is ignored when it renders the same prompt as a thinking
|
||||
effort, e.g. GLM-5.3 treats unknown efforts as ``max``.
|
||||
"""
|
||||
none_prompt = await self._render_probe_prompt("none")
|
||||
if none_prompt is None:
|
||||
return "low"
|
||||
for effort in get_args(AnthropicEffort):
|
||||
if await self._render_probe_prompt(effort) == none_prompt:
|
||||
return "low"
|
||||
return "none"
|
||||
|
||||
async def _render_probe_prompt(
|
||||
self, effort: AnthropicDisabledThinkingEffort
|
||||
) -> tuple[list[int] | None, str | None] | None:
|
||||
request = ChatCompletionRequest(
|
||||
messages=[{"role": "user", "content": "Hi"}],
|
||||
reasoning_effort=effort,
|
||||
)
|
||||
try:
|
||||
result = await self.online_renderer.render_chat(request)
|
||||
except Exception:
|
||||
logger.debug("Rendering reasoning_effort=%r failed", effort, exc_info=True)
|
||||
return None
|
||||
if isinstance(result, ErrorResponse):
|
||||
return None
|
||||
_, (engine_input,) = result
|
||||
components = self._extract_prompt_components(engine_input)
|
||||
return components.token_ids, components.text
|
||||
|
||||
@classmethod
|
||||
def _should_merge_inline_system(cls, online_renderer: OnlineRenderer) -> bool:
|
||||
"""Probe the chat templates the renderer applies, not the CLI override.
|
||||
|
||||
Both the tool and non-tool templates are checked since they may differ.
|
||||
"""
|
||||
renderer = online_renderer.renderer
|
||||
tool_variants: tuple[list[dict[str, Any]] | None, ...] = (None, [])
|
||||
if not isinstance(renderer, HfRenderer) or renderer.tokenizer is None:
|
||||
merge = cls._detect_merge_inline_system(online_renderer.chat_template)
|
||||
else:
|
||||
merge = any(
|
||||
cls._detect_merge_inline_system(
|
||||
resolve_chat_template(
|
||||
renderer.tokenizer,
|
||||
online_renderer.chat_template,
|
||||
tools,
|
||||
model_config=online_renderer.model_config,
|
||||
)
|
||||
)
|
||||
for tools in tool_variants
|
||||
)
|
||||
if merge:
|
||||
logger.warning(
|
||||
"The chat template requires system-first ordering, so inline "
|
||||
"system messages in /v1/messages requests (e.g. Claude Code's "
|
||||
"per-turn reminders) are merged into the leading system prompt. "
|
||||
"Each new one changes the prompt prefix, so the rest of the "
|
||||
"conversation misses the prefix cache. Pass a --chat-template "
|
||||
"that accepts non-leading system messages to avoid this."
|
||||
)
|
||||
return merge
|
||||
|
||||
@staticmethod
|
||||
def _detect_merge_inline_system(chat_template: str | None) -> bool:
|
||||
@@ -197,6 +284,7 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
anthropic_request: AnthropicMessagesRequest | AnthropicCountTokensRequest,
|
||||
*,
|
||||
merge_inline_system: bool = False,
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffort = "none",
|
||||
) -> ChatCompletionRequest:
|
||||
"""Convert Anthropic message format to OpenAI format."""
|
||||
openai_messages: list[dict[str, Any]] = []
|
||||
@@ -214,6 +302,7 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
req = cls._build_base_request(anthropic_request, openai_messages)
|
||||
cls._handle_streaming_options(req, anthropic_request)
|
||||
cls._handle_output_config(req, anthropic_request)
|
||||
cls._handle_thinking(req, anthropic_request, disabled_thinking_effort)
|
||||
cls._convert_tool_choice(anthropic_request, req)
|
||||
cls._convert_tools(anthropic_request, req)
|
||||
return req
|
||||
@@ -494,6 +583,33 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
chat_template_kwargs=anthropic_request.chat_template_kwargs,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _handle_thinking(
|
||||
cls,
|
||||
req: ChatCompletionRequest,
|
||||
anthropic_request: AnthropicMessagesRequest | AnthropicCountTokensRequest,
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffort = "none",
|
||||
) -> None:
|
||||
"""Handle extended-thinking configuration.
|
||||
|
||||
``display`` is intentionally ignored: suppressing reasoning would mark
|
||||
it ended for structured outputs and drop it from multi-turn history.
|
||||
"""
|
||||
if isinstance(anthropic_request, AnthropicCountTokensRequest):
|
||||
return
|
||||
thinking: AnthropicThinkingConfig | None = anthropic_request.thinking
|
||||
if thinking is None:
|
||||
return
|
||||
|
||||
if thinking.type == "disabled":
|
||||
# "none" clears enable_thinking for templates that honor it; models
|
||||
# that cannot disable thinking are configured with a low effort.
|
||||
req.reasoning_effort = disabled_thinking_effort
|
||||
elif thinking.type == "enabled":
|
||||
req.thinking_token_budget = thinking.budget_tokens
|
||||
# "adaptive" pins nothing: the model chooses depth beneath the ceiling
|
||||
# already set from output_config.effort.
|
||||
|
||||
@classmethod
|
||||
def _handle_output_config(
|
||||
cls,
|
||||
@@ -602,9 +718,13 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
"""
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
logger.debug("Received messages request %s", request.model_dump_json())
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffort = "none"
|
||||
if request.thinking is not None and request.thinking.type == "disabled":
|
||||
disabled_thinking_effort = await self._get_disabled_thinking_effort()
|
||||
chat_req = self.to_chat_completion_request(
|
||||
request,
|
||||
merge_inline_system=self._merge_inline_system,
|
||||
disabled_thinking_effort=disabled_thinking_effort,
|
||||
)
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
logger.debug("Convert to OpenAI request %s", chat_req.model_dump_json())
|
||||
|
||||
@@ -1450,6 +1450,7 @@ class ChatTemplateConfig:
|
||||
chat_template: str | None = None
|
||||
chat_template_content_format: ChatTemplateContentFormatOption = "auto"
|
||||
trust_request_chat_template: bool = False
|
||||
trust_request_mm_kwargs: bool = False
|
||||
|
||||
|
||||
def validate_chat_template(chat_template: Path | str | None):
|
||||
|
||||
@@ -9,7 +9,7 @@ import importlib.metadata
|
||||
import sys
|
||||
from importlib.util import find_spec
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -44,6 +44,7 @@ def main():
|
||||
import vllm.entrypoints.cli.collect_env
|
||||
import vllm.entrypoints.cli.launch
|
||||
import vllm.entrypoints.cli.openai
|
||||
import vllm.entrypoints.cli.preload
|
||||
import vllm.entrypoints.cli.run_batch
|
||||
import vllm.entrypoints.cli.serve
|
||||
import vllm.entrypoints.cli.snapshot
|
||||
@@ -59,6 +60,7 @@ def main():
|
||||
vllm.entrypoints.cli.launch,
|
||||
vllm.entrypoints.cli.benchmark.main,
|
||||
vllm.entrypoints.cli.collect_env,
|
||||
vllm.entrypoints.cli.preload,
|
||||
vllm.entrypoints.cli.run_batch,
|
||||
vllm.entrypoints.cli.snapshot,
|
||||
]
|
||||
@@ -108,7 +110,9 @@ def main():
|
||||
cmds[cmd.name] = cmd
|
||||
args = parser.parse_args()
|
||||
if args.subparser in cmds:
|
||||
cmds[args.subparser].validate(args)
|
||||
cmd = cmds[args.subparser]
|
||||
configure_logging_from_args(args)
|
||||
cmd.validate(args)
|
||||
|
||||
if hasattr(args, "dispatch_function"):
|
||||
args.dispatch_function(args)
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The `preload` subcommand for the vLLM CLI.
|
||||
|
||||
Launches one weight cache daemon per GPU; each daemon holds the
|
||||
post-quantized, TP-sharded weights of its rank in GPU memory and serves
|
||||
CUDA IPC handles to vLLM engines over a Unix domain socket, so restarting
|
||||
engines can map the weights via zero-copy IPC instead of reloading from disk:
|
||||
|
||||
vllm preload --model /path/to/model --tensor-parallel-size 4
|
||||
|
||||
Engines then load from the daemons with:
|
||||
|
||||
vllm serve /path/to/model --tensor-parallel-size 4 --load-format ipc_cache
|
||||
|
||||
Tensor, expert and data parallelism are supported, including across nodes;
|
||||
see vllm/model_executor/model_loader/weight_cache/daemon.py for the rank
|
||||
layout and rendezvous details.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import multiprocessing
|
||||
import queue
|
||||
import signal
|
||||
import sys
|
||||
import typing
|
||||
from itertools import product
|
||||
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
from vllm.entrypoints.serve.utils.api_utils import VLLM_SUBCMD_PARSER_EPILOG
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
check_ipc_platform_support,
|
||||
)
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
else:
|
||||
FlexibleArgumentParser = argparse.ArgumentParser
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class PreloadSubcommand(CLISubcommand):
|
||||
"""The `preload` subcommand for the vLLM CLI."""
|
||||
|
||||
name = "preload"
|
||||
|
||||
@staticmethod
|
||||
def add_cli_args(parser: FlexibleArgumentParser) -> None:
|
||||
EngineArgs.add_cli_args(parser)
|
||||
parser.add_argument(
|
||||
"--weight-cache-socket-dir",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Directory for the daemon Unix sockets (default: tempdir).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--weight-cache-master-port",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Rendezvous port for the daemon's own TP group. Must differ "
|
||||
"from the engine's --master-port (the daemon holds its group open "
|
||||
"while 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.",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def cmd(args: argparse.Namespace) -> None:
|
||||
# Imported here so `vllm --help` and friends stay free of torch.
|
||||
from vllm.model_executor.model_loader.weight_cache.daemon import (
|
||||
_reject_unsupported_parallelism,
|
||||
_run_daemon,
|
||||
get_draft_daemon_config,
|
||||
plan_local_ranks,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_cache.utils import (
|
||||
format_daemon_role,
|
||||
)
|
||||
|
||||
engine_args = EngineArgs.from_cli_args(args)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
if vllm_config.load_config.load_format == "ipc_cache":
|
||||
raise ValueError(
|
||||
"The weight cache daemon itself must load from disk; use the "
|
||||
"default --load-format"
|
||||
)
|
||||
# Config-only so it can fail before any model loading; the quant
|
||||
# method check needs the created model and runs in
|
||||
# WeightCacheDaemon.get_model.
|
||||
check_ipc_platform_support()
|
||||
parallel_config = vllm_config.parallel_config
|
||||
_reject_unsupported_parallelism(parallel_config)
|
||||
tp_size = parallel_config.tensor_parallel_size
|
||||
dp_size = parallel_config.data_parallel_size
|
||||
|
||||
placements = plan_local_ranks(parallel_config)
|
||||
local_world_size = len(placements)
|
||||
if dp_size == 1:
|
||||
nnodes = parallel_config.nnodes
|
||||
node_rank = parallel_config.node_rank
|
||||
master_addr = parallel_config.master_addr
|
||||
else:
|
||||
master_addr = parallel_config.data_parallel_master_ip
|
||||
if parallel_config.nnodes > 1:
|
||||
nnodes = parallel_config.nnodes
|
||||
node_rank = parallel_config.node_rank
|
||||
else:
|
||||
nnodes = dp_size // parallel_config.data_parallel_size_local
|
||||
node_rank = parallel_config.data_parallel_rank // (
|
||||
parallel_config.data_parallel_size_local
|
||||
)
|
||||
if nnodes > 1 and master_addr in ("127.0.0.1", "localhost"):
|
||||
raise ValueError(
|
||||
"Data parallelism across nodes requires a reachable "
|
||||
"--data-parallel-address for the daemon rendezvous"
|
||||
)
|
||||
|
||||
# The daemon forms its own world group and holds it open while
|
||||
# serving, so it needs a rendezvous port distinct from the engine's.
|
||||
# All nodes must agree on it; single-node can auto-pick a free port.
|
||||
# The master address is the engine's --master-addr (TP across nodes)
|
||||
# or --data-parallel-address.
|
||||
if nnodes > 1 and args.weight_cache_master_port is None:
|
||||
raise ValueError(
|
||||
"--weight-cache-master-port is required when the daemons span nodes"
|
||||
)
|
||||
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[tuple[str, int]] = ctx.Queue()
|
||||
# Local index == device index; global rank enumerates DP then TP.
|
||||
expected_ready = {
|
||||
(format_daemon_role(is_draft), dp_rank * tp_size + tp_rank)
|
||||
for (is_draft, _, _), (_, dp_rank, tp_rank) in product(groups, placements)
|
||||
}
|
||||
procs = [
|
||||
ctx.Process(
|
||||
target=_run_daemon,
|
||||
args=(
|
||||
tp_rank,
|
||||
local_rank,
|
||||
config,
|
||||
init_method,
|
||||
args.weight_cache_socket_dir,
|
||||
ready_queue,
|
||||
is_draft,
|
||||
dp_rank,
|
||||
),
|
||||
name=f"vllm-weight-cache-{format_daemon_role(is_draft)}-"
|
||||
f"{dp_rank * tp_size + tp_rank}",
|
||||
)
|
||||
for (is_draft, config, init_method), (
|
||||
local_rank,
|
||||
dp_rank,
|
||||
tp_rank,
|
||||
) in product(groups, placements)
|
||||
]
|
||||
for proc in procs:
|
||||
proc.start()
|
||||
|
||||
def _shutdown(signum, frame):
|
||||
for proc in procs:
|
||||
proc.terminate()
|
||||
|
||||
signal.signal(signal.SIGINT, _shutdown)
|
||||
signal.signal(signal.SIGTERM, _shutdown)
|
||||
|
||||
ready: set[tuple[str, int]] = set()
|
||||
while len(ready) < len(expected_ready):
|
||||
try:
|
||||
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:
|
||||
logger.error(
|
||||
"Weight cache daemon rank(s) exited during startup "
|
||||
"(exitcodes=%s); shutting down.",
|
||||
[p.exitcode for p in dead],
|
||||
)
|
||||
for proc in procs:
|
||||
proc.terminate()
|
||||
for proc in procs:
|
||||
proc.join()
|
||||
sys.exit(max((p.exitcode or 0) for p in procs))
|
||||
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) x %d role(s) in %s =====",
|
||||
node_rank,
|
||||
nnodes,
|
||||
local_world_size,
|
||||
len(groups),
|
||||
socket_dir_msg,
|
||||
)
|
||||
|
||||
for proc in procs:
|
||||
proc.join()
|
||||
sys.exit(max(proc.exitcode or 0 for proc in procs))
|
||||
|
||||
def subparser_init(
|
||||
self, subparsers: argparse._SubParsersAction
|
||||
) -> FlexibleArgumentParser:
|
||||
preload_parser = subparsers.add_parser(
|
||||
self.name,
|
||||
help="Launch weight cache daemons (one per GPU) for fast engine restarts.",
|
||||
description="Launch weight cache daemons (one per GPU) that "
|
||||
"keep post-quantized weights in GPU memory and serve them to "
|
||||
"engines over CUDA IPC.",
|
||||
usage="vllm preload --model <model> [options]",
|
||||
)
|
||||
self.add_cli_args(preload_parser)
|
||||
preload_parser.epilog = VLLM_SUBCMD_PARSER_EPILOG.format(subcmd=self.name)
|
||||
return preload_parser
|
||||
|
||||
|
||||
def cmd_init() -> list[CLISubcommand]:
|
||||
return [PreloadSubcommand()]
|
||||
@@ -185,6 +185,7 @@ async def init_generate_state(
|
||||
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
|
||||
enable_force_include_usage=args.enable_force_include_usage,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
disabled_thinking_effort=args.anthropic_disabled_thinking_effort,
|
||||
)
|
||||
if "generate" in supported_tasks
|
||||
else None
|
||||
|
||||
@@ -6,10 +6,8 @@
|
||||
import json
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
import regex as re
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
model_serializer,
|
||||
)
|
||||
@@ -21,7 +19,6 @@ from vllm.entrypoints.serve.engine.protocol import OpenAIBaseModel, UsageInfo
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -52,6 +49,34 @@ def validate_cache_salt(cache_salt: object) -> None:
|
||||
)
|
||||
|
||||
|
||||
def validate_request_mm_kwargs(
|
||||
*,
|
||||
mm_processor_kwargs: dict[str, Any] | None,
|
||||
media_io_kwargs: dict[str, dict[str, Any]] | None,
|
||||
trust_request_mm_kwargs: bool,
|
||||
) -> None:
|
||||
"""Reject untrusted per-request multimodal kwarg overrides."""
|
||||
if trust_request_mm_kwargs:
|
||||
return
|
||||
|
||||
if mm_processor_kwargs:
|
||||
raise VLLMValidationError(
|
||||
"Per-request mm_processor_kwargs are disabled by default because "
|
||||
"they can change multimodal preprocessing resource usage. Start "
|
||||
"the server with --trust-request-mm-kwargs only when clients "
|
||||
"are trusted.",
|
||||
parameter="mm_processor_kwargs",
|
||||
)
|
||||
if media_io_kwargs:
|
||||
raise VLLMValidationError(
|
||||
"Per-request media_io_kwargs are disabled by default because "
|
||||
"they can change multimodal media loading resource usage. Start "
|
||||
"the server with --trust-request-mm-kwargs only when clients "
|
||||
"are trusted.",
|
||||
parameter="media_io_kwargs",
|
||||
)
|
||||
|
||||
|
||||
class SpeculativeDecodingMetrics(OpenAIBaseModel):
|
||||
"""Per-request speculative-decoding acceptance metrics.
|
||||
|
||||
@@ -261,53 +286,6 @@ class FunctionDefinition(OpenAIBaseModel):
|
||||
return data
|
||||
|
||||
|
||||
# extra="forbid" is a workaround to have kwargs as a field,
|
||||
# see https://github.com/pydantic/pydantic/issues/3125
|
||||
class LogitsProcessorConstructor(BaseModel):
|
||||
qualname: str
|
||||
args: list[Any] | None = None
|
||||
kwargs: dict[str, Any] | None = None
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
LogitsProcessors = list[str | LogitsProcessorConstructor]
|
||||
|
||||
|
||||
def get_logits_processors(
|
||||
processors: LogitsProcessors | None, pattern: str | None
|
||||
) -> list[Any] | None:
|
||||
if processors and pattern:
|
||||
logits_processors = []
|
||||
for processor in processors:
|
||||
qualname = processor if isinstance(processor, str) else processor.qualname
|
||||
if not re.match(pattern, qualname):
|
||||
raise ValueError(
|
||||
f"Logits processor '{qualname}' is not allowed by this "
|
||||
"server. See --logits-processor-pattern engine argument "
|
||||
"for more information."
|
||||
)
|
||||
try:
|
||||
logits_processor = resolve_obj_by_qualname(qualname)
|
||||
except Exception as e:
|
||||
raise ValueError(
|
||||
f"Logits processor '{qualname}' could not be resolved: {e}"
|
||||
) from e
|
||||
if isinstance(processor, LogitsProcessorConstructor):
|
||||
logits_processor = logits_processor(
|
||||
*processor.args or [], **processor.kwargs or {}
|
||||
)
|
||||
logits_processors.append(logits_processor)
|
||||
return logits_processors
|
||||
elif processors:
|
||||
raise ValueError(
|
||||
"The `logits_processors` argument is not supported by this "
|
||||
"server. See --logits-processor-pattern engine argument "
|
||||
"for more information."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
class FunctionCall(OpenAIBaseModel):
|
||||
# Internal field to preserve native tool call ID from tool parser.
|
||||
# Excluded from serialization to maintain OpenAI API compatibility
|
||||
|
||||
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from vllm.entrypoints.generate.generative_scoring.serving import (
|
||||
GenerativeScoringRequest,
|
||||
GenerativeScoringResponse,
|
||||
ServingGenerativeScoring,
|
||||
)
|
||||
@@ -31,26 +32,22 @@ def generative_scoring(request: Request) -> ServingGenerativeScoring | None:
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def create_generative_scoring(raw_request: Request):
|
||||
async def create_generative_scoring(
|
||||
request: GenerativeScoringRequest, raw_request: Request
|
||||
):
|
||||
handler = generative_scoring(raw_request)
|
||||
if handler is None:
|
||||
raise NotImplementedError(
|
||||
"The model does not support the Generative Scoring API"
|
||||
)
|
||||
|
||||
raw_body = await raw_request.json()
|
||||
|
||||
from vllm.entrypoints.generate.generative_scoring.serving import (
|
||||
GenerativeScoringRequest,
|
||||
)
|
||||
|
||||
gen_request = GenerativeScoringRequest(**raw_body)
|
||||
result = await handler.create_generative_scoring(gen_request, raw_request)
|
||||
result = await handler.create_generative_scoring(request, raw_request)
|
||||
|
||||
if isinstance(result, ErrorResponse):
|
||||
return JSONResponse(content=result.model_dump(), status_code=result.error.code)
|
||||
|
||||
@@ -92,6 +92,7 @@ async def init_app_state(
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
trust_request_chat_template=args.trust_request_chat_template,
|
||||
trust_request_mm_kwargs=args.trust_request_mm_kwargs,
|
||||
enable_auto_tools=args.enable_auto_tool_choice,
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
|
||||
@@ -15,7 +15,7 @@ from typing import Any
|
||||
import vllm.envs as envs
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
from vllm.reasoning import ReasoningParserManager
|
||||
from vllm.tool_parsers import ToolParserManager
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
@@ -216,6 +216,7 @@ def main():
|
||||
)
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args()
|
||||
configure_logging_from_args(args)
|
||||
validate_parsed_serve_args(args)
|
||||
|
||||
uvloop.run(run_server(args))
|
||||
|
||||
@@ -14,6 +14,9 @@ from typing import Any, Literal
|
||||
import vllm.envs as envs
|
||||
from vllm.config import config
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs, optional_type
|
||||
from vllm.entrypoints.anthropic.protocol import (
|
||||
AnthropicDisabledThinkingEffortOption,
|
||||
)
|
||||
from vllm.entrypoints.chat_utils import (
|
||||
ChatTemplateContentFormatOption,
|
||||
validate_chat_template,
|
||||
@@ -90,6 +93,11 @@ class BaseFrontendArgs:
|
||||
"""Whether to trust the chat template provided in the request. If False,
|
||||
the server will always use the chat template specified by `--chat-template`
|
||||
or the ones from tokenizer."""
|
||||
trust_request_mm_kwargs: bool = False
|
||||
"""Whether to trust per-request multimodal kwargs (`mm_processor_kwargs`
|
||||
and `media_io_kwargs`). If False, the server rejects non-empty values
|
||||
because they can change multimodal preprocessing resource usage. Only
|
||||
enable this when API clients are trusted."""
|
||||
default_chat_template_kwargs: dict[str, Any] | None = None
|
||||
"""Default keyword arguments to pass to the chat template renderer.
|
||||
These will be merged with request-level chat_template_kwargs,
|
||||
@@ -131,8 +139,6 @@ class BaseFrontendArgs:
|
||||
The `demo` Python tool executes model-generated code in Docker without
|
||||
network isolation by default. See the security guide for more
|
||||
information."""
|
||||
log_config_file: str | None = envs.VLLM_LOGGING_CONFIG_PATH
|
||||
"""Path to logging config JSON file for both vllm and uvicorn"""
|
||||
max_log_len: int | None = None
|
||||
"""Max number of prompt characters or prompt ID numbers being printed in
|
||||
log. The default of None means unlimited."""
|
||||
@@ -181,6 +187,13 @@ class BaseFrontendArgs:
|
||||
``--default-chat-template-kwargs '{"cohere_format": "..."}'`` -- any
|
||||
explicit request-level ``chat_template_kwargs.cohere_format`` takes
|
||||
priority."""
|
||||
anthropic_disabled_thinking_effort: AnthropicDisabledThinkingEffortOption = "auto"
|
||||
"""Anthropic ``/v1/messages`` only. The ``reasoning_effort`` used for
|
||||
requests with ``thinking: {"type": "disabled"}``. ``none`` turns thinking
|
||||
off for models that support it; ``low`` suits models that always think
|
||||
(e.g. GLM-5.3) or reject ``none`` (e.g. gpt-oss). ``auto`` (default) uses
|
||||
``low`` when the renderer rejects ``none`` or renders it the same as a
|
||||
thinking effort, and ``none`` otherwise."""
|
||||
log_error_stack: bool = envs.VLLM_SERVER_DEV_MODE
|
||||
"""If set to True, log the stack trace of error responses"""
|
||||
tokens_only: bool = False
|
||||
|
||||
@@ -23,7 +23,7 @@ import uvloop
|
||||
from fastapi import FastAPI, Response
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
from vllm.utils.system_utils import (
|
||||
decorate_logs,
|
||||
kill_process_tree,
|
||||
@@ -251,6 +251,8 @@ def _run_rust_vllm_dp_server(child_args: argparse.Namespace) -> None:
|
||||
|
||||
def _run_vllm_dp_server(child_args: argparse.Namespace) -> None:
|
||||
"""Entrypoint function for the vLLM DP Server."""
|
||||
configure_logging_from_args(child_args)
|
||||
|
||||
# Create a fresh process group for the vLLM DP Server,
|
||||
# so that CTRL-C is propagated cleanly.
|
||||
os.setpgrp()
|
||||
@@ -558,4 +560,5 @@ class DPSupervisor:
|
||||
|
||||
|
||||
def run_dp_supervisor(args: argparse.Namespace) -> None:
|
||||
configure_logging_from_args(args)
|
||||
uvloop.run(DPSupervisor(args).run())
|
||||
|
||||
@@ -44,7 +44,7 @@ import uvloop
|
||||
from vllm import envs
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.entrypoints.serve.utils.api_utils import log_version_and_model
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
@@ -89,10 +89,18 @@ async def serve_grpc(args: argparse.Namespace):
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
# Tolerate client keepalive pings every 10s (default 300s is too
|
||||
# strict for non-streaming requests where no DATA frames flow
|
||||
# during generation)
|
||||
("grpc.http2.min_recv_ping_interval_without_data_ms", 10000),
|
||||
# A non-streaming Generate writes nothing while the engine
|
||||
# decodes, so client keepalive and BDP-probe PINGs arriving in
|
||||
# that window are strikes and eventually earn a
|
||||
# GOAWAY(ENHANCE_YOUR_CALM, "too_many_pings") that fails every
|
||||
# in-flight RPC. Disable the strike count to tolerate them.
|
||||
("grpc.http2.max_ping_strikes", 0),
|
||||
# GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS expands to
|
||||
# a string with no "recv", and gRPC Core silently ignores unknown
|
||||
# keys, so the misspelt form left the 300s default in force.
|
||||
("grpc.http2.min_ping_interval_without_data_ms", 10000),
|
||||
# Without this, gRPC Core widens the floor to a fixed two hours
|
||||
# once no streams are open, striking keepalives between requests.
|
||||
("grpc.keepalive_permit_without_calls", True),
|
||||
],
|
||||
)
|
||||
@@ -187,6 +195,7 @@ def main():
|
||||
parser = AsyncEngineArgs.add_cli_args(parser)
|
||||
|
||||
args = parser.parse_args()
|
||||
configure_logging_from_args(args)
|
||||
|
||||
# Run server
|
||||
try:
|
||||
|
||||
@@ -57,6 +57,7 @@ async def init_render_app_state(
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
trust_request_chat_template=args.trust_request_chat_template,
|
||||
trust_request_mm_kwargs=args.trust_request_mm_kwargs,
|
||||
enable_auto_tools=args.enable_auto_tool_choice,
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
|
||||
@@ -8,7 +8,7 @@ from argparse import Namespace
|
||||
|
||||
from vllm import AsyncEngineArgs, envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
|
||||
from ..app import build_app
|
||||
from ..launcher import serve_http, setup_server
|
||||
@@ -87,7 +87,10 @@ async def run_launch_fastapi(args: argparse.Namespace) -> None:
|
||||
# cache space warning from CpuPlatform.check_and_update_config.
|
||||
envs.VLLM_CPU_KVCACHE_SPACE = 0
|
||||
|
||||
vllm_config = VllmConfig(model_config=model_config)
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
logging_config=engine_args.create_logging_config(),
|
||||
)
|
||||
shutdown_task = await build_and_serve_renderer(
|
||||
vllm_config, listen_address, sock, args
|
||||
)
|
||||
@@ -115,6 +118,7 @@ if __name__ == "__main__":
|
||||
)
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args()
|
||||
configure_logging_from_args(args)
|
||||
validate_parsed_serve_args(args)
|
||||
|
||||
uvloop.run(run_launch_fastapi(args))
|
||||
|
||||
@@ -61,7 +61,7 @@ from vllm.entrypoints.speech_to_text.translation.protocol import (
|
||||
TranslationResponseVerbose,
|
||||
)
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_from_args, init_logger
|
||||
from vllm.reasoning import ReasoningParserManager
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
@@ -289,6 +289,7 @@ def make_arg_parser(parser: FlexibleArgumentParser):
|
||||
def parse_args():
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible batch runner.")
|
||||
args = make_arg_parser(parser).parse_args()
|
||||
configure_logging_from_args(args)
|
||||
|
||||
# Backward compatibility: If --url is set, use it for host
|
||||
url_explicit = any(arg == "--url" or arg.startswith("--url=") for arg in sys.argv)
|
||||
|
||||
@@ -38,7 +38,13 @@ def get_uvicorn_log_config(args: Namespace) -> dict | None:
|
||||
3. Otherwise, return None (use uvicorn defaults)
|
||||
"""
|
||||
# First, try to load from file if specified
|
||||
log_config = load_log_config(args.log_config_file)
|
||||
logging_config = getattr(args, "logging_config", None)
|
||||
log_config_file = (
|
||||
logging_config.pylogging_config_file
|
||||
if logging_config is not None
|
||||
else getattr(args, "log_config_file", None)
|
||||
)
|
||||
log_config = load_log_config(log_config_file)
|
||||
if log_config is not None:
|
||||
return log_config
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ from vllm.entrypoints.generate.beam_search.offline import BeamSearchOfflineMixin
|
||||
from vllm.entrypoints.pooling.offline import PoolingOfflineMixin
|
||||
from vllm.entrypoints.serve.utils.api_utils import log_non_default_args
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logger import configure_logging_if_needed, init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.model_executor.layers.quantization import QuantizationMethods
|
||||
from vllm.outputs import PoolingRequestOutput, RequestOutput
|
||||
@@ -76,8 +76,8 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
Args:
|
||||
model: The name or path of a HuggingFace Transformers model.
|
||||
tokenizer: The name or path of a HuggingFace Transformers tokenizer.
|
||||
tokenizer_mode: The tokenizer mode. "auto" will use the fast tokenizer
|
||||
if available, and "slow" will always use the slow tokenizer.
|
||||
tokenizer_mode: The tokenizer mode. See
|
||||
[ModelConfig.tokenizer_mode][vllm.config.ModelConfig.tokenizer_mode].
|
||||
skip_tokenizer_init: If true, skip initialization of tokenizer and
|
||||
detokenizer. Expect valid prompt_token_ids and None for prompt
|
||||
from the input.
|
||||
@@ -338,6 +338,7 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
configure_logging_if_needed(engine_args.create_logging_config())
|
||||
log_non_default_args(engine_args)
|
||||
|
||||
self.llm_engine = LLMEngine.from_engine_args(
|
||||
|
||||
@@ -215,7 +215,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
# https://platform.openai.com/docs/api-reference/chat/create
|
||||
messages: list[ChatCompletionMessageParam]
|
||||
model: str | None = None
|
||||
frequency_penalty: float | None = 0.0
|
||||
frequency_penalty: float | None = None
|
||||
logit_bias: dict[str, float] | None = None
|
||||
logprobs: bool | None = False
|
||||
top_logprobs: int | None = 0
|
||||
@@ -226,7 +226,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
)
|
||||
max_completion_tokens: int | None = None
|
||||
n: int | None = 1
|
||||
presence_penalty: float | None = 0.0
|
||||
presence_penalty: float | None = None
|
||||
response_format: AnyResponseFormat | None = None
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: StopParam = []
|
||||
@@ -624,6 +624,8 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
# Default sampling parameters for chat completion requests
|
||||
_DEFAULT_SAMPLING_PARAMS: dict = {
|
||||
"repetition_penalty": 1.0,
|
||||
"presence_penalty": 0.0,
|
||||
"frequency_penalty": 0.0,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": 0,
|
||||
@@ -661,28 +663,15 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
max_tokens: int,
|
||||
default_sampling_params: dict,
|
||||
) -> SamplingParams:
|
||||
# Default parameters
|
||||
if (repetition_penalty := self.repetition_penalty) is None:
|
||||
repetition_penalty = default_sampling_params.get(
|
||||
"repetition_penalty",
|
||||
self._DEFAULT_SAMPLING_PARAMS["repetition_penalty"],
|
||||
)
|
||||
if (temperature := self.temperature) is None:
|
||||
temperature = default_sampling_params.get(
|
||||
"temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
|
||||
)
|
||||
if (top_p := self.top_p) is None:
|
||||
top_p = default_sampling_params.get(
|
||||
"top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
|
||||
)
|
||||
if (top_k := self.top_k) is None:
|
||||
top_k = default_sampling_params.get(
|
||||
"top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
|
||||
)
|
||||
if (min_p := self.min_p) is None:
|
||||
min_p = default_sampling_params.get(
|
||||
"min_p", self._DEFAULT_SAMPLING_PARAMS["min_p"]
|
||||
# Priority: user -> server default -> OpenAI default
|
||||
sampling_params = {
|
||||
name: (
|
||||
value
|
||||
if (value := getattr(self, name)) is not None
|
||||
else default_sampling_params.get(name, default)
|
||||
)
|
||||
for name, default in self._DEFAULT_SAMPLING_PARAMS.items()
|
||||
}
|
||||
|
||||
# Merge server-default stop_token_ids (e.g., model-specific tokens
|
||||
# like </call> for gpt-oss) with any request-specified ones
|
||||
@@ -709,14 +698,8 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
extra_args["ec_transfer_params"] = self.ec_transfer_params
|
||||
return SamplingParams.from_optional(
|
||||
n=self.n,
|
||||
presence_penalty=self.presence_penalty,
|
||||
frequency_penalty=self.frequency_penalty,
|
||||
repetition_penalty=repetition_penalty,
|
||||
temperature=temperature,
|
||||
**sampling_params,
|
||||
watermarking=self.watermarking,
|
||||
top_p=top_p,
|
||||
top_k=top_k,
|
||||
min_p=min_p,
|
||||
seed=self.seed,
|
||||
stop=self.stop,
|
||||
stop_token_ids=stop_token_ids,
|
||||
|
||||
@@ -672,11 +672,14 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
|
||||
# set the previous values for the next iteration
|
||||
previous_num_tokens[i] += len(output.token_ids)
|
||||
if parser is not None:
|
||||
if parser is not None and self._include_reasoning_tokens_details:
|
||||
generated_token_ids[i].extend(output.token_ids)
|
||||
previous_reasoning_tokens[i] = parser.count_reasoning_tokens(
|
||||
tuple(generated_token_ids[i])
|
||||
)
|
||||
if include_continuous_usage:
|
||||
previous_reasoning_tokens[i] = (
|
||||
parser.count_reasoning_tokens(
|
||||
tuple(generated_token_ids[i])
|
||||
)
|
||||
)
|
||||
|
||||
# if the message delta is None (e.g. because it was a
|
||||
# "control token" for tool calls or the parser otherwise
|
||||
@@ -693,11 +696,13 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
logprobs = None
|
||||
|
||||
if delta_message is None:
|
||||
# NOTE: If return_token_ids is enabled, we still need to
|
||||
# send a chunk with token_ids even if delta_message is None
|
||||
# NOTE: If return_token_ids or logprobs are enabled, we
|
||||
# still need to send a chunk even if delta_message is None
|
||||
# to ensure all tokens are included in the response
|
||||
if output.finish_reason is None and (
|
||||
not request.return_token_ids or hide_stream_metadata
|
||||
if (
|
||||
output.finish_reason is None
|
||||
and logprobs is None
|
||||
and (not request.return_token_ids or hide_stream_metadata)
|
||||
):
|
||||
continue
|
||||
delta_message = DeltaMessage()
|
||||
@@ -757,7 +762,11 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
# finish_reason is:
|
||||
# "tool_calls" for "auto" or "required" tool calls,
|
||||
# and "stop" for named tool calls.
|
||||
if tools_streamed[i] and not tool_choice_function_name:
|
||||
if (
|
||||
tools_streamed[i]
|
||||
and not tool_choice_function_name
|
||||
and output.finish_reason == "stop"
|
||||
):
|
||||
finish_reason_ = "tool_calls"
|
||||
else:
|
||||
finish_reason_ = (
|
||||
@@ -814,6 +823,13 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
data = chunk.model_dump_json(exclude_unset=True)
|
||||
yield f"data: {data}\n\n"
|
||||
|
||||
if self._include_reasoning_tokens_details and not include_continuous_usage:
|
||||
for i, parser in enumerate(parsers):
|
||||
if parser is not None and generated_token_ids[i]:
|
||||
previous_reasoning_tokens[i] = parser.count_reasoning_tokens(
|
||||
tuple(generated_token_ids[i])
|
||||
)
|
||||
|
||||
# once the final token is handled, if stream_options.include_usage
|
||||
# is sent, send the usage
|
||||
if include_usage:
|
||||
|
||||
@@ -55,12 +55,12 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
| None
|
||||
) = None
|
||||
echo: bool | None = False
|
||||
frequency_penalty: float | None = 0.0
|
||||
frequency_penalty: float | None = None
|
||||
logit_bias: dict[str, float] | None = None
|
||||
logprobs: int | None = None
|
||||
max_tokens: int | None = 16
|
||||
n: int = 1
|
||||
presence_penalty: float | None = 0.0
|
||||
presence_penalty: float | None = None
|
||||
seed: int | None = Field(None, ge=_INT64_MIN, le=_INT64_MAX)
|
||||
stop: StopParam = []
|
||||
stream: bool | None = False
|
||||
@@ -278,6 +278,8 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
# Default sampling parameters for completion requests
|
||||
_DEFAULT_SAMPLING_PARAMS: dict = {
|
||||
"repetition_penalty": 1.0,
|
||||
"presence_penalty": 0.0,
|
||||
"frequency_penalty": 0.0,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"top_k": 0,
|
||||
@@ -321,28 +323,15 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
if default_sampling_params is None:
|
||||
default_sampling_params = {}
|
||||
|
||||
# Default parameters
|
||||
if (repetition_penalty := self.repetition_penalty) is None:
|
||||
repetition_penalty = default_sampling_params.get(
|
||||
"repetition_penalty",
|
||||
self._DEFAULT_SAMPLING_PARAMS["repetition_penalty"],
|
||||
)
|
||||
if (temperature := self.temperature) is None:
|
||||
temperature = default_sampling_params.get(
|
||||
"temperature", self._DEFAULT_SAMPLING_PARAMS["temperature"]
|
||||
)
|
||||
if (top_p := self.top_p) is None:
|
||||
top_p = default_sampling_params.get(
|
||||
"top_p", self._DEFAULT_SAMPLING_PARAMS["top_p"]
|
||||
)
|
||||
if (top_k := self.top_k) is None:
|
||||
top_k = default_sampling_params.get(
|
||||
"top_k", self._DEFAULT_SAMPLING_PARAMS["top_k"]
|
||||
)
|
||||
if (min_p := self.min_p) is None:
|
||||
min_p = default_sampling_params.get(
|
||||
"min_p", self._DEFAULT_SAMPLING_PARAMS["min_p"]
|
||||
# Priority: user -> server default -> OpenAI default
|
||||
sampling_params = {
|
||||
name: (
|
||||
value
|
||||
if (value := getattr(self, name)) is not None
|
||||
else default_sampling_params.get(name, default)
|
||||
)
|
||||
for name, default in self._DEFAULT_SAMPLING_PARAMS.items()
|
||||
}
|
||||
|
||||
# Merge server-default stop_token_ids (e.g., model-specific tokens
|
||||
# like </call> for gpt-oss) with any request-specified ones
|
||||
@@ -371,14 +360,8 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
extra_args["ec_transfer_params"] = self.ec_transfer_params
|
||||
return SamplingParams.from_optional(
|
||||
n=self.n,
|
||||
presence_penalty=self.presence_penalty,
|
||||
frequency_penalty=self.frequency_penalty,
|
||||
repetition_penalty=repetition_penalty,
|
||||
temperature=temperature,
|
||||
**sampling_params,
|
||||
watermarking=self.watermarking,
|
||||
top_p=top_p,
|
||||
top_k=top_k,
|
||||
min_p=min_p,
|
||||
seed=self.seed,
|
||||
stop=self.stop,
|
||||
stop_token_ids=stop_token_ids,
|
||||
|
||||
@@ -116,9 +116,7 @@ class OpenAIServingCompletion(GenerateBaseServing):
|
||||
See https://platform.openai.com/docs/api-reference/completions/create
|
||||
for the API specification. This API mimics the OpenAI Completion API.
|
||||
|
||||
NOTE: Currently we do not support the following feature:
|
||||
- suffix (the language models we currently support do not support
|
||||
suffix)
|
||||
NOTE: suffix is only supported by models that implement FIM rendering.
|
||||
"""
|
||||
return await self._with_kv_transfer_rejection_cleanup(
|
||||
self._create_completion(request, raw_request), request, raw_request
|
||||
|
||||
@@ -615,12 +615,14 @@ class HarmonyContext(ConversationContext):
|
||||
available_tools: list[str],
|
||||
function_tool_names: frozenset[str],
|
||||
response_parser: Parser | None = None,
|
||||
request: ResponsesRequest | None = None,
|
||||
):
|
||||
from vllm.parser.harmony import HarmonyParser, Segment
|
||||
|
||||
assert isinstance(response_parser, HarmonyParser)
|
||||
|
||||
self._messages = messages
|
||||
self.request = request
|
||||
self.response_parser: HarmonyParser = response_parser
|
||||
self.finish_reason: str | None = None
|
||||
self.available_tools = available_tools
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# Adapted from
|
||||
# https://github.com/lm-sys/FastChat/blob/168ccc29d3f7edc50823016105c024fe2282732a/fastchat/protocol/openai_api_protocol.py
|
||||
import time
|
||||
from typing import Any, Literal, TypeAlias
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from openai.types.responses import (
|
||||
ResponseCodeInterpreterCallCodeDeltaEvent,
|
||||
@@ -49,6 +49,7 @@ from openai.types.responses.tool import Tool
|
||||
from openai.types.shared import Metadata, Reasoning
|
||||
from openai_harmony import Message as OpenAIHarmonyMessage
|
||||
from pydantic import (
|
||||
BeforeValidator,
|
||||
Field,
|
||||
ValidationError,
|
||||
field_serializer,
|
||||
@@ -135,6 +136,31 @@ ResponseInputOutputMessage: TypeAlias = (
|
||||
ResponseInputOutputItem: TypeAlias = ResponseInputItemParam | ResponseOutputItem
|
||||
|
||||
|
||||
def _default_input_image_details(value: Any) -> Any:
|
||||
"""Set the API default for input images before SDK type validation."""
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
|
||||
content = value.get("content")
|
||||
if not isinstance(content, list):
|
||||
return value
|
||||
|
||||
new_content = []
|
||||
changed = False
|
||||
for part in content:
|
||||
new_part = part
|
||||
if (
|
||||
isinstance(part, dict)
|
||||
and part.get("type") == "input_image"
|
||||
and "detail" not in part
|
||||
):
|
||||
new_part = {**part, "detail": "auto"}
|
||||
changed = True
|
||||
new_content.append(new_part)
|
||||
|
||||
return {**value, "content": new_content} if changed else value
|
||||
|
||||
|
||||
class ResponsesRequest(OpenAIBaseModel):
|
||||
# Ordered by official OpenAI API documentation
|
||||
# https://platform.openai.com/docs/api-reference/responses/create
|
||||
@@ -152,7 +178,15 @@ class ResponsesRequest(OpenAIBaseModel):
|
||||
]
|
||||
| None
|
||||
) = None
|
||||
input: str | list[ResponseInputOutputItem]
|
||||
input: (
|
||||
str
|
||||
| list[
|
||||
Annotated[
|
||||
ResponseInputOutputItem,
|
||||
BeforeValidator(_default_input_image_details),
|
||||
]
|
||||
]
|
||||
)
|
||||
instructions: str | None = None
|
||||
max_output_tokens: int | None = None
|
||||
max_tool_calls: int | None = None
|
||||
|
||||
@@ -443,6 +443,7 @@ class OpenAIServingResponses(GenerateBaseServing):
|
||||
available_tools,
|
||||
function_tool_names,
|
||||
response_parser=response_parser,
|
||||
request=request,
|
||||
)
|
||||
else:
|
||||
if envs.VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT:
|
||||
@@ -678,8 +679,12 @@ class OpenAIServingResponses(GenerateBaseServing):
|
||||
tok_params=tok_params,
|
||||
)
|
||||
|
||||
sampling_params.max_tokens = max_model_len - self._extract_prompt_len(
|
||||
engine_input
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
max_model_len,
|
||||
context.request.max_output_tokens if context.request else None,
|
||||
self._extract_prompt_len(engine_input),
|
||||
self.default_sampling_params,
|
||||
self.override_max_tokens,
|
||||
)
|
||||
elif isinstance(context, ParsableContext):
|
||||
(engine_input,) = await self._render_next_turn(
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm import PoolingRequestOutput, envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateConfig
|
||||
from vllm.entrypoints.generate.base.protocol import validate_request_mm_kwargs
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.serve.engine.serving import BaseServing
|
||||
from vllm.entrypoints.serve.engine.typing import AnyRequest
|
||||
@@ -60,6 +61,7 @@ class PoolingBaseServing(ABC, BaseServing):
|
||||
self.return_tokens_as_token_ids = return_tokens_as_token_ids
|
||||
self.log_error_stack = log_error_stack
|
||||
self.chat_template_config = chat_template_config
|
||||
self.trust_request_mm_kwargs = chat_template_config.trust_request_mm_kwargs
|
||||
|
||||
# Shared thread pool executor for preprocessing and postprocessing.
|
||||
self._executor: Executor = self.renderer._executor
|
||||
@@ -108,6 +110,11 @@ class PoolingBaseServing(ABC, BaseServing):
|
||||
request: AnyPoolingRequest,
|
||||
raw_request: Request | None = None,
|
||||
):
|
||||
validate_request_mm_kwargs(
|
||||
mm_processor_kwargs=getattr(request, "mm_processor_kwargs", None),
|
||||
media_io_kwargs=getattr(request, "media_io_kwargs", None),
|
||||
trust_request_mm_kwargs=self.trust_request_mm_kwargs,
|
||||
)
|
||||
base_request_id = self._base_request_id(
|
||||
raw_request, getattr(request, "request_id", None)
|
||||
)
|
||||
|
||||
@@ -166,6 +166,7 @@ def init_pooling_state(
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
trust_request_chat_template=args.trust_request_chat_template,
|
||||
trust_request_mm_kwargs=args.trust_request_mm_kwargs,
|
||||
)
|
||||
|
||||
state.serving_pooling = (
|
||||
|
||||
@@ -621,7 +621,7 @@ class CrossEncoderIOProcessor(ScoringIOProcessor):
|
||||
model_config,
|
||||
)
|
||||
|
||||
# Apply truncation before defining closures
|
||||
# Limit the query and document separately before composing them.
|
||||
if max_tokens_per_query > 0 and isinstance(prompt_1, str):
|
||||
prompt_1 = truncate_text_to_tokens(
|
||||
prompt_1, tokenizer, max_tokens_per_query
|
||||
@@ -666,16 +666,8 @@ class CrossEncoderIOProcessor(ScoringIOProcessor):
|
||||
full_prompt = tokenizer.decode(prompt_inputs["input_ids"])
|
||||
else:
|
||||
# `llm as reranker` defaults to not using separating token.
|
||||
if max_tokens_per_doc > 0 and isinstance(prompt_2, str):
|
||||
query_ids = tokenizer.encode(prompt_1, add_special_tokens=False)
|
||||
doc_ids = tokenizer.encode(prompt_2, add_special_tokens=False)
|
||||
doc_ids = doc_ids[:max_tokens_per_doc]
|
||||
input_ids = query_ids + doc_ids
|
||||
full_prompt = tokenizer.decode(input_ids)
|
||||
prompt_inputs = {"input_ids": input_ids}
|
||||
else:
|
||||
full_prompt = prompt_1 + prompt_2
|
||||
prompt_inputs = tokenizer(text=full_prompt, **local_kwargs)
|
||||
full_prompt = prompt_1 + prompt_2
|
||||
prompt_inputs = tokenizer(text=full_prompt, **local_kwargs)
|
||||
return full_prompt, prompt_inputs
|
||||
|
||||
# FIXME: For now, we only apply a template when one is explicitly provided.
|
||||
|
||||
@@ -48,13 +48,27 @@ def truncate_text_to_tokens(
|
||||
|
||||
Uses offset_mapping to slice the original text at the exact character
|
||||
boundary, avoiding lossy encode→decode round-trips that can shift
|
||||
the token count by 1-3 tokens due to BPE merge boundary changes.
|
||||
the token count due to BPE merge boundary changes.
|
||||
"""
|
||||
encoding = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
|
||||
if len(encoding["input_ids"]) <= max_tokens:
|
||||
return text
|
||||
char_end = encoding["offset_mapping"][max_tokens - 1][1]
|
||||
return text[:char_end]
|
||||
if max_tokens <= 0:
|
||||
return ""
|
||||
|
||||
while text:
|
||||
encoding = tokenizer(
|
||||
text,
|
||||
add_special_tokens=False,
|
||||
return_offsets_mapping=True,
|
||||
)
|
||||
offsets = encoding["offset_mapping"]
|
||||
if len(encoding["input_ids"]) <= max_tokens:
|
||||
break
|
||||
|
||||
char_end = min(offsets[max_tokens - 1][1], offsets[max_tokens][0])
|
||||
if char_end >= len(text):
|
||||
char_end = len(text) - 1
|
||||
text = text[:char_end]
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def compute_maxsim_score(q_emb: torch.Tensor, d_emb: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -57,9 +57,7 @@ class ServingRender(BaseServing):
|
||||
self.tool_server = tool_server
|
||||
|
||||
self._merge_inline_system = (
|
||||
AnthropicServingMessages._detect_merge_inline_system(
|
||||
online_renderer.chat_template
|
||||
)
|
||||
AnthropicServingMessages._should_merge_inline_system(online_renderer)
|
||||
)
|
||||
|
||||
self._placeholder_metadata_parser: MultiModalDataParser | None = None
|
||||
|
||||
@@ -590,7 +590,10 @@ class ServingTokens(GenerateBaseServing):
|
||||
step_top_logprobs.items()
|
||||
)
|
||||
if num_output_top_logprobs is not None
|
||||
and i < max(num_output_top_logprobs, 1)
|
||||
and (
|
||||
num_output_top_logprobs == -1
|
||||
or i < max(num_output_top_logprobs, 1)
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
@@ -41,6 +41,9 @@ class BaseServing:
|
||||
self,
|
||||
request: AnyRequest | AnyPoolingRequest,
|
||||
) -> ErrorResponse | None:
|
||||
if self.request_logger is not None:
|
||||
self.request_logger.log_request_body(request)
|
||||
|
||||
error_response = None
|
||||
|
||||
if self._is_model_supported(request.model):
|
||||
|
||||
@@ -6,7 +6,7 @@ import regex as re
|
||||
|
||||
def sanitize_message(message: str) -> str:
|
||||
"""Strip memory addresses, tracebacks, and file paths from error messages."""
|
||||
message = re.sub(r" at 0x[0-9a-f]+>", ">", message)
|
||||
message = re.sub(r" at 0x[0-9a-fA-F]+>", ">", message)
|
||||
message = re.sub(r'\n?\s*File "[^"]+", line \d+, in \S+(\n\s+.*)?', "", message)
|
||||
message = re.sub(
|
||||
r"/(?:home|usr|opt|var|tmp|root|lib|mnt|srv)(?:/[\w.\-]+)+", "<path>", message
|
||||
|
||||
@@ -6,6 +6,8 @@ from collections.abc import Sequence
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.entrypoints.pooling.typing import AnyPoolingRequest
|
||||
from vllm.entrypoints.serve.engine.typing import AnyRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.pooling_params import PoolingParams
|
||||
@@ -29,7 +31,7 @@ class RequestLogger:
|
||||
"`--enable-log-requests` is set but "
|
||||
"the minimum log level is higher than DEBUG. "
|
||||
"Only limited information will be logged to minimize overhead. "
|
||||
"To view more details, set `VLLM_LOGGING_LEVEL=DEBUG`."
|
||||
"To view more details, set `--log-level DEBUG`."
|
||||
)
|
||||
|
||||
def log_inputs(
|
||||
@@ -67,6 +69,15 @@ class RequestLogger:
|
||||
lora_request,
|
||||
)
|
||||
|
||||
def log_request_body(self, request: AnyRequest | AnyPoolingRequest) -> None:
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
max_log_len = self.max_log_len if self.max_log_len is not None else -1
|
||||
logger.debug(
|
||||
"Request %s JSON body: %s",
|
||||
getattr(request, "request_id", "N/A"),
|
||||
request.model_dump_json(exclude_unset=True)[:max_log_len],
|
||||
)
|
||||
|
||||
def log_outputs(
|
||||
self,
|
||||
request_id: str,
|
||||
|
||||
@@ -916,6 +916,58 @@ def _patch_inductor_fallback_allow_list() -> None:
|
||||
|
||||
_patch_inductor_fallback_allow_list()
|
||||
|
||||
|
||||
def _apply_inductor_pattern_matcher_patch() -> None:
|
||||
"""Allow custom ops and functionalization wrappers with unsupported dtypes."""
|
||||
from torch._inductor import pattern_matcher
|
||||
from torch._inductor.lowering import fallback_node_due_to_unsupported_type
|
||||
|
||||
def fallback_for_builtin(node, allow_cpu_inputs=True):
|
||||
return (
|
||||
isinstance(node.target, torch._ops.OpOverload)
|
||||
and torch._library.utils.is_builtin(node.target)
|
||||
and fallback_node_due_to_unsupported_type(node, allow_cpu_inputs)
|
||||
)
|
||||
|
||||
pattern_matcher.fallback_node_due_to_unsupported_type = fallback_for_builtin
|
||||
|
||||
|
||||
def _patch_inductor_pattern_matcher() -> None:
|
||||
"""Apply the backport when Inductor imports its pattern matcher."""
|
||||
import sys
|
||||
|
||||
target_name = "torch._inductor.pattern_matcher"
|
||||
if target_name in sys.modules:
|
||||
_apply_inductor_pattern_matcher_patch()
|
||||
return
|
||||
|
||||
import importlib.abc
|
||||
|
||||
class _PatternMatcherPatchFinder(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname != target_name:
|
||||
return None
|
||||
sys.meta_path.remove(self)
|
||||
spec = importlib.util.find_spec(fullname)
|
||||
if spec is None or spec.loader is None:
|
||||
return None
|
||||
original_exec = spec.loader.exec_module
|
||||
|
||||
def _exec_then_patch(module):
|
||||
original_exec(module)
|
||||
_apply_inductor_pattern_matcher_patch()
|
||||
|
||||
spec.loader.exec_module = _exec_then_patch # type: ignore[method-assign]
|
||||
return spec
|
||||
|
||||
sys.meta_path.insert(0, _PatternMatcherPatchFinder())
|
||||
|
||||
|
||||
# Remove once the minimum supported torch includes
|
||||
# https://github.com/pytorch/pytorch/pull/196013.
|
||||
if not is_torch_equal_or_newer("2.16.0.dev"):
|
||||
_patch_inductor_pattern_matcher()
|
||||
|
||||
# ============================================================
|
||||
# Triton Autotuner determinism
|
||||
# ============================================================
|
||||
|
||||
+21
-18
@@ -63,6 +63,7 @@ if TYPE_CHECKING:
|
||||
VLLM_USE_RAY_COMPILED_DAG_CHANNEL_TYPE: Literal["auto", "nccl", "shm"] = "auto"
|
||||
VLLM_USE_RAY_COMPILED_DAG_OVERLAP_COMM: bool = False
|
||||
VLLM_USE_RAY_WRAPPED_PP_COMM: bool = True
|
||||
VLLM_XPU_PP_MICROBATCH: bool = True
|
||||
VLLM_USE_RAY_V2_EXECUTOR_BACKEND: bool = False
|
||||
VLLM_DISTRIBUTED_USE_SPLIT_GROUP: bool = False
|
||||
VLLM_XLA_USE_SPMD: bool = False
|
||||
@@ -123,6 +124,7 @@ if TYPE_CHECKING:
|
||||
VLLM_USE_TRITON_AWQ: bool = False
|
||||
VLLM_FASTSAFETENSORS_QUEUE_SIZE: int = 0
|
||||
VLLM_TRITON_FORCE_FIRST_CONFIG: bool = False
|
||||
VLLM_TRITON_JIT_WARMUP_NUM_THREADS: int = 4
|
||||
VLLM_ALLOW_RUNTIME_LORA_UPDATING: bool = False
|
||||
VLLM_SKIP_P2P_CHECK: bool = False
|
||||
VLLM_DISABLED_KERNELS: list[str] = []
|
||||
@@ -139,7 +141,7 @@ if TYPE_CHECKING:
|
||||
VLLM_ROCM_USE_AITER_LINEAR_HIPBMM: bool = False
|
||||
VLLM_ROCM_USE_AITER_MOE: bool = True
|
||||
VLLM_ROCM_AITER_MOE_DISPATCH_POLICY: int = 0
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: bool = False
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: Literal["auto", "a4w4", "a8w4", "a16w4"] = "auto"
|
||||
VLLM_ROCM_USE_AITER_RMSNORM: bool = True
|
||||
VLLM_ROCM_USE_AITER_MLA: bool = True
|
||||
VLLM_ROCM_AITER_MLA_ASM_PADDING: Literal["auto", "gluon", "asm"] = "auto"
|
||||
@@ -317,7 +319,6 @@ if TYPE_CHECKING:
|
||||
VLLM_ELASTIC_EP_SCALE_UP_LAUNCH: bool = False
|
||||
VLLM_ELASTIC_EP_DRAIN_REQUESTS: bool = False
|
||||
VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS: bool = True
|
||||
VLLM_XPU_ENABLE_XPU_GRAPH: bool = False
|
||||
VLLM_XPU_FORCE_N_CONTIG_WEIGHT: bool = False
|
||||
VLLM_XPU_USE_SAMPLER_KERNEL: bool = True
|
||||
VLLM_XPU_INC_WNA16_BACKEND: Literal["auto", "ark", "w4a16", "w4a8"] = "auto"
|
||||
@@ -924,6 +925,11 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_USE_RAY_WRAPPED_PP_COMM": lambda: bool(
|
||||
int(os.getenv("VLLM_USE_RAY_WRAPPED_PP_COMM", "1"))
|
||||
),
|
||||
# Using a flag to control microbatch on XPU device, users on XPU device can
|
||||
# decide to disable it when they needed.
|
||||
"VLLM_XPU_PP_MICROBATCH": lambda: bool(
|
||||
int(os.getenv("VLLM_XPU_PP_MICROBATCH", "1"))
|
||||
),
|
||||
# When True and distributed_executor_backend="ray", use RayExecutorV2
|
||||
# (MQ-based) instead of RayDistributedExecutor (compiled-graph backend).
|
||||
"VLLM_USE_RAY_V2_EXECUTOR_BACKEND": lambda: bool(
|
||||
@@ -1182,6 +1188,11 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
os.environ.get("VLLM_TRITON_FORCE_FIRST_CONFIG", "0").strip().lower()
|
||||
in ("1", "true")
|
||||
),
|
||||
# Maximum compiler threads per worker for registered CUDA Triton JIT warmup.
|
||||
# Set to 1 for serial warmup. Does not affect runtime JIT or autotuning.
|
||||
"VLLM_TRITON_JIT_WARMUP_NUM_THREADS": lambda: int(
|
||||
os.getenv("VLLM_TRITON_JIT_WARMUP_NUM_THREADS", "4")
|
||||
),
|
||||
# If set, allow loading or unloading lora adapters in runtime,
|
||||
"VLLM_ALLOW_RUNTIME_LORA_UPDATING": lambda: (
|
||||
os.environ.get("VLLM_ALLOW_RUNTIME_LORA_UPDATING", "0").strip().lower()
|
||||
@@ -1269,18 +1280,13 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_ROCM_USE_AITER_MOE": lambda: (
|
||||
os.getenv("VLLM_ROCM_USE_AITER_MOE", "True").lower() in ("true", "1")
|
||||
),
|
||||
# Route K3 SiTU MXFP4 MoE through the FlyDSL SiTUv2 path (a4w4 fp4
|
||||
# activations, separated gate/up layout) instead of default a16w4. vLLM
|
||||
# sets AITER_SITUV2_A4W4 at init when this flag is on and clears any
|
||||
# legacy AITER_SITUV2_A8W4 override (AITER checks A8W4 first).
|
||||
# VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4 is a deprecated alias for existing
|
||||
# recipes; it does not select a8w4 kernels.
|
||||
# Needs AITER >= v0.1.20 (ROCm/aiter#4463) for the a4w4 dispatch flag
|
||||
# and tuned kimik3_a4w4_*_fmoe.csv rows; otherwise FlyDSL uses heuristics.
|
||||
"VLLM_ROCM_USE_AITER_MOE_SITUV2": lambda: (
|
||||
os.getenv("VLLM_ROCM_USE_AITER_MOE_SITUV2", "0").lower() in ("true", "1")
|
||||
or os.getenv("VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4", "0").lower()
|
||||
in ("true", "1")
|
||||
# Activation dtype for the Kimi-K3 SiTU MXFP4 MoE (AITER FlyDSL SiTUv2):
|
||||
# auto (= a4w4), a4w4, a8w4 or a16w4. Legacy 1/0 mean a4w4/a16w4.
|
||||
"VLLM_ROCM_USE_AITER_MOE_SITUV2": env_with_choices(
|
||||
"VLLM_ROCM_USE_AITER_MOE_SITUV2",
|
||||
"auto",
|
||||
["auto", "a4w4", "a8w4", "a16w4", "0", "1"],
|
||||
case_sensitive=False,
|
||||
),
|
||||
# MoE sorting dispatch policy for AITER fused MoE kernels.
|
||||
# 0 = auto (default): single-pass for small batches, multi-pass
|
||||
@@ -2139,10 +2145,6 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS": lambda: bool(
|
||||
int(os.getenv("VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS", "1"))
|
||||
),
|
||||
# Whether enable XPU graph on Intel GPU
|
||||
"VLLM_XPU_ENABLE_XPU_GRAPH": lambda: bool(
|
||||
int(os.getenv("VLLM_XPU_ENABLE_XPU_GRAPH", "0"))
|
||||
),
|
||||
# Force N-contiguous weight layout for all XPU unquantized linears.
|
||||
"VLLM_XPU_FORCE_N_CONTIG_WEIGHT": lambda: bool(
|
||||
int(os.getenv("VLLM_XPU_FORCE_N_CONTIG_WEIGHT", "0"))
|
||||
@@ -2277,6 +2279,7 @@ def compile_factors() -> dict[str, object]:
|
||||
hash everything else. This keeps the cache key aligned across workers."""
|
||||
ignored_factors: set[str] = {
|
||||
"MAX_JOBS",
|
||||
"VLLM_TRITON_JIT_WARMUP_NUM_THREADS",
|
||||
"VLLM_RPC_BASE_PATH",
|
||||
"VLLM_USE_MODELSCOPE",
|
||||
"VLLM_RINGBUFFER_WARNING_INTERVAL",
|
||||
|
||||
+14
-3
@@ -58,8 +58,17 @@ class BatchDescriptor:
|
||||
|
||||
|
||||
def _compute_sp_num_tokens(
|
||||
num_tokens_across_dp_cpu: torch.Tensor, sequence_parallel_size: int
|
||||
num_tokens_across_dp_cpu: torch.Tensor,
|
||||
sequence_parallel_size: int,
|
||||
pcp_size: int = 1,
|
||||
use_ep: bool = True,
|
||||
) -> list[int]:
|
||||
if pcp_size > 1:
|
||||
num_tokens_across_dp_cpu = (
|
||||
num_tokens_across_dp_cpu.repeat_interleave(pcp_size)
|
||||
if use_ep
|
||||
else num_tokens_across_dp_cpu * pcp_size
|
||||
)
|
||||
sp_tokens = (
|
||||
num_tokens_across_dp_cpu + sequence_parallel_size - 1
|
||||
) // sequence_parallel_size
|
||||
@@ -98,12 +107,14 @@ class DPMetadata:
|
||||
return DPMetadata(num_tokens_across_dp_cpu)
|
||||
|
||||
@contextmanager
|
||||
def sp_local_sizes(self, sequence_parallel_size: int):
|
||||
def sp_local_sizes(
|
||||
self, sequence_parallel_size: int, pcp_size: int = 1, use_ep: bool = False
|
||||
):
|
||||
"""Context manager for setting self.local_sizes. Same as self.chunked_sizes
|
||||
but without any chunking.
|
||||
"""
|
||||
self.local_sizes = _compute_sp_num_tokens(
|
||||
self.num_tokens_across_dp_cpu, sequence_parallel_size
|
||||
self.num_tokens_across_dp_cpu, sequence_parallel_size, pcp_size, use_ep
|
||||
)
|
||||
try:
|
||||
yield self.local_sizes
|
||||
|
||||
@@ -74,7 +74,7 @@ class ConfigSet:
|
||||
f"If your GPU is a variant of a supported platform, "
|
||||
f"consider adding a mapping in _GPU_NAME_ALIASES in "
|
||||
f"vllm/kernels/helion/utils.py, or run "
|
||||
f"scripts/autotune_helion_kernels.py to generate configs "
|
||||
f"tools/autotune_helion_kernels.py to generate configs "
|
||||
f"for your platform."
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ specific op module it needs, e.g.::
|
||||
|
||||
which triggers that op's ``@register_kernel`` as an import side effect.
|
||||
|
||||
Tools that need the full registry (e.g. scripts/autotune_helion_kernels.py)
|
||||
Tools that need the full registry (e.g. tools/autotune_helion_kernels.py)
|
||||
call ``import_all_ops()`` to force every op module to register.
|
||||
"""
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user