Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
+121
-2
@@ -1167,7 +1167,8 @@ def _rocm_aiter_fused_allreduce_rmsnorm_quant_per_group_impl(
|
||||
w=weight,
|
||||
eps=epsilon,
|
||||
group_size=group_size,
|
||||
registered=torch.cuda.is_current_stream_capturing(),
|
||||
registered=torch.cuda.is_current_stream_capturing()
|
||||
and ca.enable_register_for_capturing,
|
||||
use_1stage=use_1stage,
|
||||
)
|
||||
assert result is not None
|
||||
@@ -1219,7 +1220,8 @@ def _rocm_aiter_fused_allreduce_rmsnorm_quant_per_group_with_bf16_norm_impl(
|
||||
w=weight,
|
||||
eps=epsilon,
|
||||
group_size=group_size,
|
||||
registered=torch.cuda.is_current_stream_capturing(),
|
||||
registered=torch.cuda.is_current_stream_capturing()
|
||||
and ca.enable_register_for_capturing,
|
||||
use_1stage=use_1stage,
|
||||
emit_bf16=True,
|
||||
)
|
||||
@@ -1997,6 +1999,8 @@ class rocm_aiter_ops:
|
||||
|
||||
# Check if the env variable is set
|
||||
_AITER_ENABLED = envs.VLLM_ROCM_USE_AITER
|
||||
# Chunk length the AITER FlyDSL K5 prefill kernels are compiled for.
|
||||
GDN_FLYDSL_CHUNK_SIZE = 64
|
||||
_CUSTOM_ALL_REDUCE_ENABLED = envs.VLLM_ROCM_USE_AITER_CUSTOM_AR
|
||||
_LINEAR_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR
|
||||
_FMOE_ENABLED = envs.VLLM_ROCM_USE_AITER_MOE
|
||||
@@ -2467,6 +2471,23 @@ class rocm_aiter_ops:
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _gdn_flydsl_prefill_kernels_importable() -> bool:
|
||||
try:
|
||||
from aiter.ops.flydsl.linear_attention_prefill_kernels import ( # noqa: F401
|
||||
chunk_gated_delta_rule_fwd_h_flydsl_opt,
|
||||
gdn_prepare_flydsl_supported,
|
||||
gdn_prepare_fwd_flydsl,
|
||||
)
|
||||
from aiter.ops.triton.gated_delta_net import ( # noqa: F401
|
||||
build_gated_delta_rule_prefill_metadata,
|
||||
chunk_gated_delta_rule_opt_vk,
|
||||
)
|
||||
|
||||
return True
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def are_gdn_triton_kernels_available(cls) -> bool:
|
||||
@@ -2478,6 +2499,100 @@ class rocm_aiter_ops:
|
||||
"""
|
||||
return cls._AITER_ENABLED and cls._gdn_triton_kernels_importable()
|
||||
|
||||
@classmethod
|
||||
@functools.cache
|
||||
def is_gdn_flydsl_prefill_available(cls) -> bool:
|
||||
"""Whether the opt-in AITER FlyDSL GDN prefill path can be used.
|
||||
|
||||
Selecting the backend is an explicit opt-in in itself, but it still
|
||||
runs AITER kernels, so VLLM_ROCM_USE_AITER remains the one switch that
|
||||
turns all of them off.
|
||||
"""
|
||||
return (
|
||||
cls._AITER_ENABLED
|
||||
and is_aiter_found_and_supported()
|
||||
and cls._gdn_flydsl_prefill_kernels_importable()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def build_gdn_flydsl_prefill_metadata(
|
||||
cls,
|
||||
seq_lens_cpu: list[int],
|
||||
cu_seqlens: torch.Tensor,
|
||||
) -> object:
|
||||
"""Build the reusable varlen metadata FlyDSL GDN prefill runs against.
|
||||
|
||||
The K5 recurrence is compiled for a fixed 64-token chunk, so the chunk
|
||||
size is a property of the AITER kernel rather than of FLA, and is not
|
||||
the caller's to choose.
|
||||
"""
|
||||
from aiter.ops.triton.gated_delta_net import (
|
||||
build_gated_delta_rule_prefill_metadata,
|
||||
)
|
||||
|
||||
return build_gated_delta_rule_prefill_metadata(
|
||||
seq_lens_cpu,
|
||||
cu_seqlens=cu_seqlens,
|
||||
chunk_size=cls.GDN_FLYDSL_CHUNK_SIZE,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def gdn_flydsl_prefill(
|
||||
cls,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor,
|
||||
initial_state: torch.Tensor,
|
||||
output_final_state: bool,
|
||||
cu_seqlens: torch.Tensor | None,
|
||||
aiter_prefill_metadata: object | None,
|
||||
use_qk_l2norm_in_kernel: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Run GDN prefill through AITER's VK path with the FlyDSL kernels.
|
||||
|
||||
Every argument AITER takes is named here rather than forwarded as
|
||||
``**kwargs``, so a rename or reordering on the AITER side fails at this
|
||||
call instead of silently binding to the wrong parameter.
|
||||
"""
|
||||
from aiter.ops.flydsl.linear_attention_prefill_kernels import (
|
||||
gdn_prepare_flydsl_supported,
|
||||
)
|
||||
from aiter.ops.triton.gated_delta_net import chunk_gated_delta_rule_opt_vk
|
||||
|
||||
if cu_seqlens is not None and aiter_prefill_metadata is None:
|
||||
raise RuntimeError(
|
||||
"AITER FlyDSL GDN prefill requires reusable varlen prefill metadata."
|
||||
)
|
||||
if not gdn_prepare_flydsl_supported(k, v):
|
||||
raise RuntimeError(
|
||||
"AITER FlyDSL GDN prepare does not support the runtime input shape, "
|
||||
"dtype, or device."
|
||||
)
|
||||
logger.info_once(
|
||||
"Dispatching AITER FlyDSL GDN prefill (prepare=flydsl, chunk=flydsl)."
|
||||
)
|
||||
return chunk_gated_delta_rule_opt_vk(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
g=g,
|
||||
beta=beta,
|
||||
initial_state=initial_state,
|
||||
output_final_state=output_final_state,
|
||||
cu_seqlens=cu_seqlens,
|
||||
use_chunk_flydsl=True,
|
||||
use_prepare_flydsl=True,
|
||||
state_dtype=initial_state.dtype,
|
||||
prefill_metadata=aiter_prefill_metadata,
|
||||
# The caller stages the state densely and writes it back, so the
|
||||
# kernel gets a plain [N, H, V, K] buffer and never an index into
|
||||
# the pool; there is correspondingly nothing to update in place.
|
||||
inplace_final_state=False,
|
||||
use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_rdna_gdn_triton_kernels_available(cls) -> bool:
|
||||
"""RDNA4 (gfx12) analog of are_gdn_triton_kernels_available()."""
|
||||
@@ -2994,6 +3109,10 @@ class rocm_aiter_ops:
|
||||
transpose_scale,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_fused_mla_dual_rms_norm_group_quant_op() -> OpOverload:
|
||||
return torch.ops.vllm.fused_mla_dual_rms_norm_group_quant.default
|
||||
|
||||
@staticmethod
|
||||
def rms_norm(
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -27,7 +27,6 @@ from vllm.benchmarks.datasets.datasets import (
|
||||
RandomMultiModalDataset,
|
||||
SampleRequest,
|
||||
ShareGPTDataset,
|
||||
SonnetDataset,
|
||||
SpecBench,
|
||||
VisionArenaDataset,
|
||||
add_dataset_parser,
|
||||
@@ -71,7 +70,6 @@ __all__ = [
|
||||
"RandomMultiModalDataset",
|
||||
"SampleRequest",
|
||||
"ShareGPTDataset",
|
||||
"SonnetDataset",
|
||||
"SpecBench",
|
||||
"VisionArenaDataset",
|
||||
"add_dataset_parser",
|
||||
|
||||
@@ -12,8 +12,8 @@ Usage
|
||||
::
|
||||
|
||||
python -m vllm.benchmarks.datasets.create_txt_slices_dataset \\
|
||||
--input sonnet.txt \\
|
||||
--output sonnet_dataset.jsonl \\
|
||||
--input corpus.txt \\
|
||||
--output dataset.jsonl \\
|
||||
--tokenizer gpt2 \\
|
||||
--num-prompts 1000 \\
|
||||
--input-len 1024 \\
|
||||
@@ -23,7 +23,7 @@ The resulting JSONL file can then be used with the serving benchmark::
|
||||
|
||||
python -m vllm.benchmarks.serve \\
|
||||
--dataset-name custom \\
|
||||
--dataset-path sonnet_dataset.jsonl \\
|
||||
--dataset-path dataset.jsonl \\
|
||||
...
|
||||
"""
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ datasets. Each dataset subclass of BenchmarkDataset must implement sample
|
||||
generation. Supported dataset types include:
|
||||
- ShareGPT
|
||||
- Random (synthetic)
|
||||
- Sonnet
|
||||
- BurstGPT
|
||||
- HuggingFace
|
||||
- VisionArena
|
||||
@@ -31,7 +30,6 @@ from typing import Any, cast
|
||||
import numpy as np
|
||||
import pybase64 as base64
|
||||
from PIL import Image
|
||||
from typing_extensions import deprecated
|
||||
|
||||
from vllm.benchmarks.datasets.utils import (
|
||||
RangeRatio,
|
||||
@@ -1598,7 +1596,6 @@ def add_dataset_parser(parser: FlexibleArgumentParser):
|
||||
choices=[
|
||||
"sharegpt",
|
||||
"burstgpt",
|
||||
"sonnet",
|
||||
"random",
|
||||
"random-mm",
|
||||
"random-rerank",
|
||||
@@ -1622,8 +1619,7 @@ def add_dataset_parser(parser: FlexibleArgumentParser):
|
||||
"--dataset-path",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to the sharegpt/sonnet dataset or the HF dataset ID if "
|
||||
"using HF dataset.",
|
||||
help="Path to the ShareGPT dataset or the HF dataset ID if using HF dataset.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-oversample",
|
||||
@@ -1681,26 +1677,6 @@ def add_dataset_parser(parser: FlexibleArgumentParser):
|
||||
help="Category for spec bench dataset. If None, use all categories.",
|
||||
)
|
||||
|
||||
sonnet_group = parser.add_argument_group("sonnet dataset options")
|
||||
sonnet_group.add_argument(
|
||||
"--sonnet-input-len",
|
||||
type=int,
|
||||
default=550,
|
||||
help="Number of input tokens per request, used only for sonnet dataset.",
|
||||
)
|
||||
sonnet_group.add_argument(
|
||||
"--sonnet-output-len",
|
||||
type=int,
|
||||
default=150,
|
||||
help="Number of output tokens per request, used only for sonnet dataset.",
|
||||
)
|
||||
sonnet_group.add_argument(
|
||||
"--sonnet-prefix-len",
|
||||
type=int,
|
||||
default=200,
|
||||
help="Number of prefix tokens per request, used only for sonnet dataset.",
|
||||
)
|
||||
|
||||
sharegpt_group = parser.add_argument_group("sharegpt dataset options")
|
||||
sharegpt_group.add_argument(
|
||||
"--sharegpt-output-len",
|
||||
@@ -2134,45 +2110,6 @@ def get_samples(
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
|
||||
elif args.dataset_name == "sonnet":
|
||||
assert tokenizer is not None, (
|
||||
"Tokenizer must be initialized for the 'sonnet' dataset."
|
||||
)
|
||||
sonnet_dataset = SonnetDataset(
|
||||
dataset_path=args.dataset_path, disable_shuffle=args.disable_shuffle
|
||||
)
|
||||
# For the "sonnet" dataset, formatting depends on the backend.
|
||||
# Chat-style backends leave templating to the server; completions
|
||||
# backends need the prompt rendered client side.
|
||||
if args.backend in ("openai-chat", "openai-responses"):
|
||||
input_requests = sonnet_dataset.sample(
|
||||
num_requests=args.num_prompts,
|
||||
input_len=args.sonnet_input_len,
|
||||
output_len=args.sonnet_output_len,
|
||||
prefix_len=args.sonnet_prefix_len,
|
||||
tokenizer=tokenizer,
|
||||
return_prompt_formatted=False,
|
||||
request_id_prefix=args.request_id_prefix,
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
else:
|
||||
assert (
|
||||
hasattr(tokenizer, "chat_template") and tokenizer.chat_template
|
||||
) or (
|
||||
hasattr(tokenizer, "default_chat_template")
|
||||
and tokenizer.default_chat_template
|
||||
), "Tokenizer/model must have chat template for sonnet dataset."
|
||||
input_requests = sonnet_dataset.sample(
|
||||
num_requests=args.num_prompts,
|
||||
input_len=args.sonnet_input_len,
|
||||
output_len=args.sonnet_output_len,
|
||||
prefix_len=args.sonnet_prefix_len,
|
||||
tokenizer=tokenizer,
|
||||
return_prompt_formatted=True,
|
||||
request_id_prefix=args.request_id_prefix,
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
|
||||
elif args.dataset_name == "hf":
|
||||
# all following datasets are implemented from the
|
||||
# HuggingFaceDataset base class
|
||||
@@ -3070,106 +3007,6 @@ class SpecBench(CustomDataset):
|
||||
)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Sonnet Dataset Implementation
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
@deprecated(
|
||||
"SonnetDataset is deprecated and will be removed in a future version.",
|
||||
)
|
||||
class SonnetDataset(BenchmarkDataset):
|
||||
"""Simplified implementation of the Sonnet dataset. Loads poem lines from a
|
||||
text file and generates sample requests. Default values here copied from
|
||||
`benchmark_serving.py` for the sonnet dataset.
|
||||
"""
|
||||
|
||||
DEFAULT_PREFIX_LEN = 200
|
||||
DEFAULT_INPUT_LEN = 550
|
||||
DEFAULT_OUTPUT_LEN = 150
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
super().__init__(**kwargs)
|
||||
self.load_data()
|
||||
|
||||
def load_data(self) -> None:
|
||||
if not self.dataset_path:
|
||||
raise ValueError("dataset_path must be provided.")
|
||||
with open(self.dataset_path, encoding="utf-8") as f:
|
||||
self.data = f.readlines()
|
||||
|
||||
def sample(
|
||||
self,
|
||||
tokenizer: TokenizerLike,
|
||||
num_requests: int,
|
||||
request_id_prefix: str = "",
|
||||
no_oversample: bool = False,
|
||||
prefix_len: int = DEFAULT_PREFIX_LEN,
|
||||
input_len: int = DEFAULT_INPUT_LEN,
|
||||
output_len: int = DEFAULT_OUTPUT_LEN,
|
||||
return_prompt_formatted: bool = False,
|
||||
**kwargs,
|
||||
) -> list[SampleRequest]:
|
||||
poem_lines = self.data
|
||||
assert poem_lines is not None
|
||||
# Calculate average token length for a poem line.
|
||||
tokenized_lines = [tokenizer(line).input_ids for line in poem_lines]
|
||||
avg_len = sum(len(tokens) for tokens in tokenized_lines) / len(tokenized_lines)
|
||||
|
||||
# Build the base prompt.
|
||||
base_prompt = "Pick as many lines as you can from these poem lines:\n"
|
||||
base_msg = [{"role": "user", "content": base_prompt}]
|
||||
base_fmt = tokenizer.apply_chat_template(
|
||||
base_msg, # type: ignore[arg-type]
|
||||
add_generation_prompt=True,
|
||||
tokenize=False,
|
||||
)
|
||||
assert isinstance(base_fmt, str)
|
||||
base_offset = len(tokenizer(base_fmt).input_ids)
|
||||
if input_len <= base_offset:
|
||||
raise ValueError(
|
||||
f"'input_len' must be higher than the base prompt length "
|
||||
f"({base_offset})."
|
||||
)
|
||||
|
||||
# Determine how many poem lines to use.
|
||||
num_input_lines = max(round((input_len - base_offset) / avg_len), 1)
|
||||
num_prefix_lines = max(round((prefix_len - base_offset) / avg_len), 0)
|
||||
prefix_lines = poem_lines[:num_prefix_lines]
|
||||
|
||||
samples: list[SampleRequest] = []
|
||||
ind = 0
|
||||
while len(samples) < num_requests:
|
||||
extra_lines = random.choices(
|
||||
poem_lines, k=num_input_lines - num_prefix_lines
|
||||
)
|
||||
prompt = f"{base_prompt}{''.join(prefix_lines + extra_lines)}"
|
||||
msg = [{"role": "user", "content": prompt}]
|
||||
prompt_formatted = tokenizer.apply_chat_template(
|
||||
msg, # type: ignore[arg-type]
|
||||
add_generation_prompt=True,
|
||||
tokenize=False,
|
||||
)
|
||||
assert isinstance(prompt_formatted, str)
|
||||
prompt_len = len(tokenizer(prompt_formatted).input_ids)
|
||||
if prompt_len <= input_len:
|
||||
samples.append(
|
||||
SampleRequest(
|
||||
prompt=(
|
||||
prompt_formatted if return_prompt_formatted else prompt
|
||||
),
|
||||
prompt_len=prompt_len,
|
||||
expected_output_len=output_len,
|
||||
request_id=request_id_prefix + str(ind),
|
||||
)
|
||||
)
|
||||
ind += 1
|
||||
return samples
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# BurstGPT Dataset Implementation
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
@@ -119,6 +119,7 @@ def main(args: argparse.Namespace):
|
||||
beam_width=args.n,
|
||||
max_tokens=args.output_len,
|
||||
ignore_eos=True,
|
||||
watermarking=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -122,8 +122,6 @@ def _validate_api_url(
|
||||
if isinstance(expected_suffixes, str):
|
||||
expected_suffixes = {expected_suffixes}
|
||||
|
||||
expected_suffixes = {*expected_suffixes, "profile"}
|
||||
|
||||
if not api_url.endswith(tuple(expected_suffixes)):
|
||||
raise ValueError(f"{api_name} URL must end with one of: {expected_suffixes}.")
|
||||
|
||||
@@ -158,6 +156,34 @@ def _get_headers(content_type: str | None = None) -> dict[str, str]:
|
||||
return headers
|
||||
|
||||
|
||||
async def async_request_profile(
|
||||
api_url: str,
|
||||
session: aiohttp.ClientSession,
|
||||
extra_headers: dict | None = None,
|
||||
) -> RequestFuncOutput:
|
||||
_validate_api_url(
|
||||
api_url,
|
||||
"Profiling API",
|
||||
{"start_profile", "stop_profile"},
|
||||
)
|
||||
|
||||
headers = _get_headers()
|
||||
if extra_headers:
|
||||
headers |= extra_headers
|
||||
|
||||
output = RequestFuncOutput()
|
||||
try:
|
||||
async with session.post(url=api_url, headers=headers) as response:
|
||||
output.success = response.status == 200
|
||||
if not output.success:
|
||||
output.error = response.reason or ""
|
||||
except Exception:
|
||||
exc_info = sys.exc_info()
|
||||
output.error = "".join(traceback.format_exception(*exc_info))
|
||||
|
||||
return output
|
||||
|
||||
|
||||
async def async_request_openai_completions(
|
||||
request_func_input: RequestFuncInput,
|
||||
session: aiohttp.ClientSession,
|
||||
|
||||
@@ -241,6 +241,7 @@ def benchmark_multimodal_processor(
|
||||
temperature=0.0,
|
||||
max_tokens=output_len,
|
||||
detokenize=True,
|
||||
watermarking=False,
|
||||
)
|
||||
for output_len in expected_output_lens
|
||||
]
|
||||
@@ -262,7 +263,8 @@ def benchmark_multimodal_processor(
|
||||
warmup_prompts = [req.prompt for req in warmup_requests]
|
||||
warmup_output_lens = [req.expected_output_len for req in warmup_requests]
|
||||
warmup_sampling_params = [
|
||||
SamplingParams(max_tokens=output_len) for output_len in warmup_output_lens
|
||||
SamplingParams(max_tokens=output_len, watermarking=False)
|
||||
for output_len in warmup_output_lens
|
||||
]
|
||||
llm.chat(
|
||||
warmup_prompts,
|
||||
|
||||
+14
-39
@@ -49,6 +49,7 @@ from vllm.benchmarks.lib.endpoint_request_func import (
|
||||
POOLING_BACKENDS,
|
||||
RequestFuncInput,
|
||||
RequestFuncOutput,
|
||||
async_request_profile,
|
||||
)
|
||||
from vllm.benchmarks.lib.ready_checker import wait_for_endpoint
|
||||
from vllm.benchmarks.lib.utils import (
|
||||
@@ -252,7 +253,7 @@ async def fetch_spec_decode_metrics(
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
accepted_per_pos=accepted_per_pos,
|
||||
)
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
return None
|
||||
|
||||
|
||||
@@ -314,7 +315,7 @@ async def fetch_diffusion_metrics(
|
||||
num_canvas_positions=num_canvas_positions,
|
||||
num_committed_tokens=num_committed_tokens,
|
||||
)
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
except (TimeoutError, aiohttp.ClientError):
|
||||
return None
|
||||
|
||||
|
||||
@@ -936,22 +937,10 @@ async def benchmark(
|
||||
|
||||
if profile:
|
||||
print("Starting profiler...")
|
||||
profile_input = RequestFuncInput(
|
||||
model=model_id,
|
||||
model_name=model_name,
|
||||
prompt=test_prompt,
|
||||
api_url=base_url + "/start_profile",
|
||||
prompt_len=test_prompt_len,
|
||||
output_len=test_output_len,
|
||||
logprobs=logprobs,
|
||||
multi_modal_content=test_mm_content,
|
||||
ignore_eos=ignore_eos,
|
||||
profile_output = await async_request_profile(
|
||||
base_url + "/start_profile",
|
||||
session,
|
||||
extra_headers=extra_headers,
|
||||
extra_body=test_extra_body,
|
||||
chat_messages=test_chat_messages,
|
||||
)
|
||||
profile_output = await request_func(
|
||||
request_func_input=profile_input, session=session
|
||||
)
|
||||
if profile_output.success:
|
||||
print("Profiler started")
|
||||
@@ -1469,16 +1458,10 @@ async def benchmark(
|
||||
|
||||
if profile:
|
||||
print("Stopping profiler...")
|
||||
profile_input = RequestFuncInput(
|
||||
model=model_id,
|
||||
prompt=test_prompt,
|
||||
api_url=base_url + "/stop_profile",
|
||||
prompt_len=test_prompt_len,
|
||||
output_len=test_output_len,
|
||||
logprobs=logprobs,
|
||||
)
|
||||
profile_output = await request_func(
|
||||
request_func_input=profile_input, session=session
|
||||
profile_output = await async_request_profile(
|
||||
base_url + "/stop_profile",
|
||||
session,
|
||||
extra_headers=extra_headers,
|
||||
)
|
||||
if profile_output.success:
|
||||
print("Profiler stopped")
|
||||
@@ -1670,8 +1653,7 @@ def add_cli_args(parser: FlexibleArgumentParser):
|
||||
"--input-len",
|
||||
type=int,
|
||||
default=None,
|
||||
help="General input length for datasets. Maps to dataset-specific "
|
||||
"input length arguments (e.g., --random-input-len, --sonnet-input-len). "
|
||||
help="General input length for datasets. Maps to --random-input-len. "
|
||||
"If not specified, uses dataset defaults.",
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -1679,7 +1661,7 @@ def add_cli_args(parser: FlexibleArgumentParser):
|
||||
type=int,
|
||||
default=None,
|
||||
help="General output length for datasets. Maps to dataset-specific "
|
||||
"output length arguments (e.g., --random-output-len, --sonnet-output-len). "
|
||||
"output length arguments (e.g., --random-output-len, --hf-output-len). "
|
||||
"If not specified, uses dataset defaults.",
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -2132,18 +2114,16 @@ async def main_async(args: argparse.Namespace) -> dict[str, Any]:
|
||||
raise ValueError(
|
||||
f"Cannot use '{args.dataset_name}' dataset with --dataset-path. "
|
||||
"Please specify the appropriate --dataset-name (e.g., "
|
||||
"'sharegpt', 'custom', 'sonnet') for your dataset file: "
|
||||
"'sharegpt', 'custom', 'hf') for your dataset file: "
|
||||
f"{args.dataset_path}"
|
||||
)
|
||||
|
||||
# Map general --input-len and --output-len to all dataset-specific arguments
|
||||
# Map general length options to dataset-specific arguments.
|
||||
if args.input_len is not None:
|
||||
args.random_input_len = args.input_len
|
||||
args.sonnet_input_len = args.input_len
|
||||
|
||||
if args.output_len is not None:
|
||||
args.random_output_len = args.output_len
|
||||
args.sonnet_output_len = args.output_len
|
||||
args.sharegpt_output_len = args.output_len
|
||||
args.custom_output_len = args.output_len
|
||||
args.hf_output_len = args.output_len
|
||||
@@ -2216,11 +2196,6 @@ async def main_async(args: argparse.Namespace) -> dict[str, Any]:
|
||||
"Sampling parameters are only supported by openai-compatible backends."
|
||||
)
|
||||
|
||||
# The Responses API accepts every sampling parameter above except
|
||||
# min_p, which it would silently drop as an unknown field.
|
||||
if args.backend == "openai-responses" and "min_p" in sampling_params:
|
||||
raise ValueError("--min-p is not supported by the Responses API.")
|
||||
|
||||
if "temperature" not in sampling_params:
|
||||
print(
|
||||
"WARNING: vllm bench serve no longer sets temperature==0 (greedy) "
|
||||
|
||||
@@ -8,9 +8,9 @@ from dataclasses import dataclass
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar, Self
|
||||
|
||||
from typing_extensions import Self, override
|
||||
from typing_extensions import override
|
||||
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.collection_utils import full_groupby
|
||||
|
||||
@@ -4,10 +4,9 @@ import argparse
|
||||
import math
|
||||
from dataclasses import dataclass, fields
|
||||
from pathlib import Path
|
||||
from typing import ClassVar, Literal, get_args
|
||||
from typing import ClassVar, Literal, assert_never, get_args
|
||||
|
||||
import numpy as np
|
||||
from typing_extensions import assert_never
|
||||
|
||||
from vllm.benchmarks.datasets import DEFAULT_NUM_PROMPTS
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
@@ -6,9 +6,9 @@ import signal
|
||||
import subprocess
|
||||
import time
|
||||
from types import TracebackType
|
||||
from typing import Self
|
||||
|
||||
import requests
|
||||
from typing_extensions import Self
|
||||
|
||||
|
||||
class ServerProcess:
|
||||
|
||||
@@ -178,6 +178,7 @@ def _run_vllm_requests(
|
||||
beam_width=n,
|
||||
max_tokens=output_len,
|
||||
ignore_eos=True,
|
||||
watermarking=False,
|
||||
),
|
||||
)
|
||||
if do_profile:
|
||||
@@ -553,10 +554,6 @@ def _to_serve_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
# matching prior throughput behaviour of omitting output_len when unset.
|
||||
d["hf_output_len"] = output_len
|
||||
d["sharegpt_output_len"] = output_len
|
||||
# sonnet reads dedicated attrs; fall back to SonnetDataset's own defaults.
|
||||
d["sonnet_input_len"] = input_len if input_len is not None else 550
|
||||
d["sonnet_output_len"] = output_len if output_len is not None else 150
|
||||
d["sonnet_prefix_len"] = prefix_len
|
||||
# Explicit --enable-multimodal-chat wins; otherwise auto-enable for the
|
||||
# multimodal chat backend (preserves today's vllm-chat handling). Callers
|
||||
# without a --backend flag (e.g. bench mm-processor) drive every request
|
||||
@@ -709,14 +706,14 @@ def validate_args(args):
|
||||
)
|
||||
|
||||
# --prefix-len: only used when dataset_name is 'random', 'random-mm',
|
||||
# 'sonnet', or not set.
|
||||
# or not set.
|
||||
if (
|
||||
args.dataset_name not in {"random", "random-mm", "sonnet", None}
|
||||
args.dataset_name not in {"random", "random-mm", None}
|
||||
and args.prefix_len is not None
|
||||
):
|
||||
warnings.warn(
|
||||
"--prefix-len will be ignored since --dataset-name\
|
||||
is not 'random', 'random-mm', 'sonnet', or not set.",
|
||||
is not 'random', 'random-mm', or not set.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
@@ -802,7 +799,6 @@ def add_cli_args(parser: FlexibleArgumentParser):
|
||||
choices=[
|
||||
"sharegpt",
|
||||
"random",
|
||||
"sonnet",
|
||||
"burstgpt",
|
||||
"hf",
|
||||
"prefix_repetition",
|
||||
|
||||
@@ -1088,10 +1088,13 @@ class VllmBackend:
|
||||
# Honors opt-outs such as CompilationMode.NONE or VLLM_DISABLE_COMPILE_CACHE.
|
||||
disable_cache = not is_compile_cache_enabled(self.inductor_config)
|
||||
|
||||
# TODO(patchy): ngram gpu kernel will cause vllm torch compile cache errors.
|
||||
# TODO(patchy): the V1 torch.compile ngram-gpu kernel causes vllm
|
||||
# torch compile cache errors. The V2 implementation is pure Triton and
|
||||
# does not need the cache disabled.
|
||||
is_ngram_gpu_enabled = (
|
||||
vllm_config.speculative_config is not None
|
||||
and vllm_config.speculative_config.use_ngram_gpu()
|
||||
and not vllm_config.use_v2_model_runner
|
||||
)
|
||||
disable_cache = disable_cache or is_ngram_gpu_enabled
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1074,16 +1074,148 @@ class MLADualRMSPerTokenQuantPattern(
|
||||
return _replacement
|
||||
|
||||
|
||||
class MLADualRMSGroupQuantPattern(
|
||||
VllmPatternReplacement[
|
||||
...,
|
||||
tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
],
|
||||
]
|
||||
):
|
||||
"""Fuse the MLA FP8 *block-scale* attention path -- q-latent RMSNorm + FP8
|
||||
group quant plus kv-latent RMSNorm -- into AITER's
|
||||
``fused_qk_rmsnorm_group_quant``.
|
||||
|
||||
With a block-scale FP8 ``q_b_proj`` (DeepSeek fp8), the earlier
|
||||
``RocmAiterRMSNormQuantFusionPass`` folds the q side into
|
||||
``rocm_aiter_rmsnorm_fp8_group_quant`` (the Triton rms+group-quant kernel)
|
||||
and leaves the kv side a plain ``vllm_ir.rms_norm``. This pattern matches
|
||||
that asymmetric pair::
|
||||
|
||||
gemm -> split_with_sizes([q_dim, kv_dim])
|
||||
+-- q_c -> rocm_aiter_rmsnorm_fp8_group_quant -> (q_fp8, q_scale)
|
||||
+-- kv_lora -> split_with_sizes([kv_c_dim, k_pe_dim])
|
||||
+-- kv_c -> vllm_ir.rms_norm -> kv_normed (bf16)
|
||||
+-- k_pe
|
||||
"""
|
||||
|
||||
GROUP_QUANT_OP = rocm_aiter_ops.get_rmsnorm_group_fused_quant_op()
|
||||
FUSED_OP = rocm_aiter_ops.get_fused_mla_dual_rms_norm_group_quant_op()
|
||||
|
||||
def __init__(self, epsilon: float) -> None:
|
||||
self._epsilon = epsilon
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
q_dim, kv_c_dim, k_pe_dim = 256, 128, 64
|
||||
return [
|
||||
self.empty_bf16(5, q_dim + kv_c_dim + k_pe_dim),
|
||||
self.empty_bf16(q_dim),
|
||||
self.empty_bf16(kv_c_dim),
|
||||
]
|
||||
|
||||
@property
|
||||
def pattern(
|
||||
self,
|
||||
) -> Callable[
|
||||
...,
|
||||
tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
],
|
||||
]:
|
||||
eps = self._epsilon
|
||||
group_quant_op = self.GROUP_QUANT_OP
|
||||
|
||||
def _pattern(
|
||||
projected: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
kv_weight: torch.Tensor,
|
||||
) -> tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
]:
|
||||
q_dim = q_weight.shape[0]
|
||||
kv_dim = projected.shape[-1] - q_dim
|
||||
kv_c_dim = kv_weight.shape[0]
|
||||
k_pe_dim = kv_dim - kv_c_dim
|
||||
q_c, kv_lora = projected.split([q_dim, kv_dim], dim=-1)
|
||||
kv_c, k_pe = kv_lora.split([kv_c_dim, k_pe_dim], dim=-1)
|
||||
quant_kwargs = dict(
|
||||
x=q_c,
|
||||
weight=q_weight,
|
||||
variance_epsilon=eps,
|
||||
group_size=128,
|
||||
)
|
||||
q_quant = group_quant_op(**quant_kwargs)
|
||||
kv_normed = vllm.ir.ops.rms_norm(kv_c, kv_weight, eps)
|
||||
return q_quant[0], q_quant[1], kv_normed, k_pe
|
||||
|
||||
return _pattern
|
||||
|
||||
@property
|
||||
def replacement(
|
||||
self,
|
||||
) -> Callable[
|
||||
...,
|
||||
tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
],
|
||||
]:
|
||||
eps = self._epsilon
|
||||
fused_op = self.FUSED_OP
|
||||
|
||||
def _replacement(
|
||||
projected: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
kv_weight: torch.Tensor,
|
||||
) -> tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
]:
|
||||
q_dim = q_weight.shape[0]
|
||||
kv_dim = projected.shape[-1] - q_dim
|
||||
kv_c_dim = kv_weight.shape[0]
|
||||
k_pe_dim = kv_dim - kv_c_dim
|
||||
q_c, kv_lora = projected.split([q_dim, kv_dim], dim=-1)
|
||||
kv_c, k_pe = kv_lora.split([kv_c_dim, k_pe_dim], dim=-1)
|
||||
at = fused_op(
|
||||
q_c,
|
||||
q_weight,
|
||||
kv_c,
|
||||
kv_weight,
|
||||
eps,
|
||||
eps,
|
||||
128,
|
||||
False,
|
||||
)
|
||||
# q_fp8, q_scale, kv_normed, k_pe
|
||||
return at[0], at[1], at[2], k_pe
|
||||
|
||||
return _replacement
|
||||
|
||||
|
||||
class MLADualRMSNormFusionPass(VllmFusionPatternMatcherPass):
|
||||
"""Post-grad PatternMatcher pass that fuses paired q / kv RMS norms in
|
||||
MLA attention into ``fused_mla_dual_rms_norm`` backed by aiter's
|
||||
``fused_qk_rmsnorm`` HIP kernel.
|
||||
|
||||
The FP8 attention path is also handled via
|
||||
:class:`MLADualRMSPerTokenQuantPattern`, which fuses the q-latent RMSNorm +
|
||||
FP8 per-token quant together with the kv-latent RMSNorm into
|
||||
``fused_mla_dual_rms_norm_per_token_quant`` backed by aiter's
|
||||
``fused_qk_rmsnorm_per_token_quant`` HIP kernel.
|
||||
:class:`MLADualRMSPerTokenQuantPattern` or :class:`MLADualRMSGroupQuantPattern`,
|
||||
which fuse the q-latent RMSNorm + FP8 per-token/group quant together with
|
||||
the kv-latent RMSNorm into ``fused_mla_dual_rms_norm_<per_token|group>_quant``
|
||||
backed by aiter's ``fused_qk_rmsnorm_<per_token|group>_quant`` HIP kernel.
|
||||
"""
|
||||
|
||||
def __init__(self, config: VllmConfig) -> None:
|
||||
@@ -1092,3 +1224,4 @@ class MLADualRMSNormFusionPass(VllmFusionPatternMatcherPass):
|
||||
for epsilon in [1e-5, 1e-6]:
|
||||
self.register(MLADualRMSNormPattern(epsilon))
|
||||
self.register(MLADualRMSPerTokenQuantPattern(epsilon))
|
||||
self.register(MLADualRMSGroupQuantPattern(epsilon))
|
||||
|
||||
@@ -1,620 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import functools
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch._inductor.pattern_matcher as pm
|
||||
import torch.fx as fx
|
||||
from torch._higher_order_ops.auto_functionalize import auto_functionalized
|
||||
from torch._inductor.pattern_matcher import PatternMatcherPass
|
||||
|
||||
import vllm.ir.ops
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.utils import Range
|
||||
from vllm.distributed import get_tp_group, tensor_model_parallel_all_reduce
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
|
||||
from ..inductor_pass import enable_fake_mode
|
||||
from ..utility.noop_elimination import NoOpEliminationPass
|
||||
from ..vllm_inductor_pass import VllmInductorPass, VllmPatternMatcherPass
|
||||
from .matcher_utils import MatcherQuantFP8
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
if hasattr(torch.ops._C, "scaled_fp4_quant"):
|
||||
SCALED_FP4_QUANT_OUT_OVERLOAD = torch.ops._C.scaled_fp4_quant.out
|
||||
SCALED_FP4_QUANT_DEFAULT_OVERLOAD = torch.ops._C.scaled_fp4_quant.default
|
||||
|
||||
# Min hidden size per device capability for sequence parallelism
|
||||
# Only apply sequence parallelism for models with hidden_size >= threshold
|
||||
SP_MIN_HIDDEN_SIZE: dict[int, int] = {
|
||||
90: 8192, # H100: only for models with hidden_size >= 8192
|
||||
100: 8192, # Blackwell family: only for models with hidden_size >= 8192
|
||||
}
|
||||
|
||||
# Min size per GPU per device capability for sequence parallelism
|
||||
# Total min size = min_per_gpu_size * tp_size
|
||||
# This ensures the threshold scales appropriately with tensor parallelism
|
||||
SP_MIN_PER_GPU_SIZE_MB: dict[int, float] = {
|
||||
90: 8, # 8MB per GPU for H100
|
||||
# Use a more conservative threshold on Blackwell so TP8 starts later.
|
||||
100: 32,
|
||||
}
|
||||
|
||||
|
||||
def get_sequence_parallelism_threshold(
|
||||
hidden_size: int,
|
||||
tp_size: int,
|
||||
element_size: int,
|
||||
) -> int | None:
|
||||
"""Calculate the minimum token threshold for applying sequence parallelism.
|
||||
|
||||
Returns None if sequence parallelism should not be applied based on model size.
|
||||
|
||||
Branching logic based on device capability:
|
||||
- Check if hidden_size >= SP_MIN_HIDDEN_SIZE[device_capability]
|
||||
- If not, returns None (SP disabled for small models on this device)
|
||||
- If yes, calculates threshold based on per-GPU size
|
||||
|
||||
Formula: min_token_num = (min_per_gpu_size_mb * tp_size * MiB) //
|
||||
(hidden_size * element_size)
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_xpu():
|
||||
min_hidden_size = 4096
|
||||
min_per_gpu_size_mb = 8.0
|
||||
elif current_platform.is_cuda():
|
||||
capability = current_platform.get_device_capability()
|
||||
if capability is None:
|
||||
return None
|
||||
|
||||
# Collapse Blackwell variants (sm100/sm103/...) into one policy bucket.
|
||||
if current_platform.is_device_capability_family(100):
|
||||
device_capability = 100
|
||||
else:
|
||||
device_capability = capability.to_int()
|
||||
|
||||
# Check if device has configured thresholds
|
||||
_hidden = SP_MIN_HIDDEN_SIZE.get(device_capability)
|
||||
_gpu_mb = SP_MIN_PER_GPU_SIZE_MB.get(device_capability)
|
||||
if _hidden is None or _gpu_mb is None:
|
||||
return None
|
||||
min_hidden_size, min_per_gpu_size_mb = _hidden, _gpu_mb
|
||||
else:
|
||||
return None
|
||||
|
||||
# Only apply sequence parallelism for models meeting the size threshold
|
||||
if hidden_size < min_hidden_size:
|
||||
return None
|
||||
|
||||
MiB = 1024 * 1024
|
||||
min_size = min_per_gpu_size_mb * MiB * tp_size
|
||||
return int(min_size // (hidden_size * element_size))
|
||||
|
||||
|
||||
def get_first_out_wrapper(
|
||||
fn: Callable[..., Sequence[torch.Tensor]],
|
||||
) -> Callable[..., torch.Tensor]:
|
||||
@functools.wraps(fn)
|
||||
def wrapper(*args: Any) -> torch.Tensor:
|
||||
return fn(*args)[0]
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class _SequenceParallelPatternHelper:
|
||||
"""Helper for sequence parallelism patterns."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
epsilon: float,
|
||||
dtype: torch.dtype,
|
||||
device: str | None,
|
||||
) -> None:
|
||||
self.epsilon = epsilon
|
||||
self.dtype = dtype
|
||||
self.device = device
|
||||
self.tp_group = get_tp_group()
|
||||
self.tp_size = get_tensor_model_parallel_world_size()
|
||||
self.tp_rank = get_tensor_model_parallel_rank()
|
||||
|
||||
def _all_reduce(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return tensor_model_parallel_all_reduce(x)
|
||||
|
||||
def _reduce_scatter(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.ops.vllm.reduce_scatter.default(
|
||||
x, dim=0, world_size=self.tp_size, group_name=self.tp_group.unique_name
|
||||
)
|
||||
|
||||
def _all_gather(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.ops.vllm.all_gather.default(
|
||||
x, dim=0, world_size=self.tp_size, group_name=self.tp_group.unique_name
|
||||
)
|
||||
|
||||
def empty(self, *args: Any, **kwargs: Any) -> torch.Tensor:
|
||||
return torch.empty(*args, dtype=self.dtype, device=self.device, **kwargs)
|
||||
|
||||
def empty_f32(self, *args: Any, **kwargs: Any) -> torch.Tensor:
|
||||
return torch.empty(*args, dtype=torch.float32, device=self.device, **kwargs)
|
||||
|
||||
|
||||
class FirstAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
|
||||
def __init__(self, epsilon: float, dtype: torch.dtype, device: str | None) -> None:
|
||||
super().__init__(epsilon, dtype, device)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
# input, weight
|
||||
return [self.empty([1, 8, 4]), self.empty([4])]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(input)
|
||||
rmsnorm = vllm.ir.ops.rms_norm(all_reduce, weight, self.epsilon)
|
||||
|
||||
return rmsnorm, all_reduce
|
||||
|
||||
def replacement(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
reduce_scatter = self._reduce_scatter(input)
|
||||
|
||||
rmsnorm = vllm.ir.ops.rms_norm(reduce_scatter, weight, self.epsilon)
|
||||
all_gather = self._all_gather(rmsnorm)
|
||||
return all_gather, reduce_scatter
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
|
||||
|
||||
class MiddleAllReduceRMSNormPattern(_SequenceParallelPatternHelper):
|
||||
def __init__(self, epsilon: float, dtype: torch.dtype, device: str | None) -> None:
|
||||
super().__init__(epsilon, dtype, device)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
mm_1 = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
|
||||
residual = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
rms_norm_weights = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
|
||||
return [
|
||||
residual,
|
||||
mm_1,
|
||||
rms_norm_weights,
|
||||
]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(mm_1)
|
||||
rmsnorm = vllm.ir.ops.fused_add_rms_norm(
|
||||
all_reduce, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
return rmsnorm[0], rmsnorm[1]
|
||||
|
||||
def replacement(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# The pattern matcher replaces from the end of the graph
|
||||
# (last layer first). At the time each match is replaced,
|
||||
# the preceding layer has NOT been replaced yet, so
|
||||
# `residual` is still full-size and the slice below is
|
||||
# correct. Once the preceding layer IS replaced, its
|
||||
# residual output shrinks to [local_len, H], and this
|
||||
# slice becomes semantically incorrect (e.g. for rank > 0,
|
||||
# the indices would be out of bounds). However, since the
|
||||
# symbolic output shape equals the input shape,
|
||||
# NoOpEliminationPass (called at the end of
|
||||
# SequenceParallelismPass.__call__) removes these slices
|
||||
# before the graph is ever executed or compiled.
|
||||
reduce_scatter = self._reduce_scatter(mm_1)
|
||||
local_len = reduce_scatter.size(0)
|
||||
# when the preceding VocabParallelEmbedding is excluded
|
||||
# from the FX graph (e.g., passing `inputs_embeds` directly in VLMs),
|
||||
# the FirstAllReduceRMSNorm pattern is never matched. we must
|
||||
# perform a proper TP-aware slice here. simply using `[0:local_len]`
|
||||
# would incorrectly cause all ranks to process rank 0's chunk.
|
||||
residual = residual[
|
||||
self.tp_rank * local_len : self.tp_rank * local_len + local_len, ...
|
||||
]
|
||||
rmsnorm = vllm.ir.ops.fused_add_rms_norm(
|
||||
reduce_scatter, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
all_gather = self._all_gather(rmsnorm[0])
|
||||
# residual output is now [local_len, H]; the next layer's
|
||||
# slice on it is semantically incorrect until
|
||||
# NoOpEliminationPass removes it.
|
||||
return all_gather, rmsnorm[1]
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
pm.register_replacement(
|
||||
get_first_out_wrapper(pattern),
|
||||
get_first_out_wrapper(replacement),
|
||||
self.get_inputs(),
|
||||
pm.fwd_only,
|
||||
pm_pass,
|
||||
)
|
||||
|
||||
|
||||
class FirstAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
|
||||
def __init__(
|
||||
self,
|
||||
epsilon: float,
|
||||
dtype: torch.dtype,
|
||||
device: str | None,
|
||||
) -> None:
|
||||
super().__init__(epsilon, dtype, device)
|
||||
self.quant_matcher = MatcherQuantFP8(kFp8StaticTensorSym)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
# input, weight, scale
|
||||
return [self.empty([1, 8, 4]), self.empty([4]), self.empty_f32([1, 1])]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(input)
|
||||
rms = vllm.ir.ops.rms_norm(all_reduce, weight, self.epsilon)
|
||||
quant, _ = self.quant_matcher(rms, scale)
|
||||
return quant, all_reduce
|
||||
|
||||
def replacement(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
reduce_scatter = self._reduce_scatter(input)
|
||||
rms = vllm.ir.ops.rms_norm(reduce_scatter, weight, self.epsilon)
|
||||
quant, _ = self.quant_matcher(rms, scale)
|
||||
all_gather = self._all_gather(quant)
|
||||
|
||||
return all_gather, reduce_scatter
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
|
||||
|
||||
class MiddleAllReduceRMSNormStaticFP8Pattern(_SequenceParallelPatternHelper):
|
||||
def __init__(self, epsilon: float, dtype: torch.dtype, device: str | None) -> None:
|
||||
super().__init__(epsilon, dtype, device)
|
||||
self.quant_matcher = MatcherQuantFP8(kFp8StaticTensorSym)
|
||||
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
mm_1 = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
residual = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
rms_norm_weights = torch.empty([4, 4], device=self.device, dtype=self.dtype)
|
||||
scale = torch.empty([1, 1], device=self.device, dtype=torch.float32)
|
||||
|
||||
return [residual, mm_1, rms_norm_weights, scale]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(mm_1)
|
||||
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
|
||||
all_reduce, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
quant, _ = self.quant_matcher(rms, scale)
|
||||
return quant, residual_out
|
||||
|
||||
def replacement(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
# See MiddleAllReduceRMSNormPattern.replacement for a
|
||||
# detailed explanation of the temporary slice below:
|
||||
# it is correct when first inserted, becomes semantically
|
||||
# incorrect after the preceding layer is replaced, and is
|
||||
# removed by NoOpEliminationPass before the graph is compiled.
|
||||
reduce_scatter = self._reduce_scatter(mm_1)
|
||||
local_len = reduce_scatter.size(0)
|
||||
# when the preceding VocabParallelEmbedding is excluded
|
||||
# from the FX graph (e.g., passing `inputs_embeds` directly in VLMs),
|
||||
# the FirstAllReduceRMSNorm pattern is never matched. we must
|
||||
# perform a proper TP-aware slice here. simply using `[0:local_len]`
|
||||
# would incorrectly cause all ranks to process rank 0's chunk.
|
||||
residual = residual[
|
||||
self.tp_rank * local_len : self.tp_rank * local_len + local_len, ...
|
||||
]
|
||||
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
|
||||
reduce_scatter, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
quant, _ = self.quant_matcher(rms, scale)
|
||||
all_gather = self._all_gather(quant)
|
||||
# residual output is now [local_len, H]; the next layer's
|
||||
# slice on it is semantically incorrect until
|
||||
# NoOpEliminationPass removes it.
|
||||
return all_gather, residual_out
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
|
||||
pm.register_replacement(
|
||||
get_first_out_wrapper(pattern),
|
||||
get_first_out_wrapper(replacement),
|
||||
self.get_inputs(),
|
||||
pm.fwd_only,
|
||||
pm_pass,
|
||||
)
|
||||
|
||||
|
||||
class FirstAllReduceRMSNormStaticNVFP4Pattern(_SequenceParallelPatternHelper):
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
input = self.empty([8, 16])
|
||||
weight = self.empty([16])
|
||||
input_global_scale = self.empty_f32([1, 1])
|
||||
quant_output = torch.empty([8, 8], device=self.device, dtype=torch.uint8)
|
||||
output_scale = torch.empty([128, 4], device=self.device, dtype=torch.int32)
|
||||
return [input, weight, input_global_scale, quant_output, output_scale]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
input_global_scale: torch.Tensor,
|
||||
quant_output: torch.Tensor,
|
||||
output_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(input)
|
||||
rms = vllm.ir.ops.rms_norm(all_reduce, weight, self.epsilon)
|
||||
quant = auto_functionalized(
|
||||
SCALED_FP4_QUANT_OUT_OVERLOAD,
|
||||
input=rms,
|
||||
input_scale=input_global_scale,
|
||||
is_sf_swizzled_layout=True,
|
||||
output=quant_output,
|
||||
output_scale=output_scale,
|
||||
)
|
||||
return quant[1], all_reduce, quant[2]
|
||||
|
||||
def replacement(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
input_global_scale: torch.Tensor,
|
||||
quant_output: torch.Tensor,
|
||||
output_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
reduce_scatter = self._reduce_scatter(input)
|
||||
rms = vllm.ir.ops.rms_norm(reduce_scatter, weight, self.epsilon)
|
||||
rms = torch.ops.aten.view.default(rms, [-1, rms.shape[-1]])
|
||||
quant = SCALED_FP4_QUANT_DEFAULT_OVERLOAD(
|
||||
rms,
|
||||
input_global_scale,
|
||||
True,
|
||||
)
|
||||
return (
|
||||
self._all_gather(quant[0]),
|
||||
reduce_scatter,
|
||||
self._all_gather(quant[1]),
|
||||
)
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
|
||||
|
||||
class MiddleAllReduceRMSNormStaticNVFP4Pattern(_SequenceParallelPatternHelper):
|
||||
def get_inputs(self) -> list[torch.Tensor]:
|
||||
mm_1 = self.empty([8, 16])
|
||||
residual = self.empty([8, 16])
|
||||
rms_norm_weights = self.empty([16])
|
||||
input_global_scale = self.empty_f32([1, 1])
|
||||
quant_output = torch.empty([8, 8], device=self.device, dtype=torch.uint8)
|
||||
output_scale = torch.empty([128, 4], device=self.device, dtype=torch.int32)
|
||||
return [
|
||||
residual,
|
||||
mm_1,
|
||||
rms_norm_weights,
|
||||
input_global_scale,
|
||||
quant_output,
|
||||
output_scale,
|
||||
]
|
||||
|
||||
def register(self, pm_pass: PatternMatcherPass) -> None:
|
||||
def pattern(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
input_global_scale: torch.Tensor,
|
||||
quant_output: torch.Tensor,
|
||||
output_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
all_reduce = self._all_reduce(mm_1)
|
||||
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
|
||||
all_reduce, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
quant = auto_functionalized(
|
||||
SCALED_FP4_QUANT_OUT_OVERLOAD,
|
||||
input=rms,
|
||||
input_scale=input_global_scale,
|
||||
is_sf_swizzled_layout=True,
|
||||
output=quant_output,
|
||||
output_scale=output_scale,
|
||||
)
|
||||
return quant[1], residual_out, quant[2]
|
||||
|
||||
def replacement(
|
||||
residual: torch.Tensor,
|
||||
mm_1: torch.Tensor,
|
||||
rms_norm_weights: torch.Tensor,
|
||||
input_global_scale: torch.Tensor,
|
||||
quant_output: torch.Tensor,
|
||||
output_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
# Keep this slice in sync with the non-quantized SP replacement:
|
||||
# once the previous SP pattern fires, it becomes a no-op.
|
||||
reduce_scatter = self._reduce_scatter(mm_1)
|
||||
residual = residual[0 : reduce_scatter.size(0), ...]
|
||||
rms, residual_out = vllm.ir.ops.fused_add_rms_norm(
|
||||
reduce_scatter, residual, rms_norm_weights, self.epsilon
|
||||
)
|
||||
rms = torch.ops.aten.view.default(rms, [-1, rms.shape[-1]])
|
||||
quant = SCALED_FP4_QUANT_DEFAULT_OVERLOAD(
|
||||
rms,
|
||||
input_global_scale,
|
||||
True,
|
||||
)
|
||||
return self._all_gather(quant[0]), residual_out, self._all_gather(quant[1])
|
||||
|
||||
pm.register_replacement(
|
||||
pattern, replacement, self.get_inputs(), pm.fwd_only, pm_pass
|
||||
)
|
||||
|
||||
|
||||
class SequenceParallelismPass(VllmPatternMatcherPass):
|
||||
"""This pass enables sequence parallelism for models.
|
||||
It identifies patterns where an AllReduce operation is followed by
|
||||
an RMSNorm (or RMSNorm and then Quantization) operation.
|
||||
These patterns are replaced with a ReduceScatter operation, followed by
|
||||
a local RMSNorm/Quantization, and then an AllGather operation.
|
||||
|
||||
The general transformation is:
|
||||
Input -> AllReduce -> RMSNorm -> Output
|
||||
becomes
|
||||
Input -> ReduceScatter -> RMSNorm -> AllGather -> Output
|
||||
|
||||
While this pass itself does not directly yield performance improvements,
|
||||
it lays the groundwork for subsequent fusion passes, such as
|
||||
GEMM + ReduceScatter and AllGather + GEMM fusions. These fusions can
|
||||
significantly reduce communication overhead and improve overall model
|
||||
performance.
|
||||
|
||||
This pass is only supported when compiling the whole graph (fullgraph
|
||||
mode, i.e. using Inductor graph partition or empty splitting_ops).
|
||||
Piecewise compilation is not supported because the residual tensor
|
||||
gets split across TP ranks, causing size mismatches at subgraph
|
||||
boundaries.
|
||||
|
||||
This pass splits up the residual tensor across TP ranks and hence divides
|
||||
its size. The pattern matcher starts at the end of the graph (last layer
|
||||
first), so when each replacement inserts a residual slice, the preceding
|
||||
layer has not been replaced yet and the slice is correct. Once the
|
||||
preceding layer IS replaced, its residual output shrinks and the slice
|
||||
becomes semantically incorrect (out-of-bounds indices for rank > 0).
|
||||
The graph is never executed in this intermediate state —
|
||||
NoOpEliminationPass removes these slices based on symbolic shape equality
|
||||
(input shape == output shape) before the graph is compiled.
|
||||
"""
|
||||
|
||||
@enable_fake_mode
|
||||
def __init__(self, config: VllmConfig) -> None:
|
||||
super().__init__(config)
|
||||
|
||||
# Get min_token_num threshold
|
||||
# Read min_token_num from config (calculated during config init)
|
||||
self.min_token_num = None
|
||||
if config.model_config is not None:
|
||||
pass_config = config.compilation_config.pass_config
|
||||
self.min_token_num = pass_config.sp_min_token_num
|
||||
|
||||
if self.min_token_num is not None:
|
||||
# Take the min to avoid exceeding max_num_batched_tokens
|
||||
max_batched = config.scheduler_config.max_num_batched_tokens
|
||||
if max_batched is not None:
|
||||
self.min_token_num = min(self.min_token_num, max_batched)
|
||||
logger.debug_once(
|
||||
f"Sequence parallelism min token threshold: {self.min_token_num}",
|
||||
scope="global",
|
||||
)
|
||||
|
||||
# Used to clean up redundant views created temporarily
|
||||
# to circumvent residual shape change issues
|
||||
self.noop_cleanup = NoOpEliminationPass(config)
|
||||
self.noop_cleanup.pass_name = f"{self.pass_name}.{self.noop_cleanup.pass_name}"
|
||||
|
||||
self.patterns: PatternMatcherPass = PatternMatcherPass(
|
||||
pass_name="sequence_parallelism_pass"
|
||||
)
|
||||
|
||||
for epsilon in [1e-5, 1e-6]:
|
||||
# RMSNorm + Static FP8 quantization patterns
|
||||
FirstAllReduceRMSNormStaticFP8Pattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
MiddleAllReduceRMSNormStaticFP8Pattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
|
||||
if "SCALED_FP4_QUANT_OUT_OVERLOAD" in globals():
|
||||
FirstAllReduceRMSNormStaticNVFP4Pattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
MiddleAllReduceRMSNormStaticNVFP4Pattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
|
||||
# Normal RMSNorm patterns
|
||||
FirstAllReduceRMSNormPattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
|
||||
MiddleAllReduceRMSNormPattern(
|
||||
epsilon, self.model_dtype, self.device
|
||||
).register(self.patterns)
|
||||
|
||||
self.dump_patterns(config, self.patterns)
|
||||
|
||||
def is_applicable_for_range(self, compile_range: Range) -> bool:
|
||||
"""Determines if sequence parallelism should be applied for the given
|
||||
compile range.
|
||||
|
||||
SP is only beneficial for larger batch sizes where the communication
|
||||
overhead is amortized. For small batches, the overhead of splitting
|
||||
and gathering tensors across TP ranks outweighs the benefits.
|
||||
|
||||
Returns False (SP disabled) when:
|
||||
- min_token_num is None (SP disabled for this device/config)
|
||||
- The compile range starts below the minimum token threshold
|
||||
"""
|
||||
assert (
|
||||
self.compilation_config.use_inductor_graph_partition
|
||||
or not self.compilation_config.splitting_ops
|
||||
), "SequenceParallelismPass requires full-graph compilation"
|
||||
|
||||
# min_token_num is None when SP is disabled for this device/config
|
||||
# (e.g., non-CUDA platform, unsupported GPU, or small hidden_size)
|
||||
if self.min_token_num is None:
|
||||
return False
|
||||
|
||||
# Only apply SP when batch size meets the minimum threshold
|
||||
return compile_range.start >= self.min_token_num
|
||||
|
||||
@VllmInductorPass.time_and_log
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
self.matched_count = self.patterns.apply(graph)
|
||||
logger.debug("Replaced %s patterns", self.matched_count)
|
||||
# Clean up reshape nodes
|
||||
self.noop_cleanup(graph)
|
||||
@@ -35,13 +35,11 @@ if current_platform.is_cuda_alike() or current_platform.is_xpu():
|
||||
RMSNormReshapeFusionPass,
|
||||
)
|
||||
from .fusion.qk_norm_rope_fusion import QKNormRoPEFusionPass
|
||||
from .fusion.sequence_parallelism import SequenceParallelismPass
|
||||
from .utility.split_coalescing import SplitCoalescingPass
|
||||
|
||||
if current_platform.is_cuda_alike():
|
||||
from .fusion.act_quant_fusion import ActivationQuantFusionPass
|
||||
from .fusion.attn_quant_fusion import AttnQuantFusionPass
|
||||
from .fusion.collective_fusion import AsyncTPPass
|
||||
from .fusion.mla_attn_quant_fusion import MLAAttnQuantFusionPass
|
||||
from .fusion.mla_rope_kvcache_cat_fusion import MLARoPEKVCacheCatFusionPass
|
||||
from .fusion.qk_norm_rope_kvcache_fusion import QkNormRopeKvCacheFusionPass
|
||||
@@ -156,11 +154,6 @@ class PostGradPassManager(CustomGraphPass): # type: ignore[misc]
|
||||
if self.pass_config.eliminate_noops:
|
||||
self.passes += [NoOpEliminationPass(config)]
|
||||
|
||||
if self.pass_config.enable_sp:
|
||||
self.passes += [SequenceParallelismPass(config)]
|
||||
if self.pass_config.fuse_gemm_comms:
|
||||
self.passes += [AsyncTPPass(config)]
|
||||
|
||||
if enable_transformers_norm_canonicalization:
|
||||
self.passes += [AddRMSNormFusionPass(config)]
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ CacheDType = Literal[
|
||||
"turboquant_4bit_nc",
|
||||
"turboquant_k3v4_nc",
|
||||
"turboquant_3bit_nc",
|
||||
"ultraquant_4bit",
|
||||
"int4_per_token_head",
|
||||
"int8_per_token_head",
|
||||
"fp8_per_token_head",
|
||||
@@ -229,6 +230,15 @@ class CacheConfig:
|
||||
for hybrid models where requests occupy multiple KV cache groups."""
|
||||
kv_cache_max_concurrency: float | None = field(default=None, init=False)
|
||||
"""Per-DP-engine maximum concurrency at max_model_len tokens."""
|
||||
# The two differ when hashes are finer than the scheduler block but partial
|
||||
# hash hits are off (e.g. a sliding-window group cannot look up sub-block
|
||||
# hits), so hits only land on the scheduler block.
|
||||
# TODO(zjy0516): Merge into one value
|
||||
hash_block_size: int | None = field(default=None, init=False)
|
||||
"""Tokens per prefix-cache block hash."""
|
||||
cache_hit_alignment_tokens: int | None = field(default=None, init=False)
|
||||
"""Token granularity at which prefix-cache hits land: `hash_block_size`
|
||||
with partial hash hits, otherwise the scheduler block size."""
|
||||
|
||||
kv_sharing_fast_prefill: bool = False
|
||||
"""In some KV sharing setups, e.g. YOCO (https://arxiv.org/abs/2405.05254),
|
||||
@@ -297,6 +307,8 @@ class CacheConfig:
|
||||
"effective_attention_block_size",
|
||||
"kv_cache_size_tokens",
|
||||
"kv_cache_max_concurrency",
|
||||
"hash_block_size",
|
||||
"cache_hit_alignment_tokens",
|
||||
# Feature toggles not impacting compiled graph shape
|
||||
"kv_sharing_fast_prefill",
|
||||
"swa_bounded_replay",
|
||||
|
||||
+35
-58
@@ -133,12 +133,6 @@ class PassConfig:
|
||||
"""Fuse the custom Attention and MLAAttention + quant ops."""
|
||||
eliminate_noops: bool = Field(default=True)
|
||||
"""Eliminate no-op ops."""
|
||||
enable_sp: bool = None # type: ignore[assignment]
|
||||
"""Enable sequence parallelism. Requires TP>1. Automatically disabled
|
||||
if the model's hidden_size is too small for SP to be beneficial
|
||||
(threshold is device-capability dependent)."""
|
||||
fuse_gemm_comms: bool = None # type: ignore[assignment]
|
||||
"""Enable async TP."""
|
||||
fuse_allreduce_rms: bool = None # type: ignore[assignment]
|
||||
"""Enable flashinfer allreduce fusion."""
|
||||
enable_qk_norm_rope_fusion: bool = None # type: ignore[assignment]
|
||||
@@ -183,12 +177,6 @@ class PassConfig:
|
||||
8: 1, # 1MB
|
||||
},
|
||||
}, where key is the device capability"""
|
||||
sp_min_token_num: int | None = None
|
||||
"""The minimum number of tokens above which vllm should use
|
||||
sequence parallelism. Specified as an integer token count.
|
||||
Unspecified will fallback to default values which are compute
|
||||
capability and world size dependent."""
|
||||
|
||||
# TODO(luka) better pass enabling system.
|
||||
|
||||
def flashinfer_max_size(self, world_size: int) -> int | None:
|
||||
@@ -231,8 +219,6 @@ class PassConfig:
|
||||
"fuse_norm_quant",
|
||||
"fuse_act_quant",
|
||||
"fuse_attn_quant",
|
||||
"enable_sp",
|
||||
"fuse_gemm_comms",
|
||||
"fuse_allreduce_rms",
|
||||
"fuse_act_padding",
|
||||
"fuse_mla_dual_rms_norm",
|
||||
@@ -570,6 +556,24 @@ class CompilationConfig:
|
||||
If we limit the video count per prompt to `0`, it will also be set to `0`
|
||||
(i.e., fall back to image-only mode)."""
|
||||
|
||||
cudagraph_decoder_replay: bool = True
|
||||
"""Run the decoder replay layers of YOCO models (e.g. DeepSeek-V4.1) in CUDA
|
||||
graphs of their own, and trim them in PIECEWISE graph steps. Requires
|
||||
breakable PIECEWISE graphs; off under LoRA, prompt embeddings and non-first
|
||||
PP ranks."""
|
||||
|
||||
decoder_replay_cudagraph_capture_sizes: list[int] = field(default_factory=list)
|
||||
"""Decoder replay CUDA graph sizes for YOCO models (e.g. DeepSeek-V4.1), at
|
||||
most max_num_batched_tokens. If empty: multiples of sliding_window up to
|
||||
min(max_cudagraph_capture_size, max_num_seqs * sliding_window), coarser past
|
||||
16 * sliding_window. Larger replay batches run eagerly."""
|
||||
|
||||
decoder_replay_trim_threshold: int = Field(default=768, ge=0)
|
||||
"""For YOCO models (e.g. DeepSeek-V4.1), PIECEWISE graphs with at least this
|
||||
many padded tokens trim the decoder replay batch; must exceed the replay
|
||||
window (128), below which nothing trims. Independent of the replay graph
|
||||
capture sizes; eager steps still trim."""
|
||||
|
||||
# Inductor capture
|
||||
compile_sizes: list[int | str] | None = None
|
||||
"""Sizes to compile for inductor. In addition
|
||||
@@ -770,6 +774,8 @@ class CompilationConfig:
|
||||
# Qwen4Exp's AMD backend still uses these splitting ops.
|
||||
"vllm::qwen4_exp_ple_short_conv",
|
||||
"vllm::qwen4_exp_qsa_with_output",
|
||||
# The fused prepare calls this op instead of the one above.
|
||||
"vllm::qwen4_exp_qsa_prepare_with_output",
|
||||
"vllm::linear_attention",
|
||||
"vllm::qwen_gdn_attention_core",
|
||||
"vllm::qwen_gdn_attention_core_fused_norm_packed",
|
||||
@@ -984,10 +990,16 @@ class CompilationConfig:
|
||||
# (fixme @boyuan) combo kernel does not support cpu yet.
|
||||
and not current_platform.is_cpu()
|
||||
):
|
||||
from torch._inductor import config as inductor_config
|
||||
|
||||
# use horizontal fusion, which is useful for fusing qk-norm and
|
||||
# qk-rope when query and key have different shapes.
|
||||
self.inductor_compile_config["combo_kernels"] = True
|
||||
self.inductor_compile_config["benchmark_combo_kernel"] = True
|
||||
|
||||
deterministic = self.inductor_compile_config.get(
|
||||
"deterministic", getattr(inductor_config, "deterministic", False)
|
||||
)
|
||||
self.inductor_compile_config["benchmark_combo_kernel"] = not deterministic
|
||||
|
||||
if self.use_inductor_graph_partition and not is_torch_equal_or_newer(
|
||||
"2.9.0.dev"
|
||||
@@ -1033,6 +1045,11 @@ class CompilationConfig:
|
||||
f"Invalid backend for piecewise compilation: {self.backend}"
|
||||
)
|
||||
|
||||
if any(s <= 0 for s in self.decoder_replay_cudagraph_capture_sizes):
|
||||
raise ValueError(
|
||||
"All decoder_replay_cudagraph_capture_sizes must be positive"
|
||||
)
|
||||
|
||||
# Validate encoder CUDA graph configuration
|
||||
if (
|
||||
self.cudagraph_mm_encoder
|
||||
@@ -1215,25 +1232,6 @@ class CompilationConfig:
|
||||
self.cudagraph_mode = CUDAGraphMode.FULL
|
||||
self.splitting_ops = []
|
||||
|
||||
if (
|
||||
not self.use_inductor_graph_partition
|
||||
and (self.pass_config.enable_sp or self.pass_config.fuse_gemm_comms)
|
||||
and self.splitting_ops
|
||||
):
|
||||
logger.warning_once(
|
||||
"Sequence parallelism requires full-graph compilation when "
|
||||
"use_inductor_graph_partition is off. Setting splitting_ops "
|
||||
"to an empty list to preserve SP and async TP."
|
||||
)
|
||||
self.splitting_ops = []
|
||||
if self.cudagraph_mode.has_piecewise_cudagraphs():
|
||||
logger.warning_once(
|
||||
"Sequence parallelism is incompatible with piecewise "
|
||||
"cudagraph when use_inductor_graph_partition is off. "
|
||||
"Setting cudagraph_mode to FULL."
|
||||
)
|
||||
self.cudagraph_mode = CUDAGraphMode.FULL
|
||||
|
||||
# Disable CUDA graphs for DeepEP high-throughput since its not CG compatible
|
||||
if (
|
||||
all2all_backend == "deepep_high_throughput"
|
||||
@@ -1374,7 +1372,6 @@ class CompilationConfig:
|
||||
min_cg_attn_backend: str | None,
|
||||
uniform_decode_query_len: int = 1,
|
||||
use_v2_model_runner: bool = False,
|
||||
tensor_parallel_size: int = 1,
|
||||
kv_cache_config: "KVCacheConfig | None" = None,
|
||||
max_num_reqs: int | None = None,
|
||||
is_profiling: bool = False,
|
||||
@@ -1506,10 +1503,7 @@ class CompilationConfig:
|
||||
and cudagraph_mode.decode_mode() == CUDAGraphMode.FULL
|
||||
and uniform_decode_query_len > 1
|
||||
):
|
||||
self.adjust_cudagraph_sizes_for_spec_decode(
|
||||
uniform_decode_query_len,
|
||||
tensor_parallel_size,
|
||||
)
|
||||
self.adjust_cudagraph_sizes_for_spec_decode(uniform_decode_query_len)
|
||||
|
||||
# For Mamba models with FULL decode cudagraphs, each decode
|
||||
# sequence needs one Mamba cache block. The decode cudagraph
|
||||
@@ -1538,25 +1532,8 @@ class CompilationConfig:
|
||||
self.cudagraph_mode = cudagraph_mode
|
||||
return cudagraph_mode
|
||||
|
||||
def adjust_cudagraph_sizes_for_spec_decode(
|
||||
self, uniform_decode_query_len: int, tensor_parallel_size: int
|
||||
):
|
||||
def adjust_cudagraph_sizes_for_spec_decode(self, uniform_decode_query_len: int):
|
||||
multiple_of = uniform_decode_query_len
|
||||
if tensor_parallel_size > 1 and self.pass_config.enable_sp:
|
||||
multiple_of = max(uniform_decode_query_len, tensor_parallel_size)
|
||||
if (
|
||||
multiple_of % uniform_decode_query_len != 0
|
||||
or multiple_of % tensor_parallel_size != 0
|
||||
):
|
||||
raise ValueError(
|
||||
f"Can't determine cudagraph shapes that are both a "
|
||||
f"multiple of {uniform_decode_query_len} "
|
||||
f"(num_speculative_tokens + 1) required by spec-decode "
|
||||
f"and {tensor_parallel_size} (tensor_parallel_size) "
|
||||
f"required by sequence parallelism please adjust "
|
||||
f"num_speculative_tokens or disable sequence parallelism"
|
||||
)
|
||||
|
||||
if not self.cudagraph_capture_sizes or multiple_of <= 1:
|
||||
return
|
||||
|
||||
@@ -1576,7 +1553,7 @@ class CompilationConfig:
|
||||
if len(rounded_sizes) == 0:
|
||||
raise ValueError(
|
||||
f"No valid cudagraph sizes after rounding to multiple of {multiple_of} "
|
||||
f"(num_speculative_tokens + 1 or tp if sequence parallelism is enabled)"
|
||||
f"(num_speculative_tokens + 1)"
|
||||
f" please adjust num_speculative_tokens ({uniform_decode_query_len - 1}"
|
||||
f") or max_cudagraph_capture_size ({self.max_cudagraph_capture_size})"
|
||||
f" or cudagraph_capture_sizes ({self.cudagraph_capture_sizes})"
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Self
|
||||
|
||||
from pydantic import model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config.utils import config, get_hash_factors, hash_factors
|
||||
|
||||
|
||||
@@ -137,6 +137,7 @@ MoEBackend = Literal[
|
||||
"humming",
|
||||
"triton_unfused",
|
||||
"aiter",
|
||||
"aiter_mega_moe",
|
||||
"aiter_triton_mxfp4_bf16",
|
||||
"flydsl",
|
||||
"hpc",
|
||||
@@ -278,6 +279,9 @@ class KernelConfig:
|
||||
enable_flashinfer_autotune: bool = None # type: ignore[assignment]
|
||||
"""If True, run FlashInfer autotuning during kernel warmup."""
|
||||
|
||||
enable_rocm_segmented_attn_autotune: bool = False
|
||||
"""If True, autotune ROCm segmented attention during kernel warmup on RDNA GPUs."""
|
||||
|
||||
# TODO(roberto): Remove after registered CuTeDSL warmups are migrated
|
||||
# to the shared JIT warmup infrastructure.
|
||||
# https://github.com/vllm-project/vllm/pull/47451
|
||||
@@ -314,6 +318,9 @@ class KernelConfig:
|
||||
- "humming": Use Humming Mixed Precision kernels
|
||||
- "triton_unfused": Use Triton unfused MoE kernels
|
||||
- "aiter": Use AMD AITer kernels (ROCm only)
|
||||
- "aiter_mega_moe": Use the AITER MegaMoE fused dispatch/GEMM/combine
|
||||
kernel (ROCm gfx950, requires DP+EP with a MoRI all2all backend;
|
||||
DeepSeek-V4 only)
|
||||
- "aiter_triton_mxfp4_bf16": Use the AITER Triton MXFP4 W4A16
|
||||
(moe_gemm_a16w4) MoE kernel (ROCm gfx942/gfx950/gfx1250)
|
||||
- "flydsl": Use AMD FlyDSL kernels (ROCm only)
|
||||
@@ -406,6 +413,7 @@ class KernelConfig:
|
||||
"enable_cutedsl_warmup",
|
||||
"enable_jit_warmup",
|
||||
"enable_flashinfer_autotune",
|
||||
"enable_rocm_segmented_attn_autotune",
|
||||
"ir_op_priority", # handled separately below
|
||||
}
|
||||
if self.linear_backend_per_quant is None:
|
||||
|
||||
+4
-5
@@ -2,11 +2,10 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
from typing import TYPE_CHECKING, Any, Literal, Self
|
||||
|
||||
import torch
|
||||
from pydantic import ConfigDict, Field, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config.utils import config
|
||||
@@ -25,7 +24,6 @@ logger = init_logger(__name__)
|
||||
|
||||
LoRADType = Literal["auto", "float16", "bfloat16"]
|
||||
MaxLoRARanks = Literal[1, 8, 16, 32, 64, 128, 256, 320, 512]
|
||||
LoRAExtraVocabSize = Literal[256, 512]
|
||||
|
||||
|
||||
@config(config=ConfigDict(arbitrary_types_allowed=True))
|
||||
@@ -82,8 +80,9 @@ class LoRAConfig:
|
||||
"""If True, load MoE expert adapters in the "shared-outer" layout, where the
|
||||
gate/up (`w1`/`w3`) lora_A and the down (`w2`) lora_B are shared across all
|
||||
experts (stored once with expert-dim 1) instead of per-expert. The shared
|
||||
factors are broadcast to the expert count at kernel time. Only meaningful for
|
||||
MoE models whose adapters use this layout; ignored otherwise."""
|
||||
factors are broadcast to the expert count at kernel time. 3D-weight MoE
|
||||
models use `FusedMoEWithLoRA` for this layout. Only meaningful for MoE
|
||||
models whose adapters use this layout; ignored otherwise."""
|
||||
max_lora_cls_labels: int | None = Field(default=None, ge=1)
|
||||
"""Maximum output size for LoRA classification heads. Defaults to the
|
||||
base classification head size."""
|
||||
|
||||
@@ -725,7 +725,7 @@ class MultiModalConfig:
|
||||
# The model expects raw pixels and normalises on device;
|
||||
# overriding these per request would silently double-normalise.
|
||||
for key in ("do_normalize", "do_rescale"):
|
||||
if key in inference_kwargs:
|
||||
if inference_kwargs.get(key):
|
||||
logger.warning_once(
|
||||
"mm_device_do_normalize is enabled; ignoring "
|
||||
"per-request mm_processor_kwargs[%r].",
|
||||
|
||||
@@ -5,13 +5,12 @@ import os
|
||||
import socket
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
from typing import TYPE_CHECKING, Any, Literal, Self, overload
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from torch.distributed import ProcessGroup, ReduceOp, Store
|
||||
from typing_extensions import Self
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.fault_tolerance import FaultToleranceConfig
|
||||
|
||||
+40
-9
@@ -2,10 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
from typing import Any, Literal
|
||||
from typing import Any, Literal, Self
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config.utils import config
|
||||
from vllm.logger import init_logger
|
||||
@@ -22,6 +21,34 @@ ProtonHook = Literal["triton"]
|
||||
ProtonOutputFormat = Literal["hatchet", "hatchet_msgpack", "chrome_trace"]
|
||||
|
||||
|
||||
def validate_profile_prefix(prefix: str | None) -> str | None:
|
||||
"""Validate a trace filename prefix supplied for one profiling session."""
|
||||
if prefix is None:
|
||||
return None
|
||||
if (
|
||||
not 1 <= len(prefix) <= 128
|
||||
or not prefix.isascii()
|
||||
or not prefix[0].isalnum()
|
||||
or any(not (char.isalnum() or char in "._-") for char in prefix[1:])
|
||||
):
|
||||
raise ValueError(
|
||||
"profile_prefix must be 1-128 ASCII characters, start with a letter "
|
||||
"or number, and contain only letters, numbers, '.', '_', or '-'"
|
||||
)
|
||||
return prefix
|
||||
|
||||
|
||||
def validate_profile_iteration_bounds(
|
||||
delay_iterations: int | None,
|
||||
max_iterations: int | None,
|
||||
) -> None:
|
||||
"""Validate iteration bounds supplied for one profiling session."""
|
||||
if delay_iterations is not None and delay_iterations < 0:
|
||||
raise ValueError("delay_iterations must be greater than or equal to 0")
|
||||
if max_iterations is not None and max_iterations < 0:
|
||||
raise ValueError("max_iterations must be greater than or equal to 0")
|
||||
|
||||
|
||||
def _is_uri_path(path: str) -> bool:
|
||||
"""Check if path is a URI (scheme://...), excluding Windows drive letters.
|
||||
|
||||
@@ -136,6 +163,16 @@ class ProfilerConfig:
|
||||
Defaults to 0, meaning no limit.
|
||||
"""
|
||||
|
||||
@property
|
||||
def should_profile_frontend(self) -> bool:
|
||||
"""Whether the frontend CPU profiler should be enabled."""
|
||||
activities = self.torch_profiler_activities
|
||||
return (
|
||||
self.profiler == "torch"
|
||||
and not self.ignore_frontend
|
||||
and (activities is None or "CPU" in activities)
|
||||
)
|
||||
|
||||
warmup_iterations: int = Field(default=0, ge=0)
|
||||
"""Number of warmup iterations for PyTorch profiler schedule.
|
||||
During warmup, the profiler runs but data is discarded. This helps reduce
|
||||
@@ -188,13 +225,7 @@ class ProfilerConfig:
|
||||
raise ValueError(
|
||||
"torch_profiler_activities must not contain duplicates"
|
||||
)
|
||||
records_cpu_activity = activities is None or "CPU" in activities
|
||||
if (
|
||||
self.profiler == "torch"
|
||||
and has_delay_or_limit
|
||||
and not self.ignore_frontend
|
||||
and records_cpu_activity
|
||||
):
|
||||
if has_delay_or_limit and self.should_profile_frontend:
|
||||
logger.warning_once(
|
||||
"Using 'torch' profiler with delay_iterations or max_iterations "
|
||||
"while ignore_frontend is False may result in high overhead."
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kMxfp4Dynamic,
|
||||
kMxfp4Static,
|
||||
kMxfp8Dynamic,
|
||||
kNvfp4DynamicToken,
|
||||
kNvfp4Static,
|
||||
)
|
||||
|
||||
@@ -40,6 +41,7 @@ QUANT_KEY_NAMES: dict[str, QuantKey] = {
|
||||
"fp8_per_block_dynamic": kFp8Dynamic128Sym,
|
||||
"mxfp8": kMxfp8Dynamic,
|
||||
"mxfp4": kMxfp4Dynamic,
|
||||
"nvfp4_per_token": kNvfp4DynamicToken,
|
||||
"int8_per_channel_static": kInt8StaticChannelSym,
|
||||
# Load-time MXFP4-to-int4 for Kimi-K3 on gfx942.
|
||||
"int4_per_group_32": kInt4Static32,
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import InitVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self, cast
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config.utils import config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
import copy
|
||||
import functools
|
||||
from collections.abc import Callable, Mapping
|
||||
from typing import TYPE_CHECKING, Any, Literal, get_args
|
||||
from typing import TYPE_CHECKING, Any, Literal, Self, get_args
|
||||
|
||||
from pydantic import Field, SkipValidation, field_validator, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config import LoadConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
@@ -1970,6 +1969,9 @@ class SpeculativeConfig:
|
||||
def use_ngram_gpu(self) -> bool:
|
||||
return self.method == "ngram_gpu"
|
||||
|
||||
def use_ngram(self) -> bool:
|
||||
return self.method in ("ngram", "ngram_gpu")
|
||||
|
||||
def use_multi_module_mtp(self) -> bool:
|
||||
if self.method != "mtp" or self.draft_model_config is None:
|
||||
return False
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any, Literal
|
||||
from typing import Any, Literal, Self
|
||||
|
||||
from pydantic import model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config.utils import config
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
+66
-175
@@ -60,6 +60,7 @@ if TYPE_CHECKING:
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
else:
|
||||
PreTrainedConfig = Any
|
||||
@@ -151,12 +152,10 @@ class OptimizationLevel(IntEnum):
|
||||
PerformanceMode = Literal["balanced", "interactivity", "throughput"]
|
||||
|
||||
IS_QUANTIZED = False
|
||||
IS_DENSE = False
|
||||
# The optimizations that depend on these properties currently set to False
|
||||
# in all cases.
|
||||
# if model_config is not None:
|
||||
# IS_QUANTIZED = lambda c: c.model_config.is_quantized()
|
||||
# IS_DENSE = lambda c: not c.model_config.is_model_moe()
|
||||
# See https://github.com/vllm-project/vllm/issues/25689.
|
||||
|
||||
|
||||
@@ -265,8 +264,6 @@ OPTIMIZATION_LEVEL_00 = {
|
||||
"fuse_act_quant": False,
|
||||
"fuse_allreduce_rms": False,
|
||||
"fuse_attn_quant": False,
|
||||
"enable_sp": False,
|
||||
"fuse_gemm_comms": False,
|
||||
"fuse_act_padding": False,
|
||||
"fuse_mla_dual_rms_norm": False,
|
||||
"fuse_rope_kvcache": False,
|
||||
@@ -288,8 +285,6 @@ OPTIMIZATION_LEVEL_01 = {
|
||||
"fuse_act_quant": enable_act_fusion,
|
||||
"fuse_allreduce_rms": False,
|
||||
"fuse_attn_quant": False,
|
||||
"enable_sp": False,
|
||||
"fuse_gemm_comms": False,
|
||||
"fuse_act_padding": enable_norm_pad_fusion,
|
||||
"fuse_mla_dual_rms_norm": enable_mla_dual_rms_norm_fusion,
|
||||
"fuse_rope_kvcache": False,
|
||||
@@ -311,8 +306,6 @@ OPTIMIZATION_LEVEL_02 = {
|
||||
"fuse_act_quant": enable_act_fusion,
|
||||
"fuse_allreduce_rms": enable_allreduce_rms_fusion,
|
||||
"fuse_attn_quant": IS_QUANTIZED,
|
||||
"enable_sp": IS_DENSE,
|
||||
"fuse_gemm_comms": IS_DENSE,
|
||||
"fuse_act_padding": enable_norm_pad_fusion,
|
||||
"fuse_mla_dual_rms_norm": enable_mla_dual_rms_norm_fusion,
|
||||
"fuse_rope_kvcache": enable_rope_kvcache_fusion,
|
||||
@@ -334,8 +327,6 @@ OPTIMIZATION_LEVEL_03 = {
|
||||
"fuse_act_quant": enable_act_fusion,
|
||||
"fuse_allreduce_rms": enable_allreduce_rms_fusion,
|
||||
"fuse_attn_quant": IS_QUANTIZED,
|
||||
"enable_sp": IS_DENSE,
|
||||
"fuse_gemm_comms": IS_DENSE,
|
||||
"fuse_act_padding": enable_norm_pad_fusion,
|
||||
"fuse_mla_dual_rms_norm": enable_mla_dual_rms_norm_fusion,
|
||||
"fuse_rope_kvcache": enable_rope_kvcache_fusion,
|
||||
@@ -647,13 +638,15 @@ class VllmConfig:
|
||||
speculative_config = self.speculative_config
|
||||
if speculative_config is None:
|
||||
return 0
|
||||
if speculative_config.use_dflash():
|
||||
# DFlash requires an extra lookahead slot since it uses in-fill-style
|
||||
# decoding instead of standard next-token sampling, so it has a query
|
||||
# for the last sampled token plus queries for each draft token.
|
||||
dspark_fill_in = speculative_config.use_dspark() and not getattr(
|
||||
speculative_config.draft_model_config.hf_config, "sample_from_anchor", True
|
||||
)
|
||||
if speculative_config.use_dflash() or dspark_fill_in:
|
||||
# Fill-in drafting uses a bonus query plus one query per draft token.
|
||||
# DSpark's anchor-sampling layout does not need the extra slot.
|
||||
return self.num_speculative_tokens + 1
|
||||
if speculative_config.use_eagle() or speculative_config.uses_draft_model():
|
||||
# DSpark (covered by use_eagle) drafts a block of num_speculative_tokens
|
||||
# Anchor-sampling DSpark drafts a block of num_speculative_tokens
|
||||
# query tokens in which the anchor itself is the first prediction
|
||||
# position (no separate bonus query), so it needs exactly
|
||||
# num_speculative_tokens lookahead slots.
|
||||
@@ -716,7 +709,7 @@ class VllmConfig:
|
||||
and model_config.enable_sleep_mode
|
||||
and model_config.sleep_mode_backend == "cumem"
|
||||
and self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE
|
||||
and current_platform.is_cuda()
|
||||
and current_platform.is_cuda_alike()
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -832,9 +825,6 @@ class VllmConfig:
|
||||
or model.dtype != torch.bfloat16
|
||||
or model.quantization is not None
|
||||
or not current_platform.is_cuda()
|
||||
# Sequence parallelism / async TP are torch.compile passes.
|
||||
or self.compilation_config.pass_config.enable_sp
|
||||
or self.compilation_config.pass_config.fuse_gemm_comms
|
||||
):
|
||||
return False
|
||||
family = bi._get_tuned_matmul_arch_family(
|
||||
@@ -1319,15 +1309,22 @@ class VllmConfig:
|
||||
if not self.use_v2_model_runner:
|
||||
raise ValueError("trace replay requires Model Runner V2")
|
||||
|
||||
def _check_watermarking_unsupported(
|
||||
def _check_supports_watermarking(
|
||||
self,
|
||||
config: "SamplingParams | BeamSearchParams | None" = None,
|
||||
*,
|
||||
beam_search: bool = False,
|
||||
custom_sampler: bool = False,
|
||||
) -> None:
|
||||
) -> bool:
|
||||
watermark_config = getattr(self, "watermark_config", None)
|
||||
if watermark_config is None:
|
||||
return
|
||||
if config is not None and config.watermarking is True:
|
||||
logger.warning_once(
|
||||
"Watermarking is enabled for this request, but the engine has no "
|
||||
"watermark configuration. This and subsequent requests will run "
|
||||
"without watermarking.",
|
||||
scope="global",
|
||||
)
|
||||
return False
|
||||
if self.speculative_config is not None:
|
||||
speculative_config = self.speculative_config
|
||||
if speculative_config.draft_sample_method != "probabilistic":
|
||||
@@ -1382,12 +1379,44 @@ class VllmConfig:
|
||||
watermark_config.alpha,
|
||||
scope="global",
|
||||
)
|
||||
if beam_search:
|
||||
raise ValueError("Beam search is not supported with watermarking.")
|
||||
if custom_sampler:
|
||||
raise ValueError(
|
||||
"Model-specific custom samplers are not supported with watermarking."
|
||||
)
|
||||
if config is None:
|
||||
return True
|
||||
if config.watermarking is False:
|
||||
return False
|
||||
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
|
||||
if isinstance(config, BeamSearchParams):
|
||||
logger.warning_once(
|
||||
"Watermarking is enabled, but beam search cannot be watermarked. "
|
||||
"This and subsequent beam search requests will run without "
|
||||
"watermarking.",
|
||||
scope="global",
|
||||
)
|
||||
return False
|
||||
if not isinstance(config, SamplingParams):
|
||||
raise TypeError(f"Unsupported watermarking config: {type(config).__name__}")
|
||||
if config.trace_decode_token_ids is not None:
|
||||
logger.warning_once(
|
||||
"Watermarking is enabled, but trace replay cannot be watermarked. "
|
||||
"This and subsequent trace replay requests will run without "
|
||||
"watermarking.",
|
||||
scope="global",
|
||||
)
|
||||
return False
|
||||
if config.temperature == 0:
|
||||
logger.warning_once(
|
||||
"Watermarking is enabled, but greedy decoding "
|
||||
"(temperature=0) cannot be watermarked. This and subsequent "
|
||||
"greedy requests will use ordinary greedy sampling.",
|
||||
scope="global",
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _resolve_and_verify_engram_config(self) -> None:
|
||||
"""Resolve defaults and validate n-gram embedding settings."""
|
||||
@@ -1451,7 +1480,7 @@ class VllmConfig:
|
||||
self.try_verify_and_update_config()
|
||||
self._resolve_and_verify_engram_config()
|
||||
|
||||
self._check_watermarking_unsupported()
|
||||
self._check_supports_watermarking()
|
||||
# Models may have supplied their own DCP defaults above; anything still
|
||||
# unset falls back to the stock ones.
|
||||
self.parallel_config.set_dcp_defaults()
|
||||
@@ -1735,26 +1764,6 @@ class VllmConfig:
|
||||
)
|
||||
self.compilation_config.mode = CompilationMode.NONE
|
||||
|
||||
# TODO: This is a stopgap that turns sequence parallelism / async TP
|
||||
# off under batch invariance. Make the sequence-parallel reduce-scatter
|
||||
# path batch-invariant instead so they can stay enabled (#56370).
|
||||
# Sequence parallelism / async TP rewrite all_reduce + rms_norm into a
|
||||
# reduce-scatter whose reduction order depends on the batch, so they
|
||||
# are not batch-invariant. Decide this before the breakable-CUDA-graph
|
||||
# default below, which declines to auto-enable when they are on.
|
||||
pass_config = self.compilation_config.pass_config
|
||||
if envs.VLLM_BATCH_INVARIANT and (
|
||||
pass_config.enable_sp or pass_config.fuse_gemm_comms
|
||||
):
|
||||
logger.warning_once(
|
||||
"Disabling sequence parallelism and async TP "
|
||||
"(pass_config.enable_sp / fuse_gemm_comms) when "
|
||||
"VLLM_BATCH_INVARIANT is enabled: the reduce-scatter path "
|
||||
"is not batch-invariant (see vllm-project/vllm#56370)."
|
||||
)
|
||||
pass_config.enable_sp = False
|
||||
pass_config.fuse_gemm_comms = False
|
||||
|
||||
breakable_cudagraph_enabled = self._maybe_enable_breakable_cudagraph()
|
||||
|
||||
if not breakable_cudagraph_enabled and (
|
||||
@@ -1843,6 +1852,12 @@ class VllmConfig:
|
||||
raise ValueError(
|
||||
"HiSparse does not support decode context parallelism."
|
||||
)
|
||||
if self.compilation_config.cudagraph_mode == CUDAGraphMode.FULL:
|
||||
raise ValueError(
|
||||
"HiSparse does not support cudagraph_mode=FULL; use "
|
||||
"FULL_AND_PIECEWISE (the default), which captures FULL graphs "
|
||||
"for decode batches."
|
||||
)
|
||||
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
|
||||
@@ -1879,38 +1894,6 @@ class VllmConfig:
|
||||
breakable_cudagraph_enabled=breakable_cudagraph_enabled
|
||||
)
|
||||
|
||||
# async tp is built on top of sequence parallelism and requires it.
|
||||
pass_config = self.compilation_config.pass_config
|
||||
if pass_config.fuse_gemm_comms:
|
||||
pass_config.enable_sp = True
|
||||
if pass_config.enable_sp:
|
||||
if self.parallel_config.tensor_parallel_size == 1:
|
||||
logger.warning_once("Sequence Parallelism requires TP>1, disabling")
|
||||
pass_config.enable_sp = False
|
||||
pass_config.fuse_gemm_comms = False
|
||||
else:
|
||||
if pass_config.sp_min_token_num is None:
|
||||
from vllm.compilation.passes.fusion.sequence_parallelism import (
|
||||
get_sequence_parallelism_threshold,
|
||||
)
|
||||
|
||||
tp_size = self.parallel_config.tensor_parallel_size
|
||||
hidden_size = self.model_config.get_hidden_size()
|
||||
assert isinstance(self.model_config.dtype, torch.dtype)
|
||||
element_size = self.model_config.dtype.itemsize
|
||||
pass_config.sp_min_token_num = get_sequence_parallelism_threshold(
|
||||
hidden_size, tp_size, element_size
|
||||
)
|
||||
|
||||
if pass_config.sp_min_token_num is None:
|
||||
logger.warning_once(
|
||||
"Model hidden_size too small for the SP "
|
||||
"threshold heuristic, disabling. To force SP, "
|
||||
"set pass_config.sp_min_token_num manually."
|
||||
)
|
||||
pass_config.enable_sp = False
|
||||
pass_config.fuse_gemm_comms = False
|
||||
|
||||
from vllm.utils.torch_utils import HAS_OPAQUE_TYPE
|
||||
|
||||
if HAS_OPAQUE_TYPE:
|
||||
@@ -2143,30 +2126,6 @@ class VllmConfig:
|
||||
data_parallel_size=effective_dp_size,
|
||||
)
|
||||
|
||||
if self.compilation_config.pass_config.enable_sp:
|
||||
# With pipeline parallelism, native rms norm tracing errors due to
|
||||
# incorrect residual shape.
|
||||
# Use custom rms norm to unblock. In the future,
|
||||
# the pass will operate on higher-level IR to avoid the issue.
|
||||
# TODO: https://github.com/vllm-project/vllm/issues/27894
|
||||
if self.compilation_config.mode != CompilationMode.VLLM_COMPILE:
|
||||
logger.warning_once(
|
||||
"Sequence parallelism is enabled, but running in wrong "
|
||||
"vllm compile mode: %s.",
|
||||
self.compilation_config.mode,
|
||||
)
|
||||
|
||||
if self.parallel_config.pipeline_parallel_size > 1:
|
||||
if "-rms_norm" not in self.compilation_config.custom_ops:
|
||||
self.compilation_config.custom_ops.append("+rms_norm")
|
||||
else:
|
||||
logger.warning_once(
|
||||
"Sequence parallelism not supported with "
|
||||
"native rms_norm when using %s, "
|
||||
"this will likely lead to an error.",
|
||||
"pipeline parallelism",
|
||||
)
|
||||
|
||||
# final check of cudagraph mode after all possible updates
|
||||
if current_platform.is_cuda_alike():
|
||||
if (
|
||||
@@ -2354,29 +2313,6 @@ class VllmConfig:
|
||||
# Log the custom passes that are enabled
|
||||
self.compilation_config.pass_config.log_enabled_passes()
|
||||
|
||||
def update_sizes_for_sequence_parallelism(self, possible_sizes: list) -> list:
|
||||
# remove the sizes that not multiple of tp_size when
|
||||
# enable sequence parallelism
|
||||
removed_sizes = [
|
||||
size
|
||||
for size in possible_sizes
|
||||
if size % self.parallel_config.tensor_parallel_size != 0
|
||||
]
|
||||
if removed_sizes:
|
||||
logger.warning(
|
||||
"Batch sizes %s are removed because they are not "
|
||||
"multiple of tp_size %d when "
|
||||
"sequence parallelism is enabled",
|
||||
removed_sizes,
|
||||
self.parallel_config.tensor_parallel_size,
|
||||
)
|
||||
|
||||
return [
|
||||
size
|
||||
for size in possible_sizes
|
||||
if size % self.parallel_config.tensor_parallel_size == 0
|
||||
]
|
||||
|
||||
def _set_max_num_scheduled_tokens(self):
|
||||
"""In most cases, the scheduler may schedule a batch with as many tokens as the
|
||||
worker is configured to handle.
|
||||
@@ -2624,16 +2560,6 @@ class VllmConfig:
|
||||
# de-duplicate and sort the sizes
|
||||
cudagraph_capture_sizes = sorted(set(cudagraph_capture_sizes))
|
||||
|
||||
if (
|
||||
self.parallel_config.tensor_parallel_size > 1
|
||||
and self.compilation_config.pass_config.enable_sp
|
||||
):
|
||||
# Sequence parallelism only captures TP-divisible sizes, so a
|
||||
# wider non-divisible decode batch cannot be captured under SP.
|
||||
cudagraph_capture_sizes = self.update_sizes_for_sequence_parallelism(
|
||||
cudagraph_capture_sizes
|
||||
)
|
||||
|
||||
# user-specific compilation_config.max_cudagraph_capture_size get
|
||||
# truncated to valid_max_size when they are inconsistent.
|
||||
valid_max_size = (
|
||||
@@ -2723,37 +2649,6 @@ class VllmConfig:
|
||||
"allreduce-rms fusion will be enabled for all num_tokens."
|
||||
)
|
||||
|
||||
# Add the compile ranges for sequence parallelism
|
||||
if compilation_config.pass_config.enable_sp:
|
||||
pass_config = compilation_config.pass_config
|
||||
|
||||
# Calculate min_token_num if not explicitly provided
|
||||
# User override works regardless of hidden_size
|
||||
if pass_config.sp_min_token_num is None:
|
||||
from vllm.compilation.passes.fusion.sequence_parallelism import (
|
||||
get_sequence_parallelism_threshold,
|
||||
)
|
||||
|
||||
tp_size = self.parallel_config.tensor_parallel_size
|
||||
hidden_size = self.model_config.get_hidden_size()
|
||||
assert isinstance(self.model_config.dtype, torch.dtype)
|
||||
element_size = self.model_config.dtype.itemsize
|
||||
pass_config.sp_min_token_num = get_sequence_parallelism_threshold(
|
||||
hidden_size, tp_size, element_size
|
||||
)
|
||||
|
||||
min_token_num = pass_config.sp_min_token_num
|
||||
max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
|
||||
if min_token_num is not None and (
|
||||
max_num_batched_tokens is not None
|
||||
and min_token_num < max_num_batched_tokens
|
||||
and min_token_num > 1
|
||||
):
|
||||
# Add endpoint at min_token_num - 1 to ensure SP applies
|
||||
# starting from min_token_num
|
||||
# This creates ranges: [1, min-1] (no SP), [min, max] (SP applies)
|
||||
computed_compile_ranges_endpoints.append(min_token_num - 1)
|
||||
|
||||
if compilation_config.pass_config.fuse_rope_kvcache:
|
||||
max_token_num = (
|
||||
compilation_config.pass_config.rope_kvcache_fusion_max_token_num
|
||||
@@ -3083,12 +2978,6 @@ class VllmConfig:
|
||||
unsupported: list[str] = []
|
||||
speculative_config = self.speculative_config
|
||||
|
||||
if (
|
||||
self.compilation_config.pass_config.enable_sp
|
||||
and self.parallel_config.tensor_parallel_size > 1
|
||||
):
|
||||
unsupported.append("sequence parallelism")
|
||||
|
||||
# V2 does not implement the external_launcher (torchrun) PP-output
|
||||
# broadcast that V1 uses to keep all ranks in sync (broadcast_pp_output).
|
||||
if (
|
||||
@@ -3099,9 +2988,6 @@ class VllmConfig:
|
||||
|
||||
if speculative_config is not None:
|
||||
if speculative_config.method in (
|
||||
# https://github.com/vllm-project/vllm/pull/40704
|
||||
"ngram",
|
||||
"ngram_gpu",
|
||||
"suffix",
|
||||
"medusa",
|
||||
"mlp_speculator",
|
||||
@@ -3118,6 +3004,11 @@ class VllmConfig:
|
||||
):
|
||||
unsupported.append("parallel drafting for EAGLE speculative decoding")
|
||||
|
||||
# The V2 draft-model speculator has no token mapping between the
|
||||
# draft and target vocabularies (TLI is TBD in #47172).
|
||||
if getattr(speculative_config, "use_heterogeneous_vocab", False):
|
||||
unsupported.append("heterogeneous-vocabulary draft models")
|
||||
|
||||
if self.parallel_config.use_ubatching:
|
||||
unsupported.extend(self._get_dbo_unsupported_features())
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import hashlib
|
||||
from typing import Literal
|
||||
from typing import Literal, Self
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.config.utils import config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -98,7 +98,7 @@ class CuMemAllocator:
|
||||
offloaded to CPU memory, and the rest of the tensors will be discarded.
|
||||
When we call `wake_up`, all tensors that are previously offloaded
|
||||
will be loaded back to GPU memory, and the rest of the tensors will
|
||||
have empty memory.
|
||||
have empty memory (zeroed on ROCm).
|
||||
|
||||
Why it needs to be a singleton?
|
||||
When allocated tensors are garbage collected, PyTorch will call
|
||||
@@ -331,7 +331,7 @@ class CuMemAllocator:
|
||||
def wake_up(self, tags: list[str] | None = None) -> None:
|
||||
"""Wake up the allocator from sleep mode.
|
||||
All data that is previously offloaded will be loaded back to GPU
|
||||
memory, and the rest of the data will have empty memory.
|
||||
memory, and the rest will have empty memory (zeroed on ROCm).
|
||||
|
||||
Args:
|
||||
tags: The deferrable tags (weights, kv_cache) to load back to GPU
|
||||
@@ -358,6 +358,10 @@ class CuMemAllocator:
|
||||
cpu_ptr = cpu_backup_tensor.data_ptr()
|
||||
libcudart.cudaMemcpy(ptr, cpu_ptr, size_in_bytes)
|
||||
data.cpu_backup_tensor = None
|
||||
elif current_platform.is_rocm():
|
||||
# amdgpu <6.14 may return stale VRAM (#44972); drop with its support
|
||||
libcudart.cudaMemset(ptr, 0, handle[1])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
@contextmanager
|
||||
def use_memory_pool(self, tag: str | None = None):
|
||||
|
||||
@@ -67,8 +67,12 @@ class AuxOutputSchedulerConnector:
|
||||
block_hashes_by_request[request_id] = packed
|
||||
self._sent_hash_counts[request_id] = len(request.block_hashes)
|
||||
assert request.sampling_params is not None
|
||||
# A P/D prefiller may cut the prompt short of the requested start.
|
||||
scheduled_requests[request_id] = max(
|
||||
request.sampling_params.routed_experts_prompt_start,
|
||||
min(
|
||||
request.sampling_params.routed_experts_prompt_start,
|
||||
request.num_prompt_tokens,
|
||||
),
|
||||
0 if request.num_output_tokens == 0 else request.num_tokens - 1,
|
||||
)
|
||||
# A settled token can complete a hash block after the next async schedule
|
||||
|
||||
@@ -30,6 +30,8 @@ class AiterCustomAllreduce:
|
||||
group: ProcessGroup,
|
||||
device: int | str | torch.device,
|
||||
max_size: int | None = None,
|
||||
*,
|
||||
register_graph_buffers: bool = True,
|
||||
):
|
||||
from aiter.dist.device_communicators.custom_all_reduce import (
|
||||
CustomAllreduce as _AiterCustomAllreduce,
|
||||
@@ -38,7 +40,10 @@ class AiterCustomAllreduce:
|
||||
if max_size is None:
|
||||
max_size = self.MAX_SIZE
|
||||
|
||||
self._impl = _AiterCustomAllreduce(group, device, max_size=max_size)
|
||||
kwargs = {}
|
||||
if not register_graph_buffers:
|
||||
kwargs["enable_register_for_capturing"] = False
|
||||
self._impl = _AiterCustomAllreduce(group, device, max_size=max_size, **kwargs)
|
||||
|
||||
@property
|
||||
def aiter_ca(self):
|
||||
|
||||
@@ -171,6 +171,42 @@ class AgRsAll2AllManager(All2AllManagerBase):
|
||||
hidden_states = dist_group.reduce_scatterv(hidden_states, dim=0, sizes=sizes)
|
||||
return hidden_states
|
||||
|
||||
def allocate_combine_input(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
dist_group = self._get_comm_group(is_sequence_parallel)
|
||||
sizes = self._get_sizes(shape[0] // dist_group.world_size, dist_group)
|
||||
if sum(sizes) != shape[0] or any(size != sizes[0] for size in sizes):
|
||||
return None
|
||||
device_communicator = dist_group.device_communicator
|
||||
if device_communicator is None:
|
||||
return None
|
||||
return device_communicator.get_symmetric_memory_buffer(
|
||||
"moe_ag_rs_combine", shape, dtype, device
|
||||
)
|
||||
|
||||
def combine_into_output(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor:
|
||||
dist_group = self._get_comm_group(is_sequence_parallel)
|
||||
sizes = self._get_sizes(
|
||||
hidden_states.shape[0] // dist_group.world_size,
|
||||
dist_group,
|
||||
)
|
||||
return dist_group.reduce_scatterv_into_output(
|
||||
hidden_states,
|
||||
output,
|
||||
dim=0,
|
||||
sizes=sizes,
|
||||
)
|
||||
|
||||
def destroy(self):
|
||||
pass
|
||||
|
||||
@@ -972,6 +1008,11 @@ class MoriAll2AllManager(All2AllManagerBase):
|
||||
self.handle_cache = Cache()
|
||||
|
||||
torch._C._distributed_c10d._register_process_group("mori", cpu_group)
|
||||
if get_current_vllm_config().kernel_config.moe_backend == "aiter_mega_moe":
|
||||
# MegaMoEV2 places its dispatch/combine workspaces on the MoRI
|
||||
# symmetric heap, which defaults to 2 GB. MegaMoEV2 requires > 4GB
|
||||
heap_size = os.environ.setdefault("MORI_SHMEM_HEAP_SIZE", "8G")
|
||||
logger.info_once("AITER MegaMoE: MORI_SHMEM_HEAP_SIZE=%s", heap_size)
|
||||
mori.shmem.shmem_torch_process_group_init("mori")
|
||||
|
||||
def _make_all2all_kwargs(
|
||||
|
||||
@@ -157,6 +157,24 @@ class All2AllManagerBase:
|
||||
def combine(self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False):
|
||||
raise NotImplementedError
|
||||
|
||||
def allocate_combine_input(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
return None
|
||||
|
||||
def combine_into_output(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor:
|
||||
output.copy_(self.combine(hidden_states, is_sequence_parallel))
|
||||
return output
|
||||
|
||||
def destroy(self):
|
||||
pass
|
||||
|
||||
@@ -315,6 +333,25 @@ class DeviceCommunicatorBase:
|
||||
) -> torch.Tensor:
|
||||
raise NotImplementedError
|
||||
|
||||
def reduce_scatterv_into_output(
|
||||
self,
|
||||
input_: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
dim: int = -1,
|
||||
sizes: list[int] | None = None,
|
||||
) -> torch.Tensor:
|
||||
output.copy_(self.reduce_scatterv(input_, dim, sizes))
|
||||
return output
|
||||
|
||||
def get_symmetric_memory_buffer(
|
||||
self,
|
||||
role: str,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> torch.Tensor | None:
|
||||
return None
|
||||
|
||||
def gather(
|
||||
self, input_: torch.Tensor, dst: int = 0, dim: int = -1
|
||||
) -> torch.Tensor | None:
|
||||
@@ -417,5 +454,23 @@ class DeviceCommunicatorBase:
|
||||
"""
|
||||
return hidden_states
|
||||
|
||||
def allocate_combine_input(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
return None
|
||||
|
||||
def combine_into_output(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor:
|
||||
output.copy_(self.combine(hidden_states, is_sequence_parallel))
|
||||
return output
|
||||
|
||||
def batch_isend_irecv(self, p2p_ops: list):
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm.distributed.device_communicators.all_reduce_utils import (
|
||||
from vllm.distributed.device_communicators.pynccl import register_nccl_symmetric_ops
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import (
|
||||
is_symmetric_memory_enabled,
|
||||
is_symmetric_memory_tensor,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
@@ -26,6 +27,10 @@ from .base_device_communicator import DeviceCommunicatorBase
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Since NCCL 2.29.2, ncclSymkPickKernel accepts registered input with
|
||||
# non-registered output for ReduceScatter (ncclSymSendRegRecvNonreg).
|
||||
NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION = 22902
|
||||
|
||||
|
||||
class CudaCommunicator(DeviceCommunicatorBase):
|
||||
def __init__(
|
||||
@@ -146,6 +151,7 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
self.aiter_ar_comm = AiterCustomAllreduce(
|
||||
group=self.cpu_group,
|
||||
device=self.device,
|
||||
register_graph_buffers=register,
|
||||
)
|
||||
|
||||
if use_custom_allreduce and self.aiter_ar_comm is None and self.world_size > 1:
|
||||
@@ -169,6 +175,7 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
self.aiter_ar_comm = AiterCustomAllreduce(
|
||||
group=self.cpu_group,
|
||||
device=self.device,
|
||||
register_graph_buffers=register,
|
||||
)
|
||||
if self.aiter_ar_comm.disabled:
|
||||
self.aiter_ar_comm = None
|
||||
@@ -505,13 +512,33 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
def reduce_scatterv(
|
||||
self, input_: torch.Tensor, dim: int = -1, sizes: list[int] | None = None
|
||||
):
|
||||
return self._reduce_scatterv(input_, dim, sizes)
|
||||
|
||||
def reduce_scatterv_into_output(
|
||||
self,
|
||||
input_: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
dim: int = -1,
|
||||
sizes: list[int] | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._reduce_scatterv(input_, dim, sizes, output)
|
||||
|
||||
def _reduce_scatterv(
|
||||
self,
|
||||
input_: torch.Tensor,
|
||||
dim: int,
|
||||
sizes: list[int] | None,
|
||||
output: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
world_size = self.world_size
|
||||
pynccl_comm = self.pynccl_comm
|
||||
assert pynccl_comm is not None
|
||||
assert not pynccl_comm.disabled, "reduce_scatterv requires PyNccl"
|
||||
if dim < 0:
|
||||
# Convert negative dim to positive.
|
||||
dim += input_.dim()
|
||||
|
||||
sizes_are_explicit = sizes is not None
|
||||
# 'sizes' is not needed if all inputs in the same group have the same
|
||||
# shape
|
||||
if sizes is not None and all(s == sizes[0] for s in sizes):
|
||||
@@ -529,35 +556,63 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
assert input_tensor.shape[0] % world_size == 0
|
||||
chunk_size = input_tensor.shape[0] // world_size
|
||||
output_shape = (chunk_size,) + input_tensor.shape[1:]
|
||||
if output is not None:
|
||||
assert dim == 0, "preallocated reduce-scatter output requires dim=0"
|
||||
assert output.shape == output_shape
|
||||
assert output.dtype == input_tensor.dtype
|
||||
assert output.device == input_tensor.device
|
||||
assert output.is_contiguous()
|
||||
|
||||
if self._can_use_aiter_ag_rs(sizes):
|
||||
aiter_comm = self.aiter_ar_comm
|
||||
assert aiter_comm is not None
|
||||
if aiter_comm.should_custom_rs(input_tensor, dim=0):
|
||||
output = torch.empty(
|
||||
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
|
||||
)
|
||||
if output is None:
|
||||
output = torch.empty(
|
||||
output_shape,
|
||||
dtype=input_tensor.dtype,
|
||||
device=input_tensor.device,
|
||||
)
|
||||
aiter_comm.custom_reduce_scatter(input_tensor, output, dim=0)
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
# Symmetric memory is only used when all ranks have uniform sizes.
|
||||
# ncclCommWindowRegister is collective: asymmetric pool allocations
|
||||
# from variable per-rank sizes cause deadlocks.
|
||||
use_symm_mem = sizes is None and should_nccl_symm_mem_ag_rs()
|
||||
if use_symm_mem:
|
||||
output = self._reduce_scatter_symm_mem(input_tensor)
|
||||
else:
|
||||
output = torch.empty(
|
||||
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
|
||||
uniform_sizes = sizes is None or all(size == sizes[0] for size in sizes)
|
||||
direct_output_supported = (
|
||||
output is None
|
||||
or is_symmetric_memory_tensor(output)
|
||||
or pynccl_comm.nccl_version >= NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION
|
||||
)
|
||||
use_symm_mem = (
|
||||
uniform_sizes
|
||||
and direct_output_supported
|
||||
and (
|
||||
output is None
|
||||
or not sizes_are_explicit
|
||||
or is_symmetric_memory_tensor(input_tensor)
|
||||
)
|
||||
and should_nccl_symm_mem_ag_rs()
|
||||
)
|
||||
if use_symm_mem:
|
||||
output = self._reduce_scatter_symm_mem(input_tensor, output)
|
||||
else:
|
||||
if output is None:
|
||||
output = torch.empty(
|
||||
output_shape, dtype=input_tensor.dtype, device=input_tensor.device
|
||||
)
|
||||
use_deterministic_rs = envs.VLLM_BATCH_INVARIANT and world_size > 2
|
||||
if use_deterministic_rs:
|
||||
# Reduce to a fixed root (0) for determinism
|
||||
reduced = torch.empty_like(input_tensor)
|
||||
sizes = sizes if sizes else [chunk_size] * world_size
|
||||
scatter_sizes = sizes
|
||||
if scatter_sizes is None:
|
||||
scatter_sizes = [chunk_size] * world_size
|
||||
pynccl_comm.reduce(reduced, input_tensor, root=0)
|
||||
pynccl_comm.scatter(output, reduced, sizes, root=0)
|
||||
elif sizes is not None and sizes.count(sizes[0]) != len(sizes):
|
||||
pynccl_comm.scatter(output, reduced, scatter_sizes, root=0)
|
||||
elif not uniform_sizes:
|
||||
assert sizes is not None
|
||||
pynccl_comm.reduce_scatterv(output, input_tensor, sizes=sizes)
|
||||
else:
|
||||
pynccl_comm.reduce_scatter(output, input_tensor)
|
||||
@@ -576,54 +631,64 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
|
||||
Allocating a fresh symm tensor per collective pays the
|
||||
``nccl_symm_mem_context`` snapshot + window-registration scan on every
|
||||
call (~0.5 ms/RS+AG pair, dwarfing the NVLS transfer itself). Instead we
|
||||
allocate once per ``(role, shape, dtype)``, register once, and reuse.
|
||||
call (~0.5 ms/RS+AG pair, dwarfing the NVLS transfer itself). Instead,
|
||||
each ``(role, shape[1:], dtype, device)`` keeps a geometric high-water
|
||||
allocation and returns a leading slice. Superseded allocations remain
|
||||
referenced because a captured CUDA graph may still use their pointers;
|
||||
geometric growth bounds their total capacity to less than twice the
|
||||
current allocation.
|
||||
|
||||
Safe for serial (eager) sequence parallelism: each collective's result
|
||||
is consumed on the same stream before the next same-role collective
|
||||
reuses the buffer. Distinct roles (e.g. ``rs_in`` vs ``ag_out``, both
|
||||
full-size) get distinct buffers so a reduce-scatter input copy never
|
||||
clobbers a still-live all-gather output.
|
||||
Safe across serial MoE layers and eager sequence parallelism: the
|
||||
producer and collective are ordered on the same stream before the next
|
||||
same-role operation reuses the buffer. DBO microbatches use distinct
|
||||
cache entries. Any future cross-layer communication overlap must also
|
||||
use distinct roles.
|
||||
"""
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import (
|
||||
nccl_symm_mem_context,
|
||||
)
|
||||
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
|
||||
|
||||
pynccl_comm = self.pynccl_comm
|
||||
assert pynccl_comm is not None
|
||||
assert shape, "symmetric scratch buffers require at least one dimension"
|
||||
cache = self.__dict__.setdefault("_symm_scratch_bufs", {})
|
||||
key = (role, tuple(shape), dtype)
|
||||
key = (role, dbo_current_ubatch_id(), tuple(shape[1:]), dtype, device)
|
||||
buf = cache.get(key)
|
||||
if buf is None:
|
||||
requested_rows = shape[0]
|
||||
if buf is None or buf.shape[0] < requested_rows:
|
||||
capacity = (
|
||||
requested_rows if buf is None else max(requested_rows, 2 * buf.shape[0])
|
||||
)
|
||||
with nccl_symm_mem_context(pynccl_comm):
|
||||
buf = torch.empty(shape, dtype=dtype, device=device)
|
||||
new_buf = torch.empty(
|
||||
(capacity, *shape[1:]), dtype=dtype, device=device
|
||||
)
|
||||
if buf is not None:
|
||||
retired = self.__dict__.setdefault("_retired_symm_scratch_bufs", {})
|
||||
retired.setdefault(key, []).append(buf)
|
||||
buf = new_buf
|
||||
cache[key] = buf
|
||||
return buf
|
||||
return buf[:requested_rows]
|
||||
|
||||
def _reduce_scatter_symm_mem(
|
||||
self,
|
||||
input_tensor: torch.Tensor,
|
||||
output: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""ReduceScatter using NCCL symmetric memory (NVLS).
|
||||
|
||||
Only called for uniform-size reduce_scatter (variable sizes are
|
||||
guarded out by the caller to avoid asymmetric ncclCommWindowRegister).
|
||||
Uses persistent pre-registered scratch (see _get_symm_scratch).
|
||||
The MoE reduce_scatterv path passes explicit uniform sizes and calls
|
||||
this only with an already-registered input, so that path never stages.
|
||||
Uniform calls without a caller-owned output retain their existing
|
||||
opt-in behavior and stage ordinary input into registered scratch.
|
||||
The output may be ordinary memory.
|
||||
"""
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import (
|
||||
is_symmetric_memory_tensor,
|
||||
)
|
||||
|
||||
pynccl_comm = self.pynccl_comm
|
||||
assert pynccl_comm is not None
|
||||
|
||||
chunk = input_tensor.shape[0] // self.world_size
|
||||
output_shape = (chunk,) + tuple(input_tensor.shape[1:])
|
||||
|
||||
symm_output = self._get_symm_scratch(
|
||||
"rs_out", output_shape, input_tensor.dtype, input_tensor.device
|
||||
)
|
||||
# NVLS reduce-scatter (LDMC) requires the input in symmetric memory.
|
||||
if is_symmetric_memory_tensor(input_tensor):
|
||||
symm_input = input_tensor
|
||||
else:
|
||||
@@ -635,8 +700,31 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
)
|
||||
symm_input.copy_(input_tensor)
|
||||
|
||||
pynccl_comm.reduce_scatter(symm_output, symm_input)
|
||||
return symm_output
|
||||
if output is None:
|
||||
output = self._get_symm_scratch(
|
||||
"rs_out", output_shape, input_tensor.dtype, input_tensor.device
|
||||
)
|
||||
pynccl_comm.reduce_scatter(output, symm_input)
|
||||
return output
|
||||
|
||||
def get_symmetric_memory_buffer(
|
||||
self,
|
||||
role: str,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> torch.Tensor | None:
|
||||
pynccl_comm = self.pynccl_comm
|
||||
if (
|
||||
pynccl_comm is None
|
||||
or pynccl_comm.disabled
|
||||
or pynccl_comm.world_size == 1
|
||||
or pynccl_comm.nccl_version < NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION
|
||||
or not should_nccl_symm_mem_ag_rs()
|
||||
):
|
||||
return None
|
||||
output = self._get_symm_scratch(role, shape, dtype, device)
|
||||
return output if is_symmetric_memory_tensor(output) else None
|
||||
|
||||
def send(self, tensor: torch.Tensor, dst: int | None = None) -> None:
|
||||
"""Sends a tensor to the destination rank in a blocking way."""
|
||||
@@ -925,6 +1013,29 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
is_sequence_parallel,
|
||||
)
|
||||
|
||||
def allocate_combine_input(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
assert self.all2all_manager is not None
|
||||
return self.all2all_manager.allocate_combine_input(
|
||||
shape, dtype, device, is_sequence_parallel
|
||||
)
|
||||
|
||||
def combine_into_output(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor:
|
||||
assert self.all2all_manager is not None
|
||||
return self.all2all_manager.combine_into_output(
|
||||
hidden_states, output, is_sequence_parallel
|
||||
)
|
||||
|
||||
def batch_isend_irecv(self, p2p_ops: list):
|
||||
pynccl_comm = self.pynccl_comm
|
||||
if pynccl_comm is not None and not pynccl_comm.disabled:
|
||||
|
||||
@@ -9,6 +9,7 @@ import shutil
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import weakref
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing import shared_memory
|
||||
@@ -472,6 +473,12 @@ class Handle:
|
||||
remote_addr_ipv6: bool = False
|
||||
|
||||
|
||||
def _close_zmq(context: zmq.Context, sockets: list[zmq.Socket]) -> None:
|
||||
for socket in sockets:
|
||||
socket.close(linger=0)
|
||||
context.term()
|
||||
|
||||
|
||||
class MessageQueue:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -561,9 +568,26 @@ class MessageQueue:
|
||||
remote_subscribe_addr=remote_subscribe_addr,
|
||||
remote_addr_ipv6=remote_addr_ipv6,
|
||||
)
|
||||
self._close_zmq_on_collect(context)
|
||||
|
||||
logger.debug("vLLM message queue communication handle: %s", self.handle)
|
||||
|
||||
def _close_zmq_on_collect(self, context: zmq.Context) -> None:
|
||||
# pyzmq's Context.__del__ can block forever in term() when the context
|
||||
# and its sockets are collected in the same GC cycle, so the finalizer
|
||||
# keeps them alive and closes the sockets before terminating.
|
||||
sockets = [self.local_socket, self.remote_socket]
|
||||
if self._spin_condition is not None:
|
||||
sockets += [
|
||||
self._spin_condition.local_notify_socket,
|
||||
self._spin_condition.read_cancel_socket,
|
||||
self._spin_condition.write_cancel_socket,
|
||||
]
|
||||
finalizer = weakref.finalize(
|
||||
self, _close_zmq, context, [s for s in sockets if s is not None]
|
||||
)
|
||||
finalizer.atexit = False # type: ignore[misc]
|
||||
|
||||
def export_handle(self) -> Handle:
|
||||
return self.handle
|
||||
|
||||
@@ -613,6 +637,7 @@ class MessageQueue:
|
||||
self._spin_condition = None # type: ignore
|
||||
|
||||
self.shutting_down = False
|
||||
self._close_zmq_on_collect(context)
|
||||
return self
|
||||
|
||||
def wait_until_ready(self):
|
||||
|
||||
@@ -115,7 +115,11 @@ class ECCPUScheduler:
|
||||
self._element_size: int = 0
|
||||
self._ack_timeout_s: float = 0.0
|
||||
if self._nixl_enabled:
|
||||
self._setup_nixl(vllm_config)
|
||||
try:
|
||||
self._setup_nixl(vllm_config)
|
||||
except Exception:
|
||||
self.shutdown()
|
||||
raise
|
||||
|
||||
def _setup_nixl(self, vllm_config: "VllmConfig") -> None:
|
||||
# Lazy imports keep nixl/zmq off the gate-off path.
|
||||
@@ -165,35 +169,26 @@ class ECCPUScheduler:
|
||||
self._peer_host = envs.VLLM_EC_SIDE_CHANNEL_HOST
|
||||
self._peer_port = envs.VLLM_EC_SIDE_CHANNEL_PORT
|
||||
|
||||
# Registering the region with NIXL and binding the control sockets are
|
||||
# the first side effects here. __init__ propagates a failure, so the
|
||||
# caller never receives a scheduler it could shut down: unwind through
|
||||
# the same teardown shutdown() uses.
|
||||
try:
|
||||
self._data = NixlDataTransport(
|
||||
agent_name=engine_id,
|
||||
base_ptr=self._region.blocks.data_ptr(),
|
||||
num_blocks=self._region.num_blocks,
|
||||
block_size_bytes=self._region.block_size_bytes,
|
||||
total_size_bytes=self._region.num_blocks
|
||||
* self._region.block_size_bytes,
|
||||
self._data = NixlDataTransport(
|
||||
agent_name=engine_id,
|
||||
base_ptr=self._region.blocks.data_ptr(),
|
||||
num_blocks=self._region.num_blocks,
|
||||
block_size_bytes=self._region.block_size_bytes,
|
||||
total_size_bytes=self._region.num_blocks * self._region.block_size_bytes,
|
||||
)
|
||||
if self._is_producer:
|
||||
assert self._peer_host is not None
|
||||
assert self._peer_port is not None
|
||||
self._producer_session = ProducerSession(
|
||||
transport=ZmqServerTransport(
|
||||
host=self._peer_host, port=self._peer_port
|
||||
),
|
||||
data=self._data,
|
||||
cache=self._cache,
|
||||
compat_hash=self._compat_hash,
|
||||
)
|
||||
if self._is_producer:
|
||||
assert self._peer_host is not None
|
||||
assert self._peer_port is not None
|
||||
self._producer_session = ProducerSession(
|
||||
transport=ZmqServerTransport(
|
||||
host=self._peer_host, port=self._peer_port
|
||||
),
|
||||
data=self._data,
|
||||
cache=self._cache,
|
||||
compat_hash=self._compat_hash,
|
||||
)
|
||||
if self._is_consumer:
|
||||
self._transport = ZmqClientTransport()
|
||||
except Exception:
|
||||
self._teardown_nixl()
|
||||
raise
|
||||
if self._is_consumer:
|
||||
self._transport = ZmqClientTransport()
|
||||
|
||||
def has_cache_item(self, identifier: str) -> bool:
|
||||
if not self._is_consumer:
|
||||
|
||||
@@ -454,8 +454,8 @@ class ElasticEPScalingExecutor:
|
||||
torch.compiler.reset()
|
||||
with set_current_vllm_config(self.worker.vllm_config):
|
||||
reset_compile_wrapper(self.worker.model_runner.get_model())
|
||||
if speculator is not None:
|
||||
reset_compile_wrapper(speculator.model)
|
||||
if draft_model := getattr(speculator, "model", None):
|
||||
reset_compile_wrapper(draft_model)
|
||||
|
||||
gc.collect()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
@@ -120,8 +120,8 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
P2POp(
|
||||
torch.distributed.isend,
|
||||
tensor,
|
||||
dst_rank,
|
||||
self._ep_group,
|
||||
group=self._ep_group,
|
||||
group_peer=dst_rank,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -136,8 +136,8 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
P2POp(
|
||||
torch.distributed.irecv,
|
||||
tensor,
|
||||
src_rank,
|
||||
self._ep_group,
|
||||
group=self._ep_group,
|
||||
group_peer=src_rank,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -199,8 +199,8 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
P2POp(
|
||||
torch.distributed.isend,
|
||||
cpu_tensor,
|
||||
peer_rank,
|
||||
self._cpu_group,
|
||||
group=self._cpu_group,
|
||||
group_peer=peer_rank,
|
||||
)
|
||||
)
|
||||
continue
|
||||
@@ -211,8 +211,8 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
P2POp(
|
||||
torch.distributed.irecv,
|
||||
cpu_tensor,
|
||||
peer_rank,
|
||||
self._cpu_group,
|
||||
group=self._cpu_group,
|
||||
group_peer=peer_rank,
|
||||
)
|
||||
)
|
||||
recv_staging.append((tensor, cpu_tensor))
|
||||
|
||||
@@ -256,8 +256,6 @@ def kv_postprocess_blksize_on_receive(cache, indices, block_size_ratio):
|
||||
|
||||
"""
|
||||
blocks_to_update = cache.index_select(0, indices)
|
||||
# use physical order
|
||||
blocks_to_update = blocks_to_update.permute(0, 2, 1, 3)
|
||||
n_kv_heads, block_size, head_size = blocks_to_update.shape[1:]
|
||||
remote_block_size = block_size // block_size_ratio
|
||||
n_blocks = block_size_ratio
|
||||
@@ -267,56 +265,28 @@ def kv_postprocess_blksize_on_receive(cache, indices, block_size_ratio):
|
||||
.permute(0, 2, 1, 3, 4)
|
||||
.flatten(2, 3)
|
||||
)
|
||||
permuted_blocks = permuted_blocks.permute(0, 2, 1, 3)
|
||||
cache.index_copy_(0, indices, permuted_blocks)
|
||||
|
||||
|
||||
def kv_postprocess_layout_on_receive(cache, indices):
|
||||
"""Transforms the layout of received KV cache blocks to the local format.
|
||||
|
||||
This method corrects layout mismatches from direct memory copies by
|
||||
permuting the tensor dimensions.
|
||||
|
||||
4D cache:
|
||||
- **Source Layout:** `[num_blocks, n_kv_head, block_size, head_dim]`
|
||||
- **Target Layout:** `[num_blocks, block_size, n_kv_head, head_dim]`
|
||||
5D cache:
|
||||
- **Source Layout:** `[num_blocks, kv_dim, n_kv_head, block_size, head_dim]`
|
||||
- **Target Layout:** `[num_blocks, kv_dim, block_size, n_kv_head, head_dim]`
|
||||
|
||||
Implementation:
|
||||
- x = blocks_to_update.reshape(src_shape) # view local kv with sender layout
|
||||
- permuted_blocks = x.permute(*inv_order) # transpose n_kv_heads, block_size
|
||||
- cache.index_copy_(0, indices, permuted_blocks) # copy permuted kv back
|
||||
|
||||
"""
|
||||
blocks_to_update = cache.index_select(0, indices)
|
||||
target_shape = list(blocks_to_update.shape)
|
||||
target_shape[0] = -1
|
||||
inv_order = [0, 1, 3, 2, 4] if blocks_to_update.ndim == 5 else [0, 2, 1, 3]
|
||||
src_shape = tuple(target_shape[i] for i in inv_order)
|
||||
blocks_to_update = cache.index_select(0, indices)
|
||||
permuted_blocks = blocks_to_update.reshape(src_shape).permute(*inv_order)
|
||||
cache.index_copy_(0, indices, permuted_blocks)
|
||||
|
||||
|
||||
def kv_postprocess_blksize_and_layout_on_receive(cache, indices, block_size_ratio):
|
||||
"""Transforms the layout of received KV cache to the local block_size and LBHNC.
|
||||
(Only works for local blocksize > remote blocksize)
|
||||
(Only works for local blocksize >= remote blocksize)
|
||||
|
||||
prefill is LBHNC, smaller block_size
|
||||
decode(local) is LBNHC, larger block_size
|
||||
"""
|
||||
blocks_to_update = cache.index_select(0, indices)
|
||||
|
||||
block_size, n_kv_heads, head_size = blocks_to_update.shape[1:]
|
||||
n_kv_heads, block_size, head_size = blocks_to_update.shape[1:]
|
||||
remote_block_size = block_size // block_size_ratio
|
||||
n_blocks = block_size_ratio
|
||||
|
||||
# View the received bytes in memory order as the remote head-major blocks.
|
||||
permuted_blocks = (
|
||||
blocks_to_update.reshape(-1, n_blocks, n_kv_heads, remote_block_size, head_size)
|
||||
.permute(0, 1, 3, 2, 4)
|
||||
.flatten(1, 2)
|
||||
blocks_to_update.transpose(1, 2)
|
||||
.reshape(-1, n_blocks, n_kv_heads, remote_block_size, head_size)
|
||||
.permute(0, 2, 1, 3, 4)
|
||||
.flatten(2, 3)
|
||||
)
|
||||
cache.index_copy_(0, indices, permuted_blocks)
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -179,6 +180,10 @@ class KVConnectorWorkerMetadata(ABC):
|
||||
class KVConnectorBase_V1(ABC):
|
||||
"""Base class for KV connectors."""
|
||||
|
||||
# Source label for this connector's external hits. Subclasses must set
|
||||
# HOST/DISK/P2P or override get_external_cache_hit_sources().
|
||||
_cache_hit_source = CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
"""Whether external hits can complete divergent local hybrid hits.
|
||||
@@ -527,6 +532,24 @@ class KVConnectorBase_V1(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
"""Split ``num_external_tokens`` by the cache tier that supplied them.
|
||||
|
||||
Called after :meth:`update_state_after_alloc`, so the load plan is
|
||||
known. Counts must sum to ``num_external_tokens``; a mismatch is
|
||||
reported as ``external_unspecified``. Only non-zero counts are
|
||||
included.
|
||||
|
||||
Default: all tokens under ``_cache_hit_source``.
|
||||
"""
|
||||
if num_external_tokens == 0:
|
||||
return {}
|
||||
return {self._cache_hit_source: num_external_tokens}
|
||||
|
||||
@abstractmethod
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
@@ -560,7 +583,11 @@ class KVConnectorBase_V1(ABC):
|
||||
"""Build the connector metadata for this step.
|
||||
|
||||
This function should NOT modify fields in the scheduler_output.
|
||||
Also, calling this function will reset the state of the connector.
|
||||
FIXME: one exception:
|
||||
synchronous READ connectors may remove attention blocks they fully
|
||||
overwrite this step from new_block_ids_to_zero. They must complete
|
||||
those loads before the blocks are used and fail the step if a load fails.
|
||||
Calling this function will reset the state of the connector.
|
||||
|
||||
Args:
|
||||
scheduler_output (SchedulerOutput): the scheduler output object.
|
||||
|
||||
@@ -30,10 +30,12 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
PromMetric,
|
||||
PromMetricT,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
|
||||
from vllm.v1.hisparse.layout import get_hisparse_steady_state_concurrency
|
||||
from vllm.v1.hisparse.types import SparseKVOffloadCommand, SparseKVRowMirror
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
@@ -44,6 +46,8 @@ if TYPE_CHECKING:
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.request import Request
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class HiSparseConnectorMetadata(KVConnectorMetadata):
|
||||
@@ -99,6 +103,17 @@ class HiSparseConnectorScheduler:
|
||||
assert self.coordinator is None
|
||||
self.coordinator = coordinator
|
||||
|
||||
def get_kv_connector_stats(self) -> HiSparseKVConnectorStats | None:
|
||||
if self.coordinator is None:
|
||||
return None
|
||||
host_pool = self.coordinator.get_host_block_pool()
|
||||
assert host_pool is not None
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_host_usage(
|
||||
host_pool.get_usage(), len(self.coordinator.pending_spills)
|
||||
)
|
||||
return stats
|
||||
|
||||
def build_connector_meta(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> HiSparseConnectorMetadata:
|
||||
@@ -223,6 +238,16 @@ class HiSparseConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
),
|
||||
draft_kv_lookahead=vllm_config.num_lookahead_tokens,
|
||||
)
|
||||
max_model_len = vllm_config.model_config.max_model_len
|
||||
steady_concurrency = get_hisparse_steady_state_concurrency(
|
||||
vllm_config, kv_cache_config
|
||||
)
|
||||
logger.info_once(
|
||||
"HiSparse steady-state maximum concurrency for %s tokens per "
|
||||
"request: %.2fx (running requests reading from host).",
|
||||
f"{max_model_len:,}",
|
||||
steady_concurrency,
|
||||
)
|
||||
elif role == KVConnectorRole.WORKER:
|
||||
self.connector_worker = HiSparseConnectorWorker(
|
||||
vllm_config, kv_cache_config
|
||||
@@ -263,9 +288,11 @@ class HiSparseConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
self.connector_worker.reset_hot_state()
|
||||
|
||||
def get_kv_connector_stats(self) -> KVConnectorStats | None:
|
||||
if self.connector_worker is None:
|
||||
return None
|
||||
return self.connector_worker.get_kv_connector_stats()
|
||||
if self.connector_worker is not None:
|
||||
return self.connector_worker.get_kv_connector_stats()
|
||||
if self.connector_scheduler is not None:
|
||||
return self.connector_scheduler.get_kv_connector_stats()
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def build_kv_connector_stats(
|
||||
|
||||
@@ -14,14 +14,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
)
|
||||
from vllm.v1.metrics.utils import create_metric_per_engine
|
||||
|
||||
_HISPARSE_COUNTERS: tuple[tuple[str, str], ...] = (
|
||||
("cache_hits", "Number of HiSparse device hot-buffer hits."),
|
||||
("cache_misses", "Number of HiSparse device hot-buffer misses."),
|
||||
(
|
||||
"host_to_device_bytes",
|
||||
"Bytes transferred from host KV storage to HiSparse hot buffers.",
|
||||
),
|
||||
)
|
||||
_HISPARSE_LEVEL_KEYS = frozenset({"host_cache_usage_perc", "pending_page_transfers"})
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -30,6 +23,8 @@ class HiSparseKVConnectorStats(KVConnectorStats):
|
||||
|
||||
Each list entry is the delta recorded over one device counter snapshot
|
||||
interval, so a list can hold multiple snapshots per logging interval.
|
||||
The host-tier gauges are level values, not deltas: aggregation keeps
|
||||
only the most recent observation.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
@@ -39,10 +34,12 @@ class HiSparseKVConnectorStats(KVConnectorStats):
|
||||
|
||||
def reset(self):
|
||||
# Must be serializable
|
||||
self.data: dict[str, list[int]] = {
|
||||
self.data: dict[str, list[int | float]] = {
|
||||
"cache_hits": [],
|
||||
"cache_misses": [],
|
||||
"host_to_device_bytes": [],
|
||||
"host_cache_usage_perc": [],
|
||||
"pending_page_transfers": [],
|
||||
}
|
||||
|
||||
def record_snapshot(self, hits: int, misses: int, host_to_device_bytes: int):
|
||||
@@ -50,21 +47,32 @@ class HiSparseKVConnectorStats(KVConnectorStats):
|
||||
self.data["cache_misses"].append(misses)
|
||||
self.data["host_to_device_bytes"].append(host_to_device_bytes)
|
||||
|
||||
def record_host_usage(self, usage: float, pending_page_transfers: int) -> None:
|
||||
self.data["host_cache_usage_perc"].append(usage)
|
||||
self.data["pending_page_transfers"].append(pending_page_transfers)
|
||||
|
||||
def aggregate(self, other: KVConnectorStats) -> KVConnectorStats:
|
||||
if not other.is_empty():
|
||||
for k, v in other.data.items():
|
||||
accumulator = self.data[k]
|
||||
assert isinstance(accumulator, list)
|
||||
accumulator.extend(v)
|
||||
if k in _HISPARSE_LEVEL_KEYS:
|
||||
accumulator.extend(v[-1:])
|
||||
else:
|
||||
accumulator.extend(v)
|
||||
return self
|
||||
|
||||
def reduce(self) -> dict[str, int | float]:
|
||||
# Compute compact representative stats suitable for CLI logging.
|
||||
return {
|
||||
reduced: dict[str, int | float] = {
|
||||
"HiSparse hot-buffer hits": sum(self.data["cache_hits"]),
|
||||
"HiSparse hot-buffer misses": sum(self.data["cache_misses"]),
|
||||
"HiSparse host-to-device bytes": sum(self.data["host_to_device_bytes"]),
|
||||
}
|
||||
if self.data["host_cache_usage_perc"]:
|
||||
usage = self.data["host_cache_usage_perc"][-1]
|
||||
reduced["HiSparse host KV cache usage %"] = round(100 * usage, 1)
|
||||
return reduced
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return all(len(values) == 0 for values in self.data.values())
|
||||
@@ -80,18 +88,66 @@ class HiSparsePromMetrics(KVConnectorPromMetrics):
|
||||
):
|
||||
super().__init__(vllm_config, metric_types, labelnames, per_engine_labelvalues)
|
||||
|
||||
self.hisparse_counters: dict[str, Any] = {}
|
||||
for name, documentation in _HISPARSE_COUNTERS:
|
||||
counter = self._counter_cls(
|
||||
name=f"vllm:hisparse_{name}",
|
||||
documentation=documentation,
|
||||
labelnames=labelnames,
|
||||
)
|
||||
self.hisparse_counters[name] = create_metric_per_engine(
|
||||
counter, self.per_engine_labelvalues
|
||||
)
|
||||
counter_cache_hits = self._counter_cls(
|
||||
name="vllm:hisparse_cache_hits",
|
||||
documentation="Number of HiSparse device hot-buffer hits.",
|
||||
labelnames=labelnames,
|
||||
)
|
||||
counter_cache_misses = self._counter_cls(
|
||||
name="vllm:hisparse_cache_misses",
|
||||
documentation="Number of HiSparse device hot-buffer misses.",
|
||||
labelnames=labelnames,
|
||||
)
|
||||
counter_host_to_device_bytes = self._counter_cls(
|
||||
name="vllm:hisparse_host_to_device_bytes",
|
||||
documentation=(
|
||||
"Bytes transferred from host KV storage to HiSparse hot buffers."
|
||||
),
|
||||
labelnames=labelnames,
|
||||
)
|
||||
self.hisparse_counters: dict[str, Any] = {
|
||||
"cache_hits": create_metric_per_engine(
|
||||
counter_cache_hits, self.per_engine_labelvalues
|
||||
),
|
||||
"cache_misses": create_metric_per_engine(
|
||||
counter_cache_misses, self.per_engine_labelvalues
|
||||
),
|
||||
"host_to_device_bytes": create_metric_per_engine(
|
||||
counter_host_to_device_bytes, self.per_engine_labelvalues
|
||||
),
|
||||
}
|
||||
|
||||
gauge_host_cache_usage = self._gauge_cls(
|
||||
name="vllm:hisparse_host_cache_usage_perc",
|
||||
documentation=(
|
||||
"HiSparse host KV-cache usage. 1 means 100 percent usage. "
|
||||
"Evictable cached blocks count as free."
|
||||
),
|
||||
multiprocess_mode="mostrecent",
|
||||
labelnames=labelnames,
|
||||
)
|
||||
gauge_pending_page_transfers = self._gauge_cls(
|
||||
name="vllm:hisparse_pending_page_transfers",
|
||||
documentation=(
|
||||
"HiSparse page transfers (write-backs and restores) not yet completed."
|
||||
),
|
||||
multiprocess_mode="mostrecent",
|
||||
labelnames=labelnames,
|
||||
)
|
||||
self.hisparse_gauges: dict[str, Any] = {
|
||||
"host_cache_usage_perc": create_metric_per_engine(
|
||||
gauge_host_cache_usage, self.per_engine_labelvalues
|
||||
),
|
||||
"pending_page_transfers": create_metric_per_engine(
|
||||
gauge_pending_page_transfers, self.per_engine_labelvalues
|
||||
),
|
||||
}
|
||||
|
||||
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
|
||||
for name, counter in self.hisparse_counters.items():
|
||||
for value in transfer_stats_data.get(name, []):
|
||||
counter[engine_idx].inc(value)
|
||||
for name, gauge in self.hisparse_gauges.items():
|
||||
values = transfer_stats_data.get(name, [])
|
||||
if values:
|
||||
gauge[engine_idx].set(values[-1])
|
||||
|
||||
@@ -417,7 +417,6 @@ class HiSparseConnectorWorker:
|
||||
self._clear_forward_mirror_state()
|
||||
for handle in self.cache_handles:
|
||||
handle.all_context_pages_resident = metadata.all_context_pages_resident
|
||||
handle.mirror_from_resident = True
|
||||
self._copy_host_blocks(metadata.host_block_copies, previous_host_write_event)
|
||||
transfers = (
|
||||
metadata.command.page_transfers if metadata.command is not None else []
|
||||
|
||||
@@ -67,6 +67,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
SlidingWindowMLASpec,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.request import RequestStatus
|
||||
from vllm.v1.worker.block_table import BlockTable
|
||||
from vllm.v1.worker.utils import select_common_block_size
|
||||
@@ -700,6 +701,8 @@ class MooncakeConnectorMetadata(KVConnectorMetadata):
|
||||
|
||||
|
||||
class MooncakeConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
@@ -894,6 +897,10 @@ class MooncakeConnectorScheduler:
|
||||
# GDN is represented as a MambaSpec in vLLM. This Mooncake MambaSpec
|
||||
# path is currently tested with GDN; Mamba2 is not validated yet.
|
||||
self._has_mamba = kv_cache_config.has_mamba_layers
|
||||
self._bounded_replay = any(
|
||||
g.kv_cache_spec.prefix_replay_tokens > 0
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
|
||||
# Requests that need to start recv/send.
|
||||
# New requests are added by update_state_after_alloc in
|
||||
@@ -938,8 +945,10 @@ class MooncakeConnectorScheduler:
|
||||
|
||||
def _get_remote_prefill_token_count(self, num_prompt_tokens: int) -> int:
|
||||
"""D-side only. Returns N-1 for Mamba models since the decoder
|
||||
always recomputes the last token and must start from h(N-1)."""
|
||||
if self._has_mamba and num_prompt_tokens > 1:
|
||||
always recomputes the last token and must start from h(N-1), and for
|
||||
DSV41 SWA bounded replay, whose window is not replayed after a P/D load
|
||||
and must be laid out for that token."""
|
||||
if (self._has_mamba or self._bounded_replay) and num_prompt_tokens > 1:
|
||||
return num_prompt_tokens - 1
|
||||
return num_prompt_tokens
|
||||
|
||||
@@ -955,6 +964,9 @@ class MooncakeConnectorScheduler:
|
||||
params is not None
|
||||
and not params.get("_p_side_truncated")
|
||||
and request.num_prompt_tokens > 1
|
||||
# A request that skips reading the prefix cache (prompt logprobs)
|
||||
# loads nothing on the decoder, which recomputes its whole prompt.
|
||||
and not request.get_skip_reading_prefix_cache()
|
||||
):
|
||||
if request.prompt_token_ids is not None:
|
||||
request.prompt_token_ids.pop()
|
||||
@@ -970,7 +982,11 @@ class MooncakeConnectorScheduler:
|
||||
|
||||
def on_new_request(self, request: "Request") -> None:
|
||||
params = request.kv_transfer_params
|
||||
if params is not None and params.get("do_remote_decode") and self._has_mamba:
|
||||
if (
|
||||
params is not None
|
||||
and params.get("do_remote_decode")
|
||||
and (self._has_mamba or self._bounded_replay)
|
||||
):
|
||||
self._truncate_mamba_request_for_prefill(request)
|
||||
|
||||
def get_num_new_matched_tokens(
|
||||
@@ -2422,9 +2438,30 @@ class MooncakeConnectorWorker:
|
||||
|
||||
async def _connect_to_prefiller_bootstrap(self, remote_bootstrap_addr: str):
|
||||
url = remote_bootstrap_addr + "/query"
|
||||
max_attempts = _BOOTSTRAP_MAX_ATTEMPTS
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url)
|
||||
async with httpx.AsyncClient(
|
||||
timeout=envs.VLLM_MOONCAKE_CONNECTOR_TIMEOUT
|
||||
) as client:
|
||||
retry_delay = 0.1
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
response = await client.get(url)
|
||||
break
|
||||
except httpx.RequestError as e:
|
||||
if attempt == max_attempts:
|
||||
raise
|
||||
logger.warning(
|
||||
"Bootstrap query to %s failed on attempt %d/%d "
|
||||
"(%s: %s); retrying in %.1f seconds",
|
||||
remote_bootstrap_addr,
|
||||
attempt,
|
||||
max_attempts,
|
||||
type(e).__name__,
|
||||
e,
|
||||
retry_delay,
|
||||
)
|
||||
await asyncio.sleep(retry_delay)
|
||||
response.raise_for_status()
|
||||
data: dict = response.json()
|
||||
for _, dp_entry in data.items():
|
||||
@@ -2439,8 +2476,9 @@ class MooncakeConnectorWorker:
|
||||
self._tp_size[remote_engine_id] = len(dp_entry["worker_addr"])
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"Failed to connect to bootstrap server %s: %s",
|
||||
"Failed to connect to bootstrap server %s (%s): %s",
|
||||
remote_bootstrap_addr,
|
||||
type(e).__name__,
|
||||
e,
|
||||
)
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
SlidingWindowSpec,
|
||||
is_full_attention_spec,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
@@ -222,6 +223,8 @@ def resolve_moriio_transfer_ack(
|
||||
|
||||
|
||||
class MoRIIOConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
# The READ path always transfers the recurrent-state slot, including
|
||||
@@ -578,12 +581,31 @@ class MoRIIOConnectorScheduler:
|
||||
else (0, self.block_size)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
]
|
||||
# add 1 to conservatively account for boundary overlap eg window isn't fully
|
||||
# aligned with blocks.
|
||||
# +1 conservatively covers window/block boundary overlap.
|
||||
self.blocks_per_sw = [
|
||||
cdiv(n_tokens, block_size) + 1 if n_tokens else 0
|
||||
for n_tokens, block_size in sw_sizes_tokens
|
||||
]
|
||||
# Per-group block size over transfer_groups (matching blocks_per_sw and
|
||||
# the connector's block payload), used to clamp each full-attention group
|
||||
# to its prompt length on the WRITE save path.
|
||||
self._group_block_sizes = [
|
||||
getattr(g.kv_cache_spec, "block_size", self.block_size)
|
||||
for g in kv_cache_config.transfer_groups
|
||||
]
|
||||
# The WRITE-mode prompt-block clamp only covers full-attention groups, so
|
||||
# MoRIIO + speculative decoding is not yet safe on sliding-window /
|
||||
# hybrid models. TODO: lift once SWA + spec is validated end-to-end.
|
||||
if (
|
||||
self.mode == MoRIIOMode.WRITE
|
||||
and vllm_config.speculative_config is not None
|
||||
and any(bps != 0 for bps in self.blocks_per_sw)
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"MoRIIO with speculative decoding is not yet supported for "
|
||||
"sliding-window / hybrid models: the prompt-block clamp is only "
|
||||
"validated for full-attention KV groups."
|
||||
)
|
||||
# In WRITE mode and chunked prefill, we perform the write after the last chunk.
|
||||
# Hence we need to track once we are in the last chunk. We do this by computing
|
||||
# len(block_ids[g]) * block_size[g] for a full attn group g, as hybrid groups
|
||||
@@ -747,6 +769,9 @@ class MoRIIOConnectorScheduler:
|
||||
num_prompt_tokens = request.num_prompt_tokens
|
||||
num_external_tokens = max(num_prompt_tokens - num_computed_tokens, 0)
|
||||
if self.mode == MoRIIOMode.WRITE:
|
||||
params = request.kv_transfer_params or {}
|
||||
if not params.get("do_remote_prefill"):
|
||||
return 0, False
|
||||
# MoriiO in write mode, no remote prefill. Hybrid models never get
|
||||
# here: register_kv_caches refuses WRITE mode for them, so there is
|
||||
# no recurrent-state accounting to do.
|
||||
@@ -1175,6 +1200,45 @@ class MoRIIOConnectorScheduler:
|
||||
|
||||
params["do_remote_prefill"] = False
|
||||
|
||||
def _clamp_to_prompt_blocks(self, req: "Request", block_ids: BlockIds) -> BlockIds:
|
||||
"""Drop trailing speculative-lookahead blocks the consumer never
|
||||
allocated, keeping each full-attention group's prompt blocks.
|
||||
|
||||
Args:
|
||||
req: Request being saved.
|
||||
block_ids: Per-KV-cache-group local block ids.
|
||||
|
||||
Returns:
|
||||
``block_ids`` with every full-attention group truncated to
|
||||
``ceil(num_prompt_tokens / block_size)`` leading blocks;
|
||||
sliding-window groups are left unchanged.
|
||||
|
||||
"""
|
||||
clamped = list(block_ids)
|
||||
changed = False
|
||||
for g, group_blocks in enumerate(block_ids):
|
||||
if self.blocks_per_sw[g] != 0:
|
||||
continue
|
||||
num_prompt_blocks = math.ceil(
|
||||
req.num_prompt_tokens / self._group_block_sizes[g]
|
||||
)
|
||||
if len(group_blocks) > num_prompt_blocks:
|
||||
clamped[g] = group_blocks[:num_prompt_blocks]
|
||||
changed = True
|
||||
return clamped if changed else block_ids
|
||||
|
||||
def _is_final_prefill_chunk(
|
||||
self, req: "Request", scheduler_output: SchedulerOutput
|
||||
) -> bool:
|
||||
"""Whether this step completes the prompt.
|
||||
|
||||
``build_connector_meta`` runs before ``_update_after_schedule``, so
|
||||
``num_computed_tokens`` excludes the current chunk; add this step's
|
||||
scheduled tokens. Token progress is lookahead-safe unlike block counts.
|
||||
"""
|
||||
num_scheduled = scheduler_output.num_scheduled_tokens.get(req.request_id, 0)
|
||||
return req.num_computed_tokens + num_scheduled >= req.num_prompt_tokens
|
||||
|
||||
def build_connector_meta(
|
||||
self,
|
||||
scheduler_output: SchedulerOutput,
|
||||
@@ -1188,38 +1252,36 @@ class MoRIIOConnectorScheduler:
|
||||
# It places the request metadata into the saving queue.
|
||||
|
||||
for i, req_id in enumerate(scheduler_output.scheduled_cached_reqs.req_ids):
|
||||
# Non-disagg requests aren't registered here; skip them
|
||||
# instead of KeyError-ing.
|
||||
if req_id not in self._reqs_need_pending_save:
|
||||
continue
|
||||
req, existing_blocks = self._reqs_need_pending_save[req_id]
|
||||
# The final chunk may allocate no new blocks (the previous chunk
|
||||
# reserved speculative-lookahead slack), so new_block_ids is None;
|
||||
# still fall through to the final-chunk check below.
|
||||
new_block_ids = scheduler_output.scheduled_cached_reqs.new_block_ids[i]
|
||||
|
||||
if new_block_ids is not None:
|
||||
# A non-disagg request (no kv_transfer_params, e.g. smoke
|
||||
# test) is never registered in _reqs_need_pending_save;
|
||||
# indexing it unconditionally would KeyError and crash the
|
||||
# EngineCore. Skip it silently.
|
||||
if req_id not in self._reqs_need_pending_save:
|
||||
continue
|
||||
req, existing_blocks = self._reqs_need_pending_save[req_id]
|
||||
updated_blocks = [
|
||||
existing_blocks = [
|
||||
existing_blocks[g] + new_block_ids[g]
|
||||
for g in range(len(new_block_ids))
|
||||
]
|
||||
self._reqs_need_pending_save[req_id] = (req, updated_blocks)
|
||||
saved_tokens = (
|
||||
len(updated_blocks[self._full_attn_group_idx])
|
||||
* self._full_attn_block_size
|
||||
)
|
||||
if saved_tokens >= req.num_prompt_tokens:
|
||||
# Final chunk: live kv_transfer_params may be cleared,
|
||||
# so prefer the snapshot from update_state_after_alloc.
|
||||
kv_params = self._req_kv_params.pop(
|
||||
req_id, req.kv_transfer_params or {}
|
||||
)
|
||||
meta.add_new_req(
|
||||
request_id=req_id,
|
||||
local_block_ids=self._reqs_need_pending_save[req_id][1],
|
||||
kv_transfer_params=kv_params,
|
||||
write_mode=True,
|
||||
)
|
||||
del self._reqs_need_pending_save[req_id]
|
||||
self._reqs_need_pending_save[req_id] = (req, existing_blocks)
|
||||
if not self._is_final_prefill_chunk(req, scheduler_output):
|
||||
continue
|
||||
# Live kv_transfer_params may be cleared; prefer the
|
||||
# update_state_after_alloc snapshot.
|
||||
kv_params = self._req_kv_params.pop(
|
||||
req_id, req.kv_transfer_params or {}
|
||||
)
|
||||
save_block_ids = self._clamp_to_prompt_blocks(req, existing_blocks)
|
||||
meta.add_new_req(
|
||||
request_id=req_id,
|
||||
local_block_ids=save_block_ids,
|
||||
kv_transfer_params=kv_params,
|
||||
write_mode=True,
|
||||
)
|
||||
del self._reqs_need_pending_save[req_id]
|
||||
|
||||
# Loop through scheduled reqs and convert to ReqMeta.
|
||||
for req_id, (req, block_ids) in self._reqs_need_recv.items():
|
||||
@@ -1229,19 +1291,34 @@ class MoRIIOConnectorScheduler:
|
||||
local_block_ids=block_ids,
|
||||
kv_transfer_params=kv_params,
|
||||
)
|
||||
if (
|
||||
self.mode == MoRIIOMode.READ
|
||||
and self._has_mamba
|
||||
and scheduler_output.new_block_ids_to_zero
|
||||
):
|
||||
# Hybrid models zero recycled attention pages that held Mamba state.
|
||||
# Host-submitted READs overwrite these pages and can race zeroing.
|
||||
# Hybrid READ metadata puts the aligned attention pages first.
|
||||
read_dst_block_ids = {
|
||||
b
|
||||
for _, block_ids in self._reqs_need_recv.values()
|
||||
for b in block_ids[0]
|
||||
}
|
||||
scheduler_output.new_block_ids_to_zero = [
|
||||
b
|
||||
for b in scheduler_output.new_block_ids_to_zero
|
||||
if b not in read_dst_block_ids
|
||||
]
|
||||
|
||||
for req_id, (req, block_ids) in self._reqs_need_save.items():
|
||||
kv_params = self._req_kv_params.get(req_id, req.kv_transfer_params or {})
|
||||
tokens_covered = (
|
||||
len(block_ids[self._full_attn_group_idx]) * self._full_attn_block_size
|
||||
)
|
||||
if req.num_prompt_tokens > tokens_covered:
|
||||
# not last chunk prefill
|
||||
if not self._is_final_prefill_chunk(req, scheduler_output):
|
||||
self._reqs_need_pending_save[req_id] = (req, block_ids)
|
||||
continue
|
||||
save_block_ids = self._clamp_to_prompt_blocks(req, block_ids)
|
||||
meta.add_new_req(
|
||||
request_id=req_id,
|
||||
local_block_ids=block_ids,
|
||||
local_block_ids=save_block_ids,
|
||||
kv_transfer_params=kv_params,
|
||||
write_mode=True,
|
||||
)
|
||||
|
||||
@@ -377,10 +377,8 @@ def iter_layer_registration_regions(
|
||||
)
|
||||
region_len = geometry.num_blocks * geometry.regions_per_block * geometry.block_len
|
||||
if geometry.regions_per_block == 1:
|
||||
# With padded or interleaved pages the block stride exceeds the
|
||||
# meaningful block_len; register the strided span. The span ends with
|
||||
# the last block's meaningful bytes, not a whole stride, so it never
|
||||
# runs past the backing allocation of a strided layer view.
|
||||
# Padded/interleaved pages stride past block_len: register the strided
|
||||
# span, ending at the last block's bytes so it stays in-allocation.
|
||||
block_stride_bytes = geometry.block_stride * kv_cache.element_size()
|
||||
region_len = max(
|
||||
region_len,
|
||||
@@ -431,12 +429,8 @@ def compute_block_transfer_offsets(
|
||||
[list[int], list[int], list[int]], tuple[list[int], list[int], list[int]]
|
||||
] = merge_contiguous_offsets,
|
||||
) -> tuple[list[int], list[int], list[int]]:
|
||||
# A shorter (or empty) local list is the READ-mode "drop the transfer, just
|
||||
# free the prefill blocks" case (full-prefix-hit / aborted-before-scheduled):
|
||||
# decode pulls fewer blocks than the prefill holds. The zip loop below pairs
|
||||
# local[i]<->remote[i] and sizes by len(local), so a short local transfers
|
||||
# only what decode allocated and an empty local is a no-op. A longer local
|
||||
# list is a genuine bug and still fails loudly.
|
||||
# A shorter/empty local list transfers only what decode allocated (READ-mode
|
||||
# partial or full-prefix-hit); a longer local list is a genuine bug.
|
||||
if len(local_block_ids) > len(remote_block_ids):
|
||||
raise ValueError(
|
||||
"local_block_ids longer than remote_block_ids: "
|
||||
|
||||
@@ -31,6 +31,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -451,6 +452,18 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
to_return = (toks, load_async)
|
||||
return to_return
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
chosen_connector = self._requests_to_connector.get(request.request_id)
|
||||
if chosen_connector is None:
|
||||
return super().get_external_cache_hit_sources(request, num_external_tokens)
|
||||
return self._connectors[chosen_connector].get_external_cache_hit_sources(
|
||||
request, num_external_tokens
|
||||
)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
):
|
||||
|
||||
@@ -101,6 +101,10 @@ class NixlBaseConnectorScheduler:
|
||||
)
|
||||
)
|
||||
self._has_mamba = kv_cache_config.has_mamba_layers
|
||||
self._bounded_replay = any(
|
||||
g.kv_cache_spec.prefix_replay_tokens > 0
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
|
||||
logger.info("Initializing NIXL Scheduler %s", engine_id)
|
||||
if vllm_config.scheduler_config.disable_hybrid_kv_cache_manager:
|
||||
@@ -376,14 +380,16 @@ class NixlBaseConnectorScheduler:
|
||||
"""Trailing prompt tokens the prefiller must not compute; the decoder
|
||||
recomputes them locally.
|
||||
|
||||
Mamba needs h(N-1) so the decoder can derive h(N) itself. Multi-module
|
||||
Mamba needs h(N-1) so the decoder can derive h(N) itself. DSV41's sliding
|
||||
window under bounded replay is not replayed after a P/D load, so it must
|
||||
be laid out for the token the decoder recomputes. Multi-module
|
||||
MTP needs to keep its whole lookahead window off of the prefiller, which
|
||||
would otherwise embed the unverified drafts in the MTP layer's KV cache. The
|
||||
decoder would never rebuild them, because the update is sized by the rejection
|
||||
count, which is zero for the first decode.
|
||||
"""
|
||||
return max(
|
||||
1 if self._has_mamba else 0,
|
||||
1 if self._has_mamba or self._bounded_replay else 0,
|
||||
self.vllm_config.num_prefill_lookahead_tokens - 1,
|
||||
)
|
||||
|
||||
@@ -412,6 +418,9 @@ class NixlBaseConnectorScheduler:
|
||||
# Guard against repeated truncation after preemption/reschedule.
|
||||
and not params.get("_p_side_truncated")
|
||||
and request.num_prompt_tokens > backoff
|
||||
# A request that skips reading the prefix cache (prompt logprobs)
|
||||
# loads nothing on the decoder, which recomputes its whole prompt.
|
||||
and not request.get_skip_reading_prefix_cache()
|
||||
):
|
||||
if request.prompt_token_ids is not None:
|
||||
del request.prompt_token_ids[-backoff:]
|
||||
|
||||
@@ -14,7 +14,6 @@ import uuid
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import msgspec
|
||||
@@ -31,7 +30,6 @@ from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
get_current_attn_backends,
|
||||
kv_postprocess_blksize_and_layout_on_receive,
|
||||
kv_postprocess_blksize_on_receive,
|
||||
kv_postprocess_layout_on_receive,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
CopyBlocksOp,
|
||||
@@ -101,6 +99,11 @@ logger = init_logger(__name__)
|
||||
|
||||
_SHARED_REGION_GROUP_ID = -1
|
||||
|
||||
# Re-handshake delay bounds for a pull peer whose local metadata keeps getting
|
||||
# invalidated, eg due to a persistent RDMA fault.
|
||||
_INVALID_PEER_MIN_BACKOFF_S = 1.0
|
||||
_INVALID_PEER_MAX_BACKOFF_S = 60.0
|
||||
|
||||
|
||||
def _region_sort_key(layer_name: str) -> tuple[tuple[int, int | str], ...]:
|
||||
"""Sort transfer regions in model-layer order, then by cache name."""
|
||||
@@ -340,7 +343,7 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
|
||||
# Per-FA-descriptor replicate flag, in _build_fa_local emission order.
|
||||
fa_desc_replicated = self._fa_desc_replicated(num_fa_descs)
|
||||
fa_desc_replicated = self._fa_desc_replicated(num_fa_descs, block_size_ratio)
|
||||
sharded_desc_end = len(src_blocks_data) - (
|
||||
self._logical_num_blocks if self._ple_region_index is not None else 0
|
||||
)
|
||||
@@ -383,19 +386,22 @@ class NixlBaseConnectorWorker:
|
||||
"""
|
||||
return tp_ratio < 0 and (not self.use_mla or len(plan.all_source_ranks) > 1)
|
||||
|
||||
def _fa_desc_replicated(self, num_fa_descs: int) -> list[bool]:
|
||||
"""Per-FA-descriptor replicate flag, in _build_fa_local emission order
|
||||
(region-major; one desc per block, with K/V packed). Length ``num_fa_descs``.
|
||||
def _fa_desc_replicated(
|
||||
self, num_fa_descs: int, block_size_ratio: int = 1
|
||||
) -> list[bool]:
|
||||
"""Per-FA-descriptor replicate flag, in _build_fa_local emission order:
|
||||
region-major, ``region_num_blocks[i] * block_size_ratio`` descs per
|
||||
region. Length ``num_fa_descs``.
|
||||
"""
|
||||
assert self.transfer_topo is not None
|
||||
n_regions = len(self.block_len_per_layer)
|
||||
if n_regions == 0 or self.num_regions == 0:
|
||||
return [False] * num_fa_descs
|
||||
nblk = num_fa_descs // self.num_regions
|
||||
region_indices = self._transfer_layer_region_indices or range(n_regions)
|
||||
flags: list[bool] = []
|
||||
for i in range(n_regions):
|
||||
replicated = self._is_region_replicated(i)
|
||||
flags.extend([replicated] * nblk)
|
||||
for i in region_indices:
|
||||
num_descs = self.region_num_blocks[i] * block_size_ratio
|
||||
flags.extend([self._is_region_replicated(i)] * num_descs)
|
||||
assert len(flags) == num_fa_descs, (
|
||||
f"FA desc flags {len(flags)} != num_fa_descs {num_fa_descs}"
|
||||
)
|
||||
@@ -682,6 +688,12 @@ class NixlBaseConnectorWorker:
|
||||
self._remote_agents: dict[EngineId, dict[tuple[int, int], str]] = defaultdict(
|
||||
dict
|
||||
)
|
||||
# Failed reads need a local metadata probe; invalid peers wait for drain.
|
||||
self._failed_remote_engines: set[EngineId] = set()
|
||||
self._invalid_remote_engines: set[EngineId] = set()
|
||||
# Invalid engine -> (backoff, earliest release time). Kept across release
|
||||
# so that repeat invalidations back off.
|
||||
self._invalid_engine_backoff: dict[EngineId, tuple[float, float]] = {}
|
||||
# Map of engine_id -> clock offset.
|
||||
self._engine_clock_offset: dict[EngineId, float] = {}
|
||||
|
||||
@@ -775,9 +787,12 @@ class NixlBaseConnectorWorker:
|
||||
self.region_names: list[str] = []
|
||||
self.region_num_blocks: list[int] = []
|
||||
self._mixed_mem_types = False
|
||||
# True on TP ranks that share a HiSparse host pool with TP rank 0 and
|
||||
# leave its NIXL registration and DRAM reads to rank 0.
|
||||
self._skip_dram_xfer = False
|
||||
self._desc_is_dram_by_block_size: dict[int, np.ndarray] = {}
|
||||
self._desc_pos_by_block_size: dict[int, np.ndarray] = {}
|
||||
self._dram_src_handles_by_block_size: dict[int, int] = {}
|
||||
self._dram_src_handles_by_block_size: dict[int, int | None] = {}
|
||||
|
||||
# PP>1 (push mode): this worker holds a contiguous layer slice and
|
||||
# transfers into the matching sub-range of a PP=1 remote's regions.
|
||||
@@ -814,7 +829,7 @@ class NixlBaseConnectorWorker:
|
||||
# Populated dynamically during handshake based on remote configuration.
|
||||
# Per-source split handles, keyed by (tp_ratio, remote_block_size).
|
||||
self.src_xfer_handles_by_tp_ratio: dict[tuple[int, int], list[int]] = {}
|
||||
self._dram_src_handles_by_tp_ratio: dict[tuple[int, int], list[int]] = {}
|
||||
self._dram_src_handles_by_tp_ratio: dict[tuple[int, int], list[int | None]] = {}
|
||||
# Map of engine_id -> {tp_rank: nixl_prepped_dlist_handle (int)}.
|
||||
self.dst_xfer_side_handles = defaultdict[EngineId, dict[int, int]](dict)
|
||||
|
||||
@@ -918,6 +933,9 @@ class NixlBaseConnectorWorker:
|
||||
# page it overlays, so its regions cannot be recovered from spec type.
|
||||
self._scratch_region_indices = list[int]()
|
||||
self._ple_region_index: int | None = None
|
||||
# Page length of the PLE short-conv state; its region may be shared with
|
||||
# pages of a different (smaller) size, so it cannot use the region's.
|
||||
self._ple_block_len: int | None = None
|
||||
|
||||
# Enable different block lengths for different layers *only* when MLA is used.
|
||||
# This is not used for SSM layers, which use the counterpart `mamba_ssm_size`.
|
||||
@@ -1447,6 +1465,7 @@ class NixlBaseConnectorWorker:
|
||||
seen_base_addresses: list[int] = []
|
||||
self._ssm_region_indices = []
|
||||
self._scratch_region_indices = []
|
||||
self._ple_block_len = None
|
||||
self._ple_region_index = None
|
||||
|
||||
packed_storage = _share_storage_and_block_stride(list(xfer_buffers.values()))
|
||||
@@ -1734,6 +1753,7 @@ class NixlBaseConnectorWorker:
|
||||
assert self._is_csa_linear
|
||||
assert self._ple_region_index in (None, region_index)
|
||||
self._ple_region_index = region_index
|
||||
self._ple_block_len = block_len
|
||||
elif region_index not in self._ssm_region_indices:
|
||||
self._ssm_region_indices.append(region_index)
|
||||
elif (
|
||||
@@ -1804,12 +1824,15 @@ class NixlBaseConnectorWorker:
|
||||
self.num_descs = sum(xfer_region_num_blocks)
|
||||
|
||||
self._mixed_mem_types = len(set(region_mem_types)) > 1
|
||||
self._skip_dram_xfer = self._leaves_dram_xfer_to_rank0()
|
||||
if self._mixed_mem_types:
|
||||
assert self.use_mla and not self._has_mamba, (
|
||||
"Mixed-device KV registration is only supported for MLA "
|
||||
"models without Mamba layers."
|
||||
)
|
||||
for mem_type in sorted(set(region_mem_types)):
|
||||
if mem_type == "DRAM" and self._skip_dram_xfer:
|
||||
continue
|
||||
ranges_for_mem_type = [
|
||||
(start, end - start, device_id, "")
|
||||
for (_, cache_mem_type), (
|
||||
@@ -1865,6 +1888,7 @@ class NixlBaseConnectorWorker:
|
||||
else self.host_buffer_kv_cache_layout,
|
||||
block_size=self.block_size,
|
||||
ssm_sizes=self._mamba_ssm_size,
|
||||
ple_block_len=self._ple_block_len,
|
||||
attn_backend_name=self.backend_name,
|
||||
physical_blocks_per_logical_kv_block=(
|
||||
self._physical_blocks_per_logical_kv_block
|
||||
@@ -1886,6 +1910,19 @@ class NixlBaseConnectorWorker:
|
||||
agent_metadata_bytes=encoder.encode(agent_metadata),
|
||||
)
|
||||
|
||||
def _ple_page_len(self) -> int:
|
||||
"""Transfer length of one PLE state page.
|
||||
|
||||
The PLE page shares its region with the first page of other cache
|
||||
groups (block-outer layout), whose block_len may be smaller; the
|
||||
descriptors must cover the whole PLE page or part of the conv state
|
||||
never reaches the decode side."""
|
||||
assert self._ple_region_index is not None
|
||||
assert self._ple_block_len is not None, (
|
||||
"PLE region registered without its page length"
|
||||
)
|
||||
return self._ple_block_len
|
||||
|
||||
def _build_mamba_local(self, base_addresses: list[int]) -> np.ndarray:
|
||||
"""Build desc regions (conv sub-projections + ssm) per layer for
|
||||
local mamba blocks with DS conv layout, as an Nx3 uint64 array.
|
||||
@@ -1940,7 +1977,7 @@ class NixlBaseConnectorWorker:
|
||||
parts.append(self._stack_descs(blk_addrs + conv_size, ssm_size, device_id))
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
block_len = self.block_len_per_layer[region_index] * physical_per_logical
|
||||
block_len = self._ple_page_len() * physical_per_logical
|
||||
block_stride = (
|
||||
self.block_stride_per_layer[region_index] * physical_per_logical
|
||||
)
|
||||
@@ -1999,11 +2036,12 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
local_block_len = (
|
||||
self.block_len_per_layer[region_index]
|
||||
* self._physical_blocks_per_logical_kv_block
|
||||
self._ple_page_len() * self._physical_blocks_per_logical_kv_block
|
||||
)
|
||||
# Same NIXL_CONNECTOR_VERSION on both sides, so the field is set.
|
||||
assert nixl_agent_meta.ple_block_len is not None
|
||||
remote_block_len = (
|
||||
nixl_agent_meta.block_lens[region_index] * remote_physical_per_logical
|
||||
nixl_agent_meta.ple_block_len * remote_physical_per_logical
|
||||
)
|
||||
if local_block_len != remote_block_len:
|
||||
raise ValueError(
|
||||
@@ -2174,18 +2212,16 @@ class NixlBaseConnectorWorker:
|
||||
self._desc_pos_by_block_size[block_size] = desc_pos
|
||||
|
||||
# DRAM descriptors are registered under CPU device 0.
|
||||
blocks_data = [
|
||||
(addr, length, 0) if is_dram else (addr, length, dev)
|
||||
for (addr, length, dev), is_dram in zip(
|
||||
blocks_data, desc_is_dram, strict=True
|
||||
blocks_data[desc_is_dram, 2] = 0
|
||||
dram_blocks = blocks_data[dram_idx]
|
||||
vram_blocks = blocks_data[vram_idx]
|
||||
if self._skip_dram_xfer:
|
||||
self._dram_src_handles_by_block_size[block_size] = None
|
||||
else:
|
||||
dram_descs = self.nixl_wrapper.get_xfer_descs(dram_blocks, "DRAM")
|
||||
self._dram_src_handles_by_block_size[block_size] = (
|
||||
self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", dram_descs)
|
||||
)
|
||||
]
|
||||
dram_blocks = [blocks_data[i] for i in dram_idx]
|
||||
vram_blocks = [blocks_data[i] for i in vram_idx]
|
||||
dram_descs = self.nixl_wrapper.get_xfer_descs(dram_blocks, "DRAM")
|
||||
self._dram_src_handles_by_block_size[block_size] = (
|
||||
self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", dram_descs)
|
||||
)
|
||||
descs = self.nixl_wrapper.get_xfer_descs(vram_blocks, self.nixl_memory_type)
|
||||
return (
|
||||
self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", descs),
|
||||
@@ -2414,12 +2450,15 @@ class NixlBaseConnectorWorker:
|
||||
if self._mixed_mem_types:
|
||||
handle_data = np.asarray(handle_data, dtype=np.uint64)
|
||||
desc_is_dram = self._desc_is_dram_by_block_size[remote_block_size]
|
||||
dram_descs = self.nixl_wrapper.get_xfer_descs(
|
||||
handle_data[desc_is_dram], "DRAM"
|
||||
)
|
||||
dram_handle = self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT", dram_descs
|
||||
)
|
||||
if self._skip_dram_xfer:
|
||||
dram_handle = None
|
||||
else:
|
||||
dram_descs = self.nixl_wrapper.get_xfer_descs(
|
||||
handle_data[desc_is_dram], "DRAM"
|
||||
)
|
||||
dram_handle = self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT", dram_descs
|
||||
)
|
||||
self._dram_src_handles_by_tp_ratio[split_key].append(dram_handle)
|
||||
handle_data = handle_data[~desc_is_dram]
|
||||
descs = self.nixl_wrapper.get_xfer_descs(
|
||||
@@ -2555,6 +2594,7 @@ class NixlBaseConnectorWorker:
|
||||
if (
|
||||
self.kv_transfer_config.enable_permute_local_kv
|
||||
and nixl_agent_meta.kv_cache_layout == "LBHNC"
|
||||
and kv_cache_layout == "LBNHC"
|
||||
):
|
||||
logger.info(
|
||||
"Remote is LBHNC and local is LBNHC, enabled additional permute "
|
||||
@@ -2566,9 +2606,11 @@ class NixlBaseConnectorWorker:
|
||||
self.enable_permute_local_kv = True
|
||||
else:
|
||||
raise RuntimeError(
|
||||
"Heterogeneous TP expects same kv_cache_layout. "
|
||||
"Or enable experimental feature to use HND to NHD support by "
|
||||
"setting 'enable_permute_local_kv'=True in --kv-transfer-config."
|
||||
"Heterogeneous TP expects same kv_cache_layout (local "
|
||||
f"{kv_cache_layout}, remote {nixl_agent_meta.kv_cache_layout}). "
|
||||
"Or enable experimental feature to receive LBHNC into a local "
|
||||
"LBNHC cache by setting 'enable_permute_local_kv'=True "
|
||||
"in --kv-transfer-config."
|
||||
)
|
||||
# if remote_agent used attn is not same as local,
|
||||
# hint heterogenuous attn post process
|
||||
@@ -2754,26 +2796,10 @@ class NixlBaseConnectorWorker:
|
||||
"d2h",
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def _attention_kv_caches(self) -> list[torch.Tensor]:
|
||||
"""Device KV caches of attention layers (mamba states excluded),
|
||||
as consumed by the receive post-process."""
|
||||
assert self.device_kv_caches, (
|
||||
"_attention_kv_caches accessed before register_kv_caches"
|
||||
)
|
||||
mamba_layers = {
|
||||
name
|
||||
for g, group in enumerate(self.kv_cache_config.transfer_groups)
|
||||
if _is_ssm_spec(self._group_spec_types[g])
|
||||
for name in group.layer_names
|
||||
}
|
||||
kv_caches = self.device_kv_caches
|
||||
return [cache for name, cache in kv_caches.items() if name not in mamba_layers]
|
||||
|
||||
def post_process_device_kv_on_receive(
|
||||
self,
|
||||
block_size_ratio: int,
|
||||
block_ids_list: list[tuple[list[int], int]],
|
||||
block_ids_list: list[tuple[int, list[int], int]],
|
||||
convert: bool = True,
|
||||
):
|
||||
"""Post process device kv cache after receiving from remote.
|
||||
@@ -2822,9 +2848,11 @@ class NixlBaseConnectorWorker:
|
||||
block_size_ratio,
|
||||
)
|
||||
|
||||
attn_caches = self._attention_kv_caches
|
||||
device = attn_caches[0].device
|
||||
for block_ids, covered_sub_blocks in block_ids_list:
|
||||
for group, block_ids, covered_sub_blocks in block_ids_list:
|
||||
attn_caches = [
|
||||
self.device_kv_caches[name]
|
||||
for name in self.kv_cache_config.transfer_groups[group].layer_names
|
||||
]
|
||||
# Blocks the transfer didn't write: the token tail of the last
|
||||
# partially covered block, then everything beyond it.
|
||||
covered_blocks, sub_blocks_in_last = divmod(
|
||||
@@ -2834,17 +2862,16 @@ class NixlBaseConnectorWorker:
|
||||
has_stale = first_stale < len(block_ids)
|
||||
indices = None
|
||||
if convert or has_stale:
|
||||
indices = async_tensor_h2d(block_ids, device, torch.long)
|
||||
indices = async_tensor_h2d(block_ids, attn_caches[0].device, torch.long)
|
||||
|
||||
if convert:
|
||||
for cache in attn_caches:
|
||||
if self.enable_permute_local_kv and block_size_ratio > 1:
|
||||
if self.enable_permute_local_kv:
|
||||
kv_postprocess_blksize_and_layout_on_receive(
|
||||
cache, indices, block_size_ratio
|
||||
)
|
||||
elif self.enable_permute_local_kv:
|
||||
kv_postprocess_layout_on_receive(cache, indices)
|
||||
else:
|
||||
elif KVCacheLayout[self.kv_cache_layout].is_block_contiguous:
|
||||
# Token-major blocks get the sub-blocks in token order.
|
||||
kv_postprocess_blksize_on_receive(
|
||||
cache, indices, block_size_ratio
|
||||
)
|
||||
@@ -2852,10 +2879,10 @@ class NixlBaseConnectorWorker:
|
||||
if sub_blocks_in_last:
|
||||
last_block_id = block_ids[covered_blocks]
|
||||
for cache in attn_caches:
|
||||
# Both post-processed layouts leave tokens on dim 1.
|
||||
sub_block_tokens = cache.shape[1] // block_size_ratio
|
||||
# Attention caches are [B, H, N, C]: tokens on dim 2.
|
||||
sub_block_tokens = cache.shape[2] // block_size_ratio
|
||||
zero_from = sub_blocks_in_last * sub_block_tokens
|
||||
cache[last_block_id, zero_from:].zero_()
|
||||
cache[last_block_id, :, zero_from:].zero_()
|
||||
if has_stale:
|
||||
assert indices is not None
|
||||
stale_ids = indices[first_stale:]
|
||||
@@ -2878,6 +2905,27 @@ class NixlBaseConnectorWorker:
|
||||
indices=indices,
|
||||
)
|
||||
|
||||
def _leaves_dram_xfer_to_rank0(self) -> bool:
|
||||
"""Whether this rank leaves the DRAM regions' NIXL work to TP rank 0.
|
||||
|
||||
A HiSparse host pool shared by the local TP ranks (one mmap per DP
|
||||
rank) is registered with NIXL and filled by TP rank 0 alone: every
|
||||
rank would otherwise register the same pages on every NIC and READ the
|
||||
same host KV into them. Private pools are unaffected.
|
||||
"""
|
||||
if not (
|
||||
self._mixed_mem_types and self.kv_cache_config.hisparse_shared_host_pool
|
||||
):
|
||||
return False
|
||||
skip = self.tp_rank != 0
|
||||
logger.info(
|
||||
"HiSparse host pool: NIXL DRAM registration and reads on TP rank 0 "
|
||||
"only (tp_rank=%d, skip=%s)",
|
||||
self.tp_rank,
|
||||
skip,
|
||||
)
|
||||
return skip
|
||||
|
||||
def _zero_region_blocks(self, block_ids: BlockIds) -> None:
|
||||
"""Clear clipped physical pages in their owning region only."""
|
||||
if not any(block_ids):
|
||||
@@ -2886,6 +2934,9 @@ class NixlBaseConnectorWorker:
|
||||
for region, blocks in enumerate(block_ids):
|
||||
if not blocks:
|
||||
continue
|
||||
if self._skip_dram_xfer and self.region_mem_types[region] == "DRAM":
|
||||
# The shared pool is rank 0's to write.
|
||||
continue
|
||||
cache = self.device_kv_caches[self.region_names[region]]
|
||||
storage = cache.untyped_storage()
|
||||
pages = torch.empty(0, dtype=torch.uint8, device=cache.device).set_(
|
||||
@@ -3003,7 +3054,7 @@ class NixlBaseConnectorWorker:
|
||||
len(meta.remote.block_ids[g]),
|
||||
)
|
||||
block_ids_for_blocksize_post_process[block_size_ratio].append(
|
||||
(local_group, covered_sub_blocks)
|
||||
(g, local_group, covered_sub_blocks)
|
||||
)
|
||||
# post processing for heterogeneous attention
|
||||
if self.enable_heterogeneous_attn_post_process:
|
||||
@@ -3031,7 +3082,7 @@ class NixlBaseConnectorWorker:
|
||||
# Handle timeout to avoid stranding blocks on remote.
|
||||
self._reap_expired_send_leases(done_sending)
|
||||
|
||||
self._cleanup_replaced_remote_engines()
|
||||
self._cleanup_remote_engines()
|
||||
return KVConnectorTransferResults(
|
||||
finished_sending=done_sending,
|
||||
finished_recving=done_recving,
|
||||
@@ -3197,6 +3248,12 @@ class NixlBaseConnectorWorker:
|
||||
"""
|
||||
if record_failed_transfer:
|
||||
self.xfer_stats.record_failed_transfer()
|
||||
if (
|
||||
self._TRANSFER_MODE == "pull"
|
||||
and (meta := self._recving_metadata.get(req_id)) is not None
|
||||
and meta.remote is not None
|
||||
):
|
||||
self._failed_remote_engines.add(meta.remote.engine_id)
|
||||
if failed_req_ids is not None:
|
||||
failed_req_ids.add(req_id)
|
||||
return handle is None or self._try_release_xfer_handle(req_id, handle)
|
||||
@@ -3236,6 +3293,9 @@ class NixlBaseConnectorWorker:
|
||||
):
|
||||
continue # handshake is still pending
|
||||
|
||||
# Refresh the TTL: a heartbeat means the router still paired this P-D,
|
||||
# so requests are still waiting on this engine
|
||||
self._engine_last_active[engine_id] = time.perf_counter()
|
||||
# Build the heartbeat message: "HB:req1,req2,..."
|
||||
hb_msg = ("HB:" + ",".join(hb_info.req_ids)).encode()
|
||||
for agent_name in self._remote_agents[engine_id].values():
|
||||
@@ -3586,10 +3646,13 @@ class NixlBaseConnectorWorker:
|
||||
prevents us from using background threads, though memory usage is not guaranteed
|
||||
to be "optimal" until a new handshake is performed.
|
||||
|
||||
Engines with active transfers or pending handshakes cannot be stale:
|
||||
Engines with active transfers, heartbeats or pending handshakes cannot
|
||||
be stale:
|
||||
- Reads stamp _engine_last_active when they are issued, and engines a
|
||||
transfer is still reading from are held back explicitly, since the
|
||||
stamp is not refreshed while the read runs.
|
||||
- Heartbeats stamp it too, so an engine stays registered while this
|
||||
instance holds requests waiting on it.
|
||||
- Pending handshakes don't have an _engine_last_active entry yet
|
||||
"""
|
||||
# NOTE (NickLucche): This does NOT currently prevent OOMing if a huge number
|
||||
@@ -3638,15 +3701,38 @@ class NixlBaseConnectorWorker:
|
||||
engine_id,
|
||||
)
|
||||
|
||||
def _cleanup_replaced_remote_engines(self) -> None:
|
||||
"""Release replaced pull peers once requests and handshakes have drained."""
|
||||
def _cleanup_remote_engines(self) -> None:
|
||||
"""Release replaced or locally invalid pull peers after their reads drain."""
|
||||
# TODO: Also handle push mode, which handshakes in both directions.
|
||||
if self._TRANSFER_MODE != "pull":
|
||||
return
|
||||
# A background handshake may be loading native metadata with the GIL
|
||||
# released. Defer both probing and cleanup until it has finished.
|
||||
with self._handshake_lock:
|
||||
if self._handshake_futures:
|
||||
return
|
||||
replaced = self._remote_agents.keys() - self._engine_by_address.values()
|
||||
if not replaced:
|
||||
now = time.perf_counter()
|
||||
for engine_id in self._failed_remote_engines - self._invalid_remote_engines:
|
||||
agents = self._remote_agents.get(engine_id, {}).values()
|
||||
try:
|
||||
# No descriptors: query local existence, not peer health.
|
||||
if not all(map(self.nixl_wrapper.check_remote_metadata, agents)):
|
||||
self._mark_remote_engine_invalid(engine_id, now)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Could not check local NIXL metadata for engine %s.",
|
||||
engine_id,
|
||||
exc_info=True,
|
||||
)
|
||||
self._failed_remote_engines.clear()
|
||||
# Invalid peers keep rejecting new reads until their backoff has elapsed.
|
||||
invalid = {
|
||||
engine_id
|
||||
for engine_id in self._invalid_remote_engines
|
||||
if self._invalid_engine_backoff.get(engine_id, (0.0, 0.0))[1] <= now
|
||||
}
|
||||
if not replaced and not invalid:
|
||||
return
|
||||
# _recving_metadata is only accessed from this (main) thread.
|
||||
busy = {
|
||||
@@ -3654,9 +3740,42 @@ class NixlBaseConnectorWorker:
|
||||
for meta in self._recving_metadata.values()
|
||||
if meta.remote is not None
|
||||
}
|
||||
for engine_id in replaced - busy:
|
||||
# Replaced peers can still serve queued requests. Invalid peers reject
|
||||
# new reads, but must retain descriptors until outstanding handles end.
|
||||
invalid -= self._engines_with_inflight_transfers()
|
||||
for engine_id in (replaced - busy) | invalid:
|
||||
self._cleanup_remote_engine(engine_id, log_eviction=False)
|
||||
logger.info("Released NIXL state for replaced remote engine %s.", engine_id)
|
||||
logger.info(
|
||||
"Released NIXL state for replaced or locally invalid remote engine %s.",
|
||||
engine_id,
|
||||
)
|
||||
|
||||
def _mark_remote_engine_invalid(self, engine_id: EngineId, now: float) -> None:
|
||||
"""Schedule release of an engine whose local NIXL metadata is gone.
|
||||
|
||||
The first invalidation is released as soon as reads drain. Repeats
|
||||
before the peer has stayed healthy for the max backoff double the
|
||||
delay, during which reads fail fast instead of re-handshaking.
|
||||
"""
|
||||
# Forget engines that have stayed healthy long enough.
|
||||
for eid, (_, release_at) in list(self._invalid_engine_backoff.items()):
|
||||
if now - release_at > _INVALID_PEER_MAX_BACKOFF_S:
|
||||
del self._invalid_engine_backoff[eid]
|
||||
prev = self._invalid_engine_backoff.get(engine_id)
|
||||
backoff = 0.0
|
||||
if prev is not None:
|
||||
backoff = min(
|
||||
max(2 * prev[0], _INVALID_PEER_MIN_BACKOFF_S),
|
||||
_INVALID_PEER_MAX_BACKOFF_S,
|
||||
)
|
||||
self._invalid_engine_backoff[engine_id] = (backoff, now + backoff)
|
||||
self._invalid_remote_engines.add(engine_id)
|
||||
logger.warning(
|
||||
"Local NIXL metadata for remote engine %s was invalidated; "
|
||||
"re-handshaking after reads drain%s.",
|
||||
engine_id,
|
||||
f" and a {backoff:.0f}s backoff" if backoff else "",
|
||||
)
|
||||
|
||||
def _cleanup_remote_engine(
|
||||
self, engine_id: EngineId, *, log_eviction: bool = True
|
||||
@@ -3664,8 +3783,8 @@ class NixlBaseConnectorWorker:
|
||||
"""Remove all state for a single remote engine.
|
||||
|
||||
Releases NIXL resources (dlist handles, remote agents) and clears
|
||||
all per-engine data structures. Used by TTL eviction, replaced peer
|
||||
cleanup and shutdown.
|
||||
all per-engine data structures. Used by TTL eviction, replaced/invalid
|
||||
peer cleanup and shutdown.
|
||||
"""
|
||||
assert engine_id in self._remote_agents
|
||||
|
||||
@@ -3681,6 +3800,9 @@ class NixlBaseConnectorWorker:
|
||||
for agent_name in agents.values():
|
||||
self.nixl_wrapper.remove_remote_agent(agent_name)
|
||||
|
||||
self._failed_remote_engines.discard(engine_id)
|
||||
self._invalid_remote_engines.discard(engine_id)
|
||||
|
||||
self.kv_caches_base_addr.pop(engine_id, None)
|
||||
self.dst_num_blocks.pop(engine_id, None)
|
||||
self.dst_region_num_blocks.pop(engine_id, None)
|
||||
@@ -3715,11 +3837,13 @@ class NixlBaseConnectorWorker:
|
||||
for handles in self.src_xfer_handles_by_tp_ratio.values():
|
||||
for handle in handles:
|
||||
self.nixl_wrapper.release_dlist_handle(handle)
|
||||
for handles in self._dram_src_handles_by_tp_ratio.values():
|
||||
for handle in handles:
|
||||
self.nixl_wrapper.release_dlist_handle(handle)
|
||||
for handle in self._dram_src_handles_by_block_size.values():
|
||||
self.nixl_wrapper.release_dlist_handle(handle)
|
||||
for dram_handles in self._dram_src_handles_by_tp_ratio.values():
|
||||
for dram_handle in dram_handles:
|
||||
if dram_handle is not None:
|
||||
self.nixl_wrapper.release_dlist_handle(dram_handle)
|
||||
for dram_handle in self._dram_src_handles_by_block_size.values():
|
||||
if dram_handle is not None:
|
||||
self.nixl_wrapper.release_dlist_handle(dram_handle)
|
||||
except Exception:
|
||||
logger.exception("NIXL dlist-handle release failed at shutdown.")
|
||||
self.src_xfer_handles_by_block_size.clear()
|
||||
|
||||
@@ -58,6 +58,7 @@ from vllm.forward_context import ForwardContext
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -77,6 +78,8 @@ logger = init_logger(__name__)
|
||||
class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
"""Base connector with common logic shared by pull and push modes."""
|
||||
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
return True
|
||||
|
||||
@@ -49,8 +49,9 @@ PUSH_REG_NOTIF_PREFIX = b"PUSH_REG:"
|
||||
# 11: Add per-region transfer geometry and memory types to NixlAgentMetadata
|
||||
# 12: Add per-region member names for PP push
|
||||
# 13: Add packed-member layouts and order-independent packed-push backend hashes
|
||||
# 14: Add Qwen3.8-Flash-Next PLE page length - #59997
|
||||
#
|
||||
NIXL_CONNECTOR_VERSION: int = 13
|
||||
NIXL_CONNECTOR_VERSION: int = 14
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -73,6 +74,8 @@ class NixlAgentMetadata:
|
||||
region_mem_types: list[str] | None = None
|
||||
dcp_size: int = 1
|
||||
pcp_size: int = 1
|
||||
# Page length of the PLE short-conv state (None when the model has none).
|
||||
ple_block_len: int | None = None
|
||||
# Layer names sharing each advertised region, in region order.
|
||||
region_members: list[list[str]] = field(default_factory=list)
|
||||
# Packed member -> (byte offset in its region's block, bytes per page).
|
||||
|
||||
@@ -72,26 +72,11 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
# Aborted cleanup requests have already been removed from the scheduler.
|
||||
if meta.awaiting_kvs or any(meta.local_block_ids):
|
||||
self._recving_metadata[req_id] = meta
|
||||
if remote_engine_id not in self._remote_agents:
|
||||
# Initiate handshake with remote engine to exchange metadata.
|
||||
with self._handshake_lock:
|
||||
if remote_engine_id not in self._remote_agents:
|
||||
self._background_nixl_handshake(req_id, remote_engine_id, meta)
|
||||
continue
|
||||
|
||||
# Handshake already completed, start async read xfer.
|
||||
self._read_blocks_for_req(req_id, meta)
|
||||
|
||||
# Start transfers for requests whose handshakes have now finished.
|
||||
while not self._ready_requests.empty():
|
||||
req_id, meta = self._ready_requests.get_nowait()
|
||||
assert meta.remote is not None
|
||||
if meta.remote.engine_id not in self._remote_agents:
|
||||
# The engine was released after its handshake completed, so
|
||||
# handshake again. This fails if the engine is gone.
|
||||
self._background_nixl_handshake(req_id, meta.remote.engine_id, meta)
|
||||
continue
|
||||
self._read_blocks_for_req(req_id, meta)
|
||||
self._read_blocks_for_req(*self._ready_requests.get_nowait())
|
||||
|
||||
if self.pcp_rank > 0 and not self.pcp_dcp_sharded:
|
||||
# Replicated-KV PCP: only PCP rank 0 serves the KV, so this rank
|
||||
@@ -151,6 +136,15 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
def _read_blocks_for_req(self, req_id: str, meta: ReqMeta):
|
||||
assert meta.remote is not None and self.transfer_topo is not None
|
||||
engine_id = meta.remote.engine_id
|
||||
if engine_id in self._invalid_remote_engines:
|
||||
self._handle_failed_transfer(
|
||||
req_id, None, self._recv_failures, record_failed_transfer=False
|
||||
)
|
||||
return
|
||||
if engine_id not in self._remote_agents:
|
||||
# Also re-handshakes queued requests that outlived invalid-peer cleanup.
|
||||
self._background_nixl_handshake(req_id, engine_id, meta)
|
||||
return
|
||||
# Update last activity from this remote. Mind that cleanup is done on main
|
||||
# thread (this one), so we don't race on this structure.
|
||||
self._engine_last_active[engine_id] = time.perf_counter()
|
||||
@@ -599,7 +593,16 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
remote_ids = np.asarray(remote_block_descs_ids)
|
||||
is_dram = desc_is_dram[local_ids]
|
||||
|
||||
assert local_dram_handle is not None
|
||||
if self._skip_dram_xfer:
|
||||
# TP rank 0 reads the DRAM (shared host pool) part for every
|
||||
# local rank; keep only the device part. Register the request
|
||||
# even if nothing is left, so it still completes and notifies.
|
||||
keep = ~is_dram
|
||||
local_ids = local_ids[keep]
|
||||
remote_ids = remote_ids[keep]
|
||||
is_dram = is_dram[keep]
|
||||
self._recving_transfers.setdefault(request_id, [])
|
||||
assert local_dram_handle is not None or not is_dram.any()
|
||||
reads = (
|
||||
(is_dram, local_dram_handle),
|
||||
(~is_dram, local_device_handle),
|
||||
|
||||
@@ -44,8 +44,10 @@ class NixlKVConnectorStats(KVConnectorStats):
|
||||
"num_notifications_after_expiry": [],
|
||||
}
|
||||
|
||||
def record_transfer(self, res: "nixlXferTelemetry"):
|
||||
def record_transfer(self, res: "nixlXferTelemetry | None"):
|
||||
# Keep metrics units consistent with rest of the code: time us->s
|
||||
if res is None:
|
||||
return
|
||||
self.data["transfer_duration"].append(res.xferDuration / 1e6)
|
||||
self.data["post_duration"].append(res.postDuration / 1e6)
|
||||
self.data["bytes_transferred"].append(res.totalBytes)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field, replace
|
||||
from itertools import chain, islice
|
||||
@@ -56,6 +57,7 @@ from vllm.v1.kv_offload.base import (
|
||||
TierMatcher,
|
||||
make_offload_key,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
@@ -375,6 +377,9 @@ class RequestOffloadState:
|
||||
# Fine-grained token boundary selected beyond the last complete offload
|
||||
# chunk. It is consumed when the corresponding load is scheduled.
|
||||
partial_tail_boundary: int | None = None
|
||||
# Loaded attention keys cover their token positions. Recurrent state
|
||||
# supports the whole reused external prefix.
|
||||
load_key_ranges: list[tuple[int, int, OffloadKey]] = field(default_factory=list)
|
||||
# True once on_request_finished has been signaled to the manager.
|
||||
finished_signaled: bool = False
|
||||
|
||||
@@ -587,8 +592,9 @@ class OffloadingConnectorScheduler:
|
||||
sliding_window_groups.sort(key=_sliding_window_sort_key, reverse=True)
|
||||
|
||||
# used by _lookup
|
||||
self._full_attention_groups: tuple[int, ...] = tuple(full_attention_groups)
|
||||
self._sliding_window_groups: tuple[int, ...] = tuple(sliding_window_groups)
|
||||
self._lookup_groups = tuple(full_attention_groups) + self._sliding_window_groups
|
||||
self._lookup_groups = self._full_attention_groups + self._sliding_window_groups
|
||||
self._mamba_align_size: int | None = resolve_mamba_align_size(
|
||||
spec, kv_cache_config
|
||||
)
|
||||
@@ -1090,6 +1096,53 @@ class OffloadingConnectorScheduler:
|
||||
|
||||
return num_hit_tokens, bool(num_hit_tokens)
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: Request,
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
"""Split the accepted external hit by the tier each loaded key came from.
|
||||
|
||||
Attention keys cover only their loaded token ranges; recurrent state
|
||||
covers the whole reused prefix. Overlaps report the outermost tier.
|
||||
Uncovered tokens, including omitted sliding-window history, are
|
||||
``external_unspecified``.
|
||||
"""
|
||||
sources: dict[CacheHitSource, int] = {}
|
||||
if num_external_tokens == 0:
|
||||
return sources
|
||||
req_status = self._req_status[request.request_id]
|
||||
start = req_status.num_locally_computed_tokens
|
||||
end = start + num_external_tokens
|
||||
|
||||
events: list[tuple[int, int, CacheHitSource]] = [
|
||||
(end, 0, CacheHitSource.EXTERNAL_UNSPECIFIED)
|
||||
]
|
||||
for lo, hi, key in req_status.load_key_ranges:
|
||||
lo, hi = max(start, lo), min(end, hi)
|
||||
if lo >= hi:
|
||||
continue
|
||||
source = CacheHitSource(
|
||||
self.manager.get_load_source(key, req_status.req_context)
|
||||
)
|
||||
events.extend(((lo, 1, source), (hi, -1, source)))
|
||||
|
||||
# Sweep endpoints instead of rescanning every range for each interval.
|
||||
active: Counter[CacheHitSource] = Counter()
|
||||
position = start
|
||||
for boundary, delta, source in sorted(events):
|
||||
if boundary > position:
|
||||
tiers = [tier for tier, count in active.items() if count > 0]
|
||||
tier = (
|
||||
CacheHitSource.outermost(tiers)
|
||||
if tiers
|
||||
else CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
)
|
||||
sources[tier] = sources.get(tier, 0) + boundary - position
|
||||
active[source] += delta
|
||||
position = boundary
|
||||
return sources
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: Request, blocks: KVCacheBlocks, num_external_tokens: int
|
||||
):
|
||||
@@ -1105,6 +1158,7 @@ class OffloadingConnectorScheduler:
|
||||
assert partial_tail_boundary == num_cached_tokens
|
||||
|
||||
keys_to_load: list[OffloadKey] = []
|
||||
req_status.load_key_ranges.clear()
|
||||
dst_block_ids: list[int] = []
|
||||
# per group
|
||||
group_sizes: list[int] = []
|
||||
@@ -1157,9 +1211,9 @@ class OffloadingConnectorScheduler:
|
||||
)
|
||||
end_chunk_idx = num_chunks - (partial_tail_boundary is not None)
|
||||
assert len(offload_keys) >= end_chunk_idx
|
||||
keys_to_load.extend(offload_keys[start_chunk_idx:end_chunk_idx])
|
||||
group_keys_to_load = offload_keys[start_chunk_idx:end_chunk_idx]
|
||||
if partial_tail_boundary is not None:
|
||||
keys_to_load.append(
|
||||
group_keys_to_load.append(
|
||||
self._make_boundary_key(
|
||||
request,
|
||||
group_config.group_idx,
|
||||
@@ -1167,6 +1221,24 @@ class OffloadingConnectorScheduler:
|
||||
req_status.req_context,
|
||||
)
|
||||
)
|
||||
keys_to_load.extend(group_keys_to_load)
|
||||
if isinstance(group_config.kv_cache_spec, MambaSpec):
|
||||
req_status.load_key_ranges.extend(
|
||||
(num_locally_computed_tokens, num_cached_tokens, key)
|
||||
for key in group_keys_to_load
|
||||
)
|
||||
else:
|
||||
for chunk_idx, key in enumerate(
|
||||
group_keys_to_load, start_chunk_idx
|
||||
):
|
||||
range_start = max(
|
||||
load_start_gpu_block_idx * tokens_per_block,
|
||||
chunk_idx * tokens_per_chunk,
|
||||
)
|
||||
range_end = min(
|
||||
num_cached_tokens, (chunk_idx + 1) * tokens_per_chunk
|
||||
)
|
||||
req_status.load_key_ranges.append((range_start, range_end, key))
|
||||
|
||||
dst_block_ids.extend(
|
||||
block.block_id
|
||||
|
||||
@@ -45,6 +45,7 @@ from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.kv_offload.factory import OffloadingSpecFactory
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import Request
|
||||
|
||||
@@ -179,6 +180,16 @@ class OffloadingConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
bound = min(per_group_hits[group_id] for group_id in self._bounding_group_ids)
|
||||
return max(0, bound - num_computed_tokens)
|
||||
|
||||
def get_external_cache_hit_sources(
|
||||
self,
|
||||
request: "Request",
|
||||
num_external_tokens: int,
|
||||
) -> dict[CacheHitSource, int]:
|
||||
assert self.connector_scheduler is not None
|
||||
return self.connector_scheduler.get_external_cache_hit_sources(
|
||||
request, num_external_tokens
|
||||
)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
|
||||
):
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.simple_kv_offload.manager import (
|
||||
BoundaryStoreStats,
|
||||
@@ -109,6 +110,9 @@ class SimpleCPUOffloadConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
f"expected one of {VALID_KV_OFFLOAD_BACKENDS}"
|
||||
)
|
||||
disk_mode = kv_offload_backend == "disk"
|
||||
self._cache_hit_source = (
|
||||
CacheHitSource.DISK if disk_mode else CacheHitSource.HOST
|
||||
)
|
||||
|
||||
disk_path = extra_config.get("disk_path", None) or None
|
||||
disk_capacity_bytes = int(
|
||||
|
||||
@@ -42,6 +42,7 @@ import torch.distributed
|
||||
import torch.distributed._functional_collectives as funcol
|
||||
import torch.distributed._symmetric_memory
|
||||
from torch.distributed import Backend, ProcessGroup, Store
|
||||
from torch.distributed.constants import default_pg_timeout
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.distributed.device_communicators.base_device_communicator import (
|
||||
@@ -49,6 +50,7 @@ from vllm.distributed.device_communicators.base_device_communicator import (
|
||||
)
|
||||
from vllm.distributed.utils import (
|
||||
StatelessProcessGroup,
|
||||
create_tcp_store,
|
||||
get_cached_tcp_store_client,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
@@ -801,6 +803,19 @@ class GroupCoordinator:
|
||||
raise ValueError("No device communicator found")
|
||||
return self.device_communicator.reduce_scatterv(input_, dim, sizes)
|
||||
|
||||
def reduce_scatterv_into_output(
|
||||
self,
|
||||
input_: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
dim: int = -1,
|
||||
sizes: list[int] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.device_communicator is None:
|
||||
raise ValueError("No device communicator found")
|
||||
return self.device_communicator.reduce_scatterv_into_output(
|
||||
input_, output, dim, sizes
|
||||
)
|
||||
|
||||
def _reduce_scatter_out_place(self, input_: torch.Tensor, dim: int) -> torch.Tensor:
|
||||
if self.device_communicator is None:
|
||||
raise ValueError("No device communicator found")
|
||||
@@ -1442,6 +1457,32 @@ class GroupCoordinator:
|
||||
else:
|
||||
return hidden_states
|
||||
|
||||
def allocate_combine_input(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor | None:
|
||||
if self.device_communicator is None:
|
||||
return None
|
||||
return self.device_communicator.allocate_combine_input(
|
||||
shape, dtype, device, is_sequence_parallel
|
||||
)
|
||||
|
||||
def combine_into_output(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
is_sequence_parallel: bool = False,
|
||||
) -> torch.Tensor:
|
||||
if self.device_communicator is None:
|
||||
output.copy_(hidden_states)
|
||||
return output
|
||||
return self.device_communicator.combine_into_output(
|
||||
hidden_states, output, is_sequence_parallel
|
||||
)
|
||||
|
||||
|
||||
_WORLD: GroupCoordinator | None = None
|
||||
_INNER_DP_WORLD: GroupCoordinator | None = None
|
||||
@@ -1790,6 +1831,7 @@ def init_distributed_environment(
|
||||
|
||||
config = get_current_vllm_config_or_none()
|
||||
enable_elastic_ep = config is not None and config.parallel_config.enable_elastic_ep
|
||||
world_pg_store: Store | None = None
|
||||
if (
|
||||
config is not None
|
||||
and config.parallel_config.distributed_executor_backend != "external_launcher"
|
||||
@@ -1813,7 +1855,46 @@ def init_distributed_environment(
|
||||
distributed_init_method = get_distributed_init_method(ip, port)
|
||||
else:
|
||||
ip = parallel_config.data_parallel_master_ip
|
||||
port = parallel_config.get_next_dp_init_port()
|
||||
if (
|
||||
parallel_config._coord_store_port
|
||||
and not torch.distributed.is_initialized()
|
||||
):
|
||||
# Group rank 0 lets the world-group TCPStore bind port 0
|
||||
# and publishes the kernel-assigned port via the
|
||||
# coordination store. A one-shot client of our own: the
|
||||
# cached one is inherited across fork and shared with
|
||||
# sibling workers.
|
||||
coord_store = create_tcp_store(
|
||||
ip,
|
||||
parallel_config._coord_store_port,
|
||||
is_master=False,
|
||||
wait_for_workers=False,
|
||||
)
|
||||
if rank == 0:
|
||||
# Workers can only connect once the port is published.
|
||||
world_pg_store = create_tcp_store(
|
||||
ip,
|
||||
0,
|
||||
world_size=world_size,
|
||||
is_master=True,
|
||||
wait_for_workers=False,
|
||||
timeout=timeout or default_pg_timeout,
|
||||
multi_tenant=True,
|
||||
)
|
||||
port = world_pg_store.port
|
||||
coord_store.set("world_pg_port", str(port).encode())
|
||||
else:
|
||||
port = int(coord_store.get("world_pg_port").decode())
|
||||
world_pg_store = create_tcp_store(
|
||||
ip,
|
||||
port,
|
||||
world_size=world_size,
|
||||
is_master=False,
|
||||
timeout=timeout or default_pg_timeout,
|
||||
multi_tenant=True,
|
||||
)
|
||||
else:
|
||||
port = parallel_config.get_next_dp_init_port()
|
||||
distributed_init_method = get_distributed_init_method(ip, port)
|
||||
logger.debug(
|
||||
"Adjusting world_size=%d rank=%d distributed_init_method=%s for DP",
|
||||
@@ -1843,8 +1924,8 @@ def init_distributed_environment(
|
||||
"Fallback Gloo backend is not available."
|
||||
)
|
||||
backend = "gloo"
|
||||
store = None
|
||||
if distributed_init_method.startswith("file://"):
|
||||
store = world_pg_store
|
||||
if store is None and distributed_init_method.startswith("file://"):
|
||||
store = torch.distributed.FileStore(
|
||||
distributed_init_method.removeprefix("file://"), world_size
|
||||
)
|
||||
|
||||
@@ -38,9 +38,7 @@ logger = init_logger(__name__)
|
||||
# We prefer to use os.sched_yield as it results in tighter polling loops,
|
||||
# measured to be around 3e-7 seconds. However on earlier versions of Python
|
||||
# os.sched_yield() does not release the GIL, so we fall back to time.sleep(0)
|
||||
USE_SCHED_YIELD = (sys.version_info[:3] >= (3, 11, 1)) or (
|
||||
sys.version_info[:2] == (3, 10) and sys.version_info[2] >= 8
|
||||
)
|
||||
USE_SCHED_YIELD = sys.version_info[:3] >= (3, 11, 1)
|
||||
|
||||
|
||||
def sched_yield():
|
||||
@@ -52,8 +50,8 @@ def sched_yield():
|
||||
|
||||
def ensure_divisibility(numerator, denominator):
|
||||
"""Ensure that numerator is divisible by the denominator."""
|
||||
assert numerator % denominator == 0, "{} is not divisible by {}".format(
|
||||
numerator, denominator
|
||||
assert numerator % denominator == 0, (
|
||||
f"{numerator} is not divisible by {denominator}"
|
||||
)
|
||||
|
||||
|
||||
@@ -146,9 +144,7 @@ def get_pp_indices(
|
||||
try:
|
||||
partitions = [int(layer) for layer in partition_list_str.split(",")]
|
||||
except ValueError as err:
|
||||
raise ValueError(
|
||||
"Invalid partition string: {}".format(partition_list_str)
|
||||
) from err
|
||||
raise ValueError(f"Invalid partition string: {partition_list_str}") from err
|
||||
if len(partitions) != pp_size:
|
||||
raise ValueError(f"{len(partitions)=} does not match {pp_size=}.")
|
||||
if sum(partitions) != num_hidden_layers:
|
||||
|
||||
@@ -11,12 +11,12 @@ from typing import (
|
||||
ClassVar,
|
||||
Generic,
|
||||
Protocol,
|
||||
Self,
|
||||
TypeVar,
|
||||
runtime_checkable,
|
||||
)
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
@@ -58,7 +58,7 @@ def _json_safe_update_payload(
|
||||
class HTTPVLLMWeightSyncClient:
|
||||
"""Talks to a vLLM server over the RLHF HTTP routes.
|
||||
|
||||
Mirrors `vllm/entrypoints/serve/dev/rlhf/api_router.py`:
|
||||
Mirrors `vllm/entrypoints/rl/online/api_router.py`:
|
||||
`/init_weight_transfer_engine`, `/start_weight_update`, `/update_weights`,
|
||||
`/finish_weight_update`.
|
||||
"""
|
||||
|
||||
@@ -4,12 +4,11 @@
|
||||
|
||||
import pickle
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Self
|
||||
|
||||
import pybase64 as base64
|
||||
import torch
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor, reduce_tensor
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config.weight_transfer import WeightTransferConfig
|
||||
|
||||
@@ -15,10 +15,9 @@ in every caller.
|
||||
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, Self, cast
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
TrainerInitInfo,
|
||||
|
||||
@@ -5,10 +5,9 @@
|
||||
from collections.abc import Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar, Self
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
@@ -24,7 +24,7 @@ import uuid
|
||||
from collections.abc import Callable, Collection
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, ClassVar
|
||||
from typing import Any, ClassVar, Self
|
||||
|
||||
import ray
|
||||
import torch
|
||||
@@ -33,7 +33,6 @@ from torch.multiprocessing.reductions import (
|
||||
rebuild_cuda_tensor,
|
||||
reduce_tensor,
|
||||
)
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
ParamMeta,
|
||||
|
||||
@@ -11,10 +11,9 @@ from collections.abc import Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar, Self
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
+43
-16
@@ -839,7 +839,9 @@ class EngineArgs:
|
||||
)
|
||||
|
||||
fail_on_environ_validation: bool = False
|
||||
gdn_prefill_backend: Literal["flashinfer", "triton", "cutedsl"] | None = None
|
||||
gdn_prefill_backend: (
|
||||
Literal["flashinfer", "triton", "cutedsl", "aiter_flydsl"] | None
|
||||
) = None
|
||||
kda_prefill_backend: (
|
||||
Literal["auto", "triton", "flashkda", "flashinfer", "fused"] | None
|
||||
) = None
|
||||
@@ -1890,7 +1892,7 @@ class EngineArgs:
|
||||
parser.add_argument(
|
||||
"--gdn-prefill-backend",
|
||||
dest="gdn_prefill_backend",
|
||||
choices=["flashinfer", "triton", "cutedsl"],
|
||||
choices=["flashinfer", "triton", "cutedsl", "aiter_flydsl"],
|
||||
default=None,
|
||||
help="Select GDN prefill backend.",
|
||||
)
|
||||
@@ -2111,7 +2113,7 @@ class EngineArgs:
|
||||
for x in cvd.split(",")
|
||||
]
|
||||
for i in int_ids:
|
||||
if i >= len(cvd_ids):
|
||||
if not 0 <= i < len(cvd_ids):
|
||||
raise ValueError(
|
||||
f"--device-ids index {i} is out of range for "
|
||||
f"{current_platform.device_control_env_var}"
|
||||
@@ -2136,6 +2138,25 @@ class EngineArgs:
|
||||
cfg = json.loads(cfg)
|
||||
return WatermarkConfig(**cfg)
|
||||
|
||||
def create_structured_outputs_config(self) -> StructuredOutputsConfig:
|
||||
"""Merge frontend parser flags into the structured outputs config.
|
||||
|
||||
Mutates `self.structured_outputs_config` in place and returns it
|
||||
(not a copy). Model-specific defaults (e.g. gpt_oss ->
|
||||
"openai_gptoss") are applied later by `verify_and_update_config`
|
||||
only when the resolved value is still empty, so explicit CLI flags
|
||||
take precedence.
|
||||
"""
|
||||
if self.reasoning_parser:
|
||||
self.structured_outputs_config.reasoning_parser = self.reasoning_parser
|
||||
|
||||
if self.reasoning_parser_plugin:
|
||||
self.structured_outputs_config.reasoning_parser_plugin = (
|
||||
self.reasoning_parser_plugin
|
||||
)
|
||||
|
||||
return self.structured_outputs_config
|
||||
|
||||
def create_observability_config(self) -> ObservabilityConfig:
|
||||
return ObservabilityConfig(
|
||||
show_hidden_metrics_for_version=self.show_hidden_metrics_for_version,
|
||||
@@ -2252,15 +2273,23 @@ class EngineArgs:
|
||||
kv_offloading_backend=self.kv_offloading_backend,
|
||||
)
|
||||
|
||||
if resolved_cache_dtype.startswith("turboquant_"):
|
||||
# TurboQuant and UltraQuant both keep boundary attention layers at the
|
||||
# native dtype, and compute those layers the same way.
|
||||
uses_packed_kv_backend = (
|
||||
resolved_cache_dtype.startswith("turboquant_")
|
||||
or resolved_cache_dtype == "ultraquant_4bit"
|
||||
)
|
||||
if uses_packed_kv_backend:
|
||||
from vllm.model_executor.layers.quantization.turboquant.config import (
|
||||
TurboQuantConfig,
|
||||
)
|
||||
|
||||
boundary = TurboQuantConfig.get_boundary_skip_layers(model_config)
|
||||
existing = set(cache_config.kv_cache_dtype_skip_layers)
|
||||
# Sorted so the order does not depend on set iteration: the list is
|
||||
# a CacheConfig hash factor. Entries can also be attention type
|
||||
# names (e.g. "sliding_window"), so sort them as strings.
|
||||
cache_config.kv_cache_dtype_skip_layers = sorted(
|
||||
existing | set(boundary), key=int
|
||||
set(cache_config.kv_cache_dtype_skip_layers) | set(boundary)
|
||||
)
|
||||
|
||||
ray_runtime_env = None
|
||||
@@ -2662,14 +2691,18 @@ class EngineArgs:
|
||||
|
||||
# TurboQuant requires FlashAttention 2 — FA3 boundary layers assert
|
||||
# FlashAttentionImpl which fails with TurboQuantAttentionImpl.
|
||||
if resolved_cache_dtype.startswith("turboquant_") and (
|
||||
# UltraQuant subclasses that impl, so it inherits the same limit.
|
||||
if uses_packed_kv_backend and (
|
||||
attention_config.flash_attn_version is None
|
||||
or attention_config.flash_attn_version >= 3
|
||||
):
|
||||
logger.warning(
|
||||
"TurboQuant is not yet compatible with FlashAttention >= 3. "
|
||||
"%s is not yet compatible with FlashAttention >= 3. "
|
||||
"Overriding flash_attn_version to 2. To silence this "
|
||||
"warning, pass --attention-config.flash_attn_version=2"
|
||||
"warning, pass --attention-config.flash_attn_version=2",
|
||||
"TurboQuant"
|
||||
if resolved_cache_dtype.startswith("turboquant_")
|
||||
else "UltraQuant",
|
||||
)
|
||||
attention_config.flash_attn_version = 2
|
||||
|
||||
@@ -2728,13 +2761,7 @@ class EngineArgs:
|
||||
load_config = self.create_load_config()
|
||||
|
||||
# Pass reasoning_parser into StructuredOutputsConfig
|
||||
if self.reasoning_parser:
|
||||
self.structured_outputs_config.reasoning_parser = self.reasoning_parser
|
||||
|
||||
if self.reasoning_parser_plugin:
|
||||
self.structured_outputs_config.reasoning_parser_plugin = (
|
||||
self.reasoning_parser_plugin
|
||||
)
|
||||
self.create_structured_outputs_config()
|
||||
|
||||
observability_config = self.create_observability_config()
|
||||
|
||||
|
||||
@@ -162,8 +162,14 @@ class EngineClient(ABC):
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def start_profile(self) -> None:
|
||||
"""Start profiling the engine."""
|
||||
async def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Start profiling with optional per-session overrides."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -229,6 +229,17 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
top_p: float | None = None
|
||||
|
||||
# vLLM-specific fields that are not in Anthropic spec
|
||||
return_mm_kwargs: bool = Field(
|
||||
default=True,
|
||||
description=(
|
||||
"If false, the render response's `features` set `kwargs_data` "
|
||||
"and `mm_metadata` to null, for callers that need only the token "
|
||||
"layout and item hashes, such as cache-aware routers. Do not send "
|
||||
"such a response to `/inference/v1/generate`, which reads a null "
|
||||
"`kwargs_data` as every item being cached. Only supported on the "
|
||||
"render endpoints; ignored on regular generation endpoints."
|
||||
),
|
||||
)
|
||||
cache_salt: str | None = Field(
|
||||
default=None,
|
||||
min_length=1,
|
||||
@@ -242,6 +253,12 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
"to 256 bit)."
|
||||
),
|
||||
)
|
||||
watermarking: bool | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Whether to apply the engine's configured watermark to this request."
|
||||
),
|
||||
)
|
||||
kv_transfer_params: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
description="KVTransfer parameters used for disaggregated serving.",
|
||||
@@ -379,7 +396,9 @@ class AnthropicCountTokensRequest(BaseModel):
|
||||
|
||||
model: str
|
||||
messages: list[AnthropicMessage]
|
||||
output_config: AnthropicOutputConfig | None = None
|
||||
system: str | list[AnthropicContentBlock] | None = None
|
||||
thinking: AnthropicThinkingConfig | None = None
|
||||
tool_choice: AnthropicToolChoice | None = None
|
||||
tools: list[AnthropicTool] | None = None
|
||||
|
||||
|
||||
@@ -613,6 +613,7 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
temperature=anthropic_request.temperature,
|
||||
top_p=anthropic_request.top_p,
|
||||
top_k=anthropic_request.top_k,
|
||||
watermarking=anthropic_request.watermarking,
|
||||
cache_salt=anthropic_request.cache_salt,
|
||||
kv_transfer_params=anthropic_request.kv_transfer_params,
|
||||
ec_transfer_params=anthropic_request.ec_transfer_params,
|
||||
@@ -632,8 +633,6 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
``display`` is intentionally ignored: suppressing reasoning would mark
|
||||
it ended for structured outputs and drop it from multi-turn history.
|
||||
"""
|
||||
if isinstance(anthropic_request, AnthropicCountTokensRequest):
|
||||
return
|
||||
thinking: AnthropicThinkingConfig | None = anthropic_request.thinking
|
||||
if thinking is None:
|
||||
return
|
||||
@@ -654,8 +653,6 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
anthropic_request: AnthropicMessagesRequest | AnthropicCountTokensRequest,
|
||||
) -> None:
|
||||
"""Handle output configuration such as output format and effort."""
|
||||
if isinstance(anthropic_request, AnthropicCountTokensRequest):
|
||||
return
|
||||
output_config: AnthropicOutputConfig | None = anthropic_request.output_config
|
||||
if output_config and output_config.format and output_config.format.json_schema:
|
||||
req.response_format = ResponseFormat(
|
||||
@@ -1237,9 +1234,13 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
raw_request: Request | None = None,
|
||||
) -> AnthropicCountTokensResponse | ErrorResponse:
|
||||
"""Implements Anthropic's messages.count_tokens endpoint."""
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffort = "none"
|
||||
if request.thinking is not None and request.thinking.type == "disabled":
|
||||
disabled_thinking_effort = await self._get_disabled_thinking_effort()
|
||||
chat_req = self.to_chat_completion_request(
|
||||
request,
|
||||
merge_inline_system=self._merge_inline_system,
|
||||
disabled_thinking_effort=disabled_thinking_effort,
|
||||
)
|
||||
result = await self.render_chat_request(chat_req)
|
||||
if isinstance(result, ErrorResponse):
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import (
|
||||
Final,
|
||||
Generic,
|
||||
Literal,
|
||||
Required,
|
||||
TypeAlias,
|
||||
TypeVar,
|
||||
Union,
|
||||
@@ -48,7 +49,7 @@ from PIL import Image
|
||||
from pydantic import BaseModel, ConfigDict, TypeAdapter
|
||||
|
||||
# pydantic needs the TypedDict from typing_extensions
|
||||
from typing_extensions import Required, TypedDict, override
|
||||
from typing_extensions import TypedDict, override
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config import ModelConfig
|
||||
|
||||
@@ -328,19 +328,10 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
None
|
||||
)
|
||||
|
||||
from vllm.v1.engine.utils import get_engine_zmq_addresses
|
||||
from vllm.v1.engine.utils import bind_engine_zmq_listeners
|
||||
|
||||
# Defer port allocation to the child's bind() to avoid TOCTOU, except
|
||||
# for Rust front-end and Ray DP, which can't see the post-bind rebind
|
||||
# (CLI-arg subprocess / pickled-into-actor snapshot respectively) and
|
||||
# so pre-allocate driver-side -- reintroducing the original race only
|
||||
# there.
|
||||
is_ray_dp = parallel_config.data_parallel_backend == "ray"
|
||||
addresses = get_engine_zmq_addresses(
|
||||
vllm_config,
|
||||
num_api_servers,
|
||||
defer_api_server_ports=not (rust_frontend_path or is_ray_dp),
|
||||
)
|
||||
zmq_listeners = bind_engine_zmq_listeners(vllm_config, num_api_servers)
|
||||
addresses = zmq_listeners.addresses
|
||||
|
||||
with launch_core_engines(
|
||||
vllm_config, executor_class, log_stats, addresses
|
||||
@@ -365,8 +356,8 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
sock=sock,
|
||||
grpc_sock=grpc_sock,
|
||||
args=args,
|
||||
input_address=addresses.inputs[0],
|
||||
output_address=addresses.outputs[0],
|
||||
input_listener=zmq_listeners.inputs[0],
|
||||
output_listener=zmq_listeners.outputs[0],
|
||||
engine_start_index=expected_engine_start_index,
|
||||
engine_count=expected_engine_count,
|
||||
data_parallel_size=parallel_config.data_parallel_size,
|
||||
@@ -379,22 +370,12 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
sock=sock,
|
||||
args=args,
|
||||
num_servers=num_api_servers,
|
||||
input_addresses=addresses.inputs,
|
||||
output_addresses=addresses.outputs,
|
||||
input_listeners=zmq_listeners.inputs,
|
||||
output_listeners=zmq_listeners.outputs,
|
||||
stats_update_address=stats_update_address,
|
||||
tensor_queue=engine_launch.tensor_queue,
|
||||
)
|
||||
|
||||
if not is_ray_dp:
|
||||
# Forward each child's bound endpoints to the engine handshake
|
||||
# (runs on ``with`` exit). Skipped for Ray DP, where addresses
|
||||
# are pre-allocated above and Ray actors already hold them.
|
||||
actual_inputs, actual_outputs = (
|
||||
api_server_manager.gather_actual_addresses()
|
||||
)
|
||||
addresses.inputs = actual_inputs
|
||||
addresses.outputs = actual_outputs
|
||||
|
||||
# Set frontend processes to watch during engine startup.
|
||||
# If any of these processes exit before the engines are up, the engine startup
|
||||
# will be aborted with an error.
|
||||
|
||||
@@ -40,6 +40,9 @@ from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.exception_handling.error_response import (
|
||||
create_error_response,
|
||||
)
|
||||
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
|
||||
from vllm.entrypoints.serve.utils.api_utils import (
|
||||
load_aware_call,
|
||||
@@ -138,15 +141,9 @@ if _SDK_AVAILABLE:
|
||||
|
||||
try:
|
||||
result = await handler.create_chat_v2(request, raw_request)
|
||||
except Exception as e: # noqa: BLE001 - report as 500 for parity
|
||||
except Exception as e:
|
||||
logger.exception("Error in /cohere/v2/chat: %s", e)
|
||||
return JSONResponse(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
|
||||
content=CohereError(
|
||||
message=sanitize_message(str(e)),
|
||||
id=_request_id(raw_request),
|
||||
).model_dump(exclude_none=True),
|
||||
)
|
||||
return _error_response(create_error_response(e), raw_request)
|
||||
|
||||
match result:
|
||||
case ErrorResponse():
|
||||
@@ -194,19 +191,18 @@ if _SDK_AVAILABLE:
|
||||
try:
|
||||
chat_request = handler.to_chat_completion_request(request)
|
||||
result = await render_handler.render_chat_request(chat_request)
|
||||
except Exception as e: # noqa: BLE001 - report as 500 for parity
|
||||
except Exception as e:
|
||||
logger.exception("Error in /cohere/v2/chat/render: %s", e)
|
||||
return JSONResponse(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
|
||||
content=CohereError(
|
||||
message=sanitize_message(str(e)),
|
||||
id=_request_id(raw_request),
|
||||
).model_dump(exclude_none=True),
|
||||
)
|
||||
return _error_response(create_error_response(e), raw_request)
|
||||
|
||||
if isinstance(result, ErrorResponse):
|
||||
return _error_response(result, raw_request)
|
||||
|
||||
if (kwargs := result.reasoning_parser_kwargs) is not None:
|
||||
kwargs.chat_template_kwargs = handler._engine_chat_template_kwargs(
|
||||
kwargs.chat_template_kwargs
|
||||
)
|
||||
|
||||
return JSONResponse(content=result.model_dump())
|
||||
|
||||
class CohereErrorEnvelopeMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
@@ -175,6 +175,12 @@ class CohereChatV2Request(BaseModel):
|
||||
# vLLM-specific extensions (not in Cohere spec). These mirror what the
|
||||
# Anthropic and OpenAI surfaces already expose so V2 callers can reach
|
||||
# the same engine knobs when needed.
|
||||
watermarking: bool | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Whether to apply the engine's configured watermark to this request."
|
||||
),
|
||||
)
|
||||
kv_transfer_params: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
description="KVTransfer parameters used for disaggregated serving.",
|
||||
|
||||
@@ -58,6 +58,7 @@ from vllm.entrypoints.cohere.protocol import (
|
||||
CohereChatV2Request,
|
||||
CohereChatV2Response,
|
||||
CohereFinishReason,
|
||||
CohereLogprobItem,
|
||||
CohereUsage,
|
||||
CohereUsageBilledUnits,
|
||||
CohereUsageTokens,
|
||||
@@ -79,6 +80,7 @@ from vllm.entrypoints.generate.base.protocol import (
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionResponse,
|
||||
ChatCompletionResponseChoice,
|
||||
ChatCompletionStreamResponse,
|
||||
ChatCompletionToolsParam,
|
||||
ChatMessage,
|
||||
@@ -557,10 +559,13 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
temperature=request.temperature,
|
||||
top_p=request.p,
|
||||
top_k=request.k,
|
||||
watermarking=request.watermarking,
|
||||
seed=request.seed,
|
||||
frequency_penalty=request.frequency_penalty,
|
||||
presence_penalty=request.presence_penalty,
|
||||
logprobs=request.logprobs,
|
||||
# Cohere logprob items carry token ids alongside the logprobs.
|
||||
return_token_ids=request.logprobs,
|
||||
priority=request.priority or 0,
|
||||
kv_transfer_params=request.kv_transfer_params,
|
||||
chat_template_kwargs=request.chat_template_kwargs,
|
||||
@@ -1090,9 +1095,29 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
),
|
||||
message=assistant_msg,
|
||||
usage=usage,
|
||||
logprobs=self._build_logprobs(choice),
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _build_logprobs(
|
||||
choice: ChatCompletionResponseChoice,
|
||||
) -> list[CohereLogprobItem] | None:
|
||||
if (
|
||||
choice.logprobs is None
|
||||
or not choice.logprobs.content
|
||||
or choice.token_ids is None
|
||||
):
|
||||
return None
|
||||
return [
|
||||
CohereLogprobItem(
|
||||
text=entry.token, token_ids=[token_id], logprobs=[entry.logprob]
|
||||
)
|
||||
for entry, token_id in zip(
|
||||
choice.logprobs.content, choice.token_ids, strict=True
|
||||
)
|
||||
]
|
||||
|
||||
def _create_chat_message(self, *args: Any, **kwargs: Any) -> ChatMessage:
|
||||
"""Route response construction through the citation-carrying subclass.
|
||||
|
||||
|
||||
@@ -53,6 +53,12 @@ def register_generate_api_routers(app: FastAPI):
|
||||
|
||||
register_generative_scoring_api_router(app)
|
||||
|
||||
from .structured_decisions.api_router import (
|
||||
register_structured_decisions_api_router,
|
||||
)
|
||||
|
||||
register_structured_decisions_api_router(app)
|
||||
|
||||
|
||||
async def init_generate_state(
|
||||
engine_client: "EngineClient",
|
||||
@@ -220,3 +226,31 @@ async def init_generate_state(
|
||||
state.openai_serving_models,
|
||||
request_logger=request_logger,
|
||||
)
|
||||
|
||||
from .structured_decisions.serving import ServingStructuredDecisions
|
||||
from .structured_decisions.strategies import ReadContext, select_read_strategy
|
||||
|
||||
strategy = None
|
||||
if "generate" in supported_tasks:
|
||||
try:
|
||||
strategy_cls = select_read_strategy(engine_client.model_config)
|
||||
strategy = strategy_cls(
|
||||
ReadContext(
|
||||
engine_client=engine_client,
|
||||
online_renderer=state.online_renderer,
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
)
|
||||
)
|
||||
except ValueError:
|
||||
strategy = None
|
||||
state.serving_structured_decisions = (
|
||||
ServingStructuredDecisions(
|
||||
state.openai_serving_models,
|
||||
strategy,
|
||||
request_logger=request_logger,
|
||||
)
|
||||
if strategy is not None
|
||||
else None
|
||||
)
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import (
|
||||
BaseModel,
|
||||
BeforeValidator,
|
||||
Field,
|
||||
model_serializer,
|
||||
)
|
||||
@@ -26,6 +27,12 @@ StopParam: TypeAlias = (
|
||||
str | Annotated[list[str], Field(max_length=envs.VLLM_MAX_STOP_STRINGS)] | None
|
||||
)
|
||||
|
||||
# `top_logprobs` is nullable in the OpenAI spec; null means the same as omitted.
|
||||
TopLogprobsParam: TypeAlias = Annotated[
|
||||
int,
|
||||
BeforeValidator(lambda v: 0 if v is None else v, json_schema_input_type=int | None),
|
||||
]
|
||||
|
||||
_CACHE_SALT_FORBIDDEN_CHARS = frozenset("@/\\\x00")
|
||||
_MAX_CACHE_SALT_LENGTH = 128
|
||||
|
||||
@@ -223,7 +230,11 @@ def validate_structural_tag_response_format(
|
||||
|
||||
|
||||
def validate_structural_tag_payload(payload: Any, *, parameter: str) -> None:
|
||||
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
|
||||
from vllm.sampling_params import (
|
||||
SamplingParams,
|
||||
StructuredOutputsParams,
|
||||
check_json_nesting,
|
||||
)
|
||||
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
|
||||
|
||||
if isinstance(payload, str) and not payload:
|
||||
@@ -232,6 +243,9 @@ def validate_structural_tag_payload(payload: Any, *, parameter: str) -> None:
|
||||
parameter=parameter,
|
||||
)
|
||||
|
||||
if isinstance(payload, str):
|
||||
# Raised here so the error is not reported as a malformed tag below
|
||||
check_json_nesting(payload, structural_tag=True)
|
||||
try:
|
||||
validate_xgrammar_grammar(
|
||||
SamplingParams(
|
||||
|
||||
@@ -32,6 +32,7 @@ from vllm.logger import init_logger
|
||||
from vllm.logprobs import Logprob, PromptLogprobs
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
|
||||
from vllm.tracing import (
|
||||
contains_trace_headers,
|
||||
extract_trace_headers,
|
||||
@@ -346,32 +347,33 @@ def format_token_id_placeholder(token_id: int) -> str:
|
||||
return f"token_id:{token_id}"
|
||||
|
||||
|
||||
def resolve_token_id_placeholder(
|
||||
token: str, tokenizer: TokenizerLike
|
||||
) -> tuple[str, list[int] | None]:
|
||||
"""Decode a 'token_id:N' placeholder back to a token string and UTF-8 bytes.
|
||||
def decode_token_ids(
|
||||
token_ids: list[int], tokenizer: TokenizerLike
|
||||
) -> list[tuple[str, list[int] | None]]:
|
||||
"""Decode token ids individually to their token strings and UTF-8 bytes.
|
||||
|
||||
Returns (token, None) unchanged if token is not a placeholder.
|
||||
This is the inverse of format_token_id_placeholder / _get_decoded_token
|
||||
when return_as_token_id=True.
|
||||
Uses the engine's per-token detokenization, which restores the
|
||||
SentencePiece leading space that `convert_tokens_to_string` drops, so the
|
||||
strings match the coupled endpoints. Ids are decoded in one batch (callers
|
||||
pass a position's sampled id together with its top-k ids). An id with no
|
||||
vocab entry decodes to ("", None).
|
||||
"""
|
||||
suffix = token.removeprefix("token_id:")
|
||||
if suffix == token:
|
||||
return token, None
|
||||
try:
|
||||
token_id = int(suffix)
|
||||
except ValueError:
|
||||
return token, None
|
||||
token_repr = tokenizer.convert_ids_to_tokens([token_id])[0]
|
||||
if token_repr is None:
|
||||
logger.warning_once(
|
||||
"resolve_token_id_placeholder: token_id %d has no vocab entry; "
|
||||
"substituting empty string",
|
||||
token_id,
|
||||
)
|
||||
return "", None
|
||||
token_str = tokenizer.convert_tokens_to_string([token_repr])
|
||||
return token_str, list(token_str.encode("utf-8", errors="replace"))
|
||||
pieces = tokenizer.convert_ids_to_tokens(token_ids)
|
||||
known = [tid for tid, piece in zip(token_ids, pieces) if piece is not None]
|
||||
decoded = iter(convert_ids_list_to_tokens(tokenizer, known))
|
||||
out: list[tuple[str, list[int] | None]] = []
|
||||
for tid, piece in zip(token_ids, pieces):
|
||||
if piece is None:
|
||||
logger.warning_once(
|
||||
"decode_token_ids: token_id %d has no vocab entry; "
|
||||
"substituting empty string",
|
||||
tid,
|
||||
)
|
||||
out.append(("", None))
|
||||
continue
|
||||
token_str = next(decoded)
|
||||
out.append((token_str, list(token_str.encode("utf-8", errors="replace"))))
|
||||
return out
|
||||
|
||||
|
||||
def clamp_prompt_logprobs(
|
||||
|
||||
@@ -8,7 +8,7 @@ import torch
|
||||
from tqdm import tqdm
|
||||
|
||||
from vllm import RequestOutput, TextPrompt, TokensPrompt
|
||||
from vllm.entrypoints.offline_utils import OfflineInferenceMixin
|
||||
from vllm.entrypoints.common.offline import OfflineInferenceMixin
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.pooling_params import PoolingParams
|
||||
@@ -82,7 +82,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
temperature = params.temperature
|
||||
ignore_eos = params.ignore_eos
|
||||
length_penalty = params.length_penalty
|
||||
self.llm_engine.vllm_config._check_watermarking_unsupported(beam_search=True)
|
||||
self.llm_engine.input_processor.resolve_watermarking(params)
|
||||
|
||||
tokenizer = self.renderer.get_tokenizer()
|
||||
eos_token_id = tokenizer.eos_token_id
|
||||
@@ -120,6 +120,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
logprobs=2 * beam_width,
|
||||
max_tokens=1,
|
||||
temperature=temperature,
|
||||
watermarking=False,
|
||||
detokenize=False,
|
||||
skip_clone=True, # Internal beam search, safe to skip clone
|
||||
)
|
||||
@@ -457,6 +458,7 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
logprobs=base_params.logprobs,
|
||||
max_tokens=1,
|
||||
temperature=base_params.temperature,
|
||||
watermarking=base_params.watermarking,
|
||||
detokenize=False,
|
||||
allowed_token_ids=(
|
||||
allowed_ids
|
||||
|
||||
@@ -40,6 +40,7 @@ class BeamSearchOnlineMixin(ABC):
|
||||
temperature = params.temperature
|
||||
length_penalty = params.length_penalty
|
||||
include_stop_str_in_output = params.include_stop_str_in_output
|
||||
self.engine_client.input_processor.resolve_watermarking(params)
|
||||
|
||||
tokenizer = self.renderer.get_tokenizer()
|
||||
eos_token_id = tokenizer.eos_token_id
|
||||
@@ -62,6 +63,7 @@ class BeamSearchOnlineMixin(ABC):
|
||||
logprobs=logprobs_num,
|
||||
max_tokens=1,
|
||||
temperature=temperature,
|
||||
watermarking=False,
|
||||
detokenize=False,
|
||||
)
|
||||
all_beams = [
|
||||
|
||||
@@ -11,13 +11,15 @@ logits (task="generate").
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections.abc import AsyncGenerator, Mapping
|
||||
from typing import Literal
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.generate.base.protocol import validate_cache_salt
|
||||
from vllm.entrypoints.generate.label_reads import next_token_label_reads
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.serve.engine.protocol import (
|
||||
ErrorResponse,
|
||||
@@ -28,7 +30,6 @@ from vllm.entrypoints.serve.engine.serving import BaseServing
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.inputs import EngineInput, tokens_input
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tracing import (
|
||||
@@ -37,7 +38,6 @@ from vllm.tracing import (
|
||||
log_tracing_disabled_warning,
|
||||
)
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.async_utils import merge_async_iterators
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -60,6 +60,7 @@ class GenerativeScoringRequest(OpenAIBaseModel):
|
||||
the full vocab for those ids (False).
|
||||
item_first: If True, prepend items to query. Otherwise append items to query.
|
||||
add_special_tokens: Whether to add special tokens when tokenizing.
|
||||
cache_salt: Optional salt for prefix caching.
|
||||
|
||||
"""
|
||||
|
||||
@@ -92,6 +93,17 @@ class GenerativeScoringRequest(OpenAIBaseModel):
|
||||
default=True,
|
||||
description="Whether to add special tokens when tokenizing.",
|
||||
)
|
||||
cache_salt: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"If specified, the prefix cache will be salted with the provided "
|
||||
"string to prevent an attacker to guess prompts in multi-user "
|
||||
"environments. The salt should be random, protected from "
|
||||
"access by 3rd parties, and long enough to be "
|
||||
"unpredictable (e.g., 43 characters base64-encoded, corresponding "
|
||||
"to 256 bit)."
|
||||
),
|
||||
)
|
||||
priority: int = Field(
|
||||
default=0,
|
||||
ge=-(2**63),
|
||||
@@ -105,6 +117,13 @@ class GenerativeScoringRequest(OpenAIBaseModel):
|
||||
description="The request_id related to this request.",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def check_cache_salt_support(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
validate_cache_salt(data.get("cache_salt"))
|
||||
return data
|
||||
|
||||
|
||||
class GenerativeScoringItemResult(OpenAIBaseModel):
|
||||
"""Result for a single item in the generative scoring response.
|
||||
@@ -261,6 +280,7 @@ class ServingGenerativeScoring(BaseServing):
|
||||
logprobs=len(request.label_token_ids),
|
||||
logprob_token_ids=request.label_token_ids,
|
||||
n=1,
|
||||
watermarking=False,
|
||||
)
|
||||
|
||||
# Get trace headers
|
||||
@@ -270,37 +290,28 @@ class ServingGenerativeScoring(BaseServing):
|
||||
else await self._get_trace_headers(raw_request.headers)
|
||||
)
|
||||
|
||||
# Schedule requests for all inputs
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = []
|
||||
for i, engine_input in enumerate(engine_inputs):
|
||||
request_id_item = f"{request_id}-{i}"
|
||||
|
||||
self._log_inputs(
|
||||
request_id_item,
|
||||
f"{request_id}-{i}",
|
||||
engine_input,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_input,
|
||||
sampling_params,
|
||||
request_id_item,
|
||||
try:
|
||||
reads = await next_token_label_reads(
|
||||
self.engine_client,
|
||||
engine_inputs,
|
||||
[sampling_params] * len(engine_inputs),
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
)
|
||||
generators.append(generator)
|
||||
|
||||
# Collect results
|
||||
result_generator = merge_async_iterators(*generators)
|
||||
results: list[RequestOutput | None] = [None] * len(engine_inputs)
|
||||
|
||||
try:
|
||||
async for i, res in result_generator:
|
||||
results[i] = res
|
||||
except asyncio.CancelledError:
|
||||
return self.create_error_response("Client disconnected")
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
except Exception as e:
|
||||
logger.exception("Error during generation")
|
||||
return self.create_error_response(e)
|
||||
@@ -310,45 +321,8 @@ class ServingGenerativeScoring(BaseServing):
|
||||
total_prompt_tokens = 0
|
||||
total_completion_tokens = 0
|
||||
|
||||
for i, result in enumerate(results):
|
||||
if result is None:
|
||||
return self.create_error_response(
|
||||
f"Failed to generate result for item {i}"
|
||||
)
|
||||
|
||||
# Check for errors
|
||||
if result.outputs and result.outputs[0].finish_reason == "error":
|
||||
return self.create_error_response(f"Generation error for item {i}")
|
||||
|
||||
# Get logprobs from the generated token
|
||||
if not result.outputs or len(result.outputs) == 0:
|
||||
return self.create_error_response(f"No output generated for item {i}")
|
||||
|
||||
output = result.outputs[0]
|
||||
if output.logprobs is None or len(output.logprobs) == 0:
|
||||
return self.create_error_response(
|
||||
f"No logprobs available for item {i}. "
|
||||
"This might indicate an issue with logprobs configuration."
|
||||
)
|
||||
|
||||
# The logprobs dict maps token_id -> Logprob object
|
||||
# For logprobs=-1, this contains all vocab tokens
|
||||
logprobs_dict = output.logprobs[0]
|
||||
|
||||
# Extract logprobs for label tokens
|
||||
label_logprobs: dict[int, float] = {}
|
||||
missing_tokens = []
|
||||
for token_id in request.label_token_ids:
|
||||
if token_id in logprobs_dict:
|
||||
label_logprobs[token_id] = logprobs_dict[token_id].logprob
|
||||
else:
|
||||
missing_tokens.append(token_id)
|
||||
|
||||
if missing_tokens:
|
||||
return self.create_error_response(
|
||||
f"Token IDs {missing_tokens} not found in logprobs for item {i}. "
|
||||
"This might indicate the tokens are outside the model's vocabulary."
|
||||
)
|
||||
for i, read in enumerate(reads):
|
||||
label_logprobs = dict(zip(request.label_token_ids, read.logprobs))
|
||||
|
||||
# Compute probabilities based on apply_softmax setting
|
||||
token_probs = self._compute_probabilities(
|
||||
@@ -369,7 +343,7 @@ class ServingGenerativeScoring(BaseServing):
|
||||
|
||||
# Update token counts
|
||||
total_prompt_tokens += prompt_token_counts[i]
|
||||
total_completion_tokens += len(output.token_ids)
|
||||
total_completion_tokens += len(read.result.outputs[0].token_ids)
|
||||
|
||||
# Build response
|
||||
model_name = self.models.model_name(lora_request)
|
||||
@@ -441,7 +415,9 @@ class ServingGenerativeScoring(BaseServing):
|
||||
if len(prompt_token_ids) > max_prompt_len:
|
||||
prompt_token_ids = prompt_token_ids[:max_prompt_len]
|
||||
|
||||
engine_inputs.append(tokens_input(prompt_token_ids))
|
||||
engine_inputs.append(
|
||||
tokens_input(prompt_token_ids, cache_salt=request.cache_salt)
|
||||
)
|
||||
prompt_token_counts.append(len(prompt_token_ids))
|
||||
|
||||
return engine_inputs, prompt_token_counts
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""One-token reads that return the logprobs of chosen label tokens."""
|
||||
|
||||
from collections.abc import AsyncGenerator, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.inputs import EngineInput
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.async_utils import merge_async_iterators
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LabelRead:
|
||||
result: RequestOutput
|
||||
logprobs: list[float]
|
||||
"""Full-vocabulary logprob of each label token, in ``logprob_token_ids``
|
||||
order."""
|
||||
|
||||
|
||||
async def next_token_label_reads(
|
||||
engine_client: EngineClient,
|
||||
engine_inputs: Sequence[EngineInput],
|
||||
sampling_params: Sequence[SamplingParams],
|
||||
request_id: str,
|
||||
*,
|
||||
lora_request: LoRARequest | None = None,
|
||||
trace_headers: Mapping[str, str] | None = None,
|
||||
priority: int = 0,
|
||||
) -> list[LabelRead]:
|
||||
"""Runs one read per input at once, as request ``{request_id}-{i}``. Each
|
||||
read's params set ``max_tokens=1`` and the label tokens as
|
||||
``logprob_token_ids``. Raises ValueError naming the item when a read has
|
||||
no output or lacks a label's logprob."""
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = [
|
||||
engine_client.generate(
|
||||
engine_input,
|
||||
params,
|
||||
f"{request_id}-{i}",
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=priority,
|
||||
)
|
||||
for i, (engine_input, params) in enumerate(zip(engine_inputs, sampling_params))
|
||||
]
|
||||
results: list[RequestOutput | None] = [None] * len(generators)
|
||||
async for i, res in merge_async_iterators(*generators):
|
||||
results[i] = res
|
||||
|
||||
reads = []
|
||||
for i, (result, params) in enumerate(zip(results, sampling_params)):
|
||||
if result is None:
|
||||
raise ValueError(f"Failed to generate result for item {i}")
|
||||
if not result.outputs:
|
||||
raise ValueError(f"No output generated for item {i}")
|
||||
output = result.outputs[0]
|
||||
if output.finish_reason == "error":
|
||||
raise ValueError(f"Generation error for item {i}")
|
||||
if not output.logprobs:
|
||||
raise ValueError(
|
||||
f"No logprobs available for item {i}. "
|
||||
"This might indicate an issue with logprobs configuration."
|
||||
)
|
||||
logprobs = output.logprobs[0]
|
||||
label_ids = params.logprob_token_ids or []
|
||||
missing = [t for t in label_ids if t not in logprobs]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"Token IDs {missing} not found in logprobs for item {i}. "
|
||||
"This might indicate the tokens are outside the model's vocabulary."
|
||||
)
|
||||
reads.append(LabelRead(result, [logprobs[t].logprob for t in label_ids]))
|
||||
return reads
|
||||
@@ -0,0 +1,52 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from http import HTTPStatus
|
||||
|
||||
from fastapi import APIRouter, Depends, FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.utils.api_utils import (
|
||||
load_aware_call,
|
||||
validate_json_request,
|
||||
with_cancellation,
|
||||
)
|
||||
|
||||
from .protocol import StructuredDecisionRequest
|
||||
from .serving import ServingStructuredDecisions
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def structured_decisions(request: Request) -> ServingStructuredDecisions | None:
|
||||
return getattr(request.app.state, "serving_structured_decisions", None)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/systemone",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_IMPLEMENTED.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def create_structured_decision(
|
||||
request: StructuredDecisionRequest, raw_request: Request
|
||||
):
|
||||
handler = structured_decisions(raw_request)
|
||||
if handler is None:
|
||||
raise NotImplementedError(
|
||||
"The model does not support the structured decision API"
|
||||
)
|
||||
result = await handler.create_decision(request, raw_request)
|
||||
if isinstance(result, ErrorResponse):
|
||||
return JSONResponse(content=result.model_dump(), status_code=result.error.code)
|
||||
return JSONResponse(content=result.model_dump())
|
||||
|
||||
|
||||
def register_structured_decisions_api_router(app: FastAPI):
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,108 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Request and response models of the structured decisions API (/v1/systemone)."""
|
||||
|
||||
import time
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.entrypoints.generate.base.protocol import validate_cache_salt
|
||||
from vllm.entrypoints.serve.engine.protocol import OpenAIBaseModel
|
||||
from vllm.renderers import ChatParams, TokenizeParams, merge_kwargs
|
||||
from vllm.utils import random_uuid
|
||||
|
||||
|
||||
class QuestionSpec(OpenAIBaseModel):
|
||||
type: str
|
||||
instructions: Any = ""
|
||||
criteria: Any = None
|
||||
|
||||
|
||||
class StructuredDecisionRequest(OpenAIBaseModel):
|
||||
model: str | None = None
|
||||
state: Any = Field(..., description="What the questions are about: text or JSON.")
|
||||
questions: dict[str, QuestionSpec] = Field(
|
||||
..., description="Question id to question, asked in this order."
|
||||
)
|
||||
instructions: str | None = Field(
|
||||
default=None, description="Context placed ahead of the questions."
|
||||
)
|
||||
chat_template_kwargs: dict[str, Any] | None = None
|
||||
cache_salt: str | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"If specified, the prefix cache will be salted with the provided "
|
||||
"string to prevent an attacker to guess prompts in multi-user "
|
||||
"environments. The salt should be random, protected from "
|
||||
"access by 3rd parties, and long enough to be "
|
||||
"unpredictable (e.g., 43 characters base64-encoded, corresponding "
|
||||
"to 256 bit)."
|
||||
),
|
||||
)
|
||||
priority: int = Field(default=0, ge=-(2**63), le=2**63 - 1)
|
||||
request_id: str = Field(default_factory=random_uuid)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def check_cache_salt_support(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict):
|
||||
validate_cache_salt(data.get("cache_salt"))
|
||||
return data
|
||||
|
||||
|
||||
class DecisionUsage(OpenAIBaseModel):
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
|
||||
|
||||
class QuestionDiagnostics(OpenAIBaseModel):
|
||||
label_mass: float = Field(
|
||||
description="Probability the model put on the labels, over the full "
|
||||
"vocabulary. A low value means most of the probability went to tokens "
|
||||
"that are not labels."
|
||||
)
|
||||
argmax_is_label: bool
|
||||
|
||||
|
||||
class StructuredDecisionResponse(OpenAIBaseModel):
|
||||
id: str
|
||||
object: Literal["structured_decision"] = "structured_decision"
|
||||
created: int = Field(default_factory=lambda: int(time.time()))
|
||||
model: str
|
||||
answers: dict[str, dict[str, Any]]
|
||||
usage: DecisionUsage
|
||||
diagnostics: dict[str, QuestionDiagnostics]
|
||||
|
||||
|
||||
class ReadPromptRequest(OpenAIBaseModel):
|
||||
"""Chat options for one read's prompt: the state and the question in the
|
||||
user turn, ending at the generation prompt so the label is the reply's
|
||||
first token. Thinking is off unless the request turns it on, or the label
|
||||
would follow a thought rather than start the reply."""
|
||||
|
||||
chat_template_kwargs: dict[str, Any] | None = None
|
||||
cache_salt: str | None = None
|
||||
|
||||
def build_chat_params(
|
||||
self,
|
||||
default_template: str | None,
|
||||
default_template_content_format: ChatTemplateContentFormatOption,
|
||||
) -> ChatParams:
|
||||
return ChatParams(
|
||||
chat_template=default_template,
|
||||
chat_template_content_format=default_template_content_format,
|
||||
chat_template_kwargs=merge_kwargs(
|
||||
merge_kwargs({"enable_thinking": False}, self.chat_template_kwargs),
|
||||
dict(add_generation_prompt=True, continue_final_message=False),
|
||||
),
|
||||
)
|
||||
|
||||
def build_tok_params(self, model_config: ModelConfig) -> TokenizeParams:
|
||||
return TokenizeParams(
|
||||
max_total_tokens=model_config.max_model_len,
|
||||
max_output_tokens=1,
|
||||
add_special_tokens=False,
|
||||
)
|
||||
@@ -0,0 +1,240 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Question types for structured decisions.
|
||||
|
||||
A question type turns a request's criteria into options, writes the question
|
||||
for the model with a label per option, and builds the answer from the label
|
||||
probabilities.
|
||||
"""
|
||||
|
||||
import math
|
||||
import string
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
|
||||
class StructuredDecisionError(ValueError):
|
||||
"""An invalid request. Returned as a 400."""
|
||||
|
||||
|
||||
#: A choice labels its options A to Z in order. A single capital letter is one
|
||||
#: token at the start of a reply for the tokenizers tested. Every read checks it.
|
||||
LABELS = tuple(string.ascii_uppercase)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Option:
|
||||
name: str
|
||||
description: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Question:
|
||||
id: str
|
||||
type: "QuestionType"
|
||||
instructions: str
|
||||
options: tuple[Option, ...]
|
||||
labels: tuple[str, ...]
|
||||
|
||||
|
||||
class QuestionType(ABC):
|
||||
name: ClassVar[str]
|
||||
#: The labels of a question's options, in option order.
|
||||
label_set: ClassVar[tuple[str, ...]] = LABELS
|
||||
reply_instruction: ClassVar[str] = "Answer with the letter of one option only."
|
||||
|
||||
@abstractmethod
|
||||
def parse_options(self, qid: str, criteria: Any) -> list[Option]: ...
|
||||
|
||||
@abstractmethod
|
||||
def answer(
|
||||
self, question: Question, probs: list[float], label_mass: float
|
||||
) -> dict[str, Any]:
|
||||
"""The answer for ``question``. ``probs[i]`` is the probability of
|
||||
``question.labels[i]`` among the labels, and the list sums to 1.
|
||||
``label_mass`` is the labels' total probability over the vocabulary."""
|
||||
|
||||
def reply_line(self, label: str, option: Option) -> str | None:
|
||||
"""The option's line in the prompt, or None to leave it out."""
|
||||
return (
|
||||
f"{label}: {option.name} - {option.description}"
|
||||
if option.description
|
||||
else f"{label}: {option.name}"
|
||||
)
|
||||
|
||||
def prompt(self, question: Question) -> str:
|
||||
"""The question as the model reads it, after the state."""
|
||||
lines = [f"Question: {question.instructions}"] if question.instructions else []
|
||||
for label, o in zip(question.labels, question.options):
|
||||
line = self.reply_line(label, o)
|
||||
if line is not None:
|
||||
lines.append(line)
|
||||
lines.append(self.reply_instruction)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
QUESTION_TYPES: dict[str, QuestionType] = {}
|
||||
|
||||
|
||||
def register_question_type(cls: type[QuestionType]) -> type[QuestionType]:
|
||||
if cls.name in QUESTION_TYPES:
|
||||
raise ValueError(f"question type {cls.name!r} is already registered")
|
||||
QUESTION_TYPES[cls.name] = cls()
|
||||
return cls
|
||||
|
||||
|
||||
def get_question_type(name: str) -> QuestionType:
|
||||
try:
|
||||
return QUESTION_TYPES[name]
|
||||
except KeyError:
|
||||
raise StructuredDecisionError(
|
||||
f"unknown question type {name!r}; supported: {sorted(QUESTION_TYPES)}"
|
||||
) from None
|
||||
|
||||
|
||||
def build_question(
|
||||
qid: str,
|
||||
type_name: str,
|
||||
instructions: Any,
|
||||
criteria: Any,
|
||||
max_options: int,
|
||||
) -> Question:
|
||||
if not qid:
|
||||
raise StructuredDecisionError("question ids must be non-empty")
|
||||
qtype = get_question_type(type_name)
|
||||
options = qtype.parse_options(qid, criteria)
|
||||
if not options:
|
||||
raise StructuredDecisionError(f"question {qid!r}: needs at least one option")
|
||||
names = [o.name for o in options]
|
||||
if len(set(names)) != len(names):
|
||||
raise StructuredDecisionError(f"question {qid!r}: duplicate option names")
|
||||
limit = min(max_options, len(qtype.label_set))
|
||||
if len(options) > limit:
|
||||
raise StructuredDecisionError(
|
||||
f"question {qid!r}: at most {limit} options for this model"
|
||||
)
|
||||
if not isinstance(instructions, str):
|
||||
instructions = "" if instructions is None else str(instructions)
|
||||
return Question(
|
||||
id=qid,
|
||||
type=qtype,
|
||||
instructions=instructions,
|
||||
options=tuple(options),
|
||||
labels=qtype.label_set[: len(options)],
|
||||
)
|
||||
|
||||
|
||||
def argmax(values: list[float]) -> int:
|
||||
return max(range(len(values)), key=values.__getitem__)
|
||||
|
||||
|
||||
def label_softmax(logprobs: list[float]) -> list[float]:
|
||||
"""Softmax of the label logprobs."""
|
||||
top = max(logprobs)
|
||||
weights = [math.exp(lp - top) for lp in logprobs]
|
||||
total = sum(weights)
|
||||
return [w / total for w in weights]
|
||||
|
||||
|
||||
@register_question_type
|
||||
class ChoiceQuestion(QuestionType):
|
||||
"""Pick one option. ``criteria`` maps each option name to a description,
|
||||
or to null."""
|
||||
|
||||
name = "choice"
|
||||
|
||||
def parse_options(self, qid: str, criteria: Any) -> list[Option]:
|
||||
if not isinstance(criteria, dict) or not criteria:
|
||||
raise StructuredDecisionError(
|
||||
f"question {qid!r}: choice criteria must map option names to "
|
||||
"a description or null"
|
||||
)
|
||||
return [
|
||||
Option(str(name), None if desc is None else str(desc))
|
||||
for name, desc in criteria.items()
|
||||
]
|
||||
|
||||
def answer(
|
||||
self, question: Question, probs: list[float], label_mass: float
|
||||
) -> dict[str, Any]:
|
||||
top = argmax(probs)
|
||||
return {
|
||||
"type": self.name,
|
||||
"choice": question.options[top].name,
|
||||
"probabilities": {a.name: p for a, p in zip(question.options, probs)},
|
||||
# The chosen label's probability over the whole vocabulary, so a
|
||||
# read that mostly wanted a non-label token reports low confidence.
|
||||
"confidence": probs[top] * label_mass,
|
||||
}
|
||||
|
||||
|
||||
@register_question_type
|
||||
class NoulQuestion(QuestionType):
|
||||
"""Yes or no. ``criteria`` may describe what true and false mean."""
|
||||
|
||||
name = "noul"
|
||||
label_set = ("yes", "no")
|
||||
reply_instruction = "Answer with yes or no only."
|
||||
|
||||
def parse_options(self, qid: str, criteria: Any) -> list[Option]:
|
||||
if criteria is not None and (
|
||||
not isinstance(criteria, dict) or not criteria.keys() <= {"true", "false"}
|
||||
):
|
||||
raise StructuredDecisionError(
|
||||
f"question {qid!r}: noul criteria must be an object with true and false"
|
||||
)
|
||||
criteria = criteria or {}
|
||||
true = criteria.get("true")
|
||||
false = criteria.get("false")
|
||||
return [
|
||||
Option("yes", None if true is None else str(true)),
|
||||
Option("no", None if false is None else str(false)),
|
||||
]
|
||||
|
||||
def reply_line(self, label: str, option: Option) -> str | None:
|
||||
return f"{label}: {option.description}" if option.description else None
|
||||
|
||||
def answer(
|
||||
self, question: Question, probs: list[float], label_mass: float
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"type": self.name,
|
||||
"noul": probs[0],
|
||||
"probabilities": {"yes": probs[0], "no": probs[1]},
|
||||
# The chosen label's probability over the whole vocabulary, like a
|
||||
# choice's confidence.
|
||||
"confidence": max(probs) * label_mass,
|
||||
}
|
||||
|
||||
|
||||
@register_question_type
|
||||
class ScoreQuestion(QuestionType):
|
||||
"""Rate the state on an ordered scale. ``criteria`` is the ordered list of
|
||||
level names, from the first to the last level of the scale."""
|
||||
|
||||
name = "score"
|
||||
# 0-indexed like the answer, so a level's label is its score.
|
||||
label_set = tuple(string.digits)
|
||||
reply_instruction = "Answer with the number of one level only."
|
||||
|
||||
def parse_options(self, qid: str, criteria: Any) -> list[Option]:
|
||||
if not isinstance(criteria, list) or len(criteria) < 2:
|
||||
raise StructuredDecisionError(
|
||||
f"question {qid!r}: score criteria must be an ordered list of levels"
|
||||
)
|
||||
return [Option(str(level)) for level in criteria]
|
||||
|
||||
def answer(
|
||||
self, question: Question, probs: list[float], label_mass: float
|
||||
) -> dict[str, Any]:
|
||||
top = argmax(probs)
|
||||
return {
|
||||
"type": self.name,
|
||||
# The expected level, 0-indexed, so a level's index in the request's
|
||||
# criteria is its value.
|
||||
"score": sum(i * p for i, p in enumerate(probs)),
|
||||
"legend": {str(i): o.name for i, o in enumerate(question.options)},
|
||||
"probabilities": {str(i): p for i, p in enumerate(probs)},
|
||||
"confidence": probs[top] * label_mass,
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.engine.serving import BaseServing
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.logger import init_logger
|
||||
from vllm.tracing import (
|
||||
contains_trace_headers,
|
||||
extract_trace_headers,
|
||||
log_tracing_disabled_warning,
|
||||
)
|
||||
|
||||
from .protocol import (
|
||||
DecisionUsage,
|
||||
QuestionDiagnostics,
|
||||
StructuredDecisionRequest,
|
||||
StructuredDecisionResponse,
|
||||
)
|
||||
from .question_types import Question, StructuredDecisionError, build_question
|
||||
from .strategies import DecisionLimits, ReadStrategy
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def state_text(state: Any) -> str:
|
||||
return state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
|
||||
|
||||
|
||||
def parse_questions(
|
||||
request: StructuredDecisionRequest,
|
||||
limits: DecisionLimits,
|
||||
) -> list[Question]:
|
||||
if not request.questions:
|
||||
raise StructuredDecisionError("questions: needs at least one question")
|
||||
if len(request.questions) > limits.max_questions:
|
||||
raise StructuredDecisionError(
|
||||
f"questions: at most {limits.max_questions} for this model"
|
||||
)
|
||||
questions = []
|
||||
for qid, spec in request.questions.items():
|
||||
if spec.model_extra:
|
||||
raise StructuredDecisionError(
|
||||
f"question {qid!r}: unknown field(s) {sorted(spec.model_extra)}"
|
||||
)
|
||||
questions.append(
|
||||
build_question(
|
||||
qid,
|
||||
spec.type,
|
||||
spec.instructions,
|
||||
spec.criteria,
|
||||
limits.max_options,
|
||||
)
|
||||
)
|
||||
return questions
|
||||
|
||||
|
||||
class ServingStructuredDecisions(BaseServing):
|
||||
def __init__(
|
||||
self,
|
||||
models: OpenAIServingModels,
|
||||
strategy: ReadStrategy,
|
||||
*,
|
||||
request_logger: RequestLogger | None = None,
|
||||
) -> None:
|
||||
model_config = strategy.context.engine_client.model_config
|
||||
super().__init__(
|
||||
models=models, model_config=model_config, request_logger=request_logger
|
||||
)
|
||||
self.strategy = strategy
|
||||
self.limits = strategy.limits()
|
||||
|
||||
async def _get_trace_headers(
|
||||
self, headers: Mapping[str, str]
|
||||
) -> Mapping[str, str] | None:
|
||||
if not contains_trace_headers(headers):
|
||||
return None
|
||||
if not await self.strategy.context.engine_client.is_tracing_enabled():
|
||||
log_tracing_disabled_warning()
|
||||
return None
|
||||
return extract_trace_headers(headers)
|
||||
|
||||
async def create_decision(
|
||||
self,
|
||||
request: StructuredDecisionRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> StructuredDecisionResponse | ErrorResponse:
|
||||
if (error := await self._check_model(request)) is not None: # type: ignore[arg-type]
|
||||
return error
|
||||
engine_client = self.strategy.context.engine_client
|
||||
if engine_client.errored:
|
||||
raise engine_client.dead_error
|
||||
|
||||
base_id = self._base_request_id(raw_request, default=request.request_id)
|
||||
request_id = f"decision-{base_id}"
|
||||
try:
|
||||
questions = parse_questions(request, self.limits)
|
||||
lora_request = self._maybe_get_adapters(request) # type: ignore[arg-type]
|
||||
engine_client.check_admission(len(questions))
|
||||
trace_headers = (
|
||||
None
|
||||
if raw_request is None
|
||||
else await self._get_trace_headers(raw_request.headers)
|
||||
)
|
||||
reads = await self.strategy.read(
|
||||
questions,
|
||||
request.instructions,
|
||||
state_text(request.state),
|
||||
request_id=request_id,
|
||||
chat_template_kwargs=request.chat_template_kwargs,
|
||||
lora_request=lora_request,
|
||||
priority=request.priority,
|
||||
cache_salt=request.cache_salt,
|
||||
trace_headers=trace_headers,
|
||||
)
|
||||
except StructuredDecisionError as e:
|
||||
return self.create_error_response(e)
|
||||
except asyncio.CancelledError:
|
||||
return self.create_error_response("Client disconnected")
|
||||
|
||||
answers: dict[str, dict[str, Any]] = {}
|
||||
diagnostics: dict[str, QuestionDiagnostics] = {}
|
||||
for q, read in zip(questions, reads):
|
||||
answers[q.id] = q.type.answer(q, read.probs, read.label_mass)
|
||||
diagnostics[q.id] = QuestionDiagnostics(
|
||||
label_mass=read.label_mass, argmax_is_label=read.argmax_is_label
|
||||
)
|
||||
return StructuredDecisionResponse(
|
||||
id=request_id,
|
||||
model=self.models.model_name(lora_request),
|
||||
answers=answers,
|
||||
usage=DecisionUsage(
|
||||
input_tokens=sum(r.input_tokens for r in reads),
|
||||
output_tokens=sum(r.output_tokens for r in reads),
|
||||
),
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Read strategies: how a model is asked for label probabilities.
|
||||
|
||||
Only models in NEXT_TOKEN_ARCHITECTURES are currently supported.
|
||||
"""
|
||||
|
||||
import math
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.entrypoints.generate.label_reads import next_token_label_reads
|
||||
from vllm.inputs import EngineInput
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.renderers.inputs.preprocess import extract_prompt_components
|
||||
from vllm.renderers.online_renderer import OnlineRenderer
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
|
||||
from .protocol import ReadPromptRequest
|
||||
from .question_types import (
|
||||
LABELS,
|
||||
QUESTION_TYPES,
|
||||
Question,
|
||||
StructuredDecisionError,
|
||||
label_softmax,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReadContext:
|
||||
engine_client: EngineClient
|
||||
online_renderer: OnlineRenderer
|
||||
chat_template: str | None
|
||||
chat_template_content_format: ChatTemplateContentFormatOption
|
||||
default_chat_template_kwargs: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DecisionLimits:
|
||||
max_questions: int
|
||||
max_options: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class QuestionRead:
|
||||
probs: list[float]
|
||||
label_mass: float
|
||||
argmax_is_label: bool
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
|
||||
|
||||
class ReadStrategy(ABC):
|
||||
def __init__(self, context: ReadContext):
|
||||
self.context = context
|
||||
|
||||
@abstractmethod
|
||||
def limits(self) -> DecisionLimits: ...
|
||||
|
||||
@abstractmethod
|
||||
async def read(
|
||||
self,
|
||||
questions: list[Question],
|
||||
instructions: str | None,
|
||||
state: str,
|
||||
*,
|
||||
request_id: str,
|
||||
chat_template_kwargs: dict[str, Any] | None,
|
||||
lora_request: LoRARequest | None,
|
||||
priority: int,
|
||||
cache_salt: str | None = None,
|
||||
trace_headers: Mapping[str, str] | None = None,
|
||||
) -> list[QuestionRead]:
|
||||
"""One read per question, in order."""
|
||||
|
||||
|
||||
def reply_label_ids(
|
||||
tokenizer: TokenizerLike,
|
||||
prompt_ids: Sequence[int],
|
||||
labels: Sequence[str] = LABELS,
|
||||
) -> tuple[list[int], list[int]]:
|
||||
"""The prompt's ids after its last added token, and the token each of
|
||||
``labels`` adds after them as the first token of the reply. Raises
|
||||
ValueError if a label is not one distinct token there."""
|
||||
added = set(tokenizer.get_added_vocab().values())
|
||||
start = max((i + 1 for i, t in enumerate(prompt_ids) if t in added), default=0)
|
||||
tail = list(prompt_ids[start:])
|
||||
text = tokenizer.decode(tail)
|
||||
ids: list[int] = []
|
||||
for label in labels:
|
||||
extended = tokenizer.encode(text + label, add_special_tokens=False)
|
||||
if extended[:-1] != tail or extended[-1] in ids:
|
||||
raise ValueError(
|
||||
f"label {label!r} is not one distinct token after this model's "
|
||||
"chat prompt"
|
||||
)
|
||||
ids.append(extended[-1])
|
||||
return tail, ids
|
||||
|
||||
|
||||
class NextTokenStrategy(ReadStrategy):
|
||||
"""Autoregressive models. Each question is one request: the state, then the
|
||||
question with its labeled options, and the logprobs of the label tokens as
|
||||
the reply's first token. The requests share the state. With prefix caching,
|
||||
it is prefilled once."""
|
||||
|
||||
def __init__(self, context: ReadContext):
|
||||
super().__init__(context)
|
||||
tokenizer = context.online_renderer.renderer.get_tokenizer()
|
||||
probe = tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": "x"}],
|
||||
**{
|
||||
**context.default_chat_template_kwargs,
|
||||
"chat_template": context.chat_template,
|
||||
"add_generation_prompt": True,
|
||||
"tokenize": True,
|
||||
"return_dict": False,
|
||||
"enable_thinking": False,
|
||||
},
|
||||
)
|
||||
if isinstance(probe, str):
|
||||
probe = tokenizer.encode(probe, add_special_tokens=False)
|
||||
# Every prompt ends with the same generation prompt, so a label's token
|
||||
# is the same for every question.
|
||||
self.tail, _ = reply_label_ids(tokenizer, probe, ())
|
||||
self.label_ids: dict[str, int] = {}
|
||||
for qtype in QUESTION_TYPES.values():
|
||||
_, ids = reply_label_ids(tokenizer, probe, qtype.label_set)
|
||||
self.label_ids.update(zip(qtype.label_set, ids))
|
||||
|
||||
def limits(self) -> DecisionLimits:
|
||||
return DecisionLimits(max_questions=64, max_options=len(LABELS))
|
||||
|
||||
def _read_request(
|
||||
self, chat_template_kwargs: dict[str, Any] | None, cache_salt: str | None = None
|
||||
) -> ReadPromptRequest:
|
||||
if (chat_template_kwargs or {}).get("enable_thinking"):
|
||||
raise StructuredDecisionError(
|
||||
"a read is the reply's first token, so thinking must be off"
|
||||
)
|
||||
return ReadPromptRequest(
|
||||
chat_template_kwargs=chat_template_kwargs, cache_salt=cache_salt
|
||||
)
|
||||
|
||||
async def _render(
|
||||
self, read_request: ReadPromptRequest, messages: list[dict[str, Any]]
|
||||
) -> tuple[EngineInput, list[int]]:
|
||||
ctx = self.context
|
||||
_, (engine_input,) = await ctx.online_renderer.preprocess_chat(
|
||||
read_request,
|
||||
messages,
|
||||
default_template=ctx.chat_template,
|
||||
default_template_content_format=ctx.chat_template_content_format,
|
||||
default_template_kwargs=ctx.default_chat_template_kwargs,
|
||||
)
|
||||
prompt_ids = extract_prompt_components(
|
||||
ctx.engine_client.model_config, engine_input
|
||||
).token_ids
|
||||
return engine_input, list(prompt_ids or [])
|
||||
|
||||
async def read(
|
||||
self,
|
||||
questions: list[Question],
|
||||
instructions: str | None,
|
||||
state: str,
|
||||
*,
|
||||
request_id: str,
|
||||
chat_template_kwargs: dict[str, Any] | None,
|
||||
lora_request: LoRARequest | None,
|
||||
priority: int,
|
||||
cache_salt: str | None = None,
|
||||
trace_headers: Mapping[str, str] | None = None,
|
||||
) -> list[QuestionRead]:
|
||||
ctx = self.context
|
||||
read_request = self._read_request(chat_template_kwargs, cache_salt)
|
||||
|
||||
slots, engine_inputs = [], []
|
||||
for q in questions:
|
||||
messages = [{"role": "user", "content": f"{state}\n\n{q.type.prompt(q)}"}]
|
||||
if instructions:
|
||||
messages.insert(0, {"role": "system", "content": instructions})
|
||||
engine_input, prompt_ids = await self._render(read_request, messages)
|
||||
if prompt_ids[len(prompt_ids) - len(self.tail) :] != self.tail:
|
||||
raise StructuredDecisionError(
|
||||
"these chat options end the prompt differently, so the "
|
||||
"labels' tokens are unknown"
|
||||
)
|
||||
slots.append([self.label_ids[label] for label in q.labels])
|
||||
engine_inputs.append(engine_input)
|
||||
|
||||
label_reads = await next_token_label_reads(
|
||||
ctx.engine_client,
|
||||
engine_inputs,
|
||||
[
|
||||
SamplingParams(max_tokens=1, temperature=0.0, logprob_token_ids=ids)
|
||||
for ids in slots
|
||||
],
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=priority,
|
||||
)
|
||||
|
||||
reads = []
|
||||
for ids, label_read in zip(slots, label_reads):
|
||||
output = label_read.result.outputs[0]
|
||||
reads.append(
|
||||
QuestionRead(
|
||||
probs=label_softmax(label_read.logprobs),
|
||||
label_mass=sum(math.exp(lp) for lp in label_read.logprobs),
|
||||
argmax_is_label=bool(output.token_ids)
|
||||
and output.token_ids[0] in ids,
|
||||
input_tokens=len(label_read.result.prompt_token_ids or ()),
|
||||
output_tokens=len(output.token_ids),
|
||||
)
|
||||
)
|
||||
return reads
|
||||
|
||||
|
||||
NEXT_TOKEN_ARCHITECTURES = frozenset(
|
||||
{
|
||||
"Qwen3ForCausalLM",
|
||||
"Qwen3_5ForConditionalGeneration",
|
||||
"Qwen3_5MoeForConditionalGeneration",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# label_mass sums the labels' full-vocabulary probabilities. The logprobs modes
|
||||
# return those probabilities. The logits modes return raw logits instead.
|
||||
LOGPROBS_MODES = frozenset({"raw_logprobs", "processed_logprobs"})
|
||||
|
||||
|
||||
def select_read_strategy(model_config: ModelConfig) -> type[ReadStrategy]:
|
||||
"""Raise ValueError when the model cannot serve structured decisions."""
|
||||
if model_config.architecture not in NEXT_TOKEN_ARCHITECTURES:
|
||||
raise ValueError(
|
||||
"The structured decisions API does not support "
|
||||
f"{model_config.architecture}. Supported architectures: "
|
||||
f"{sorted(NEXT_TOKEN_ARCHITECTURES)}"
|
||||
)
|
||||
if model_config.logprobs_mode not in LOGPROBS_MODES:
|
||||
raise ValueError(
|
||||
"Structured decisions need --logprobs-mode raw_logprobs or "
|
||||
f"processed_logprobs, not {model_config.logprobs_mode}"
|
||||
)
|
||||
return NextTokenStrategy
|
||||
@@ -8,7 +8,7 @@ import signal
|
||||
import socket
|
||||
import tempfile
|
||||
from argparse import Namespace
|
||||
from collections.abc import AsyncIterator
|
||||
from collections.abc import AsyncIterator, MutableSequence
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
@@ -118,6 +118,7 @@ async def build_and_serve(
|
||||
listen_address: str,
|
||||
sock: socket.socket,
|
||||
args: Namespace,
|
||||
peer_loads: tuple[MutableSequence[int], int] | None = None,
|
||||
**uvicorn_kwargs,
|
||||
) -> asyncio.Task:
|
||||
"""Build FastAPI app, initialize state, and start serving.
|
||||
@@ -142,6 +143,7 @@ async def build_and_serve(
|
||||
app,
|
||||
sock=sock,
|
||||
enable_ssl_refresh=args.enable_ssl_refresh,
|
||||
peer_loads=peer_loads,
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
log_level=args.uvicorn_log_level,
|
||||
@@ -185,12 +187,17 @@ async def run_server_worker(
|
||||
if args.reasoning_parser_plugin and len(args.reasoning_parser_plugin) > 3:
|
||||
ReasoningParserManager.import_reasoning_parser(args.reasoning_parser_plugin)
|
||||
|
||||
peer_loads = None
|
||||
if client_config and "api_server_loads" in client_config:
|
||||
loads = client_config.pop("api_server_loads")
|
||||
peer_loads = (loads, client_config["client_index"])
|
||||
|
||||
async with build_async_engine_client(
|
||||
args,
|
||||
client_config=client_config,
|
||||
) as engine_client:
|
||||
shutdown_task = await build_and_serve(
|
||||
engine_client, listen_address, sock, args, **uvicorn_kwargs
|
||||
engine_client, listen_address, sock, args, peer_loads, **uvicorn_kwargs
|
||||
)
|
||||
# NB: Await server shutdown only after the backend context is exited
|
||||
try:
|
||||
|
||||
@@ -36,6 +36,10 @@ def register_api_routers(
|
||||
|
||||
register_vllm_dev_api_routers(app)
|
||||
|
||||
from vllm.entrypoints.rl.factories import register_rl_api_routers
|
||||
|
||||
register_rl_api_routers(app)
|
||||
|
||||
if "generate" in supported_tasks:
|
||||
from vllm.entrypoints.generate.api_router import (
|
||||
register_generate_api_routers,
|
||||
|
||||
@@ -200,7 +200,7 @@ async def _probe_endpoint(
|
||||
# vLLM returns 503 on EngineDeadError, so we should return
|
||||
# immediately if vLLM responds with a non-200 status code.
|
||||
return response.status == HTTPStatus.OK
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
|
||||
except (TimeoutError, aiohttp.ClientError) as e:
|
||||
# Allow retry of connection errors.
|
||||
logger.debug(
|
||||
"Probe attempt %d/%d failed on port %d: %r",
|
||||
|
||||
@@ -5,7 +5,7 @@ import asyncio
|
||||
import contextlib
|
||||
import signal
|
||||
import socket
|
||||
from collections.abc import Generator
|
||||
from collections.abc import Generator, MutableSequence
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
@@ -34,23 +34,149 @@ from .utils.constants import (
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# A worker with more connections than another leaves a pending connection to
|
||||
# the less loaded one, rechecking every 1 ms, for up to 5 ms (it may be busy).
|
||||
_ACCEPT_DEFER_CHECKS = 5
|
||||
# The load of a worker that is not accepting (also the initial value of the
|
||||
# shared array), so it is never the least loaded.
|
||||
_NOT_ACCEPTING = 2**31 - 1
|
||||
|
||||
|
||||
class NoSignalServer(uvicorn.Server):
|
||||
"""Uvicorn server that never installs its own SIGINT/SIGTERM handlers.
|
||||
|
||||
Callers register their own handlers on the event loop for graceful
|
||||
shutdown; uvicorn's would race with and override them (see #49668).
|
||||
|
||||
With ``peer_loads`` (several API workers on one shared socket: a shared
|
||||
array with one slot per worker, and this worker's index), each worker
|
||||
publishes its number of open connections, and a pending connection is
|
||||
accepted by the least loaded worker. The event loop's own server would
|
||||
accept every queued connection in whichever worker wakes first.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: uvicorn.Config,
|
||||
peer_loads: tuple[MutableSequence[int], int] | None = None,
|
||||
):
|
||||
super().__init__(config)
|
||||
self.peer_loads = peer_loads
|
||||
self._accept_tasks: set[asyncio.Task] = set()
|
||||
self._connecting = 0
|
||||
|
||||
@contextlib.contextmanager
|
||||
def capture_signals(self) -> Generator[None, None, None]:
|
||||
yield
|
||||
|
||||
def _publish_load(self) -> None:
|
||||
assert self.peer_loads is not None
|
||||
loads, index = self.peer_loads
|
||||
loads[index] = len(self.server_state.connections) + self._connecting
|
||||
|
||||
def _least_loaded(self) -> bool:
|
||||
assert self.peer_loads is not None
|
||||
loads, index = self.peer_loads
|
||||
return loads[index] <= min(loads)
|
||||
|
||||
async def startup(self, sockets: list[socket.socket] | None = None) -> None:
|
||||
if not (self.peer_loads and sockets):
|
||||
return await super().startup(sockets)
|
||||
# With no sockets uvicorn starts no asyncio server; _accept serves
|
||||
# them with uvicorn's protocol instead.
|
||||
await super().startup(sockets=[])
|
||||
if not self.started: # lifespan startup failed (uvicorn < 0.50)
|
||||
return
|
||||
self._publish_load()
|
||||
for sock in sockets:
|
||||
sock.listen(self.config.backlog)
|
||||
sock.setblocking(False)
|
||||
self._track(self._accept(sock))
|
||||
|
||||
def _track(self, coro) -> None:
|
||||
task = asyncio.create_task(coro)
|
||||
self._accept_tasks.add(task)
|
||||
task.add_done_callback(self._accept_tasks.discard)
|
||||
|
||||
async def _accept(self, sock: socket.socket) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
while True:
|
||||
await _readable(loop, sock)
|
||||
# Connections closed since the last accept; peers refresh likewise.
|
||||
self._publish_load()
|
||||
for _ in range(_ACCEPT_DEFER_CHECKS):
|
||||
if self._least_loaded():
|
||||
break
|
||||
await asyncio.sleep(0.001)
|
||||
try:
|
||||
conn, _ = sock.accept()
|
||||
except (BlockingIOError, InterruptedError, ConnectionAbortedError):
|
||||
continue # another worker took it
|
||||
except OSError:
|
||||
# e.g. EMFILE; asyncio's own server also retries after 1 s.
|
||||
logger.exception("Error accepting a connection")
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
self._connecting += 1
|
||||
self._publish_load()
|
||||
# Its own task, so a TLS handshake does not hold up the next accept.
|
||||
self._track(self._connect(loop, conn))
|
||||
|
||||
async def _connect(self, loop: asyncio.AbstractEventLoop, conn: socket.socket):
|
||||
config = self.config
|
||||
try:
|
||||
await loop.connect_accepted_socket(
|
||||
lambda: config.http_protocol_class( # type: ignore[call-arg]
|
||||
config=config,
|
||||
server_state=self.server_state,
|
||||
app_state=self.lifespan.state,
|
||||
_loop=loop,
|
||||
),
|
||||
conn,
|
||||
ssl=config.ssl,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
conn.close()
|
||||
raise
|
||||
except Exception:
|
||||
# e.g. a failed TLS handshake
|
||||
logger.debug("Accepted connection failed to start", exc_info=True)
|
||||
conn.close()
|
||||
finally:
|
||||
self._connecting -= 1
|
||||
self._publish_load()
|
||||
|
||||
async def shutdown(self, sockets: list[socket.socket] | None = None) -> None:
|
||||
# Before super() closes the listening sockets.
|
||||
tasks = list(self._accept_tasks)
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
if self.peer_loads is not None:
|
||||
loads, index = self.peer_loads
|
||||
loads[index] = _NOT_ACCEPTING
|
||||
await super().shutdown(sockets)
|
||||
|
||||
|
||||
async def _readable(loop: asyncio.AbstractEventLoop, sock: socket.socket) -> None:
|
||||
ready: asyncio.Future[None] = loop.create_future()
|
||||
|
||||
def wake() -> None:
|
||||
if not ready.done():
|
||||
ready.set_result(None)
|
||||
|
||||
loop.add_reader(sock, wake)
|
||||
try:
|
||||
await ready
|
||||
finally:
|
||||
loop.remove_reader(sock)
|
||||
|
||||
|
||||
async def serve_http(
|
||||
app: FastAPI,
|
||||
sock: socket.socket | None,
|
||||
enable_ssl_refresh: bool = False,
|
||||
peer_loads: tuple[MutableSequence[int], int] | None = None,
|
||||
**uvicorn_kwargs: Any,
|
||||
):
|
||||
"""Start a FastAPI app using Uvicorn, with support for custom Uvicorn config
|
||||
@@ -96,7 +222,7 @@ async def serve_http(
|
||||
config.h11_max_incomplete_event_size = h11_max_incomplete_event_size
|
||||
config.h11_max_header_count = h11_max_header_count
|
||||
config.load()
|
||||
server = NoSignalServer(config)
|
||||
server = NoSignalServer(config, peer_loads=peer_loads)
|
||||
app.state.server = server
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
@@ -50,6 +50,16 @@ async def init_render_app_state(
|
||||
default_chat_template_kwargs = resolve_default_chat_template_kwargs(args)
|
||||
state.tool_server = await init_tool_server(args)
|
||||
|
||||
# The config-resolved reasoning parser carries both the CLI flag (merged
|
||||
# in the entrypoint via `create_structured_outputs_config`) and any
|
||||
# model-specific default applied by `verify_and_update_config`
|
||||
# (e.g. "openai_gptoss" for gpt_oss), matching the main API server.
|
||||
# Keep `args.reasoning_parser` as the first source so callers that build
|
||||
# a VllmConfig without that merge still honor an explicit flag.
|
||||
reasoning_parser = (
|
||||
args.reasoning_parser or vllm_config.structured_outputs_config.reasoning_parser
|
||||
)
|
||||
|
||||
state.online_renderer = OnlineRenderer(
|
||||
model_config=vllm_config.model_config,
|
||||
renderer=renderer,
|
||||
@@ -62,7 +72,7 @@ async def init_render_app_state(
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
tool_strict_level=args.tool_strict_level,
|
||||
reasoning_parser=args.reasoning_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
log_error_stack=args.log_error_stack,
|
||||
)
|
||||
@@ -79,7 +89,7 @@ async def init_render_app_state(
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
tool_strict_level=args.tool_strict_level,
|
||||
reasoning_parser=args.reasoning_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
log_error_stack=args.log_error_stack,
|
||||
)
|
||||
|
||||
@@ -87,9 +87,14 @@ async def run_launch_fastapi(args: argparse.Namespace) -> None:
|
||||
# cache space warning from CpuPlatform.check_and_update_config.
|
||||
envs.VLLM_CPU_KVCACHE_SPACE = 0
|
||||
|
||||
# Merge frontend parser flags (e.g. --reasoning-parser) into the
|
||||
# structured outputs config, mirroring `create_engine_config`, which this
|
||||
# GPU-less entrypoint bypasses. Model-specific defaults are then applied
|
||||
# by `verify_and_update_config` during VllmConfig construction.
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
logging_config=engine_args.create_logging_config(),
|
||||
structured_outputs_config=engine_args.create_structured_outputs_config(),
|
||||
)
|
||||
shutdown_task = await build_and_serve_renderer(
|
||||
vllm_config, listen_address, sock, args
|
||||
|
||||
@@ -385,7 +385,7 @@ async def upload_data(output_url: str, data_or_file: str, from_file: bool) -> No
|
||||
if from_file:
|
||||
with open(data_or_file, "rb") as file:
|
||||
async with session.put(output_url, data=file) as response:
|
||||
if response.status != 200:
|
||||
if not 200 <= response.status < 300:
|
||||
error_text = await response.text()
|
||||
raise Exception(
|
||||
f"Failed to upload file.\n"
|
||||
@@ -394,7 +394,7 @@ async def upload_data(output_url: str, data_or_file: str, from_file: bool) -> No
|
||||
)
|
||||
else:
|
||||
async with session.put(output_url, data=data_or_file) as response:
|
||||
if response.status != 200:
|
||||
if not 200 <= response.status < 300:
|
||||
error_text = await response.text()
|
||||
raise Exception(
|
||||
f"Failed to upload data.\n"
|
||||
|
||||
+23
-65
@@ -3,13 +3,12 @@
|
||||
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, overload
|
||||
|
||||
import cloudpickle
|
||||
import torch.nn as nn
|
||||
from pydantic import ValidationError
|
||||
from tqdm.auto import tqdm
|
||||
from typing_extensions import overload
|
||||
|
||||
from vllm.config import (
|
||||
AttentionConfig,
|
||||
@@ -28,18 +27,16 @@ from vllm.config.model import (
|
||||
TokenizerMode,
|
||||
)
|
||||
from vllm.config.quantization import QuantizationConfigArgs
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
WeightTransferInitRequest,
|
||||
WeightTransferUpdateRequest,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.entrypoints.chat_utils import (
|
||||
ChatCompletionMessageParam,
|
||||
ChatTemplateContentFormatOption,
|
||||
load_chat_template,
|
||||
)
|
||||
from vllm.entrypoints.common.offline import _O, _R, OfflineInferenceMixin
|
||||
from vllm.entrypoints.generate.beam_search.offline import BeamSearchOfflineMixin
|
||||
from vllm.entrypoints.pooling.offline import PoolingOfflineMixin
|
||||
from vllm.entrypoints.rl.offline import RLOfflineMixin
|
||||
from vllm.entrypoints.serve.utils.api_utils import log_non_default_args
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.logger import configure_logging_if_needed, init_logger
|
||||
@@ -56,7 +53,6 @@ from vllm.v1.engine.llm_engine import LLMEngine
|
||||
from vllm.v1.sample.logits_processor import LogitsProcessor
|
||||
|
||||
from ..renderers import ChatParams
|
||||
from .offline_utils import _O, _R, OfflineInferenceMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.metrics.reader import Metric
|
||||
@@ -64,7 +60,9 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
class LLM(
|
||||
BeamSearchOfflineMixin, PoolingOfflineMixin, RLOfflineMixin, OfflineInferenceMixin
|
||||
):
|
||||
"""An LLM for generating texts from given prompts and sampling parameters.
|
||||
|
||||
This class includes a tokenizer, a language model (possibly distributed
|
||||
@@ -785,16 +783,30 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
mm_processor_kwargs=mm_processor_kwargs,
|
||||
)
|
||||
|
||||
def start_profile(self, profile_prefix: str | None = None) -> None:
|
||||
"""Start profiling with optional custom trace prefix.
|
||||
def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Start profiling with optional per-session overrides.
|
||||
|
||||
Args:
|
||||
profile_prefix: Optional prefix for the trace file names. If provided,
|
||||
trace files will be named as "<prefix>_dp<X>_pp<Y>_tp<Z>".
|
||||
If not provided, default naming will be used.
|
||||
delay_iterations: Optional number of worker iterations to skip before
|
||||
profiling starts.
|
||||
max_iterations: Optional maximum number of worker iterations to profile.
|
||||
Zero means no limit.
|
||||
|
||||
"""
|
||||
self.llm_engine.start_profile(profile_prefix)
|
||||
self.llm_engine.start_profile(
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def stop_profile(self) -> None:
|
||||
self.llm_engine.stop_profile()
|
||||
@@ -870,60 +882,6 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
"""
|
||||
return self.llm_engine.get_metrics()
|
||||
|
||||
def init_weight_transfer_engine(
|
||||
self, request: WeightTransferInitRequest | dict
|
||||
) -> None:
|
||||
"""Initialize weight transfer for RL training.
|
||||
|
||||
Args:
|
||||
request: Weight transfer initialization request with backend-specific info
|
||||
|
||||
"""
|
||||
init_info_dict = (
|
||||
request["init_info"] if isinstance(request, dict) else request.init_info
|
||||
)
|
||||
|
||||
self.llm_engine.collective_rpc(
|
||||
"init_weight_transfer_engine", kwargs={"init_info": init_info_dict}
|
||||
)
|
||||
|
||||
def start_weight_update(self) -> None:
|
||||
"""Start a new weight update."""
|
||||
self.llm_engine.collective_rpc("start_weight_update")
|
||||
|
||||
def start_draft_weight_update(self) -> None:
|
||||
"""Start a new weight update targeting the speculative draft model."""
|
||||
self.llm_engine.collective_rpc("start_draft_weight_update")
|
||||
|
||||
def update_weights(self, request: WeightTransferUpdateRequest | dict) -> None:
|
||||
"""Update the weights of the model.
|
||||
|
||||
Args:
|
||||
request: Weight update request with backend-specific update info
|
||||
|
||||
"""
|
||||
update_info_dict = (
|
||||
request["update_info"] if isinstance(request, dict) else request.update_info
|
||||
)
|
||||
|
||||
self.llm_engine.collective_rpc(
|
||||
"update_weights", kwargs={"update_info": update_info_dict}
|
||||
)
|
||||
|
||||
def finish_weight_update(self, weight_version: str | None = None) -> None:
|
||||
"""Finish the weight update and set its version if provided."""
|
||||
self.llm_engine.collective_rpc("finish_weight_update")
|
||||
if weight_version is not None:
|
||||
self.llm_engine.set_weight_version(weight_version)
|
||||
|
||||
def update_weight_version(self, new_version: str) -> None:
|
||||
"""Set the weight version without updating weights."""
|
||||
self.llm_engine.set_weight_version(new_version)
|
||||
|
||||
def get_weight_version(self) -> str:
|
||||
"""Return the latest committed weight version."""
|
||||
return self.llm_engine.get_weight_version()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Return a transformers-style hierarchical view of the model."""
|
||||
# Cache the result to avoid repeated collective_rpc calls
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user