Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-20 22:55:38 +09:00
83 changed files with 4549 additions and 1058 deletions
+6 -3
View File
@@ -14,6 +14,7 @@ import torch
import torch.multiprocessing as mp
from vllm.distributed import get_ep_group
from vllm.platforms import current_platform
from vllm.utils.flashinfer import (
has_flashinfer_nvlink_one_sided,
has_flashinfer_nvlink_two_sided,
@@ -23,6 +24,8 @@ from vllm.utils.network_utils import get_open_port
from ..utils import init_test_distributed_environment
DEVICE = current_platform.device_type
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -483,7 +486,7 @@ def _args_dispatch_combine_worker(rank, world_size):
from vllm.forward_context import get_forward_context
cpu_group = get_ep_group().cpu_group
device = torch.device(f"cuda:{rank}")
device = torch.device(f"{DEVICE}:{rank}")
hidden_size = 64
tokens_per_rank = 16
@@ -624,7 +627,7 @@ def _two_sided_data_worker(rank, world_size):
# Use DP group because MnnvlMoe workspace allocation calls get_dp_group()
# internally and requires dp_size == ep_size.
cpu_group = get_dp_group().cpu_group
device = torch.device(f"cuda:{rank}")
device = torch.device(f"{DEVICE}:{rank}")
num_gpus = torch.accelerator.device_count()
hidden_size = 128
@@ -769,7 +772,7 @@ def _one_sided_data_worker(rank, world_size):
from vllm.forward_context import get_forward_context
cpu_group = get_dp_group().cpu_group
device = torch.device(f"cuda:{rank}")
device = torch.device(f"{DEVICE}:{rank}")
hidden_size = 256
tokens_per_rank = 32
+11 -5
View File
@@ -15,6 +15,7 @@ import pytest
from tests.utils import multi_gpu_test
from vllm.config import VllmConfig
from vllm.engine.arg_utils import EngineArgs
from vllm.platforms import current_platform
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.executor import multiproc_executor
from vllm.v1.executor.multiproc_executor import MultiprocExecutor
@@ -378,8 +379,8 @@ def test_multiproc_executor_properties():
def test_multiproc_executor_multi_node():
"""Test MultiprocExecutor with multi-node configuration.
This simulates 2 nodes with TP=4:
- Node 0 (rank 0): Uses GPUs 0,1 (CUDA_VISIBLE_DEVICES=0,1) with TP=2
- Node 1 (rank 1): Uses GPUs 2,3 (CUDA_VISIBLE_DEVICES=2,3) with TP=2
- Node 0 (rank 0): Uses GPUs 0,1 (device_control_env_var=0,1) with TP=2
- Node 1 (rank 1): Uses GPUs 2,3 (device_control_env_var=2,3) with TP=2
Total world_size = 4, nnodes = 2
"""
# Python 3.14+ changed default multiprocessing start method to 'forkserver'
@@ -392,15 +393,20 @@ def test_multiproc_executor_multi_node():
# symm_mem does not work for simulating multi instance in single node
os.environ["VLLM_ALLREDUCE_USE_SYMM_MEM"] = "0"
# Use the platform-specific device control env var (e.g.
# CUDA_VISIBLE_DEVICES on CUDA, ZE_AFFINITY_MASK on XPU) so that each
# node only sees its own devices on different platform.
device_control_env_var = current_platform.device_control_env_var
def run_node(node_rank: int, result_queue: multiprocessing.Queue, port: int):
"""Run a single node's executor."""
executor = None
try:
# Set CUDA_VISIBLE_DEVICES for this node
# Restrict visible devices for this node
if node_rank == 0:
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
os.environ[device_control_env_var] = "0,1"
else:
os.environ["CUDA_VISIBLE_DEVICES"] = "2,3"
os.environ[device_control_env_var] = "2,3"
# Create config for this node
vllm_config = create_vllm_config(
@@ -52,6 +52,7 @@ def _make_generate_response(
logprobs: dict | None = None,
prompt_logprobs: list | None = None,
kv_transfer_params: dict | None = None,
metrics: dict | None = None,
) -> dict:
choice: dict = {
"index": 0,
@@ -64,6 +65,7 @@ def _make_generate_response(
"choices": [choice],
"prompt_logprobs": prompt_logprobs,
"kv_transfer_params": kv_transfer_params,
"metrics": metrics,
}
@@ -266,6 +268,49 @@ async def test_derender_chat_kv_transfer_params_passthrough(client):
assert response.json()["kv_transfer_params"] == kv
@pytest.mark.asyncio
async def test_derender_chat_metrics_passthrough(client):
gen_req = await _render_chat(client)
metrics = {
"speculative_decoding": {
"mean_acceptance_length": 2.0,
"draft_acceptance_rate": 0.5,
"acceptance_histogram": [0, 1],
"num_spec_steps": 1,
"num_accepted_draft_tokens": 1,
"num_draft_tokens": 2,
"num_spec_tokens": 1,
}
}
response = await client.post(
"/v1/chat/completions/derender",
json={
"model": MODEL_NAME,
"generate_response": _make_generate_response(
gen_req["token_ids"][:3], metrics=metrics
),
},
)
assert response.status_code == 200
actual = response.json()["metrics"]
assert set(actual) == {
"time_to_first_token_ms",
"generation_time_ms",
"queue_time_ms",
"mean_itl_ms",
"tokens_per_second",
"speculative_decoding",
}
assert all(
actual[name] is None for name in actual if name != "speculative_decoding"
)
assert actual["speculative_decoding"] == {
**metrics["speculative_decoding"],
"per_step_accepted": None,
"per_step_drafted": None,
}
@pytest.mark.asyncio
async def test_derender_chat_empty_token_ids(client):
"""Empty token_ids list returns 400."""
@@ -27,6 +27,8 @@ from vllm.entrypoints.generate.base.protocol import (
DeltaFunctionCall,
DeltaMessage,
DeltaToolCall,
PerRequestMetrics,
SpeculativeDecodingMetrics,
)
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
DerenderStreamState,
@@ -164,6 +166,7 @@ def _make_stream_chunk(
finish_reason: str | None = None,
request_id: str = "test-req",
usage: dict | None = None,
metrics: PerRequestMetrics | None = None,
) -> GenerateStreamResponse:
"""Build a GenerateStreamResponse SSE chunk."""
return GenerateStreamResponse(
@@ -176,6 +179,7 @@ def _make_stream_chunk(
)
],
usage=UsageInfo(**usage) if usage else None,
metrics=metrics,
)
@@ -512,6 +516,26 @@ class TestDerenderChatStream:
assert chunk1.choices[0].delta.role == "assistant"
assert chunk2.choices[0].delta.role is None
@pytest.mark.asyncio
async def test_metrics_passthrough(self, derenderer):
metrics = PerRequestMetrics(
speculative_decoding=SpeculativeDecodingMetrics(
mean_acceptance_length=2.0,
draft_acceptance_rate=0.5,
acceptance_histogram=[0, 1],
num_spec_steps=1,
num_accepted_draft_tokens=1,
num_draft_tokens=2,
num_spec_tokens=1,
)
)
chunk, _ = await derenderer.derender_chat_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk([], metrics=metrics),
state=DerenderStreamState(),
)
assert chunk.metrics == metrics
@pytest.mark.asyncio
async def test_chunked_equals_oneshot(self, derenderer, tokenizer):
"""Sum of streaming content deltas == one shot decode."""
@@ -28,6 +28,7 @@ from vllm.renderers import renderer_from_config
from vllm.renderers.online_renderer import OnlineRenderer
from vllm.sampling_params import SamplingParams
from vllm.v1.engine.async_llm import AsyncLLM
from vllm.v1.metrics.stats import RequestSpecDecodeMetrics
MODEL_NAME = "openai-community/gpt2"
BASE_MODEL_PATHS = [
@@ -130,6 +131,7 @@ def _make_request_output(
logprobs: list[dict[int, Any] | None] | None = None,
num_cached_tokens: int | None = None,
index: int = 0,
spec_decode_metrics: RequestSpecDecodeMetrics | None = None,
) -> RequestOutput:
return RequestOutput(
request_id=request_id,
@@ -144,6 +146,7 @@ def _make_request_output(
cumulative_logprob=None,
logprobs=logprobs,
finish_reason=finish_reason,
spec_decode_metrics=spec_decode_metrics,
)
],
finished=finished,
@@ -321,6 +324,145 @@ async def test_stream_basic():
assert data_chunks[2]["choices"][0]["finish_reason"] == "stop"
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True])
async def test_serve_tokens_returns_spec_decode_metrics(stream: bool):
engine = _mock_engine()
metrics = RequestSpecDecodeMetrics.new(num_spec_tokens=3)
metrics.observe(num_draft_tokens=3, num_accepted=2)
async def mock_generate(*args, **kwargs):
yield _make_request_output(
"req-1",
token_ids=[10],
finish_reason="stop",
finished=True,
spec_decode_metrics=metrics,
)
engine.generate = MagicMock(side_effect=mock_generate)
serving = _build_serving_tokens(engine)
request = GenerateRequest(
token_ids=[1, 2, 3],
sampling_params=SamplingParams(max_tokens=1),
model=MODEL_NAME,
stream=stream,
stream_options=StreamOptions(include_usage=True) if stream else None,
)
response = await serving.serve_tokens(request)
if stream:
chunks = [chunk async for chunk in response]
payload = next(
chunk
for chunk in _parse_sse_chunks(chunks)
if isinstance(chunk, dict) and chunk.get("metrics")
)["metrics"]["speculative_decoding"]
else:
assert isinstance(response, GenerateResponse)
assert response.metrics is not None
assert response.metrics.speculative_decoding is not None
payload = response.metrics.speculative_decoding.model_dump()
assert payload["num_draft_tokens"] == 3
assert payload["num_accepted_draft_tokens"] == 2
assert payload["num_spec_steps"] == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("include_usage", [False, True])
async def test_stream_returns_spec_decode_metrics_on_empty_terminal_output(
include_usage,
):
engine = _mock_engine()
metrics = RequestSpecDecodeMetrics.new(num_spec_tokens=3)
metrics.observe(num_draft_tokens=3, num_accepted=2)
async def mock_generate(*args, **kwargs):
yield _make_request_output("req-1", token_ids=[10])
yield _make_request_output(
"req-1",
token_ids=[],
finish_reason="stop",
finished=True,
spec_decode_metrics=metrics,
)
engine.generate = MagicMock(side_effect=mock_generate)
serving = _build_serving_tokens(engine)
request = GenerateRequest(
token_ids=[1, 2, 3],
sampling_params=SamplingParams(max_tokens=1),
model=MODEL_NAME,
stream=True,
stream_options=StreamOptions(include_usage=include_usage),
)
chunks = [chunk async for chunk in await serving.serve_tokens(request)]
data_chunks = [chunk for chunk in _parse_sse_chunks(chunks) if chunk != "[DONE]"]
assert "metrics" not in data_chunks[0]
assert len(data_chunks) == 1 + int(include_usage)
if include_usage:
assert data_chunks[1]["choices"] == []
assert (
data_chunks[1]["metrics"]["speculative_decoding"]["num_draft_tokens"] == 3
)
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True])
async def test_serve_tokens_omits_spec_decode_metrics_for_parallel_sampling(
stream: bool,
):
engine = _mock_engine()
metrics = RequestSpecDecodeMetrics.new(num_spec_tokens=3)
metrics.observe(num_draft_tokens=3, num_accepted=2)
result = _make_request_output(
"req-1",
token_ids=[10],
finish_reason="stop",
finished=True,
spec_decode_metrics=metrics,
)
result.outputs.append(
CompletionOutput(
index=1,
text="",
token_ids=[20],
cumulative_logprob=None,
logprobs=None,
finish_reason="stop",
spec_decode_metrics=metrics,
)
)
async def mock_generate(*args, **kwargs):
yield result
engine.generate = MagicMock(side_effect=mock_generate)
serving = _build_serving_tokens(engine)
request = GenerateRequest(
token_ids=[1, 2, 3],
sampling_params=SamplingParams(max_tokens=1, n=2),
model=MODEL_NAME,
stream=stream,
stream_options=StreamOptions(include_usage=True) if stream else None,
)
response = await serving.serve_tokens(request)
if stream:
chunks = [chunk async for chunk in response]
assert all(
"metrics" not in chunk
for chunk in _parse_sse_chunks(chunks)
if isinstance(chunk, dict)
)
else:
assert isinstance(response, GenerateResponse)
assert response.metrics is None
@pytest.mark.asyncio
async def test_non_stream_returns_final_prompt_token_ids_when_requested():
engine = _mock_engine()
+17 -3
View File
@@ -1384,24 +1384,33 @@ def test_humming_global_valid_shape_m(
assert result == expected
def test_humming_permute_scratch_is_keyed_by_runtime_topk(
def test_humming_permute_scratch_is_shared_by_config(
monkeypatch: pytest.MonkeyPatch,
):
from types import SimpleNamespace
from unittest.mock import Mock
import vllm.model_executor.layers.fused_moe.experts.fused_humming_moe as humming
import vllm.model_executor.layers.fused_moe.moe_permute_unpermute as permute
import vllm.v1.worker.workspace as workspace
manager = workspace.WorkspaceManager(torch.device("cpu"))
monkeypatch.setattr(workspace, "_manager", manager)
scratch_topk6 = Mock()
scratch_topk1 = Mock()
scratch_type = Mock(side_effect=[scratch_topk6, scratch_topk1])
monkeypatch.setattr(humming, "moe_permute_unpermute_supported", lambda: True)
monkeypatch.setattr(humming, "MoEPermuteScratch", scratch_type)
monkeypatch.setattr(permute, "MoEPermuteScratch", scratch_type)
moe_config = make_dummy_moe_config(max_num_tokens=512, experts_per_token=6)
moe_config.moe_parallel_config.dp_size = 2
experts = SimpleNamespace(_permute_scratch={}, moe_config=moe_config)
experts = SimpleNamespace(moe_config=moe_config)
other_layer = SimpleNamespace(moe_config=moe_config)
assert humming.HummingExpertsBase._get_permute_scratch(experts, 6) is scratch_topk6
assert (
humming.HummingExpertsBase._get_permute_scratch(other_layer, 6) is scratch_topk6
)
assert humming.HummingExpertsBase._get_permute_scratch(experts, 1) is scratch_topk1
assert humming.HummingExpertsBase._get_permute_scratch(experts, 6) is scratch_topk6
@@ -1412,6 +1421,11 @@ def test_humming_permute_scratch_is_keyed_by_runtime_topk(
assert second_call.kwargs["max_num_tokens"] == 6144
assert second_call.kwargs["topk"] == 1
manager.lock()
assert humming.HummingExpertsBase._get_permute_scratch(experts, 6) is scratch_topk6
with pytest.raises(AssertionError, match="was not allocated during warmup"):
humming.HummingExpertsBase._get_permute_scratch(experts, 2)
def test_humming_delegates_to_instance_activation():
from types import SimpleNamespace
+163 -12
View File
@@ -15,12 +15,14 @@ from vllm.model_executor.layers.fused_moe.expert_map_manager import (
)
from vllm.model_executor.layers.fused_moe.moe_permute_unpermute import (
MoEPermuteScratch,
get_moe_permute_scratch,
moe_permute,
moe_permute_unpermute_supported,
moe_unpermute,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.worker.workspace import current_workspace_manager
NUM_EXPERTS = [16, 64, 256]
TOP_KS = [2, 6, 8]
@@ -120,6 +122,7 @@ def torch_unpermute(
@pytest.mark.parametrize("topk", TOP_KS)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize("ep_size", EP_SIZE)
@pytest.mark.parametrize("use_scratch", [False, True])
def test_moe_permute_unpermute(
n_token: int,
n_hidden: int,
@@ -127,6 +130,8 @@ def test_moe_permute_unpermute(
n_expert: int,
ep_size: int,
dtype: torch.dtype,
use_scratch: bool,
workspace_init,
):
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
@@ -160,6 +165,18 @@ def test_moe_permute_unpermute(
expert_map=expert_map,
)
scratch = None
if use_scratch:
scratch = get_moe_permute_scratch(
max_num_tokens=n_token,
topk=topk,
num_experts=n_expert,
num_local_experts=n_local_expert,
device=hidden_states.device,
hidden_size=n_hidden,
hidden_dtype=dtype,
)
(
permuted_hidden_states,
_,
@@ -173,6 +190,7 @@ def test_moe_permute_unpermute(
n_expert=n_expert,
n_local_expert=n_local_expert,
expert_map=expert_map,
scratch=scratch,
)
# check expert_first_token_offset
@@ -212,20 +230,22 @@ def test_moe_permute_unpermute(
torch.testing.assert_close(result4, gold4, atol=2e-2, rtol=0)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
def test_moe_permute_reuses_scratch_buffers(dtype: torch.dtype):
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("n_token", [1, 33, 128])
@pytest.mark.parametrize("topk", [1, 6, 8])
def test_moe_permute_reuses_scratch_buffers(
dtype: torch.dtype, n_token: int, topk: int, workspace_init
):
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
n_token = 64
n_hidden = 2048
n_expert = 16
topk = 4
hidden_states = torch.randn((n_token, n_hidden), device="cuda").to(dtype)
gating_output = torch.randn((n_token, n_expert), device="cuda").to(dtype)
_, topk_ids, _ = fused_topk(hidden_states, gating_output, topk, False)
scratch = MoEPermuteScratch(
scratch_config = dict(
max_num_tokens=n_token,
topk=topk,
num_experts=n_expert,
@@ -234,6 +254,7 @@ def test_moe_permute_reuses_scratch_buffers(dtype: torch.dtype):
hidden_size=n_hidden,
hidden_dtype=hidden_states.dtype,
)
scratch = get_moe_permute_scratch(**scratch_config)
first = moe_permute(
hidden_states=hidden_states,
@@ -242,13 +263,26 @@ def test_moe_permute_reuses_scratch_buffers(dtype: torch.dtype):
n_expert=n_expert,
scratch=scratch,
)
second = moe_permute(
hidden_states=hidden_states,
a1q_scale=None,
topk_ids=topk_ids,
n_expert=n_expert,
scratch=scratch,
)
current_workspace_manager().lock()
assert get_moe_permute_scratch(**scratch_config) is scratch
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
second = moe_permute(
hidden_states=hidden_states,
a1q_scale=None,
topk_ids=topk_ids,
n_expert=n_expert,
scratch=get_moe_permute_scratch(**scratch_config),
)
for _ in range(2):
hidden_states.add_(1)
topk_ids.copy_(topk_ids.roll(1, 0))
graph.replay()
expected = moe_permute(hidden_states, None, topk_ids, n_expert)
for actual, reference in zip(second, expected):
if actual is not None:
torch.testing.assert_close(actual, reference)
(
permuted_hidden_states_1,
@@ -288,6 +322,123 @@ def test_moe_permute_reuses_scratch_buffers(dtype: torch.dtype):
)
def test_moe_permute_scratch_reused_across_graph_sizes(workspace_init) -> None:
"""Switching graph sizes must not expose metadata left by a larger batch."""
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
device = torch.device("cuda:0")
scratch = get_moe_permute_scratch(
max_num_tokens=128,
topk=6,
num_experts=16,
num_local_experts=16,
device=device,
hidden_size=2048,
hidden_dtype=torch.bfloat16,
)
current_workspace_manager().lock()
runs = []
for n_token in (128, 1, 33):
hidden = torch.randn((n_token, 2048), dtype=torch.bfloat16, device=device)
topk_ids = torch.randint(16, (n_token, 6), device=device)
moe_permute(hidden, None, topk_ids, 16, scratch=scratch)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
output = moe_permute(hidden, None, topk_ids, 16, scratch=scratch)
runs.append((graph, hidden, topk_ids, output))
for graph, hidden, topk_ids, output in runs + runs[::-1]:
hidden.add_(1)
topk_ids.copy_((topk_ids + 1) % 16)
graph.replay()
expected = moe_permute(hidden, None, topk_ids, 16)
for actual, reference in zip(output, expected):
if actual is not None:
torch.testing.assert_close(actual, reference)
def test_moe_permute_scratch_isolated_across_execution_slots(monkeypatch) -> None:
"""Concurrent graph replays in different ubatches/lanes cannot share scratch."""
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
from vllm.v1.worker import workspace
device = torch.device("cuda:0")
manager = workspace.WorkspaceManager(device, num_ubatches=2, num_lanes=2)
monkeypatch.setattr(workspace, "_manager", manager)
ubatch = 0
monkeypatch.setattr(workspace, "dbo_current_ubatch_id", lambda: ubatch)
scratch_config = dict(
max_num_tokens=64,
topk=6,
num_experts=16,
num_local_experts=16,
device=device,
hidden_size=2048,
hidden_dtype=torch.bfloat16,
)
runs = []
for i, n_token in enumerate((1, 7, 33, 64)):
ubatch = i // 2
stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with workspace.use_workspace_lane(i % 2), torch.cuda.stream(stream):
hidden = torch.randn((n_token, 2048), dtype=torch.bfloat16, device=device)
topk_ids = torch.randint(16, (n_token, 6), device=device)
scratch = get_moe_permute_scratch(**scratch_config)
moe_permute(hidden, None, topk_ids, 16, scratch=scratch)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=stream):
output = moe_permute(hidden, None, topk_ids, 16, scratch=scratch)
runs.append((stream, graph, hidden, topk_ids, output, scratch))
torch.cuda.current_stream().wait_stream(stream)
assert len({run[-1].permuted_hidden_states.data_ptr() for run in runs}) == 4
manager.lock()
for _ in range(3):
for i, (stream, graph, hidden, topk_ids, _, scratch) in enumerate(runs):
ubatch = i // 2
with workspace.use_workspace_lane(i % 2), torch.cuda.stream(stream):
assert get_moe_permute_scratch(**scratch_config) is scratch
hidden.add_(1)
topk_ids.copy_((topk_ids + 1) % 16)
graph.replay()
for stream, _, hidden, topk_ids, output, _ in runs:
torch.cuda.current_stream().wait_stream(stream)
expected = moe_permute(hidden, None, topk_ids, 16)
for actual, reference in zip(output, expected):
if actual is not None:
torch.testing.assert_close(actual, reference)
def test_moe_permute_scratch_without_manager(monkeypatch) -> None:
"""Standalone calls get independent scratch with initialized row indices."""
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
from vllm.v1.worker import workspace
monkeypatch.setattr(workspace, "_manager", None)
config = dict(
max_num_tokens=4,
topk=2,
num_experts=4,
num_local_experts=4,
device=torch.device("cuda"),
)
first = get_moe_permute_scratch(**config)
second = get_moe_permute_scratch(**config)
assert (
first.token_expert_indices.data_ptr() != second.token_expert_indices.data_ptr()
)
torch.testing.assert_close(
first.token_expert_indices, torch.arange(8, dtype=torch.int32, device="cuda")
)
def test_moe_permute_ignores_invalid_expert_ids_with_scratch() -> None:
if not moe_permute_unpermute_supported():
pytest.skip("moe_permute_unpermute is not supported on this platform.")
@@ -17,6 +17,7 @@ from vllm.model_executor.layers.quantization.utils.int8_utils import (
per_token_quant_int8,
)
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
get_marlin_workspace,
marlin_make_empty,
marlin_make_workspace_new,
marlin_permute_bias,
@@ -43,6 +44,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
)
from vllm.platforms import current_platform
from vllm.scalar_type import scalar_types
from vllm.v1.worker.workspace import current_workspace_manager
if current_platform.is_rocm():
pytest.skip(
@@ -477,6 +479,62 @@ def test_marlin_gemm(
assert max_diff < 0.04
def test_marlin_persistent_locks_cuda_graph_streams(workspace_init):
"""Compiled GEMMs select stream-local locks at runtime and survive replay."""
size_m, size_k, size_n = 32, 1024, 2048
inputs = [rand_data((size_m, size_k)) for _ in range(2)]
weight = rand_data((size_k, size_n))
quant_type = scalar_types.uint4b8
w_ref, qweight, scales = marlin_quantize(weight, quant_type, 128)
zeros = marlin_make_empty(scales.device)
streams = [torch.cuda.Stream() for _ in inputs]
graphs = [torch.cuda.CUDAGraph() for _ in inputs]
locks = []
outputs = []
@torch.compile(backend="eager", fullgraph=True)
def run(x):
return torch.ops.vllm.marlin_gemm(
x,
qweight,
None,
scales,
None,
None,
zeros,
None,
quant_type.id,
size_m,
size_n,
size_k,
use_atomic_add=False,
use_fp32_reduce=True,
)
for stream, graph, x in zip(streams, graphs, inputs):
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream):
locks.append(get_marlin_workspace(x.device))
run(x)
with torch.cuda.graph(graph, stream=stream):
outputs.append(run(x))
torch.cuda.current_stream().wait_stream(stream)
assert locks[0].data_ptr() != locks[1].data_ptr()
current_workspace_manager().lock()
for _ in range(3):
for stream, graph, x, lock in zip(streams, graphs, inputs, locks):
with torch.cuda.stream(stream):
assert get_marlin_workspace(x.device) is lock
x.add_(0.1)
graph.replay()
for stream in streams:
torch.cuda.current_stream().wait_stream(stream)
for x, output, lock in zip(inputs, outputs, locks):
assert compute_max_diff(output, x @ w_ref) < 0.04
assert torch.count_nonzero(lock) == 0
def test_marlin_gemm_subset_input():
quant_type = scalar_types.uint4b8
group_size = 128
@@ -14,6 +14,7 @@ from vllm import _custom_ops as ops
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
GPTQ_MARLIN_TILE,
apply_gptq_marlin_linear,
get_marlin_workspace,
marlin_make_empty,
marlin_make_workspace_new,
marlin_moe_padded_intermediate,
@@ -225,7 +226,7 @@ def test_fp8_marlin_padded_round_trip(shape, use_bias):
input=x,
weight=layer.weight,
weight_scale=layer.weight_scale,
workspace=layer.workspace,
workspace=get_marlin_workspace(layer.weight.device),
size_n=size_n,
size_k=size_k,
bias=layer.bias if use_bias else None,
@@ -288,7 +289,7 @@ def test_nvfp4_marlin_padded_round_trip(shape):
weight=layer.weight,
weight_scale=layer.weight_scale,
weight_global_scale=layer.weight_global_scale,
workspace=layer.workspace,
workspace=get_marlin_workspace(layer.weight.device),
size_n=size_n,
size_k=size_k,
)
@@ -392,7 +393,7 @@ def test_fp8_block_marlin_padded_round_trip(shape):
input=x,
weight=layer.weight,
weight_scale=layer.weight_scale_inv,
workspace=layer.workspace,
workspace=get_marlin_workspace(layer.weight.device),
size_n=size_n,
size_k=size_k,
bias=None,
@@ -440,7 +441,7 @@ def test_mxfp8_marlin_padded_round_trip(shape):
input=x,
weight=layer.weight,
weight_scale=layer.weight_scale,
workspace=layer.workspace,
workspace=get_marlin_workspace(layer.weight.device),
size_n=size_n,
size_k=size_k,
)
@@ -756,7 +757,7 @@ def test_fp8_marlin_moe_padded_round_trip(shape, quant):
topk_ids,
quant_type_id=scalar_types.float8_e4m3fn.id,
global_num_experts=e,
workspace=layer.workspace,
workspace=get_marlin_workspace(device),
)
with set_current_vllm_config(VllmConfig()):
ref = torch_experts(
@@ -833,7 +834,7 @@ def test_mxfp8_marlin_moe_padded_round_trip(shape):
topk_ids,
quant_type_id=scalar_types.float8_e4m3fn.id,
global_num_experts=e,
workspace=layer.workspace,
workspace=get_marlin_workspace(device),
)
with set_current_vllm_config(VllmConfig()):
ref = torch_experts(
@@ -384,9 +384,16 @@ def test_leading_invalid_tail_slot():
_assert_eq(r_ref, r_kern)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
def test_amd_prefill_seed_honors_padded_tail_block_stride():
"""The tail shares a padded indexer allocation in production."""
def test_prefill_seed_honors_padded_tail_block_stride():
"""The tail shares a padded indexer allocation in production.
``get_kv_cache_config_from_groups`` aliases each tail tensor onto its
indexer tensor with the indexer's block stride (38016 B for GLM-5.3-Flash
vs a dense 2048 B tail block), so a seed kernel that addresses blocks
densely writes into an unrelated indexer block and leaves the request's
tail block untouched. Runs on every platform; the NVIDIA kernel had this
bug while the AMD kernel did not.
"""
kpool = 4
num_blocks = 6
logical_block_elems = 2 * kpool * HEAD_DIM
+23 -8
View File
@@ -1871,17 +1871,32 @@ def test_sparse_indexer_topk_backend_resolution() -> None:
has_coop = _has_cooperative_topk()
has_fi = _has_flashinfer_topk()
# "auto" is exactly the pre-existing chain: cooperative -> persistent ->
# per_row. It must never select the opt-in backends by itself.
# "auto" is the chain cooperative -> persistent -> per_row, with the
# cooperative/persistent switch at cooperative_topk's cluster-wave row
# limit. It must never select the opt-in backends by itself.
if has_coop:
assert resolve("auto") == "cooperative"
from vllm.model_executor.layers.indexer_topk import (
AUTO_COOPERATIVE_MAX_ROWS,
)
# cooperative for every batch within its cluster-wave row limit...
assert (
resolve("auto", k=512, num_rows=AUTO_COOPERATIVE_MAX_ROWS) == "cooperative"
)
assert resolve("auto", k=512, num_rows=8) == "cooperative"
# Past cooperative's 64-row limit -> persistent, even where
# DeepSelect would be applicable.
# ...persistent past the row limit, even where DeepSelect would be
# applicable.
assert (
resolve("auto", k=512, num_rows=AUTO_COOPERATIVE_MAX_ROWS + 1)
== "persistent"
)
assert resolve("auto", k=512, num_rows=128) == "persistent"
# 16B-aligned (cooperative TMA ok) but not DeepSelect-aligned:
# still cooperative at <= 64 rows...
assert resolve("auto", unaligned_logits, num_rows=64) == "cooperative"
# 16B-aligned (cooperative TMA ok) but not DeepSelect-aligned: the
# same row-limit logic applies.
assert (
resolve("auto", unaligned_logits, num_rows=AUTO_COOPERATIVE_MAX_ROWS)
== "cooperative"
)
# ...and persistent past the row limit.
assert resolve("auto", unaligned_logits, num_rows=128) == "persistent"
# Unsupported topk (outside {512, 1024, 2048} for the workspace kernels)
@@ -330,8 +330,8 @@ def _load_marlin_checkpoint_format_weights(layer):
)
def test_marlin_post_load_preserves_runtime_tensor_addresses(monkeypatch, dist_init):
"""Marlin must reuse the workspace storage captured by CUDA graphs."""
def test_marlin_post_load_does_not_own_workspace(monkeypatch, dist_init):
"""Weight reload must not create layer-owned Marlin lock storage."""
_stub_marlin_ops(monkeypatch)
kernel = _make_marlin_kernel()
@@ -339,19 +339,17 @@ def test_marlin_post_load_preserves_runtime_tensor_addresses(monkeypatch, dist_i
_load_marlin_checkpoint_format_weights(layer)
kernel.process_weights_after_loading(layer)
workspace_ptr = kernel.workspace.data_ptr()
assert not hasattr(kernel, "workspace")
_load_marlin_checkpoint_format_weights(layer)
kernel.process_weights_after_loading(layer)
assert kernel.workspace.data_ptr() == workspace_ptr
assert torch.all(kernel.workspace == 0)
assert not hasattr(kernel, "workspace")
@pytest.mark.parametrize("variant", ["fp8", "mxfp8", "nvfp4"])
def test_marlin_prepare_layer_preserves_workspace_address(monkeypatch, variant):
"""The Marlin fallback prepare_* functions rerun on weight reload and must
reuse the workspace storage whose address captured CUDA graphs hold."""
def test_marlin_prepare_layer_does_not_own_workspace(monkeypatch, variant):
"""Weight preparation must not attach runtime workspace to model layers."""
from vllm import _custom_ops as ops
from vllm.model_executor.layers.quantization.utils import (
marlin_utils,
@@ -417,34 +415,57 @@ def test_marlin_prepare_layer_preserves_workspace_address(monkeypatch, variant):
load_checkpoint_format_weights()
prepare(layer)
workspace_ptr = layer.workspace.data_ptr()
assert not hasattr(layer, "workspace")
# Reload: fresh checkpoint-format tensors, prepare runs again
load_checkpoint_format_weights()
prepare(layer)
assert layer.workspace.data_ptr() == workspace_ptr
assert torch.all(layer.workspace == 0)
assert not hasattr(layer, "workspace")
def test_marlin_make_workspace_new_rejects_incompatible_existing(monkeypatch):
"""An incompatible existing workspace means the address captured by CUDA
graphs is already unusable; allocating a replacement would hide that."""
def test_marlin_workspace_uses_persistent_workspace_manager(monkeypatch):
"""Calls reuse initialized locks; independent streams get separate storage."""
from vllm.model_executor.layers.quantization.utils import marlin_utils
from vllm.utils import torch_utils
from vllm.v1.worker import workspace as workspace_module
monkeypatch.setattr(marlin_utils, "num_compute_units", lambda _: 4)
device = torch.device("cpu")
manager = workspace_module.WorkspaceManager(device)
monkeypatch.setattr(workspace_module, "_manager", manager)
stream = "main"
monkeypatch.setattr(torch_utils, "current_stream", lambda: stream)
workspace = marlin_utils.marlin_make_workspace_new(device)
reused = marlin_utils.marlin_make_workspace_new(device, existing=workspace)
assert reused is workspace
workspace = marlin_utils.get_marlin_workspace(device)
assert workspace.shape == (4 * marlin_utils.MARLIN_MAX_BLOCKS_PER_SM,)
assert workspace.dtype == torch.int32
assert torch.count_nonzero(workspace) == 0
with pytest.raises(ValueError, match="incompatible"):
marlin_utils.marlin_make_workspace_new(device, 4, existing=workspace)
with pytest.raises(ValueError, match="incompatible"):
marlin_utils.marlin_make_workspace_new(
device, existing=workspace.to(torch.int64)
)
workspace.fill_(1)
assert marlin_utils.get_marlin_workspace(device) is workspace
assert torch.all(workspace == 1)
stream = "aux"
aux_workspace = marlin_utils.get_marlin_workspace(device)
assert aux_workspace.data_ptr() != workspace.data_ptr()
assert torch.count_nonzero(aux_workspace) == 0
manager.lock()
assert marlin_utils.get_marlin_workspace(device) is aux_workspace
def test_marlin_workspace_without_manager(monkeypatch):
from vllm.model_executor.layers.quantization.utils import marlin_utils
from vllm.v1.worker import workspace as workspace_module
monkeypatch.setattr(workspace_module, "_manager", None)
monkeypatch.setattr(marlin_utils, "num_compute_units", lambda _: 4)
first = marlin_utils.get_marlin_workspace(torch.device("cpu"))
second = marlin_utils.get_marlin_workspace(torch.device("cpu"))
assert first.data_ptr() != second.data_ptr()
assert first.shape == (4 * marlin_utils.MARLIN_MAX_BLOCKS_PER_SM,)
assert torch.count_nonzero(first) == 0
def test_model_cleanup(dist_init, default_vllm_config):
@@ -1,11 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Focused unit tests for the GLM decode top-k dispatch."""
"""Tests for the GLM kpool indexer's top-k backend wiring."""
import pytest
import torch
from vllm.models.glm5next.nvidia.sparse_indexer import _use_cooperative_topk
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.platforms import current_platform
pytestmark = pytest.mark.skipif(
@@ -13,29 +13,31 @@ pytestmark = pytest.mark.skipif(
)
@pytest.mark.parametrize("num_rows", [1, 64], ids=["1row", "64rows"])
@torch.inference_mode()
def test_cooperative_topk_is_selected_for_supported_batch(num_rows: int):
logits = torch.empty(num_rows, 8192, dtype=torch.float32, device="cuda")
assert _use_cooperative_topk(logits, 512, num_rows)
def _require_deep_gemm() -> None:
from vllm.utils.deep_gemm import has_deep_gemm
if not has_deep_gemm():
pytest.skip("kpool indexer requires DeepGEMM")
@pytest.mark.parametrize(
("num_rows", "select_k", "stride_padding"),
[
(65, 512, 0),
(1, 256, 0),
(1, 512, 1),
],
ids=["too_many_rows", "unsupported_k", "unaligned_stride"],
)
@torch.inference_mode()
def test_cooperative_topk_falls_back_on_unsupported_batch(
num_rows: int, select_k: int, stride_padding: int
):
logits = torch.empty(
num_rows, 8192 + stride_padding, dtype=torch.float32, device="cuda"
)
if stride_padding:
logits = logits[:, :8192]
assert not _use_cooperative_topk(logits, select_k, num_rows)
@pytest.mark.parametrize("backend", ["auto", "persistent", "cooperative", "torch"])
def test_kpool_indexer_dispatches_through_shared_topk_backend(backend: str) -> None:
"""The kpool indexer must read kernel_config.sparse_indexer_topk_backend
and hand it to the shared SparseIndexerTopk dispatcher, rather than
hard-coding its own cooperative/persistent/per_row choice."""
_require_deep_gemm()
from vllm.models.glm5next.nvidia.sparse_indexer import SparseAttnIndexerKpool
cfg = VllmConfig(kernel_config={"sparse_indexer_topk_backend": backend})
with set_current_vllm_config(cfg):
op = SparseAttnIndexerKpool(
k_cache=None,
quant_block_size=128,
scale_fmt="ue8m0",
topk_tokens=2048,
head_dim=128,
max_pool_len=4096,
max_total_seq_len=8192,
topk_indices_buffer=torch.empty(8, 2176, dtype=torch.int32, device="cuda"),
)
assert op.topk_backend == backend
@@ -55,6 +55,10 @@ def kimi_vl_chat_template(content: str) -> str:
)
def deepseek_v41_chat_template(content: str) -> str:
return f"<|begin▁of▁sentence|><|User|>{content}<|Assistant|></think>"
def step3_vl_chat_template(content: str) -> str:
return (
"<|begin▁of▁sentence|> You are a helpful assistant.<|BOT|>user\n "
@@ -221,6 +225,25 @@ MODEL_CONFIGS: dict[str, VitCudagraphTestConfig] = {
vllm_runner_kwargs={"gpu_memory_utilization": 0.80},
marks=[pytest.mark.core_model],
),
"deepseek_v41": VitCudagraphTestConfig(
model="deepseek-ai/DeepSeek-V4.1-Flash",
modalities=["image"],
image_prompt=deepseek_v41_chat_template(
"<|deepseek_image|>\n\nWhat is in this image?"
),
compilation_config_overrides={
"encoder_cudagraph_token_budgets": [1024],
},
vllm_runner_kwargs={
"load_format": "dummy",
"attention_backend": "FLASHMLA_SPARSE_DSV41",
"hf_overrides": partial(
dummy_hf_overrides,
model_arch="DeepseekV41ForCausalLM",
exist_overrides={"vision_n_layers": 1},
),
},
),
"step3_vl": VitCudagraphTestConfig(
model="stepfun-ai/Step3-VL-10B",
modalities=["image"],
@@ -218,8 +218,14 @@ def test_model_tensor_schema(model_id: str):
factories = model_cls._processor_factory
# Capture helpers return capture-buffer containers (e.g.
# EncoderCudaGraphCaptureInputs), not TensorSchema mm inputs.
capture_helpers = {"prepare_encoder_cudagraph_capture_inputs"}
inputs_parse_methods = []
for attr_name in dir(model_cls):
if attr_name in capture_helpers:
continue
attr = getattr(model_cls, attr_name)
if hasattr(attr, "__annotations__"):
return_type = attr.__annotations__.get("return", None)
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.models.deepseek_v4.amd.rocm import _wo_a_block_scale_to_e8m0
def test_wo_a_block_scale_to_e8m0_from_float():
scale = torch.tensor([[0.5, 1.0, 2.0, 4.0]], dtype=torch.float32)
encoded = _wo_a_block_scale_to_e8m0(scale)
assert encoded is not None
torch.testing.assert_close(
encoded,
torch.tensor([[126, 127, 128, 129]], dtype=torch.uint8),
)
assert encoded.is_contiguous()
def test_wo_a_block_scale_to_e8m0_preserves_encoded_scales():
raw = torch.tensor([[125, 127, 131]], dtype=torch.uint8)
encoded = raw.view(torch.float8_e8m0fnu)
converted = _wo_a_block_scale_to_e8m0(encoded)
assert converted is not None
torch.testing.assert_close(converted, raw)
@pytest.mark.parametrize(
"scale",
[
torch.tensor([[0.0, 1.0]]),
torch.tensor([[-1.0, 1.0]]),
torch.tensor([[0.75, 1.0]]),
torch.tensor([[float("inf"), 1.0]]),
torch.ones(1, dtype=torch.int32),
],
)
def test_wo_a_block_scale_to_e8m0_rejects_invalid_scales(scale: torch.Tensor):
assert _wo_a_block_scale_to_e8m0(scale) is None
@@ -0,0 +1,166 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Truncation must bound the prompt *after* multimodal placeholders expand.
``TokenizeParams.apply_post_tokenization`` truncates the unexpanded prompt, so
one placeholder token can expand into many and push the result back over
``truncate_prompt_tokens`` (vllm-project/vllm#57038).
"""
import numpy as np
import pytest
import torch
from vllm.config import ModelConfig, VllmConfig
from vllm.exceptions import VLLMValidationError
from vllm.multimodal.inputs import PlaceholderRange
from vllm.renderers import renderer_from_config
from vllm.renderers.base import BaseRenderer
from vllm.renderers.hf import _ensure_prompt_embeds_placeholder_token
from vllm.renderers.params import TokenizeParams
def _renderer():
"""A BaseRenderer stub: only the tokenizer attribute is needed here."""
class _StubRenderer(BaseRenderer):
def __init__(self):
self.tokenizer = None
def render_messages(self, *args, **kwargs):
raise NotImplementedError
return _StubRenderer()
def _mm_input(num_tokens: int, offset: int, length: int, **extra):
return {
"type": "multimodal",
"prompt_token_ids": list(range(num_tokens)),
"mm_kwargs": {},
"mm_hashes": {},
"mm_placeholders": {"audio": [PlaceholderRange(offset=offset, length=length)]},
**extra,
}
def _params(limit: int | None, side: str = "right"):
return TokenizeParams(
max_total_tokens=4096,
truncate_prompt_tokens=limit,
truncation_side=side,
)
def test_expanded_prompt_is_bounded():
"""The reported case: audio fits, trailing text is cut to the limit."""
engine_input = _mm_input(num_tokens=147, offset=1, length=52)
_renderer()._truncate_expanded_prompt(engine_input, _params(96))
assert engine_input["prompt_token_ids"] == list(range(96))
assert engine_input["mm_placeholders"]["audio"][0] == PlaceholderRange(
offset=1, length=52
)
def test_prompt_within_limit_is_untouched():
engine_input = _mm_input(num_tokens=64, offset=1, length=52)
_renderer()._truncate_expanded_prompt(engine_input, _params(96))
assert engine_input["prompt_token_ids"] == list(range(64))
def test_split_multimodal_span_is_rejected():
"""Cutting mid-span would desync features from token ids, so reject."""
engine_input = _mm_input(num_tokens=147, offset=80, length=50)
with pytest.raises(VLLMValidationError, match="truncate_prompt_tokens"):
_renderer()._truncate_expanded_prompt(engine_input, _params(96))
def test_dropped_multimodal_span_is_rejected():
"""A span entirely past the cut would be discarded silently."""
engine_input = _mm_input(num_tokens=147, offset=100, length=20)
with pytest.raises(VLLMValidationError, match="truncate_prompt_tokens"):
_renderer()._truncate_expanded_prompt(engine_input, _params(96))
def test_left_truncation_shifts_placeholder_offsets():
engine_input = _mm_input(num_tokens=147, offset=100, length=20)
_renderer()._truncate_expanded_prompt(engine_input, _params(96, side="left"))
assert engine_input["prompt_token_ids"] == list(range(51, 147))
# The span started at 100 and 51 leading tokens were dropped.
assert engine_input["mm_placeholders"]["audio"][0] == PlaceholderRange(
offset=49, length=20
)
def test_text_only_input_is_untouched():
"""Only multimodal prompts grow after tokenization, so nothing else runs."""
engine_input = {
"type": "token",
"prompt_token_ids": list(range(147)),
"prompt_token_offsets": [(i, i + 1) for i in range(147)],
}
_renderer()._truncate_expanded_prompt(engine_input, _params(96))
assert engine_input["prompt_token_ids"] == list(range(147))
assert len(engine_input["prompt_token_offsets"]) == 147
def test_no_truncation_requested_is_noop():
engine_input = _mm_input(num_tokens=147, offset=1, length=52)
_renderer()._truncate_expanded_prompt(engine_input, _params(None))
assert engine_input["prompt_token_ids"] == list(range(147))
def test_mixed_prompt_embeds_truncation_covers_embeds_spans():
"""Bound in _process_singleton, where prompt_embeds spans are already attached."""
model_config = ModelConfig(
"Qwen/Qwen3-ASR-0.6B-hf",
revision="7f1569a48a89f3e3f4dc3a5c9d28bddd903bc76c",
dtype="float32",
max_model_len=4096,
mm_processor_cache_gb=0,
enable_prompt_embeds=True,
)
renderer = renderer_from_config(VllmConfig(model_config=model_config))
tok = renderer.tokenizer
pe_id = _ensure_prompt_embeds_placeholder_token(tok)
hidden = model_config.get_hidden_size()
audio = np.zeros(4 * 16000, dtype=np.float32)
pe_len = 20
tensors = [torch.zeros(pe_len, hidden, dtype=torch.float32)]
def _build_prompt():
text = "<|audio_start|><|audio_pad|><|audio_end|>"
ids = tok.encode(text) + [pe_id] + tok.encode(" tail" * 40)
return {
"prompt_token_ids": ids,
"multi_modal_data": {"audio": (audio, 16000)},
"_prompt_embeds": (tensors, pe_id),
}
# A limit past every span (audio ends at 52, prompt_embeds at 74):
# truncation should succeed and bound the prompt.
out = renderer._process_singleton(
_build_prompt(),
tok_params=_params(79),
)
assert len(out["prompt_token_ids"]) == 79
# A limit inside the prompt_embeds span (54..74): must be rejected.
with pytest.raises(VLLMValidationError, match="truncate_prompt_tokens"):
renderer._process_singleton(
_build_prompt(),
tok_params=_params(64),
)
+5
View File
@@ -1427,8 +1427,10 @@ def init_test_distributed_environment(
get_current_vllm_config_or_none,
set_current_vllm_config,
)
from vllm.platforms import current_platform
distributed_init_method = f"tcp://localhost:{distributed_init_port}"
backend = current_platform.dist_backend
if data_parallel_size > 1:
# For DP we need to set a common DP master port
@@ -1449,6 +1451,7 @@ def init_test_distributed_environment(
rank=rank % tp_pp_world,
distributed_init_method=distributed_init_method,
local_rank=local_rank if local_rank >= 0 else rank,
backend=backend,
)
ensure_model_parallel_initialized(tp_size, pp_size)
return
@@ -1460,6 +1463,7 @@ def init_test_distributed_environment(
rank=rank,
distributed_init_method=distributed_init_method,
local_rank=local_rank,
backend=backend,
)
ensure_model_parallel_initialized(tp_size, pp_size)
else:
@@ -1470,6 +1474,7 @@ def init_test_distributed_environment(
rank=rank,
distributed_init_method=distributed_init_method,
local_rank=local_rank,
backend=backend,
)
ensure_model_parallel_initialized(tp_size, pp_size)
@@ -391,3 +391,66 @@ def test_interleaved_decode_pollution_legacy_vs_circular():
# The circular mapping keeps the rings isolated under interleaving.
torch.testing.assert_close(circular, ground_truth)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
@pytest.mark.parametrize(
"per_req,num_actual,padded_len",
[
([list(range(10)), list(range(12))], 22, 22),
([list(range(10)), list(range(12))], 22, 30),
([[3, 4], [0], [7, 8, 9]], 6, 8),
([[5]], 1, 1),
],
)
def test_triton_mapping_matches_cpu(per_req, num_actual, padded_len):
"""The CUDA (Triton) path must match the CPU torch reference, including
tokens between the last request boundary and num_actual_tokens (mapped to
the last request) and untouched padding beyond num_actual."""
positions, qsl, slot_mapping, _, num_reqs = make_batch(
per_req, padded_len=padded_len
)
# Replace the all--1 placeholder slots with sentinel values to check the
# padding range is copied through untouched.
slot_mapping = torch.arange(padded_len, dtype=torch.int64) + 1000
bt = make_tail_block_table(list(range(5, 5 + num_reqs)))
ref = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
got = circular_tail_slots(
slot_mapping.cuda(),
bt.cuda(),
qsl.cuda().to(torch.int32),
positions.cuda(),
num_actual,
num_reqs,
)
torch.testing.assert_close(got.cpu(), ref)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
def test_triton_mapping_reads_strided_block_table():
"""The kernel must address the block table through its real stride(0),
not a dense assumption (the #57477 class of bug): a tail block table that
is a column view of a wider allocation must still read column 0."""
per_req = [list(range(10)), list(range(12))]
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
own_blocks = [11, 22]
wide = torch.zeros(num_reqs, 8, dtype=torch.int32)
bt = wide[:, 1:4] # non-contiguous view, stride(0) == 8
bt[:, 0] = torch.tensor(own_blocks, dtype=torch.int32)
ref = circular_tail_slots(
slot_mapping, bt.contiguous(), qsl, positions, num_actual, num_reqs
)
got = circular_tail_slots(
slot_mapping.cuda(),
bt.cuda(),
qsl.cuda().to(torch.int32),
positions.cuda(),
num_actual,
num_reqs,
)
torch.testing.assert_close(got.cpu(), ref)
for req, blk in enumerate(own_blocks):
start, end = int(qsl[req]), int(qsl[req + 1])
assert (got[start:end] // KPOOL == blk).all()
@@ -4,6 +4,7 @@
import asyncio
import json
from math import lcm
from uuid import uuid4
import httpx
@@ -12,6 +13,7 @@ from openai.types.chat import ChatCompletionMessageParam
from prometheus_client.parser import text_string_to_metric_families
from tests.utils import RemoteOpenAIServer
from vllm.utils.math_utils import round_down
MODEL = "Qwen/Qwen3.5-0.8B"
NUM_CONVERSATIONS = 8
@@ -34,6 +36,29 @@ def _user_turns(conversation: int) -> list[str]:
]
async def _scheduler_block_size(client: httpx.AsyncClient) -> int:
"""Return the coarsest boundary an expected cache hit can land on.
Mirrors ``scheduler_block_size`` in ``resolve_kv_cache_block_sizes``, which
the engine keeps internal: the LCM of the resolved group block sizes. A
finer ``prefix_match_unit`` only adds hits, so this stays conservative.
"""
response = await client.get("/metrics")
response.raise_for_status()
for family in text_string_to_metric_families(response.text):
for sample in family.samples:
if sample.name != "vllm:cache_config_info":
continue
sizes = [
int(value)
for name in ("block_size", "mamba_block_size")
if (value := sample.labels.get(name, "None")) != "None"
]
assert sizes, f"no block size in {sample.labels}"
return lcm(*sizes)
raise AssertionError("missing vllm:cache_config_info metric")
async def _prefix_cache_counters(
client: httpx.AsyncClient,
) -> tuple[float, float]:
@@ -83,13 +108,13 @@ def server(request):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"server, min_hit_rate",
# MTP re-prefills an extra block; both floors reject one more missed block.
[pytest.param(False, 0.90, id="base"), pytest.param(True, 0.75, id="mtp")],
"server, dropped_blocks",
# MTP's prefill lookahead pollutes the tail block, so EAGLE drops one.
[pytest.param(False, 0, id="base"), pytest.param(True, 1, id="mtp")],
indirect=["server"],
)
async def test_prefix_cache_hit_rate(
server: RemoteOpenAIServer, min_hit_rate: float
server: RemoteOpenAIServer, dropped_blocks: int
) -> None:
# Isolate sessions so another conversation cannot hide a cache miss.
salts = [uuid4().hex for _ in range(NUM_CONVERSATIONS)]
@@ -102,6 +127,8 @@ async def test_prefix_cache_hit_rate(
server.get_async_client() as client,
httpx.AsyncClient(base_url=server.url_root, timeout=METRICS_TIMEOUT) as metrics,
):
block_size = await _scheduler_block_size(metrics)
print(f"{block_size=}")
async def run_conversation(session: int, *, replay: bool) -> tuple[int, int]:
history = histories[session]
@@ -126,15 +153,30 @@ async def test_prefix_cache_hit_rate(
assert cached is not None, context
assert 0 <= cached < prompt, context
assert prompt >= MIN_PROMPT_TOKENS, context
if not replay and turn == 0:
assert cached == 0, context
else:
assert cached / prompt >= min_hit_rate, (
f"{context}, {min_hit_rate=}"
)
if replay:
assert prompt == prompt_lengths[session][turn], context
# The identical request computed this whole prompt, but at
# least one token is always recomputed.
computed = prompt - 1
elif turn:
computed = prompt_lengths[session][turn - 1]
else:
assert cached == 0, context
computed = 0
# Every token below the last reachable boundary must be reused.
floor = max(
0, round_down(computed, block_size) - dropped_blocks * block_size
)
print(
f"{session=} {turn=} {replay=} {prompt=} {cached=} {floor=} "
f"hit_rate={cached / prompt:.4f}"
)
assert cached >= floor, (
f"{context}, {computed=}, {block_size=}, "
f"hit_rate={cached / prompt:.4f}, "
f"expected_hit_rate={floor / prompt:.4f}"
)
if not replay:
prompt_lengths[session].append(prompt)
history.append(
{
@@ -0,0 +1,279 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Routing and registration behaviour of the EPD proxy."""
import asyncio
from typing import Any
from unittest.mock import AsyncMock, Mock
import msgspec
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from examples.disaggregated.disaggregated_encoder import (
disagg_epd_proxy as proxy_module,
)
from examples.disaggregated.disaggregated_encoder.disagg_epd_proxy import (
EPDProxy,
EPDProxyConfig,
InstanceRecord,
InstanceRegistry,
InstanceRole,
build_app,
extract_mm_items,
)
ENCODE = InstanceRole.ENCODE
PREFILL = InstanceRole.PREFILL
DECODE = InstanceRole.DECODE
PD = InstanceRole.PREFILL_DECODE
IMAGE_ITEM = {"type": "image_url", "image_url": {"url": "http://img/0.png"}}
@pytest.fixture
def proxy():
registry = InstanceRegistry(probe_interval=0)
return EPDProxy(registry)
class TestRouting:
def test_no_decode_instance_is_service_unavailable(self, proxy):
"""The proxy comes up before anything registers, so this is normal."""
with pytest.raises(HTTPException) as excinfo:
proxy.route(num_items=0)
assert excinfo.value.status_code == 503
def test_media_without_an_encoder_is_service_unavailable(self, proxy):
proxy.registry.register(InstanceRecord(PD, "http://d0:8000"))
assert proxy.route(num_items=0).decode.url == "http://d0:8000"
with pytest.raises(HTTPException) as excinfo:
proxy.route(num_items=1)
assert excinfo.value.status_code == 503
def test_prefill_is_optional(self, proxy):
"""An E+PD deployment registers no prefill instance at all."""
proxy.registry.register(InstanceRecord(PD, "http://d0:8000"))
assert proxy.route(num_items=0).prefill is None
def test_encoder_roster_tracks_new_instances(self, proxy):
proxy.registry.register(InstanceRecord(PD, "http://d0:8000"))
for index in range(2):
proxy.registry.register(InstanceRecord(ENCODE, f"http://e{index}:8000"))
assert proxy.route(num_items=3).encoder_urls == [
"http://e0:8000",
"http://e1:8000",
]
proxy.registry.unregister("http://e0:8000")
assert proxy.route(num_items=3).encoder_urls == ["http://e1:8000"]
@pytest.mark.parametrize("unregister", [False, True])
def test_standalone_decode_always_requires_healthy_prefill(self, unregister):
app = build_app()
proxy = app.state.proxy
proxy.registry.register(InstanceRecord(DECODE, "http://d0:8000"))
with pytest.raises(HTTPException) as excinfo:
proxy.route(num_items=0)
assert excinfo.value.status_code == 503
proxy.registry.register(InstanceRecord(PREFILL, "http://p0:8000"))
route = proxy.route(num_items=0)
assert route.decode.url == "http://d0:8000"
assert route.consumer.url == "http://p0:8000"
if unregister:
proxy.registry.unregister("http://p0:8000")
else:
for _ in range(proxy.registry._fail_threshold):
proxy.registry._on_probe_failure(route.prefill, 0)
with pytest.raises(HTTPException) as excinfo:
proxy.route(num_items=0)
assert excinfo.value.status_code == 503
class TestConsumerAddress:
"""Which stage receives the embedding depends on the topology."""
def test_shared_storage_connectors_name_no_target(self, proxy):
"""Rotate replicas without requiring a push endpoint."""
proxy.registry.register(InstanceRecord(PD, "http://d0:8000", dp_size=2))
route = proxy.route(num_items=0)
assert route.consumer_zmq is None
assert route.dp_rank == 0
assert proxy.route(num_items=0).dp_rank == 1
def test_decode_is_the_consumer_when_prefill_is_not_split_out(self, proxy):
proxy.registry.register(
InstanceRecord(PD, "http://d0:8000", ec_zmq_addrs=["tcp://d0:20001"])
)
assert proxy.route(num_items=0).consumer_zmq == "tcp://d0:20001"
def test_prefill_is_the_consumer_when_it_is_split_out(self, proxy):
"""In E+P+D the prefill instance consumes the embedding, not decode.
Reading the address out of whichever list it came from -- rather than
from the record that reported one -- sends the push to the wrong
instance in this topology.
"""
proxy.registry.register(
InstanceRecord(PREFILL, "http://p0:8000", ec_zmq_addrs=["tcp://p0:20001"])
)
proxy.registry.register(InstanceRecord(DECODE, "http://d0:8000"))
assert proxy.route(num_items=0).consumer_zmq == "tcp://p0:20001"
class TestProxyApi:
@pytest.fixture
def client(self, monkeypatch):
monkeypatch.setenv("ADMIN_API_KEY", "test-key")
config = EPDProxyConfig(probe_interval=0)
with TestClient(build_app(config)) as client:
client.headers["X-API-Key"] = "test-key"
yield client
def test_proxy_serves_before_anything_registers(self, client):
assert client.get("/health").status_code == 200
assert client.get("/instances").json()["encode"]["live"] == []
def test_requests_are_refused_until_a_decoder_registers(self, client):
response = client.post(
"/v1/chat/completions", json={"model": "m", "messages": []}
)
assert response.status_code == 503
assert client.get("/v1/models").status_code == 503
def test_http_registration_keeps_consumer_replica_and_address_together(
self, client
):
payload: dict[str, Any] = {
"role": "prefill_decode",
"url": "http://d0:8000/",
"dp_size": 2,
"ec_zmq_addrs": ["tcp://d0:20001", "tcp://d0:20003"],
}
assert client.post("/instances", json=payload).json() == {"registered": True}
assert client.post("/instances", json=payload).json() == {"registered": False}
proxy = client.app.state.proxy
for rank in [0, 1, 0]:
route = proxy.route(0)
assert route.dp_rank == rank
assert route.consumer_zmq == payload["ec_zmq_addrs"][rank]
assert client.delete("/instances", params={"url": payload["url"]}).json() == {
"removed": True
}
assert proxy.registry.pick(PD) is None
def test_registration_rejects_invalid_topology(self, client):
cases: list[tuple[dict[str, Any], int]] = [
({"dp_size": 0}, 422),
({"dp_size": 2, "ec_zmq_addrs": ["tcp://d0:20001"]}, 422),
({"role": "decode", "ec_zmq_addrs": ["tcp://d0:20001"]}, 400),
({"role": "encode", "ec_zmq_addrs": ["tcp://d0:20001"]}, 400),
]
for fields, status in cases:
response = client.post(
"/instances",
json={"url": "http://d0:8000", "role": "prefill_decode", **fields},
)
assert response.status_code == status
def test_registration_requires_admin_key(self, client):
client.headers.pop("X-API-Key")
assert (
client.post(
"/instances", json={"role": "encode", "url": "http://e0:8000"}
).status_code
== 403
)
assert (
client.delete("/instances", params={"url": "http://e0:8000"}).status_code
== 403
)
@pytest.mark.parametrize("split_role", ["prefill", "decode"])
@pytest.mark.parametrize("combined_first", [False, True])
def test_registration_rejects_mixed_topologies(
self, client, split_role, combined_first
):
roles = ["prefill_decode", split_role]
if not combined_first:
roles.reverse()
first = {"role": roles[0], "url": "http://first:8000"}
second = {"role": roles[1], "url": "http://second:8000"}
assert client.post("/instances", json=first).status_code == 200
assert client.post("/instances", json=second).status_code == 409
# Health eviction must not silently permit a topology switch.
registry = client.app.state.registry
record = registry._live[first["url"]]
for _ in range(registry._fail_threshold):
registry._on_probe_failure(record, 0)
assert client.post("/instances", json=second).status_code == 409
assert client.delete("/instances", params={"url": first["url"]}).json() == {
"removed": True
}
assert client.post("/instances", json=second).status_code == 200
def test_extract_mm_items_finds_media_across_messages():
req = {
"messages": [
{"role": "user", "content": "plain text"},
{"role": "user", "content": [IMAGE_ITEM, {"type": "text", "text": "hi"}]},
{"role": "user", "content": [IMAGE_ITEM]},
]
}
assert extract_mm_items(req) == [IMAGE_ITEM, IMAGE_ITEM]
@pytest.mark.parametrize("push", [False, True])
def test_encoder_handles_and_json_metadata_survive_rewrite(proxy, push, monkeypatch):
"""Keep main's hash-keyed handles and per-item push IDs after the proxy move."""
proxy.registry.register(InstanceRecord(ENCODE, "http://encoder"))
proxy.registry.register(
InstanceRecord(
PD,
"http://decode",
ec_zmq_addrs=["tcp://decode:14579"] if push else [],
)
)
handle = {
"metadata": {"image_grid_thw": [[1, 2, 3]]},
"item_indices": [0, 1],
"peer_port": 5601,
}
response = Mock(
status=200,
read=AsyncMock(
return_value=msgspec.json.encode(
{"ec_transfer_params": {"engine-hash": handle}}
)
),
)
session = Mock(post=AsyncMock(return_value=response))
monkeypatch.setattr(proxy_module, "encode_session", session)
original = {"messages": [{"role": "user", "content": [IMAGE_ITEM, IMAGE_ITEM]}]}
route = proxy.route(2)
prepared, _, _ = asyncio.run(
proxy_module.prepare_for_decode(
original, "request", route.encoder_urls, None, route.consumer_zmq
)
)
assert "ec_transfer_params" not in original
assert prepared["ec_transfer_params"]["engine-hash"] == handle
items = prepared["ec_transfer_params"]["ec_items"]
assert [item["mm_hash"] for item in items] == ["engine-hash", "engine-hash"]
assert items[0]["transfer_id"] != items[1]["transfer_id"]
assert session.post.call_count == 1
sent = msgspec.json.decode(session.post.call_args.kwargs["data"]).get(
"ec_transfer_params"
)
if push:
assert sent == {
"consumer_zmq": "tcp://decode:14579",
"ec_items": [{"transfer_id": item["transfer_id"]} for item in items],
}
else:
assert sent is None
for index in range(2):
assert prepared["messages"][0]["content"][index]["image_embeds"] == {
"image_grid_thw": [1, 2, 3]
}
@@ -8,6 +8,7 @@ change to them is what these tests catch.
import asyncio
import importlib.util
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -27,6 +28,7 @@ def proxy():
spec = importlib.util.spec_from_file_location("disagg_epd_proxy_retry", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
@@ -48,7 +50,7 @@ def test_maybe_prefill_leaves_the_caller_body_untouched(proxy, monkeypatch):
"""
served = [{"remote_block_ids": [1, 2]}, {}]
async def _stage(req_data, p_url, req_id):
async def _stage(req_data, p_url, req_id, dp_rank=None):
assert "kv_transfer_params" not in req_data
return _Response(served.pop(0))
@@ -222,7 +224,7 @@ def test_a_decode_retry_does_not_inherit_the_previous_handles(proxy, monkeypatch
_EncoderSession([{"encoder-side-hash": handle}, {}]),
)
async def _no_prefill(req_data, p_url, req_id):
async def _no_prefill(req_data, p_url, req_id, dp_rank=None):
return req_data
monkeypatch.setattr(proxy, "maybe_prefill", _no_prefill)
@@ -280,6 +282,7 @@ def test_raw_media_keeps_encoder_transfer_identity(proxy, monkeypatch):
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("prefill", [False, True])
@pytest.mark.parametrize("dynamic", [False, True])
@pytest.mark.parametrize(
"request_options",
[
@@ -293,7 +296,7 @@ def test_raw_media_keeps_encoder_transfer_identity(proxy, monkeypatch):
],
)
async def test_http_roundtrip_preserves_payload_and_response_bytes(
proxy, monkeypatch, stream, prefill, request_options
proxy, monkeypatch, stream, prefill, dynamic, request_options
):
"""Preserve media and scheduling context across HTTP hops and retries."""
seen: dict[str, list[dict]] = {"encode": [], "prefill": [], "decode": []}
@@ -307,6 +310,10 @@ async def test_http_roundtrip_preserves_payload_and_response_bytes(
async def backend(request):
stage = request.match_info["stage"]
if dynamic:
consumer = "prefill" if prefill else "decode"
expected_rank = "0" if stage == consumer else None
assert request.headers.get("X-data-parallel-rank") == expected_rank
assert request.content_type == "application/json"
body = await request.json()
seen[stage].append(body)
@@ -354,6 +361,10 @@ async def test_http_roundtrip_preserves_payload_and_response_bytes(
monkeypatch.setattr(proxy.app.state, "ec_consumer_dp_size", 1, raising=False)
monkeypatch.setattr(proxy, "DECODE_RETRIES", 1)
monkeypatch.setattr(proxy, "NO_REWRITE", False)
target_app = proxy.app
if dynamic:
monkeypatch.setenv("ADMIN_API_KEY", "test-key")
target_app = proxy.build_app(proxy.EPDProxyConfig(probe_interval=0))
item = {"type": "image_url", "image_url": {"url": "data:image/png;base64,YWJj"}}
body = {
"model": "test",
@@ -377,9 +388,37 @@ async def test_http_roundtrip_preserves_payload_and_response_bytes(
await proxy.on_startup()
try:
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=proxy.app), base_url="http://proxy"
transport=httpx.ASGITransport(app=target_app), base_url="http://proxy"
) as client:
if dynamic:
registrations = [("encode", "encode")]
registrations += (
[("prefill", "prefill"), ("decode", "decode")]
if prefill
else [("prefill_decode", "decode")]
)
for role, stage in registrations:
consumer = "prefill" if prefill else "decode"
registered = await client.post(
"/instances",
headers={"X-API-Key": "test-key"},
json={
"role": role,
"url": str(server.make_url(f"/{stage}")),
"dp_size": 2 if stage == consumer else 1,
},
)
assert registered.status_code == 200
response = await client.post("/v1/chat/completions", json=body)
if dynamic:
removed = await client.delete(
"/instances",
headers={"X-API-Key": "test-key"},
params={"url": str(server.make_url("/decode"))},
)
assert removed.json() == {"removed": True}
unavailable = await client.post("/v1/chat/completions", json=body)
assert unavailable.status_code == 503
assert response.status_code == 200
assert response.content == expected
assert response.headers["content-type"].startswith(
@@ -14,6 +14,7 @@ across calls so consecutive requests keep advancing through every URL.
"""
import importlib.util
import sys
from collections import Counter
from pathlib import Path
@@ -27,6 +28,7 @@ def _load_proxy_module():
spec = importlib.util.spec_from_file_location("disagg_epd_proxy_under_test", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
@@ -0,0 +1,156 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Dynamic registration and liveness for the EPD proxy's instance registry."""
from unittest.mock import patch
import pytest
from examples.disaggregated.disaggregated_encoder.disagg_epd_proxy import (
InstanceRecord,
InstanceRegistry,
InstanceRole,
)
ENCODE = InstanceRole.ENCODE
DECODE = InstanceRole.DECODE
@pytest.fixture
def registry():
return InstanceRegistry(probe_interval=0, fail_threshold=3, evicted_ttl=60.0)
def _fill(registry, role, count, prefix="http://h"):
for index in range(count):
registry.register(InstanceRecord(role, f"{prefix}{index}:8000"))
async def _probe_round(registry, healthy: set[str], now: float = 0.0):
"""Run one probe pass where only `healthy` URLs answer."""
async def fake_probe(self, session, url):
return url in healthy
with (
patch.object(InstanceRegistry, "_probe", fake_probe),
patch(
"examples.disaggregated.disaggregated_encoder.disagg_epd_proxy.time.monotonic",
return_value=now,
),
):
await registry._probe_once(session=None)
class TestRegistration:
def test_registering_is_idempotent_and_reports_novelty(self, registry):
record = InstanceRecord(ENCODE, "http://e0:8000")
assert registry.register(record) is True
assert registry.register(record) is False
assert registry.urls(ENCODE) == ["http://e0:8000"]
def test_transfer_addresses_stay_with_the_registered_consumer(self, registry):
"""Roster updates must not shift a consumer's transfer addresses."""
registry.register(InstanceRecord(DECODE, "http://d0:8000"))
registry.register(
InstanceRecord(
DECODE,
"http://d0:8000",
ec_zmq_addrs=["tcp://d0:20001", "tcp://d0:20002"],
dp_size=2,
)
)
picked = registry.pick(DECODE)
assert picked.ec_zmq_addrs == ["tcp://d0:20001", "tcp://d0:20002"]
assert picked.dp_size == 2
def test_unregister_is_terminal(self, registry):
registry.register(InstanceRecord(ENCODE, "http://e0:8000"))
assert registry.unregister("http://e0:8000") is True
assert registry.unregister("http://e0:8000") is False
assert registry.pick(ENCODE) is None
def test_round_robin_survives_registration(self, registry):
_fill(registry, ENCODE, 2)
assert [record.url for record in registry.pick_many(ENCODE, 2)] == [
"http://h0:8000",
"http://h1:8000",
]
registry.register(InstanceRecord(ENCODE, "http://h2:8000"))
assert registry.pick(ENCODE).url == "http://h2:8000"
class TestLiveness:
@pytest.mark.asyncio
async def test_identical_reregistration_preserves_inflight_probe_results(
self, registry
):
"""Repeated registrations must not suppress eviction or recovery."""
url = "http://e0:8000"
registry.register(InstanceRecord(ENCODE, url))
healthy = False
async def probe(self, session, url):
registry.register(InstanceRecord(ENCODE, url))
return healthy
with patch.object(InstanceRegistry, "_probe", probe):
for _ in range(registry._fail_threshold):
await registry._probe_once(None)
assert registry.status()["encode"] == {"live": [], "evicted": [url]}
healthy = True
await registry._probe_once(None)
assert registry.status()["encode"] == {"live": [url], "evicted": []}
@pytest.mark.asyncio
async def test_consecutive_failures_stop_routing(self, registry):
registry.register(InstanceRecord(ENCODE, "http://e0:8000"))
registry.register(InstanceRecord(ENCODE, "http://e1:8000"))
for _ in range(registry._fail_threshold):
await _probe_round(registry, healthy={"http://e1:8000"})
assert registry.urls(ENCODE) == ["http://e1:8000"]
assert registry.status()["encode"]["evicted"] == ["http://e0:8000"]
@pytest.mark.asyncio
@pytest.mark.parametrize("role", [ENCODE, DECODE])
async def test_a_recovered_instance_rejoins_without_re_registering(
self, registry, role
):
"""Restarting every encoder to recover from a blip is not acceptable."""
registry.register(InstanceRecord(role, "http://e0:8000"))
for _ in range(registry._fail_threshold):
await _probe_round(registry, healthy=set())
assert registry.urls(role) == []
await _probe_round(registry, healthy={"http://e0:8000"}, now=1)
assert registry.urls(role) == ["http://e0:8000"]
@pytest.mark.asyncio
async def test_re_registration_does_not_override_failed_health_checks(
self, registry
):
record = InstanceRecord(ENCODE, "http://e0:8000")
registry.register(record)
for _ in range(registry._fail_threshold):
await _probe_round(registry, healthy=set())
registry.register(record)
assert registry.urls(ENCODE) == []
@pytest.mark.asyncio
@pytest.mark.parametrize("healthy", [False, True])
async def test_inflight_probe_cannot_restore_unregistered_instance(
self, registry, healthy
):
record = InstanceRecord(ENCODE, "http://e0:8000")
registry.register(record)
for _ in range(registry._fail_threshold):
await _probe_round(registry, healthy=set())
async def probe(self, session, url):
registry.unregister(url)
return healthy
with patch.object(InstanceRegistry, "_probe", probe):
await registry._probe_once(None)
assert registry.status()["encode"] == {"live": [], "evicted": []}
@@ -19,8 +19,10 @@ from tests.v1.simple_kv_offload.test_scheduler import (
SchedulerFixture,
_alloc_and_register,
_allocate_cp_gpu_blocks,
_allocate_gpu_blocks,
_make_cp_request,
_make_kv_cache_config,
_make_scratch_kv_cache_config,
_make_vllm_config,
make_request,
make_scheduler_output,
@@ -757,3 +759,37 @@ def test_mamba_align_skips_positional_event_metadata() -> None:
get_block_hash(make_block_hash_with_group_id(req.block_hashes[idx], 0))
)
assert ev.block_hashes == [expected_hash]
def test_scratch_group_store_emits_events_for_cacheable_groups_only() -> None:
"""Event metadata is resolved only for prefix-cacheable groups.
A scratch group (GLM-5.3-Flash kpool tail) has a block size that does not
divide the hash block size, so viewing the request hashes at its block
size is impossible; the store must skip it and still emit BlockStored
for the attention blocks.
"""
fix = make_events_scheduler(kv_cache_config=_make_scratch_kv_cache_config(16))
sched = fix.scheduler
gpu_pool = fix.gpu_block_pool
num_blocks = 2
req = make_request(num_blocks=num_blocks)
fa_blocks = _allocate_gpu_blocks(gpu_pool, req, num_blocks, group_id=0)
scratch_block = gpu_pool.get_new_blocks(1)
kv_blocks = KVCacheBlocks(blocks=(fa_blocks, scratch_block))
req.num_computed_tokens = num_blocks * BLOCK_SIZE
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
sched_out = make_scheduler_output(
{req.request_id: num_blocks * BLOCK_SIZE},
new_reqs={req.request_id: kv_blocks.get_block_ids()},
)
meta = sched.build_connector_meta(sched_out)
assert sorted(meta.store_gpu_blocks) == sorted(b.block_id for b in fa_blocks)
simulate_store_completion(sched, meta.store_event)
events = list(sched.take_events())
assert len(events) == num_blocks
assert all(isinstance(e, BlockStored) for e in events)
assert {e.group_idx for e in events} == {0}
assert all(len(e.token_ids) == BLOCK_SIZE for e in events)
+222 -1
View File
@@ -41,7 +41,9 @@ from vllm.v1.core.single_type_kv_cache_manager import (
register_all_kvcache_specs,
)
from vllm.v1.kv_cache_interface import (
CircularBufferSpec,
FullAttentionSpec,
KpoolTailSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheTensor,
@@ -125,6 +127,45 @@ def _make_kv_cache_config(
)
def _make_scratch_kv_cache_config(
num_blocks: int, scratch_block_size: int = 4
) -> KVCacheConfig:
"""FullAttention group plus a non-prefix-cacheable scratch group.
Mirrors GLM-5.3-Flash, whose kpool-tail group holds one per-request
scratch block of ``index_kpool`` tokens: it is excluded from prefix
caching, so its block size neither divides nor is divided by the
hash block size in general.
"""
register_all_kvcache_specs(vllm_config=None)
fa_config = _make_kv_cache_config(num_blocks, num_groups=1)
scratch_layers = ["layer_scratch"]
scratch_spec = KpoolTailSpec(
block_size=scratch_block_size,
num_kv_heads=2,
head_size=HEAD_SIZE,
head_size_v=0,
dtype=DTYPE,
sliding_window=scratch_block_size,
)
assert not scratch_spec.prefix_cacheable
scratch_bytes = scratch_spec.page_size_bytes * num_blocks
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=fa_config.kv_cache_tensors
+ [
KVCacheTensor(
size=scratch_bytes,
layers=scratch_layers,
layer_stride=scratch_bytes,
block_stride=scratch_spec.page_size_bytes,
)
],
kv_cache_groups=fa_config.kv_cache_groups
+ [KVCacheGroupSpec(scratch_layers, scratch_spec)],
)
def _make_vllm_config(block_size: int = BLOCK_SIZE) -> VllmConfig:
"""Minimal VllmConfig for scheduler tests (no GPU)."""
model_config = ModelConfig(
@@ -174,9 +215,13 @@ def make_scheduler(
num_gpu_blocks: int = 16,
num_groups: int = 1,
lazy: bool = False,
kv_cache_config: KVCacheConfig | None = None,
) -> SchedulerFixture:
"""Build a SimpleCPUOffloadScheduler with small block pools."""
kv_cache_config = _make_kv_cache_config(num_gpu_blocks, num_groups)
if kv_cache_config is None:
kv_cache_config = _make_kv_cache_config(num_gpu_blocks, num_groups)
else:
num_groups = len(kv_cache_config.kv_cache_groups)
vllm_config = _make_vllm_config()
cpu_capacity_bytes = _BYTES_PER_BLOCK * num_cpu_blocks * num_groups
@@ -1392,6 +1437,63 @@ def test_multi_group_null_blocks_skipped() -> None:
)
# ---------------------------------------------------------------------------
# Test 8b: Non-prefix-cacheable scratch groups take no part in store or load
# ---------------------------------------------------------------------------
def test_scratch_group_excluded_from_store_and_load() -> None:
"""A scratch group (GLM-5.3-Flash kpool tail) is never stored or loaded.
Its single per-request block carries no hash, so the store must offload
only the attention blocks and the load must pair only attention blocks.
"""
fix = make_scheduler(
num_cpu_blocks=8,
num_gpu_blocks=16,
kv_cache_config=_make_scratch_kv_cache_config(16),
)
sched = fix.scheduler
gpu_pool = fix.gpu_block_pool
num_blocks = 2
req = make_request(num_blocks=num_blocks)
fa_blocks = _allocate_gpu_blocks(gpu_pool, req, num_blocks, group_id=0)
scratch_block = gpu_pool.get_new_blocks(1)
kv_blocks = KVCacheBlocks(blocks=(fa_blocks, scratch_block))
req.num_computed_tokens = num_blocks * BLOCK_SIZE
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
sched_out = make_scheduler_output(
{req.request_id: num_blocks * BLOCK_SIZE},
new_reqs={req.request_id: kv_blocks.get_block_ids()},
)
meta = sched.build_connector_meta(sched_out)
assert sorted(meta.store_gpu_blocks) == sorted(b.block_id for b in fa_blocks)
simulate_store_completion(sched, meta.store_event)
req2 = Request(
request_id="req-scratch-load",
prompt_token_ids=req.prompt_token_ids,
sampling_params=req.sampling_params,
pooling_params=None,
mm_features=None,
block_hasher=req._block_hasher,
)
hit_tokens, is_async = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens == num_blocks * BLOCK_SIZE
assert is_async is True
fa_blocks2 = gpu_pool.get_new_blocks(num_blocks)
scratch_block2 = gpu_pool.get_new_blocks(1)
kv_blocks2 = KVCacheBlocks(blocks=(fa_blocks2, scratch_block2))
sched.update_state_after_alloc(req2, kv_blocks2, num_external_tokens=hit_tokens)
sched_out2 = make_scheduler_output(
{req2.request_id: 1},
new_reqs={req2.request_id: kv_blocks2.get_block_ids()},
)
meta2 = sched.build_connector_meta(sched_out2)
assert sorted(meta2.load_gpu_blocks) == sorted(b.block_id for b in fa_blocks2)
assert len(meta2.load_cpu_blocks) == num_blocks
# ---------------------------------------------------------------------------
# Test 9: Chunked prefill accumulates block_ids across steps
# ---------------------------------------------------------------------------
@@ -2844,3 +2946,122 @@ def test_finished_eager_store_recovers_nulled_window_tail() -> None:
hit_tokens, is_async = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens == num_blocks * BLOCK_SIZE
assert is_async is True
QSA_RING_BLOCK_SIZE = 4
def _make_qsa_hybrid_kv_cache_config(num_blocks: int) -> KVCacheConfig:
register_all_kvcache_specs(vllm_config=None)
full_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=NUM_KV_HEADS,
head_size=HEAD_SIZE,
dtype=DTYPE,
)
ring_spec = CircularBufferSpec(
block_size=QSA_RING_BLOCK_SIZE,
num_kv_heads=NUM_KV_HEADS,
head_size=HEAD_SIZE,
head_size_v=0,
dtype=DTYPE,
)
groups = [
KVCacheGroupSpec(["layer_0"], full_spec),
KVCacheGroupSpec(["qsa_ring"], ring_spec),
]
tensors = [
KVCacheTensor(
size=group.kv_cache_spec.page_size_bytes * num_blocks,
layers=list(group.layer_names),
layer_stride=group.kv_cache_spec.page_size_bytes * num_blocks,
block_stride=group.kv_cache_spec.page_size_bytes,
)
for group in groups
]
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=tensors,
kv_cache_groups=groups,
)
def _make_qsa_scheduler(
lazy: bool = False,
) -> tuple[SimpleCPUOffloadScheduler, BlockPool]:
kv_cache_config = _make_qsa_hybrid_kv_cache_config(num_blocks=16)
sched = SimpleCPUOffloadScheduler(
vllm_config=_make_vllm_config(),
kv_cache_config=kv_cache_config,
cpu_capacity_bytes=_BYTES_PER_BLOCK * 8 * 2,
scheduler_block_size=BLOCK_SIZE,
hash_block_size=BLOCK_SIZE,
lazy_offload=lazy,
)
gpu_pool = BlockPool(
num_gpu_blocks=16, enable_caching=True, hash_block_size=BLOCK_SIZE
)
sched.bind_gpu_block_pool(gpu_pool)
return sched, gpu_pool
def test_qsa_ring_group_is_never_stored_or_loaded() -> None:
sched, gpu_pool = _make_qsa_scheduler()
assert sched.prefix_cacheable_group_ids == (0,)
num_blocks = 2
req = make_request(num_blocks=num_blocks)
fa_blocks = _allocate_gpu_blocks(gpu_pool, req, num_blocks, group_id=0)
ring_block = gpu_pool.get_new_blocks(1)[0]
kv_blocks = KVCacheBlocks(blocks=(fa_blocks, [ring_block]))
req.num_computed_tokens = num_blocks * BLOCK_SIZE
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
sched_out = make_scheduler_output(
{req.request_id: num_blocks * BLOCK_SIZE},
new_reqs={req.request_id: kv_blocks.get_block_ids()},
)
meta = sched.build_connector_meta(sched_out)
assert set(meta.store_gpu_blocks) == {block.block_id for block in fa_blocks}
assert ring_block.block_id not in meta.store_gpu_blocks
assert meta.store_event >= 0
simulate_store_completion(sched, meta.store_event)
req2 = Request(
request_id="req-qsa-load",
prompt_token_ids=req.prompt_token_ids,
sampling_params=req.sampling_params,
pooling_params=None,
mm_features=None,
block_hasher=req._block_hasher,
)
hit_tokens, is_async = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens == num_blocks * BLOCK_SIZE
assert is_async is True
fa_blocks2 = gpu_pool.get_new_blocks(num_blocks)
ring_block2 = gpu_pool.get_new_blocks(1)[0]
kv_blocks2 = KVCacheBlocks(blocks=(fa_blocks2, [ring_block2]))
sched.update_state_after_alloc(req2, kv_blocks2, num_external_tokens=hit_tokens)
meta2 = sched.build_connector_meta(make_scheduler_output({req2.request_id: 1}))
assert set(meta2.load_gpu_blocks) == {block.block_id for block in fa_blocks2}
assert ring_block2.block_id not in meta2.load_gpu_blocks
assert len(meta2.load_cpu_blocks) == num_blocks
def test_lazy_target_blocks_ignore_non_prefix_cacheable_groups() -> None:
with_ring = _make_qsa_hybrid_kv_cache_config(num_blocks=16)
without_ring = KVCacheConfig(
num_blocks=16,
kv_cache_tensors=with_ring.kv_cache_tensors[:1],
kv_cache_groups=with_ring.kv_cache_groups[:1],
)
max_batched = 64
target_with = SimpleCPUOffloadScheduler._estimate_lazy_target_blocks(
with_ring, max_batched
)
target_without = SimpleCPUOffloadScheduler._estimate_lazy_target_blocks(
without_ring, max_batched
)
assert target_with == target_without
+63
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import cast
from unittest.mock import Mock
import pytest
import torch
@@ -124,3 +125,65 @@ def test_workspace_lane_validation(monkeypatch) -> None:
with pytest.raises(ValueError, match="at least one"):
workspace.WorkspaceManager(torch.device("cpu"), num_lanes=0)
def test_persistent_resources_are_lazy_and_isolated(monkeypatch) -> None:
"""Only the requesting slot allocates; each ubatch/lane owns its resource."""
active_ubatch = 0
monkeypatch.setattr(workspace, "dbo_current_ubatch_id", lambda: active_ubatch)
manager = workspace.WorkspaceManager(
torch.device("cpu"), num_ubatches=2, num_lanes=2
)
factory = Mock(side_effect=lambda: {"buffer": torch.zeros(8)})
resources = []
for ubatch in range(2):
active_ubatch = ubatch
for lane in range(2):
with workspace.use_workspace_lane(lane):
resource = manager.get_persistent_resource("scratch", factory)
resources.append(resource)
resource["buffer"].fill_(len(resources))
assert manager.get_persistent_resource("scratch", factory) is resource
assert factory.call_count == len(resources)
assert len({r["buffer"].data_ptr() for r in resources}) == 4
for i, resource in enumerate(resources, 1):
assert torch.all(resource["buffer"] == i)
def test_persistent_resource_lock_applies_to_each_slot(monkeypatch) -> None:
monkeypatch.setattr(workspace, "dbo_current_ubatch_id", lambda: 0)
manager = workspace.WorkspaceManager(torch.device("cpu"), num_lanes=2)
factory = Mock(side_effect=object)
first = manager.get_persistent_resource("scratch", factory)
manager.lock()
assert manager.get_persistent_resource("scratch", factory) is first
with pytest.raises(AssertionError, match="was not allocated during warmup"):
manager.get_persistent_resource("new", factory)
with workspace.use_workspace_lane(1):
with pytest.raises(AssertionError, match="was not allocated during warmup"):
manager.get_persistent_resource("scratch", factory)
assert factory.call_count == 1
manager.unlock()
assert manager.get_persistent_resource("scratch", factory) is not first
assert manager.get_persistent_resource("scratch", factory) is first
def test_persistent_tensor_preserves_contents_and_rejects_changes() -> None:
"""Initialization happens once and transient scratch cannot overwrite locks."""
manager = workspace.WorkspaceManager(torch.device("cpu"))
first = manager.get_persistent("locks", (8,), torch.int32, zero_init=True)
assert torch.count_nonzero(first) == 0
first.fill_(1)
(scratch,) = manager.get_simultaneous(((1024,), torch.uint8))
scratch.zero_()
assert manager.get_persistent("locks", (8,), torch.int32, zero_init=True) is first
assert torch.all(first == 1)
with pytest.raises(ValueError, match="requested shape"):
manager.get_persistent("locks", (16,), torch.int32)
with pytest.raises(ValueError, match="requested shape"):
manager.get_persistent("locks", (8,), torch.int64)
manager.lock()
assert manager.get_persistent("locks", (8,), torch.int32) is first
with pytest.raises(AssertionError, match="was not allocated during warmup"):
manager.get_persistent("new", (8,), torch.int32)