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
+25
View File
@@ -345,6 +345,7 @@ def _rocm_aiter_fused_moe_impl(
shared_w1_scale: torch.Tensor | None = None,
shared_w2_scale: torch.Tensor | None = None,
shared_expert_id: int = -1,
q_dtype_a: torch.dtype | None = None,
) -> torch.Tensor:
has_shared_expert = _validate_rocm_aiter_fused_moe_shared_expert_args(
shared_w1,
@@ -378,6 +379,12 @@ def _rocm_aiter_fused_moe_impl(
shared_w2_scale=shared_w2_scale,
shared_expert_id=shared_expert_id,
)
if q_dtype_a is not None:
# DeepSeek V4.1 a4w4 override (use_mxfp4_w4a4_dsv4 in
# rocm_aiter_moe.py). rocm_aiter_ops.fused_moe_supports_quant_dtype_a()
# is checked at config time, so this is only reached on an AITER
# build new enough to accept it.
extra_kwargs["quant_dtype_a"] = q_dtype_a
return fused_moe(
hidden_states,
@@ -435,6 +442,7 @@ def _rocm_aiter_fused_moe_fake(
shared_w1_scale: torch.Tensor | None = None,
shared_w2_scale: torch.Tensor | None = None,
shared_expert_id: int = -1,
q_dtype_a: torch.dtype | None = None,
) -> torch.Tensor:
if output_dtype is not None:
return torch.empty_like(hidden_states, dtype=output_dtype)
@@ -2485,6 +2493,21 @@ class rocm_aiter_ops:
return "gate_mode" in inspect.signature(fused_moe).parameters
@classmethod
@if_aiter_supported
@functools.cache
def fused_moe_supports_quant_dtype_a(cls) -> bool:
"""Probe whether the installed aiter.fused_moe accepts `quant_dtype_a`.
Added in https://github.com/ROCm/aiter/pull/5439 (unreleased at
merge time). Older AITER can't override the activation quant dtype.
"""
import inspect
from aiter.fused_moe import fused_moe
return "quant_dtype_a" in inspect.signature(fused_moe).parameters
@staticmethod
def _probe_dsv4_i384_fhmoe_capability(num_tokens: int) -> bool:
"""Probe AITER's CSV-backed DSV4 native-I384 FHMoE contract."""
@@ -3005,6 +3028,7 @@ class rocm_aiter_ops:
shared_w1_scale: torch.Tensor | None = None,
shared_w2_scale: torch.Tensor | None = None,
shared_expert_id: int = -1,
q_dtype_a: torch.dtype | None = None,
) -> torch.Tensor:
return torch.ops.vllm.rocm_aiter_fused_moe(
hidden_states,
@@ -3036,6 +3060,7 @@ class rocm_aiter_ops:
shared_w1_scale,
shared_w2_scale,
shared_expert_id,
q_dtype_a,
)
@staticmethod
+25 -9
View File
@@ -2587,6 +2587,8 @@ def fused_minimax_m3_qknorm_rope_kv_insert(
skip_index_branch: bool = False,
q_fp8_out: torch.Tensor | None = None,
q_fp8_scale: float = 1.0,
kv_k_scale: torch.Tensor | None = None,
kv_v_scale: torch.Tensor | None = None,
) -> None:
"""Fused MiniMax-M3 attention pre-processing (in-place).
@@ -2610,7 +2612,14 @@ def fused_minimax_m3_qknorm_rope_kv_insert(
attention's flat TMA descriptor.
If ``q_fp8_out`` is given, the same normalized q is also written in FP8
E4M3 using ``q_fp8_scale`` as its dequantization scale.
E4M3 using ``q_fp8_scale`` as its dequantization scale. Without ``q_out``,
q is then written only in FP8 and the q slice of ``qkv`` is left as is.
``kv_cache_dtype="nvfp4"`` quantizes k/v into the packed HND
``[num_blocks, 2 * num_kv_heads, block_size, 72]`` uint8 cache using the
device dequantization scales ``kv_k_scale``/``kv_v_scale``. Slot
``2 * head + side`` (K = 0, V = 1) holds that head's E2M1 data followed by
its E4M3 block scales, so every head is one contiguous run of the page.
When ``skip_index_branch`` is true, sparse rows still keep their packed
``[index_q | index_k]`` tail, but the kernel only processes the main q/k/v
@@ -2641,6 +2650,8 @@ def fused_minimax_m3_qknorm_rope_kv_insert(
skip_index_branch,
q_fp8_out,
q_fp8_scale,
kv_k_scale,
kv_v_scale,
)
@@ -3666,7 +3677,7 @@ def causal_conv1d_fwd_cpu(
cache_indices: torch.Tensor | None,
has_initial_state: torch.Tensor | None,
silu_activation: bool,
is_vnni: bool,
is_weight_packed: bool,
) -> torch.Tensor:
return torch.ops._C.causal_conv1d_fwd_cpu(
x,
@@ -3678,7 +3689,7 @@ def causal_conv1d_fwd_cpu(
has_initial_state,
silu_activation,
-1,
is_vnni,
is_weight_packed,
)
@@ -3689,7 +3700,7 @@ def causal_conv1d_update_cpu(
bias: torch.Tensor | None,
silu_activation: bool,
conv_state_indices: torch.Tensor | None,
is_vnni: bool,
is_weight_packed: bool,
num_accepted_tokens: torch.Tensor | None = None,
) -> torch.Tensor:
return torch.ops._C.causal_conv1d_update_cpu(
@@ -3701,7 +3712,7 @@ def causal_conv1d_update_cpu(
num_accepted_tokens,
conv_state_indices,
-1,
is_vnni,
is_weight_packed,
)
@@ -4434,18 +4445,23 @@ def cpu_gemm_wna16(
pack_factor: int,
isa_hint: str,
) -> torch.Tensor:
output = torch.empty((input.size(0), scales.size(1)), dtype=input.dtype)
# Match int4_scaled_mm_cpu: flatten >2-D activations to [M, K] for the
# C++ kernel, then restore the original leading dims on the output.
x_shape = input.shape
x_2d = input.reshape(-1, x_shape[-1]) if len(x_shape) > 2 else input
out = torch.empty((x_2d.size(0), scales.size(1)), dtype=input.dtype)
torch.ops._C.cpu_gemm_wna16(
input,
x_2d,
q_weight,
output,
out,
scales,
zeros,
bias,
pack_factor,
isa_hint,
)
return output
out = out.reshape(x_shape[:-1] + (out.size(-1),)) if len(x_shape) > 2 else out
return out
def cpu_activation_lut_bf16(input: torch.Tensor, activation: str) -> torch.Tensor:
+66
View File
@@ -135,6 +135,46 @@ def _fused_add_gemma_rms_norm_impl(
torch.ops._C.fused_add_gemma_rms_norm(input, residual, weight, epsilon)
def _layer_norm_impl(
out: torch.Tensor,
input: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
epsilon: float,
) -> None:
torch.ops._C.layer_norm(out, input, weight, bias, epsilon)
def _fused_add_layer_norm_impl(
input: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
epsilon: float,
) -> None:
torch.ops._C.fused_add_layer_norm(input, residual, weight, bias, epsilon)
def _nemotron_layer_norm_impl(
out: torch.Tensor,
input: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
epsilon: float,
) -> None:
torch.ops._C.nemotron_layer_norm(out, input, weight, bias, epsilon)
def _fused_add_nemotron_layer_norm_impl(
input: torch.Tensor,
residual: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
epsilon: float,
) -> None:
torch.ops._C.fused_add_nemotron_layer_norm(input, residual, weight, bias, epsilon)
def _gdn_attention_core_xpu_impl(
core_attn_out: torch.Tensor,
z: torch.Tensor,
@@ -1268,6 +1308,32 @@ class xpu_ops:
mutates_args=["input", "residual"],
)
if hasattr(torch.ops._C, "layer_norm"):
direct_register_custom_op(
op_name="xpu_layer_norm",
op_func=_layer_norm_impl,
mutates_args=["out"],
)
direct_register_custom_op(
op_name="xpu_fused_add_layer_norm",
op_func=_fused_add_layer_norm_impl,
mutates_args=["input", "residual"],
)
if hasattr(torch.ops._C, "nemotron_layer_norm"):
direct_register_custom_op(
op_name="xpu_nemotron_layer_norm",
op_func=_nemotron_layer_norm_impl,
mutates_args=["out"],
)
direct_register_custom_op(
op_name="xpu_fused_add_nemotron_layer_norm",
op_func=_fused_add_nemotron_layer_norm_impl,
mutates_args=["input", "residual"],
)
direct_register_custom_op(
op_name="xpu_ops_deepseek_scaling_rope",
op_func=_xpu_ops_deepseek_scaling_rope_impl,
+12 -18
View File
@@ -25,7 +25,7 @@ from dataclasses import dataclass, replace
from functools import cache
from io import BytesIO
from pathlib import Path
from tempfile import NamedTemporaryFile
from tempfile import TemporaryDirectory
from typing import Any, cast
import numpy as np
@@ -975,32 +975,26 @@ class RandomMultiModalDataset(RandomDataset):
dtype=np.uint8,
)
# Create a temporary video file in memory
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
fps = 30 # frames per second
with NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
temp_path = temp_file.name
with TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir) / "video.mp4"
# Create video writer
video_writer = cv2.VideoWriter(
temp_path, fourcc=fourcc, fps=fps, frameSize=(width, height)
str(temp_path), fourcc=fourcc, fps=fps, frameSize=(width, height)
)
if not video_writer.isOpened():
raise RuntimeError("Failed to create video writer")
try:
if not video_writer.isOpened():
raise RuntimeError("Failed to create video writer")
for frame in random_pixels:
video_writer.write(frame)
for frame in random_pixels:
video_writer.write(frame)
finally:
video_writer.release()
video_writer.release()
temp_file.close()
# Read the video file content
with open(temp_path, "rb") as f:
video_content = f.read()
return {"bytes": video_content}
return {"bytes": temp_path.read_bytes()}
def map_config_to_modality(self, config: tuple[int, int, int]) -> str:
"""Map the configuration to the modality."""
+141 -30
View File
@@ -221,29 +221,80 @@ def run_comb(
base_path: Path,
num_runs: int,
dry_run: bool,
warmup_num_prompts: int = 0,
continue_on_error: bool = False,
):
if not _comb_is_valid(serve_comb, bench_comb, link_vars):
return None
comb_data = list[dict[str, object]]()
def run_benchmark_with_error_handling(
*,
bench_overrides: ParameterSweepItem,
run_number: int,
output_path: Path,
):
try:
return run_benchmark(
server,
bench_cmd,
serve_overrides=serve_comb,
bench_overrides=bench_overrides,
run_number=run_number,
output_path=output_path,
dry_run=dry_run,
)
except Exception as exc:
if not continue_on_error:
raise
failure_path = output_path.with_name(output_path.stem + ".failure.json")
failure_path.parent.mkdir(parents=True, exist_ok=True)
failure_path.write_text(
json.dumps(
{
"run_number": run_number,
"error_type": type(exc).__name__,
"error": str(exc),
"serve_overrides": dict(serve_comb),
"bench_overrides": dict(bench_overrides),
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print(f"[FAILED BENCHMARK] run={run_number}: {type(exc).__name__}: {exc}")
print(f"Failure details: {failure_path}")
if server is not None:
with contextlib.suppress(Exception):
server.after_bench()
return None
if warmup_num_prompts > 0:
warmup_overrides = bench_comb | {"num_prompts": warmup_num_prompts}
run_benchmark_with_error_handling(
bench_overrides=warmup_overrides,
run_number=-1,
output_path=base_path / "warmup.json",
)
for run_number in range(num_runs):
run_data = run_benchmark(
server,
bench_cmd,
serve_overrides=serve_comb,
run_data = run_benchmark_with_error_handling(
bench_overrides=bench_comb,
run_number=run_number,
output_path=_get_comb_run_path(base_path, run_number),
dry_run=dry_run,
)
if run_data is not None:
comb_data.append(run_data)
if dry_run:
return None
if not comb_data:
print("[NO SUCCESSFUL MEASURED RUNS] leaving combination retryable")
return []
with _get_comb_run_path(base_path, run_number=None).open("w") as f:
json.dump(comb_data, f, indent=4)
@@ -262,36 +313,69 @@ def run_combs(
link_vars: list[tuple[str, str]],
experiment_dir: Path,
num_runs: int,
warmup_num_prompts: int,
dry_run: bool,
continue_on_error: bool = False,
):
all_data = list[dict[str, object]]()
for serve_comb in serve_params:
with server_ctx(
serve_cmd,
after_bench_cmd,
show_stdout=show_stdout,
serve_comb=serve_comb,
bench_params=bench_params,
experiment_dir=experiment_dir,
dry_run=dry_run,
server_ready_timeout=server_ready_timeout,
) as server:
for bench_comb in bench_params:
base_path = _get_comb_base_path(experiment_dir, serve_comb, bench_comb)
try:
with server_ctx(
serve_cmd,
after_bench_cmd,
show_stdout=show_stdout,
serve_comb=serve_comb,
bench_params=bench_params,
experiment_dir=experiment_dir,
dry_run=dry_run,
server_ready_timeout=server_ready_timeout,
) as server:
for bench_comb in bench_params:
base_path = _get_comb_base_path(
experiment_dir, serve_comb, bench_comb
)
comb_data = run_comb(
server,
bench_cmd,
serve_comb=serve_comb,
bench_comb=bench_comb,
link_vars=link_vars,
base_path=base_path,
num_runs=num_runs,
dry_run=dry_run,
comb_data = run_comb(
server,
bench_cmd,
serve_comb=serve_comb,
bench_comb=bench_comb,
link_vars=link_vars,
base_path=base_path,
num_runs=num_runs,
warmup_num_prompts=warmup_num_prompts,
dry_run=dry_run,
continue_on_error=continue_on_error,
)
if comb_data is not None:
all_data.extend(comb_data)
except Exception as exc:
if not continue_on_error:
raise
failure_name = sanitize_filename(
f"SERVE-{serve_comb.name or 'default'}-failure.json"
)
failure_path = experiment_dir / failure_name
failure_path.parent.mkdir(parents=True, exist_ok=True)
failure_path.write_text(
json.dumps(
{
"error_type": type(exc).__name__,
"error": str(exc),
"serve_overrides": dict(serve_comb),
},
indent=2,
)
if comb_data is not None:
all_data.extend(comb_data)
+ "\n",
encoding="utf-8",
)
print(
"[FAILED SERVER COMBINATION] "
f"{serve_comb.name or '(default)'}: "
f"{type(exc).__name__}: {exc}"
)
print(f"Failure details: {failure_path}")
if dry_run:
return None
@@ -315,6 +399,8 @@ class SweepServeArgs:
output_dir: Path
experiment_name: str
num_runs: int
warmup_num_prompts: int
continue_on_error: bool
dry_run: bool
resume: bool
@@ -351,6 +437,9 @@ class SweepServeArgs:
num_runs = args.num_runs
if num_runs < 1:
raise ValueError("`num_runs` should be at least 1.")
warmup_num_prompts = args.warmup_num_prompts
if warmup_num_prompts < 0:
raise ValueError("`warmup_num_prompts` should be at least 0.")
return cls(
serve_cmd=serve_cmd,
@@ -363,6 +452,8 @@ class SweepServeArgs:
output_dir=Path(args.output_dir),
experiment_name=experiment_name,
num_runs=num_runs,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=args.continue_on_error,
dry_run=args.dry_run,
resume=args.resume,
server_ready_timeout=args.server_ready_timeout,
@@ -453,6 +544,24 @@ class SweepServeArgs:
default=3,
help="Number of runs per parameter combination.",
)
parser.add_argument(
"--warmup-num-prompts",
type=int,
default=0,
help=(
"Number of prompts in one unmeasured warmup run before each "
"parameter combination. The warmup is saved as warmup.json but "
"excluded from summary statistics."
),
)
parser.add_argument(
"--continue-on-error",
action="store_true",
help=(
"Record and skip a failed warmup or benchmark run instead of "
"terminating the entire sweep."
),
)
parser.add_argument(
"--dry-run",
action="store_true",
@@ -523,7 +632,9 @@ def run_main(args: SweepServeArgs):
bench_params=args.bench_params,
experiment_dir=experiment_dir,
num_runs=args.num_runs,
warmup_num_prompts=args.warmup_num_prompts,
dry_run=args.dry_run,
continue_on_error=args.continue_on_error,
)
+26 -4
View File
@@ -63,6 +63,8 @@ def run_comb_workload(
experiment_dir: Path,
num_runs: int,
dry_run: bool,
warmup_num_prompts: int,
continue_on_error: bool,
workload_var: WorkloadVariable,
workload_value: int,
) -> list[dict[str, object]] | None:
@@ -82,6 +84,8 @@ def run_comb_workload(
),
num_runs=num_runs,
dry_run=dry_run,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=continue_on_error,
)
@@ -97,6 +101,8 @@ def explore_comb_workloads(
experiment_dir: Path,
num_runs: int,
dry_run: bool,
warmup_num_prompts: int,
continue_on_error: bool,
):
print("[WL START]")
print(f"Serve parameters: {serve_comb.as_text() or '(None)'}")
@@ -129,6 +135,8 @@ def explore_comb_workloads(
experiment_dir=experiment_dir,
num_runs=num_runs,
dry_run=dry_run,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=continue_on_error,
workload_var=workload_var,
workload_value=1,
)
@@ -141,16 +149,22 @@ def explore_comb_workloads(
experiment_dir=experiment_dir,
num_runs=num_runs,
dry_run=dry_run,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=continue_on_error,
workload_var=workload_var,
workload_value=dataset_size,
)
if serial_workload_data is None or batch_workload_data is None:
if not serial_workload_data or not batch_workload_data:
if dry_run:
print("Omitting intermediate Workload iterations.")
print("[WL END]")
return
else:
print(
"Unable to establish both Workload Explorer endpoints; "
"skipping intermediate workload levels."
)
print("[WL END]")
return []
serial_workload_value = math.ceil(
_estimate_workload_avg(serial_workload_data, workload_var)
@@ -181,6 +195,8 @@ def explore_comb_workloads(
experiment_dir=experiment_dir,
num_runs=num_runs,
dry_run=dry_run,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=continue_on_error,
workload_var=workload_var,
workload_value=inter_workload_value,
)
@@ -207,6 +223,8 @@ def explore_combs_workloads(
experiment_dir: Path,
num_runs: int,
dry_run: bool,
warmup_num_prompts: int,
continue_on_error: bool,
):
if any(bench_comb.has_param(workload_var) for bench_comb in bench_params):
raise ValueError(
@@ -238,6 +256,8 @@ def explore_combs_workloads(
experiment_dir=experiment_dir,
num_runs=num_runs,
dry_run=dry_run,
warmup_num_prompts=warmup_num_prompts,
continue_on_error=continue_on_error,
)
if comb_data is not None:
@@ -315,6 +335,8 @@ def run_main(args: SweepServeWorkloadArgs):
experiment_dir=experiment_dir,
num_runs=args.num_runs,
dry_run=args.dry_run,
warmup_num_prompts=args.warmup_num_prompts,
continue_on_error=args.continue_on_error,
)
+25 -12
View File
@@ -142,6 +142,10 @@ class CompilerManager:
self.compilation_config = compilation_config
self.compiler = make_compiler(compilation_config)
self.loaded_artifacts: dict[str, Any] = {}
self.prefix: str = ""
def _log_prefix(self) -> str:
return f"[{self.prefix}] " if self.prefix else ""
def compute_hash(self, vllm_config: VllmConfig) -> str:
return self.compiler.compute_hash(vllm_config)
@@ -179,6 +183,7 @@ class CompilerManager:
self.disable_cache = disable_cache
self.cache_dir = cache_dir
self.cache_file_path = os.path.join(cache_dir, "vllm_compile_cache.py")
self.prefix = prefix
if not disable_cache and os.path.exists(self.cache_file_path):
# load the cache from the file
@@ -287,9 +292,10 @@ class CompilerManager:
# after loading the last graph for this shape, record the time.
# there can be multiple graphs due to piecewise compilation.
elapsed = time.perf_counter() - compilation_start_time
logger.info_once(
"Directly load the compiled graph(s) for compile range %s "
"from the cache, took %.3f s",
logger.info(
"%sDirectly load the compiled graph(s) for compile "
"range %s from the cache, took %.3f s",
self._log_prefix(),
str(compile_range),
elapsed,
)
@@ -373,8 +379,9 @@ class CompilerManager:
self.is_cache_updated = True
if graph_index == 0:
# adds some info logging for the first graph
logger.info_once(
"Cache the graph of compile range %s for later use",
logger.info(
"%sCache the graph of compile range %s for later use",
self._log_prefix(),
str(compile_range),
)
logger.debug_once(
@@ -388,8 +395,9 @@ class CompilerManager:
# after compiling the last graph, record the end time
if graph_index == num_graphs - 1:
elapsed = time.perf_counter() - compilation_start_time
logger.info_once(
"Compiling a graph for compile range %s takes %.2f s",
logger.info(
"%sCompiling a graph for compile range %s takes %.2f s",
self._log_prefix(),
str(compile_range),
elapsed,
)
@@ -865,6 +873,9 @@ class VllmBackend:
# `torch.compile` is JIT compiled, so we don't need to
# do anything here
def _log_prefix(self) -> str:
return f"[{self.prefix}] " if self.prefix else ""
def collect_standalone_compile_artifacts(
self,
) -> tuple[Any, dict[str, list[int]] | None, dict[str, bool] | None]:
@@ -1085,10 +1096,11 @@ class VllmBackend:
disable_cache = disable_cache or is_ngram_gpu_enabled
if disable_cache:
logger.info_once("vLLM's torch.compile cache is disabled.")
logger.info("%svLLM's torch.compile cache is disabled.", self._log_prefix())
else:
logger.info_once(
"Using cache directory: %s for vLLM's torch.compile",
logger.info(
"%sUsing cache directory: %s for vLLM's torch.compile",
self._log_prefix(),
local_cache_dir,
)
@@ -1148,8 +1160,9 @@ class VllmBackend:
current_perf = time.perf_counter()
current_epoch = time.time()
dynamo_time = current_perf - torch_compile_start_time
logger.info_once(
"Dynamo bytecode transform time: %.2f s",
logger.info(
"%sDynamo bytecode transform time: %.2f s",
self._log_prefix(),
dynamo_time,
)
+1 -1
View File
@@ -418,7 +418,7 @@ class InductorStandaloneAdaptor(CompilerInterface):
assert isinstance(handle, tuple)
assert isinstance(handle[0], str)
assert isinstance(handle[1], str)
path = handle[1]
path = os.path.join(self.cache_dir, handle[0])
inductor_compiled_graph = torch._inductor.CompiledArtifact.load(
path=path, format=self.save_format
)
+38 -10
View File
@@ -292,7 +292,12 @@ def _try_load_aot_compiled_fn(
Re-raises on failure when ``VLLM_FORCE_AOT_LOAD`` is set.
"""
try:
with monitor_torch_compile(model.vllm_config, is_encoder=model._is_encoder):
with monitor_torch_compile(
model.vllm_config,
is_encoder=model._is_encoder,
tag=getattr(model, "_compile_tag", ""),
announce_start=False,
):
with (
set_current_vllm_config(model.vllm_config),
open(aot_compilation_path, "rb") as f,
@@ -309,8 +314,12 @@ def _try_load_aot_compiled_fn(
with maybe_use_cudagraph_partition_wrapper(model.vllm_config):
loaded_fn._artifacts.compiled_fn.finalize_loading(model.vllm_config)
compilation_counter.num_aot_artifacts_loaded += 1
tag = getattr(model, "_compile_tag", "")
log_prefix = f"[{tag}] " if tag else ""
logger.info(
"Directly load AOT compilation from path %s", aot_compilation_path
"%sDirectly load AOT compilation from path %s",
log_prefix,
aot_compilation_path,
)
return loaded_fn
except Exception as e:
@@ -319,8 +328,11 @@ def _try_load_aot_compiled_fn(
message = "Compile cache file corrupted."
else:
message = str(e)
tag = getattr(model, "_compile_tag", "")
log_prefix = f"[{tag}] " if tag else ""
logger.warning(
"Compiling model again due to a load failure from %s, reason: %s",
"%sCompiling model again due to a load failure from %s, reason: %s",
log_prefix,
aot_compilation_path,
message,
)
@@ -402,6 +414,16 @@ def _support_torch_compile(
compilation_counter.num_models_seen += 1
self.compiled = False
# Capture the active model tag (e.g. "backbone", "eagle_head") so
# later compilation/warmup log lines can identify which component
# they belong to. Mirror VllmBackend's precedence rule
# (`compile_prefix or model_tag`) so log tags line up with the
# cache-dir tag: encoders use the class name, everything else
# falls through to `model_tag`.
from vllm.compilation.backends import model_tag as _current_model_tag
self._compile_tag = (cls.__name__ if is_encoder else "") or _current_model_tag
# Handled by monkeypatching `TorchCompileWithNoGuardsWrapper` into base class
TorchCompileWithNoGuardsWrapper.__init__(
self,
@@ -567,7 +589,7 @@ def _support_torch_compile(
self.aot_compiled_fn = loaded_fn
self.was_aot_compile_fn_loaded_from_disk = True
with (
monitor_profiling_run(),
monitor_profiling_run(tag=self._compile_tag),
maybe_use_cudagraph_partition_wrapper(self.vllm_config),
):
output = self.aot_compiled_fn(self, *args, **kwargs)
@@ -667,7 +689,9 @@ def _support_torch_compile(
self._aot_compilation_path = aot_compilation_path
self._aot_cache_dir = cache_dir
with monitor_torch_compile(
self.vllm_config, is_encoder=self._is_encoder
self.vllm_config,
is_encoder=self._is_encoder,
tag=self._compile_tag,
):
self.aot_compiled_fn = self.aot_compile(*args, **kwargs)
compilation_counter.num_aot_compiles += 1
@@ -675,14 +699,15 @@ def _support_torch_compile(
# AOT artifact.
self.save_aot_compiled_function()
with monitor_profiling_run():
with monitor_profiling_run(tag=self._compile_tag):
output = self.aot_compiled_fn(self, *args, **kwargs)
else:
with monitor_torch_compile(
self.vllm_config,
"torch.compile and initial profiling/warmup "
"%storch.compile and initial profiling/warmup "
"run together took %.2f s in total",
is_encoder=self._is_encoder,
tag=self._compile_tag,
):
output = TorchCompileWithNoGuardsWrapper.__call__(
self, # type: ignore[arg-type]
@@ -706,6 +731,7 @@ def _support_torch_compile(
self.aot_compiled_fn and self._aot_compilation_path and self._aot_cache_dir
)
log_prefix = f"[{self._compile_tag}] " if self._compile_tag else ""
try:
os.makedirs(self._aot_cache_dir, exist_ok=True)
# File saving should be atomic, so we will save to a temporary location
@@ -714,13 +740,15 @@ def _support_torch_compile(
self.aot_compiled_fn.save_compiled_function(tmp_file)
os.replace(tmp_file, self._aot_compilation_path)
compilation_counter.num_aot_artifacts_saved += 1
logger.info_once(
"saved AOT compiled function to %s",
logger.info(
"%ssaved AOT compiled function to %s",
log_prefix,
self._aot_compilation_path,
)
except Exception as e:
logger.warning(
"unable to save AOT compiled function to %s: %s",
"%sunable to save AOT compiled function to %s: %s",
log_prefix,
self._aot_compilation_path,
e,
)
+16 -5
View File
@@ -17,18 +17,27 @@ torch_compile_start_time: float = 0.0
@contextlib.contextmanager
def monitor_torch_compile(
vllm_config: VllmConfig,
message: str = "torch.compile took %.2f s in total",
message: str = "%storch.compile took %.2f s in total",
is_encoder: bool = False,
tag: str = "",
announce_start: bool = True,
) -> Generator[None, None, None]:
"""Context manager that times torch.compile and manages depyf debugging.
On normal exit: logs the compile time and exits depyf.
On exception: cleans up depyf without logging (compilation failed).
``announce_start=False`` suppresses the "Starting torch.compile" line;
used by the AOT-load probe so a failed load attempt doesn't announce a
compile it didn't perform.
"""
global torch_compile_start_time
torch_compile_start_time = time.perf_counter()
compilation_config = vllm_config.compilation_config
log_prefix = f"[{tag}] " if tag else ""
if announce_start and compilation_config.mode == CompilationMode.VLLM_COMPILE:
logger.info("%sStarting torch.compile", log_prefix)
depyf_cm = None
path = vllm_config.compile_debug_dump_path()
if compilation_config.mode == CompilationMode.VLLM_COMPILE and path:
@@ -50,7 +59,7 @@ def monitor_torch_compile(
compilation_config.encoder_compilation_time += total_compile_time
else:
compilation_config.compilation_time += total_compile_time
logger.info_once(message, total_compile_time)
logger.info(message, log_prefix, total_compile_time)
finally:
if depyf_cm is not None:
try:
@@ -60,7 +69,7 @@ def monitor_torch_compile(
@contextlib.contextmanager
def monitor_profiling_run() -> Generator[None, None, None]:
def monitor_profiling_run(tag: str = "") -> Generator[None, None, None]:
"""Context manager that times the initial profiling run.
Asserts that no backend compilation occurs during the profiling run
@@ -78,8 +87,10 @@ def monitor_profiling_run() -> Generator[None, None, None]:
"backend compilation occurred during the initial profiling run; "
"all compilation should be complete before the profiling run starts."
)
logger.info_once(
"Initial profiling/warmup run took %.2f s",
log_prefix = f"[{tag}] " if tag else ""
logger.info(
"%sInitial profiling/warmup run took %.2f s",
log_prefix,
elapsed,
)
+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(
+6 -1
View File
@@ -148,6 +148,11 @@ def mma_mxfp8(
loc=None,
ip=None,
) -> None:
# CuTe DSL 4.8 renamed the block-scale enum and keyword.
if hasattr(nvvm, "Tcgen05MMABlockScale"):
scale_kwargs = {"block_scale": nvvm.Tcgen05MMABlockScale.DEFAULT}
else:
scale_kwargs = {"scale_vec_size": nvvm.Tcgen05MMAScaleVecSize.X1}
with cute.arch.elect_one():
nvvm.tcgen05_mma_block_scale(
nvvm.Tcgen05MMAKind.MXF8F6F4,
@@ -159,9 +164,9 @@ def mma_mxfp8(
Boolean(enable_input_d).ir_value(loc=loc, ip=ip),
_make_tmem_llvm_ptr(sfa_tmem, loc=loc, ip=ip),
_make_tmem_llvm_ptr(sfb_tmem, loc=loc, ip=ip),
scale_vec_size=nvvm.Tcgen05MMAScaleVecSize.X1,
loc=loc,
ip=ip,
**scale_kwargs,
)
+3
View File
@@ -13,6 +13,9 @@ from vllm.platforms import current_platform
# py_handle has type list[int] on ROCm and int otherwise
HandleType: TypeAlias = tuple[int, int, int, list[int] | int]
# Selective wake may defer only these; any wake restores every other tag.
DEFERRABLE_TAGS: tuple[str, ...] = ("weights", "kv_cache")
@dataclasses.dataclass
class AllocationData:
+20 -13
View File
@@ -16,7 +16,7 @@ from typing import Any
import torch
from vllm.device_allocator import AllocationData, HandleType
from vllm.device_allocator import DEFERRABLE_TAGS, AllocationData, HandleType
from vllm.device_allocator.alloc_conf import (
EXPANDABLE_SEGMENTS,
conf_flag_enabled,
@@ -139,7 +139,7 @@ class CuMemAllocator:
def __init__(self):
self.pointer_to_data: dict[int, AllocationData] = {}
self.current_tag: str = CuMemAllocator.default_tag
self.allocator_and_pools: dict[str, Any] = {}
self.allocator_and_pools: dict[str, list[Any]] = {}
# Creating strong references to the two callbacks here to prevent
# these ephemeral bound-method objects being garbage collected.
# See discussions in https://github.com/vllm-project/vllm/pull/22724
@@ -167,7 +167,7 @@ class CuMemAllocator:
if not self.allocator_and_pools:
return
pool_entries = list(self.allocator_and_pools.values())
pool_entries = [e for es in self.allocator_and_pools.values() for e in es]
self.allocator_and_pools.clear()
mem_pools = [entry[0] for entry in pool_entries]
@@ -334,9 +334,9 @@ class CuMemAllocator:
memory, and the rest of the data will have empty memory.
Args:
tags: The tags of the memory allocation that will be loaded
back to GPU memory. If None, all memory allocation will be loaded
back to GPU memory.
tags: The deferrable tags (weights, kv_cache) to load back to GPU
memory; every other tag is always loaded back. If None, all
memory allocation will be loaded back to GPU memory.
"""
gc.collect()
@@ -345,7 +345,7 @@ class CuMemAllocator:
for ptr, data in self.pointer_to_data.items():
if not data.is_asleep:
continue
if tags is None or data.tag in tags:
if tags is None or data.tag in tags or data.tag not in DEFERRABLE_TAGS:
handle = data.handle
create_and_map(handle)
data.is_asleep = False
@@ -392,6 +392,10 @@ class CuMemAllocator:
old_tag = self.current_tag
self.current_tag = tag
try:
if tag != old_tag:
# Older pools of this tag are never reused, so trim them.
for pool, _ in self.allocator_and_pools.get(tag, []):
self._trim(pool)
with use_memory_pool_with_allocator(
self.python_malloc_callback, self.python_free_callback
) as data:
@@ -400,7 +404,7 @@ class CuMemAllocator:
# and the memory pool.
# to avoid the issue, we keep a reference of the data.
# see https://github.com/pytorch/pytorch/issues/146431 .
self.allocator_and_pools[tag] = data
self.allocator_and_pools.setdefault(tag, []).append(data)
yield
# PyTorch's bug, calling torch.cuda.empty_cache() will error
# when using pluggable allocator, see
@@ -413,16 +417,19 @@ class CuMemAllocator:
# TODO: we should expose `empty_cache` method in the memory
# pool.
# TODO: ask for help from PyTorch team to expose this method.
allocations = data[0].snapshot()
for allocation in allocations:
if allocation["allocated_size"] == 0:
handle = self._python_free_callback(allocation["address"])
unmap_and_release(handle)
self._trim(data[0])
finally:
self.current_tag = old_tag
if expandable_was_enabled:
set_alloc_conf(prev_conf)
def _trim(self, pool: Any) -> None:
"""Release free segments of a pool that is never allocated from again."""
for allocation in pool.snapshot():
data = self.pointer_to_data.get(allocation["address"])
if allocation["allocated_size"] == 0 and data and not data.is_asleep:
unmap_and_release(self._python_free_callback(allocation["address"]))
def get_current_usage(self) -> int:
"""Get the total number of bytes allocated in the memory pool."""
sum_bytes: int = 0
+10 -5
View File
@@ -9,7 +9,7 @@ from typing import Any
import torch
from vllm.device_allocator import AllocationData, HandleType
from vllm.device_allocator import DEFERRABLE_TAGS, AllocationData, HandleType
from vllm.logger import init_logger
from vllm.utils.torch_utils import PIN_MEMORY
@@ -145,7 +145,7 @@ class XpuMemAllocator:
def __init__(self):
self.pointer_to_data: dict[int, AllocationData] = {}
self.current_tag: str = XpuMemAllocator.default_tag
self.allocator_and_pools: dict[str, Any] = {}
self.allocator_and_pools: dict[str, list[Any]] = {}
self.python_malloc_callback = self._python_malloc_callback
self.python_free_callback = self._python_free_callback
@@ -267,7 +267,11 @@ class XpuMemAllocator:
for ptr, data in self.pointer_to_data.items():
if not data.is_asleep:
continue
if tags is not None and data.tag not in tags:
if (
tags is not None
and data.tag not in tags
and data.tag in DEFERRABLE_TAGS
):
continue
create_and_allocate(data.handle)
data.is_asleep = False
@@ -300,7 +304,7 @@ class XpuMemAllocator:
# MemPool teardown may invoke allocator virtual methods (e.g. raw_delete)
# when releasing cached blocks. If allocator wrappers are dropped first,
# C++ can hit "pure virtual method called" during shutdown.
pool_entries = list(self.allocator_and_pools.values())
pool_entries = [e for es in self.allocator_and_pools.values() for e in es]
self.allocator_and_pools.clear()
mem_pools = [entry[0] for entry in pool_entries]
@@ -333,7 +337,8 @@ class XpuMemAllocator:
self.python_malloc_callback,
self.python_free_callback,
) as data:
self.allocator_and_pools[tag] = data
# Keep every entry's pool alive (pytorch/pytorch#146431).
self.allocator_and_pools.setdefault(tag, []).append(data)
yield
finally:
self.current_tag = old_tag
@@ -1065,7 +1065,9 @@ class DeepEPV2All2AllManager(All2AllManagerBase):
if os.environ.get("EP_DISABLE_GIN", "0") != "0":
return
gin_type = query_nccl_gin_type(group)
gin_type = query_nccl_gin_type(
group, railed=envs.VLLM_DEEPEP_V2_ALLOW_HYBRID_MODE
)
if gin_type is None:
raise RuntimeError(
"DeepEPv2 communicator properties query failed; "
@@ -68,8 +68,11 @@ class CudaCommunicator(DeviceCommunicatorBase):
envs.VLLM_ALLREDUCE_USE_FLASHINFER_PCIE_IPC
and not envs.VLLM_BATCH_INVARIANT
)
use_aiter_allreduce = use_custom_allreduce and bool(
rocm_aiter_ops.is_custom_all_reduce_enabled()
# Neither AITER nor QuickReduce all-reduce has a fixed reduction order.
use_aiter_allreduce = (
use_custom_allreduce
and not envs.VLLM_BATCH_INVARIANT
and bool(rocm_aiter_ops.is_custom_all_reduce_enabled())
)
self.use_custom_allreduce = use_custom_allreduce
@@ -166,7 +169,12 @@ class CudaCommunicator(DeviceCommunicatorBase):
else:
self.use_aiter_ag_rs = True
if use_custom_allreduce and self.world_size > 1 and current_platform.is_rocm():
if (
use_custom_allreduce
and self.world_size > 1
and current_platform.is_rocm()
and not envs.VLLM_BATCH_INVARIANT
):
# Initialize a custom quick all-reduce implementation for AMD.
# Quick reduce is designed as a complement to custom allreduce
# (vLLM's or AITER's), so it is initialized for either backend.
@@ -119,6 +119,7 @@ from vllm.distributed.utils import is_weak_contiguous # noqa: E402
class CustomAllreduce:
_SUPPORTED_WORLD_SIZES = [2, 4, 6, 8, 16]
batch_invariant = False
_DEFAULT_ALL_GATHER_MAX_SIZE = 2 * 1024 * 1024
_DEFAULT_MNNVL_ALL_GATHER_MAX_SIZES = {
2: 8 * 1024 * 1024,
@@ -179,6 +180,7 @@ class CustomAllreduce:
self.mnnvl_multimem_rs_local_ptr = 0
self.mnnvl_multimem_rs_multicast_ptr = 0
self.mnnvl_only = False
self.batch_invariant = envs.VLLM_BATCH_INVARIANT
if not custom_ar:
# disable because of missing custom allreduce library
@@ -504,7 +506,7 @@ class CustomAllreduce:
# for 4 or more non NVLink-capable GPUs, custom allreduce provides
# little performance improvement over NCCL.
if self.world_size == 2 or self.fully_connected:
return inp_size < self.max_size
return self.batch_invariant or inp_size < self.max_size
return False
def all_reduce(
@@ -518,13 +520,27 @@ class CustomAllreduce:
"""
if out is None:
out = torch.empty_like(inp)
chunk_numel = self.max_size // inp.element_size()
if inp.numel() <= chunk_numel:
self._all_reduce_chunk(inp, out, registered)
return out
# Storage-order views: the gate only admits one contiguous block.
flat_inp = inp.as_strided((inp.numel(),), (1,), inp.storage_offset())
flat_out = out.as_strided((out.numel(),), (1,), out.storage_offset())
for start in range(0, flat_inp.numel(), chunk_numel):
end = start + chunk_numel
self._all_reduce_chunk(flat_inp[start:end], flat_out[start:end], registered)
return out
def _all_reduce_chunk(
self, inp: torch.Tensor, out: torch.Tensor, registered: bool
) -> None:
if registered:
ops.all_reduce(self._ptr, inp, out, 0, 0)
else:
ops.all_reduce(
self._ptr, inp, out, self.buffer_ptrs[self.rank], self.max_size
)
return out
def custom_all_reduce(self, input: torch.Tensor) -> torch.Tensor | None:
"""The main allreduce API that provides support for cuda graph."""
@@ -603,6 +619,9 @@ class CustomAllreduce:
) -> _ReduceScatterBackend | None:
if self.disabled or not current_platform.is_cuda():
return None
# The size gates below would switch backends per batch.
if self.batch_invariant:
return None
if self.world_size == 16 and not self.mnnvl_only:
return None
inp_size = inp.nbytes
@@ -1,7 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import hashlib
import hmac
import pickle
import secrets
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable
from contextlib import contextmanager, suppress
@@ -97,6 +100,9 @@ class SingleWriterShmRingBuffer:
- Reader synchronization handled by is_free_fn callback
- Writer handles garbage collection (free_buf) based on reader feedback
Shared Memory Layout:
`[32-byte handle-signing secret][ring buffer chunks...]`
Memory Layout per Buffer Chunk:
`[4-byte monotonic_id][4-byte chunk_size][actual_data...]`
^metadata_start ^data_start
@@ -119,6 +125,8 @@ class SingleWriterShmRingBuffer:
self.SIZE_NBYTES = 4
# 4 bytes for id, 4 bytes for buffer size
self.MD_SIZE = self.ID_NBYTES + self.SIZE_NBYTES
self.AUTH_SECRET_BYTES = 32
self.DATA_OFFSET = self.AUTH_SECRET_BYTES
self.monotonic_id_end = 0
self.monotonic_id_start = 0
self.data_buffer_start = 0
@@ -129,8 +137,11 @@ class SingleWriterShmRingBuffer:
# we are creating a buffer
self.metadata: dict[int, int] = {} # monotonic_id -> start address
self.shared_memory = shared_memory.SharedMemory(
create=True, size=self.data_buffer_size, name=name
create=True,
size=self.data_buffer_size + self.DATA_OFFSET,
name=name,
)
self._init_auth_secret()
else:
# we are opening an existing buffer
# fix to https://stackoverflow.com/q/62748654/9191338
@@ -146,7 +157,9 @@ class SingleWriterShmRingBuffer:
# so the shared memory block size may be larger or equal
# to the requested size. The size parameter is ignored
# when attaching to an existing block.
assert self.shared_memory.size >= self.data_buffer_size
assert (
self.shared_memory.size >= self.data_buffer_size + self.DATA_OFFSET
)
logger.debug(
"Shared memory created/opened with name: %s, size: %d",
@@ -164,11 +177,25 @@ class SingleWriterShmRingBuffer:
"""Clear the ring buffer."""
assert self.is_writer, "Only the writer can clear the buffer."
self.metadata.clear()
self.monotonic_id_end = 0
self.monotonic_id_start = 0
# Keep IDs increasing so handles issued before the clear (e.g. for
# requests still draining) fail the ID check once their chunk is
# reused, instead of resolving to a different object.
self.monotonic_id_start = self.monotonic_id_end
self.data_buffer_start = 0
self.data_buffer_end = 0
def get_auth_secret(self) -> bytes:
"""Return the current handle-signing secret."""
assert self.shared_memory.buf is not None, "Buffer has been closed"
return bytes(self.shared_memory.buf[: self.AUTH_SECRET_BYTES])
def _init_auth_secret(self) -> None:
assert self.is_writer, "Only the writer can set the auth secret."
assert self.shared_memory.buf is not None, "Buffer has been closed"
self.shared_memory.buf[: self.AUTH_SECRET_BYTES] = secrets.token_bytes(
self.AUTH_SECRET_BYTES
)
def close(self) -> None:
"""Close the shared memory."""
if hasattr(self, "shared_memory"):
@@ -219,13 +246,14 @@ class SingleWriterShmRingBuffer:
# first 4 bytes as the monotonic id
buf_idx = self.data_buffer_end % self.data_buffer_size
self.shared_memory.buf[buf_idx : buf_idx + self.ID_NBYTES] = self.int2byte(
self.monotonic_id_end
physical_idx = self.DATA_OFFSET + buf_idx
self.shared_memory.buf[physical_idx : physical_idx + self.ID_NBYTES] = (
self.int2byte(self.monotonic_id_end)
)
# next 4 bytes as the size of the data buffer
self.shared_memory.buf[buf_idx + self.ID_NBYTES : buf_idx + self.MD_SIZE] = (
self.int2byte(size)
)
self.shared_memory.buf[
physical_idx + self.ID_NBYTES : physical_idx + self.MD_SIZE
] = self.int2byte(size)
# record metadata
self.metadata[self.monotonic_id_end % self.ID_MAX] = self.data_buffer_end
@@ -240,14 +268,19 @@ class SingleWriterShmRingBuffer:
def access_buf(self, address: int):
assert self.shared_memory.buf is not None, "Buffer has been closed"
buf_idx = address % self.data_buffer_size
physical_idx = self.DATA_OFFSET + buf_idx
# read metadata
metadata_buff = self.shared_memory.buf[buf_idx : buf_idx + self.MD_SIZE]
metadata_buff = self.shared_memory.buf[
physical_idx : physical_idx + self.MD_SIZE
]
id = self.byte2int(metadata_buff[: self.ID_NBYTES])
size = self.byte2int(metadata_buff[self.ID_NBYTES : self.MD_SIZE])
# yield the data buffer and metadata
data_buff = self.shared_memory.buf[buf_idx + self.MD_SIZE : buf_idx + size]
data_buff = self.shared_memory.buf[
physical_idx + self.MD_SIZE : physical_idx + size
]
with (
memoryview(data_buff) as data_view,
):
@@ -423,7 +456,8 @@ class SingleWriterShmObjectStorage:
Architecture:
- Single writer process can put(key, value) objects
- Multiple reader processes can get(address, monotonic_id) objects
- Multiple reader processes can get(address, monotonic_id, signature, key)
objects
- Built on SingleWriterShmRingBuffer for efficient shared memory management
- Thread-safe operations with reader synchronization via locks
@@ -439,6 +473,13 @@ class SingleWriterShmObjectStorage:
- Automatic Cleanup: Garbage collection happens transparently during
allocation
Handle Signatures:
- Handles are signed with an HMAC of (key, address, monotonic_id), keyed by
a random secret stored at the start of the shared memory
- The writer signs the handles it issues and rejects stale or forged
handles supplied by requests
- Readers verify the signature in get/touch before reading shared memory
Memory Layout per Object:
`[4-byte reference_count][metadata_size][serialized_object_data]`
@@ -521,6 +562,76 @@ class SingleWriterShmObjectStorage:
else:
raise ValueError(f"Unsupported data type for serialization: {type(data)}")
def _validate_monotonic_id(
self,
address: int,
monotonic_id: int,
buf_metadata: tuple[int, int],
) -> None:
if buf_metadata[0] != monotonic_id:
raise ValueError(
f"Data for address:id '{address}:{monotonic_id}'"
" has been modified or is invalid."
)
def _verify_reader_signature(
self,
address: int,
monotonic_id: int,
signature: list[int] | None,
key: str | None,
) -> None:
if signature is None or key is None:
raise ValueError("Missing SHM handle signature for cache key.")
if (
not isinstance(signature, list)
or len(signature) != hashlib.sha256().digest_size
or any(type(byte) is not int or not 0 <= byte <= 255 for byte in signature)
or not isinstance(key, str)
):
raise ValueError("Invalid SHM handle signature for cache key.")
expected_signature = self._make_signature(key, address, monotonic_id)
if not hmac.compare_digest(bytes(signature), expected_signature):
raise ValueError("Invalid SHM handle signature for cache key.")
def verify_signature(
self,
key: str | None,
address: int,
monotonic_id: int,
signature: list[int] | None,
) -> None:
"""Verify that a handle was issued for the given key.
For writers: the handle must also be the key's current entry
For readers: only the signature is checked
Args:
key: String key the handle belongs to
address: Address of the object
monotonic_id: Monotonic ID of the object
signature: Signature issued with the handle
"""
if self.is_writer and (
key is None or self.key_index.get(key) != (address, monotonic_id)
):
raise ValueError("Invalid SHM handle signature for cache key.")
self._verify_reader_signature(address, monotonic_id, signature, key)
def _make_signature(self, key: str, address: int, monotonic_id: int) -> bytes:
payload = (
hashlib.sha256(key.encode("utf-8")).digest()
+ address.to_bytes(8, "little", signed=False)
+ monotonic_id.to_bytes(4, "little", signed=False)
)
return hmac.new(
self.ring_buffer.get_auth_secret(),
payload,
hashlib.sha256,
).digest()
def increment_writer_flag(self, id: int) -> None:
"""Set the in-use flag for the writer."""
self.writer_flag[id] = self.writer_flag.get(id, 0) + 1
@@ -555,6 +666,11 @@ class SingleWriterShmObjectStorage:
self.increment_writer_flag(monotonic_id)
return address, monotonic_id
def get_signature(self, key: str) -> list[int]:
"""Sign the handle of a cached object so readers can verify it."""
address, monotonic_id = self.key_index[key]
return list(self._make_signature(key, address, monotonic_id))
def put(self, key: str, value: Any) -> tuple[int, int]:
"""Store a key-value pair in the object storage.
Attempts to free max_object_size bytes using FIFO order
@@ -605,15 +721,20 @@ class SingleWriterShmObjectStorage:
self.id_index[monotonic_id] = key
return address, monotonic_id
def get(self, address: int, monotonic_id: int) -> Any:
def get(
self,
address: int,
monotonic_id: int,
signature: list[int] | None = None,
key: str | None = None,
) -> Any:
if not self.is_writer:
# Reject forged handles before dereferencing the supplied address.
self.verify_signature(key, address, monotonic_id, signature)
# Read data from buffer
with self.ring_buffer.access_buf(address) as (data_view, buf_metadata):
# check id from metadata
if buf_metadata[0] != monotonic_id:
raise ValueError(
f"Data for address:id '{address}:{monotonic_id}'"
" has been modified or is invalid."
)
self._validate_monotonic_id(address, monotonic_id, buf_metadata)
obj = self.ser_de.deserialize(data_view[self.flag_bytes :])
@@ -633,6 +754,7 @@ class SingleWriterShmObjectStorage:
key: str,
address: int = 0,
monotonic_id: int = 0,
signature: list[int] | None = None,
) -> None:
"""Touch an existing cached item to update its eviction status.
@@ -643,6 +765,7 @@ class SingleWriterShmObjectStorage:
key: String key of the object to touch
address: Address of the object (only for readers)
monotonic_id: Monotonic ID of the object (only for readers)
signature: Server-issued handle signature (only for readers)
"""
if self._reader_lock is None:
@@ -652,10 +775,13 @@ class SingleWriterShmObjectStorage:
# Writer side: increment writer_flag to raise eviction threshold
self.increment_writer_flag(monotonic_id)
else:
# Reject forged handles before dereferencing the supplied address.
self.verify_signature(key, address, monotonic_id, signature)
with (
self._reader_lock,
self.ring_buffer.access_buf(address) as (data_view, _),
self.ring_buffer.access_buf(address) as (data_view, buf_metadata),
):
self._validate_monotonic_id(address, monotonic_id, buf_metadata)
reader_count = self.ring_buffer.byte2int(data_view[: self.flag_bytes])
# NOTE(Long):
@@ -721,7 +721,12 @@ class ElasticEPScalingExecutor:
self._suppress_eplb(),
serving_state,
):
runner._dummy_run(runner.max_num_tokens, is_profile=True, skip_eplb=True)
runner._dummy_run(
runner.max_num_tokens,
is_profile=True,
skip_eplb=True,
randomize_inputs=self.worker.randomize_dummy_inputs,
)
self.worker.compile_or_warm_up_model()
lock_workspace()
+5 -3
View File
@@ -68,9 +68,11 @@ class BlockStored(KVCacheEvent):
lora_name: str | None
"""Extra keys used in block hash computation, one entry per block in
block_hashes. Each entry contains MM identifiers, LoRA name, cache_salt,
prompt embedding hashes, etc. for that specific block. Exposed for external
KV cache consumers to reconstruct block hashes.
block_hashes. Each entry contains, in order, the LoRA name (if
`lora_name` is set), `(mm_identifier, offset)` pairs, the cache_salt
string and prompt embedding digests for that specific block. These are
published untagged; the block hash itself uses each value tagged with
its source, e.g. `("lora", name)` or `("mm", mm_identifier, offset)`.
"""
extra_keys: list[tuple[Any, ...] | None] | None = None
@@ -33,6 +33,16 @@ EngineId = str
BlockIds = tuple[list[int], ...] | list[list[int]]
def clip_ssm_state_blocks(blocks: list[int], num_spec_blocks: int) -> list[int]:
"""Drop speculative scratch slots and keep only the running-state slot."""
if not blocks:
return blocks
# Keep at least the running-state slot, even before scratch allocation.
if num_scratch := min(num_spec_blocks, len(blocks) - 1):
blocks = blocks[:-num_scratch]
return blocks[-1:]
def get_kv_connector_cache_layout(vllm_config: VllmConfig | None = None):
# NOTE (NickLucche) When running disaggregated PD with NIXL, LBHNC layout is
# used for faster transfer.
@@ -106,21 +106,6 @@ class HiSparseConnectorScheduler:
# HiSparse rebinds worker state every step, so the load must start
# before the forward rather than being deferred to post-forward.
scheduler_output.has_sync_kv_loads = True
scheduler_output.block_table_updates = (
self.coordinator.take_block_table_updates() or None
)
command = self.coordinator.build_offload_command()
host_block_copies = self.coordinator.take_host_block_copies()
source_group_id = self.coordinator.host_group_id
assert source_group_id is not None
source_block_ids = [
block_id
for request in scheduler_output.scheduled_new_reqs
for block_id in request.block_ids[source_group_id]
]
for new_block_ids in scheduler_output.scheduled_cached_reqs.new_block_ids:
if new_block_ids is not None:
source_block_ids.extend(new_block_ids[source_group_id])
num_computed_tokens = {
request.req_id: request.num_computed_tokens
for request in scheduler_output.scheduled_new_reqs
@@ -141,6 +126,29 @@ class HiSparseConnectorScheduler:
scheduler_output.num_scheduled_tokens.items()
)
)
# Runs first: it plans this step's transfers and table updates.
self.coordinator.advance_scheduled(
(
request_id,
min(start + count, self.requests[request_id].num_tokens),
)
for request_id, start, count in scheduled_requests
)
scheduler_output.block_table_updates = (
self.coordinator.take_block_table_updates() or None
)
command = self.coordinator.build_offload_command()
host_block_copies = self.coordinator.take_host_block_copies()
source_group_id = self.coordinator.host_group_id
assert source_group_id is not None
source_block_ids = [
block_id
for request in scheduler_output.scheduled_new_reqs
for block_id in request.block_ids[source_group_id]
]
for new_block_ids in scheduler_output.scheduled_cached_reqs.new_block_ids:
if new_block_ids is not None:
source_block_ids.extend(new_block_ids[source_group_id])
row_mirrors = {}
for request_id, scheduled_start, scheduled_count in scheduled_requests:
mirror_start = scheduled_start
@@ -301,6 +301,10 @@ class HiSparseConnectorWorker:
self._submitted_mirror_layers: set[int] = set()
self._layer_ready_events = tuple(torch.Event() for _ in cache_handles)
self._forward_ready_event = torch.Event()
self._draft_layers = tuple(
index for index, cache in enumerate(cache_handles) if cache.draft_layer
)
self._draft_mirror_pending = False
self._set_row_mirrors(())
self.cache_layer_names = cache_layer_names
self._group_leaders = tuple(
@@ -344,9 +348,11 @@ class HiSparseConnectorWorker:
self._init_dma()
if self.is_host_writer:
for layer_index, handle in enumerate(cache_handles):
handle.submit_layer_mirror = partial(
self._enqueue_layer_mirror, layer_index
)
# Draft layers are mirrored once in the next start_step instead.
if not handle.draft_layer:
handle.submit_layer_mirror = partial(
self._enqueue_layer_mirror, layer_index
)
self._initialized = True
def set_request_state_indices(self, indices: torch.Tensor) -> None:
@@ -397,16 +403,17 @@ class HiSparseConnectorWorker:
num_tokens: int = 0,
) -> None:
self._stage_row_mirror_mapping(num_tokens)
self._finish_previous_step()
previous_host_write_event = self.host_write_event
self.host_write_event = self.host_write_events[self._next_host_write_event]
self._next_host_write_event ^= 1
current_stream().wait_event(previous_host_write_event)
self._release_completed_dma_descriptors()
self._dma_submitted = False
mirrors = _flatten_row_mirrors(metadata.row_mirrors, request_ids)
if self._slot_mapping_staging is not None:
self._slot_mapping_staging.candidates = mirrors
self._set_row_mirrors(mirrors)
self._dma_submitted = False
self._clear_forward_mirror_state()
for handle in self.cache_handles:
handle.all_context_pages_resident = metadata.all_context_pages_resident
@@ -849,7 +856,12 @@ class HiSparseConnectorWorker:
if num_rows == 0:
return
if self.is_host_writer:
expected_layers = {index for index, _ in active}
# The drafter has not written its layers' rows yet; the next
# start_step mirrors them after it runs.
self._draft_mirror_pending = bool(self._draft_layers)
expected_layers = {index for index, _ in active}.difference(
self._draft_layers
)
if self._per_layer_mirrored and self._per_layer_mirrored != expected_layers:
raise RuntimeError(
"HiSparse per-layer DMA did not mirror every active layer: "
@@ -884,9 +896,6 @@ class HiSparseConnectorWorker:
compute_stream = current_stream()
self._forward_ready_event.record()
self._finish_mirror_phase(self._forward_ready_event)
transfers = self._post_forward_transfers
self._post_forward_transfers = []
self._submit_transfers(transfers)
if self.is_host_writer:
if self._dma_submitted:
compute_stream.wait_event(self.host_write_event)
@@ -895,6 +904,24 @@ class HiSparseConnectorWorker:
self.host_write_event.record(compute_stream)
self._release_completed_dma_descriptors()
def _finish_previous_step(self) -> None:
"""Mirror the previous step's draft-layer rows, then hand its pages over.
Runs before this step's work, so after the previous step's drafter.
Post-forward transfers are ordered behind the draft mirror, so a page is
never reported clean, and its resident block never released, before
its draft-layer rows reach the host. Both land in the previous step's
host write event, which this step waits on before its forward and its
host copies, since the scheduler may already have reused the
finished requests' blocks they read and write.
"""
if self._draft_mirror_pending:
self._draft_mirror_pending = False
self._enqueue_row_dma(self._draft_layers)
transfers = self._post_forward_transfers
self._post_forward_transfers = []
self._submit_transfers(transfers)
def take_completed_host_copies(self) -> list[int]:
"""Drain host copies this worker has enqueued for this step."""
completed = self._completed_host_copy_dst_ids
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import itertools
import logging
import queue
import threading
@@ -62,6 +63,8 @@ from vllm.v1.kv_cache_interface import (
KpoolTailSpec,
KVCacheSpec,
MambaSpec,
MLAAttentionSpec,
SlidingWindowMLASpec,
SlidingWindowSpec,
)
from vllm.v1.request import RequestStatus
@@ -90,6 +93,12 @@ if TYPE_CHECKING:
ReqId = str # Internal scheduler request ID
TransferId = str # KV transfer coordination ID (shared by P/D)
# Follow NIXL (`nixl/base_worker.py`): HMA packed pages can put more than one
# KV group on a single allocation. group_index=-1 flattens every group's block
# ids onto that region. Hybrid KV manager assigns distinct ids per group, so
# flatten does not copy the same block twice.
_SHARED_REGION_GROUP_ID = -1
@dataclass(frozen=True)
class TransferRegion:
@@ -99,6 +108,34 @@ class TransferRegion:
block_len: int
kv_block_len: int
group_index: int = 0
# Groups that share this allocation. Empty unless group_index is -1.
shared_group_ids: tuple[int, ...] = ()
# Byte offset of this view from the start of its block row.
row_offset: int = 0
def _block_ids_for_region(
block_ids_by_group: list[list[int]],
group_index: int,
shared_group_ids: tuple[int, ...] = (),
) -> list[int]:
"""Follow NIXL `_block_ids_by_region`.
-1 flattens only the groups that share this allocation. NIXL can flatten
every group because its packed flag means they all share one storage;
Mooncake can still have a separate Mamba group in the same request.
"""
if group_index == _SHARED_REGION_GROUP_ID:
assert shared_group_ids, "Shared packed region is missing its group ids."
return list(
itertools.chain.from_iterable(
block_ids_by_group[group] for group in shared_group_ids
)
)
assert 0 <= group_index < len(block_ids_by_group), (
"Transfer region references a missing KV group."
)
return list(block_ids_by_group[group_index])
def _get_tp_ratio(local_tp_size: int, remote_tp_size: int) -> int:
@@ -129,6 +166,8 @@ def _expand_transfer_regions(
layer_names: list[str],
layer_indices: list[int],
group_indices: list[int] | None = None,
shared_group_ids: list[tuple[int, ...]] | None = None,
row_offsets: list[int] | None = None,
) -> list[TransferRegion]:
"""Expand registered KV tensors into the regions transferred by Mooncake."""
assert (
@@ -150,6 +189,14 @@ def _expand_transfer_regions(
"Mooncake transfer regions require matching group metadata lengths, "
f"got group_indices={len(group_indices)}, layer_names={len(layer_names)}."
)
if shared_group_ids is None:
shared_group_ids = [() for _ in layer_names]
assert len(shared_group_ids) == len(layer_names)
# Missing offsets must not look like row starts, or every run would be
# promoted to the full row.
if row_offsets is None:
row_offsets = [-1] * len(layer_names)
assert len(row_offsets) == len(layer_names)
regions: list[TransferRegion] = []
for (
base_addr,
@@ -158,6 +205,8 @@ def _expand_transfer_regions(
layer_name,
layer_index,
group_index,
region_groups,
row_offset,
) in zip(
base_addrs,
block_lens,
@@ -165,6 +214,8 @@ def _expand_transfer_regions(
layer_names,
layer_indices,
group_indices,
shared_group_ids,
row_offsets,
):
regions.append(
TransferRegion(
@@ -174,6 +225,8 @@ def _expand_transfer_regions(
block_len=block_len,
kv_block_len=kv_block_len,
group_index=group_index,
shared_group_ids=region_groups,
row_offset=row_offset,
)
)
return regions
@@ -377,12 +430,168 @@ def _align_transfer_regions(
f"{remote_region.group_index}."
),
)
if (
local_region.shared_group_ids
and remote_region.shared_group_ids
and local_region.shared_group_ids != remote_region.shared_group_ids
):
return (
[],
[],
(
"Mooncake shared-group set mismatch for "
f"{local_region.layer_name}: producer="
f"{local_region.shared_group_ids}, consumer="
f"{remote_region.shared_group_ids}."
),
)
aligned_local.append(local_region)
aligned_remote.append(remote_region)
return aligned_local, aligned_remote, None
def _coalesce_contiguous_transfer_regions(
local_regions: list[TransferRegion],
remote_regions: list[TransferRegion],
*,
promote_full_row: bool = False,
) -> tuple[list[TransferRegion], list[TransferRegion]]:
"""Merge aligned packed slices that are adjacent on both sides.
Page-contiguous views stay addressable by layer name for hetero PP
(#56033). KV groups overlay one row and must stay separate: each group
owns a different block-id space. A run that starts at row offset 0 is
lifted to the full row so consecutive blocks can coalesce.
"""
if len(local_regions) != len(remote_regions):
return local_regions, remote_regions
def adjacent(
run_start: TransferRegion, prev: TransferRegion, nxt: TransferRegion
) -> bool:
# Page padding sits between unpadded payloads. Allow that gap, but
# keep the whole run inside the row that `run_start` began. Anchoring
# on `prev` would slide the bound forward as the run grows.
return (
prev.group_index == nxt.group_index
and prev.shared_group_ids == nxt.shared_group_ids
and prev.block_len == nxt.block_len
and prev.base_addr + prev.kv_block_len <= nxt.base_addr
and nxt.base_addr + nxt.kv_block_len
<= run_start.base_addr + run_start.block_len
)
def span(region: TransferRegion, kv_block_len: int) -> TransferRegion:
return TransferRegion(
layer_name=region.layer_name,
layer_index=region.layer_index,
base_addr=region.base_addr,
block_len=region.block_len,
kv_block_len=kv_block_len,
group_index=region.group_index,
shared_group_ids=region.shared_group_ids,
row_offset=region.row_offset,
)
def promote(
merged_local: list[TransferRegion], merged_remote: list[TransferRegion]
) -> tuple[list[TransferRegion], list[TransferRegion]]:
if not promote_full_row:
return merged_local, merged_remote
# Each KV group overlays the row from offset 0. Promoting that run to
# the full row copies bytes the group's block ids exclusively own.
# Equal block_len is the row-structure check: both peers packed the
# same stride, so row_offset does not need a second compare in align.
promoted_local: list[TransferRegion] = []
promoted_remote: list[TransferRegion] = []
for local_region, remote_region in zip(merged_local, merged_remote):
if (
local_region.row_offset == 0
and remote_region.row_offset == 0
and local_region.block_len == remote_region.block_len
and local_region.kv_block_len <= local_region.block_len
and remote_region.kv_block_len <= remote_region.block_len
):
promoted_local.append(span(local_region, local_region.block_len))
promoted_remote.append(span(remote_region, remote_region.block_len))
else:
promoted_local.append(local_region)
promoted_remote.append(remote_region)
return promoted_local, promoted_remote
if len(local_regions) <= 1:
return promote(list(local_regions), list(remote_regions))
merged_local: list[TransferRegion] = []
merged_remote: list[TransferRegion] = []
run_local = [local_regions[0]]
run_remote = [remote_regions[0]]
def flush() -> None:
if len(run_local) == 1:
merged_local.append(run_local[0])
merged_remote.append(run_remote[0])
return
for merged, run in ((merged_local, run_local), (merged_remote, run_remote)):
span_len = run[-1].base_addr + run[-1].kv_block_len - run[0].base_addr
merged.append(span(run[0], span_len))
for local_region, remote_region in zip(local_regions[1:], remote_regions[1:]):
if adjacent(run_local[0], run_local[-1], local_region) and adjacent(
run_remote[0], run_remote[-1], remote_region
):
run_local.append(local_region)
run_remote.append(remote_region)
continue
flush()
run_local = [local_region]
run_remote = [remote_region]
flush()
return promote(merged_local, merged_remote)
def _has_opaque_packed_row(
row_offsets: list[int], kv_block_lens: list[int], block_lens: list[int]
) -> bool:
"""Branch B is one row-sized region at offset 0, so later layer names are gone.
Page-contiguous views keep kv_block_len below the stride until promotion,
and promotion happens after this handshake check.
"""
if (
not row_offsets
or len(row_offsets) != len(kv_block_lens)
or len(row_offsets) != len(block_lens)
):
return False
return any(
offset == 0 and length == stride
for offset, length, stride in zip(row_offsets, kv_block_lens, block_lens)
)
def _pp_mismatch_hides_packed_layers(
local_pp_size: int,
remote_pp_size: int,
*,
local_has_opaque_row: bool,
remote_row_offsets: list[int],
remote_kv_block_lens: list[int],
remote_block_lens: list[int],
) -> bool:
"""A row that dropped per-layer names cannot be aligned across PP sizes.
Either side may be the one that collapsed the row. Matching PP still
lines up, because both stages keep the same first layer name.
"""
if local_pp_size == remote_pp_size:
return False
return local_has_opaque_row or _has_opaque_packed_row(
remote_row_offsets, remote_kv_block_lens, remote_block_lens
)
def _get_tensor_dense_flag(tensor: torch.Tensor) -> bool | None:
is_dense = getattr(tensor, "is_non_overlapping_and_dense", None)
if callable(is_dense):
@@ -405,6 +614,12 @@ class MooncakeXferMetadata(
registered_layer_names: list[str] = msgspec.field(default_factory=list)
registered_layer_indices: list[int] = msgspec.field(default_factory=list)
registered_group_indices: list[int] = msgspec.field(default_factory=list)
# Parallel to registered regions. Each entry is the groups that share
# that region. Empty means the peer did not send the field.
registered_shared_group_ids: list[list[int]] = msgspec.field(default_factory=list)
# Byte offset of each registered view from its block row. -1 means the
# peer did not send the field, so the run must not be promoted.
registered_row_offsets: list[int] = msgspec.field(default_factory=list)
remote_pp_size: int = 1
@@ -999,7 +1214,18 @@ class MooncakeConnectorWorker:
self.registered_layer_names: list[str] = []
self.registered_layer_indices: list[int] = []
self.registered_group_indices: list[int] = []
# Parallel to registered regions. -1 flattens only these groups.
self.region_shared_groups: list[tuple[int, ...]] = []
# Parallel to registered regions. -1 is not a packed row view.
self.region_row_offsets: list[int] = []
self.opaque_packed_storages: set[int] = set()
self.seen_base_addresses: list[int] = []
# Aligned regions depend only on the peer's registered layout.
# The third item is an error string when alignment cannot proceed.
self._prepared_transfer_regions: dict[
tuple,
tuple[list[TransferRegion], list[TransferRegion], str | None],
] = {}
assert (parallel_config := vllm_config.parallel_config)
dp_rank = parallel_config.data_parallel_index
@@ -1266,39 +1492,35 @@ class MooncakeConnectorWorker:
)
await sock.send_multipart((identity, self._encoder.encode(response)))
return
local_regions = self._get_transfer_regions(
self.kv_caches_base_addr,
self.block_len_per_layer,
self.kv_block_len_per_layer,
self.registered_layer_names,
self.registered_layer_indices,
self.registered_group_indices,
)
remote_regions = self._get_transfer_regions(
meta.kv_caches_base_addr,
meta.block_lens,
meta.kv_block_lens,
meta.registered_layer_names,
meta.registered_layer_indices,
meta.registered_group_indices,
)
local_regions, remote_regions, align_err = _align_transfer_regions(
local_regions,
remote_regions,
allow_partial_layers=(
meta.remote_pp_size > 1 and meta.remote_pp_size != self.pp_size
),
)
if align_err is not None:
if _pp_mismatch_hides_packed_layers(
self.pp_size,
meta.remote_pp_size,
local_has_opaque_row=bool(self.opaque_packed_storages),
remote_row_offsets=meta.registered_row_offsets,
remote_kv_block_lens=meta.kv_block_lens,
remote_block_lens=meta.block_lens,
):
msg = (
"Mooncake non-page-contiguous packed regions keep only the "
"first layer name, so they cannot be aligned across PP sizes "
f"{self.pp_size} and {meta.remote_pp_size}."
)
logger.error(msg)
response = MooncakeXferResponse(
status=MooncakeXferResponseStatus.ERROR,
err_msg=align_err,
err_msg=msg,
)
await sock.send_multipart((identity, self._encoder.encode(response)))
return
validation_err = self._validate_head_resharding_layout(
meta.remote_tp_size, local_regions
) or _validate_asymmetric_region_lengths(
local_regions, remote_regions, prep_err = self._prepare_transfer_regions(meta)
if prep_err is not None:
response = MooncakeXferResponse(
status=MooncakeXferResponseStatus.ERROR,
err_msg=prep_err,
)
await sock.send_multipart((identity, self._encoder.encode(response)))
return
validation_err = _validate_asymmetric_region_lengths(
local_regions=local_regions,
remote_regions=remote_regions,
local_tp_size=self.tp_size,
@@ -1600,12 +1822,16 @@ class MooncakeConnectorWorker:
"Aligned Mooncake transfer regions must belong to the same "
"KV group."
)
group_index = local_region.group_index
assert group_index < len(local_block_ids_by_group), (
"Transfer region references a missing KV group."
local_block_ids = _block_ids_for_region(
local_block_ids_by_group,
local_region.group_index,
local_region.shared_group_ids,
)
remote_block_ids = _block_ids_for_region(
remote_block_ids_by_group,
remote_region.group_index,
local_region.shared_group_ids,
)
local_block_ids = local_block_ids_by_group[group_index]
remote_block_ids = remote_block_ids_by_group[group_index]
if not local_block_ids:
continue
@@ -1738,6 +1964,17 @@ class MooncakeConnectorWorker:
self.registered_layer_names = []
self.registered_layer_indices = []
self.registered_group_indices = []
self.region_shared_groups = []
self.region_row_offsets = []
self.opaque_packed_storages = set()
self._prepared_transfer_regions.clear()
packed_storage_to_region: dict[int, int] = {}
packed_view_to_region: dict[tuple[int, int, int], int] = {}
collapsed_views = 0
num_blocks = (
self.kv_cache_config.num_blocks * self._physical_blocks_per_logical_kv_block
)
for layer_name, cache in kv_caches.items():
layer_index = extract_layer_index(layer_name)
@@ -1751,6 +1988,104 @@ class MooncakeConnectorWorker:
# One raw page tensor per layer; for Mamba that page holds all the
# recurrent states, unpacked only when binding the cache for execution.
self._log_debug_cache_registration(layer_name, cache)
group_index = self.kv_cache_config.transfer_group_index_by_layer[layer_name]
storage = cache.untyped_storage()
storage_addr = storage.data_ptr()
if storage_addr not in seen_storage_ptrs:
seen_storage_ptrs.add(storage_addr)
kv_data_ptrs.append(storage_addr)
kv_data_lens.append(storage.nbytes())
is_mla_region = isinstance(
layer_spec, (MLAAttentionSpec, SlidingWindowMLASpec)
)
tensor_blocks = cache.shape[0] if cache.ndim > 1 else num_blocks
if cache.ndim == 1:
# A flat buffer is block-major only when it is an integral run
# of this layer's pages. NIXL uses the same remainder check.
hnc_contiguous = False
page = (
layer_spec.page_size_bytes
if isinstance(layer_spec, AttentionSpec)
else 0
)
remainder = (
storage.nbytes() - tensor_blocks * page
if tensor_blocks > 0 and page > 0
else -1
)
if 0 <= remainder < page:
block_stride = page
storage_is_block_major = True
else:
block_stride = 0
storage_is_block_major = False
else:
block_stride = cache.stride(0) * cache.element_size()
storage_is_block_major = (
tensor_blocks > 0
and tensor_blocks * block_stride == storage.nbytes()
)
hnc_contiguous = (
cache.ndim == 4
and cache.stride(2) == cache.shape[3]
and cache.stride(1) == cache.shape[2] * cache.shape[3]
)
# Follow NIXL packed pages. Page-contiguous slices stay per layer so
# hetero PP can align by name (#56033). A non-contiguous row cannot
# name a sub-span, so it is one region anchored at the allocation.
use_packed_row = (
not isinstance(layer_spec, (MambaSpec, KpoolTailSpec))
and storage_is_block_major
and block_stride > 0
and (is_mla_region or not hnc_contiguous)
)
if use_packed_row:
page_contiguous = (
cache.ndim > 1
and cache[0].is_contiguous()
and 0 < cache[0].nbytes <= block_stride
)
if page_contiguous:
view_addr = cache.data_ptr()
kv_block_len = cache[0].nbytes
else:
# NIXL branch B: length is the row, base is the allocation.
view_addr = storage_addr
kv_block_len = block_stride
self.opaque_packed_storages.add(storage_addr)
# Same PP on both sides still aligns by the first layer name.
# A remote PP mismatch is rejected at send time, once the
# peer's PP size is known.
dedupe_key = (view_addr, block_stride, kv_block_len)
region_idx = packed_view_to_region.get(dedupe_key)
if region_idx is not None:
collapsed_views += 1
# -1 means these groups share the view. Flatten only them.
groups = list(self.region_shared_groups[region_idx])
if group_index not in groups:
groups.append(group_index)
self.region_shared_groups[region_idx] = tuple(groups)
if len(self.region_shared_groups[region_idx]) > 1:
self.registered_group_indices[region_idx] = (
_SHARED_REGION_GROUP_ID
)
continue
if not page_contiguous:
self.opaque_packed_storages.add(storage_addr)
if storage_addr not in packed_storage_to_region:
packed_storage_to_region[storage_addr] = len(region_base_addresses)
packed_view_to_region[dedupe_key] = len(region_base_addresses)
region_base_addresses.append(view_addr)
self.block_len_per_layer.append(block_stride)
self.kv_block_len_per_layer.append(kv_block_len)
self.registered_layer_names.append(layer_name)
self.registered_layer_indices.append(layer_index)
self.registered_group_indices.append(group_index)
self.region_shared_groups.append((group_index,))
self.region_row_offsets.append(view_addr - storage_addr)
continue
block_is_contiguous = is_non_overlapping_and_dense(cache[0])
if not block_is_contiguous:
# Non-block-compact layouts scatter a block across per-head
@@ -1791,15 +2126,10 @@ class MooncakeConnectorWorker:
self.kv_block_len_per_layer.append(kv_block_len)
self.registered_layer_names.append(layer_name)
self.registered_layer_indices.append(layer_index)
self.registered_group_indices.append(
self.kv_cache_config.transfer_group_index_by_layer[layer_name]
)
storage = cache.untyped_storage()
storage_addr = storage.data_ptr()
if storage_addr not in seen_storage_ptrs:
seen_storage_ptrs.add(storage_addr)
kv_data_ptrs.append(storage_addr)
kv_data_lens.append(storage.nbytes())
self.registered_group_indices.append(group_index)
self.region_shared_groups.append((group_index,))
# Not a view into a shared packed row, so do not promote it.
self.region_row_offsets.append(-1)
self.kv_caches_base_addr = region_base_addresses
self.seen_base_addresses = kv_data_ptrs
@@ -1807,6 +2137,18 @@ class MooncakeConnectorWorker:
if not kv_data_ptrs:
raise RuntimeError("No KV cache tensors were registered with Mooncake.")
if packed_storage_to_region and (
collapsed_views
or len(packed_view_to_region) != len(packed_storage_to_region)
):
logger.info(
"Mooncake packed KV xfer: %s layer regions over %s storage "
"regions (%s duplicate views collapsed).",
len(packed_view_to_region),
len(packed_storage_to_region),
collapsed_views,
)
ret_value = self.engine.batch_register_memory(kv_data_ptrs, kv_data_lens)
if ret_value != 0:
raise RuntimeError("Mooncake batch memory registration failed.")
@@ -1962,6 +2304,10 @@ class MooncakeConnectorWorker:
registered_layer_names=self.registered_layer_names,
registered_layer_indices=self.registered_layer_indices,
registered_group_indices=self.registered_group_indices,
registered_shared_group_ids=[
list(groups) for groups in self.region_shared_groups
],
registered_row_offsets=self.region_row_offsets,
)
encoded_data = self._encoder.encode(metadata)
@@ -2209,6 +2555,131 @@ class MooncakeConnectorWorker:
def _producer_cache_is_replicated(self) -> bool:
return self.transfer_topo.local_replicates_kv_cache
def _prepare_transfer_regions(
self, meta: MooncakeXferMetadata
) -> tuple[list[TransferRegion], list[TransferRegion], str | None]:
"""Align and coalesce once per peer layout.
``send_kv_to_decode`` runs on every scheduler batch. The registered
layout does not change until the next ``register_kv_caches``.
"""
cache_key = (
meta.remote_hostname,
meta.remote_port,
meta.remote_tp_size,
meta.remote_tp_rank,
meta.remote_pp_size,
tuple(meta.kv_caches_base_addr),
tuple(meta.block_lens),
tuple(meta.kv_block_lens),
tuple(meta.registered_layer_names),
tuple(meta.registered_layer_indices),
tuple(meta.registered_group_indices),
tuple(tuple(groups) for groups in meta.registered_shared_group_ids),
tuple(meta.registered_row_offsets),
)
cached = self._prepared_transfer_regions.get(cache_key)
if cached is not None:
return cached
def finish(
local: list[TransferRegion],
remote: list[TransferRegion],
err: str | None,
) -> tuple[list[TransferRegion], list[TransferRegion], str | None]:
prepared = (local, remote, err)
self._prepared_transfer_regions[cache_key] = prepared
return prepared
shared_groups: list[tuple[int, ...]] | None = self.region_shared_groups
if len(self.region_shared_groups) != len(self.registered_layer_names):
if _SHARED_REGION_GROUP_ID in self.registered_group_indices:
return finish(
[],
[],
(
"Mooncake shared-group metadata does not match "
"registered layers, so a shared packed region cannot "
"be transferred."
),
)
shared_groups = None
local_rows: list[int] | None = self.region_row_offsets
if len(self.region_row_offsets) != len(self.registered_layer_names):
local_rows = None
local_regions = self._get_transfer_regions(
self.kv_caches_base_addr,
self.block_len_per_layer,
self.kv_block_len_per_layer,
self.registered_layer_names,
self.registered_layer_indices,
self.registered_group_indices,
shared_groups,
local_rows,
)
remote_shared_groups = [
tuple(groups) for groups in meta.registered_shared_group_ids
]
remote_shared: list[tuple[int, ...]] | None = remote_shared_groups
if len(remote_shared_groups) != len(meta.registered_layer_names):
remote_shared = None
remote_rows = meta.registered_row_offsets
remote_row_offsets: list[int] | None = remote_rows
if len(remote_rows) != len(meta.registered_layer_names):
remote_row_offsets = None
remote_regions = self._get_transfer_regions(
meta.kv_caches_base_addr,
meta.block_lens,
meta.kv_block_lens,
meta.registered_layer_names,
meta.registered_layer_indices,
meta.registered_group_indices,
remote_shared,
remote_row_offsets,
)
pre_align_local = local_regions
pre_align_remote = remote_regions
local_regions, remote_regions, align_err = _align_transfer_regions(
local_regions,
remote_regions,
allow_partial_layers=meta.remote_pp_size != self.pp_size,
)
if align_err is not None:
return finish([], [], align_err)
# Head checks must see every layer name. Coalesce keeps only the first.
head_err = self._validate_head_resharding_layout(
meta.remote_tp_size, local_regions
)
if head_err is not None:
return finish([], [], head_err)
# Hetero TP indexes kv_block_len as one head-sharded payload. A merged
# multi-layer span would land that offset on the wrong layer.
# Replicated KV keeps that offset at 0. MLA is replicated in practice;
# gating on use_mla alone would promote and then fail the length check
# for a non-replicated MLA rank with tp_ratio != 1.
tp_ratio = _get_tp_ratio(self.tp_size, meta.remote_tp_size)
if tp_ratio == 1 or self._producer_cache_is_replicated():
covered_both_sides = len(local_regions) == len(pre_align_local) and len(
remote_regions
) == len(pre_align_remote)
n_aligned = len(local_regions)
local_regions, remote_regions = _coalesce_contiguous_transfer_regions(
local_regions,
remote_regions,
promote_full_row=covered_both_sides,
)
logger.info(
"Mooncake packed coalesce: %s aligned regions -> %s transfer regions.",
n_aligned,
len(local_regions),
)
self._prepared_transfer_regions[cache_key] = (
local_regions,
remote_regions,
None,
)
return local_regions, remote_regions, None
def _validate_head_resharding_layout(
self, remote_tp_size: int, local_regions: list[TransferRegion]
) -> str | None:
@@ -2242,6 +2713,8 @@ class MooncakeConnectorWorker:
layer_names: list[str],
layer_indices: list[int],
group_indices: list[int] | None = None,
shared_group_ids: list[tuple[int, ...]] | None = None,
row_offsets: list[int] | None = None,
) -> list[TransferRegion]:
if not group_indices:
group_indices = [
@@ -2255,6 +2728,8 @@ class MooncakeConnectorWorker:
layer_names=layer_names,
layer_indices=layer_indices,
group_indices=group_indices,
shared_group_ids=shared_group_ids,
row_offsets=row_offsets,
)
def _get_sender_transfer_plan(
@@ -2329,6 +2804,10 @@ def _async_loop(loop: asyncio.AbstractEventLoop):
def should_launch_bootstrap_server(vllm_config: VllmConfig) -> bool:
if (kv_config := vllm_config.kv_transfer_config) is not None and (
kv_config.get_from_extra_config("bootstrap_server_address", None) is not None
):
return False
assert (parallel_config := vllm_config.parallel_config)
# Only the TP=0, PP=0 worker of the designated engine should launch it.
if get_tensor_model_parallel_rank() != 0:
@@ -2351,6 +2830,17 @@ def get_mooncake_bootstrap_addr(vllm_config: VllmConfig) -> tuple[str, int]:
This is only used by prefillers to register workers.
Decoders should get addr from kv_transfer_params.
"""
if (kv_config := vllm_config.kv_transfer_config) is not None:
address = kv_config.get_from_extra_config("bootstrap_server_address", None)
if address is not None:
from vllm.utils.network_utils import split_host_port
host, port = split_host_port(address)
if not host or not 1 <= port <= 65535:
raise ValueError(
"bootstrap_server_address must specify a host and port"
)
return host, port
assert (parallel_config := vllm_config.parallel_config)
if parallel_config.local_engines_only:
# In hybrid or external LB mode, connect to local server.
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import socket
import threading
import time
from dataclasses import dataclass
@@ -32,9 +33,7 @@ class EngineEntry:
class MooncakeBootstrapServer:
"""A centralized server running on the global rank 0 prefiller worker.
Prefiller workers register their connection info (IP, port, ranks) here.
"""
"""A centralized registry for prefiller connection info (IP, port, ranks)."""
def __init__(self, host: str, port: int):
self.workers: dict[int, EngineEntry] = {}
@@ -45,6 +44,8 @@ class MooncakeBootstrapServer:
self._register_routes()
self.server_thread: threading.Thread | None = None
self.server: uvicorn.Server | None = None
self._socket: socket.socket | None = None
self._startup_error: BaseException | None = None
def __del__(self):
self.shutdown()
@@ -54,27 +55,74 @@ class MooncakeBootstrapServer:
self.app.post("/register")(self.register_worker)
self.app.get("/query", response_model=dict[int, EngineEntry])(self.query)
def start(self):
def start(self, *, timeout: float = 30.0):
if self.server_thread:
return
if (
self.server_thread.is_alive()
and self.server is not None
and self.server.started
and not self.server.should_exit
and self._socket is not None
and self._socket.fileno() >= 0
):
return
raise RuntimeError(
"Mooncake bootstrap server is still starting or stopping"
)
config = uvicorn.Config(app=self.app, host=self.host, port=self.port)
self.server = uvicorn.Server(config=config)
self.server_thread = threading.Thread(
target=self.server.run, name="mooncake_bootstrap_server", daemon=True
)
self.server_thread.start()
while not self.server.started:
time.sleep(0.1) # Wait for the server to start
try:
# Bind in the caller so errors propagate, and retain the listener
# when handing it to Uvicorn, including for automatically chosen ports.
family = socket.AF_INET6 if ":" in self.host else socket.AF_INET
self._socket = socket.create_server((self.host, self.port), family=family)
self.port = self._socket.getsockname()[1]
config = uvicorn.Config(app=self.app, host=self.host, port=self.port)
server = self.server = uvicorn.Server(config=config)
listener = self._socket
self._startup_error = None
def run():
try:
server.run(sockets=[listener])
except BaseException as exc:
self._startup_error = exc
self.server_thread = threading.Thread(
target=run, name="mooncake_bootstrap_server", daemon=True
)
self.server_thread.start()
deadline = time.monotonic() + timeout
while not server.started:
if not self.server_thread.is_alive():
raise RuntimeError(
"Mooncake bootstrap server exited during startup"
) from self._startup_error
if time.monotonic() >= deadline:
raise TimeoutError(
"Mooncake bootstrap server did not start in time"
)
time.sleep(0.01)
except BaseException:
self.shutdown()
raise
logger.info("Mooncake Bootstrap Server started at %s:%d", self.host, self.port)
def shutdown(self):
if self.server_thread is None or self.server is None or not self.server.started:
return
self.server.should_exit = True
self.server_thread.join()
logger.info("Mooncake Bootstrap Server stopped.")
was_started = self.server is not None and self.server.started
if self.server is not None:
self.server.should_exit = True
if self.server_thread is not None and self.server_thread.ident is not None:
self.server_thread.join(timeout=5)
if self._socket is not None:
self._socket.close()
self._socket = None
if self.server_thread is not None and self.server_thread.is_alive():
logger.warning("Mooncake bootstrap server did not stop in time")
else:
self.server_thread = None
self.server = None
if was_started:
logger.info("Mooncake Bootstrap Server stopped.")
async def register_worker(self, payload: RegisterWorkerPayload):
"""Handles registration of a prefiller worker."""
@@ -17,7 +17,10 @@ import torch
import zmq
from vllm.config import CUDAGraphMode, VllmConfig
from vllm.distributed.kv_transfer.kv_connector.utils import BlockIds
from vllm.distributed.kv_transfer.kv_connector.utils import (
BlockIds,
clip_ssm_state_blocks,
)
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
KVConnectorBase_V1,
KVConnectorMetadata,
@@ -88,10 +91,10 @@ from vllm.utils.network_utils import (
from vllm.v1.attention.selector import get_attn_backend
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheConfig,
MambaSpec,
SlidingWindowSpec,
is_full_attention_spec,
)
from vllm.v1.outputs import KVConnectorOutput
from vllm.v1.request import RequestStatus
@@ -108,7 +111,7 @@ logger = init_logger(__name__)
# wait only needs to be long enough for it to make progress.
_SQ_FULL_BACKOFF_INITIAL_S = 0.001
_SQ_FULL_BACKOFF_MAX_S = 0.05
_MAX_LOCAL_DECODE_TAIL_BLOCKS = 1
_MAX_LOCAL_MAMBA_TAIL_BLOCKS = 1
try:
@@ -436,6 +439,19 @@ def _split_kv_cache_group_kinds(
return attn, mamba
def _validate_hybrid_speculation(vllm_config: VllmConfig) -> None:
speculative_config = vllm_config.speculative_config
if speculative_config is None:
return
# DSpark is allowlisted because it is the only hybrid speculative method
# validated end to end with MoRIIO READ.
if not speculative_config.use_dspark():
raise MoRIIOError(
"MoRIIO hybrid READ supports DSpark speculative decoding only, got "
f"method={speculative_config.method!r}"
)
def _validate_mamba_specs(specs: Collection[MambaSpec]) -> MambaSpec | None:
"""Validate the common packed-state contract and return its representative."""
specs = tuple(specs)
@@ -477,44 +493,52 @@ class MoRIIOConnectorScheduler:
kv_cache_config
)
self._has_mamba = bool(self._mamba_group_ids)
mamba_spec = None
if self._has_mamba:
if len(self._attn_group_ids) != 1:
raise MoRIIOError(
"MoRIIO hybrid READ requires exactly one transferable "
"attention group, got "
f"{len(self._attn_group_ids)} attention groups"
f"{len(self._attn_group_ids)}; a drafter that owns a "
"separate attention group is not supported, give it the "
"target's group or disable KV transfer for it"
)
mamba_specs = [
cast(MambaSpec, kv_cache_config.transfer_groups[group_id].kv_cache_spec)
for group_id in self._mamba_group_ids
]
_validate_mamba_specs(mamba_specs)
if vllm_config.speculative_config is not None:
raise MoRIIOError(
"MoRIIO hybrid READ does not support speculative decoding"
)
mamba_spec = _validate_mamba_specs(mamba_specs)
_validate_hybrid_speculation(vllm_config)
if self.mode != MoRIIOMode.READ:
raise MoRIIOError(
"MoRIIO hybrid (mamba/KDA) transfer is implemented for READ "
"mode only; set kv_connector_extra_config.read_mode=true"
)
# Only "all" mode keeps a state per block position; the other modes keep
# a single running state in the last slot.
self._ssm_state_slots_are_positional = (
vllm_config.cache_config.mamba_cache_mode == "all"
self._num_ssm_scratch_blocks = (
mamba_spec.num_speculative_blocks if mamba_spec is not None else 0
)
self.block_size = vllm_config.cache_config.block_size
self._max_decode_tail_blocks = (
_MAX_LOCAL_DECODE_TAIL_BLOCKS
if self._has_mamba
else math.ceil((vllm_config.num_lookahead_tokens + 1) / self.block_size)
)
attn_block_size = self.block_size
max_decode_tail_tokens = 1 + vllm_config.num_lookahead_tokens
if self._has_mamba:
attn_spec = kv_cache_config.transfer_groups[
self._attn_group_ids[0]
].kv_cache_spec
attn_block_size = attn_spec.block_size
if attn_spec.dcp_sharded:
attn_block_size *= (
vllm_config.parallel_config.decode_context_parallel_size
)
# Admission can pad the final prompt token to 1 + num_spec rows;
# allocate_slots reserves drafter lookahead in addition to those.
max_decode_tail_tokens += vllm_config.num_speculative_tokens
self._max_decode_tail_blocks = cdiv(max_decode_tail_tokens, attn_block_size)
self.engine_id: EngineId = engine_id
self._is_hma_required = (
not vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
and any(
not isinstance(g.kv_cache_spec, FullAttentionSpec)
not is_full_attention_spec(g.kv_cache_spec)
for g in kv_cache_config.transfer_groups
)
)
@@ -524,9 +548,9 @@ class MoRIIOConnectorScheduler:
unsupported = [
type(g.kv_cache_spec).__name__
for g in kv_cache_config.transfer_groups
if not isinstance(
g.kv_cache_spec,
(FullAttentionSpec, SlidingWindowSpec, MambaSpec),
if not (
is_full_attention_spec(g.kv_cache_spec)
or isinstance(g.kv_cache_spec, (SlidingWindowSpec, MambaSpec))
)
]
if unsupported:
@@ -565,7 +589,7 @@ class MoRIIOConnectorScheduler:
self._full_attn_group_idx = 0
self._full_attn_block_size = self.block_size
for gi, group in enumerate(kv_cache_config.kv_cache_groups):
if isinstance(group.kv_cache_spec, FullAttentionSpec):
if is_full_attention_spec(group.kv_cache_spec):
self._full_attn_group_idx = gi
self._full_attn_block_size = getattr(
group.kv_cache_spec, "block_size", self.block_size
@@ -953,6 +977,9 @@ class MoRIIOConnectorScheduler:
)
aligned_local_mamba: list[list[int]] = []
aligned_remote_mamba: list[list[int]] = []
# Scratch slots were removed by
# split_block_groups, so only one local running
# state tail can remain.
for local_group, remote_group in zip(
mamba_block_groups,
remote_mamba_groups,
@@ -960,7 +987,9 @@ class MoRIIOConnectorScheduler:
):
aligned_local, aligned_remote = (
self._align_read_blocks(
local_group, remote_group, 1
local_group,
remote_group,
_MAX_LOCAL_MAMBA_TAIL_BLOCKS,
)
)
aligned_local_mamba.append(aligned_local)
@@ -1247,8 +1276,8 @@ class MoRIIOConnectorScheduler:
"""Select transferable attention and Mamba block groups.
The wire payload stores the attention group first, followed by every
Mamba group in transfer-group order. Outside ``mamba_cache_mode="all"``,
only each group's running-state slot is transferred.
Mamba group in transfer-group order. Only each group's running-state
slot is transferred.
"""
if not block_ids:
return [], []
@@ -1257,21 +1286,14 @@ class MoRIIOConnectorScheduler:
transfer_block_ids = self.kv_cache_config.select_transfer_block_ids(block_ids)
attn = list(transfer_block_ids[self._attn_group_ids[0]])
mamba_groups = [
self._clip_mamba_group(list(transfer_block_ids[group_id]))
clip_ssm_state_blocks(
list(transfer_block_ids[group_id]),
self._num_ssm_scratch_blocks,
)
for group_id in self._mamba_group_ids
]
return attn, mamba_groups
def _clip_mamba_group(self, blocks: list[int]) -> list[int]:
"""Keep only the state-bearing slots of one mamba kv cache group."""
if not blocks:
return blocks
if not self._ssm_state_slots_are_positional:
# Single running state: everything before it is a null placeholder
# or the previous step's superseded state.
blocks = blocks[-1:]
return blocks
@staticmethod
def _align_read_blocks(
local_block_ids: list[int],
@@ -1282,9 +1304,9 @@ class MoRIIOConnectorScheduler:
Prefix hits can make the decode's unhashed suffix shorter than the
prefill's full list, so read from the matching remote suffix. The
decoder can instead have one extra tail block for the locally
recomputed final token; that block has no remote source and is not
transferred.
decoder can instead have extra tail blocks for the locally recomputed
final token and speculative slots; these have no remote source and are
not transferred.
"""
if len(local_block_ids) > len(remote_block_ids):
extra_decode_blocks = len(local_block_ids) - len(remote_block_ids)
@@ -13,6 +13,7 @@ from vllm import envs
from vllm.distributed.kv_transfer.kv_connector.utils import (
BlockIds,
EngineId,
clip_ssm_state_blocks,
yield_req_data,
)
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
@@ -153,11 +154,6 @@ class NixlBaseConnectorScheduler:
else None
for g in kv_cache_config.transfer_groups
]
# Only "all" mode keeps a state per block position; the other modes
# keep a single running state in the last non-speculative slot.
self._ssm_state_slots_are_positional = (
vllm_config.cache_config.mamba_cache_mode == "all"
)
# Threshold to decide whether to compute kv cache locally
# or pull from a remote node: minimum number of remote
@@ -257,11 +253,9 @@ class NixlBaseConnectorScheduler:
out-of-window blocks only prior to the `request_finished_all_groups`
hook.
SSM groups keep only their state-bearing slots: the trailing
speculative scratch slots always go, and in single-state cache modes
so does everything before the running state (null placeholders and
the previous step's superseded state). "all" mode keeps its remaining
slots, which the worker pairs position-wise.
SSM groups keep only their state-bearing slot: the trailing
speculative scratch slots and everything before the running state
(null placeholders and the previous step's superseded state) go.
Use this at every block-id exchange point. Pass ``clip_ssm=False``
for per-step partial lists (host-buffer save), where the SSM strip
@@ -288,11 +282,7 @@ class NixlBaseConnectorScheduler:
and blocks
and (n_spec_blocks := self._ssm_spec_blocks[i]) is not None
):
if n_spec := min(n_spec_blocks, len(blocks) - 1):
blocks = blocks[:-n_spec]
if not self._ssm_state_slots_are_positional:
# Never empty: downstream reads that as a full prefix hit.
blocks = blocks[-1:]
blocks = clip_ssm_state_blocks(blocks, n_spec_blocks)
clipped.append(blocks)
return tuple(clipped)
@@ -2702,17 +2702,18 @@ class NixlBaseConnectorWorker:
assert self.copy_blocks is not None
local_block_ids = meta.local_physical_block_ids
# TODO (NickLucche) D2H<>H2D ops could benefit from coalescing io across groups
# The h2d block copies below are intentionally synchronous.
# Every KV cache group allocates from the same BlockPool, so block ids
# are unique across groups and the per-group copies can be issued as one.
block_ids = [block_id for group in local_block_ids for block_id in group]
# The h2d block copy below is intentionally synchronous.
with gpu_sync_allowed():
for group_block_ids in local_block_ids:
self.copy_blocks(
self.host_xfer_buffers,
self.device_kv_caches,
group_block_ids,
group_block_ids,
"h2d",
)
self.copy_blocks(
self.host_xfer_buffers,
self.device_kv_caches,
block_ids,
block_ids,
"h2d",
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"synced recved kv of request[%s] to device kv buffer,"
@@ -2740,14 +2741,18 @@ class NixlBaseConnectorWorker:
",".join(map(str, meta.local_physical_block_ids)),
)
# blocking
for group_block_ids in meta.local_physical_block_ids:
self.copy_blocks(
self.device_kv_caches,
self.host_xfer_buffers,
group_block_ids,
group_block_ids,
"d2h",
)
block_ids = [
block_id
for group in meta.local_physical_block_ids
for block_id in group
]
self.copy_blocks(
self.device_kv_caches,
self.host_xfer_buffers,
block_ids,
block_ids,
"d2h",
)
@cached_property
def _attention_kv_caches(self) -> list[torch.Tensor]:
@@ -3510,13 +3515,12 @@ class NixlBaseConnectorWorker:
if _is_ssm_spec(self._group_spec_types[i]):
if num_decode_blocks == num_prefill_blocks:
continue
# Only state-bearing slots reach here, single-state modes
# just one (see get_exchange_clipped_blocks), so differing
# counts mean position-indexed "all"-mode lists. A longer
# prefill list carries earlier positions the decode side
# already has (prefix hit) -> take its tail; a longer decode
# list holds the position D recomputes itself, which gets
# no prefill state.
# Only state-bearing slots reach here, normally just one
# (see get_exchange_clipped_blocks). A longer prefill list
# carries earlier positions the decode side already has
# (prefix hit) -> take its tail; a longer decode list holds
# the position D recomputes itself, which gets no prefill
# state.
assert num_decode_blocks - num_prefill_blocks <= 1, (
f"Group {i}: unpairable SSM state slots, "
f"decode={num_decode_blocks} prefill={num_prefill_blocks}"
@@ -660,6 +660,7 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
req_id not in self._reqs_to_send
and req_id not in self._reqs_to_process
):
self.xfer_stats.record_notification_after_expiry()
logger.error(
"Potentially invalid KV blocks for "
"unrecognized request %s were retrieved by "
@@ -786,6 +786,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
else:
# Not tracked on either side (lease may have expired
# before the notif arrived). Log and skip.
self.xfer_stats.record_notification_after_expiry()
logger.error(
"Unrecognized request %s notif (may have expired).",
req_id,
@@ -41,6 +41,7 @@ class NixlKVConnectorStats(KVConnectorStats):
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
def record_transfer(self, res: "nixlXferTelemetry"):
@@ -66,6 +67,10 @@ class NixlKVConnectorStats(KVConnectorStats):
"""Record a request that had its KV blocks expire."""
self.data["num_kv_expired_reqs"].append(1)
def record_notification_after_expiry(self):
"""Record a completion notification that arrived after its request expired."""
self.data["num_notifications_after_expiry"].append(1)
def clone_and_reset(self) -> "NixlKVConnectorStats":
old = copy.copy(self)
self.reset()
@@ -79,6 +84,7 @@ class NixlKVConnectorStats(KVConnectorStats):
and len(self.data["num_failed_notifications"]) == 0
and len(self.data["num_failed_handshakes"]) == 0
and len(self.data["num_kv_expired_reqs"]) == 0
and len(self.data["num_notifications_after_expiry"]) == 0
)
def aggregate(self, other: KVConnectorStats) -> KVConnectorStats:
@@ -95,12 +101,14 @@ class NixlKVConnectorStats(KVConnectorStats):
# and notification failures are grouped as sporadic
# lower-transport-layer events, while KV expiry is reported separately
# as it is an actionable autoscaler signal rather than a transport
# issue.
# issue. Notifications arriving after expiry are surfaced too, as the
# reader may have consumed KV blocks that were already reused.
failure_counts = {
"Num failed transfers": len(self.data["num_failed_transfers"])
+ len(self.data["num_failed_handshakes"])
+ len(self.data["num_failed_notifications"]),
"Num KV expired reqs": len(self.data["num_kv_expired_reqs"]),
"Num notifs after expiry": len(self.data["num_notifications_after_expiry"]),
}
if self.num_successful_transfers == 0:
# Timing / throughput stats only cover successful transfers. If
@@ -262,6 +270,18 @@ class NixlPromMetrics(KVConnectorPromMetrics):
counter_nixl_num_kv_expired_reqs, self.per_engine_labelvalues
)
counter_nixl_num_notifications_after_expiry = self._counter_cls(
name="vllm:nixl_num_notifications_after_expiry",
documentation="Number of completion notifications for requests that "
"were no longer tracked, usually because their KV lease expired. The "
"KV blocks may have been reused before the transfer finished. Counted "
"per notification (one per remote rank), not per request.",
labelnames=labelnames,
)
self.counter_nixl_num_notifications_after_expiry = create_metric_per_engine(
counter_nixl_num_notifications_after_expiry, self.per_engine_labelvalues
)
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
for prom_obj, list_item_key in zip(
[
@@ -284,6 +304,7 @@ class NixlPromMetrics(KVConnectorPromMetrics):
self.counter_nixl_num_failed_transfers,
self.counter_nixl_num_failed_notifications,
self.counter_nixl_num_kv_expired_reqs,
self.counter_nixl_num_notifications_after_expiry,
],
[
# Transfer, handshake and notification failures are grouped:
@@ -297,6 +318,7 @@ class NixlPromMetrics(KVConnectorPromMetrics):
),
("num_failed_notifications",),
("num_kv_expired_reqs",),
("num_notifications_after_expiry",),
],
):
for counter_item_key in counter_item_keys:
@@ -157,15 +157,10 @@ def build_offloading_config(
)
replicated_layout = (
vllm_config.model_config.use_mla
# Exact type: fail closed on wrappers and sliding-window variants.
and type(single_group_spec) is MLAAttentionSpec
# Page accounting: one MLA page per layer, no packed/mixed rows.
and worker_kv_bytes_per_block > 0
and worker_kv_bytes_per_block
== single_group_spec.page_size_bytes
* len(kv_cache_config.kv_cache_groups[0].layer_names)
# Safe MVP boundary: TP-only, no other parallel axes.
and parallel_config.tensor_parallel_size > 1
and kv_cache_config.kv_tp_replicas == parallel_config.tensor_parallel_size
and worker_kv_bytes_per_block > 0
# Safe MVP boundary: TP-only, no other parallel axes.
and parallel_config.pipeline_parallel_size == 1
and parallel_config.prefill_context_parallel_size == 1
and parallel_config.decode_context_parallel_size == 1
@@ -233,9 +228,10 @@ def build_offloading_config(
and parallel_config.world_size == tp_size
)
if canonical_layout and is_parallelism_agnostic:
if canonical_layout:
replicated_layout = (
all(
is_parallelism_agnostic
and all(
type(spec) is MLAAttentionSpec
for _, group in selected_groups
for spec in iter_layer_specs(group.kv_cache_spec)
@@ -31,6 +31,7 @@ from vllm.v1.core.kv_cache_utils import (
BlockHash,
maybe_convert_block_hash,
resolve_block_hashes,
to_event_extra_keys,
)
from vllm.v1.kv_cache_interface import (
KVCacheGroupSpec,
@@ -393,9 +394,7 @@ class OffloadingEventsTracker:
lora_id=meta.lora_id,
medium=_MEDIUM_TO_EVENT_STR[event.medium],
lora_name=meta.lora_name,
extra_keys=(
list(meta.extra_keys) if meta.extra_keys is not None else None
),
extra_keys=to_event_extra_keys(meta.extra_keys),
group_idx=meta.group_idx,
kv_cache_spec_kind=meta.kv_cache_spec.kv_cache_spec_kind,
kv_cache_spec_sliding_window=(
@@ -156,7 +156,7 @@ def resolve_mamba_align_size(
"""Scan all KV cache groups in *spec* and return the single mamba alignment
size, or None if no group requires mamba alignment.
For MambaSpec groups in "align" or "all" cache mode the hit window must be
For MambaSpec groups in "align" cache mode the hit window must be
rounded down to a multiple of the offloaded chunk size. Asserts that all
such groups agree on the same value.
"""
@@ -164,10 +164,7 @@ def resolve_mamba_align_size(
for group in spec.config.groups:
tokens_per_block = group.tokens_per_block
kv_spec = kv_cache_config.kv_cache_groups[group.group_id].kv_cache_spec
if isinstance(kv_spec, MambaSpec) and kv_spec.mamba_cache_mode in (
"align",
"all",
):
if isinstance(kv_spec, MambaSpec) and kv_spec.mamba_cache_mode == "align":
tokens_per_chunk = tokens_per_block * spec.blocks_per_chunk
assert mamba_align_size is None or mamba_align_size == tokens_per_chunk
mamba_align_size = tokens_per_chunk
@@ -250,6 +250,13 @@ WeightTransferEngineFactory.register_engine(
)
WeightTransferEngineFactory.register_engine(
"modelexpress",
"vllm.distributed.weight_transfer.modelexpress_engine",
"ModelExpressWeightTransferEngine",
)
# Trainer-side engines, parallel to the worker registry above.
WeightTransferTrainerFactory.register_engine(
"nccl",
@@ -0,0 +1,41 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Re-export the weight-transfer backend maintained by ModelExpress.
Install ModelExpress from the main branch's modelexpress_client/python
subdirectory.
"""
try:
from modelexpress import configure_vllm_logging
from modelexpress_rl.inference.engines.vllm.weight_transfer_engine import (
ModelExpressWeightTransferEngine,
ModelExpressWeightTransferInitInfo,
ModelExpressWeightTransferUpdateInfo,
)
except ModuleNotFoundError as exc:
if exc.name not in {
"modelexpress",
"modelexpress_rl",
"modelexpress_rl.inference",
"modelexpress_rl.inference.engines",
"modelexpress_rl.inference.engines.vllm",
"modelexpress_rl.inference.engines.vllm.weight_transfer_engine",
}:
raise
raise ImportError(
"The 'modelexpress' weight transfer backend requires ModelExpress. "
"Install it with `uv pip install "
"'git+https://github.com/ai-dynamo/modelexpress@main"
"#subdirectory=modelexpress_client/python'`."
) from exc
configure_vllm_logging()
__all__ = [
"ModelExpressWeightTransferEngine",
"ModelExpressWeightTransferInitInfo",
"ModelExpressWeightTransferUpdateInfo",
]
@@ -26,6 +26,7 @@ from vllm.distributed.weight_transfer.packed_tensor import (
DEFAULT_PACKED_BUFFER_SIZE_BYTES,
DEFAULT_PACKED_NUM_BUFFERS,
)
from vllm.utils.nccl import unpinned_nccl_env
def decode_nccl_unique_id(
@@ -154,7 +155,8 @@ def stateless_init_process_group(
pg = StatelessProcessGroup.create(
host=master_address, port=master_port, rank=rank, world_size=world_size
)
return PyNcclCommunicator(pg, device=device)
with unpinned_nccl_env():
return PyNcclCommunicator(pg, device=device)
def uid_init_process_group(
@@ -170,12 +172,13 @@ def uid_init_process_group(
"""
from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
return PyNcclCommunicator.from_unique_id_bytes(
nccl_unique_id_bytes,
rank=rank,
world_size=world_size,
device=device,
)
with unpinned_nccl_env():
return PyNcclCommunicator.from_unique_id_bytes(
nccl_unique_id_bytes,
rank=rank,
world_size=world_size,
device=device,
)
def worker_init_process_group(
+8
View File
@@ -723,6 +723,9 @@ class EngineArgs:
kv_cache_metrics_sample: float = get_field(
ObservabilityConfig, "kv_cache_metrics_sample"
)
custom_histogram_buckets: dict[str, list[float]] | None = (
ObservabilityConfig.custom_histogram_buckets
)
cudagraph_metrics: bool = ObservabilityConfig.cudagraph_metrics
enable_layerwise_nvtx_tracing: bool = (
ObservabilityConfig.enable_layerwise_nvtx_tracing
@@ -1633,6 +1636,10 @@ class EngineArgs:
"--kv-cache-metrics-sample",
**observability_kwargs["kv_cache_metrics_sample"],
)
observability_group.add_argument(
"--custom-histogram-buckets",
**observability_kwargs["custom_histogram_buckets"],
)
observability_group.add_argument(
"--cudagraph-metrics",
**observability_kwargs["cudagraph_metrics"],
@@ -2126,6 +2133,7 @@ class EngineArgs:
per_request_spec_decode_metrics=self.per_request_spec_decode_metrics,
kv_cache_metrics=self.kv_cache_metrics,
kv_cache_metrics_sample=self.kv_cache_metrics_sample,
custom_histogram_buckets=self.custom_histogram_buckets,
cudagraph_metrics=self.cudagraph_metrics,
enable_layerwise_nvtx_tracing=self.enable_layerwise_nvtx_tracing,
enable_mfu_metrics=self.enable_mfu_metrics,
+6 -2
View File
@@ -199,8 +199,8 @@ class EngineClient(ABC):
...
@abstractmethod
async def wake_up(self, tags: list[str] | None = None) -> None:
"""Wake up the engine."""
async def wake_up(self, tags: list[str] | None = None) -> bool:
"""Wake the tagged resources; return whether every engine is fully awake."""
...
@abstractmethod
@@ -268,6 +268,10 @@ class EngineClient(ABC):
"""Perform a collective RPC call to the given path."""
raise NotImplementedError
async def compute_weight_checksums(self) -> list[dict[str, str]]:
"""Return rank-qualified weight digests from every worker of every engine."""
raise NotImplementedError
async def handle_fault(
self, fault_tolerance_request: FaultToleranceRequest
) -> FaultToleranceResult:
+62
View File
@@ -44,6 +44,8 @@ class AnthropicContentBlock(BaseModel):
"tool_reference",
"thinking",
"redacted_thinking",
"tool_addition",
"tool_removal",
]
text: str | None = None
# For image content
@@ -62,6 +64,28 @@ class AnthropicContentBlock(BaseModel):
signature: str | None = None
# For redacted thinking content (safety-filtered by the API)
data: str | None = None
# For tool_addition/tool_removal content
tool: "AnthropicToolChange | None" = None
@model_validator(mode="after")
def validate_tool_change(self) -> "AnthropicContentBlock":
if self.type not in ("tool_addition", "tool_removal"):
return self
if self.tool is None:
raise ValueError(f"tool is required for {self.type} blocks")
if self.type == "tool_removal" and self.tool.type != "tool_reference":
raise ValueError("tool_removal only accepts a tool_reference")
return self
def _reject_tool_changes(content: str | list[AnthropicContentBlock] | None) -> None:
if content is None or isinstance(content, str):
return
for block in content:
if block.type in ("tool_addition", "tool_removal"):
raise ValueError(
f'{block.type} blocks are only allowed in messages with role "system"'
)
class AnthropicMessage(BaseModel):
@@ -70,6 +94,12 @@ class AnthropicMessage(BaseModel):
role: Literal["user", "assistant", "system"]
content: str | list[AnthropicContentBlock]
@model_validator(mode="after")
def validate_tool_change_role(self) -> "AnthropicMessage":
if self.role != "system":
_reject_tool_changes(self.content)
return self
class AnthropicTool(BaseModel):
"""Tool definition."""
@@ -90,6 +120,26 @@ class AnthropicTool(BaseModel):
return v
class AnthropicToolChangeReference(BaseModel):
"""A tool named by a tool_addition or tool_removal block."""
type: Literal["tool_reference"]
name: str
class AnthropicToolChangeDefinition(BaseModel):
"""A tool defined by value in a tool_addition block."""
type: Literal["tool_definition"]
definition: AnthropicTool
AnthropicToolChange = Annotated[
AnthropicToolChangeReference | AnthropicToolChangeDefinition,
Field(discriminator="type"),
]
class AnthropicToolChoice(BaseModel):
"""Tool Choice definition."""
@@ -231,6 +281,12 @@ class AnthropicMessagesRequest(BaseModel):
raise ValueError("max_tokens must be positive")
return v
@field_validator("system")
@classmethod
def validate_system(cls, v):
_reject_tool_changes(v)
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
@@ -343,6 +399,12 @@ class AnthropicCountTokensRequest(BaseModel):
raise ValueError("Model is required")
return v
@field_validator("system")
@classmethod
def validate_system(cls, v):
_reject_tool_changes(v)
return v
class AnthropicCountTokensResponse(BaseModel):
"""Anthropic messages.count_tokens response."""
+124 -32
View File
@@ -10,7 +10,7 @@ import logging
import time
import uuid
from collections.abc import AsyncGenerator
from typing import Any, get_args
from typing import Any, Literal, get_args
import jinja2
from fastapi import Request
@@ -31,6 +31,8 @@ from vllm.entrypoints.anthropic.protocol import (
AnthropicOutputConfig,
AnthropicStreamEvent,
AnthropicThinkingConfig,
AnthropicTool,
AnthropicToolChangeDefinition,
AnthropicUsage,
)
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
@@ -97,6 +99,46 @@ def _build_anthropic_usage(
return AnthropicUsage(**kwargs)
def _to_anthropic_stop_reason(
finish_reason: str | None,
stop_reason: int | str | None,
tool_used: bool,
tool_complete: bool,
) -> tuple[
Literal["end_turn", "max_tokens", "stop_sequence", "tool_use"] | None,
str | None,
]:
"""Map an OpenAI finish reason to Anthropic ``(stop_reason, stop_sequence)``.
Anthropic reports ``tool_use`` whenever the model invoked a tool. The chat
layer reports ``finish_reason="stop"`` for a named (forced) tool call, so
``tool_used`` records whether a ``tool_use`` block was produced.
``max_tokens`` always wins. A matched stop string wins unless the tool
calls are complete (``tool_complete``): a call it cut short must not run.
"""
if finish_reason == "length":
return "max_tokens", None
if finish_reason not in ("stop", "tool_calls"):
return None, None
if tool_complete:
return "tool_use", None
# vLLM reports the matched stop string in stop_reason (a str);
# an int stop-token-id or None (natural EOS) is not a stop sequence.
if isinstance(stop_reason, str):
return "stop_sequence", stop_reason
if finish_reason == "tool_calls" or tool_used:
return "tool_use", None
return "end_turn", None
def _is_json(text: str) -> bool:
try:
json.loads(text)
except json.JSONDecodeError:
return False
return True
def wrap_data_with_event(data: str, event: str):
return f"event: {event}\ndata: {data}\n\n"
@@ -141,11 +183,6 @@ class AnthropicServingMessages(OpenAIServingChat):
enable_force_include_usage=enable_force_include_usage,
default_chat_template_kwargs=default_chat_template_kwargs,
)
self.stop_reason_map = {
"stop": "end_turn",
"length": "max_tokens",
"tool_calls": "tool_use",
}
self._merge_inline_system = self._should_merge_inline_system(online_renderer)
# Resolved lazily from the renderer when "auto".
self._disabled_thinking_effort: AnthropicDisabledThinkingEffort | None = (
@@ -218,7 +255,7 @@ class AnthropicServingMessages(OpenAIServingChat):
for tools in tool_variants
)
if merge:
logger.warning(
logger.warning_once(
"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. "
@@ -675,6 +712,51 @@ class AnthropicServingMessages(OpenAIServingChat):
}
)
@classmethod
def _resolve_tools(
cls,
anthropic_request: AnthropicMessagesRequest | AnthropicCountTokensRequest,
) -> list[AnthropicTool] | None:
"""Apply tool_addition/tool_removal blocks in ``messages`` to ``tools``.
Chat templates see a single tool list, so this resolves the tools in
effect at the end of the conversation: a tool added by reference is no
longer deferred, a tool added by value is declared, and a removed tool
is dropped.
"""
changes = [
block
for msg in anthropic_request.messages
if not isinstance(msg.content, str)
for block in msg.content
if block.type in ("tool_addition", "tool_removal")
]
if not changes:
return anthropic_request.tools
tools = {tool.name: tool for tool in anthropic_request.tools or []}
removed: set[str] = set()
for block in changes:
change = block.tool
assert change is not None
if isinstance(change, AnthropicToolChangeDefinition):
name = change.definition.name
tools[name] = change.definition
else:
name = change.name
if name not in tools:
raise ValueError(
f"{block.type} references tool {name!r}, "
"which is not declared in tools"
)
if block.type == "tool_addition":
tools[name] = tools[name].model_copy(update={"defer_loading": None})
if block.type == "tool_removal":
removed.add(name)
else:
removed.discard(name)
return [tool for name, tool in tools.items() if name not in removed]
@classmethod
def _convert_tools(
cls,
@@ -682,11 +764,12 @@ class AnthropicServingMessages(OpenAIServingChat):
req: ChatCompletionRequest,
) -> None:
"""Convert Anthropic tools to OpenAI format."""
if anthropic_request.tools is None:
anthropic_tools = cls._resolve_tools(anthropic_request)
if anthropic_tools is None:
return
tools = []
for tool in anthropic_request.tools:
for tool in anthropic_tools:
tools.append(
ChatCompletionToolsParam.model_validate(
{
@@ -751,18 +834,13 @@ class AnthropicServingMessages(OpenAIServingChat):
ec_transfer_params=generator.ec_transfer_params,
)
choice = generator.choices[0]
if choice.finish_reason == "stop":
# vLLM reports the matched stop string in stop_reason (a str);
# an int stop-token-id or None (natural EOS) maps to end_turn.
if isinstance(choice.stop_reason, str):
result.stop_reason = "stop_sequence"
result.stop_sequence = choice.stop_reason
else:
result.stop_reason = "end_turn"
elif choice.finish_reason == "length":
result.stop_reason = "max_tokens"
elif choice.finish_reason == "tool_calls":
result.stop_reason = "tool_use"
result.stop_reason, result.stop_sequence = _to_anthropic_stop_reason(
choice.finish_reason,
choice.stop_reason,
tool_used=bool(choice.message.tool_calls),
# Their arguments are json-decoded below, so parsed calls are complete.
tool_complete=bool(choice.message.tool_calls),
)
content: list[AnthropicContentBlock] = []
if choice.message.reasoning:
@@ -845,6 +923,10 @@ class AnthropicServingMessages(OpenAIServingChat):
# Matched stop string, when generation stopped on one (a str);
# int stop-token-id / None are not stop sequences.
stop_sequence: int | str | None = None
tool_used = False
# Arguments of the latest tool_use block; only the last call can be
# cut short by a stop string.
last_tool_args: list[str] = []
state = _ActiveBlockState()
# Map from tool call index to tool_use_id
tool_index_to_id: dict[int, str] = {}
@@ -954,19 +1036,21 @@ class AnthropicServingMessages(OpenAIServingChat):
if len(origin_chunk.choices) == 0:
for event in stop_and_flush():
yield event
if isinstance(stop_sequence, str):
stop_delta = AnthropicDelta(
stop_reason="stop_sequence",
stop_sequence=stop_sequence,
)
else:
stop_delta = AnthropicDelta(
stop_reason=self.stop_reason_map.get(
finish_reason or "stop"
anthropic_stop_reason, anthropic_stop_sequence = (
_to_anthropic_stop_reason(
finish_reason or "stop",
stop_sequence,
tool_used=tool_used,
tool_complete=(
tool_used and _is_json("".join(last_tool_args))
),
# Set explicitly so exclude_unset=True keeps it.
stop_sequence=None,
)
)
stop_delta = AnthropicDelta(
stop_reason=anthropic_stop_reason,
# Set explicitly so exclude_unset=True keeps it.
stop_sequence=anthropic_stop_sequence,
)
chunk = AnthropicStreamEvent(
type="message_delta",
delta=stop_delta,
@@ -1060,6 +1144,8 @@ class AnthropicServingMessages(OpenAIServingChat):
):
for event in stop_and_flush():
yield event
tool_used = True
last_tool_args = []
start_event = start_block(
AnthropicContentBlock(
type="tool_use",
@@ -1075,6 +1161,9 @@ class AnthropicServingMessages(OpenAIServingChat):
and tool_call.function.arguments
and state.tool_use_id == tool_call.id
):
last_tool_args.append(
tool_call.function.arguments
)
chunk = AnthropicStreamEvent(
index=(
state.block_index
@@ -1100,6 +1189,9 @@ class AnthropicServingMessages(OpenAIServingChat):
and tool_call.function.arguments
and state.tool_use_id == tool_use_id
):
last_tool_args.append(
tool_call.function.arguments
)
chunk = AnthropicStreamEvent(
index=(
state.block_index
+63
View File
@@ -1814,6 +1814,32 @@ PART_TYPES_TO_SKIP_NONE_CONTENT = (
TEXT_PART_TYPES = frozenset(
{"text", "input_text", "output_text", "refusal", "thinking"}
)
# Content part types that carry no multimodal data.
_TEXT_CONTENT_PART_TYPES = TEXT_PART_TYPES | {"tool_reference"}
# Keys that mark a content part as multimodal, whatever its ``type``.
_MEDIA_CONTENT_PART_KEYS = frozenset(MM_PARSER_MAP) - _TEXT_CONTENT_PART_TYPES
def has_non_text_content(messages: Any) -> bool:
"""Whether any message in ``messages`` has a non-text content part.
Only list content is inspected, so validated chat content that is a
one-shot iterator is never consumed.
"""
if not isinstance(messages, list):
return False
for msg in messages:
content = msg.get("content") if isinstance(msg, dict) else None
if not isinstance(content, list):
continue
for part in content:
if isinstance(part, dict) and (
any(key in part for key in _MEDIA_CONTENT_PART_KEYS)
or not isinstance(part_type := part.get("type", "text"), str)
or part_type not in _TEXT_CONTENT_PART_TYPES
):
return True
return False
def _parse_chat_message_content_parts(
@@ -2009,6 +2035,41 @@ _AssistantParser = partial(cast, ChatCompletionAssistantMessageParam)
_ToolParser = partial(cast, ChatCompletionToolMessageParam)
_CLAUDE_CODE_BILLING_HEADER = "x-anthropic-billing-header"
def _strip_claude_code_billing_header(
parts: Iterable[ChatCompletionContentPartParam],
) -> list[ChatCompletionContentPartParam]:
"""Drop Claude Code's attribution header line from system text parts.
Its ``cch`` value changes on every request, so a prompt that keeps it
misses the prefix cache from the header on. Gateways that translate
Anthropic requests to chat completions keep it; ``/v1/messages`` drops
the same block.
"""
out: list[ChatCompletionContentPartParam] = []
for part in parts:
if isinstance(part, str):
text: object = part
elif isinstance(part, dict) and part.get("type") == "text":
text = part.get("text")
else:
text = None
if not (isinstance(text, str) and text.startswith(_CLAUDE_CODE_BILLING_HEADER)):
out.append(part)
continue
rest = text.partition("\n")[2]
if not rest:
continue
out.append(
cast(ChatCompletionContentPartParam, rest)
if isinstance(part, str)
else cast(ChatCompletionContentPartParam, {**part, "text": rest})
)
return out
def _parse_chat_message_content(
message: ChatCompletionMessageParam,
mm_tracker: BaseMultiModalItemTracker,
@@ -2024,6 +2085,8 @@ def _parse_chat_message_content(
content = []
elif isinstance(content, str):
content = [ChatCompletionContentPartTextParam(type="text", text=content)]
if role == "system":
content = _strip_claude_code_billing_header(content) # type: ignore[arg-type]
result = _parse_chat_message_content_parts(
role,
content, # type: ignore
+16 -6
View File
@@ -170,6 +170,7 @@ class PreloadSubcommand(CLISubcommand):
parallel_config = vllm_config.parallel_config
_reject_unsupported_parallelism(parallel_config)
tp_size = parallel_config.tensor_parallel_size
pp_size = parallel_config.pipeline_parallel_size
dp_size = parallel_config.data_parallel_size
placements = plan_local_ranks(parallel_config)
@@ -230,16 +231,21 @@ class PreloadSubcommand(CLISubcommand):
ctx = multiprocessing.get_context("spawn")
ready_queue: multiprocessing.Queue[tuple[str, int]] = ctx.Queue()
# Local index == device index; global rank enumerates DP then TP.
# Local index == device index; global rank enumerates DP, PP, 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)
(
format_daemon_role(is_draft),
dp_rank * pp_size * tp_size + pp_rank * tp_size + tp_rank,
)
for (is_draft, _, _), (_, dp_rank, pp_rank, tp_rank) in product(
groups, placements
)
}
procs = [
ctx.Process(
target=_run_daemon,
args=(
tp_rank,
dp_rank * pp_size * tp_size + pp_rank * tp_size + tp_rank,
local_rank,
config,
init_method,
@@ -247,13 +253,17 @@ class PreloadSubcommand(CLISubcommand):
ready_queue,
is_draft,
dp_rank,
pp_rank,
),
name=(
f"vllm-weight-cache-{format_daemon_role(is_draft)}-"
f"{(dp_rank * pp_size * tp_size + pp_rank * tp_size + tp_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,
pp_rank,
tp_rank,
) in product(groups, placements)
]
+12
View File
@@ -13,9 +13,11 @@ from vllm.entrypoints.cli.types import CLISubcommand
from vllm.entrypoints.launchers.api_server.entry import run_server, setup_server
from vllm.entrypoints.launchers.cli_args import (
make_arg_parser,
propagate_flash_late_interaction,
validate_parsed_serve_args,
)
from vllm.entrypoints.launchers.dp_supervisor import run_dp_supervisor
from vllm.entrypoints.launchers.launcher import create_server_socket
from vllm.entrypoints.serve.utils.api_utils import VLLM_SUBCMD_PARSER_EPILOG
from vllm.logger import init_logger
from vllm.reasoning import ReasoningParserManager
@@ -185,6 +187,7 @@ def run_headless(args: argparse.Namespace):
# Create the EngineConfig.
engine_args = vllm.AsyncEngineArgs.from_cli_args(args)
propagate_flash_late_interaction(args, engine_args)
usage_context = UsageContext.OPENAI_API_SERVER
vllm_config = engine_args.create_engine_config(
usage_context=usage_context, headless=True
@@ -293,8 +296,16 @@ def run_multi_api_server(args: argparse.Namespace):
signal.signal(signal.SIGINT, signal_handler)
listen_address, sock = setup_server(args, reuse_port=num_api_servers > 1)
# `--grpc-port` is only accepted for the Rust frontend, which inherits this
# listener like the HTTP one. gRPC follows the HTTP TCP host, or IPv4
# loopback when HTTP uses a Unix socket.
grpc_sock = None
if args.grpc_port is not None:
grpc_host = "127.0.0.1" if args.uds else (args.host or "")
grpc_sock = create_server_socket((grpc_host, args.grpc_port), reuse_port=False)
engine_args = vllm.AsyncEngineArgs.from_cli_args(args)
propagate_flash_late_interaction(args, engine_args)
engine_args._api_process_count = num_api_servers
engine_args._api_process_rank = -1
@@ -352,6 +363,7 @@ def run_multi_api_server(args: argparse.Namespace):
api_server_manager = RustFrontendProcessManager(
binary_path=rust_frontend_path,
sock=sock,
grpc_sock=grpc_sock,
args=args,
input_address=addresses.inputs[0],
output_address=addresses.outputs[0],
@@ -51,6 +51,9 @@ async def build_async_engine_client(
# Context manager to handle engine_client lifecycle
# Ensures everything is shutdown and cleaned up on error/exit
engine_args = AsyncEngineArgs.from_cli_args(args)
from ..cli_args import propagate_flash_late_interaction
propagate_flash_late_interaction(args, engine_args)
if client_config:
engine_args._api_process_count = client_config.get("client_count", 1)
engine_args._api_process_rank = client_config.get("client_index", 0)
+75 -3
View File
@@ -22,6 +22,7 @@ from vllm.entrypoints.chat_utils import (
validate_chat_template,
)
from vllm.entrypoints.openai.models.protocol import LoRAModulePath
from vllm.logger import init_logger
from vllm.tool_parsers import ToolParserManager
from vllm.tool_parsers.tool_strict_level import ToolStrictLevelName
from vllm.utils.argparse_utils import FlexibleArgumentParser
@@ -31,6 +32,8 @@ from .utils.constants import (
H11_MAX_INCOMPLETE_EVENT_SIZE_DEFAULT,
)
logger = init_logger(__name__)
class LoRAParserAction(argparse.Action):
def __call__(
@@ -281,6 +284,11 @@ class FrontendArgs(BaseFrontendArgs):
"""Host name."""
port: int = 8000
"""Port number."""
grpc_port: int | None = None
"""Enable the Rust frontend's additional gRPC Inference and Control services
on this port. Requires `VLLM_USE_RUST_FRONTEND=1 vllm serve`; HTTP remains on
`--port`. Binds on `--host`, or 127.0.0.1 with `--uds`. Cannot be combined
with the Python gRPC server's `--grpc` flag."""
data_parallel_supervisor_port: int = 9256
"""HTTP port for aggregated health endpoints in multi-port external LB
mode."""
@@ -363,7 +371,10 @@ class FrontendArgs(BaseFrontendArgs):
"""
enable_flash_late_interaction: bool = True
"""If set, run pooling score MaxSim on GPU in the API server process.
Can significantly improve late-interaction scoring performance."""
Can significantly improve late-interaction scoring performance.
When disabled, the setting is also propagated to the engine's
`PoolerConfig`, so the engine-side scorer uses the reference MaxSim
path instead of the fused Triton kernel."""
@classmethod
def _customize_cli_kwargs(
@@ -445,8 +456,10 @@ def make_arg_parser(parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
"--grpc",
action="store_true",
default=False,
help="Launch a gRPC server instead of the HTTP OpenAI-compatible "
"server. Requires: pip install vllm[grpc].",
help="Launch the Python gRPC (SMG VllmEngine) server on --port instead "
"of the HTTP OpenAI-compatible server. Requires: pip install vllm[grpc]. "
"Cannot be combined with --grpc-port, which enables the Rust "
"frontend's gRPC services.",
)
parser = FrontendArgs.add_cli_args(parser)
parser = AsyncEngineArgs.add_cli_args(parser)
@@ -454,6 +467,38 @@ def make_arg_parser(parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
return parser
def validate_grpc_port_arg(args: argparse.Namespace) -> None:
"""Validate the Rust frontend's optional gRPC listener."""
if getattr(args, "grpc_port", None) is None:
return
if args.grpc:
raise ValueError(
"--grpc and --grpc-port are mutually exclusive. Use --grpc "
"--port for the Python gRPC server, or VLLM_USE_RUST_FRONTEND=1 "
"with --grpc-port for the Rust frontend."
)
if not envs.VLLM_USE_RUST_FRONTEND or getattr(args, "subparser", None) != "serve":
raise ValueError("--grpc-port requires VLLM_USE_RUST_FRONTEND=1 vllm serve")
if args.headless or (
args.api_server_count is not None and args.api_server_count <= 0
):
raise ValueError(
"--grpc-port requires a Rust frontend; remove --headless "
"and non-positive --api-server-count"
)
if args.data_parallel_multi_port_external_lb:
raise ValueError(
"--grpc-port is incompatible with "
"--data-parallel-multi-port-external-lb: "
"its frontends would share the same gRPC port"
)
if not 0 <= args.grpc_port <= 65535:
raise ValueError("--grpc-port must be between 0 and 65535")
if args.grpc_port != 0 and args.grpc_port == args.port and not args.uds:
raise ValueError("--grpc-port must differ from --port when HTTP uses TCP")
def validate_parsed_serve_args(args: argparse.Namespace):
"""Quick checks for model serve args that raise prior to loading."""
# `vllm launch <component>` builds its parser with make_arg_parser too (see
@@ -463,6 +508,16 @@ def validate_parsed_serve_args(args: argparse.Namespace):
# Ensure that the chat template is valid; raises if it likely isn't
validate_chat_template(args.chat_template)
if args.chat_template is not None and "hf" in (
args.tool_call_parser,
getattr(args, "reasoning_parser", None),
):
logger.warning(
"--chat-template is set; the hf parser still expects "
"the checkpoint's output format."
)
validate_grpc_port_arg(args)
# Enable auto tool needs a tool call parser to be valid
if args.enable_auto_tool_choice and not args.tool_call_parser:
@@ -498,3 +553,20 @@ def create_parser_for_docs() -> FlexibleArgumentParser:
prog="-m vllm.entrypoints.launchers.api_server.entry"
)
return make_arg_parser(parser_for_docs)
def propagate_flash_late_interaction(args, engine_args) -> None:
"""Propagate `--no-enable-flash-late-interaction` into the engine config.
The frontend flag alone only disables the API-server scoring path;
mirroring it into `PoolerConfig.enable_flash_late_interaction` lets the
engine-side scorer fall back to the reference MaxSim path too.
"""
if getattr(args, "enable_flash_late_interaction", True):
return
from vllm.config.pooler import PoolerConfig
if engine_args.pooler_config is None:
engine_args.pooler_config = PoolerConfig(enable_flash_late_interaction=False)
else:
engine_args.pooler_config.enable_flash_late_interaction = False
@@ -8,6 +8,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from vllm import envs
from vllm.config.logging import LogFormatter
from vllm.engine.protocol import EngineClient
from vllm.logger import init_logger
from vllm.utils.gc_utils import freeze_gc_heap
@@ -33,8 +34,8 @@ def get_uvicorn_log_config(args: Namespace) -> dict | None:
Priority:
1. If log_config_file is specified, use it
2. If disable_access_log_for_endpoints is specified, create a config with
the access log filter
2. If disable_access_log_for_endpoints or JSON formatting is specified,
create a config with the requested filter and format
3. Otherwise, return None (use uvicorn defaults)
"""
# First, try to load from file if specified
@@ -48,19 +49,21 @@ def get_uvicorn_log_config(args: Namespace) -> dict | None:
if log_config is not None:
return log_config
# If endpoints to filter are specified, create a config with the filter
if args.disable_access_log_for_endpoints:
formatter: LogFormatter = (
logging_config.formatter if logging_config is not None else "text"
)
if args.disable_access_log_for_endpoints or formatter == "json":
from vllm.logging_utils import create_uvicorn_log_config
# Parse comma-separated string into list
excluded_paths = [
p.strip()
for p in args.disable_access_log_for_endpoints.split(",")
for p in (args.disable_access_log_for_endpoints or "").split(",")
if p.strip()
]
return create_uvicorn_log_config(
excluded_paths=excluded_paths,
log_level=args.uvicorn_log_level,
formatter=formatter,
)
return None
+5 -2
View File
@@ -839,7 +839,7 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
"""
self.llm_engine.release_kv_cache_memory()
def wake_up(self, tags: list[str] | None = None):
def wake_up(self, tags: list[str] | None = None) -> bool:
"""Wake up the engine from sleep mode. See the [sleep][vllm.LLM.sleep]
method for more details.
@@ -851,8 +851,11 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
(or None) before the engine is used again.
Use tags=["scheduling"] to resume from level 0 sleep.
Returns:
Whether the engine is fully awake.
"""
self.llm_engine.wake_up(tags)
return self.llm_engine.wake_up(tags)
def get_metrics(self) -> list["Metric"]:
"""Return a snapshot of aggregated metrics from Prometheus.
+1 -1
View File
@@ -173,7 +173,7 @@ class HarmonyPythonTool(Tool):
processed = ResponseFunctionToolCallOutputItem(
id=f"fco_{random_uuid()}",
type="function_call_output",
call_id=f"call_{random_uuid()}",
call_id=last_msg.call_id,
output=msg.content[0].text,
status="completed",
)
@@ -129,17 +129,6 @@ class OpenAIServingChatBatch(OpenAIServingChat):
return render_result
single_requests, all_conversations, engine_prompts = render_result
parser: Parser | None = None
if self.parser_cls is not None:
chat_template_kwargs = self._effective_chat_template_kwargs(
single_requests[0]
)
parser = self.parser_cls(
tokenizer,
None, # tools
chat_template_kwargs=chat_template_kwargs,
)
request_id = (
f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
)
@@ -202,7 +191,7 @@ class OpenAIServingChatBatch(OpenAIServingChat):
all_conversations,
tokenizer,
request_metadata,
parser,
self.parser_cls,
)
async def chat_completion_full_generator_batch(
@@ -214,7 +203,7 @@ class OpenAIServingChatBatch(OpenAIServingChat):
all_conversations: list[list[ConversationMessage]],
tokenizer: TokenizerLike,
request_metadata: RequestResponseMetadata,
parser: Parser | None = None,
parser_cls: type[Parser] | None = None,
) -> ErrorResponse | ChatCompletionResponse:
"""Handle batched (non-streaming) chat completions.
@@ -273,10 +262,21 @@ class OpenAIServingChatBatch(OpenAIServingChat):
else:
logprobs = None
if parser is not None:
if parser_cls is not None:
single_request = request.to_chat_completion_request(
request.messages[prompt_idx]
)
parser = parser_cls(
tokenizer,
None,
chat_template_kwargs=self._effective_chat_template_kwargs(
single_request
),
)
parser.set_prompt_token_ids(final_res.prompt_token_ids)
reasoning, content, _ = parser.parse(
output.text,
request=request, # type: ignore[arg-type]
request=single_request,
model_output_token_ids=output.token_ids,
)
if not request.include_reasoning:
@@ -20,10 +20,9 @@ from pydantic import (
from vllm.config import ModelConfig
from vllm.entrypoints.chat_utils import (
MM_PARSER_MAP,
TEXT_PART_TYPES,
ChatCompletionMessageParam,
ChatTemplateContentFormatOption,
has_non_text_content,
)
from vllm.entrypoints.generate.base.protocol import (
AnyResponseFormat,
@@ -60,11 +59,6 @@ logger = init_logger(__name__)
_INT64_MIN = -(2**63)
_INT64_MAX = 2**63 - 1
# Content part types that carry no multimodal data.
_TEXT_CONTENT_PART_TYPES = TEXT_PART_TYPES | {"tool_reference"}
# Keys that mark a content part as multimodal, whatever its ``type``.
_MEDIA_CONTENT_PART_KEYS = frozenset(MM_PARSER_MAP) - _TEXT_CONTENT_PART_TYPES
class ChatMessage(OpenAIBaseModel):
role: str
@@ -991,29 +985,16 @@ class ChatCompletionRequest(OpenAIBaseModel):
if not isinstance(data, dict):
return data
kv_transfer_params = data.get("kv_transfer_params")
messages = data.get("messages")
if (
not isinstance(kv_transfer_params, dict)
or kv_transfer_params.get("prompt_token_ids") is None
or not isinstance(messages, list)
isinstance(kv_transfer_params, dict)
and kv_transfer_params.get("prompt_token_ids") is not None
and has_non_text_content(data.get("messages"))
):
return data
for msg in messages:
content = msg.get("content") if isinstance(msg, dict) else None
if not isinstance(content, list):
continue
for part in content:
if isinstance(part, dict) and (
any(key in part for key in _MEDIA_CONTENT_PART_KEYS)
or not isinstance(part_type := part.get("type", "text"), str)
or part_type not in _TEXT_CONTENT_PART_TYPES
):
logger.debug(
"Ignoring kv_transfer_params['prompt_token_ids']: "
"messages have non-text content and are rendered instead."
)
kv_transfer_params.pop("prompt_token_ids")
return data
logger.debug(
"Ignoring kv_transfer_params['prompt_token_ids']: "
"messages have non-text content and are rendered instead."
)
kv_transfer_params.pop("prompt_token_ids")
return data
@model_validator(mode="before")
@@ -165,6 +165,7 @@ class OpenAIServingChat(GenerateBaseServing):
tool_strict_level=tool_strict_level,
model_name=self.model_config.model,
is_harmony=self.model_config.hf_config.model_type == "gpt_oss",
tokenizer=self.renderer.tokenizer,
)
self.exclude_tools_when_tool_choice_none = exclude_tools_when_tool_choice_none
@@ -974,6 +975,8 @@ class OpenAIServingChat(GenerateBaseServing):
parser = self._make_parser(
request, tokenizer, self._effective_chat_template_kwargs(request)
)
if parser is not None and final_res.prompt_token_ids is not None:
parser.set_prompt_token_ids(final_res.prompt_token_ids)
token_ids = output.token_ids
out_logprobs = output.logprobs
+18
View File
@@ -212,6 +212,16 @@ class OpenAIServingModels:
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)
previous = self.lora_requests.get(lora_name)
if previous is not None and previous.lora_path == lora_path:
logger.warning(
"Reloaded LoRA adapter '%s' in place from the same path '%s'. "
"Prefix-cache blocks computed with its previous weights are "
"not invalidated; load changed weights from a new path to "
"avoid reusing them.",
lora_name,
lora_path,
)
self.lora_requests[lora_name] = lora_request
logger.info(
"Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path
@@ -245,6 +255,14 @@ class OpenAIServingModels:
status_code=HTTPStatus.BAD_REQUEST,
)
if self.is_base_model(request.lora_name):
return create_error_response(
message=f"The lora adapter '{request.lora_name}' conflicts with a "
"served base model.",
err_type="InvalidUserInput",
status_code=HTTPStatus.BAD_REQUEST,
)
# If not loading inplace
# Check if the lora adapter with the given name already exists
if not request.load_inplace and request.lora_name in self.lora_requests:
+22 -9
View File
@@ -24,7 +24,6 @@ from vllm import envs
from vllm.entrypoints.chat_utils import (
ChatTemplateContentFormatOption,
)
from vllm.entrypoints.generate.base.protocol import FunctionCall
from vllm.entrypoints.mcp.tool import Tool
from vllm.entrypoints.mcp.tool_server import ToolServer
from vllm.entrypoints.openai.parser.harmony_utils import render_for_completion
@@ -37,6 +36,9 @@ from vllm.entrypoints.openai.responses.utils import (
build_response_output_items,
construct_tool_dicts,
)
from vllm.entrypoints.serve.utils.tool_calls_utils import (
maybe_filter_parallel_tool_calls,
)
from vllm.outputs import RequestOutput
from vllm.parser.abstract_parser import Parser
from vllm.tokenizers import TokenizerLike
@@ -192,6 +194,9 @@ class SimpleContext(ConversationContext):
self._accumulated_text: str = ""
self._accumulated_token_ids: list[int] = []
self._accumulated_logprobs: list = []
# Items already sent as output_item.done events; the final
# streaming response reuses them instead of reparsing.
self.streamed_output_items: list[ResponseOutputItem] | None = None
self.num_prompt_tokens = 0
self.num_output_tokens = 0
@@ -369,7 +374,9 @@ class ParsableContext(ConversationContext):
build_response_output_items(
reasoning=reasoning,
content=content,
tool_calls=tool_calls,
tool_calls=maybe_filter_parallel_tool_calls(
tool_calls or [], self.request
),
tools=self.request.tools,
)
)
@@ -435,7 +442,9 @@ class ParsableContext(ConversationContext):
return False
async def call_python_tool(
self, tool_session: Union["ClientSession", Tool], last_msg: FunctionCall
self,
tool_session: Union["ClientSession", Tool],
last_msg: ResponseFunctionToolCall,
) -> list[ResponseInputOutputItem]:
self.called_tools.add("python")
if isinstance(tool_session, Tool):
@@ -450,7 +459,7 @@ class ParsableContext(ConversationContext):
message = ResponseFunctionToolCallOutputItem(
id=f"mcpo_{random_uuid()}",
type="function_call_output",
call_id=f"call_{random_uuid()}",
call_id=last_msg.call_id,
output=result_str,
status="completed",
)
@@ -458,7 +467,9 @@ class ParsableContext(ConversationContext):
return [message]
async def call_search_tool(
self, tool_session: Union["ClientSession", Tool], last_msg: FunctionCall
self,
tool_session: Union["ClientSession", Tool],
last_msg: ResponseFunctionToolCall,
) -> list[ResponseInputOutputItem]:
self.called_tools.add("browser")
if isinstance(tool_session, Tool):
@@ -476,7 +487,7 @@ class ParsableContext(ConversationContext):
message = ResponseFunctionToolCallOutputItem(
id=f"fco_{random_uuid()}",
type="function_call_output",
call_id=f"call_{random_uuid()}",
call_id=last_msg.call_id,
output=result_str,
status="completed",
)
@@ -484,8 +495,10 @@ class ParsableContext(ConversationContext):
return [message]
async def call_container_tool(
self, tool_session: Union["ClientSession", Tool], last_msg: Message
) -> list[Message]:
self,
tool_session: Union["ClientSession", Tool],
last_msg: ResponseFunctionToolCall,
) -> list[ResponseInputOutputItem]:
"""Call container tool. Expect this to be run in a stateful docker
with command line terminal.
The official container tool would at least
@@ -518,7 +531,7 @@ class ParsableContext(ConversationContext):
message = ResponseFunctionToolCallOutputItem(
id=f"fco_{random_uuid()}",
type="function_call_output",
call_id=f"call_{random_uuid()}",
call_id=last_msg.call_id,
output=result_str,
status="completed",
)
@@ -42,9 +42,6 @@ from openai.types.responses import (
ResponseInProgressEvent as OpenAIResponseInProgressEvent,
)
from openai.types.responses.response import IncompleteDetails, ToolChoice
from openai.types.responses.response_reasoning_item import (
Content as ResponseReasoningTextContent,
)
from openai.types.responses.tool import Tool
from openai.types.shared import Metadata, Reasoning
from openai_harmony import Message as OpenAIHarmonyMessage
@@ -845,50 +842,6 @@ class ResponsesResponse(OpenAIBaseModel):
)
# TODO: this code can be removed once
# https://github.com/openai/openai-python/issues/2634 has been resolved
class ResponseReasoningPartDoneEvent(OpenAIBaseModel):
content_index: int
"""The index of the content part that is done."""
item_id: str
"""The ID of the output item that the content part was added to."""
output_index: int
"""The index of the output item that the content part was added to."""
part: ResponseReasoningTextContent
"""The content part that is done."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.reasoning_part.done"]
"""The type of the event. Always `response.reasoning_part.done`."""
# TODO: this code can be removed once
# https://github.com/openai/openai-python/issues/2634 has been resolved
class ResponseReasoningPartAddedEvent(OpenAIBaseModel):
content_index: int
"""The index of the content part that is done."""
item_id: str
"""The ID of the output item that the content part was added to."""
output_index: int
"""The index of the output item that the content part was added to."""
part: ResponseReasoningTextContent
"""The content part that is done."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.reasoning_part.added"]
"""The type of the event. Always `response.reasoning_part.added`."""
# vLLM Streaming Events
# Note: we override the response type with the vLLM ResponsesResponse type
class ResponseCompletedEvent(OpenAIResponseCompletedEvent):
@@ -913,8 +866,6 @@ StreamingResponsesResponse: TypeAlias = (
| ResponseContentPartDoneEvent
| ResponseReasoningTextDeltaEvent
| ResponseReasoningTextDoneEvent
| ResponseReasoningPartAddedEvent
| ResponseReasoningPartDoneEvent
| ResponseCodeInterpreterCallInProgressEvent
| ResponseCodeInterpreterCallCodeDeltaEvent
| ResponseWebSearchCallInProgressEvent
+61 -49
View File
@@ -15,7 +15,6 @@ from openai.types.responses import (
ResponseOutputMessage,
ResponseOutputText,
ResponseStatus,
response_text_delta_event,
)
from openai.types.responses.response_output_text import Logprob, LogprobTopLogprob
from pydantic import TypeAdapter
@@ -73,6 +72,9 @@ from vllm.entrypoints.openai.responses.utils import (
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
from vllm.entrypoints.serve.utils.tool_calls_utils import (
maybe_filter_parallel_tool_calls,
)
from vllm.exceptions import GenerationError, VLLMValidationError
from vllm.inputs import EngineInput
from vllm.logger import init_logger
@@ -139,6 +141,7 @@ class OpenAIServingResponses(GenerateBaseServing):
tool_strict_level=tool_strict_level,
model_name=self.model_config.model,
is_harmony=self.model_config.hf_config.model_type == "gpt_oss",
tokenizer=self.renderer.tokenizer,
)
self.enable_prompt_tokens_details = enable_prompt_tokens_details
self.enable_force_include_usage = enable_force_include_usage
@@ -332,6 +335,16 @@ class OpenAIServingResponses(GenerateBaseServing):
if maybe_validation_error is not None:
return maybe_validation_error
maybe_template_error = self.online_renderer.validate_chat_template(
request_chat_template=None,
chat_template_kwargs=request.chat_template_kwargs,
trust_request_chat_template=(
self.online_renderer.trust_request_chat_template
),
)
if maybe_template_error is not None:
return maybe_template_error
self._preflight()
if request.store and not self.enable_store:
@@ -434,6 +447,12 @@ class OpenAIServingResponses(GenerateBaseServing):
response_parser = self._make_response_parser(
request, tokenizer, chat_template_kwargs
)
if response_parser is not None:
prompt_token_ids = self._extract_prompt_components(
engine_input
).token_ids
if prompt_token_ids is not None:
response_parser.set_prompt_token_ids(prompt_token_ids)
context: ConversationContext
function_tool_names = extract_function_tool_names(request.tools)
@@ -691,6 +710,12 @@ class OpenAIServingResponses(GenerateBaseServing):
context.request,
context.response_messages,
)
if context.response_parser is not None:
prompt_token_ids = self._extract_prompt_components(
engine_input
).token_ids
if prompt_token_ids is not None:
context.response_parser.set_prompt_token_ids(prompt_token_ids)
sampling_params.max_tokens = get_max_tokens(
max_model_len,
@@ -810,14 +835,19 @@ class OpenAIServingResponses(GenerateBaseServing):
if final_output.finish_reason == "length":
status = "incomplete"
# TODO: Build final response items from the accumulated streaming
# parser results instead of reparsing the complete output.
output = self._make_response_output_items(
request,
final_output,
tokenizer,
parser=context.response_parser,
streamed_items = context.streamed_output_items
self._log_final_output(
request, final_output, is_streaming=streamed_items is not None
)
if streamed_items is not None:
output = streamed_items
else:
output = self._make_response_output_items(
request,
final_output,
tokenizer,
parser=context.response_parser,
)
if request.enable_response_messages:
input_messages = context.input_messages
@@ -959,32 +989,21 @@ class OpenAIServingResponses(GenerateBaseServing):
)
return out
def _create_stream_response_logprobs(
def _log_final_output(
self,
token_ids: Sequence[int],
logprobs: SampleLogprobs | None,
tokenizer: TokenizerLike,
top_logprobs: int | None = None,
) -> list[response_text_delta_event.Logprob]:
lgs = self._create_response_logprobs(
token_ids=token_ids,
logprobs=logprobs,
tokenizer=tokenizer,
top_logprobs=top_logprobs,
)
return [
response_text_delta_event.Logprob(
token=lg.token,
logprob=lg.logprob,
top_logprobs=[
response_text_delta_event.LogprobTopLogprob(
token=tl.token, logprob=tl.logprob
)
for tl in lg.top_logprobs
],
request: ResponsesRequest,
final_output: CompletionOutput,
is_streaming: bool,
) -> None:
if self.enable_log_outputs and self.request_logger:
self.request_logger.log_outputs(
request_id=request.request_id,
outputs=final_output.text,
output_token_ids=final_output.token_ids,
finish_reason=final_output.finish_reason,
is_streaming=is_streaming,
delta=False,
)
for lg in lgs
]
def _make_response_output_items(
self,
@@ -993,17 +1012,6 @@ class OpenAIServingResponses(GenerateBaseServing):
tokenizer: TokenizerLike,
parser: Parser | None = None,
) -> list[ResponseOutputItem]:
# Log complete response if output logging is enabled
if self.enable_log_outputs and self.request_logger:
self.request_logger.log_outputs(
request_id=request.request_id,
outputs=final_output.text,
output_token_ids=final_output.token_ids,
finish_reason=final_output.finish_reason,
is_streaming=False,
delta=False,
)
# Compute logprobs if requested
logprobs = None
if request.is_include_output_logprobs() and final_output.logprobs:
@@ -1028,7 +1036,7 @@ class OpenAIServingResponses(GenerateBaseServing):
return build_response_output_items(
reasoning=reasoning,
content=content,
tool_calls=tool_calls,
tool_calls=maybe_filter_parallel_tool_calls(tool_calls or [], request),
logprobs=logprobs,
tools=request.tools,
)
@@ -1192,16 +1200,16 @@ class OpenAIServingResponses(GenerateBaseServing):
) -> AsyncGenerator[StreamingResponsesResponse, None]:
processor = SimpleStreamingEventProcessor(tools=request.tools)
hide_stream_metadata = not request.include_reasoning and self.parser is not None
hide_stream_metadata = (
not request.include_reasoning and context.response_parser is not None
)
def _get_logprobs(
output: CompletionOutput,
) -> list[response_text_delta_event.Logprob]:
def _get_logprobs(output: CompletionOutput) -> list[Logprob]:
if not request.is_include_output_logprobs():
return []
if hide_stream_metadata:
return []
return self._create_stream_response_logprobs(
return self._create_response_logprobs(
token_ids=output.token_ids,
logprobs=output.logprobs,
tokenizer=tokenizer,
@@ -1231,6 +1239,7 @@ class OpenAIServingResponses(GenerateBaseServing):
if not delta_message:
continue
delta_message = maybe_filter_parallel_tool_calls(delta_message, request)
for dm in split_delta(delta_message):
target_state, tool_call = processor.resolve_target_state(dm)
@@ -1249,6 +1258,9 @@ class OpenAIServingResponses(GenerateBaseServing):
for event in processor.close_current():
yield _increment_sequence_number_and_return(event)
assert isinstance(context, SimpleContext)
context.streamed_output_items = processor.output_items
async def _process_harmony_streaming_events(
self,
request: ResponsesRequest,
@@ -38,6 +38,7 @@ from openai.types.responses import (
ResponseMcpCallArgumentsDoneEvent,
ResponseMcpCallCompletedEvent,
ResponseMcpCallInProgressEvent,
ResponseOutputItem,
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseOutputMessage,
@@ -51,6 +52,7 @@ from openai.types.responses import (
ResponseWebSearchCallInProgressEvent,
ResponseWebSearchCallSearchingEvent,
response_function_web_search,
response_output_text,
response_text_delta_event,
)
from openai.types.responses.response_output_item import McpCall
@@ -60,6 +62,7 @@ from openai.types.responses.response_reasoning_item import (
from openai.types.responses.tool import Tool
from openai_harmony import Message as HarmonyMessage
from vllm.entrypoints.chat_utils import make_tool_call_id
from vllm.entrypoints.generate.base.protocol import DeltaMessage, DeltaToolCall
from vllm.entrypoints.mcp.tool_server import ToolServer
from vllm.entrypoints.openai.parser.harmony_utils import (
@@ -67,8 +70,6 @@ from vllm.entrypoints.openai.parser.harmony_utils import (
is_function_recipient,
)
from vllm.entrypoints.openai.responses.protocol import (
ResponseReasoningPartAddedEvent,
ResponseReasoningPartDoneEvent,
StreamingResponsesResponse,
)
from vllm.entrypoints.openai.responses.utils import (
@@ -217,16 +218,13 @@ def emit_reasoning_delta_events(
)
state.current_content_index += 1
events.append(
ResponseReasoningPartAddedEvent(
type="response.reasoning_part.added",
ResponseContentPartAddedEvent(
type="response.content_part.added",
sequence_number=-1,
output_index=state.current_output_index,
item_id=state.current_item_id,
content_index=state.current_content_index,
part=ResponseReasoningTextContent(
text="",
type="reasoning_text",
),
part={"text": "", "type": "reasoning_text"},
)
)
events.append(
@@ -454,13 +452,13 @@ def emit_reasoning_done_events(
)
)
events.append(
ResponseReasoningPartDoneEvent(
type="response.reasoning_part.done",
ResponseContentPartDoneEvent(
type="response.content_part.done",
sequence_number=-1,
item_id=state.current_item_id,
output_index=state.current_output_index,
content_index=state.current_content_index,
part=content,
part=content.model_dump(),
)
)
events.append(
@@ -816,11 +814,13 @@ class SimpleStreamingState:
current_item_id: str = ""
content_index: int = 0
accumulated_text: str = ""
accumulated_logprobs: list[response_output_text.Logprob] = field(
default_factory=list
)
tool_call_id: str = ""
tool_call_name: str = ""
tool_call_namespace: str | None = None
tool_call_index: int | None = None
has_emitted_tool_call_delta: bool = False
current_state: _StateType = field(default_factory=lambda: _StateType.NONE)
@@ -828,9 +828,10 @@ def emit_simple_content_open(
state: SimpleStreamingState,
) -> list[StreamingResponsesResponse]:
state.current_state = _StateType.CONTENT
state.current_item_id = random_uuid()
state.current_item_id = f"msg_{random_uuid()}"
state.content_index = 0
state.accumulated_text = ""
state.accumulated_logprobs = []
return [
ResponseOutputItemAddedEvent(
type="response.output_item.added",
@@ -860,12 +861,32 @@ def emit_simple_content_open(
]
def _to_stream_logprobs(
logprobs: list[response_output_text.Logprob],
) -> list[response_text_delta_event.Logprob]:
return [
response_text_delta_event.Logprob(
token=lp.token,
logprob=lp.logprob,
top_logprobs=[
response_text_delta_event.LogprobTopLogprob(
token=tl.token, logprob=tl.logprob
)
for tl in lp.top_logprobs
],
)
for lp in logprobs
]
def emit_simple_content_delta(
state: SimpleStreamingState,
delta: str,
logprobs: list[response_text_delta_event.Logprob] | None = None,
logprobs: list[response_output_text.Logprob] | None = None,
) -> list[StreamingResponsesResponse]:
state.accumulated_text += delta
if logprobs:
state.accumulated_logprobs.extend(logprobs)
return [
ResponseTextDeltaEvent(
type="response.output_text.delta",
@@ -874,7 +895,7 @@ def emit_simple_content_delta(
output_index=state.output_index,
item_id=state.current_item_id,
delta=delta,
logprobs=logprobs or [],
logprobs=_to_stream_logprobs(logprobs or []),
)
]
@@ -886,6 +907,7 @@ def emit_simple_content_done(
type="output_text",
text=state.accumulated_text,
annotations=[],
logprobs=state.accumulated_logprobs or None,
)
events: list[StreamingResponsesResponse] = [
ResponseTextDoneEvent(
@@ -915,7 +937,6 @@ def emit_simple_content_done(
role="assistant",
content=[part] if state.accumulated_text else [],
status="completed",
summary=[],
),
),
]
@@ -928,7 +949,7 @@ def emit_simple_reasoning_open(
state: SimpleStreamingState,
) -> list[StreamingResponsesResponse]:
state.current_state = _StateType.REASONING
state.current_item_id = random_uuid()
state.current_item_id = f"rs_{random_uuid()}"
state.content_index = 0
state.accumulated_text = ""
return [
@@ -943,16 +964,13 @@ def emit_simple_reasoning_open(
status="in_progress",
),
),
ResponseReasoningPartAddedEvent(
type="response.reasoning_part.added",
ResponseContentPartAddedEvent(
type="response.content_part.added",
sequence_number=-1,
output_index=state.output_index,
item_id=state.current_item_id,
content_index=state.content_index,
part=ResponseReasoningTextContent(
text="",
type="reasoning_text",
),
part={"text": "", "type": "reasoning_text"},
),
]
@@ -990,13 +1008,13 @@ def emit_simple_reasoning_done(
content_index=state.content_index,
text=state.accumulated_text,
),
ResponseReasoningPartDoneEvent(
type="response.reasoning_part.done",
ResponseContentPartDoneEvent(
type="response.content_part.done",
sequence_number=-1,
item_id=state.current_item_id,
output_index=state.output_index,
content_index=state.content_index,
part=part,
part=part.model_dump(),
),
ResponseOutputItemDoneEvent(
type="response.output_item.done",
@@ -1021,15 +1039,15 @@ def emit_simple_tool_call_open(
name: str,
index: int | None,
namespace: str | None = None,
call_id: str | None = None,
) -> list[StreamingResponsesResponse]:
state.current_state = _StateType.TOOL_CALL
state.current_item_id = random_uuid()
state.tool_call_id = f"call_{random_uuid()}"
state.current_item_id = f"fc_{random_uuid()}"
state.tool_call_id = call_id or make_tool_call_id()
state.tool_call_name = name
state.tool_call_namespace = namespace
state.tool_call_index = index
state.accumulated_text = ""
state.has_emitted_tool_call_delta = False
return [
ResponseOutputItemAddedEvent(
type="response.output_item.added",
@@ -1053,7 +1071,6 @@ def emit_simple_tool_call_delta(
delta: str,
) -> list[StreamingResponsesResponse]:
state.accumulated_text += delta
state.has_emitted_tool_call_delta = True
return [
ResponseFunctionCallArgumentsDeltaEvent(
type="response.function_call_arguments.delta",
@@ -1068,19 +1085,15 @@ def emit_simple_tool_call_delta(
def emit_simple_tool_call_done(
state: SimpleStreamingState,
) -> list[StreamingResponsesResponse]:
events: list[StreamingResponsesResponse] = []
if state.has_emitted_tool_call_delta:
events.append(
ResponseFunctionCallArgumentsDoneEvent(
type="response.function_call_arguments.done",
sequence_number=-1,
output_index=state.output_index,
item_id=state.current_item_id,
arguments=state.accumulated_text,
name=state.tool_call_name,
)
)
events.append(
events: list[StreamingResponsesResponse] = [
ResponseFunctionCallArgumentsDoneEvent(
type="response.function_call_arguments.done",
sequence_number=-1,
output_index=state.output_index,
item_id=state.current_item_id,
arguments=state.accumulated_text,
name=state.tool_call_name,
),
ResponseOutputItemDoneEvent(
type="response.output_item.done",
sequence_number=-1,
@@ -1095,7 +1108,7 @@ def emit_simple_tool_call_done(
call_id=state.tool_call_id,
),
),
)
]
state.output_index += 1
state.tool_call_namespace = None
state.current_state = _StateType.NONE
@@ -1181,6 +1194,7 @@ class SimpleStreamingEventProcessor:
) -> None:
self.state = state or SimpleStreamingState()
self.tool_call_name_map = build_responses_tool_call_name_map(tools)
self.output_items: list[ResponseOutputItem] = []
def resolve_target_state(
self, delta_message: DeltaMessage
@@ -1226,7 +1240,13 @@ class SimpleStreamingEventProcessor:
handlers = self._STATE_HANDLERS.get(self.state.current_state)
if handlers is None:
return []
return handlers.done_fn(self.state)
events = handlers.done_fn(self.state)
self.output_items.extend(
event.item
for event in events
if isinstance(event, ResponseOutputItemDoneEvent)
)
return events
def open(
self, target_state: _StateType, tool_call: Any = None
@@ -1244,6 +1264,7 @@ class SimpleStreamingEventProcessor:
call_name.name,
tool_call.index,
call_name.namespace,
tool_call.id,
)
return handlers.open_fn(self.state)
@@ -1251,9 +1272,7 @@ class SimpleStreamingEventProcessor:
self,
delta_message: DeltaMessage,
output: CompletionOutput,
get_logprobs: Callable[
[CompletionOutput], list[response_text_delta_event.Logprob]
]
get_logprobs: Callable[[CompletionOutput], list[response_output_text.Logprob]]
| None = None,
) -> list[StreamingResponsesResponse]:
"""Emit incremental events for the current state from the delta."""
+32 -1
View File
@@ -117,6 +117,20 @@ class ServingDerender(BaseServing):
return None
def _validate_prompt_token_ids(
self,
prompt_token_ids: list[list[int] | None],
) -> ErrorResponse | None:
"""Reject caller-supplied prompt_token_ids longer than max_model_len."""
max_model_len = self.model_config.max_model_len
for ids in prompt_token_ids:
if ids is not None and len(ids) > max_model_len:
return self.create_error_response(
f"prompt_token_ids length ({len(ids)}) exceeds "
f"max_model_len ({max_model_len})."
)
return None
async def derender_chat_response(
self,
request: DerenderChatRequest,
@@ -138,6 +152,10 @@ class ServingDerender(BaseServing):
if bounds_error is not None:
return bounds_error
prompt_ids_error = self._validate_prompt_token_ids([request.prompt_token_ids])
if prompt_ids_error is not None:
return prompt_ids_error
if self.online_derenderer.parser is not None and request.chat_request is None:
return self.create_error_response(
"chat_request is required when a tool or reasoning parser is "
@@ -147,7 +165,9 @@ class ServingDerender(BaseServing):
try:
choices = await self.online_derenderer.derender_chat(
request.generate_response, request.chat_request
request.generate_response,
request.chat_request,
request.prompt_token_ids,
)
except ValueError as exc:
return self.create_error_response(str(exc))
@@ -203,6 +223,11 @@ class ServingDerender(BaseServing):
if bounds_error is not None:
return bounds_error
if request.prompt_token_ids is not None:
prompt_ids_error = self._validate_prompt_token_ids(request.prompt_token_ids)
if prompt_ids_error is not None:
return prompt_ids_error
(
choices,
total_prompt_tokens,
@@ -211,6 +236,7 @@ class ServingDerender(BaseServing):
request.generate_responses,
request.prompt_tokens,
completion_request=request.completion_request,
prompt_token_ids=request.prompt_token_ids,
)
first = request.generate_responses[0]
@@ -367,6 +393,10 @@ class ServingDerender(BaseServing):
if error_check_ret is not None:
return error_check_ret
prompt_ids_error = self._validate_prompt_token_ids([request.prompt_token_ids])
if prompt_ids_error is not None:
return prompt_ids_error
model_name = request.model or self.models.model_name()
try:
(
@@ -378,6 +408,7 @@ class ServingDerender(BaseServing):
state=request.stream_state,
prompt_tokens=request.prompt_tokens,
completion_request=request.completion_request,
prompt_token_ids=request.prompt_token_ids,
)
except ValueError as exc:
return self.create_error_response(str(exc))
@@ -5,6 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
from pydantic import (
BaseModel,
Field,
NonNegativeInt,
PrivateAttr,
field_validator,
model_validator,
@@ -362,7 +363,7 @@ class GenerateStreamResponse(BaseModel):
)
choices: list[GenerateResponseStreamChoice]
usage: UsageInfo | None = Field(default=None)
prompt_token_ids: list[int] | None = None
prompt_token_ids: list[NonNegativeInt] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
metrics: PerRequestMetrics | None = None
@@ -382,7 +383,7 @@ class GenerateResponse(BaseModel):
usage: UsageInfo | None = Field(default=None)
prompt_logprobs: list[dict[int, Logprob] | None] | None = None
prompt_token_id_logprobs: str | None = None
prompt_token_ids: list[int] | None = None
prompt_token_ids: list[NonNegativeInt] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
metrics: PerRequestMetrics | None = None
@@ -421,6 +422,15 @@ class DerenderChatRequest(BaseModel):
len(GenerateRequest.token_ids) from the render step.
"""
prompt_token_ids: list[NonNegativeInt] | None = None
"""Prompt token IDs (`GenerateRequest.token_ids` from /render). Seeds
detokenization from the prompt tail so the first output token keeps its
leading space on SentencePiece tokenizers. Falls back to
`generate_response.prompt_token_ids`, then to unseeded decoding.
Only the last few IDs are read, so a suffix of the prompt is enough.
"""
chat_request: ChatCompletionRequest | None = None
"""The original (post-adjust_request) ChatCompletionRequest from /render.
@@ -455,6 +465,14 @@ class DerenderCompletionRequest(BaseModel):
If provided, len(prompt_tokens) must equal len(generate_responses).
"""
prompt_token_ids: list[list[NonNegativeInt] | None] | None = None
"""One prompt token ID list per response, used to seed detokenization.
See `DerenderChatRequest.prompt_token_ids`.
If provided, len(prompt_token_ids) must equal len(generate_responses).
A `None` entry falls back to `generate_responses[i].prompt_token_ids`.
"""
completion_request: CompletionRequest | None = None
"""The original (post-adjust_request) CompletionRequest from /render.
@@ -472,6 +490,13 @@ class DerenderCompletionRequest(BaseModel):
f"prompt_tokens length ({len(self.prompt_tokens)}) must equal "
f"generate_responses length ({len(self.generate_responses)})"
)
if self.prompt_token_ids is not None and len(self.prompt_token_ids) != len(
self.generate_responses
):
raise ValueError(
f"prompt_token_ids length ({len(self.prompt_token_ids)}) must "
f"equal generate_responses length ({len(self.generate_responses)})"
)
return self
@@ -546,6 +571,17 @@ class DerenderStreamState(BaseModel):
window is transiently empty (e.g. usage only final chunk).
"""
logprob_context_token_ids: list[int] = Field(default_factory=list, max_length=4)
"""Trailing sampled token IDs carried across chunks so byte-fallback
(U+FFFD) correction during logprob placeholder resolution has context
at chunk boundaries. Bounded to the 4-token window that
``_correct_decoded_token`` reads."""
logprob_text_offset: int = Field(default=0, ge=0)
"""Cumulative emitted text length. Seeds ``text_offset`` for completion
streaming logprobs so offsets stay absolute across chunks, mirroring
``initial_text_offset`` in the generate streaming path."""
output_token_ids: list[int] = Field(default_factory=list)
"""All output tokens seen so far. Parser path only.
@@ -616,7 +652,7 @@ class DerenderChatStreamRequest(BaseModel):
prompt_tokens: int | None = None
"""Prompt token count for usage. Forwarded from the render step."""
prompt_token_ids: list[int] | None = None
prompt_token_ids: list[NonNegativeInt] | None = None
"""Prompt token IDs. Required by the parser path's `parse_delta` to
settle its initial reasoning state (e.g. chat templates that pre-open
``<think>``). `prompt_tokens` is a usage count and cannot serve this
@@ -625,8 +661,15 @@ class DerenderChatStreamRequest(BaseModel):
Rejected with a 400 (by `ServingDerender`) when a tool or reasoning
parser is configured and this is omitted. Without it, `parse_delta`
cannot tell whether the prompt left reasoning open and would silently
misclassify reasoning content as plain content. Unused on the plain
detokenization path.
misclassify reasoning content as plain content. On all paths it also
seeds detokenization on the first chunk, falling back to
`generate_chunk.prompt_token_ids` when omitted (see
`DerenderChatRequest.prompt_token_ids`).
With a parser configured, send the full list. Parsers look back to the
last reasoning marker which can be anywhere in the prompt, so a suffix
can flip the initial reasoning state. Without a parser, a suffix is
enough.
"""
chat_request: ChatCompletionRequest | None = None
@@ -655,6 +698,12 @@ class DerenderCompletionStreamRequest(BaseModel):
prompt_tokens: int | None = None
"""Prompt token count for usage."""
prompt_token_ids: list[NonNegativeInt] | None = None
"""Prompt token IDs, used on the first chunk to seed detokenization.
Falls back to `generate_chunk.prompt_token_ids`. See
`DerenderChatRequest.prompt_token_ids`.
"""
completion_request: CompletionRequest | None = None
"""The original (post adjust_request) CompletionRequest from /render."""
# --8<-- [end:derender-completion-stream-request]
@@ -39,6 +39,7 @@ from vllm.inputs import EngineInput, TokensPrompt, mm_input
from vllm.logger import init_logger
from vllm.logprobs import Logprob
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
MultiModalKwargsItems,
PlaceholderRange,
)
@@ -106,6 +107,23 @@ class ServingTokens(GenerateBaseServing):
else getattr(mc, "override_generation_config", {}).get("max_new_tokens")
)
def _validate_mm_cache_handles(
self,
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]],
mm_hashes: dict[str, list[str]],
) -> ErrorResponse | None:
cache = self.online_renderer.renderer.mm_processor_cache
if cache is None:
return None
try:
for modality, items in mm_kwargs.items():
for mm_hash, item in zip(mm_hashes[modality], items, strict=True):
if item is not None:
cache.validate_input_item(item, mm_hash)
except ValueError as error:
return self.create_error_response(error)
return None
async def serve_tokens(
self,
request: GenerateRequest,
@@ -201,6 +219,8 @@ class ServingTokens(GenerateBaseServing):
# Deserialize full tensor data and optional metadata-only data.
# Metadata-only items are valid when ec_transfer_params is set.
mm_kwargs = mm_kwargs_from_features(features)
if error := self._validate_mm_cache_handles(mm_kwargs, features.mm_hashes):
return error
engine_input = mm_input(
prompt_token_ids=request.token_ids,
@@ -495,6 +515,10 @@ class ServingTokens(GenerateBaseServing):
else None
)
sampling_mask = None
if output.sampling_mask is not None:
sampling_mask = output.sampling_mask.token_ids
chunk = GenerateStreamResponse(
request_id=request_id,
choices=[
@@ -504,6 +528,7 @@ class ServingTokens(GenerateBaseServing):
finish_reason=finish_reason,
token_ids=as_list(delta_token_ids),
routed_experts=routed_experts_b64,
sampling_mask=sampling_mask,
)
],
)
+64 -30
View File
@@ -3,16 +3,18 @@
import json
from http import HTTPStatus
from typing import Annotated
from typing import Annotated, Any, Literal
from fastapi import APIRouter, Body, FastAPI, HTTPException, Query, Request
from fastapi.responses import JSONResponse
from vllm.distributed.weight_transfer.base import (
WeightTransferInitRequest,
WeightTransferUpdatePayload,
WeightTransferUpdateRequest,
)
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.serve.dev.rlhf.metrics import weight_operation_metrics
from vllm.logger import init_logger
from vllm.v1.engine import PauseMode
@@ -104,6 +106,10 @@ async def abort_requests(raw_request: Request) -> JSONResponse:
body = await raw_request.json()
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="Invalid JSON format") from e # noqa: B904
if not isinstance(body, dict):
raise HTTPException(
status_code=400, detail="Request body must be a JSON object"
)
request_ids = body.get("request_ids")
@@ -154,50 +160,40 @@ async def is_paused(raw_request: Request) -> JSONResponse:
@router.post("/init_weight_transfer_engine")
async def init_weight_transfer_engine(raw_request: Request):
try:
body = await raw_request.json()
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="Invalid JSON format") from e # noqa: B904
init_info = body.get("init_info")
if init_info is None:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail="Missing 'init_info' in request body",
async def init_weight_transfer_engine(
raw_request: Request,
init_info: Annotated[dict[str, Any], Body(embed=True)],
):
with weight_operation_metrics().record("init"):
await engine_client(raw_request).init_weight_transfer_engine(
WeightTransferInitRequest(init_info=init_info)
)
await engine_client(raw_request).init_weight_transfer_engine(
WeightTransferInitRequest(init_info=init_info)
)
return JSONResponse(content={"message": "Weight transfer initialized"})
@router.post("/start_weight_update")
async def start_weight_update(raw_request: Request):
await engine_client(raw_request).start_weight_update()
with weight_operation_metrics().record("start"):
await engine_client(raw_request).start_weight_update()
return JSONResponse(content={"message": "Weight update started"})
@router.post("/start_draft_weight_update")
async def start_draft_weight_update(raw_request: Request):
await engine_client(raw_request).start_draft_weight_update()
with weight_operation_metrics().record("start_draft"):
await engine_client(raw_request).start_draft_weight_update()
return JSONResponse(content={"message": "Draft weight update started"})
@router.post("/update_weights")
async def update_weights(raw_request: Request):
try:
body = await raw_request.json()
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="Invalid JSON format") from e # noqa: B904
update_info = body.get("update_info")
if update_info is None:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail="Missing 'update_info' in request body",
async def update_weights(
raw_request: Request,
update_info: Annotated[WeightTransferUpdatePayload, Body(embed=True)],
):
with weight_operation_metrics().record("update"):
await engine_client(raw_request).update_weights(
request=WeightTransferUpdateRequest(update_info=update_info)
)
await engine_client(raw_request).update_weights(
request=WeightTransferUpdateRequest(update_info=update_info)
)
return JSONResponse(content={"message": "Weights updated"})
@@ -206,7 +202,8 @@ async def finish_weight_update(
raw_request: Request,
weight_version: Annotated[str | None, Body(embed=True)] = None,
):
await engine_client(raw_request).finish_weight_update(weight_version)
with weight_operation_metrics().record("finish"):
await engine_client(raw_request).finish_weight_update(weight_version)
return JSONResponse(content={"message": "Weight update finished"})
@@ -225,6 +222,43 @@ async def weight_info(raw_request: Request):
return JSONResponse(content={"weight_version": weight_version})
@router.post("/weight_checker")
async def weight_checker(
raw_request: Request,
action: Annotated[Literal["checksum", "reset", "compare"], Body(embed=True)],
baseline: Annotated[dict[str, str] | None, Body(embed=True)] = None,
) -> JSONResponse:
"""Checksum, reset, or compare model weights against a baseline."""
client = engine_client(raw_request)
if action == "reset":
await client.collective_rpc("reset_weights")
return JSONResponse(content={"status": "reset"})
if action == "compare" and baseline is None:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail="action='compare' requires a 'baseline' object",
)
checksums: dict[str, str] = {}
for worker_checksums in await client.compute_weight_checksums():
if duplicates := checksums.keys() & worker_checksums.keys():
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
detail=f"Duplicate weight checksum keys: {sorted(duplicates)}",
)
checksums.update(worker_checksums)
if action == "checksum":
return JSONResponse(content={"checksums": checksums})
assert baseline is not None
mismatches = sorted(
key
for key in checksums.keys() | baseline.keys()
if checksums.get(key) != baseline.get(key)
)
return JSONResponse(content={"match": not mismatches, "mismatches": mismatches})
@router.get("/get_world_size")
async def get_world_size(
raw_request: Request,
@@ -0,0 +1,56 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Duration and in-flight metrics for RL weight-transfer operations."""
from collections.abc import Iterator
from contextlib import contextmanager
from threading import Lock
from time import perf_counter
from typing import Literal
from prometheus_client import REGISTRY, CollectorRegistry, Gauge, Histogram
Operation = Literal["init", "start", "start_draft", "update", "finish"]
class WeightOperationMetrics:
def __init__(self, registry: CollectorRegistry = REGISTRY):
self.duration = Histogram(
"vllm:rl_weight_update_operation_duration_seconds",
"Duration of one weight-transfer operation.",
["operation"],
buckets=(0.01, 0.1, 1, 10, 30, 60, 120, 300, 600),
registry=registry,
)
self.in_flight = Gauge(
"vllm:rl_weight_update_operations_in_flight",
"Weight-transfer operations currently awaited.",
["operation"],
multiprocess_mode="livesum",
registry=registry,
)
@contextmanager
def record(self, operation: Operation) -> Iterator[None]:
in_flight = self.in_flight.labels(operation)
in_flight.inc()
started = perf_counter()
try:
yield
finally:
in_flight.dec()
self.duration.labels(operation).observe(perf_counter() - started)
_metrics: WeightOperationMetrics | None = None
_metrics_lock = Lock()
def weight_operation_metrics() -> WeightOperationMetrics:
# Lazy, so the collectors exist only after multiprocess Prometheus setup.
global _metrics
if _metrics is None:
with _metrics_lock:
if _metrics is None:
_metrics = WeightOperationMetrics()
return _metrics
@@ -29,6 +29,11 @@ async def collective_rpc(raw_request: Request):
status_code=HTTPStatus.BAD_REQUEST.value,
detail=f"JSON decode error: {e}",
) from e
if not isinstance(body, dict):
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST.value,
detail="Request body must be a JSON object",
)
method = body.get("method")
if method is None:
raise HTTPException(
+25 -14
View File
@@ -2,11 +2,16 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from fastapi import APIRouter, FastAPI, Request
from fastapi.responses import JSONResponse, Response
from typing import Annotated
from fastapi import APIRouter, FastAPI, Query, Request
from fastapi.responses import JSONResponse
from vllm.engine.protocol import EngineClient
from vllm.logger import init_logger
from vllm.v1.engine import PauseMode
from .metrics import sleep_mode_operation_metrics
logger = init_logger(__name__)
@@ -19,29 +24,35 @@ router = APIRouter()
@router.post("/sleep")
async def sleep(raw_request: Request):
# get POST params
level = raw_request.query_params.get("level", "1")
mode = raw_request.query_params.get("mode", "abort")
await engine_client(raw_request).sleep(int(level), mode)
return Response(status_code=200)
async def sleep(
raw_request: Request,
level: Annotated[int, Query(ge=0, le=2)] = 1,
mode: Annotated[PauseMode, Query()] = "abort",
) -> JSONResponse:
with sleep_mode_operation_metrics().record("sleep"):
await engine_client(raw_request).sleep(level, mode)
return JSONResponse(content={"status": "sleeping", "level": level})
@router.post("/release_kv_cache_memory")
async def release_kv_cache_memory(raw_request: Request):
await engine_client(raw_request).release_kv_cache_memory()
return Response(status_code=200)
async def release_kv_cache_memory(raw_request: Request) -> JSONResponse:
with sleep_mode_operation_metrics().record("release_kv_cache_memory"):
await engine_client(raw_request).release_kv_cache_memory()
return JSONResponse(content={"status": "kv_cache_released"})
@router.post("/wake_up")
async def wake_up(raw_request: Request):
async def wake_up(raw_request: Request) -> JSONResponse:
tags = raw_request.query_params.getlist("tags")
if tags == []:
# set to None to wake up all tags if no tags are provided
tags = None
logger.info("wake up the engine with tags: %s", tags)
await engine_client(raw_request).wake_up(tags)
return Response(status_code=200)
with sleep_mode_operation_metrics().record("wake"):
fully_awake = await engine_client(raw_request).wake_up(tags)
return JSONResponse(
content={"status": "awake" if fully_awake else "sleeping", "tags": tags}
)
@router.get("/is_sleeping")
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Metrics for dispatched sleep-mode frontend operations."""
from collections.abc import Iterator
from contextlib import contextmanager
from threading import Lock
from time import perf_counter
from typing import Literal
from prometheus_client import REGISTRY, CollectorRegistry, Gauge, Histogram
Operation = Literal["sleep", "release_kv_cache_memory", "wake"]
BUCKETS = (0.01, 0.1, 1, 10, 30, 60, 120, 300, 600)
class SleepModeOperationMetrics:
def __init__(self, registry: CollectorRegistry | None = None):
registry = REGISTRY if registry is None else registry
self.duration = Histogram(
"vllm:sleep_mode_operation_duration_seconds",
"Duration of one sleep-mode operation.",
["operation"],
buckets=BUCKETS,
registry=registry,
)
self.in_flight = Gauge(
"vllm:sleep_mode_operations_in_flight",
"Sleep-mode operations currently awaited.",
["operation"],
multiprocess_mode="livesum",
registry=registry,
)
@contextmanager
def record(self, operation: Operation) -> Iterator[None]:
active = self.in_flight.labels(operation)
started = perf_counter()
active.inc()
try:
yield
finally:
active.dec()
self.duration.labels(operation).observe(perf_counter() - started)
_metrics: SleepModeOperationMetrics | None = None
_metrics_lock = Lock()
def sleep_mode_operation_metrics() -> SleepModeOperationMetrics:
global _metrics
if _metrics is None:
with _metrics_lock:
if _metrics is None:
_metrics = SleepModeOperationMetrics()
return _metrics
@@ -2,35 +2,42 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import TypeVar
from vllm.entrypoints.generate.base.protocol import DeltaMessage, FunctionCall
from vllm.entrypoints.openai.chat_completion.protocol import (
ChatCompletionRequest,
ChatCompletionResponseChoice,
ChatCompletionResponseStreamChoice,
)
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
# Used internally
_ChatCompletionResponseChoiceT = TypeVar(
"_ChatCompletionResponseChoiceT",
_ToolCallsContainerT = TypeVar(
"_ToolCallsContainerT",
ChatCompletionResponseChoice,
ChatCompletionResponseStreamChoice,
DeltaMessage,
list[FunctionCall],
)
def maybe_filter_parallel_tool_calls(
choice: _ChatCompletionResponseChoiceT, request: ChatCompletionRequest
) -> _ChatCompletionResponseChoiceT:
item: _ToolCallsContainerT,
request: ChatCompletionRequest | ResponsesRequest,
) -> _ToolCallsContainerT:
"""Filter to first tool call only when parallel_tool_calls is explicitly False."""
if request.parallel_tool_calls is not False:
return choice
return item
if isinstance(choice, ChatCompletionResponseChoice) and choice.message.tool_calls:
choice.message.tool_calls = choice.message.tool_calls[:1]
elif (
isinstance(choice, ChatCompletionResponseStreamChoice)
and choice.delta.tool_calls
):
choice.delta.tool_calls = [
tool_call for tool_call in choice.delta.tool_calls if tool_call.index == 0
if isinstance(item, list):
return item[:1]
if isinstance(item, ChatCompletionResponseChoice):
if item.message.tool_calls:
item.message.tool_calls = item.message.tool_calls[:1]
return item
delta = item.delta if isinstance(item, ChatCompletionResponseStreamChoice) else item
if delta.tool_calls:
delta.tool_calls = [
tool_call for tool_call in delta.tool_calls if tool_call.index == 0
]
return choice
return item
+22 -3
View File
@@ -25,6 +25,7 @@ if TYPE_CHECKING:
CUDA_VISIBLE_DEVICES: str | None = None
VLLM_ENGINE_ITERATION_TIMEOUT_S: int = 60
VLLM_ENGINE_READY_TIMEOUT_S: int = 600
VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT: float = 30.0
VLLM_API_KEY: str | None = None
VLLM_DEBUG_LOG_API_SERVER_RESPONSE: bool = False
S3_ACCESS_KEY_ID: str | None = None
@@ -141,6 +142,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_A4W4_DSV4: bool | None = None
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
@@ -811,6 +813,11 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_ENGINE_READY_TIMEOUT_S": lambda: int(
os.environ.get("VLLM_ENGINE_READY_TIMEOUT_S", "600")
),
# Maximum wall-clock seconds allowed for a single chat template render.
# Set to 0 to disable the timeout.
"VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT": lambda: float(
os.environ.get("VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT", "30")
),
# API key for vLLM API server
"VLLM_API_KEY": lambda: os.environ.get("VLLM_API_KEY", None),
# Whether to log responses from API Server for debugging
@@ -905,7 +912,8 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_ZENTORCH_WEIGHT_PREPACK": lambda: bool(
int(os.getenv("VLLM_ZENTORCH_WEIGHT_PREPACK", "1"))
),
# (CPU backend only) whether to use SGLang INT4 W4A8 kernels for AWQ.
# (CPU backend only) whether to use SGLang INT4 W4A8 kernels for AWQ, and
# on Zen CPUs whether to serve int4 checkpoints as DA8W4 rather than W4A16.
"VLLM_CPU_INT4_W4A8": lambda: bool(int(os.getenv("VLLM_CPU_INT4_W4A8", "1"))),
# If the env var is set, Ray Compiled Graph uses the specified
# channel type to communicate between workers belonging to
@@ -1291,6 +1299,13 @@ environment_variables: dict[str, Callable[[], Any]] = {
["auto", "a4w4", "a8w4", "a16w4", "0", "1"],
case_sensitive=False,
),
# Opt-in switch for a4w4 (FP4 activation) MoE on DeepSeek V4.1, AITER
# MXFP4 backend. Default is a8w4 (FP8); set to "1" to enable a4w4
# ("true" is not accepted -- only "0"/"1"). Raises if set for other
# models.
"VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4": lambda: maybe_convert_bool(
os.getenv("VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4")
),
# MoE sorting dispatch policy for AITER fused MoE kernels.
# 0 = auto (default): single-pass for small batches, multi-pass
# for large batches
@@ -2009,9 +2024,13 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_DEEPEP_LOW_LATENCY_USE_MNNVL": lambda: bool(
int(os.getenv("VLLM_DEEPEP_LOW_LATENCY_USE_MNNVL", "0"))
),
# DeepEP v2: enable two-tier NVLink+RDMA hybrid mode
# DeepEP v2: use NVLink+RDMA hybrid communication across NVLink domains.
# * hybrid mode = multi-node RDMA
# * non hybrid mode = nvlink
# Set to 1 (the default) to allow DeepEP to autoselect hybrid vs non-hybrid.
# Set to 0 to disable hybrid mode.
"VLLM_DEEPEP_V2_ALLOW_HYBRID_MODE": lambda: bool(
int(os.getenv("VLLM_DEEPEP_V2_ALLOW_HYBRID_MODE", "0"))
int(os.getenv("VLLM_DEEPEP_V2_ALLOW_HYBRID_MODE", "1"))
),
# DeepEP v2: use fewer SMs at slight throughput cost
"VLLM_DEEPEP_V2_PREFER_OVERLAP": lambda: bool(
+16 -4
View File
@@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
import vllm.envs as envs
from vllm.logging_utils import ColoredFormatter, NewLineFormatter
from vllm.logging_utils.formatter import JSON_FORMAT as _JSON_FORMAT
if TYPE_CHECKING:
from vllm.config.logging import LoggingConfig
@@ -30,7 +31,6 @@ _FORMAT = (
"[%(fileinfo)s:%(lineno)d] %(message)s"
)
_DATE_FORMAT = "%m-%d %H:%M:%S"
_vllm_process_info: tuple[str, int] | None = None
@@ -211,10 +211,12 @@ def _configure_vllm_root_logger(config: "LoggingConfig | None" = None) -> None:
configure_logging = envs.VLLM_CONFIGURE_LOGGING
log_level = envs.VLLM_LOGGING_LEVEL
log_config_file = envs.VLLM_LOGGING_CONFIG_PATH
log_formatter = "text"
else:
configure_logging = config.configure_logging
log_level = config.log_level
log_config_file = config.pylogging_config_file
log_formatter = config.formatter
if not configure_logging and log_config_file:
raise RuntimeError(
@@ -233,12 +235,22 @@ def _configure_vllm_root_logger(config: "LoggingConfig | None" = None) -> None:
# Refresh these values in case env vars have changed.
vllm_handler["level"] = log_level
vllm_handler["stream"] = envs.VLLM_LOGGING_STREAM
vllm_handler["formatter"] = "vllm_color" if _use_color() else "vllm"
for formatter in logging_config["formatters"].values():
formatter["log_level"] = log_level
if log_formatter == "json":
logging_config["formatters"] = {
"vllm_json": {
"class": "pythonjsonlogger.jsonlogger.JsonFormatter",
"format": _JSON_FORMAT,
}
}
vllm_handler["formatter"] = "vllm_json"
else:
vllm_handler["formatter"] = "vllm_color" if _use_color() else "vllm"
vllm_loggers = logging_config["loggers"]["vllm"]
vllm_loggers["level"] = log_level
for formatter in logging_config["formatters"].values():
formatter["log_level"] = log_level
if log_config_file:
if not path.exists(log_config_file):
+4 -4
View File
@@ -1,14 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.logging_utils.access_log_filter import (
UvicornAccessLogFilter,
create_uvicorn_log_config,
)
from vllm.logging_utils.formatter import ColoredFormatter, NewLineFormatter
from vllm.logging_utils.lazy import lazy
from vllm.logging_utils.log_time import logtime
from vllm.logging_utils.torch_tensor import tensors_str_no_data
from vllm.logging_utils.uvicorn_logging import (
UvicornAccessLogFilter,
create_uvicorn_log_config,
)
__all__ = [
"NewLineFormatter",
+4
View File
@@ -4,6 +4,10 @@
import logging
from pathlib import Path
JSON_FORMAT = (
"%(asctime)s %(levelname)s %(name)s %(processName)s %(process)d %(message)s"
)
class NewLineFormatter(logging.Formatter):
"""Adds logging prefix to newlines to align multi-line messages."""
@@ -1,15 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Access log filter for uvicorn to exclude specific endpoints from logging.
This module provides a logging filter that can be used to suppress access logs
for specific endpoints (e.g., /health, /metrics) to reduce log noise in
production environments.
"""
"""Uvicorn logging configuration and access log filtering."""
import logging
from typing import Literal
from urllib.parse import urlparse
from vllm.logging_utils.formatter import JSON_FORMAT
class UvicornAccessLogFilter(logging.Filter):
"""A logging filter that excludes access logs for specified endpoint paths.
@@ -70,8 +68,9 @@ class UvicornAccessLogFilter(logging.Filter):
def create_uvicorn_log_config(
excluded_paths: list[str] | None = None,
log_level: str = "info",
formatter: Literal["text", "json"] = "text",
) -> dict:
"""Create a uvicorn logging configuration with access log filtering.
"""Create a uvicorn logging configuration with optional access filtering.
This function generates a logging configuration dictionary that can be
passed to uvicorn's `log_config` parameter. It sets up the access log
@@ -80,6 +79,7 @@ def create_uvicorn_log_config(
Args:
excluded_paths: List of URL paths to exclude from access logs.
log_level: The log level for uvicorn loggers.
formatter: Format used for uvicorn logs.
Returns:
A dictionary containing the logging configuration.
@@ -140,4 +140,13 @@ def create_uvicorn_log_config(
},
},
}
if formatter == "json":
json_formatter = {
"class": "pythonjsonlogger.jsonlogger.JsonFormatter",
"format": JSON_FORMAT,
}
config["formatters"] = {
"default": json_formatter.copy(),
"access": json_formatter.copy(),
}
return config
@@ -16,6 +16,7 @@ from vllm.model_executor.determinism.batch_invariant_configs import (
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.mem_utils import get_max_shared_memory_bytes
from vllm.utils.nccl import pin_nccl_env
from vllm.utils.platform_utils import num_compute_units
from vllm.utils.torch_utils import is_torch_equal_or_newer
@@ -1139,25 +1140,33 @@ def enable_batch_invariant_mode():
def override_envs_for_invariance():
os.environ["VLLM_ALLREDUCE_USE_SYMM_MEM"] = "0"
# Only the 1-stage kernel has a size- and rank-independent reduction order.
os.environ["VLLM_CUSTOM_ALLREDUCE_ALGO"] = "1stage"
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
# NCCL determinism settings
# NCCL determinism settings. NCCL keeps the launch mode process-wide, so,
# unlike the pins below, it also applies to communicators shared with other
# processes.
os.environ["NCCL_LAUNCH_MODE"] = "GROUP"
os.environ["NCCL_COLLNET_ENABLE"] = "0"
os.environ["NCCL_NVLS_ENABLE"] = "0"
os.environ["NCCL_P2P_NET_DISABLE"] = "1"
os.environ["NCCL_MIN_NCHANNELS"] = "1"
os.environ["NCCL_MAX_NCHANNELS"] = "1"
os.environ["NCCL_PROTO"] = "Simple"
# NCCL >= 2.31 zero-fills the algorithm table of every collective when
# NCCL_ALGO is set and re-enables only the named ones; together with the
# NCCL_PROTO above, collectives not named here end up with no algorithm
# and fail with ncclInvalidUsage. Re-enable Ring and Tree for all
# collectives, then pin AllReduce to Tree for determinism.
os.environ["NCCL_ALGO"] = "ring,tree;allreduce:tree"
os.environ["NCCL_NTHREADS"] = "1"
os.environ["NCCL_SOCKET_NTHREADS"] = "1"
pin_nccl_env(
{
"NCCL_COLLNET_ENABLE": "0",
"NCCL_NVLS_ENABLE": "0",
"NCCL_P2P_NET_DISABLE": "1",
"NCCL_MIN_NCHANNELS": "1",
"NCCL_MAX_NCHANNELS": "1",
"NCCL_PROTO": "Simple",
# NCCL >= 2.31 zero-fills the algorithm table of every collective
# when NCCL_ALGO is set and re-enables only the named ones; together
# with the NCCL_PROTO above, collectives not named here end up with
# no algorithm and fail with ncclInvalidUsage. Re-enable Ring and
# Tree for all collectives, then pin AllReduce to Tree.
"NCCL_ALGO": "ring,tree;allreduce:tree",
"NCCL_NTHREADS": "1",
"NCCL_SOCKET_NTHREADS": "1",
}
)
# torch.compile settings
os.environ["VLLM_USE_AOT_COMPILE"] = "0"
@@ -480,6 +480,621 @@ _BATCH_INVARIANT_MATMUL_TUNED_CONFIGS: dict[
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(6144, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp2_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 3)),
(4, _MatmulMConfig(16, 128, 8, 5)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(32, 128, 8, 5)),
(64, _MatmulMConfig(32, 128, 4, 4)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 5)),
(1024, _MatmulMConfig(128, 64, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2048, 3072): _MatmulShapeConfig( # Qwen3-1.7B tp2_down_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 5)),
(4, _MatmulMConfig(16, 64, 4, 3)),
(8, _MatmulMConfig(16, 64, 8, 4)),
(16, _MatmulMConfig(16, 64, 8, 3)),
(32, _MatmulMConfig(16, 64, 8, 3)),
(64, _MatmulMConfig(16, 64, 4, 5)),
(256, _MatmulMConfig(64, 64, 8, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 64, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(2048, 1024): _MatmulShapeConfig( # Qwen3-1.7B tp2_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 2)),
(4, _MatmulMConfig(16, 32, 8, 4)),
(8, _MatmulMConfig(32, 128, 8, 5)),
(16, _MatmulMConfig(32, 128, 4, 4)),
(32, _MatmulMConfig(64, 128, 4, 3)),
(64, _MatmulMConfig(16, 256, 4, 3)),
(256, _MatmulMConfig(32, 128, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 4)),
(1024, _MatmulMConfig(128, 128, 8, 3)),
(2048, _MatmulMConfig(64, 128, 4, 5)),
),
),
(75968, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp2_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 3)),
(4, _MatmulMConfig(16, 256, 8, 3)),
(8, _MatmulMConfig(16, 256, 8, 3)),
(16, _MatmulMConfig(16, 256, 4, 3)),
(32, _MatmulMConfig(32, 256, 8, 3)),
(64, _MatmulMConfig(64, 256, 8, 3)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(3072, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp4_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 4, 3)),
(4, _MatmulMConfig(32, 128, 4, 5)),
(8, _MatmulMConfig(16, 128, 8, 3)),
(16, _MatmulMConfig(32, 128, 8, 4)),
(32, _MatmulMConfig(32, 128, 8, 5)),
(64, _MatmulMConfig(64, 32, 8, 3)),
(256, _MatmulMConfig(128, 64, 8, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(64, 64, 4, 5)),
(2048, _MatmulMConfig(64, 128, 8, 4)),
),
),
(2048, 1536): _MatmulShapeConfig( # Qwen3-1.7B tp4_down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 2)),
(4, _MatmulMConfig(16, 256, 4, 3)),
(8, _MatmulMConfig(32, 128, 4, 2)),
(16, _MatmulMConfig(32, 32, 8, 5)),
(32, _MatmulMConfig(32, 32, 8, 4)),
(64, _MatmulMConfig(32, 128, 4, 4)),
(256, _MatmulMConfig(64, 64, 4, 3)),
(512, _MatmulMConfig(128, 64, 8, 4)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 64, 8, 4)),
),
),
(1024, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp4_qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 4)),
(4, _MatmulMConfig(16, 32, 8, 4)),
(8, _MatmulMConfig(16, 32, 4, 4)),
(16, _MatmulMConfig(32, 128, 8, 3)),
(32, _MatmulMConfig(32, 128, 8, 4)),
(64, _MatmulMConfig(32, 64, 4, 5)),
(256, _MatmulMConfig(64, 32, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 5)),
(2048, _MatmulMConfig(128, 128, 8, 3)),
),
),
(2048, 512): _MatmulShapeConfig( # Qwen3-1.7B tp4_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 32, 4, 5)),
(4, _MatmulMConfig(64, 128, 4, 2)),
(8, _MatmulMConfig(16, 128, 4, 2)),
(16, _MatmulMConfig(16, 256, 8, 3)),
(32, _MatmulMConfig(64, 32, 8, 4)),
(64, _MatmulMConfig(16, 128, 8, 4)),
(256, _MatmulMConfig(64, 64, 8, 5)),
(512, _MatmulMConfig(32, 128, 8, 4)),
(1024, _MatmulMConfig(64, 64, 8, 3)),
(2048, _MatmulMConfig(64, 128, 8, 3)),
),
),
(37984, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp4_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 4)),
(4, _MatmulMConfig(16, 128, 8, 5)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 128, 8, 4)),
(32, _MatmulMConfig(32, 128, 4, 5)),
(64, _MatmulMConfig(64, 128, 4, 5)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(1536, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp8_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 3)),
(4, _MatmulMConfig(16, 256, 4, 3)),
(8, _MatmulMConfig(16, 32, 8, 5)),
(16, _MatmulMConfig(32, 32, 8, 3)),
(32, _MatmulMConfig(32, 128, 8, 4)),
(64, _MatmulMConfig(16, 128, 8, 4)),
(256, _MatmulMConfig(32, 128, 8, 3)),
(512, _MatmulMConfig(64, 128, 8, 4)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(64, 64, 4, 4)),
),
),
(2048, 768): _MatmulShapeConfig( # Qwen3-1.7B tp8_down_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(32, 64, 4, 3)),
(4, _MatmulMConfig(32, 64, 8, 3)),
(8, _MatmulMConfig(16, 32, 4, 5)),
(16, _MatmulMConfig(32, 64, 4, 2)),
(32, _MatmulMConfig(16, 64, 8, 3)),
(64, _MatmulMConfig(16, 32, 8, 2)),
(256, _MatmulMConfig(32, 32, 4, 4)),
(512, _MatmulMConfig(32, 64, 4, 5)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(512, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp8_qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(64, 64, 8, 5)),
(4, _MatmulMConfig(16, 32, 4, 4)),
(8, _MatmulMConfig(16, 32, 4, 5)),
(16, _MatmulMConfig(32, 128, 8, 3)),
(32, _MatmulMConfig(64, 64, 8, 5)),
(64, _MatmulMConfig(32, 128, 8, 4)),
(256, _MatmulMConfig(16, 128, 4, 4)),
(512, _MatmulMConfig(32, 64, 8, 3)),
(1024, _MatmulMConfig(64, 64, 4, 4)),
(2048, _MatmulMConfig(64, 128, 4, 4)),
),
),
(2048, 256): _MatmulShapeConfig( # Qwen3-1.7B tp8_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 2)),
(4, _MatmulMConfig(16, 128, 4, 2)),
(8, _MatmulMConfig(32, 256, 4, 2)),
(16, _MatmulMConfig(32, 32, 8, 4)),
(32, _MatmulMConfig(16, 256, 4, 3)),
(64, _MatmulMConfig(128, 32, 8, 3)),
(256, _MatmulMConfig(16, 32, 8, 2)),
(512, _MatmulMConfig(16, 32, 4, 3)),
(1024, _MatmulMConfig(64, 256, 4, 3)),
(2048, _MatmulMConfig(64, 128, 8, 4)),
),
),
(18992, 2048): _MatmulShapeConfig( # Qwen3-1.7B tp8_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 128, 8, 5)),
(8, _MatmulMConfig(16, 128, 8, 3)),
(16, _MatmulMConfig(16, 128, 4, 5)),
(32, _MatmulMConfig(32, 128, 8, 5)),
(64, _MatmulMConfig(64, 128, 8, 4)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 8, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(9728, 2560): _MatmulShapeConfig( # Qwen3-4B tp2_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 4)),
(4, _MatmulMConfig(16, 64, 8, 3)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(32, 64, 8, 4)),
(64, _MatmulMConfig(32, 128, 4, 3)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 5)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2560, 4864): _MatmulShapeConfig( # Qwen3-4B tp2_down_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 32, 4, 3)),
(4, _MatmulMConfig(16, 128, 8, 3)),
(8, _MatmulMConfig(16, 64, 8, 4)),
(16, _MatmulMConfig(32, 64, 8, 4)),
(32, _MatmulMConfig(16, 64, 4, 3)),
(64, _MatmulMConfig(32, 32, 8, 4)),
(256, _MatmulMConfig(64, 64, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(3072, 2560): _MatmulShapeConfig( # Qwen3-4B tp2_qkv_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 3)),
(4, _MatmulMConfig(16, 32, 8, 2)),
(8, _MatmulMConfig(16, 32, 8, 4)),
(16, _MatmulMConfig(16, 64, 4, 3)),
(32, _MatmulMConfig(32, 64, 4, 4)),
(64, _MatmulMConfig(16, 128, 4, 3)),
(256, _MatmulMConfig(64, 128, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(2560, 2048): _MatmulShapeConfig( # Qwen3-4B tp2_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 4)),
(4, _MatmulMConfig(32, 128, 4, 4)),
(8, _MatmulMConfig(16, 128, 4, 3)),
(16, _MatmulMConfig(32, 128, 4, 5)),
(32, _MatmulMConfig(16, 128, 8, 4)),
(64, _MatmulMConfig(16, 128, 8, 4)),
(256, _MatmulMConfig(128, 32, 8, 5)),
(512, _MatmulMConfig(128, 64, 8, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 8, 3)),
),
),
(75968, 2560): _MatmulShapeConfig( # Qwen3-4B tp2_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 64, 8, 5)),
(8, _MatmulMConfig(16, 64, 4, 5)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(32, 64, 4, 5)),
(64, _MatmulMConfig(64, 256, 4, 3)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 8, 3)),
),
),
(4864, 2560): _MatmulShapeConfig( # Qwen3-4B tp4_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 5)),
(4, _MatmulMConfig(16, 128, 4, 4)),
(8, _MatmulMConfig(16, 32, 8, 4)),
(16, _MatmulMConfig(16, 128, 8, 4)),
(32, _MatmulMConfig(16, 128, 4, 5)),
(64, _MatmulMConfig(16, 128, 4, 3)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2560, 2432): _MatmulShapeConfig( # Qwen3-4B tp4_down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 4)),
(4, _MatmulMConfig(16, 32, 4, 5)),
(8, _MatmulMConfig(32, 64, 8, 4)),
(16, _MatmulMConfig(32, 128, 8, 5)),
(32, _MatmulMConfig(16, 128, 4, 4)),
(64, _MatmulMConfig(64, 32, 4, 3)),
(256, _MatmulMConfig(32, 128, 8, 4)),
(512, _MatmulMConfig(64, 128, 4, 5)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(1536, 2560): _MatmulShapeConfig( # Qwen3-4B tp4_qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 4)),
(4, _MatmulMConfig(16, 32, 8, 3)),
(8, _MatmulMConfig(16, 32, 4, 4)),
(16, _MatmulMConfig(32, 128, 8, 3)),
(32, _MatmulMConfig(16, 128, 4, 3)),
(64, _MatmulMConfig(16, 64, 8, 4)),
(256, _MatmulMConfig(128, 32, 4, 5)),
(512, _MatmulMConfig(64, 128, 4, 5)),
(1024, _MatmulMConfig(64, 256, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 4)),
),
),
(2560, 1024): _MatmulShapeConfig( # Qwen3-4B tp4_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 5)),
(4, _MatmulMConfig(16, 32, 8, 3)),
(8, _MatmulMConfig(16, 128, 4, 3)),
(16, _MatmulMConfig(32, 256, 4, 3)),
(32, _MatmulMConfig(16, 128, 4, 2)),
(64, _MatmulMConfig(32, 256, 8, 3)),
(256, _MatmulMConfig(32, 128, 4, 5)),
(512, _MatmulMConfig(64, 128, 8, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(37984, 2560): _MatmulShapeConfig( # Qwen3-4B tp4_lm_head
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 3)),
(4, _MatmulMConfig(16, 128, 8, 3)),
(8, _MatmulMConfig(16, 128, 4, 3)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(16, 32, 4, 5)),
(64, _MatmulMConfig(32, 32, 4, 5)),
(256, _MatmulMConfig(64, 128, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(2432, 2560): _MatmulShapeConfig( # Qwen3-4B tp8_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 4, 5)),
(4, _MatmulMConfig(32, 128, 4, 3)),
(8, _MatmulMConfig(16, 128, 8, 3)),
(16, _MatmulMConfig(16, 128, 4, 4)),
(32, _MatmulMConfig(16, 128, 8, 4)),
(64, _MatmulMConfig(16, 128, 4, 3)),
(256, _MatmulMConfig(64, 64, 4, 5)),
(512, _MatmulMConfig(64, 128, 4, 4)),
(1024, _MatmulMConfig(128, 128, 8, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2560, 1216): _MatmulShapeConfig( # Qwen3-4B tp8_down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 2)),
(4, _MatmulMConfig(16, 128, 8, 4)),
(8, _MatmulMConfig(16, 32, 4, 3)),
(16, _MatmulMConfig(32, 32, 4, 3)),
(32, _MatmulMConfig(16, 128, 8, 4)),
(64, _MatmulMConfig(32, 128, 8, 4)),
(256, _MatmulMConfig(32, 128, 4, 5)),
(512, _MatmulMConfig(64, 128, 8, 4)),
(1024, _MatmulMConfig(64, 256, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(768, 2560): _MatmulShapeConfig( # Qwen3-4B tp8_qkv_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(32, 32, 4, 2)),
(4, _MatmulMConfig(16, 64, 8, 3)),
(8, _MatmulMConfig(16, 64, 8, 4)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(32, 64, 8, 4)),
(64, _MatmulMConfig(16, 64, 8, 4)),
(256, _MatmulMConfig(64, 32, 4, 5)),
(512, _MatmulMConfig(64, 64, 8, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 64, 4, 3)),
),
),
(2560, 512): _MatmulShapeConfig( # Qwen3-4B tp8_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 4)),
(4, _MatmulMConfig(16, 32, 4, 2)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(32, 32, 4, 5)),
(32, _MatmulMConfig(32, 256, 4, 3)),
(64, _MatmulMConfig(32, 128, 8, 5)),
(256, _MatmulMConfig(16, 256, 4, 2)),
(512, _MatmulMConfig(32, 128, 8, 4)),
(1024, _MatmulMConfig(128, 128, 8, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(18992, 2560): _MatmulShapeConfig( # Qwen3-4B tp8_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 4)),
(4, _MatmulMConfig(16, 64, 8, 5)),
(8, _MatmulMConfig(16, 128, 8, 3)),
(16, _MatmulMConfig(16, 128, 8, 5)),
(32, _MatmulMConfig(32, 128, 8, 5)),
(64, _MatmulMConfig(64, 128, 8, 4)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(12288, 4096): _MatmulShapeConfig( # Qwen3-8B tp2_gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 3)),
(4, _MatmulMConfig(16, 128, 8, 5)),
(8, _MatmulMConfig(16, 128, 8, 4)),
(16, _MatmulMConfig(16, 128, 4, 4)),
(32, _MatmulMConfig(32, 128, 4, 4)),
(64, _MatmulMConfig(64, 128, 4, 5)),
(256, _MatmulMConfig(64, 64, 4, 5)),
(512, _MatmulMConfig(128, 64, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(4096, 6144): _MatmulShapeConfig( # Qwen3-8B tp2_down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 5)),
(4, _MatmulMConfig(16, 32, 8, 5)),
(8, _MatmulMConfig(16, 32, 8, 3)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(16, 64, 8, 4)),
(64, _MatmulMConfig(32, 64, 4, 5)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 64, 8, 4)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(3072, 4096): _MatmulShapeConfig( # Qwen3-8B tp2_qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 4)),
(4, _MatmulMConfig(16, 32, 8, 3)),
(8, _MatmulMConfig(16, 128, 4, 3)),
(16, _MatmulMConfig(16, 32, 4, 4)),
(32, _MatmulMConfig(32, 32, 8, 5)),
(64, _MatmulMConfig(16, 128, 8, 4)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 8, 3)),
(1024, _MatmulMConfig(64, 64, 4, 5)),
(2048, _MatmulMConfig(128, 64, 4, 3)),
),
),
(75968, 4096): _MatmulShapeConfig( # Qwen3-8B tp2_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 3)),
(4, _MatmulMConfig(16, 256, 8, 3)),
(8, _MatmulMConfig(16, 256, 8, 3)),
(16, _MatmulMConfig(16, 256, 8, 3)),
(32, _MatmulMConfig(32, 256, 8, 3)),
(64, _MatmulMConfig(64, 256, 8, 3)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 8, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(4096, 3072): _MatmulShapeConfig( # Qwen3-8B tp4_down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 3)),
(4, _MatmulMConfig(16, 128, 4, 5)),
(8, _MatmulMConfig(16, 128, 4, 4)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(32, 128, 4, 3)),
(64, _MatmulMConfig(16, 128, 4, 4)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 64, 8, 4)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(1536, 4096): _MatmulShapeConfig( # Qwen3-8B tp4_qkv_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 4, 5)),
(4, _MatmulMConfig(16, 64, 8, 3)),
(8, _MatmulMConfig(32, 64, 4, 5)),
(16, _MatmulMConfig(16, 64, 8, 4)),
(32, _MatmulMConfig(16, 32, 8, 3)),
(64, _MatmulMConfig(16, 64, 8, 5)),
(256, _MatmulMConfig(64, 64, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 64, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(4096, 1024): _MatmulShapeConfig( # Qwen3-8B tp4_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 4)),
(4, _MatmulMConfig(32, 128, 8, 4)),
(8, _MatmulMConfig(16, 256, 8, 3)),
(16, _MatmulMConfig(16, 128, 8, 3)),
(32, _MatmulMConfig(16, 128, 4, 4)),
(64, _MatmulMConfig(64, 64, 4, 3)),
(256, _MatmulMConfig(128, 64, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 5)),
(1024, _MatmulMConfig(128, 64, 4, 4)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(37984, 4096): _MatmulShapeConfig( # Qwen3-8B tp4_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 3)),
(4, _MatmulMConfig(16, 128, 4, 5)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 128, 8, 3)),
(32, _MatmulMConfig(32, 128, 8, 3)),
(64, _MatmulMConfig(64, 128, 8, 3)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(4096, 1536): _MatmulShapeConfig( # Qwen3-8B tp8_down_proj
block_k=32,
m_buckets=(
(1, _MatmulMConfig(32, 128, 8, 5)),
(4, _MatmulMConfig(16, 256, 4, 5)),
(8, _MatmulMConfig(16, 64, 4, 4)),
(16, _MatmulMConfig(16, 128, 8, 3)),
(32, _MatmulMConfig(16, 64, 4, 3)),
(64, _MatmulMConfig(16, 128, 4, 4)),
(256, _MatmulMConfig(64, 128, 4, 4)),
(512, _MatmulMConfig(128, 128, 8, 5)),
(1024, _MatmulMConfig(128, 256, 8, 4)),
(2048, _MatmulMConfig(128, 128, 8, 4)),
),
),
(768, 4096): _MatmulShapeConfig( # Qwen3-8B tp8_qkv_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 5)),
(4, _MatmulMConfig(16, 32, 8, 3)),
(8, _MatmulMConfig(32, 64, 4, 5)),
(16, _MatmulMConfig(32, 64, 8, 3)),
(32, _MatmulMConfig(32, 32, 8, 5)),
(64, _MatmulMConfig(64, 32, 8, 3)),
(256, _MatmulMConfig(32, 64, 4, 4)),
(512, _MatmulMConfig(64, 64, 8, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 64, 4, 3)),
),
),
(4096, 512): _MatmulShapeConfig( # Qwen3-8B tp8_o_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 2)),
(4, _MatmulMConfig(32, 128, 4, 2)),
(8, _MatmulMConfig(16, 256, 4, 2)),
(16, _MatmulMConfig(32, 256, 4, 3)),
(32, _MatmulMConfig(32, 256, 8, 3)),
(64, _MatmulMConfig(32, 128, 4, 5)),
(256, _MatmulMConfig(64, 32, 8, 4)),
(512, _MatmulMConfig(128, 128, 8, 3)),
(1024, _MatmulMConfig(128, 64, 4, 4)),
(2048, _MatmulMConfig(128, 128, 8, 3)),
),
),
(18992, 4096): _MatmulShapeConfig( # Qwen3-8B tp8_lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 64, 8, 4)),
(8, _MatmulMConfig(16, 64, 8, 5)),
(16, _MatmulMConfig(16, 128, 4, 3)),
(32, _MatmulMConfig(32, 64, 8, 5)),
(64, _MatmulMConfig(64, 128, 8, 3)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
},
}
@@ -213,5 +213,10 @@ def _get_isa_hint(dtype: torch.dtype) -> str:
return "amx"
elif current_platform.get_cpu_architecture() == CpuArchEnum.RISCV:
return "rvv"
elif (
dtype == torch.bfloat16
and current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC
):
return "vsx"
else:
return "vec"
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Zentorch W4A16 GPTQ weight-only-quantized linear kernel for AMD Zen CPUs.
"""Zentorch int4 weight-quantized linear kernels for AMD Zen CPUs.
Selected by ``choose_mp_linear_kernel`` ahead of the generic oneDNN-backed
``CPUWNA16LinearKernel``. When ``can_implement`` rejects a layer, the selector
@@ -9,12 +9,13 @@ falls through to the next kernel in ``_POSSIBLE_KERNELS[PlatformEnum.CPU]``.
import torch
from vllm import envs
from vllm.logger import init_logger
from vllm.model_executor.kernels.linear.zentorch_utils import has_zentorch_op
from vllm.platforms import current_platform
from vllm.scalar_type import scalar_types
from .cpu import CPUWNA16LinearKernel
from .cpu import _CPUWNA16_SUPPORTED_QUANT_TYPES, CPUWNA16LinearKernel
from .MPLinearKernel import MPLinearLayerConfig
logger = init_logger(__name__)
@@ -34,17 +35,35 @@ def _import_unpack_from_int32():
class ZentorchWNA16LinearKernel(CPUWNA16LinearKernel):
"""W4A16 GPTQ kernel backed by ``torch.ops.zentorch.zentorch_woq_linear``."""
"""Int4 kernel backed by ``zentorch_dynamic_qlinear`` (DA8W4) or
``zentorch_woq_linear`` (W4A16)."""
@classmethod
def can_implement(cls, c: MPLinearLayerConfig) -> tuple[bool, str | None]:
ok, reason = super().can_implement(c)
if not ok:
return ok, reason
if not current_platform.is_zen_cpu():
return False, "ZentorchWNA16 requires an AMD Zen CPU."
# Not super(): its N/K multiple-of-32 rule is a oneDNN packing
# constraint the zentorch repack does not share.
if c.weight_type not in _CPUWNA16_SUPPORTED_QUANT_TYPES:
return (
False,
f"Quant type ({c.weight_type}) not supported by "
"CPUWNA16, supported types are: "
f"{_CPUWNA16_SUPPORTED_QUANT_TYPES}",
)
# -1 is per-channel, one group spanning K. Anything else has to divide
# K, which is stricter than the parent's multiple-of-2 rule.
if c.group_size != -1:
in_features = c.partition_weight_shape[0]
if c.group_size <= 0 or in_features % c.group_size != 0:
return (
False,
f"Group size ({c.group_size}) must divide input size "
f"({in_features})",
)
if not has_zentorch_op(["zentorch_woq_repack_weight", "zentorch_woq_linear"]):
return (
False,
@@ -89,8 +108,81 @@ class ZentorchWNA16LinearKernel(CPUWNA16LinearKernel):
num_groups = weight_scale.shape[1]
return num_groups > 0 and in_features % num_groups == 0
def _maybe_process_da8w4_weights(self, layer: torch.nn.Module) -> bool:
"""Repack ``layer`` into the DA8W4 layout, or leave it untouched.
Returns False without mutating the layer when it is not eligible, so
the caller falls through to the W4A16 paths.
"""
if not envs.VLLM_CPU_INT4_W4A8:
return False
if not has_zentorch_op(["zentorch_dynamic_qlinear"]):
return False
# DA8W4 is symmetric-only, and the kernel rejects f32 activations.
if self.config.zero_points or self.config.weight_type == scalar_types.uint4:
return False
if self.config.act_type != torch.bfloat16:
return False
if not self._zentorch_woq_eligible(layer):
return False
weight_q = getattr(layer, self.w_q_name)
weight_s = getattr(layer, self.w_s_name)
weight_packed = weight_q.data if hasattr(weight_q, "data") else weight_q
weight_scale = weight_s.data if hasattr(weight_s, "data") else weight_s
bits = self.config.weight_type.mantissa
pack_factor = torch.iinfo(weight_packed.dtype).bits // bits
out_features, num_groups = weight_scale.shape[0], weight_scale.shape[1]
in_features = weight_packed.shape[1] * pack_factor
# AOCL sym_quant requires K/G to be a multiple of 4; K must be even to
# pack two s4 values per byte.
if (in_features // num_groups) % 4 != 0 or in_features % 2 != 0:
return False
if self.w_zp_name is not None:
setattr(layer, self.w_zp_name, None)
unpack_from_int32 = _import_unpack_from_int32()
weight_unpacked = unpack_from_int32(
weight_packed,
bits,
torch.Size([out_features, in_features]),
packed_dim=weight_q.packed_dim,
)
# The WOQ repack packs 8 int4 per int32, which on little-endian is the
# same byte stream as s4 [N, K/2]; the kernel takes either view.
layer._zentorch_da8w4_packed = (
torch.ops.zentorch.zentorch_woq_repack_weight.default(
weight_unpacked.to(torch.int8).contiguous()
).view(torch.int8)
)
# CT stores scales as [N, G]; DA8W4 wants per-group {G, N}.
layer._zentorch_da8w4_scale = weight_scale.t().to(torch.bfloat16).contiguous()
for param_name in (self.w_q_name, self.w_s_name):
param = getattr(layer, param_name, None)
if param is not None and hasattr(param, "data"):
param.data = torch.empty(0)
layer._zentorch_kind = "compressed_tensors_w4a8_da8w4"
layer._zentorch_da8w4 = True
layer._zentorch_processed_weights = True
logger.info_once(
"[zen_cpu] Using zentorch_dynamic_qlinear for DA8W4 (W4A8) "
"(weight_type=%s, group_size=%d)",
self.config.weight_type,
in_features // num_groups,
)
return True
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
"""Repack CT GPTQ weights into the zentorch WOQ layout.
"""Repack CT GPTQ weights into the zentorch DA8W4 or WOQ layout.
Falls back to ``CPUWNA16LinearKernel.process_weights_after_loading``
via ``super()`` when the layer doesn't satisfy
@@ -101,6 +193,9 @@ class ZentorchWNA16LinearKernel(CPUWNA16LinearKernel):
if getattr(layer, "_zentorch_processed_weights", False):
return
if self._maybe_process_da8w4_weights(layer):
return
if not self._zentorch_woq_eligible(layer):
logger.info_once(
"[zen_cpu] ZentorchWNA16 fast path not eligible for this "
@@ -186,6 +281,16 @@ class ZentorchWNA16LinearKernel(CPUWNA16LinearKernel):
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
if getattr(layer, "_zentorch_da8w4", False):
# The kernel reads bias through a raw pointer, so it must be
# contiguous; the weight and scales already are.
return torch.ops.zentorch.zentorch_dynamic_qlinear.default(
x if x.dtype == torch.bfloat16 else x.to(torch.bfloat16),
layer._zentorch_da8w4_packed,
layer._zentorch_da8w4_scale,
bias.contiguous() if bias is not None else None,
)
if getattr(layer, "_zentorch_processed_weights", False):
return torch.ops.zentorch.zentorch_woq_linear.default(
x,
@@ -145,16 +145,16 @@ def _block32_tiled_kernel(
for kk in range(0, K_PER_SPLIT, BLOCK_K):
if EVEN_K:
x = tl.load(x_ptrs, mask=m_mask[:, None], other=0.0)
xs = tl.load(xs_ptrs, mask=m_mask[:, None], other=127)
xs = tl.load(xs_ptrs, mask=m_mask[:, None], other=0)
w = tl.load(w_ptrs, mask=n_mask[:, None], other=0.0)
ws = tl.load(ws_ptrs, mask=n_mask[:, None], other=127)
ws = tl.load(ws_ptrs, mask=n_mask[:, None], other=0)
else:
k_ok = (offs_k + kk) < K
s_ok = (offs_sk + kk // 32) < K // 32
x = tl.load(x_ptrs, mask=m_mask[:, None] & k_ok[None, :], other=0.0)
xs = tl.load(xs_ptrs, mask=m_mask[:, None] & s_ok[None, :], other=127)
xs = tl.load(xs_ptrs, mask=m_mask[:, None] & s_ok[None, :], other=0)
w = tl.load(w_ptrs, mask=n_mask[:, None] & k_ok[None, :], other=0.0)
ws = tl.load(ws_ptrs, mask=n_mask[:, None] & s_ok[None, :], other=127)
ws = tl.load(ws_ptrs, mask=n_mask[:, None] & s_ok[None, :], other=0)
acc = tl.dot_scaled(x, xs, "e4m3", w.T, ws, "e4m3", acc=acc)
x_ptrs += BLOCK_K
w_ptrs += BLOCK_K
@@ -240,9 +240,9 @@ def _block32_packed_kernel(
ws_mask = ws_mask & (wg < K // 32)
x = tl.load(x_ptr + rows[:, None] * K + xk, mask=x_mask, other=0.0)
w = tl.load(w_ptr + cols[:, None] * K + wk, mask=w_mask, other=0.0)
xs = tl.load(xs_ptr + rows[:, None] * (K // 32) + xg, mask=xs_mask, other=127)
xs = tl.load(xs_ptr + rows[:, None] * (K // 32) + xg, mask=xs_mask, other=0)
ws = tl.load(
ws_ptr + (cols[:, None] // 32) * (K // 32) + wg, mask=ws_mask, other=127
ws_ptr + (cols[:, None] // 32) * (K // 32) + wg, mask=ws_mask, other=0
)
acc = tl.dot_scaled(x, xs, "e4m3", w.T, ws, "e4m3", acc=acc)
# Keep only products of matching K panels: the block diagonal.
@@ -609,6 +609,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
vllm_config = get_current_vllm_config()
parallel_config = vllm_config.parallel_config
self.use_pcp = parallel_config.prefill_context_parallel_size > 1
self.pcp_shard_decode_requests = parallel_config.pcp_shard_decode_requests
compilation_config = vllm_config.compilation_config
if prefix in compilation_config.static_forward_context:
raise ValueError(f"Duplicate layer name: {prefix}")
@@ -784,6 +785,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
slot_mapping,
attn_metadata.num_decode_tokens if attn_metadata is not None else None,
self.use_pcp,
pcp_shard_decode_requests=self.pcp_shard_decode_requests,
)
assert slot_mapping is not None
if cache is not None:
@@ -1350,6 +1352,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
common_kwargs = dict(
block_size=vllm_config.cache_config.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.head_size,
dtype=kv_cache_dtype,
cache_dtype_str=self.kv_cache_dtype,
@@ -165,7 +165,6 @@ T = TypeVar("T", bound=SparseMLACommonMetadata)
class SparseMLACommonMetadataBuilder(AttentionMetadataBuilder[T]):
metadata_cls: type[T]
require_uniform_decodes: ClassVar[bool] = False
hisparse_supports_multi_token_decode: ClassVar[bool] = False
def __init__(
self,
@@ -259,8 +258,6 @@ class SparseMLACommonMetadataBuilder(AttentionMetadataBuilder[T]):
) -> None:
if self.vllm_config.attention_config.hisparse_config is not None:
reorder_batch_threshold = 1
if not self.hisparse_supports_multi_token_decode:
supports_spec_as_decode = False
super()._init_reorder_batch_threshold(
reorder_batch_threshold,
supports_spec_as_decode,
@@ -21,6 +21,8 @@ class AttentionLayerBase(ABC):
impl: "AttentionImpl"
supports_dcp: bool = True
# Set by the speculator on its draft model's layers.
is_draft_layer: bool = False
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
"""Bind the allocated KV cache tensor to this layer.
@@ -6,6 +6,7 @@ from typing import Union
import torch
import vllm.envs as envs
from vllm.config import ParallelConfig, SchedulerConfig
from vllm.config.kernel import MoEBackend
from vllm.distributed import get_dp_group, get_pcp_group, get_tensor_model_parallel_rank
@@ -1247,6 +1248,12 @@ class FusedMoEParallelConfig:
)
# Model types validated for VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1. This flag
# also changes the MXFP4 weight shuffle layout, so using it on other models
# can produce garbled output.
_AITER_MOE_A4W4_DSV4_VALIDATED_MODEL_TYPES = ("deepseek_v41", "deepseek_v41_text")
# Adapted from pplx-kernels tests/all_to_all_utils.py
@dataclass
class FusedMoEConfig:
@@ -1314,6 +1321,11 @@ class FusedMoEConfig:
tp_shard_with_padding: bool = False
rocm_aiter_fmoe_enabled: bool = False
aiter_fmoe_shared_expert_enabled: bool = False
# Whether to force MXFP4 (a4w4) MoE activations for DeepSeek V4.1 on
# ROCm/AITER. Opt-in via VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1; rejected
# for any other model type. Resolved here, not in the forward path,
# because get_current_vllm_config() isn't set there.
use_mxfp4_w4a4_dsv4: bool = False
def __post_init__(self):
from vllm._aiter_ops import rocm_aiter_ops
@@ -1345,6 +1357,29 @@ class FusedMoEConfig:
rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()
)
if self.rocm_aiter_fmoe_enabled and envs.VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4:
from vllm.config import get_current_vllm_config_or_none
vllm_config = get_current_vllm_config_or_none()
model_type = (
getattr(vllm_config.model_config.hf_config, "model_type", None)
if vllm_config is not None
else None
)
if model_type not in _AITER_MOE_A4W4_DSV4_VALIDATED_MODEL_TYPES:
raise ValueError(
f"VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1 only supports "
f"model_type in {_AITER_MOE_A4W4_DSV4_VALIDATED_MODEL_TYPES}, "
f"got {model_type!r}. Unset this env var for this model."
)
if not rocm_aiter_ops.fused_moe_supports_quant_dtype_a():
raise ValueError(
"VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1 needs an AITER build "
"with fused_moe(quant_dtype_a=...) support "
"(ROCm/aiter#5439+). Upgrade AITER or unset this env var."
)
self.use_mxfp4_w4a4_dsv4 = True
if self.use_mori_kernels:
assert self.rocm_aiter_fmoe_enabled, (
"Mori needs to be used with aiter fused_moe for now."
@@ -295,6 +295,7 @@ class AiterW4A16ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepseekV4,
RoutingMethodType.DeepSeekV3,
)
@staticmethod
@@ -344,6 +345,7 @@ class AiterW4A16ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepseekV4,
RoutingMethodType.DeepSeekV3,
]
@staticmethod
@@ -373,11 +375,20 @@ class AiterW4A16ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
score_mode = (
"sqrtsoftplus"
if self.moe_config.routing_method == RoutingMethodType.DeepseekV4
else None
)
routing_method = self.moe_config.routing_method
if routing_method == RoutingMethodType.DeepseekV4:
score_mode = "sqrtsoftplus"
elif routing_method == RoutingMethodType.DeepSeekV3:
# MiMo-V2.6: an ungrouped sigmoid router with a per-expert
# correction bias. aiter's flat top-k implements this natively
# (select on sigmoid(logits) + bias, return the unbiased sigmoid
# scores).
assert e_score_correction_bias is not None, (
"DeepSeekV3 routing requires e_score_correction_bias"
)
score_mode = "sigmoid"
else:
score_mode = None
return aiter_triton_kernel_w4a16_moe_forward(
hidden_states=hidden_states,
w1=w1,
@@ -51,6 +51,32 @@ from vllm.platforms import CpuArchEnum, current_platform
from vllm.utils.math_utils import round_up
logger = init_logger(__name__)
# ===========================================================================
# Weight layout
# ===========================================================================
def swigluoai_w13_interleave_perm(
experts_cls: type[mk.FusedMoEExperts],
activation: MoEActivation,
two_i: int,
device: torch.device,
) -> torch.Tensor | None:
"""Index taking a half-split w13 ``[gate | up]`` to the interleaved order
ZenDNN's ``swiglu_oai_mul`` expects, or None when no reorder is needed.
Callers apply it along whichever axis holds their output channels."""
if not getattr(experts_cls, "requires_interleaved_w13", False):
return None
if activation != MoEActivation.SWIGLUOAI:
return None
i = two_i // 2
return torch.stack(
[torch.arange(0, i, device=device), torch.arange(i, two_i, device=device)],
dim=1,
).flatten()
# ===========================================================================
# Unquantized (BF16/FP16/FP32) MoE
# ===========================================================================
@@ -1476,15 +1502,17 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
"ZenCPUExpertsInt8 requires per-channel weight scales on the layer."
)
num_experts = self.w1_scale.shape[0]
self._w1_scale_bf16 = (
# ZenDNN's fast routed MoE kernel only accepts f32 expert scales; bf16
# silently drops the layer onto the slower per-expert path.
self._w1_scale_f32 = (
self.w1_scale.detach()
.to(torch.bfloat16)
.to(torch.float32)
.reshape(num_experts, -1)
.contiguous()
)
self._w2_scale_bf16 = (
self._w2_scale_f32 = (
self.w2_scale.detach()
.to(torch.bfloat16)
.to(torch.float32)
.reshape(num_experts, -1)
.contiguous()
)
@@ -1611,8 +1639,8 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
topk_ids.to(torch.int32).contiguous(),
apply_router_weight_on_input, # skip_weighted
str(activation.value).lower(),
self._w1_scale_bf16,
self._w2_scale_bf16,
self._w1_scale_f32,
self._w2_scale_f32,
)
@@ -14,11 +14,14 @@ from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
NVFP4_PER_TOKEN_BASE_GLOBAL_SCALE,
activation_to_flashinfer_int,
quantize_nvfp4_per_token_input,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kNvfp4Dynamic,
kNvfp4DynamicToken,
kNvfp4Static,
)
from vllm.platforms import current_platform
@@ -40,6 +43,7 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
per_token_activation: bool = False,
):
super().__init__(
moe_config=moe_config,
@@ -63,6 +67,14 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
self.gemm1_clamp_limit = quant_config.gemm1_clamp_limit
self.situ_beta = moe_config.activation_situ_beta
self.situ_linear_beta = moe_config.activation_situ_linear_beta
self.per_token_activation = per_token_activation
self.per_token_global_scale = None
if per_token_activation:
assert quant_config.a2_gscale is not None
self.per_token_global_scale = quant_config.a2_gscale.new_full(
(1,),
NVFP4_PER_TOKEN_BASE_GLOBAL_SCALE,
)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
layer.w13_weight_scale_2.data.mul_(layer.w13_input_scale)
@@ -92,6 +104,7 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
) -> bool:
SUPPORTED_W_A = [
(kNvfp4Static, kNvfp4Dynamic),
(kNvfp4Static, kNvfp4DynamicToken),
]
return (weight_key, activation_key) in SUPPORTED_W_A
@@ -114,6 +127,10 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
@property
def expects_unquantized_inputs(self) -> bool:
return self.per_token_activation
def workspace_shapes(
self,
M: int,
@@ -127,8 +144,8 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
workspace1 = (0,)
workspace2 = (0,)
# K is packed (K//2 for uint8), so output uses hidden_dim.
assert self.hidden_dim == K * 2
expected_hidden_dim = K if self.expects_unquantized_inputs else K * 2
assert self.hidden_dim == expected_hidden_dim
output = (M, self.hidden_dim)
return (workspace1, workspace2, output)
@@ -151,13 +168,26 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
apply_router_weight_on_input: bool | None,
):
assert self.quant_dtype == "nvfp4"
assert a1q_scale is not None
assert self.w1_scale is not None
assert self.w2_scale is not None
if self.expects_unquantized_inputs:
hidden_states, block_scale, per_token_scale = (
quantize_nvfp4_per_token_input(hidden_states)
)
fc2_input_scale = self.per_token_global_scale
else:
assert a1q_scale is not None
block_scale = a1q_scale
per_token_scale = None
fc2_input_scale = self.a2_gscale
assert block_scale is not None
assert fc2_input_scale is not None
# a1q_scale is (M, K//16) float8_e4m3fn from fp4_quantize.
# The functional API expects x_sf with trailing dim: (M, K//16, 1).
x_sf = a1q_scale.unsqueeze(-1)
x_sf = block_scale.unsqueeze(-1)
# The kernel defaults swiglu_{alpha,beta,limit} to the plain-SwiGLU
# values, so only forward the ones the model actually sets.
@@ -188,6 +218,9 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
}
swiglu_kwargs = {k: v for k, v in swiglu_params.items() if v is not None}
per_token_kwargs = (
{"per_token_scale": per_token_scale} if self.per_token_activation else {}
)
flashinfer_cute_dsl_fused_moe_nvfp4(
x=hidden_states,
x_sf=x_sf,
@@ -196,7 +229,7 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
w1_weight=w1,
w1_weight_sf=self.w1_scale,
w1_alpha=self.g1_alphas,
fc2_input_scale=self.a2_gscale,
fc2_input_scale=fc2_input_scale,
w2_weight=w2,
w2_weight_sf=self.w2_scale,
w2_alpha=self.g2_alphas,
@@ -209,4 +242,5 @@ class FlashInferCuteDSLExperts(mk.FusedMoEExpertsModular):
MoEActivation.SILU if activation == MoEActivation.SITU else activation
),
**swiglu_kwargs,
**per_token_kwargs,
)
@@ -375,15 +375,13 @@ def rocm_aiter_fused_experts(
intermediate_pad // 64 * 64 * (2 if moe_config.tp_size == 1 else 1)
)
# https://github.com/ROCm/aiter/pull/3123 specialized the AITER stage1 GEMMs
# for interleaved vs separated gate and up weights.
# For gpt-oss i.e. use_mxfp4_w4a16=True, the weights are shuffled by
# `rocm_aiter_ops.shuffle_weight_a16w4` in `oracle/mxfp4.py`,
# which always sets `is_guinterleave=True`.
# Hence, we pass in GateMode.INTERLEAVE to match the weight shuffling.
# AITER's stage1 GEMM needs gate_mode to match how weights were
# shuffled at load time (oracle/mxfp4.py). gpt-oss uses INTERLEAVE;
# DeepSeek V4.1 a4w4 uses SEPARATED (see below).
from aiter.ops.flydsl.moe_common import GateMode
gate_mode = ""
q_dtype_a = None
if activation == MoEActivation.SITU:
gate_mode = (
GateMode.INTERLEAVE.value
@@ -391,7 +389,15 @@ def rocm_aiter_fused_experts(
else GateMode.SEPARATED.value
)
elif quant_config.use_mxfp4_w4a16:
gate_mode = GateMode.INTERLEAVE.value
if moe_config.use_mxfp4_w4a4_dsv4:
# Opt-in a4w4 for DeepSeek V4.1 (VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4=1).
# Must match the SEPARATED weight shuffle from load time.
from aiter import dtypes
gate_mode = GateMode.SEPARATED.value
q_dtype_a = dtypes.fp4x2
else:
gate_mode = GateMode.INTERLEAVE.value
elif activation_interleave is not None:
gate_mode = (
GateMode.INTERLEAVE.value
@@ -433,6 +439,7 @@ def rocm_aiter_fused_experts(
shared_w1_scale=shared_w1_scale,
shared_w2_scale=shared_w2_scale,
shared_expert_id=shared_expert_id,
q_dtype_a=q_dtype_a,
)
@@ -24,6 +24,7 @@ from vllm.model_executor.layers.fused_moe.utils import fi_moe_largest_bucket
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
activation_to_flashinfer_int,
has_flashinfer_situ_activation,
quantize_nvfp4_per_token_input,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
@@ -37,10 +38,6 @@ from vllm.utils.flashinfer import has_flashinfer_trtllm_fused_moe
logger = init_logger(__name__)
# Base scale for per-token NVFP4 activation quant; the kernel folds the
# per-token global scale (from the activation amax) on top of it.
_PER_TOKEN_BASE_GLOBAL_SCALE = 1.0 / (448.0 * 6.0)
class TrtLlmNvFp4ExpertsBase:
"""NvFp4 TRTLLM-Gen MoE kernels. Supports modular and monolithic interface."""
@@ -259,23 +256,6 @@ class TrtLlmNvFp4ExpertsBase:
def expects_unquantized_inputs(self) -> bool:
return self.per_token_activation
def _quantize_per_token_input(
self, hidden_states: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""NVFP4-quantize activations with a per-token global scale.
Returns ``(packed_fp4, block_scale, per_token_scale)``.
"""
from flashinfer import SfLayout, nvfp4_quantize
hs_fp4, hs_block_scale, per_token_scale = nvfp4_quantize(
hidden_states,
_PER_TOKEN_BASE_GLOBAL_SCALE,
sfLayout=SfLayout.layout_linear,
per_token_activation=True,
)
return hs_fp4, hs_block_scale, per_token_scale
def _get_chunk_size(self) -> int:
MAX_GRID_Y = 65535
MAX_TILE_TOKENS_DIM = 128
@@ -361,9 +341,9 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
# Per-token: input is unquantized, quantize it here. Otherwise it was
# already quantized in prepare() with the static global scale.
if self.per_token_activation:
if self.expects_unquantized_inputs:
hidden_states, block_scale, per_token_scale = (
self._quantize_per_token_input(hidden_states)
quantize_nvfp4_per_token_input(hidden_states)
)
else:
block_scale, per_token_scale = a1q_scale, None
@@ -437,7 +417,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
) -> UnfinalizedMoEOutput | None:
assert self._supports_activation(activation)
# Per-token defers input quant to _invoke_kernel, so a1q_scale is None.
assert a1q_scale is not None or self.per_token_activation
assert a1q_scale is not None or self.expects_unquantized_inputs
# DeepEP produces int64 indexes.
topk_ids = topk_ids.to(dtype=torch.int32)
@@ -539,7 +519,7 @@ class TrtLlmNvFp4ExpertsMonolithic(
import flashinfer
assert self._supports_activation(activation)
assert a1q_scale is not None or self.per_token_activation
assert a1q_scale is not None or self.expects_unquantized_inputs
assert self.quant_config.w1_scale is not None
assert self.quant_config.w2_scale is not None
assert (
@@ -551,9 +531,9 @@ class TrtLlmNvFp4ExpertsMonolithic(
)
# Per-token: input is unquantized, quantize it here (see modular apply).
if self.per_token_activation:
if self.expects_unquantized_inputs:
hidden_states, block_scale, per_token_scale = (
self._quantize_per_token_input(hidden_states)
quantize_nvfp4_per_token_input(hidden_states)
)
else:
block_scale, per_token_scale = a1q_scale, None
@@ -0,0 +1,204 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Zentorch fused MoE experts for AMD Zen CPUs."""
from collections.abc import Callable
import torch
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.model_executor.kernels.linear.zentorch_utils import (
_ZENTORCH_MOE_ACTIVATIONS,
_moe_activation_to_str,
has_zentorch_op,
)
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEParallelConfig,
FusedMoEQuantConfig,
RoutingMethodType,
)
from vllm.model_executor.layers.fused_moe.router.cpu_router import select_experts
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kInt4Static,
kInt4Static32,
)
class ZentorchExpertsInt4(mk.FusedMoEExpertsMonolithic):
"""DA8W4 (W4A8) group-quantized monolithic MoE experts."""
# swiglu_oai_mul reads gate/up interleaved, not in the half-split order the
# weight loader leaves behind.
requires_interleaved_w13 = True
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
):
super().__init__(moe_config, quant_config)
# Defaults hold until process_weights_after_loading sees the layer.
self.renormalize = moe_config.routing_method in (
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
)
self.custom_routing_function: Callable | None = None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
"""Capture the router config that the monolithic apply() signature
cannot carry; Custom routing has no other source for it."""
self.renormalize = layer.renormalize
self.custom_routing_function = layer.custom_routing_function
@property
def expects_unquantized_inputs(self) -> bool:
return True
@staticmethod
def activation_format() -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
@staticmethod
def _supports_current_device() -> bool:
return has_zentorch_op(["zentorch_fused_moe", "zentorch_woq_repack_weight"])
@staticmethod
def is_supported_config(
cls: type[mk.FusedMoEExperts],
moe_config: FusedMoEConfig,
weight_key: QuantKey | None,
activation_key: QuantKey | None,
activation_format: mk.FusedMoEActivationFormat,
) -> tuple[bool, str | None]:
supported, reason = mk.FusedMoEExperts.is_supported_config(
cls, moe_config, weight_key, activation_key, activation_format
)
if not supported:
return supported, reason
if moe_config.in_dtype != torch.bfloat16:
return False, "kernel requires bfloat16 activations"
# The grouped GEMM needs tokens spread over at least two experts, which
# top_k=1 cannot satisfy once decode drops to a single token.
if moe_config.experts_per_token < 2:
return False, "kernel requires experts_per_token >= 2"
return True, None
@staticmethod
def _supports_no_act_and_mul() -> bool:
return False
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
return _moe_activation_to_str(activation) in _ZENTORCH_MOE_ACTIVATIONS
@staticmethod
def _supports_parallel_config(
moe_parallel_config: FusedMoEParallelConfig,
) -> bool:
# apply() passes select_experts' global ids straight to the kernel, so
# every expert has to be resident on the rank.
return not moe_parallel_config.use_ep
@staticmethod
def _supports_quant_scheme(
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return (weight_key, activation_key) in [
(kInt4Static, None),
(kInt4Static32, None),
]
@staticmethod
def _supports_routing_method(
routing_method: RoutingMethodType,
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return routing_method in [
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.Custom,
]
@staticmethod
def _supports_router_logits_dtype(
router_logits_dtype: torch.dtype | None,
routing_method: RoutingMethodType,
) -> bool:
return True
def supports_expert_map(self) -> bool:
return False
def apply(
self,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
router_logits: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
apply_router_weight_on_input: bool,
# grouped topk + fused topk bias parameters
num_expert_group: int | None = None,
e_score_correction_bias: torch.Tensor | None = None,
routed_scaling_factor: float | None = None,
topk_group: int | None = None,
) -> torch.Tensor:
if apply_router_weight_on_input:
raise NotImplementedError(
"ZentorchExpertsInt4 does not support "
"apply_router_weight_on_input=True."
)
if (
self.moe_config.routing_method == RoutingMethodType.Custom
and self.custom_routing_function is None
):
raise RuntimeError(
"ZentorchExpertsInt4 needs the model's custom_routing_function "
"for RoutingMethodType.Custom."
)
topk_weights, topk_ids = select_experts(
hidden_states=hidden_states,
router_logits=router_logits,
use_grouped_topk=num_expert_group is not None,
top_k=self.moe_config.experts_per_token,
renormalize=self.renormalize,
topk_group=topk_group,
num_expert_group=num_expert_group,
custom_routing_function=self.custom_routing_function,
scoring_func="softmax",
routed_scaling_factor=(
routed_scaling_factor if routed_scaling_factor is not None else 1.0
),
e_score_correction_bias=e_score_correction_bias,
)
output = torch.empty_like(hidden_states)
torch.ops.zentorch.zentorch_fused_moe(
output,
hidden_states,
w1,
w2,
self.w1_bias,
self.w2_bias,
topk_weights,
topk_ids,
False, # skip_weighted
_moe_activation_to_str(activation),
self.w1_scale,
self.w2_scale,
)
return output
__all__ = ["ZentorchExpertsInt4"]
@@ -12,6 +12,7 @@ from compressed_tensors.quantization import (
import vllm._custom_ops as ops
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm import envs
from vllm.config.kernel import MoEBackend
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe.config import (
@@ -55,6 +56,7 @@ class WNA16MoEBackend(Enum):
BATCHED_MARLIN = "BATCHED_MARLIN"
HUMMING = "HUMMING"
CPU = "CPU"
ZEN_CPU = "ZEN_CPU"
FLASHINFER_TRTLLM = "FLASHINFER_TRTLLM"
TRITON = "TRITON"
XPU = "XPU"
@@ -98,6 +100,12 @@ def backend_to_kernel_cls(
)
return [CPUExpertsInt4]
elif backend == WNA16MoEBackend.ZEN_CPU:
from vllm.model_executor.layers.fused_moe.experts.zentorch_moe import (
ZentorchExpertsInt4,
)
return [ZentorchExpertsInt4]
elif backend == WNA16MoEBackend.EMULATION:
from vllm.model_executor.layers.fused_moe.experts.int4_emulation_moe import (
Int4EmulationTritonExperts,
@@ -117,7 +125,7 @@ def backend_to_kernel_cls(
def _get_priority_backends() -> list[WNA16MoEBackend]:
"""Get available backends in priority order based on platform and config."""
if current_platform.is_cpu():
return [WNA16MoEBackend.CPU]
return [WNA16MoEBackend.ZEN_CPU, WNA16MoEBackend.CPU]
if current_platform.is_xpu():
return [WNA16MoEBackend.XPU]
@@ -160,6 +168,27 @@ def _backend_incompatibility_reason(
from vllm.model_executor.layers.quantization.auto_gptq import AutoGPTQConfig
from vllm.model_executor.layers.quantization.moe_wna16 import MoeWNA16Config
if backend == WNA16MoEBackend.ZEN_CPU:
if not envs.VLLM_CPU_INT4_W4A8:
return "VLLM_CPU_INT4_W4A8=0 disables the DA8W4 path"
if may_have_zp:
return "zero points are not supported"
if isinstance(quant_config, MoeWNA16Config):
return "the MoeWNA16 weight layout is not supported"
if isinstance(quant_config, AutoGPTQConfig) and quant_config.desc_act:
return "GPTQ activation ordering is not supported"
if (
isinstance(quant_config, QuantizationArgs)
and quant_config.actorder == "group"
):
return "group activation ordering is not supported"
group_size = getattr(quant_config, "group_size", None)
if group_size is None or group_size <= 0:
return "DA8W4 requires group-quantized weights"
# AOCL sym_quant requires the group size to be a multiple of 4.
if group_size % 4 != 0:
return f"group size {group_size} is not a multiple of 4"
if backend == WNA16MoEBackend.TRITON:
if may_have_bias:
return "expert bias is not supported"
@@ -403,10 +432,14 @@ def make_wna16_moe_kernel(
from vllm.model_executor.layers.fused_moe.experts.xpu_moe import (
XPUExpertsWNA16,
)
from vllm.model_executor.layers.fused_moe.experts.zentorch_moe import (
ZentorchExpertsInt4,
)
# Currently, we only support TrtLlmMxint4ExpertsMonolithic, MarlinExperts,
# BatchedMarlinExperts, XPUExpertsWNA16, CPUExpertsInt4, the Humming
# grouped/indexed experts, and Int4EmulationTritonExperts
# BatchedMarlinExperts, XPUExpertsWNA16, CPUExpertsInt4,
# ZentorchExpertsInt4, the Humming grouped/indexed experts, and
# Int4EmulationTritonExperts
allowed_experts: tuple[type[mk.FusedMoEExperts], ...] = (
MarlinExperts,
BatchedMarlinExperts,
@@ -414,6 +447,7 @@ def make_wna16_moe_kernel(
TrtLlmMxint4ExpertsMonolithic,
XPUExpertsWNA16,
CPUExpertsInt4,
ZentorchExpertsInt4,
Int4EmulationTritonExperts,
Rdna3WNA16Experts,
)
@@ -1034,6 +1068,64 @@ def _process_weights_cpu(
)
def _zen_repack_s4(packed: torch.Tensor, in_features: int) -> torch.Tensor:
"""Repack CT int4 ``[E, N, K//8]`` into zentorch s4 ``[E, N, K//8]``."""
from vllm.model_executor.kernels.linear.mixed_precision.zentorch import (
_import_unpack_from_int32,
)
num_experts, out_features, _ = packed.shape
# packed_dim indexes the 2D expert slice, which is N-first, so K is dim 1.
unpacked = _import_unpack_from_int32()(
packed,
4,
torch.Size([num_experts, out_features, in_features]),
packed_dim=1,
)
# CT is already N-first, which is what the repack consumes.
repack_op = torch.ops.zentorch.zentorch_woq_repack_weight.default
return torch.stack([repack_op(w) for w in unpacked])
def _process_weights_zen_cpu(
w13: torch.Tensor,
w2: torch.Tensor,
w13_scale: torch.Tensor,
w2_scale: torch.Tensor,
w13_bias: torch.Tensor | None = None,
w2_bias: torch.Tensor | None = None,
) -> tuple[
torch.Tensor, # w13_qweight
torch.Tensor, # w2_qweight
torch.Tensor, # w13_scales
torch.Tensor, # w2_scales
torch.Tensor | None, # w13_qzeros
torch.Tensor | None, # w2_qzeros
torch.Tensor | None, # w13_input_global_scale
torch.Tensor | None, # w2_input_global_scale
torch.Tensor | None, # w13_bias
torch.Tensor | None, # w2_bias
]:
"""Zen CPU INT4 DA8W4 (W4A8) weight post-processing."""
# CT WNA16 buffers are N-first, so the scales are [E, N, G].
hidden_size = w2_scale.shape[1]
intermediate_size = w13_scale.shape[1] // 2
# The kernel reads per-group scales as [E, G, N], so N-first needs a swap.
return (
_zen_repack_s4(w13.data, hidden_size),
_zen_repack_s4(w2.data, intermediate_size),
w13_scale.data.transpose(1, 2).to(torch.bfloat16).contiguous(),
w2_scale.data.transpose(1, 2).to(torch.bfloat16).contiguous(),
None, # w13_qzeros (symmetric)
None, # w2_qzeros (symmetric)
None, # w13_input_global_scale
None, # w2_input_global_scale
w13_bias,
w2_bias,
)
def _process_weights_xpu(
layer: torch.nn.Module,
quant_config: QuantizationConfig,
@@ -1584,6 +1676,15 @@ def convert_to_wna16_moe_kernel_format(
w13_bias,
w2_bias,
)
elif backend == WNA16MoEBackend.ZEN_CPU:
return _process_weights_zen_cpu(
w13,
w2,
w13_scale,
w2_scale,
w13_bias,
w2_bias,
)
elif backend == WNA16MoEBackend.FLASHINFER_TRTLLM:
return _process_weights_flashinfer(
w13,
@@ -1382,6 +1382,7 @@ def convert_weight_to_mxfp4_moe_kernel_format(
w2_bias: torch.Tensor | None = None,
_cache_permute_indices: dict[torch.Size, torch.Tensor] | None = None,
activation: MoEActivation | None = None,
use_separated_a4w4: bool = False,
) -> tuple[
torch.Tensor,
torch.Tensor,
@@ -1626,10 +1627,16 @@ def convert_weight_to_mxfp4_moe_kernel_format(
from aiter.ops.shuffle import shuffle_scale as _shuf_s
from aiter.ops.shuffle import shuffle_weight as _shuf_w
# DeepSeek V4.1 a4w4 uses ATOM's SEPARATED gate/up layout instead of
# the default INTERLEAVE shuffle (INTERLEAVE + fp4x2 has no tuned
# kernel and produces garbage output). Must match GateMode.SEPARATED
# in rocm_aiter_moe.py.
is_guinterleave = not use_separated_a4w4
w13_weight = torch.nn.Parameter(
_shuf_w(
w13_weight.data.view(torch.float4_e2m1fn_x2),
is_guinterleave=True,
is_guinterleave=is_guinterleave,
gate_up=True,
),
requires_grad=False,
@@ -1637,14 +1644,14 @@ def convert_weight_to_mxfp4_moe_kernel_format(
shuffled_w13_scale = _shuf_s(
w13_weight_scale.reshape(-1, w13_weight_scale.shape[-1]),
num_experts,
True,
is_guinterleave,
True,
)
w2_weight = torch.nn.Parameter(
_shuf_w(
w2_weight.data.view(torch.float4_e2m1fn_x2),
is_guinterleave=True,
is_guinterleave=is_guinterleave,
gate_up=False,
),
requires_grad=False,
@@ -1653,7 +1660,7 @@ def convert_weight_to_mxfp4_moe_kernel_format(
shuffled_w2_scale = _shuf_s(
w2_weight_scale.reshape(-1, w2_weight_scale.shape[-1]),
num_experts,
True,
is_guinterleave,
False,
)

Some files were not shown because too many files have changed in this diff Show More