Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
+69
-6
@@ -643,6 +643,36 @@ def _check_aiter_mla_fp8_support() -> bool:
|
||||
return _AITER_MLA_SUPPORTS_FP8
|
||||
|
||||
|
||||
def _rocm_aiter_gather_kv_b_proj_impl(
|
||||
kv_cache: torch.Tensor,
|
||||
kv_scale: torch.Tensor,
|
||||
kv_indptr: torch.Tensor,
|
||||
kv_indices: torch.Tensor,
|
||||
cu_seq_lens: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> None:
|
||||
from aiter.ops.triton.gather_kv_b_proj import gather_kv_b_proj
|
||||
|
||||
gather_kv_b_proj(
|
||||
kv_cache, kv_scale, kv_indptr, kv_indices, cu_seq_lens, weight, None, k, v
|
||||
)
|
||||
|
||||
|
||||
def _rocm_aiter_gather_kv_b_proj_fake(
|
||||
kv_cache: torch.Tensor,
|
||||
kv_scale: torch.Tensor,
|
||||
kv_indptr: torch.Tensor,
|
||||
kv_indices: torch.Tensor,
|
||||
cu_seq_lens: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _rocm_aiter_mla_decode_fwd_impl(
|
||||
q: torch.Tensor,
|
||||
kv_buffer: torch.Tensor,
|
||||
@@ -1086,7 +1116,10 @@ def _rocm_aiter_fused_allreduce_rmsnorm_impl(
|
||||
hidden_dim = input_.shape[-1]
|
||||
row_size = hidden_dim * input_.element_size()
|
||||
fused_qr_rmsnorm_ok = (
|
||||
qr_comm is not None
|
||||
# aiter.qr_all_reduce_rmsnorm does not implement Gemma's
|
||||
# (1 + weight) scaling.
|
||||
not gemma_norm
|
||||
and qr_comm is not None
|
||||
and not getattr(qr_comm, "disabled", True)
|
||||
and hasattr(qr_comm, "should_quick_allreduce")
|
||||
and qr_comm.should_quick_allreduce(input_)
|
||||
@@ -1133,7 +1166,16 @@ def _rocm_aiter_fused_allreduce_rmsnorm_impl(
|
||||
use_1stage=use_1stage,
|
||||
gemma_norm=gemma_norm,
|
||||
)
|
||||
assert result is not None
|
||||
if result is None:
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
return torch.ops.vllm_aiter.fused_add_rms_norm(
|
||||
tensor_model_parallel_all_reduce(input_),
|
||||
residual,
|
||||
weight,
|
||||
epsilon,
|
||||
gemma_norm,
|
||||
)
|
||||
return result[0], result[1]
|
||||
|
||||
|
||||
@@ -2502,11 +2544,10 @@ class rocm_aiter_ops:
|
||||
@classmethod
|
||||
@functools.cache
|
||||
def is_gdn_flydsl_prefill_available(cls) -> bool:
|
||||
"""Whether the opt-in AITER FlyDSL GDN prefill path can be used.
|
||||
"""Whether the 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.
|
||||
It runs AITER kernels, so VLLM_ROCM_USE_AITER remains the one switch
|
||||
that turns all of them off.
|
||||
"""
|
||||
return (
|
||||
cls._AITER_ENABLED
|
||||
@@ -2839,6 +2880,13 @@ class rocm_aiter_ops:
|
||||
dispatch_key=current_platform.dispatch_key,
|
||||
)
|
||||
|
||||
direct_register_custom_op(
|
||||
op_name="rocm_aiter_gather_kv_b_proj",
|
||||
op_func=_rocm_aiter_gather_kv_b_proj_impl,
|
||||
mutates_args=["k", "v"],
|
||||
fake_impl=_rocm_aiter_gather_kv_b_proj_fake,
|
||||
dispatch_key=current_platform.dispatch_key,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="rocm_aiter_mla_decode_fwd",
|
||||
op_func=_rocm_aiter_mla_decode_fwd_impl,
|
||||
@@ -3453,6 +3501,21 @@ class rocm_aiter_ops:
|
||||
extra_indices=extra_kv_indices,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def gather_kv_b_proj(
|
||||
kv_cache: torch.Tensor,
|
||||
kv_scale: torch.Tensor,
|
||||
kv_indptr: torch.Tensor,
|
||||
kv_indices: torch.Tensor,
|
||||
cu_seq_lens: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> None:
|
||||
torch.ops.vllm.rocm_aiter_gather_kv_b_proj(
|
||||
kv_cache, kv_scale, kv_indptr, kv_indices, cu_seq_lens, weight, k, v
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def mla_decode_fwd(
|
||||
q: torch.Tensor,
|
||||
|
||||
+26
-6
@@ -2195,6 +2195,32 @@ def moe_align_block_size(
|
||||
)
|
||||
|
||||
|
||||
def fused_globalize_align_block_size(
|
||||
topk_idx: torch.Tensor,
|
||||
psum: torch.Tensor,
|
||||
rank_expert_offset: int,
|
||||
global_num_experts: int,
|
||||
local_num_experts: int,
|
||||
block_size: int,
|
||||
sorted_ids: torch.Tensor,
|
||||
expert_ids: torch.Tensor,
|
||||
num_tokens_post_pad: torch.Tensor,
|
||||
scatter_idx: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
torch.ops._moe_C.fused_globalize_align_block_size(
|
||||
topk_idx,
|
||||
psum,
|
||||
rank_expert_offset,
|
||||
global_num_experts,
|
||||
local_num_experts,
|
||||
block_size,
|
||||
sorted_ids,
|
||||
expert_ids,
|
||||
num_tokens_post_pad,
|
||||
scatter_idx,
|
||||
)
|
||||
|
||||
|
||||
def batched_moe_align_block_size(
|
||||
max_tokens_per_batch: int,
|
||||
block_size: int,
|
||||
@@ -4464,12 +4490,6 @@ def cpu_gemm_wna16(
|
||||
return out
|
||||
|
||||
|
||||
def cpu_activation_lut_bf16(input: torch.Tensor, activation: str) -> torch.Tensor:
|
||||
out = torch.empty_like(input)
|
||||
torch.ops._C.activation_lut_bf16(out, input, activation)
|
||||
return out
|
||||
|
||||
|
||||
def cpu_prepack_moe_weight(
|
||||
weight: torch.Tensor,
|
||||
isa: str,
|
||||
|
||||
+7
-3
@@ -1064,7 +1064,11 @@ class xpu_ops:
|
||||
"when block_table is disabled, cu_seqlens_k is needed"
|
||||
)
|
||||
if out is None:
|
||||
out = torch.empty(q.shape, dtype=q.dtype, device=q.device)
|
||||
out = torch.empty(
|
||||
q.shape[:-1] + (v.shape[-1],),
|
||||
dtype=q.dtype,
|
||||
device=q.device,
|
||||
)
|
||||
real_window_size: tuple[int, int]
|
||||
if window_size is None:
|
||||
real_window_size = (-1, -1)
|
||||
@@ -1087,8 +1091,8 @@ class xpu_ops:
|
||||
block_table=block_table,
|
||||
s_aux=s_aux,
|
||||
window_size=real_window_size,
|
||||
# alibi_slopes = alibi_slopes,
|
||||
# softcap=softcap,
|
||||
alibi_slopes=alibi_slopes,
|
||||
softcap=softcap,
|
||||
return_softmax_lse=return_softmax_lse,
|
||||
q_descale=q_descale,
|
||||
k_descale=k_descale,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,148 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Build a `SchedulerOutput` for an exact batch, without the scheduler."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.benchmarks.forward.shapes import BenchCase
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.core.sched.output import NewRequestData, SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
SlidingWindowSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BenchBatch:
|
||||
scheduler_output: SchedulerOutput
|
||||
# req_id -> token IDs of the query tokens, in order.
|
||||
query_token_ids: dict[str, np.ndarray]
|
||||
# Per KV cache group: allocated (begin, end) block ranges.
|
||||
group_block_ranges: list[list[tuple[int, int]]]
|
||||
num_blocks: int
|
||||
# req_id -> the runner's expected (scheduled, computed, is_decode).
|
||||
expected: dict[str, tuple[int, int, bool]]
|
||||
|
||||
@property
|
||||
def num_tokens(self) -> int:
|
||||
return self.scheduler_output.total_num_scheduled_tokens
|
||||
|
||||
@property
|
||||
def req_ids(self) -> list[str]:
|
||||
return list(self.scheduler_output.num_scheduled_tokens)
|
||||
|
||||
def finish(self) -> SchedulerOutput:
|
||||
"""A step that only removes this batch's requests."""
|
||||
output = SchedulerOutput.make_empty()
|
||||
output.finished_req_ids = set(self.req_ids)
|
||||
return output
|
||||
|
||||
|
||||
def kv_block_size(spec: KVCacheSpec, dcp_size: int) -> int:
|
||||
"""Tokens per block as the scheduler counts them: DCP spreads each
|
||||
block's tokens over the DCP ranks."""
|
||||
return spec.block_size * (dcp_size if spec.dcp_sharded else 1)
|
||||
|
||||
|
||||
def _num_blocks(
|
||||
spec: KVCacheSpec, computed: int, kv_len: int, dcp_size: int
|
||||
) -> tuple[int, int]:
|
||||
"""Return (leading null blocks, live blocks) for one request."""
|
||||
block_size = kv_block_size(spec, dcp_size)
|
||||
if isinstance(spec, UniformTypeKVCacheSpecs):
|
||||
spec = spec.first_spec
|
||||
if isinstance(spec, (CircularBufferSpec, MambaSpec)):
|
||||
return 0, 1
|
||||
total = -(-kv_len // block_size)
|
||||
skipped = 0
|
||||
if isinstance(spec, SlidingWindowSpec):
|
||||
# Blocks wholly before the window are freed to the null block.
|
||||
skipped = max(0, computed - spec.sliding_window + 1) // block_size
|
||||
return skipped, total - skipped
|
||||
|
||||
|
||||
def build_batch(
|
||||
case: BenchCase,
|
||||
kv_cache_groups,
|
||||
num_kv_blocks: int,
|
||||
vocab_size: int,
|
||||
rng: np.random.Generator,
|
||||
dcp_size: int = 1,
|
||||
) -> BenchBatch:
|
||||
"""Allocate disjoint blocks and build `NewRequestData` for every request.
|
||||
|
||||
Groups share one block pool, so block IDs are unique across groups. Block
|
||||
0 is the null block.
|
||||
|
||||
With prefix P = K - Q (KV length K, query length Q):
|
||||
|
||||
| Kind | prompt tokens | num_computed_tokens | spec tokens |
|
||||
| ------------------ | ------------- | ------------------- | ----------- |
|
||||
| Prefill | K | P | - |
|
||||
| Decode | P | P | - |
|
||||
| Verify (D drafts) | P | P | D |
|
||||
|
||||
Unless chunked, a prefill's prefix is a prefix hit, which replays its last
|
||||
R = min(window, P) tokens on models with SWA bounded replay (window 0
|
||||
otherwise), like the scheduler: it schedules R + Q tokens from
|
||||
replay_start = num_computed_tokens = P - R.
|
||||
"""
|
||||
replay_window = max(
|
||||
(group.kv_cache_spec.prefix_replay_tokens for group in kv_cache_groups),
|
||||
default=0,
|
||||
)
|
||||
expected: dict[str, tuple[int, int, bool]] = {}
|
||||
cursor = 1
|
||||
new_reqs = []
|
||||
query_token_ids = {}
|
||||
group_block_ranges: list[list[tuple[int, int]]] = [[] for _ in kv_cache_groups]
|
||||
output = SchedulerOutput.make_empty()
|
||||
for i, req in enumerate(case.requests):
|
||||
req_id = f"bench-{i}"
|
||||
replay = min(replay_window, req.prefix_len) if req.prefix_hit else 0
|
||||
computed = req.prefix_len - replay
|
||||
block_ids = []
|
||||
for group, ranges in zip(kv_cache_groups, group_block_ranges):
|
||||
skipped, live = _num_blocks(
|
||||
group.kv_cache_spec, computed, req.kv_len, dcp_size
|
||||
)
|
||||
block_ids.append([0] * skipped + list(range(cursor, cursor + live)))
|
||||
ranges.append((cursor, cursor + live))
|
||||
cursor += live
|
||||
tokens = rng.integers(0, vocab_size, req.kv_len, dtype=np.int64)
|
||||
prompt = tokens[: req.prefix_len] if req.is_decode else tokens
|
||||
query_token_ids[req_id] = tokens[computed:]
|
||||
expected[req_id] = (req.query_len + replay, computed, req.is_decode)
|
||||
new_reqs.append(
|
||||
NewRequestData(
|
||||
req_id=req_id,
|
||||
prompt_token_ids=prompt.tolist(),
|
||||
prefill_token_ids=prompt.tolist(),
|
||||
mm_features=[],
|
||||
sampling_params=SamplingParams(max_tokens=16, temperature=0.0),
|
||||
pooling_params=None,
|
||||
block_ids=tuple(block_ids),
|
||||
num_computed_tokens=computed,
|
||||
lora_request=None,
|
||||
replay_start=computed if replay else 0,
|
||||
)
|
||||
)
|
||||
output.num_scheduled_tokens[req_id] = req.query_len + replay
|
||||
if req.num_draft_tokens:
|
||||
output.scheduled_spec_decode_tokens[req_id] = tokens[
|
||||
req.prefix_len + 1 :
|
||||
].tolist()
|
||||
if cursor > num_kv_blocks:
|
||||
raise ValueError(
|
||||
f"Case {case.name!r} needs {cursor} KV blocks, but only "
|
||||
f"{num_kv_blocks} exist. Increase the KV cache size."
|
||||
)
|
||||
output.scheduled_new_reqs = new_reqs
|
||||
output.total_num_scheduled_tokens = sum(output.num_scheduled_tokens.values())
|
||||
return BenchBatch(output, query_token_ids, group_block_ranges, cursor, expected)
|
||||
@@ -0,0 +1,248 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Capture the forward of one exact batch as a one-shot CUDA graph and time it.
|
||||
|
||||
The graph is captured for a single batch and only replays that batch, so the
|
||||
host-side decisions baked in at capture (attention plans, kernel choices by
|
||||
query length, chunk splits) are correct by construction. This deliberately
|
||||
bypasses vLLM's CUDA graph manager: no capture sizes, padding or dummy
|
||||
metadata. Each replay first restores the KV blocks the step writes, so state the
|
||||
forward mutates in place (e.g. compressor state) is the same on every replay.
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.benchmarks.forward.batch import BenchBatch
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.distributed.parallel_state import get_world_group, graph_capture
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
|
||||
|
||||
def _first_tensor(output: Any) -> torch.Tensor:
|
||||
if isinstance(output, tuple):
|
||||
output = output[0]
|
||||
assert isinstance(output, torch.Tensor), type(output)
|
||||
return output
|
||||
|
||||
|
||||
def _compare(actual: torch.Tensor, expected: torch.Tensor) -> dict[str, float]:
|
||||
delta = actual.float() - expected.float()
|
||||
scale = expected.float().square().mean().sqrt().clamp(min=1e-12)
|
||||
return {
|
||||
"max_abs": delta.abs().max().item(),
|
||||
"relative_rms": (delta.square().mean().sqrt() / scale).item(),
|
||||
}
|
||||
|
||||
|
||||
class ForwardBench:
|
||||
"""Runs one batch through the runner's `execute_model`, timing its forward.
|
||||
|
||||
`execute_model` prepares the inputs, attention metadata and forward context
|
||||
as in serving; the bench takes over the eager model call. Two steps: the
|
||||
first ("warmup") runs the model eagerly, which triggers JIT, autotuning and
|
||||
lazy init. The second ("capture") captures, validates and times the graph.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
runner: Any,
|
||||
batch: BenchBatch,
|
||||
iters: int,
|
||||
samples: int,
|
||||
state_views: list[torch.Tensor],
|
||||
):
|
||||
self.runner = runner
|
||||
self.batch = batch
|
||||
self.device = runner.device
|
||||
self.iters = iters
|
||||
self.samples = samples
|
||||
self.state_views = state_views
|
||||
self.phase = "warmup"
|
||||
self.result: dict[str, Any] = {}
|
||||
|
||||
def run(self) -> dict[str, Any]:
|
||||
runner, model = self.runner, self.runner.model
|
||||
# The runner's eager branch calls `model(**inputs)`.
|
||||
assert runner.compilation_config.cudagraph_mode == CUDAGraphMode.NONE
|
||||
assert runner.ubatch_runner is None
|
||||
prepare_inputs = runner.prepare_inputs
|
||||
self._model_forward = model.forward
|
||||
|
||||
def prepare_and_check(*args, **kwargs) -> InputBatch:
|
||||
self._input_batch = prepare_inputs(*args, **kwargs)
|
||||
self._check_batch(self._input_batch)
|
||||
return self._input_batch
|
||||
|
||||
# Instance attributes shadow the methods for these two steps only.
|
||||
runner.prepare_inputs = prepare_and_check
|
||||
model.forward = self._forward
|
||||
try:
|
||||
for self.phase in ("warmup", "capture"):
|
||||
runner.execute_model(self.batch.scheduler_output)
|
||||
finally:
|
||||
del runner.prepare_inputs, model.forward
|
||||
# No sample_tokens follows.
|
||||
runner.execute_model_state = None
|
||||
return self.result
|
||||
|
||||
def _forward(self, **inputs) -> Any:
|
||||
self._write_input_ids(self._input_batch, inputs["input_ids"])
|
||||
# Models may update the forward context in place (e.g. sequence
|
||||
# parallelism shards is_padding); every call must start from the
|
||||
# context the runner built.
|
||||
context = get_forward_context()
|
||||
saved = dict(vars(context))
|
||||
|
||||
def run_model() -> Any:
|
||||
for name, value in saved.items():
|
||||
setattr(context, name, value)
|
||||
return self._model_forward(**inputs)
|
||||
|
||||
self._run_model = run_model
|
||||
if self.phase == "warmup":
|
||||
return run_model()
|
||||
return self._capture_and_time()
|
||||
|
||||
def _check_batch(self, input_batch: InputBatch) -> None:
|
||||
"""Fail unless the runner built exactly the requested batch."""
|
||||
expected = self.batch.expected
|
||||
assert sorted(input_batch.req_ids) == sorted(expected), input_batch.req_ids
|
||||
for i, req_id in enumerate(input_batch.req_ids):
|
||||
actual = (
|
||||
int(input_batch.num_scheduled_tokens[i]),
|
||||
int(input_batch.num_computed_tokens_np[i]),
|
||||
not bool(input_batch.is_prefilling_np[i]),
|
||||
)
|
||||
assert actual == expected[req_id], (
|
||||
f"{req_id}: got (scheduled, computed, decode) = {actual}, "
|
||||
f"wanted {expected[req_id]}"
|
||||
)
|
||||
assert input_batch.num_tokens == self.batch.num_tokens
|
||||
self.result["num_tokens_after_padding"] = input_batch.num_tokens_after_padding
|
||||
self.result["batch_order"] = input_batch.req_ids
|
||||
|
||||
def _write_input_ids(
|
||||
self, input_batch: InputBatch, input_ids: torch.Tensor | None
|
||||
) -> None:
|
||||
"""Decode/verify inputs otherwise come from sampler state."""
|
||||
if input_ids is None:
|
||||
return
|
||||
ids = np.concatenate(
|
||||
[self.batch.query_token_ids[req_id] for req_id in input_batch.req_ids]
|
||||
)
|
||||
input_ids[: len(ids)].copy_(torch.from_numpy(ids))
|
||||
|
||||
def _capture_and_time(self) -> Any:
|
||||
world = get_world_group()
|
||||
# The forward mutates state it reads (e.g. compressor state), so
|
||||
# every run starts by restoring the KV blocks the step writes.
|
||||
snapshots = [(view, view.clone()) for view in self.state_views]
|
||||
|
||||
def restore() -> None:
|
||||
for view, saved in snapshots:
|
||||
view.copy_(saved)
|
||||
|
||||
# A rendezvous and the timing events live inside the graph, after the
|
||||
# restore: neither rank skew, the restore nor host launch gaps reach
|
||||
# the timed interval.
|
||||
flag = torch.zeros(1, device=self.device)
|
||||
# TODO(woosuk): Support ROCm. The bench hangs there, likely on these
|
||||
# in-graph events.
|
||||
self._events = (
|
||||
torch.cuda.Event(enable_timing=True, external=True),
|
||||
torch.cuda.Event(enable_timing=True, external=True),
|
||||
)
|
||||
if world.world_size > 1:
|
||||
# Initialize the communicator outside capture.
|
||||
torch.distributed.all_reduce(flag, group=world.device_group)
|
||||
with graph_capture(self.device) as capture_context:
|
||||
stream = capture_context.stream
|
||||
# Some kernels set up per-stream state on first use, outside capture.
|
||||
eager = _first_tensor(self._run_model()).clone()
|
||||
restore()
|
||||
reference = _first_tensor(self._run_model()).clone()
|
||||
stream.synchronize()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph, stream=stream):
|
||||
restore()
|
||||
if world.world_size > 1:
|
||||
torch.distributed.all_reduce(flag, group=world.device_group)
|
||||
self._events[0].record()
|
||||
output = self._run_model()
|
||||
self._events[1].record()
|
||||
hidden = _first_tensor(output)
|
||||
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
first = hidden.clone()
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
self.result.update(
|
||||
# Same step from the same restored state: should match exactly.
|
||||
eager_repeat=_compare(reference, eager),
|
||||
graph_vs_eager=_compare(first, reference),
|
||||
graph_deterministic=bool(torch.equal(first, hidden)),
|
||||
finite=bool(hidden.isfinite().all()),
|
||||
state_reset_bytes=sum(
|
||||
v.numel() * v.element_size() for v in self.state_views
|
||||
),
|
||||
)
|
||||
self.result["latency_us"] = self._time(graph)
|
||||
del graph
|
||||
return output
|
||||
|
||||
def _time(self, graph: torch.cuda.CUDAGraph) -> dict[str, Any]:
|
||||
"""Per-replay forward time between in-graph events, MAX across ranks."""
|
||||
world = get_world_group()
|
||||
start, end = self._events
|
||||
self._warmup(graph)
|
||||
times = []
|
||||
for _ in range(self.iters * self.samples):
|
||||
graph.replay()
|
||||
end.synchronize()
|
||||
times.append(start.elapsed_time(end) * 1000)
|
||||
arr = torch.tensor(times, device=self.device)
|
||||
if world.world_size > 1:
|
||||
torch.distributed.all_reduce(
|
||||
arr, op=torch.distributed.ReduceOp.MAX, group=world.device_group
|
||||
)
|
||||
arr = arr.cpu().numpy()
|
||||
sample_medians = np.median(arr.reshape(self.samples, -1), axis=1)
|
||||
median = float(np.median(arr))
|
||||
return {
|
||||
"timer": "graph_events" + ("_rank_max" if world.world_size > 1 else ""),
|
||||
"median": median,
|
||||
# Stability: spread of per-sample medians relative to the median.
|
||||
"sample_spread_pct": float(
|
||||
100 * (sample_medians.max() - sample_medians.min()) / median
|
||||
),
|
||||
"mean": float(arr.mean()),
|
||||
"std": float(arr.std()),
|
||||
"min": float(arr.min()),
|
||||
"p90": float(np.percentile(arr, 90)),
|
||||
"count": len(arr),
|
||||
"samples_us": [round(float(t), 2) for t in arr],
|
||||
}
|
||||
|
||||
def _warmup(self, graph: torch.cuda.CUDAGraph, seconds: float = 1.0) -> None:
|
||||
"""Replay until clocks and caches reach a steady state."""
|
||||
world = get_world_group()
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
begin = time.perf_counter()
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
per_replay = max(time.perf_counter() - begin, 1e-6)
|
||||
# Same count on every rank: the graph may contain collectives.
|
||||
count = torch.tensor([max(self.iters, int(seconds / per_replay))])
|
||||
torch.distributed.all_reduce(
|
||||
count, op=torch.distributed.ReduceOp.MAX, group=world.cpu_group
|
||||
)
|
||||
for _ in range(int(count.item())):
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
@@ -0,0 +1,70 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""KV blocks of a benchmark case: initialization and the blocks a step writes.
|
||||
|
||||
Only the case's blocks are touched, group by group: groups can alias one
|
||||
allocation with different layouts, and the batch builder keeps their block IDs
|
||||
disjoint. Zero KV times within a few percent of random KV, even for sparse
|
||||
attention (DeepSeek-V4.1, ~100K context), so zeros are the only init for now.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.benchmarks.forward.batch import BenchBatch, kv_block_size
|
||||
|
||||
|
||||
def _tensors(kv_cache) -> Iterator[torch.Tensor]:
|
||||
if isinstance(kv_cache, torch.Tensor):
|
||||
if kv_cache.numel():
|
||||
yield kv_cache
|
||||
elif isinstance(kv_cache, (list, tuple)):
|
||||
for item in kv_cache:
|
||||
yield from _tensors(item)
|
||||
|
||||
|
||||
def _block_dim(tensor: torch.Tensor, num_blocks: int) -> tuple[int, int]:
|
||||
"""Return (block dim, kernel blocks per allocator block)."""
|
||||
for dim in range(min(2, tensor.dim())):
|
||||
if tensor.shape[dim] >= num_blocks and tensor.shape[dim] % num_blocks == 0:
|
||||
return dim, tensor.shape[dim] // num_blocks
|
||||
raise ValueError(f"No block dim of size {num_blocks} in {tuple(tensor.shape)}")
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def zero_kv_blocks(
|
||||
static_forward_context: dict, kv_cache_groups, batch: BenchBatch, num_blocks: int
|
||||
) -> None:
|
||||
for group, ranges in zip(kv_cache_groups, batch.group_block_ranges):
|
||||
for name in group.layer_names:
|
||||
layer = static_forward_context[name]
|
||||
for tensor in _tensors(getattr(layer, "kv_cache", None)):
|
||||
dim, factor = _block_dim(tensor, num_blocks)
|
||||
for begin, end in ranges:
|
||||
tensor.narrow(dim, begin * factor, (end - begin) * factor).zero_()
|
||||
|
||||
|
||||
def touched_kv_views(
|
||||
static_forward_context: dict,
|
||||
kv_cache_groups,
|
||||
batch: BenchBatch,
|
||||
num_blocks: int,
|
||||
dcp_size: int,
|
||||
) -> list[torch.Tensor]:
|
||||
"""Views of the KV blocks a step may write: each request's last
|
||||
ceil(scheduled / block_size) + 2 blocks, in every group."""
|
||||
scheduled_tokens = [batch.expected[req_id][0] for req_id in batch.req_ids]
|
||||
views = []
|
||||
for group, ranges in zip(kv_cache_groups, batch.group_block_ranges):
|
||||
block_size = kv_block_size(group.kv_cache_spec, dcp_size)
|
||||
for name in group.layer_names:
|
||||
layer = static_forward_context[name]
|
||||
for tensor in _tensors(getattr(layer, "kv_cache", None)):
|
||||
dim, factor = _block_dim(tensor, num_blocks)
|
||||
for (begin, end), tokens in zip(ranges, scheduled_tokens):
|
||||
first = max(begin, end - (-(-tokens // block_size) + 2))
|
||||
views.append(
|
||||
tensor.narrow(dim, first * factor, (end - first) * factor)
|
||||
)
|
||||
return views
|
||||
@@ -0,0 +1,224 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Benchmark the model forward of exact batches as one-shot CUDA graphs.
|
||||
|
||||
Each case is a list of requests `(query_len, kv_len, num_draft_tokens)`
|
||||
per DP rank. The bench builds the batch without the scheduler, runs it through
|
||||
the real `execute_model` (input prep, attention metadata, DP sync), and times
|
||||
the target-model forward captured as a CUDA graph. Sampling, the speculator
|
||||
and CPU step overhead aren't measured.
|
||||
|
||||
Single GPU: `vllm bench forward --model M --case decode=32*1@8192`.
|
||||
Multi-GPU: `torchrun --nproc-per-node=N -m vllm.entrypoints.cli.main bench
|
||||
forward ...`, one process per GPU.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.benchmarks.forward.shapes import (
|
||||
BenchCase,
|
||||
jitter_kv_lens,
|
||||
load_cases,
|
||||
parse_case,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def add_cli_args(parser: FlexibleArgumentParser) -> None:
|
||||
parser.add_argument(
|
||||
"--case",
|
||||
action="append",
|
||||
default=[],
|
||||
help="`NAME=REQS`, where REQS is a comma list of `[N*]Q[@K][c][:D]` "
|
||||
"(query length Q, KV length K including the query (default Q), D draft "
|
||||
"tokens, N requests). A prefill's prefix is a prefix-cache hit unless c "
|
||||
"marks a chunked prefill. E.g. `decode=32*1@8192`, "
|
||||
"`verify=16*4@4096:3`, `prefill=8192`, `hit=2048@10240`, "
|
||||
"`mix=8192,32*1@8192`. Repeatable.",
|
||||
)
|
||||
parser.add_argument("--shapes", help="JSON or YAML file with cases.")
|
||||
parser.add_argument(
|
||||
"--kv-len-jitter",
|
||||
type=float,
|
||||
default=0.5,
|
||||
help="Draw each request's prefix (KV length minus query length) "
|
||||
"uniformly within +-this fraction of its value, like the varied lengths "
|
||||
"of a real batch, capped at the max model length. Seeded by --seed only, "
|
||||
"so every DP rank gets the same lengths. 0 keeps the exact lengths.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--kv-init",
|
||||
choices=["zeros"],
|
||||
default="zeros",
|
||||
help="Initial KV cache contents of each case's blocks.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--routing",
|
||||
choices=["auto", "real", "balanced"],
|
||||
default="auto",
|
||||
help="MoE routing. balanced: fixed routing with equal load per EP rank. "
|
||||
"auto: balanced with dummy weights, else real.",
|
||||
)
|
||||
parser.add_argument("--iters", type=int, default=20, help="Replays per sample.")
|
||||
parser.add_argument("--samples", type=int, default=5)
|
||||
parser.add_argument("--output-json", help="Write results to this file.")
|
||||
EngineArgs.add_cli_args(parser)
|
||||
parser.set_defaults(load_format="dummy", enable_prefix_caching=False)
|
||||
|
||||
|
||||
def _setup_env() -> None:
|
||||
os.environ["VLLM_USE_V2_MODEL_RUNNER"] = "1"
|
||||
os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
|
||||
# Each case's eager pass compiles exactly the shapes it needs.
|
||||
os.environ.setdefault("VLLM_DEEP_GEMM_WARMUP", "skip")
|
||||
if "RANK" in os.environ:
|
||||
return # Launched by torchrun.
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
os.environ.update(
|
||||
RANK="0",
|
||||
LOCAL_RANK="0",
|
||||
WORLD_SIZE="1",
|
||||
MASTER_ADDR="127.0.0.1",
|
||||
MASTER_PORT=str(port),
|
||||
)
|
||||
|
||||
|
||||
def _make_engine_args(args: argparse.Namespace, cases: list[BenchCase]):
|
||||
from vllm.config.compilation import CompilationMode, CUDAGraphMode
|
||||
|
||||
engine_args = EngineArgs.from_cli_args(args)
|
||||
engine_args.distributed_executor_backend = "external_launcher"
|
||||
engine_args.enable_prefix_caching = False
|
||||
engine_args.compilation_config.mode = CompilationMode.NONE
|
||||
engine_args.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
if engine_args.max_num_seqs is None:
|
||||
engine_args.max_num_seqs = max(len(c.requests) for c in cases)
|
||||
if engine_args.max_num_batched_tokens is None:
|
||||
# Prefix hits may replay up to a window more per request.
|
||||
engine_args.max_num_batched_tokens = max(
|
||||
8192,
|
||||
*(
|
||||
c.num_tokens + 1024 * sum(r.prefix_hit for r in c.requests)
|
||||
for c in cases
|
||||
),
|
||||
)
|
||||
return engine_args
|
||||
|
||||
|
||||
def run_case(runner, case: BenchCase, args: argparse.Namespace) -> dict[str, Any]:
|
||||
from vllm.benchmarks.forward.batch import build_batch
|
||||
from vllm.benchmarks.forward.capture import ForwardBench
|
||||
from vllm.benchmarks.forward.kv_init import touched_kv_views, zero_kv_blocks
|
||||
from vllm.benchmarks.forward.routing import install_routing
|
||||
|
||||
context = runner.vllm_config.compilation_config.static_forward_context
|
||||
kv_config = runner.kv_cache_config
|
||||
dcp_size = runner.parallel_config.decode_context_parallel_size
|
||||
rng = np.random.default_rng([args.seed, runner.dp_rank])
|
||||
batch = build_batch(
|
||||
case,
|
||||
kv_config.kv_cache_groups,
|
||||
kv_config.num_blocks,
|
||||
runner.model_config.get_vocab_size(),
|
||||
rng,
|
||||
dcp_size,
|
||||
)
|
||||
zero_kv_blocks(context, kv_config.kv_cache_groups, batch, kv_config.num_blocks)
|
||||
bench = ForwardBench(
|
||||
runner,
|
||||
batch,
|
||||
args.iters,
|
||||
args.samples,
|
||||
touched_kv_views(
|
||||
context, kv_config.kv_cache_groups, batch, kv_config.num_blocks, dcp_size
|
||||
),
|
||||
)
|
||||
routing, balanced = install_routing(
|
||||
runner, args.routing, args.load_format == "dummy", batch.num_tokens, args.seed
|
||||
)
|
||||
try:
|
||||
result = bench.run()
|
||||
if balanced is not None:
|
||||
balanced.check_applied()
|
||||
finally:
|
||||
runner.execute_model(batch.finish())
|
||||
if balanced is not None:
|
||||
balanced.remove()
|
||||
return {
|
||||
"num_tokens": batch.num_tokens,
|
||||
"kv_blocks": batch.num_blocks,
|
||||
"routing": routing,
|
||||
**result,
|
||||
}
|
||||
|
||||
|
||||
def main(args: argparse.Namespace) -> None:
|
||||
cases = [parse_case(c) for c in args.case]
|
||||
if args.shapes:
|
||||
cases += load_cases(args.shapes)
|
||||
if not cases:
|
||||
raise ValueError("Pass at least one --case or --shapes.")
|
||||
if not 0 <= args.kv_len_jitter < 1:
|
||||
raise ValueError("--kv-len-jitter must be in [0, 1).")
|
||||
_setup_env()
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed.parallel_state import get_world_group
|
||||
|
||||
llm = LLM.from_engine_args(_make_engine_args(args, cases))
|
||||
runner = llm.llm_engine.model_executor.driver_worker.worker.model_runner
|
||||
# Same draw on every rank: shapes are balanced across DP ranks.
|
||||
max_kv_len = runner.model_config.max_model_len
|
||||
cases = [
|
||||
jitter_kv_lens(c, args.kv_len_jitter, max_kv_len, args.seed) for c in cases
|
||||
]
|
||||
world = get_world_group()
|
||||
results = []
|
||||
with torch.inference_mode(), set_current_vllm_config(runner.vllm_config):
|
||||
for case in cases:
|
||||
result = run_case(runner, case, args)
|
||||
gathered: list[Any] = [None] * world.world_size
|
||||
torch.distributed.all_gather_object(gathered, result, group=world.cpu_group)
|
||||
if world.rank != 0:
|
||||
continue
|
||||
rank0 = gathered[0]
|
||||
latency = rank0["latency_us"] # Each replay is the max over ranks.
|
||||
results.append(
|
||||
{
|
||||
"case": case.name,
|
||||
"requests": [asdict(r) for r in case.requests],
|
||||
"median_us": latency["median"],
|
||||
"ranks": gathered,
|
||||
}
|
||||
)
|
||||
print(
|
||||
f"[forward] {case.name}: {len(case.requests)} reqs, "
|
||||
f"{rank0['num_tokens']} tokens, median {latency['median']:.1f} us, "
|
||||
f"sample spread {latency['sample_spread_pct']:.2f}%, graph vs "
|
||||
f"eager rel rms {rank0['graph_vs_eager']['relative_rms']:.1e}",
|
||||
flush=True,
|
||||
)
|
||||
if latency["sample_spread_pct"] > 0.5:
|
||||
logger.warning(
|
||||
"%s: unstable timing (sample medians spread %.2f%%).",
|
||||
case.name,
|
||||
latency["sample_spread_pct"],
|
||||
)
|
||||
if world.rank == 0 and args.output_json:
|
||||
with open(args.output_json, "w") as f:
|
||||
json.dump(results, f, indent=2)
|
||||
@@ -0,0 +1,227 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Balanced MoE routing for benchmarks with dummy weights.
|
||||
|
||||
Dummy gate weights give degenerate routing, which skews MoE and all-to-all
|
||||
cost. The routing still runs; its result is replaced by the fixture at
|
||||
whichever boundary the layer exposes:
|
||||
|
||||
- Gate output: fixed logits whose top-k is the fixture. Covers every backend
|
||||
that routes from logits, including monolithic kernels that run top-k
|
||||
internally (e.g. FlashInfer TRTLLM).
|
||||
- Experts input: models that compute top-k themselves and pass
|
||||
`topk_ids` to their experts (e.g. MegaMoE with a fused gate) get the
|
||||
fixture's IDs. The routing weights are kept; they don't affect cost.
|
||||
|
||||
Hash-routed layers ignore logits and keep their tables unless their experts
|
||||
take `topk_ids`.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Fixture logits: chosen experts score far above the rest under any monotonic
|
||||
# scoring function, so top-k picks exactly them.
|
||||
_CHOSEN_LOGIT = 4.0
|
||||
_OTHER_LOGIT = -4.0
|
||||
|
||||
|
||||
def balanced_topk_ids(
|
||||
num_tokens: int, num_experts: int, top_k: int, ep_size: int, rng
|
||||
) -> np.ndarray:
|
||||
"""Expert IDs [num_tokens, top_k] giving every EP rank equal load.
|
||||
|
||||
Each token's slots go round-robin over EP ranks, to distinct experts.
|
||||
"""
|
||||
assert num_experts % ep_size == 0
|
||||
local = num_experts // ep_size
|
||||
slots = np.arange(num_tokens)[:, None] * top_k + np.arange(top_k)
|
||||
ranks = slots % ep_size
|
||||
# Slots of one token that land on the same rank take consecutive experts.
|
||||
repeat = np.zeros_like(ranks)
|
||||
for j in range(1, top_k):
|
||||
repeat[:, j] = (ranks[:, :j] == ranks[:, j : j + 1]).sum(axis=1)
|
||||
assert repeat.max() < local
|
||||
base = rng.integers(local, size=(num_tokens, ep_size))
|
||||
offset = np.take_along_axis(base, ranks, axis=1)
|
||||
return ranks * local + (offset + repeat) % local
|
||||
|
||||
|
||||
def _moe_layers(model: torch.nn.Module) -> list[tuple[torch.nn.Module, GateLinear]]:
|
||||
"""(MoE module, gate) per layer, in model order."""
|
||||
layers: dict[GateLinear, torch.nn.Module] = {}
|
||||
for module in model.modules():
|
||||
gate = getattr(module, "gate", None)
|
||||
if not isinstance(gate, GateLinear) or gate in layers:
|
||||
continue
|
||||
if _top_k(module) is not None:
|
||||
layers[gate] = module
|
||||
return [(module, gate) for gate, module in layers.items()]
|
||||
|
||||
|
||||
def _top_k(module: torch.nn.Module) -> int | None:
|
||||
"""The MoE layer's top-k, from the module or its experts submodules."""
|
||||
for sub in module.modules():
|
||||
for name in ("top_k", "n_activated_experts"):
|
||||
top_k = getattr(sub, name, None)
|
||||
if isinstance(top_k, int):
|
||||
return top_k
|
||||
return None
|
||||
|
||||
|
||||
class BalancedRouting:
|
||||
"""Installs balanced routing for one case; `remove()` restores the model."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: torch.nn.Module,
|
||||
num_tokens: int,
|
||||
dp_rank: int,
|
||||
dp_size: int,
|
||||
ep_size: int,
|
||||
seed: int,
|
||||
device: torch.device,
|
||||
):
|
||||
layers = _moe_layers(model)
|
||||
if not layers:
|
||||
raise ValueError("No MoE gates found; use --routing real.")
|
||||
self._hooks = []
|
||||
self._biases: list[tuple[torch.Tensor, torch.Tensor]] = []
|
||||
self._fired = [0] * len(layers)
|
||||
self._layers = layers
|
||||
# Per-rank rows, with headroom for padding; every rank generates the
|
||||
# same global fixture and takes its slice.
|
||||
rows = -(-num_tokens // 256) * 256 + 256
|
||||
for layer, (module, gate) in enumerate(layers):
|
||||
if (getattr(module, "num_expert_group", None) or 1) > 1:
|
||||
raise NotImplementedError("Balanced routing with grouped top-k.")
|
||||
num_experts = gate.weight.shape[0]
|
||||
top_k = _top_k(module)
|
||||
assert top_k is not None
|
||||
rng = np.random.default_rng([seed, layer])
|
||||
ids = balanced_topk_ids(rows * dp_size, num_experts, top_k, ep_size, rng)[
|
||||
dp_rank * rows : (dp_rank + 1) * rows
|
||||
]
|
||||
logits = torch.full((rows, num_experts), _OTHER_LOGIT, dtype=torch.float32)
|
||||
logits.scatter_(1, torch.from_numpy(ids), _CHOSEN_LOGIT)
|
||||
# Distinct values: no ties for any top-k implementation.
|
||||
logits += torch.from_numpy(rng.uniform(0, 0.5, logits.shape)).float()
|
||||
self._hooks.append(
|
||||
gate.register_forward_hook(
|
||||
self._substitute(logits.to(device), self._fired, layer)
|
||||
)
|
||||
)
|
||||
bias = getattr(gate, "e_score_correction_bias", None)
|
||||
if bias is None:
|
||||
bias = getattr(module, "e_score_correction_bias", None)
|
||||
if isinstance(bias, torch.Tensor):
|
||||
self._biases.append((bias, bias.detach().clone()))
|
||||
bias.data.zero_()
|
||||
experts = getattr(module, "experts", None)
|
||||
if isinstance(experts, torch.nn.Module):
|
||||
params = list(inspect.signature(experts.forward).parameters)
|
||||
if "topk_ids" in params:
|
||||
self._hooks.append(
|
||||
experts.register_forward_pre_hook(
|
||||
self._substitute_ids(
|
||||
torch.from_numpy(ids).to(device),
|
||||
params.index("topk_ids"),
|
||||
self._fired,
|
||||
layer,
|
||||
),
|
||||
with_kwargs=True,
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _substitute(fixture: torch.Tensor, fired: list[int], layer: int):
|
||||
cast = [fixture]
|
||||
|
||||
def hook(module, inputs, output):
|
||||
fired[layer] += 1
|
||||
logits = output[0] if isinstance(output, tuple) else output
|
||||
if cast[0].dtype != logits.dtype:
|
||||
cast[0] = fixture.to(logits.dtype) # Once, at warmup.
|
||||
replaced = cast[0][: logits.shape[0]]
|
||||
return (replaced, *output[1:]) if isinstance(output, tuple) else replaced
|
||||
|
||||
return hook
|
||||
|
||||
@staticmethod
|
||||
def _substitute_ids(fixture: torch.Tensor, index: int, fired, layer: int):
|
||||
cast = [fixture]
|
||||
|
||||
def hook(module, args, kwargs):
|
||||
fired[layer] += 1
|
||||
ids = kwargs["topk_ids"] if "topk_ids" in kwargs else args[index]
|
||||
if cast[0].dtype != ids.dtype:
|
||||
cast[0] = fixture.to(ids.dtype) # Once, at warmup.
|
||||
replaced = cast[0][: ids.shape[0]]
|
||||
if "topk_ids" in kwargs:
|
||||
return args, {**kwargs, "topk_ids": replaced}
|
||||
return (*args[:index], replaced, *args[index + 1 :]), kwargs
|
||||
|
||||
return hook
|
||||
|
||||
def check_applied(self) -> None:
|
||||
"""Fail if a layer bypassed both the gate and the experts hooks."""
|
||||
missed = [
|
||||
type(module).__name__
|
||||
for (module, _), fired in zip(self._layers, self._fired)
|
||||
if not fired
|
||||
]
|
||||
if missed:
|
||||
raise RuntimeError(
|
||||
f"Balanced routing didn't reach {len(missed)} MoE layers "
|
||||
f"({missed[0]}): their gate is fused away. Use --routing real."
|
||||
)
|
||||
|
||||
def remove(self) -> None:
|
||||
for hook in self._hooks:
|
||||
hook.remove()
|
||||
for bias, saved in self._biases:
|
||||
bias.data.copy_(saved)
|
||||
|
||||
|
||||
def install_routing(
|
||||
runner, requested: str, dummy_weights: bool, num_tokens: int, seed: int
|
||||
) -> tuple[str, BalancedRouting | None]:
|
||||
"""Resolve `--routing` and install balanced routing if selected.
|
||||
|
||||
`auto` is balanced with dummy weights and real otherwise; it falls back to
|
||||
real routing when the model doesn't support the fixture.
|
||||
"""
|
||||
mode = requested
|
||||
if mode == "auto":
|
||||
mode = "balanced" if dummy_weights else "real"
|
||||
if mode == "real":
|
||||
return mode, None
|
||||
parallel = runner.parallel_config
|
||||
ep_size = (
|
||||
parallel.data_parallel_size * parallel.tensor_parallel_size
|
||||
if parallel.enable_expert_parallel
|
||||
else 1
|
||||
)
|
||||
try:
|
||||
routing = BalancedRouting(
|
||||
runner.model,
|
||||
num_tokens,
|
||||
runner.dp_rank,
|
||||
runner.dp_size,
|
||||
ep_size,
|
||||
seed,
|
||||
runner.device,
|
||||
)
|
||||
except (ValueError, NotImplementedError) as e:
|
||||
if requested == "balanced":
|
||||
raise
|
||||
logger.warning("Using real routing: %s", e)
|
||||
return "real", None
|
||||
return mode, routing
|
||||
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Exact batch shapes for `vllm bench forward`."""
|
||||
|
||||
import json
|
||||
import zlib
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import regex as re
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BenchRequest:
|
||||
query_len: int
|
||||
# KV length after the step: the prefix already in the KV cache plus the
|
||||
# query tokens.
|
||||
kv_len: int
|
||||
# Spec-decode verify: query_len == 1 + num_draft_tokens.
|
||||
num_draft_tokens: int = 0
|
||||
# The prefix was computed by this request's earlier chunks. Otherwise a
|
||||
# prefill's prefix is a prefix-cache hit, of which models with SWA bounded
|
||||
# replay (DeepSeek-V4.1) recompute the last window.
|
||||
chunked: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (
|
||||
self.query_len < 1
|
||||
or self.kv_len < self.query_len
|
||||
or self.num_draft_tokens < 0
|
||||
):
|
||||
raise ValueError(f"Invalid request: {self}")
|
||||
if self.num_draft_tokens and not self.is_decode:
|
||||
raise ValueError(
|
||||
f"Verify needs query_len == 1 + num_draft_tokens and a prefix: {self}"
|
||||
)
|
||||
if self.chunked and (self.is_decode or not self.prefix_len):
|
||||
raise ValueError(f"A chunk needs a prefill with a prefix: {self}")
|
||||
|
||||
@property
|
||||
def prefix_len(self) -> int:
|
||||
return self.kv_len - self.query_len
|
||||
|
||||
@property
|
||||
def is_decode(self) -> bool:
|
||||
"""Decode or verify; otherwise a prefill."""
|
||||
return self.prefix_len > 0 and self.query_len == 1 + self.num_draft_tokens
|
||||
|
||||
@property
|
||||
def prefix_hit(self) -> bool:
|
||||
return self.prefix_len > 0 and not self.is_decode and not self.chunked
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BenchCase:
|
||||
name: str
|
||||
requests: tuple[BenchRequest, ...]
|
||||
|
||||
@property
|
||||
def num_tokens(self) -> int:
|
||||
return sum(r.query_len for r in self.requests)
|
||||
|
||||
|
||||
def jitter_kv_lens(
|
||||
case: BenchCase, jitter: float, max_kv_len: int, seed: int
|
||||
) -> BenchCase:
|
||||
"""Draw each request's prefix uniformly within +-jitter of its value.
|
||||
|
||||
Query lengths are kept, so a fresh prefill stays one and a non-empty
|
||||
prefix stays non-empty. KV lengths are capped at `max_kv_len`. The draw
|
||||
depends only on the seed and the case's name, not on the other cases.
|
||||
"""
|
||||
rng = np.random.default_rng([seed, zlib.crc32(case.name.encode())])
|
||||
requests = []
|
||||
for req in case.requests:
|
||||
if req.kv_len > max_kv_len:
|
||||
raise ValueError(f"{case.name}: KV length {req.kv_len} > {max_kv_len}")
|
||||
prefix = req.prefix_len
|
||||
if prefix and jitter:
|
||||
prefix = max(1, round(prefix * rng.uniform(1 - jitter, 1 + jitter)))
|
||||
kv_len = min(req.query_len + prefix, max_kv_len)
|
||||
requests.append(replace(req, kv_len=kv_len))
|
||||
return replace(case, requests=tuple(requests))
|
||||
|
||||
|
||||
_REQ_RE = re.compile(r"^(?:(\d+)\*)?(\d+)(?:@(\d+))?(c)?(?::(\d+))?$")
|
||||
|
||||
|
||||
def parse_case(text: str) -> BenchCase:
|
||||
"""Parse `NAME=REQS`, where REQS is a comma list of `[N*]Q[@K][c][:D]`.
|
||||
|
||||
Q is the query length, K the KV length including the query (default Q, a
|
||||
fresh prefill), D the number of draft tokens (verify) and N the number of
|
||||
such requests. A prefill's prefix is a prefix-cache hit unless `c` marks
|
||||
it as a chunked prefill. For example, `decode=32*1@8192`,
|
||||
`verify=16*4@4096:3`, `prefill=8192`, `hit=8192@40960`,
|
||||
`chunk=8192@40960c` or `mix=8192,32*1@8192`.
|
||||
"""
|
||||
name, sep, body = text.partition("=")
|
||||
if not sep:
|
||||
name, body = text, text
|
||||
requests: list[BenchRequest] = []
|
||||
for item in body.split(","):
|
||||
match = _REQ_RE.match(item.strip())
|
||||
if match is None:
|
||||
raise ValueError(f"Invalid request {item!r} in case {text!r}")
|
||||
count, query, kv, chunked, drafts = match.groups()
|
||||
request = BenchRequest(
|
||||
int(query), int(kv or query), int(drafts or 0), chunked=bool(chunked)
|
||||
)
|
||||
requests.extend([request] * int(count or 1))
|
||||
return BenchCase(name, tuple(requests))
|
||||
|
||||
|
||||
def load_cases(path: str) -> list[BenchCase]:
|
||||
"""Load cases from a JSON or YAML file.
|
||||
|
||||
Format: `{"cases": [{"name": ..., "requests": [{"query_len": ...,
|
||||
"kv_len": ..., "num_draft_tokens": ..., "chunked": ..., "count": ...}]}]}`.
|
||||
"""
|
||||
text = Path(path).read_text()
|
||||
if path.endswith((".yaml", ".yml")):
|
||||
import yaml
|
||||
|
||||
data = yaml.safe_load(text)
|
||||
else:
|
||||
data = json.loads(text)
|
||||
cases = []
|
||||
for case in data["cases"]:
|
||||
requests: list[BenchRequest] = []
|
||||
for req in case["requests"]:
|
||||
req = dict(req)
|
||||
count = req.pop("count", 1)
|
||||
requests.extend([BenchRequest(**req)] * count)
|
||||
cases.append(BenchCase(case["name"], tuple(requests)))
|
||||
return cases
|
||||
@@ -235,7 +235,6 @@ async def async_request_openai_completions(
|
||||
handler = StreamedResponseHandler()
|
||||
|
||||
async for chunk_bytes in response.content.iter_any():
|
||||
chunk_bytes = chunk_bytes.strip()
|
||||
if not chunk_bytes:
|
||||
continue
|
||||
|
||||
@@ -412,7 +411,6 @@ async def async_request_openai_chat_completions(
|
||||
first_chunk_received = False
|
||||
handler = StreamedResponseHandler()
|
||||
async for chunk_bytes in response.content.iter_any():
|
||||
chunk_bytes = chunk_bytes.strip()
|
||||
if not chunk_bytes:
|
||||
continue
|
||||
|
||||
@@ -713,7 +711,6 @@ async def async_request_openai_audio(
|
||||
handler = StreamedResponseHandler()
|
||||
|
||||
async for chunk_bytes in response.content.iter_any():
|
||||
chunk_bytes = chunk_bytes.strip()
|
||||
if not chunk_bytes:
|
||||
continue
|
||||
|
||||
|
||||
+34
-24
@@ -823,22 +823,25 @@ async def benchmark(
|
||||
# Reuses connections across requests to reduce TLS handshake overhead.
|
||||
# Use ssl_context if provided, otherwise default to True for https URLs
|
||||
ssl_setting = ssl_context if ssl_context is not None else ("https://" in api_url)
|
||||
connector = aiohttp.TCPConnector(
|
||||
limit=max_concurrency or 0,
|
||||
limit_per_host=max_concurrency or 0,
|
||||
ttl_dns_cache=300,
|
||||
use_dns_cache=True,
|
||||
keepalive_timeout=60,
|
||||
enable_cleanup_closed=True,
|
||||
force_close=False,
|
||||
ssl=ssl_setting,
|
||||
)
|
||||
|
||||
session = aiohttp.ClientSession(
|
||||
connector=connector,
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=6 * 60 * 60),
|
||||
)
|
||||
def make_session(limit: int) -> aiohttp.ClientSession:
|
||||
connector = aiohttp.TCPConnector(
|
||||
limit=limit,
|
||||
limit_per_host=limit,
|
||||
ttl_dns_cache=300,
|
||||
use_dns_cache=True,
|
||||
keepalive_timeout=60,
|
||||
enable_cleanup_closed=True,
|
||||
force_close=False,
|
||||
ssl=ssl_setting,
|
||||
)
|
||||
return aiohttp.ClientSession(
|
||||
connector=connector,
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=6 * 60 * 60),
|
||||
)
|
||||
|
||||
session = make_session(max_concurrency or 0)
|
||||
|
||||
print("Starting initial single prompt test run...")
|
||||
test_prompt, test_prompt_len, test_output_len, test_mm_content = (
|
||||
@@ -997,11 +1000,16 @@ async def benchmark(
|
||||
chat_messages=None,
|
||||
)
|
||||
interval = 1 / probe_request_rate
|
||||
while not probe_stop.is_set():
|
||||
probe_outputs.append(
|
||||
await request_func(request_func_input=probe_input, session=session)
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
# The main session's pool is capped at max_concurrency, so probes use
|
||||
# their own connection.
|
||||
async with make_session(1) as probe_session:
|
||||
while not probe_stop.is_set():
|
||||
probe_outputs.append(
|
||||
await request_func(
|
||||
request_func_input=probe_input, session=probe_session
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
|
||||
probe_task: asyncio.Task | None = None
|
||||
if probe_request_rate > 0:
|
||||
@@ -1080,15 +1088,17 @@ async def benchmark(
|
||||
)
|
||||
outputs: list[RequestFuncOutput] = await asyncio.gather(*tasks)
|
||||
|
||||
if probe_task is not None:
|
||||
probe_stop.set()
|
||||
await probe_task
|
||||
|
||||
if pbar is not None:
|
||||
pbar.close()
|
||||
|
||||
benchmark_duration = time.perf_counter() - benchmark_start_time
|
||||
|
||||
# Stop probes after measuring the duration, so the final probe interval
|
||||
# is not counted toward the main workload's throughput.
|
||||
if probe_task is not None:
|
||||
probe_stop.set()
|
||||
await probe_task
|
||||
|
||||
spec_decode_metrics_after = await fetch_spec_decode_metrics(base_url, session)
|
||||
spec_decode_stats: dict[str, Any] | None = None
|
||||
if spec_decode_metrics_before is not None and spec_decode_metrics_after is not None:
|
||||
|
||||
@@ -625,15 +625,7 @@ def assign_loras(requests, args):
|
||||
|
||||
def validate_args(args):
|
||||
"""Validate command-line arguments."""
|
||||
# === Deprecation and Defaulting ===
|
||||
if args.dataset is not None:
|
||||
warnings.warn(
|
||||
"The '--dataset' argument will be deprecated in the next release. "
|
||||
"Please use '--dataset-name' and '--dataset-path' instead.",
|
||||
stacklevel=2,
|
||||
)
|
||||
args.dataset_path = args.dataset
|
||||
|
||||
# === Defaulting ===
|
||||
if not getattr(args, "tokenizer", None):
|
||||
args.tokenizer = args.model
|
||||
|
||||
@@ -647,11 +639,7 @@ def validate_args(args):
|
||||
raise ValueError("--prequeue-requests is not supported with --async-engine")
|
||||
|
||||
# === Dataset Configuration ===
|
||||
if (
|
||||
not args.dataset
|
||||
and not args.dataset_path
|
||||
and args.dataset_name not in {"prefix_repetition"}
|
||||
):
|
||||
if not args.dataset_path and args.dataset_name != "prefix_repetition":
|
||||
print("When dataset path is not set, it will default to random dataset")
|
||||
args.dataset_name = "random"
|
||||
random_input_len = getattr(args, "random_input_len", None)
|
||||
@@ -809,15 +797,6 @@ def add_cli_args(parser: FlexibleArgumentParser):
|
||||
help="Name of the dataset to benchmark on.",
|
||||
default="sharegpt",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dataset",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to the ShareGPT dataset, will be deprecated in\
|
||||
the next release. The dataset is expected to "
|
||||
"be a json in form of list[dict[..., conversations: "
|
||||
"list[dict[..., value: <prompt_or_response>]]]]",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dataset-path", type=str, default=None, help="Path to the dataset"
|
||||
)
|
||||
|
||||
@@ -94,10 +94,13 @@ def make_copy_and_call(
|
||||
return copy_and_call
|
||||
|
||||
|
||||
def make_compiler(compilation_config: CompilationConfig) -> CompilerInterface:
|
||||
assert not envs.VLLM_USE_MEGA_AOT_ARTIFACT or envs.VLLM_USE_STANDALONE_COMPILE, (
|
||||
"VLLM_USE_MEGA_AOT_ARTIFACT=1 requires VLLM_USE_STANDALONE_COMPILE=1"
|
||||
)
|
||||
def make_compiler(
|
||||
compilation_config: CompilationConfig, *, use_aot_compile: bool
|
||||
) -> CompilerInterface:
|
||||
assert (
|
||||
not (use_aot_compile and envs.VLLM_USE_MEGA_AOT_ARTIFACT)
|
||||
or envs.VLLM_USE_STANDALONE_COMPILE
|
||||
), "VLLM_USE_MEGA_AOT_ARTIFACT=1 requires VLLM_USE_STANDALONE_COMPILE=1"
|
||||
|
||||
if compilation_config.backend == "inductor":
|
||||
# Use standalone compile only if requested, version is new enough,
|
||||
@@ -107,11 +110,12 @@ def make_compiler(compilation_config: CompilationConfig) -> CompilerInterface:
|
||||
):
|
||||
logger.debug("Using InductorStandaloneAdaptor")
|
||||
return InductorStandaloneAdaptor(
|
||||
compilation_config.compile_cache_save_format
|
||||
compilation_config.compile_cache_save_format,
|
||||
use_aot_compile=use_aot_compile,
|
||||
)
|
||||
else:
|
||||
logger.debug("Using InductorAdaptor")
|
||||
return InductorAdaptor()
|
||||
return InductorAdaptor(use_aot_compile=use_aot_compile)
|
||||
elif compilation_config.backend == "eager":
|
||||
logger.debug("Using EagerAdaptor")
|
||||
return EagerAdaptor()
|
||||
@@ -136,11 +140,16 @@ class CompilerManager:
|
||||
support int as key.
|
||||
"""
|
||||
|
||||
def __init__(self, compilation_config: CompilationConfig) -> None:
|
||||
def __init__(
|
||||
self, compilation_config: CompilationConfig, *, use_aot_compile: bool
|
||||
) -> None:
|
||||
self.cache: dict[tuple[Range, int, str], Any] = dict()
|
||||
self.is_cache_updated = False
|
||||
self.compilation_config = compilation_config
|
||||
self.compiler = make_compiler(compilation_config)
|
||||
self.use_aot_compile = use_aot_compile
|
||||
self.compiler = make_compiler(
|
||||
compilation_config, use_aot_compile=use_aot_compile
|
||||
)
|
||||
self.loaded_artifacts: dict[str, Any] = {}
|
||||
self.prefix: str = ""
|
||||
|
||||
@@ -185,7 +194,11 @@ class CompilerManager:
|
||||
self.cache_file_path = os.path.join(cache_dir, "vllm_compile_cache.py")
|
||||
self.prefix = prefix
|
||||
|
||||
if not disable_cache and os.path.exists(self.cache_file_path):
|
||||
if (
|
||||
self.use_aot_compile
|
||||
and not disable_cache
|
||||
and os.path.exists(self.cache_file_path)
|
||||
):
|
||||
# load the cache from the file
|
||||
with open(self.cache_file_path) as f:
|
||||
# we use ast.literal_eval to parse the data
|
||||
@@ -216,7 +229,7 @@ class CompilerManager:
|
||||
)
|
||||
|
||||
def save_to_file(self) -> None:
|
||||
if self.disable_cache or not self.is_cache_updated:
|
||||
if not self.use_aot_compile or self.disable_cache or not self.is_cache_updated:
|
||||
return
|
||||
printer = pprint.PrettyPrinter(indent=4)
|
||||
data = printer.pformat(self.cache)
|
||||
@@ -230,6 +243,8 @@ class CompilerManager:
|
||||
graph_index: int,
|
||||
compile_range: Range,
|
||||
) -> Callable[..., Any] | None:
|
||||
if not self.use_aot_compile:
|
||||
return None
|
||||
if (compile_range, graph_index, self.compiler.name) not in self.cache:
|
||||
return None
|
||||
|
||||
@@ -370,7 +385,11 @@ class CompilerManager:
|
||||
assert compiled_graph is not None, "Failed to compile the graph"
|
||||
|
||||
# store the artifact in the cache
|
||||
if is_compile_cache_enabled(additional_inductor_config) and handle is not None:
|
||||
if (
|
||||
self.use_aot_compile
|
||||
and is_compile_cache_enabled(additional_inductor_config)
|
||||
and handle is not None
|
||||
):
|
||||
self.cache[(compile_range, graph_index, self.compiler.name)] = {
|
||||
"graph_handle": handle,
|
||||
"cache_key": cache_key,
|
||||
@@ -839,6 +858,7 @@ class VllmBackend:
|
||||
vllm_config: VllmConfig,
|
||||
prefix: str = "",
|
||||
is_encoder: bool = False,
|
||||
use_aot_compile: bool = True,
|
||||
) -> None:
|
||||
# if the model is initialized with a non-empty prefix,
|
||||
# then usually it's enough to use that prefix,
|
||||
@@ -859,9 +879,10 @@ class VllmBackend:
|
||||
|
||||
self.vllm_config = vllm_config
|
||||
self.compilation_config = vllm_config.compilation_config
|
||||
self.use_mega_artifact = use_aot_compile and envs.VLLM_USE_MEGA_AOT_ARTIFACT
|
||||
|
||||
self.compiler_manager: CompilerManager = CompilerManager(
|
||||
self.compilation_config
|
||||
self.compilation_config, use_aot_compile=use_aot_compile
|
||||
)
|
||||
|
||||
# Deepcopy the inductor config to detach the post-grad custom pass
|
||||
@@ -892,7 +913,7 @@ class VllmBackend:
|
||||
returns_tuple
|
||||
|
||||
"""
|
||||
if not envs.VLLM_USE_MEGA_AOT_ARTIFACT:
|
||||
if not self.use_mega_artifact:
|
||||
return None, None, None
|
||||
|
||||
from .caching import StandaloneCompiledArtifacts
|
||||
@@ -1091,12 +1112,12 @@ class VllmBackend:
|
||||
# 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 = (
|
||||
is_v1_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
|
||||
disable_cache = disable_cache or is_v1_ngram_gpu_enabled
|
||||
|
||||
if disable_cache:
|
||||
logger.info("%svLLM's torch.compile cache is disabled.", self._log_prefix())
|
||||
@@ -1193,7 +1214,7 @@ class VllmBackend:
|
||||
# keep a split_gm copy from BEFORE the interpreter replaces
|
||||
# submodules with PiecewiseBackend -- used for serialization
|
||||
original_split_gm = None
|
||||
if envs.VLLM_USE_MEGA_AOT_ARTIFACT:
|
||||
if self.use_mega_artifact:
|
||||
original_split_gm = deepcopy(self.split_gm)
|
||||
|
||||
from torch._dynamo.utils import lazy_format_graph_code
|
||||
@@ -1285,9 +1306,7 @@ class VllmBackend:
|
||||
logger.debug_once("Computation graph saved to %s", graph_path)
|
||||
|
||||
self._called = True
|
||||
graph_to_serialize = (
|
||||
original_split_gm if envs.VLLM_USE_MEGA_AOT_ARTIFACT else self.graph
|
||||
)
|
||||
graph_to_serialize = original_split_gm if self.use_mega_artifact else self.graph
|
||||
|
||||
execution_code, submod_names, consts = generate_execution_code(self.split_gm)
|
||||
# Use getattr to get correct callables: __dict__ has PiecewiseBackend
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import contextlib
|
||||
import copy
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import ExitStack
|
||||
from typing import Any, Literal
|
||||
from unittest.mock import patch
|
||||
@@ -26,6 +26,22 @@ logger = init_logger(__name__)
|
||||
_last_inductor_triton_cache_dir: str | None = None
|
||||
|
||||
|
||||
def initialize_inductor_cache(base_cache_dir: str) -> None:
|
||||
global _last_inductor_triton_cache_dir
|
||||
# Keep artifacts together unless the caller supplies a Triton cache.
|
||||
inductor_cache = os.path.join(base_cache_dir, "inductor_cache")
|
||||
os.makedirs(inductor_cache, exist_ok=True)
|
||||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = inductor_cache
|
||||
triton_cache = os.environ.get("TRITON_CACHE_DIR")
|
||||
# A directory assigned by an earlier adaptor is still a model-local
|
||||
# default, rather than a caller override for subsequent models.
|
||||
if triton_cache is None or triton_cache == _last_inductor_triton_cache_dir:
|
||||
triton_cache = os.path.join(base_cache_dir, "triton_cache")
|
||||
_last_inductor_triton_cache_dir = triton_cache
|
||||
os.makedirs(triton_cache, exist_ok=True)
|
||||
os.environ["TRITON_CACHE_DIR"] = triton_cache
|
||||
|
||||
|
||||
class CompilerInterface:
|
||||
"""The interface for a compiler that can be used by vLLM."""
|
||||
|
||||
@@ -151,18 +167,18 @@ class AlwaysHitShapeEnv:
|
||||
return ""
|
||||
|
||||
|
||||
def _get_vllm_functorch_config() -> dict[str, Any]:
|
||||
def _get_vllm_functorch_config(use_aot_compile: bool = True) -> dict[str, Any]:
|
||||
"""Return the functorch config overrides that vLLM applies at compile time.
|
||||
|
||||
Used by both set_functorch_config() and get_inductor_factors() to ensure
|
||||
the compile-time config and cache key are always consistent."""
|
||||
cfg: dict[str, Any] = {}
|
||||
if not envs.VLLM_USE_MEGA_AOT_ARTIFACT:
|
||||
if not (use_aot_compile and envs.VLLM_USE_MEGA_AOT_ARTIFACT):
|
||||
cfg["bundled_autograd_cache"] = False
|
||||
return cfg
|
||||
|
||||
|
||||
def get_inductor_factors() -> list[Any]:
|
||||
def get_inductor_factors(use_aot_compile: bool = True) -> list[Any]:
|
||||
factors: list[Any] = []
|
||||
# summarize system state
|
||||
from torch._inductor.codecache import CacheBase
|
||||
@@ -180,7 +196,7 @@ def get_inductor_factors() -> list[Any]:
|
||||
from torch._inductor import config as inductor_config
|
||||
|
||||
factors.append(inductor_config.save_config_portable())
|
||||
with functorch_config.patch(_get_vllm_functorch_config()):
|
||||
with functorch_config.patch(_get_vllm_functorch_config(use_aot_compile)):
|
||||
factors.append(functorch_config.save_config_portable())
|
||||
return factors
|
||||
|
||||
@@ -254,13 +270,16 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
|
||||
name = "inductor_standalone"
|
||||
|
||||
def __init__(self, save_format: Literal["binary", "unpacked"]) -> None:
|
||||
def __init__(
|
||||
self, save_format: Literal["binary", "unpacked"], *, use_aot_compile: bool
|
||||
) -> None:
|
||||
if not is_torch_equal_or_newer("2.10.0"):
|
||||
_patch_standalone_compile_atomic_save()
|
||||
self.save_format = save_format
|
||||
self.use_aot_compile = use_aot_compile
|
||||
|
||||
def compute_hash(self, vllm_config: VllmConfig) -> str:
|
||||
factors = get_inductor_factors()
|
||||
factors = get_inductor_factors(self.use_aot_compile)
|
||||
hash_str: str = safe_hash(
|
||||
str(factors).encode(), usedforsecurity=False
|
||||
).hexdigest()[:10]
|
||||
@@ -270,6 +289,10 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
self, cache_dir: str, disable_cache: bool = False, prefix: str = ""
|
||||
) -> None:
|
||||
self.cache_dir = cache_dir
|
||||
if not self.use_aot_compile and not disable_cache:
|
||||
initialize_inductor_cache(
|
||||
cache_dir[: -len(prefix)] if prefix else cache_dir
|
||||
)
|
||||
|
||||
def compile(
|
||||
self,
|
||||
@@ -285,7 +308,6 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
if compiler_config is not None:
|
||||
current_config.update(compiler_config)
|
||||
set_inductor_config(current_config, compile_range)
|
||||
set_functorch_config()
|
||||
|
||||
if compile_range.is_single_size():
|
||||
dynamic_shapes = "from_example_inputs"
|
||||
@@ -296,7 +318,11 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
|
||||
supports_aot = is_torch_equal_or_newer("2.10.0")
|
||||
|
||||
if not supports_aot and envs.VLLM_USE_MEGA_AOT_ARTIFACT:
|
||||
if (
|
||||
not supports_aot
|
||||
and self.use_aot_compile
|
||||
and envs.VLLM_USE_MEGA_AOT_ARTIFACT
|
||||
):
|
||||
logger.error(
|
||||
"CRITICAL: VLLM_USE_MEGA_AOT_ARTIFACT "
|
||||
"is enabled but PyTorch version does not support 'aot' "
|
||||
@@ -314,7 +340,9 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
if is_torch_equal_or_newer("2.13.0.dev"):
|
||||
compile_kwargs["donate_graph_module"] = True # type: ignore[assignment]
|
||||
|
||||
use_aot: bool = supports_aot and envs.VLLM_USE_MEGA_AOT_ARTIFACT
|
||||
use_aot: bool = (
|
||||
supports_aot and self.use_aot_compile and envs.VLLM_USE_MEGA_AOT_ARTIFACT
|
||||
)
|
||||
# only add 'aot' parameter if both supported and enabled...
|
||||
# this will set bundled_autograd_cache
|
||||
# https://github.com/pytorch/pytorch/blob/9bbc5b2905c260adf41bc866a732f9c121a2828a/torch/_inductor/standalone_compile.py#L359 # noqa
|
||||
@@ -366,9 +394,12 @@ class InductorStandaloneAdaptor(CompilerInterface):
|
||||
else:
|
||||
fake_mode_ctx = contextlib.nullcontext()
|
||||
|
||||
with pregrad_ctx, fake_mode_ctx:
|
||||
with pregrad_ctx, fake_mode_ctx, set_functorch_config(self.use_aot_compile):
|
||||
compiled_graph = standalone_compile(graph, example_inputs, **compile_kwargs)
|
||||
|
||||
if not self.use_aot_compile:
|
||||
return compiled_graph, None
|
||||
|
||||
if use_aot:
|
||||
from torch._inductor.standalone_compile import AOTCompiledArtifact
|
||||
|
||||
@@ -445,8 +476,11 @@ class InductorAdaptor(CompilerInterface):
|
||||
|
||||
name = "inductor"
|
||||
|
||||
def __init__(self, *, use_aot_compile: bool) -> None:
|
||||
self.use_aot_compile = use_aot_compile
|
||||
|
||||
def compute_hash(self, vllm_config: VllmConfig) -> str:
|
||||
factors = get_inductor_factors()
|
||||
factors = get_inductor_factors(self.use_aot_compile)
|
||||
hash_str: str = safe_hash(
|
||||
str(factors).encode(), usedforsecurity=False
|
||||
).hexdigest()[:10]
|
||||
@@ -455,24 +489,12 @@ class InductorAdaptor(CompilerInterface):
|
||||
def initialize_cache(
|
||||
self, cache_dir: str, disable_cache: bool = False, prefix: str = ""
|
||||
) -> None:
|
||||
global _last_inductor_triton_cache_dir
|
||||
self.cache_dir = cache_dir
|
||||
self.prefix = prefix
|
||||
self.base_cache_dir = cache_dir[: -len(prefix)] if prefix else cache_dir
|
||||
if disable_cache:
|
||||
return
|
||||
# Keep artifacts together unless the caller supplies a Triton cache.
|
||||
inductor_cache = os.path.join(self.base_cache_dir, "inductor_cache")
|
||||
os.makedirs(inductor_cache, exist_ok=True)
|
||||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = inductor_cache
|
||||
triton_cache = os.environ.get("TRITON_CACHE_DIR")
|
||||
# A directory assigned by an earlier adaptor is still a model-local
|
||||
# default, rather than a caller override for subsequent models.
|
||||
if triton_cache is None or triton_cache == _last_inductor_triton_cache_dir:
|
||||
triton_cache = os.path.join(self.base_cache_dir, "triton_cache")
|
||||
_last_inductor_triton_cache_dir = triton_cache
|
||||
os.makedirs(triton_cache, exist_ok=True)
|
||||
os.environ["TRITON_CACHE_DIR"] = triton_cache
|
||||
initialize_inductor_cache(self.base_cache_dir)
|
||||
|
||||
def compile(
|
||||
self,
|
||||
@@ -495,7 +517,6 @@ class InductorAdaptor(CompilerInterface):
|
||||
current_config["fx_graph_remote_cache"] = False
|
||||
|
||||
set_inductor_config(current_config, compile_range)
|
||||
set_functorch_config()
|
||||
|
||||
# inductor can inplace modify the graph, so we need to copy it
|
||||
# see https://github.com/pytorch/pytorch/issues/138980
|
||||
@@ -554,6 +575,7 @@ class InductorAdaptor(CompilerInterface):
|
||||
return AlwaysHitShapeEnv()
|
||||
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(set_functorch_config(self.use_aot_compile))
|
||||
# for hijacking the hash of the compiled graph
|
||||
stack.enter_context(
|
||||
patch(
|
||||
@@ -754,9 +776,17 @@ def set_inductor_config(config: dict[str, Any], compile_range: Range) -> None:
|
||||
)
|
||||
|
||||
|
||||
def set_functorch_config() -> None:
|
||||
for k, v in _get_vllm_functorch_config().items():
|
||||
setattr(torch._functorch.config, k, v)
|
||||
@contextlib.contextmanager
|
||||
def set_functorch_config(use_aot_compile: bool) -> Generator[None, None, None]:
|
||||
overrides = _get_vllm_functorch_config(use_aot_compile)
|
||||
if use_aot_compile:
|
||||
# Preserve the existing native configuration lifetime.
|
||||
for key, value in overrides.items():
|
||||
setattr(torch._functorch.config, key, value)
|
||||
yield
|
||||
else:
|
||||
with torch._functorch.config.patch(overrides):
|
||||
yield
|
||||
|
||||
|
||||
def trigger_inductor_lazy_init(device: torch.device | None = None) -> None:
|
||||
|
||||
@@ -110,6 +110,7 @@ def support_torch_compile(
|
||||
mark_unbacked_dims: dict[str, int | list[int]] | None = None,
|
||||
enable_if: Callable[[VllmConfig], bool] | None = None,
|
||||
is_encoder: bool = False,
|
||||
use_aot_compile: bool = True,
|
||||
) -> Callable[[type[_T]], type[_T]]: ...
|
||||
|
||||
|
||||
@@ -124,6 +125,7 @@ def support_torch_compile(
|
||||
mark_unbacked_dims: dict[str, int | list[int]] | None = None,
|
||||
enable_if: Callable[[VllmConfig], bool] | None = None,
|
||||
is_encoder: bool = False,
|
||||
use_aot_compile: bool = True,
|
||||
) -> Callable[[type[_T]], type[_T]] | type[_T]:
|
||||
"""A decorator to add support for compiling the forward method of a class.
|
||||
|
||||
@@ -175,6 +177,10 @@ def support_torch_compile(
|
||||
the lifetime of the model, otherwise, it cannot be captured as a single
|
||||
computation graph.
|
||||
|
||||
`use_aot_compile=False` disables model AOT in DYNAMO_TRACE_ONCE and
|
||||
VLLM_COMPILE modes. In VLLM_COMPILE mode, it also skips mega and direct
|
||||
compiled artifacts while retaining the underlying PyTorch graph caches.
|
||||
|
||||
`enable_if` is a function that takes a `VllmConfig` object as input and
|
||||
returns a boolean value indicating whether to compile the model or not.
|
||||
This is useful if you want to compile the model only when certain
|
||||
@@ -243,6 +249,7 @@ def support_torch_compile(
|
||||
mark_unbacked_dims,
|
||||
enable_if,
|
||||
is_encoder,
|
||||
use_aot_compile,
|
||||
)
|
||||
|
||||
if cls is not None:
|
||||
@@ -347,6 +354,7 @@ def _support_torch_compile(
|
||||
mark_unbacked_dims: dict[str, int | list[int]] | None = None,
|
||||
enable_if: Callable[[VllmConfig], bool] | None = None,
|
||||
is_encoder: bool = False,
|
||||
use_aot_compile: bool = True,
|
||||
) -> type[_T]:
|
||||
"""Internal implementation of support_torch_compile decorator."""
|
||||
if TorchCompileWithNoGuardsWrapper in cls.__bases__:
|
||||
@@ -396,6 +404,7 @@ def _support_torch_compile(
|
||||
|
||||
self.vllm_config = vllm_config
|
||||
self.compilation_config = self.vllm_config.compilation_config
|
||||
self._allow_aot_compile = use_aot_compile
|
||||
enable_compile = enable_if is None or enable_if(vllm_config)
|
||||
# for CompilationMode.STOCK_TORCH_COMPILE , the upper level model runner
|
||||
# will handle the compilation, so we don't need to do anything here.
|
||||
@@ -544,7 +553,7 @@ def _support_torch_compile(
|
||||
ds_type = self.compilation_config.dynamic_shapes_config.type
|
||||
cache_dir = None
|
||||
aot_compilation_path = None
|
||||
if envs.VLLM_USE_AOT_COMPILE:
|
||||
if self._allow_aot_compile and envs.VLLM_USE_AOT_COMPILE:
|
||||
"""
|
||||
When using torch.compile in AOT mode, we store the cache artifacts
|
||||
under VLLM_CACHE_ROOT/torch_compile_cache/torch_aot_compile/{hash}
|
||||
@@ -597,7 +606,7 @@ def _support_torch_compile(
|
||||
|
||||
if self.compiled:
|
||||
assert (
|
||||
not envs.VLLM_USE_AOT_COMPILE
|
||||
not (self._allow_aot_compile and envs.VLLM_USE_AOT_COMPILE)
|
||||
or self.vllm_config.compilation_config.backend == "eager"
|
||||
)
|
||||
return TorchCompileWithNoGuardsWrapper.__call__(self, *args, **kwargs) # type: ignore[arg-type]
|
||||
@@ -680,7 +689,7 @@ def _support_torch_compile(
|
||||
torch.fx.experimental._config.patch(**fx_config_patches),
|
||||
torch._inductor.config.patch(**inductor_config_patches),
|
||||
):
|
||||
use_aot_compile = envs.VLLM_USE_AOT_COMPILE
|
||||
use_aot_compile = self._allow_aot_compile and envs.VLLM_USE_AOT_COMPILE
|
||||
if self.vllm_config.compilation_config.backend == "eager":
|
||||
logger.warning("Detected eager backend, disabling AOT compile.")
|
||||
use_aot_compile = False
|
||||
|
||||
@@ -1149,6 +1149,8 @@ class AllReduceFusionPass(VllmPatternMatcherPass):
|
||||
|
||||
# TODO: make BasePattern to inherit from VllmPatternReplacement
|
||||
class AiterAllreduceFusedRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
gemma_norm = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
epsilon: float,
|
||||
@@ -1170,7 +1172,8 @@ class AiterAllreduceFusedRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
input: torch.Tensor, weight: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
allreduce_output = tensor_model_parallel_all_reduce(input)
|
||||
rms = vllm.ir.ops.rms_norm(allreduce_output, weight, self.epsilon)
|
||||
norm_weight = weight.float() + 1.0 if self.gemma_norm else weight
|
||||
rms = vllm.ir.ops.rms_norm(allreduce_output, norm_weight, self.epsilon)
|
||||
|
||||
return rms, allreduce_output
|
||||
|
||||
@@ -1187,13 +1190,22 @@ class AiterAllreduceFusedRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
residual=residual,
|
||||
weight=weight.to(input.dtype),
|
||||
epsilon=self.epsilon,
|
||||
gemma_norm=self.gemma_norm,
|
||||
)
|
||||
return allreduce[0], allreduce[1]
|
||||
|
||||
return _replacement
|
||||
|
||||
|
||||
class AiterAllreduceFusedGemmaRMSNormPattern(AiterAllreduceFusedRMSNormPattern):
|
||||
"""Match all-reduce followed by GemmaRMSNorm without a residual."""
|
||||
|
||||
gemma_norm = True
|
||||
|
||||
|
||||
class AiterAllreduceFusedAddRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
gemma_norm = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
epsilon: float,
|
||||
@@ -1216,8 +1228,9 @@ class AiterAllreduceFusedAddRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
residual: torch.Tensor, input: torch.Tensor, weight: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
allreduce_output = tensor_model_parallel_all_reduce(input)
|
||||
norm_weight = weight.float() + 1.0 if self.gemma_norm else weight
|
||||
rms, residual = vllm.ir.ops.fused_add_rms_norm(
|
||||
allreduce_output, residual, weight, self.epsilon
|
||||
allreduce_output, residual, norm_weight, self.epsilon
|
||||
)
|
||||
return rms, residual
|
||||
|
||||
@@ -1233,12 +1246,19 @@ class AiterAllreduceFusedAddRMSNormPattern(BasePattern, VllmPatternReplacement):
|
||||
residual=residual,
|
||||
weight=weight.to(input.dtype),
|
||||
epsilon=self.epsilon,
|
||||
gemma_norm=self.gemma_norm,
|
||||
)
|
||||
return allreduce[0], allreduce[1]
|
||||
|
||||
return _replacement
|
||||
|
||||
|
||||
class AiterAllreduceFusedAddGemmaRMSNormPattern(AiterAllreduceFusedAddRMSNormPattern):
|
||||
"""Match all-reduce followed by fused-add GemmaRMSNorm."""
|
||||
|
||||
gemma_norm = True
|
||||
|
||||
|
||||
class AiterAllreduceFusedAddRMSNormOutputOnlyPattern(
|
||||
AiterAllreduceFusedAddRMSNormPattern
|
||||
):
|
||||
@@ -1267,6 +1287,14 @@ class AiterAllreduceFusedAddRMSNormOutputOnlyPattern(
|
||||
return _replacement
|
||||
|
||||
|
||||
class AiterAllreduceFusedAddGemmaRMSNormOutputOnlyPattern(
|
||||
AiterAllreduceFusedAddRMSNormOutputOnlyPattern
|
||||
):
|
||||
"""Match fused-add GemmaRMSNorm when its residual output is dead."""
|
||||
|
||||
gemma_norm = True
|
||||
|
||||
|
||||
class AiterAllreduceFusedRMSNormGroupQuantFP8Pattern(
|
||||
BasePattern, VllmPatternReplacement
|
||||
):
|
||||
@@ -1608,7 +1636,7 @@ class RocmAiterAllReduceFusionPass(VllmFusionPatternMatcherPass):
|
||||
# AR+RMS-only fusion runs first and consumes the all_reduce node,
|
||||
# leaving the trailing quant op stranded as an unfused kernel.
|
||||
# Register larger subgraphs first (DeepSeek indexer fan-out, then
|
||||
# quant-only AR+RMS+quant, then AR+RMS-only).
|
||||
# quant-only AR+RMS+quant, then Gemma AR+RMS, then AR+RMS-only).
|
||||
if supports_per_group_quant:
|
||||
self.register(
|
||||
AiterAllreduceFusedAddRMSNormGroupQuantWithIndexerPattern(
|
||||
@@ -1632,6 +1660,30 @@ class RocmAiterAllReduceFusionPass(VllmFusionPatternMatcherPass):
|
||||
)
|
||||
)
|
||||
|
||||
# Must stay above the non-Gemma AR+RMS patterns below, which would
|
||||
# otherwise match first.
|
||||
self.register(
|
||||
AiterAllreduceFusedGemmaRMSNormPattern(
|
||||
epsilon,
|
||||
self.model_dtype,
|
||||
self.device,
|
||||
)
|
||||
)
|
||||
self.register(
|
||||
AiterAllreduceFusedAddGemmaRMSNormPattern(
|
||||
epsilon,
|
||||
self.model_dtype,
|
||||
self.device,
|
||||
)
|
||||
)
|
||||
self.register(
|
||||
AiterAllreduceFusedAddGemmaRMSNormOutputOnlyPattern(
|
||||
epsilon,
|
||||
self.model_dtype,
|
||||
self.device,
|
||||
)
|
||||
)
|
||||
|
||||
self.register(
|
||||
AiterAllreduceFusedRMSNormPattern(
|
||||
epsilon,
|
||||
|
||||
@@ -481,8 +481,13 @@ class MatcherQuantFP8(MatcherCustomOp):
|
||||
|
||||
if self.quant_key.scale.static:
|
||||
assert scale is not None
|
||||
group_shape = self.quant_key.scale.group_shape
|
||||
_, result = auto_functionalized(
|
||||
self.QUANT_OP, result=result, input=input, scale=scale
|
||||
self.QUANT_OP,
|
||||
result=result,
|
||||
input=input,
|
||||
scale=scale,
|
||||
group_shape=[group_shape.row, group_shape.col],
|
||||
)
|
||||
return result, scale
|
||||
else:
|
||||
|
||||
@@ -85,6 +85,8 @@ class TorchCompileWithNoGuardsWrapper:
|
||||
return ctx.result
|
||||
return callable_fn(*args, **kwargs)
|
||||
|
||||
_allow_aot_compile: bool = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
compile_prefix: str = "",
|
||||
@@ -104,7 +106,10 @@ class TorchCompileWithNoGuardsWrapper:
|
||||
raise RuntimeError("Compilation mode cannot be NO_COMPILATION")
|
||||
|
||||
backend = vllm_config.compilation_config.init_backend(
|
||||
vllm_config, prefix=compile_prefix, is_encoder=is_encoder
|
||||
vllm_config,
|
||||
prefix=compile_prefix,
|
||||
is_encoder=is_encoder,
|
||||
use_aot_compile=self._allow_aot_compile,
|
||||
)
|
||||
options = {}
|
||||
|
||||
@@ -151,7 +156,7 @@ class TorchCompileWithNoGuardsWrapper:
|
||||
_apply_constrain_to_fx_strides_patch()
|
||||
|
||||
aot_context = nullcontext()
|
||||
if envs.VLLM_USE_AOT_COMPILE:
|
||||
if self._allow_aot_compile and envs.VLLM_USE_AOT_COMPILE:
|
||||
if hasattr(torch._dynamo.config, "enable_aot_compile"):
|
||||
aot_context = torch._dynamo.config.patch(enable_aot_compile=True)
|
||||
else:
|
||||
|
||||
@@ -61,6 +61,11 @@ class AttentionConfig:
|
||||
flash_attn_max_num_splits_for_cuda_graph: int = 32
|
||||
"""Flash Attention max number splits for cuda graph decode."""
|
||||
|
||||
tokenspeed_mla_min_split_kv: int = Field(default=1, ge=1, le=256)
|
||||
"""Minimum KV splits for TokenSpeed MLA decode. The default of 1 preserves
|
||||
automatic scheduling. Larger values request a split floor and may increase
|
||||
workspace memory. Only applies to the TokenSpeed MLA backend."""
|
||||
|
||||
tq_max_kv_splits_for_cuda_graph: int = 32
|
||||
"""TurboQuant max NUM_KV_SPLITS for cuda graph decode.
|
||||
Fixes the split count so grid dimensions are constant across captures,
|
||||
@@ -112,6 +117,15 @@ class AttentionConfig:
|
||||
When False (default), pure prefill batches use forward_mha when implemented.
|
||||
Set to True to always use the MQA path."""
|
||||
|
||||
sparse_mla_prefill_workspace_factor: int | None = Field(default=None, ge=2)
|
||||
"""Sparse MLA prefill workspace size, in multiples of `max_model_len`.
|
||||
FlashMLA sparse gathers a prefill step's context KV into this workspace and
|
||||
runs attention in more chunks when the step holds more. The sparse indexer's
|
||||
prefill K buffer is sized to fit in the same memory. Lower values return
|
||||
memory to the KV cache at long `max_model_len`; the minimum of 2 leaves room
|
||||
for a full-length request's context-parallel shard. If None, 5 when
|
||||
`max_model_len` is at most 256K tokens, else 2."""
|
||||
|
||||
flex_attn_block_m: int | None = None
|
||||
"""Triton kernel BLOCK_M tile size for flex attention.
|
||||
Must be a power of 2 >= 16. If None and VLLM_BATCH_INVARIANT=1,
|
||||
|
||||
+14
-15
@@ -121,6 +121,7 @@ class CacheConfig:
|
||||
|
||||
cache_dtype: CacheDType = "auto"
|
||||
"""Data type for kv cache storage. If "auto", will use model data type.
|
||||
An explicit float16 or bfloat16 must match the model data type.
|
||||
CUDA 11.8+ supports fp8 (=fp8_e4m3) and fp8_e5m2. ROCm (AMD GPU) supports
|
||||
fp8 (=fp8_e4m3). Intel Gaudi (HPU) supports fp8 (using fp8_inc).
|
||||
Some models (namely DeepSeekV3.2) default to fp8, set to bfloat16 to use
|
||||
@@ -176,8 +177,7 @@ class CacheConfig:
|
||||
page."""
|
||||
mamba_block_size: int | None = Field(default=None, gt=0)
|
||||
"""Size of a contiguous cache block in number of tokens for mamba cache.
|
||||
Can be set only when prefix caching is enabled.
|
||||
Value must be a multiple of 8 to align with causal_conv1d kernel."""
|
||||
Can be set only when prefix caching is enabled."""
|
||||
mamba_cache_dtype: MambaDType = "auto"
|
||||
"""The data type to use for the Mamba cache (both the conv as well as the
|
||||
ssm state). If set to 'auto', the data type will be inferred from the model
|
||||
@@ -187,19 +187,19 @@ class CacheConfig:
|
||||
still be controlled by mamba_cache_dtype). If set to 'auto', the data type
|
||||
for the ssm state will be determined by mamba_cache_dtype."""
|
||||
mamba_cache_mode: MambaCacheMode = "none"
|
||||
"""The cache strategy for Mamba layers:
|
||||
"""The cache strategy for Mamba layers, derived from `enable_prefix_caching`:
|
||||
|
||||
- "none": set when prefix caching is disabled.
|
||||
- "align": only cache the mamba state of the last token of each scheduler step and
|
||||
when the token is at position i * block_size. This is the default when prefix
|
||||
caching is enabled.
|
||||
- "none": prefix caching is disabled.
|
||||
- "align": prefix caching is enabled. Only cache the mamba state of the last
|
||||
token of each scheduler step and when the token is at position
|
||||
i * block_size.
|
||||
"""
|
||||
enable_mamba_shared_prefix_checkpoint: bool = False
|
||||
"""Also register a Mamba "align" checkpoint at the shared-prefix junction --
|
||||
where an EAGLE/MTP sibling was observed to resume -- instead of only at the
|
||||
prompt tail. Off by default; only takes effect with `mamba_cache_mode`
|
||||
"align", EAGLE on the Mamba group, and a prefix match unit smaller than the
|
||||
Mamba block size."""
|
||||
prompt tail. Off by default; only takes effect with prefix caching enabled,
|
||||
EAGLE on the Mamba group, and a prefix match unit smaller than the Mamba
|
||||
block size."""
|
||||
replayssm_buffer_len: int = Field(default=16, gt=0)
|
||||
"""ReplaySSM logical history length B for Mamba2. Triton uses B physical
|
||||
rows and FlashInfer uses B+T, where T is the target verification length.
|
||||
@@ -207,11 +207,10 @@ class CacheConfig:
|
||||
use_replayssm: bool = False
|
||||
"""Use the ReplaySSM Mamba2 decode kernel: cache recent SSM inputs and skip
|
||||
the per-step full-state store, writing the checkpoint back only on flush.
|
||||
Requires mamba_cache_mode 'none' or 'align' (prefix caching) and the Triton
|
||||
or FlashInfer mamba backend. Mamba2 speculative decode requires FlashInfer
|
||||
and mamba_cache_mode 'none'. In align mode flushes are most efficient when
|
||||
mamba_block_size is a multiple of replayssm_buffer_len, but this is not
|
||||
required."""
|
||||
Requires the Triton or FlashInfer mamba backend; FlashInfer does not support
|
||||
prefix caching yet. Mamba2 speculative decode requires FlashInfer. With
|
||||
prefix caching, flushes are most efficient when mamba_block_size is a
|
||||
multiple of replayssm_buffer_len, but this is not required."""
|
||||
use_recoverssm: bool = field(default=False, init=False)
|
||||
"""Whether Kimi-K3 KDA uses RecoverSSM speculative decode."""
|
||||
|
||||
|
||||
@@ -1085,6 +1085,7 @@ class CompilationConfig:
|
||||
vllm_config: "VllmConfig",
|
||||
prefix: str = "",
|
||||
is_encoder: bool = False,
|
||||
use_aot_compile: bool = True,
|
||||
) -> str | Callable:
|
||||
"""Initialize the backend for the compilation config from a vllm config.
|
||||
|
||||
@@ -1093,6 +1094,7 @@ class CompilationConfig:
|
||||
prefix: Cache directory prefix for this compiled module.
|
||||
is_encoder: Whether this module is used in an encoder (as
|
||||
opposed to a text backbone).
|
||||
use_aot_compile: Whether the module permits AOT and direct artifacts.
|
||||
|
||||
Returns:
|
||||
The backend for the compilation config.
|
||||
@@ -1124,7 +1126,12 @@ class CompilationConfig:
|
||||
|
||||
from vllm.compilation.backends import VllmBackend
|
||||
|
||||
return VllmBackend(vllm_config, prefix=prefix, is_encoder=is_encoder)
|
||||
return VllmBackend(
|
||||
vllm_config,
|
||||
prefix=prefix,
|
||||
is_encoder=is_encoder,
|
||||
use_aot_compile=use_aot_compile,
|
||||
)
|
||||
|
||||
def post_init_cudagraph_sizes(self) -> None:
|
||||
"""To complete the initialization after cudagraph related
|
||||
|
||||
@@ -55,6 +55,11 @@ class ECTransferConfig:
|
||||
"""The Python module path to dynamically load the EC connector from.
|
||||
Only supported in V1."""
|
||||
|
||||
mm_encoder_output_widths: dict[str, int] = field(default_factory=dict, init=False)
|
||||
"""Per-token width of the encoder output for each modality, measured by EC
|
||||
producers at startup. It can exceed the LM embedding width (e.g. DeepStack).
|
||||
"""
|
||||
|
||||
def compute_hash(self) -> str:
|
||||
"""WARNING: Whenever a new field is added to this config,
|
||||
ensure that it is included in the factors list if
|
||||
|
||||
@@ -71,6 +71,8 @@ class EngramConfig:
|
||||
|
||||
def verify_model_config(self, model_config: "ModelConfig | None") -> None:
|
||||
"""Reject Engram configuration for models without n-gram embeddings."""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
field = (
|
||||
_NGRAM_LAYER_FIELDS.get(model_config.architecture)
|
||||
if model_config is not None
|
||||
|
||||
@@ -291,6 +291,12 @@ class KernelConfig:
|
||||
enable_jit_warmup: bool = True
|
||||
"""If True, run JIT compile warmup during kernel warmup."""
|
||||
|
||||
monokernel: bool = False
|
||||
"""If True, run the eligible layers of decode steps on the model's
|
||||
MonoKernel: a persistent kernel that runs most or all of one decoder layer
|
||||
in a single launch (DeepSeek-V4.1 on MI355X). A deployment that cannot run
|
||||
it is refused at startup."""
|
||||
|
||||
moe_backend: MoEBackend = "auto"
|
||||
"""Backend for MoE expert computation kernels. Available options:
|
||||
|
||||
|
||||
+17
-10
@@ -310,12 +310,8 @@ class ModelConfig:
|
||||
window functionality of the model, capping to sliding window size. If the
|
||||
model does not support sliding window, this argument is ignored."""
|
||||
disable_cascade_attn: bool = True
|
||||
"""Disable cascade attention for V1. While cascade attention does not
|
||||
change the mathematical correctness, disabling it could be useful for
|
||||
preventing potential numerical issues. This defaults to True, so users
|
||||
must opt in to cascade attention by setting this to False. Even when this
|
||||
is set to False, cascade attention will only be used when the heuristic
|
||||
tells that it's beneficial."""
|
||||
"""Deprecated: cascade attention has been removed, so this has no effect.
|
||||
It will be removed in v0.33.0."""
|
||||
skip_tokenizer_init: bool = False
|
||||
"""Skip initialization of tokenizer and detokenizer. Expects valid
|
||||
`prompt_token_ids` and `None` for prompt from the input. The generated
|
||||
@@ -372,6 +368,9 @@ class ModelConfig:
|
||||
hip platforms are supported)."""
|
||||
sleep_preserve_parameter_names: list[str] = field(default_factory=list)
|
||||
"""Parameter-name globs to preserve across level-2 sleep.
|
||||
Use target globs for frozen Engram table weights and scales omitted by the
|
||||
trainer (e.g. ``*.engram.embed_tokens.weight*``).
|
||||
Use ``draft.<name>`` for draft-private parameters, or ``draft.*`` for all.
|
||||
The sender must omit these parameters; loaders must preserve their storage."""
|
||||
sleep_mode_backend: str = "cumem"
|
||||
"""Mechanism used to free and restore GPU state for sleep mode. ``"cumem"``
|
||||
@@ -508,6 +507,10 @@ class ModelConfig:
|
||||
# here early.
|
||||
if self.multimodal_config:
|
||||
factors["language_model_only"] = self.multimodal_config.language_model_only
|
||||
# Sizes Qwen3.5's M-RoPE cache.
|
||||
factors["video_pruning"] = (
|
||||
self.multimodal_config.is_multimodal_pruning_enabled()
|
||||
)
|
||||
return hash_factors(factors)
|
||||
|
||||
def _update_nested(
|
||||
@@ -1530,6 +1533,14 @@ class ModelConfig:
|
||||
self,
|
||||
parallel_config: ParallelConfig,
|
||||
) -> None:
|
||||
if parallel_config.enable_hc_sp and parallel_config.tensor_parallel_size > 1:
|
||||
if not current_platform.is_cuda():
|
||||
raise ValueError("--enable-hc-sp currently requires CUDA")
|
||||
if not self.registry.is_hc_sp_supported_model(self.architectures, self):
|
||||
raise ValueError("--enable-hc-sp is not supported for this model")
|
||||
if parallel_config.pipeline_parallel_size != 1:
|
||||
raise ValueError("--enable-hc-sp requires PP=1")
|
||||
|
||||
total_num_attention_heads = self.model_arch_config.total_num_attention_heads
|
||||
tensor_parallel_size = parallel_config.tensor_parallel_size
|
||||
if total_num_attention_heads % tensor_parallel_size != 0:
|
||||
@@ -2027,10 +2038,6 @@ class ModelConfig:
|
||||
def has_inner_state(self):
|
||||
return self._model_info.has_inner_state
|
||||
|
||||
@property
|
||||
def supports_mamba_prefix_caching(self) -> bool:
|
||||
return self._model_info.supports_mamba_prefix_caching
|
||||
|
||||
@property
|
||||
def supports_replayssm(self) -> bool:
|
||||
return self._model_info.supports_replayssm
|
||||
|
||||
+35
-1
@@ -181,6 +181,11 @@ class ParallelConfig:
|
||||
--data-parallel-start-rank."""
|
||||
is_moe_model: bool | None = None
|
||||
"""Whether the deployed model is MoE (if known)."""
|
||||
enable_hc_sp: bool = False
|
||||
"""Enable sequence parallelism for HyperConnection (HC) computation.
|
||||
Currently supported by Qwen4Exp on CUDA with TP>1 and PP=1 (ignored when TP=1).
|
||||
Does not change MoE parallelism. MoE SP may enable HC SP independently of this flag.
|
||||
"""
|
||||
enable_expert_parallel: bool = False
|
||||
"""Use expert parallelism instead of tensor parallelism for MoE layers."""
|
||||
enable_batch_sharded_sampling: bool | None = None
|
||||
@@ -235,6 +240,15 @@ class ParallelConfig:
|
||||
disable_custom_all_reduce: bool = False
|
||||
"""Disable the custom all-reduce kernel and fall back to NCCL."""
|
||||
|
||||
enable_shm_tensor_arena: bool = False
|
||||
"""Route large CPU tensors (e.g. multimodal ``pixel_values``) in the
|
||||
engine→worker broadcast through a zero-copy shared-memory arena instead of
|
||||
sending a copy to every reader. **Experimental**: may be reconciled with
|
||||
vLLM's existing multimodal shm tensor caching in a future release. Opt-in;
|
||||
most beneficial for multimodal serving with large images and tensor
|
||||
parallelism. Active only when all queue readers are node-local; reserves
|
||||
slots in ``/dev/shm``."""
|
||||
|
||||
enable_elastic_ep: bool = False
|
||||
"""Enable elastic expert parallelism with stateless NCCL groups for DP/EP."""
|
||||
elastic_ep_max_dp_size: int = Field(default=None, ge=1) # type: ignore[assignment]
|
||||
@@ -295,7 +309,10 @@ class ParallelConfig:
|
||||
"""The full name of the worker extension class to use. The worker extension
|
||||
class is dynamically inherited by the worker class. This is used to inject
|
||||
new attributes and methods to the worker class for use in collective_rpc
|
||||
calls."""
|
||||
calls. It may also define `init_worker_extension(self)`, called after
|
||||
device and distributed initialization but before model loading, and
|
||||
`destroy_worker_extension(self)`, called (best-effort) before the worker
|
||||
shuts down."""
|
||||
master_addr: str = "127.0.0.1"
|
||||
"""distributed master address for multi-node distributed
|
||||
inference when distributed_executor_backend is mp."""
|
||||
@@ -821,6 +838,22 @@ class ParallelConfig:
|
||||
def local_world_size(self) -> int:
|
||||
return self.world_size // self.nnodes_within_dp
|
||||
|
||||
def get_local_gpu_index(
|
||||
self, local_rank: int, dp_local_rank: int | None = None
|
||||
) -> int:
|
||||
"""Map a worker's local rank to its host-local logical GPU index."""
|
||||
if (
|
||||
self.distributed_executor_backend not in ("ray", "external_launcher")
|
||||
and self.data_parallel_backend != "ray"
|
||||
and self.nnodes_within_dp == 1
|
||||
):
|
||||
if dp_local_rank is None:
|
||||
dp_local_rank = self.data_parallel_rank_local
|
||||
if dp_local_rank is None:
|
||||
dp_local_rank = self.data_parallel_index
|
||||
return local_rank + dp_local_rank * self.world_size
|
||||
return local_rank
|
||||
|
||||
@staticmethod
|
||||
def has_unfinished_dp(dp_group: ProcessGroup, has_unfinished: bool) -> bool:
|
||||
tensor = torch.tensor([has_unfinished], dtype=torch.int32, device="cpu")
|
||||
@@ -901,6 +934,7 @@ class ParallelConfig:
|
||||
"nnodes",
|
||||
"max_parallel_loading_workers",
|
||||
"disable_custom_all_reduce",
|
||||
"enable_shm_tensor_arena",
|
||||
"ray_workers_use_nsight",
|
||||
"ray_runtime_env",
|
||||
"placement_group",
|
||||
|
||||
@@ -67,7 +67,7 @@ class PoolerConfig:
|
||||
"""
|
||||
Whether the engine-side late-interaction scorer may use the fused
|
||||
flash-maxsim Triton kernel. Disabled automatically when the API server
|
||||
is started with `--no-enable-flash-late-interaction`; the reference
|
||||
is started with `--disable-flash-late-interaction`; the reference
|
||||
scorer is used instead.
|
||||
"""
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class SchedulerConfig:
|
||||
In real usage, this should be set in `EngineArgs.create_engine_config`.
|
||||
"""
|
||||
|
||||
max_num_scheduled_tokens: int | None = Field(default=None, ge=0)
|
||||
max_num_scheduled_tokens: int | None = Field(default=None, ge=1)
|
||||
"""Maximum number of tokens that the scheduler may issue in a single iteration.
|
||||
|
||||
This is usually equal to max_num_batched_tokens, but can be smaller in cases
|
||||
|
||||
+18
-54
@@ -72,8 +72,6 @@ EagleModelTypes = Literal[
|
||||
]
|
||||
SpeculativeMethod = Literal[
|
||||
"ngram",
|
||||
"medusa",
|
||||
"mlp_speculator",
|
||||
"draft_model",
|
||||
"suffix",
|
||||
"custom_class",
|
||||
@@ -1058,9 +1056,16 @@ class SpeculativeConfig:
|
||||
)
|
||||
if hf_config.model_type == "glm5_next":
|
||||
hf_config.model_type = "glm5_next_mtp"
|
||||
n_predict = hf_config.get_text_config().num_nextn_predict_layers
|
||||
text_config = hf_config.get_text_config()
|
||||
share_mtp_indices = getattr(
|
||||
text_config, "index_share_for_mtp_iteration", False
|
||||
)
|
||||
hf_config.update(
|
||||
{"n_predict": n_predict, "architectures": ["Glm5NextMTPModel"]}
|
||||
{
|
||||
"n_predict": text_config.num_nextn_predict_layers,
|
||||
"architectures": ["Glm5NextMTPModel"],
|
||||
"index_share_for_mtp_iteration": share_mtp_indices,
|
||||
}
|
||||
)
|
||||
|
||||
return hf_config
|
||||
@@ -1265,20 +1270,12 @@ class SpeculativeConfig:
|
||||
self.prompt_lookup_min = 0
|
||||
|
||||
if self.model is not None:
|
||||
# Old-format Medusa checkpoints (e.g. FasterDecoding/medusa-*)
|
||||
# lack a model_type key in config.json, so AutoConfig cannot
|
||||
# detect them. When the method is explicitly "medusa", inject
|
||||
# model_type so MedusaConfig.from_pretrained is used instead.
|
||||
draft_hf_overrides: HfOverrides
|
||||
if self.method == "medusa":
|
||||
draft_hf_overrides = {"model_type": "medusa"}
|
||||
else:
|
||||
# Compose any callable hf_overrides set on the target so the
|
||||
# draft config receives the same transform (e.g. the test
|
||||
# shrink). Dict overrides stay target-only.
|
||||
draft_hf_overrides = SpeculativeConfig.compose_draft_hf_overrides(
|
||||
self.target_model_config.hf_overrides
|
||||
)
|
||||
# Compose any callable hf_overrides set on the target so the
|
||||
# draft config receives the same transform (e.g. the test
|
||||
# shrink). Dict overrides stay target-only.
|
||||
draft_hf_overrides = SpeculativeConfig.compose_draft_hf_overrides(
|
||||
self.target_model_config.hf_overrides
|
||||
)
|
||||
self.draft_model_config = ModelConfig(
|
||||
model=self.model,
|
||||
runner="draft",
|
||||
@@ -1305,17 +1302,6 @@ class SpeculativeConfig:
|
||||
config_format=self.target_model_config.config_format,
|
||||
)
|
||||
|
||||
# Old-format Medusa checkpoints (e.g. FasterDecoding/medusa-*)
|
||||
# omit vocab_size in config.json, so MedusaConfig falls back to
|
||||
# its default (32001). Align with the target model's vocab size
|
||||
# to avoid shape mismatches when loading LM-head weights.
|
||||
if self.method == "medusa":
|
||||
target_vocab = self.target_model_config.hf_config.vocab_size
|
||||
draft_hf = self.draft_model_config.hf_config
|
||||
if draft_hf.vocab_size != target_vocab:
|
||||
draft_hf.vocab_size = target_vocab
|
||||
draft_hf.truncated_vocab_size = target_vocab
|
||||
|
||||
# Automatically detect the method
|
||||
if self.method in ("eagle", "eagle3", "dflash", "dspark"):
|
||||
pass
|
||||
@@ -1346,10 +1332,6 @@ class SpeculativeConfig:
|
||||
)
|
||||
):
|
||||
self.method = "dspark"
|
||||
elif self.draft_model_config.hf_config.model_type == "medusa":
|
||||
self.method = "medusa"
|
||||
elif self.draft_model_config.hf_config.model_type == "mlp_speculator":
|
||||
self.method = "mlp_speculator"
|
||||
elif self.draft_model_config.hf_config.model_type in get_args(
|
||||
MTPModelTypes
|
||||
):
|
||||
@@ -1461,13 +1443,6 @@ class SpeculativeConfig:
|
||||
if self.method in ("dflash", "dspark"):
|
||||
self.parallel_drafting = True
|
||||
|
||||
if self.num_speculative_tokens is not None and hasattr(
|
||||
self.draft_model_config.hf_config, "num_lookahead_tokens"
|
||||
):
|
||||
self.draft_model_config.hf_config.num_lookahead_tokens = (
|
||||
self.num_speculative_tokens
|
||||
)
|
||||
|
||||
n_predict = getattr(
|
||||
self.draft_model_config.hf_config, "n_predict", None
|
||||
)
|
||||
@@ -1543,7 +1518,6 @@ class SpeculativeConfig:
|
||||
SpeculativeConfig._verify_and_get_draft_tp(
|
||||
self.target_parallel_config,
|
||||
self.draft_tensor_parallel_size,
|
||||
self.draft_model_config.hf_config,
|
||||
)
|
||||
)
|
||||
self.draft_model_config.max_model_len = (
|
||||
@@ -1705,7 +1679,6 @@ class SpeculativeConfig:
|
||||
def _verify_and_get_draft_tp(
|
||||
target_parallel_config: ParallelConfig,
|
||||
speculative_draft_tensor_parallel_size: int | None,
|
||||
draft_hf_config: PreTrainedConfig,
|
||||
) -> int:
|
||||
"""Verifies and adjusts the tensor parallel size for a draft model
|
||||
specified using speculative_draft_tensor_parallel_size.
|
||||
@@ -1713,18 +1686,9 @@ class SpeculativeConfig:
|
||||
# If speculative_draft_tensor_parallel_size is unset then set it
|
||||
# appropriately else verify that it is set correctly.
|
||||
if speculative_draft_tensor_parallel_size is None:
|
||||
if draft_hf_config.model_type == "mlp_speculator":
|
||||
speculative_draft_tensor_parallel_size = 1
|
||||
if target_parallel_config.tensor_parallel_size > 1:
|
||||
logger.warning(
|
||||
"%s cannot currently be run with tp>1; "
|
||||
"setting speculative_draft_tensor_parallel_size=1",
|
||||
draft_hf_config.model_type,
|
||||
)
|
||||
else:
|
||||
speculative_draft_tensor_parallel_size = (
|
||||
target_parallel_config.tensor_parallel_size
|
||||
)
|
||||
speculative_draft_tensor_parallel_size = (
|
||||
target_parallel_config.tensor_parallel_size
|
||||
)
|
||||
elif speculative_draft_tensor_parallel_size not in (
|
||||
1,
|
||||
target_parallel_config.tensor_parallel_size,
|
||||
|
||||
+87
-104
@@ -78,14 +78,9 @@ _QWEN4EXP_RECOVERSSM_ARCHS = (
|
||||
"Qwen4ExpMTP",
|
||||
)
|
||||
|
||||
# TODO(rocm): These models are either unsupported by MRV2 or slower with
|
||||
# MRV2 on AMD GPUs.
|
||||
ROCM_DEFAULT_MRV1_ARCHITECTURES = frozenset(
|
||||
{"DeepseekV32ForCausalLM", "DeepseekV4ForCausalLM", "GlmMoeDsaForCausalLM"}
|
||||
)
|
||||
|
||||
DEFAULT_BREAKABLE_CUDAGRAPH_ARCHITECTURES = frozenset(
|
||||
{
|
||||
"AliceAIForCausalLM",
|
||||
"DeepseekV32MTPModel",
|
||||
"DeepseekV32ForCausalLM",
|
||||
"DeepseekV4ForCausalLM",
|
||||
@@ -734,30 +729,6 @@ class VllmConfig:
|
||||
if use_v2_model_runner is not None:
|
||||
return use_v2_model_runner
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
model_config = self.model_config
|
||||
if model_config is not None and current_platform.is_rocm():
|
||||
architectures = getattr(model_config, "architectures", ())
|
||||
if any(arch in ROCM_DEFAULT_MRV1_ARCHITECTURES for arch in architectures):
|
||||
# This default is a speed preference, not a claim that V1 can
|
||||
# serve the config, so it yields where V1 cannot. It yields by
|
||||
# falling through to the checks below, not by selecting V2.
|
||||
v1_unsupported = self._get_v1_model_runner_unsupported_features()
|
||||
if not v1_unsupported:
|
||||
logger.warning_once(
|
||||
"Defaulting to V1 model runner on ROCm for model "
|
||||
"architectures: %s",
|
||||
", ".join(architectures),
|
||||
)
|
||||
return False
|
||||
logger.warning_once(
|
||||
"Skipping the ROCm V1 model runner default for %s: V1 does "
|
||||
"not support %s.",
|
||||
", ".join(architectures),
|
||||
", ".join(v1_unsupported),
|
||||
)
|
||||
|
||||
if not HAS_TRITON:
|
||||
logger.warning_once(
|
||||
"Model Runner V2 requires Triton; using the V1 model runner instead."
|
||||
@@ -1236,6 +1207,21 @@ class VllmConfig:
|
||||
):
|
||||
return
|
||||
|
||||
if self.model_config is not None and self.model_config.enable_sleep_mode:
|
||||
# Lazy import to avoid circular dependencies
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import (
|
||||
KVConnectorFactory,
|
||||
)
|
||||
|
||||
connector_cls = KVConnectorFactory.get_connector_class(
|
||||
self.kv_transfer_config
|
||||
)
|
||||
if not connector_cls.supports_sleep_mode(self.kv_transfer_config):
|
||||
raise ValueError(
|
||||
f"{self.kv_transfer_config.kv_connector} does not support "
|
||||
"sleep mode."
|
||||
)
|
||||
|
||||
# PyTorch's expandable_segments allocator uses CUDA VMM, which can
|
||||
# remap a virtual address range to different physical pages over the
|
||||
# engine's lifetime. KV connectors that pin KV cache memory (e.g.
|
||||
@@ -1448,6 +1434,24 @@ class VllmConfig:
|
||||
self.engram_config.verify_parallel_config(self.parallel_config)
|
||||
logger.info_once("Resolved Engram configuration: %s", str(self.engram_config))
|
||||
|
||||
def _reject_mismatched_float_kv_cache(self) -> None:
|
||||
"""Reject an explicit float16/bfloat16 KV dtype that differs from the model."""
|
||||
cache_dtype = self.cache_config.cache_dtype
|
||||
if self.model_config is None or cache_dtype not in ("float16", "bfloat16"):
|
||||
return
|
||||
model_dtype = str(self.model_config.dtype).removeprefix("torch.")
|
||||
if model_dtype == cache_dtype:
|
||||
return
|
||||
allowed = (
|
||||
f"`auto` or `{model_dtype}`"
|
||||
if model_dtype in ("float16", "bfloat16")
|
||||
else "`auto`"
|
||||
)
|
||||
raise ValueError(
|
||||
f'kv_cache_dtype="{cache_dtype}" is incompatible with '
|
||||
f'dtype="{model_dtype}". Please set `--kv-cache-dtype` to {allowed}.'
|
||||
)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Verify configs are valid & consistent with each other."""
|
||||
# To give each torch profile run a unique instance name.
|
||||
@@ -1478,6 +1482,7 @@ class VllmConfig:
|
||||
logger.info_once("Performance mode set to '%s'.", self.performance_mode)
|
||||
|
||||
self.try_verify_and_update_config()
|
||||
self._reject_mismatched_float_kv_cache()
|
||||
self._resolve_and_verify_engram_config()
|
||||
|
||||
self._check_supports_watermarking()
|
||||
@@ -1569,8 +1574,6 @@ class VllmConfig:
|
||||
self.quant_config.use_deep_gemm = False
|
||||
logger.warning_once(
|
||||
"Auto-disabled DeepGemm for model_type=%s on Blackwell. "
|
||||
"DeepGemm E8M0 scale format causes accuracy degradation "
|
||||
"for this architecture. Falling back to CUTLASS. "
|
||||
"To disable DeepGemm globally, set VLLM_USE_DEEP_GEMM=0.",
|
||||
model_type,
|
||||
)
|
||||
@@ -1693,18 +1696,6 @@ class VllmConfig:
|
||||
else:
|
||||
self.parallel_config.disable_nccl_for_dp_synchronization = False
|
||||
|
||||
if (
|
||||
self.speculative_config is not None
|
||||
and self.scheduler_config.async_scheduling
|
||||
and self.model_config is not None
|
||||
and not self.model_config.disable_cascade_attn
|
||||
):
|
||||
logger.warning_once(
|
||||
"Disabling cascade attention (not yet compatible with "
|
||||
"async speculative decoding).",
|
||||
)
|
||||
self.model_config.disable_cascade_attn = True
|
||||
|
||||
if (
|
||||
self.observability_config.per_request_spec_decode_metrics != "none"
|
||||
and self.speculative_config is None
|
||||
@@ -1836,6 +1827,16 @@ class VllmConfig:
|
||||
self._maybe_disable_dynamic_sd_for_data_parallel()
|
||||
self._maybe_override_dynamic_sd_cudagraph_mode()
|
||||
|
||||
if (
|
||||
self.attention_config.sparse_mla_prefill_workspace_factor is None
|
||||
and self.model_config is not None
|
||||
):
|
||||
# Resolved once: KV cache auto-fit can lower max_model_len later, and
|
||||
# factor * max_model_len must stay within the workspace reserved at init.
|
||||
self.attention_config.sparse_mla_prefill_workspace_factor = (
|
||||
5 if self.model_config.max_model_len <= 256 * 1024 else 2
|
||||
)
|
||||
|
||||
if (
|
||||
self.attention_config.hisparse_config is None
|
||||
and self.kv_transfer_config is not None
|
||||
@@ -2127,57 +2128,45 @@ class VllmConfig:
|
||||
)
|
||||
|
||||
# final check of cudagraph mode after all possible updates
|
||||
if current_platform.is_cuda_alike():
|
||||
if (
|
||||
self.compilation_config.cudagraph_mode.has_full_cudagraphs()
|
||||
and self.model_config is not None
|
||||
and not self.model_config.disable_cascade_attn
|
||||
and not self.compilation_config.cudagraph_mode.has_piecewise_cudagraphs() # noqa: E501
|
||||
):
|
||||
logger.warning_once(
|
||||
"No piecewise cudagraph for executing cascade attention. "
|
||||
"Will fall back to eager execution if a batch runs into "
|
||||
"cascade attentions."
|
||||
)
|
||||
|
||||
if self.compilation_config.cudagraph_mode.requires_piecewise_compilation():
|
||||
assert (
|
||||
self.compilation_config.mode == CompilationMode.VLLM_COMPILE
|
||||
or envs.VLLM_USE_BREAKABLE_CUDAGRAPH
|
||||
), (
|
||||
"Compilation mode should be CompilationMode.VLLM_COMPILE "
|
||||
"when cudagraph_mode piecewise cudagraphs is used, "
|
||||
f"cudagraph_mode={self.compilation_config.cudagraph_mode}"
|
||||
)
|
||||
if (
|
||||
self.model_config
|
||||
and envs.VLLM_BATCH_INVARIANT
|
||||
and not self.model_config.disable_cascade_attn
|
||||
current_platform.is_cuda_alike()
|
||||
and self.compilation_config.cudagraph_mode.requires_piecewise_compilation()
|
||||
):
|
||||
self.model_config.disable_cascade_attn = True
|
||||
logger.warning_once(
|
||||
"Disabling cascade attention when VLLM_BATCH_INVARIANT is enabled.",
|
||||
assert (
|
||||
self.compilation_config.mode == CompilationMode.VLLM_COMPILE
|
||||
or envs.VLLM_USE_BREAKABLE_CUDAGRAPH
|
||||
), (
|
||||
"Compilation mode should be CompilationMode.VLLM_COMPILE "
|
||||
"when cudagraph_mode piecewise cudagraphs is used, "
|
||||
f"cudagraph_mode={self.compilation_config.cudagraph_mode}"
|
||||
)
|
||||
|
||||
if self.parallel_config.use_ubatching:
|
||||
a2a_backend = self.parallel_config.all2all_backend
|
||||
assert a2a_backend in [
|
||||
"deepep_low_latency",
|
||||
"deepep_high_throughput",
|
||||
"nixl_ep",
|
||||
], (
|
||||
"Microbatching currently only supports the deepep_low_latency, "
|
||||
"deepep_high_throughput, and nixl_ep all2all backends. "
|
||||
f"{a2a_backend} is not supported. To fix use "
|
||||
"--all2all-backend=deepep_low_latency, "
|
||||
"--all2all-backend=deepep_high_throughput, or "
|
||||
"--all2all-backend=nixl_ep and install the matching kernels."
|
||||
if current_platform.is_rocm():
|
||||
supported_backends = [
|
||||
"deepep_low_latency",
|
||||
"deepep_high_throughput",
|
||||
"nixl_ep",
|
||||
# The naive DP/EP prepare/finalize runs its all-gather /
|
||||
# reduce-scatter on the comm stream under DBO.
|
||||
"allgather_reducescatter",
|
||||
]
|
||||
else:
|
||||
# CUDA and other platforms.
|
||||
supported_backends = [
|
||||
"deepep_low_latency",
|
||||
"deepep_high_throughput",
|
||||
"nixl_ep",
|
||||
]
|
||||
assert a2a_backend in supported_backends, (
|
||||
"Microbatching currently only supports the "
|
||||
f"{', '.join(supported_backends)} all2all backends on this "
|
||||
f"platform. {a2a_backend} is not supported. To fix use one of "
|
||||
f"{', '.join('--all2all-backend=' + b for b in supported_backends)}"
|
||||
" and install the matching kernels."
|
||||
)
|
||||
|
||||
if not self.model_config.disable_cascade_attn:
|
||||
self.model_config.disable_cascade_attn = True
|
||||
logger.warning_once("Disabling cascade attention when DBO is enabled.")
|
||||
|
||||
if not self.instance_id:
|
||||
self.instance_id = random_uuid()[:5]
|
||||
|
||||
@@ -2196,10 +2185,10 @@ class VllmConfig:
|
||||
self._verify_aux_output_compatibility()
|
||||
|
||||
# Hybrid KV cache manager (HMA) runtime rules:
|
||||
# - Explicit enable (--no-disable-kv-cache-manager): error if runtime
|
||||
# - Explicit enable (--enable-hybrid-kv-cache-manager): error if runtime
|
||||
# disables it
|
||||
# - No preference: auto-disable for unsupported features or connector configs
|
||||
# - Explicit disable (--disable-kv-cache-manager): always respect it
|
||||
# - Explicit disable (--disable-hybrid-kv-cache-manager): always respect it
|
||||
need_disable_hybrid_kv_cache_manager = False
|
||||
# logger should only print warning message for hybrid models. As we
|
||||
# can't know whether the model is hybrid or not now, so we don't log
|
||||
@@ -2260,7 +2249,7 @@ class VllmConfig:
|
||||
raise ValueError(
|
||||
"Hybrid KV cache manager was explicitly enabled but is not "
|
||||
"supported in this configuration. Consider omitting the "
|
||||
"--no-disable-hybrid-kv-cache-manager flag to let vLLM decide"
|
||||
"--enable-hybrid-kv-cache-manager flag to let vLLM decide"
|
||||
" automatically."
|
||||
)
|
||||
|
||||
@@ -2987,12 +2976,7 @@ class VllmConfig:
|
||||
unsupported.append("pipeline parallelism with external_launcher")
|
||||
|
||||
if speculative_config is not None:
|
||||
if speculative_config.method in (
|
||||
"suffix",
|
||||
"medusa",
|
||||
"mlp_speculator",
|
||||
"custom_class",
|
||||
):
|
||||
if speculative_config.method in ("suffix", "custom_class"):
|
||||
unsupported.append(f"speculative method '{speculative_config.method}'")
|
||||
|
||||
# V2 EagleSpeculator does not support parallel_drafting (for P-Eagle).
|
||||
@@ -3394,9 +3378,8 @@ class VllmConfig:
|
||||
self.model_config is not None
|
||||
and self.model_config.architecture in _QWEN4EXP_RECOVERSSM_ARCHS
|
||||
)
|
||||
self.cache_config.use_recoverssm = (
|
||||
self.num_speculative_tokens > 0
|
||||
and (is_kda_model or is_qwen4exp_recoverssm_model)
|
||||
self.cache_config.use_recoverssm = self.num_speculative_tokens > 0 and (
|
||||
is_kda_model or is_qwen4exp_recoverssm_model
|
||||
)
|
||||
use_mamba_replayssm_spec = (
|
||||
self.num_speculative_tokens > 0 and not self.cache_config.use_recoverssm
|
||||
@@ -3445,7 +3428,7 @@ class VllmConfig:
|
||||
and not self.use_v2_model_runner
|
||||
):
|
||||
raise ValueError(
|
||||
"RecoverSSM with align mode requires VLLM_USE_V2_MODEL_RUNNER=1"
|
||||
"RecoverSSM with prefix caching requires VLLM_USE_V2_MODEL_RUNNER=1"
|
||||
)
|
||||
if self.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError(
|
||||
@@ -3456,8 +3439,8 @@ class VllmConfig:
|
||||
elif use_mamba_replayssm_spec:
|
||||
if self.cache_config.mamba_cache_mode != "none":
|
||||
raise ValueError(
|
||||
"FlashInfer ReplaySSM speculative decoding requires "
|
||||
"--mamba-cache-mode none"
|
||||
"FlashInfer ReplaySSM speculative decoding does not support "
|
||||
"prefix caching; use --disable-prefix-caching"
|
||||
)
|
||||
query_len = 1 + self.num_speculative_tokens
|
||||
if self.cache_config.replayssm_buffer_len < query_len:
|
||||
@@ -3475,8 +3458,8 @@ class VllmConfig:
|
||||
elif self.mamba_config.backend == MambaBackendEnum.FLASHINFER:
|
||||
if self.cache_config.mamba_cache_mode == "align":
|
||||
raise ValueError(
|
||||
"FlashInfer ReplaySSM does not support "
|
||||
"--mamba-cache-mode align yet; use none"
|
||||
"FlashInfer ReplaySSM does not support prefix caching yet; "
|
||||
"use --disable-prefix-caching"
|
||||
)
|
||||
elif self.mamba_config.backend != MambaBackendEnum.TRITON:
|
||||
raise ValueError(
|
||||
|
||||
+57
-8
@@ -3,6 +3,7 @@
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Coroutine, Mapping, MutableMapping
|
||||
from pathlib import Path
|
||||
@@ -60,6 +61,33 @@ class MediaDownloadSizeExceededError(ValueError):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class MediaRequestDownloadSizeExceededError(ValueError):
|
||||
"""Raised when all HTTP media downloads in one request exceed the limit."""
|
||||
|
||||
|
||||
class MediaRequestDownloadBudget:
|
||||
"""Thread-safe total of HTTP media bytes received for one request."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.used = 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def charge(self, size: int) -> None:
|
||||
limit_mb = envs.VLLM_MAX_MEDIA_REQUEST_DOWNLOAD_SIZE_MB
|
||||
if limit_mb <= 0:
|
||||
return
|
||||
limit = limit_mb * MiB_bytes
|
||||
with self._lock:
|
||||
received = self.used + size
|
||||
if received > limit:
|
||||
raise MediaRequestDownloadSizeExceededError(
|
||||
"Request media downloads exceed "
|
||||
f"VLLM_MAX_MEDIA_REQUEST_DOWNLOAD_SIZE_MB={limit_mb:g} "
|
||||
f"({received} bytes received)."
|
||||
)
|
||||
self.used = received
|
||||
|
||||
|
||||
def _get_media_download_limit_bytes() -> int | None:
|
||||
max_size_mb = envs.VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB
|
||||
if max_size_mb <= 0:
|
||||
@@ -105,19 +133,26 @@ def _append_chunk(
|
||||
received_bytes: int,
|
||||
max_bytes: int | None,
|
||||
media_download_limit: bool,
|
||||
request_budget: MediaRequestDownloadBudget | None = None,
|
||||
) -> int:
|
||||
if not chunk:
|
||||
return received_bytes
|
||||
received_bytes += len(chunk)
|
||||
if max_bytes is not None and received_bytes > max_bytes:
|
||||
_raise_size_exceeded(max_bytes, received_bytes, media_download_limit)
|
||||
if request_budget is not None:
|
||||
request_budget.charge(len(chunk))
|
||||
chunks.append(chunk)
|
||||
return received_bytes
|
||||
|
||||
|
||||
def _read_response_bytes(response: requests.Response, max_bytes: int | None) -> bytes:
|
||||
def _read_response_bytes(
|
||||
response: requests.Response,
|
||||
max_bytes: int | None,
|
||||
request_budget: MediaRequestDownloadBudget | None = None,
|
||||
) -> bytes:
|
||||
max_bytes, media_download_limit = _get_response_size_limit(max_bytes)
|
||||
if max_bytes is None:
|
||||
if max_bytes is None and request_budget is None:
|
||||
return response.content
|
||||
|
||||
_check_content_length(
|
||||
@@ -129,16 +164,23 @@ def _read_response_bytes(response: requests.Response, max_bytes: int | None) ->
|
||||
received_bytes = 0
|
||||
for chunk in response.iter_content(_RESPONSE_READ_CHUNK_SIZE):
|
||||
received_bytes = _append_chunk(
|
||||
chunks, chunk, received_bytes, max_bytes, media_download_limit
|
||||
chunks,
|
||||
chunk,
|
||||
received_bytes,
|
||||
max_bytes,
|
||||
media_download_limit,
|
||||
request_budget,
|
||||
)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
async def _async_read_response_bytes(
|
||||
response: aiohttp.ClientResponse, max_bytes: int | None
|
||||
response: aiohttp.ClientResponse,
|
||||
max_bytes: int | None,
|
||||
request_budget: MediaRequestDownloadBudget | None = None,
|
||||
) -> bytes:
|
||||
max_bytes, media_download_limit = _get_response_size_limit(max_bytes)
|
||||
if max_bytes is None:
|
||||
if max_bytes is None and request_budget is None:
|
||||
return await response.read()
|
||||
|
||||
_check_content_length(response.content_length, max_bytes, media_download_limit)
|
||||
@@ -146,7 +188,12 @@ async def _async_read_response_bytes(
|
||||
received_bytes = 0
|
||||
async for chunk in response.content.iter_chunked(_RESPONSE_READ_CHUNK_SIZE):
|
||||
received_bytes = _append_chunk(
|
||||
chunks, chunk, received_bytes, max_bytes, media_download_limit
|
||||
chunks,
|
||||
chunk,
|
||||
received_bytes,
|
||||
max_bytes,
|
||||
media_download_limit,
|
||||
request_budget,
|
||||
)
|
||||
return b"".join(chunks)
|
||||
|
||||
@@ -407,6 +454,7 @@ class HTTPConnection:
|
||||
timeout: float | None = None,
|
||||
allow_redirects: bool = True,
|
||||
max_bytes: int | None = None,
|
||||
request_budget: MediaRequestDownloadBudget | None = None,
|
||||
) -> bytes:
|
||||
with self.get_response(
|
||||
url,
|
||||
@@ -416,7 +464,7 @@ class HTTPConnection:
|
||||
) as r:
|
||||
r.raise_for_status()
|
||||
|
||||
return _read_response_bytes(r, max_bytes)
|
||||
return _read_response_bytes(r, max_bytes, request_budget)
|
||||
|
||||
@_async_retry
|
||||
async def async_get_bytes(
|
||||
@@ -426,6 +474,7 @@ class HTTPConnection:
|
||||
timeout: float | None = None,
|
||||
allow_redirects: bool = True,
|
||||
max_bytes: int | None = None,
|
||||
request_budget: MediaRequestDownloadBudget | None = None,
|
||||
) -> bytes:
|
||||
async with await self.get_async_response(
|
||||
url,
|
||||
@@ -434,7 +483,7 @@ class HTTPConnection:
|
||||
) as r:
|
||||
r.raise_for_status()
|
||||
|
||||
return await _async_read_response_bytes(r, max_bytes)
|
||||
return await _async_read_response_bytes(r, max_bytes, request_budget)
|
||||
|
||||
def get_text(self, url: str, *, timeout: float | None = None) -> str:
|
||||
with self.get_response(url, timeout=timeout) as r:
|
||||
|
||||
@@ -146,6 +146,7 @@ class XpuMemAllocator:
|
||||
self.pointer_to_data: dict[int, AllocationData] = {}
|
||||
self.current_tag: str = XpuMemAllocator.default_tag
|
||||
self.allocator_and_pools: dict[str, list[Any]] = {}
|
||||
self._pending_allocators: list[Any] = []
|
||||
self.python_malloc_callback = self._python_malloc_callback
|
||||
self.python_free_callback = self._python_free_callback
|
||||
|
||||
@@ -291,24 +292,17 @@ class XpuMemAllocator:
|
||||
data.cpu_backup_tensor = None
|
||||
|
||||
def release_pools(self) -> None:
|
||||
"""Drop Python references to MemPool/pluggable allocators eagerly.
|
||||
|
||||
This prevents pool destruction from being deferred to interpreter
|
||||
finalization, which can happen after parts of XPU runtime are already
|
||||
torn down.
|
||||
"""
|
||||
if not self.allocator_and_pools:
|
||||
"""Release pools, retaining allocators until their allocations are freed."""
|
||||
if not self.allocator_and_pools and not self._pending_allocators:
|
||||
return
|
||||
|
||||
# Note: keep allocators alive while MemPool objects are destroyed.
|
||||
# MemPool teardown may invoke allocator virtual methods (e.g. raw_delete)
|
||||
# when releasing cached blocks. If allocator wrappers are dropped first,
|
||||
# C++ can hit "pure virtual method called" during shutdown.
|
||||
pool_entries = [e for es in self.allocator_and_pools.values() for e in es]
|
||||
self.allocator_and_pools.clear()
|
||||
|
||||
mem_pools = [entry[0] for entry in pool_entries]
|
||||
allocators = [entry[1] for entry in pool_entries]
|
||||
# Live tensors can outlast their MemPool wrappers. Keep allocators alive
|
||||
# across calls so deferred frees cannot invoke a destroyed allocator.
|
||||
self._pending_allocators.extend(entry[1] for entry in pool_entries)
|
||||
pool_entries.clear()
|
||||
|
||||
xpu_sync = getattr(torch.xpu, "synchronize", None)
|
||||
@@ -318,12 +312,14 @@ class XpuMemAllocator:
|
||||
except Exception:
|
||||
logger.debug("torch.xpu.synchronize() failed during release_pools")
|
||||
|
||||
# Phase 1: drop MemPool refs while allocators are still strongly held.
|
||||
mem_pools.clear()
|
||||
gc.collect()
|
||||
torch.xpu.empty_cache()
|
||||
|
||||
# Phase 2: now it is safe to release allocator wrappers.
|
||||
allocators.clear()
|
||||
# Free callbacks remove allocation records, including cached blocks.
|
||||
# If any remain, a later release_pools() call must retry this cleanup.
|
||||
if not self.pointer_to_data:
|
||||
self._pending_allocators.clear()
|
||||
|
||||
@contextmanager
|
||||
def use_memory_pool(self, tag: str | None = None):
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.utils.flashinfer import (
|
||||
from vllm.utils.func_utils import supports_kw
|
||||
from vllm.utils.import_utils import (
|
||||
check_moonep_system_support,
|
||||
deep_ep_v2_unavailable_reason,
|
||||
has_deep_ep,
|
||||
has_deep_ep_v2,
|
||||
has_mori,
|
||||
@@ -1011,7 +1012,11 @@ class MoriAll2AllManager(All2AllManagerBase):
|
||||
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")
|
||||
# (> 8GB with a fused shared expert).
|
||||
heap_size = os.environ.setdefault(
|
||||
"MORI_SHMEM_HEAP_SIZE",
|
||||
"16G" if envs.VLLM_ROCM_AITER_MEGA_MOE_FUSE_SHARED_EXPERTS else "8G",
|
||||
)
|
||||
logger.info_once("AITER MegaMoE: MORI_SHMEM_HEAP_SIZE=%s", heap_size)
|
||||
mori.shmem.shmem_torch_process_group_init("mori")
|
||||
|
||||
@@ -1104,10 +1109,7 @@ class DeepEPV2All2AllManager(All2AllManagerBase):
|
||||
"""
|
||||
|
||||
def __init__(self, cpu_group, tcp_store_group=None, device_group=None):
|
||||
assert has_deep_ep_v2(), (
|
||||
"DeepEP v2 (ElasticBuffer) not available. Requires DeepEP >= 2.0 "
|
||||
"(https://github.com/deepseek-ai/DeepEP) and NCCL >= 2.30.4."
|
||||
)
|
||||
assert has_deep_ep_v2(), deep_ep_v2_unavailable_reason()
|
||||
super().__init__(cpu_group, tcp_store_group)
|
||||
self._device_group = device_group
|
||||
self.handle_cache = Cache()
|
||||
|
||||
@@ -413,6 +413,17 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
out = ca_comm.custom_all_reduce(input_)
|
||||
assert out is not None
|
||||
return out
|
||||
if (
|
||||
envs.VLLM_BATCH_INVARIANT
|
||||
and current_platform.is_rocm()
|
||||
and input_.is_floating_point()
|
||||
):
|
||||
# Integer sums are exact in any order and stay on RCCL.
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
all_reduce_batch_invariant,
|
||||
)
|
||||
|
||||
return all_reduce_batch_invariant(input_, self.device_group)
|
||||
symm_mem_comm = self.symm_mem_comm
|
||||
if symm_mem_comm is not None and symm_mem_comm.should_use_symm_mem(input_):
|
||||
out = symm_mem_comm.all_reduce(input_)
|
||||
@@ -498,7 +509,17 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
chunk_size = input_tensor.shape[0] // world_size
|
||||
output_shape = (chunk_size,) + input_tensor.shape[1:]
|
||||
|
||||
if should_nccl_symm_mem_ag_rs():
|
||||
if (
|
||||
envs.VLLM_BATCH_INVARIANT
|
||||
and current_platform.is_rocm()
|
||||
and input_.is_floating_point()
|
||||
):
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
reduce_scatter_batch_invariant,
|
||||
)
|
||||
|
||||
output = reduce_scatter_batch_invariant(input_tensor, self.device_group)
|
||||
elif should_nccl_symm_mem_ag_rs():
|
||||
output = self._reduce_scatter_symm_mem(input_tensor)
|
||||
else:
|
||||
output = torch.empty(
|
||||
@@ -563,6 +584,22 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
assert output.device == input_tensor.device
|
||||
assert output.is_contiguous()
|
||||
|
||||
if (
|
||||
envs.VLLM_BATCH_INVARIANT
|
||||
and current_platform.is_rocm()
|
||||
and input_.is_floating_point()
|
||||
):
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
reduce_scatter_batch_invariant,
|
||||
)
|
||||
|
||||
result = reduce_scatter_batch_invariant(
|
||||
input_tensor, self.device_group, sizes=sizes
|
||||
)
|
||||
if output is not None:
|
||||
return output.copy_(result)
|
||||
return result.movedim(0, dim).contiguous()
|
||||
|
||||
if self._can_use_aiter_ag_rs(sizes):
|
||||
aiter_comm = self.aiter_ar_comm
|
||||
assert aiter_comm is not None
|
||||
@@ -814,12 +851,19 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
return bd is not None and bd.uniform
|
||||
|
||||
def suspend(self) -> None:
|
||||
from .flashinfer_all_reduce import checkpoint_prepare_fi_ar_workspaces
|
||||
|
||||
# FlashInfer AR syncs over the gloo cpu_group, so order vs. NCCL is free.
|
||||
checkpoint_prepare_fi_ar_workspaces(self.cpu_group, skip_unsupported=True)
|
||||
if self.pynccl_comm is not None:
|
||||
self.pynccl_comm.suspend()
|
||||
|
||||
def resume(self) -> None:
|
||||
from .flashinfer_all_reduce import checkpoint_restore_fi_ar_workspaces
|
||||
|
||||
if self.pynccl_comm is not None:
|
||||
self.pynccl_comm.resume()
|
||||
checkpoint_restore_fi_ar_workspaces(self.cpu_group, skip_unsupported=True)
|
||||
|
||||
def checkpoint_prepare(self) -> None:
|
||||
# Only FlashInfer all-reduce and FlashInfer all2all are supported for now.
|
||||
|
||||
@@ -360,14 +360,30 @@ def _fi_ar_workspaces_for_group(group: ProcessGroup) -> list[Any]:
|
||||
return group_workspaces
|
||||
|
||||
|
||||
def checkpoint_prepare_fi_ar_workspaces(group: ProcessGroup) -> None:
|
||||
def checkpoint_prepare_fi_ar_workspaces(
|
||||
group: ProcessGroup, skip_unsupported: bool = False
|
||||
) -> None:
|
||||
for workspace in _fi_ar_workspaces_for_group(group):
|
||||
workspace.checkpoint_prepare()
|
||||
try:
|
||||
workspace.checkpoint_prepare()
|
||||
except NotImplementedError:
|
||||
if not skip_unsupported:
|
||||
raise
|
||||
logger.info_once(
|
||||
"FlashInfer all-reduce workspace backed by torch symmetric memory "
|
||||
"stays resident during suspend."
|
||||
)
|
||||
|
||||
|
||||
def checkpoint_restore_fi_ar_workspaces(group: ProcessGroup) -> None:
|
||||
def checkpoint_restore_fi_ar_workspaces(
|
||||
group: ProcessGroup, skip_unsupported: bool = False
|
||||
) -> None:
|
||||
for workspace in _fi_ar_workspaces_for_group(group):
|
||||
workspace.checkpoint_restore(TorchDistBackend(group=group))
|
||||
try:
|
||||
workspace.checkpoint_restore(TorchDistBackend(group=group))
|
||||
except NotImplementedError:
|
||||
if not skip_unsupported:
|
||||
raise
|
||||
|
||||
|
||||
atexit.register(destroy_fi_ar_workspace)
|
||||
|
||||
@@ -28,7 +28,7 @@ from vllm.distributed.utils import is_weak_contiguous # noqa: E402, F401
|
||||
|
||||
|
||||
class QuickReduceRegime(Enum):
|
||||
# Keep integer ids aligned with csrc/quickreduce/quick_reduce.h
|
||||
# Keep integer ids aligned with csrc/rocm/quickreduce/quick_reduce.h
|
||||
FP = 0
|
||||
INT8 = 1
|
||||
INT6 = 2
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import ray
|
||||
import torch
|
||||
from ray.exceptions import RayChannelError
|
||||
from ray.experimental.channel.communicator import Communicator, TorchTensorAllocator
|
||||
from torch.distributed import ReduceOp
|
||||
|
||||
from vllm.distributed.device_communicators.base_device_communicator import (
|
||||
DeviceCommunicatorBase,
|
||||
)
|
||||
from vllm.distributed.parallel_state import get_pp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.torch_utils import current_stream
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class RayPPCommunicator(Communicator):
|
||||
"""Communicator to be used for pipeline parallelism in Ray Compiled Graph.
|
||||
This is wraps around the vLLM _PP GroupCoordinator.
|
||||
|
||||
This class is not thread-safe.
|
||||
"""
|
||||
|
||||
_comm: DeviceCommunicatorBase | None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
world_size: int,
|
||||
comm_id: Any,
|
||||
rank: int | None,
|
||||
actor_handles: list["ray.actor.ActorHandle"],
|
||||
cuda_stream: torch.cuda.Stream | None,
|
||||
use_communication_streams: bool = False,
|
||||
):
|
||||
"""Initialize a RayPPCommunicator that can be used to communicate with
|
||||
other Ray Compiled Graph actors for pipeline parallelism.
|
||||
|
||||
Args:
|
||||
world_size: The number of participating actors.
|
||||
comm_id: A unique communicator ID. This is just to conform with
|
||||
the Ray Communicator API and is not used.
|
||||
rank: The rank of this actor. If None, then the caller is not a
|
||||
participant of the RayPPCommunicator group (e.g., the Ray
|
||||
driver).
|
||||
actor_handles: A list of actor handles.
|
||||
cuda_stream: A CUDA stream to dispatch communication ops to. This
|
||||
is not supported.
|
||||
use_communication_streams: Whether to use communication streams.
|
||||
This is not supported.
|
||||
|
||||
"""
|
||||
self._world_size = world_size
|
||||
self._rank: int | None = None
|
||||
self._actor_handles = actor_handles
|
||||
if use_communication_streams:
|
||||
raise NotImplementedError("use_communication_streams is not supported")
|
||||
if cuda_stream is not None and cuda_stream != current_stream():
|
||||
raise ValueError(
|
||||
"cuda_stream other than the current stream is not supported"
|
||||
)
|
||||
|
||||
if rank is not None:
|
||||
# Rank is not None, this is Ray worker
|
||||
assert ray.get_gpu_ids(), "RayPPCommunicator has no GPUs assigned"
|
||||
|
||||
self._comm = get_pp_group().device_communicator
|
||||
assert self._comm is not None
|
||||
|
||||
# Since we wrap around the vLLM _PP communicator, we use
|
||||
# the rank from the vLLM communicator, and ignore the rank
|
||||
# passed in from Ray.
|
||||
# TODO(rui): refactor the Ray Communicator API so that
|
||||
# it also supports no rank passed in.
|
||||
self._rank = self._comm.rank_in_group
|
||||
|
||||
self._build_actor_rank_mapping()
|
||||
else:
|
||||
# Rank is None, this is Ray driver
|
||||
self._comm = None
|
||||
|
||||
self._closed = False
|
||||
|
||||
def _build_actor_rank_mapping(self):
|
||||
"""Use collective communication to build a mapping from actor IDs to ranks.
|
||||
This should be called once during initialization.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return {}
|
||||
|
||||
current_actor = ray.get_runtime_context().current_actor
|
||||
actor_id_str = current_actor._actor_id.hex()
|
||||
|
||||
# Ray actor IDs are 32-character hex strings (128 bits)
|
||||
ACTOR_ID_LEN = 32
|
||||
actor_id_bytes = bytearray(actor_id_str.encode("utf-8"))
|
||||
assert len(actor_id_bytes) == ACTOR_ID_LEN, (
|
||||
f"Unexpected actor ID length: {len(actor_id_bytes)}"
|
||||
)
|
||||
|
||||
actor_id_tensor = torch.frombuffer(actor_id_bytes, dtype=torch.uint8).to(
|
||||
self._comm.device
|
||||
)
|
||||
|
||||
# All-gather full actor IDs from all actors
|
||||
gathered_ids = self._comm.all_gather(actor_id_tensor, dim=0)
|
||||
|
||||
# Build mapping: actor_id -> device_comm_rank
|
||||
self._actor_id_to_rank = {}
|
||||
for rank in range(self._world_size):
|
||||
start_idx = rank * ACTOR_ID_LEN
|
||||
end_idx = (rank + 1) * ACTOR_ID_LEN
|
||||
actor_bytes = gathered_ids[start_idx:end_idx].cpu().numpy().tobytes()
|
||||
actor_id = actor_bytes.decode("utf-8")
|
||||
self._actor_id_to_rank[actor_id] = rank
|
||||
|
||||
def initialize(self, rank: int) -> None:
|
||||
# No additional initialization is needed.
|
||||
pass
|
||||
|
||||
def get_actor_handles(self) -> list["ray.actor.ActorHandle"]:
|
||||
return self._actor_handles
|
||||
|
||||
def get_rank(self, actor: ray.actor.ActorHandle) -> int:
|
||||
"""Return the given actor's rank using device communicator collective ops."""
|
||||
assert hasattr(self, "_actor_id_to_rank"), (
|
||||
"Actor rank mapping not built. "
|
||||
"This should have been done during initialization."
|
||||
)
|
||||
|
||||
actor_id_str = actor._actor_id.hex()
|
||||
|
||||
if actor_id_str in self._actor_id_to_rank:
|
||||
return self._actor_id_to_rank[actor_id_str] # type: ignore
|
||||
else:
|
||||
raise ValueError(f"Actor {actor} not found in communicator group")
|
||||
|
||||
def get_self_rank(self) -> int | None:
|
||||
"""Return this actor's rank."""
|
||||
return self._rank
|
||||
|
||||
def get_world_size(self) -> int:
|
||||
"""Return the number of ranks in the RayPPCommunicator group."""
|
||||
return self._world_size
|
||||
|
||||
def send(self, buf: "torch.Tensor", peer_rank: int) -> None:
|
||||
"""Send a torch.Tensor to a peer.
|
||||
|
||||
This returns when the send kernel has been queued, but the kernel may
|
||||
not have completed. Therefore, the caller should ensure that there are
|
||||
no concurrent writes to the sent `buf` until the send has finished.
|
||||
That is, either all writes should be submitted on the current stream
|
||||
(self._cuda_stream) or, if on a different stream, that stream should
|
||||
synchronize with the current stream.
|
||||
|
||||
Args:
|
||||
buf: The torch.Tensor to send. It should already be on this
|
||||
actor's default device.
|
||||
peer_rank: The rank of the actor to send to.
|
||||
|
||||
"""
|
||||
if self._closed:
|
||||
raise RayChannelError("RayPPCommunicator has been destroyed.")
|
||||
|
||||
assert self._comm is not None
|
||||
self._comm.send(buf, peer_rank)
|
||||
|
||||
def recv(
|
||||
self,
|
||||
shape: tuple[int, ...],
|
||||
dtype: "torch.dtype",
|
||||
peer_rank: int,
|
||||
allocator: TorchTensorAllocator,
|
||||
) -> "torch.Tensor":
|
||||
"""Receive a torch.Tensor from a peer and synchronize the current stream.
|
||||
|
||||
After this call returns, the receive buffer is safe to read from
|
||||
any stream. An RayChannelError will be raised if an error occurred
|
||||
(e.g., remote actor died), and the buffer is not safe to read.
|
||||
|
||||
Args:
|
||||
shape: The shape of the tensor to receive.
|
||||
dtype: The dtype of the tensor to receive.
|
||||
peer_rank: The rank of the actor to receive from.
|
||||
allocator: The allocator to use to create the received tensor.
|
||||
This is ignored for this implementation.
|
||||
|
||||
"""
|
||||
if self._closed:
|
||||
raise RayChannelError("RayPPCommunicator has been destroyed.")
|
||||
|
||||
assert self._comm is not None
|
||||
size = torch.Size(shape)
|
||||
buf = self._comm.recv(size, dtype, src=peer_rank)
|
||||
|
||||
# Buffer values are undefined if NCCL ops are aborted. Therefore, we
|
||||
# need to synchronize here and check that the channel is still
|
||||
# open to ensure that the receive buffer is valid.
|
||||
# TODO(swang): Avoid CUDA synchronization.
|
||||
current_stream().synchronize()
|
||||
|
||||
if self._closed:
|
||||
raise RayChannelError("RayPPCommunicator has been destroyed.")
|
||||
return buf
|
||||
|
||||
def allgather(
|
||||
self,
|
||||
send_buf: "torch.Tensor",
|
||||
recv_buf: "torch.Tensor",
|
||||
):
|
||||
raise NotImplementedError("allgather is not supported")
|
||||
|
||||
def allreduce(
|
||||
self,
|
||||
send_buf: "torch.Tensor",
|
||||
recv_buf: "torch.Tensor",
|
||||
op: ReduceOp = ReduceOp.SUM,
|
||||
):
|
||||
raise NotImplementedError("allreduce is not supported")
|
||||
|
||||
def reducescatter(
|
||||
self,
|
||||
send_buf: "torch.Tensor",
|
||||
recv_buf: "torch.Tensor",
|
||||
op: ReduceOp = ReduceOp.SUM,
|
||||
):
|
||||
raise NotImplementedError("reducescatter is not supported")
|
||||
|
||||
@property
|
||||
def recv_stream(self):
|
||||
return torch.cuda.StreamContext(current_stream())
|
||||
|
||||
@property
|
||||
def send_stream(self):
|
||||
return torch.cuda.StreamContext(current_stream())
|
||||
|
||||
def destroy(self) -> None:
|
||||
# Just sets a flag, vLLM manages the lifecycle of the underlying
|
||||
# _PP GroupCoordinator.
|
||||
self._closed = True
|
||||
|
||||
def get_transport_name(self) -> str:
|
||||
return "nccl"
|
||||
|
||||
@classmethod
|
||||
def generate_communicator_id(cls) -> Any:
|
||||
return uuid.uuid4()
|
||||
@@ -61,6 +61,10 @@ SPINLOOP_TIMEOUT_SECONDS = 0.1
|
||||
if TYPE_CHECKING:
|
||||
from _typeshed import SizedBuffer
|
||||
|
||||
from vllm.distributed.device_communicators.shm_tensor_arena import (
|
||||
ShmTensorArena,
|
||||
)
|
||||
|
||||
VLLM_RINGBUFFER_WARNING_INTERVAL = envs.VLLM_RINGBUFFER_WARNING_INTERVAL
|
||||
# Cap on how long an idle reader parks before re-reading the authoritative SHM
|
||||
# written-flag. Bounds lost-notify recovery latency to ~5s while the periodic
|
||||
@@ -404,8 +408,8 @@ def _rebuild_tensor(buf: Any, shape: tuple[int, ...], dtype_str: str) -> torch.T
|
||||
Counterpart of `_reduce_tensor`. Note that pickle passes the original
|
||||
buffer-providing object from `loads(buffers=...)` straight to this
|
||||
function (no `PickleBuffer` wrapper on the receiving side), so `buf` is
|
||||
a `zmq.Frame`, a `memoryview` of a shared-memory ring chunk, or `bytes`
|
||||
if the buffer was serialized in-band.
|
||||
a `zmq.Frame`, an owned `bytearray` from the shared-memory ring, or
|
||||
`bytes`/`bytearray` if the buffer was serialized in-band.
|
||||
"""
|
||||
dtype = getattr(torch, dtype_str)
|
||||
assert isinstance(dtype, torch.dtype)
|
||||
@@ -419,11 +423,8 @@ def _rebuild_tensor(buf: Any, shape: tuple[int, ...], dtype_str: str) -> torch.T
|
||||
except ValueError:
|
||||
# Empty or read-only frame buffer; fall through to the copy path.
|
||||
pass
|
||||
# Shared-memory ring buffer chunks are reused by the writer once all
|
||||
# readers have marked them read, so we must copy out of them. bytearray
|
||||
# (vs bytes) keeps the resulting tensor writable, matching normal tensor
|
||||
# semantics.
|
||||
raw = bytearray(buf)
|
||||
# dequeue already owns SHM buffers. Copy other buffers to keep them writable.
|
||||
raw = buf if isinstance(buf, bytearray) else bytearray(buf)
|
||||
if not raw:
|
||||
assert 0 in shape
|
||||
return torch.empty(shape, dtype=dtype)
|
||||
@@ -471,6 +472,7 @@ class Handle:
|
||||
local_notify_addr: str | None = None
|
||||
remote_subscribe_addr: str | None = None
|
||||
remote_addr_ipv6: bool = False
|
||||
tensor_arena_handle: tuple[int, int, int, str] | None = None
|
||||
|
||||
|
||||
def _close_zmq(context: zmq.Context, sockets: list[zmq.Socket]) -> None:
|
||||
@@ -490,6 +492,7 @@ class MessageQueue:
|
||||
max_chunk_bytes: int = 1024 * 1024 * 24,
|
||||
max_chunks: int = 10,
|
||||
connect_ip: str | None = None,
|
||||
enable_shm_tensor_arena: bool = False,
|
||||
):
|
||||
if local_reader_ranks is None:
|
||||
local_reader_ranks = list(range(n_local_reader))
|
||||
@@ -501,12 +504,22 @@ class MessageQueue:
|
||||
self.shutting_down = False
|
||||
context = Context()
|
||||
|
||||
self.tensor_arena: ShmTensorArena | None = None
|
||||
if n_local_reader > 0:
|
||||
# for local readers, we will:
|
||||
# 1. create a shared memory ring buffer to communicate small data
|
||||
# 2. create a publish-subscribe socket to communicate large data
|
||||
self.buffer = ShmRingBuffer(n_local_reader, max_chunk_bytes, max_chunks)
|
||||
|
||||
# Zero-copy arena for large CPU tensors (see ShmTensorArena).
|
||||
# Local readers only: remote readers receive the pickled bytes
|
||||
# over a socket and cannot map the arena, so the substitution
|
||||
# would break them.
|
||||
if enable_shm_tensor_arena and n_remote_reader == 0:
|
||||
from vllm.distributed.device_communicators import shm_tensor_arena
|
||||
|
||||
self.tensor_arena = shm_tensor_arena.ShmTensorArena(n_local_reader)
|
||||
|
||||
# XPUB is very similar to PUB,
|
||||
# except that it can receive subscription messages
|
||||
# to confirm the number of subscribers
|
||||
@@ -567,6 +580,9 @@ class MessageQueue:
|
||||
local_notify_addr=local_notify_addr,
|
||||
remote_subscribe_addr=remote_subscribe_addr,
|
||||
remote_addr_ipv6=remote_addr_ipv6,
|
||||
tensor_arena_handle=(
|
||||
self.tensor_arena.handle() if self.tensor_arena is not None else None
|
||||
),
|
||||
)
|
||||
self._close_zmq_on_collect(context)
|
||||
|
||||
@@ -599,6 +615,7 @@ class MessageQueue:
|
||||
|
||||
context = Context()
|
||||
|
||||
self.tensor_arena = None
|
||||
if rank in handle.local_reader_ranks:
|
||||
assert handle.buffer_handle is not None
|
||||
self.buffer = ShmRingBuffer(*handle.buffer_handle)
|
||||
@@ -607,6 +624,23 @@ class MessageQueue:
|
||||
self._is_local_reader = True
|
||||
self._is_remote_reader = False
|
||||
|
||||
arena_handle = handle.tensor_arena_handle
|
||||
if arena_handle is not None:
|
||||
from vllm.distributed.device_communicators import shm_tensor_arena
|
||||
|
||||
self.tensor_arena = shm_tensor_arena.ShmTensorArena(
|
||||
*arena_handle, reader_rank=self.local_reader_rank
|
||||
)
|
||||
# `shared_memory` is unset (not just None) if attaching to
|
||||
# the writer's segment raised FileNotFoundError -- see
|
||||
# ShmTensorArena.__init__'s reader branch. Registering a
|
||||
# broken arena is a no-op deferred failure (same convention
|
||||
# ShmRingBuffer uses above), not a crash here.
|
||||
if hasattr(self.tensor_arena, "shared_memory"):
|
||||
shm_tensor_arena._TENSOR_ARENAS[
|
||||
self.tensor_arena.shared_memory.name
|
||||
] = self.tensor_arena
|
||||
|
||||
self.local_socket = context.socket(SUB)
|
||||
self.local_socket.setsockopt_string(SUBSCRIBE, "")
|
||||
socket_addr = handle.local_subscribe_addr
|
||||
@@ -880,12 +914,21 @@ class MessageQueue:
|
||||
# dispatch table would otherwise shadow them.
|
||||
dispatch_table = dict(copyreg.dispatch_table)
|
||||
dispatch_table[torch.Tensor] = _reduce_tensor
|
||||
arena = self.tensor_arena
|
||||
with io.BytesIO() as bio:
|
||||
pickler = pickle.Pickler(
|
||||
bio,
|
||||
protocol=pickle.HIGHEST_PROTOCOL,
|
||||
buffer_callback=oob_callback,
|
||||
)
|
||||
pickler: pickle.Pickler
|
||||
if arena is not None:
|
||||
from vllm.distributed.device_communicators.shm_tensor_arena import (
|
||||
_ArenaPickler,
|
||||
)
|
||||
|
||||
pickler = _ArenaPickler(bio, arena, buffer_callback=oob_callback)
|
||||
else:
|
||||
pickler = pickle.Pickler(
|
||||
bio,
|
||||
protocol=pickle.HIGHEST_PROTOCOL,
|
||||
buffer_callback=oob_callback,
|
||||
)
|
||||
pickler.dispatch_table = dispatch_table
|
||||
pickler.dump(obj)
|
||||
all_buffers[0] = bio.getvalue()
|
||||
@@ -922,6 +965,9 @@ class MessageQueue:
|
||||
):
|
||||
"""Read from message queue with optional timeout (in seconds)"""
|
||||
if self._is_local_reader:
|
||||
# See ShmTensorArena.flush_releases for what this retires and why.
|
||||
if self.tensor_arena is not None:
|
||||
self.tensor_arena.flush_releases()
|
||||
with self.acquire_read(timeout, indefinite) as buf:
|
||||
overflow = buf[0] == 1
|
||||
if not overflow:
|
||||
@@ -932,7 +978,9 @@ class MessageQueue:
|
||||
buf_offset = offset + 4
|
||||
buf_len = from_bytes_big(buf[offset:buf_offset])
|
||||
offset = buf_offset + buf_len
|
||||
all_buffers.append(buf[buf_offset:offset])
|
||||
buffer = buf[buf_offset:offset]
|
||||
# Out-of-band arrays may outlive this reusable ring slot.
|
||||
all_buffers.append(buffer if i == 0 else bytearray(buffer))
|
||||
obj = pickle.loads(all_buffers[0], buffers=all_buffers[1:])
|
||||
if overflow:
|
||||
obj = MessageQueue.recv(self.local_socket, timeout)
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Zero-copy shared-memory arena for large CPU tensors (multimodal fast path).
|
||||
|
||||
Problem: `MessageQueue.enqueue` (see `shm_broadcast.py`) pickles the whole
|
||||
payload, and torch's default tensor pickling copies bytes into the pickle
|
||||
stream on the writer and back out on every local reader. For a large
|
||||
`pixel_values` tensor (up to hundreds of MB) this blocks the EngineCore step
|
||||
loop for ~1s with all GPUs idle.
|
||||
|
||||
Fast path: `_ArenaPickler.reducer_override` intercepts qualifying CPU
|
||||
tensors during pickling, memcpys them ONCE into a free arena slot, and
|
||||
pickles a tiny `(arena_name, slot, nbytes, dtype, shape)` stub. Readers
|
||||
rebuild a zero-copy view of the mapped slot (`torch.frombuffer`).
|
||||
|
||||
Slot lifecycle: single writer, n_reader readers, per-slot metadata
|
||||
[written_flag, reader0_done, ..., readerN_done] (same protocol as
|
||||
ShmRingBuffer). A slot is not released when rebuilt: the rebuilt tensor is
|
||||
the SOURCE of an async H2D copy, and callers like chunked-prefill
|
||||
`prompt_embeds` retain it across many steps. Release is queued only once the
|
||||
tensor's storage is freed, i.e. once no tensor or view of the slot remains
|
||||
(see `get_tensor`), and is further gated on a CUDA event on the pinned fast
|
||||
path, since the H2D can outlive the step that issued it (see
|
||||
`flush_releases`).
|
||||
|
||||
The writer NEVER blocks: no free slot (or an oversized tensor) falls back to
|
||||
the default pickle path, so worst case matches today's behavior.
|
||||
|
||||
Physical memory: slots are paged in lazily, so an arena on a queue that
|
||||
never carries big tensors costs ~0. Creation is guarded by
|
||||
`check_shm_free_space` (like `ShmRingBuffer`) so an undersized `/dev/shm`
|
||||
fails fast instead of a `SIGBUS` mid-copy.
|
||||
"""
|
||||
|
||||
import pickle
|
||||
import weakref
|
||||
from contextlib import suppress
|
||||
from multiprocessing import shared_memory
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.distributed.device_communicators.shm_broadcast import (
|
||||
check_shm_free_space,
|
||||
memory_fence,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Arena sizing — internal constants (kept off the env/CLI surface).
|
||||
_ARENA_SLOTS = 8
|
||||
_ARENA_SLOT_BYTES = 256 * 1024 * 1024
|
||||
# Minimum contiguous CPU-tensor size to divert into the arena; smaller tensors
|
||||
# take the out-of-band pickle-buffer path.
|
||||
_ARENA_MIN_BYTES = 8 * 1024 * 1024
|
||||
|
||||
# Reader-side registry: arena shm name -> attached ShmTensorArena, keyed by
|
||||
# name rather than a single slot since a process isn't guaranteed to attach
|
||||
# to only one. Populated by `MessageQueue.create_from_handle`; consumed by
|
||||
# the `_rebuild_arena_*` unpickle hooks. WEAK-value: a strong reference here
|
||||
# would keep the arena (and its pinned mapping) alive for the process
|
||||
# lifetime, and would need `MessageQueue.shutdown` to remove it explicitly --
|
||||
# unsafe since shutdown() can run on a different thread than an in-flight
|
||||
# `dequeue`. Instead an entry just disappears once nothing else references
|
||||
# that arena.
|
||||
_TENSOR_ARENAS: weakref.WeakValueDictionary[str, "ShmTensorArena"] = (
|
||||
weakref.WeakValueDictionary()
|
||||
)
|
||||
|
||||
|
||||
class ShmTensorArena:
|
||||
"""Slotted shared-memory arena: one writer, n_reader zero-copy readers.
|
||||
|
||||
Memory layout: [slot0 | slot1 | ... | slotN-1 | meta0 | meta1 | ... ]
|
||||
where each meta is (1 + n_reader) bytes: [written_flag, reader_done...].
|
||||
Slot states mirror ShmRingBuffer:
|
||||
written=0 -> free (never written / being written)
|
||||
written=1, some reader_done=0 -> in use, cannot reuse
|
||||
written=1, all reader_done=1 -> consumed, can reuse
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
n_reader: int,
|
||||
slot_bytes: int = _ARENA_SLOT_BYTES,
|
||||
n_slots: int = _ARENA_SLOTS,
|
||||
name: str | None = None,
|
||||
reader_rank: int = -1,
|
||||
):
|
||||
self.n_reader = n_reader
|
||||
self.slot_bytes = slot_bytes
|
||||
self.n_slots = n_slots
|
||||
self.reader_rank = reader_rank # -1 for the writer
|
||||
self.metadata_size = 1 + n_reader
|
||||
self.metadata_offset = slot_bytes * n_slots
|
||||
self.total_bytes = (slot_bytes + self.metadata_size) * n_slots
|
||||
self._next_slot = 0
|
||||
self._fallbacks = 0
|
||||
self._pin_attempted = False
|
||||
self._pinned = False
|
||||
self._pinned_ptr = 0
|
||||
# slots queued for release once the storage of the tensor `get_tensor`
|
||||
# handed out is freed; flushed at the next dequeue.
|
||||
self._pending_release: list[int] = []
|
||||
# slots whose release is gated on an H2D-completion CUDA event: each
|
||||
# entry is (event, [slot_idx, ...]). Only populated on the pinned fast
|
||||
# path, where the source-side DMA is asynchronous (see flush_releases).
|
||||
self._deferred_releases: list[tuple[torch.cuda.Event, list[int]]] = []
|
||||
|
||||
if name is None:
|
||||
self.is_creator = True
|
||||
# Same guard as ShmRingBuffer: SharedMemory/ftruncate can succeed
|
||||
# on an undersized /dev/shm, so check up front instead of SIGBUS
|
||||
# on first write past tmpfs capacity.
|
||||
check_shm_free_space(self.total_bytes, allocation_name="ShmTensorArena")
|
||||
self.shared_memory = shared_memory.SharedMemory(
|
||||
create=True, size=self.total_bytes
|
||||
)
|
||||
assert self.shared_memory.buf is not None
|
||||
with self.shared_memory.buf[self.metadata_offset :] as meta:
|
||||
torch.frombuffer(meta, dtype=torch.uint8).fill_(0)
|
||||
else:
|
||||
self.is_creator = False
|
||||
# same resource_tracker workaround as ShmRingBuffer
|
||||
with patch(
|
||||
"multiprocessing.resource_tracker.register",
|
||||
lambda *args, **kwargs: None,
|
||||
):
|
||||
try:
|
||||
self.shared_memory = shared_memory.SharedMemory(name=name)
|
||||
assert self.shared_memory.size >= self.total_bytes
|
||||
except FileNotFoundError:
|
||||
# deserialized on a different node; arena unused there
|
||||
pass
|
||||
|
||||
def handle(self):
|
||||
return (self.n_reader, self.slot_bytes, self.n_slots, self.shared_memory.name)
|
||||
|
||||
def _meta(self, idx: int) -> memoryview:
|
||||
start = self.metadata_offset + idx * self.metadata_size
|
||||
assert self.shared_memory.buf is not None
|
||||
return self.shared_memory.buf[start : start + self.metadata_size]
|
||||
|
||||
def _slot(self, idx: int, nbytes: int) -> memoryview:
|
||||
start = idx * self.slot_bytes
|
||||
assert self.shared_memory.buf is not None
|
||||
return self.shared_memory.buf[start : start + nbytes]
|
||||
|
||||
# ---- writer side ----
|
||||
|
||||
def write_tensor(self, t: torch.Tensor) -> int | None:
|
||||
"""Copy tensor bytes into a free slot; return slot idx or None
|
||||
(caller must then fall back to the default pickle path)."""
|
||||
nbytes = t.numel() * t.element_size()
|
||||
if nbytes > self.slot_bytes:
|
||||
return None
|
||||
try:
|
||||
# Computed before claiming a slot: exotic tensors (e.g. conjugate
|
||||
# bit set) raise RuntimeError here, same as `_reduce_tensor`'s
|
||||
# identical view -- fail before claiming, not after.
|
||||
src = t.detach().reshape(-1).view(torch.uint8)
|
||||
except RuntimeError:
|
||||
return None
|
||||
memory_fence()
|
||||
for probe in range(self.n_slots):
|
||||
idx = (self._next_slot + probe) % self.n_slots
|
||||
with self._meta(idx) as meta:
|
||||
free = meta[0] == 0 or sum(meta[1:]) == self.n_reader
|
||||
if not free:
|
||||
continue
|
||||
meta[0] = 0 # claim
|
||||
slot_mv = self._slot(idx, nbytes)
|
||||
try:
|
||||
dst = torch.frombuffer(slot_mv, dtype=torch.uint8, count=nbytes)
|
||||
dst.copy_(src)
|
||||
finally:
|
||||
slot_mv.release()
|
||||
with self._meta(idx) as meta:
|
||||
for i in range(1, self.n_reader + 1):
|
||||
meta[i] = 0
|
||||
memory_fence()
|
||||
meta[0] = 1
|
||||
memory_fence()
|
||||
self._next_slot = (idx + 1) % self.n_slots
|
||||
return idx
|
||||
self._fallbacks += 1
|
||||
if self._fallbacks == 1 or self._fallbacks % 100 == 0:
|
||||
logger.info(
|
||||
"ShmTensorArena: no free slot (%d bytes, %d fallbacks so far); "
|
||||
"falling back to the out-of-band pickle path.",
|
||||
nbytes,
|
||||
self._fallbacks,
|
||||
)
|
||||
return None
|
||||
|
||||
# ---- reader side ----
|
||||
|
||||
def _ensure_pinned(self):
|
||||
"""Pin the whole arena mapping via cudaHostRegister in THIS process
|
||||
(lazy, once). Without it the HtoD of a zero-copy tensor pays
|
||||
first-touch page faults on the tmpfs mapping plus pageable staging
|
||||
(~hundreds of ms for 200MB); registration allocates+pins the pages
|
||||
once, making every later HtoD a true DMA. Failure (no CUDA in this
|
||||
process, etc.) is fine — the copy still works, just slower."""
|
||||
if self._pin_attempted:
|
||||
return
|
||||
self._pin_attempted = True
|
||||
try:
|
||||
if not current_platform.is_cuda_alike():
|
||||
return
|
||||
import ctypes
|
||||
|
||||
buf = self.shared_memory.buf
|
||||
assert buf is not None
|
||||
ptr = ctypes.addressof(ctypes.c_char.from_buffer(buf))
|
||||
ret = current_platform.cudart().cudaHostRegister(ptr, self.total_bytes, 0)
|
||||
self._pinned = int(ret) == 0
|
||||
if self._pinned:
|
||||
self._pinned_ptr = ptr
|
||||
logger.info(
|
||||
"ShmTensorArena: cudaHostRegister(%d MB) -> %s",
|
||||
self.total_bytes >> 20,
|
||||
"pinned" if self._pinned else f"error {int(ret)}",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info("ShmTensorArena: host-register skipped: %s", e)
|
||||
|
||||
def _unpin(self):
|
||||
"""Undo the pin from _ensure_pinned via cudaHostUnregister; must run
|
||||
before the mapping is closed. Failures are ignored — at interpreter
|
||||
shutdown the CUDA context may already be gone, and the registration
|
||||
dies with the process anyway."""
|
||||
if not self._pinned:
|
||||
return
|
||||
self._pinned = False
|
||||
with suppress(Exception):
|
||||
current_platform.cudart().cudaHostUnregister(self._pinned_ptr)
|
||||
|
||||
def get_tensor(
|
||||
self, idx: int, nbytes: int, dtype: torch.dtype, shape: tuple[int, ...]
|
||||
) -> torch.Tensor:
|
||||
"""Zero-copy view of a slot as a tensor. The slot is queued for
|
||||
release once the returned tensor's storage is freed, i.e. once the
|
||||
caller has dropped it along with any views/slices or wrappers (such
|
||||
as `torch.nn.Parameter`) sharing that storage."""
|
||||
self._ensure_pinned()
|
||||
# The tensor's storage holds the only reference to `holder` and drops
|
||||
# it when freed, firing the finalizer. (`weakref.finalize` can't
|
||||
# target the tensor itself, which views and wrappers don't keep alive,
|
||||
# nor the memoryview, which doesn't support weakrefs.)
|
||||
holder = np.frombuffer(self._slot(idx, nbytes), dtype=np.uint8)
|
||||
# Binds to the current list OBJECT: `flush_releases` must mutate it in
|
||||
# place, never rebind `self._pending_release`.
|
||||
weakref.finalize(holder, self._pending_release.append, idx)
|
||||
return torch.from_numpy(holder).view(dtype).view(shape)
|
||||
|
||||
def _mark_released(self, idxs: list[int]):
|
||||
"""Set THIS reader's done flag on the given slots; a slot becomes
|
||||
reusable once every reader has done so."""
|
||||
for idx in idxs:
|
||||
with self._meta(idx) as meta:
|
||||
meta[1 + self.reader_rank] = 1
|
||||
memory_fence()
|
||||
|
||||
def _record_release_event(self):
|
||||
"""Record a CUDA event on the current (compute) stream, or return None
|
||||
if this process has no usable CUDA context. Called from flush_releases,
|
||||
which runs after the previous step's H2D was enqueued on that same
|
||||
stream, so the event is ordered strictly after that H2D."""
|
||||
try:
|
||||
event = current_platform.Event()
|
||||
event.record()
|
||||
return event
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def flush_releases(self):
|
||||
"""Retire this reader's arena slots that are ready for writer reuse.
|
||||
|
||||
Called on every `MessageQueue.dequeue`. `_pending_release` holds
|
||||
slots whose tensor storage was just freed (see `get_tensor`). On
|
||||
the pinned fast path that tensor was the source of an async
|
||||
`non_blocking=True` H2D that can outlive the collection, so instead
|
||||
of marking released immediately we record a CUDA event (ordered
|
||||
after that H2D on the same stream) and move the slot to
|
||||
`_deferred_releases` until `event.query()` says it's done -- a
|
||||
not-yet-complete slot just waits one more `dequeue`. Unpinned (or no
|
||||
CUDA context), the H2D already staged synchronously, so the slot is
|
||||
safe to release right away.
|
||||
|
||||
A slot only becomes free for the writer (`write_tensor`) once every
|
||||
reader has marked it released (`_mark_released`).
|
||||
"""
|
||||
if self._deferred_releases:
|
||||
still_pending = []
|
||||
for deferred_event, idxs in self._deferred_releases:
|
||||
if deferred_event.query():
|
||||
self._mark_released(idxs)
|
||||
else:
|
||||
still_pending.append((deferred_event, idxs))
|
||||
self._deferred_releases = still_pending
|
||||
|
||||
if not self._pending_release:
|
||||
return
|
||||
# Drain in place with atomic pops, never rebind (see get_tensor): a
|
||||
# finalizer may append from another thread concurrently.
|
||||
idxs = []
|
||||
while self._pending_release:
|
||||
idxs.append(self._pending_release.pop())
|
||||
|
||||
event = self._record_release_event() if self._pinned else None
|
||||
if event is None:
|
||||
self._mark_released(idxs)
|
||||
else:
|
||||
self._deferred_releases.append((event, idxs))
|
||||
|
||||
def __del__(self):
|
||||
if hasattr(self, "shared_memory"):
|
||||
self._unpin()
|
||||
try:
|
||||
self.shared_memory.close()
|
||||
if self.is_creator:
|
||||
self.shared_memory.unlink()
|
||||
except BufferError:
|
||||
# zero-copy tensor views may still hold exported pointers at
|
||||
# interpreter shutdown; the mapping dies with the process.
|
||||
pass
|
||||
|
||||
|
||||
def _rebuild_arena_tensor(arena_name, slot_idx, nbytes, dtype_str, shape):
|
||||
"""Unpickle hook: rebuild a tensor as a zero-copy view of an arena slot."""
|
||||
arena = _TENSOR_ARENAS[arena_name]
|
||||
return arena.get_tensor(slot_idx, nbytes, getattr(torch, dtype_str), shape)
|
||||
|
||||
|
||||
def _rebuild_arena_parameter(arena_name, slot_idx, nbytes, dtype_str, shape):
|
||||
"""Unpickle hook for `torch.nn.Parameter` (shares the slot's storage)."""
|
||||
t = _rebuild_arena_tensor(arena_name, slot_idx, nbytes, dtype_str, shape)
|
||||
return torch.nn.Parameter(t, requires_grad=False)
|
||||
|
||||
|
||||
# Types `_ArenaPickler.reducer_override` diverts, mapped to the rebuild hook
|
||||
# that reconstructs them. Any other type -- including other `torch.Tensor`
|
||||
# subclasses -- falls through to the normal pickle path, since an arbitrary
|
||||
# subclass can't be faithfully rebuilt from just the slot's bytes.
|
||||
_ARENA_REBUILD_FNS = {
|
||||
torch.Tensor: _rebuild_arena_tensor,
|
||||
torch.nn.Parameter: _rebuild_arena_parameter,
|
||||
}
|
||||
|
||||
|
||||
class _ArenaPickler(pickle.Pickler):
|
||||
"""Pickler that diverts large contiguous CPU tensors into the arena.
|
||||
|
||||
`reducer_override` is consulted before an object's normal reduction. For
|
||||
a qualifying tensor (exact type in `_ARENA_REBUILD_FNS`, CPU, strided,
|
||||
contiguous, not `requires_grad`, above the divert-size threshold -- the
|
||||
same criteria `_reduce_tensor` uses, plus size) it does one memcpy into a
|
||||
free slot and returns a tiny rebuild stub. Anything that doesn't qualify,
|
||||
or finds the arena full, returns `NotImplemented` and falls through to
|
||||
the normal out-of-band pickle path, exactly as if no arena were attached.
|
||||
"""
|
||||
|
||||
def __init__(self, file, arena: ShmTensorArena, buffer_callback=None):
|
||||
super().__init__(
|
||||
file,
|
||||
protocol=pickle.HIGHEST_PROTOCOL,
|
||||
buffer_callback=buffer_callback,
|
||||
)
|
||||
self.arena = arena
|
||||
|
||||
def reducer_override(self, obj):
|
||||
rebuild_fn = _ARENA_REBUILD_FNS.get(type(obj))
|
||||
if (
|
||||
rebuild_fn is not None
|
||||
and obj.device.type == "cpu"
|
||||
and obj.layout == torch.strided
|
||||
and obj.is_contiguous()
|
||||
and not obj.requires_grad
|
||||
and obj.numel() * obj.element_size() >= _ARENA_MIN_BYTES
|
||||
):
|
||||
idx = self.arena.write_tensor(obj)
|
||||
if idx is not None:
|
||||
return (
|
||||
rebuild_fn,
|
||||
(
|
||||
self.arena.shared_memory.name,
|
||||
idx,
|
||||
obj.numel() * obj.element_size(),
|
||||
str(obj.dtype).removeprefix("torch."),
|
||||
tuple(obj.shape),
|
||||
),
|
||||
)
|
||||
return NotImplemented
|
||||
@@ -33,12 +33,14 @@ class ECCPUConnectorMetadata(ECConnectorMetadata):
|
||||
saves: dict[str, list[int]] = field(default_factory=dict)
|
||||
|
||||
# Consumer role: mm_hashes whose bytes are available in the local mmap,
|
||||
# mapped to (transfer_id, block_ids); the worker's start_load_caches
|
||||
# mapped to (transfer_id, block_ids, shape); the worker's start_load_caches
|
||||
# copies mmap[block_ids] → GPU encoder_cache and reports the transfer_id
|
||||
# once its copy lands. The id is minted per dispatch, so two loads of the
|
||||
# same mm_hash in different steps are distinct and a late report from the
|
||||
# earlier one cannot release the later one's pin.
|
||||
loads: dict[str, tuple[int, list[int]]] = field(default_factory=dict)
|
||||
loads: dict[str, tuple[int, list[int], tuple[int, int]]] = field(
|
||||
default_factory=dict
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -66,30 +68,6 @@ class ECCPUWorkerMetadata(ECConnectorWorkerMetadata):
|
||||
return self
|
||||
|
||||
|
||||
def _get_encoder_cache_hidden_dim(vllm_config: "VllmConfig") -> int:
|
||||
"""Return the per-token hidden dimension for encoder cache entries.
|
||||
|
||||
For most models this equals the LLM's hidden size. Qwen3-VL (and any
|
||||
future model with deepstack visual encoding) is an exception: the ViT
|
||||
concatenates its own output with features from N decoder layers before
|
||||
storing in encoder_cache, producing a tensor of width
|
||||
``out_hidden_size * (1 + N)`` per visual token. Using the plain LLM
|
||||
hidden size would under-allocate EC blocks and silently truncate the
|
||||
transferred data, leading to a shape mismatch on the consumer.
|
||||
"""
|
||||
model_config = vllm_config.model_config
|
||||
hf_config = getattr(model_config, "hf_config", None)
|
||||
vision_config = (
|
||||
getattr(hf_config, "vision_config", None) if hf_config is not None else None
|
||||
)
|
||||
if vision_config is not None:
|
||||
out_hidden_size = getattr(vision_config, "out_hidden_size", None)
|
||||
deepstack_indexes = getattr(vision_config, "deepstack_visual_indexes", None)
|
||||
if out_hidden_size is not None and deepstack_indexes:
|
||||
return out_hidden_size * (1 + len(deepstack_indexes))
|
||||
return model_config.get_inputs_embeds_size()
|
||||
|
||||
|
||||
def create_ec_shared_region(vllm_config: "VllmConfig") -> ECSharedRegion:
|
||||
"""Build the EC mmap region from `vllm_config`.
|
||||
|
||||
@@ -103,7 +81,7 @@ def create_ec_shared_region(vllm_config: "VllmConfig") -> ECSharedRegion:
|
||||
engine_id = f"{vllm_config.instance_id}_dp{dp_index}"
|
||||
|
||||
dtype = vllm_config.model_config.dtype
|
||||
hidden_dim = _get_encoder_cache_hidden_dim(vllm_config)
|
||||
hidden_dim = vllm_config.model_config.get_inputs_embeds_size()
|
||||
element_size = torch.empty(0, dtype=dtype).element_size()
|
||||
block_size_bytes = hidden_dim * element_size
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ import json
|
||||
|
||||
import msgspec
|
||||
|
||||
# Bump when the on-wire shape (XferReq/XferAck) changes in a
|
||||
# Bump when the wire format or tensor/block layout changes in a
|
||||
# backward-incompatible way. Peers reject mismatched versions.
|
||||
EC_CONNECTOR_VERSION: int = 1
|
||||
EC_CONNECTOR_VERSION: int = 2
|
||||
|
||||
|
||||
class XferStatus(enum.IntEnum):
|
||||
|
||||
@@ -16,12 +16,14 @@ import torch
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.common import (
|
||||
ECCPUConnectorMetadata,
|
||||
ECCPUWorkerMetadata,
|
||||
_get_encoder_cache_hidden_dim,
|
||||
create_ec_shared_region,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.scheduler.embedding_cache import (
|
||||
EmbeddingCache,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.encoder_output_width import (
|
||||
get_encoder_output_width,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.utils import (
|
||||
PlaceholderMetadataResolver,
|
||||
collect_ec_item_metadata,
|
||||
@@ -49,6 +51,7 @@ class ECCPUScheduler:
|
||||
"""Scheduler delegate for the ECCPUConnector."""
|
||||
|
||||
def __init__(self, vllm_config: "VllmConfig") -> None:
|
||||
self._vllm_config = vllm_config
|
||||
ec_config = vllm_config.ec_transfer_config
|
||||
assert ec_config is not None
|
||||
self._is_producer: bool = ec_config.is_ec_producer
|
||||
@@ -61,8 +64,8 @@ class ECCPUScheduler:
|
||||
|
||||
# mm_hash → block IDs allocated this step for GPU→mmap saves.
|
||||
self._pending_saves: dict[str, list[int]] = {}
|
||||
# mm_hash → (transfer_id, block IDs) to load from mmap→GPU this step.
|
||||
self._pending_loads: dict[str, tuple[int, list[int]]] = {}
|
||||
# mm_hash → (transfer_id, block IDs, shape) to load from mmap→GPU.
|
||||
self._pending_loads: dict[str, tuple[int, list[int], tuple[int, int]]] = {}
|
||||
|
||||
# Dispatched loads awaiting completion reports, keyed by transfer id:
|
||||
# transfer_id → (mm_hash, reports still outstanding). The pin taken at
|
||||
@@ -108,11 +111,9 @@ class ECCPUScheduler:
|
||||
self._unrecoverable: set[str] = set()
|
||||
self._peer_host: str | None = None
|
||||
self._peer_port: int | None = None
|
||||
# Model shape for size checks + compat hash; only set by
|
||||
# _setup_nixl (the gate-off path never touches model_config).
|
||||
self._dtype: torch.dtype | None = None
|
||||
self._hidden_dim: int = 0
|
||||
self._element_size: int = 0
|
||||
dtype = vllm_config.model_config.dtype
|
||||
assert isinstance(dtype, torch.dtype)
|
||||
self._dtype = dtype
|
||||
self._ack_timeout_s: float = 0.0
|
||||
if self._nixl_enabled:
|
||||
try:
|
||||
@@ -148,9 +149,6 @@ class ECCPUScheduler:
|
||||
)
|
||||
engine_id = self._ec_config.engine_id
|
||||
assert engine_id is not None
|
||||
self._dtype = vllm_config.model_config.dtype
|
||||
self._hidden_dim = _get_encoder_cache_hidden_dim(vllm_config)
|
||||
self._element_size = torch.empty(0, dtype=self._dtype).element_size()
|
||||
# How long a consumer waits for an XferAck. The producer answers from
|
||||
# its scheduler step, so its reply latency scales with the encoder's
|
||||
# batch size: a deployment whose steps run longer must raise this.
|
||||
@@ -296,22 +294,30 @@ class ECCPUScheduler:
|
||||
# held by a quarantined/settling DMA and cannot be reused.
|
||||
return False
|
||||
|
||||
expected = pos.length * self._hidden_dim * self._element_size
|
||||
try:
|
||||
size = int(remote["size_bytes"])
|
||||
shape = tuple(int(dim) for dim in remote["shape"])
|
||||
except (KeyError, TypeError, ValueError) as error:
|
||||
raise _RemoteUnavailable("the announced size was unusable") from error
|
||||
if size != expected:
|
||||
# The width is the producer's to report; the row count is not.
|
||||
num_embeds = pos.get_num_embeds()
|
||||
if (
|
||||
len(shape) != 2
|
||||
or shape[0] != num_embeds
|
||||
or size != self._num_blocks(shape) * self._region.block_size_bytes
|
||||
):
|
||||
logger.warning(
|
||||
"EC consumer: size mismatch mm_hash=%s announced=%d expected=%d",
|
||||
"EC consumer: size mismatch mm_hash=%s announced=%d shape=%s "
|
||||
"expected %d rows",
|
||||
mm_hash,
|
||||
size,
|
||||
expected,
|
||||
shape,
|
||||
num_embeds,
|
||||
)
|
||||
raise _RemoteUnavailable("the announced size was wrong")
|
||||
|
||||
try:
|
||||
started = self._start_xfer(mm_hash, remote, expected)
|
||||
started = self._start_xfer(mm_hash, remote, size, (shape[0], shape[1]))
|
||||
except Exception as error:
|
||||
logger.exception(
|
||||
"EC consumer: failed to start NIXL xfer mm_hash=%s", mm_hash
|
||||
@@ -377,7 +383,11 @@ class ECCPUScheduler:
|
||||
return failed
|
||||
|
||||
def _start_xfer(
|
||||
self, mm_hash: str, info: "dict[str, Any]", size_bytes: int
|
||||
self,
|
||||
mm_hash: str,
|
||||
info: "dict[str, Any]",
|
||||
size_bytes: int,
|
||||
shape: tuple[int, int],
|
||||
) -> bool:
|
||||
"""Allocate a not-ready cache entry and start a NIXL READ into it.
|
||||
|
||||
@@ -391,7 +401,7 @@ class ECCPUScheduler:
|
||||
)
|
||||
|
||||
n_blocks = max(1, ceil(size_bytes / self._region.block_size_bytes))
|
||||
entry = self._cache.alloc(mm_hash, n_blocks)
|
||||
entry = self._cache.alloc(mm_hash, n_blocks, shape)
|
||||
if entry is None:
|
||||
logger.debug(
|
||||
"EC consumer: cache full for mm_hash=%s (%d blocks); deferring",
|
||||
@@ -491,22 +501,36 @@ class ECCPUScheduler:
|
||||
"""
|
||||
self._step_completed.clear()
|
||||
|
||||
def _num_blocks(self, shape: tuple[int, ...]) -> int:
|
||||
size_bytes = shape[0] * shape[1] * self._dtype.itemsize
|
||||
block_size = self._region.block_size_bytes
|
||||
return (size_bytes + block_size - 1) // block_size
|
||||
|
||||
def update_state_after_alloc(self, request: "Request", index: int) -> None:
|
||||
feature = request.mm_features[index]
|
||||
mm_hash = feature.identifier
|
||||
|
||||
if self._is_producer and self._cache.get(mm_hash) is None:
|
||||
entry = self._cache.alloc(mm_hash, feature.mm_position.length)
|
||||
shape = (
|
||||
feature.mm_position.get_num_embeds(),
|
||||
get_encoder_output_width(self._vllm_config, feature.modality),
|
||||
)
|
||||
entry = self._cache.alloc(mm_hash, self._num_blocks(shape), shape)
|
||||
if entry is not None:
|
||||
self._pending_saves[mm_hash] = list(entry.block_ids)
|
||||
|
||||
if self._is_consumer and mm_hash not in self._pending_loads:
|
||||
entry = self._cache.get(mm_hash)
|
||||
if entry is not None and entry.ready:
|
||||
assert entry.shape is not None
|
||||
self._cache.pin(mm_hash)
|
||||
transfer_id = self._next_transfer_id
|
||||
self._next_transfer_id += 1
|
||||
self._pending_loads[mm_hash] = (transfer_id, list(entry.block_ids))
|
||||
self._pending_loads[mm_hash] = (
|
||||
transfer_id,
|
||||
list(entry.block_ids),
|
||||
entry.shape,
|
||||
)
|
||||
self._load_acks[transfer_id] = (mm_hash, self._expected_load_reports)
|
||||
|
||||
def build_connector_meta(
|
||||
@@ -608,13 +632,13 @@ class ECCPUScheduler:
|
||||
# A read arriving before the save lands is NACKed NACK_NOT_READY,
|
||||
# which the consumer retries on a later step rather than treating
|
||||
# as a miss.
|
||||
size_bytes = (
|
||||
feature.mm_position.length * self._hidden_dim * self._element_size
|
||||
)
|
||||
assert entry.shape is not None
|
||||
size_bytes = len(entry.block_ids) * self._region.block_size_bytes
|
||||
items[mm_hash].update(
|
||||
peer_host=self._peer_host,
|
||||
peer_port=self._peer_port,
|
||||
size_bytes=size_bytes,
|
||||
shape=list(entry.shape),
|
||||
)
|
||||
logger.debug(
|
||||
"EC producer: announcing NIXL-readable encodings req_id=%s items=%s",
|
||||
|
||||
@@ -14,13 +14,20 @@ from collections import OrderedDict
|
||||
|
||||
|
||||
class CacheEntry:
|
||||
"""A single cache entry. Read `.block_ids` and `.ready` freely;
|
||||
mutations only through EmbeddingCache methods."""
|
||||
"""A single cache entry. Read `.block_ids`, `.shape` and `.ready` freely;
|
||||
mutations only through EmbeddingCache methods.
|
||||
|
||||
__slots__ = ("block_ids", "_pin_count")
|
||||
`shape` is the encoder output the blocks hold, so a load can restore it
|
||||
without knowing how wide this model's encoder output is.
|
||||
"""
|
||||
|
||||
def __init__(self, block_ids: tuple[int, ...]) -> None:
|
||||
__slots__ = ("block_ids", "shape", "_pin_count")
|
||||
|
||||
def __init__(
|
||||
self, block_ids: tuple[int, ...], shape: tuple[int, int] | None = None
|
||||
) -> None:
|
||||
self.block_ids = block_ids
|
||||
self.shape = shape
|
||||
self._pin_count = -1 # not ready
|
||||
|
||||
@property
|
||||
@@ -76,7 +83,9 @@ class EmbeddingCache:
|
||||
with self._lock:
|
||||
return len(self._entries) != len(self._entries_free_list)
|
||||
|
||||
def alloc(self, key: str, n_blocks: int) -> CacheEntry | None:
|
||||
def alloc(
|
||||
self, key: str, n_blocks: int, shape: tuple[int, int] | None = None
|
||||
) -> CacheEntry | None:
|
||||
"""Allocate *n_blocks* for *key*, evicting as needed.
|
||||
|
||||
The entry starts not-ready. Returns None if there is not enough
|
||||
@@ -97,7 +106,7 @@ class EmbeddingCache:
|
||||
# in the free list when it is evicted, and lets consumers detect
|
||||
# which of an entry's blocks are adjacent.
|
||||
block_ids = tuple(sorted(self._free_blocks.pop() for _ in range(n_blocks)))
|
||||
entry = CacheEntry(block_ids)
|
||||
entry = CacheEntry(block_ids, shape)
|
||||
self._entries[key] = entry
|
||||
return entry
|
||||
|
||||
|
||||
@@ -267,8 +267,7 @@ class ECCPUWorker:
|
||||
# so they are added up in uint64; signed arithmetic rejects them.
|
||||
src_base = np.uint64(src.view(-1).view(torch.uint8).data_ptr())
|
||||
dst_base = self._region.blocks.data_ptr()
|
||||
# Entries are sized by placeholder count, which can exceed the number
|
||||
# of embeddings, so blocks the output never reaches get no descriptor.
|
||||
# Copy only the tensor bytes, excluding any block padding.
|
||||
n_used = -(-total_bytes // block_size)
|
||||
if n_used:
|
||||
slots, first_blocks, num_blocks = _coalesce_runs(block_ids[:n_used])
|
||||
@@ -367,7 +366,7 @@ class ECCPUWorker:
|
||||
load_items = sorted(
|
||||
connector_metadata.loads.items(), key=lambda kv: kv[1][1][0]
|
||||
)
|
||||
total_blocks = sum(len(block_ids) for _, (_, block_ids) in load_items)
|
||||
total_blocks = sum(len(block_ids) for _, (_, block_ids, _) in load_items)
|
||||
|
||||
stream = self._acquire_stream()
|
||||
compute_stream = current_platform.current_stream()
|
||||
@@ -384,7 +383,7 @@ class ECCPUWorker:
|
||||
|
||||
bufs = self._buf_pool.acquire(total_blocks)
|
||||
slots, first_blocks, num_blocks = _coalesce_runs(
|
||||
list(chain.from_iterable(ids for _, (_, ids) in load_items))
|
||||
list(chain.from_iterable(ids for _, (_, ids, _) in load_items))
|
||||
)
|
||||
bufs.add_copies(
|
||||
0,
|
||||
@@ -405,7 +404,7 @@ class ECCPUWorker:
|
||||
Transfer(
|
||||
start_event=start_event,
|
||||
end_event=end_event,
|
||||
completions=[tid for _, (tid, _) in load_items],
|
||||
completions=[tid for _, (tid, _, _) in load_items],
|
||||
bufs=bufs,
|
||||
stream=stream,
|
||||
num_bytes=total_blocks * block_size,
|
||||
@@ -414,11 +413,10 @@ class ECCPUWorker:
|
||||
|
||||
# Slice contiguous buffer into per-hash views.
|
||||
offset = 0
|
||||
for mm_hash, (_, block_ids) in load_items:
|
||||
for mm_hash, (_, block_ids, shape) in load_items:
|
||||
n = len(block_ids)
|
||||
encoder_cache[mm_hash] = (
|
||||
dst_buf[offset : offset + n].view(dtype).reshape(n, -1)
|
||||
)
|
||||
flat = dst_buf[offset : offset + n].view(dtype).reshape(-1)
|
||||
encoder_cache[mm_hash] = flat[: shape[0] * shape[1]].view(shape)
|
||||
offset += n
|
||||
|
||||
current_platform.current_stream().wait_stream(stream)
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Encoder output widths for sizing EC transfers.
|
||||
|
||||
An encoder can emit features wider than the LM embedding (DeepStack packs
|
||||
several layers on the last dim) by an amount only the model knows. Producers
|
||||
size transfers before the first real item is encoded, so the engine measures
|
||||
the width once at startup by encoding a dummy item per modality.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def _measure_on_worker(worker: Any) -> dict[str, int]:
|
||||
"""Encode one dummy item per modality; runs on every worker.
|
||||
|
||||
Returns {} on ranks that hold no encoder.
|
||||
"""
|
||||
from vllm.distributed.parallel_state import get_pp_group
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.encoder_budget import MultiModalBudget
|
||||
from vllm.multimodal.utils import group_and_batch_mm_kwargs
|
||||
from vllm.utils.torch_utils import PIN_MEMORY
|
||||
|
||||
runner = worker.model_runner
|
||||
if not runner.supports_mm_inputs or not get_pp_group().is_first_rank:
|
||||
return {}
|
||||
budget = MultiModalBudget(
|
||||
worker.vllm_config, MULTIMODAL_REGISTRY, enable_cache=False
|
||||
)
|
||||
model = runner.get_model()
|
||||
widths: dict[str, int] = {}
|
||||
for modality in budget.mm_max_toks_per_item:
|
||||
items = budget.get_dummy_encoder_profile_inputs(modality, 1)
|
||||
if not items:
|
||||
continue
|
||||
_, _, mm_kwargs = next(
|
||||
group_and_batch_mm_kwargs(
|
||||
items, device=runner.device, pin_memory=PIN_MEMORY
|
||||
)
|
||||
)
|
||||
outputs = model.embed_multimodal(**mm_kwargs)
|
||||
widths[modality] = int(outputs[0].shape[-1])
|
||||
del outputs
|
||||
return widths
|
||||
|
||||
|
||||
def measure_encoder_output_widths(
|
||||
vllm_config: "VllmConfig", collective_rpc: Callable[..., list[Any]]
|
||||
) -> None:
|
||||
"""Record the encoder output widths on an EC producer's config.
|
||||
|
||||
Call after the model is loaded and before the KV cache is allocated: the
|
||||
Scheduler's connector reads the widths, and once the KV cache holds the
|
||||
memory budget there is no room left for a dummy encode.
|
||||
|
||||
Raises:
|
||||
ValueError: No worker could encode a dummy item, or workers disagree.
|
||||
|
||||
"""
|
||||
ec_config = vllm_config.ec_transfer_config
|
||||
if ec_config is None or not ec_config.is_ec_producer:
|
||||
return
|
||||
reports = [widths for widths in collective_rpc(_measure_on_worker) if widths]
|
||||
if not reports:
|
||||
raise ValueError(
|
||||
"EC producer could not measure the encoder output width: the model "
|
||||
"encoded no dummy multimodal input."
|
||||
)
|
||||
if any(widths != reports[0] for widths in reports):
|
||||
raise ValueError(f"Workers disagree on the encoder output widths: {reports}")
|
||||
logger.info("EC producer encoder output widths: %s", reports[0])
|
||||
ec_config.mm_encoder_output_widths = reports[0]
|
||||
|
||||
|
||||
def get_encoder_output_width(vllm_config: "VllmConfig", modality: str) -> int:
|
||||
"""Encoder output width for `modality`, as measured at producer startup.
|
||||
|
||||
Raises:
|
||||
ValueError: No width was measured for `modality`, so a transfer
|
||||
cannot be sized.
|
||||
|
||||
"""
|
||||
assert vllm_config.ec_transfer_config is not None
|
||||
widths = vllm_config.ec_transfer_config.mm_encoder_output_widths
|
||||
if modality not in widths:
|
||||
raise ValueError(
|
||||
f"No encoder output width was measured for modality {modality!r}; "
|
||||
f"measured: {sorted(widths)}"
|
||||
)
|
||||
return widths[modality]
|
||||
@@ -202,7 +202,7 @@ class ECExampleConnector(ECConnectorBase):
|
||||
|
||||
def _found_match_for_mm_data(self, mm_hash) -> bool:
|
||||
"""Check if the cache is hit for the request."""
|
||||
filename = self._generate_filename_debug(mm_hash)
|
||||
filename = self._generate_filename_debug(mm_hash, create_folder=False)
|
||||
return os.path.exists(filename)
|
||||
|
||||
def _generate_foldername_debug(
|
||||
@@ -219,11 +219,13 @@ class ECExampleConnector(ECConnectorBase):
|
||||
os.makedirs(foldername, exist_ok=True)
|
||||
return foldername
|
||||
|
||||
def _generate_filename_debug(self, mm_hash: str) -> str:
|
||||
def _generate_filename_debug(
|
||||
self,
|
||||
mm_hash: str,
|
||||
create_folder: bool = True,
|
||||
) -> str:
|
||||
"""Return the full path of the safetensors file for this mm_hash.
|
||||
Ensures the parent directory exists because
|
||||
`_generate_foldername_debug` is called with its default
|
||||
(`create_folder=True`).
|
||||
If `create_folder` is True (default) the parent directory is created.
|
||||
"""
|
||||
foldername = self._generate_foldername_debug(mm_hash) # <- folder auto-created
|
||||
foldername = self._generate_foldername_debug(mm_hash, create_folder)
|
||||
return os.path.join(foldername, "encoder_cache.safetensors")
|
||||
|
||||
@@ -20,8 +20,8 @@ import torch
|
||||
from vllm.distributed.ec_transfer.ec_connector.base import (
|
||||
ECConnectorMetadata,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.common import (
|
||||
_get_encoder_cache_hidden_dim,
|
||||
from vllm.distributed.ec_transfer.ec_connector.encoder_output_width import (
|
||||
get_encoder_output_width,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake.config import (
|
||||
_RESERVATION_TTL_SECONDS,
|
||||
@@ -85,9 +85,7 @@ class ECMooncakeScheduler:
|
||||
self._is_consumer = config.is_consumer
|
||||
self._control_addr = config.control_addr
|
||||
self._push_wait_timeout = config.push_wait_timeout_s
|
||||
self._encoder_cache_hidden_dim = (
|
||||
_get_encoder_cache_hidden_dim(vllm_config) if config.is_producer else None
|
||||
)
|
||||
self._vllm_config = vllm_config
|
||||
self._model_config = vllm_config.model_config
|
||||
self._control_client = ControlClient(config.control_timeout_ms)
|
||||
self._control_executor = ThreadPoolExecutor(
|
||||
@@ -447,8 +445,10 @@ class ECMooncakeScheduler:
|
||||
def _encoder_output_spec(self, request: Any, index: int) -> TensorSpec:
|
||||
dtype = self._model_config.dtype
|
||||
assert isinstance(dtype, torch.dtype)
|
||||
assert self._encoder_cache_hidden_dim is not None
|
||||
shape = (request.get_num_encoder_embeds(index), self._encoder_cache_hidden_dim)
|
||||
hidden_dim = get_encoder_output_width(
|
||||
self._vllm_config, request.mm_features[index].modality
|
||||
)
|
||||
shape = (request.get_num_encoder_embeds(index), hidden_dim)
|
||||
return TensorSpec(shape, str(dtype), math.prod(shape) * dtype.itemsize)
|
||||
|
||||
def update_state_after_alloc(self, request: Any, index: int) -> None:
|
||||
|
||||
@@ -323,39 +323,47 @@ class EplbState:
|
||||
"""
|
||||
if len(self.model_states) > 0:
|
||||
model = next(iter(self.model_states.values())).model
|
||||
if (
|
||||
model.num_routed_experts != new_model.num_routed_experts
|
||||
or model.num_redundant_experts != new_model.num_redundant_experts
|
||||
or model.num_physical_experts != new_model.num_physical_experts
|
||||
or model.num_logical_experts != new_model.num_logical_experts
|
||||
or model.num_expert_groups != new_model.num_expert_groups
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Model: {} "
|
||||
"with config {} "
|
||||
"{} {} {} {} "
|
||||
"mismatch with new model {} "
|
||||
"with config {} "
|
||||
"{} {} {} {}".format(
|
||||
type(model),
|
||||
model.num_routed_experts,
|
||||
model.num_redundant_experts,
|
||||
model.num_physical_experts,
|
||||
model.num_logical_experts,
|
||||
model.num_expert_groups,
|
||||
type(new_model),
|
||||
new_model.num_routed_experts,
|
||||
new_model.num_redundant_experts,
|
||||
new_model.num_physical_experts,
|
||||
new_model.num_logical_experts,
|
||||
new_model.num_expert_groups,
|
||||
)
|
||||
self.assert_confs_equal(model, new_model)
|
||||
|
||||
@staticmethod
|
||||
def assert_confs_equal(
|
||||
model: MixtureOfExperts, new_model: MixtureOfExperts
|
||||
) -> None:
|
||||
"""Raise if the models have different expert parallel configurations."""
|
||||
if (
|
||||
model.num_routed_experts != new_model.num_routed_experts
|
||||
or model.num_redundant_experts != new_model.num_redundant_experts
|
||||
or model.num_physical_experts != new_model.num_physical_experts
|
||||
or model.num_logical_experts != new_model.num_logical_experts
|
||||
or model.num_expert_groups != new_model.num_expert_groups
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Model: {} "
|
||||
"with config {} "
|
||||
"{} {} {} {} "
|
||||
"mismatch with new model {} "
|
||||
"with config {} "
|
||||
"{} {} {} {}".format(
|
||||
type(model),
|
||||
model.num_routed_experts,
|
||||
model.num_redundant_experts,
|
||||
model.num_physical_experts,
|
||||
model.num_logical_experts,
|
||||
model.num_expert_groups,
|
||||
type(new_model),
|
||||
new_model.num_routed_experts,
|
||||
new_model.num_redundant_experts,
|
||||
new_model.num_physical_experts,
|
||||
new_model.num_logical_experts,
|
||||
new_model.num_expert_groups,
|
||||
)
|
||||
)
|
||||
|
||||
def add_model(
|
||||
self,
|
||||
model: MixtureOfExperts,
|
||||
model_config: ModelConfig,
|
||||
model_name: str | None = None,
|
||||
):
|
||||
"""Build the initial EPLB state."""
|
||||
self.validate_ep_configuration(model)
|
||||
@@ -506,7 +514,7 @@ class EplbState:
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
),
|
||||
model_name=model_config.model,
|
||||
model_name=model_name or model_config.model,
|
||||
model=model,
|
||||
expert_buffer=expert_buffer,
|
||||
rebalanced=False,
|
||||
@@ -576,15 +584,15 @@ class EplbState:
|
||||
|
||||
"""
|
||||
ep_group = get_ep_group().device_group
|
||||
if is_profile:
|
||||
self.rearrange(is_profile=True)
|
||||
return
|
||||
|
||||
if is_dummy:
|
||||
# Do not record load metrics for dummy steps
|
||||
for eplb_model_state in self.model_states.values():
|
||||
eplb_model_state.expert_load_pass.zero_()
|
||||
|
||||
if is_profile:
|
||||
self.rearrange(is_profile=True)
|
||||
return
|
||||
|
||||
if (
|
||||
log_stats
|
||||
and self.expert_rearrangement_step
|
||||
|
||||
@@ -20,6 +20,7 @@ from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.attention.backend import AttentionBackend
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheConfig
|
||||
from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -351,6 +352,35 @@ def get_current_attn_backends(
|
||||
]
|
||||
|
||||
|
||||
def get_current_attn_backends_and_specs(
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
fallback: list[type[AttentionBackend]],
|
||||
) -> tuple[list[type[AttentionBackend]], list[AttentionSpec | None]]:
|
||||
"""Distinct (backend, spec) pairs of the transfer layers, else ``fallback``.
|
||||
|
||||
Compressed caches are skipped: their kernel pages never split transferred
|
||||
blocks.
|
||||
"""
|
||||
pairs: dict[tuple[type[AttentionBackend], AttentionSpec | None], None] = {}
|
||||
layer_type = cast(type[Any], AttentionLayerBase)
|
||||
for group in kv_cache_config.transfer_groups:
|
||||
specs = getattr(group.kv_cache_spec, "kv_cache_specs", {})
|
||||
layers = get_layers_from_vllm_config(vllm_config, layer_type, group.layer_names)
|
||||
for name, layer in layers.items():
|
||||
spec = specs.get(name, group.kv_cache_spec)
|
||||
if isinstance(spec, AttentionSpec) and spec.tokens_per_state > 1:
|
||||
layout = vllm_config.cache_config.get_resolved_kv_cache_layout()
|
||||
assert layout.is_block_outermost, "Compressed caches must be packed"
|
||||
continue
|
||||
if not isinstance(spec, AttentionSpec):
|
||||
spec = None
|
||||
pairs[layer.get_attn_backend(), spec] = None
|
||||
if not pairs:
|
||||
return fallback, [None] * len(fallback)
|
||||
return [backend for backend, _ in pairs], [spec for _, spec in pairs]
|
||||
|
||||
|
||||
def get_current_attn_backend(
|
||||
vllm_config: VllmConfig, layer_names: list[str] | None = None
|
||||
) -> type[AttentionBackend]:
|
||||
|
||||
@@ -56,6 +56,7 @@ from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.kv_transfer import KVTransferConfig
|
||||
from vllm.distributed.kv_events import KVCacheEvent, KVConnectorKVEvents
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
KVConnectorPromMetrics,
|
||||
@@ -205,6 +206,11 @@ class KVConnectorBase_V1(ABC):
|
||||
"""
|
||||
return self._kv_transfer_config.is_kv_producer
|
||||
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: "KVTransferConfig") -> bool:
|
||||
"""Whether the connector can follow the KV cache remap of sleep mode."""
|
||||
return True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
@@ -293,6 +299,15 @@ class KVConnectorBase_V1(ABC):
|
||||
"""
|
||||
return
|
||||
|
||||
def unregister_kv_caches(self) -> None:
|
||||
"""Drop KV cache registrations before sleep. Transfers are already
|
||||
drained. Idempotent."""
|
||||
return
|
||||
|
||||
def restore_kv_caches(self) -> None:
|
||||
"""Redo `unregister_kv_caches` after wake-up. Idempotent."""
|
||||
return
|
||||
|
||||
def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp):
|
||||
"""Set the xPU-specific ops for copying KV between host and device.
|
||||
Needed when host buffer is used for kv transfer (e.g., in NixlConnector)
|
||||
|
||||
@@ -36,7 +36,11 @@ 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.hisparse.types import (
|
||||
SparseKVOffloadCommand,
|
||||
SparseKVResidencyUpdate,
|
||||
SparseKVRowMirror,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -56,6 +60,7 @@ class HiSparseConnectorMetadata(KVConnectorMetadata):
|
||||
source_block_ids: tuple[int, ...]
|
||||
row_mirrors: dict[str, tuple[SparseKVRowMirror, ...]]
|
||||
all_context_pages_resident: bool
|
||||
residency_updates: dict[str, SparseKVResidencyUpdate]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -112,6 +117,8 @@ class HiSparseConnectorScheduler:
|
||||
stats.record_host_usage(
|
||||
host_pool.get_usage(), len(self.coordinator.pending_spills)
|
||||
)
|
||||
if host_pool.metrics_collector is not None:
|
||||
stats.record_host_evictions(host_pool.metrics_collector.drain_events())
|
||||
return stats
|
||||
|
||||
def build_connector_meta(
|
||||
@@ -141,7 +148,7 @@ class HiSparseConnectorScheduler:
|
||||
scheduler_output.num_scheduled_tokens.items()
|
||||
)
|
||||
)
|
||||
# Runs first: it plans this step's transfers and table updates.
|
||||
# Runs first: it plans this step's transfers and residency changes.
|
||||
self.coordinator.advance_scheduled(
|
||||
(
|
||||
request_id,
|
||||
@@ -149,9 +156,6 @@ class HiSparseConnectorScheduler:
|
||||
)
|
||||
for request_id, start, count in scheduled_requests
|
||||
)
|
||||
scheduler_output.block_table_updates = (
|
||||
self.coordinator.take_block_table_updates() or None
|
||||
)
|
||||
command = self.coordinator.build_offload_command()
|
||||
host_block_copies = self.coordinator.take_host_block_copies()
|
||||
source_group_id = self.coordinator.host_group_id
|
||||
@@ -190,6 +194,9 @@ class HiSparseConnectorScheduler:
|
||||
tuple(source_block_ids),
|
||||
row_mirrors,
|
||||
self.coordinator.all_context_pages_resident(scheduled_requests),
|
||||
self.coordinator.take_residency_updates(
|
||||
scheduler_output.num_scheduled_tokens
|
||||
),
|
||||
)
|
||||
|
||||
def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
|
||||
|
||||
@@ -12,6 +12,8 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
PromMetric,
|
||||
PromMetricT,
|
||||
)
|
||||
from vllm.v1.metrics.buckets import histogram_buckets
|
||||
from vllm.v1.metrics.stats import KVCacheEvictionEvent
|
||||
from vllm.v1.metrics.utils import create_metric_per_engine
|
||||
|
||||
_HISPARSE_LEVEL_KEYS = frozenset({"host_cache_usage_perc", "pending_page_transfers"})
|
||||
@@ -40,6 +42,9 @@ class HiSparseKVConnectorStats(KVConnectorStats):
|
||||
"host_to_device_bytes": [],
|
||||
"host_cache_usage_perc": [],
|
||||
"pending_page_transfers": [],
|
||||
"host_block_lifetime_seconds": [],
|
||||
"host_block_idle_before_evict_seconds": [],
|
||||
"host_block_reuse_gap_seconds": [],
|
||||
}
|
||||
|
||||
def record_snapshot(self, hits: int, misses: int, host_to_device_bytes: int):
|
||||
@@ -51,6 +56,12 @@ class HiSparseKVConnectorStats(KVConnectorStats):
|
||||
self.data["host_cache_usage_perc"].append(usage)
|
||||
self.data["pending_page_transfers"].append(pending_page_transfers)
|
||||
|
||||
def record_host_evictions(self, events: list[KVCacheEvictionEvent]) -> None:
|
||||
for event in events:
|
||||
self.data["host_block_lifetime_seconds"].append(event.lifetime_seconds)
|
||||
self.data["host_block_idle_before_evict_seconds"].append(event.idle_seconds)
|
||||
self.data["host_block_reuse_gap_seconds"].extend(event.reuse_gaps_seconds)
|
||||
|
||||
def aggregate(self, other: KVConnectorStats) -> KVConnectorStats:
|
||||
if not other.is_empty():
|
||||
for k, v in other.data.items():
|
||||
@@ -143,6 +154,53 @@ class HiSparsePromMetrics(KVConnectorPromMetrics):
|
||||
),
|
||||
}
|
||||
|
||||
self.hisparse_histograms: dict[str, Any] = {}
|
||||
if vllm_config.observability_config.kv_cache_metrics:
|
||||
residency_buckets = histogram_buckets(
|
||||
"kv_cache_residency",
|
||||
overrides=vllm_config.observability_config.custom_histogram_buckets,
|
||||
)
|
||||
histogram_host_block_lifetime = self._histogram_cls(
|
||||
name="vllm:hisparse_host_block_lifetime_seconds",
|
||||
documentation=(
|
||||
"Histogram of HiSparse host KV block lifetime from allocation "
|
||||
"to eviction. Sampled metrics (controlled by "
|
||||
"--kv-cache-metrics-sample)."
|
||||
),
|
||||
buckets=residency_buckets,
|
||||
labelnames=labelnames,
|
||||
)
|
||||
histogram_host_block_idle_before_evict = self._histogram_cls(
|
||||
name="vllm:hisparse_host_block_idle_before_evict_seconds",
|
||||
documentation=(
|
||||
"Histogram of HiSparse host KV block idle time before eviction. "
|
||||
"Sampled metrics (controlled by --kv-cache-metrics-sample)."
|
||||
),
|
||||
buckets=residency_buckets,
|
||||
labelnames=labelnames,
|
||||
)
|
||||
histogram_host_block_reuse_gap = self._histogram_cls(
|
||||
name="vllm:hisparse_host_block_reuse_gap_seconds",
|
||||
documentation=(
|
||||
"Histogram of time gaps between consecutive HiSparse host KV "
|
||||
"block accesses. Sampled metrics (controlled by "
|
||||
"--kv-cache-metrics-sample)."
|
||||
),
|
||||
buckets=residency_buckets,
|
||||
labelnames=labelnames,
|
||||
)
|
||||
self.hisparse_histograms = {
|
||||
"host_block_lifetime_seconds": create_metric_per_engine(
|
||||
histogram_host_block_lifetime, self.per_engine_labelvalues
|
||||
),
|
||||
"host_block_idle_before_evict_seconds": create_metric_per_engine(
|
||||
histogram_host_block_idle_before_evict, self.per_engine_labelvalues
|
||||
),
|
||||
"host_block_reuse_gap_seconds": create_metric_per_engine(
|
||||
histogram_host_block_reuse_gap, 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, []):
|
||||
@@ -151,3 +209,6 @@ class HiSparsePromMetrics(KVConnectorPromMetrics):
|
||||
values = transfer_stats_data.get(name, [])
|
||||
if values:
|
||||
gauge[engine_idx].set(values[-1])
|
||||
for name, histogram in self.hisparse_histograms.items():
|
||||
for value in transfer_stats_data.get(name, []):
|
||||
histogram[engine_idx].observe(value)
|
||||
|
||||
@@ -26,7 +26,11 @@ from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.utils.torch_utils import current_stream
|
||||
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
|
||||
from vllm.v1.hisparse.layout import HISPARSE_HOT_SUFFIX
|
||||
from vllm.v1.hisparse.runtime import HiSparseCacheHandle, release_pinned_state
|
||||
from vllm.v1.hisparse.runtime import (
|
||||
HiSparseCacheHandle,
|
||||
release_pinned_state,
|
||||
update_hisparse_residency,
|
||||
)
|
||||
from vllm.v1.hisparse.types import SparseKVPageTransfer, SparseKVRowMirror
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
HiSparseHotSpec,
|
||||
@@ -334,6 +338,10 @@ class HiSparseConnectorWorker:
|
||||
"HiSparse request-state mapping does not match max_num_seqs."
|
||||
)
|
||||
self.hot_backing = hot_backing
|
||||
self.residency: torch.Tensor | None = next(
|
||||
(cache.residency for cache in cache_handles if cache.residency is not None),
|
||||
None,
|
||||
)
|
||||
self._pending_invalid_block_ids: list[int] = []
|
||||
# Destination block ids of host copies this worker has run.
|
||||
self._completed_host_copy_dst_ids: list[int] = []
|
||||
@@ -408,6 +416,10 @@ class HiSparseConnectorWorker:
|
||||
self.host_write_event = self.host_write_events[self._next_host_write_event]
|
||||
self._next_host_write_event ^= 1
|
||||
current_stream().wait_event(previous_host_write_event)
|
||||
if self.shared_host_region is not None and not num_tokens:
|
||||
# Without a forward, no TP collective keeps rank 0 from recording
|
||||
# a shared event again before every rank has issued its wait.
|
||||
get_tp_group().barrier()
|
||||
self._release_completed_dma_descriptors()
|
||||
self._dma_submitted = False
|
||||
mirrors = _flatten_row_mirrors(metadata.row_mirrors, request_ids)
|
||||
@@ -437,6 +449,15 @@ class HiSparseConnectorWorker:
|
||||
self._pending_invalid_block_ids.extend(metadata.source_block_ids)
|
||||
if request_state_indices is not None:
|
||||
self.set_request_state_indices(request_state_indices)
|
||||
if metadata.residency_updates:
|
||||
assert self.residency is not None
|
||||
assert request_state_indices is not None and request_ids is not None
|
||||
update_hisparse_residency(
|
||||
self.residency,
|
||||
metadata.residency_updates,
|
||||
request_ids,
|
||||
request_state_indices,
|
||||
)
|
||||
|
||||
def _clear_forward_mirror_state(self) -> None:
|
||||
self._per_layer_mirrored.clear()
|
||||
|
||||
@@ -99,8 +99,13 @@ class KVConnectorLogging:
|
||||
# Produce a single cumulative stats object for the last time
|
||||
# interval from the recorded observations.
|
||||
xfer_metrics = self.transfer_stats_accumulator.reduce()
|
||||
xfer_metrics_str = ", ".join(f"{k}={v}" for k, v in xfer_metrics.items())
|
||||
log_fn("KV Transfer metrics: %s", xfer_metrics_str)
|
||||
# A payload can hold static config facts alone (info metric), which reduce()
|
||||
# drops, because they belong to the Prometheus metrics only.
|
||||
if xfer_metrics:
|
||||
xfer_metrics_str = ", ".join(
|
||||
f"{k}={v}" for k, v in xfer_metrics.items()
|
||||
)
|
||||
log_fn("KV Transfer metrics: %s", xfer_metrics_str)
|
||||
|
||||
# Reset metrics for next interval
|
||||
self.reset()
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
import asyncio
|
||||
import itertools
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections import OrderedDict, defaultdict
|
||||
from collections.abc import Collection
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
@@ -21,11 +23,12 @@ import zmq.asyncio
|
||||
from huggingface_hub.utils import httpx
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
EngineId,
|
||||
TransferTopology,
|
||||
get_current_attn_backends,
|
||||
get_current_attn_backends_and_specs,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorBase_V1,
|
||||
@@ -59,8 +62,8 @@ from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KpoolTailSpec,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
@@ -69,12 +72,14 @@ from vllm.v1.kv_cache_interface import (
|
||||
)
|
||||
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
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_BOOTSTRAP_MAX_ATTEMPTS: Final[int] = 3
|
||||
# Decode restarts mint new layout ids, so stale peer layouts pile up. Evicting
|
||||
# one only costs that peer a LAYOUT_MISS and one layout resend.
|
||||
_MAX_PEER_LAYOUTS: Final[int] = 1024
|
||||
|
||||
try:
|
||||
from mooncake.engine import TransferEngine
|
||||
@@ -622,6 +627,9 @@ class MooncakeXferMetadata(
|
||||
# peer did not send the field, so the run must not be promoted.
|
||||
registered_row_offsets: list[int] = msgspec.field(default_factory=list)
|
||||
remote_pp_size: int = 1
|
||||
# Random per register_kv_caches, so ids never repeat across restarts.
|
||||
# 0 means the peer sends the layout on every pull.
|
||||
layout_id: int = 0
|
||||
|
||||
|
||||
class MooncakeXferResponseStatus(IntEnum):
|
||||
@@ -631,6 +639,9 @@ class MooncakeXferResponseStatus(IntEnum):
|
||||
CONTINUE = 1
|
||||
# Something wrong, see err_msg
|
||||
ERROR = 2
|
||||
# P does not hold the layout for this layout_id; resend it.
|
||||
# Only sent for pulls with a nonzero layout_id and no layout.
|
||||
LAYOUT_MISS = 3
|
||||
|
||||
|
||||
class MooncakeXferResponse(
|
||||
@@ -641,6 +652,9 @@ class MooncakeXferResponse(
|
||||
ok_reqs: list[ReqId] | None = None
|
||||
err_reqs: list[ReqId] | None = None
|
||||
err_msg: str | None = None
|
||||
# The pull's layout_id once P holds that layout. D omits the layout only
|
||||
# after seeing it, so a P that predates this field always gets it.
|
||||
layout_id: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -800,10 +814,34 @@ class MooncakeConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
############################################################
|
||||
# Worker Side Methods
|
||||
############################################################
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: KVTransferConfig) -> bool:
|
||||
# Sleep mode is only validated over RDMA, not NVLink or TENT.
|
||||
if any(
|
||||
v in os.environ
|
||||
for v in (
|
||||
"MC_FORCE_MNNVL",
|
||||
"MC_INTRANODE_NVLINK",
|
||||
"MC_USE_TENT",
|
||||
"MC_USE_TEV1",
|
||||
)
|
||||
):
|
||||
return False
|
||||
extra_config = kv_transfer_config.kv_connector_extra_config
|
||||
return extra_config.get("mooncake_protocol", "rdma") == "rdma"
|
||||
|
||||
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
|
||||
assert self.connector_worker is not None
|
||||
self.connector_worker.register_kv_caches(kv_caches)
|
||||
|
||||
def unregister_kv_caches(self) -> None:
|
||||
assert self.connector_worker is not None
|
||||
self.connector_worker.unregister_kv_caches()
|
||||
|
||||
def restore_kv_caches(self) -> None:
|
||||
assert self.connector_worker is not None
|
||||
self.connector_worker.restore_kv_caches()
|
||||
|
||||
def get_finished(
|
||||
self, finished_req_ids: set[str]
|
||||
) -> tuple[set[str] | None, set[str] | None]:
|
||||
@@ -1239,12 +1277,22 @@ class MooncakeConnectorWorker:
|
||||
self.region_row_offsets: list[int] = []
|
||||
self.opaque_packed_storages: set[int] = set()
|
||||
self.seen_base_addresses: list[int] = []
|
||||
self._kv_data_lens: list[int] = []
|
||||
self._kv_unregistered = False
|
||||
# Aligned regions depend only on the peer's registered layout.
|
||||
# The third item is an error string when alignment cannot proceed.
|
||||
self._prepared_transfer_regions: dict[
|
||||
tuple,
|
||||
tuple[list[TransferRegion], list[TransferRegion], str | None],
|
||||
] = {}
|
||||
# (host, port, tp_rank, pp_size, tp_size, layout_id) -> regions, in LRU
|
||||
# order. Filled only after a pull that actually carried the layout.
|
||||
self._layout_by_peer: OrderedDict[
|
||||
tuple, tuple[list[TransferRegion], list[TransferRegion]]
|
||||
] = OrderedDict()
|
||||
self._kv_layout_id = 0
|
||||
# Decode side: worker addresses that echoed the current layout_id.
|
||||
self._acked_layout_peers: set[str] = set()
|
||||
|
||||
assert (parallel_config := vllm_config.parallel_config)
|
||||
dp_rank = parallel_config.data_parallel_index
|
||||
@@ -1350,7 +1398,10 @@ class MooncakeConnectorWorker:
|
||||
# physical block sizes. Pick the common (smallest) block size so that
|
||||
# KV-cache registration and transfer work correctly for both models.
|
||||
backends = get_current_attn_backends(self.vllm_config)
|
||||
kernel_block_size = select_common_block_size(self.block_size, backends)
|
||||
backends, specs = get_current_attn_backends_and_specs(
|
||||
self.vllm_config, self.kv_cache_config, backends
|
||||
)
|
||||
kernel_block_size = select_common_block_size(self.block_size, backends, specs)
|
||||
if self.block_size != kernel_block_size:
|
||||
logger.info_once(
|
||||
"User-specified logical block size (%s) does not match"
|
||||
@@ -1531,14 +1582,30 @@ class MooncakeConnectorWorker:
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
return
|
||||
local_regions, remote_regions, prep_err = self._prepare_transfer_regions(meta)
|
||||
if prep_err is not None:
|
||||
response = MooncakeXferResponse(
|
||||
status=MooncakeXferResponseStatus.ERROR,
|
||||
err_msg=prep_err,
|
||||
if meta.layout_id and not meta.kv_caches_base_addr:
|
||||
stored = self._lookup_peer_layout(meta)
|
||||
if stored is None:
|
||||
response = MooncakeXferResponse(
|
||||
status=MooncakeXferResponseStatus.LAYOUT_MISS,
|
||||
err_msg=(
|
||||
f"Mooncake KV layout {meta.layout_id:#x} from "
|
||||
f"{meta.remote_hostname}:{meta.remote_port} is not cached."
|
||||
),
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
return
|
||||
local_regions, remote_regions = stored
|
||||
else:
|
||||
local_regions, remote_regions, prep_err = self._prepare_transfer_regions(
|
||||
meta
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
return
|
||||
if prep_err is not None:
|
||||
response = MooncakeXferResponse(
|
||||
status=MooncakeXferResponseStatus.ERROR,
|
||||
err_msg=prep_err,
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
return
|
||||
validation_err = _validate_asymmetric_region_lengths(
|
||||
local_regions=local_regions,
|
||||
remote_regions=remote_regions,
|
||||
@@ -1599,6 +1666,7 @@ class MooncakeConnectorWorker:
|
||||
status=MooncakeXferResponseStatus.FINISH,
|
||||
err_reqs=list(pending_reqs),
|
||||
err_msg="Timeout waiting for P side ready.",
|
||||
layout_id=meta.layout_id,
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
break
|
||||
@@ -1689,6 +1757,7 @@ class MooncakeConnectorWorker:
|
||||
ok_reqs=[d_req_id for d_req_id, _ in ok_ready_reqs] or None,
|
||||
err_reqs=err_reqs or None,
|
||||
err_msg=err_msg,
|
||||
layout_id=meta.layout_id,
|
||||
)
|
||||
await sock.send_multipart((identity, self._encoder.encode(response)))
|
||||
|
||||
@@ -1727,11 +1796,12 @@ class MooncakeConnectorWorker:
|
||||
)
|
||||
group_specs = self.kv_cache_config.transfer_groups
|
||||
return [
|
||||
BlockTable.map_to_kernel_blocks(
|
||||
np.array(group),
|
||||
self._physical_blocks_per_logical_kv_block,
|
||||
block_arange,
|
||||
).tolist()
|
||||
(
|
||||
np.array(group)[:, None] * self._physical_blocks_per_logical_kv_block
|
||||
+ block_arange
|
||||
)
|
||||
.reshape(-1)
|
||||
.tolist()
|
||||
if not isinstance(group_specs[i].kv_cache_spec, MambaSpec)
|
||||
else group
|
||||
for i, group in enumerate(block_ids)
|
||||
@@ -1987,6 +2057,10 @@ class MooncakeConnectorWorker:
|
||||
self.region_row_offsets = []
|
||||
self.opaque_packed_storages = set()
|
||||
self._prepared_transfer_regions.clear()
|
||||
self._layout_by_peer.clear()
|
||||
self._acked_layout_peers.clear()
|
||||
# Odd, so never 0 (the "layout on every pull" marker).
|
||||
self._kv_layout_id = secrets.randbits(63) | 1
|
||||
|
||||
packed_storage_to_region: dict[int, int] = {}
|
||||
packed_view_to_region: dict[tuple[int, int, int], int] = {}
|
||||
@@ -2054,7 +2128,7 @@ class MooncakeConnectorWorker:
|
||||
# hetero PP can align by name (#56033). A non-contiguous row cannot
|
||||
# name a sub-span, so it is one region anchored at the allocation.
|
||||
use_packed_row = (
|
||||
not isinstance(layer_spec, (MambaSpec, KpoolTailSpec))
|
||||
not isinstance(layer_spec, (MambaSpec, CircularBufferSpec))
|
||||
and storage_is_block_major
|
||||
and block_stride > 0
|
||||
and (is_mla_region or not hnc_contiguous)
|
||||
@@ -2121,9 +2195,7 @@ class MooncakeConnectorWorker:
|
||||
block_len = region_cache.stride(0) * region_cache.element_size()
|
||||
region_base_addresses.append(base_addr)
|
||||
|
||||
if isinstance(layer_spec, KpoolTailSpec):
|
||||
kv_block_len = layer_spec.unpadded_page_size_bytes // 2
|
||||
elif isinstance(layer_spec, AttentionSpec) and block_is_contiguous:
|
||||
if isinstance(layer_spec, AttentionSpec) and block_is_contiguous:
|
||||
assert (
|
||||
layer_spec.page_size_bytes
|
||||
% self._physical_blocks_per_logical_kv_block
|
||||
@@ -2133,6 +2205,8 @@ class MooncakeConnectorWorker:
|
||||
layer_spec.page_size_bytes
|
||||
// self._physical_blocks_per_logical_kv_block
|
||||
)
|
||||
elif isinstance(layer_spec, MambaSpec) and block_is_contiguous:
|
||||
kv_block_len = layer_spec.page_size_bytes
|
||||
else:
|
||||
kv_block_len = block_len
|
||||
if kv_block_len > block_len:
|
||||
@@ -2152,6 +2226,7 @@ class MooncakeConnectorWorker:
|
||||
|
||||
self.kv_caches_base_addr = region_base_addresses
|
||||
self.seen_base_addresses = kv_data_ptrs
|
||||
self._kv_data_lens = kv_data_lens
|
||||
|
||||
if not kv_data_ptrs:
|
||||
raise RuntimeError("No KV cache tensors were registered with Mooncake.")
|
||||
@@ -2207,6 +2282,24 @@ class MooncakeConnectorWorker:
|
||||
f"{ready_timeout:.0f}s."
|
||||
)
|
||||
|
||||
def unregister_kv_caches(self) -> None:
|
||||
if self._kv_unregistered or not self.seen_base_addresses:
|
||||
return
|
||||
ret_value = self.engine.batch_unregister_memory(self.seen_base_addresses)
|
||||
if ret_value != 0:
|
||||
raise RuntimeError("Mooncake batch memory unregistration failed.")
|
||||
self._kv_unregistered = True
|
||||
|
||||
def restore_kv_caches(self) -> None:
|
||||
if not self._kv_unregistered:
|
||||
return
|
||||
ret_value = self.engine.batch_register_memory(
|
||||
self.seen_base_addresses, self._kv_data_lens
|
||||
)
|
||||
if ret_value != 0:
|
||||
raise RuntimeError("Mooncake batch memory registration failed.")
|
||||
self._kv_unregistered = False
|
||||
|
||||
async def fetch_finished_recving_reqs(self) -> set[ReqId]:
|
||||
finished_recving_reqs = self.finished_recving_reqs
|
||||
self.finished_recving_reqs = set()
|
||||
@@ -2307,64 +2400,74 @@ class MooncakeConnectorWorker:
|
||||
pull_metas: dict[ReqId, PullReqMeta],
|
||||
):
|
||||
req_ids = set(pull_metas)
|
||||
metadata = MooncakeXferMetadata(
|
||||
remote_hostname=self.hostname,
|
||||
remote_port=self.rpc_port,
|
||||
remote_tp_size=self.tp_size,
|
||||
remote_tp_rank=self.tp_rank,
|
||||
remote_pp_size=self.pp_size,
|
||||
req_blocks={
|
||||
req_id: (pull_meta.transfer_id, pull_meta.local_block_ids)
|
||||
for req_id, pull_meta in pull_metas.items()
|
||||
},
|
||||
kv_caches_base_addr=self.kv_caches_base_addr,
|
||||
block_lens=self.block_len_per_layer,
|
||||
kv_block_lens=self.kv_block_len_per_layer,
|
||||
registered_layer_names=self.registered_layer_names,
|
||||
registered_layer_indices=self.registered_layer_indices,
|
||||
registered_group_indices=self.registered_group_indices,
|
||||
registered_shared_group_ids=[
|
||||
list(groups) for groups in self.region_shared_groups
|
||||
],
|
||||
registered_row_offsets=self.region_row_offsets,
|
||||
include_layout = (
|
||||
not self._kv_layout_id or worker_addr not in self._acked_layout_peers
|
||||
)
|
||||
|
||||
encoded_data = self._encoder.encode(metadata)
|
||||
logger.debug(
|
||||
"Size of encoded MooncakeXferMetadata: %d bytes", len(encoded_data)
|
||||
)
|
||||
logger.debug(
|
||||
"Sending kv transfer request for %s on path: %s", req_ids, worker_addr
|
||||
)
|
||||
|
||||
# Send query for the request.
|
||||
try:
|
||||
with make_zmq_socket(
|
||||
self.async_zmq_ctx, worker_addr, zmq.DEALER, bind=False, linger=0
|
||||
) as sock:
|
||||
# If something goes wrong, let P wait timeout first (in asyncio.wait()).
|
||||
sock.setsockopt(
|
||||
zmq.RCVTIMEO, (envs.VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT + 60) * 1000
|
||||
# Each pass either returns or breaks out of the recv loop to resend
|
||||
# the layout after a LAYOUT_MISS.
|
||||
while True:
|
||||
metadata = self._build_pull_metadata(
|
||||
pull_metas, include_layout=include_layout
|
||||
)
|
||||
encoded_data = self._encoder.encode(metadata)
|
||||
logger.debug(
|
||||
"MooncakeXferMetadata to %s is %d bytes (%s).",
|
||||
worker_addr,
|
||||
len(encoded_data),
|
||||
"layout" if include_layout else "blocks",
|
||||
)
|
||||
logger.debug(
|
||||
"Sending kv transfer request for %s on path: %s", req_ids, worker_addr
|
||||
)
|
||||
try:
|
||||
with make_zmq_socket(
|
||||
self.async_zmq_ctx, worker_addr, zmq.DEALER, bind=False, linger=0
|
||||
) as sock:
|
||||
sock.setsockopt(
|
||||
zmq.RCVTIMEO,
|
||||
(envs.VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT + 60) * 1000,
|
||||
)
|
||||
await sock.send(encoded_data)
|
||||
while True:
|
||||
ret_msg = await sock.recv()
|
||||
response = self._xfer_resp_decoder.decode(ret_msg)
|
||||
status = response.status
|
||||
if status == MooncakeXferResponseStatus.LAYOUT_MISS:
|
||||
self._acked_layout_peers.discard(worker_addr)
|
||||
if not include_layout:
|
||||
logger.info(
|
||||
"Mooncake prefill %s lost the KV layout; "
|
||||
"resending it.",
|
||||
worker_addr,
|
||||
)
|
||||
include_layout = True
|
||||
break
|
||||
if status in (
|
||||
MooncakeXferResponseStatus.ERROR,
|
||||
MooncakeXferResponseStatus.LAYOUT_MISS,
|
||||
):
|
||||
self._handle_failed_recv(
|
||||
pull_metas,
|
||||
req_ids,
|
||||
response.err_msg or "transfer error",
|
||||
)
|
||||
return
|
||||
if (
|
||||
self._kv_layout_id
|
||||
and response.layout_id == self._kv_layout_id
|
||||
):
|
||||
self._acked_layout_peers.add(worker_addr)
|
||||
self.process_pulling_result(response, pull_metas)
|
||||
if status == MooncakeXferResponseStatus.FINISH:
|
||||
return
|
||||
except zmq.ContextTerminated:
|
||||
logger.debug(
|
||||
"ZMQ context terminated, exiting Mooncake receiver thread."
|
||||
)
|
||||
await sock.send(encoded_data)
|
||||
while True:
|
||||
ret_msg = await sock.recv()
|
||||
response = self._xfer_resp_decoder.decode(ret_msg)
|
||||
if response.status == MooncakeXferResponseStatus.ERROR:
|
||||
self._handle_failed_recv(
|
||||
pull_metas,
|
||||
req_ids,
|
||||
response.err_msg or "transfer error",
|
||||
)
|
||||
return
|
||||
self.process_pulling_result(response, pull_metas)
|
||||
if response.status == MooncakeXferResponseStatus.FINISH:
|
||||
break
|
||||
except zmq.ContextTerminated:
|
||||
logger.debug("ZMQ context terminated, exiting Mooncake receiver thread.")
|
||||
except Exception as e:
|
||||
self._handle_failed_recv(pull_metas, req_ids, f"transfer failed: {e}")
|
||||
return
|
||||
return
|
||||
except Exception as e:
|
||||
self._handle_failed_recv(pull_metas, req_ids, f"transfer failed: {e}")
|
||||
return
|
||||
|
||||
def _handle_failed_recv(
|
||||
self,
|
||||
@@ -2623,6 +2726,8 @@ class MooncakeConnectorWorker:
|
||||
)
|
||||
cached = self._prepared_transfer_regions.get(cache_key)
|
||||
if cached is not None:
|
||||
# A new layout_id can carry a layout this cache already holds.
|
||||
self._remember_peer_layout(meta, cached)
|
||||
return cached
|
||||
|
||||
def finish(
|
||||
@@ -2716,12 +2821,86 @@ class MooncakeConnectorWorker:
|
||||
n_aligned,
|
||||
len(local_regions),
|
||||
)
|
||||
self._prepared_transfer_regions[cache_key] = (
|
||||
local_regions,
|
||||
remote_regions,
|
||||
None,
|
||||
prepared = (local_regions, remote_regions, None)
|
||||
self._prepared_transfer_regions[cache_key] = prepared
|
||||
self._remember_peer_layout(meta, prepared)
|
||||
return prepared
|
||||
|
||||
def _peer_layout_key(self, meta: MooncakeXferMetadata) -> tuple:
|
||||
return (
|
||||
meta.remote_hostname,
|
||||
meta.remote_port,
|
||||
meta.remote_tp_rank,
|
||||
meta.remote_pp_size,
|
||||
meta.remote_tp_size,
|
||||
meta.layout_id,
|
||||
)
|
||||
|
||||
def _remember_peer_layout(
|
||||
self,
|
||||
meta: MooncakeXferMetadata,
|
||||
prepared: tuple[list[TransferRegion], list[TransferRegion], str | None],
|
||||
) -> None:
|
||||
local_regions, remote_regions, err = prepared
|
||||
if err is not None or not meta.layout_id:
|
||||
return
|
||||
key = self._peer_layout_key(meta)
|
||||
self._layout_by_peer[key] = (local_regions, remote_regions)
|
||||
self._layout_by_peer.move_to_end(key)
|
||||
while len(self._layout_by_peer) > _MAX_PEER_LAYOUTS:
|
||||
self._layout_by_peer.popitem(last=False)
|
||||
|
||||
def _lookup_peer_layout(
|
||||
self, meta: MooncakeXferMetadata
|
||||
) -> tuple[list[TransferRegion], list[TransferRegion]] | None:
|
||||
key = self._peer_layout_key(meta)
|
||||
stored = self._layout_by_peer.get(key)
|
||||
if stored is not None:
|
||||
self._layout_by_peer.move_to_end(key)
|
||||
return stored
|
||||
|
||||
def _build_pull_metadata(
|
||||
self,
|
||||
pull_metas: dict[ReqId, PullReqMeta],
|
||||
*,
|
||||
include_layout: bool,
|
||||
) -> MooncakeXferMetadata:
|
||||
req_blocks = {
|
||||
req_id: (pull_meta.transfer_id, pull_meta.local_block_ids)
|
||||
for req_id, pull_meta in pull_metas.items()
|
||||
}
|
||||
if not include_layout:
|
||||
return MooncakeXferMetadata(
|
||||
remote_hostname=self.hostname,
|
||||
remote_port=self.rpc_port,
|
||||
remote_tp_size=self.tp_size,
|
||||
remote_tp_rank=self.tp_rank,
|
||||
remote_pp_size=self.pp_size,
|
||||
layout_id=self._kv_layout_id,
|
||||
req_blocks=req_blocks,
|
||||
kv_caches_base_addr=[],
|
||||
block_lens=[],
|
||||
kv_block_lens=[],
|
||||
)
|
||||
return MooncakeXferMetadata(
|
||||
remote_hostname=self.hostname,
|
||||
remote_port=self.rpc_port,
|
||||
remote_tp_size=self.tp_size,
|
||||
remote_tp_rank=self.tp_rank,
|
||||
remote_pp_size=self.pp_size,
|
||||
layout_id=self._kv_layout_id,
|
||||
req_blocks=req_blocks,
|
||||
kv_caches_base_addr=self.kv_caches_base_addr,
|
||||
block_lens=self.block_len_per_layer,
|
||||
kv_block_lens=self.kv_block_len_per_layer,
|
||||
registered_layer_names=self.registered_layer_names,
|
||||
registered_layer_indices=self.registered_layer_indices,
|
||||
registered_group_indices=self.registered_group_indices,
|
||||
registered_shared_group_ids=[
|
||||
list(groups) for groups in self.region_shared_groups
|
||||
],
|
||||
registered_row_offsets=self.region_row_offsets,
|
||||
)
|
||||
return local_regions, remote_regions, None
|
||||
|
||||
def _validate_head_resharding_layout(
|
||||
self, remote_tp_size: int, local_regions: list[TransferRegion]
|
||||
|
||||
@@ -18,7 +18,7 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_events import (
|
||||
BlockStored,
|
||||
KVCacheEvent,
|
||||
@@ -127,6 +127,10 @@ class MooncakeStoreKVEvents(KVConnectorKVEvents):
|
||||
class MooncakeStoreConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
"""KV connector using MooncakeDistributedStore as shared KV pool."""
|
||||
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: KVTransferConfig) -> bool:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _validate_kv_cache_config(
|
||||
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
|
||||
@@ -3,22 +3,27 @@
|
||||
"""External-store cache-hit coordinator for MooncakeStoreConnector."""
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import NamedTuple, cast
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, NamedTuple, cast
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.data import (
|
||||
chunk_hashes_for_block_size,
|
||||
)
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.kv_cache_coordinator import replay_boundaries
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
BlockHash,
|
||||
KVCacheBlock,
|
||||
eagle_proof_margin,
|
||||
resolve_dcp_kv_cache_spec,
|
||||
)
|
||||
from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
SingleTypeKVCacheManager,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
@@ -26,6 +31,9 @@ from vllm.v1.kv_cache_interface import (
|
||||
)
|
||||
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
|
||||
class StoreSpecGroup(NamedTuple):
|
||||
spec: KVCacheSpec
|
||||
@@ -82,7 +90,7 @@ class MooncakeStoreCoordinator:
|
||||
hash_block_size: int,
|
||||
use_eagle: bool = False,
|
||||
retention_interval: int | None = None,
|
||||
dcp_world_size: int = 1,
|
||||
enable_partial_hash_hits: bool = False,
|
||||
) -> None:
|
||||
# Mirrors core's resolve_kv_cache_block_sizes: the hash unit only has
|
||||
# to divide groups that participate in prefix caching. Non-shareable
|
||||
@@ -110,14 +118,51 @@ class MooncakeStoreCoordinator:
|
||||
}
|
||||
self.hash_block_size = hash_block_size
|
||||
self.lcm_block_size = scheduler_block_size
|
||||
self.enable_partial_hash_hits = partial_hash_hits_enabled(
|
||||
kv_cache_groups, hash_block_size, dcp_world_size
|
||||
)
|
||||
# Core's decision: whether hits land on the hash unit, below the block.
|
||||
self.enable_partial_hash_hits = enable_partial_hash_hits
|
||||
self.use_eagle = use_eagle
|
||||
# Mirror vLLM core's KVCacheCoordinator.retention_interval.
|
||||
self.retention_interval = retention_interval
|
||||
self._verify_and_split_kv_cache_groups()
|
||||
|
||||
@classmethod
|
||||
def from_kv_cache_config(
|
||||
cls,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
vllm_config: "VllmConfig",
|
||||
scheduler_block_size: int,
|
||||
hash_block_size: int,
|
||||
) -> "MooncakeStoreCoordinator":
|
||||
"""Build the coordinator the connector's scheduler and workers share.
|
||||
|
||||
Specs are DCP-resolved, so a block spans the tokens of one block-table
|
||||
entry. Partial hits follow core's hit alignment, which checks every KV
|
||||
cache group and its manager, not only the groups the store transfers;
|
||||
unset (a config the engine core did not resolve) keeps hits on the
|
||||
block.
|
||||
"""
|
||||
dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size
|
||||
spec_config = vllm_config.speculative_config
|
||||
alignment = kv_cache_config.cache_hit_alignment_tokens
|
||||
return cls(
|
||||
[
|
||||
replace(
|
||||
group,
|
||||
kv_cache_spec=resolve_dcp_kv_cache_spec(
|
||||
group.kv_cache_spec, dcp_world_size
|
||||
),
|
||||
)
|
||||
for group in kv_cache_config.prefix_cacheable_groups
|
||||
],
|
||||
scheduler_block_size,
|
||||
hash_block_size,
|
||||
use_eagle=spec_config is not None and spec_config.use_eagle_block_drop(),
|
||||
retention_interval=kv_cache_config.prefix_cache_retention_interval,
|
||||
enable_partial_hash_hits=(
|
||||
alignment is not None and alignment < scheduler_block_size
|
||||
),
|
||||
)
|
||||
|
||||
def align_lookup_length(self, length: int) -> int:
|
||||
alignment = (
|
||||
self.hash_block_size
|
||||
@@ -167,6 +212,17 @@ class MooncakeStoreCoordinator:
|
||||
self.eagle_group_ids = {
|
||||
gid for g in attention_groups if g.use_eagle for gid in g.group_ids
|
||||
}
|
||||
self.eagle_proof_margin_by_group = {
|
||||
gid: eagle_proof_margin(
|
||||
group.spec.block_size,
|
||||
self.hash_block_size,
|
||||
self.enable_partial_hash_hits
|
||||
and group.manager_cls.supports_fine_grained_hash_lookup,
|
||||
)
|
||||
for group in attention_groups
|
||||
if group.use_eagle and not isinstance(group.spec, MambaSpec)
|
||||
for gid in group.group_ids
|
||||
}
|
||||
|
||||
def find_longest_cache_hit(
|
||||
self,
|
||||
@@ -286,6 +342,15 @@ class MooncakeStoreCoordinator:
|
||||
f"aligned_token_len ({aligned_token_len}) must be a multiple of "
|
||||
f"{mask_alignment}"
|
||||
)
|
||||
reachable_boundaries = (
|
||||
()
|
||||
if num_prompt_tokens is None
|
||||
else replay_boundaries(
|
||||
num_prompt_tokens,
|
||||
self.lcm_block_size,
|
||||
use_eagle=bool(self.eagle_group_ids),
|
||||
)
|
||||
)
|
||||
masks: list[list[bool] | None] = []
|
||||
for g_idx, g in enumerate(self.kv_cache_groups):
|
||||
spec = _unwrap_spec(g.kv_cache_spec)
|
||||
@@ -297,9 +362,6 @@ class MooncakeStoreCoordinator:
|
||||
manager_cls = KVCacheSpecRegistry.get_manager_class(spec)
|
||||
assert manager_cls is not None
|
||||
use_eagle = g_idx in self.eagle_group_ids
|
||||
reachable_boundaries = (
|
||||
() if num_prompt_tokens is None else (num_prompt_tokens - 1,)
|
||||
)
|
||||
mask = manager_cls.reachable_block_mask(
|
||||
start_block=start_chunk,
|
||||
end_block=end_chunk,
|
||||
@@ -394,14 +456,16 @@ class MooncakeStoreCoordinator:
|
||||
# never drops a block, so a widened bound would match past the
|
||||
# attention-verified hit and resume from speculative state (#43559).
|
||||
if drop_eagle_block and not isinstance(spec, MambaSpec):
|
||||
eagle_margin = (
|
||||
self.hash_block_size
|
||||
if self.enable_partial_hash_hits
|
||||
and manager_cls.supports_fine_grained_hash_lookup
|
||||
and spec.block_size > self.hash_block_size
|
||||
else spec.block_size
|
||||
eagle_margin = eagle_proof_margin(
|
||||
spec.block_size,
|
||||
self.hash_block_size,
|
||||
self.enable_partial_hash_hits
|
||||
and manager_cls.supports_fine_grained_hash_lookup,
|
||||
)
|
||||
_max_length = min(
|
||||
curr_hit_length + eagle_margin,
|
||||
len(block_hashes) * self.hash_block_size,
|
||||
)
|
||||
_max_length = min(curr_hit_length + eagle_margin, max_length)
|
||||
hit_blocks, _new_hit_length = manager_cls.find_longest_cache_hit(
|
||||
block_hashes=block_hashes, # type: ignore[arg-type]
|
||||
max_length=_max_length,
|
||||
@@ -449,20 +513,3 @@ def _unwrap_spec(spec: KVCacheSpec) -> KVCacheSpec:
|
||||
if isinstance(spec, UniformTypeKVCacheSpecs):
|
||||
return next(iter(spec.kv_cache_specs.values()))
|
||||
return spec
|
||||
|
||||
|
||||
def partial_hash_hits_enabled(
|
||||
kv_cache_groups: Sequence[KVCacheGroupSpec],
|
||||
hash_block_size: int,
|
||||
dcp_world_size: int = 1,
|
||||
) -> bool:
|
||||
"""Match core's DCP-aware Mamba partial-hit condition."""
|
||||
return any(
|
||||
isinstance(spec := _unwrap_spec(g.kv_cache_spec), MambaSpec)
|
||||
and spec.mamba_cache_mode == "align"
|
||||
and (
|
||||
(dcp_world_size == 1 and spec.block_size > hash_block_size)
|
||||
or (dcp_world_size > 1 and spec.block_size >= hash_block_size)
|
||||
)
|
||||
for g in kv_cache_groups
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import cast
|
||||
from typing import NamedTuple, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -712,6 +712,7 @@ class RequestTracker:
|
||||
# For a fresh request this is len(prompt). For a resumed-from-preemption
|
||||
# request it includes previously-generated tokens, which are re-prefilled.
|
||||
prefill_end_tokens: int = 0
|
||||
partial_tail_sent: bool = False
|
||||
|
||||
def reset(self) -> None:
|
||||
self.token_len = 0
|
||||
@@ -720,6 +721,7 @@ class RequestTracker:
|
||||
self.token_ids = None
|
||||
self.has_pending_offload = False
|
||||
self.prefill_end_tokens = 0
|
||||
self.partial_tail_sent = False
|
||||
|
||||
def update(
|
||||
self,
|
||||
@@ -739,6 +741,14 @@ class RequestTracker:
|
||||
existing.extend(new)
|
||||
|
||||
|
||||
class BoundaryPut(NamedTuple):
|
||||
"""A block stored under the hash of the prefix ending at ``num_tokens``."""
|
||||
|
||||
group_id: int
|
||||
block_id: int
|
||||
num_tokens: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReqMeta:
|
||||
"""Per-request metadata for store put/get operations."""
|
||||
@@ -756,15 +766,24 @@ class ReqMeta:
|
||||
# Absolute request offset represented by token_ids[0].
|
||||
token_ids_start: int = 0
|
||||
num_prompt_tokens: int | None = None
|
||||
# Total prefill tokens, including generated tokens replayed after preemption.
|
||||
prefill_end_tokens: int | None = None
|
||||
# Identifies this store job for the engine's lifetime. A request id cannot
|
||||
# serve that purpose: it is reused once a preempted request resumes, so it
|
||||
# would release the wrong job's blocks.
|
||||
store_job_id: int | None = None
|
||||
# Core-provided (group_id, block_id, boundary_tokens) mamba "align"
|
||||
# boundary states. A block-aligned entry is a committed boundary snapshot;
|
||||
# a non-aligned entry is the sub-block CoW tail. The store-job reference
|
||||
# keeps each exact block alive until every worker rank finishes the job.
|
||||
boundary_state_offloads: list[tuple[int, int, int]] | None = None
|
||||
# Blocks stored under an explicit prefix hash rather than by position:
|
||||
# core-provided mamba "align" states (a block-aligned entry is a committed
|
||||
# snapshot, a non-aligned one the sub-block CoW prompt tail) and the
|
||||
# scheduler-resolved non-Mamba blocks of the prompt's partial tail. The
|
||||
# store-job reference keeps each block alive until every worker rank
|
||||
# finishes the job.
|
||||
boundary_puts: list[BoundaryPut] | None = None
|
||||
# Total computed prefix length at the end of this step.
|
||||
completed_token_len: int | None = None
|
||||
# Set on the save that first covers the whole prompt, so the scheduler
|
||||
# publishes the prompt's partial tail once rather than on every save.
|
||||
publish_partial_tail: bool = False
|
||||
|
||||
@staticmethod
|
||||
def from_request_tracker(
|
||||
@@ -773,8 +792,12 @@ class ReqMeta:
|
||||
load_spec: LoadSpec | None = None,
|
||||
skip_save: bool | None = False,
|
||||
block_hashes: list[BlockHash] | None = None,
|
||||
save_partial_tail: bool = False,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> "ReqMeta | None":
|
||||
"""Create ReqMeta from a RequestTracker."""
|
||||
if save_partial_tail:
|
||||
assert num_prompt_tokens is not None
|
||||
if block_hashes is None:
|
||||
block_hashes = []
|
||||
input_token_len = tracker.token_len
|
||||
@@ -783,7 +806,15 @@ class ReqMeta:
|
||||
chunk_boundary = cdiv(token_ids_start + 1, block_size) * block_size
|
||||
num_tokens_to_save = input_token_len // block_size * block_size
|
||||
|
||||
skip_save = skip_save or num_tokens_to_save < chunk_boundary
|
||||
publish_tail = (
|
||||
save_partial_tail
|
||||
and not tracker.partial_tail_sent
|
||||
and num_prompt_tokens is not None
|
||||
and 0 < num_prompt_tokens <= input_token_len
|
||||
)
|
||||
skip_save = skip_save or (
|
||||
num_tokens_to_save < chunk_boundary and not publish_tail
|
||||
)
|
||||
# A ReqMeta must never carry both a save AND a load.
|
||||
# The save would also be wasted work — the bytes are being looked up
|
||||
# in the store right now. Later cached_reqs steps save new tokens
|
||||
@@ -795,6 +826,7 @@ class ReqMeta:
|
||||
|
||||
if not skip_save:
|
||||
tracker.num_saved_tokens = num_tokens_to_save
|
||||
tracker.partial_tail_sent |= publish_tail
|
||||
|
||||
token_ids = None
|
||||
if tracker.token_ids and not skip_save:
|
||||
@@ -826,7 +858,10 @@ class ReqMeta:
|
||||
block_hashes=block_hashes,
|
||||
token_ids=token_ids,
|
||||
token_ids_start=token_ids_start,
|
||||
num_prompt_tokens=tracker.prefill_end_tokens,
|
||||
num_prompt_tokens=num_prompt_tokens,
|
||||
prefill_end_tokens=tracker.prefill_end_tokens,
|
||||
completed_token_len=input_token_len,
|
||||
publish_partial_tail=publish_tail and not skip_save,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -5,14 +5,17 @@
|
||||
# (vllm_ascend/distributed/kv_transfer/kv_pool/ascend_store/).
|
||||
"""Scheduler-side logic for MooncakeStoreConnector."""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorMetadata,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.coordinator import ( # noqa: E501
|
||||
partial_hash_hits_enabled,
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.coordinator import (
|
||||
MooncakeStoreCoordinator,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.data import ( # noqa: E501
|
||||
BoundaryPut,
|
||||
LoadSpec,
|
||||
MooncakeStoreConnectorMetadata,
|
||||
MooncakeStoreWorkerMetadata,
|
||||
@@ -23,12 +26,19 @@ from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.worker import (
|
||||
LookupKeyClient,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.core.kv_cache_utils import resolve_kv_cache_block_sizes
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
resolve_kv_cache_block_sizes,
|
||||
)
|
||||
from vllm.v1.core.sched.output import NewRequestData, SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
MambaSpec,
|
||||
get_mamba_prefill_checkpoint_position,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import Request
|
||||
|
||||
@@ -49,6 +59,79 @@ def _new_req_prefill_tokens(request: NewRequestData) -> list[int]:
|
||||
return request.prompt_token_ids
|
||||
|
||||
|
||||
def _partial_tail_non_mamba_puts(
|
||||
coord: MooncakeStoreCoordinator,
|
||||
req_meta: ReqMeta,
|
||||
block_sizes: Sequence[int],
|
||||
) -> list[BoundaryPut]:
|
||||
"""Locate the non-Mamba blocks a partial-tail save publishes.
|
||||
|
||||
A later request resumes at the prompt's Mamba checkpoint (``boundary``) only
|
||||
if both pieces of KV are stored:
|
||||
|
||||
- Mamba groups: the state at ``boundary``, handed off by the core as a
|
||||
boundary put of its own, so Mamba groups are not listed here.
|
||||
- Other groups: the KV from the last LCM-aligned normal save up to
|
||||
``boundary`` plus the group's EAGLE proof margin (``proof_end``). Each
|
||||
block is keyed by the hash at its end, clipped to ``proof_end``.
|
||||
|
||||
Groups whose proof is not computed yet are omitted. For example, with LCM
|
||||
16, blocks of 4 tokens, and a checkpoint at 44, the full-attention blocks
|
||||
are 8-10, keyed at 36, 40 and 44.
|
||||
|
||||
A Mamba state handed off at any other position, i.e. a shared-prefix
|
||||
junction (``--enable-mamba-shared-prefix-checkpoint``), adds no puts here.
|
||||
|
||||
``block_sizes`` are the per-group block sizes, indexed like
|
||||
``req_meta.block_ids``.
|
||||
"""
|
||||
mamba_tails = [
|
||||
put.num_tokens
|
||||
for put in req_meta.boundary_puts or []
|
||||
if put.group_id in coord.mamba_group_ids
|
||||
and put.num_tokens % block_sizes[put.group_id]
|
||||
]
|
||||
# The tail is due on the save that first covers the prompt, or when Mamba
|
||||
# hands off its checkpoint state.
|
||||
if not mamba_tails and not req_meta.publish_partial_tail:
|
||||
return []
|
||||
prompt_tokens = req_meta.num_prompt_tokens
|
||||
completed = req_meta.completed_token_len
|
||||
assert prompt_tokens is not None and completed is not None
|
||||
hash_block_size = coord.hash_block_size
|
||||
# Core drops the Mamba checkpoint whenever EAGLE block drop is on, whichever
|
||||
# groups carry the eagle flag.
|
||||
boundary = get_mamba_prefill_checkpoint_position(
|
||||
prompt_tokens, hash_block_size, coord.use_eagle
|
||||
)
|
||||
# Any other sub-block Mamba hand-off is a shared-prefix junction. Its
|
||||
# attention KV, EAGLE proof included, ends on an attention block end no later
|
||||
# than this checkpoint's proof, so the normal and prompt-tail saves store it.
|
||||
if not req_meta.publish_partial_tail and boundary not in mamba_tails:
|
||||
return []
|
||||
num_hashes = len(req_meta.block_hashes)
|
||||
if boundary == 0 or boundary // hash_block_size > num_hashes:
|
||||
return []
|
||||
start = boundary // coord.lcm_block_size * coord.lcm_block_size
|
||||
puts: list[BoundaryPut] = []
|
||||
for group_id, block_size in enumerate(block_sizes):
|
||||
if group_id in coord.mamba_group_ids:
|
||||
continue
|
||||
proof_end = boundary + coord.eagle_proof_margin_by_group.get(group_id, 0)
|
||||
if proof_end > completed or proof_end // hash_block_size > num_hashes:
|
||||
continue
|
||||
group_blocks = req_meta.block_ids[group_id]
|
||||
for block_idx in range(start // block_size, cdiv(proof_end, block_size)):
|
||||
if block_idx >= len(group_blocks):
|
||||
break
|
||||
block_id = group_blocks[block_idx]
|
||||
if block_id == NULL_BLOCK_ID:
|
||||
continue
|
||||
num_tokens = min((block_idx + 1) * block_size, proof_end)
|
||||
puts.append(BoundaryPut(group_id, block_id, num_tokens))
|
||||
return puts
|
||||
|
||||
|
||||
class MooncakeStoreScheduler:
|
||||
"""Scheduler-side component for MooncakeStoreConnector."""
|
||||
|
||||
@@ -84,21 +167,30 @@ class MooncakeStoreScheduler:
|
||||
self._block_size, self._hash_block_size = resolve_kv_cache_block_sizes(
|
||||
kv_cache_config, vllm_config
|
||||
)
|
||||
self.enable_partial_hash_hits = partial_hash_hits_enabled(
|
||||
store_groups,
|
||||
self._hash_block_size,
|
||||
vllm_config.parallel_config.decode_context_parallel_size,
|
||||
)
|
||||
mamba_groups = {
|
||||
group_id: group.kv_cache_spec
|
||||
for group_id, group in enumerate(store_groups)
|
||||
if isinstance(group.kv_cache_spec, MambaSpec)
|
||||
}
|
||||
assert all(
|
||||
spec.mamba_cache_mode == "align" for spec in mamba_groups.values()
|
||||
), "MooncakeStoreScheduler requires mamba_cache_mode='align'"
|
||||
self._boundary_state_group_ids = frozenset(mamba_groups)
|
||||
|
||||
# Mirrors MooncakeStoreConnector._capacity_only.
|
||||
self._capacity_only = (
|
||||
self.kv_role == "kv_consumer"
|
||||
and not self.enable_lookup
|
||||
and not self.save_decode_cache
|
||||
)
|
||||
self._store_coord: MooncakeStoreCoordinator | None = None
|
||||
self.enable_partial_hash_hits = False
|
||||
if not self._capacity_only:
|
||||
assert all(
|
||||
spec.mamba_cache_mode == "align" for spec in mamba_groups.values()
|
||||
), "MooncakeStoreScheduler requires mamba_cache_mode='align'"
|
||||
self._store_coord = MooncakeStoreCoordinator.from_kv_cache_config(
|
||||
kv_cache_config, vllm_config, self._block_size, self._hash_block_size
|
||||
)
|
||||
self.enable_partial_hash_hits = self._store_coord.enable_partial_hash_hits
|
||||
|
||||
self._gpu_block_pool: BlockPool | None = None
|
||||
self._num_workers = vllm_config.parallel_config.world_size
|
||||
self._next_store_job_id = 0
|
||||
@@ -273,6 +365,8 @@ class MooncakeStoreScheduler:
|
||||
# producer. Loads are still carried by the same metadata.
|
||||
skip_save=is_consumer,
|
||||
block_hashes=request_real.block_hashes,
|
||||
num_prompt_tokens=request_real.num_prompt_tokens,
|
||||
save_partial_tail=self.enable_partial_hash_hits,
|
||||
)
|
||||
if req_meta is not None:
|
||||
meta.add_request(req_meta)
|
||||
@@ -323,6 +417,8 @@ class MooncakeStoreScheduler:
|
||||
load_spec=load_spec,
|
||||
skip_save=is_consumer,
|
||||
block_hashes=request_real.block_hashes,
|
||||
num_prompt_tokens=request_real.num_prompt_tokens,
|
||||
save_partial_tail=self.enable_partial_hash_hits,
|
||||
)
|
||||
else:
|
||||
# Decode/chunked request
|
||||
@@ -364,6 +460,8 @@ class MooncakeStoreScheduler:
|
||||
load_spec=None,
|
||||
skip_save=False,
|
||||
block_hashes=unfinished_req.block_hashes,
|
||||
num_prompt_tokens=unfinished_req.num_prompt_tokens,
|
||||
save_partial_tail=self.enable_partial_hash_hits,
|
||||
)
|
||||
|
||||
if req_meta is not None:
|
||||
@@ -398,6 +496,7 @@ class MooncakeStoreScheduler:
|
||||
load_spec=load_spec,
|
||||
skip_save=None,
|
||||
block_hashes=unfinished_req.block_hashes,
|
||||
num_prompt_tokens=unfinished_req.num_prompt_tokens,
|
||||
)
|
||||
if req_meta is not None:
|
||||
meta.add_request(req_meta)
|
||||
@@ -421,7 +520,8 @@ class MooncakeStoreScheduler:
|
||||
meta.add_request(req_meta)
|
||||
self._finished_partial_tail_metas.clear()
|
||||
|
||||
self._reference_save_blocks(meta)
|
||||
if not self._capacity_only:
|
||||
self._reference_save_blocks(meta)
|
||||
return meta
|
||||
|
||||
def _apply_current_save_block_ids(
|
||||
@@ -455,6 +555,9 @@ class MooncakeStoreScheduler:
|
||||
itself is freed, until every rank reports the job done.
|
||||
"""
|
||||
pool = self._gpu_block_pool
|
||||
coord = self._store_coord
|
||||
assert coord is not None
|
||||
block_sizes = [g.kv_cache_spec.block_size for g in coord.kv_cache_groups]
|
||||
for req_meta in meta.requests:
|
||||
if not req_meta.can_save:
|
||||
continue
|
||||
@@ -464,27 +567,27 @@ class MooncakeStoreScheduler:
|
||||
if req_meta.store_job_id is not None:
|
||||
assert req_meta.store_job_id in self._pinned_saves
|
||||
continue
|
||||
if tail := _partial_tail_non_mamba_puts(coord, req_meta, block_sizes):
|
||||
req_meta.boundary_puts = [*tail, *(req_meta.boundary_puts or [])]
|
||||
req_meta.store_job_id = store_job_id = self._next_store_job_id
|
||||
self._next_store_job_id += 1
|
||||
block_ids: list[int] = []
|
||||
if req_meta.boundary_state_offloads:
|
||||
block_ids.extend(
|
||||
block_id for _, block_id, _ in req_meta.boundary_state_offloads
|
||||
)
|
||||
block_ids = [put.block_id for put in req_meta.boundary_puts or []]
|
||||
assert NULL_BLOCK_ID not in block_ids, (
|
||||
"A null block cannot back a boundary-state offload"
|
||||
)
|
||||
# Every allocated block is referenced, not just the ones covering
|
||||
# this job's token range: a rank resumes from its own last
|
||||
# successful offset, which lags the scheduler's whenever a save was
|
||||
# skipped or failed, so it may read anywhere below the range.
|
||||
block_ids.extend(
|
||||
block_id
|
||||
for group_id, group in enumerate(req_meta.block_ids)
|
||||
if group_id not in self._boundary_state_group_ids
|
||||
for block_id in group
|
||||
if block_id != NULL_BLOCK_ID
|
||||
"A null block cannot back a boundary put"
|
||||
)
|
||||
if req_meta.token_len_chunk:
|
||||
# Normal prefix save: pin all non-Mamba sources for retries.
|
||||
# Every allocated block is referenced, not just the ones covering
|
||||
# this job's token range: a rank resumes from its own last
|
||||
# successful offset, which lags the scheduler's whenever a save was
|
||||
# skipped or failed, so it may read anywhere below the range.
|
||||
block_ids.extend(
|
||||
block_id
|
||||
for group_id, group in enumerate(req_meta.block_ids)
|
||||
if group_id not in self._boundary_state_group_ids
|
||||
for block_id in group
|
||||
if block_id != NULL_BLOCK_ID
|
||||
)
|
||||
# An aligned boundary block may also be present in the request's
|
||||
# block table. Take and release exactly one reference per block.
|
||||
block_ids = list(dict.fromkeys(block_ids))
|
||||
@@ -515,17 +618,40 @@ class MooncakeStoreScheduler:
|
||||
if boundary_tokens > tracker.prefill_end_tokens:
|
||||
return False
|
||||
|
||||
pinned_block_ids: list[int] = []
|
||||
remapped_offloads: list[tuple[int, int, int]] = []
|
||||
mamba_puts: list[BoundaryPut] = []
|
||||
for group_id, block_id, boundary in partial_tail_offloads:
|
||||
store_group_id = self._store_group_id_by_kv_cache_group_id.get(group_id)
|
||||
if store_group_id not in self._boundary_state_group_ids:
|
||||
return False
|
||||
if block_id == NULL_BLOCK_ID:
|
||||
return False
|
||||
pinned_block_ids.append(block_id)
|
||||
remapped_offloads.append((store_group_id, block_id, boundary))
|
||||
pinned_block_ids = list(dict.fromkeys(pinned_block_ids))
|
||||
mamba_puts.append(BoundaryPut(store_group_id, block_id, boundary))
|
||||
req_meta = ReqMeta(
|
||||
req_id=request.request_id,
|
||||
token_len_chunk=0,
|
||||
block_ids=tuple(
|
||||
block_ids[group_id].copy() for group_id in self._store_group_ids
|
||||
),
|
||||
block_hashes=list(request.block_hashes),
|
||||
can_save=True,
|
||||
num_prompt_tokens=request.num_prompt_tokens,
|
||||
prefill_end_tokens=tracker.prefill_end_tokens,
|
||||
boundary_puts=mamba_puts,
|
||||
completed_token_len=request.num_computed_tokens,
|
||||
)
|
||||
coord = self._store_coord
|
||||
assert coord is not None
|
||||
req_meta.boundary_puts = [
|
||||
*_partial_tail_non_mamba_puts(
|
||||
coord,
|
||||
req_meta,
|
||||
[g.kv_cache_spec.block_size for g in coord.kv_cache_groups],
|
||||
),
|
||||
*mamba_puts,
|
||||
]
|
||||
pinned_block_ids = list(
|
||||
dict.fromkeys(put.block_id for put in req_meta.boundary_puts)
|
||||
)
|
||||
|
||||
pool = self._gpu_block_pool
|
||||
assert pool is not None, (
|
||||
@@ -537,18 +663,8 @@ class MooncakeStoreScheduler:
|
||||
self._pinned_saves[store_job_id] = (pinned_block_ids, self._num_workers)
|
||||
pool.touch([pool.blocks[block_id] for block_id in pinned_block_ids])
|
||||
|
||||
self._finished_partial_tail_metas[request.request_id] = ReqMeta(
|
||||
req_id=request.request_id,
|
||||
token_len_chunk=0,
|
||||
block_ids=tuple(
|
||||
block_ids[group_id].copy() for group_id in self._store_group_ids
|
||||
),
|
||||
block_hashes=list(request.block_hashes),
|
||||
can_save=True,
|
||||
num_prompt_tokens=tracker.prefill_end_tokens,
|
||||
store_job_id=store_job_id,
|
||||
boundary_state_offloads=remapped_offloads,
|
||||
)
|
||||
req_meta.store_job_id = store_job_id
|
||||
self._finished_partial_tail_metas[request.request_id] = req_meta
|
||||
tracker.has_pending_offload = True
|
||||
# The store job owns exact block refs, so request cleanup need not wait.
|
||||
return False
|
||||
@@ -575,7 +691,7 @@ class MooncakeStoreScheduler:
|
||||
# going away, so the offload is conservatively dropped.
|
||||
logger.debug("Dropping boundary-state offload for request %s", req_id)
|
||||
continue
|
||||
accepted: list[tuple[int, int, int]] = []
|
||||
accepted: list[BoundaryPut] = []
|
||||
for group_id, block_id, boundary_tokens in entries:
|
||||
# Every other group stops saving at the end of this prefill, so
|
||||
# a mamba-only key past it can never complete a joint hybrid
|
||||
@@ -589,12 +705,12 @@ class MooncakeStoreScheduler:
|
||||
store_group_id = self._store_group_id_by_kv_cache_group_id.get(group_id)
|
||||
if store_group_id not in self._boundary_state_group_ids:
|
||||
continue
|
||||
accepted.append((store_group_id, block_id, boundary_tokens))
|
||||
accepted.append(BoundaryPut(store_group_id, block_id, boundary_tokens))
|
||||
if not accepted:
|
||||
continue
|
||||
tracker.has_pending_offload = True
|
||||
if (req_meta := save_metas.get(req_id)) is not None:
|
||||
req_meta.boundary_state_offloads = accepted
|
||||
req_meta.boundary_puts = accepted
|
||||
continue
|
||||
meta.add_request(
|
||||
ReqMeta(
|
||||
@@ -603,8 +719,10 @@ class MooncakeStoreScheduler:
|
||||
block_ids=tracker.allocated_block_ids,
|
||||
block_hashes=req_tuple[0].block_hashes,
|
||||
can_save=True,
|
||||
num_prompt_tokens=tracker.prefill_end_tokens,
|
||||
boundary_state_offloads=accepted,
|
||||
num_prompt_tokens=req_tuple[0].num_prompt_tokens,
|
||||
prefill_end_tokens=tracker.prefill_end_tokens,
|
||||
boundary_puts=accepted,
|
||||
completed_token_len=tracker.token_len,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -74,7 +74,6 @@ from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
BlockHash,
|
||||
maybe_convert_block_hash,
|
||||
resolve_dcp_kv_cache_spec,
|
||||
resolve_kv_cache_block_sizes,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
@@ -569,40 +568,43 @@ class KVCacheStoreSendingThread(KVTransferThread):
|
||||
self._skip_store_requests.clear()
|
||||
return True
|
||||
|
||||
def _boundary_snapshot_puts(
|
||||
self, req_meta: ReqMeta, entries: list[tuple[int, int, int]]
|
||||
def _boundary_puts(
|
||||
self, req_meta: ReqMeta
|
||||
) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
|
||||
"""Puts for committed mamba "align" boundary-state snapshots.
|
||||
"""Puts for ``req_meta.boundary_puts``: each block under the hash of
|
||||
the prefix ending at its ``num_tokens``.
|
||||
|
||||
These are block-aligned boundaries, i.e. exactly what the normal save
|
||||
would key — but ``store_mask`` masks mamba groups out of it entirely, so
|
||||
this is their *only* writer. The exclusion is not an optimization: the
|
||||
normal save resolves a chunk's address as
|
||||
``req_meta.block_ids[g][start // block_size]``, and ``block_ids`` is the
|
||||
connector's append-only mirror of the core's per-group table. An
|
||||
align-mode table is mutated in place (a superseded state block is freed
|
||||
and nulled; speculative blocks relocate), and the connector is never
|
||||
told, so a stale mirror entry is indistinguishable from a live one — a
|
||||
retry of a failed or pressure-skipped chunk would read a block that now
|
||||
belongs to another request.
|
||||
|
||||
Each entry's handed-off block *is* the boundary state and is pinned by
|
||||
the core, so it is uploaded under its boundary-end hash key and never
|
||||
resolved positionally.
|
||||
The scheduler resolves and pins every block, so none is looked up
|
||||
positionally here. That matters for mamba "align" states: ``store_mask``
|
||||
masks mamba groups out of the normal save, which resolves a chunk's
|
||||
address as ``req_meta.block_ids[g][start // block_size]``. An align-mode
|
||||
table is mutated in place (a superseded state block is freed and
|
||||
nulled; speculative blocks relocate) without telling the connector, so
|
||||
a retried positional read could hit a block that now belongs to another
|
||||
request. The handed-off block *is* the state.
|
||||
"""
|
||||
hash_block_size = self.coord.hash_block_size
|
||||
puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
|
||||
for group_id, block_id, boundary in entries:
|
||||
if boundary == 0 or block_id == NULL_BLOCK_ID:
|
||||
for group_id, block_id, num_tokens in req_meta.boundary_puts or []:
|
||||
if (
|
||||
not self.group_participates[group_id]
|
||||
or num_tokens == 0
|
||||
or block_id == NULL_BLOCK_ID
|
||||
):
|
||||
continue
|
||||
hash_idx = boundary // hash_block_size - 1
|
||||
# A negative index would silently key the block by the last hash.
|
||||
assert num_tokens % hash_block_size == 0, (
|
||||
f"Boundary put at {num_tokens} tokens is not a multiple of the "
|
||||
f"hash block size {hash_block_size}"
|
||||
)
|
||||
hash_idx = num_tokens // hash_block_size - 1
|
||||
if hash_idx >= len(req_meta.block_hashes):
|
||||
continue
|
||||
db = self.token_databases[group_id]
|
||||
# Distribute across ranks by the same rule as normal chunks.
|
||||
put_step = self.group_put_steps[group_id]
|
||||
put_step_rank = (self.tp_rank + group_id) % put_step
|
||||
if (boundary // db.block_size - 1) % put_step != put_step_rank:
|
||||
if (cdiv(num_tokens, db.block_size) - 1) % put_step != put_step_rank:
|
||||
continue
|
||||
addr, size = db.prepare_value_for_block(block_id)
|
||||
puts.append(
|
||||
@@ -610,115 +612,20 @@ class KVCacheStoreSendingThread(KVTransferThread):
|
||||
)
|
||||
return puts
|
||||
|
||||
def _sub_block_tail_puts(
|
||||
self, req_meta: ReqMeta, entries: list[tuple[int, int, int]]
|
||||
) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
|
||||
"""Puts for the request's sub-block partial tail (its last prompt hash
|
||||
boundary), so a later request can hit the sub-block prefix.
|
||||
|
||||
Covers every group's blocks from the normal save's lcm floor to the
|
||||
boundary: the normal save floors to ``lcm_block_size``, so a
|
||||
smaller-block group's full blocks in that gap are never persisted
|
||||
elsewhere, and the consumer's lookup needs every group at every probed
|
||||
boundary. Full blocks are keyed by their block-end hash and the partial
|
||||
boundary block by the boundary sub-hash; a mamba "align" group
|
||||
contributes only its boundary block, from the core-provided CoW block.
|
||||
"""
|
||||
boundaries = {boundary for _, _, boundary in entries}
|
||||
if len(boundaries) != 1:
|
||||
raise ValueError(
|
||||
"Sub-block partial-tail offloads for one request must share a boundary"
|
||||
)
|
||||
boundary = boundaries.pop()
|
||||
hash_block_size = self.coord.hash_block_size
|
||||
if boundary == 0 or boundary // hash_block_size - 1 >= len(
|
||||
req_meta.block_hashes
|
||||
):
|
||||
return []
|
||||
|
||||
mamba_offloads = {group_id: block_id for group_id, block_id, _ in entries}
|
||||
saved = self._saved_offset.get(req_meta.req_id, 0)
|
||||
puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
|
||||
for g_idx, db in enumerate(self.token_databases):
|
||||
if not self.group_participates[g_idx]:
|
||||
continue
|
||||
group_blocks = req_meta.block_ids[g_idx]
|
||||
# Distribute across ranks by the same rule as normal chunks.
|
||||
put_step = self.group_put_steps[g_idx]
|
||||
put_step_rank = (self.tp_rank + g_idx) % put_step
|
||||
# Always include the boundary block: its sub-hash key is written
|
||||
# only here, even if normal saves already advanced past it.
|
||||
last_block = cdiv(boundary, db.block_size) - 1
|
||||
for block_idx in range(
|
||||
min(saved // db.block_size, last_block), last_block + 1
|
||||
):
|
||||
if block_idx % put_step != put_step_rank:
|
||||
continue
|
||||
valid_end = min((block_idx + 1) * db.block_size, boundary)
|
||||
key_hash = req_meta.block_hashes[valid_end // hash_block_size - 1]
|
||||
if g_idx in mamba_offloads:
|
||||
if valid_end != boundary:
|
||||
# Interior align-mode state positions are null or
|
||||
# stale (the block table is not append-only) and never
|
||||
# valid gap content; only the boundary block is
|
||||
# persisted, from the core-provided hand-off.
|
||||
continue
|
||||
block_id = mamba_offloads[g_idx]
|
||||
elif g_idx in self.coord.mamba_group_ids:
|
||||
continue
|
||||
elif block_idx < len(group_blocks):
|
||||
block_id = group_blocks[block_idx]
|
||||
else:
|
||||
continue
|
||||
if block_id == NULL_BLOCK_ID:
|
||||
logger.debug(
|
||||
"Skipping unavailable partial-tail source block "
|
||||
"(req=%s, group=%d, block=%d)",
|
||||
req_meta.req_id,
|
||||
g_idx,
|
||||
block_idx,
|
||||
)
|
||||
continue
|
||||
addr, size = db.prepare_value_for_block(block_id)
|
||||
puts.append((db.key_for(key_hash), addr, size, db.metadata))
|
||||
return puts
|
||||
|
||||
def _maybe_offload_boundary_states(self, req_meta: ReqMeta) -> bool:
|
||||
"""Persist connector-pinned mamba "align" boundary states handed off
|
||||
for this request, deduped against the store.
|
||||
"""Persist this job's boundary puts, deduped against the store.
|
||||
|
||||
This is every mamba key the connector writes — ``store_mask`` excludes
|
||||
mamba groups from the positional normal save, aligned boundaries
|
||||
included (see :meth:`_boundary_snapshot_puts`).
|
||||
|
||||
The two entry kinds are keyed and sourced differently, so they are
|
||||
prepared separately and put in one batch:
|
||||
|
||||
- block-aligned for its group: a committed boundary-state snapshot,
|
||||
the handed-off block itself;
|
||||
- not block-aligned: the sub-block CoW partial tail, which also has to
|
||||
cover the other groups' blocks in the normal save's lcm gap.
|
||||
These are every mamba key the connector writes (``store_mask`` excludes
|
||||
mamba groups from the positional normal save) plus the other groups'
|
||||
partial-tail blocks in the normal save's lcm gap.
|
||||
|
||||
Returns:
|
||||
True when no put is needed or every put succeeds, False otherwise.
|
||||
|
||||
"""
|
||||
offloads = req_meta.boundary_state_offloads
|
||||
if not offloads or not req_meta.block_hashes:
|
||||
if not req_meta.boundary_puts or not req_meta.block_hashes:
|
||||
return True
|
||||
|
||||
snapshots: list[tuple[int, int, int]] = []
|
||||
sub_block: list[tuple[int, int, int]] = []
|
||||
for group_id, block_id, boundary in offloads:
|
||||
entry = (group_id, block_id, boundary)
|
||||
if boundary % self.token_databases[group_id].block_size == 0:
|
||||
snapshots.append(entry)
|
||||
else:
|
||||
sub_block.append(entry)
|
||||
|
||||
puts = self._boundary_snapshot_puts(req_meta, snapshots)
|
||||
if sub_block and self.coord.enable_partial_hash_hits:
|
||||
puts.extend(self._sub_block_tail_puts(req_meta, sub_block))
|
||||
puts = self._boundary_puts(req_meta)
|
||||
|
||||
if not puts:
|
||||
return True
|
||||
@@ -854,9 +761,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
|
||||
|
||||
# Offload the handed-off mamba boundary states (independent of the
|
||||
# normal positional save, which may be skipped this step).
|
||||
if req_meta.boundary_state_offloads is not None and not (
|
||||
self._maybe_offload_boundary_states(req_meta)
|
||||
):
|
||||
if not self._maybe_offload_boundary_states(req_meta):
|
||||
return
|
||||
|
||||
if token_len == 0:
|
||||
@@ -870,7 +775,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
|
||||
store_masks = self.coord.store_mask(
|
||||
token_len,
|
||||
save_start,
|
||||
num_prompt_tokens=req_meta.num_prompt_tokens,
|
||||
num_prompt_tokens=req_meta.prefill_end_tokens,
|
||||
)
|
||||
|
||||
starts: list[int] = []
|
||||
@@ -1603,31 +1508,10 @@ class MooncakeStoreWorker:
|
||||
)
|
||||
return
|
||||
|
||||
self._kv_cache_groups = [
|
||||
dataclasses.replace(
|
||||
group,
|
||||
kv_cache_spec=resolve_dcp_kv_cache_spec(
|
||||
group.kv_cache_spec,
|
||||
self.dcp_size,
|
||||
),
|
||||
)
|
||||
for group in kv_cache_config.prefix_cacheable_groups
|
||||
]
|
||||
spec_cfg = getattr(vllm_config, "speculative_config", None)
|
||||
use_eagle_block_drop = bool(
|
||||
spec_cfg.use_eagle_block_drop()
|
||||
if spec_cfg is not None
|
||||
and callable(getattr(spec_cfg, "use_eagle_block_drop", None))
|
||||
else False
|
||||
)
|
||||
self.coord = MooncakeStoreCoordinator(
|
||||
self._kv_cache_groups,
|
||||
scheduler_block_size=self.block_size,
|
||||
hash_block_size=self.hash_block_size,
|
||||
use_eagle=use_eagle_block_drop,
|
||||
retention_interval=kv_cache_config.prefix_cache_retention_interval,
|
||||
dcp_world_size=self.dcp_size,
|
||||
self.coord = MooncakeStoreCoordinator.from_kv_cache_config(
|
||||
kv_cache_config, vllm_config, self.block_size, self.hash_block_size
|
||||
)
|
||||
self._kv_cache_groups = self.coord.kv_cache_groups
|
||||
self.store_tp_size, store_namespace, store_layout_cls = (
|
||||
self._select_store_layout(extra_config)
|
||||
)
|
||||
|
||||
@@ -71,6 +71,7 @@ class WriteTask:
|
||||
remote_ip: str
|
||||
multi_pod_hosts: list[str] = field(default_factory=list)
|
||||
remote_dp_size_local: int = 0
|
||||
remote_dp_size: int = 1
|
||||
enqueue_time: float = field(default_factory=time.perf_counter)
|
||||
retried: int = 0
|
||||
|
||||
@@ -307,8 +308,8 @@ class MoRIIOConfig:
|
||||
# WRITE mode.
|
||||
# transfer_timeout -> Timeout for waiting_for_transfer_complete before
|
||||
# raising TransferError (sec).
|
||||
# defer_timeout -> Timeout before a deferred send with no finished_sending
|
||||
# notification is reaped and its blocks force-freed (sec).
|
||||
# defer_timeout -> Timeout for deferred WRITE allocation or a missing
|
||||
# READ release notification (sec).
|
||||
# recv_abort_timeout -> Timeout before an in-flight recv whose RDMA
|
||||
# completion never arrived is aborted (sec).
|
||||
|
||||
@@ -414,8 +415,8 @@ class MoRIIOConstants:
|
||||
# Timeout (seconds) for waiting_for_transfer_complete before raising TransferError.
|
||||
# Overridable via kv_connector_extra_config["transfer_timeout"].
|
||||
DEFAULT_TRANSFER_TIMEOUT = 30.0
|
||||
# Timeout (seconds) before a deferred send with no finished_sending
|
||||
# notification is reaped and its blocks force-freed.
|
||||
# Timeout (seconds) for deferred WRITE allocation or a missing READ release
|
||||
# notification.
|
||||
# Overridable via kv_connector_extra_config["defer_timeout"].
|
||||
DEFAULT_DEFER_TIMEOUT = 60.0
|
||||
# Timeout (seconds) before an in-flight recv whose RDMA completion was lost
|
||||
|
||||
@@ -5,7 +5,7 @@ import math
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections import OrderedDict, defaultdict
|
||||
from collections.abc import Collection
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
@@ -16,7 +16,7 @@ import numpy as np
|
||||
import torch
|
||||
import zmq
|
||||
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
from vllm.config import CUDAGraphMode, KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
BlockIds,
|
||||
clip_ssm_state_blocks,
|
||||
@@ -25,6 +25,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorBase_V1,
|
||||
KVConnectorMetadata,
|
||||
KVConnectorRole,
|
||||
KVConnectorTransferResults,
|
||||
SupportsHMA,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
@@ -116,6 +117,9 @@ logger = init_logger(__name__)
|
||||
_SQ_FULL_BACKOFF_INITIAL_S = 0.001
|
||||
_SQ_FULL_BACKOFF_MAX_S = 0.05
|
||||
_MAX_LOCAL_MAMBA_TAIL_BLOCKS = 1
|
||||
# A WRITE failure is broadcast to every decode DP rank, so ranks that never
|
||||
# see the request would otherwise keep its transfer id forever.
|
||||
_MAX_UNMATCHED_WRITE_FAILURES = 4096
|
||||
|
||||
|
||||
try:
|
||||
@@ -225,6 +229,10 @@ def resolve_moriio_transfer_ack(
|
||||
class MoRIIOConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
_cache_hit_source = CacheHitSource.P2P
|
||||
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: KVTransferConfig) -> bool:
|
||||
return False
|
||||
|
||||
@property
|
||||
def supports_divergent_local_hybrid_hits(self) -> bool:
|
||||
# The READ path always transfers the recurrent-state slot, including
|
||||
@@ -356,6 +364,12 @@ class MoRIIOConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
assert self.connector_worker is not None
|
||||
return self.connector_worker.get_finished()
|
||||
|
||||
def get_transfer_results(
|
||||
self, finished_req_ids: set[str]
|
||||
) -> KVConnectorTransferResults:
|
||||
assert self.connector_worker is not None
|
||||
return self.connector_worker.get_transfer_results()
|
||||
|
||||
def get_block_ids_with_load_errors(self) -> set[int]:
|
||||
"""Blocks whose MoRIIO read failed, for the scheduler to recompute."""
|
||||
if self.connector_worker is None:
|
||||
@@ -667,12 +681,10 @@ class MoRIIOConnectorScheduler:
|
||||
set_role(ROLE.CONSUMER)
|
||||
# Reqs to send and their expiration time
|
||||
self._reqs_need_send: dict[ReqId, float] = {}
|
||||
# Deadlines for requests whose block freeing was deferred.
|
||||
# Survives across scheduler steps. If the worker never reports
|
||||
# finished_sending before the deadline, we inject them into
|
||||
# connector_output.finished_sending so the scheduler frees the blocks to avoid
|
||||
# hanging indefinitely waiting for a free notification that never comes.
|
||||
# Value: (deadline, transfer_id) for unmapping after mutation.
|
||||
# Requests whose block freeing is deferred. READ mode uses the deadline
|
||||
# as a missing-ACK watchdog; WRITE mode waits for the worker ACK because
|
||||
# only the worker can mark the transfer terminal before blocks are freed.
|
||||
# Value: (deadline, transfer_id) for unmapping after completion.
|
||||
self._deferred_send_deadlines: dict[ReqId, tuple[float, TransferId | None]] = {}
|
||||
self._defer_timeout = float(
|
||||
self.kv_transfer_config.kv_connector_extra_config.get(
|
||||
@@ -768,10 +780,10 @@ class MoRIIOConnectorScheduler:
|
||||
|
||||
num_prompt_tokens = request.num_prompt_tokens
|
||||
num_external_tokens = max(num_prompt_tokens - num_computed_tokens, 0)
|
||||
params = request.kv_transfer_params or {}
|
||||
if not params.get("do_remote_prefill"):
|
||||
return 0, False
|
||||
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.
|
||||
@@ -1131,7 +1143,14 @@ class MoRIIOConnectorScheduler:
|
||||
_should_notify = self._global_dp_rank == remote_dp_rank
|
||||
else:
|
||||
_should_notify = self._is_kv_master
|
||||
if _should_notify:
|
||||
if _should_notify and num_external_tokens == 0:
|
||||
# Nothing left to fetch (full local prefix hit), so release
|
||||
# the producer's blocks instead of sending an empty
|
||||
# allocation, which it rejects.
|
||||
self._release_write_prefill_blocks(
|
||||
request.request_id, request.kv_transfer_params
|
||||
)
|
||||
elif _should_notify:
|
||||
peer_zmq = get_peer_zmq_from_request_id(
|
||||
request.request_id, is_producer=False
|
||||
)
|
||||
@@ -1159,12 +1178,6 @@ class MoRIIOConnectorScheduler:
|
||||
f"remote_notify_port={remote_notify_port!r})"
|
||||
)
|
||||
|
||||
# num_external_tokens == 0: nothing to push, so don't tell
|
||||
# the producer to write into these blocks.
|
||||
block_notify_list = (
|
||||
blocks.get_block_ids()[0] if num_external_tokens > 0 else []
|
||||
)
|
||||
|
||||
# Wide-EP multi-pod: a pod binds notify sockets only for
|
||||
# its LOCAL ranks, so the port offset must use the per-pod
|
||||
# local rank (% dp_local), not the global rank. Single-pod
|
||||
@@ -1191,7 +1204,7 @@ class MoRIIOConnectorScheduler:
|
||||
self.send_notify_block(
|
||||
req_id=request.request_id,
|
||||
transfer_id=request.kv_transfer_params["transfer_id"],
|
||||
block_notify_list=block_notify_list,
|
||||
block_notify_list=blocks.get_block_ids()[0],
|
||||
host=_notify_host,
|
||||
port=target_port,
|
||||
)
|
||||
@@ -1541,8 +1554,9 @@ class MoRIIOConnectorScheduler:
|
||||
* An ACK that arrives BEFORE its request finished is parked in
|
||||
``_pending_sent_acks`` and released on a later step once the
|
||||
request enters ``_deferred_send_deadlines``.
|
||||
* A deferred send whose ACK never arrives is reaped after
|
||||
``_defer_timeout`` and surfaced, so leaked blocks are freed.
|
||||
* In READ mode, a deferred send whose ACK never arrives is reaped
|
||||
after ``_defer_timeout``. WRITE-mode timeouts are owned by the worker,
|
||||
which marks the transfer terminal before ACKing the block release.
|
||||
* A parked ACK that never matches a deferral before its own
|
||||
deadline is a stale duplicate (e.g. a real ACK landing after the
|
||||
send was already reaped) and is dropped.
|
||||
@@ -1575,7 +1589,7 @@ class MoRIIOConnectorScheduler:
|
||||
expired = [
|
||||
req_id
|
||||
for req_id, (deadline, _) in self._deferred_send_deadlines.items()
|
||||
if now >= deadline
|
||||
if self.mode == MoRIIOMode.READ and now >= deadline
|
||||
]
|
||||
if expired:
|
||||
safe.update(expired)
|
||||
@@ -1685,6 +1699,7 @@ class MoRIIOConnectorWorker:
|
||||
# Completions that arrived before transfer_id_to_request_id was populated.
|
||||
# Retried each step until the mapping is established.
|
||||
self._unmatched_write_completions: set[str] = set()
|
||||
self._unmatched_write_failures: OrderedDict[TransferId, None] = OrderedDict()
|
||||
# Producer-side READ-mode ACK fan-in. When decode TP is larger than
|
||||
# prefill TP, multiple decode ranks can read from one prefill rank and
|
||||
# notify the same transfer_id. Blocks are reusable only after all ACKs.
|
||||
@@ -1877,6 +1892,7 @@ class MoRIIOConnectorWorker:
|
||||
remote_ip: str,
|
||||
multi_pod_hosts: list[str],
|
||||
remote_dp_size_local: int,
|
||||
remote_dp_size: int,
|
||||
) -> None:
|
||||
"""Schedule a block write operation.
|
||||
|
||||
@@ -1892,6 +1908,7 @@ class MoRIIOConnectorWorker:
|
||||
remote_ip: IP address of remote node
|
||||
multi_pod_hosts: List of pod IPs for multi-pod Wide-EP
|
||||
remote_dp_size_local: Per-pod DP size for multi-pod
|
||||
remote_dp_size: Global DP size of the decode instance
|
||||
|
||||
"""
|
||||
# synchronization to prevent dirty reads between
|
||||
@@ -1915,6 +1932,7 @@ class MoRIIOConnectorWorker:
|
||||
remote_ip=remote_ip,
|
||||
multi_pod_hosts=multi_pod_hosts,
|
||||
remote_dp_size_local=remote_dp_size_local,
|
||||
remote_dp_size=remote_dp_size,
|
||||
)
|
||||
self._writer.schedule_write(task)
|
||||
|
||||
@@ -2435,10 +2453,15 @@ class MoRIIOConnectorWorker:
|
||||
caches_data = []
|
||||
self.layer_base_addr_index = {}
|
||||
base_addr_idx = 0
|
||||
|
||||
# HMA (#53721 Gemma4 SWA, GLM-5.2 DSA, MiniMax): transfers already
|
||||
# size RDMA from per-layer geometry, so allow divergent block_len
|
||||
# (bytes) always, and divergent block_size (tokens/page) only when
|
||||
# the hybrid KV cache manager is enabled. Without HMA, block_size
|
||||
# must stay uniform for the peer page handshake.
|
||||
hma_enabled = (
|
||||
not self.vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
)
|
||||
|
||||
for layer_name in kv_caches:
|
||||
self.layer_base_addr_index[layer_name] = base_addr_idx
|
||||
if self._is_mamba_layer(layer_name):
|
||||
@@ -2453,16 +2476,31 @@ class MoRIIOConnectorWorker:
|
||||
base_addr_idx += 1
|
||||
continue
|
||||
geometry = self._get_layer_transfer_geometry(layer_name)
|
||||
if hma_enabled:
|
||||
if geometry.block_len != self.block_len:
|
||||
if geometry.block_size != self.block_size:
|
||||
if not hma_enabled:
|
||||
raise ValueError(
|
||||
"MoRIIO KV cache block length mismatch for layer "
|
||||
f"{layer_name}: {geometry.block_len} != {self.block_len}"
|
||||
"MoRIIO KV cache block size mismatch for layer "
|
||||
f"{layer_name}: {geometry.block_size} != "
|
||||
f"{self.block_size}"
|
||||
)
|
||||
elif geometry.block_size != self.block_size:
|
||||
raise ValueError(
|
||||
"MoRIIO KV cache block size mismatch for layer "
|
||||
f"{layer_name}: {geometry.block_size} != {self.block_size}"
|
||||
logger.debug(
|
||||
"MoRIIO HMA per-layer block_size for %s: %d "
|
||||
"(page/default %d); continuing with per-layer sizes.",
|
||||
layer_name,
|
||||
geometry.block_size,
|
||||
self.block_size,
|
||||
)
|
||||
if geometry.block_len != self.block_len:
|
||||
# Unlike block_size above, divergent block_len is allowed
|
||||
# unconditionally (not gated on hma_enabled) -- it covers
|
||||
# non-hybrid models too, e.g. GLM-5.2 DSA's per-layer
|
||||
# geometry. Don't attribute it to HMA in the log.
|
||||
logger.debug(
|
||||
"MoRIIO per-layer block_len for %s: %d "
|
||||
"(page/default %d); continuing with per-layer sizes.",
|
||||
layer_name,
|
||||
geometry.block_len,
|
||||
self.block_len,
|
||||
)
|
||||
# num_blocks is advertised as a single scalar to the peer, so must it
|
||||
# be uniform
|
||||
@@ -2492,6 +2530,7 @@ class MoRIIOConnectorWorker:
|
||||
# and a run that has three should not look identical in the log.
|
||||
distinct_block_lens = sorted(set(self.block_lens.values()))
|
||||
if len(distinct_block_lens) > 1:
|
||||
self.block_len = max(distinct_block_lens)
|
||||
logger.info(
|
||||
"MoRIIO registered %d attention layers with %d distinct block "
|
||||
"lengths (bytes): %s; transfer sizes and strides are per layer, "
|
||||
@@ -2686,6 +2725,28 @@ class MoRIIOConnectorWorker:
|
||||
|
||||
return done_sending, done_recving
|
||||
|
||||
def get_transfer_results(self) -> KVConnectorTransferResults:
|
||||
done_sending, done_recving = self.get_finished()
|
||||
failed_recving: set[ReqId] = set()
|
||||
|
||||
if self.mode == MoRIIOMode.WRITE and not self.is_producer:
|
||||
pending = self._unmatched_write_failures
|
||||
mapping = self.transfer_id_to_request_id
|
||||
for transfer_id in self.moriio_wrapper.pop_failed_write_req_ids():
|
||||
pending[transfer_id] = None
|
||||
for transfer_id in [t for t in pending if t in mapping]:
|
||||
del pending[transfer_id]
|
||||
failed_recving.add(mapping[transfer_id])
|
||||
while len(pending) > _MAX_UNMATCHED_WRITE_FAILURES:
|
||||
pending.popitem(last=False)
|
||||
done_recving |= failed_recving
|
||||
|
||||
return KVConnectorTransferResults(
|
||||
finished_sending=done_sending,
|
||||
finished_recving=done_recving,
|
||||
failed_recving=failed_recving,
|
||||
)
|
||||
|
||||
def wait_for_layer_load(self, layer_name: str) -> None:
|
||||
"""Block until all in-flight READs of this layer have landed.
|
||||
|
||||
@@ -3258,6 +3319,7 @@ class MoRIIOConnectorWorker:
|
||||
remote_ip=meta.remote_host,
|
||||
multi_pod_hosts=hosts,
|
||||
remote_dp_size_local=dp_local,
|
||||
remote_dp_size=int(meta.remote_dp_size),
|
||||
)
|
||||
|
||||
def merge_contiguous_blocks(
|
||||
|
||||
@@ -33,8 +33,10 @@ from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
TransferError,
|
||||
TransferId,
|
||||
WriteTask,
|
||||
fold_local_rank,
|
||||
get_port_offset,
|
||||
get_role,
|
||||
pod_index,
|
||||
zmq_ctx,
|
||||
)
|
||||
|
||||
@@ -226,15 +228,6 @@ class MoRIIOWriter:
|
||||
for task in self._deferred_tasks:
|
||||
if self._is_transfer_terminal(task.transfer_id):
|
||||
continue
|
||||
if now - task.enqueue_time > defer_timeout:
|
||||
logger.error(
|
||||
"Deferred write task for request %s expired after %.1fs "
|
||||
"(remote blocks never arrived), marking done",
|
||||
task.request_id,
|
||||
now - task.enqueue_time,
|
||||
)
|
||||
self._mark_request_done(task.transfer_id)
|
||||
continue
|
||||
if self._is_remote_ready(task):
|
||||
try:
|
||||
self._execute_write_task(task)
|
||||
@@ -244,11 +237,42 @@ class MoRIIOWriter:
|
||||
task.request_id,
|
||||
)
|
||||
self._mark_request_done(task.transfer_id)
|
||||
elif (
|
||||
now - task.enqueue_time > defer_timeout
|
||||
and self.worker.moriio_wrapper.fail_unallocated_write(task.transfer_id)
|
||||
):
|
||||
self._notify_write_failed(task, now - task.enqueue_time)
|
||||
else:
|
||||
still_deferred.append(task)
|
||||
|
||||
self._deferred_tasks = still_deferred
|
||||
|
||||
def _notify_write_failed(self, task: WriteTask, age: float) -> None:
|
||||
self._clear_transfer_state(task.transfer_id)
|
||||
logger.error(
|
||||
"Deferred write task for request %s timed out after %.1fs waiting "
|
||||
"for remote blocks",
|
||||
task.request_id,
|
||||
age,
|
||||
)
|
||||
# No remote allocation arrived, so the decode DP rank that owns the
|
||||
# request is unknown. Tell every rank; the others drop it.
|
||||
for decode_dp_rank in range(max(task.remote_dp_size, 1)):
|
||||
remote_ip, remote_port = self._resolve_notify_endpoint(task, decode_dp_rank)
|
||||
try:
|
||||
self.worker.moriio_wrapper.send_notify(
|
||||
task.transfer_id,
|
||||
remote_ip,
|
||||
remote_port,
|
||||
message_type="write_failed",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to notify decode DP rank %d that transfer %s timed out",
|
||||
decode_dp_rank,
|
||||
task.transfer_id,
|
||||
)
|
||||
|
||||
def _clear_transfer_state(self, transfer_id: TransferId) -> None:
|
||||
with self._write_state_lock:
|
||||
self._scheduled_writes.pop(transfer_id, None)
|
||||
@@ -314,27 +338,12 @@ class MoRIIOWriter:
|
||||
request_info = self._get_remote_alloc_info(task.transfer_id)
|
||||
with self._write_state_lock:
|
||||
request_info.completion_request_id = task.request_id
|
||||
# Wide-EP multi-pod: task.remote_ip addresses only the first pod,
|
||||
# so resolve the per-rank host from multi_pod_hosts (falls back to
|
||||
# task.remote_ip for single-pod or on any indexing miss).
|
||||
_remote_ip = task.remote_ip
|
||||
_hosts = task.multi_pod_hosts
|
||||
_dp_local = task.remote_dp_size_local
|
||||
if _hosts and _dp_local > 0:
|
||||
_pod_idx = int(request_info.decode_dp_rank) // _dp_local
|
||||
if 0 <= _pod_idx < len(_hosts):
|
||||
_remote_ip = _hosts[_pod_idx]
|
||||
request_info.completion_remote_ip = _remote_ip
|
||||
# Resolve the final notify port under the lock so finalize only
|
||||
# reads it. The offset uses the per-pod local rank (% dp_local),
|
||||
# since each pod binds notify sockets only for its local ranks;
|
||||
# single-pod is bit-identical (modulus is a no-op).
|
||||
_decode_dp_rank_for_port = int(request_info.decode_dp_rank)
|
||||
if _dp_local > 0:
|
||||
_decode_dp_rank_for_port = _decode_dp_rank_for_port % _dp_local
|
||||
request_info.completion_notify_port = task.remote_notify_port + (
|
||||
get_port_offset(_decode_dp_rank_for_port, self.worker.tp_rank)
|
||||
)
|
||||
# Resolve the final notify endpoint under the lock so finalize only
|
||||
# reads it.
|
||||
(
|
||||
request_info.completion_remote_ip,
|
||||
request_info.completion_notify_port,
|
||||
) = self._resolve_notify_endpoint(task, request_info.decode_dp_rank)
|
||||
if task.transfer_id in self._sealed_writes:
|
||||
request_info.writes_expected = self._sealed_writes[task.transfer_id]
|
||||
|
||||
@@ -506,6 +515,26 @@ class MoRIIOWriter:
|
||||
remote_port,
|
||||
)
|
||||
|
||||
def _resolve_notify_endpoint(
|
||||
self, task: WriteTask, decode_dp_rank: int
|
||||
) -> tuple[str, int]:
|
||||
# Wide-EP multi-pod: task.remote_ip addresses only the first pod, so
|
||||
# resolve the per-rank host from multi_pod_hosts (falls back to
|
||||
# task.remote_ip for single-pod or on any indexing miss). The port
|
||||
# offset uses the per-pod local rank, since each pod binds notify
|
||||
# sockets only for its local ranks.
|
||||
decode_dp_rank = int(decode_dp_rank)
|
||||
dp_local = task.remote_dp_size_local
|
||||
remote_ip = task.remote_ip
|
||||
if task.multi_pod_hosts and dp_local > 0:
|
||||
remote_pod = pod_index(decode_dp_rank, dp_local)
|
||||
if 0 <= remote_pod < len(task.multi_pod_hosts):
|
||||
remote_ip = task.multi_pod_hosts[remote_pod]
|
||||
remote_port = task.remote_notify_port + get_port_offset(
|
||||
fold_local_rank(decode_dp_rank, dp_local), self.worker.tp_rank
|
||||
)
|
||||
return remote_ip, remote_port
|
||||
|
||||
|
||||
class MoRIIOWrapper:
|
||||
"""Wrapper for MoRIIO engine operations.
|
||||
@@ -539,6 +568,7 @@ class MoRIIOWrapper:
|
||||
self.done_req_ids: list[MoRIIOTransferAck] = []
|
||||
self.done_remote_allocate_req_dict: dict[TransferId, RemoteAllocInfo] = {}
|
||||
self.done_write_cache_req_ids: list[str] = []
|
||||
self.failed_write_cache_req_ids: list[str] = []
|
||||
self._terminal_transfer_ids: OrderedDict[TransferId, None] = OrderedDict()
|
||||
self._transfer_timeout = transfer_timeout
|
||||
self.notify_thread: threading.Thread | None = None
|
||||
@@ -803,6 +833,8 @@ class MoRIIOWrapper:
|
||||
self._handle_remote_blocks_message(data)
|
||||
elif message_type == "write_done":
|
||||
self._handle_write_done_message(data)
|
||||
elif message_type == "write_failed":
|
||||
self._handle_write_failed_message(data)
|
||||
elif message_type == "release":
|
||||
self._handle_release_message(data)
|
||||
else:
|
||||
@@ -837,6 +869,12 @@ class MoRIIOWrapper:
|
||||
with self.lock:
|
||||
self.done_write_cache_req_ids.append(transfer_id)
|
||||
|
||||
def _handle_write_failed_message(self, data: dict):
|
||||
assert get_role() != ROLE.PRODUCER, "Only decode can get WRITE failure messages"
|
||||
transfer_id = data["transfer_id"]
|
||||
with self.lock:
|
||||
self.failed_write_cache_req_ids.append(transfer_id)
|
||||
|
||||
def _handle_release_message(self, data: dict):
|
||||
assert get_role() == ROLE.PRODUCER, (
|
||||
"Only prefill can get transfer release messages"
|
||||
@@ -852,6 +890,23 @@ class MoRIIOWrapper:
|
||||
self.done_remote_allocate_req_dict.pop(transfer_id, None)
|
||||
self._mark_transfer_terminal_locked(transfer_id)
|
||||
|
||||
def fail_unallocated_write(self, transfer_id: TransferId) -> bool:
|
||||
"""Mark a WRITE transfer terminal and release its source blocks if
|
||||
decode never sent its allocation.
|
||||
|
||||
Returns False if the transfer is already terminal or the allocation
|
||||
has arrived; the writer then drops or executes the task as usual.
|
||||
"""
|
||||
with self.lock:
|
||||
if (
|
||||
self._is_transfer_terminal_locked(transfer_id)
|
||||
or transfer_id in self.done_remote_allocate_req_dict
|
||||
):
|
||||
return False
|
||||
self._mark_transfer_terminal_locked(transfer_id)
|
||||
self.done_req_ids.append(MoRIIOTransferAck(transfer_id))
|
||||
return True
|
||||
|
||||
def _handle_completion_message(self, msg: str):
|
||||
with self.lock:
|
||||
if get_role() == ROLE.PRODUCER:
|
||||
@@ -929,6 +984,12 @@ class MoRIIOWrapper:
|
||||
self.done_write_cache_req_ids = []
|
||||
return done_write_cache
|
||||
|
||||
def pop_failed_write_req_ids(self):
|
||||
with self.lock:
|
||||
failed_write_cache = set(self.failed_write_cache_req_ids)
|
||||
self.failed_write_cache_req_ids = []
|
||||
return failed_write_cache
|
||||
|
||||
def shutdown(self):
|
||||
logger.debug("Closing MoRIIOWrapper and cleaning up ZMQ sockets")
|
||||
for path, sock in self.paths.items():
|
||||
|
||||
@@ -222,6 +222,17 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
def requires_kv_delivery(self) -> bool:
|
||||
return any(c.requires_kv_delivery for c in self._connectors)
|
||||
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: "KVTransferConfig") -> bool:
|
||||
children = [
|
||||
KVTransferConfig(**{"engine_id": kv_transfer_config.engine_id, **c})
|
||||
for c in kv_transfer_config.kv_connector_extra_config.get("connectors", [])
|
||||
]
|
||||
return bool(children) and all(
|
||||
KVConnectorFactory.get_connector_class(c).supports_sleep_mode(c)
|
||||
for c in children
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _get_connector_classes_and_configs(
|
||||
cls, vllm_config: "VllmConfig"
|
||||
@@ -252,6 +263,14 @@ class MultiConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
for c in self._connectors:
|
||||
c.register_kv_caches(kv_caches)
|
||||
|
||||
def unregister_kv_caches(self) -> None:
|
||||
for c in self._connectors:
|
||||
c.unregister_kv_caches()
|
||||
|
||||
def restore_kv_caches(self) -> None:
|
||||
for c in self._connectors:
|
||||
c.restore_kv_caches()
|
||||
|
||||
def bind_kv_cache_manager(self, kv_cache_manager: "KVCacheManager") -> None:
|
||||
for connector in self._connectors:
|
||||
connector.bind_kv_cache_manager(kv_cache_manager)
|
||||
|
||||
@@ -28,6 +28,7 @@ from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
EngineTransferInfo,
|
||||
TransferTopology,
|
||||
get_current_attn_backends,
|
||||
get_current_attn_backends_and_specs,
|
||||
kv_postprocess_blksize_and_layout_on_receive,
|
||||
kv_postprocess_blksize_on_receive,
|
||||
)
|
||||
@@ -64,7 +65,11 @@ from vllm.distributed.kv_transfer.kv_connector.v1.ssm_conv_transfer_utils import
|
||||
MambaConvSplitInfo,
|
||||
derive_mamba_conv_split,
|
||||
)
|
||||
from vllm.distributed.nixl_utils import NixlWrapper, nixl_agent_config
|
||||
from vllm.distributed.nixl_utils import (
|
||||
NixlWrapper,
|
||||
check_nixl_version,
|
||||
nixl_agent_config,
|
||||
)
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_pcp_group,
|
||||
get_tensor_model_parallel_rank,
|
||||
@@ -79,7 +84,6 @@ from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KpoolTailSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
@@ -88,7 +92,6 @@ from vllm.v1.kv_cache_interface import (
|
||||
UniformTypeKVCacheSpecs,
|
||||
iter_layer_specs,
|
||||
)
|
||||
from vllm.v1.worker.block_table import BlockTable
|
||||
from vllm.v1.worker.utils import select_common_block_size
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -120,46 +123,6 @@ def _share_storage_and_block_stride(caches: list[torch.Tensor]) -> bool:
|
||||
return len(block_strides) == len(storage_ptrs) == 1
|
||||
|
||||
|
||||
def _tensor_byte_span_end(cache: torch.Tensor) -> int:
|
||||
"""Return the exclusive end address touched by a nonnegative-stride view."""
|
||||
if cache.numel() == 0:
|
||||
return cache.data_ptr()
|
||||
if any(stride < 0 for stride in cache.stride()):
|
||||
raise ValueError("NIXL cache views must have nonnegative strides")
|
||||
max_element_offset = sum(
|
||||
(size - 1) * stride for size, stride in zip(cache.shape, cache.stride())
|
||||
)
|
||||
return cache.data_ptr() + (max_element_offset + 1) * cache.element_size()
|
||||
|
||||
|
||||
def _uses_dense_virtual_transfer_pages(
|
||||
layer_spec: KVCacheSpec,
|
||||
cache: torch.Tensor,
|
||||
physical_page_size: int,
|
||||
num_blocks: int,
|
||||
) -> bool:
|
||||
"""Return whether a compressed kernel view can be split into NIXL pages."""
|
||||
if not (
|
||||
isinstance(layer_spec, MLAAttentionSpec)
|
||||
and layer_spec.tokens_per_state > 1
|
||||
and cache.ndim == 4
|
||||
and cache.shape[1] == 1
|
||||
and cache.is_contiguous()
|
||||
and physical_page_size > 0
|
||||
and layer_spec.state_content_size_bytes > 0
|
||||
):
|
||||
return False
|
||||
|
||||
block_stride = cache.stride(0) * cache.element_size()
|
||||
return (
|
||||
block_stride > physical_page_size
|
||||
and block_stride % physical_page_size == 0
|
||||
and physical_page_size % layer_spec.state_content_size_bytes == 0
|
||||
and cache.shape[0] * (block_stride // physical_page_size) == num_blocks
|
||||
and cache.nbytes == num_blocks * physical_page_size
|
||||
)
|
||||
|
||||
|
||||
class NixlBaseConnectorWorker:
|
||||
"""Base implementation of Worker side methods shared by pull and push."""
|
||||
|
||||
@@ -318,20 +281,23 @@ class NixlBaseConnectorWorker:
|
||||
src_blocks_data: np.ndarray,
|
||||
num_fa_descs: int,
|
||||
block_size_ratio: int = 1,
|
||||
) -> Iterator[list[tuple[int, int, int]]]:
|
||||
) -> Iterator[np.ndarray]:
|
||||
"""Build split handle data for P_TP > D_TP scenario.
|
||||
|
||||
num_fa_descs is the boundary between FA and SSM descriptors.
|
||||
Split counts are derived from source_ranks_per_group lengths.
|
||||
FA uses rank_to_attention_slot for the slot offset;
|
||||
SSM uses the rank's positional index.
|
||||
Each Nx5 strided desc covers one region, so slicing it slices every block.
|
||||
"""
|
||||
fa_idx = next(
|
||||
i for i, t in enumerate(self._group_spec_types) if _is_attention_spec(t)
|
||||
)
|
||||
fa_num_splits = len(plan.source_ranks_per_group[fa_idx])
|
||||
|
||||
has_ssm_descs = num_fa_descs < len(src_blocks_data)
|
||||
starts = self._strided_desc_starts(src_blocks_data)
|
||||
num_descs = int(src_blocks_data[:, 4].sum())
|
||||
has_ssm_descs = num_fa_descs < num_descs
|
||||
ssm_idx = next(
|
||||
(i for i, t in enumerate(self._group_spec_types) if _is_ssm_spec(t)),
|
||||
None,
|
||||
@@ -341,38 +307,34 @@ class NixlBaseConnectorWorker:
|
||||
if has_ssm_descs and ssm_idx is not None
|
||||
else 0
|
||||
)
|
||||
|
||||
# Per-FA-descriptor replicate flag, in _build_fa_local emission order.
|
||||
fa_desc_replicated = self._fa_desc_replicated(num_fa_descs, block_size_ratio)
|
||||
sharded_desc_end = len(src_blocks_data) - (
|
||||
sharded_desc_end = num_descs - (
|
||||
self._logical_num_blocks if self._ple_region_index is not None else 0
|
||||
)
|
||||
assert num_fa_descs <= sharded_desc_end
|
||||
|
||||
assert block_size_ratio == 1 or fa_num_splits == 1 or all(fa_desc_replicated), (
|
||||
# REPLICATE (MLA) descs are read whole on every rank; SPLIT (full-attn)
|
||||
# descs take this rank's head slice. SSM descs before the PLE pages are
|
||||
# sharded by the rank's positional index; PLE pages are copied whole.
|
||||
is_fa = starts < num_fa_descs
|
||||
fa_replicated = self._fa_desc_replicated(
|
||||
starts[is_fa], num_fa_descs, block_size_ratio
|
||||
)
|
||||
assert block_size_ratio == 1 or fa_num_splits == 1 or fa_replicated.all(), (
|
||||
"Head-sharded attention reads with P_TP > D_TP and heterogeneous "
|
||||
"block sizes are not supported"
|
||||
)
|
||||
src_blocks_list = src_blocks_data.tolist()
|
||||
fa_split = is_fa.copy()
|
||||
fa_split[is_fa] = ~fa_replicated
|
||||
ssm_split = ~is_fa & (starts < sharded_desc_end)
|
||||
|
||||
for p_idx, p_rank in enumerate(plan.all_source_ranks):
|
||||
fa_slot = plan.rank_to_attention_slot.get(p_rank, 0)
|
||||
|
||||
handle: list[tuple[int, int, int]] = []
|
||||
for j, (addr, local_len, dev) in enumerate(src_blocks_list):
|
||||
if j < num_fa_descs:
|
||||
if fa_desc_replicated[j]:
|
||||
# REPLICATE (MLA): whole block written on every rank.
|
||||
handle.append((addr, local_len, dev))
|
||||
else:
|
||||
# SPLIT (full-attn): this rank's head slice.
|
||||
chunk = local_len // fa_num_splits
|
||||
handle.append((addr + fa_slot * chunk, chunk, dev))
|
||||
elif j < sharded_desc_end:
|
||||
chunk = local_len // ssm_num_splits
|
||||
handle.append((addr + p_idx * chunk, chunk, dev))
|
||||
else:
|
||||
handle.append((addr, local_len, dev))
|
||||
handle = src_blocks_data.copy()
|
||||
handle[fa_split, 1] //= fa_num_splits
|
||||
handle[fa_split, 0] += fa_slot * handle[fa_split, 1]
|
||||
if ssm_num_splits:
|
||||
handle[ssm_split, 1] //= ssm_num_splits
|
||||
handle[ssm_split, 0] += p_idx * handle[ssm_split, 1]
|
||||
yield handle
|
||||
|
||||
def _needs_split_local_xfer_handles(self, tp_ratio: int, plan: TPMapping) -> bool:
|
||||
@@ -387,25 +349,30 @@ 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, 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``.
|
||||
self,
|
||||
desc_starts: np.ndarray,
|
||||
num_fa_descs: int,
|
||||
block_size_ratio: int = 1,
|
||||
) -> np.ndarray:
|
||||
"""Replicate flag per FA strided desc, given each one's flat block index.
|
||||
|
||||
_build_fa_local emits regions in order, with
|
||||
``region_num_blocks[i] * block_size_ratio`` blocks per region. A strided
|
||||
desc never spans regions, so the region owning its first block decides.
|
||||
"""
|
||||
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
|
||||
return np.zeros(len(desc_starts), dtype=bool)
|
||||
region_indices = self._transfer_layer_region_indices or range(n_regions)
|
||||
flags: list[bool] = []
|
||||
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}"
|
||||
region_ends = np.cumsum(
|
||||
[self.region_num_blocks[i] * block_size_ratio for i in region_indices]
|
||||
)
|
||||
return flags
|
||||
assert region_ends[-1] == num_fa_descs, (
|
||||
f"FA region blocks {region_ends[-1]} != num_fa_descs {num_fa_descs}"
|
||||
)
|
||||
replicated = np.array([self._is_region_replicated(i) for i in region_indices])
|
||||
return replicated[np.searchsorted(region_ends, desc_starts, side="right")]
|
||||
|
||||
def _is_region_replicated(self, region_idx: int) -> bool:
|
||||
"""Whether region ``region_idx`` is transferred REPLICATE vs SPLIT.
|
||||
@@ -543,6 +510,55 @@ class NixlBaseConnectorWorker:
|
||||
# One layer per region keeps a second alignment pass a no-op.
|
||||
nixl_agent_meta.region_members = [[name] for name in self._transfer_layer_names]
|
||||
|
||||
def _split_remote_packed_rows(self, nixl_agent_meta: NixlAgentMetadata) -> None:
|
||||
"""Map the remote's whole-row region onto our per-layer regions.
|
||||
|
||||
E.g. a BLHNC prefiller registers one region whose block is a full row
|
||||
holding every layer's page, while a HiSparse decoder registers one
|
||||
region per layer. Using the advertised `packed_member_layouts`, the
|
||||
remote row is rewritten in place as one virtual region per local layer:
|
||||
|
||||
remote row b: [ L0 page | L1 page | ... ] base=B, stride=S
|
||||
^off0 ^off1
|
||||
|
||||
remote metadata, before: [(B, S, S)] # (base, len, stride)
|
||||
remote metadata, after: [(B + off0, page0, S), # L0
|
||||
(B + off1, page1, S)] # L1
|
||||
|
||||
Remote regions outside the row (e.g. a separate indexer) pass through.
|
||||
"""
|
||||
layouts = nixl_agent_meta.packed_member_layouts
|
||||
remote_names = nixl_agent_meta.region_names
|
||||
assert remote_names is not None, "Remote advertised no region_names"
|
||||
(row,) = [i for i, name in enumerate(remote_names) if name in layouts]
|
||||
if nixl_agent_meta.region_group_ids is not None and (
|
||||
nixl_agent_meta.region_group_ids[row] == _SHARED_REGION_GROUP_ID
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Reading multi-group packed KV rows into per-layer regions is not "
|
||||
"supported; use the same KV cache layout on P and D."
|
||||
)
|
||||
remote_index = {name: i for i, name in enumerate(remote_names)}
|
||||
regions = [
|
||||
(row, *layouts[name])
|
||||
if name in layouts
|
||||
else (remote_index[name], 0, nixl_agent_meta.block_lens[remote_index[name]])
|
||||
for name in self.region_names
|
||||
]
|
||||
nixl_agent_meta.kv_caches_base_addr = [
|
||||
nixl_agent_meta.kv_caches_base_addr[i] + offset for i, offset, _ in regions
|
||||
]
|
||||
nixl_agent_meta.block_lens = [page_size for _, _, page_size in regions]
|
||||
nixl_agent_meta.block_strides = [
|
||||
nixl_agent_meta.block_strides[i] for i, _, _ in regions
|
||||
]
|
||||
for attr in ("region_num_blocks", "region_group_ids", "region_mem_types"):
|
||||
values = getattr(nixl_agent_meta, attr)
|
||||
if values is not None:
|
||||
setattr(nixl_agent_meta, attr, [values[i] for i, _, _ in regions])
|
||||
nixl_agent_meta.region_names = list(self.region_names)
|
||||
nixl_agent_meta.packed_member_layouts = {}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
@@ -553,6 +569,8 @@ class NixlBaseConnectorWorker:
|
||||
if nixl_wrapper_cls is None:
|
||||
logger.error("NIXL is not available")
|
||||
raise RuntimeError("NIXL is not available")
|
||||
# Descriptor lists are prepared in NIXL's strided (Nx5) form.
|
||||
check_nixl_version("1.5.0")
|
||||
logger.info("Initializing NIXL wrapper")
|
||||
logger.info("Initializing NIXL worker %s", engine_id)
|
||||
|
||||
@@ -951,6 +969,7 @@ class NixlBaseConnectorWorker:
|
||||
self._has_packed_cache = KVCacheLayout[self.kv_cache_layout].is_block_outermost
|
||||
# Region layer membership is populated for HMA and packed layouts.
|
||||
self.region_members = []
|
||||
self._packed_member_layouts: dict[str, tuple[int, int]] = {}
|
||||
# Local layer order, set by ``_set_region_layers`` only when
|
||||
# routing by layer name. Empty means region-index routing.
|
||||
self._transfer_layer_names = tuple[str, ...]()
|
||||
@@ -985,8 +1004,10 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
|
||||
def _sync_block_size_with_kernel(self) -> None:
|
||||
backends = get_current_attn_backends(self.vllm_config)
|
||||
kernel_block_size = select_common_block_size(self.block_size, backends)
|
||||
backends, specs = get_current_attn_backends_and_specs(
|
||||
self.vllm_config, self.kv_cache_config, self.attn_backends
|
||||
)
|
||||
kernel_block_size = select_common_block_size(self.block_size, backends, specs)
|
||||
# Number of blocks not accounting for kernel block mismatches
|
||||
self._logical_num_blocks = self.num_blocks
|
||||
if self.block_size != kernel_block_size:
|
||||
@@ -1425,7 +1446,7 @@ class NixlBaseConnectorWorker:
|
||||
if self._supports_pp_hma and self._has_packed_cache:
|
||||
# PP can reorder the same backends across stages of a packed model.
|
||||
backend_name = ",".join(
|
||||
sorted(backend.get_name() for backend in self.attn_backends)
|
||||
sorted({backend.get_name() for backend in self.attn_backends})
|
||||
)
|
||||
self.compat_hash = compute_nixl_compatibility_hash(
|
||||
self.vllm_config,
|
||||
@@ -1468,41 +1489,20 @@ class NixlBaseConnectorWorker:
|
||||
self._ple_block_len = None
|
||||
self._ple_region_index = None
|
||||
|
||||
packed_storage = _share_storage_and_block_stride(list(xfer_buffers.values()))
|
||||
# CSA-linear needs separate logical regions for attention and state
|
||||
# aliases even though every view shares one block-major allocation.
|
||||
packed_storage = packed_storage and not self._is_csa_linear
|
||||
# A shared packed row may transfer whole only if every page in it is
|
||||
# replicated across TP ranks: MLA without SSM state. Head-sharded
|
||||
# attention or SSM state (e.g. Qwen3.8-Flash-Next) must stay split.
|
||||
packed_storage = (
|
||||
_share_storage_and_block_stride(list(xfer_buffers.values()))
|
||||
and self.use_mla
|
||||
and not self._has_mamba
|
||||
)
|
||||
if route_packed_layers and any(
|
||||
not isinstance(spec, (MLAAttentionSpec, SlidingWindowMLASpec))
|
||||
for spec in self._layer_specs.values()
|
||||
):
|
||||
raise NotImplementedError("PP push with packed KV caches requires MLA")
|
||||
|
||||
layer_specs: dict[str, KVCacheSpec] = {}
|
||||
compressed_region_owners: dict[int, torch.Tensor] = {}
|
||||
for layer_name, cache in xfer_buffers.items():
|
||||
layer_spec = self._layer_specs.get(layer_name)
|
||||
if isinstance(layer_spec, UniformTypeKVCacheSpecs):
|
||||
layer_spec = layer_spec.kv_cache_specs[layer_name]
|
||||
if layer_spec is None:
|
||||
continue
|
||||
layer_specs[layer_name] = layer_spec
|
||||
physical_page_size = (
|
||||
layer_spec.page_size_bytes
|
||||
if isinstance(layer_spec, MambaSpec)
|
||||
else layer_spec.page_size_bytes
|
||||
// self._physical_blocks_per_logical_kv_block
|
||||
)
|
||||
num_blocks = (
|
||||
self._logical_num_blocks
|
||||
if isinstance(layer_spec, MambaSpec)
|
||||
else self.num_blocks
|
||||
)
|
||||
if _uses_dense_virtual_transfer_pages(
|
||||
layer_spec, cache, physical_page_size, num_blocks
|
||||
):
|
||||
compressed_region_owners.setdefault(cache.data_ptr(), cache)
|
||||
|
||||
track_region_layers = self._tracks_region_layers()
|
||||
region_layers: list[list[str]] = []
|
||||
packed_member_layouts: dict[str, tuple[int, int]] = {}
|
||||
@@ -1527,7 +1527,7 @@ class NixlBaseConnectorWorker:
|
||||
# kernel requires a specific block size. This leads to SSM and FA layers
|
||||
# having different num_blocks.
|
||||
# `_physical_blocks_per_logical_kv_block` ratio is used to adjust for this.
|
||||
layer_spec = layer_specs.get(layer_name)
|
||||
layer_spec = self._layer_specs.get(layer_name)
|
||||
if layer_spec is None:
|
||||
logger.debug(
|
||||
"Skipping layer %s as no KVCache spec is present. "
|
||||
@@ -1556,7 +1556,6 @@ class NixlBaseConnectorWorker:
|
||||
if isinstance(layer_spec, MambaSpec)
|
||||
else logical_num_blocks * self._physical_blocks_per_logical_kv_block
|
||||
)
|
||||
base_addr = cache.data_ptr()
|
||||
is_mla_region = isinstance(
|
||||
layer_spec, (MLAAttentionSpec, SlidingWindowMLASpec)
|
||||
)
|
||||
@@ -1587,32 +1586,6 @@ class NixlBaseConnectorWorker:
|
||||
region_device_id,
|
||||
)
|
||||
|
||||
if isinstance(layer_spec, KpoolTailSpec):
|
||||
compressed_owner = compressed_region_owners.get(cache.data_ptr())
|
||||
if compressed_owner is not None:
|
||||
owner_storage = compressed_owner.untyped_storage()
|
||||
owner_end = compressed_owner.data_ptr() + compressed_owner.nbytes
|
||||
tail_is_covered = (
|
||||
compressed_owner.is_contiguous()
|
||||
and owner_storage.data_ptr() == storage_addr
|
||||
and _tensor_byte_span_end(cache) <= owner_end
|
||||
)
|
||||
if not tail_is_covered:
|
||||
raise AssertionError(
|
||||
"Kpool tail cache is not fully covered by its compressed "
|
||||
f"indexer region: layer={layer_name}, "
|
||||
f"tail_shape={tuple(cache.shape)}, "
|
||||
f"tail_stride={tuple(cache.stride())}, "
|
||||
f"owner_shape={tuple(compressed_owner.shape)}, "
|
||||
f"owner_stride={tuple(compressed_owner.stride())}"
|
||||
)
|
||||
logger.debug(
|
||||
"Skipping layer %s because its compressed indexer region "
|
||||
"covers the same storage",
|
||||
layer_name,
|
||||
)
|
||||
continue
|
||||
|
||||
if isinstance(layer_spec, MambaSpec):
|
||||
physical_ratio = self._physical_blocks_per_logical_kv_block
|
||||
block_len = physical_page_size // physical_ratio
|
||||
@@ -1647,31 +1620,24 @@ class NixlBaseConnectorWorker:
|
||||
and cache[0].is_contiguous()
|
||||
and cache[0].nbytes == physical_page_size
|
||||
)
|
||||
virtual_transfer_pages = _uses_dense_virtual_transfer_pages(
|
||||
layer_spec, cache, physical_page_size, num_blocks
|
||||
)
|
||||
# Push workers address the pages of packed MLA rows by layer.
|
||||
packed_mla_push = (
|
||||
track_region_layers
|
||||
and self._has_packed_cache
|
||||
# Block-outermost MLA: one block row holds every layer's page.
|
||||
packed_mla = (
|
||||
self._has_packed_cache
|
||||
and not self._has_mamba
|
||||
and packed_storage
|
||||
and storage_is_block_major
|
||||
and is_mla_region
|
||||
)
|
||||
if virtual_transfer_pages:
|
||||
# A compressed kernel row can contain multiple NIXL transfer pages.
|
||||
region_specs = [
|
||||
(cache.data_ptr(), physical_page_size, physical_page_size)
|
||||
]
|
||||
elif packed_mla_push and use_layer_name_routing:
|
||||
if packed_mla and use_layer_name_routing:
|
||||
# PP>1 prefill stage: register only this layer's page of each row.
|
||||
region_specs = [
|
||||
(cache.data_ptr(), physical_page_size, block_stride)
|
||||
]
|
||||
elif packed_mla_push:
|
||||
# PP=1 decode or prefill: register whole rows, and advertise where
|
||||
# this layer's page sits so a PP>1 prefill can write into it.
|
||||
storage_block_len = registration_len // num_blocks
|
||||
elif packed_mla and (self.pp_size == 1 or not page_contiguous):
|
||||
# Register whole rows so a block is a single descriptor. Also,
|
||||
# advertise where this layer's page sits so a remote with
|
||||
# LB* can still address it (HiSparse).
|
||||
storage_block_len = block_stride
|
||||
region_specs = [
|
||||
(registration_base, storage_block_len, storage_block_len)
|
||||
]
|
||||
@@ -1805,6 +1771,7 @@ class NixlBaseConnectorWorker:
|
||||
self.region_num_blocks = [self.num_blocks] * self.num_regions
|
||||
|
||||
self._set_region_layers(region_layers)
|
||||
self._packed_member_layouts = packed_member_layouts
|
||||
|
||||
if self.pp_size > 1 and not use_layer_name_routing:
|
||||
start_layer, end_layer = self.model_config.get_layers_start_end_indices(
|
||||
@@ -1900,7 +1867,7 @@ class NixlBaseConnectorWorker:
|
||||
dcp_size=self.dcp_size,
|
||||
pcp_size=self.pcp_size,
|
||||
region_members=self.region_members,
|
||||
packed_member_layouts=packed_member_layouts,
|
||||
packed_member_layouts=self._packed_member_layouts,
|
||||
)
|
||||
# Wrap metadata in payload with hash for defensive decoding
|
||||
assert self.compat_hash is not None
|
||||
@@ -1925,7 +1892,7 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
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.
|
||||
local mamba blocks with DS conv layout, as Nx5 uint64 strided descs.
|
||||
|
||||
A Mamba block interleaves conv and SSM state, which crucially differ in
|
||||
size, so the two are indexed as separate sub-regions. Attention blocks
|
||||
@@ -1963,28 +1930,32 @@ class NixlBaseConnectorWorker:
|
||||
num_blocks = self._logical_num_blocks
|
||||
physical_per_logical = self._physical_blocks_per_logical_kv_block
|
||||
device_id = self.device_id
|
||||
block_arange = np.arange(num_blocks, dtype=np.uint64)
|
||||
parts: list[np.ndarray] = []
|
||||
strided_descs: list[tuple[int, int, int, int, int]] = []
|
||||
|
||||
region_indices = self._ssm_region_indices or range(len(base_addresses))
|
||||
for i in region_indices:
|
||||
base_addr = base_addresses[i]
|
||||
block_stride = self.block_stride_per_layer[i] * physical_per_logical
|
||||
blk_addrs = base_addr + block_arange * block_stride
|
||||
for off, sz in conv_offsets:
|
||||
parts.append(self._stack_descs(blk_addrs + off, sz, device_id))
|
||||
strided_descs.append(
|
||||
(base_addr + off, sz, device_id, block_stride, num_blocks)
|
||||
)
|
||||
# SSM temporal state follows the conv state.
|
||||
parts.append(self._stack_descs(blk_addrs + conv_size, ssm_size, device_id))
|
||||
strided_descs.append(
|
||||
(base_addr + conv_size, ssm_size, device_id, block_stride, num_blocks)
|
||||
)
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
block_len = self._ple_page_len() * physical_per_logical
|
||||
block_stride = (
|
||||
self.block_stride_per_layer[region_index] * physical_per_logical
|
||||
)
|
||||
block_addrs = base_addresses[region_index] + block_arange * block_stride
|
||||
parts.append(self._stack_descs(block_addrs, block_len, self.device_id))
|
||||
base_addr = base_addresses[region_index]
|
||||
strided_descs.append(
|
||||
(base_addr, block_len, device_id, block_stride, num_blocks)
|
||||
)
|
||||
|
||||
return np.concatenate(parts)
|
||||
return self._pack_strided_descs(strided_descs)
|
||||
|
||||
def _build_mamba_remote(
|
||||
self,
|
||||
@@ -1994,7 +1965,7 @@ class NixlBaseConnectorWorker:
|
||||
) -> np.ndarray:
|
||||
"""Build remote desc regions (conv sub-projections + ssm) per layer.
|
||||
For hetero-TP, each D rank reads only its sub-projection slice from
|
||||
the P rank. Returns an Nx3 uint64 array."""
|
||||
the P rank. Returns Nx5 uint64 strided descs."""
|
||||
assert nixl_agent_meta.kv_caches_base_addr, (
|
||||
"Remote KV cache base addresses must not be empty."
|
||||
)
|
||||
@@ -2014,9 +1985,8 @@ class NixlBaseConnectorWorker:
|
||||
remote_physical_per_logical = transfer_info.remote_physical_blocks_per_logical
|
||||
num_blocks = nixl_agent_meta.num_blocks // remote_physical_per_logical
|
||||
device_id = nixl_agent_meta.device_id
|
||||
block_arange = np.arange(num_blocks, dtype=np.uint64)
|
||||
|
||||
parts: list[np.ndarray] = []
|
||||
strided_descs: list[tuple[int, int, int, int, int]] = []
|
||||
# NOTE (ZhanqiuHu): use per-layer block_lens[i], not [0], in case
|
||||
# block lengths vary across layers (e.g. MLA).
|
||||
region_indices = self._ssm_region_indices or range(
|
||||
@@ -2027,12 +1997,15 @@ class NixlBaseConnectorWorker:
|
||||
block_stride = (
|
||||
nixl_agent_meta.block_strides[i] * remote_physical_per_logical
|
||||
)
|
||||
blk_addrs = base_addr + block_arange * block_stride
|
||||
for off, sz in conv_offsets:
|
||||
parts.append(self._stack_descs(blk_addrs + off, sz, device_id))
|
||||
strided_descs.append(
|
||||
(base_addr + off, sz, device_id, block_stride, num_blocks)
|
||||
)
|
||||
# SSM temporal state is also TP-sharded on the heads dimension.
|
||||
ssm_addrs = blk_addrs + conv_size_remote + local_offset * ssm_read_size
|
||||
parts.append(self._stack_descs(ssm_addrs, ssm_read_size, device_id))
|
||||
ssm_addr = base_addr + conv_size_remote + local_offset * ssm_read_size
|
||||
strided_descs.append(
|
||||
(ssm_addr, ssm_read_size, device_id, block_stride, num_blocks)
|
||||
)
|
||||
|
||||
if (region_index := self._ple_region_index) is not None:
|
||||
local_block_len = (
|
||||
@@ -2052,52 +2025,85 @@ class NixlBaseConnectorWorker:
|
||||
nixl_agent_meta.block_strides[region_index]
|
||||
* remote_physical_per_logical
|
||||
)
|
||||
block_addrs = (
|
||||
nixl_agent_meta.kv_caches_base_addr[region_index]
|
||||
+ block_arange * remote_block_stride
|
||||
addr = nixl_agent_meta.kv_caches_base_addr[region_index]
|
||||
strided_descs.append(
|
||||
(addr, remote_block_len, device_id, remote_block_stride, num_blocks)
|
||||
)
|
||||
parts.append(self._stack_descs(block_addrs, remote_block_len, device_id))
|
||||
|
||||
return np.concatenate(parts)
|
||||
return self._pack_strided_descs(strided_descs)
|
||||
|
||||
@staticmethod
|
||||
def _stack_descs(addrs: np.ndarray, length: int, device_id: int) -> np.ndarray:
|
||||
out = np.empty((addrs.shape[0], 3), dtype=np.uint64)
|
||||
out[:, 0] = addrs
|
||||
out[:, 1] = length
|
||||
out[:, 2] = device_id
|
||||
return out
|
||||
def _pack_strided_descs(
|
||||
strided_descs: list[tuple[int, int, int, int, int]],
|
||||
) -> np.ndarray:
|
||||
"""Pack (addr, len, dev_id, stride, count) rows into an Nx5 uint64 array.
|
||||
|
||||
Each row describes `count` blocks of `len` bytes whose starts are
|
||||
`stride` bytes apart; NIXL >= 1.5 prepares this layout directly.
|
||||
"""
|
||||
return np.array(strided_descs, dtype=np.uint64).reshape(-1, 5)
|
||||
|
||||
@staticmethod
|
||||
def _block_strided_descs(
|
||||
base_addr: int,
|
||||
block_len: int,
|
||||
block_stride: int,
|
||||
num_blocks: int,
|
||||
block_size_ratio: int,
|
||||
device_id: int,
|
||||
) -> np.ndarray:
|
||||
"""Nx5 strided descs for `num_blocks` blocks, each split into
|
||||
`block_size_ratio` sub-blocks of `block_len` bytes.
|
||||
|
||||
Evenly spaced sub-blocks collapse into one strided desc. In a padded
|
||||
block the sub-blocks abut only within the block, so each block gets
|
||||
its own.
|
||||
"""
|
||||
if block_size_ratio == 1 or block_stride == block_size_ratio * block_len:
|
||||
stride = block_stride // block_size_ratio
|
||||
count = num_blocks * block_size_ratio
|
||||
return np.array(
|
||||
[[base_addr, block_len, device_id, stride, count]], dtype=np.uint64
|
||||
)
|
||||
strided_descs = np.empty((num_blocks, 5), dtype=np.uint64)
|
||||
strided_descs[:, 0] = (
|
||||
base_addr + np.arange(num_blocks, dtype=np.uint64) * block_stride
|
||||
)
|
||||
strided_descs[:, 1] = block_len
|
||||
strided_descs[:, 2] = device_id
|
||||
strided_descs[:, 3] = block_len
|
||||
strided_descs[:, 4] = block_size_ratio
|
||||
return strided_descs
|
||||
|
||||
@staticmethod
|
||||
def _strided_desc_starts(strided_descs: np.ndarray) -> np.ndarray:
|
||||
"""Flat block index of each strided desc's first block."""
|
||||
counts = strided_descs[:, 4]
|
||||
return np.cumsum(counts) - counts
|
||||
|
||||
def _build_fa_local(
|
||||
self,
|
||||
base_addresses: list[int],
|
||||
block_size_ratio: int,
|
||||
) -> np.ndarray:
|
||||
"""Build local FA descriptors as an Nx3 uint64 array."""
|
||||
"""Build local FA descriptors as Nx5 uint64 strided descs."""
|
||||
assert self.transfer_topo is not None
|
||||
assert base_addresses, "Local KV cache base addresses must not be empty."
|
||||
device_id = self.device_id
|
||||
region_indices = self._transfer_layer_region_indices or range(
|
||||
len(base_addresses)
|
||||
)
|
||||
parts: list[np.ndarray] = []
|
||||
for i in region_indices:
|
||||
base_addr = base_addresses[i]
|
||||
block_len = self.block_len_per_layer[i] // block_size_ratio
|
||||
logical_blocks = np.repeat(
|
||||
np.arange(self.region_num_blocks[i], dtype=np.uint64),
|
||||
block_size_ratio,
|
||||
)
|
||||
split_offsets = np.tile(
|
||||
np.arange(block_size_ratio, dtype=np.uint64),
|
||||
parts = [
|
||||
self._block_strided_descs(
|
||||
base_addresses[i],
|
||||
self.block_len_per_layer[i] // block_size_ratio,
|
||||
self.block_stride_per_layer[i],
|
||||
self.region_num_blocks[i],
|
||||
block_size_ratio,
|
||||
device_id,
|
||||
)
|
||||
addrs = (
|
||||
base_addr
|
||||
+ logical_blocks * self.block_stride_per_layer[i]
|
||||
+ split_offsets * block_len
|
||||
)
|
||||
parts.append(self._stack_descs(addrs, block_len, device_id))
|
||||
for i in region_indices
|
||||
]
|
||||
return np.concatenate(parts)
|
||||
|
||||
def _build_fa_remote(
|
||||
@@ -2106,7 +2112,7 @@ class NixlBaseConnectorWorker:
|
||||
nixl_agent_meta: NixlAgentMetadata,
|
||||
block_size_ratio: int,
|
||||
) -> np.ndarray:
|
||||
"""Build remote FA descriptors as an Nx3 uint64 array."""
|
||||
"""Build remote FA descriptors as Nx5 uint64 strided descs."""
|
||||
assert self.transfer_topo is not None
|
||||
assert nixl_agent_meta.kv_caches_base_addr, (
|
||||
"Remote KV cache base addresses must not be empty."
|
||||
@@ -2122,7 +2128,7 @@ class NixlBaseConnectorWorker:
|
||||
] * len(nixl_agent_meta.kv_caches_base_addr)
|
||||
device_id = nixl_agent_meta.device_id
|
||||
block_strides = nixl_agent_meta.block_strides
|
||||
parts: list[np.ndarray] = []
|
||||
strided_descs: list[tuple[int, int, int, int, int]] = []
|
||||
use_layer_name_routing = bool(self._transfer_layer_region_indices)
|
||||
for i, base_addr in enumerate(nixl_agent_meta.kv_caches_base_addr):
|
||||
local_region = (
|
||||
@@ -2144,10 +2150,12 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
local_block_len = local_block_len // num_reads
|
||||
|
||||
block_arange = np.arange(region_num_blocks[i], dtype=np.uint64)
|
||||
addrs = base_addr + rank_offset + block_arange * block_strides[i]
|
||||
parts.append(self._stack_descs(addrs, local_block_len, device_id))
|
||||
return np.concatenate(parts)
|
||||
addr = base_addr + rank_offset
|
||||
count = region_num_blocks[i]
|
||||
strided_descs.append(
|
||||
(addr, local_block_len, device_id, block_strides[i], count)
|
||||
)
|
||||
return self._pack_strided_descs(strided_descs)
|
||||
|
||||
def register_local_xfer_handler(
|
||||
self,
|
||||
@@ -2170,13 +2178,13 @@ class NixlBaseConnectorWorker:
|
||||
blocks_data = self._build_fa_local(local_base_addresses, block_size_ratio)
|
||||
logger.debug(
|
||||
"Created %s blocks for src engine %s and rank %s on device id %s",
|
||||
len(blocks_data),
|
||||
blocks_data[:, 4].sum(),
|
||||
self.engine_id,
|
||||
self.tp_rank,
|
||||
self.device_id,
|
||||
)
|
||||
if self._has_mamba:
|
||||
assert self.num_descs * block_size_ratio == len(blocks_data)
|
||||
assert self.num_descs * block_size_ratio == blocks_data[:, 4].sum()
|
||||
# TODO (ZhanqiuHu): For homogeneous TP (tp_ratio == 1), the 3-descs split
|
||||
# is unnecessary — a single conv desc per block suffices. Consider
|
||||
# adding a fast path that falls back to the standard 2-region
|
||||
@@ -2202,7 +2210,7 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
]
|
||||
)
|
||||
assert len(desc_is_dram) == len(blocks_data)
|
||||
assert len(desc_is_dram) == blocks_data[:, 4].sum()
|
||||
desc_pos = np.empty(len(desc_is_dram), dtype=np.int64)
|
||||
dram_idx = np.where(desc_is_dram)[0]
|
||||
vram_idx = np.where(~desc_is_dram)[0]
|
||||
@@ -2210,28 +2218,32 @@ class NixlBaseConnectorWorker:
|
||||
desc_pos[vram_idx] = np.arange(len(vram_idx), dtype=np.int64)
|
||||
self._desc_is_dram_by_block_size[block_size] = desc_is_dram
|
||||
self._desc_pos_by_block_size[block_size] = desc_pos
|
||||
|
||||
# DRAM descriptors are registered under CPU device 0.
|
||||
blocks_data[desc_is_dram, 2] = 0
|
||||
dram_blocks = blocks_data[dram_idx]
|
||||
vram_blocks = blocks_data[vram_idx]
|
||||
# A strided desc never spans regions, so its first block decides.
|
||||
strided_is_dram = desc_is_dram[self._strided_desc_starts(blocks_data)]
|
||||
blocks_data[strided_is_dram, 2] = 0
|
||||
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)
|
||||
self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT",
|
||||
blocks_data[strided_is_dram],
|
||||
mem_type="DRAM",
|
||||
)
|
||||
)
|
||||
descs = self.nixl_wrapper.get_xfer_descs(vram_blocks, self.nixl_memory_type)
|
||||
return (
|
||||
self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", descs),
|
||||
blocks_data,
|
||||
device_handle = self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT",
|
||||
blocks_data[~strided_is_dram],
|
||||
mem_type=self.nixl_memory_type,
|
||||
)
|
||||
return device_handle, blocks_data
|
||||
|
||||
mem_type = self.region_mem_types[0]
|
||||
descs = self.nixl_wrapper.get_xfer_descs(blocks_data, mem_type)
|
||||
# NIXL_INIT_AGENT to be used for preparations of local descs.
|
||||
return self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", descs), blocks_data
|
||||
handle = self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT", blocks_data, mem_type=self.region_mem_types[0]
|
||||
)
|
||||
return handle, blocks_data
|
||||
|
||||
def add_remote_agent(
|
||||
self,
|
||||
@@ -2308,6 +2320,11 @@ class NixlBaseConnectorWorker:
|
||||
"prefill TP yet"
|
||||
)
|
||||
self._align_remote_regions_by_layer(nixl_agent_meta)
|
||||
elif nixl_agent_meta.packed_member_layouts and not self._packed_member_layouts:
|
||||
# With HiSparse, P may be on BL* while D is LB*, as only indexer is on HBM.
|
||||
# TODO (NickLucche) we may consider not allowing this case at all (P BL*)
|
||||
# and just clear this function.
|
||||
self._split_remote_packed_rows(nixl_agent_meta)
|
||||
elif (
|
||||
self.pp_size > 1
|
||||
and len(nixl_agent_meta.kv_caches_base_addr) > num_local_regions
|
||||
@@ -2338,6 +2355,17 @@ class NixlBaseConnectorWorker:
|
||||
start:end
|
||||
]
|
||||
|
||||
if (
|
||||
self._packed_member_layouts
|
||||
and not self._transfer_layer_region_indices
|
||||
and self._packed_member_layouts != nixl_agent_meta.packed_member_layouts
|
||||
):
|
||||
# Whole rows transfer as one unit, so both sides must pack them alike.
|
||||
raise RuntimeError(
|
||||
"Packed KV block rows differ between P and D. Use the same "
|
||||
"VLLM_KV_CACHE_LAYOUT and block size on both sides."
|
||||
)
|
||||
|
||||
### Register remote engine in TransferTopology (idempotent).
|
||||
physical_blocks_per_logical = (
|
||||
nixl_agent_meta.physical_blocks_per_logical_kv_block
|
||||
@@ -2448,23 +2476,23 @@ class NixlBaseConnectorWorker:
|
||||
block_size_ratio,
|
||||
):
|
||||
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]
|
||||
strided_is_dram = desc_is_dram[
|
||||
self._strided_desc_starts(handle_data)
|
||||
]
|
||||
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
|
||||
"NIXL_INIT_AGENT",
|
||||
handle_data[strided_is_dram],
|
||||
mem_type="DRAM",
|
||||
)
|
||||
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(
|
||||
handle_data, self.nixl_memory_type
|
||||
handle_data = handle_data[~strided_is_dram]
|
||||
handle = self.nixl_wrapper.prep_xfer_dlist(
|
||||
"NIXL_INIT_AGENT", handle_data, mem_type=self.nixl_memory_type
|
||||
)
|
||||
handle = self.nixl_wrapper.prep_xfer_dlist("NIXL_INIT_AGENT", descs)
|
||||
self.src_xfer_handles_by_tp_ratio[split_key].append(handle)
|
||||
|
||||
### Register remote agent memory regions
|
||||
@@ -2481,7 +2509,7 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
logger.debug(
|
||||
"Created %s blocks for dst engine %s with remote rank %s and local rank %s",
|
||||
len(blocks_data),
|
||||
blocks_data[:, 4].sum(),
|
||||
engine_id,
|
||||
remote_tp_rank,
|
||||
self.tp_rank,
|
||||
@@ -2500,9 +2528,10 @@ class NixlBaseConnectorWorker:
|
||||
raise NotImplementedError(
|
||||
"NIXL pull does not yet support a mixed-memory producer"
|
||||
)
|
||||
descs = self.nixl_wrapper.get_xfer_descs(blocks_data, remote_mem_types.pop())
|
||||
self.dst_xfer_side_handles[engine_id][remote_tp_rank] = (
|
||||
self.nixl_wrapper.prep_xfer_dlist(remote_agent_name, descs)
|
||||
self.nixl_wrapper.prep_xfer_dlist(
|
||||
remote_agent_name, blocks_data, mem_type=remote_mem_types.pop()
|
||||
)
|
||||
)
|
||||
|
||||
return remote_agent_name
|
||||
@@ -2574,7 +2603,7 @@ class NixlBaseConnectorWorker:
|
||||
"is not supported for Mamba hybrid models. "
|
||||
f"Local: {self._physical_blocks_per_logical_kv_block}, "
|
||||
f"Remote: {remote_physical_per_logical}. "
|
||||
"Disable prefix caching with --no-enable-prefix-caching."
|
||||
"Disable prefix caching with --disable-prefix-caching."
|
||||
)
|
||||
|
||||
if block_size_ratio != 1:
|
||||
@@ -3388,11 +3417,9 @@ class NixlBaseConnectorWorker:
|
||||
physical_block_ids.append(group)
|
||||
else:
|
||||
physical_block_ids.append(
|
||||
BlockTable.map_to_kernel_blocks(
|
||||
np.array(group),
|
||||
ratio,
|
||||
block_arange,
|
||||
).tolist()
|
||||
(np.array(group)[:, None] * ratio + block_arange)
|
||||
.reshape(-1)
|
||||
.tolist()
|
||||
)
|
||||
return physical_block_ids
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
EngineId,
|
||||
)
|
||||
@@ -140,6 +140,10 @@ class NixlBaseConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
############################################################
|
||||
# Class Methods
|
||||
############################################################
|
||||
@classmethod
|
||||
def supports_sleep_mode(cls, kv_transfer_config: KVTransferConfig) -> bool:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_required_kvcache_layout(cls, vllm_config: VllmConfig):
|
||||
if vllm_config.model_config is None:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
@@ -10,14 +11,30 @@ from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
PromMetric,
|
||||
PromMetricT,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.kv_offload.base import (
|
||||
ConfigInfoMapping,
|
||||
OffloadingCounterMetadata,
|
||||
OffloadingGaugeMetadata,
|
||||
OffloadingHistogramMetadata,
|
||||
OffloadingMetricMetadata,
|
||||
OffloadingSpec,
|
||||
)
|
||||
from vllm.v1.kv_offload.factory import OffloadingSpecFactory
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
KV_OFFLOAD_CONFIG_INFO = "vllm:kv_offload_config_info"
|
||||
|
||||
_INFO_METRIC_HELP = (
|
||||
"Static configuration of the KV offload managers of this engine instance. "
|
||||
"The configured offloading spec declares the label names, and each manager "
|
||||
"fills the values, so a series appears from the first scheduler step of its "
|
||||
"engine. A manager reports one series for each configuration it holds, and "
|
||||
"a label of its own tells the series apart. Each engine reports its own "
|
||||
"configuration, not the instance total."
|
||||
)
|
||||
|
||||
|
||||
class _TransferMetricName:
|
||||
"""Flat metric names for GPU↔offload-medium transfer operations."""
|
||||
@@ -166,6 +183,9 @@ class _StatsKey:
|
||||
TYPES = "types"
|
||||
# Maps metric name -> {label values tuple -> observed value (number or list)}
|
||||
DATA = "data"
|
||||
# One mapping of info metric label name -> label value for each series.
|
||||
# None until a manager reports it, and one empty mapping for no fact.
|
||||
INFO = "info"
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -177,6 +197,7 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
{
|
||||
_StatsKey.TYPES: {name: _MetricType.*, ...},
|
||||
_StatsKey.DATA: {name: {labelvalues: value, ...}, ...},
|
||||
_StatsKey.INFO: [{labelname: labelvalue, ...}, ...] | None,
|
||||
}
|
||||
|
||||
This structure is self-describing: it survives IPC serialization
|
||||
@@ -187,6 +208,12 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
use the latest snapshot per-label-tuple, and histogram values are lists of
|
||||
observed samples per-label-tuple. Unlabeled metrics use ``()`` as their
|
||||
labelvalues tuple.
|
||||
|
||||
``INFO`` holds the static config facts of one series each, which the
|
||||
scheduler sends once per process. It stays out of ``DATA``, because its
|
||||
label names are known only when the payload arrives. It holds label names,
|
||||
not metric names, so a manager that accesses its own metrics walks
|
||||
``metric_sections()``.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
@@ -197,6 +224,7 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
self.data: dict[str, Any] = {
|
||||
_StatsKey.TYPES: {},
|
||||
_StatsKey.DATA: {},
|
||||
_StatsKey.INFO: None,
|
||||
}
|
||||
|
||||
@property
|
||||
@@ -207,10 +235,28 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
def _values(self) -> dict[str, Any]:
|
||||
return self.data[_StatsKey.DATA]
|
||||
|
||||
def metric_sections(self) -> tuple[dict[str, Any], ...]:
|
||||
"""Return the type section and the value section, in that order.
|
||||
|
||||
A manager that accesses its own metrics walks these sections. Each one
|
||||
is a mutable reference.
|
||||
"""
|
||||
return (self._types, self._values)
|
||||
|
||||
def aggregate(self, other: "KVConnectorStats") -> "KVConnectorStats":
|
||||
if other.is_empty():
|
||||
return self
|
||||
assert isinstance(other, OffloadingConnectorStats)
|
||||
# The scheduler payload merges into the worker payload
|
||||
# (v1/core/sched/scheduler.py), so the info must survive the merge in
|
||||
# this direction to reach the Prometheus frontend. reduce() drops it, so
|
||||
# it never reaches a log line. The scheduler sends it once, so a later
|
||||
# payload with no info must not clear it.
|
||||
other_info = other.data.get(_StatsKey.INFO)
|
||||
if other_info is not None:
|
||||
self.data[_StatsKey.INFO] = [
|
||||
dict(series_info) for series_info in other_info
|
||||
]
|
||||
other_types = other._types
|
||||
other_values = other._values
|
||||
for key, other_label_values in other_values.items():
|
||||
@@ -268,7 +314,11 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
return return_dict
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not self.data.get(_StatsKey.DATA)
|
||||
# An info-only payload is not empty. It carries no observation, but the
|
||||
# caller drops an empty payload, and the info must reach the frontend.
|
||||
return (
|
||||
not self.data.get(_StatsKey.DATA) and self.data.get(_StatsKey.INFO) is None
|
||||
)
|
||||
|
||||
def increase_counter(
|
||||
self,
|
||||
@@ -294,6 +344,18 @@ class OffloadingConnectorStats(KVConnectorStats):
|
||||
gauge_values = self._values.setdefault(gauge_name, {})
|
||||
gauge_values[labelvalues] = gauge_value
|
||||
|
||||
def set_info(self, info: Sequence[ConfigInfoMapping]) -> None:
|
||||
"""Put the static config facts of this engine on the stats payload.
|
||||
|
||||
Args:
|
||||
info: One mapping of info metric label name to label value for each
|
||||
series, as OffloadingManager.config_info() returns it. An empty
|
||||
mapping still gives one series, with an empty value on every
|
||||
label the spec declared.
|
||||
|
||||
"""
|
||||
self.data[_StatsKey.INFO] = [dict(series_info) for series_info in info]
|
||||
|
||||
def observe_histogram(
|
||||
self,
|
||||
histogram_name: str,
|
||||
@@ -322,14 +384,22 @@ class OffloadPromMetrics(KVConnectorPromMetrics):
|
||||
kv_transfer_config = vllm_config.kv_transfer_config
|
||||
assert kv_transfer_config is not None
|
||||
extra_config = kv_transfer_config.kv_connector_extra_config
|
||||
spec_cls = OffloadingSpecFactory.get_spec_cls(extra_config)
|
||||
self._spec_cls: type[OffloadingSpec] = OffloadingSpecFactory.get_spec_cls(
|
||||
extra_config
|
||||
)
|
||||
# The spec declares the info label names here; a manager fills the
|
||||
# values later, and _observe_info() aligns the two.
|
||||
self._info_keys: tuple[str, ...] = self._spec_cls.config_info_keys(extra_config)
|
||||
self._offloading_metric_metadata: dict[str, OffloadingMetricMetadata] = {
|
||||
**spec_cls.build_metric_definitions(extra_config),
|
||||
**self._spec_cls.build_metric_definitions(extra_config),
|
||||
**get_connector_metric_definitions(),
|
||||
KV_OFFLOAD_CONFIG_INFO: OffloadingGaugeMetadata(
|
||||
documentation=_INFO_METRIC_HELP, labelnames=self._info_keys
|
||||
),
|
||||
}
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
self._observe_deprecated_metrics = issubclass(spec_cls, CPUOffloadingSpec)
|
||||
self._observe_deprecated_metrics = issubclass(self._spec_cls, CPUOffloadingSpec)
|
||||
self._offloading_metric_defs: dict[str, PromMetricT] = {}
|
||||
# (engine_idx, metric_name, labelvalues) -> metric with bound labels
|
||||
self.offloading_metrics: dict[
|
||||
@@ -393,6 +463,7 @@ class OffloadPromMetrics(KVConnectorPromMetrics):
|
||||
metric_cls = self._counter_cls
|
||||
elif isinstance(metadata, OffloadingGaugeMetadata):
|
||||
metric_cls = self._gauge_cls
|
||||
kwargs["multiprocess_mode"] = metadata.multiprocess_mode
|
||||
elif isinstance(metadata, OffloadingHistogramMetadata):
|
||||
metric_cls = self._histogram_cls
|
||||
if metadata.buckets is not None:
|
||||
@@ -476,8 +547,52 @@ class OffloadPromMetrics(KVConnectorPromMetrics):
|
||||
observation
|
||||
)
|
||||
|
||||
def _observe_info(self, info: Sequence[dict[str, Any]], engine_idx: int) -> None:
|
||||
"""Publish the static config facts of one engine, one series per mapping.
|
||||
|
||||
The spec declares the label names, so a payload only fills them. A
|
||||
declared name that no series fills reads empty on every series. A payload
|
||||
name that the spec did not declare is dropped. Either gap logs once.
|
||||
|
||||
The check covers the payload as a whole, and not one series, because the
|
||||
declaration holds the names of every series. A name that one series owns
|
||||
reads empty on the other series by design. A series that leaves a name of
|
||||
its own unfilled therefore stays hidden here.
|
||||
|
||||
Args:
|
||||
info: One mapping of label name to label value for each series, as
|
||||
OffloadingManager.config_info() returns it.
|
||||
engine_idx: Index of the reporting engine.
|
||||
|
||||
"""
|
||||
filled: dict[str, None] = {}
|
||||
for series_info in info:
|
||||
filled.update(dict.fromkeys(series_info))
|
||||
labelvalues = tuple(
|
||||
str(series_info.get(key, "")) for key in self._info_keys
|
||||
)
|
||||
self._set_gauge(KV_OFFLOAD_CONFIG_INFO, 1, labelvalues, engine_idx)
|
||||
|
||||
never_filled = tuple(key for key in self._info_keys if key not in filled)
|
||||
dropped = tuple(key for key in filled if key not in self._info_keys)
|
||||
if never_filled or dropped:
|
||||
logger.warning_once(
|
||||
"%s: spec %s and the manager of engine %d disagree on the KV "
|
||||
"offload config labels. Declared, and no series filled them, so "
|
||||
"empty on every series: %s. Filled, and the spec did not "
|
||||
"declare them, so dropped: %s.",
|
||||
KV_OFFLOAD_CONFIG_INFO,
|
||||
self._spec_cls.__name__,
|
||||
engine_idx,
|
||||
never_filled,
|
||||
dropped,
|
||||
)
|
||||
|
||||
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
|
||||
"""Observe transfer statistics."""
|
||||
info = transfer_stats_data.get(_StatsKey.INFO)
|
||||
if info is not None:
|
||||
self._observe_info(info, engine_idx)
|
||||
metric_types = transfer_stats_data.get(_StatsKey.TYPES, {})
|
||||
metric_data = transfer_stats_data.get(_StatsKey.DATA, {})
|
||||
for key, label_value_map in metric_data.items():
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from collections.abc import Iterable, Iterator, Sequence
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import dataclass, field, replace
|
||||
from itertools import chain, islice
|
||||
from typing import Any, NamedTuple
|
||||
@@ -574,6 +575,10 @@ class OffloadingConnectorScheduler:
|
||||
)
|
||||
self.manager: OffloadingManager = spec.get_manager()
|
||||
self._connector_stats = OffloadingConnectorStats()
|
||||
# The static config facts ride on the first stats payload of this
|
||||
# process. A Prometheus child holds the values it received, so one
|
||||
# payload is enough.
|
||||
self._info_sent = False
|
||||
|
||||
full_attention_groups: list[int] = []
|
||||
sliding_window_groups: list[int] = []
|
||||
@@ -636,6 +641,71 @@ class OffloadingConnectorScheduler:
|
||||
|
||||
self._events_tracker = OffloadingEventsTracker(spec.kv_events_config)
|
||||
|
||||
# Holds the manager lock for the current schedule(), or None between steps.
|
||||
# Read and written only by the scheduler thread, so it needs no
|
||||
# synchronization of its own. Declared on the class so an instance built
|
||||
# without __init__ still reads None rather than raising.
|
||||
_step_region: ExitStack | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Manager exclusion
|
||||
#
|
||||
# The manager is entered from the scheduler thread and, for managers that
|
||||
# run one, from a tier-poll thread. Manager methods never take their
|
||||
# own lock, so the exclusion boundary lives here. manager.lock may be a
|
||||
# no-op for a manager that needs no exclusion; it is entered regardless.
|
||||
#
|
||||
# schedule() holds one region for the whole step: opened by the first
|
||||
# manager-touching hook and closed at the end of build_connector_meta.
|
||||
# That span is required, not tidiness -- get_num_new_matched_tokens
|
||||
# establishes lookup() HITs that update_state_after_alloc later pins with
|
||||
# prepare_load(), and prepare_store() evicts after both. Releasing between
|
||||
# them would let another thread evict a block the step already treated as
|
||||
# present.
|
||||
#
|
||||
# Hooks outside schedule() use a short region instead, so the manager is
|
||||
# free while the engine runs the model.
|
||||
#
|
||||
# The step region outlives any single call, so it cannot be a with-block;
|
||||
# an ExitStack carries the entered lock from open to close instead.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _acquire_step(self) -> None:
|
||||
"""Open the step-scoped region. Idempotent within a step."""
|
||||
if self._step_region is not None:
|
||||
return
|
||||
region = ExitStack()
|
||||
region.enter_context(self.manager.lock)
|
||||
self._step_region = region
|
||||
|
||||
def _release_step(self) -> None:
|
||||
"""Close the step-scoped region, letting other threads in."""
|
||||
region = self._step_region
|
||||
if region is None:
|
||||
return
|
||||
self._step_region = None
|
||||
region.close()
|
||||
|
||||
@contextmanager
|
||||
def _manager_locked(self) -> Iterator[None]:
|
||||
"""Hold the manager for the duration of one hook outside schedule().
|
||||
|
||||
None of these hooks can legitimately run inside the step-scoped region:
|
||||
on_new_request comes from add_request, has_pending_push_work from the
|
||||
engine's liveness check before schedule(), the rest from output
|
||||
processing or a client RPC. So finding the region open here means a
|
||||
previous schedule() raised between _acquire_step() and the release in
|
||||
build_connector_meta. Recover instead of deadlocking.
|
||||
"""
|
||||
if self._step_region is not None:
|
||||
logger.error(
|
||||
"Offloading manager lock was left held by a previous "
|
||||
"schedule(); releasing it before continuing."
|
||||
)
|
||||
self._release_step()
|
||||
with self.manager.lock:
|
||||
yield
|
||||
|
||||
def _maybe_observe_lookup_async_delay(
|
||||
self, req_status: RequestOffloadState
|
||||
) -> None:
|
||||
@@ -1027,7 +1097,8 @@ class OffloadingConnectorScheduler:
|
||||
def on_new_request(self, request: Request) -> None:
|
||||
"""Called when a new request is added to the scheduler."""
|
||||
req_context = _create_req_context(request)
|
||||
offloading_context = self.manager.on_new_request(req_context)
|
||||
with self._manager_locked():
|
||||
offloading_context = self.manager.on_new_request(req_context)
|
||||
req_status = RequestOffloadState(
|
||||
config=self.config,
|
||||
req=request,
|
||||
@@ -1063,6 +1134,10 @@ class OffloadingConnectorScheduler:
|
||||
(between scheduler steps).
|
||||
|
||||
"""
|
||||
# First manager-touching hook of a step: opens the step-scoped region,
|
||||
# closed at the end of build_connector_meta.
|
||||
self._acquire_step()
|
||||
|
||||
req_status = self._req_status[request.request_id]
|
||||
for group_state in req_status.group_states:
|
||||
group_state.block_ids.clear()
|
||||
@@ -1146,9 +1221,21 @@ class OffloadingConnectorScheduler:
|
||||
def update_state_after_alloc(
|
||||
self, request: Request, blocks: KVCacheBlocks, num_external_tokens: int
|
||||
):
|
||||
# Track allocated block IDs regardless of num_external_tokens so
|
||||
# re-allocation flush detection sees blocks allocated by other
|
||||
# connectors in a MultiConnector setup.
|
||||
for group_blocks in blocks.blocks:
|
||||
self._current_batch_allocated_block_ids.update(
|
||||
block.block_id for block in group_blocks if block.block_id != 0
|
||||
)
|
||||
|
||||
if num_external_tokens == 0:
|
||||
return
|
||||
|
||||
# prepare_load() below pins keys that get_num_new_matched_tokens()
|
||||
# already saw as HIT, so both must sit inside the same region.
|
||||
self._acquire_step()
|
||||
|
||||
req_status = self._req_status[request.request_id]
|
||||
|
||||
num_locally_computed_tokens = req_status.num_locally_computed_tokens
|
||||
@@ -1168,10 +1255,6 @@ class OffloadingConnectorScheduler:
|
||||
req_status.group_states,
|
||||
):
|
||||
group_blocks = blocks.blocks[group_config.group_idx]
|
||||
self._current_batch_allocated_block_ids.update(
|
||||
block.block_id for block in group_blocks if block.block_id != 0
|
||||
)
|
||||
|
||||
tokens_per_block = group_config.tokens_per_block
|
||||
tokens_per_chunk = group_config.tokens_per_chunk
|
||||
offload_keys = group_state.offload_keys
|
||||
@@ -1845,13 +1928,24 @@ class OffloadingConnectorScheduler:
|
||||
|
||||
def build_connector_meta(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> KVConnectorMetadata:
|
||||
# A step that scheduled nothing reaches build_connector_meta without
|
||||
# any earlier manager touch, so open the region here too.
|
||||
self._acquire_step()
|
||||
try:
|
||||
return self._build_connector_meta(scheduler_output)
|
||||
finally:
|
||||
# The step is over: hand the manager back.
|
||||
self._release_step()
|
||||
|
||||
def _build_connector_meta(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> KVConnectorMetadata:
|
||||
self._update_req_states(scheduler_output)
|
||||
schedule_end_context = ScheduleEndContext(
|
||||
new_req_ids=[req.req_id for req in scheduler_output.scheduled_new_reqs],
|
||||
preempted_req_ids=scheduler_output.preempted_req_ids or (),
|
||||
)
|
||||
self.manager.on_schedule_end(schedule_end_context)
|
||||
|
||||
# Flush jobs for preempted requests.
|
||||
for req_id in scheduler_output.preempted_req_ids or ():
|
||||
@@ -1897,6 +1991,12 @@ class OffloadingConnectorScheduler:
|
||||
self._current_batch_load_jobs = {}
|
||||
self._current_batch_jobs_to_flush = set()
|
||||
self._current_batch_allocated_block_ids = set()
|
||||
|
||||
# Last manager call of the step, after every prepare_store and
|
||||
# on_request_finished above. on_schedule_end is documented as running at
|
||||
# the end of the step, and callers rely on that to bound the step's
|
||||
# exclusive access to the manager.
|
||||
self.manager.on_schedule_end(schedule_end_context)
|
||||
return meta
|
||||
|
||||
def has_pending_push_work(self) -> bool:
|
||||
@@ -1904,8 +2004,17 @@ class OffloadingConnectorScheduler:
|
||||
|
||||
While True, build_connector_meta() and update_connector_output()
|
||||
continue to be called even when no requests are scheduled.
|
||||
|
||||
Must use a short region, never the step-scoped one. The engine asks this
|
||||
before schedule() and returns early when the answer is False, so a
|
||||
step-scoped acquire here would never reach build_connector_meta's
|
||||
release and would hold the manager for good -- which is precisely the
|
||||
state an idle engine settles into.
|
||||
"""
|
||||
return bool(self._jobs) or self.manager.has_pending_work()
|
||||
if self._jobs:
|
||||
return True
|
||||
with self._manager_locked():
|
||||
return self.manager.has_pending_work()
|
||||
|
||||
def update_connector_output(self, connector_output: KVConnectorOutput):
|
||||
"""Update KVConnector state from worker-side connectors output.
|
||||
@@ -1915,6 +2024,10 @@ class OffloadingConnectorScheduler:
|
||||
connectors output.
|
||||
|
||||
"""
|
||||
with self._manager_locked():
|
||||
self._update_connector_output(connector_output)
|
||||
|
||||
def _update_connector_output(self, connector_output: KVConnectorOutput):
|
||||
meta = connector_output.kv_connector_worker_meta
|
||||
if not isinstance(meta, OffloadingWorkerMetadata):
|
||||
assert meta is None
|
||||
@@ -1993,13 +2106,22 @@ class OffloadingConnectorScheduler:
|
||||
stats = self._connector_stats
|
||||
self._connector_stats = OffloadingConnectorStats()
|
||||
|
||||
manager_stats = self.manager.get_stats()
|
||||
with self._manager_locked():
|
||||
manager_stats = self.manager.get_stats()
|
||||
if manager_stats is not None:
|
||||
if stats is None:
|
||||
stats = manager_stats
|
||||
else:
|
||||
stats.aggregate(manager_stats)
|
||||
|
||||
if not self._info_sent:
|
||||
if stats is None:
|
||||
stats = OffloadingConnectorStats()
|
||||
# Sent even when the manager reports no facts, so that the metric
|
||||
# exists whenever offloading runs.
|
||||
stats.set_info(self.manager.config_info())
|
||||
self._info_sent = True
|
||||
|
||||
return stats
|
||||
|
||||
def request_finished(
|
||||
@@ -2022,8 +2144,9 @@ class OffloadingConnectorScheduler:
|
||||
# Untracked request (offloading never started): no in-flight jobs,
|
||||
# nothing was deferred, so finalize immediately.
|
||||
req_context = _create_req_context(request)
|
||||
self.manager.on_new_request(req_context)
|
||||
self.manager.on_request_finished(req_context)
|
||||
with self._manager_locked():
|
||||
self.manager.on_new_request(req_context)
|
||||
self.manager.on_request_finished(req_context)
|
||||
return False, None
|
||||
|
||||
self._maybe_observe_lookup_async_delay(req_status)
|
||||
@@ -2055,7 +2178,16 @@ class OffloadingConnectorScheduler:
|
||||
the underlying :class:`OffloadingEvent` stream.
|
||||
|
||||
"""
|
||||
yield from self._events_tracker.take_events(self.manager.take_events())
|
||||
# Drain the manager eagerly, inside the region. manager.take_events() is
|
||||
# itself a generator whose backing list is cleared once exhausted, so
|
||||
# iterating it lazily would both hold the manager for as long as the
|
||||
# consumer takes and let a concurrent writer append events that the
|
||||
# clear then discards unpublished.
|
||||
with self._manager_locked():
|
||||
manager_events = list(self.manager.take_events())
|
||||
# Still a generator, so callers testing the result for truthiness keep
|
||||
# seeing a non-empty object the way they do today.
|
||||
yield from self._events_tracker.take_events(manager_events)
|
||||
|
||||
def reset_cache(self) -> None:
|
||||
"""Reset the offloading manager cache, evicting all stored chunks."""
|
||||
@@ -2064,6 +2196,13 @@ class OffloadingConnectorScheduler:
|
||||
assert not self._current_batch_jobs_to_flush
|
||||
assert not self._current_batch_allocated_block_ids
|
||||
|
||||
# Held for the whole reset. manager.reset_cache() drains tiers by
|
||||
# polling them itself, so a tier-poll thread locked out here loses
|
||||
# nothing; it simply skips rounds until the reset completes.
|
||||
with self._manager_locked():
|
||||
self._reset_cache()
|
||||
|
||||
def _reset_cache(self) -> None:
|
||||
# Flush all in-flight jobs
|
||||
self._current_batch_jobs_to_flush.update(self._jobs.keys())
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import functools
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
@@ -91,6 +92,24 @@ def is_nixl_available() -> bool:
|
||||
return pkg in sys.modules or importlib.util.find_spec(pkg) is not None
|
||||
|
||||
|
||||
@functools.cache
|
||||
def check_nixl_version(min_version: str) -> None:
|
||||
"""Raise if the installed NIXL package is older than ``min_version``."""
|
||||
from importlib.metadata import packages_distributions, version
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
pkg = _get_nixl_package_name()
|
||||
for dist in packages_distributions().get(pkg, ()):
|
||||
installed = version(dist)
|
||||
if Version(installed) < Version(min_version):
|
||||
raise RuntimeError(
|
||||
f"NIXL >= {min_version} is required, but {dist}=={installed} "
|
||||
"is installed"
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
def alias_nixl_for_ray() -> None:
|
||||
"""Let Ray's ``nixl._api`` import resolve to the ROCm implementation."""
|
||||
if not current_platform.is_rocm() or "nixl._api" in sys.modules:
|
||||
@@ -112,5 +131,6 @@ __all__ = [
|
||||
"nixl_agent_config",
|
||||
"nixlXferTelemetry",
|
||||
"is_nixl_available",
|
||||
"check_nixl_version",
|
||||
"alias_nixl_for_ray",
|
||||
]
|
||||
|
||||
@@ -2444,6 +2444,11 @@ def get_tensor_model_parallel_rank() -> int:
|
||||
return get_tp_group().rank_in_group
|
||||
|
||||
|
||||
def get_pipeline_model_parallel_rank() -> int:
|
||||
"""Return my rank for the pipeline model parallel group."""
|
||||
return get_pp_group().rank_in_group
|
||||
|
||||
|
||||
def get_node_count() -> int:
|
||||
"""Return the total number of nodes in the distributed environment."""
|
||||
assert _NODE_COUNT is not None, "distributed environment is not initialized"
|
||||
|
||||
@@ -514,9 +514,7 @@ class WeightTransferEngine(ABC, Generic[TInitInfo, TUpdateInfo]):
|
||||
|
||||
@abstractmethod
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the weight transfer engine.
|
||||
This should be called when the worker is shutting down.
|
||||
"""
|
||||
"""Release transfer resources without shutting down the inference worker."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ class HTTPVLLMWeightSyncClient:
|
||||
|
||||
Mirrors `vllm/entrypoints/rl/online/api_router.py`:
|
||||
`/init_weight_transfer_engine`, `/start_weight_update`, `/update_weights`,
|
||||
`/finish_weight_update`.
|
||||
`/finish_weight_update`, `/shutdown_weight_transfer_engine`.
|
||||
"""
|
||||
|
||||
def __init__(self, base_url: str, timeout: float = 300) -> None:
|
||||
@@ -78,6 +78,9 @@ class HTTPVLLMWeightSyncClient:
|
||||
def init_weight_transfer_engine(self, init_info: dict[str, Any]) -> None:
|
||||
self._post("init_weight_transfer_engine", {"init_info": init_info})
|
||||
|
||||
def shutdown_weight_transfer_engine(self) -> None:
|
||||
self._post("shutdown_weight_transfer_engine")
|
||||
|
||||
def start_weight_update(self) -> None:
|
||||
self._post("start_weight_update")
|
||||
|
||||
@@ -109,6 +112,11 @@ class RayVLLMWeightSyncClient:
|
||||
request = WeightTransferInitRequest(init_info=init_info)
|
||||
ray.get([h.init_weight_transfer_engine.remote(request) for h in self.handles])
|
||||
|
||||
def shutdown_weight_transfer_engine(self) -> None:
|
||||
import ray
|
||||
|
||||
ray.get([h.shutdown_weight_transfer_engine.remote() for h in self.handles])
|
||||
|
||||
def start_weight_update(self) -> None:
|
||||
import ray
|
||||
|
||||
|
||||
@@ -449,5 +449,7 @@ class M2NWeightTransferEngine(
|
||||
torch.accelerator.synchronize()
|
||||
self._handle.destroy()
|
||||
self._handle = None
|
||||
self.model_update_group = None
|
||||
if self.model_update_group is not None:
|
||||
self.model_update_group.destroy()
|
||||
self.model_update_group = None
|
||||
self._parameter_destinations = []
|
||||
|
||||
@@ -410,4 +410,6 @@ class M2NTrainerWeightTransferEngine(TrainerWeightTransferEngine[M2NTrainerInitI
|
||||
if self._executor is not None:
|
||||
self._executor.shutdown()
|
||||
self._executor = None
|
||||
self.group = None
|
||||
if self.group is not None:
|
||||
self.group.destroy()
|
||||
self.group = None
|
||||
|
||||
@@ -229,7 +229,7 @@ class NCCLWeightTransferEngine(
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self.model_update_group is not None:
|
||||
# Clean up the communicator by removing the reference
|
||||
self.model_update_group.destroy()
|
||||
self.model_update_group = None
|
||||
|
||||
|
||||
@@ -456,4 +456,6 @@ class NCCLTrainerWeightTransferEngine(TrainerWeightTransferEngine[NCCLTrainerIni
|
||||
torch.cuda.current_stream().synchronize()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.model_update_group = None
|
||||
if self.model_update_group is not None:
|
||||
self.model_update_group.destroy()
|
||||
self.model_update_group = None
|
||||
|
||||
@@ -50,7 +50,7 @@ def unpack_tensor(
|
||||
unpacked_tensors = packed_tensor.split(tensor_sizes)
|
||||
|
||||
return [
|
||||
(name, tensor.contiguous().view(dtype).view(*shape))
|
||||
(name, tensor.contiguous().view(dtype).view(shape))
|
||||
for name, shape, dtype, tensor in zip(names, shapes, dtypes, unpacked_tensors)
|
||||
]
|
||||
|
||||
@@ -105,7 +105,7 @@ def pack_tensors(
|
||||
|
||||
name, orig_tensor = item
|
||||
# Apply post processing and convert to linearized uint8 tensor
|
||||
tensor = post_iter_func(item).contiguous().view(torch.uint8).view(-1)
|
||||
tensor = post_iter_func(item).contiguous().view(-1).view(torch.uint8)
|
||||
|
||||
if tensor.numel() > buffer_size_bytes:
|
||||
import warnings
|
||||
@@ -350,7 +350,7 @@ def packed_ipc_producer(
|
||||
|
||||
for name, orig_tensor in iterator:
|
||||
flat = (
|
||||
post_iter_func((name, orig_tensor)).contiguous().view(torch.uint8).view(-1)
|
||||
post_iter_func((name, orig_tensor)).contiguous().view(-1).view(torch.uint8)
|
||||
)
|
||||
|
||||
if flat.numel() > buffer_size_bytes:
|
||||
|
||||
@@ -316,9 +316,8 @@ class ShardedRDTWeightTransferEngine(
|
||||
raise ValueError(
|
||||
f"The 'sharded_rdt' weight transfer backend requires "
|
||||
f"distributed_executor_backend='ray', got {backend!r}. Pass "
|
||||
f"--distributed-executor-backend ray (and keep "
|
||||
f"VLLM_USE_RAY_V2_EXECUTOR_BACKEND=1, the default, so the "
|
||||
f"workers are RayExecutorV2 actors with tensor transport)."
|
||||
f"--distributed-executor-backend ray so the workers are "
|
||||
f"RayExecutorV2 actors with tensor transport."
|
||||
)
|
||||
# Ownership table, routing rules, and (once bound) every producer's
|
||||
# handle — pulls go to one owner per chunk, but free_group fans out to
|
||||
|
||||
@@ -186,6 +186,7 @@ class SparseNCCLWeightTransferEngine(
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self.model_update_group is not None:
|
||||
self.model_update_group.destroy()
|
||||
self.model_update_group = None
|
||||
|
||||
|
||||
@@ -371,4 +372,6 @@ class SparseNCCLTrainerWeightTransferEngine(
|
||||
torch.cuda.current_stream().synchronize()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.model_update_group = None
|
||||
if self.model_update_group is not None:
|
||||
self.model_update_group.destroy()
|
||||
self.model_update_group = None
|
||||
|
||||
@@ -184,6 +184,11 @@ def union_dict_and_str(val: str) -> str | dict[str, str] | None:
|
||||
return optional_type(json.loads)(val)
|
||||
|
||||
|
||||
def parse_reasoning_parser(val: str) -> str:
|
||||
"""Map `none` (any case) to the unset default, as `vllm-rs serve` does."""
|
||||
return "" if val.lower() == "none" else val
|
||||
|
||||
|
||||
def is_type(type_hint: TypeHint, type: TypeHintT) -> TypeIs[TypeHintT]:
|
||||
"""Check if the type hint is a specific type."""
|
||||
return type_hint is type or get_origin(type_hint) is type
|
||||
@@ -453,6 +458,18 @@ _LOG_CONFIG_FILE_DEPRECATION_MESSAGE = (
|
||||
)
|
||||
|
||||
|
||||
_MAMBA_CACHE_MODE_DEPRECATION_MESSAGE = (
|
||||
"--mamba-cache-mode is deprecated and will be removed in v0.33.0. "
|
||||
"It has no effect: Mamba prefix caching follows --enable-prefix-caching."
|
||||
)
|
||||
|
||||
|
||||
_DISABLE_CASCADE_ATTN_DEPRECATION_MESSAGE = (
|
||||
"--disable-cascade-attn is deprecated and has no effect since cascade "
|
||||
"attention has been removed. It will be removed in v0.33.0."
|
||||
)
|
||||
|
||||
|
||||
class DeprecatedLogConfigFileAction(argparse.Action):
|
||||
"""Warn when the legacy ``--log-config-file`` option is used."""
|
||||
|
||||
@@ -538,6 +555,7 @@ class EngineArgs:
|
||||
data_parallel_external_lb: bool = False
|
||||
data_parallel_multi_port_external_lb: bool = False
|
||||
data_parallel_backend: DataParallelBackend = ParallelConfig.data_parallel_backend
|
||||
enable_hc_sp: bool = ParallelConfig.enable_hc_sp
|
||||
enable_expert_parallel: bool = ParallelConfig.enable_expert_parallel
|
||||
enable_batch_sharded_sampling: bool | None = (
|
||||
ParallelConfig.enable_batch_sharded_sampling
|
||||
@@ -578,7 +596,7 @@ class EngineArgs:
|
||||
CacheConfig, "prefix_cache_retention_interval"
|
||||
)
|
||||
disable_sliding_window: bool = ModelConfig.disable_sliding_window
|
||||
disable_cascade_attn: bool = ModelConfig.disable_cascade_attn
|
||||
disable_cascade_attn: bool | None = None
|
||||
offload_backend: str = OffloadConfig.offload_backend
|
||||
cpu_offload_gb: float = UVAOffloadConfig.cpu_offload_gb
|
||||
cpu_offload_params: set[str] = get_field(UVAOffloadConfig, "cpu_offload_params")
|
||||
@@ -622,6 +640,7 @@ class EngineArgs:
|
||||
allow_deprecated_quantization: bool = ModelConfig.allow_deprecated_quantization
|
||||
enforce_eager: bool = ModelConfig.enforce_eager
|
||||
disable_custom_all_reduce: bool = ParallelConfig.disable_custom_all_reduce
|
||||
enable_shm_tensor_arena: bool = ParallelConfig.enable_shm_tensor_arena
|
||||
language_model_only: bool = MultiModalConfig.language_model_only
|
||||
limit_mm_per_prompt: dict[str, int | dict[str, int]] = get_field(
|
||||
MultiModalConfig, "limit_per_prompt"
|
||||
@@ -750,6 +769,7 @@ class EngineArgs:
|
||||
enable_flashinfer_autotune: bool = get_field(
|
||||
KernelConfig, "enable_flashinfer_autotune"
|
||||
)
|
||||
monokernel: bool = get_field(KernelConfig, "monokernel")
|
||||
worker_cls: str = ParallelConfig.worker_cls
|
||||
worker_extension_cls: str = ParallelConfig.worker_extension_cls
|
||||
|
||||
@@ -789,7 +809,7 @@ class EngineArgs:
|
||||
mamba_ssm_cache_dtype: MambaDType = CacheConfig.mamba_ssm_cache_dtype
|
||||
mamba_block_size: int | None = get_field(CacheConfig, "mamba_block_size")
|
||||
prefix_match_unit: int | None = get_field(CacheConfig, "prefix_match_unit")
|
||||
mamba_cache_mode: MambaCacheMode = CacheConfig.mamba_cache_mode
|
||||
mamba_cache_mode: MambaCacheMode | None = None
|
||||
enable_mamba_shared_prefix_checkpoint: bool = (
|
||||
CacheConfig.enable_mamba_shared_prefix_checkpoint
|
||||
)
|
||||
@@ -983,7 +1003,10 @@ class EngineArgs:
|
||||
"--disable-sliding-window", **model_kwargs["disable_sliding_window"]
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--disable-cascade-attn", **model_kwargs["disable_cascade_attn"]
|
||||
"--disable-cascade-attn",
|
||||
action=argparse.BooleanOptionalAction,
|
||||
default=None,
|
||||
help=_DISABLE_CASCADE_ATTN_DEPRECATION_MESSAGE,
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--skip-tokenizer-init", **model_kwargs["skip_tokenizer_init"]
|
||||
@@ -1096,6 +1119,10 @@ class EngineArgs:
|
||||
|
||||
# Structured outputs arguments
|
||||
structured_outputs_kwargs = get_kwargs(StructuredOutputsConfig)
|
||||
structured_outputs_kwargs["reasoning_parser"]["type"] = parse_reasoning_parser
|
||||
structured_outputs_kwargs["reasoning_parser"]["help"] += (
|
||||
"\n\n`none` disables reasoning parsing, the same as leaving it unset."
|
||||
)
|
||||
structured_outputs_group = parser.add_argument_group(
|
||||
title="StructuredOutputsConfig",
|
||||
description=StructuredOutputsConfig.__doc__,
|
||||
@@ -1257,6 +1284,7 @@ class EngineArgs:
|
||||
"server per local data parallel rank and exposes aggregated health on "
|
||||
"a supervisor port.",
|
||||
)
|
||||
parallel_group.add_argument("--enable-hc-sp", **parallel_kwargs["enable_hc_sp"])
|
||||
parallel_group.add_argument(
|
||||
"--enable-expert-parallel",
|
||||
"-ep",
|
||||
@@ -1274,6 +1302,10 @@ class EngineArgs:
|
||||
"--all2all-backend", **parallel_kwargs["all2all_backend"]
|
||||
)
|
||||
parallel_group.add_argument("--enable-dbo", **parallel_kwargs["enable_dbo"])
|
||||
parallel_group.add_argument(
|
||||
"--enable-shm-tensor-arena",
|
||||
**parallel_kwargs["enable_shm_tensor_arena"],
|
||||
)
|
||||
parallel_group.add_argument(
|
||||
"--ubatch-size",
|
||||
**parallel_kwargs["ubatch_size"],
|
||||
@@ -1386,7 +1418,12 @@ class EngineArgs:
|
||||
"--prefix-match-unit", **cache_kwargs["prefix_match_unit"]
|
||||
)
|
||||
cache_group.add_argument(
|
||||
"--mamba-cache-mode", **cache_kwargs["mamba_cache_mode"]
|
||||
"--mamba-cache-mode",
|
||||
**{
|
||||
**cache_kwargs["mamba_cache_mode"],
|
||||
"default": None,
|
||||
"help": _MAMBA_CACHE_MODE_DEPRECATION_MESSAGE,
|
||||
},
|
||||
)
|
||||
cache_group.add_argument(
|
||||
"--enable-mamba-shared-prefix-checkpoint",
|
||||
@@ -1786,6 +1823,7 @@ class EngineArgs:
|
||||
"--enable-flashinfer-autotune",
|
||||
**kernel_kwargs["enable_flashinfer_autotune"],
|
||||
)
|
||||
kernel_group.add_argument("--monokernel", **kernel_kwargs["monokernel"])
|
||||
moe_backend_kwargs = kernel_kwargs["moe_backend"]
|
||||
moe_backend_kwargs["type"] = lambda s: s.lower().replace("-", "_")
|
||||
kernel_group.add_argument("--moe-backend", **moe_backend_kwargs)
|
||||
@@ -1933,6 +1971,8 @@ class EngineArgs:
|
||||
"launched vLLM.",
|
||||
self.seed,
|
||||
)
|
||||
if self.disable_cascade_attn is not None:
|
||||
warnings.warn(_DISABLE_CASCADE_ATTN_DEPRECATION_MESSAGE, stacklevel=1)
|
||||
|
||||
return ModelConfig(
|
||||
model=self.model,
|
||||
@@ -1964,7 +2004,6 @@ class EngineArgs:
|
||||
use_fp64_gumbel=self.use_fp64_gumbel,
|
||||
enable_trace_replay=self.enable_trace_replay,
|
||||
disable_sliding_window=self.disable_sliding_window,
|
||||
disable_cascade_attn=self.disable_cascade_attn,
|
||||
skip_tokenizer_init=self.skip_tokenizer_init,
|
||||
enable_prompt_embeds=self.enable_prompt_embeds,
|
||||
served_model_name=self.served_model_name,
|
||||
@@ -2244,6 +2283,8 @@ class EngineArgs:
|
||||
assert self.enable_prefix_caching is not None, (
|
||||
"enable_prefix_caching must be set by this point"
|
||||
)
|
||||
if self.mamba_cache_mode is not None:
|
||||
logger.warning_once(_MAMBA_CACHE_MODE_DEPRECATION_MESSAGE)
|
||||
|
||||
cache_config = CacheConfig(
|
||||
block_size=self.block_size, # type: ignore[arg-type]
|
||||
@@ -2263,7 +2304,6 @@ class EngineArgs:
|
||||
mamba_ssm_cache_dtype=self.mamba_ssm_cache_dtype,
|
||||
mamba_block_size=self.mamba_block_size,
|
||||
prefix_match_unit=self.prefix_match_unit,
|
||||
mamba_cache_mode=self.mamba_cache_mode,
|
||||
enable_mamba_shared_prefix_checkpoint=(
|
||||
self.enable_mamba_shared_prefix_checkpoint
|
||||
),
|
||||
@@ -2527,6 +2567,7 @@ class EngineArgs:
|
||||
data_parallel_backend=self.data_parallel_backend,
|
||||
data_parallel_hybrid_lb=self.data_parallel_hybrid_lb,
|
||||
is_moe_model=model_config.is_moe,
|
||||
enable_hc_sp=self.enable_hc_sp,
|
||||
enable_expert_parallel=self.enable_expert_parallel,
|
||||
enable_batch_sharded_sampling=self.enable_batch_sharded_sampling,
|
||||
enable_ep_weight_filter=self.enable_ep_weight_filter,
|
||||
@@ -2534,6 +2575,7 @@ class EngineArgs:
|
||||
enable_elastic_ep=self.enable_elastic_ep,
|
||||
elastic_ep_max_dp_size=self.elastic_ep_max_dp_size,
|
||||
enable_dbo=self.enable_dbo,
|
||||
enable_shm_tensor_arena=self.enable_shm_tensor_arena,
|
||||
ubatch_size=self.ubatch_size,
|
||||
dbo_decode_token_threshold=self.dbo_decode_token_threshold,
|
||||
dp_sync_interval=self.dp_sync_interval,
|
||||
@@ -2735,6 +2777,8 @@ class EngineArgs:
|
||||
"are mutually exclusive"
|
||||
)
|
||||
kernel_config.enable_flashinfer_autotune = self.enable_flashinfer_autotune
|
||||
if self.monokernel:
|
||||
kernel_config.monokernel = True
|
||||
if self.moe_backend != "auto":
|
||||
kernel_config.moe_backend = self.moe_backend
|
||||
if self.linear_backend != "auto":
|
||||
@@ -2893,10 +2937,14 @@ class EngineArgs:
|
||||
try:
|
||||
device_memory = current_platform.get_device_total_memory()
|
||||
device_name = current_platform.get_device_name().lower()
|
||||
# GB10 (DGX Spark, cc 12.1) has the memory but not the compute of
|
||||
# a large discrete GPU, keep it on the small tier.
|
||||
is_gb10 = current_platform.is_device_capability((12, 1))
|
||||
except Exception:
|
||||
# This is only used to set default_max_num_batched_tokens
|
||||
device_memory = 0
|
||||
device_name = ""
|
||||
is_gb10 = False
|
||||
|
||||
# NOTE(Kuntai): Setting large `max_num_batched_tokens` for A100 reduces
|
||||
# throughput, see PR #17885 for more details.
|
||||
@@ -2911,7 +2959,11 @@ class EngineArgs:
|
||||
UsageContext.LLM_CLASS: 1024,
|
||||
UsageContext.OPENAI_API_SERVER: 1024,
|
||||
}
|
||||
elif device_memory >= 70 * GiB_bytes and "a100" not in device_name:
|
||||
elif (
|
||||
device_memory >= 70 * GiB_bytes
|
||||
and "a100" not in device_name
|
||||
and not is_gb10
|
||||
):
|
||||
# For GPUs like H100 and H200, use larger offline defaults.
|
||||
default_max_num_batched_tokens = {
|
||||
UsageContext.LLM_CLASS: 16384,
|
||||
@@ -3190,7 +3242,9 @@ class AsyncEngineArgs(EngineArgs):
|
||||
help="Enable logging request information, dependent on log level:\n"
|
||||
"- INFO: Request ID, parameters and LoRA request.\n"
|
||||
"- DEBUG: Prompt inputs (e.g: text, token IDs).\n"
|
||||
"You can set the minimum log level via `VLLM_LOGGING_LEVEL`.",
|
||||
"You can set the minimum log level via `VLLM_LOGGING_LEVEL`.\n"
|
||||
"You can also set a separate log level for request JSON body "
|
||||
"via `VLLM_REQUEST_BODY_LOG_LEVEL` (default: DEBUG).",
|
||||
)
|
||||
current_platform.pre_register_and_update(parser)
|
||||
return parser
|
||||
|
||||
@@ -224,7 +224,6 @@ class EngineClient(ABC):
|
||||
self,
|
||||
*,
|
||||
mode: "PauseMode" = "abort",
|
||||
wait_for_inflight_requests: bool = False,
|
||||
clear_cache: bool = True,
|
||||
) -> None:
|
||||
"""Pause new generation/encoding requests.
|
||||
@@ -236,7 +235,6 @@ class EngineClient(ABC):
|
||||
- ``"wait"``: Wait for in-flight requests to complete.
|
||||
- ``"keep"``: Freeze requests in queue; they resume on
|
||||
:meth:`resume_generation`.
|
||||
wait_for_inflight_requests: DEPRECATED. Use ``mode="wait"`` instead.
|
||||
clear_cache: DEPRECATED. Whether to clear KV and prefix caches
|
||||
after draining.
|
||||
|
||||
@@ -298,6 +296,10 @@ class EngineClient(ABC):
|
||||
"""Initialize weight transfer for RL training."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def shutdown_weight_transfer_engine(self) -> None:
|
||||
"""Release the trainer connection without shutting down inference."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def start_weight_update(self) -> None:
|
||||
"""Start a new weight update."""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -8,6 +8,10 @@ from typing import Annotated, Any, Literal
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.entrypoints.generate.base.protocol import (
|
||||
MMPayload,
|
||||
resolve_return_mm_kwargs_alias,
|
||||
)
|
||||
|
||||
|
||||
class AnthropicError(BaseModel):
|
||||
@@ -229,15 +233,25 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
top_p: float | None = None
|
||||
|
||||
# vLLM-specific fields that are not in Anthropic spec
|
||||
return_mm_kwargs: bool = Field(
|
||||
default=True,
|
||||
mm_payload: MMPayload = Field(
|
||||
default="tensors",
|
||||
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."
|
||||
"What the render response's `features` carry for multimodal "
|
||||
"items. 'tensors' serializes the processed tensors into "
|
||||
"`kwargs_data` and `mm_metadata`. 'none' sets both to null for "
|
||||
"callers that need only the token layout and item hashes, such as "
|
||||
"cache-aware routers. Do not send a 'none' 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."
|
||||
),
|
||||
)
|
||||
return_mm_kwargs: bool | None = Field(
|
||||
default=None,
|
||||
deprecated="return_mm_kwargs is deprecated in favor of the mm_payload field",
|
||||
description=(
|
||||
"Deprecated alias: false is the same as `mm_payload='none'`. "
|
||||
"Ignored when `mm_payload` is set."
|
||||
),
|
||||
)
|
||||
cache_salt: str | None = Field(
|
||||
@@ -304,6 +318,11 @@ class AnthropicMessagesRequest(BaseModel):
|
||||
_reject_tool_changes(v)
|
||||
return v
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def apply_return_mm_kwargs_alias(cls, data: Any) -> Any:
|
||||
return resolve_return_mm_kwargs_alias(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_thinking_budget(self) -> "AnthropicMessagesRequest":
|
||||
# P/D prefill legs are sent with max_tokens=1 and never decode; the
|
||||
|
||||
@@ -35,7 +35,6 @@ from vllm.entrypoints.anthropic.protocol import (
|
||||
AnthropicToolChangeDefinition,
|
||||
AnthropicUsage,
|
||||
)
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.entrypoints.generate.base.protocol import (
|
||||
JsonSchemaResponseFormat,
|
||||
ResponseFormat,
|
||||
@@ -54,6 +53,7 @@ from vllm.entrypoints.serve.engine.protocol import ErrorResponse, UsageInfo
|
||||
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.logger import init_logger
|
||||
from vllm.renderers.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.renderers.hf import HfRenderer, resolve_chat_template
|
||||
from vllm.renderers.online_renderer import OnlineRenderer
|
||||
|
||||
@@ -160,9 +160,11 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
reasoning_parser: str = "",
|
||||
enable_auto_tools: bool = False,
|
||||
tool_parser: str | None = None,
|
||||
tool_strict_level: str = "auto",
|
||||
tool_strict_level: str | None = None,
|
||||
enable_prompt_tokens_details: bool = False,
|
||||
enable_force_include_usage: bool = False,
|
||||
enable_log_outputs: bool = False,
|
||||
enable_log_deltas: bool = True,
|
||||
default_chat_template_kwargs: dict[str, Any] | None = None,
|
||||
disabled_thinking_effort: AnthropicDisabledThinkingEffortOption = "auto",
|
||||
):
|
||||
@@ -181,6 +183,8 @@ class AnthropicServingMessages(OpenAIServingChat):
|
||||
tool_parser=tool_parser,
|
||||
enable_prompt_tokens_details=enable_prompt_tokens_details,
|
||||
enable_force_include_usage=enable_force_include_usage,
|
||||
enable_log_outputs=enable_log_outputs,
|
||||
enable_log_deltas=enable_log_deltas,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
)
|
||||
self._merge_inline_system = self._should_merge_inline_system(online_renderer)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import argparse
|
||||
|
||||
from vllm.benchmarks.forward.main import add_cli_args, main
|
||||
from vllm.entrypoints.cli.benchmark.base import BenchmarkSubcommandBase
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
|
||||
class BenchmarkForwardSubcommand(BenchmarkSubcommandBase):
|
||||
"""The `forward` subcommand for `vllm bench`."""
|
||||
|
||||
name = "forward"
|
||||
help = "Benchmark the model forward of exact batches as CUDA graphs."
|
||||
|
||||
@classmethod
|
||||
def add_cli_args(cls, parser: FlexibleArgumentParser) -> None:
|
||||
add_cli_args(parser)
|
||||
|
||||
@staticmethod
|
||||
def cmd(args: argparse.Namespace) -> None:
|
||||
main(args)
|
||||
@@ -38,6 +38,7 @@ def maybe_exec_rust_bench() -> None:
|
||||
def _import_bench_subcommand_modules() -> None:
|
||||
# Imported lazily so `BenchmarkSubcommandBase` subclasses register only
|
||||
# when `vllm bench` is actually invoked.
|
||||
import vllm.entrypoints.cli.benchmark.forward # noqa: F401
|
||||
import vllm.entrypoints.cli.benchmark.latency # noqa: F401
|
||||
import vllm.entrypoints.cli.benchmark.mm_processor # noqa: F401
|
||||
import vllm.entrypoints.cli.benchmark.serve # noqa: F401
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The `download-kernels` subcommand for the vLLM CLI.
|
||||
|
||||
Installs the precompiled kernels that vLLM's dependencies would otherwise
|
||||
download or compile at startup. Run it after installing or upgrading vLLM:
|
||||
|
||||
vllm download-kernels
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import typing
|
||||
from importlib.util import find_spec
|
||||
|
||||
from vllm.entrypoints.cli.types import CLISubcommand
|
||||
from vllm.logger import init_logger
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
else:
|
||||
FlexibleArgumentParser = argparse.ArgumentParser
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _download_flashinfer_kernels(dry_run: bool) -> int:
|
||||
if find_spec("flashinfer") is None:
|
||||
logger.info("FlashInfer is not installed; skipping its kernels.")
|
||||
return 0
|
||||
from vllm.utils.flashinfer import has_flashinfer_jit_cache_wheels
|
||||
|
||||
cmd = [sys.executable, "-m", "flashinfer"]
|
||||
if has_flashinfer_jit_cache_wheels():
|
||||
cmd.append("download-kernels")
|
||||
else:
|
||||
logger.info(
|
||||
"FlashInfer does not publish flashinfer-jit-cache for this CUDA "
|
||||
"version; installing flashinfer-cubin only."
|
||||
)
|
||||
cmd.append("install-cubin-wheel")
|
||||
if dry_run:
|
||||
cmd.append("--dry-run")
|
||||
# FlashInfer refuses to import while kernels from another FlashInfer version
|
||||
# are installed, which would stop its own CLI from replacing them.
|
||||
env = {**os.environ, "FLASHINFER_DISABLE_VERSION_CHECK": "1"}
|
||||
return subprocess.run(cmd, env=env, check=False).returncode
|
||||
|
||||
|
||||
class DownloadKernelsSubcommand(CLISubcommand):
|
||||
"""The `download-kernels` subcommand for the vLLM CLI."""
|
||||
|
||||
name = "download-kernels"
|
||||
|
||||
@staticmethod
|
||||
def add_cli_args(parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Print the install commands without running them.",
|
||||
)
|
||||
return parser
|
||||
|
||||
@staticmethod
|
||||
def cmd(args: argparse.Namespace) -> None:
|
||||
sys.exit(_download_flashinfer_kernels(args.dry_run))
|
||||
|
||||
def subparser_init(
|
||||
self, subparsers: argparse._SubParsersAction
|
||||
) -> FlexibleArgumentParser:
|
||||
parser = subparsers.add_parser(
|
||||
self.name,
|
||||
help="Install precompiled kernels for faster startup.",
|
||||
description=(
|
||||
"Install the precompiled kernels that vLLM's dependencies would "
|
||||
"otherwise download or compile at startup. Run it after "
|
||||
"installing or upgrading vLLM."
|
||||
),
|
||||
usage="vllm download-kernels [--dry-run]",
|
||||
)
|
||||
return DownloadKernelsSubcommand.add_cli_args(parser)
|
||||
|
||||
|
||||
def cmd_init() -> list[CLISubcommand]:
|
||||
return [DownloadKernelsSubcommand()]
|
||||
@@ -42,6 +42,7 @@ def main():
|
||||
|
||||
import vllm.entrypoints.cli.benchmark.main
|
||||
import vllm.entrypoints.cli.collect_env
|
||||
import vllm.entrypoints.cli.download_kernels
|
||||
import vllm.entrypoints.cli.launch
|
||||
import vllm.entrypoints.cli.openai
|
||||
import vllm.entrypoints.cli.preload
|
||||
@@ -60,6 +61,7 @@ def main():
|
||||
vllm.entrypoints.cli.launch,
|
||||
vllm.entrypoints.cli.benchmark.main,
|
||||
vllm.entrypoints.cli.collect_env,
|
||||
vllm.entrypoints.cli.download_kernels,
|
||||
vllm.entrypoints.cli.preload,
|
||||
vllm.entrypoints.cli.run_batch,
|
||||
vllm.entrypoints.cli.snapshot,
|
||||
|
||||
@@ -39,6 +39,7 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
check_ipc_platform_support,
|
||||
)
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
@@ -157,7 +158,13 @@ class PreloadSubcommand(CLISubcommand):
|
||||
)
|
||||
|
||||
engine_args = EngineArgs.from_cli_args(args)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
# Warmup context for flashinfer autotune.
|
||||
usage_context = (
|
||||
UsageContext.OPENAI_API_SERVER
|
||||
if engine_args.kernel_config.enable_flashinfer_autotune is not False
|
||||
else None
|
||||
)
|
||||
vllm_config = engine_args.create_engine_config(usage_context=usage_context)
|
||||
if vllm_config.load_config.load_format == "ipc_cache":
|
||||
raise ValueError(
|
||||
"The weight cache daemon itself must load from disk; use the "
|
||||
|
||||
@@ -45,7 +45,6 @@ from fastapi import Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.entrypoints.cohere.cohere_chat_message import (
|
||||
CitationSource as InternalCitationSource,
|
||||
)
|
||||
@@ -91,6 +90,7 @@ from vllm.entrypoints.serve.engine.protocol import ErrorInfo, ErrorResponse
|
||||
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.parser.abstract_parser import Parser
|
||||
from vllm.renderers.chat_utils import ChatTemplateContentFormatOption
|
||||
from vllm.renderers.cohere import (
|
||||
MESSAGES_CITATIONS_KEY,
|
||||
POSITION_TO_SOURCE_KEY,
|
||||
@@ -251,9 +251,11 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
reasoning_parser: str = "",
|
||||
enable_auto_tools: bool = False,
|
||||
tool_parser: str | None = None,
|
||||
tool_strict_level: str = "auto",
|
||||
tool_strict_level: str | None = None,
|
||||
enable_prompt_tokens_details: bool = False,
|
||||
enable_force_include_usage: bool = False,
|
||||
enable_log_outputs: bool = False,
|
||||
enable_log_deltas: bool = True,
|
||||
default_chat_template_kwargs: dict[str, Any] | None = None,
|
||||
is_reasoning_model: bool = True,
|
||||
) -> None:
|
||||
@@ -272,6 +274,8 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
tool_parser=tool_parser,
|
||||
enable_prompt_tokens_details=enable_prompt_tokens_details,
|
||||
enable_force_include_usage=enable_force_include_usage,
|
||||
enable_log_outputs=enable_log_outputs,
|
||||
enable_log_deltas=enable_log_deltas,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
)
|
||||
# Controls how the assistant's chain-of-thought is surfaced on
|
||||
@@ -498,7 +502,7 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
# Map every content block to a plain ``{"type": "text", "text":
|
||||
# ...}`` part, mirroring the shape :meth:`_convert_user_message`
|
||||
# emits for multi-part user content. vLLM's
|
||||
# ``_parse_chat_message_content`` collapses a text-only tool
|
||||
# ``parse_chat_message_content`` collapses a text-only tool
|
||||
# part list back into ``"\n".join(...)`` on the way to the
|
||||
# renderer, so simple chat templates that expect string tool
|
||||
# content still work; keeping the list here just preserves the
|
||||
@@ -508,8 +512,8 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
# Tool message content uses ``ToolMessageV2Content``, a union of
|
||||
# ``TextToolContent`` and ``DocumentToolContent``. The latter
|
||||
# produces ``{"type": "document", "document": {...}}`` blocks,
|
||||
# which vLLM's shared ``_parse_chat_message_content_parts`` in
|
||||
# ``vllm/entrypoints/chat_utils.py`` rejects because the OpenAI
|
||||
# which vLLM's shared ``parse_chat_message_content_parts`` in
|
||||
# ``vllm/renderers/chat_utils.py`` rejects because the OpenAI
|
||||
# ``ChatCompletionContentPartParam`` union only knows text /
|
||||
# image / audio / etc. Emitting them anyway triggers a Pydantic
|
||||
# ``ValidatorIterator`` failure at chat-parsing time, so we
|
||||
@@ -597,7 +601,7 @@ class CohereServingChatV2(OpenAIServingChat):
|
||||
json_schema=(
|
||||
JsonSchemaResponseFormat(
|
||||
name="cohere_v2_json_schema",
|
||||
json_schema=rf.json_schema,
|
||||
schema=rf.json_schema,
|
||||
)
|
||||
if rf.json_schema
|
||||
else None
|
||||
|
||||
@@ -15,15 +15,15 @@ from vllm import (
|
||||
SamplingParams,
|
||||
)
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.entrypoints.chat_utils import (
|
||||
ChatCompletionMessageParam,
|
||||
ChatTemplateContentFormatOption,
|
||||
)
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.inputs import EngineInput
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.renderers import BaseRenderer, ChatParams, merge_kwargs
|
||||
from vllm.renderers.chat_utils import (
|
||||
ChatCompletionMessageParam,
|
||||
ChatTemplateContentFormatOption,
|
||||
)
|
||||
from vllm.renderers.inputs.preprocess import (
|
||||
conversation_to_seq,
|
||||
parse_model_prompt,
|
||||
@@ -54,6 +54,7 @@ class OfflineInferenceMixin:
|
||||
renderer: BaseRenderer
|
||||
llm_engine: "LLMEngine"
|
||||
model_config: ModelConfig
|
||||
chat_template: str | None
|
||||
|
||||
def _resolve_mm_lora(
|
||||
self,
|
||||
@@ -180,7 +181,9 @@ class OfflineInferenceMixin:
|
||||
renderer = self.renderer
|
||||
|
||||
chat_params = ChatParams(
|
||||
chat_template=chat_template,
|
||||
chat_template=(
|
||||
self.chat_template if chat_template is None else chat_template
|
||||
),
|
||||
chat_template_content_format=chat_template_content_format,
|
||||
chat_template_kwargs=merge_kwargs(
|
||||
chat_template_kwargs,
|
||||
@@ -281,10 +284,13 @@ class OfflineInferenceMixin:
|
||||
|
||||
def _priority_to_seq(
|
||||
self,
|
||||
priority: list[int] | None,
|
||||
priority: int | Sequence[int] | None,
|
||||
num_requests: int,
|
||||
) -> Sequence[int]:
|
||||
if priority is not None:
|
||||
if priority is None:
|
||||
priority = 0
|
||||
|
||||
if isinstance(priority, Sequence):
|
||||
if len(priority) != num_requests:
|
||||
raise VLLMValidationError(
|
||||
f"The lengths of prompts ({num_requests}) "
|
||||
@@ -293,7 +299,7 @@ class OfflineInferenceMixin:
|
||||
|
||||
return priority
|
||||
|
||||
return [0] * num_requests
|
||||
return [priority] * num_requests
|
||||
|
||||
def _add_completion_requests(
|
||||
self,
|
||||
@@ -304,7 +310,7 @@ class OfflineInferenceMixin:
|
||||
*,
|
||||
use_tqdm: bool | Callable[..., tqdm] = True,
|
||||
lora_request: Sequence[LoRARequest] | LoRARequest | None = None,
|
||||
priority: list[int] | None = None,
|
||||
priority: int | Sequence[int] | None = None,
|
||||
tokenization_kwargs: dict[str, Any] | None = None,
|
||||
mm_processor_kwargs: dict[str, Any] | None = None,
|
||||
) -> list[str]:
|
||||
@@ -341,7 +347,7 @@ class OfflineInferenceMixin:
|
||||
*,
|
||||
use_tqdm: bool | Callable[..., tqdm] = True,
|
||||
lora_request: Sequence[LoRARequest] | LoRARequest | None = None,
|
||||
priority: list[int] | None = None,
|
||||
priority: int | Sequence[int] | None = None,
|
||||
tokenization_kwargs: dict[str, Any] | None = None,
|
||||
mm_processor_kwargs: dict[str, Any] | None = None,
|
||||
):
|
||||
@@ -367,6 +373,7 @@ class OfflineInferenceMixin:
|
||||
*,
|
||||
use_tqdm: bool | Callable[..., tqdm] = True,
|
||||
lora_request: Sequence[LoRARequest] | LoRARequest | None = None,
|
||||
priority: int | Sequence[int] | None = None,
|
||||
chat_template: str | None = None,
|
||||
chat_template_content_format: ChatTemplateContentFormatOption = "auto",
|
||||
add_generation_prompt: bool = True,
|
||||
@@ -381,6 +388,7 @@ class OfflineInferenceMixin:
|
||||
params=params,
|
||||
use_tqdm=use_tqdm,
|
||||
lora_request=lora_request,
|
||||
priority=priority,
|
||||
chat_template=chat_template,
|
||||
chat_template_content_format=chat_template_content_format,
|
||||
chat_template_kwargs=chat_template_kwargs,
|
||||
@@ -402,7 +410,7 @@ class OfflineInferenceMixin:
|
||||
*,
|
||||
use_tqdm: bool | Callable[..., tqdm] = True,
|
||||
lora_request: Sequence[LoRARequest] | LoRARequest | None = None,
|
||||
priority: list[int] | None = None,
|
||||
priority: int | Sequence[int] | None = None,
|
||||
chat_template: str | None = None,
|
||||
chat_template_content_format: ChatTemplateContentFormatOption = "auto",
|
||||
add_generation_prompt: bool = True,
|
||||
|
||||
@@ -53,12 +53,6 @@ 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",
|
||||
@@ -69,7 +63,7 @@ async def init_generate_state(
|
||||
default_chat_template_kwargs: dict[str, Any],
|
||||
):
|
||||
from vllm.entrypoints.anthropic.serving import AnthropicServingMessages
|
||||
from vllm.entrypoints.chat_utils import load_chat_template
|
||||
from vllm.renderers.chat_utils import load_chat_template
|
||||
|
||||
# The Cohere serving handler depends on the optional `cohere` SDK for
|
||||
# its wire-format protocol models, and is additionally gated on the
|
||||
@@ -190,6 +184,8 @@ async def init_generate_state(
|
||||
reasoning_parser=args.structured_outputs_config.reasoning_parser,
|
||||
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
|
||||
enable_force_include_usage=args.enable_force_include_usage,
|
||||
enable_log_outputs=args.enable_log_outputs,
|
||||
enable_log_deltas=args.enable_log_deltas,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
disabled_thinking_effort=args.anthropic_disabled_thinking_effort,
|
||||
)
|
||||
@@ -212,6 +208,8 @@ async def init_generate_state(
|
||||
reasoning_parser=args.structured_outputs_config.reasoning_parser,
|
||||
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
|
||||
enable_force_include_usage=args.enable_force_include_usage,
|
||||
enable_log_outputs=args.enable_log_outputs,
|
||||
enable_log_deltas=args.enable_log_deltas,
|
||||
default_chat_template_kwargs=default_chat_template_kwargs,
|
||||
is_reasoning_model=args.cohere_is_reasoning_model,
|
||||
)
|
||||
@@ -226,31 +224,3 @@ 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
|
||||
)
|
||||
|
||||
@@ -15,10 +15,10 @@ from pydantic import (
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.utils import replace
|
||||
from vllm.entrypoints.chat_utils import make_tool_call_id
|
||||
from vllm.entrypoints.serve.engine.protocol import OpenAIBaseModel, UsageInfo
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.renderers.chat_utils import make_tool_call_id
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -33,6 +33,8 @@ TopLogprobsParam: TypeAlias = Annotated[
|
||||
BeforeValidator(lambda v: 0 if v is None else v, json_schema_input_type=int | None),
|
||||
]
|
||||
|
||||
MMPayload: TypeAlias = Literal["tensors", "none"]
|
||||
|
||||
_CACHE_SALT_FORBIDDEN_CHARS = frozenset("@/\\\x00")
|
||||
_MAX_CACHE_SALT_LENGTH = 128
|
||||
|
||||
@@ -56,6 +58,17 @@ def validate_cache_salt(cache_salt: object) -> None:
|
||||
)
|
||||
|
||||
|
||||
def resolve_return_mm_kwargs_alias(data: Any) -> Any:
|
||||
"""Map the deprecated `return_mm_kwargs=False` onto `mm_payload="none"`."""
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
and data.get("return_mm_kwargs") is False
|
||||
and "mm_payload" not in data
|
||||
):
|
||||
data = {**data, "mm_payload": "none"}
|
||||
return data
|
||||
|
||||
|
||||
def validate_request_mm_kwargs(
|
||||
*,
|
||||
mm_processor_kwargs: dict[str, Any] | None,
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import json
|
||||
import time
|
||||
from collections.abc import Awaitable, Mapping
|
||||
from collections.abc import Awaitable
|
||||
from dataclasses import dataclass, field
|
||||
from http import HTTPStatus
|
||||
from typing import ClassVar, Generic, TypeVar
|
||||
|
||||
from fastapi import Request
|
||||
from pydantic import ConfigDict
|
||||
from starlette.datastructures import Headers
|
||||
|
||||
from vllm import RequestOutput
|
||||
from vllm.engine.protocol import EngineClient
|
||||
@@ -33,11 +32,6 @@ 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,
|
||||
log_tracing_disabled_warning,
|
||||
)
|
||||
from vllm.v1.metrics.stats import RequestStateStats
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -222,20 +216,6 @@ class GenerateBaseServing(BaseServing, BeamSearchOnlineMixin):
|
||||
status_code=e.status_code,
|
||||
)
|
||||
|
||||
async def _get_trace_headers(
|
||||
self,
|
||||
headers: Headers,
|
||||
) -> Mapping[str, str] | None:
|
||||
is_tracing_enabled = await self.engine_client.is_tracing_enabled()
|
||||
|
||||
if is_tracing_enabled:
|
||||
return extract_trace_headers(headers)
|
||||
|
||||
if contains_trace_headers(headers):
|
||||
log_tracing_disabled_warning()
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_data_parallel_rank(raw_request: Request | None) -> int | None:
|
||||
"""Pulls the data parallel rank from a header, if provided."""
|
||||
|
||||
@@ -11,7 +11,6 @@ logits (task="generate").
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import Request
|
||||
@@ -28,15 +27,11 @@ from vllm.entrypoints.serve.engine.protocol import (
|
||||
)
|
||||
from vllm.entrypoints.serve.engine.serving import BaseServing
|
||||
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.exceptions import GenerationError
|
||||
from vllm.inputs import EngineInput, tokens_input
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tracing import (
|
||||
contains_trace_headers,
|
||||
extract_trace_headers,
|
||||
log_tracing_disabled_warning,
|
||||
)
|
||||
from vllm.utils import random_uuid
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -312,6 +307,8 @@ class ServingGenerativeScoring(BaseServing):
|
||||
return self.create_error_response("Client disconnected")
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
except GenerationError as e:
|
||||
return self.create_error_response(e)
|
||||
except Exception as e:
|
||||
logger.exception("Error during generation")
|
||||
return self.create_error_response(e)
|
||||
@@ -462,17 +459,3 @@ class ServingGenerativeScoring(BaseServing):
|
||||
token_id: math.exp(logprob)
|
||||
for token_id, logprob in label_logprobs.items()
|
||||
}
|
||||
|
||||
async def _get_trace_headers(
|
||||
self,
|
||||
headers: Mapping[str, str],
|
||||
) -> Mapping[str, str] | None:
|
||||
"""Extract trace headers from request headers."""
|
||||
if not contains_trace_headers(headers):
|
||||
return None
|
||||
|
||||
if not await self.engine_client.is_tracing_enabled():
|
||||
log_tracing_disabled_warning()
|
||||
return None
|
||||
|
||||
return extract_trace_headers(headers)
|
||||
|
||||
@@ -6,6 +6,7 @@ from collections.abc import AsyncGenerator, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.exceptions import GenerationError
|
||||
from vllm.inputs import EngineInput
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.outputs import RequestOutput
|
||||
@@ -33,7 +34,7 @@ async def next_token_label_reads(
|
||||
) -> 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
|
||||
``logprob_token_ids``. Raises GenerationError naming the item when a read has
|
||||
no output or lacks a label's logprob."""
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = [
|
||||
engine_client.generate(
|
||||
@@ -53,14 +54,14 @@ async def next_token_label_reads(
|
||||
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}")
|
||||
raise GenerationError(f"Failed to generate result for item {i}")
|
||||
if not result.outputs:
|
||||
raise ValueError(f"No output generated for item {i}")
|
||||
raise GenerationError(f"No output generated for item {i}")
|
||||
output = result.outputs[0]
|
||||
if output.finish_reason == "error":
|
||||
raise ValueError(f"Generation error for item {i}")
|
||||
raise GenerationError(f"Generation error for item {i}")
|
||||
if not output.logprobs:
|
||||
raise ValueError(
|
||||
raise GenerationError(
|
||||
f"No logprobs available for item {i}. "
|
||||
"This might indicate an issue with logprobs configuration."
|
||||
)
|
||||
@@ -68,7 +69,7 @@ async def next_token_label_reads(
|
||||
label_ids = params.logprob_token_ids or []
|
||||
missing = [t for t in label_ids if t not in logprobs]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
raise GenerationError(
|
||||
f"Token IDs {missing} not found in logprobs for item {i}. "
|
||||
"This might indicate the tokens are outside the model's vocabulary."
|
||||
)
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.datastructures import State
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.openai.decisions.state import init_decisions_state
|
||||
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 vllm.entrypoints.serve.utils.request_logger import RequestLogger
|
||||
from vllm.renderers.chat_utils import load_chat_template
|
||||
from vllm.tasks import SupportedTask
|
||||
|
||||
from .protocol import StructuredDecisionRequest
|
||||
from .serving import ServingStructuredDecisions
|
||||
@@ -50,3 +58,29 @@ async def create_structured_decision(
|
||||
|
||||
def register_structured_decisions_api_router(app: FastAPI):
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
def init_structured_decisions_state(
|
||||
engine_client: EngineClient,
|
||||
state: State,
|
||||
args: Namespace,
|
||||
request_logger: RequestLogger | None,
|
||||
supported_tasks: tuple[SupportedTask, ...],
|
||||
default_chat_template_kwargs: dict[str, Any],
|
||||
):
|
||||
strategy = init_decisions_state(
|
||||
engine_client,
|
||||
state,
|
||||
args,
|
||||
request_logger,
|
||||
load_chat_template(args.chat_template),
|
||||
default_chat_template_kwargs,
|
||||
supported_tasks,
|
||||
)
|
||||
state.serving_structured_decisions = (
|
||||
ServingStructuredDecisions(
|
||||
state.openai_serving_models, strategy, request_logger=request_logger
|
||||
)
|
||||
if strategy is not None
|
||||
else None
|
||||
)
|
||||
|
||||
@@ -7,11 +7,8 @@ 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
|
||||
|
||||
|
||||
@@ -30,6 +27,15 @@ class StructuredDecisionRequest(OpenAIBaseModel):
|
||||
instructions: str | None = Field(
|
||||
default=None, description="Context placed ahead of the questions."
|
||||
)
|
||||
images: list[str] | None = Field(
|
||||
default=None, description="Image URLs or data URLs, for models that see."
|
||||
)
|
||||
audio: list[str] | None = Field(
|
||||
default=None, description="Audio URLs or data URLs, for models that hear."
|
||||
)
|
||||
videos: list[str] | None = Field(
|
||||
default=None, description="Video URLs or data URLs, for models that see."
|
||||
)
|
||||
chat_template_kwargs: dict[str, Any] | None = None
|
||||
cache_salt: str | None = Field(
|
||||
default=None,
|
||||
@@ -75,34 +81,3 @@ class StructuredDecisionResponse(OpenAIBaseModel):
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
# 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 vllm.entrypoints.openai.decisions.question_types import (
|
||||
Question,
|
||||
StructuredDecisionError,
|
||||
build_question,
|
||||
)
|
||||
from vllm.entrypoints.openai.decisions.serving import BaseServingDecisions
|
||||
from vllm.entrypoints.openai.decisions.strategies import DecisionLimits
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
|
||||
from .protocol import (
|
||||
DecisionUsage,
|
||||
@@ -24,14 +20,6 @@ from .protocol import (
|
||||
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(
|
||||
@@ -57,35 +45,24 @@ def parse_questions(
|
||||
spec.instructions,
|
||||
spec.criteria,
|
||||
limits.max_options,
|
||||
labeled=limits.labeled,
|
||||
)
|
||||
)
|
||||
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)
|
||||
class ServingStructuredDecisions(BaseServingDecisions):
|
||||
def _media(self, request: StructuredDecisionRequest) -> dict[str, list[str]]:
|
||||
urls = {
|
||||
"image": request.images,
|
||||
"audio": request.audio,
|
||||
"video": request.videos,
|
||||
}
|
||||
media = {modality: items for modality, items in urls.items() if items}
|
||||
if unsupported := media.keys() - self.strategy.modalities:
|
||||
names = ", ".join(sorted(unsupported))
|
||||
raise StructuredDecisionError(f"this model does not take {names} inputs")
|
||||
return media
|
||||
|
||||
async def create_decision(
|
||||
self,
|
||||
@@ -102,8 +79,9 @@ class ServingStructuredDecisions(BaseServing):
|
||||
request_id = f"decision-{base_id}"
|
||||
try:
|
||||
questions = parse_questions(request, self.limits)
|
||||
media = self._media(request)
|
||||
lora_request = self._maybe_get_adapters(request) # type: ignore[arg-type]
|
||||
engine_client.check_admission(len(questions))
|
||||
engine_client.check_admission(self.strategy.num_requests(questions))
|
||||
trace_headers = (
|
||||
None
|
||||
if raw_request is None
|
||||
@@ -112,13 +90,14 @@ class ServingStructuredDecisions(BaseServing):
|
||||
reads = await self.strategy.read(
|
||||
questions,
|
||||
request.instructions,
|
||||
state_text(request.state),
|
||||
self.strategy.render_state(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,
|
||||
media=media,
|
||||
)
|
||||
except StructuredDecisionError as e:
|
||||
return self.create_error_response(e)
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
# 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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user