Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-03 21:59:03 +07:00
1012 changed files with 61873 additions and 14499 deletions
+4 -1
View File
@@ -93,7 +93,10 @@ class AttentionConfig:
an SM100-class GPU, DeepGEMM >= 2.8 and the DeepSelect top-k extension
(the top-k runs on the kernels' bf16 logits). The sparse path costs
O(candidate blocks) per query regardless of context length, so it pays off
for long contexts (roughly 32K tokens and beyond) and is slower below."""
for long contexts (roughly 32K tokens and beyond) and is slower below.
On ROCm gfx950 it runs aiter's paged MXFP4 MQA-logits kernel over the
candidate pool instead, with fp32 logits, and keeps the masked dense walk
for steps whose contexts are too short for the pool to pay."""
hisparse_config: HiSparseConfig | None = None
"""HiSparse host-resident KV configuration. Setting this enables experimental
+10 -24
View File
@@ -59,7 +59,7 @@ CacheDType = Literal[
MambaDType = Literal["auto", "float32", "float16", "bfloat16"]
MambaCacheMode = Literal["all", "align", "none"]
MambaCacheMode = Literal["align", "none"]
PrefixCachingHashAlgo = Literal["sha256", "sha256_cbor", "xxhash", "xxhash_cbor"]
KVOffloadingBackend = Literal["native", "lmcache"]
@@ -75,8 +75,6 @@ class CacheConfig:
Accepts None (meaning "use default"). After construction, always int."""
user_specified_block_size: bool = field(default=False, init=False)
"""Whether block_size was explicitly provided. Derived automatically."""
user_specified_mamba_block_size: bool = field(default=False, init=False)
"""Whether mamba_block_size was explicitly provided. Derived automatically."""
kv_cache_layout: str | None = field(default=None, init=False)
"""Resolved physical KV cache layout name (a ``KVCacheLayout`` member).
@@ -191,7 +189,6 @@ class CacheConfig:
"""The cache strategy for Mamba layers:
- "none": set when prefix caching is disabled.
- "all": cache the mamba state of all tokens at position i * block_size.
- "align": only cache the mamba state of the last token of each scheduler step and
when the token is at position i * block_size. This is the default when prefix
caching is enabled.
@@ -204,15 +201,16 @@ class CacheConfig:
Mamba block size."""
replayssm_buffer_len: int = Field(default=16, gt=0)
"""ReplaySSM logical history length B for Mamba2. Triton uses B physical
rows and FlashInfer uses B+1. Kimi-K3 speculative decode does not use B.
Default 16."""
rows and FlashInfer uses B+T, where T is the target verification length.
Kimi-K3 speculative decode does not use B. Default 16."""
use_replayssm: bool = False
"""Use the ReplaySSM Mamba2 decode kernel: cache recent SSM inputs and skip
the per-step full-state store, writing the checkpoint back only on flush.
Requires mamba_cache_mode 'none' or 'align' (prefix caching) and the Triton
or FlashInfer mamba backend; standard (non-speculative) decode only. In align
mode flushes are most efficient when mamba_block_size is a multiple of
replayssm_buffer_len, but this is not required."""
or FlashInfer mamba backend. Mamba2 speculative decode requires FlashInfer
and mamba_cache_mode 'none'. In align mode flushes are most efficient when
mamba_block_size is a multiple of replayssm_buffer_len, but this is not
required."""
use_recoverssm: bool = field(default=False, init=False)
"""Whether Kimi-K3 KDA uses RecoverSSM speculative decode."""
@@ -242,7 +240,9 @@ class CacheConfig:
swa_bounded_replay: bool = True
"""Keep the sliding-window KV of models that support it (DeepSeek-V4.1)
out of prefix caching and rebuild it after a prefix hit by recomputing the
hit's last window. Requires model runner V2."""
hit's last window. The layers past the last KV-source layer then also run
eager prefill steps on each request's trailing window only. Requires model
runner V2."""
kv_cache_memory_bytes: int | None = None
"""Size of KV Cache per GPU in bytes. By default, this is set to None
@@ -290,7 +290,6 @@ class CacheConfig:
"mamba_page_size_padded",
"skip_page_size_padded",
"user_specified_block_size",
"user_specified_mamba_block_size",
"_block_size_resolved",
# Post-init/derived counters
"num_gpu_blocks",
@@ -334,21 +333,8 @@ class CacheConfig:
self.block_size = self.DEFAULT_BLOCK_SIZE
else:
self.user_specified_block_size = True
if self.mamba_block_size is not None:
self.user_specified_mamba_block_size = True
return self
@field_validator("mamba_cache_mode", mode="after")
@classmethod
def _validate_mamba_cache_mode(cls, mode: MambaCacheMode) -> MambaCacheMode:
if mode == "all":
logger.warning_once(
"Mamba cache mode 'all' is deprecated and will be removed in an "
"upcoming release. If this is a problem, please open an issue "
"at https://github.com/vllm-project/vllm/issues."
)
return mode
@field_validator("cache_dtype", mode="after")
@classmethod
def _validate_cache_dtype(cls, cache_dtype: CacheDType) -> CacheDType:
+1 -5
View File
@@ -72,8 +72,6 @@ class EngramConfig:
def verify_model_config(self, model_config: "ModelConfig | None") -> None:
"""Reject Engram configuration for models without n-gram embeddings."""
from vllm.platforms import current_platform
field = (
_NGRAM_LAYER_FIELDS.get(model_config.architecture)
if model_config is not None
@@ -82,13 +80,11 @@ class EngramConfig:
if (
model_config is None
or field is None
or not current_platform.is_cuda_alike()
or not getattr(model_config.hf_text_config, field, None)
):
raise ValueError(
"EngramConfig requires a model with supported Engram "
"embeddings, non-empty n-gram layer ids, and a CUDA-alike "
"device (CUDA or ROCm)."
"embeddings and non-empty n-gram layer ids."
)
if self.host_file_gather and (
field != "ple_layer_ids" or current_platform.is_rocm()
+3
View File
@@ -48,6 +48,9 @@ class IrOpPriorityConfig:
# Implementations are hidden from Dynamo,
# so they don't show up in the traced files list.
from vllm.ir.op import IrOp
from vllm.platforms import current_platform
current_platform.import_ir_kernels()
assert "_impls" not in factors
factors["_impls"] = {
+8 -4
View File
@@ -9,6 +9,7 @@ import vllm.envs as envs
from vllm.config.utils import config
LogLevel = Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"]
LogFormatter = Literal["text", "json"]
@config
@@ -17,8 +18,8 @@ class LoggingConfig:
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
``--logging-config.formatter json``. ``--log-level`` and legacy
``--log-config-file`` override their matching fields. Set
``configure_logging`` to false to skip applying a ``dictConfig``.
"""
@@ -27,6 +28,9 @@ class LoggingConfig:
)
"""Log level used when no custom logging configuration is provided."""
formatter: LogFormatter = "text"
"""Formatter used by the built-in logging configuration."""
configure_logging: bool = Field(default_factory=lambda: envs.VLLM_CONFIGURE_LOGGING)
"""Whether to apply a Python logging configuration.
@@ -41,6 +45,6 @@ class LoggingConfig:
"""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.
A custom ``dictConfig`` is authoritative over ``log_level`` and
``formatter`` for logger, handler, and formatter settings.
"""
+19 -2
View File
@@ -26,7 +26,7 @@ from vllm.config.quantization import QuantizationConfigArgs
from vllm.config.scheduler import RunnerType
from vllm.config.utils import config, getattr_iter
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.platforms import CpuArchEnum, current_platform
from vllm.tasks import PoolingTask, ScoreType, SupportedTask
from vllm.transformers_utils.config import (
ConfigFormat,
@@ -108,6 +108,16 @@ HfOverrides = dict[str, Any] | Callable[[PreTrainedConfig], PreTrainedConfig]
ModelImpl = Literal["auto", "vllm", "transformers", "terratorch"]
LayerBlockType = Literal["attention", "linear_attention", "mamba"]
_ATTENTION_LAYER_TYPES = frozenset(
{
"full_attention",
"deepseek_sparse_attention",
"qwen_sparse_attention",
}
)
"""`layer_types` spellings that consume a full attention KV cache. Sparse
attention still caches every token, so it counts as attention here."""
_RUNNER_CONVERTS: dict[RunnerType, list[ConvertType]] = {
"generate": [],
"pooling": ["embed", "classify"],
@@ -1718,7 +1728,8 @@ class ModelConfig:
if layer_types_value is not None:
if block_type == "attention":
return sum(
t == "full_attention" for t in layer_types_value[start:end]
t in _ATTENTION_LAYER_TYPES
for t in layer_types_value[start:end]
)
elif block_type == "linear_attention":
return sum(
@@ -2419,6 +2430,12 @@ def _get_and_verify_dtype(
config_dtype,
is_pooling_model=is_pooling_model,
)
if (
current_platform.is_cpu()
and current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC
and torch_dtype in (torch.float16, torch.float32)
):
torch_dtype = torch.bfloat16
else:
if dtype not in _STR_DTYPE_TO_TORCH_DTYPE:
raise ValueError(f"Unknown dtype: {dtype!r}")
+63
View File
@@ -1,7 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import math
from functools import cached_property
from itertools import pairwise
from typing import Any, Literal
from packaging.version import parse
@@ -65,6 +67,18 @@ class ObservabilityConfig:
kv_cache_metrics_sample: float = Field(default=0.01, gt=0, le=1)
"""Sampling rate for KV cache metrics (0.0, 1.0]. Default 0.01 = 1% of blocks."""
custom_histogram_buckets: dict[str, list[float]] | None = None
"""Custom Prometheus histogram bucket boundaries, as a JSON mapping from
bucket-family key to a list of strictly increasing, positive, finite
upper bounds. When a family key is present, its list replaces the default
buckets for every histogram in that family; families not listed keep
their defaults. Known families: `request_latency`, `time_to_first_token`,
`inter_token_latency`, `iteration_tokens`, `request_params_n`,
`request_num_preemptions`, `request_tokens`, `kv_cache_residency`. Example:
`--custom-histogram-buckets '{"request_latency": [0.01, 0.05, 0.1, 0.5]}'`.
Note that every extra bucket adds one time series per metric and label
set."""
cudagraph_metrics: bool = False
"""Enable CUDA graph metrics (number of padded/unpadded tokens, runtime cudagraph
dispatch modes, and their observed frequencies at every logging interval)."""
@@ -150,6 +164,55 @@ class ObservabilityConfig:
)
return value
@field_validator("custom_histogram_buckets", mode="before")
@classmethod
def _reject_bool_histogram_bounds(cls, value: object) -> object:
"""Reject booleans before pydantic silently coerces them to floats."""
if isinstance(value, dict):
for family, buckets in value.items():
if not isinstance(buckets, list):
continue
for bound in buckets:
if isinstance(bound, bool):
raise ValueError(
f"custom_histogram_buckets[{family!r}]: bound "
f"{bound!r} must be a number, not a boolean"
)
return value
@field_validator("custom_histogram_buckets")
@classmethod
def _validate_custom_histogram_buckets(
cls, value: dict[str, list[float]] | None
) -> dict[str, list[float]] | None:
if value is None:
return value
from vllm.v1.metrics.buckets import BUCKET_FAMILY_KEYS
for family, buckets in value.items():
if family not in BUCKET_FAMILY_KEYS:
raise ValueError(
f"custom_histogram_buckets: unknown bucket family "
f"{family!r}; known families: {sorted(BUCKET_FAMILY_KEYS)}"
)
if not buckets:
raise ValueError(
f"custom_histogram_buckets[{family!r}]: bucket list "
"must not be empty"
)
for bound in buckets:
if not math.isfinite(bound) or bound <= 0:
raise ValueError(
f"custom_histogram_buckets[{family!r}]: bound "
f"{bound!r} must be finite and greater than 0"
)
if any(a >= b for a, b in pairwise(buckets)):
raise ValueError(
f"custom_histogram_buckets[{family!r}]: bounds {buckets} "
"must be strictly increasing"
)
return value
@model_validator(mode="after")
def _validate_tracing_config(self):
if self.collect_detailed_traces and not self.otlp_traces_endpoint:
+13 -4
View File
@@ -599,6 +599,19 @@ class ParallelConfig:
"""Process world size across TP, PCP, PP, and DP."""
return self.world_size * self.data_parallel_size
@property
def pcp_shard_decode_requests(self) -> bool:
"""Whether PCP can shard decode requests across its ranks.
PCP-only execution replicates the KV cache, so each decode request can
have a single PCP owner. DCP shards the KV cache and therefore requires
every decode request to run on every participating DCP rank.
"""
return (
self.prefill_context_parallel_size > 1
and self.decode_context_parallel_size == 1
)
@property
def use_ubatching(self) -> bool:
return self.enable_dbo or self.ubatch_size > 1
@@ -1087,10 +1100,6 @@ class ParallelConfig:
# Lazy import to avoid circular import
from vllm.v1.executor import Executor
# Enable batch invariance settings if requested
if envs.VLLM_BATCH_INVARIANT:
self.disable_custom_all_reduce = True
if (
self.distributed_executor_backend is not None
and not isinstance(self.distributed_executor_backend, str)
+8
View File
@@ -63,6 +63,14 @@ class PoolerConfig:
`None` uses the pooler's default, which is `True` in most cases.
"""
enable_flash_late_interaction: bool = True
"""
Whether the engine-side late-interaction scorer may use the fused
flash-maxsim Triton kernel. Disabled automatically when the API server
is started with `--no-enable-flash-late-interaction`; the reference
scorer is used instead.
"""
## for embedding models
dimensions: int | None = None
"""
+1 -1
View File
@@ -1059,7 +1059,7 @@ class SpeculativeConfig:
)
if hf_config.model_type == "glm5_next":
hf_config.model_type = "glm5_next_mtp"
n_predict = hf_config.num_nextn_predict_layers
n_predict = hf_config.get_text_config().num_nextn_predict_layers
hf_config.update(
{"n_predict": n_predict, "architectures": ["Glm5NextMTPModel"]}
)
+22 -5
View File
@@ -158,17 +158,20 @@ def getattr_iter(
return default_factory() if default_factory is not None else default
def get_attr_docs(cls: type[Any]) -> dict[str, str]:
def _get_own_attr_docs(cls: type[Any], out: dict[str, str]) -> None:
"""Get any docstrings placed after attribute assignments in a class body.
https://davidism.com/mit-license/
"""
cls_node = ast.parse(textwrap.dedent(inspect.getsource(cls))).body[0]
try:
source = inspect.getsource(cls)
except (OSError, TypeError):
# ``object`` and classes without retrievable source (e.g. builtins).
return
cls_node = ast.parse(textwrap.dedent(source)).body[0]
if not isinstance(cls_node, ast.ClassDef):
raise TypeError("Given object was not a class.")
out = {}
return
# Consider each pair of nodes.
for a, b in pairwise(cls_node.body):
@@ -194,6 +197,20 @@ def get_attr_docs(cls: type[Any]) -> dict[str, str]:
out[target.id] = doc
def get_attr_docs(cls: type[Any]) -> dict[str, str]:
"""Get any docstrings placed after attribute assignments in a class body or
its bases."""
if not isinstance(cls, type):
raise TypeError("Given object was not a class.")
out: dict[str, str] = {}
# Walk the MRO from the most-base class to ``cls`` so that a docstring
# redefined on a subclass overrides the one inherited from a base class.
for base in reversed(cls.__mro__):
_get_own_attr_docs(base, out)
return out
+68 -29
View File
@@ -1272,9 +1272,15 @@ class VllmConfig:
return
if not self.use_v2_model_runner:
raise ValueError("sampling distribution replay requires Model Runner V2")
if self.speculative_config is not None:
speculative_config = self.speculative_config
if (
speculative_config is not None
and speculative_config.enable_adaptive_verification
):
raise ValueError(
"sampling distribution replay does not support speculative decoding"
"sampling distribution replay with speculative decoding "
"requires fixed verification boundaries; disable adaptive "
"verification"
)
if model_config.is_diffusion:
raise ValueError(
@@ -1351,13 +1357,6 @@ class VllmConfig:
"share of output tokens supplied by accepted drafts.",
scope="global",
)
if watermark_config.deduplicate_contexts != "none":
logger.warning_once(
"Context deduplication is not supported with speculative "
"decoding and will not be applied to accepted drafts, "
"rejection-recovery tokens, or bonus tokens.",
scope="global",
)
if watermark_config.algorithm == "dual_key_gumbel" and (
watermark_config.alpha != get_field(WatermarkConfig, "alpha").default
):
@@ -1377,8 +1376,6 @@ class VllmConfig:
def _resolve_and_verify_engram_config(self) -> None:
"""Resolve defaults and validate n-gram embedding settings."""
from vllm.platforms import current_platform
model_config = self.model_config
speculative_config = self.speculative_config
# Draft configs inherit the target's communication groups and settings.
@@ -1399,9 +1396,7 @@ class VllmConfig:
"Disable --enable-dbo and set --ubatch-size to 0."
)
if self.engram_config is None:
if not current_platform.is_cuda_alike() or not model_has_engram_layers(
model_config
):
if not model_has_engram_layers(model_config):
return
self.engram_config = EngramConfig()
self.engram_config.verify_model_config(model_config)
@@ -1833,6 +1828,14 @@ class VllmConfig:
raise ValueError(
"HiSparse does not support decode context parallelism."
)
if not self.scheduler_config.scheduler_reserve_full_isl:
# Without it, async loads admitted against free host blocks can
# each wait on host pages the others hold, and waiting requests
# are never preempted to free them.
raise ValueError(
"HiSparse requires --scheduler-reserve-full-isl; remove "
"--no-scheduler-reserve-full-isl."
)
if self.model_config is not None and not hasattr(
self.model_config.hf_config, "index_topk"
):
@@ -2031,11 +2034,15 @@ class VllmConfig:
# 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
):
scheduler_name = (
"DiffusionAsyncScheduler"
if self.scheduler_config.async_scheduling
else "DiffusionScheduler"
)
self.scheduler_config.scheduler_cls = (
"vllm.v1.core.sched.diffusion_scheduler.DiffusionAsyncScheduler"
f"vllm.v1.core.sched.diffusion_scheduler.{scheduler_name}"
)
self._normalize_piecewise_cudagraph_mode(
@@ -3091,9 +3098,6 @@ class VllmConfig:
if self.parallel_config.use_ubatching:
unsupported.extend(self._get_dbo_unsupported_features())
if self.cache_config.mamba_cache_mode == "all":
unsupported.append("mamba cache mode 'all'")
return unsupported
def _get_v1_model_runner_unsupported_features(self) -> list[str]:
@@ -3464,7 +3468,25 @@ class VllmConfig:
if not self.cache_config.use_replayssm:
self.cache_config.use_recoverssm = False
return self
self.cache_config.use_recoverssm = self.num_speculative_tokens > 0
kda_architectures = (
"KimiLinearForCausalLM",
"KimiK3ForConditionalGeneration",
)
is_kda_model = (
self.model_config is not None
and self.model_config.architecture in kda_architectures
)
is_qwen4exp_recoverssm_model = (
self.model_config is not None
and self.model_config.architecture in _QWEN4EXP_RECOVERSSM_ARCHS
)
self.cache_config.use_recoverssm = (
self.num_speculative_tokens > 0
and (is_kda_model or is_qwen4exp_recoverssm_model)
)
use_mamba_replayssm_spec = (
self.num_speculative_tokens > 0 and not self.cache_config.use_recoverssm
)
if self.model_config is not None and not self.model_config.supports_replayssm:
raise ValueError(
@@ -3482,6 +3504,13 @@ class VllmConfig:
"--use-replayssm on Qwen4Exp selects GDN RecoverSSM and requires "
"speculative decoding (num_speculative_tokens > 0)"
)
if (
self.mamba_config.backend == MambaBackendEnum.FLASHINFER
and self.cache_config.replayssm_buffer_len > 16
):
raise ValueError(
"FlashInfer ReplaySSM requires --replayssm-buffer-len <= 16"
)
if self.cache_config.use_recoverssm:
if self.model_config is not None and self.model_config.architecture not in (
"KimiLinearForCausalLM",
@@ -3497,10 +3526,6 @@ class VllmConfig:
"SSM state caches, not --enable-mamba-cache-stochastic-"
"rounding, which requires an explicit float16 cache"
)
if self.cache_config.mamba_cache_mode not in ("none", "align"):
raise ValueError(
"RecoverSSM supports only none and align Mamba cache modes"
)
if (
self.cache_config.mamba_cache_mode == "align"
and not self.use_v2_model_runner
@@ -3514,11 +3539,25 @@ class VllmConfig:
)
if self.mamba_config.backend != MambaBackendEnum.TRITON:
raise ValueError("RecoverSSM requires --mamba-backend triton")
elif self.cache_config.mamba_cache_mode == "all":
raise ValueError(
"--use-replayssm supports prefix caching only in align mode; "
"pass --mamba-cache-mode align"
)
elif use_mamba_replayssm_spec:
if self.cache_config.mamba_cache_mode != "none":
raise ValueError(
"FlashInfer ReplaySSM speculative decoding requires "
"--mamba-cache-mode none"
)
query_len = 1 + self.num_speculative_tokens
if self.cache_config.replayssm_buffer_len < query_len:
raise ValueError(
"FlashInfer ReplaySSM speculative decoding requires "
"--replayssm-buffer-len >= 1 + num_speculative_tokens "
f"({query_len}); got "
f"{self.cache_config.replayssm_buffer_len}"
)
if self.mamba_config.backend != MambaBackendEnum.FLASHINFER:
raise ValueError(
"Mamba2 ReplaySSM speculative decoding requires "
"--mamba-backend flashinfer"
)
elif self.mamba_config.backend == MambaBackendEnum.FLASHINFER:
if self.cache_config.mamba_cache_mode == "align":
raise ValueError(