[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests
- Drop dead model modules, keeping files live imports require - Remove anthropic, cohere, codegen entrypoints and batch STT modes - Delete unused attention backends, MoE experts, and NPU/XPU util leaves - Strip dead third_party trees and ROCm leaves with no CUDA path - Remove mooncake EC connectors: dependency missing since branch base - Re-audit verified by full import sweep and Qwen3.5 smoke test Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,205 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.utils import make_local_attention_virtual_batches
|
||||
|
||||
|
||||
@dataclass
|
||||
class LocalAttentionTestData:
|
||||
# Input parameters
|
||||
batch_spec: BatchSpec
|
||||
attn_chunk_size: int
|
||||
block_size: int
|
||||
# Expected return values
|
||||
expected_q_seqlens: list[int]
|
||||
expected_k_seqlens: list[int]
|
||||
expected_local_block_table: list[list[int]]
|
||||
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
test_data_list = [
|
||||
# Same as example in docstring of make_local_attention_virtual_batches
|
||||
# except block table has 9 columns instead of 10
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[4, 10, 5],
|
||||
seq_lens=[6, 17, 9],
|
||||
),
|
||||
attn_chunk_size=4,
|
||||
block_size=2,
|
||||
expected_q_seqlens=[2, 2, 1, 4, 4, 1, 4, 1],
|
||||
expected_k_seqlens=[4, 2, 4, 4, 4, 1, 4, 1],
|
||||
# 2 pages per local branch
|
||||
# (chunk size 4 // block size 2)
|
||||
expected_local_block_table=[
|
||||
[0, 1], # local-batch 0, (batch 0, starting from k[0])
|
||||
[2, 3], # local-batch 1, (batch 0, starting from k[4])
|
||||
[11, 12], # local-batch 2, (batch 1, starting from k[4])
|
||||
[13, 14], # local-batch 3, (batch 1, starting from k[8])
|
||||
[15, 16], # local-batch 4, (batch 1, starting from k[12])
|
||||
[17, 17], # local-batch 5, (batch 1, starting from k[16])
|
||||
[20, 21], # local-batch 6, (batch 2, starting from k[4])
|
||||
[22, 23], # local-batch 7, (batch 2, starting from k[8])
|
||||
],
|
||||
),
|
||||
# Case where block indices are not clipped to block table ncols-1
|
||||
# because tokens_in_last_block == attn_chunk_size
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[8],
|
||||
seq_lens=[12],
|
||||
),
|
||||
attn_chunk_size=4,
|
||||
block_size=2,
|
||||
expected_q_seqlens=[4, 4],
|
||||
expected_k_seqlens=[4, 4],
|
||||
expected_local_block_table=[
|
||||
[2, 3],
|
||||
[4, 5],
|
||||
],
|
||||
),
|
||||
# Case where all kv_seq positions are involved in attn
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[7],
|
||||
# 10 - 7 = 3 previously computed tokens
|
||||
seq_lens=[10],
|
||||
),
|
||||
attn_chunk_size=4,
|
||||
block_size=2,
|
||||
expected_q_seqlens=[1, 4, 2],
|
||||
expected_k_seqlens=[4, 4, 2],
|
||||
expected_local_block_table=[
|
||||
[0, 1],
|
||||
[2, 3],
|
||||
[4, 4],
|
||||
],
|
||||
),
|
||||
# Case where attn_chunk_size > kv_seq_len
|
||||
# so no extra mini virtual batches are created
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[4],
|
||||
seq_lens=[6],
|
||||
),
|
||||
# Larger than kv_seq_len
|
||||
attn_chunk_size=10,
|
||||
block_size=2,
|
||||
# No change to q_seqlens and k_seqlens
|
||||
expected_q_seqlens=[4],
|
||||
expected_k_seqlens=[6],
|
||||
# In this case, we only need a block-table like:
|
||||
# block_table = [ [0, 1, 2] ] # 1 batch, 3 pages
|
||||
# But we need to pad it to 5 pages per local batch
|
||||
# because currently the pages_per_local_batch
|
||||
# is calculated as (attn_chunk_size // block_size)
|
||||
expected_local_block_table=[
|
||||
[0, 1, 2, 2, 2],
|
||||
],
|
||||
),
|
||||
# Block size equal to chunk size
|
||||
# Expect single page per batch in local batch table
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[6, 6],
|
||||
seq_lens=[8, 8],
|
||||
),
|
||||
attn_chunk_size=4,
|
||||
block_size=4,
|
||||
expected_q_seqlens=[2, 4, 2, 4],
|
||||
expected_k_seqlens=[4, 4, 4, 4],
|
||||
# Initial block table = [
|
||||
# [0, 1], < batch 0
|
||||
# [2, 3], < batch 1
|
||||
# ]
|
||||
expected_local_block_table=[
|
||||
[0], # local-batch 0, (batch 0, starting from k[0])
|
||||
[1], # local-batch 1, (batch 0, starting from k[4])
|
||||
[2], # local-batch 1, (batch 0, starting from k[0])
|
||||
[3], # local-batch 1, (batch 0, starting from k[4])
|
||||
],
|
||||
),
|
||||
# Case where query falls in the second attention chunk
|
||||
# k_toks > 0 1 2 3 4
|
||||
# q_toks v _____________
|
||||
# 0 | 1
|
||||
# 1 | 1 1
|
||||
# 2 | 1 1 1
|
||||
# 3 | 1 1 1 1
|
||||
# 4 | 1
|
||||
# where tokens 0,1,2,3 have been pre-computed
|
||||
LocalAttentionTestData(
|
||||
batch_spec=BatchSpec(
|
||||
query_lens=[1],
|
||||
seq_lens=[5],
|
||||
),
|
||||
attn_chunk_size=4,
|
||||
block_size=2,
|
||||
expected_q_seqlens=[1],
|
||||
expected_k_seqlens=[1],
|
||||
expected_local_block_table=[
|
||||
[2, 2],
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("test_data", test_data_list)
|
||||
def test_local_attention_virtual_batches(test_data: LocalAttentionTestData):
|
||||
device = torch.device(f"{DEVICE_TYPE}:0")
|
||||
batch_spec = test_data.batch_spec
|
||||
attn_chunk_size = test_data.attn_chunk_size
|
||||
block_size = test_data.block_size
|
||||
expected_q_seqlens = test_data.expected_q_seqlens
|
||||
expected_k_seqlens = test_data.expected_k_seqlens
|
||||
expected_local_block_table = test_data.expected_local_block_table
|
||||
|
||||
# Create common attention metadata
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch_spec,
|
||||
block_size,
|
||||
device,
|
||||
# Use torch.arange instead of torch.randint so we can assert on
|
||||
# block table tensor values. The block table will have shape
|
||||
# (num_batches, cdiv(max_seq_len, block_size)) and the values will be
|
||||
# arranged from 0 to cdiv(max_seq_len, block_size)-1
|
||||
arange_block_indices=True,
|
||||
)
|
||||
|
||||
# Call the function
|
||||
result, _ = make_local_attention_virtual_batches(
|
||||
attn_chunk_size, common_attn_metadata, block_size
|
||||
)
|
||||
|
||||
# Convert to numpy for easier comparison
|
||||
actual_q_seqlens = np.diff(result.query_start_loc_cpu.numpy())
|
||||
assert result.seq_lens_cpu_upper_bound is not None
|
||||
actual_k_seqlens = result.seq_lens_cpu_upper_bound.numpy()
|
||||
|
||||
# Check that all query lengths are less than or equal to attn_chunk_size
|
||||
assert all(q_len <= attn_chunk_size for q_len in actual_q_seqlens)
|
||||
# Check that all key lengths are less than or equal to attn_chunk_size
|
||||
assert all(k_len <= attn_chunk_size for k_len in actual_k_seqlens)
|
||||
# Check that the total number of query tokens is preserved
|
||||
assert sum(actual_q_seqlens) == sum(batch_spec.query_lens)
|
||||
|
||||
# Verify results
|
||||
np.testing.assert_array_equal(actual_q_seqlens, expected_q_seqlens)
|
||||
np.testing.assert_array_equal(actual_k_seqlens, expected_k_seqlens)
|
||||
|
||||
expected_block_table_tensor = torch.tensor(
|
||||
expected_local_block_table, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
print(f"Expected block table:\n{expected_block_table_tensor}")
|
||||
print(f"Actual block table:\n{result.block_table_tensor}")
|
||||
|
||||
torch.testing.assert_close(result.block_table_tensor, expected_block_table_tensor)
|
||||
@@ -1,146 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for CUDA attention backend selection and probe error handling.
|
||||
|
||||
Environment-shaped probe failures (missing packages, unreadable caches,
|
||||
broken driver installs) must mark the backend unavailable rather than
|
||||
terminating engine init; programming errors must still propagate.
|
||||
See https://github.com/vllm-project/vllm/issues/51658.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.cuda import CudaPlatform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.selector import AttentionSelectorConfig
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUDA-specific tests"
|
||||
)
|
||||
|
||||
SELECTOR_CONFIG = AttentionSelectorConfig(
|
||||
head_size=64,
|
||||
dtype=torch.float16,
|
||||
kv_cache_dtype=None,
|
||||
block_size=16,
|
||||
)
|
||||
|
||||
SM90 = DeviceCapability(major=9, minor=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
ImportError("flashinfer is not installed"),
|
||||
PermissionError(13, "Permission denied", "/root/.cache/flashinfer"),
|
||||
OSError("libcuda.so.1: cannot open shared object file"),
|
||||
],
|
||||
)
|
||||
def test_get_valid_backends_records_environment_failure(exc):
|
||||
with patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc):
|
||||
valid, invalid_reasons = CudaPlatform.get_valid_backends(
|
||||
device_capability=SM90,
|
||||
attn_selector_config=SELECTOR_CONFIG,
|
||||
num_heads=32,
|
||||
)
|
||||
assert valid == []
|
||||
assert invalid_reasons
|
||||
for _priority, reasons in invalid_reasons.values():
|
||||
assert reasons == [f"{type(exc).__name__}: {exc}"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc",
|
||||
[
|
||||
RuntimeError("CUDA error: no kernel image is available"),
|
||||
AttributeError("module has no attribute 'get_builder_cls'"),
|
||||
KeyboardInterrupt(),
|
||||
],
|
||||
)
|
||||
def test_get_valid_backends_propagates_unexpected_errors(exc):
|
||||
with (
|
||||
patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc),
|
||||
pytest.raises(type(exc)),
|
||||
):
|
||||
CudaPlatform.get_valid_backends(
|
||||
device_capability=SM90,
|
||||
attn_selector_config=SELECTOR_CONFIG,
|
||||
num_heads=32,
|
||||
)
|
||||
|
||||
|
||||
def test_get_valid_backends_keeps_probing_after_failure():
|
||||
healthy = MagicMock()
|
||||
healthy.validate_configuration.return_value = []
|
||||
side_effects = [OSError("probe failed")] + [healthy] * 32
|
||||
|
||||
with patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=side_effects):
|
||||
valid, invalid_reasons = CudaPlatform.get_valid_backends(
|
||||
device_capability=SM90,
|
||||
attn_selector_config=SELECTOR_CONFIG,
|
||||
num_heads=32,
|
||||
)
|
||||
assert len(invalid_reasons) == 1
|
||||
assert valid
|
||||
|
||||
|
||||
def test_sm90_nope_mla_prefers_flashinfer_without_changing_rope_order():
|
||||
backend_cls = MagicMock()
|
||||
backend_cls.validate_configuration.return_value = []
|
||||
sparse_backends = {
|
||||
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
|
||||
AttentionBackendEnum.FLASHMLA_SPARSE,
|
||||
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
|
||||
}
|
||||
|
||||
def sparse_order(head_size: int) -> list[AttentionBackendEnum]:
|
||||
config = SELECTOR_CONFIG._replace(
|
||||
head_size=head_size,
|
||||
use_mla=True,
|
||||
use_sparse=True,
|
||||
)
|
||||
with patch(
|
||||
"vllm.platforms.cuda._get_attn_backend_class",
|
||||
return_value=backend_cls,
|
||||
):
|
||||
valid, _ = CudaPlatform.get_valid_backends(
|
||||
device_capability=SM90,
|
||||
attn_selector_config=config,
|
||||
num_heads=32,
|
||||
)
|
||||
return [
|
||||
candidate.backend
|
||||
for candidate in valid
|
||||
if candidate.backend in sparse_backends
|
||||
]
|
||||
|
||||
assert sparse_order(512) == [
|
||||
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
|
||||
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
|
||||
AttentionBackendEnum.FLASHMLA_SPARSE,
|
||||
]
|
||||
assert sparse_order(576) == [
|
||||
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
|
||||
AttentionBackendEnum.FLASHMLA_SPARSE,
|
||||
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
|
||||
]
|
||||
|
||||
|
||||
def test_selected_backend_probe_failure_raises_value_error_with_cause():
|
||||
exc = OSError("libcuda.so.1: cannot open shared object file")
|
||||
with (
|
||||
patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc),
|
||||
patch.object(CudaPlatform, "get_device_capability", return_value=SM90),
|
||||
pytest.raises(ValueError, match="OSError") as excinfo,
|
||||
):
|
||||
CudaPlatform.get_attn_backend_cls(
|
||||
selected_backend=AttentionBackendEnum.FLASH_ATTN,
|
||||
attn_selector_config=SELECTOR_CONFIG,
|
||||
num_heads=32,
|
||||
)
|
||||
assert excinfo.value.__cause__ is exc
|
||||
@@ -1,165 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The empty-shard mask fused into the DCP A2A pack kernel must be bit-exact
|
||||
with the eager ``mask_dcp_empty_shards_`` pass it replaces."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.ops.dcp import (
|
||||
_dcp_a2a_lse_pack_dim,
|
||||
_dcp_a2a_pack_send,
|
||||
mask_dcp_empty_shards_,
|
||||
)
|
||||
|
||||
requires_accelerator = pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="needs a CUDA or ROCm device for the Triton pack kernel",
|
||||
)
|
||||
|
||||
|
||||
def _pack(out, lse, world_size, h_per_rank, head_dim, seq_lens, query_start_loc):
|
||||
lse_pack_dim = _dcp_a2a_lse_pack_dim(out.dtype)
|
||||
send = torch.zeros(
|
||||
(world_size, out.shape[0], h_per_rank, head_dim + lse_pack_dim),
|
||||
device=out.device,
|
||||
dtype=out.dtype,
|
||||
)
|
||||
_dcp_a2a_pack_send(
|
||||
out,
|
||||
lse,
|
||||
send,
|
||||
world_size,
|
||||
h_per_rank,
|
||||
head_dim,
|
||||
lse_pack_dim,
|
||||
seq_lens=seq_lens,
|
||||
query_start_loc=query_start_loc,
|
||||
)
|
||||
return send
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
|
||||
@pytest.mark.parametrize("world_size,h_per_rank", [(8, 2), (8, 16), (4, 4), (2, 1)])
|
||||
@pytest.mark.parametrize("tokens_per_req", [1, 2, 3])
|
||||
@pytest.mark.parametrize("num_pad_rows", [0, 2])
|
||||
@requires_accelerator
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens_list",
|
||||
[
|
||||
[16, 16, 16, 16], # no empty shards (the long-context decode case)
|
||||
[16, 0, 16, 0], # interior empty shards
|
||||
[0, 0, 0, 0], # every shard empty
|
||||
[16, 16, 0, 0], # trailing empty shards, i.e. cudagraph padding
|
||||
[0, 16, 16, 16], # leading empty shard
|
||||
[16] * 52, # the profiled conc-52 decode batch
|
||||
[7], # single request
|
||||
],
|
||||
)
|
||||
def test_fused_mask_matches_eager(
|
||||
dtype, world_size, h_per_rank, tokens_per_req, num_pad_rows, seq_lens_list
|
||||
):
|
||||
torch.manual_seed(0)
|
||||
device = "cuda"
|
||||
head_dim = 512
|
||||
num_seqs = len(seq_lens_list)
|
||||
# tokens_per_req > 1 is the MTP / multi-token-verify shape.
|
||||
num_rows = num_seqs * tokens_per_req + num_pad_rows
|
||||
num_heads = world_size * h_per_rank
|
||||
|
||||
out = torch.randn(num_rows, num_heads, head_dim, device=device, dtype=dtype)
|
||||
lse = torch.randn(num_rows, num_heads, device=device, dtype=torch.float32)
|
||||
seq_lens = torch.tensor(seq_lens_list, device=device, dtype=torch.int32)
|
||||
query_start_loc = torch.arange(
|
||||
0,
|
||||
(num_seqs + 1) * tokens_per_req,
|
||||
tokens_per_req,
|
||||
device=device,
|
||||
dtype=torch.int32,
|
||||
) # rows past query_start_loc[-1] are cudagraph padding
|
||||
|
||||
# Reference: mask eagerly, then pack with masking disabled.
|
||||
ref_lse = lse.clone()
|
||||
mask_dcp_empty_shards_(ref_lse, seq_lens, query_start_loc)
|
||||
expected = _pack(out, ref_lse, world_size, h_per_rank, head_dim, None, None)
|
||||
|
||||
# Under test: pack with the mask fused in.
|
||||
actual = _pack(
|
||||
out, lse.clone(), world_size, h_per_rank, head_dim, seq_lens, query_start_loc
|
||||
)
|
||||
|
||||
# The packed LSE slots hold halves of an fp32, not meaningful floats, so
|
||||
# compare the send buffers bitwise: -inf's high half is a NaN in fp16.
|
||||
assert torch.equal(actual.view(torch.int16), expected.view(torch.int16)), (
|
||||
"fused mask is not bit-exact with the eager mask"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
|
||||
@pytest.mark.parametrize("seed", range(8))
|
||||
@requires_accelerator
|
||||
def test_fused_mask_matches_eager_ragged(dtype, seed):
|
||||
"""Non-uniform per-request query lengths.
|
||||
|
||||
The uniform-stride cases above never exercise an unequal gap between
|
||||
consecutive ``query_start_loc`` entries, which is what the in-kernel
|
||||
boundary search has to get right. MTP with partial acceptance produces
|
||||
exactly this: some requests contribute one row, others several, in the
|
||||
same batch.
|
||||
"""
|
||||
torch.manual_seed(seed)
|
||||
device = "cuda"
|
||||
world_size, h_per_rank, head_dim = 8, 2, 512
|
||||
num_seqs = 17
|
||||
|
||||
query_lens = torch.randint(1, 5, (num_seqs,), dtype=torch.int32)
|
||||
query_start_loc = torch.zeros(num_seqs + 1, dtype=torch.int32)
|
||||
query_start_loc[1:] = torch.cumsum(query_lens, 0)
|
||||
# Mix real, empty, and (via padding rows) out-of-range shards.
|
||||
seq_lens = torch.randint(0, 2, (num_seqs,), dtype=torch.int32) * 16
|
||||
num_rows = int(query_start_loc[-1]) + 3
|
||||
|
||||
query_start_loc = query_start_loc.to(device)
|
||||
seq_lens = seq_lens.to(device)
|
||||
num_heads = world_size * h_per_rank
|
||||
out = torch.randn(num_rows, num_heads, head_dim, device=device, dtype=dtype)
|
||||
lse = torch.randn(num_rows, num_heads, device=device, dtype=torch.float32)
|
||||
|
||||
ref_lse = lse.clone()
|
||||
mask_dcp_empty_shards_(ref_lse, seq_lens, query_start_loc)
|
||||
expected = _pack(out, ref_lse, world_size, h_per_rank, head_dim, None, None)
|
||||
actual = _pack(
|
||||
out, lse.clone(), world_size, h_per_rank, head_dim, seq_lens, query_start_loc
|
||||
)
|
||||
|
||||
assert torch.equal(actual.view(torch.int16), expected.view(torch.int16)), (
|
||||
f"ragged query_start_loc mismatch: query_lens={query_lens.tolist()}, "
|
||||
f"seq_lens={seq_lens.tolist()}"
|
||||
)
|
||||
|
||||
|
||||
@requires_accelerator
|
||||
def test_mask_disabled_is_unmasked():
|
||||
"""Passing no seq_lens/query_start_loc must leave the LSE untouched."""
|
||||
torch.manual_seed(0)
|
||||
device = "cuda"
|
||||
world_size, h_per_rank, head_dim = 8, 2, 512
|
||||
out = torch.randn(
|
||||
4, world_size * h_per_rank, head_dim, device=device, dtype=torch.bfloat16
|
||||
)
|
||||
lse = torch.randn(4, world_size * h_per_rank, device=device, dtype=torch.float32)
|
||||
|
||||
packed = _pack(out, lse, world_size, h_per_rank, head_dim, None, None)
|
||||
assert torch.isfinite(packed.float()).all()
|
||||
|
||||
|
||||
def test_eager_mask_handles_rank_with_no_local_sequences():
|
||||
"""Padded graph rows are all empty when a DCP rank has no sequences."""
|
||||
lse = torch.randn(8, 4, dtype=torch.float32)
|
||||
seq_lens = torch.empty(0, dtype=torch.int32)
|
||||
query_start_loc = torch.tensor([0], dtype=torch.int32)
|
||||
|
||||
mask_dcp_empty_shards_(lse, seq_lens, query_start_loc)
|
||||
|
||||
assert torch.isneginf(lse).all()
|
||||
@@ -1,223 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.model_executor.layers.mamba.gdn import qwen_gdn_linear_attn
|
||||
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
|
||||
ChunkGatedDeltaRule,
|
||||
_resolve_gdn_prefill_backend,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
|
||||
def _make_config(
|
||||
*,
|
||||
backend: str = "aiter_flydsl",
|
||||
head_k_dim: int | None = 128,
|
||||
head_v_dim: int | None = 128,
|
||||
dtype: torch.dtype = torch.bfloat16,
|
||||
):
|
||||
return SimpleNamespace(
|
||||
additional_config={"gdn_prefill_backend": backend},
|
||||
model_config=SimpleNamespace(
|
||||
dtype=dtype,
|
||||
hf_text_config=SimpleNamespace(
|
||||
linear_key_head_dim=head_k_dim,
|
||||
linear_value_head_dim=head_v_dim,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_on_rocm(config, *, kernels_available: bool = True, mi3xx: bool = True):
|
||||
with (
|
||||
patch.object(
|
||||
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=True
|
||||
),
|
||||
patch.object(
|
||||
qwen_gdn_linear_attn.rocm_aiter_ops,
|
||||
"is_gdn_flydsl_prefill_available",
|
||||
return_value=kernels_available,
|
||||
),
|
||||
patch("vllm.platforms.rocm.on_mi3xx", return_value=mi3xx),
|
||||
):
|
||||
return _resolve_gdn_prefill_backend(config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"head_k_dim,head_v_dim,dtype,expected",
|
||||
[
|
||||
(128, 128, torch.bfloat16, "aiter_flydsl"),
|
||||
(64, 128, torch.bfloat16, "triton"),
|
||||
(128, 64, torch.bfloat16, "triton"),
|
||||
(128, 128, torch.float16, "triton"),
|
||||
],
|
||||
)
|
||||
def test_resolve_aiter_flydsl_gdn_prefill_backend(
|
||||
head_k_dim: int,
|
||||
head_v_dim: int,
|
||||
dtype: torch.dtype,
|
||||
expected: str,
|
||||
):
|
||||
config = _make_config(head_k_dim=head_k_dim, head_v_dim=head_v_dim, dtype=dtype)
|
||||
|
||||
requested, active = _resolve_on_rocm(config)
|
||||
|
||||
assert requested == "aiter_flydsl"
|
||||
assert active == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mi3xx,kernels_available,head_k_dim,expected",
|
||||
[
|
||||
(True, True, 128, "aiter_flydsl"),
|
||||
(False, True, 128, "triton"),
|
||||
(True, False, 128, "triton"),
|
||||
(True, True, 64, "triton"),
|
||||
],
|
||||
)
|
||||
def test_auto_defaults_to_aiter_flydsl(
|
||||
mi3xx: bool, kernels_available: bool, head_k_dim: int, expected: str
|
||||
):
|
||||
"""Under auto, FlyDSL is the default only where it was validated and the
|
||||
model and build can serve it; everything else stays on Triton."""
|
||||
config = _make_config(backend="auto", head_k_dim=head_k_dim)
|
||||
|
||||
assert _resolve_on_rocm(
|
||||
config, kernels_available=kernels_available, mi3xx=mi3xx
|
||||
) == ("auto", expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend", ["aiter_flydsl", "auto"])
|
||||
def test_kda_style_model_cannot_select_flydsl(backend: str):
|
||||
"""Kimi K3 KDA reports head dims through linear_attn_config, not these.
|
||||
|
||||
Its builder overrides _build_chunk_metadata, which the AITER path skips,
|
||||
so this pins the reason the two never meet: the resolver turns the model
|
||||
down before the builder is ever constructed.
|
||||
"""
|
||||
config = _make_config(backend=backend, head_k_dim=None, head_v_dim=None)
|
||||
|
||||
assert _resolve_on_rocm(config) == (backend, "triton")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("on_rocm", [True, False], ids=["kernels_missing", "not_rocm"])
|
||||
def test_explicit_aiter_flydsl_fails_closed(on_rocm: bool):
|
||||
"""An explicit request that cannot be honoured is a configuration error.
|
||||
|
||||
Falling back silently would report the run as healthy while the requested
|
||||
kernels were never used.
|
||||
"""
|
||||
config = _make_config()
|
||||
if on_rocm:
|
||||
with pytest.raises(RuntimeError, match="not importable"):
|
||||
_resolve_on_rocm(config, kernels_available=False)
|
||||
return
|
||||
with (
|
||||
patch.object(
|
||||
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=False
|
||||
),
|
||||
patch.object(
|
||||
qwen_gdn_linear_attn.current_platform, "is_cuda", return_value=True
|
||||
),
|
||||
pytest.raises(RuntimeError, match="aiter_flydsl"),
|
||||
):
|
||||
_resolve_gdn_prefill_backend(config)
|
||||
|
||||
|
||||
def _flydsl_prefill_unavailable() -> bool:
|
||||
if not current_platform.is_rocm():
|
||||
return True
|
||||
from vllm.platforms.rocm import on_mi3xx
|
||||
|
||||
return not on_mi3xx() or not rocm_aiter_ops.is_gdn_flydsl_prefill_available()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
_flydsl_prefill_unavailable(),
|
||||
reason="needs gfx942/gfx950 with the AITER FlyDSL GDN prefill kernels installed",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"state_dtype", [torch.float32, torch.bfloat16], ids=["fp32_state", "bf16_state"]
|
||||
)
|
||||
def test_aiter_flydsl_prefill_matches_triton_reference(state_dtype: torch.dtype):
|
||||
"""Run both prefill paths on device and compare.
|
||||
|
||||
The reference is the same AITER entry point with the FlyDSL prepare and K5
|
||||
kernels switched off, so the only thing that differs between the two calls
|
||||
is the kernels this backend exists to select. The state dtype follows
|
||||
--mamba-ssm-cache-dtype, which may be float32 or bfloat16.
|
||||
"""
|
||||
from aiter.ops.triton.gated_delta_net import chunk_gated_delta_rule_opt_vk
|
||||
|
||||
torch.manual_seed(0)
|
||||
device = torch.device("cuda")
|
||||
seq_lens = [70, 130]
|
||||
total_tokens = sum(seq_lens)
|
||||
num_k_heads, num_v_heads, head_dim = 2, 4, 128
|
||||
|
||||
# use_qk_l2norm_in_kernel=False matches the prefill path, where the model
|
||||
# has already normalised q and k. Feeding raw normals instead lets the
|
||||
# delta rule run away to NaN, which says nothing about either kernel.
|
||||
q = torch.nn.functional.normalize(
|
||||
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
|
||||
).to(torch.bfloat16)
|
||||
k = torch.nn.functional.normalize(
|
||||
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
|
||||
).to(torch.bfloat16)
|
||||
v = torch.randn(
|
||||
1, total_tokens, num_v_heads, head_dim, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
# g is a log-domain decay, so keep it negative or the recurrence diverges
|
||||
# and the comparison stops saying anything about the kernels.
|
||||
g = -torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
|
||||
beta = torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
|
||||
cu_seqlens = torch.tensor([0, 70, 200], dtype=torch.int32, device=device)
|
||||
initial_state = torch.randn(
|
||||
len(seq_lens),
|
||||
num_v_heads,
|
||||
head_dim,
|
||||
head_dim,
|
||||
device=device,
|
||||
).to(state_dtype)
|
||||
|
||||
shared = {
|
||||
"q": q,
|
||||
"k": k,
|
||||
"v": v,
|
||||
"g": g,
|
||||
"beta": beta,
|
||||
"output_final_state": True,
|
||||
"cu_seqlens": cu_seqlens,
|
||||
"use_qk_l2norm_in_kernel": False,
|
||||
}
|
||||
|
||||
reference_out, reference_state = chunk_gated_delta_rule_opt_vk(
|
||||
initial_state=initial_state.clone(),
|
||||
state_dtype=state_dtype,
|
||||
use_chunk_flydsl=False,
|
||||
use_prepare_flydsl=False,
|
||||
**shared,
|
||||
)
|
||||
flydsl_out, flydsl_state = ChunkGatedDeltaRule.forward_aiter_flydsl(
|
||||
None,
|
||||
initial_state=initial_state.clone(),
|
||||
aiter_prefill_metadata=rocm_aiter_ops.build_gdn_flydsl_prefill_metadata(
|
||||
seq_lens, cu_seqlens=cu_seqlens
|
||||
),
|
||||
**shared,
|
||||
)
|
||||
|
||||
assert flydsl_state.dtype == state_dtype
|
||||
torch.testing.assert_close(
|
||||
flydsl_out.float(), reference_out.float(), rtol=2e-2, atol=2e-2
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
flydsl_state.float(), reference_state.float(), rtol=2e-2, atol=2e-2
|
||||
)
|
||||
@@ -1,154 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.triton_attn import TritonAttentionMetadataBuilder
|
||||
from vllm.v1.attention.backends.triton_attn_diffkv import (
|
||||
TritonAttentionDiffKVMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
|
||||
|
||||
# 64 segments only while num_seqs * num_kv_heads * 16 < 188 SMs on SM12.0 and
|
||||
# the 64-segment scratch holds every query token (e.g. multi-query verify).
|
||||
@pytest.mark.parametrize(
|
||||
"builder_cls",
|
||||
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"capability,num_kv_heads,num_seqs,query_len,segments",
|
||||
[
|
||||
((12, 0), 1, 11, 1, 64),
|
||||
((12, 0), 1, 12, 1, 16),
|
||||
((12, 0), 8, 1, 1, 64),
|
||||
((12, 0), 8, 2, 1, 16),
|
||||
((9, 0), 1, 1, 1, 16),
|
||||
((12, 0), 1, 2, 4, 64),
|
||||
((12, 0), 1, 10, 4, 16),
|
||||
],
|
||||
)
|
||||
def test_split_k_segments_follow_sm_occupancy(
|
||||
monkeypatch, builder_cls, capability, num_kv_heads, num_seqs, query_len, segments
|
||||
):
|
||||
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
current_platform, "is_device_capability", lambda cap: cap == capability
|
||||
)
|
||||
monkeypatch.setattr(current_platform, "num_compute_units", lambda: 188)
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
get_num_attention_heads=lambda _: 8,
|
||||
get_num_kv_heads=lambda _: num_kv_heads,
|
||||
get_head_size=lambda: 128,
|
||||
rswa_window=None,
|
||||
),
|
||||
parallel_config=None,
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=16),
|
||||
speculative_config=None,
|
||||
compilation_config=SimpleNamespace(
|
||||
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
|
||||
),
|
||||
)
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=num_kv_heads, head_size=128, dtype=torch.bfloat16
|
||||
)
|
||||
builder = builder_cls(spec, ["layer.0"], config, "cpu")
|
||||
batch = BatchSpec(seq_lens=[128] * num_seqs, query_lens=[query_len] * num_seqs)
|
||||
metadata = builder.build(0, create_common_attn_metadata(batch, 16, "cpu"))
|
||||
assert metadata.num_par_softmax_segments == segments
|
||||
assert metadata.softmax_segm_output.shape[2] == segments
|
||||
assert metadata.softmax_segm_max.shape[0] >= num_seqs * query_len
|
||||
# DiffKV re-allocates the output; it must stay sized like the base buffers.
|
||||
assert builder.softmax_segm_output.shape[0] == builder.softmax_segm_max.shape[0]
|
||||
assert (
|
||||
metadata.softmax_segm_output.data_ptr()
|
||||
== builder.softmax_segm_output.data_ptr()
|
||||
)
|
||||
|
||||
|
||||
def _draft_builder(builder_cls, rswa_window: int | None):
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
get_num_attention_heads=lambda _: 8,
|
||||
get_num_kv_heads=lambda _: 1,
|
||||
get_head_size=lambda: 128,
|
||||
rswa_window=rswa_window,
|
||||
),
|
||||
parallel_config=None,
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=16),
|
||||
speculative_config=None,
|
||||
compilation_config=SimpleNamespace(
|
||||
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
|
||||
),
|
||||
)
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
|
||||
)
|
||||
return builder_cls(spec, ["layer.0"], config, "cpu")
|
||||
|
||||
|
||||
def _draft_decode_batch(seq_lens: list[int]):
|
||||
batch = BatchSpec(seq_lens=seq_lens, query_lens=[1] * len(seq_lens))
|
||||
return create_common_attn_metadata(batch, 16, "cpu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"builder_cls",
|
||||
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
|
||||
)
|
||||
@pytest.mark.parametrize("rswa_window", [None, 64])
|
||||
def test_draft_decode_update_flag_matches_build_writes(builder_cls, rswa_window):
|
||||
"""The update is a no-op, so the builder may claim support only when
|
||||
build() writes no builder-owned tensor that a captured graph reads."""
|
||||
builder = _draft_builder(builder_cls, rswa_window)
|
||||
common_metadata = _draft_decode_batch([5, 9])
|
||||
common_metadata.rswa_prefix_lens = torch.tensor([3, 7], dtype=torch.int32)
|
||||
|
||||
def owned_bytes():
|
||||
# Bytes, not values: uninitialized scratch may hold NaNs.
|
||||
return {
|
||||
name: value.view(torch.uint8).clone()
|
||||
for name, value in vars(builder).items()
|
||||
if isinstance(value, torch.Tensor)
|
||||
}
|
||||
|
||||
before = owned_bytes()
|
||||
builder.build(0, common_metadata)
|
||||
after = owned_bytes()
|
||||
|
||||
written = [name for name in before if not torch.equal(before[name], after[name])]
|
||||
assert builder.supports_draft_decode_metadata_update is (not written)
|
||||
assert builder.supports_draft_decode_metadata_update is (rswa_window is None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"builder_cls",
|
||||
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
|
||||
)
|
||||
def test_draft_decode_update_matches_fresh_build(builder_cls):
|
||||
"""A replayed graph reads metadata built at capture; after an in-place
|
||||
update it must match a fresh build of the replayed batch."""
|
||||
torch.manual_seed(0)
|
||||
builder = _draft_builder(builder_cls, rswa_window=None)
|
||||
captured = _draft_decode_batch([100, 120])
|
||||
metadata = builder.build(0, captured)
|
||||
|
||||
replayed = _draft_decode_batch([128, 30])
|
||||
# The replayed batch arrives through the same persistent input buffers.
|
||||
captured.seq_lens.copy_(replayed.seq_lens)
|
||||
captured.block_table_tensor.copy_(replayed.block_table_tensor)
|
||||
captured.slot_mapping.copy_(replayed.slot_mapping)
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
expected = _draft_builder(builder_cls, rswa_window=None).build(0, replayed)
|
||||
assert torch.equal(metadata.seq_lens, expected.seq_lens)
|
||||
assert torch.equal(metadata.block_table, expected.block_table)
|
||||
assert torch.equal(metadata.slot_mapping, expected.slot_mapping)
|
||||
assert torch.equal(metadata.query_start_loc, expected.query_start_loc)
|
||||
@@ -1,158 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.triton_attn import TritonAttentionMetadataBuilder
|
||||
from vllm.v1.attention.backends.triton_attn_diffkv import (
|
||||
TritonAttentionDiffKVMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVQuantMode
|
||||
|
||||
|
||||
def _build(
|
||||
monkeypatch,
|
||||
builder_cls,
|
||||
capability,
|
||||
num_kv_heads,
|
||||
query_lens,
|
||||
max_num_seqs=16,
|
||||
num_speculative_tokens=None,
|
||||
parallel_drafting=False,
|
||||
kv_quant_mode=KVQuantMode.NONE,
|
||||
):
|
||||
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
current_platform, "is_device_capability", lambda cap: cap == capability
|
||||
)
|
||||
monkeypatch.setattr(current_platform, "num_compute_units", lambda: 188)
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
get_num_attention_heads=lambda _: 8,
|
||||
get_num_kv_heads=lambda _: num_kv_heads,
|
||||
get_head_size=lambda: 128,
|
||||
rswa_window=None,
|
||||
),
|
||||
parallel_config=None,
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=max_num_seqs),
|
||||
speculative_config=(
|
||||
None
|
||||
if num_speculative_tokens is None
|
||||
else SimpleNamespace(
|
||||
num_speculative_tokens=num_speculative_tokens,
|
||||
parallel_drafting=parallel_drafting,
|
||||
)
|
||||
),
|
||||
compilation_config=SimpleNamespace(
|
||||
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
|
||||
),
|
||||
)
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
kv_quant_mode=kv_quant_mode,
|
||||
)
|
||||
builder = builder_cls(spec, ["layer.0"], config, "cpu")
|
||||
batch = BatchSpec(seq_lens=[128] * len(query_lens), query_lens=query_lens)
|
||||
metadata = builder.build(0, create_common_attn_metadata(batch, 16, "cpu"))
|
||||
assert metadata.softmax_segm_output.shape[2] == metadata.num_par_softmax_segments
|
||||
assert metadata.softmax_segm_max.shape[0] >= sum(query_lens)
|
||||
# DiffKV re-allocates the output; it must stay sized like the base buffers.
|
||||
assert builder.softmax_segm_output.shape[0] == builder.softmax_segm_max.shape[0]
|
||||
assert (
|
||||
metadata.softmax_segm_output.data_ptr()
|
||||
== builder.softmax_segm_output.data_ptr()
|
||||
)
|
||||
return builder, metadata
|
||||
|
||||
|
||||
BUILDERS = [TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder]
|
||||
|
||||
|
||||
# Verify batches: the 64-segment scratch holds min(11, max_num_seqs) * (1 + K)
|
||||
# rows, and its 16-segment view covers every 3D-eligible sequence. 64 segments
|
||||
# follow the request count, not Q blocks: on SM12.0 they stay faster for verify
|
||||
# batches up to 11 requests (22 Q blocks at K=3).
|
||||
@pytest.mark.parametrize("builder_cls", BUILDERS)
|
||||
@pytest.mark.parametrize(
|
||||
"max_num_seqs,num_speculative_tokens,num_seqs,rows,segments",
|
||||
[
|
||||
(16, 3, 10, 44, 64),
|
||||
(16, 3, 11, 44, 64),
|
||||
(16, 3, 12, 44, 16),
|
||||
(16, 3, 16, 44, 16),
|
||||
(1, 5, 1, 6, 64),
|
||||
],
|
||||
)
|
||||
def test_split_k_segment_rows_cover_verify_queries(
|
||||
monkeypatch,
|
||||
builder_cls,
|
||||
max_num_seqs,
|
||||
num_speculative_tokens,
|
||||
num_seqs,
|
||||
rows,
|
||||
segments,
|
||||
):
|
||||
builder, metadata = _build(
|
||||
monkeypatch,
|
||||
builder_cls,
|
||||
(12, 0),
|
||||
1,
|
||||
[1 + num_speculative_tokens] * num_seqs,
|
||||
max_num_seqs,
|
||||
num_speculative_tokens,
|
||||
)
|
||||
assert builder.softmax_segm_max.shape[:2] == (rows, 8)
|
||||
assert metadata.num_par_softmax_segments == segments
|
||||
|
||||
|
||||
# Without SM12.0 64-segment reuse, the scratch holds exactly
|
||||
# min(seq_threshold_3D, max_num_seqs) * query_len rows for split-K query_lens.
|
||||
@pytest.mark.parametrize(
|
||||
"num_speculative_tokens,parallel_drafting,max_num_seqs,rows",
|
||||
[
|
||||
(None, False, 8, 8),
|
||||
(4, False, 8, 40),
|
||||
(7, False, 8, 64),
|
||||
(8, False, 8, 64),
|
||||
(3, True, 8, 56),
|
||||
(4, True, 8, 64),
|
||||
(5, False, 1, 6),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"kv_quant_mode", [KVQuantMode.NONE, KVQuantMode.INT4_PER_TOKEN_HEAD]
|
||||
)
|
||||
def test_split_k_scratch_rows_follow_speculative_config(
|
||||
monkeypatch,
|
||||
num_speculative_tokens,
|
||||
parallel_drafting,
|
||||
max_num_seqs,
|
||||
rows,
|
||||
kv_quant_mode,
|
||||
):
|
||||
# The INT4 launcher never runs multi-query split-K.
|
||||
if kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
|
||||
rows = max_num_seqs
|
||||
builder, _ = _build(
|
||||
monkeypatch,
|
||||
TritonAttentionMetadataBuilder,
|
||||
(9, 0),
|
||||
1,
|
||||
[1],
|
||||
max_num_seqs,
|
||||
num_speculative_tokens,
|
||||
parallel_drafting,
|
||||
kv_quant_mode,
|
||||
)
|
||||
assert builder.softmax_segm_output.shape == (rows, 8, 16, 128)
|
||||
assert builder.softmax_segm_max.shape == (rows, 8, 16)
|
||||
assert builder.softmax_segm_expsum.shape == (rows, 8, 16)
|
||||
@@ -1,87 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch._subclasses.fake_tensor import FakeTensorMode
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.ops import vit_attn_wrappers
|
||||
|
||||
|
||||
def _noncontiguous_bshd(device: torch.device | None = None) -> torch.Tensor:
|
||||
return (
|
||||
torch.arange(120, dtype=torch.float32, device=device)
|
||||
.reshape(1, 3, 5, 8)
|
||||
.transpose(1, 2)
|
||||
)
|
||||
|
||||
|
||||
def test_registered_attention_wrapper_fake_layouts():
|
||||
with FakeTensorMode():
|
||||
q = _noncontiguous_bshd()
|
||||
cu_seqlens = torch.tensor([0, 5], dtype=torch.int32)
|
||||
max_seqlen = torch.tensor(5, dtype=torch.int32)
|
||||
flashinfer_cu_seqlens = torch.tensor([0, 5, 0, 5], dtype=torch.int32)
|
||||
sequence_lengths = torch.tensor([5], dtype=torch.int32)
|
||||
|
||||
outputs = (
|
||||
torch.ops.vllm.flash_attn_maxseqlen_wrapper(
|
||||
q, q, q, 1, False, None, None, cu_seqlens, max_seqlen
|
||||
),
|
||||
torch.ops.vllm.triton_attn_wrapper(
|
||||
q, q, q, 1, None, cu_seqlens, max_seqlen
|
||||
),
|
||||
torch.ops.vllm.torch_sdpa_wrapper(q, q, q, None, None, False),
|
||||
torch.ops.vllm.flashinfer_wrapper(
|
||||
q,
|
||||
q,
|
||||
q,
|
||||
1.0,
|
||||
torch.empty(1, dtype=torch.uint8),
|
||||
flashinfer_cu_seqlens,
|
||||
max_seqlen,
|
||||
sequence_lengths,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
)
|
||||
|
||||
assert all(output.is_contiguous() for output in outputs)
|
||||
|
||||
|
||||
def test_aiter_flash_attn_omits_out_and_returns_contiguous_output(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
aiter = ModuleType("aiter")
|
||||
|
||||
def flash_attn_varlen_func(q, k, v, **kwargs):
|
||||
assert "out" not in kwargs
|
||||
return q
|
||||
|
||||
aiter.__dict__["flash_attn_varlen_func"] = flash_attn_varlen_func
|
||||
monkeypatch.setitem(sys.modules, "aiter", aiter)
|
||||
monkeypatch.setattr(
|
||||
vit_attn_wrappers, "current_platform", SimpleNamespace(is_rocm=lambda: True)
|
||||
)
|
||||
q = _noncontiguous_bshd()
|
||||
assert not q.is_contiguous()
|
||||
|
||||
output = vit_attn_wrappers.flash_attn_maxseqlen_wrapper(q, q, q, 1, True, None)
|
||||
|
||||
assert torch.equal(output, q)
|
||||
assert output.is_contiguous()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="Requires GPU")
|
||||
def test_sdpa_output_layout_without_cu_seqlens():
|
||||
q = _noncontiguous_bshd(torch.device("cuda"))
|
||||
|
||||
output = vit_attn_wrappers.vit_torch_sdpa_wrapper(q, q, q)
|
||||
|
||||
assert output.is_contiguous()
|
||||
@@ -1,294 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for KVCacheConfigBuilder resolution."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import Platform
|
||||
from vllm.v1.core.kv_cache_config_builder import (
|
||||
KVCacheConfigBuilder,
|
||||
get_kv_cache_config_builder,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_planning import (
|
||||
DefaultKVCacheConfigBuilder,
|
||||
get_kv_cache_groups_from_builder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheGroupSpec
|
||||
|
||||
|
||||
def _make_vllm_config(supports_grouping: bool = False) -> MagicMock:
|
||||
"""Create a minimal mock VllmConfig for builder resolution tests.
|
||||
|
||||
``supports_grouping`` selects whether the resolved model class declares
|
||||
``SupportsKVCacheGrouping`` (exposing a ``get_kv_cache_groups`` classmethod).
|
||||
"""
|
||||
cfg = MagicMock()
|
||||
cfg.model_config.supports_kv_cache_grouping = supports_grouping
|
||||
cfg.attention_config.hisparse_config = None
|
||||
if supports_grouping:
|
||||
cfg.model_config.registry.resolve_model_cls.return_value = (
|
||||
_GroupedModel,
|
||||
"arch",
|
||||
)
|
||||
return cfg
|
||||
|
||||
|
||||
CUSTOM_PATH = "tests.v1.core.test_kv_cache_config_builder.CustomBuilder"
|
||||
DEFAULT_PATH = "vllm.v1.core.kv_cache_planning.DefaultKVCacheConfigBuilder"
|
||||
|
||||
|
||||
class CustomBuilder(DefaultKVCacheConfigBuilder):
|
||||
"""A test builder subclass."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class _GroupedModel:
|
||||
"""A test model class with a ``get_kv_cache_groups`` classmethod."""
|
||||
|
||||
@classmethod
|
||||
def get_kv_cache_groups(cls, vllm_config, kv_cache_spec):
|
||||
return []
|
||||
|
||||
|
||||
class _PartialGroupedModel:
|
||||
"""A test model class whose grouping omits layers."""
|
||||
|
||||
@classmethod
|
||||
def get_kv_cache_groups(cls, vllm_config, kv_cache_spec):
|
||||
from vllm.v1.kv_cache_interface import KVCacheGroupSpec
|
||||
|
||||
return [KVCacheGroupSpec(["a"], kv_cache_spec["a"])]
|
||||
|
||||
|
||||
class TestPlatformHookResolution:
|
||||
"""The platform hook selects only the placement builder."""
|
||||
|
||||
def test_default_hook_returns_default_builder(self):
|
||||
cfg = _make_vllm_config()
|
||||
assert Platform.get_kv_cache_config_builder_cls(cfg) == DEFAULT_PATH
|
||||
|
||||
|
||||
class TestBuilderResolution:
|
||||
@patch("vllm.platforms.current_platform")
|
||||
@pytest.mark.parametrize(
|
||||
("builder_cls_path", "expected_cls"),
|
||||
[
|
||||
(None, DefaultKVCacheConfigBuilder),
|
||||
(CUSTOM_PATH, CustomBuilder),
|
||||
],
|
||||
)
|
||||
def test_resolves_hook_selected_builder(
|
||||
self, mock_platform, builder_cls_path, expected_cls
|
||||
):
|
||||
mock_platform.get_kv_cache_config_builder_cls.return_value = (
|
||||
builder_cls_path or DEFAULT_PATH
|
||||
)
|
||||
cfg = _make_vllm_config()
|
||||
assert type(get_kv_cache_config_builder(cfg)) is expected_cls
|
||||
|
||||
@patch("vllm.platforms.current_platform")
|
||||
def test_resolves_fresh_instance_per_call(self, mock_platform):
|
||||
mock_platform.get_kv_cache_config_builder_cls.return_value = CUSTOM_PATH
|
||||
cfg = _make_vllm_config()
|
||||
assert get_kv_cache_config_builder(cfg) is not get_kv_cache_config_builder(cfg)
|
||||
|
||||
def test_public_interface_declares_two_placement_hooks(self):
|
||||
# get_kv_cache_configs lives in kv_cache_planning and is Core-owned;
|
||||
# the builder only declares the placement hooks.
|
||||
assert KVCacheConfigBuilder.__abstractmethods__ == {
|
||||
"get_kv_cache_groups",
|
||||
"get_kv_cache_config_from_groups",
|
||||
}
|
||||
assert issubclass(DefaultKVCacheConfigBuilder, KVCacheConfigBuilder)
|
||||
assert (
|
||||
"pool_bytes_per_block"
|
||||
not in DefaultKVCacheConfigBuilder.__abstractmethods__
|
||||
)
|
||||
assert (
|
||||
"max_memory_usage_bytes"
|
||||
not in DefaultKVCacheConfigBuilder.__abstractmethods__
|
||||
)
|
||||
|
||||
|
||||
class TestModelGroupingPriority:
|
||||
"""A model class with a get_kv_cache_groups classmethod owns grouping."""
|
||||
|
||||
def test_model_classmethod_owns_grouping(self):
|
||||
cfg = _make_vllm_config(supports_grouping=True)
|
||||
assert DefaultKVCacheConfigBuilder().get_kv_cache_groups(cfg, {}) == []
|
||||
|
||||
def test_model_grouping_rejects_hisparse(self):
|
||||
cfg = _make_vllm_config(supports_grouping=True)
|
||||
cfg.attention_config.hisparse_config = object()
|
||||
with pytest.raises(ValueError, match="HiSparse"):
|
||||
DefaultKVCacheConfigBuilder().get_kv_cache_groups(cfg, {})
|
||||
|
||||
|
||||
class TestCoreChecksGrouping:
|
||||
"""Core checks the grouping whether a model or a platform produced it."""
|
||||
|
||||
_SPEC = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=128, dtype="float16"
|
||||
)
|
||||
|
||||
def test_model_grouping_is_checked(self):
|
||||
cfg = _make_vllm_config(supports_grouping=True)
|
||||
cfg.model_config.registry.resolve_model_cls.return_value = (
|
||||
_PartialGroupedModel,
|
||||
"arch",
|
||||
)
|
||||
with pytest.raises(AssertionError, match="miss layers"):
|
||||
get_kv_cache_groups_from_builder(
|
||||
DefaultKVCacheConfigBuilder(), cfg, {"a": self._SPEC, "b": self._SPEC}
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("groups", "match"),
|
||||
[
|
||||
([KVCacheGroupSpec(["a"], _SPEC)], "miss layers"),
|
||||
(
|
||||
[KVCacheGroupSpec(["a", "b"], _SPEC), KVCacheGroupSpec(["b"], _SPEC)],
|
||||
"overlaps",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_platform_grouping_is_checked(self, groups, match):
|
||||
class FixedGroupsBuilder(DefaultKVCacheConfigBuilder):
|
||||
def get_kv_cache_groups(self, vllm_config, kv_cache_spec):
|
||||
return groups
|
||||
|
||||
with pytest.raises(AssertionError, match=match):
|
||||
get_kv_cache_groups_from_builder(
|
||||
FixedGroupsBuilder(),
|
||||
_make_vllm_config(),
|
||||
{"a": self._SPEC, "b": self._SPEC},
|
||||
)
|
||||
|
||||
|
||||
class TestPlatformCustomPriority:
|
||||
"""A vendor platform can override the hook to customize priority."""
|
||||
|
||||
def test_platform_builder_wins_over_model_declaration(self):
|
||||
class PlatformFirstPlatform(Platform):
|
||||
@classmethod
|
||||
def get_kv_cache_config_builder_cls(cls, vllm_config):
|
||||
return CUSTOM_PATH
|
||||
|
||||
cfg = _make_vllm_config()
|
||||
assert PlatformFirstPlatform.get_kv_cache_config_builder_cls(cfg) == CUSTOM_PATH
|
||||
with patch("vllm.platforms.current_platform", PlatformFirstPlatform):
|
||||
assert isinstance(get_kv_cache_config_builder(cfg), CustomBuilder)
|
||||
|
||||
|
||||
class TestProjectionPreservesGroupMetadata:
|
||||
"""PP projection must carry host_resident/role/enable_kv_transfer."""
|
||||
|
||||
def test_partial_projection_preserves_metadata(self):
|
||||
from vllm.v1.core.kv_cache_planning import _project_kv_cache_groups_to_worker
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheGroupRole,
|
||||
)
|
||||
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=128, dtype="float16"
|
||||
)
|
||||
group = MagicMock()
|
||||
group.layer_names = ["layer1", "layer2", "layer3"]
|
||||
group.kv_cache_spec = spec
|
||||
group.is_eagle_group = False
|
||||
group.host_resident = True
|
||||
group.enable_kv_transfer = False
|
||||
group.role = KVCacheGroupRole.HISPARSE_SOURCE
|
||||
|
||||
projected = _project_kv_cache_groups_to_worker(
|
||||
[group], {"layer1": spec, "layer2": spec}
|
||||
)
|
||||
assert len(projected) == 1
|
||||
p = projected[0]
|
||||
assert p.host_resident is True
|
||||
assert p.enable_kv_transfer is False
|
||||
assert p.role is KVCacheGroupRole.HISPARSE_SOURCE
|
||||
assert p.layer_names == ["layer1", "layer2"]
|
||||
|
||||
|
||||
class TestBytesPerBlockProbe:
|
||||
"""The single-block probe must not be polluted by num_gpu_blocks_override."""
|
||||
|
||||
def test_probe_suppresses_override(self):
|
||||
import torch
|
||||
|
||||
from vllm.config import CacheConfig, ModelConfig, VllmConfig
|
||||
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
|
||||
from vllm.v1.core.kv_cache_planning import (
|
||||
DefaultKVCacheConfigBuilder,
|
||||
_pool_bytes_per_block,
|
||||
_pool_bytes_per_block_from_builder,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheGroupSpec,
|
||||
)
|
||||
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=128, dtype=torch.float16
|
||||
)
|
||||
vc = VllmConfig(
|
||||
model_config=ModelConfig(max_model_len=100),
|
||||
cache_config=CacheConfig(block_size=16),
|
||||
)
|
||||
resolve_kv_cache_layout(vc, [["BLHNC"]], [spec])
|
||||
groups = [
|
||||
KVCacheGroupSpec(["a"], spec),
|
||||
KVCacheGroupSpec(["b"], spec),
|
||||
]
|
||||
|
||||
pure_c = _pool_bytes_per_block(vc, groups)
|
||||
vc.cache_config.num_gpu_blocks_override = 500
|
||||
probed_c = _pool_bytes_per_block_from_builder(
|
||||
DefaultKVCacheConfigBuilder(), vc, groups
|
||||
)
|
||||
assert probed_c == pure_c
|
||||
assert vc.cache_config.num_gpu_blocks_override == 500
|
||||
|
||||
@pytest.mark.parametrize("declares_pool_bytes", [False, True])
|
||||
def test_several_device_allocations_need_declared_pool_bytes(
|
||||
self, declares_pool_bytes
|
||||
):
|
||||
"""A placement with one allocation per group cannot be sized from one
|
||||
backing; the builder must declare its per-block bytes."""
|
||||
from vllm.v1.core.kv_cache_planning import _pool_bytes_per_block_from_builder
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
)
|
||||
|
||||
class PerGroupAllocationBuilder(DefaultKVCacheConfigBuilder):
|
||||
def get_kv_cache_config_from_groups(self, vllm_config, groups, num_blocks):
|
||||
tensors = [
|
||||
KVCacheTensor(
|
||||
size=page * num_blocks,
|
||||
layers=group.layer_names,
|
||||
layer_stride=page * num_blocks,
|
||||
block_stride=page,
|
||||
)
|
||||
for group, page in zip(groups, (64, 32))
|
||||
]
|
||||
return KVCacheConfig(num_blocks, tensors, groups)
|
||||
|
||||
def _get_pool_bytes_per_block(self, vllm_config, groups):
|
||||
return 64 + 32 if declares_pool_bytes else None
|
||||
|
||||
vc = _make_vllm_config()
|
||||
vc.cache_config.num_gpu_blocks_override = None
|
||||
groups = [KVCacheGroupSpec([name], MagicMock()) for name in "ab"]
|
||||
builder = PerGroupAllocationBuilder()
|
||||
if declares_pool_bytes:
|
||||
assert _pool_bytes_per_block_from_builder(builder, vc, groups) == 96
|
||||
else:
|
||||
with pytest.raises(ValueError, match="_get_pool_bytes_per_block"):
|
||||
_pool_bytes_per_block_from_builder(builder, vc, groups)
|
||||
@@ -1,69 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm import EngineArgs, LLMEngine, SamplingParams
|
||||
|
||||
PROMPTS = [
|
||||
"A robot may not injure a human being ",
|
||||
"To be or not to be,",
|
||||
"What is the meaning of life?",
|
||||
"What does the fox say? " * 20, # Test long prompt
|
||||
]
|
||||
|
||||
|
||||
def test_reset_prefix_cache_e2e(monkeypatch):
|
||||
# "spawn" is required for test to be deterministic
|
||||
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-0.6B",
|
||||
gpu_memory_utilization=0.2,
|
||||
async_scheduling=True,
|
||||
max_num_batched_tokens=32,
|
||||
max_model_len=2048,
|
||||
compilation_config={"mode": 0},
|
||||
dtype="float16",
|
||||
)
|
||||
engine = LLMEngine.from_engine_args(engine_args)
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=16,
|
||||
)
|
||||
|
||||
# No preempt case:
|
||||
for i, prompt in enumerate(PROMPTS):
|
||||
engine.add_request("ground_truth_" + str(i), prompt, sampling_params)
|
||||
|
||||
ground_truth_results = {}
|
||||
while engine.has_unfinished_requests():
|
||||
request_outputs = engine.step()
|
||||
for request_output in request_outputs:
|
||||
if request_output.finished:
|
||||
ground_truth_results[request_output.request_id] = request_output
|
||||
|
||||
# Preempt case:
|
||||
for i, prompt in enumerate(PROMPTS):
|
||||
engine.add_request("preempted_" + str(i), prompt, sampling_params)
|
||||
|
||||
step_id = 0
|
||||
preempted_results = {}
|
||||
while engine.has_unfinished_requests():
|
||||
if step_id == 10:
|
||||
engine.reset_prefix_cache(reset_running_requests=True)
|
||||
|
||||
request_outputs = engine.step()
|
||||
|
||||
for request_output in request_outputs:
|
||||
if request_output.finished:
|
||||
preempted_results[request_output.request_id] = request_output
|
||||
step_id += 1
|
||||
|
||||
for i in range(len(PROMPTS)):
|
||||
assert (
|
||||
ground_truth_results["ground_truth_" + str(i)].outputs[0].text
|
||||
== preempted_results["preempted_" + str(i)].outputs[0].text
|
||||
), (
|
||||
f"ground_truth_results['ground_truth_{i}'].outputs[0].text="
|
||||
f"{ground_truth_results['ground_truth_' + str(i)].outputs[0].text} "
|
||||
f"preempted_results['preempted_{i}'].outputs[0].text="
|
||||
f"{preempted_results['preempted_' + str(i)].outputs[0].text}"
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM
|
||||
|
||||
MODEL = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
PROMPT = "Hello my name is Robert and I"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def llm() -> LLM:
|
||||
return LLM(
|
||||
MODEL,
|
||||
enforce_eager=True,
|
||||
enable_prefix_caching=True,
|
||||
long_prefill_token_threshold=2,
|
||||
max_num_batched_tokens=6,
|
||||
max_num_seqs=3,
|
||||
block_size=16,
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_partial_prefill(llm):
|
||||
outputs = llm.generate([PROMPT] * 3)
|
||||
assert len(outputs) == 3
|
||||
for output in outputs:
|
||||
assert len(output.outputs) == 1
|
||||
|
||||
|
||||
def test_prefix_cache_stats_is_recorded(llm):
|
||||
# 17 tokens will make sure first 16 tokens are cached in a block
|
||||
input_tokens = {"prompt_token_ids": [101] * 17}
|
||||
_ = llm.generate([input_tokens])
|
||||
outputs = llm.generate([input_tokens])
|
||||
assert outputs[0].num_cached_tokens == 16
|
||||
@@ -1,679 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for the breakable cudagraph primitives."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
HAS_DEVICE_GRAPH = current_platform.is_cuda_alike() or current_platform.is_xpu()
|
||||
|
||||
if current_platform.is_xpu():
|
||||
from vllm.v1.worker.xpu_model_runner import _torch_cuda_wrapper
|
||||
|
||||
# Route torch.cuda graph/stream APIs to torch.xpu, as XPUModelRunner does.
|
||||
with _torch_cuda_wrapper():
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable_breakable_cudagraph(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Enable breakable cudagraphs for this module's tests only.
|
||||
|
||||
eager_break_during_capture reads the env at decoration time, which
|
||||
happens inside the test bodies, so a per-test fixture suffices.
|
||||
monkeypatch restores the env so other test files running in the same
|
||||
pytest process are unaffected (a module-level os.environ assignment
|
||||
used to leak into test_cudagraph_dispatch.py and break it).
|
||||
"""
|
||||
import vllm.envs as envs
|
||||
|
||||
monkeypatch.setenv("VLLM_USE_BREAKABLE_CUDAGRAPH", "1")
|
||||
envs.disable_envs_cache()
|
||||
|
||||
|
||||
def test_piecewise_capture_builds_fresh_metadata_for_both_passes():
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import (
|
||||
BatchExecutionDescriptor,
|
||||
CudaGraphManager,
|
||||
)
|
||||
|
||||
manager = CudaGraphManager.__new__(CudaGraphManager)
|
||||
desc = BatchExecutionDescriptor(CUDAGraphMode.PIECEWISE, 8, None)
|
||||
manager.device = torch.device("cpu")
|
||||
manager._capture_descs = {CUDAGraphMode.PIECEWISE: [desc]}
|
||||
manager._graphs_captured = False
|
||||
manager.use_breakable_cg = True
|
||||
manager.ubatch_runner = None
|
||||
|
||||
create_calls = []
|
||||
forward_calls = []
|
||||
|
||||
def create_forward_fn(desc_arg, warmup):
|
||||
assert desc_arg == desc
|
||||
metadata = {"layer": object()}
|
||||
create_calls.append((warmup, metadata))
|
||||
|
||||
def forward_fn(cg_mode):
|
||||
assert metadata
|
||||
forward_calls.append((warmup, cg_mode, metadata))
|
||||
|
||||
return forward_fn
|
||||
|
||||
with (
|
||||
patch(
|
||||
"vllm.v1.worker.gpu.cudagraph_utils.graph_capture",
|
||||
return_value=nullcontext(),
|
||||
),
|
||||
patch(
|
||||
"vllm.v1.worker.gpu.cudagraph_utils.is_global_first_rank",
|
||||
return_value=False,
|
||||
),
|
||||
):
|
||||
manager.capture(create_forward_fn)
|
||||
|
||||
assert [warmup for warmup, _ in create_calls] == [True, False]
|
||||
assert [mode for _, mode, _ in forward_calls] == [
|
||||
CUDAGraphMode.NONE,
|
||||
CUDAGraphMode.PIECEWISE,
|
||||
]
|
||||
assert create_calls[0][1] is not create_calls[1][1]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_breakable_tls():
|
||||
"""Defensively clear thread-local capture state between tests so a
|
||||
failure in one test can't leak "nested capture" errors into the next."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
BreakableCUDAGraphCapture._tls.active = None
|
||||
yield
|
||||
BreakableCUDAGraphCapture._tls.active = None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cuda_capture_stream():
|
||||
"""A non-default CUDA stream suitable for cudagraph capture.
|
||||
|
||||
``CUDAGraph.capture_begin`` refuses to capture from the default
|
||||
stream, so all capture-using tests need to run under
|
||||
``torch.cuda.stream(...)`` for a separate stream.
|
||||
"""
|
||||
if not HAS_DEVICE_GRAPH:
|
||||
pytest.skip("CUDA or XPU graph required")
|
||||
from vllm.utils.torch_utils import _current_stream_tls
|
||||
|
||||
prev_stream = getattr(_current_stream_tls, "value", None)
|
||||
stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(stream):
|
||||
yield stream
|
||||
torch.cuda.current_stream().wait_stream(stream)
|
||||
# Exiting torch.cuda.stream() records the default stream in vllm's
|
||||
# patched set_stream cache. A later CUDAGraphWrapper capture in the same
|
||||
# process would then run on the default stream, which cannot capture
|
||||
# (this broke test_cudagraph_dispatch.py when run in-process after this
|
||||
# file). Restore the pre-fixture value so this module leaves no trace.
|
||||
_current_stream_tls.value = prev_stream
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# eager_break_during_capture: outside capture
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_decorator_passthrough_outside_capture():
|
||||
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
|
||||
|
||||
calls = []
|
||||
|
||||
@eager_break_during_capture
|
||||
def f(x):
|
||||
calls.append(x)
|
||||
return x * 2
|
||||
|
||||
assert f(3) == 6
|
||||
assert calls == [3]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BreakableCUDAGraphCapture: thread-local + nested rejection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_current_is_none_when_inactive():
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
assert BreakableCUDAGraphCapture.is_active() is False
|
||||
|
||||
|
||||
def test_thread_local_active_during_context(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
assert BreakableCUDAGraphCapture.current() is cap
|
||||
assert BreakableCUDAGraphCapture.is_active() is True
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
def test_nested_capture_raises(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
outer = BreakableCUDAGraphCapture()
|
||||
inner = BreakableCUDAGraphCapture()
|
||||
with outer, pytest.raises(RuntimeError, match="Nested.*not supported"), inner:
|
||||
pass
|
||||
|
||||
|
||||
def test_active_state_isolated_across_threads(cuda_capture_stream):
|
||||
"""Verify the thread-local 'active capture' slot is per-thread.
|
||||
|
||||
We don't run concurrent captures here -- CUDA only supports one
|
||||
in-flight capture per stream and we keep tests cheap. We just check
|
||||
that the worker thread sees its own slot as None while the main
|
||||
thread has a capture active.
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
worker_view: dict[str, BreakableCUDAGraphCapture | None] = {}
|
||||
|
||||
def worker():
|
||||
worker_view["state"] = BreakableCUDAGraphCapture.current()
|
||||
|
||||
main_cap = BreakableCUDAGraphCapture()
|
||||
with main_cap:
|
||||
# Main thread has a live capture.
|
||||
assert BreakableCUDAGraphCapture.current() is main_cap
|
||||
t = threading.Thread(target=worker)
|
||||
t.start()
|
||||
t.join()
|
||||
|
||||
# Worker thread saw None -- thread-local separation works.
|
||||
assert worker_view["state"] is None
|
||||
# Main thread's slot is cleared on exit.
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Segment list construction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_capture_with_no_eager_break_records_one_graph(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
assert len(cap.segments) == 1
|
||||
assert cap.num_graphs == 1
|
||||
assert cap.num_eager_breaks == 0
|
||||
|
||||
|
||||
def test_add_eager_creates_alternating_graph_eager_graph(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
counter = {"eager_calls": 0}
|
||||
|
||||
def eager_step():
|
||||
counter["eager_calls"] += 1
|
||||
x.add_(10.0)
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
cap.add_eager(eager_step)
|
||||
x.add_(1.0)
|
||||
cap.add_eager(eager_step)
|
||||
x.add_(1.0)
|
||||
# 3 graph segments + 2 eager segments, interleaved as G E G E G.
|
||||
assert len(cap.segments) == 5
|
||||
assert cap.num_graphs == 3
|
||||
assert cap.num_eager_breaks == 2
|
||||
# Eager fn is stored as-is in the segment list, so we can confirm
|
||||
# the alternation pattern by identity check.
|
||||
assert cap.segments[1] is eager_step
|
||||
assert cap.segments[3] is eager_step
|
||||
assert counter["eager_calls"] == 2 # only the in-capture invocation
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Capture vs eager numerical equivalence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_capture_replay_matches_eager_simple(cuda_capture_stream):
|
||||
"""Verify that replay reproduces the same end-state as a single eager
|
||||
forward, with an eager break in the middle.
|
||||
|
||||
Note: during capture, the *captured* kernels are recorded but NOT
|
||||
executed (that's CUDA-graph semantics). Only the eager segments
|
||||
actually mutate state at capture time. So we check correctness after
|
||||
``replay()``, not after ``with cap:`` exits.
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(8, device=DEVICE_TYPE)
|
||||
log: list[str] = []
|
||||
|
||||
def eager_break_op():
|
||||
x.mul_(2.0)
|
||||
log.append("eager")
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0) # recorded into graph[0]
|
||||
cap.add_eager(eager_break_op) # runs eagerly: x *= 2
|
||||
x.add_(5.0) # recorded into graph[1]
|
||||
|
||||
# Capture-time: graph kernels were recorded only; eager segment ran
|
||||
# once on x == 0, leaving x == 0.
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.zeros(8, device=DEVICE_TYPE))
|
||||
assert log == ["eager"]
|
||||
|
||||
# Replay with a fresh input: 10 -> 11 -> 22 -> 27.
|
||||
x.fill_(10.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((8,), 27.0, device=DEVICE_TYPE))
|
||||
assert log == ["eager", "eager"]
|
||||
|
||||
# Replay again with another input: 100 -> 101 -> 202 -> 207.
|
||||
x.fill_(100.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((8,), 207.0, device=DEVICE_TYPE))
|
||||
assert log == ["eager", "eager", "eager"]
|
||||
|
||||
|
||||
def test_decorator_breaks_when_invoked_inside_capture(cuda_capture_stream):
|
||||
"""Verify @eager_break_during_capture correctly routes through
|
||||
add_eager when inside a capture context, and runs straight through
|
||||
when there's no active capture."""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
|
||||
@eager_break_during_capture
|
||||
def attention_like(t: torch.Tensor) -> None:
|
||||
# In-place double; stands in for "real" attention work.
|
||||
t.mul_(2.0)
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
|
||||
# Outside capture: decorator should just call through.
|
||||
x.fill_(3.0)
|
||||
attention_like(x)
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((4,), 6.0, device=DEVICE_TYPE))
|
||||
|
||||
# Inside capture: decorator should split the graph. Only the eager
|
||||
# segment actually mutates state during capture.
|
||||
x.fill_(0.0)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(5.0) # recorded
|
||||
attention_like(x) # eager: x *= 2 (on x == 0, no-op)
|
||||
x.add_(1.0) # recorded
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.zeros(4, device=DEVICE_TYPE))
|
||||
# 2 graph segments + 1 eager segment, ordered G E G; the arithmetic
|
||||
# equivalence check below verifies the ordering.
|
||||
assert len(cap.segments) == 3
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
|
||||
# Replay: 2 -> 7 -> 14 -> 15.
|
||||
x.fill_(2.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((4,), 15.0, device=DEVICE_TYPE))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keyword", [False, True])
|
||||
def test_quantized_activation_replay_does_not_retain_tensors(
|
||||
cuda_capture_stream, keyword
|
||||
):
|
||||
"""Release the producer tensors while preserving both buffers on replay."""
|
||||
import gc
|
||||
import weakref
|
||||
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
|
||||
@eager_break_during_capture
|
||||
def consume(x, data_out, scale_out):
|
||||
data_out.copy_(x.data)
|
||||
scale_out.copy_(x.scale)
|
||||
|
||||
source = torch.ones((128, 128), device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
data_out = source.to(torch.float8_e4m3fn)
|
||||
scale_out = source[:, ::32].to(torch.uint8)
|
||||
output = torch.empty_like(source)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
data = source.to(torch.float8_e4m3fn)
|
||||
scale = source[:, ::32].to(torch.uint8)
|
||||
activation = QuantizedActivation(
|
||||
data, scale, source.dtype, source.shape, kMxfp8Dynamic
|
||||
)
|
||||
data_ref, scale_ref = weakref.ref(data), weakref.ref(scale)
|
||||
if keyword:
|
||||
consume(x=activation, data_out=data_out, scale_out=scale_out)
|
||||
else:
|
||||
consume(activation, data_out, scale_out)
|
||||
output.copy_(data_out)
|
||||
|
||||
del data, scale, activation
|
||||
gc.collect()
|
||||
assert data_ref() is None
|
||||
assert scale_ref() is None
|
||||
|
||||
for value in (1, 2, 3):
|
||||
source.fill_(value)
|
||||
cap.replay()
|
||||
cuda_capture_stream.synchronize()
|
||||
torch.testing.assert_close(output, source, rtol=0, atol=0)
|
||||
torch.testing.assert_close(scale_out, source[:, ::32].to(torch.uint8))
|
||||
|
||||
|
||||
def test_eager_attention_inside_multistream_overlap(cuda_capture_stream):
|
||||
"""Handle an eager attention break inside a multi-stream overlap region."""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
from vllm.utils.multi_stream_utils import maybe_execute_in_parallel
|
||||
|
||||
x = torch.zeros(1024, device=DEVICE_TYPE)
|
||||
output = torch.empty_like(x)
|
||||
aux_stream = torch.cuda.Stream()
|
||||
main_event = torch.cuda.Event()
|
||||
aux_event = torch.cuda.Event()
|
||||
|
||||
@eager_break_during_capture
|
||||
def attention(query: torch.Tensor, out: torch.Tensor) -> None:
|
||||
torch.add(query, 3.0, out=out)
|
||||
|
||||
def attention_frontend() -> torch.Tensor:
|
||||
query = x * 2.0
|
||||
attention_output = torch.empty_like(x)
|
||||
attention(query, attention_output)
|
||||
return attention_output
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
attention_output, gate = maybe_execute_in_parallel(
|
||||
attention_frontend,
|
||||
lambda: x * 5.0,
|
||||
main_event,
|
||||
aux_event,
|
||||
aux_stream,
|
||||
)
|
||||
torch.add(attention_output, gate, out=output)
|
||||
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
|
||||
for value in (1.0, 7.0, 19.0):
|
||||
x.fill_(value)
|
||||
cap.replay()
|
||||
cuda_capture_stream.synchronize()
|
||||
torch.testing.assert_close(
|
||||
output,
|
||||
torch.full_like(output, value * 7.0 + 3.0),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Replay ordering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_replay_invokes_eager_segments_in_order(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
log: list[str] = []
|
||||
x = torch.zeros(1, device=DEVICE_TYPE)
|
||||
|
||||
def make_eager(name):
|
||||
def step():
|
||||
log.append(name)
|
||||
x.add_(1.0)
|
||||
|
||||
return step
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("A"))
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("B"))
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("C"))
|
||||
x.add_(1.0)
|
||||
|
||||
# Capture-time invocation order
|
||||
assert log == ["A", "B", "C"]
|
||||
|
||||
log.clear()
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert log == ["A", "B", "C"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Capture cleanup releases thread-local even if body raises
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_exception_in_body_clears_active(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with pytest.raises(RuntimeError, match="boom"), cap:
|
||||
raise RuntimeError("boom")
|
||||
|
||||
# active must be reset even after an exception inside the body
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Nested decorated ops: inner op must not trigger a recursive eager break
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_nested_decorated_op_runs_inline(cuda_capture_stream):
|
||||
"""A decorated op invoked from inside another decorated op's eager
|
||||
body must execute inline -- starting a second eager break mid-flight
|
||||
corrupts the segment state and explodes ``_begin_segment``'s assert.
|
||||
|
||||
This mirrors the deepseek_v4_attention case where the outer attention
|
||||
op's impl internally dispatches sparse_attn_indexer (also decorated).
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
inner_calls = 0
|
||||
|
||||
@eager_break_during_capture
|
||||
def inner_op(t: torch.Tensor) -> None:
|
||||
nonlocal inner_calls
|
||||
inner_calls += 1
|
||||
t.add_(1.0)
|
||||
|
||||
@eager_break_during_capture
|
||||
def outer_op(t: torch.Tensor) -> None:
|
||||
# outer body calls another decorated op -- this is the case that
|
||||
# used to assert in _begin_segment.
|
||||
inner_op(t)
|
||||
t.add_(10.0)
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(2.0) # recorded in graph[0]
|
||||
outer_op(x) # one eager break, inner runs inline
|
||||
x.add_(100.0) # recorded in graph[1]
|
||||
|
||||
# Exactly one eager break (the outer); inner must NOT add a second.
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
assert inner_calls == 1 # only the capture-time invocation
|
||||
|
||||
x.fill_(0.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
# 0 -> +2 -> +1 (inner) -> +10 (outer) -> +100 = 113
|
||||
assert torch.equal(x, torch.full((4,), 113.0, device=DEVICE_TYPE))
|
||||
assert inner_calls == 2 # replay invokes the outer's lambda again
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BreakableCUDAGraphWrapper: runtime_mode dispatch gating
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _mock_vllm_config():
|
||||
config = MagicMock()
|
||||
config.parallel_config.data_parallel_size = 1
|
||||
config.parallel_config.use_sequence_parallel_moe = False
|
||||
config.parallel_config.is_moe_model = False
|
||||
return config
|
||||
|
||||
|
||||
def test_wrapper_falls_through_on_runtime_mode_mismatch():
|
||||
"""A PIECEWISE-scoped wrapper runs other modes eagerly, capturing
|
||||
nothing, so an outer CUDAGraphWrapper can own them."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
calls = []
|
||||
|
||||
def model(x):
|
||||
calls.append(x)
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
with set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=desc,
|
||||
):
|
||||
assert wrapper(1) == 2
|
||||
|
||||
assert calls == [1]
|
||||
assert not wrapper.entries
|
||||
|
||||
|
||||
def test_wrapper_captures_on_runtime_mode_match():
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
calls = []
|
||||
|
||||
def model(x):
|
||||
calls.append(x)
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
sentinel = object()
|
||||
with (
|
||||
patch.object(
|
||||
BreakableCUDAGraphWrapper, "_capture", return_value=sentinel
|
||||
) as mock_capture,
|
||||
set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
|
||||
batch_descriptor=desc,
|
||||
),
|
||||
):
|
||||
assert wrapper(1) is sentinel
|
||||
|
||||
mock_capture.assert_called_once()
|
||||
assert calls == []
|
||||
assert desc in wrapper.entries
|
||||
|
||||
|
||||
def test_wrapper_default_matches_any_non_none_mode():
|
||||
"""runtime_mode=None matches any non-NONE mode (MRV2 relies on this)."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
def model(x):
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(model, config)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
sentinel = object()
|
||||
with (
|
||||
patch.object(
|
||||
BreakableCUDAGraphWrapper, "_capture", return_value=sentinel
|
||||
) as mock_capture,
|
||||
set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=desc,
|
||||
),
|
||||
):
|
||||
assert wrapper(1) is sentinel
|
||||
|
||||
mock_capture.assert_called_once()
|
||||
assert desc in wrapper.entries
|
||||
|
||||
|
||||
def test_unwrap_recurses_through_nested_wrappers():
|
||||
"""unwrap() reaches the raw model through nested wrappers."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.compilation.cuda_graph import CUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
|
||||
def model(x):
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
inner = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
outer = CUDAGraphWrapper(inner, config, runtime_mode=CUDAGraphMode.FULL)
|
||||
|
||||
assert inner.unwrap() is model
|
||||
assert outer.unwrap() is model
|
||||
@@ -1,578 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import replace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from tests.utils import create_new_process_for_each_test
|
||||
from vllm.compilation.cuda_graph import CUDAGraphWrapper
|
||||
from vllm.compilation.monitor import set_cudagraph_capturing_enabled
|
||||
from vllm.config import (
|
||||
CompilationConfig,
|
||||
CompilationMode,
|
||||
CUDAGraphMode,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.lora import LoRAConfig
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.cudagraph_dispatcher import CudagraphDispatcher
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
HAS_DEVICE_GRAPH = current_platform.is_cuda() or current_platform.is_xpu()
|
||||
|
||||
if current_platform.is_xpu():
|
||||
from vllm.v1.worker.xpu_model_runner import _torch_cuda_wrapper
|
||||
|
||||
# Route torch.cuda graph/stream APIs to torch.xpu, as XPUModelRunner does.
|
||||
with _torch_cuda_wrapper():
|
||||
pass
|
||||
|
||||
|
||||
# Helper MLP for testing
|
||||
class SimpleMLP(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(10, 10)
|
||||
self.fc2 = nn.Linear(10, 10)
|
||||
|
||||
def forward(self, x):
|
||||
return self.fc2(self.fc1(x))
|
||||
|
||||
|
||||
def _create_vllm_config(
|
||||
compilation_config: CompilationConfig,
|
||||
max_num_seqs: int = 8,
|
||||
lora_config: bool = False,
|
||||
) -> MagicMock:
|
||||
mock_config = MagicMock(spec=VllmConfig)
|
||||
mock_config.compilation_config = compilation_config
|
||||
mock_config.scheduler_config = SchedulerConfig.default_factory(
|
||||
max_num_seqs=max_num_seqs,
|
||||
)
|
||||
mock_config.parallel_config = ParallelConfig()
|
||||
mock_config.speculative_config = None # No speculative decoding
|
||||
mock_config.num_speculative_tokens = 0
|
||||
mock_config.use_cumem_cudagraph_pool = False
|
||||
if not lora_config:
|
||||
mock_config.lora_config = None
|
||||
else:
|
||||
# Create a real LoRAConfig with specialize_active_lora enabled
|
||||
mock_config.lora_config = LoRAConfig(
|
||||
max_loras=4,
|
||||
specialize_active_lora=True,
|
||||
)
|
||||
# Mimic the behavior of VllmConfig.__post_init__()
|
||||
if compilation_config.mode == CompilationMode.VLLM_COMPILE:
|
||||
compilation_config.set_splitting_ops_for_v1(
|
||||
all2all_backend=mock_config.parallel_config.all2all_backend,
|
||||
data_parallel_size=mock_config.parallel_config.data_parallel_size,
|
||||
)
|
||||
|
||||
# mimic VllmConfig.__post_init__
|
||||
if compilation_config.cudagraph_capture_sizes:
|
||||
compilation_config.max_cudagraph_capture_size = (
|
||||
compilation_config.cudagraph_capture_sizes[-1]
|
||||
)
|
||||
|
||||
compilation_config.post_init_cudagraph_sizes()
|
||||
|
||||
return mock_config
|
||||
|
||||
|
||||
class TestCudagraphDispatcher:
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode_str,compilation_mode,lora_config",
|
||||
[
|
||||
# Test case 0: Full CG for mixed batches, no separate routine
|
||||
("FULL", CompilationMode.NONE, False),
|
||||
# Test case 1: Full CG for uniform batches, piecewise for mixed
|
||||
("FULL_AND_PIECEWISE", CompilationMode.NONE, False),
|
||||
# Test case 2: Full CG for uniform batches, no CG for mixed
|
||||
("FULL_DECODE_ONLY", CompilationMode.NONE, False),
|
||||
# Test case 3: PIECEWISE for all
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, False),
|
||||
# Test case 4: PIECEWISE for all, specialize LoRA cases
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, True),
|
||||
],
|
||||
)
|
||||
def test_dispatcher(self, cudagraph_mode_str, compilation_mode, lora_config):
|
||||
# Setup dispatcher
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=cudagraph_mode_str,
|
||||
mode=compilation_mode,
|
||||
cudagraph_capture_sizes=[1, 8],
|
||||
)
|
||||
|
||||
config = _create_vllm_config(
|
||||
comp_config, max_num_seqs=8, lora_config=lora_config
|
||||
)
|
||||
if (
|
||||
cudagraph_mode_str == "FULL_AND_PIECEWISE"
|
||||
and compilation_mode == CompilationMode.NONE
|
||||
):
|
||||
with pytest.raises(AssertionError):
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
return
|
||||
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
cudagraph_mode=comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
|
||||
# Verify the key is initialized correctly
|
||||
# With LoRA specialization (max_loras=4, specialize_active_lora=True):
|
||||
# - lora_cases = [0, 1, 2, 4, 5] (no-lora + powers of 2 up to 4 + max_loras+1)
|
||||
# - capture_sizes = [1, 8]
|
||||
# - Total keys = 2 sizes × 5 lora_cases = 10
|
||||
if cudagraph_mode_str in ["FULL_AND_PIECEWISE", "PIECEWISE"]:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.PIECEWISE]) == (
|
||||
10 if lora_config else 2
|
||||
)
|
||||
else:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.PIECEWISE]) == 0
|
||||
if cudagraph_mode_str not in ["NONE", "PIECEWISE"]:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.FULL]) == (
|
||||
10 if lora_config else 2
|
||||
)
|
||||
else:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.FULL]) == 0
|
||||
|
||||
# Test dispatch logic
|
||||
# 1. non-uniform batch, size in cudagraph size list
|
||||
# FULL mode uses exact keys with num_reqs set
|
||||
desc_full_with_reqs = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=False)
|
||||
# PIECEWISE mode uses relaxed keys with num_reqs=None
|
||||
desc_piecewise = BatchDescriptor(num_tokens=8, num_reqs=None, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8, uniform_decode=False, has_lora=False
|
||||
)
|
||||
if cudagraph_mode_str == "FULL":
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_full_with_reqs
|
||||
elif cudagraph_mode_str in ["FULL_AND_PIECEWISE", "PIECEWISE"]:
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == desc_piecewise
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 2. uniform decode batch, size in cudagraph size list
|
||||
desc_uniform_exact = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=True)
|
||||
desc_non_uniform = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8, uniform_decode=True, has_lora=False
|
||||
)
|
||||
if cudagraph_mode_str == "FULL":
|
||||
# Pure FULL mode uses non-uniform keys for all batches
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_non_uniform
|
||||
elif cudagraph_mode_str in ["FULL_DECODE_ONLY", "FULL_AND_PIECEWISE"]:
|
||||
# These modes have separate uniform decode keys
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_uniform_exact
|
||||
elif cudagraph_mode_str == "PIECEWISE":
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == replace(desc_uniform_exact, num_reqs=None, uniform=False)
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 3. No key match
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=15, uniform_decode=False, has_lora=False
|
||||
)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
assert key == BatchDescriptor(num_tokens=15)
|
||||
|
||||
# 4. invalid_modes={FULL} should have a fall back mode
|
||||
desc_full_exact = BatchDescriptor(num_tokens=8, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8,
|
||||
uniform_decode=False,
|
||||
has_lora=False,
|
||||
invalid_modes={CUDAGraphMode.FULL},
|
||||
)
|
||||
|
||||
if "PIECEWISE" in cudagraph_mode_str: # string contains check
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == replace(desc_full_exact, num_reqs=None, uniform=False)
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 5. valid_modes={NONE} always returns NONE even when keys exist
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8,
|
||||
uniform_decode=False,
|
||||
has_lora=False,
|
||||
valid_modes={CUDAGraphMode.NONE},
|
||||
)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
assert key == BatchDescriptor(num_tokens=8)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode_str,compilation_mode,expected_modes",
|
||||
[
|
||||
# FULL mode: only FULL keys, no PIECEWISE
|
||||
("FULL", CompilationMode.NONE, [CUDAGraphMode.FULL]),
|
||||
# PIECEWISE mode: only PIECEWISE keys
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, [CUDAGraphMode.PIECEWISE]),
|
||||
# FULL_DECODE_ONLY: only FULL keys for uniform decode
|
||||
("FULL_DECODE_ONLY", CompilationMode.NONE, [CUDAGraphMode.FULL]),
|
||||
# NONE mode: no keys
|
||||
("NONE", CompilationMode.NONE, []),
|
||||
],
|
||||
)
|
||||
def test_get_capture_descs(
|
||||
self, cudagraph_mode_str, compilation_mode, expected_modes
|
||||
):
|
||||
"""Test get_capture_descs returns correctly grouped and ordered descs."""
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=cudagraph_mode_str,
|
||||
mode=compilation_mode,
|
||||
cudagraph_capture_sizes=[1, 4, 8, 16],
|
||||
)
|
||||
|
||||
config = _create_vllm_config(comp_config, max_num_seqs=16)
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
cudagraph_mode=comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
|
||||
capture_descs = dispatcher.get_capture_descs()
|
||||
|
||||
# Verify we get the expected modes
|
||||
actual_modes = [mode for mode, _ in capture_descs]
|
||||
assert actual_modes == expected_modes
|
||||
|
||||
# Verify each group is sorted largest-first
|
||||
for mode, descs in capture_descs:
|
||||
assert len(descs) > 0, "Each group should have at least one descriptor"
|
||||
num_tokens_list = [d.num_tokens for d in descs]
|
||||
assert num_tokens_list == sorted(num_tokens_list, reverse=True), (
|
||||
f"Descriptors for {mode} should be sorted largest-first"
|
||||
)
|
||||
|
||||
# All descriptors in a group should have same uniform value
|
||||
uniform_values = [d.uniform for d in descs]
|
||||
assert len(set(uniform_values)) == 1, (
|
||||
"All descriptors in a group should have the same uniform value"
|
||||
)
|
||||
|
||||
def test_get_capture_descs_empty_when_not_initialized(self):
|
||||
"""Test that get_capture_descs returns empty list when keys not initialized."""
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
mode=CompilationMode.NONE,
|
||||
cudagraph_capture_sizes=[1, 8],
|
||||
)
|
||||
config = _create_vllm_config(comp_config, max_num_seqs=8)
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
# Don't initialize keys
|
||||
|
||||
assert dispatcher.get_capture_descs() == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
class TestCUDAGraphWrapper:
|
||||
def setup_method(self):
|
||||
self.vllm_config = _create_vllm_config(CompilationConfig())
|
||||
self.model = SimpleMLP().to(DEVICE_TYPE)
|
||||
self.persistent_input_buffer = torch.zeros(1, 10, device=DEVICE_TYPE)
|
||||
self.input_tensor = torch.randn(1, 10, device=DEVICE_TYPE)
|
||||
|
||||
def test_capture_and_replay(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
|
||||
# 1. Capture
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
):
|
||||
output1 = wrapper(self.input_tensor)
|
||||
# capturing phase should generate a zero output
|
||||
assert torch.allclose(output1, torch.zeros_like(output1))
|
||||
mock_cuda_graph.assert_called_once()
|
||||
|
||||
assert batch_descriptor in wrapper.concrete_cudagraph_entries
|
||||
entry = wrapper.concrete_cudagraph_entries[batch_descriptor]
|
||||
assert entry.cudagraph is not None
|
||||
|
||||
# 2. Replay
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch.object(
|
||||
entry.cudagraph, "replay", wraps=entry.cudagraph.replay
|
||||
) as mock_replay,
|
||||
):
|
||||
output2 = wrapper(self.input_tensor)
|
||||
mock_replay.assert_called_once()
|
||||
|
||||
# Compare with eager output
|
||||
eager_output = self.model(self.input_tensor)
|
||||
torch.testing.assert_close(eager_output, output2)
|
||||
|
||||
def test_bypass_on_mode_mismatch(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
patch.object(
|
||||
self.model, "forward", wraps=self.model.forward
|
||||
) as mock_forward,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
mock_cuda_graph.assert_not_called()
|
||||
mock_forward.assert_called_once()
|
||||
assert not wrapper.concrete_cudagraph_entries
|
||||
|
||||
def test_bypass_on_mode_none(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
mock_cuda_graph.assert_not_called()
|
||||
assert not wrapper.concrete_cudagraph_entries
|
||||
|
||||
|
||||
def _run_and_monitor_call(
|
||||
wrapper, input_tensor, runtime_mode, batch_descriptor, vllm_config
|
||||
):
|
||||
"""Helper to run a single call and monitor the action."""
|
||||
with (
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_graph_context,
|
||||
patch.object(wrapper, "runnable", wraps=wrapper.runnable) as mock_runnable,
|
||||
):
|
||||
entry = wrapper.concrete_cudagraph_entries.get(batch_descriptor, None)
|
||||
|
||||
context = set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=runtime_mode,
|
||||
batch_descriptor=batch_descriptor,
|
||||
)
|
||||
mock_replay = MagicMock()
|
||||
if entry and entry.cudagraph:
|
||||
with (
|
||||
context,
|
||||
patch.object(
|
||||
entry.cudagraph, "replay", new_callable=MagicMock
|
||||
) as mock_replay,
|
||||
):
|
||||
wrapper(input_tensor)
|
||||
else:
|
||||
with context:
|
||||
wrapper(input_tensor)
|
||||
|
||||
if mock_graph_context.called:
|
||||
# note that this is globally mocked, so it will be detected
|
||||
# even whether called by the inner or outer wrapper
|
||||
return "capture_global"
|
||||
if mock_replay.called:
|
||||
# only for outer wrapper
|
||||
return "replay"
|
||||
if mock_runnable.call_count > 0:
|
||||
# only for outer wrapper
|
||||
return "bypass"
|
||||
return "unknown"
|
||||
|
||||
|
||||
@create_new_process_for_each_test("spawn")
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
def test_capture_replay_bypass_logic():
|
||||
comp_config = CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
cudagraph_capture_sizes=[1, 2],
|
||||
)
|
||||
vllm_config = _create_vllm_config(comp_config)
|
||||
dispatcher = CudagraphDispatcher(vllm_config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
model = SimpleMLP().to(DEVICE_TYPE)
|
||||
full_wrapper = CUDAGraphWrapper(model, vllm_config, CUDAGraphMode.FULL)
|
||||
max_bs = 16
|
||||
persistent_input_buffer = torch.zeros(max_bs, 10, device=DEVICE_TYPE)
|
||||
input_1 = persistent_input_buffer[:1]
|
||||
input_2 = persistent_input_buffer[:2]
|
||||
input_3 = persistent_input_buffer[:3]
|
||||
|
||||
desc_1 = BatchDescriptor(num_tokens=1)
|
||||
desc_2 = BatchDescriptor(num_tokens=2)
|
||||
desc_3_unseen = BatchDescriptor(num_tokens=3)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
full_wrapper(input_1)
|
||||
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_1.num_tokens)
|
||||
# 1. Capture first shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_1, rt_mode, key, vllm_config)
|
||||
assert action == "capture_global"
|
||||
|
||||
# 2. Replay first shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_1, rt_mode, key, vllm_config)
|
||||
assert action == "replay"
|
||||
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_2.num_tokens)
|
||||
# 3. Capture second shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_2, rt_mode, key, vllm_config)
|
||||
assert action == "capture_global"
|
||||
|
||||
# 4. Replay second shape
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_2, CUDAGraphMode.FULL, key, vllm_config
|
||||
)
|
||||
assert action == "replay"
|
||||
|
||||
# 5. Bypass if no key match
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_3_unseen.num_tokens)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
action = _run_and_monitor_call(full_wrapper, input_3, rt_mode, key, vllm_config)
|
||||
assert action == "bypass"
|
||||
|
||||
# capture unseen shape is not allowed after disable
|
||||
set_cudagraph_capturing_enabled(False)
|
||||
with pytest.raises(RuntimeError):
|
||||
_run_and_monitor_call(
|
||||
full_wrapper, input_3, CUDAGraphMode.FULL, desc_3_unseen, vllm_config
|
||||
)
|
||||
set_cudagraph_capturing_enabled(True)
|
||||
|
||||
|
||||
@create_new_process_for_each_test("spawn")
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
def test_nested_wrappers():
|
||||
"""Tests a scenario with a PIECEWISE wrapper inside a FULL one."""
|
||||
comp_config = CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
cudagraph_capture_sizes=[1],
|
||||
)
|
||||
vllm_config = _create_vllm_config(comp_config)
|
||||
dispatcher = CudagraphDispatcher(vllm_config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
model = SimpleMLP().to(DEVICE_TYPE)
|
||||
full_wrapper = CUDAGraphWrapper(model, vllm_config, CUDAGraphMode.FULL)
|
||||
input_1 = torch.randn(1, 10, device=DEVICE_TYPE)
|
||||
|
||||
# Setup: Inner model is wrapped with PIECEWISE, outer with FULL
|
||||
inner_model = SimpleMLP().to(DEVICE_TYPE)
|
||||
piecewise_wrapper = CUDAGraphWrapper(
|
||||
inner_model, vllm_config, CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
inner_model.forward = MagicMock(wraps=inner_model.forward)
|
||||
outer_model = SimpleMLP().to(DEVICE_TYPE)
|
||||
# When outer model is called, it calls the piecewise_wrapper
|
||||
outer_model.forward = MagicMock(
|
||||
wraps=outer_model.forward, side_effect=piecewise_wrapper
|
||||
)
|
||||
full_wrapper = CUDAGraphWrapper(outer_model, vllm_config, CUDAGraphMode.FULL)
|
||||
|
||||
desc_1 = BatchDescriptor(num_tokens=1)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
full_wrapper(input_1)
|
||||
|
||||
# --- Test runtime mode FULL---
|
||||
# Run with FULL mode context. Expect outer wrapper to capture.
|
||||
# The inner mock should be called once inside the graph capture.
|
||||
outer_model.forward.reset_mock()
|
||||
inner_model.forward.reset_mock()
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.FULL, desc_1, vllm_config
|
||||
)
|
||||
assert action == "capture_global"
|
||||
assert outer_model.forward.call_count == 1
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# Run again. Expect outer wrapper to replay.
|
||||
# The outer model should NOT be called because the whole graph
|
||||
# is replayed.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.FULL, desc_1, vllm_config
|
||||
)
|
||||
assert action == "replay"
|
||||
assert outer_model.forward.call_count == 1 # No new call
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# --- Test runtime mode PIECEWISE ---
|
||||
outer_model.forward.reset_mock()
|
||||
inner_model.forward.reset_mock()
|
||||
# Run with PIECEWISE mode context.
|
||||
# Expect outer wrapper to bypass and call inner wrapper.
|
||||
# Inner wrapper should capture.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.PIECEWISE, desc_1, vllm_config
|
||||
)
|
||||
assert action == "capture_global"
|
||||
assert outer_model.forward.call_count == 1
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# Run again with PIECEWISE.
|
||||
# Outer bypasses, inner replays.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.PIECEWISE, desc_1, vllm_config
|
||||
)
|
||||
assert action == "bypass"
|
||||
assert outer_model.forward.call_count == 2
|
||||
assert inner_model.forward.call_count == 1
|
||||
@@ -1,123 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import create_new_process_for_each_test
|
||||
from tests.v1.attention.utils import full_cg_backend_configs as backend_configs
|
||||
from vllm import LLM
|
||||
from vllm.config import CompilationConfig, CompilationMode
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# test attention backend and cudagraph_mode combo
|
||||
# (backend_name, cudagraph_mode, supported)
|
||||
if current_platform.is_rocm():
|
||||
combo_cases_1 = [
|
||||
("RocmAttn", "FULL", True),
|
||||
("RocmAttn", "FULL_AND_PIECEWISE", True),
|
||||
("TritonAttn", "FULL", True),
|
||||
("TritonAttn", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
elif current_platform.is_xpu():
|
||||
combo_cases_1 = [
|
||||
("FA2", "FULL", True),
|
||||
("FA2", "FULL_AND_PIECEWISE", True),
|
||||
("TritonAttn", "FULL", True),
|
||||
("TritonAttn", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
else:
|
||||
combo_cases_1 = [
|
||||
("FA3", "FULL", True),
|
||||
("FA3", "FULL_AND_PIECEWISE", True),
|
||||
("FA2", "FULL", True), # Should fallback to FULL_AND_PIECEWISE
|
||||
("FA2", "FULL_AND_PIECEWISE", True),
|
||||
("FlashInfer", "FULL", True), # Should fallback to FULL_AND_PIECEWISE
|
||||
("FlashInfer", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend_name, cudagraph_mode, supported", combo_cases_1)
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_backend_and_cudagraph_mode_combo(backend_name, cudagraph_mode, supported):
|
||||
if backend_name == "FlashInfer":
|
||||
try:
|
||||
import flashinfer # noqa: F401
|
||||
except ImportError:
|
||||
pytest.skip("FlashInfer is not installed")
|
||||
backend_config = backend_configs[backend_name]
|
||||
# Dynamically skip test if GPU capability is not met
|
||||
if (
|
||||
backend_config.specific_gpu_arch
|
||||
and backend_config.specific_gpu_arch != current_platform.get_device_capability()
|
||||
):
|
||||
pytest.skip("Only Hopper GPUs support FA3 and FlashMLA")
|
||||
|
||||
attention_config = backend_config.attention_config
|
||||
|
||||
with ExitStack() as stack:
|
||||
if not supported:
|
||||
stack.enter_context(pytest.raises(Exception))
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen2-1.5B-Instruct",
|
||||
max_num_seqs=16,
|
||||
max_num_batched_tokens=128,
|
||||
trust_remote_code=True,
|
||||
gpu_memory_utilization=0.45,
|
||||
max_model_len=1024,
|
||||
attention_config=attention_config,
|
||||
compilation_config=CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
cudagraph_capture_sizes=[1, 2, 4, 8, 16, 64, 128],
|
||||
),
|
||||
)
|
||||
llm.generate(["Hello, my name is"] * 10)
|
||||
|
||||
|
||||
# test cudagraph_mode with different compilation mode.
|
||||
# (backend_name, cudagraph_mode, compilation_mode, supported)
|
||||
attn_backend = "RocmAttn" if current_platform.is_rocm() else "FA2"
|
||||
|
||||
combo_cases_2 = [
|
||||
(attn_backend, "FULL", CompilationMode.NONE, True),
|
||||
(attn_backend, "PIECEWISE", CompilationMode.NONE, True),
|
||||
(attn_backend, "PIECEWISE", CompilationMode.VLLM_COMPILE, True),
|
||||
(attn_backend, "FULL_AND_PIECEWISE", CompilationMode.NONE, True),
|
||||
(attn_backend, "FULL_DECODE_ONLY", CompilationMode.NONE, True),
|
||||
(attn_backend, "FULL_DECODE_ONLY", CompilationMode.VLLM_COMPILE, True),
|
||||
(attn_backend, "NONE", CompilationMode.NONE, True),
|
||||
(attn_backend, "NONE", CompilationMode.VLLM_COMPILE, True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_name,cudagraph_mode,compilation_mode,supported", combo_cases_2
|
||||
)
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_cudagraph_compilation_combo(
|
||||
backend_name, cudagraph_mode, compilation_mode, supported
|
||||
):
|
||||
backend_config = backend_configs[backend_name]
|
||||
attention_config = backend_config.attention_config
|
||||
|
||||
with ExitStack() as stack:
|
||||
if not supported:
|
||||
stack.enter_context(pytest.raises(Exception))
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen2-1.5B-Instruct",
|
||||
max_num_seqs=16,
|
||||
max_num_batched_tokens=128,
|
||||
trust_remote_code=True,
|
||||
gpu_memory_utilization=0.45,
|
||||
max_model_len=1024,
|
||||
attention_config=attention_config,
|
||||
compilation_config=CompilationConfig(
|
||||
mode=compilation_mode,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
cudagraph_capture_sizes=[1, 2, 4, 8, 16, 64, 128],
|
||||
),
|
||||
)
|
||||
llm.generate(["Hello, my name is"] * 10)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,981 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AutoTokenizer
|
||||
from utils import (
|
||||
BACKENDS,
|
||||
TEST_MODEL,
|
||||
_extract_step_logprobs,
|
||||
_random_prompt,
|
||||
skip_if_not_cuda,
|
||||
skip_unsupported,
|
||||
)
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TokensPrompt
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.flaky(reruns=3)
|
||||
@pytest.mark.timeout(1000)
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
@pytest.mark.parametrize("rms_norm_impl", ["default", "vllm_c"])
|
||||
def test_v1_generation_is_deterministic_across_batch_sizes_with_needle(
|
||||
backend,
|
||||
rms_norm_impl,
|
||||
):
|
||||
"""Ensures that the same request (the 'needle' prompt) yields identical output
|
||||
whether run alone (bs=1) or mixed into a larger batch (e.g., bs=64),
|
||||
using the high-level v1 LLM() API only (no manual batching).
|
||||
|
||||
Strategy:
|
||||
- Create a single LLM engine configured for the larger batch limit (N).
|
||||
- Compute a baseline output for the needle prompt when it is run alone.
|
||||
- For many trials, generate a mixed batch (size N) where the needle appears
|
||||
at a random position among random filler prompts using the same engine.
|
||||
- Track how many trials match vs mismatch, and report totals at the end.
|
||||
The test fails if any mismatches occur, but we still dump pass/fail
|
||||
counts.
|
||||
|
||||
Notes:
|
||||
- Use seeded stochastic sampling with a fixed seed to test determinism.
|
||||
- Outputs are intentionally longer and sampled at higher temperature/top_p
|
||||
to produce a more random-sounding phrase, yet remain deterministic by
|
||||
seed.
|
||||
- Keep max_tokens and max_model_len bounded for speed and memory use.
|
||||
|
||||
"""
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
|
||||
attention_config = {"backend": backend}
|
||||
# Force the C++ RMSNorm implementation so we actually exercise the
|
||||
# num_tokens-dependent block-size branches.
|
||||
kernel_config = None
|
||||
if rms_norm_impl == "vllm_c":
|
||||
kernel_config = {
|
||||
"ir_op_priority": {
|
||||
"rms_norm": ["vllm_c"],
|
||||
"fused_add_rms_norm": ["vllm_c"],
|
||||
}
|
||||
}
|
||||
# Allow overrides from environment (useful for CI tuning)
|
||||
# "facebook/opt-125m" is too small, doesn't reliably test determinism
|
||||
model = TEST_MODEL
|
||||
num_trials = int(os.getenv("VLLM_NEEDLE_TRIALS", "5"))
|
||||
max_batch_size = int(os.getenv("VLLM_NEEDLE_BATCH_SIZE", "128"))
|
||||
min_random_prompt = int(os.getenv("VLLM_MIN_PROMPT", "1024"))
|
||||
max_random_prompt = int(os.getenv("VLLM_MAX_PROMPT", "2048"))
|
||||
assert max_batch_size >= 2, "Batch size should be >= 2 to mix needle."
|
||||
|
||||
# Keep GPU memory usage low to avoid startup allocation failures.
|
||||
gpu_mem_util = float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION", "0.5"))
|
||||
max_model_len = int(os.getenv("VLLM_MAX_MODEL_LEN", "5120"))
|
||||
|
||||
# Sampling parameters: longer outputs with a more random-sounding
|
||||
# continuation,but still deterministic due to fixed seed.
|
||||
temperature = float(os.getenv("VLLM_NEEDLE_TEMPERATURE", "0.0"))
|
||||
top_p = float(os.getenv("VLLM_NEEDLE_TOP_P", "0.95"))
|
||||
max_tokens = int(os.getenv("VLLM_NEEDLE_MAX_TOKENS", "128"))
|
||||
|
||||
sampling = SamplingParams(
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
max_tokens=max_tokens,
|
||||
seed=20240919,
|
||||
)
|
||||
|
||||
needle_prompt = "There once was a "
|
||||
|
||||
llm = None
|
||||
try:
|
||||
llm = LLM_with_max_seqs(
|
||||
model=model,
|
||||
max_num_seqs=max_batch_size,
|
||||
gpu_memory_utilization=gpu_mem_util,
|
||||
max_model_len=max_model_len,
|
||||
attention_config=attention_config,
|
||||
kernel_config=kernel_config,
|
||||
)
|
||||
|
||||
# Baseline generation for the needle prompt alone.
|
||||
baseline_out = llm.generate([needle_prompt], sampling)
|
||||
assert len(baseline_out) == 1
|
||||
assert len(baseline_out[0].outputs) >= 1
|
||||
baseline_text = baseline_out[0].outputs[0].text
|
||||
|
||||
mismatches = 0
|
||||
|
||||
for trial in range(num_trials):
|
||||
# Create a batch of size `max_batch_size` and insert the needle at
|
||||
# a random index
|
||||
prompts: list[str] = []
|
||||
batch_size = random.randint(max_batch_size // 2, max_batch_size)
|
||||
needle_pos = random.randint(0, batch_size - 1)
|
||||
for i in range(batch_size):
|
||||
if i == needle_pos:
|
||||
prompts.append(needle_prompt)
|
||||
else:
|
||||
prompts.append(_random_prompt(min_random_prompt, max_random_prompt))
|
||||
|
||||
# Generate with the same engine but in a larger batch.
|
||||
outputs = llm.generate(prompts, sampling)
|
||||
# Find the needle output by position
|
||||
needle_output = outputs[needle_pos]
|
||||
assert needle_output.prompt == needle_prompt
|
||||
assert len(needle_output.outputs) >= 1
|
||||
text = needle_output.outputs[0].text
|
||||
|
||||
if text != baseline_text:
|
||||
print(f"{text}\n\n== Not the same as ==\n\n{baseline_text}\n\n")
|
||||
mismatches += 1
|
||||
|
||||
passes = num_trials - mismatches
|
||||
# Dump how many passed vs failed
|
||||
print(
|
||||
f"[determinism] total={num_trials}, passed={passes}, "
|
||||
f"failed={mismatches}, max_batch_size={max_batch_size}"
|
||||
)
|
||||
|
||||
if mismatches > 0:
|
||||
pytest.fail(
|
||||
f"Nondeterministic outputs detected: {mismatches} failed out "
|
||||
f"of {num_trials} trials (max_batch_size={max_batch_size})."
|
||||
)
|
||||
|
||||
finally:
|
||||
# Ensure engines are shutdown to free GPU/VRAM across test sessions
|
||||
if llm is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"block_m,block_n",
|
||||
[(16, 16), (8, 16)],
|
||||
)
|
||||
def test_logprobs_bitwise_batch_invariance_bs1_vs_bsN(
|
||||
backend,
|
||||
block_m,
|
||||
block_n,
|
||||
):
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
disable_custom_all_reduce=os.getenv("VLLM_TEST_DISABLE_CUSTOM_AR") == "1",
|
||||
max_num_seqs=128,
|
||||
max_model_len=8192,
|
||||
dtype="auto", # not everything is supported
|
||||
gpu_memory_utilization=0.9,
|
||||
attention_config={
|
||||
"backend": backend,
|
||||
"flex_attn_block_m": block_m,
|
||||
"flex_attn_block_n": block_n,
|
||||
},
|
||||
)
|
||||
|
||||
# Use more realistic prompts for better token generation
|
||||
prompts = [_random_prompt(10, 50) for _ in range(32)]
|
||||
|
||||
# Chunked prefill is covered by
|
||||
# test_logprobs_bitwise_batch_invariance_ragged_chunked_prefill below.
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6,
|
||||
top_p=1.0,
|
||||
max_tokens=16,
|
||||
seed=1234,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
# BS=1: run prompts individually and collect logprobs per step.
|
||||
print("\n" + "=" * 80)
|
||||
print("STARTING BS=1 RUNS (each prompt individually)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
bs1_logprobs_per_prompt = []
|
||||
bs1_tokens_per_prompt = []
|
||||
for idx, p in enumerate(prompts):
|
||||
print(f"\n[BS=1] Running prompt {idx}/{len(prompts)} - Preview: {p[:80]}...")
|
||||
outs = llm.generate([p], sp, use_tqdm=False)
|
||||
assert len(outs) == 1
|
||||
step_logprobs, token_ids = _extract_step_logprobs(outs[0])
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bs1_logprobs_per_prompt.append(step_logprobs)
|
||||
bs1_tokens_per_prompt.append(token_ids)
|
||||
print(f"[BS=1] Prompt {idx} generated tokens: {token_ids}")
|
||||
|
||||
# BS=N: run prompts in a batch and collect logprobs per step for each
|
||||
# prompt.
|
||||
print("\n" + "=" * 80)
|
||||
print(f"STARTING BS={len(prompts)} RUN (all prompts batched)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
bsN_logprobs_per_prompt = []
|
||||
bsN_tokens_per_prompt = []
|
||||
|
||||
print(f"\n[BS={len(prompts)}] Processing batched outputs...")
|
||||
for idx, o in enumerate(outs_batched):
|
||||
tokens = o.outputs[0].token_ids if o.outputs else "N/A"
|
||||
print(f"[BS={len(prompts)}] Prompt {idx} generated tokens: {tokens}")
|
||||
step_logprobs, token_ids = _extract_step_logprobs(o)
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bsN_logprobs_per_prompt.append(step_logprobs)
|
||||
bsN_tokens_per_prompt.append(token_ids)
|
||||
|
||||
# Compare step-by-step logprobs for each prompt between BS=1 and BS=N runs.
|
||||
failed_prompts = []
|
||||
for i, (logprobs_bs1, logprobs_bsN, tokens_bs1, tokens_bsN) in enumerate(
|
||||
zip(
|
||||
bs1_logprobs_per_prompt,
|
||||
bsN_logprobs_per_prompt,
|
||||
bs1_tokens_per_prompt,
|
||||
bsN_tokens_per_prompt,
|
||||
)
|
||||
):
|
||||
if len(logprobs_bs1) != len(logprobs_bsN):
|
||||
reason = (
|
||||
f"Different number of steps: {len(logprobs_bs1)} (BS=1) "
|
||||
f"vs {len(logprobs_bsN)} (BS=N)"
|
||||
)
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "all",
|
||||
"reason": reason,
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# Check if tokens match first
|
||||
if tokens_bs1 != tokens_bsN:
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "sampling",
|
||||
"reason": "Different tokens sampled",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
"bs1_all_logprobs": [
|
||||
logprobs_bs1[s].tolist() for s in range(len(logprobs_bs1))
|
||||
],
|
||||
"bsN_all_logprobs": [
|
||||
logprobs_bsN[s].tolist() for s in range(len(logprobs_bsN))
|
||||
],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
for t, (a, b) in enumerate(zip(logprobs_bs1, logprobs_bsN)):
|
||||
if a.shape != b.shape:
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Shape mismatch: {a.shape} vs {b.shape}",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
if not torch.equal(a, b):
|
||||
max_diff = torch.abs(a - b).max().item()
|
||||
# Print which token failed
|
||||
print(f"\n[DIVERGENCE] Prompt {i}, Token {t}: max_diff={max_diff:.6e}")
|
||||
bs1_tok = tokens_bs1[t] if t < len(tokens_bs1) else "N/A"
|
||||
bsN_tok = tokens_bsN[t] if t < len(tokens_bsN) else "N/A"
|
||||
print(f" Token IDs: bs1={bs1_tok}, bsN={bsN_tok}")
|
||||
print(f" BS=1 logprob: {a.tolist()}")
|
||||
print(f" BS=N logprob: {b.tolist()}")
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Bitwise mismatch (max_diff={max_diff:.6e})",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
"bs1_all_logprobs": [
|
||||
logprobs_bs1[s].tolist() for s in range(len(logprobs_bs1))
|
||||
],
|
||||
"bsN_all_logprobs": [
|
||||
logprobs_bsN[s].tolist() for s in range(len(logprobs_bsN))
|
||||
],
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
# Print summary of all failures
|
||||
if failed_prompts:
|
||||
print(f"\n{'=' * 80}")
|
||||
fail_msg = (
|
||||
f"BATCH INVARIANCE FAILURES: {len(failed_prompts)}/"
|
||||
f"{len(prompts)} prompts failed"
|
||||
)
|
||||
print(fail_msg)
|
||||
print(f"{'=' * 80}")
|
||||
for fail in failed_prompts:
|
||||
print(f"\nPrompt {fail['prompt_idx']} (step {fail['step']}):")
|
||||
print(f" Reason: {fail['reason']}")
|
||||
print(f" Preview: {fail['prompt_preview']}...")
|
||||
|
||||
# Always show the tokens
|
||||
if "bs1_tokens" in fail:
|
||||
print(f" BS=1 tokens: {fail['bs1_tokens']}")
|
||||
if "bsN_tokens" in fail:
|
||||
print(f" BS=N tokens: {fail['bsN_tokens']}")
|
||||
|
||||
if "bs1_all_logprobs" in fail:
|
||||
print(f" BS=1 logprobs for all {len(fail['bs1_all_logprobs'])} steps:")
|
||||
for step_idx, logprobs in enumerate(fail["bs1_all_logprobs"]):
|
||||
print(f" Step {step_idx}: {logprobs}")
|
||||
print(f" BS=N logprobs for all {len(fail['bsN_all_logprobs'])} steps:")
|
||||
for step_idx, logprobs in enumerate(fail["bsN_all_logprobs"]):
|
||||
print(f" Step {step_idx}: {logprobs}")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
# Fail the test with summary
|
||||
msg = (
|
||||
f"Batch invariance violated in {len(failed_prompts)}/"
|
||||
f"{len(prompts)} prompts. See output above for details."
|
||||
)
|
||||
pytest.fail(msg)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_logprobs_bitwise_batch_invariance_ragged_chunked_prefill(backend):
|
||||
"""Batch invariance must hold when a prefill is split across chunks."""
|
||||
random.seed(int(os.getenv("VLLM_TEST_SEED", "12345")))
|
||||
|
||||
prompts = (
|
||||
[_random_prompt(10, 50) for _ in range(8)]
|
||||
+ [_random_prompt(300, 450) for _ in range(4)]
|
||||
+ [_random_prompt(800, 1200) for _ in range(2)]
|
||||
)
|
||||
random.shuffle(prompts)
|
||||
|
||||
# _random_prompt takes a word target, not a token count, and the ratio
|
||||
# depends on the tokenizer, so derive the budget rather than hardcode it:
|
||||
# half the longest prompt splits that prefill whatever TEST_MODEL is, while
|
||||
# the shorter prompts are still co-scheduled whole. Floor is max_num_seqs.
|
||||
tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL)
|
||||
prompt_lens = [len(tokenizer(p).input_ids) for p in prompts]
|
||||
max_num_batched_tokens = max(len(prompts), max(prompt_lens) // 2)
|
||||
assert max_num_batched_tokens < max(prompt_lens), (
|
||||
f"a {max_num_batched_tokens}-token budget does not split the longest "
|
||||
f"prompt ({max(prompt_lens)} tokens), so nothing would be chunked"
|
||||
)
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6, top_p=1.0, max_tokens=16, seed=1234, logprobs=5
|
||||
)
|
||||
llm = LLM_with_max_seqs(
|
||||
model=TEST_MODEL,
|
||||
max_num_seqs=len(prompts),
|
||||
gpu_memory_utilization=float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION", "0.5")),
|
||||
max_model_len=4096,
|
||||
attention_config={"backend": backend},
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
)
|
||||
|
||||
try:
|
||||
bs1 = []
|
||||
for p in prompts:
|
||||
out = llm.generate([p], sp, use_tqdm=False)[0]
|
||||
bs1.append(_extract_step_logprobs(out))
|
||||
if any(logprobs is None for logprobs, _ in bs1):
|
||||
pytest.skip("Logprobs are not available on RequestOutput.")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
|
||||
mismatches = []
|
||||
for i, out in enumerate(outs_batched):
|
||||
logprobs, tokens = _extract_step_logprobs(out)
|
||||
bs1_logprobs, bs1_tokens = bs1[i]
|
||||
n = prompt_lens[i]
|
||||
if tokens != bs1_tokens:
|
||||
mismatches.append(f"prompt {i} ({n} tokens): tokens differ")
|
||||
elif not torch.equal(bs1_logprobs, logprobs):
|
||||
delta = torch.max(torch.abs(bs1_logprobs - logprobs)).item()
|
||||
mismatches.append(
|
||||
f"prompt {i} ({n} tokens): logprobs differ, max|delta|={delta:.3e}"
|
||||
)
|
||||
|
||||
assert not mismatches, (
|
||||
"Batch invariance violated under chunked prefill "
|
||||
f"(max_num_batched_tokens={max_num_batched_tokens}): "
|
||||
+ "; ".join(mismatches)
|
||||
)
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_simple_generation(backend):
|
||||
"""Simple test that runs the model with a basic prompt and prints the output.
|
||||
Useful for quick smoke testing and debugging.
|
||||
"""
|
||||
model = TEST_MODEL
|
||||
|
||||
llm = LLM(
|
||||
model=model,
|
||||
max_num_seqs=1,
|
||||
tensor_parallel_size=int(os.getenv("VLLM_TP_SIZE", "1")),
|
||||
gpu_memory_utilization=0.9,
|
||||
max_model_len=2048,
|
||||
dtype="auto",
|
||||
enable_prefix_caching=False,
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
prompt = "the capital of france is"
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=20,
|
||||
)
|
||||
|
||||
print(f"\n{'=' * 80}")
|
||||
print("Running simple generation test")
|
||||
print(f"Prompt: '{prompt}'")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
try:
|
||||
outputs = llm.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1
|
||||
output_text = outputs[0].outputs[0].text
|
||||
|
||||
print(f"Output: '{output_text}'")
|
||||
print(f"\n{'=' * 80}")
|
||||
print(f"Full completion: '{prompt}{output_text}'")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_logprobs_without_batch_invariance_should_fail(
|
||||
backend, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""This test is the inverse of test_logprobs_bitwise_batch_invariance_bs1_vs_bsN.
|
||||
It DISABLES batch invariance mode and expects to see non-deterministic behavior
|
||||
between BS=1 and BS=N runs. This demonstrates that batch invariance is actually
|
||||
doing something useful.
|
||||
|
||||
The test will PASS if we detect differences (proving batch invariance matters).
|
||||
The test will FAIL if everything matches (suggesting batch invariance isn't needed).
|
||||
"""
|
||||
# CRITICAL: Disable batch invariance for this test
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
print(f"\n{'=' * 80}")
|
||||
print("BATCH INVARIANCE DISABLED: Expecting non-deterministic behavior")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
max_num_seqs=32,
|
||||
max_model_len=8192,
|
||||
dtype="auto",
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
# build ragged prompts to change shapes significantly across BS=1 vs BS=N
|
||||
long_min = int(os.getenv("VLLM_MIN_PROMPT", "768"))
|
||||
long_max = int(os.getenv("VLLM_MAX_PROMPT", "2048"))
|
||||
prompts: list[str] = []
|
||||
options = [
|
||||
(max(long_min, 1536), max(long_max, 3072)), # very long
|
||||
(max(1024, long_min), max(2048, long_max)), # long
|
||||
(256, 512), # mid
|
||||
(10, 20), # short
|
||||
]
|
||||
|
||||
for _ in range(32):
|
||||
lo, hi = random.choice(options)
|
||||
prompts.append(_random_prompt(lo, hi))
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6,
|
||||
top_p=1.0,
|
||||
max_tokens=8,
|
||||
seed=1234,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
# BS=1: run prompts individually and collect logprobs per step.
|
||||
print("\n" + "=" * 80)
|
||||
print("STARTING BS=1 RUNS (each prompt individually)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
bs1_logprobs_per_prompt = []
|
||||
bs1_tokens_per_prompt = []
|
||||
for idx, p in enumerate(prompts):
|
||||
print(f"\n[BS=1] Running prompt {idx}/{len(prompts)} - Preview: {p[:80]}...")
|
||||
outs = llm.generate([p], sp, use_tqdm=False)
|
||||
assert len(outs) == 1
|
||||
step_logprobs, token_ids = _extract_step_logprobs(outs[0])
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bs1_logprobs_per_prompt.append(step_logprobs)
|
||||
bs1_tokens_per_prompt.append(token_ids)
|
||||
print(f"[BS=1] Prompt {idx} generated tokens: {token_ids}")
|
||||
|
||||
# BS=N: run prompts in a batch and collect logprobs per step for each prompt.
|
||||
print("\n" + "=" * 80)
|
||||
print(f"STARTING BS={len(prompts)} RUN (all prompts batched)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
bsN_logprobs_per_prompt = []
|
||||
bsN_tokens_per_prompt = []
|
||||
|
||||
print(f"\n[BS={len(prompts)}] Processing batched outputs...")
|
||||
for idx, o in enumerate(outs_batched):
|
||||
tokens = o.outputs[0].token_ids if o.outputs else "N/A"
|
||||
print(f"[BS={len(prompts)}] Prompt {idx} generated tokens: {tokens}")
|
||||
step_logprobs, token_ids = _extract_step_logprobs(o)
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bsN_logprobs_per_prompt.append(step_logprobs)
|
||||
bsN_tokens_per_prompt.append(token_ids)
|
||||
|
||||
# Compare step-by-step logprobs for each prompt between BS=1 and BS=N runs.
|
||||
differences_found = []
|
||||
for i, (logprobs_bs1, logprobs_bsN, tokens_bs1, tokens_bsN) in enumerate(
|
||||
zip(
|
||||
bs1_logprobs_per_prompt,
|
||||
bsN_logprobs_per_prompt,
|
||||
bs1_tokens_per_prompt,
|
||||
bsN_tokens_per_prompt,
|
||||
)
|
||||
):
|
||||
if len(logprobs_bs1) != len(logprobs_bsN):
|
||||
reason = (
|
||||
f"Different number of steps: {len(logprobs_bs1)} (BS=1) "
|
||||
f"vs {len(logprobs_bsN)} (BS=N)"
|
||||
)
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "all",
|
||||
"reason": reason,
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# Check if tokens match first
|
||||
if tokens_bs1 != tokens_bsN:
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "sampling",
|
||||
"reason": "Different tokens sampled",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
for t, (a, b) in enumerate(zip(logprobs_bs1, logprobs_bsN)):
|
||||
if a.shape != b.shape:
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Shape mismatch: {a.shape} vs {b.shape}",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
if not torch.equal(a, b):
|
||||
max_diff = torch.abs(a - b).max().item()
|
||||
print(
|
||||
f"\n[EXPECTED DIVERGENCE FOUND] Prompt {i}, "
|
||||
f"Token {t}: max_diff={max_diff:.6e}"
|
||||
)
|
||||
bs1_tok = tokens_bs1[t] if t < len(tokens_bs1) else "N/A"
|
||||
bsN_tok = tokens_bsN[t] if t < len(tokens_bsN) else "N/A"
|
||||
print(f" Token IDs: bs1={bs1_tok}, bsN={bsN_tok}")
|
||||
print(f" BS=1 logprob: {a.tolist()}")
|
||||
print(f" BS=N logprob: {b.tolist()}")
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Bitwise mismatch (max_diff={max_diff:.6e})",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
# Print summary
|
||||
print(f"\n{'=' * 80}")
|
||||
if differences_found:
|
||||
success_msg = (
|
||||
f"✓ SUCCESS: Batch invariance is doing something! "
|
||||
f"Found {len(differences_found)}/{len(prompts)} prompts "
|
||||
f"with differences when batch invariance was DISABLED."
|
||||
)
|
||||
print(success_msg)
|
||||
print(f"{'=' * 80}")
|
||||
for diff in differences_found:
|
||||
print(f"\nPrompt {diff['prompt_idx']} (step {diff['step']}):")
|
||||
print(f" Reason: {diff['reason']}")
|
||||
print(f" Preview: {diff['prompt_preview']}...")
|
||||
if "bs1_tokens" in diff:
|
||||
print(f" BS=1 tokens: {diff['bs1_tokens']}")
|
||||
if "bsN_tokens" in diff:
|
||||
print(f" BS=N tokens: {diff['bsN_tokens']}")
|
||||
print(f"{'=' * 80}\n")
|
||||
# Test PASSES because we found differences (batch invariance matters!)
|
||||
return
|
||||
else:
|
||||
# Test FAILS because everything matched even without batch invariance
|
||||
fail_msg = (
|
||||
f"✗ UNEXPECTED: All {len(prompts)} prompts matched "
|
||||
f"between BS=1 and BS=N even with batch invariance DISABLED. "
|
||||
f"This suggests batch invariance might not be necessary, "
|
||||
f"or the test needs more sensitive prompts."
|
||||
)
|
||||
print(fail_msg)
|
||||
print(f"{'=' * 80}\n")
|
||||
pytest.fail(fail_msg)
|
||||
|
||||
|
||||
@skip_if_not_cuda
|
||||
@pytest.mark.parametrize("backend", ["FLASH_ATTN"])
|
||||
def test_decode_logprobs_match_prefill_logprobs(
|
||||
backend,
|
||||
):
|
||||
"""Test that verifies decode logprobs match prefill logprobs.
|
||||
|
||||
For each decoded token at position i:
|
||||
1. Run decode to generate N tokens and collect their logprobs
|
||||
2. For each position i in [0, N):
|
||||
- Take prefix = prompt + tokens[0:i]
|
||||
- Run prefill(prefix + tokens[i]) to get logprob of tokens[i]
|
||||
- Verify prefill logprob matches decode logprob bitwise
|
||||
|
||||
This ensures that the logprobs from decode are consistent with what
|
||||
we would get if we ran prefill on each prefix.
|
||||
"""
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
max_num_seqs=32,
|
||||
max_model_len=8192,
|
||||
dtype="auto",
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
# Use a few test prompts
|
||||
num_test_prompts = int(os.getenv("VLLM_DECODE_PREFILL_NUM_PROMPTS", "4"))
|
||||
prompts = [_random_prompt(10, 50) for _ in range(num_test_prompts)]
|
||||
|
||||
# Generate longer sequences to test multiple decode steps
|
||||
max_tokens = int(os.getenv("VLLM_DECODE_PREFILL_MAX_TOKENS", "16"))
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.0, # Greedy for determinism
|
||||
max_tokens=max_tokens,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
print("\n" + "=" * 80)
|
||||
print("STEP 1: Running decode to generate tokens and collect logprobs")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
# Step 1: Run decode and collect logprobs
|
||||
decode_outputs = llm.generate(prompts, sp, use_tqdm=False)
|
||||
|
||||
failed_comparisons = []
|
||||
|
||||
for prompt_idx, (prompt, decode_output) in enumerate(zip(prompts, decode_outputs)):
|
||||
print(f"\n[Prompt {prompt_idx}] Testing: {prompt[:80]}...")
|
||||
|
||||
# Extract decode logprobs and tokens
|
||||
decode_logprobs, token_ids = _extract_step_logprobs(decode_output)
|
||||
if decode_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logprobs are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
|
||||
print(f"[Prompt {prompt_idx}] Generated {len(token_ids)} tokens: {token_ids}")
|
||||
print(f"[Prompt {prompt_idx}] Decode logprobs: {decode_logprobs.tolist()}")
|
||||
|
||||
# Step 2: For each token position, run prefill and compare.
|
||||
prompt_token_ids = list(decode_output.prompt_token_ids or [])
|
||||
|
||||
print(f"\n[Prompt {prompt_idx}] Verifying each token via prefill...")
|
||||
|
||||
for token_idx in range(len(token_ids)):
|
||||
# Construct the prefix up to (but not including) this token using
|
||||
# token ids directly.
|
||||
current_token = token_ids[token_idx]
|
||||
prefix_token_ids = prompt_token_ids + list(token_ids[:token_idx])
|
||||
|
||||
# Now run prefill with max_tokens=1 to get the logprob of the next token
|
||||
prefill_sp = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=1,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
print(
|
||||
f" [Token {token_idx}] Running prefill for prefix "
|
||||
f"(num_tokens={len(prefix_token_ids)})..."
|
||||
)
|
||||
prefill_output = llm.generate(
|
||||
[TokensPrompt(prompt_token_ids=prefix_token_ids)],
|
||||
prefill_sp,
|
||||
use_tqdm=False,
|
||||
)[0]
|
||||
prefill_logprobs, prefill_token_ids_out = _extract_step_logprobs(
|
||||
prefill_output
|
||||
)
|
||||
|
||||
if prefill_logprobs is None:
|
||||
print(f" [Token {token_idx}] Warning: No prefill logprobs available")
|
||||
continue
|
||||
|
||||
# The first token from prefill should match the current token
|
||||
prefill_token = prefill_token_ids_out[0]
|
||||
prefill_logprob = prefill_logprobs[0].item()
|
||||
decode_logprob = decode_logprobs[token_idx].item()
|
||||
|
||||
print(
|
||||
f" [Token {token_idx}] Decode token: {current_token}, "
|
||||
f"logprob: {decode_logprob:.8f}"
|
||||
)
|
||||
print(
|
||||
f" [Token {token_idx}] Prefill token: {prefill_token}, "
|
||||
f"logprob: {prefill_logprob:.8f}"
|
||||
)
|
||||
|
||||
# Check if tokens match
|
||||
if current_token != prefill_token:
|
||||
failed_comparisons.append(
|
||||
{
|
||||
"prompt_idx": prompt_idx,
|
||||
"token_idx": token_idx,
|
||||
"reason": "Token mismatch",
|
||||
"decode_token": current_token,
|
||||
"prefill_token": prefill_token,
|
||||
"decode_logprob": decode_logprob,
|
||||
"prefill_logprob": prefill_logprob,
|
||||
"prompt_text": prompt[:100],
|
||||
"prefix_token_ids": prefix_token_ids[:50],
|
||||
}
|
||||
)
|
||||
print(f" [Token {token_idx}] ✗ TOKEN MISMATCH!")
|
||||
continue
|
||||
|
||||
# Check if logprobs match bitwise
|
||||
if decode_logprob != prefill_logprob:
|
||||
diff = abs(decode_logprob - prefill_logprob)
|
||||
failed_comparisons.append(
|
||||
{
|
||||
"prompt_idx": prompt_idx,
|
||||
"token_idx": token_idx,
|
||||
"reason": "Logprob mismatch",
|
||||
"decode_token": current_token,
|
||||
"prefill_token": prefill_token,
|
||||
"decode_logprob": decode_logprob,
|
||||
"prefill_logprob": prefill_logprob,
|
||||
"diff": diff,
|
||||
"prompt_text": prompt[:100],
|
||||
"prefix_token_ids": prefix_token_ids[:50],
|
||||
"decode_all_tokens": token_ids,
|
||||
"decode_all_logprobs": decode_logprobs.tolist(),
|
||||
}
|
||||
)
|
||||
print(f" [Token {token_idx}] ✗ LOGPROB MISMATCH! diff={diff:.8e}")
|
||||
else:
|
||||
print(f" [Token {token_idx}] ✓ Match (bitwise equal)")
|
||||
|
||||
# Print summary
|
||||
print(f"\n{'=' * 80}")
|
||||
if failed_comparisons:
|
||||
print(f"DECODE-PREFILL MISMATCH: {len(failed_comparisons)} failures detected")
|
||||
print(f"{'=' * 80}")
|
||||
|
||||
# Group failures by prompt for better readability
|
||||
failures_by_prompt: dict[int, list[dict]] = {}
|
||||
for fail in failed_comparisons:
|
||||
pid = fail["prompt_idx"]
|
||||
if pid not in failures_by_prompt:
|
||||
failures_by_prompt[pid] = []
|
||||
failures_by_prompt[pid].append(fail)
|
||||
|
||||
for prompt_idx, failures in failures_by_prompt.items():
|
||||
print(f"\n{'=' * 80}")
|
||||
print(f"PROMPT {prompt_idx}: {failures[0]['prompt_text']}...")
|
||||
print(f"{'=' * 80}")
|
||||
print(f"Total failures for this prompt: {len(failures)}")
|
||||
|
||||
# Show where mismatches occur (which token positions)
|
||||
mismatch_positions = [f["token_idx"] for f in failures]
|
||||
print(f"Mismatch at token positions: {mismatch_positions}")
|
||||
|
||||
# Show first few failures in detail
|
||||
for i, fail in enumerate(failures[:5]): # Show first 5 failures per prompt
|
||||
print(f"\n [Failure {i + 1}] Token position {fail['token_idx']}:")
|
||||
print(f" Reason: {fail['reason']}")
|
||||
print(f" Prefix token ids: {fail['prefix_token_ids']}...")
|
||||
print(
|
||||
f" Decode: token={fail['decode_token']}, "
|
||||
f"logprob={fail['decode_logprob']:.10f}"
|
||||
)
|
||||
print(
|
||||
f" Prefill: token={fail['prefill_token']}, "
|
||||
f"logprob={fail['prefill_logprob']:.10f}"
|
||||
)
|
||||
if "diff" in fail:
|
||||
print(f" Difference: {fail['diff']:.10e}")
|
||||
# Show in hex to see bitwise difference
|
||||
import struct
|
||||
|
||||
decode_hex = struct.pack("f", fail["decode_logprob"]).hex()
|
||||
prefill_hex = struct.pack("f", fail["prefill_logprob"]).hex()
|
||||
print(f" Decode logprob (hex): 0x{decode_hex}")
|
||||
print(f" Prefill logprob (hex): 0x{prefill_hex}")
|
||||
|
||||
# If we have all tokens/logprobs, show the context
|
||||
if "decode_all_tokens" in fail and "decode_all_logprobs" in fail:
|
||||
token_idx = fail["token_idx"]
|
||||
all_tokens = fail["decode_all_tokens"]
|
||||
all_logprobs = fail["decode_all_logprobs"]
|
||||
|
||||
# Show context: 2 tokens before and after
|
||||
start = max(0, token_idx - 2)
|
||||
end = min(len(all_tokens), token_idx + 3)
|
||||
|
||||
print(f" Context (tokens {start} to {end - 1}):")
|
||||
for j in range(start, end):
|
||||
marker = " <-- MISMATCH" if j == token_idx else ""
|
||||
print(
|
||||
f" [{j}] token={all_tokens[j]}, "
|
||||
f"logprob={all_logprobs[j]:.8f}{marker}"
|
||||
)
|
||||
|
||||
if len(failures) > 5:
|
||||
print(f"\n ... and {len(failures) - 5} more failures for this prompt")
|
||||
|
||||
print(f"\n{'=' * 80}\n")
|
||||
|
||||
pytest.fail(
|
||||
f"Decode logprobs do not match prefill logprobs: "
|
||||
f"{len(failed_comparisons)} mismatches found."
|
||||
)
|
||||
else:
|
||||
print("✓ SUCCESS: All decode logprobs match prefill logprobs bitwise!")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
|
||||
def LLM_with_max_seqs(
|
||||
model: str,
|
||||
max_num_seqs: int,
|
||||
gpu_memory_utilization: float,
|
||||
max_model_len: int,
|
||||
attention_config: dict | None = None,
|
||||
kernel_config: dict | None = None,
|
||||
max_num_batched_tokens: int | None = None,
|
||||
) -> LLM:
|
||||
"""Helper to construct an LLM with a specific max_num_seqs (batch-size limit)
|
||||
using the high-level v1 LLM API, while constraining memory usage.
|
||||
"""
|
||||
extra_kwargs: dict = {}
|
||||
if kernel_config is not None:
|
||||
extra_kwargs["kernel_config"] = kernel_config
|
||||
if max_num_batched_tokens is not None:
|
||||
extra_kwargs["max_num_batched_tokens"] = max_num_batched_tokens
|
||||
return LLM(
|
||||
model=model,
|
||||
max_num_seqs=max_num_seqs,
|
||||
gpu_memory_utilization=gpu_memory_utilization,
|
||||
max_model_len=max_model_len,
|
||||
dtype="auto",
|
||||
tensor_parallel_size=int(os.getenv("VLLM_TP_SIZE", "1")),
|
||||
enable_prefix_caching=False,
|
||||
attention_config=attention_config,
|
||||
# Enable for MOE models
|
||||
# enable_expert_parallel=True,
|
||||
**extra_kwargs,
|
||||
)
|
||||
@@ -1,138 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Batch-invariance regression tests for vision-language models (VLMs)."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
from utils import _extract_step_logprobs, skip_if_not_cuda_alike
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TextPrompt
|
||||
|
||||
VLM_TEST_MODEL = os.getenv("VLLM_VLM_TEST_MODEL", "Qwen/Qwen3-VL-2B-Instruct")
|
||||
|
||||
IMAGE_PROMPT = (
|
||||
"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>"
|
||||
"Describe this image.<|im_end|><|im_start|>assistant\n"
|
||||
)
|
||||
VIDEO_PROMPT = (
|
||||
"<|im_start|>user\n<|vision_start|><|video_pad|><|vision_end|>"
|
||||
"Describe this video.<|im_end|><|im_start|>assistant\n"
|
||||
)
|
||||
|
||||
|
||||
def _make_image(seed: int, size: int) -> Image.Image:
|
||||
rng = np.random.default_rng(seed)
|
||||
return Image.fromarray(rng.integers(0, 255, (size, size, 3), dtype=np.uint8))
|
||||
|
||||
|
||||
def _make_inputs(input_type: str, num_reqs: int) -> list[TextPrompt]:
|
||||
inputs: list[TextPrompt] = []
|
||||
for i in range(num_reqs):
|
||||
if input_type == "image":
|
||||
prompt = IMAGE_PROMPT
|
||||
mm_data = {"image": _make_image(1000 + i, size=256)}
|
||||
else:
|
||||
frames = [_make_image(1000 + i + f, size=128) for f in range(4)]
|
||||
prompt = VIDEO_PROMPT
|
||||
mm_data = {
|
||||
"video": (
|
||||
frames,
|
||||
{
|
||||
"total_num_frames": len(frames),
|
||||
"fps": 1.0,
|
||||
"frames_indices": list(range(len(frames))),
|
||||
"do_sample_frames": False,
|
||||
},
|
||||
)
|
||||
}
|
||||
inputs.append({"prompt": prompt, "multi_modal_data": mm_data})
|
||||
return inputs
|
||||
|
||||
|
||||
def _assert_batch_invariant(llm: LLM, inputs: list[TextPrompt], sampling) -> None:
|
||||
bs1 = [
|
||||
_extract_step_logprobs(llm.generate([inp], sampling, use_tqdm=False)[0])
|
||||
for inp in inputs
|
||||
]
|
||||
bsN_outputs = llm.generate(inputs, sampling, use_tqdm=False)
|
||||
assert len(bs1) == len(inputs)
|
||||
assert len(bsN_outputs) == len(inputs)
|
||||
bsN = [_extract_step_logprobs(out) for out in bsN_outputs]
|
||||
|
||||
failures = []
|
||||
for i, ((lp1, t1), (lpN, tN)) in enumerate(zip(bs1, bsN)):
|
||||
if lp1 is None or lpN is None:
|
||||
failures.append(f"req {i}: selected-token logprobs are unavailable")
|
||||
continue
|
||||
if len(t1) != sampling.max_tokens or len(tN) != sampling.max_tokens:
|
||||
failures.append(
|
||||
f"req {i}: expected {sampling.max_tokens} tokens, "
|
||||
f"got bs1={len(t1)} bsN={len(tN)}"
|
||||
)
|
||||
continue
|
||||
if t1 != tN:
|
||||
failures.append(f"req {i}: token mismatch bs1={t1} bsN={tN}")
|
||||
elif not torch.equal(lp1, lpN):
|
||||
d = (lp1 - lpN).abs().max().item()
|
||||
failures.append(f"req {i}: logprob mismatch max_diff={d:.3e}")
|
||||
|
||||
if failures:
|
||||
pytest.fail(
|
||||
f"Batch invariance violated for {len(failures)}/{len(inputs)} "
|
||||
f"requests:\n" + "\n".join(failures)
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("input_type", ["image", "video"])
|
||||
@pytest.mark.parametrize("mm_encoder_attn_backend", ["FLASH_ATTN", "TORCH_SDPA"])
|
||||
def test_vlm_batch_invariance_bs1_vs_bsN(
|
||||
input_type: str,
|
||||
mm_encoder_attn_backend: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
||||
_run_vlm_batch_invariance(input_type, mm_encoder_attn_backend, enforce_eager=True)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
def test_vlm_batch_invariance_default_execution(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
||||
_run_vlm_batch_invariance("image", "FLASH_ATTN", enforce_eager=False)
|
||||
|
||||
|
||||
def _run_vlm_batch_invariance(
|
||||
input_type: str, mm_encoder_attn_backend: str, enforce_eager: bool
|
||||
) -> None:
|
||||
inputs = _make_inputs(input_type, num_reqs=4)
|
||||
sampling = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=8,
|
||||
seed=1234,
|
||||
ignore_eos=True,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
llm = LLM(
|
||||
model=VLM_TEST_MODEL,
|
||||
dtype="bfloat16",
|
||||
enforce_eager=enforce_eager,
|
||||
max_num_seqs=16,
|
||||
max_model_len=4096,
|
||||
max_num_batched_tokens=2048,
|
||||
gpu_memory_utilization=0.85,
|
||||
enable_prefix_caching=False,
|
||||
mm_processor_cache_gb=0,
|
||||
mm_encoder_attn_backend=mm_encoder_attn_backend,
|
||||
)
|
||||
try:
|
||||
_assert_batch_invariant(llm, inputs, sampling)
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
@@ -1,466 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CUTLASS batch-invariance tests.
|
||||
|
||||
The NVFP4 CUTLASS tests in this file must run with ``VLLM_BATCH_INVARIANT=1``
|
||||
before the first relevant native kernel call. Do not run them in the same pytest
|
||||
process after tests that intentionally exercise non-batch-invariant NVFP4
|
||||
scaled-mm kernels.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from tests.kernels.moe.utils import make_dummy_moe_config, make_test_quant_config
|
||||
from tests.kernels.quantization.nvfp4_utils import get_nvfp4_global_scale
|
||||
from tests.utils import TestFP8Layer, requires_fp8
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.model_executor.kernels.linear import fp8_scaled_mm_is_batch_invariant
|
||||
from vllm.model_executor.kernels.linear.scaled_mm import (
|
||||
CutlassFP8ScaledMMLinearKernel,
|
||||
TritonFP8ScaledMMLinearKernel,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe import fused_topk
|
||||
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
|
||||
from vllm.model_executor.layers.fused_moe.all2all_utils import (
|
||||
maybe_make_prepare_finalize,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.experts.cutlass_moe import (
|
||||
CutlassExpertsFp4,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8DynamicTensorSym,
|
||||
kFp8DynamicTokenSym,
|
||||
kFp8StaticChannelSym,
|
||||
kFp8StaticTensorSym,
|
||||
kFp8StaticTokenSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import set_random_seed
|
||||
|
||||
pytest.importorskip("torch.cuda")
|
||||
|
||||
_NVFP4_REQUIRES_SM100 = pytest.mark.skipif(
|
||||
not current_platform.has_device_capability(100),
|
||||
reason="Nvfp4 Requires compute capability of 10 or above.",
|
||||
)
|
||||
|
||||
_NVFP4_LINEAR_DTYPES = [torch.float16, torch.bfloat16]
|
||||
_NVFP4_LINEAR_CONSISTENCY_SHAPES = [
|
||||
(256, 128, 4096),
|
||||
(512, 256, 4096),
|
||||
(256, 256, 2048),
|
||||
(241, 160, 2048),
|
||||
(401, 352, 1984),
|
||||
(333, 320, 1008),
|
||||
(287, 96, 4096),
|
||||
]
|
||||
|
||||
_NVFP4_MOE_DTYPES = (torch.bfloat16,)
|
||||
_NVFP4_MOE_NUM_EXPERTS = (40, 64)
|
||||
_NVFP4_MOE_TOPKS = (1, 4)
|
||||
|
||||
_NVFP4_MOE_BATCH_INVARIANT_CASES = (
|
||||
{
|
||||
"m": 12,
|
||||
"n": 1024,
|
||||
"k": 1024,
|
||||
"subset_indices": ((0, 3, 7), (1, 4, 8, 10), (11, 5, 2, 9, 6)),
|
||||
},
|
||||
{
|
||||
"m": 129,
|
||||
"n": 1024,
|
||||
"k": 1024,
|
||||
"subset_indices": (
|
||||
(0, 64, 128),
|
||||
(1, 63, 64, 127),
|
||||
(32, 33, 95, 96, 128),
|
||||
),
|
||||
},
|
||||
{
|
||||
"m": 73,
|
||||
"n": 1472,
|
||||
"k": 1536,
|
||||
"subset_indices": ((0, 17, 35), (8, 36, 72), (1, 9, 33, 48, 64)),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_cuda():
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("Requires CUDA or ROCm.")
|
||||
torch.set_default_device("cuda")
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@pytest.mark.parametrize(
|
||||
"kernel",
|
||||
[
|
||||
pytest.param(
|
||||
CutlassFP8ScaledMMLinearKernel,
|
||||
marks=pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUTLASS requires CUDA."
|
||||
),
|
||||
),
|
||||
TritonFP8ScaledMMLinearKernel,
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"act_key,weight_key",
|
||||
[
|
||||
(kFp8DynamicTokenSym, kFp8StaticTensorSym),
|
||||
(kFp8DynamicTokenSym, kFp8StaticChannelSym),
|
||||
(kFp8DynamicTokenSym, kFp8StaticTokenSym),
|
||||
(kFp8StaticTensorSym, kFp8StaticTensorSym),
|
||||
# An amax over the whole batch: the GEMM is invariant, the layer is not.
|
||||
(kFp8DynamicTensorSym, kFp8StaticTensorSym),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("weight_shape", [(1024, 2048), (4608, 4096)])
|
||||
@pytest.mark.parametrize("batch_size", [1, 16, 17, 32, 64, 65, 256, 257])
|
||||
@torch.inference_mode()
|
||||
def test_fp8_scaled_mm_batch_invariant_fixed_config(
|
||||
kernel: type,
|
||||
act_key,
|
||||
weight_key,
|
||||
weight_shape: tuple[int, int],
|
||||
batch_size: int,
|
||||
default_vllm_config,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
|
||||
torch.manual_seed(0)
|
||||
layer = TestFP8Layer(
|
||||
weight_shape=weight_shape,
|
||||
activation_quant_key=act_key,
|
||||
weight_quant_key=weight_key,
|
||||
input_dtype=torch.bfloat16,
|
||||
out_dtype=torch.bfloat16,
|
||||
device=torch.device("cuda"),
|
||||
force_kernel=kernel,
|
||||
)
|
||||
assert isinstance(layer.kernel, kernel)
|
||||
dynamic_per_tensor = act_key == kFp8DynamicTensorSym
|
||||
assert fp8_scaled_mm_is_batch_invariant(layer.kernel) != dynamic_per_tensor
|
||||
|
||||
in_features = weight_shape[1]
|
||||
needle = torch.randn((1, in_features), device="cuda", dtype=torch.bfloat16)
|
||||
baseline = layer(needle)[0]
|
||||
|
||||
filler = torch.randn(
|
||||
(max(batch_size - 1, 0), in_features), device="cuda", dtype=torch.bfloat16
|
||||
)
|
||||
if dynamic_per_tensor:
|
||||
if batch_size == 1:
|
||||
pytest.skip("no other rows to move the scale")
|
||||
front_output = layer(torch.cat([needle, 100 * filler], dim=0))[0]
|
||||
assert not torch.equal(front_output, baseline)
|
||||
return
|
||||
|
||||
front_batch = torch.cat([needle, filler], dim=0)
|
||||
back_batch = torch.cat([filler, needle], dim=0)
|
||||
|
||||
front_output = layer(front_batch)[0]
|
||||
back_output = layer(back_batch)[-1]
|
||||
|
||||
torch.testing.assert_close(front_output, baseline, rtol=0, atol=0)
|
||||
torch.testing.assert_close(back_output, baseline, rtol=0, atol=0)
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@pytest.mark.parametrize("scheme", ["fp8_per_tensor", "fp8_per_channel"])
|
||||
@torch.inference_mode()
|
||||
def test_online_fp8_linear_batch_invariant(
|
||||
scheme, monkeypatch, default_vllm_config, dist_init
|
||||
):
|
||||
from vllm.config.model import ModelConfig
|
||||
from vllm.config.quantization import resolve_quantization_config
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization.online.base import (
|
||||
OnlineQuantizationConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
default_vllm_config.model_config = ModelConfig(dtype="bfloat16")
|
||||
quant_config = OnlineQuantizationConfig(resolve_quantization_config(scheme, None))
|
||||
set_random_seed(0)
|
||||
with set_default_torch_dtype(torch.bfloat16), torch.device("cuda"):
|
||||
layer = ReplicatedLinear(
|
||||
1024, 768, bias=False, quant_config=quant_config, prefix="mlp.down_proj"
|
||||
)
|
||||
layer.weight.weight_loader(layer.weight, torch.randn(768, 1024))
|
||||
|
||||
needle = torch.randn(1, 1024)
|
||||
filler = 100 * torch.randn(63, 1024)
|
||||
baseline = layer(needle)[0]
|
||||
assert torch.equal(layer(torch.cat([needle, filler]))[0][:1], baseline)
|
||||
assert torch.equal(layer(torch.cat([filler, needle]))[0][-1:], baseline)
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@torch.inference_mode()
|
||||
def test_block_fp8_batch_invariant_across_tuned_block_size_k(monkeypatch):
|
||||
"""The block-FP8 kernel applies the block scales once per K tile, so a tuned
|
||||
BLOCK_SIZE_K below the scale group size reorders the sum."""
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
base = dict(
|
||||
BLOCK_SIZE_M=64, BLOCK_SIZE_N=128, GROUP_SIZE_M=1, num_warps=4, num_stages=2
|
||||
)
|
||||
table = {256: {**base, "BLOCK_SIZE_K": 128}, 512: {**base, "BLOCK_SIZE_K": 64}}
|
||||
monkeypatch.setattr(fp8_utils, "get_w8a8_block_fp8_configs", lambda *_: table)
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
N, K, block = 12288, 2048, [128, 128]
|
||||
|
||||
set_random_seed(0)
|
||||
fp8 = current_platform.fp8_dtype()
|
||||
A = torch.randn(512, K).to(fp8)
|
||||
B = torch.randn(N, K).to(fp8)
|
||||
As = torch.rand(512, K // 128) / 100
|
||||
Bs = torch.rand(N // 128, K // 128) / 100
|
||||
|
||||
def run(m):
|
||||
return fp8_utils.w8a8_triton_block_scaled_mm(
|
||||
A[:m], B, As[:m], Bs, block, torch.bfloat16
|
||||
)[:256]
|
||||
|
||||
assert torch.equal(run(256), run(512))
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
assert not torch.equal(run(256), run(512))
|
||||
|
||||
|
||||
@_NVFP4_REQUIRES_SM100
|
||||
@pytest.mark.parametrize("dtype", _NVFP4_LINEAR_DTYPES)
|
||||
@pytest.mark.parametrize("shape", _NVFP4_LINEAR_CONSISTENCY_SHAPES)
|
||||
@torch.inference_mode()
|
||||
def test_cutlass_nvfp4_scaled_mm_batch_invariant(
|
||||
dtype: torch.dtype,
|
||||
shape: tuple[int, int, int],
|
||||
) -> None:
|
||||
"""Each row of a full-M GEMM must match its M=1 counterpart."""
|
||||
set_random_seed(12345)
|
||||
m, n, packed_k = shape
|
||||
k = packed_k * 2 # real K (FP4 elements)
|
||||
|
||||
a_dtype = torch.randn((m, k), dtype=dtype, device="cuda")
|
||||
b_dtype = torch.randn((n, k), dtype=dtype, device="cuda")
|
||||
|
||||
a_global_scale = get_nvfp4_global_scale(a_dtype)
|
||||
b_global_scale = get_nvfp4_global_scale(b_dtype)
|
||||
alpha = 1.0 / (a_global_scale * b_global_scale)
|
||||
|
||||
b_fp4, b_scale_interleaved = ops.scaled_fp4_quant(b_dtype, b_global_scale)
|
||||
|
||||
a_fp4_full, a_sf_full = ops.scaled_fp4_quant(a_dtype, a_global_scale)
|
||||
out_full = ops.cutlass_scaled_fp4_mm(
|
||||
a_fp4_full,
|
||||
b_fp4,
|
||||
a_sf_full,
|
||||
b_scale_interleaved,
|
||||
alpha,
|
||||
dtype,
|
||||
)
|
||||
|
||||
for i in range(m):
|
||||
a_row = a_dtype[i : i + 1]
|
||||
a_fp4_row, a_sf_row = ops.scaled_fp4_quant(a_row, a_global_scale)
|
||||
out_row = ops.cutlass_scaled_fp4_mm(
|
||||
a_fp4_row,
|
||||
b_fp4,
|
||||
a_sf_row,
|
||||
b_scale_interleaved,
|
||||
alpha,
|
||||
dtype,
|
||||
)
|
||||
|
||||
assert torch.equal(out_full[i], out_row[0]), (
|
||||
f"VLLM_BATCH_INVARIANT: row {i} differs between M={m} and M=1: "
|
||||
f"max_abs_diff={(out_full[i] - out_row[0]).abs().max().item()}"
|
||||
)
|
||||
|
||||
|
||||
def _make_cutlass_fp4_moe_batch_invariant_case(
|
||||
case_config: dict[str, Any],
|
||||
activation: MoEActivation,
|
||||
e: int,
|
||||
topk: int,
|
||||
dtype: torch.dtype,
|
||||
) -> dict[str, Any]:
|
||||
set_random_seed(7)
|
||||
assert topk <= e
|
||||
|
||||
hidden_states = (
|
||||
torch.randn((case_config["m"], case_config["k"]), device="cuda", dtype=dtype)
|
||||
/ 10
|
||||
)
|
||||
|
||||
w1_q, w2_q, quant_config = make_test_quant_config(
|
||||
e,
|
||||
case_config["n"],
|
||||
case_config["k"],
|
||||
in_dtype=dtype,
|
||||
quant_dtype="nvfp4",
|
||||
block_shape=None,
|
||||
per_act_token_quant=False,
|
||||
make_gate=activation.is_gated,
|
||||
)
|
||||
|
||||
score = torch.randn((case_config["m"], e), device="cuda", dtype=dtype)
|
||||
|
||||
moe_config = make_dummy_moe_config(
|
||||
num_experts=e,
|
||||
experts_per_token=topk,
|
||||
hidden_dim=case_config["k"],
|
||||
intermediate_size=case_config["n"],
|
||||
in_dtype=dtype,
|
||||
activation=activation,
|
||||
)
|
||||
prepare_finalize = maybe_make_prepare_finalize(
|
||||
moe=moe_config,
|
||||
quant_config=quant_config,
|
||||
allow_new_interface=True,
|
||||
use_monolithic=False,
|
||||
)
|
||||
assert prepare_finalize is not None
|
||||
kernel = mk.FusedMoEKernel(
|
||||
prepare_finalize,
|
||||
CutlassExpertsFp4(
|
||||
moe_config=moe_config,
|
||||
quant_config=quant_config,
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
"config": case_config,
|
||||
"hidden_states": hidden_states,
|
||||
"score": score,
|
||||
"kernel": kernel,
|
||||
"w1_q": w1_q,
|
||||
"w2_q": w2_q,
|
||||
"activation": activation,
|
||||
"e": e,
|
||||
"topk": topk,
|
||||
"dtype": dtype,
|
||||
}
|
||||
|
||||
|
||||
def _run_cutlass_fp4_moe(
|
||||
case: dict[str, Any],
|
||||
hidden_states: torch.Tensor,
|
||||
score: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
topk_weights, topk_ids, _ = fused_topk(
|
||||
hidden_states, score, case["topk"], renormalize=False
|
||||
)
|
||||
return case["kernel"].apply(
|
||||
hidden_states=hidden_states,
|
||||
w1=case["w1_q"],
|
||||
w2=case["w2_q"],
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
global_num_experts=case["e"],
|
||||
activation=case["activation"],
|
||||
apply_router_weight_on_input=False,
|
||||
expert_map=None,
|
||||
)
|
||||
|
||||
|
||||
@_NVFP4_REQUIRES_SM100
|
||||
@pytest.mark.parametrize("case_config", _NVFP4_MOE_BATCH_INVARIANT_CASES)
|
||||
@pytest.mark.parametrize("activation", [MoEActivation.SILU, MoEActivation.SWIGLUSTEP])
|
||||
@pytest.mark.parametrize("e", _NVFP4_MOE_NUM_EXPERTS)
|
||||
@pytest.mark.parametrize("topk", _NVFP4_MOE_TOPKS)
|
||||
@pytest.mark.parametrize("dtype", _NVFP4_MOE_DTYPES)
|
||||
@torch.inference_mode()
|
||||
def test_cutlass_nvfp4_moe_batch_invariant(
|
||||
case_config: dict[str, Any],
|
||||
activation: MoEActivation,
|
||||
e: int,
|
||||
topk: int,
|
||||
dtype: torch.dtype,
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
) -> None:
|
||||
case = _make_cutlass_fp4_moe_batch_invariant_case(
|
||||
case_config, activation, e, topk, dtype
|
||||
)
|
||||
case_id = f"{case['config']}, e={case['e']}, topk={case['topk']}"
|
||||
# Establish the baseline output for the full mixed batch once, then
|
||||
# compare every smaller replay against the corresponding slice here.
|
||||
batch_output = _run_cutlass_fp4_moe(case, case["hidden_states"], case["score"])
|
||||
|
||||
assert CutlassExpertsFp4._supports_batch_invariance()
|
||||
|
||||
# Re-run the whole batch with a different batch-row permutation to make
|
||||
# sure the grouped GEMM result is invariant to how tokens are packed into
|
||||
# expert work for scheduling.
|
||||
indices = torch.arange(
|
||||
case["hidden_states"].size(0), device=case["hidden_states"].device
|
||||
)
|
||||
for perm_name, perm in (
|
||||
("reversed", torch.flip(indices, dims=(0,))),
|
||||
("evens_then_odds", torch.cat((indices[::2], indices[1::2]))),
|
||||
):
|
||||
permuted_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][perm],
|
||||
case["score"][perm],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[perm],
|
||||
permuted_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: permutation '{perm_name}' changed outputs "
|
||||
"relative to the baseline batch order."
|
||||
),
|
||||
)
|
||||
|
||||
# Re-run every batch-row as a batch-size-1 input and compare against the
|
||||
# matching row from the full batch.
|
||||
for idx in range(case["hidden_states"].size(0)):
|
||||
single_idx = torch.tensor([idx], device=case["hidden_states"].device)
|
||||
single_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][single_idx],
|
||||
case["score"][single_idx],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[single_idx],
|
||||
single_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: batch-row {idx} changed between full-batch "
|
||||
"and batch-size-1 execution."
|
||||
),
|
||||
)
|
||||
|
||||
# Re-run a few nontrivial sub-batches to catch interactions that only
|
||||
# appear when multiple tokens are grouped together.
|
||||
for subset_ids in case["config"]["subset_indices"]:
|
||||
subset = torch.tensor(subset_ids, device=case["hidden_states"].device)
|
||||
subset_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][subset],
|
||||
case["score"][subset],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[subset],
|
||||
subset_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: sub-batch {list(subset_ids)} changed "
|
||||
"relative to full-batch execution."
|
||||
),
|
||||
)
|
||||
@@ -1,181 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test batch-invariant matmul against torch.matmul for various shape combinations.
|
||||
|
||||
Tests correctness (matches torch.matmul) and batch invariance (result for one
|
||||
item doesn't change based on other items in the batch).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import skip_unsupported
|
||||
|
||||
import vllm.model_executor.determinism.batch_invariant as bi
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
enable_batch_invariant_mode,
|
||||
matmul_batch_invariant,
|
||||
)
|
||||
from vllm.model_executor.determinism.batch_invariant_configs import (
|
||||
_BATCH_INVARIANT_MATMUL_TUNED_CONFIGS,
|
||||
_get_tuned_matmul_arch_family,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"a_shape,b_shape",
|
||||
[
|
||||
# 2D x 2D
|
||||
((32, 64), (64, 16)),
|
||||
# 2D x 3D
|
||||
((64, 16), (4, 16, 32)),
|
||||
# 3D x 2D
|
||||
((4, 32, 64), (64, 16)),
|
||||
# 4D x 2D
|
||||
((1, 4, 32, 64), (64, 16)),
|
||||
# 3D x 3D
|
||||
((4, 32, 64), (4, 64, 16)),
|
||||
# 3D x 4D
|
||||
((2, 32, 64), (1, 2, 64, 16)),
|
||||
# 4D x 3D (Gemma4 pattern)
|
||||
((1, 2, 32, 64), (2, 64, 16)),
|
||||
# 4D x 4D
|
||||
((1, 2, 32, 64), (4, 2, 64, 16)),
|
||||
# 2D x 4D
|
||||
((32, 64), (1, 2, 64, 16)),
|
||||
# 2D x 5D
|
||||
((32, 64), (1, 2, 2, 64, 16)),
|
||||
# 5D x 2D
|
||||
((1, 2, 2, 32, 64), (64, 16)),
|
||||
# 5D x 5D
|
||||
((1, 2, 4, 32, 64), (1, 2, 4, 64, 16)),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_matmul_correctness(a_shape, b_shape, dtype):
|
||||
"""Compare matmul_batch_invariant against torch.matmul for various shapes."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(42)
|
||||
a = torch.rand(a_shape, dtype=dtype, device=device)
|
||||
b = torch.rand(b_shape, dtype=dtype, device=device)
|
||||
|
||||
# Standard implementation (CUDA ops)
|
||||
standard_output = torch.matmul(a, b)
|
||||
|
||||
# Batch-invariant implementation (Triton)
|
||||
triton_output = matmul_batch_invariant(a, b)
|
||||
|
||||
# Compare outputs
|
||||
# Use looser tolerance for bfloat16 due to its lower precision
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1 # 10% relative tolerance for bfloat16
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2 # 1% for float16/float32
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
standard_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"matmul mismatch for a ndim={a.ndim}, b ndim={b.ndim},",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_matmul_batch_invariance(dtype):
|
||||
"""Verify that the result for one item is bitwise identical regardless
|
||||
of what other items are in the batch.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(42)
|
||||
a_single = torch.rand((1, 64, 32), dtype=dtype, device=device)
|
||||
b = torch.rand((32, 128), dtype=dtype, device=device)
|
||||
|
||||
standard_output = matmul_batch_invariant(a_single, b)
|
||||
|
||||
a_batch = torch.rand((8, 64, 32), dtype=dtype, device=device)
|
||||
a_batch[3] = a_single[0]
|
||||
|
||||
batch_output = matmul_batch_invariant(a_batch, b)
|
||||
batch_output_a = batch_output[3]
|
||||
|
||||
assert torch.equal(standard_output[0], batch_output_a)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("m", [8, 32, 256, 2048])
|
||||
@pytest.mark.parametrize("transpose_b", [False, True], ids=["contiguous", "transposed"])
|
||||
def test_matmul_batch_invariance_across_tuned_m_buckets(m, transpose_b):
|
||||
# Tuned M buckets must preserve each row's K-reduction order.
|
||||
capability = (
|
||||
current_platform.get_device_capability() if current_platform.is_cuda() else None
|
||||
)
|
||||
arch_family = _get_tuned_matmul_arch_family(capability)
|
||||
if arch_family not in _BATCH_INVARIANT_MATMUL_TUNED_CONFIGS:
|
||||
pytest.skip("No tuned persistent matmul config for this architecture")
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
n = k = 2048
|
||||
torch.manual_seed(42)
|
||||
a = torch.rand((m, k), dtype=torch.bfloat16, device=device)
|
||||
if transpose_b:
|
||||
b = torch.rand((n, k), dtype=torch.bfloat16, device=device).t()
|
||||
else:
|
||||
b = torch.rand((k, n), dtype=torch.bfloat16, device=device)
|
||||
|
||||
single_output = matmul_batch_invariant(a[:1], b)
|
||||
batch_output = matmul_batch_invariant(a, b)
|
||||
|
||||
assert torch.equal(single_output[0], batch_output[0])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def batch_invariant_mode():
|
||||
# The overrides are process-global: remove them so later tests compare
|
||||
# against the stock aten kernels again.
|
||||
enable_batch_invariant_mode()
|
||||
yield
|
||||
assert bi._batch_invariant_LIB is not None
|
||||
bi._batch_invariant_LIB._destroy()
|
||||
bi._batch_invariant_MODE = False
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.usefixtures("batch_invariant_mode")
|
||||
@pytest.mark.parametrize("op", ["mm", "addmm", "bmm"])
|
||||
def test_compiled_matmul_reaches_batch_invariant_out_overloads(op):
|
||||
"""Inductor lowers mm/addmm/bmm to ``extern_kernels.<op>(..., out=buf)``,
|
||||
i.e. the ``.out`` overload, which eager never dispatches."""
|
||||
if (
|
||||
op != "bmm"
|
||||
and current_platform.is_cuda()
|
||||
and not current_platform.is_device_capability_family(80)
|
||||
):
|
||||
pytest.skip("mm/addmm are not overridden on SM90+")
|
||||
torch.manual_seed(0)
|
||||
dtype, k, n, needle = torch.bfloat16, 1024, 768, 37
|
||||
w = torch.randn(4, k, n, device=DEVICE_TYPE, dtype=dtype)
|
||||
bias = torch.randn(n, device=DEVICE_TYPE, dtype=dtype)
|
||||
fn = {
|
||||
"mm": lambda x: torch.mm(x[0], w[0]),
|
||||
# Bare addmm: a following pointwise op would make Inductor unfuse the bias.
|
||||
"addmm": lambda x: torch.addmm(bias, x[0], w[0]),
|
||||
"bmm": lambda x: torch.bmm(x, w),
|
||||
}[op]
|
||||
compiled = torch.compile(fn, fullgraph=True)
|
||||
x = torch.randn(4, 256, k, device=DEVICE_TYPE, dtype=dtype)
|
||||
row = None
|
||||
for m in (64, 256, 128):
|
||||
xs = x[:, :m].clone()
|
||||
# With dynamic=True, a specialization on M would silently recompile.
|
||||
torch._dynamo.mark_dynamic(xs, 1)
|
||||
out = compiled(xs)
|
||||
assert torch.equal(out, fn(xs)), f"compiled {op} bypassed the BI kernel (M={m})"
|
||||
row = out[..., needle, :] if row is None else row
|
||||
assert torch.equal(out[..., needle, :], row)
|
||||
@@ -1,104 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import (
|
||||
_extract_step_logprobs,
|
||||
_random_prompt,
|
||||
skip_if_not_cuda_alike,
|
||||
)
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# FLASH_ATTN is CUDA-only.
|
||||
E2E_BACKENDS = ["TRITON_ATTN"] if current_platform.is_rocm() else ["FLASH_ATTN"]
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not hasattr(torch, "float8_e4m3fn"),
|
||||
reason="NVFP4 tests require torch.float8_e4m3fn support.",
|
||||
)
|
||||
|
||||
NVFP4_TEST_MODEL = os.getenv(
|
||||
"VLLM_TEST_NVFP4_MODEL", "nm-testing/TinyLlama-1.1B-Chat-v1.0-NVFP4"
|
||||
)
|
||||
|
||||
|
||||
def _make_llm(max_num_seqs: int, backend: str) -> LLM:
|
||||
return LLM(
|
||||
model=NVFP4_TEST_MODEL,
|
||||
max_num_seqs=max_num_seqs,
|
||||
gpu_memory_utilization=float(
|
||||
os.getenv("VLLM_NVFP4_TEST_GPU_MEMORY_UTILIZATION", "0.05")
|
||||
),
|
||||
max_model_len=int(os.getenv("VLLM_NVFP4_TEST_MAX_MODEL_LEN", "2048")),
|
||||
dtype="auto",
|
||||
tensor_parallel_size=int(os.getenv("VLLM_NVFP4_TEST_TP_SIZE", "1")),
|
||||
enable_prefix_caching=False,
|
||||
enforce_eager=True,
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("backend", E2E_BACKENDS)
|
||||
def test_dense_nvfp4_generation_is_deterministic_across_batch_sizes_e2e(backend):
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
|
||||
num_trials = int(os.getenv("VLLM_NVFP4_NEEDLE_TRIALS", "2"))
|
||||
max_batch_size = int(os.getenv("VLLM_NVFP4_NEEDLE_BATCH_SIZE", "8"))
|
||||
min_random_prompt = int(os.getenv("VLLM_NVFP4_MIN_PROMPT", "32"))
|
||||
max_random_prompt = int(os.getenv("VLLM_NVFP4_MAX_PROMPT", "96"))
|
||||
assert max_batch_size >= 2, "Batch size should be >= 2 to test invariance."
|
||||
|
||||
sampling = SamplingParams(
|
||||
temperature=float(os.getenv("VLLM_NVFP4_NEEDLE_TEMPERATURE", "0.6")),
|
||||
top_p=float(os.getenv("VLLM_NVFP4_NEEDLE_TOP_P", "0.95")),
|
||||
max_tokens=int(os.getenv("VLLM_NVFP4_NEEDLE_MAX_TOKENS", "16")),
|
||||
seed=20240919,
|
||||
logprobs=5,
|
||||
)
|
||||
needle_prompt = "Write one factual sentence about the moon."
|
||||
|
||||
llm = None
|
||||
baseline_completion = None
|
||||
baseline_logprobs = None
|
||||
try:
|
||||
llm = _make_llm(max_num_seqs=max_batch_size, backend=backend)
|
||||
baseline_output = llm.generate([needle_prompt], sampling, use_tqdm=False)[0]
|
||||
baseline_completion = baseline_output.outputs[0]
|
||||
baseline_logprobs, baseline_token_ids = _extract_step_logprobs(baseline_output)
|
||||
assert baseline_logprobs is not None
|
||||
assert baseline_token_ids is not None
|
||||
for _ in range(num_trials):
|
||||
batch_size = random.randint(max_batch_size // 2, max_batch_size)
|
||||
needle_pos = random.randint(0, batch_size - 1)
|
||||
prompts: list[str] = []
|
||||
for idx in range(batch_size):
|
||||
if idx == needle_pos:
|
||||
prompts.append(needle_prompt)
|
||||
else:
|
||||
prompts.append(_random_prompt(min_random_prompt, max_random_prompt))
|
||||
|
||||
outputs = llm.generate(prompts, sampling, use_tqdm=False)
|
||||
needle_output = outputs[needle_pos]
|
||||
needle_completion = needle_output.outputs[0]
|
||||
needle_logprobs, needle_token_ids = _extract_step_logprobs(needle_output)
|
||||
assert needle_logprobs is not None
|
||||
assert needle_token_ids is not None
|
||||
|
||||
assert needle_output.prompt == needle_prompt
|
||||
assert baseline_completion is not None
|
||||
assert baseline_logprobs is not None
|
||||
assert needle_completion.token_ids == baseline_completion.token_ids
|
||||
assert needle_completion.text == baseline_completion.text
|
||||
torch.testing.assert_close(needle_logprobs, baseline_logprobs)
|
||||
finally:
|
||||
if llm is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
@@ -1,565 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test batch-invariant RMS normalization against a PyTorch reference."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import skip_if_not_cuda_alike, skip_unsupported
|
||||
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
rms_norm_batch_invariant,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
def _rms_norm_reference(
|
||||
input_tensor: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""Compute RMSNorm independently using PyTorch operations."""
|
||||
input_fp32 = input_tensor.float()
|
||||
output = input_fp32 * torch.rsqrt(
|
||||
input_fp32.square().mean(dim=-1, keepdim=True) + eps
|
||||
)
|
||||
return (output * weight.float()).to(input_tensor.dtype)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("batch_size", [1, 4, 64, 300])
|
||||
@pytest.mark.parametrize("hidden_size", [512, 2048, 4096, 8192])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("eps", [1e-6, 1e-5])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_batch_invariant_vs_reference(
|
||||
default_vllm_config,
|
||||
batch_size: int,
|
||||
hidden_size: int,
|
||||
dtype: torch.dtype,
|
||||
eps: float,
|
||||
seed: int,
|
||||
):
|
||||
"""Compare batch-invariant Triton RMS norm against a PyTorch reference.
|
||||
|
||||
Tests that the Triton-based batch-invariant RMS norm produces numerically
|
||||
equivalent results to an independent implementation across configurations.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
# Create test input and weight
|
||||
torch.manual_seed(seed)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation (Triton)
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Compare outputs
|
||||
# Use looser tolerance for bfloat16 due to its lower precision
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1 # 10% relative tolerance for bfloat16
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2 # 1% for float16/float32
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for batch_size={batch_size}, "
|
||||
f"hidden_size={hidden_size}, "
|
||||
f"dtype={dtype}, eps={eps}, seed={seed}",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("eps", [1e-6])
|
||||
@pytest.mark.parametrize("n_extra", [3, 299])
|
||||
@pytest.mark.parametrize("seed", list(range(16)))
|
||||
def test_fused_add_rms_norm_batch_invariant_residual_path(
|
||||
hidden_size: int,
|
||||
dtype: torch.dtype,
|
||||
eps: float,
|
||||
n_extra: int,
|
||||
seed: int,
|
||||
):
|
||||
"""Test the batch-invariant fused residual-add + RMSNorm helper directly."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(seed)
|
||||
x_single = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
residual_single = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
x_batch = torch.cat(
|
||||
[
|
||||
x_single,
|
||||
torch.randn(n_extra, hidden_size, dtype=dtype, device=device),
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
residual_batch = torch.cat(
|
||||
[
|
||||
residual_single,
|
||||
torch.randn(n_extra, hidden_size, dtype=dtype, device=device),
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
def fused_add_rms_norm(x, residual, w, e) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
ops.fused_add_rms_norm(x, residual, w, e)
|
||||
return x, residual
|
||||
|
||||
out_single, residual_out_single = fused_add_rms_norm(
|
||||
x_single.clone(),
|
||||
residual_single.clone(),
|
||||
weight,
|
||||
eps,
|
||||
)
|
||||
out_batch, residual_out_batch = fused_add_rms_norm(
|
||||
x_batch.clone(),
|
||||
residual_batch.clone(),
|
||||
weight,
|
||||
eps,
|
||||
)
|
||||
|
||||
merged_single = x_single + residual_single
|
||||
ref_out = _rms_norm_reference(merged_single, weight, eps)
|
||||
|
||||
torch.testing.assert_close(
|
||||
residual_out_single,
|
||||
merged_single,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Residual output should equal x + residual exactly",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
residual_out_batch[:1],
|
||||
merged_single,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Residual output should be batch invariant",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
out_single,
|
||||
out_batch[:1],
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Fused add RMSNorm output should be batch invariant",
|
||||
)
|
||||
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2
|
||||
|
||||
torch.testing.assert_close(
|
||||
out_single,
|
||||
ref_out,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg="Fused add RMSNorm output should stay numerically close to the "
|
||||
"PyTorch RMSNorm reference",
|
||||
)
|
||||
|
||||
|
||||
FP8_DTYPE = current_platform.fp8_dtype()
|
||||
|
||||
# The large launch (num_tokens=300 >= 256) drops an un-pinned kernel to block
|
||||
# 256, while the small launch (255 rows) stays under the threshold and keeps the
|
||||
# larger block (1024, or 512 for per-block quant). Under the pin the two launches
|
||||
# use the same block, so the shared first 255 rows must match bit-for-bit; 255 is
|
||||
# the most rows a single small launch can hold (< 256, and <= 256 for per-block).
|
||||
_LARGE_TOKENS = 300
|
||||
_SMALL_TOKENS = 255
|
||||
|
||||
|
||||
def _assert_rows_bit_identical(small, large, msg):
|
||||
if small.dtype == FP8_DTYPE:
|
||||
assert torch.equal(small.view(torch.uint8), large.view(torch.uint8)), msg
|
||||
else:
|
||||
torch.testing.assert_close(small, large, rtol=0.0, atol=0.0, msg=msg)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_batch_invariant_nonresidual_kernel(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int
|
||||
):
|
||||
"""C++ ``rms_norm`` (no residual) must be batch invariant across the block
|
||||
threshold. Reached in compiled mode with ``ir_op_priority.rms_norm=["vllm_c"]``
|
||||
(default priority is ``native``/inductor codegen when compiling).
|
||||
"""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
def rms_norm(x):
|
||||
out = torch.empty_like(x)
|
||||
ops.rms_norm(out, x, weight, 1e-6)
|
||||
return out
|
||||
|
||||
large = rms_norm(rows.clone())
|
||||
small = rms_norm(rows[:_SMALL_TOKENS].clone())
|
||||
_assert_rows_bit_identical(
|
||||
small,
|
||||
large[:_SMALL_TOKENS],
|
||||
"rms_norm output depends on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
@pytest.mark.parametrize("add_residual", [False, True])
|
||||
def test_rms_norm_static_fp8_quant_batch_invariant(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int, add_residual: bool
|
||||
):
|
||||
"""C++ static per-tensor fp8-quant RMSNorm must be batch invariant across
|
||||
the block threshold. Covers ``rms_norm_static_fp8_quant`` and, with
|
||||
``add_residual``, ``fused_add_rms_norm_static_fp8_quant`` (the compiled fp8
|
||||
path where ``RMSNormQuantFusionPass`` rewrites norm + quant into them).
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
residual = (
|
||||
torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
if add_residual
|
||||
else None
|
||||
)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
quant_scale = torch.tensor(1.0, dtype=torch.float32, device=device)
|
||||
|
||||
def quant(x, res):
|
||||
out = torch.empty_like(x, dtype=FP8_DTYPE)
|
||||
if add_residual:
|
||||
torch.ops._C.fused_add_rms_norm_static_fp8_quant(
|
||||
out, x, res, weight, quant_scale, 1e-6
|
||||
)
|
||||
else:
|
||||
torch.ops._C.rms_norm_static_fp8_quant(out, x, weight, quant_scale, 1e-6)
|
||||
return out
|
||||
|
||||
large = quant(rows.clone(), residual.clone() if residual is not None else None)
|
||||
small = quant(
|
||||
rows[:_SMALL_TOKENS].clone(),
|
||||
residual[:_SMALL_TOKENS].clone() if residual is not None else None,
|
||||
)
|
||||
_assert_rows_bit_identical(
|
||||
small,
|
||||
large[:_SMALL_TOKENS],
|
||||
"static-fp8-quant RMSNorm output depends on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_per_block_quant_batch_invariant(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int
|
||||
):
|
||||
"""C++ ``rms_norm_per_block_quant`` must be batch invariant across the
|
||||
block threshold (compiled fp8 block-quant path; block pinned to 512)."""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
group_size = [1, 128]
|
||||
|
||||
def per_block_quant(x):
|
||||
return ops.rms_norm_per_block_quant(x, weight, 1e-6, FP8_DTYPE, group_size)
|
||||
|
||||
out_large, scale_large = per_block_quant(rows.clone())
|
||||
out_small, scale_small = per_block_quant(rows[:_SMALL_TOKENS].clone())
|
||||
_assert_rows_bit_identical(
|
||||
out_small,
|
||||
out_large[:_SMALL_TOKENS],
|
||||
"rms_norm_per_block_quant output depends on num_tokens (block size)",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
scale_small,
|
||||
scale_large[:_SMALL_TOKENS],
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="rms_norm_per_block_quant scales depend on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("batch_size", [1, 16, 128])
|
||||
@pytest.mark.parametrize("seq_len", [1, 32, 512])
|
||||
@pytest.mark.parametrize("hidden_size", [2048, 4096])
|
||||
def test_rms_norm_3d_input(
|
||||
default_vllm_config, batch_size: int, seq_len: int, hidden_size: int
|
||||
):
|
||||
"""Test RMS norm with 3D input tensors (batch, seq_len, hidden_size).
|
||||
|
||||
Ensures that the batch-invariant RMS norm correctly handles multi-dimensional
|
||||
inputs that are common in transformer models.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(
|
||||
batch_size, seq_len, hidden_size, dtype=dtype, device=device
|
||||
)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Use looser tolerance for bfloat16
|
||||
rtol, atol = 1e-1, 1e-1 # 10% tolerance for bfloat16
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for 3D input with batch_size={batch_size}, "
|
||||
f"seq_len={seq_len}, hidden_size={hidden_size}",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
def test_rms_norm_numerical_stability(default_vllm_config):
|
||||
"""Test RMS norm numerical stability with extreme values.
|
||||
|
||||
Ensures that both implementations handle edge cases like very small or large
|
||||
values without producing NaN or Inf.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.float16
|
||||
eps = 1e-6
|
||||
hidden_size = 2048
|
||||
|
||||
# Test cases with extreme values
|
||||
test_cases = [
|
||||
# Very small values
|
||||
torch.ones(4, hidden_size, dtype=dtype, device=device) * 1e-5,
|
||||
# Very large values
|
||||
torch.ones(4, hidden_size, dtype=dtype, device=device) * 1e4,
|
||||
# Mixed small and large
|
||||
torch.randn(4, hidden_size, dtype=dtype, device=device) * 100,
|
||||
# Values near zero
|
||||
torch.randn(4, hidden_size, dtype=dtype, device=device) * 1e-6,
|
||||
]
|
||||
|
||||
weight = torch.ones(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
for idx, input_tensor in enumerate(test_cases):
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Check for NaN or Inf
|
||||
assert not torch.isnan(reference_output).any(), (
|
||||
f"Reference RMS norm produced NaN for test case {idx}"
|
||||
)
|
||||
assert not torch.isinf(reference_output).any(), (
|
||||
f"Reference RMS norm produced Inf for test case {idx}"
|
||||
)
|
||||
assert not torch.isnan(triton_output).any(), (
|
||||
f"Triton RMS norm produced NaN for test case {idx}"
|
||||
)
|
||||
assert not torch.isinf(triton_output).any(), (
|
||||
f"Triton RMS norm produced Inf for test case {idx}"
|
||||
)
|
||||
|
||||
# Compare outputs - very lenient for extreme values with float16
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=2e-1, # 20% tolerance for extreme values
|
||||
atol=2e-1,
|
||||
msg=f"RMS norm mismatch for extreme value test case {idx}",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
def test_rms_norm_formula(default_vllm_config):
|
||||
"""Test that RMS norm follows the correct mathematical formula.
|
||||
|
||||
Verifies: output = input / sqrt(mean(input^2) + eps) * weight
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.float32 # Use float32 for higher precision in formula check
|
||||
eps = 1e-6
|
||||
hidden_size = 1024
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(8, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Compute expected output using the formula
|
||||
variance = (input_tensor.pow(2).mean(dim=-1, keepdim=True)).to(dtype)
|
||||
expected_output = input_tensor * torch.rsqrt(variance + eps) * weight
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Compare against formula
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
expected_output,
|
||||
rtol=1e-4,
|
||||
atol=1e-4,
|
||||
msg="Triton RMS norm doesn't match expected formula",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [128, 1024, 4096, 16384])
|
||||
def test_rms_norm_different_hidden_sizes(default_vllm_config, hidden_size: int):
|
||||
"""Test RMS norm with various hidden sizes to ensure block size handling.
|
||||
|
||||
The Triton kernel uses a fixed BLOCK_SIZE=1024, so this tests that it
|
||||
correctly handles hidden sizes both smaller and larger than the block size.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
batch_size = 16
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Use looser tolerance for bfloat16
|
||||
rtol, atol = 1e-1, 1e-1 # 10% tolerance for bfloat16
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for hidden_size={hidden_size}",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
def test_rms_norm_determinism(default_vllm_config):
|
||||
"""Test that batch-invariant RMS norm produces deterministic results.
|
||||
|
||||
Runs the same input through the kernel multiple times and verifies
|
||||
identical outputs.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
hidden_size = 4096
|
||||
batch_size = 32
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Run multiple times
|
||||
outputs = []
|
||||
for _ in range(5):
|
||||
output = rms_norm_batch_invariant(input_tensor.clone(), weight, eps=eps)
|
||||
outputs.append(output)
|
||||
|
||||
# All outputs should be identical
|
||||
reference = outputs[0]
|
||||
for idx, output in enumerate(outputs[1:], start=1):
|
||||
torch.testing.assert_close(
|
||||
output,
|
||||
reference,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg=f"RMS norm not deterministic: run {idx} differs from reference",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_rms_norm_batch_invariance(dtype):
|
||||
"""Same row gives identical rms_norm result regardless of batch neighbors.
|
||||
|
||||
This verifies that the output for a given row is independent of what other
|
||||
rows are present in the batch — the core batch-invariance property.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(42)
|
||||
hidden_size = 2048
|
||||
eps = 1e-6
|
||||
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
row = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Compute rms_norm on the single row alone
|
||||
out_single = rms_norm_batch_invariant(row, weight, eps=eps)
|
||||
|
||||
# Embed the same row in a larger batch with random neighbors
|
||||
batch = torch.randn(8, hidden_size, dtype=dtype, device=device)
|
||||
batch[4] = row[0]
|
||||
out_batch = rms_norm_batch_invariant(batch, weight, eps=eps)
|
||||
|
||||
assert isinstance(out_single, torch.Tensor) and isinstance(out_batch, torch.Tensor)
|
||||
assert torch.equal(out_single[0], out_batch[4]), (
|
||||
"rms_norm output for a row differs when batch context changes"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run a quick smoke test
|
||||
print("Running quick smoke test of RMS norm implementations...")
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
batch_size = 8
|
||||
hidden_size = 4096
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
assert isinstance(triton_output, torch.Tensor)
|
||||
|
||||
# Compare
|
||||
max_diff = (triton_output - reference_output).abs().max().item()
|
||||
mean_diff = (triton_output - reference_output).abs().mean().item()
|
||||
|
||||
print(f"Max difference: {max_diff:.6e}")
|
||||
print(f"Mean difference: {mean_diff:.6e}")
|
||||
print(f"Reference output sample: {reference_output[0, :5].tolist()}")
|
||||
print(f"Triton output sample: {triton_output[0, :5].tolist()}")
|
||||
|
||||
if max_diff < 1e-3:
|
||||
print("✓ Smoke test passed!")
|
||||
else:
|
||||
print("✗ Smoke test failed - differences too large")
|
||||
@@ -1,228 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""XPU-only batch-invariance tests for norm, collectives, and sampler behavior."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config import CacheConfig, LoadConfig, ModelConfig, VllmConfig
|
||||
from vllm.distributed.device_communicators.xpu_communicator import XpuCommunicator
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_xpu(), reason="XPU batch-invariance tests"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tiny_qwen3_moe_path(tmp_path):
|
||||
"""Create a local Qwen3-MoE config for dummy-loading tests."""
|
||||
from transformers import Qwen3MoeConfig
|
||||
|
||||
config = Qwen3MoeConfig(
|
||||
architectures=["Qwen3MoeForCausalLM"],
|
||||
vocab_size=256,
|
||||
hidden_size=512,
|
||||
intermediate_size=1024,
|
||||
moe_intermediate_size=512,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=128,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
max_position_embeddings=512,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
tie_word_embeddings=False,
|
||||
)
|
||||
config.save_pretrained(tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["argument", "checkpoint"])
|
||||
def test_rejects_weight_quantization(tiny_qwen3_moe_path, source):
|
||||
"""Reject both explicit and checkpoint-inferred quantization before loading."""
|
||||
from transformers import Qwen3MoeConfig
|
||||
|
||||
if source == "checkpoint":
|
||||
config = Qwen3MoeConfig.from_pretrained(tiny_qwen3_moe_path)
|
||||
config.quantization_config = {
|
||||
"quant_method": "fp8",
|
||||
"activation_scheme": "dynamic",
|
||||
}
|
||||
config.save_pretrained(tiny_qwen3_moe_path)
|
||||
|
||||
model_config = ModelConfig(
|
||||
model=str(tiny_qwen3_moe_path),
|
||||
skip_tokenizer_init=True,
|
||||
dtype="bfloat16",
|
||||
quantization="fp8" if source == "argument" else None,
|
||||
)
|
||||
assert model_config.quantization == "fp8"
|
||||
with pytest.raises(ValueError, match="supports only unquantized models"):
|
||||
VllmConfig(
|
||||
model_config=model_config,
|
||||
load_config=LoadConfig(load_format="dummy"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cache_dtype", ["fp8", "int8_per_token_head", "nvfp4"])
|
||||
def test_rejects_quantized_kv_cache(cache_dtype):
|
||||
with pytest.raises(ValueError, match="does not support quantized KV caches"):
|
||||
VllmConfig(cache_config=CacheConfig(cache_dtype=cache_dtype))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cache_dtype", ["auto", "float16", "bfloat16"])
|
||||
def test_accepts_unquantized_kv_cache(cache_dtype):
|
||||
config = VllmConfig(cache_config=CacheConfig(cache_dtype=cache_dtype))
|
||||
assert config.cache_config.cache_dtype == cache_dtype
|
||||
|
||||
|
||||
def test_quantized_kv_cache_allowed_without_batch_invariance(monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
config = VllmConfig(cache_config=CacheConfig(cache_dtype="fp8"))
|
||||
assert config.cache_config.cache_dtype == "fp8"
|
||||
|
||||
|
||||
# These dimensions and seeds locally reproduce non-invariant norm mismatches.
|
||||
# They make the invariant equality assertion exercise a discriminating case.
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"norm_name",
|
||||
"batch_size",
|
||||
"hidden_size",
|
||||
"position",
|
||||
"weight_seed",
|
||||
"input_seed",
|
||||
"input_pattern",
|
||||
),
|
||||
[
|
||||
("rms", 1024, 16384, 512, 7, 42, "normal"),
|
||||
("gemma", 257, 8192, 255, 1, 2, "normal"),
|
||||
("rms", 5, 8192, 3, 7, 46, "scaled"),
|
||||
("gemma", 5, 8192, 3, 1, 46, "scaled"),
|
||||
],
|
||||
)
|
||||
def test_residual_norm_preserves_batch_invariance(
|
||||
norm_name,
|
||||
batch_size,
|
||||
hidden_size,
|
||||
position,
|
||||
weight_seed,
|
||||
input_seed,
|
||||
input_pattern,
|
||||
monkeypatch,
|
||||
default_vllm_config,
|
||||
):
|
||||
"""Residual norm output must not change when its row changes batch position."""
|
||||
from vllm.model_executor.determinism.batch_invariant import init_batch_invariance
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm, RMSNorm
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
init_batch_invariance()
|
||||
norm_cls = RMSNorm if norm_name == "rms" else GemmaRMSNorm
|
||||
norm = norm_cls(hidden_size, eps=1e-6).to(device="xpu", dtype=torch.bfloat16)
|
||||
with torch.no_grad():
|
||||
torch.manual_seed(weight_seed)
|
||||
norm.weight.uniform_(-0.5, 0.5)
|
||||
|
||||
if input_pattern == "scaled":
|
||||
# Heterogeneous columns expose native mean's batch-dependent rounding.
|
||||
generator = torch.Generator(device="cpu").manual_seed(input_seed)
|
||||
scale = torch.randn(hidden_size, generator=generator).exp()
|
||||
x = (torch.randn(batch_size, hidden_size, generator=generator) * scale).to(
|
||||
device="xpu", dtype=torch.bfloat16
|
||||
)
|
||||
residual = (
|
||||
torch.randn(batch_size, hidden_size, generator=generator) * scale
|
||||
).to(device="xpu", dtype=torch.bfloat16)
|
||||
else:
|
||||
torch.manual_seed(input_seed)
|
||||
x = torch.randn(batch_size, hidden_size, device="xpu", dtype=torch.bfloat16)
|
||||
residual = torch.randn_like(x)
|
||||
|
||||
single_output, single_residual = norm(
|
||||
x[position : position + 1].clone(),
|
||||
residual[position : position + 1].clone(),
|
||||
)
|
||||
batch_output, batch_residual = norm(x.clone(), residual.clone())
|
||||
|
||||
assert torch.equal(single_output, batch_output[position : position + 1])
|
||||
assert torch.equal(single_residual, batch_residual[position : position + 1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"operation", ["all_reduce", "reduce_scatter", "reduce_scatterv"]
|
||||
)
|
||||
@pytest.mark.parametrize("rank", range(4))
|
||||
def test_collectives_preserve_rank_order_and_partition(monkeypatch, operation, rank):
|
||||
"""Cancellation exposes reordered sums; mock ranks require no extra XPUs."""
|
||||
from vllm.distributed.device_communicators import xpu_communicator
|
||||
|
||||
inputs = [
|
||||
torch.full((8, 3), value, dtype=torch.float32, device="xpu")
|
||||
for value in (1e20, -1e20, 3.0, 0.0)
|
||||
]
|
||||
inputs[2].add_(torch.arange(24, device="xpu").reshape(8, 3))
|
||||
|
||||
def all_gather_single(output, input_, group):
|
||||
torch.testing.assert_close(input_, inputs[rank].reshape(-1), rtol=0, atol=0)
|
||||
output.copy_(torch.stack(inputs).reshape(-1))
|
||||
|
||||
monkeypatch.setattr(xpu_communicator.dist, "all_gather_single", all_gather_single)
|
||||
communicator = XpuCommunicator.__new__(XpuCommunicator)
|
||||
communicator.world_size = 4
|
||||
communicator.rank_in_group = rank
|
||||
communicator.device_group = object()
|
||||
expected = inputs[0].clone()
|
||||
for value in inputs[1:]:
|
||||
expected.add_(value)
|
||||
assert torch.equal(expected, inputs[2])
|
||||
|
||||
if operation == "all_reduce":
|
||||
actual = communicator.all_reduce(inputs[rank])
|
||||
elif operation == "reduce_scatter":
|
||||
actual = communicator.reduce_scatter(inputs[rank], dim=0)
|
||||
expected = expected.chunk(4)[rank]
|
||||
else:
|
||||
sizes = [1, 3, 2, 2]
|
||||
actual = communicator.reduce_scatterv(inputs[rank], dim=0, sizes=sizes)
|
||||
expected = expected.split(sizes)[rank]
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
|
||||
|
||||
# This batch size, vocabulary size, and positions locally reproduce an
|
||||
# unseeded non-invariant XPU sampler mismatch.
|
||||
@pytest.mark.parametrize("position", [0, 128, 255])
|
||||
def test_seeded_sampler_preserves_full_distribution_and_rng(position, monkeypatch):
|
||||
"""Moving a request must preserve its distribution and per-request RNG."""
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.v1.sample.ops.topk_topp_sampler import TopKTopPSampler
|
||||
|
||||
assert HAS_TRITON, "XPU sampling must exercise the Triton top-k/top-p path"
|
||||
monkeypatch.setattr(envs, "VLLM_XPU_USE_SAMPLER_KERNEL", True)
|
||||
sampler = TopKTopPSampler(logprobs_mode="processed_logprobs")
|
||||
torch.manual_seed(42)
|
||||
logits = torch.randn(256, 8192, device="xpu", dtype=torch.float32)
|
||||
single_rng = torch.Generator(device="xpu").manual_seed(123)
|
||||
batch_rng = torch.Generator(device="xpu").manual_seed(123)
|
||||
k = torch.full((256,), 32, dtype=torch.int32, device="xpu")
|
||||
p = torch.full((256,), 0.9, device="xpu")
|
||||
for _ in range(3):
|
||||
single_token, single_logprobs = sampler(
|
||||
logits[position : position + 1].clone(),
|
||||
{0: single_rng},
|
||||
k[position : position + 1],
|
||||
p[position : position + 1],
|
||||
)
|
||||
batch_tokens, batch_logprobs = sampler(
|
||||
logits.clone(), {position: batch_rng}, k, p
|
||||
)
|
||||
assert single_logprobs is not None and batch_logprobs is not None
|
||||
torch.testing.assert_close(
|
||||
single_logprobs[0], batch_logprobs[position], rtol=0, atol=0
|
||||
)
|
||||
assert single_token.item() == batch_tokens[position].item()
|
||||
assert torch.equal(single_rng.get_state(), batch_rng.get_state())
|
||||
@@ -1,153 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import os
|
||||
import random
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.config import get_config
|
||||
from vllm.transformers_utils.model_arch_config_convertor import (
|
||||
ModelArchConfigConvertorBase,
|
||||
)
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.v1.attention.backends.fa_utils import flash_attn_supports_mla
|
||||
|
||||
|
||||
class DeviceConfig(NamedTuple):
|
||||
available: bool
|
||||
backends: list[str]
|
||||
|
||||
|
||||
# Maps each device to its availability and supported backends.
|
||||
DEVICE_BACKENDS: dict[str, DeviceConfig] = {
|
||||
"cuda": DeviceConfig(
|
||||
available=current_platform.is_cuda()
|
||||
and current_platform.has_device_capability(80),
|
||||
# FlashInfer backend temporarily disabled due to invariant CTA sizes.
|
||||
# See FlashInfer issue #2424
|
||||
backends=["FLASH_ATTN", "TRITON_ATTN", "FLEX_ATTENTION"],
|
||||
),
|
||||
"xpu": DeviceConfig(
|
||||
available=current_platform.is_xpu() and HAS_TRITON,
|
||||
backends=["TRITON_ATTN"],
|
||||
),
|
||||
"rocm": DeviceConfig(
|
||||
available=current_platform.is_rocm() and HAS_TRITON,
|
||||
backends=["TRITON_ATTN"],
|
||||
),
|
||||
}
|
||||
|
||||
DEFAULT_MODEL = "Qwen/Qwen3-1.7B"
|
||||
TEST_MODEL = os.getenv("VLLM_TEST_MODEL", DEFAULT_MODEL)
|
||||
|
||||
# Override backends for MLA models.
|
||||
if os.getenv("VLLM_TEST_MODEL"):
|
||||
config = get_config(TEST_MODEL, trust_remote_code=False)
|
||||
if ModelArchConfigConvertorBase(config, config.get_text_config()).is_deepseek_mla():
|
||||
DEVICE_BACKENDS["cuda"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["cuda"].available,
|
||||
backends=["TRITON_MLA"]
|
||||
+ (["FLASH_ATTN_MLA"] if flash_attn_supports_mla() else []),
|
||||
)
|
||||
DEVICE_BACKENDS["xpu"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["xpu"].available,
|
||||
backends=[],
|
||||
)
|
||||
DEVICE_BACKENDS["rocm"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["rocm"].available,
|
||||
backends=["TRITON_MLA"],
|
||||
)
|
||||
|
||||
# Only include backends for devices that are actually available.
|
||||
BACKENDS: list[str] = sorted(
|
||||
{b for cfg in DEVICE_BACKENDS.values() if cfg.available for b in cfg.backends}
|
||||
)
|
||||
|
||||
skip_unsupported = pytest.mark.skipif(
|
||||
not any(cfg.available for cfg in DEVICE_BACKENDS.values()),
|
||||
reason="Requires CUDA >= Ampere (SM80), ROCm, or Intel XPU with Triton",
|
||||
)
|
||||
|
||||
skip_if_not_cuda = pytest.mark.skipif(
|
||||
not DEVICE_BACKENDS["cuda"].available,
|
||||
reason="Requires CUDA >= Ampere (SM80)",
|
||||
)
|
||||
|
||||
skip_if_not_cuda_alike = pytest.mark.skipif(
|
||||
not (DEVICE_BACKENDS["cuda"].available or DEVICE_BACKENDS["rocm"].available),
|
||||
reason="Requires CUDA >= Ampere (SM80) or ROCm",
|
||||
)
|
||||
|
||||
requires_mx = pytest.mark.skipif(
|
||||
not (current_platform.is_rocm() and current_platform.supports_mx()),
|
||||
reason="requires a ROCm device with native MX support (gfx95x)",
|
||||
)
|
||||
|
||||
|
||||
def _random_prompt(min_words: int = 1024, max_words: int = 1024 * 2) -> str:
|
||||
# Generate more realistic prompts that will actually produce varied tokens
|
||||
# Use a mix of common English text patterns
|
||||
|
||||
prompt_templates = [
|
||||
# Question-answer style
|
||||
"Question: What is the capital of France?\nAnswer: The capital of France is",
|
||||
"Q: How does photosynthesis work?\nA: Photosynthesis is the process by which",
|
||||
"User: Can you explain quantum mechanics?\nAssistant: Quantum mechanics is",
|
||||
# Story/narrative style
|
||||
"Once upon a time in a distant galaxy, there lived",
|
||||
"The old man walked slowly down the street, remembering",
|
||||
"In the year 2157, humanity finally discovered",
|
||||
# Technical/code style
|
||||
"To implement a binary search tree in Python, first we need to",
|
||||
"The algorithm works by iterating through the array and",
|
||||
"Here's how to optimize database queries using indexing:",
|
||||
# Factual/informative style
|
||||
"The Renaissance was a period in European history that",
|
||||
"Climate change is caused by several factors including",
|
||||
"The human brain contains approximately 86 billion neurons which",
|
||||
# Conversational style
|
||||
"I've been thinking about getting a new laptop because",
|
||||
"Yesterday I went to the store and bought",
|
||||
"My favorite thing about summer is definitely",
|
||||
]
|
||||
|
||||
# Pick a random template
|
||||
base_prompt = random.choice(prompt_templates)
|
||||
|
||||
if max_words < min_words:
|
||||
max_words = min_words
|
||||
target_words = random.randint(min_words, max_words)
|
||||
|
||||
if target_words > 50:
|
||||
# For longer prompts, repeat context
|
||||
padding_text = (
|
||||
" This is an interesting topic that deserves more explanation. "
|
||||
# TODO: Update to * (target_words // 10) to better align with word ratio
|
||||
* (target_words // 50)
|
||||
)
|
||||
base_prompt = padding_text + base_prompt
|
||||
|
||||
return base_prompt
|
||||
|
||||
|
||||
def _extract_step_logprobs(request_output):
|
||||
if getattr(request_output, "outputs", None):
|
||||
inner = request_output.outputs[0]
|
||||
if hasattr(inner, "logprobs") and inner.logprobs is not None:
|
||||
t = torch.tensor(
|
||||
[
|
||||
inner.logprobs[i][tid].logprob
|
||||
for i, tid in enumerate(inner.token_ids)
|
||||
],
|
||||
dtype=torch.float32,
|
||||
)
|
||||
return t, inner.token_ids
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def is_device_capability_below_90() -> bool:
|
||||
return not current_platform.has_device_capability(90)
|
||||
@@ -1,866 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.parallel import DataParallelBackend
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.inputs import PromptType
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine import EngineCoreRequestType
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.engine.core_client import DPLBAsyncMPClient
|
||||
from vllm.v1.metrics.loggers import StatLoggerBase
|
||||
from vllm.v1.metrics.stats import IterationStats, MultiModalCacheStats, SchedulerStats
|
||||
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", 2))
|
||||
|
||||
|
||||
async def generate(
|
||||
engine: AsyncLLM,
|
||||
request_id: str,
|
||||
prompt: PromptType,
|
||||
output_kind: RequestOutputKind,
|
||||
max_tokens: int,
|
||||
prompt_logprobs: int | None = None,
|
||||
data_parallel_rank: int | None = None,
|
||||
) -> tuple[int, str]:
|
||||
# Ensure generate doesn't complete too fast for cancellation test.
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
count = 0
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
ignore_eos=True,
|
||||
output_kind=output_kind,
|
||||
temperature=0,
|
||||
prompt_logprobs=prompt_logprobs,
|
||||
)
|
||||
async for out in engine.generate(
|
||||
request_id=request_id,
|
||||
prompt=prompt,
|
||||
sampling_params=sampling_params,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
):
|
||||
num_tokens = len(out.outputs[0].token_ids)
|
||||
if output_kind == RequestOutputKind.DELTA:
|
||||
count += num_tokens
|
||||
else:
|
||||
count = num_tokens
|
||||
|
||||
await asyncio.sleep(0.0)
|
||||
|
||||
return count, request_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
"ibm-research/PowerMoE-3b",
|
||||
"hmellor/tiny-random-LlamaForCausalLM",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"output_kind",
|
||||
[
|
||||
RequestOutputKind.DELTA,
|
||||
RequestOutputKind.FINAL_ONLY,
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("data_parallel_backend", ["mp", "ray"])
|
||||
@pytest.mark.parametrize("async_scheduling", [True, False])
|
||||
@pytest.mark.asyncio
|
||||
async def test_load(
|
||||
model: str,
|
||||
output_kind: RequestOutputKind,
|
||||
data_parallel_backend: DataParallelBackend,
|
||||
async_scheduling: bool,
|
||||
):
|
||||
if async_scheduling and data_parallel_backend == "ray":
|
||||
# TODO(NickLucche) Re-enable when async scheduling is supported
|
||||
pytest.skip("Async scheduling is not supported with ray")
|
||||
elif data_parallel_backend == "ray" and current_platform.is_rocm():
|
||||
pytest.skip(
|
||||
"Ray as the distributed executor backend is not supported with ROCm."
|
||||
)
|
||||
stats_loggers = {}
|
||||
|
||||
@dataclass
|
||||
class SimpleStatsLogger(StatLoggerBase):
|
||||
init_count: int = 0
|
||||
finished_req_count: int = 0
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, engine_index: int = 0):
|
||||
stats_loggers[engine_index] = self
|
||||
|
||||
def record(
|
||||
self,
|
||||
scheduler_stats: SchedulerStats | None,
|
||||
iteration_stats: IterationStats | None,
|
||||
mm_cache_stats: MultiModalCacheStats | None = None,
|
||||
engine_idx: int = 0,
|
||||
):
|
||||
if iteration_stats:
|
||||
self.finished_req_count += len(iteration_stats.finished_requests)
|
||||
|
||||
def log_engine_initialized(self):
|
||||
self.init_count += 1
|
||||
|
||||
with ExitStack() as after:
|
||||
prompt = "This is a test of data parallel"
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model=model,
|
||||
enforce_eager=True,
|
||||
tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
|
||||
data_parallel_size=DP_SIZE,
|
||||
data_parallel_backend=data_parallel_backend,
|
||||
async_scheduling=async_scheduling,
|
||||
)
|
||||
engine = AsyncLLM.from_engine_args(
|
||||
engine_args, stat_loggers=[SimpleStatsLogger]
|
||||
)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
# The first request an engine serves pays a few hundred milliseconds of
|
||||
# one-off setup, and while it does the engine holds the requests already
|
||||
# routed to it while reporting itself idle, which is enough to skew the
|
||||
# split asserted on below. Pay it on every engine first, then measure.
|
||||
await asyncio.gather(
|
||||
*(
|
||||
generate(
|
||||
engine,
|
||||
f"warmup-{rank}",
|
||||
prompt,
|
||||
output_kind,
|
||||
max_tokens=1,
|
||||
data_parallel_rank=rank,
|
||||
)
|
||||
for rank in range(DP_SIZE)
|
||||
)
|
||||
)
|
||||
for sl in stats_loggers.values():
|
||||
sl.finished_req_count = 0
|
||||
|
||||
NUM_REQUESTS = 100
|
||||
NUM_EXPECTED_TOKENS = 10
|
||||
|
||||
request_ids = [f"request-{i}" for i in range(NUM_REQUESTS)]
|
||||
|
||||
# Create concurrent requests.
|
||||
tasks = []
|
||||
for request_id in request_ids:
|
||||
tasks.append(
|
||||
asyncio.create_task(
|
||||
generate(
|
||||
engine, request_id, prompt, output_kind, NUM_EXPECTED_TOKENS
|
||||
)
|
||||
)
|
||||
)
|
||||
# Short sleep to ensure that requests are distributed.
|
||||
await asyncio.sleep(0.01)
|
||||
# Confirm that we got all the EXPECTED tokens from the requests.
|
||||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
for task in done:
|
||||
num_generated_tokens, request_id = await task
|
||||
assert num_generated_tokens == NUM_EXPECTED_TOKENS, (
|
||||
f"{request_id} generated {num_generated_tokens} but "
|
||||
f"expected {NUM_EXPECTED_TOKENS}"
|
||||
)
|
||||
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
# testing internals here which may break
|
||||
core_client = engine.engine_core
|
||||
assert isinstance(core_client, DPLBAsyncMPClient)
|
||||
# the engines only synchronize stopping every N steps so
|
||||
# allow a small amount of time here.
|
||||
for _ in range(10):
|
||||
if not core_client.engines_running:
|
||||
break
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
assert not core_client.engines_running
|
||||
assert not core_client.reqs_in_flight
|
||||
|
||||
# Check that requests were distributed between the engines
|
||||
print(f"Stats loggers after test: {stats_loggers}")
|
||||
assert len(stats_loggers) == DP_SIZE
|
||||
assert stats_loggers[0].init_count == 1
|
||||
|
||||
for sl in stats_loggers.values():
|
||||
slogger: SimpleStatsLogger = sl
|
||||
|
||||
assert slogger.finished_req_count > NUM_REQUESTS // (DP_SIZE + 1), (
|
||||
f"requests are imbalanced: {stats_loggers}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefill_schedule_interval", [1, 4])
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_prefill_schedule_interval(prefill_schedule_interval: int):
|
||||
"""Throttling new prefills to every Nth step (DP balancing) must not break
|
||||
generation: a stream of staggered requests should still all complete with
|
||||
the expected number of tokens.
|
||||
|
||||
The throttle only engages in the DP MoE/EP engine-core path
|
||||
(`DPEngineCoreProc`), so this uses an MoE model with expert parallel.
|
||||
"""
|
||||
with ExitStack() as after:
|
||||
prompt = "This is a test of data parallel"
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model="ibm-research/PowerMoE-3b",
|
||||
enforce_eager=True,
|
||||
tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
|
||||
data_parallel_size=DP_SIZE,
|
||||
data_parallel_backend="mp",
|
||||
enable_expert_parallel=True,
|
||||
prefill_schedule_interval=prefill_schedule_interval,
|
||||
)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
NUM_REQUESTS = 50
|
||||
NUM_EXPECTED_TOKENS = 10
|
||||
|
||||
request_ids = [f"request-{i}" for i in range(NUM_REQUESTS)]
|
||||
|
||||
# Create requests with a small stagger so they arrive across many
|
||||
# steps and (with interval > 1) accumulate in the waiting queue
|
||||
# before being admitted together on cadence-aligned steps.
|
||||
tasks = []
|
||||
for request_id in request_ids:
|
||||
tasks.append(
|
||||
asyncio.create_task(
|
||||
generate(
|
||||
engine,
|
||||
request_id,
|
||||
prompt,
|
||||
RequestOutputKind.DELTA,
|
||||
NUM_EXPECTED_TOKENS,
|
||||
)
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
for task in done:
|
||||
num_generated_tokens, request_id = await task
|
||||
assert num_generated_tokens == NUM_EXPECTED_TOKENS, (
|
||||
f"{request_id} generated {num_generated_tokens} but "
|
||||
f"expected {NUM_EXPECTED_TOKENS}"
|
||||
)
|
||||
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# DP Pause/Resume Tests
|
||||
# =============================================================================
|
||||
# When expert_parallel=False: uses non-MoE model (DP replicas as separate engines).
|
||||
# When expert_parallel=True: uses MoE model + EP (DPEngineCoreProc, sync pause path).
|
||||
|
||||
DP_PAUSE_MODEL = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
DP_PAUSE_MODEL_MOE = "ibm-research/PowerMoE-3b"
|
||||
DP_PAUSE_PROMPT = "This is a test of data parallel pause"
|
||||
|
||||
|
||||
def _get_dp_pause_engine_args(expert_parallel: bool) -> AsyncEngineArgs:
|
||||
"""Engine args for DP pause tests: MoE+EP when expert_parallel else small Llama."""
|
||||
model = DP_PAUSE_MODEL_MOE if expert_parallel else DP_PAUSE_MODEL
|
||||
return AsyncEngineArgs(
|
||||
model=model,
|
||||
enforce_eager=True,
|
||||
tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
|
||||
data_parallel_size=DP_SIZE,
|
||||
data_parallel_backend="mp",
|
||||
enable_expert_parallel=expert_parallel,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("expert_parallel", [False, True])
|
||||
async def test_dp_pause_resume_basic(expert_parallel: bool):
|
||||
"""Pausing from the client (one call) pauses all DP ranks; resume clears it."""
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
assert not await engine.is_paused()
|
||||
await engine.pause_generation(mode="abort")
|
||||
assert await engine.is_paused()
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
|
||||
# Engine still works after resume
|
||||
sampling_params = SamplingParams(max_tokens=5)
|
||||
async for out in engine.generate(
|
||||
request_id="after-resume",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
pass
|
||||
assert out.finished
|
||||
|
||||
|
||||
async def _consume(generator) -> None:
|
||||
async for _ in generator:
|
||||
pass
|
||||
|
||||
|
||||
async def _poll_flag(engine: AsyncLLM, want: bool, timeout: float) -> bool:
|
||||
"""Wait for the front-end's view of the DP engines to reach ``want``."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if engine.engine_core.dp_engines_running() == want:
|
||||
return True
|
||||
await asyncio.sleep(0.05)
|
||||
return False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_late_request_does_not_block_drain():
|
||||
"""A request arriving after pause must not make the coordinator believe
|
||||
the engines are running.
|
||||
|
||||
Paused engines start no wave for it, so nothing could report wave
|
||||
completion afterwards; a running flag set on its behalf would leave drain
|
||||
no way back but a timeout.
|
||||
|
||||
MoE only: wave coordination is enabled iff the model is MoE, so a dense
|
||||
model never reaches the coordinator state this exercises.
|
||||
"""
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel=True)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
# Run a wave first, so the engines are quiesced by the pause rather
|
||||
# than by never having started, and drain has something to observe.
|
||||
long_request = asyncio.create_task(
|
||||
_consume(
|
||||
engine.generate(
|
||||
request_id="warmup",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=400, ignore_eos=True),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# A design that never reports the engines as running would satisfy
|
||||
# every drain assertion below while destroying the signal, so pin it
|
||||
# down first. Rank 0 reports the wave only after its first step, which
|
||||
# can outlast the 2s on a cold device, so wait for the report rather
|
||||
# than sample it.
|
||||
await asyncio.sleep(2)
|
||||
assert not long_request.done(), "the warmup request was too short to sample"
|
||||
assert await _poll_flag(engine, True, timeout=30), (
|
||||
"the coordinator does not report the engines as running while they are"
|
||||
)
|
||||
|
||||
await long_request
|
||||
assert await _poll_flag(engine, False, timeout=30)
|
||||
|
||||
await engine.pause_generation(mode="abort")
|
||||
await engine.wait_for_requests_to_drain(drain_timeout=30)
|
||||
|
||||
collector = await engine.add_request(
|
||||
request_id="late",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
params=SamplingParams(max_tokens=5),
|
||||
)
|
||||
assert not await _poll_flag(engine, True, timeout=5)
|
||||
|
||||
# The late request was held rather than dropped: it completes on resume.
|
||||
await engine.resume_generation()
|
||||
while True:
|
||||
out = await asyncio.wait_for(collector.get(), timeout=60)
|
||||
if out.finished:
|
||||
break
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_request_reaching_rank_after_resume_wakes_peers():
|
||||
"""A request can reach its rank only after resume (e.g. from another API
|
||||
server), with no other work anywhere. That rank must wake its peers itself,
|
||||
or it steps alone. Modelled here by holding the request's ADD on the client
|
||||
side across pause and resume."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(
|
||||
_get_dp_pause_engine_args(expert_parallel=True)
|
||||
)
|
||||
after.callback(engine.shutdown)
|
||||
client = engine.engine_core
|
||||
params = SamplingParams(max_tokens=5)
|
||||
|
||||
await _consume(engine.generate(DP_PAUSE_PROMPT, params, "warmup"))
|
||||
await engine.pause_generation(mode="abort")
|
||||
assert await _poll_flag(engine, False, timeout=30)
|
||||
|
||||
held: list[tuple] = []
|
||||
send_input = client._send_input
|
||||
|
||||
def hold_add(request_type, request, engine_id=None):
|
||||
if request_type == EngineCoreRequestType.ADD:
|
||||
held.append((request_type, request, engine_id))
|
||||
return asyncio.sleep(0)
|
||||
return send_input(request_type, request, engine_id)
|
||||
|
||||
client._send_input = hold_add
|
||||
task = asyncio.create_task(
|
||||
_consume(engine.generate(DP_PAUSE_PROMPT, params, "late"))
|
||||
)
|
||||
await asyncio.sleep(2)
|
||||
assert held
|
||||
|
||||
await engine.resume_generation()
|
||||
client._send_input = send_input
|
||||
await send_input(*held[0])
|
||||
await asyncio.wait_for(task, timeout=60)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_sleep_late_request_does_not_block_drain():
|
||||
"""The same latch, reached through sleep rather than pause.
|
||||
|
||||
Sleep stops the engines stepping just as pause does, so a request arriving
|
||||
while they are asleep can leave the coordinator believing they are running
|
||||
with nothing able to say otherwise. This is worth pinning separately from
|
||||
the pause case because it is the shape that reaches
|
||||
`_drain_requests_for_elastic_ep`, which decides from the same signal
|
||||
whether it is safe to scale.
|
||||
"""
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel=True)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
async for _ in engine.generate(
|
||||
request_id="warmup",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
assert await _poll_flag(engine, False, timeout=30)
|
||||
|
||||
await engine.sleep(level=1)
|
||||
assert await engine.is_sleeping()
|
||||
|
||||
collector = await engine.add_request(
|
||||
request_id="while-asleep",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
params=SamplingParams(max_tokens=5),
|
||||
)
|
||||
assert not await _poll_flag(engine, True, timeout=5)
|
||||
|
||||
await engine.wake_up()
|
||||
assert not await engine.is_sleeping()
|
||||
while True:
|
||||
out = await asyncio.wait_for(collector.get(), timeout=60)
|
||||
if out.finished:
|
||||
break
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("expert_parallel", [False, True])
|
||||
async def test_dp_pause_abort(expert_parallel: bool):
|
||||
"""Pause with abort from one client aborts in-flight requests on all DP ranks."""
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
# Start several requests so they are distributed across ranks
|
||||
sampling_params = SamplingParams(max_tokens=500, ignore_eos=True)
|
||||
num_requests = 4
|
||||
outputs_by_id: dict[str, list[RequestOutput]] = {}
|
||||
|
||||
async def gen(rid: str):
|
||||
out_list: list[RequestOutput] = []
|
||||
outputs_by_id[rid] = out_list
|
||||
async for out in engine.generate(
|
||||
request_id=rid,
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
out_list.append(out)
|
||||
return out_list[-1] if out_list else None
|
||||
|
||||
tasks = [asyncio.create_task(gen(f"req-{i}")) for i in range(num_requests)]
|
||||
# Wait for some tokens on at least one request
|
||||
while not any(len(o) >= 2 for o in outputs_by_id.values()):
|
||||
await asyncio.sleep(0.02)
|
||||
|
||||
await engine.pause_generation(mode="abort")
|
||||
|
||||
finals = await asyncio.gather(*tasks)
|
||||
for i, final in enumerate(finals):
|
||||
assert final is not None, f"req-{i} had no output"
|
||||
assert final.finished
|
||||
assert final.outputs[0].finish_reason == "abort"
|
||||
|
||||
assert await engine.is_paused()
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
|
||||
# New request completes after resume
|
||||
async for out in engine.generate(
|
||||
request_id="after-abort",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
assert out.finished
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("expert_parallel", [False, True])
|
||||
async def test_dp_pause_keep_then_resume(expert_parallel: bool):
|
||||
"""Start generation, pause after a few tokens (keep mode), resume; verify gap."""
|
||||
pause_duration = 2.0
|
||||
min_tokens_before_pause = 3
|
||||
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
sampling_params = SamplingParams(max_tokens=15, ignore_eos=True)
|
||||
token_times: list[tuple[int, float]] = []
|
||||
pause_token_idx = 0
|
||||
|
||||
async def generator_task():
|
||||
nonlocal pause_token_idx
|
||||
out = None
|
||||
async for output in engine.generate(
|
||||
request_id="keep-resume-req",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
token_count = len(output.outputs[0].token_ids)
|
||||
token_times.append((token_count, time.monotonic()))
|
||||
out = output
|
||||
return out
|
||||
|
||||
async def controller_task():
|
||||
nonlocal pause_token_idx
|
||||
while len(token_times) < min_tokens_before_pause:
|
||||
await asyncio.sleep(0.01)
|
||||
await engine.pause_generation(mode="keep")
|
||||
await asyncio.sleep(pause_duration)
|
||||
pause_token_idx = len(token_times)
|
||||
await engine.resume_generation()
|
||||
|
||||
gen_task = asyncio.create_task(generator_task())
|
||||
ctrl_task = asyncio.create_task(controller_task())
|
||||
final_output, _ = await asyncio.gather(gen_task, ctrl_task)
|
||||
|
||||
assert final_output is not None and final_output.finished
|
||||
assert await engine.is_paused() is False
|
||||
assert pause_token_idx >= min_tokens_before_pause
|
||||
if pause_token_idx > 0 and pause_token_idx < len(token_times):
|
||||
pause_gap = (
|
||||
token_times[pause_token_idx][1] - token_times[pause_token_idx - 1][1]
|
||||
)
|
||||
assert pause_gap >= pause_duration * 0.8, (
|
||||
f"Expected gap ~{pause_duration}s after pause, got {pause_gap:.3f}s"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_keep_race_staggered_engines():
|
||||
"""Race: send pause(keep) to engine 0, then add two requests,
|
||||
then pause(keep) to engine 1. Ensures no deadlock when pause
|
||||
requests are staggered and requests arrive in between."""
|
||||
if DP_SIZE != 2:
|
||||
pytest.skip("test_dp_pause_keep_race_staggered_engines requires DP_SIZE=2")
|
||||
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel=True)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
client = engine.engine_core
|
||||
|
||||
original_call_utility = client.call_utility_async
|
||||
mid_pause_tasks: list[asyncio.Task] = []
|
||||
|
||||
async def staggered_pause_keep(method: str, *args) -> Any:
|
||||
if method != "pause_scheduler" or not args or args[0] != "keep":
|
||||
return await original_call_utility(method, *args)
|
||||
# Fire pause(keep) to engine 0 (don't await — with DP
|
||||
# two-phase pause, consensus requires all ranks).
|
||||
pause_0 = asyncio.create_task(
|
||||
client._call_utility_async(method, *args, engine=client.core_engines[0])
|
||||
)
|
||||
# Let the event loop send the message to engine 0.
|
||||
await asyncio.sleep(0.5)
|
||||
# In the middle: send two requests (race window)
|
||||
sp = SamplingParams(max_tokens=5, ignore_eos=True)
|
||||
|
||||
async def consume_gen(req_id: str) -> None:
|
||||
async for _ in engine.generate(
|
||||
request_id=req_id,
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=sp,
|
||||
):
|
||||
pass
|
||||
|
||||
t1 = asyncio.create_task(consume_gen("race-1"))
|
||||
t2 = asyncio.create_task(consume_gen("race-2"))
|
||||
mid_pause_tasks.extend([t1, t2])
|
||||
await asyncio.sleep(3)
|
||||
# Fire pause(keep) to engine 1, then await both so
|
||||
# consensus can be reached.
|
||||
pause_1 = asyncio.create_task(
|
||||
client._call_utility_async(method, *args, engine=client.core_engines[1])
|
||||
)
|
||||
results = await asyncio.gather(pause_0, pause_1)
|
||||
return results[0]
|
||||
|
||||
client.call_utility_async = staggered_pause_keep
|
||||
|
||||
await engine.pause_generation(mode="keep")
|
||||
assert await engine.is_paused()
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
# Let the two requests we sent mid-pause complete
|
||||
await asyncio.gather(*mid_pause_tasks)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_barrier_request_deadlock():
|
||||
"""Test that a request sent while paused does not wake any engine.
|
||||
|
||||
Sequence:
|
||||
1. Pause all engines (PAUSED_ALL).
|
||||
2. Send barrier to engine 0 only — blocks in dist.barrier(dp_group).
|
||||
3. Send a request routed to engine 1.
|
||||
4. Wait for any (buggy) START_DP_WAVE propagation.
|
||||
5. Send barrier to engine 1 — completes in fixed code, deadlocks
|
||||
in buggy code because engine 1 is stuck in EP all-to-all.
|
||||
"""
|
||||
if DP_SIZE != 2:
|
||||
pytest.skip("requires DP_SIZE=2")
|
||||
|
||||
with ExitStack() as after:
|
||||
engine_args = _get_dp_pause_engine_args(expert_parallel=True)
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
client = engine.engine_core
|
||||
|
||||
# Cache get_supported_tasks so that generate() won't need to
|
||||
# send a utility call to all engines (which would hang once
|
||||
# engine 0 is blocked in the barrier).
|
||||
await engine.get_supported_tasks()
|
||||
|
||||
# Pause all engines normally — no staggering.
|
||||
await engine.pause_generation(mode="keep")
|
||||
assert await engine.is_paused()
|
||||
|
||||
original_call_utility = client.call_utility_async
|
||||
mid_barrier_tasks: list[asyncio.Task] = []
|
||||
|
||||
async def staggered_barrier(method: str, *args) -> Any:
|
||||
if method != "barrier":
|
||||
return await original_call_utility(method, *args)
|
||||
|
||||
# Send barrier to engine 0 only — it blocks in
|
||||
# dist.barrier(dp_group) waiting for engine 1.
|
||||
barrier_0 = asyncio.create_task(
|
||||
client._call_utility_async(method, *args, engine=client.core_engines[0])
|
||||
)
|
||||
await asyncio.sleep(1)
|
||||
|
||||
# While engine 0 is blocked, send a request routed
|
||||
# specifically to engine 1.
|
||||
sp = SamplingParams(max_tokens=5, ignore_eos=True)
|
||||
|
||||
engine_1 = client.core_engines[1]
|
||||
original_get_engine = client.get_core_engine_for_request
|
||||
|
||||
def route_to_engine_1(req):
|
||||
client.reqs_in_flight[req.request_id] = engine_1
|
||||
return engine_1
|
||||
|
||||
client.get_core_engine_for_request = route_to_engine_1
|
||||
|
||||
async def consume_gen(req_id: str) -> None:
|
||||
async for _ in engine.generate(
|
||||
request_id=req_id,
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=sp,
|
||||
):
|
||||
pass
|
||||
|
||||
t1 = asyncio.create_task(consume_gen("race-1"))
|
||||
mid_barrier_tasks.append(t1)
|
||||
|
||||
# Yield so generate() preprocessing completes and
|
||||
# add_request_async is called (which, in buggy code,
|
||||
# would wake engine 1).
|
||||
for _ in range(200):
|
||||
await asyncio.sleep(0)
|
||||
|
||||
client.get_core_engine_for_request = original_get_engine
|
||||
|
||||
# Wait for any START_DP_WAVE to propagate and for
|
||||
# engine 1 to potentially enter execute_dummy_batch.
|
||||
await asyncio.sleep(5)
|
||||
|
||||
# Now send barrier to engine 1. In buggy code engine 1
|
||||
# is stuck in execute_dummy_batch (EP all-to-all) while
|
||||
# engine 0 is stuck in dist.barrier(dp_group) — deadlock.
|
||||
result = await client._call_utility_async(
|
||||
method, *args, engine=client.core_engines[1]
|
||||
)
|
||||
await barrier_0
|
||||
return result
|
||||
|
||||
client.call_utility_async = staggered_barrier
|
||||
|
||||
# Drive the staggered barrier. Old code deadlocks here.
|
||||
try:
|
||||
await asyncio.wait_for(client.call_utility_async("barrier"), timeout=30)
|
||||
except TimeoutError:
|
||||
for t in mid_barrier_tasks:
|
||||
t.cancel()
|
||||
pytest.fail(
|
||||
"Staggered barrier deadlocked — a request sent while "
|
||||
"paused caused collective-op mismatch between engines"
|
||||
)
|
||||
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
# Let the two requests we sent mid-barrier complete.
|
||||
await asyncio.gather(*mid_barrier_tasks)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_wait_mode_drains_in_flight():
|
||||
"""mode="wait" through the DP consensus path: the pause lets the
|
||||
in-flight request run to completion while the consensus is pending,
|
||||
resolves only once drained, and the engine generates again on resume."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_get_dp_pause_engine_args(True))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
collector = await engine.add_request(
|
||||
request_id="inflight",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
params=SamplingParams(max_tokens=64),
|
||||
)
|
||||
# Wait for the first output, so drain has something to observe: a
|
||||
# request still queued holds no blocks and is not waited on.
|
||||
out = await asyncio.wait_for(collector.get(), timeout=30)
|
||||
await engine.pause_generation(mode="wait")
|
||||
assert await engine.is_paused()
|
||||
while not out.finished:
|
||||
out = await asyncio.wait_for(collector.get(), timeout=30)
|
||||
|
||||
await engine.resume_generation()
|
||||
async for out in engine.generate(
|
||||
request_id="after-wait",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
assert out.finished
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_while_asleep():
|
||||
"""Pausing a sleeping DP engine: sleeping ranks skip dummy batches yet
|
||||
must still reach the pause consensus, and the completion barrier must
|
||||
be harmless on workers whose memory is unmapped."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_get_dp_pause_engine_args(True))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
async for _ in engine.generate(
|
||||
request_id="warmup",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
await engine.sleep(level=1)
|
||||
assert await engine.is_sleeping()
|
||||
|
||||
await asyncio.wait_for(engine.pause_generation(mode="abort"), timeout=30)
|
||||
assert await engine.is_paused()
|
||||
|
||||
# A full wake makes the memory resident and resumes the scheduler.
|
||||
await engine.wake_up()
|
||||
assert not await engine.is_sleeping()
|
||||
async for out in engine.generate(
|
||||
request_id="after-wake",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
assert out.finished
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_pause_completion_implies_device_idle(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""A resolved pause future promises an idle device. Inflate the dummy
|
||||
batches the pause consensus manufactures so any work the pause fails to
|
||||
wait on stays visible, then require a quiet worker stream the moment
|
||||
pause_generation() returns."""
|
||||
with ExitStack() as after:
|
||||
# The probes below ship functions through collective_rpc.
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
engine = AsyncLLM.from_engine_args(_get_dp_pause_engine_args(True))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
async for _ in engine.generate(
|
||||
request_id="warmup",
|
||||
prompt=DP_PAUSE_PROMPT,
|
||||
sampling_params=SamplingParams(max_tokens=5),
|
||||
):
|
||||
pass
|
||||
|
||||
def inflate_dummy_batches(worker: Any) -> bool:
|
||||
import torch
|
||||
|
||||
inner = worker.execute_dummy_batch
|
||||
|
||||
def slow_dummy_batch() -> None:
|
||||
inner()
|
||||
# Keep the stream busy after launch, like a large-MoE forward.
|
||||
torch.cuda._sleep(200_000_000)
|
||||
|
||||
worker.execute_dummy_batch = slow_dummy_batch
|
||||
return True
|
||||
|
||||
assert all(await engine.engine_core.collective_rpc_async(inflate_dummy_batches))
|
||||
|
||||
await asyncio.wait_for(engine.pause_generation(mode="abort"), timeout=60)
|
||||
|
||||
def device_idle(worker: Any) -> bool:
|
||||
import torch
|
||||
|
||||
return bool(torch.cuda.current_stream().query())
|
||||
|
||||
assert all(await engine.engine_core.collective_rpc_async(device_idle))
|
||||
@@ -1,119 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test Dual Batch Overlap (DBO) with Data Parallelism + Expert Parallelism.
|
||||
|
||||
DBO is specifically designed for DP+EP scenarios to hide communication latency
|
||||
by overlapping computation of two batches. This test validates that DBO works
|
||||
correctly with the DeepSeek-V2-Lite model using GSM8K evaluation.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_deep_ep
|
||||
|
||||
# Detect Blackwell / B200 (compute capability 10.x)
|
||||
try:
|
||||
if torch.cuda.is_available():
|
||||
cap = torch.cuda.get_device_capability(0)
|
||||
IS_BLACKWELL = cap[0] >= 10
|
||||
else:
|
||||
IS_BLACKWELL = False
|
||||
except Exception:
|
||||
# Be conservative: if we can't detect, don't xfail by default
|
||||
IS_BLACKWELL = False
|
||||
|
||||
MODEL_NAME = "deepseek-ai/DeepSeek-V2-Lite-Chat"
|
||||
DP_SIZE = 2
|
||||
|
||||
# GSM8K eval configuration
|
||||
NUM_QUESTIONS = 256 # Fast eval for CI; but must be large enough to hit dbo thresholds
|
||||
NUM_SHOTS = 5 # Few-shot examples
|
||||
|
||||
# Expected 0.64 with 2% buffer (based on vLLM test data)
|
||||
# On ROCm, widened to 0.61 after observing 0.617 amd-ci nightly flake twice.
|
||||
MIN_ACCURACY = 0.61 if current_platform.is_rocm() else 0.62
|
||||
|
||||
# Increase max_num_seqs to trigger DBO for decode batches
|
||||
# With 64 seqs, decode batches should exceed the 32 token threshold
|
||||
MAX_NUM_SEQS = 64 # Increased from 16 to trigger decode DBO
|
||||
|
||||
# DeepEP backends to test
|
||||
DEEPEP_BACKENDS = [
|
||||
"deepep_low_latency",
|
||||
"deepep_high_throughput",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not has_deep_ep(), reason="These tests require deep_ep to run")
|
||||
@pytest.mark.parametrize("all2all_backend", DEEPEP_BACKENDS)
|
||||
@pytest.mark.xfail(
|
||||
IS_BLACKWELL,
|
||||
reason=(
|
||||
"Temporary: DBO accuracy unstable on Blackwell "
|
||||
"(doesn't meet expectation of MIN_ACCURACY = 0.62)"
|
||||
),
|
||||
)
|
||||
def test_dbo_dp_ep_gsm8k(all2all_backend: str, num_gpus_available):
|
||||
"""Test DBO with DP+EP using GSM8K evaluation."""
|
||||
lm_eval = pytest.importorskip("lm_eval")
|
||||
required_gpus = DP_SIZE
|
||||
|
||||
if num_gpus_available < required_gpus:
|
||||
pytest.skip(f"Need at least {required_gpus} GPUs (DP={DP_SIZE})")
|
||||
|
||||
# Server arguments for DBO + DP + EP
|
||||
server_args = [
|
||||
"--max-model-len",
|
||||
"4096",
|
||||
"--max-num-seqs",
|
||||
str(MAX_NUM_SEQS), # Use larger batch to trigger decode DBO
|
||||
"--trust-remote-code",
|
||||
# Note: Not using --enforce-eager to test DBO's alternate CUDA graph dispatching
|
||||
"--data-parallel-size",
|
||||
str(DP_SIZE),
|
||||
"--enable-expert-parallel",
|
||||
"--enable-dbo",
|
||||
# Fix threshold so we know we trigger DBO
|
||||
"--dbo-decode-token-threshold",
|
||||
"16",
|
||||
"--dbo-prefill-token-threshold",
|
||||
"32",
|
||||
"--all2all-backend",
|
||||
all2all_backend,
|
||||
]
|
||||
|
||||
with RemoteOpenAIServer(
|
||||
MODEL_NAME,
|
||||
server_args,
|
||||
max_wait_seconds=600, # Allow time for model loading with DP+EP
|
||||
) as remote_server:
|
||||
# Use host and port directly from RemoteOpenAIServer
|
||||
|
||||
base_url = f"http://{remote_server.host}:{remote_server.port}/v1/completions"
|
||||
|
||||
# Run GSM8K evaluation
|
||||
results = lm_eval.simple_evaluate(
|
||||
model="local-completions",
|
||||
model_args=(
|
||||
f"pretrained={MODEL_NAME},"
|
||||
f"base_url={base_url},"
|
||||
"num_concurrent=512,max_retries=3"
|
||||
),
|
||||
tasks=["gsm8k"],
|
||||
num_fewshot=NUM_SHOTS,
|
||||
limit=NUM_QUESTIONS,
|
||||
)
|
||||
# Validate accuracy is reasonable
|
||||
gsm8k = results["results"]["gsm8k"]
|
||||
accuracy = gsm8k.get(
|
||||
"exact_match,strict-match",
|
||||
gsm8k.get("exact_match,flexible-extract"),
|
||||
)
|
||||
assert accuracy is not None, f"gsm8k exact_match missing: {gsm8k}"
|
||||
assert accuracy >= MIN_ACCURACY, (
|
||||
f"DBO+DP+EP accuracy too low ({all2all_backend}): "
|
||||
f"{accuracy:.3f} < {MIN_ACCURACY:.3f} "
|
||||
)
|
||||
@@ -1,52 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL_NAME = "Qwen/Qwen3-0.6B"
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", "2"))
|
||||
TP_SIZE = int(os.getenv("TP_SIZE", "1"))
|
||||
|
||||
|
||||
def test_dense_dp_world_size():
|
||||
server_args = [
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"2048",
|
||||
"--max-num-seqs",
|
||||
"128",
|
||||
"--enforce-eager",
|
||||
"--data-parallel-size",
|
||||
str(DP_SIZE),
|
||||
"--data-parallel-size-local",
|
||||
str(DP_SIZE),
|
||||
"--tensor-parallel-size",
|
||||
str(TP_SIZE),
|
||||
]
|
||||
env_dict = {
|
||||
"VLLM_SERVER_DEV_MODE": "1",
|
||||
current_platform.device_control_env_var: ",".join(
|
||||
str(current_platform.device_id_to_physical_device_id(i))
|
||||
for i in range(DP_SIZE * TP_SIZE)
|
||||
),
|
||||
}
|
||||
|
||||
with RemoteOpenAIServer(
|
||||
MODEL_NAME,
|
||||
server_args,
|
||||
env_dict=env_dict,
|
||||
) as server:
|
||||
response = requests.get(server.url_for("get_world_size"))
|
||||
response.raise_for_status()
|
||||
assert response.json() == {"world_size": TP_SIZE * DP_SIZE}
|
||||
|
||||
response = requests.get(
|
||||
server.url_for("get_world_size"), params={"include_dp": "false"}
|
||||
)
|
||||
response.raise_for_status()
|
||||
assert response.json() == {"world_size": TP_SIZE}
|
||||
@@ -1,109 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import AsyncExitStack
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", 2))
|
||||
|
||||
if current_platform.is_rocm():
|
||||
ATTN_BACKENDS = ["ROCM_ATTN", "TRITON_ATTN", "FLEX_ATTENTION"]
|
||||
else:
|
||||
ATTN_BACKENDS = ["FLASH_ATTN"]
|
||||
|
||||
# On SM<90 (e.g., L4), batch invariance does not support CUDA graphs.
|
||||
# See https://github.com/vllm-project/vllm/pull/30018 and
|
||||
# tests/v1/determinism/utils.py for the documented limitation.
|
||||
IS_DEVICE_CAPABILITY_BELOW_90 = not current_platform.has_device_capability(90)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("attn_backend", ATTN_BACKENDS)
|
||||
@pytest.mark.xfail(
|
||||
current_platform.is_rocm(),
|
||||
reason="Test may fail on ROCm until batch invariance is enabled. "
|
||||
"See: https://github.com/vllm-project/vllm/issues/27433",
|
||||
strict=False,
|
||||
)
|
||||
async def test_run_eagle_dp(monkeypatch: pytest.MonkeyPatch, attn_backend: str):
|
||||
if not current_platform.is_rocm() and not current_platform.is_xpu():
|
||||
# This test checks that running a model with and without eagle
|
||||
# leads to identical tokens.
|
||||
#
|
||||
# NOTE: This is only true in batch invariant mode
|
||||
# (because the target model verifies all draft tokens in one big
|
||||
# forward pass)
|
||||
#
|
||||
# TODO[ROCm]: Test is passing on ROCm CI but may break in future.
|
||||
# Enable batch invariance for ROCm when possible. See:
|
||||
# https://github.com/vllm-project/vllm/issues/27433
|
||||
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
|
||||
target_model = "meta-llama/Llama-3.1-8B-Instruct"
|
||||
draft_model = "yuhuili/EAGLE-LLaMA3.1-Instruct-8B"
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model=target_model,
|
||||
tokenizer_mode="auto",
|
||||
enforce_eager=IS_DEVICE_CAPABILITY_BELOW_90,
|
||||
tensor_parallel_size=int(os.getenv("TP_SIZE", 1)),
|
||||
data_parallel_size=DP_SIZE,
|
||||
data_parallel_backend="mp", # ray takes more time
|
||||
trust_remote_code=True,
|
||||
max_model_len=16384,
|
||||
attention_config={"backend": attn_backend},
|
||||
)
|
||||
|
||||
eagle_engine_args = replace(
|
||||
engine_args,
|
||||
speculative_config={
|
||||
"model": draft_model,
|
||||
"method": "eagle",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
)
|
||||
|
||||
prompt = "This is a test of data parallel with eagle"
|
||||
num_expected_tokens = 100
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=num_expected_tokens,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.FINAL_ONLY,
|
||||
temperature=0,
|
||||
)
|
||||
|
||||
async def generate_with_timeout(given_engine: AsyncLLM):
|
||||
async for out in given_engine.generate(
|
||||
request_id="test-eagle-dp", prompt=prompt, sampling_params=sampling_params
|
||||
):
|
||||
token_ids = out.outputs[0].token_ids
|
||||
assert len(token_ids) == num_expected_tokens
|
||||
return token_ids
|
||||
|
||||
async def engine_create_and_generate(engine_args: AsyncEngineArgs):
|
||||
async with AsyncExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
token_ids = await asyncio.wait_for(
|
||||
generate_with_timeout(engine), timeout=30
|
||||
)
|
||||
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
return token_ids
|
||||
|
||||
token_ids_with_eagle = await engine_create_and_generate(eagle_engine_args)
|
||||
token_ids_no_eagle = await engine_create_and_generate(engine_args)
|
||||
|
||||
# Test for correctness
|
||||
assert token_ids_with_eagle == token_ids_no_eagle
|
||||
@@ -1,601 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from contextlib import AsyncExitStack
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
import msgspec
|
||||
import openai # use the official client for correctness check
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.distributed.elastic_ep.external_elastic_ep import (
|
||||
ExternalElasticEPScaleCoordinator,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine.core_client import DPAsyncMPClient
|
||||
|
||||
MODEL_NAME = os.getenv("MODEL_NAME", "ibm-research/PowerMoE-3b")
|
||||
ELASTIC_EP_MODEL_NAME = "deepseek-ai/DeepSeek-V2-Lite-Chat"
|
||||
|
||||
# Number of data parallel ranks for external LB testing
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", "2"))
|
||||
# Default tensor parallel size to use
|
||||
TP_SIZE = int(os.getenv("TP_SIZE", "1"))
|
||||
|
||||
|
||||
class DictStore:
|
||||
def __init__(self, values: dict[str, bytes]):
|
||||
self.values = values
|
||||
|
||||
def check(self, keys: list[str]) -> bool:
|
||||
return all(key in self.values for key in keys)
|
||||
|
||||
def get(self, key: str) -> bytes:
|
||||
return self.values[key]
|
||||
|
||||
def set(self, key: str, value: bytes) -> None:
|
||||
self.values[key] = value
|
||||
|
||||
|
||||
def test_external_elastic_ep_visible_epoch_has_bootstrap_and_phase(monkeypatch):
|
||||
client = SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_master_port=12345,
|
||||
_data_parallel_master_port_list=[12346, 12347],
|
||||
)
|
||||
)
|
||||
)
|
||||
coordinator = ExternalElasticEPScaleCoordinator(cast("DPAsyncMPClient", client))
|
||||
control_store, reconfig_store = DictStore({}), DictStore({})
|
||||
coordinator.reconfig_store_ref = reconfig_store
|
||||
monkeypatch.setattr(
|
||||
coordinator, "_setup_reconfig_bootstrap", lambda: ("127.0.0.1", 12348)
|
||||
)
|
||||
epoch, bootstrap = coordinator._prepare_reconfig_bootstrap(control_store, 2, 3)
|
||||
|
||||
for store in (control_store, reconfig_store):
|
||||
# DictStore preserves insertion order: metadata must precede the epoch.
|
||||
assert list(store.values)[-1] == coordinator.key("current_epoch")
|
||||
assert store.get(coordinator.key(epoch, "bootstrap")) == msgspec.msgpack.encode(
|
||||
bootstrap
|
||||
)
|
||||
assert store.get(coordinator.key(epoch, "phase")) == b"preparing"
|
||||
assert store.get(coordinator.key("current_epoch")) == epoch.encode()
|
||||
monkeypatch.setattr(
|
||||
coordinator, "_get_reconfig_store", lambda store=store: store
|
||||
)
|
||||
assert coordinator.get_status()["requested_data_parallel_size"] == 3
|
||||
|
||||
|
||||
def test_external_elastic_ep_calculates_target_expert_redundancy():
|
||||
client = SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
model_config=SimpleNamespace(get_num_experts=lambda: 128),
|
||||
parallel_config=SimpleNamespace(
|
||||
eplb_config=SimpleNamespace(num_redundant_experts=0)
|
||||
),
|
||||
)
|
||||
)
|
||||
coordinator = ExternalElasticEPScaleCoordinator(cast("DPAsyncMPClient", client))
|
||||
|
||||
assert coordinator._calculate_num_redundant_experts(2, 3) == 64
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("dp_rank", range(4))
|
||||
async def test_validate_expert_capacity_on_every_rank(dp_rank, monkeypatch):
|
||||
"""Validate expert capacity on every rank before waiting for an epoch."""
|
||||
client = SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
model_config=SimpleNamespace(get_num_experts=lambda: 128),
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_rank=dp_rank,
|
||||
elastic_ep_max_dp_size=4,
|
||||
data_parallel_master_ip="127.0.0.1",
|
||||
_coord_store_port=12345,
|
||||
eplb_config=SimpleNamespace(num_redundant_experts=0),
|
||||
),
|
||||
)
|
||||
)
|
||||
coordinator = ExternalElasticEPScaleCoordinator(cast("DPAsyncMPClient", client))
|
||||
store = DictStore({})
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.utils.get_cached_tcp_store_client", lambda *args: store
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="cannot retain all model experts"):
|
||||
await asyncio.wait_for(coordinator.prepare(4, 2), timeout=1)
|
||||
|
||||
assert not store.values
|
||||
assert coordinator.prepared_scale is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_external_elastic_ep_late_rank_observes_epoch_error():
|
||||
coordinator = ExternalElasticEPScaleCoordinator(
|
||||
cast("DPAsyncMPClient", SimpleNamespace())
|
||||
)
|
||||
epoch = "failed-epoch"
|
||||
store = DictStore(
|
||||
{
|
||||
coordinator.key("current_epoch"): epoch.encode(),
|
||||
coordinator.key(epoch, "error"): b"scale failed",
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="scale failed"):
|
||||
await coordinator._wait_for_bootstrap(store, requested_new_dp_size=3)
|
||||
|
||||
|
||||
class ExternalLBServerManager:
|
||||
"""Manages data parallel vLLM server instances for external
|
||||
load balancer testing."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
dp_size: int,
|
||||
api_server_count: int,
|
||||
base_server_args: list,
|
||||
tp_size: int = TP_SIZE,
|
||||
):
|
||||
self.model_name = model_name
|
||||
self.dp_size = dp_size
|
||||
self.tp_size = tp_size
|
||||
self.api_server_count = api_server_count
|
||||
self.base_server_args = base_server_args
|
||||
self.servers: list[tuple[RemoteOpenAIServer, list[str]]] = []
|
||||
self.server_threads: list[threading.Thread] = []
|
||||
|
||||
def start_rank(
|
||||
self,
|
||||
rank: int,
|
||||
dp_size: int | None = None,
|
||||
elastic_ep_scale_up_launch: bool = False,
|
||||
) -> tuple[RemoteOpenAIServer, list[str]]:
|
||||
"""Start one externally managed DP rank."""
|
||||
dp_size = self.dp_size if dp_size is None else dp_size
|
||||
server_args = self.base_server_args.copy()
|
||||
server_args.extend(
|
||||
[
|
||||
"--data-parallel-size",
|
||||
str(dp_size),
|
||||
"--data-parallel-rank",
|
||||
str(rank),
|
||||
"--data-parallel-size-local",
|
||||
"1",
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--port",
|
||||
str(8000 + rank),
|
||||
"--api-server-count",
|
||||
str(self.api_server_count),
|
||||
]
|
||||
)
|
||||
|
||||
env_dict = {
|
||||
"VLLM_SERVER_DEV_MODE": "1",
|
||||
current_platform.device_control_env_var: ",".join(
|
||||
str(current_platform.device_id_to_physical_device_id(i))
|
||||
for i in range(rank * self.tp_size, (rank + 1) * self.tp_size)
|
||||
),
|
||||
}
|
||||
if elastic_ep_scale_up_launch:
|
||||
env_dict["VLLM_ELASTIC_EP_SCALE_UP_LAUNCH"] = "1"
|
||||
|
||||
server = RemoteOpenAIServer(
|
||||
self.model_name,
|
||||
server_args,
|
||||
auto_port=False,
|
||||
env_dict=env_dict,
|
||||
)
|
||||
print(
|
||||
f"Server rank {rank} started successfully with "
|
||||
f"{self.api_server_count} API servers"
|
||||
)
|
||||
server_and_args = (server, server_args)
|
||||
self.servers.append(server_and_args)
|
||||
return server_and_args
|
||||
|
||||
def __enter__(self) -> list[tuple[RemoteOpenAIServer, list[str]]]:
|
||||
"""Start all initial server instances for external LB mode."""
|
||||
start_errors: list[Exception] = []
|
||||
for rank in range(self.dp_size):
|
||||
# Use a thread to start each server to allow parallel initialization
|
||||
def start_server(r: int):
|
||||
try:
|
||||
self.start_rank(r)
|
||||
except Exception as e:
|
||||
print(f"Failed to start server rank {r}: {e}")
|
||||
start_errors.append(e)
|
||||
|
||||
thread = threading.Thread(target=start_server, args=(rank,))
|
||||
thread.start()
|
||||
|
||||
self.server_threads.append(thread)
|
||||
|
||||
# Wait for all servers to start
|
||||
for thread in self.server_threads:
|
||||
thread.join()
|
||||
|
||||
if start_errors:
|
||||
start_error = start_errors[0]
|
||||
raise RuntimeError("Failed to start external LB servers") from start_error
|
||||
|
||||
# Give servers additional time to fully initialize and coordinate
|
||||
time.sleep(2)
|
||||
|
||||
if len(self.servers) != self.dp_size:
|
||||
raise Exception("Servers failed to start")
|
||||
|
||||
return self.servers
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Stop all server instances."""
|
||||
servers = [s for s, _ in self.servers]
|
||||
self.servers.clear()
|
||||
try:
|
||||
RemoteOpenAIServer.shutdown_many(servers)
|
||||
except Exception as e:
|
||||
print(f"Error stopping servers: {e}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def default_server_args():
|
||||
return [
|
||||
# use half precision for speed and memory savings in CI environment
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"2048",
|
||||
"--max-num-seqs",
|
||||
"128",
|
||||
"--enforce-eager",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
scope="module",
|
||||
params=[(1, False), (4, False), (1, True)],
|
||||
ids=["api-1-standard", "api-4-standard", "api-1-ep-enabled"],
|
||||
)
|
||||
def server_manager(request, default_server_args):
|
||||
api_server_count, enable_expert_parallel = request.param
|
||||
server_args = default_server_args.copy()
|
||||
if enable_expert_parallel:
|
||||
server_args.append("--enable-expert-parallel")
|
||||
|
||||
server_manager = ExternalLBServerManager(
|
||||
MODEL_NAME, DP_SIZE, api_server_count, server_args
|
||||
)
|
||||
|
||||
with server_manager:
|
||||
yield server_manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servers(server_manager):
|
||||
return server_manager.servers
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def clients(servers: list[tuple[RemoteOpenAIServer, list[str]]]):
|
||||
# Create a client for each server
|
||||
async with AsyncExitStack() as stack:
|
||||
yield [
|
||||
await stack.enter_async_context(server.get_async_client())
|
||||
for server, _ in servers
|
||||
]
|
||||
|
||||
|
||||
def _get_parallel_config(server: RemoteOpenAIServer):
|
||||
response = requests.get(server.url_for("server_info?config_format=json"))
|
||||
response.raise_for_status()
|
||||
|
||||
vllm_config = response.json()["vllm_config"]
|
||||
return vllm_config["parallel_config"]
|
||||
|
||||
|
||||
def _assert_expert_parallel_config(
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
):
|
||||
for server, server_args in servers:
|
||||
expected = "--enable-expert-parallel" in server_args
|
||||
parallel_config = _get_parallel_config(server)
|
||||
assert parallel_config["enable_expert_parallel"] is expected
|
||||
|
||||
|
||||
def _send_scale_command(
|
||||
server: RemoteOpenAIServer, new_dp_size: int
|
||||
) -> requests.Response:
|
||||
return requests.post(
|
||||
server.url_for("scale_elastic_ep"),
|
||||
json={"new_data_parallel_size": new_dp_size},
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_scale_requests_to_start(
|
||||
scale_requests: list[Future[requests.Response]],
|
||||
timeout: float = 30,
|
||||
) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
for request in scale_requests:
|
||||
if request.done():
|
||||
response = request.result()
|
||||
pytest.fail(
|
||||
"Scale request finished before the new rank was launched: "
|
||||
f"{response.status_code} {response.text}"
|
||||
)
|
||||
|
||||
if all(request.running() for request in scale_requests):
|
||||
return
|
||||
time.sleep(0.1)
|
||||
|
||||
pytest.fail("Timed out waiting for all scale requests to start")
|
||||
|
||||
|
||||
@pytest.mark.distributed(num_gpus=3)
|
||||
@pytest.mark.skipif(
|
||||
TP_SIZE != 1 or current_platform.device_count() < 3,
|
||||
reason="External Elastic EP scale-up requires three GPUs with TP_SIZE=1",
|
||||
)
|
||||
@pytest.mark.skipif(
|
||||
os.getenv("VLLM_USE_RUST_FRONTEND") == "1",
|
||||
reason="Elastic EP scaling is not supported by the Rust frontend",
|
||||
)
|
||||
def test_external_lb_elastic_ep_scale_up(default_server_args) -> None:
|
||||
server_args = [
|
||||
*default_server_args,
|
||||
"--enable-expert-parallel",
|
||||
"--all2all-backend",
|
||||
"allgather_reducescatter",
|
||||
"--attention-backend",
|
||||
"TRITON_MLA",
|
||||
"--enable-elastic-ep",
|
||||
"--elastic-ep-max-dp-size",
|
||||
"3",
|
||||
"--enable-eplb",
|
||||
"--eplb-config",
|
||||
'{"communicator":"pynccl","num_redundant_experts":0,"use_async":false}',
|
||||
]
|
||||
server_manager = ExternalLBServerManager(
|
||||
ELASTIC_EP_MODEL_NAME,
|
||||
dp_size=2,
|
||||
api_server_count=1,
|
||||
base_server_args=server_args,
|
||||
)
|
||||
|
||||
with server_manager:
|
||||
existing_servers = [server for server, _ in server_manager.servers]
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
scale_requests = [
|
||||
executor.submit(_send_scale_command, server, 3)
|
||||
for server in existing_servers
|
||||
]
|
||||
_wait_for_scale_requests_to_start(scale_requests)
|
||||
server_manager.start_rank(
|
||||
rank=2,
|
||||
dp_size=3,
|
||||
elastic_ep_scale_up_launch=True,
|
||||
)
|
||||
|
||||
for request in scale_requests:
|
||||
response = request.result(timeout=600)
|
||||
assert response.status_code == 200, response.text
|
||||
|
||||
for server, _ in server_manager.servers:
|
||||
parallel_config = _get_parallel_config(server)
|
||||
assert parallel_config["data_parallel_size"] == 3
|
||||
assert parallel_config["eplb_config"]["num_redundant_experts"] == 32
|
||||
with server.get_client() as client:
|
||||
completion = client.completions.create(
|
||||
model=ELASTIC_EP_MODEL_NAME,
|
||||
prompt="Hello, my name is",
|
||||
max_tokens=5,
|
||||
temperature=0.0,
|
||||
)
|
||||
assert completion.choices[0].finish_reason in ("length", "stop")
|
||||
|
||||
|
||||
def test_external_lb_server_info(server_manager):
|
||||
servers = server_manager.servers
|
||||
api_server_count = server_manager.api_server_count
|
||||
|
||||
for i, (server, _) in enumerate(servers):
|
||||
print(f"Testing {i=}")
|
||||
|
||||
# Each request will hit one of the API servers
|
||||
# `n_reqs` is set so that there is a good chance each server
|
||||
# receives at least one request
|
||||
n_reqs = 2 * api_server_count * api_server_count
|
||||
parallel_configs = [_get_parallel_config(server) for _ in range(n_reqs)]
|
||||
api_process_counts = [c["_api_process_count"] for c in parallel_configs]
|
||||
api_process_ranks = [c["_api_process_rank"] for c in parallel_configs]
|
||||
|
||||
assert all(c == api_server_count for c in api_process_counts), (
|
||||
api_process_counts
|
||||
)
|
||||
assert all(0 <= r < api_server_count for r in api_process_ranks), (
|
||||
api_process_ranks
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_external_lb_single_completion(
|
||||
clients: list[openai.AsyncOpenAI],
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
async def make_request(client: openai.AsyncOpenAI):
|
||||
completion = await client.completions.create(
|
||||
model=model_name, prompt="Hello, my name is", max_tokens=10, temperature=1.0
|
||||
)
|
||||
|
||||
assert completion.id is not None
|
||||
assert completion.choices is not None and len(completion.choices) == 1
|
||||
|
||||
choice = completion.choices[0]
|
||||
# The exact number of tokens can vary slightly with temperature=1.0,
|
||||
# so we check for a reasonable minimum length.
|
||||
assert len(choice.text) >= 1
|
||||
# Finish reason might not always be 'length' if the model finishes early
|
||||
# or due to other reasons, especially with high temperature.
|
||||
# So, we'll accept 'length' or 'stop'.
|
||||
assert choice.finish_reason in ("length", "stop")
|
||||
|
||||
# Token counts can also vary, so we check they are positive.
|
||||
assert completion.usage.completion_tokens > 0
|
||||
assert completion.usage.prompt_tokens > 0
|
||||
assert completion.usage.total_tokens > 0
|
||||
return completion
|
||||
|
||||
# Test single request to each server
|
||||
for i, client in enumerate(clients):
|
||||
result = await make_request(client)
|
||||
assert result is not None
|
||||
print(f"Server {i} handled single completion request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send requests to all servers in round-robin fashion
|
||||
num_requests_per_server = 25 # Total 50 requests across 2 servers
|
||||
all_tasks = []
|
||||
|
||||
for i, client in enumerate(clients):
|
||||
tasks = [make_request(client) for _ in range(num_requests_per_server)]
|
||||
all_tasks.extend(tasks)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests_per_server * len(clients)
|
||||
assert all(completion is not None for completion in results)
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of requests
|
||||
all_tasks = []
|
||||
for i, client in enumerate(clients):
|
||||
tasks = [make_request(client) for _ in range(num_requests_per_server)]
|
||||
all_tasks.extend(tasks)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests_per_server * len(clients)
|
||||
assert all(completion is not None for completion in results)
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed external LB test with {len(clients)} servers "
|
||||
f"(API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_external_lb_completion_streaming(
|
||||
clients: list[openai.AsyncOpenAI],
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
prompt = "What is an LLM?"
|
||||
|
||||
async def make_streaming_request(client: openai.AsyncOpenAI):
|
||||
# Perform a non-streaming request to get the expected full output
|
||||
single_completion = await client.completions.create(
|
||||
model=model_name,
|
||||
prompt=prompt,
|
||||
max_tokens=5,
|
||||
temperature=0.0,
|
||||
)
|
||||
single_output = single_completion.choices[0].text
|
||||
|
||||
# Perform the streaming request
|
||||
stream = await client.completions.create(
|
||||
model=model_name, prompt=prompt, max_tokens=5, temperature=0.0, stream=True
|
||||
)
|
||||
chunks: list[str] = []
|
||||
finish_reason_count = 0
|
||||
last_chunk = None
|
||||
async for chunk in stream:
|
||||
chunks.append(chunk.choices[0].text)
|
||||
if chunk.choices[0].finish_reason is not None:
|
||||
finish_reason_count += 1
|
||||
last_chunk = chunk # Keep track of the last chunk
|
||||
|
||||
# finish reason should only return in the last block for OpenAI API
|
||||
assert finish_reason_count == 1, "Finish reason should appear exactly once."
|
||||
assert last_chunk is not None, "Stream should have yielded at least one chunk."
|
||||
assert last_chunk.choices[0].finish_reason == "length", (
|
||||
"Finish reason should be 'length'."
|
||||
)
|
||||
# Check that the combined text matches the non-streamed version.
|
||||
assert "".join(chunks) == single_output, (
|
||||
"Streamed output should match non-streamed output."
|
||||
)
|
||||
return True # Indicate success for this request
|
||||
|
||||
# Test single request to each server
|
||||
for i, client in enumerate(clients):
|
||||
result = await make_streaming_request(client)
|
||||
assert result is not None
|
||||
print(f"Server {i} handled single streaming request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send streaming requests to all servers in round-robin fashion
|
||||
num_requests_per_server = 25 # Total 50 requests across 2 servers
|
||||
all_tasks = []
|
||||
|
||||
for i, client in enumerate(clients):
|
||||
tasks = [make_streaming_request(client) for _ in range(num_requests_per_server)]
|
||||
all_tasks.extend(tasks)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests_per_server * len(clients)
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of streaming requests
|
||||
all_tasks = []
|
||||
for i, client in enumerate(clients):
|
||||
tasks = [make_streaming_request(client) for _ in range(num_requests_per_server)]
|
||||
all_tasks.extend(tasks)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests_per_server * len(clients)
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed external LB streaming test with "
|
||||
f"{len(clients)} servers (API server count: {api_server_count})"
|
||||
)
|
||||
@@ -1,399 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from contextlib import AsyncExitStack
|
||||
|
||||
import openai # use the official client for correctness check
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from tests.v1.utils import check_request_balancing
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL_NAME = "ibm-research/PowerMoE-3b"
|
||||
|
||||
# Number of data parallel ranks for hybrid LB testing (4 total)
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", "4"))
|
||||
# Default tensor parallel size to use
|
||||
TP_SIZE = int(os.getenv("TP_SIZE", "1"))
|
||||
|
||||
# Number of nodes (2 nodes, each with 2 DP ranks)
|
||||
NUM_NODES = 2
|
||||
DP_SIZE_LOCAL = DP_SIZE // NUM_NODES # 2 ranks per node
|
||||
|
||||
|
||||
class HybridLBServerManager:
|
||||
"""Manages hybrid data parallel vLLM server instances where each node
|
||||
runs a single logical API server that balances requests only to the
|
||||
DP engines running on that same node."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
dp_size: int,
|
||||
api_server_count: int,
|
||||
base_server_args: list,
|
||||
dp_size_local: int = DP_SIZE_LOCAL,
|
||||
tp_size: int = TP_SIZE,
|
||||
):
|
||||
self.model_name = model_name
|
||||
self.dp_size = dp_size
|
||||
self.dp_size_local = dp_size_local
|
||||
self.tp_size = tp_size
|
||||
self.api_server_count = api_server_count
|
||||
self.base_server_args = base_server_args
|
||||
self.servers: list[tuple[RemoteOpenAIServer, list[str]]] = []
|
||||
self.server_threads: list[threading.Thread] = []
|
||||
self.num_nodes = dp_size // dp_size_local
|
||||
|
||||
def __enter__(self) -> list[tuple[RemoteOpenAIServer, list[str]]]:
|
||||
"""Start all server instances for hybrid LB mode."""
|
||||
for node_id in range(self.num_nodes):
|
||||
# Create server args for this specific node
|
||||
server_args = self.base_server_args.copy()
|
||||
|
||||
# Calculate start rank for this node
|
||||
start_rank = node_id * self.dp_size_local
|
||||
|
||||
# Add hybrid LB specific arguments
|
||||
server_args.extend(
|
||||
[
|
||||
"--data-parallel-size",
|
||||
str(self.dp_size),
|
||||
"--data-parallel-size-local",
|
||||
str(self.dp_size_local),
|
||||
"--data-parallel-start-rank",
|
||||
str(start_rank),
|
||||
"--data-parallel-hybrid-lb", # Enable hybrid LB mode
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--port",
|
||||
str(8000 + node_id), # Different port for each node
|
||||
"--api-server-count",
|
||||
str(self.api_server_count),
|
||||
"--data-parallel-address",
|
||||
"127.0.0.1",
|
||||
"--data-parallel-rpc-port",
|
||||
"13345",
|
||||
]
|
||||
)
|
||||
|
||||
# Use a thread to start each server to allow parallel initialization
|
||||
def start_server(node: int, sargs: list[str]):
|
||||
try:
|
||||
# Calculate GPU devices for this node
|
||||
gpus_per_node = self.dp_size_local * self.tp_size
|
||||
gpu_start = node * gpus_per_node
|
||||
gpu_end = gpu_start + gpus_per_node
|
||||
|
||||
# Start the server
|
||||
server = RemoteOpenAIServer(
|
||||
self.model_name,
|
||||
sargs,
|
||||
auto_port=False,
|
||||
env_dict={
|
||||
"VLLM_SERVER_DEV_MODE": "1",
|
||||
current_platform.device_control_env_var: ",".join(
|
||||
str(current_platform.device_id_to_physical_device_id(i))
|
||||
for i in range(gpu_start, gpu_end)
|
||||
),
|
||||
},
|
||||
)
|
||||
server.__enter__()
|
||||
print(
|
||||
f"Hybrid LB node {node} started successfully with "
|
||||
f"{self.dp_size_local} local DP ranks and "
|
||||
f"{self.api_server_count} API servers"
|
||||
)
|
||||
self.servers.append((server, sargs))
|
||||
except Exception as e:
|
||||
print(f"Failed to start hybrid LB node {node}: {e}")
|
||||
raise
|
||||
|
||||
thread = threading.Thread(target=start_server, args=(node_id, server_args))
|
||||
thread.start()
|
||||
|
||||
self.server_threads.append(thread)
|
||||
|
||||
# Wait for all servers to start
|
||||
for thread in self.server_threads:
|
||||
thread.join()
|
||||
|
||||
# Give servers additional time to fully initialize and coordinate
|
||||
time.sleep(3)
|
||||
|
||||
if len(self.servers) != self.num_nodes:
|
||||
raise Exception("Servers failed to start")
|
||||
|
||||
return self.servers
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Stop all server instances."""
|
||||
servers = [s for s, _ in self.servers]
|
||||
self.servers.clear()
|
||||
try:
|
||||
RemoteOpenAIServer.shutdown_many(servers)
|
||||
except Exception as e:
|
||||
print(f"Error stopping servers: {e}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def default_server_args():
|
||||
return [
|
||||
# use half precision for speed and memory savings in CI environment
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"2048",
|
||||
"--max-num-seqs",
|
||||
"128",
|
||||
"--enforce-eager",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=[1, 4])
|
||||
def server_manager(request, default_server_args):
|
||||
api_server_count = request.param
|
||||
server_manager = HybridLBServerManager(
|
||||
MODEL_NAME,
|
||||
DP_SIZE,
|
||||
api_server_count,
|
||||
default_server_args,
|
||||
DP_SIZE_LOCAL,
|
||||
TP_SIZE,
|
||||
)
|
||||
|
||||
with server_manager:
|
||||
yield server_manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servers(server_manager):
|
||||
return server_manager.servers
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def clients(servers: list[tuple[RemoteOpenAIServer, list[str]]]):
|
||||
# Create a client for each node (each node has its own API endpoint)
|
||||
async with AsyncExitStack() as stack:
|
||||
yield [
|
||||
await stack.enter_async_context(server.get_async_client())
|
||||
for server, _ in servers
|
||||
]
|
||||
|
||||
|
||||
def _get_parallel_config(server: RemoteOpenAIServer):
|
||||
response = requests.get(server.url_for("server_info?config_format=json"))
|
||||
response.raise_for_status()
|
||||
|
||||
vllm_config = response.json()["vllm_config"]
|
||||
return vllm_config["parallel_config"]
|
||||
|
||||
|
||||
def test_hybrid_dp_server_info(server_manager):
|
||||
servers = server_manager.servers
|
||||
api_server_count = server_manager.api_server_count
|
||||
|
||||
for i, (server, _) in enumerate(servers):
|
||||
print(f"Testing {i=}")
|
||||
|
||||
# Each request will hit one of the API servers
|
||||
# `n_reqs` is set so that there is a good chance each server
|
||||
# receives at least one request
|
||||
n_reqs = 2 * api_server_count * api_server_count
|
||||
parallel_configs = [_get_parallel_config(server) for _ in range(n_reqs)]
|
||||
api_process_counts = [c["_api_process_count"] for c in parallel_configs]
|
||||
api_process_ranks = [c["_api_process_rank"] for c in parallel_configs]
|
||||
|
||||
assert all(c == api_server_count for c in api_process_counts), (
|
||||
api_process_counts
|
||||
)
|
||||
assert all(0 <= r < api_server_count for r in api_process_ranks), (
|
||||
api_process_ranks
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_hybrid_lb_completion(
|
||||
clients: list[openai.AsyncOpenAI],
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
async def make_request(client: openai.AsyncOpenAI):
|
||||
completion = await client.completions.create(
|
||||
model=model_name, prompt="Hello, my name is", max_tokens=5, temperature=1.0
|
||||
)
|
||||
|
||||
assert completion.id is not None
|
||||
assert completion.choices is not None and len(completion.choices) == 1
|
||||
|
||||
choice = completion.choices[0]
|
||||
# The exact number of tokens can vary slightly with temperature=1.0,
|
||||
# so we check for a reasonable minimum length.
|
||||
assert len(choice.text) >= 1
|
||||
# Finish reason might not always be 'length' if the model finishes early
|
||||
# or due to other reasons, especially with high temperature.
|
||||
# So, we'll accept 'length' or 'stop'.
|
||||
assert choice.finish_reason in ("length", "stop")
|
||||
|
||||
# Token counts can also vary, so we check they are positive.
|
||||
assert completion.usage.completion_tokens > 0
|
||||
assert completion.usage.prompt_tokens > 0
|
||||
assert completion.usage.total_tokens > 0
|
||||
return completion
|
||||
|
||||
# Test single request to each node
|
||||
for i, client in enumerate(clients):
|
||||
result = await make_request(client)
|
||||
assert result is not None
|
||||
print(f"Hybrid LB node {i} handled single completion request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send requests to all nodes - each should balance within its local DP ranks
|
||||
num_requests = 200 # Total 200 requests across 2 nodes
|
||||
all_tasks = []
|
||||
for i in range(num_requests):
|
||||
client = clients[i % len(clients)]
|
||||
all_tasks.append(asyncio.create_task(make_request(client)))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(completion is not None for completion in results)
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of requests
|
||||
all_tasks = []
|
||||
for i in range(num_requests):
|
||||
client = clients[i % len(clients)]
|
||||
all_tasks.append(asyncio.create_task(make_request(client)))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(completion is not None for completion in results)
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed hybrid LB test with {len(clients)} nodes "
|
||||
f"({DP_SIZE_LOCAL} DP ranks each, API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing within each node
|
||||
for i, (server, _) in enumerate(servers):
|
||||
print(f"Checking request balancing for node {i}")
|
||||
check_request_balancing(server, DP_SIZE_LOCAL)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_hybrid_lb_completion_streaming(
|
||||
clients: list[openai.AsyncOpenAI],
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
prompt = "What is an LLM?"
|
||||
|
||||
async def make_streaming_request(client: openai.AsyncOpenAI):
|
||||
# Perform a non-streaming request to get the expected full output
|
||||
single_completion = await client.completions.create(
|
||||
model=model_name,
|
||||
prompt=prompt,
|
||||
max_tokens=5,
|
||||
temperature=0.0,
|
||||
)
|
||||
single_output = single_completion.choices[0].text
|
||||
|
||||
# Perform the streaming request
|
||||
stream = await client.completions.create(
|
||||
model=model_name, prompt=prompt, max_tokens=5, temperature=0.0, stream=True
|
||||
)
|
||||
chunks: list[str] = []
|
||||
finish_reason_count = 0
|
||||
last_chunk = None
|
||||
async for chunk in stream:
|
||||
chunks.append(chunk.choices[0].text)
|
||||
if chunk.choices[0].finish_reason is not None:
|
||||
finish_reason_count += 1
|
||||
last_chunk = chunk # Keep track of the last chunk
|
||||
|
||||
# finish reason should only return in the last block for OpenAI API
|
||||
assert finish_reason_count == 1, "Finish reason should appear exactly once."
|
||||
assert last_chunk is not None, "Stream should have yielded at least one chunk."
|
||||
assert last_chunk.choices[0].finish_reason == "length", (
|
||||
"Finish reason should be 'length'."
|
||||
)
|
||||
# Check that the combined text matches the non-streamed version.
|
||||
assert "".join(chunks) == single_output, (
|
||||
"Streamed output should match non-streamed output."
|
||||
)
|
||||
return True # Indicate success for this request
|
||||
|
||||
# Test single request to each node
|
||||
for i, client in enumerate(clients):
|
||||
result = await make_streaming_request(client)
|
||||
assert result is not None
|
||||
print(f"Hybrid LB node {i} handled single streaming request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send streaming requests to all nodes
|
||||
num_requests = 200 # Total 200 requests across 2 nodes
|
||||
all_tasks = []
|
||||
for i in range(num_requests):
|
||||
client = clients[i % len(clients)]
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request(client)))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of streaming requests
|
||||
all_tasks = []
|
||||
for i in range(num_requests):
|
||||
client = clients[i % len(clients)]
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request(client)))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed hybrid LB streaming test with "
|
||||
f"{len(clients)} nodes ({DP_SIZE_LOCAL} DP ranks each, "
|
||||
f"API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing within each node
|
||||
for i, (server, _) in enumerate(servers):
|
||||
print(f"Checking streaming request balancing for node {i}")
|
||||
check_request_balancing(server, DP_SIZE_LOCAL)
|
||||
@@ -1,727 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from typing import cast
|
||||
|
||||
import openai # use the official client for correctness check
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from tests.v1.utils import check_request_balancing
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL_NAME = "ibm-research/PowerMoE-3b"
|
||||
|
||||
# Number of data parallel ranks for multi-node internal LB testing
|
||||
DP_SIZE = int(os.getenv("DP_SIZE", "2"))
|
||||
# Default tensor parallel size to use
|
||||
TP_SIZE = int(os.getenv("TP_SIZE", "1"))
|
||||
|
||||
# Number of nodes to simulate
|
||||
NUM_NODES = 2
|
||||
|
||||
|
||||
async def _make_completion_request(
|
||||
client: openai.AsyncOpenAI,
|
||||
model_name: str,
|
||||
) -> openai.types.Completion:
|
||||
"""Make a single completion request and validate the response.
|
||||
|
||||
Uses temperature=1.0 to ensure diverse outputs across concurrent
|
||||
requests for realistic load balancer testing.
|
||||
"""
|
||||
completion = await client.completions.create(
|
||||
model=model_name,
|
||||
prompt="Hello, my name is",
|
||||
max_tokens=5,
|
||||
temperature=1.0,
|
||||
)
|
||||
|
||||
assert completion.id is not None, (
|
||||
f"Expected non-None completion id. usage={completion.usage!r}"
|
||||
)
|
||||
assert completion.choices is not None and len(completion.choices) == 1, (
|
||||
f"Expected 1 choice, got "
|
||||
f"{len(completion.choices) if completion.choices else 'None'}"
|
||||
)
|
||||
|
||||
choice = completion.choices[0]
|
||||
# With temperature=1.0, the model may emit a stop token immediately,
|
||||
# producing empty text with finish_reason='stop'. This is valid
|
||||
# model behavior - the test's purpose is load balancing, not output
|
||||
# quality.
|
||||
assert choice.finish_reason in ("length", "stop"), (
|
||||
f"Expected finish_reason 'length' or 'stop', "
|
||||
f"got {choice.finish_reason!r}. text={choice.text!r}"
|
||||
)
|
||||
if choice.finish_reason == "length":
|
||||
assert len(choice.text) >= 1, (
|
||||
f"Expected non-empty text with finish_reason='length', got {choice.text!r}"
|
||||
)
|
||||
|
||||
assert completion.usage.prompt_tokens > 0, (
|
||||
f"Expected positive prompt_tokens, got {completion.usage.prompt_tokens}"
|
||||
)
|
||||
assert completion.usage.total_tokens > 0, (
|
||||
f"Expected positive total_tokens, got {completion.usage.total_tokens}"
|
||||
)
|
||||
return completion
|
||||
|
||||
|
||||
async def _run_request_bursts(
|
||||
client: openai.AsyncOpenAI,
|
||||
model_name: str,
|
||||
num_requests: int = 200,
|
||||
num_bursts: int = 2,
|
||||
):
|
||||
"""Send multiple bursts of completion requests and validate all succeed."""
|
||||
for burst in range(num_bursts):
|
||||
all_tasks = []
|
||||
for _ in range(num_requests):
|
||||
all_tasks.append(
|
||||
asyncio.create_task(_make_completion_request(client, model_name))
|
||||
)
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks, return_exceptions=True)
|
||||
assert len(results) == num_requests, (
|
||||
f"Burst {burst}: expected {num_requests} results, got {len(results)}"
|
||||
)
|
||||
|
||||
for result in results:
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
|
||||
assert all(completion is not None for completion in results), (
|
||||
f"Burst {burst}: some completions were None"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
|
||||
class MultinodeInternalLBServerManager:
|
||||
"""Manages multi-node data parallel vLLM server instances for internal
|
||||
load balancer testing using --headless mode."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
dp_size: int,
|
||||
api_server_count: int,
|
||||
base_server_args: list,
|
||||
dp_per_node: int = 1,
|
||||
tp_size: int = TP_SIZE,
|
||||
):
|
||||
self.model_name = model_name
|
||||
self.dp_size = dp_size
|
||||
self.dp_per_node = dp_per_node
|
||||
self.tp_size = tp_size
|
||||
self.api_server_count = api_server_count
|
||||
self.base_server_args = base_server_args
|
||||
self.servers: list[tuple[RemoteOpenAIServer, list[str]] | None] = [None] * (
|
||||
dp_size // dp_per_node
|
||||
)
|
||||
self.server_threads: list[threading.Thread] = []
|
||||
|
||||
def __enter__(self) -> list[tuple[RemoteOpenAIServer, list[str]]]:
|
||||
"""Start all server instances for multi-node internal LB mode."""
|
||||
for server_idx, rank in enumerate(range(0, self.dp_size, self.dp_per_node)):
|
||||
# Create server args for this specific rank
|
||||
server_args = self.base_server_args.copy()
|
||||
|
||||
if rank == 0:
|
||||
# Head node - runs API server and first DP rank
|
||||
server_args.extend(
|
||||
[
|
||||
"--data-parallel-size",
|
||||
str(self.dp_size),
|
||||
"--data-parallel-size-local",
|
||||
str(self.dp_per_node),
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--port",
|
||||
"8000", # Single endpoint for all requests
|
||||
"--api-server-count",
|
||||
str(self.api_server_count),
|
||||
"--data-parallel-address",
|
||||
"127.0.0.1",
|
||||
"--data-parallel-rpc-port",
|
||||
"13345",
|
||||
]
|
||||
)
|
||||
else:
|
||||
# Secondary nodes - run in headless mode
|
||||
server_args.extend(
|
||||
[
|
||||
"--headless",
|
||||
"--data-parallel-size",
|
||||
str(self.dp_size),
|
||||
"--data-parallel-size-local",
|
||||
str(self.dp_per_node),
|
||||
"--data-parallel-start-rank",
|
||||
str(rank),
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--data-parallel-address",
|
||||
"127.0.0.1",
|
||||
"--data-parallel-rpc-port",
|
||||
"13345",
|
||||
]
|
||||
)
|
||||
|
||||
# Use a thread to start each server to allow parallel initialization
|
||||
def start_server(sidx: int, r: int, sargs: list[str]):
|
||||
gpus_per_node = self.tp_size * self.dp_per_node
|
||||
try:
|
||||
# Start the server
|
||||
server = RemoteOpenAIServer(
|
||||
self.model_name,
|
||||
sargs,
|
||||
auto_port=False,
|
||||
max_wait_seconds=int(
|
||||
os.getenv("VLLM_ENGINE_READY_TIMEOUT_S", "480")
|
||||
),
|
||||
env_dict={
|
||||
"VLLM_SERVER_DEV_MODE": "1",
|
||||
current_platform.device_control_env_var: ",".join(
|
||||
str(current_platform.device_id_to_physical_device_id(i))
|
||||
for i in range(r, r + gpus_per_node)
|
||||
),
|
||||
},
|
||||
)
|
||||
server.__enter__()
|
||||
if r == 0:
|
||||
print(
|
||||
f"Head node (rank {r}) started successfully with "
|
||||
f"{self.api_server_count} API servers"
|
||||
)
|
||||
else:
|
||||
print(f"Headless node (rank {r}) started successfully")
|
||||
self.servers[sidx] = (server, sargs)
|
||||
except Exception as e:
|
||||
print(f"Failed to start server rank {r}: {e}")
|
||||
traceback.print_exc()
|
||||
raise
|
||||
|
||||
thread = threading.Thread(
|
||||
target=start_server, args=(server_idx, rank, server_args)
|
||||
)
|
||||
thread.start()
|
||||
|
||||
self.server_threads.append(thread)
|
||||
|
||||
# Wait for all servers to start
|
||||
for thread in self.server_threads:
|
||||
thread.join()
|
||||
|
||||
# Give servers additional time to fully initialize and coordinate
|
||||
time.sleep(3)
|
||||
|
||||
if not all(self.servers):
|
||||
raise Exception("Servers failed to start")
|
||||
|
||||
return cast(list[tuple[RemoteOpenAIServer, list[str]]], self.servers)
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Stop all server instances."""
|
||||
servers = [entry[0] for entry in self.servers if entry is not None]
|
||||
self.servers.clear()
|
||||
try:
|
||||
RemoteOpenAIServer.shutdown_many(servers)
|
||||
except Exception as e:
|
||||
print(f"Error stopping servers: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
class APIOnlyServerManager:
|
||||
"""Manages API-only server (Node 0) and headless engines server (Node 1)
|
||||
for testing separated API server and engine configuration."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str,
|
||||
dp_size: int,
|
||||
api_server_count: int,
|
||||
base_server_args: list,
|
||||
tp_size: int = TP_SIZE,
|
||||
):
|
||||
self.model_name = model_name
|
||||
self.dp_size = dp_size
|
||||
self.tp_size = tp_size
|
||||
self.api_server_count = api_server_count
|
||||
self.base_server_args = base_server_args
|
||||
self.servers: list[tuple[RemoteOpenAIServer, list[str]] | None] = [None] * 2
|
||||
self.server_threads: list[threading.Thread] = []
|
||||
|
||||
def __enter__(self) -> list[tuple[RemoteOpenAIServer, list[str]]]:
|
||||
"""Start API-only server and headless engines server."""
|
||||
# Start API-only server (Node 0) - no engines, only API server
|
||||
api_server_args = self.base_server_args.copy()
|
||||
api_server_args.extend(
|
||||
[
|
||||
"--data-parallel-size",
|
||||
str(self.dp_size),
|
||||
"--data-parallel-size-local",
|
||||
"0", # No engines on this node
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--port",
|
||||
"8000",
|
||||
"--api-server-count",
|
||||
str(self.api_server_count),
|
||||
"--data-parallel-address",
|
||||
"127.0.0.1",
|
||||
"--data-parallel-rpc-port",
|
||||
"13345",
|
||||
]
|
||||
)
|
||||
|
||||
# Start headless engines server (Node 1) - all engines, no API server
|
||||
engines_server_args = self.base_server_args.copy()
|
||||
engines_server_args.extend(
|
||||
[
|
||||
"--headless",
|
||||
"--data-parallel-size",
|
||||
str(self.dp_size),
|
||||
"--data-parallel-size-local",
|
||||
str(self.dp_size), # All engines on this node
|
||||
"--tensor-parallel-size",
|
||||
str(self.tp_size),
|
||||
"--data-parallel-address",
|
||||
"127.0.0.1",
|
||||
"--data-parallel-rpc-port",
|
||||
"13345",
|
||||
]
|
||||
)
|
||||
|
||||
# Use threads to start both servers in parallel
|
||||
def start_api_server():
|
||||
try:
|
||||
server = RemoteOpenAIServer(
|
||||
self.model_name,
|
||||
api_server_args,
|
||||
auto_port=False,
|
||||
env_dict={
|
||||
"VLLM_SERVER_DEV_MODE": "1",
|
||||
# No GPUs needed for API-only server
|
||||
},
|
||||
)
|
||||
server.__enter__()
|
||||
print(
|
||||
f"API-only server started successfully with "
|
||||
f"{self.api_server_count} API servers"
|
||||
)
|
||||
self.servers[0] = (server, api_server_args)
|
||||
except Exception as e:
|
||||
print(f"Failed to start API-only server: {e}")
|
||||
raise
|
||||
|
||||
def start_engines_server():
|
||||
try:
|
||||
server = RemoteOpenAIServer(
|
||||
self.model_name,
|
||||
engines_server_args,
|
||||
auto_port=False,
|
||||
env_dict={
|
||||
current_platform.device_control_env_var: ",".join(
|
||||
str(current_platform.device_id_to_physical_device_id(i))
|
||||
for i in range(self.dp_size * self.tp_size)
|
||||
),
|
||||
},
|
||||
)
|
||||
server.__enter__()
|
||||
print(
|
||||
f"Headless engines server started successfully with "
|
||||
f"{self.dp_size} engines"
|
||||
)
|
||||
self.servers[1] = (server, engines_server_args)
|
||||
except Exception as e:
|
||||
print(f"Failed to start headless engines server: {e}")
|
||||
raise
|
||||
|
||||
# Start API server first
|
||||
api_thread = threading.Thread(target=start_api_server)
|
||||
api_thread.start()
|
||||
self.server_threads.append(api_thread)
|
||||
|
||||
# Start engines server second
|
||||
engines_thread = threading.Thread(target=start_engines_server)
|
||||
engines_thread.start()
|
||||
self.server_threads.append(engines_thread)
|
||||
|
||||
# Wait for both servers to start
|
||||
for thread in self.server_threads:
|
||||
thread.join()
|
||||
|
||||
# Give servers additional time to fully initialize and coordinate
|
||||
time.sleep(3)
|
||||
|
||||
if not all(self.servers):
|
||||
raise Exception("Both servers failed to start")
|
||||
|
||||
return cast(list[tuple[RemoteOpenAIServer, list[str]]], self.servers)
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Stop both server instances."""
|
||||
servers = [entry[0] for entry in self.servers if entry is not None]
|
||||
self.servers.clear()
|
||||
try:
|
||||
RemoteOpenAIServer.shutdown_many(servers)
|
||||
except Exception as e:
|
||||
print(f"Error stopping servers: {e}")
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def default_server_args():
|
||||
return [
|
||||
# use half precision for speed and memory savings in CI environment
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"2048",
|
||||
"--max-num-seqs",
|
||||
"128",
|
||||
"--enforce-eager",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=[1, 4])
|
||||
def server_manager(request, default_server_args):
|
||||
api_server_count = request.param
|
||||
server_manager = MultinodeInternalLBServerManager(
|
||||
MODEL_NAME,
|
||||
DP_SIZE,
|
||||
api_server_count,
|
||||
default_server_args,
|
||||
DP_SIZE // NUM_NODES,
|
||||
TP_SIZE,
|
||||
)
|
||||
|
||||
with server_manager:
|
||||
yield server_manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def servers(server_manager):
|
||||
return server_manager.servers
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=[1, 4])
|
||||
def api_only_servers(request, default_server_args):
|
||||
"""Fixture for API-only server + headless engines configuration."""
|
||||
api_server_count = request.param
|
||||
with APIOnlyServerManager(
|
||||
MODEL_NAME, DP_SIZE, api_server_count, default_server_args, TP_SIZE
|
||||
) as server_list:
|
||||
yield server_list
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(servers: list[tuple[RemoteOpenAIServer, list[str]]]):
|
||||
# For internal LB, we only connect to the head node (rank 0)
|
||||
# which provides the single API endpoint
|
||||
head_server = servers[0][0]
|
||||
async with head_server.get_async_client() as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def api_only_client(api_only_servers: list[tuple[RemoteOpenAIServer, list[str]]]):
|
||||
"""Client fixture for API-only server configuration."""
|
||||
# Connect to the API-only server (first server in the list)
|
||||
api_server = api_only_servers[0][0]
|
||||
async with api_server.get_async_client() as client:
|
||||
yield client
|
||||
|
||||
|
||||
def _get_parallel_config(server: RemoteOpenAIServer):
|
||||
response = requests.get(server.url_for("server_info?config_format=json"))
|
||||
response.raise_for_status()
|
||||
|
||||
vllm_config = response.json()["vllm_config"]
|
||||
return vllm_config["parallel_config"]
|
||||
|
||||
|
||||
def test_multinode_dp_server_info(server_manager):
|
||||
head_server = server_manager.servers[0][0]
|
||||
api_server_count = server_manager.api_server_count
|
||||
|
||||
# Each request will hit one of the API servers
|
||||
# `n_reqs` is set so that there is a good chance each server
|
||||
# receives at least one request
|
||||
n_reqs = 2 * api_server_count * api_server_count
|
||||
parallel_configs = [_get_parallel_config(head_server) for _ in range(n_reqs)]
|
||||
api_process_counts = [c["_api_process_count"] for c in parallel_configs]
|
||||
api_process_ranks = [c["_api_process_rank"] for c in parallel_configs]
|
||||
|
||||
assert all(c == api_server_count for c in api_process_counts), api_process_counts
|
||||
assert all(0 <= r < api_server_count for r in api_process_ranks), api_process_ranks
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_multinode_dp_completion(
|
||||
client: openai.AsyncOpenAI,
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
# Test single request
|
||||
result = await _make_completion_request(client, model_name)
|
||||
assert result is not None
|
||||
print("Multi-node internal LB handled single completion request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send multiple bursts - internal LB should distribute across DP ranks
|
||||
await _run_request_bursts(client, model_name)
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed multi-node internal LB test with "
|
||||
f"{len(servers)} DP ranks (API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing via Prometheus metrics
|
||||
head_server = servers[0][0]
|
||||
check_request_balancing(head_server, DP_SIZE)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_multinode_dp_completion_streaming(
|
||||
client: openai.AsyncOpenAI,
|
||||
servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
prompt = "What is an LLM?"
|
||||
|
||||
async def make_streaming_request():
|
||||
# Perform a non-streaming request to get the expected full output
|
||||
single_completion = await client.completions.create(
|
||||
model=model_name,
|
||||
prompt=prompt,
|
||||
max_tokens=5,
|
||||
temperature=0.0,
|
||||
)
|
||||
single_output = single_completion.choices[0].text
|
||||
|
||||
# Perform the streaming request
|
||||
stream = await client.completions.create(
|
||||
model=model_name, prompt=prompt, max_tokens=5, temperature=0.0, stream=True
|
||||
)
|
||||
chunks: list[str] = []
|
||||
finish_reason_count = 0
|
||||
last_chunk = None
|
||||
async for chunk in stream:
|
||||
chunks.append(chunk.choices[0].text)
|
||||
if chunk.choices[0].finish_reason is not None:
|
||||
finish_reason_count += 1
|
||||
last_chunk = chunk # Keep track of the last chunk
|
||||
|
||||
# finish reason should only return in the last block for OpenAI API
|
||||
assert finish_reason_count == 1, "Finish reason should appear exactly once."
|
||||
assert last_chunk is not None, "Stream should have yielded at least one chunk."
|
||||
assert last_chunk.choices[0].finish_reason == "length", (
|
||||
"Finish reason should be 'length'."
|
||||
)
|
||||
# Check that the combined text matches the non-streamed version.
|
||||
assert "".join(chunks) == single_output, (
|
||||
"Streamed output should match non-streamed output."
|
||||
)
|
||||
return True # Indicate success for this request
|
||||
|
||||
# Test single streaming request
|
||||
result = await make_streaming_request()
|
||||
assert result is not None
|
||||
print("Multi-node internal LB handled single streaming request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send multiple streaming requests - internal LB should distribute across
|
||||
# DP ranks
|
||||
num_requests = 200
|
||||
all_tasks = []
|
||||
for _ in range(num_requests):
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request()))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of streaming requests
|
||||
all_tasks = []
|
||||
for _ in range(num_requests):
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request()))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
_, server_args = servers[0]
|
||||
api_server_count = (
|
||||
server_args.count("--api-server-count")
|
||||
and server_args[server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed multi-node internal LB streaming test with "
|
||||
f"{len(servers)} DP ranks (API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing via Prometheus metrics
|
||||
head_server = servers[0][0]
|
||||
check_request_balancing(head_server, DP_SIZE)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_api_only_multinode_dp_completion(
|
||||
api_only_client: openai.AsyncOpenAI,
|
||||
api_only_servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
"""Test API-only server with all engines on separate headless server."""
|
||||
# Test single request
|
||||
result = await _make_completion_request(api_only_client, model_name)
|
||||
assert result is not None
|
||||
print("API-only server handled single completion request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send multiple bursts - should be distributed across engines on
|
||||
# headless server
|
||||
await _run_request_bursts(api_only_client, model_name)
|
||||
|
||||
api_server, api_server_args = api_only_servers[0]
|
||||
api_server_count = (
|
||||
api_server_args.count("--api-server-count")
|
||||
and api_server_args[api_server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed API-only multi-node test with {DP_SIZE} "
|
||||
f"engines on headless server (API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing via Prometheus metrics
|
||||
check_request_balancing(api_server, DP_SIZE)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
[MODEL_NAME],
|
||||
)
|
||||
async def test_api_only_multinode_dp_completion_streaming(
|
||||
api_only_client: openai.AsyncOpenAI,
|
||||
api_only_servers: list[tuple[RemoteOpenAIServer, list[str]]],
|
||||
model_name: str,
|
||||
) -> None:
|
||||
"""Test API-only server streaming with all engines on separate
|
||||
headless server."""
|
||||
prompt = "What is an LLM?"
|
||||
|
||||
async def make_streaming_request():
|
||||
# Perform a non-streaming request to get the expected full output
|
||||
single_completion = await api_only_client.completions.create(
|
||||
model=model_name,
|
||||
prompt=prompt,
|
||||
max_tokens=5,
|
||||
temperature=0.0,
|
||||
)
|
||||
single_output = single_completion.choices[0].text
|
||||
|
||||
# Perform the streaming request
|
||||
stream = await api_only_client.completions.create(
|
||||
model=model_name, prompt=prompt, max_tokens=5, temperature=0.0, stream=True
|
||||
)
|
||||
chunks: list[str] = []
|
||||
finish_reason_count = 0
|
||||
last_chunk = None
|
||||
async for chunk in stream:
|
||||
chunks.append(chunk.choices[0].text)
|
||||
if chunk.choices[0].finish_reason is not None:
|
||||
finish_reason_count += 1
|
||||
last_chunk = chunk # Keep track of the last chunk
|
||||
|
||||
# finish reason should only return in the last block for OpenAI API
|
||||
assert finish_reason_count == 1, "Finish reason should appear exactly once."
|
||||
assert last_chunk is not None, "Stream should have yielded at least one chunk."
|
||||
assert last_chunk.choices[0].finish_reason == "length", (
|
||||
"Finish reason should be 'length'."
|
||||
)
|
||||
# Check that the combined text matches the non-streamed version.
|
||||
assert "".join(chunks) == single_output, (
|
||||
"Streamed output should match non-streamed output."
|
||||
)
|
||||
return True # Indicate success for this request
|
||||
|
||||
# Test single streaming request
|
||||
result = await make_streaming_request()
|
||||
assert result is not None
|
||||
print("API-only server handled single streaming request successfully")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Send multiple streaming requests - should be distributed across engines
|
||||
num_requests = 200
|
||||
all_tasks = []
|
||||
for _ in range(num_requests):
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request()))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second burst of streaming requests
|
||||
all_tasks = []
|
||||
for _ in range(num_requests):
|
||||
all_tasks.append(asyncio.create_task(make_streaming_request()))
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
results = await asyncio.gather(*all_tasks)
|
||||
assert len(results) == num_requests
|
||||
assert all(results), "Not all streaming requests completed successfully."
|
||||
|
||||
_, api_server_args = api_only_servers[0]
|
||||
api_server_count = (
|
||||
api_server_args.count("--api-server-count")
|
||||
and api_server_args[api_server_args.index("--api-server-count") + 1]
|
||||
or 1
|
||||
)
|
||||
print(
|
||||
f"Successfully completed API-only streaming test with {DP_SIZE} "
|
||||
f"engines on headless server (API server count: {api_server_count})"
|
||||
)
|
||||
|
||||
# Check request balancing via Prometheus metrics
|
||||
api_server = api_only_servers[0][0]
|
||||
check_request_balancing(api_server, DP_SIZE)
|
||||
@@ -1,176 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""V2 ModelRunner + pipeline parallel + data parallel integration tests.
|
||||
|
||||
Covers the interaction between the V2 model runner's PP sampled-token
|
||||
broadcast and the DP per-step all-reduce across a few concurrency
|
||||
regimes. Requires 4 GPUs (DP=2, PP=2, TP=1) on CUDA.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import os
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
|
||||
PP_DP_MODEL = "ibm-research/PowerMoE-3b" # smallest cached MoE that supports PP
|
||||
PROMPT = "This is a test of data parallel and pipeline parallel together"
|
||||
|
||||
|
||||
def _gpu_skip_reason() -> str | None:
|
||||
if not current_platform.is_cuda():
|
||||
return "requires CUDA"
|
||||
n = current_platform.device_count()
|
||||
if n < 4:
|
||||
return f"requires 4 GPUs, got {n}"
|
||||
return None
|
||||
|
||||
|
||||
_GPU_SKIP = _gpu_skip_reason()
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(
|
||||
os.environ.get("VLLM_USE_V2_MODEL_RUNNER", "1") == "0",
|
||||
reason="V2 model runner disabled via VLLM_USE_V2_MODEL_RUNNER=0",
|
||||
),
|
||||
pytest.mark.skipif(_GPU_SKIP is not None, reason=_GPU_SKIP or ""),
|
||||
]
|
||||
|
||||
|
||||
def _engine_args(async_scheduling: bool) -> AsyncEngineArgs:
|
||||
return AsyncEngineArgs(
|
||||
model=PP_DP_MODEL,
|
||||
pipeline_parallel_size=2,
|
||||
data_parallel_size=2,
|
||||
data_parallel_backend="mp",
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=4096,
|
||||
max_num_batched_tokens=2048,
|
||||
max_num_seqs=256,
|
||||
async_scheduling=async_scheduling,
|
||||
enable_prefix_caching=False,
|
||||
enforce_eager=False,
|
||||
enable_expert_parallel=False,
|
||||
)
|
||||
|
||||
|
||||
async def _generate(engine: AsyncLLM, prompt: str, max_tokens: int) -> int:
|
||||
"""Run one streaming completion and return the number of tokens it yielded."""
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.DELTA,
|
||||
temperature=0.0,
|
||||
)
|
||||
request_id = f"req-{id(prompt):x}-{max_tokens}"
|
||||
total = 0
|
||||
async for out in engine.generate(
|
||||
request_id=request_id, prompt=prompt, sampling_params=sampling_params
|
||||
):
|
||||
total += len(out.outputs[0].token_ids)
|
||||
return total
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_scheduling", [True, False])
|
||||
async def test_pp_dp_v2_low_concurrency(async_scheduling: bool):
|
||||
"""A single in-flight request at a time, repeated, to exercise the
|
||||
PP slot ring under empty batches between decodes."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_engine_args(async_scheduling))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
for _ in range(4):
|
||||
n = await _generate(engine, PROMPT, max_tokens=16)
|
||||
assert n == 16
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_scheduling", [True, False])
|
||||
async def test_pp_dp_v2_mid_concurrency(async_scheduling: bool):
|
||||
"""64 concurrent requests, staggered, to exercise the steady-state
|
||||
DP all-reduce + PP slot-ring path."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_engine_args(async_scheduling))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
async def _one(i: int) -> int:
|
||||
await asyncio.sleep(0.01 * i) # stagger so DP load-balances
|
||||
return await _generate(engine, f"{PROMPT} {i}", max_tokens=64)
|
||||
|
||||
results = await asyncio.gather(*[_one(i) for i in range(64)])
|
||||
assert all(n == 64 for n in results), results
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pp_dp_v2_abort_mid_decode():
|
||||
"""Cancel half the in-flight requests mid-stream and confirm the
|
||||
engine survives the abort storm."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_engine_args(async_scheduling=True))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
async def _maybe_cancel(i: int):
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=64,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.DELTA,
|
||||
temperature=0.0,
|
||||
)
|
||||
request_id = f"abort-req-{i}"
|
||||
count = 0
|
||||
cancel_at = 4 if i % 2 == 0 else 64
|
||||
async for out in engine.generate(
|
||||
request_id=request_id,
|
||||
prompt=f"{PROMPT} {i}",
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
count += len(out.outputs[0].token_ids)
|
||||
if count >= cancel_at:
|
||||
break
|
||||
return count, i
|
||||
|
||||
results = await asyncio.gather(*[_maybe_cancel(i) for i in range(32)])
|
||||
for count, i in results:
|
||||
if i % 2 == 0:
|
||||
assert count >= 4
|
||||
else:
|
||||
assert count == 64
|
||||
|
||||
# Engine must still serve after the abort storm.
|
||||
final = await _generate(engine, "post-abort warmup", max_tokens=8)
|
||||
assert final == 8
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pp_dp_v2_pause_resume():
|
||||
"""Pause an engine with a request in flight, then resume and confirm
|
||||
new requests still work."""
|
||||
with ExitStack() as after:
|
||||
engine = AsyncLLM.from_engine_args(_engine_args(async_scheduling=True))
|
||||
after.callback(engine.shutdown)
|
||||
|
||||
# Start a long-running generation, let some decoding happen, then
|
||||
# pause (abort mode) and confirm the in-flight task terminates.
|
||||
inflight = asyncio.create_task(_generate(engine, PROMPT, max_tokens=128))
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
assert not await engine.is_paused()
|
||||
await engine.pause_generation(mode="abort")
|
||||
assert await engine.is_paused()
|
||||
|
||||
with contextlib.suppress(Exception):
|
||||
await inflight
|
||||
|
||||
await engine.resume_generation()
|
||||
assert not await engine.is_paused()
|
||||
|
||||
n = await _generate(engine, PROMPT, max_tokens=8)
|
||||
assert n == 8
|
||||
@@ -1,494 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Numerical checks against an independent, teacher-forced target model."""
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
|
||||
import torch
|
||||
import xgrammar as xgr
|
||||
from tokenizers.decoders import DecodeStream
|
||||
|
||||
from tests.conftest import HfRunner
|
||||
from vllm import SamplingParams
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
|
||||
from vllm.v1.engine.logprobs import LogprobsProcessor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccuracyTolerance:
|
||||
logprob_atol: float
|
||||
greedy_atol: float
|
||||
logprob_mean_atol: float = 0.1
|
||||
greedy_total_atol: float = 0.5
|
||||
|
||||
def logprob_error(self, reference: torch.Tensor) -> torch.Tensor:
|
||||
return torch.full_like(reference, self.logprob_atol)
|
||||
|
||||
|
||||
def check_first_divergence(
|
||||
baseline: RequestOutput,
|
||||
actual: RequestOutput,
|
||||
params: SamplingParams,
|
||||
tolerance: AccuracyTolerance,
|
||||
context: str,
|
||||
) -> None:
|
||||
"""Require the two engines' scores to justify their first different choice."""
|
||||
assert baseline.finished and actual.finished, context
|
||||
assert len(baseline.outputs) == len(actual.outputs) == 1, context
|
||||
assert baseline.prompt_token_ids is not None, context
|
||||
assert baseline.prompt_token_ids == actual.prompt_token_ids, context
|
||||
base, other = baseline.outputs[0], actual.outputs[0]
|
||||
position = next(
|
||||
(i for i, (a, b) in enumerate(zip(base.token_ids, other.token_ids)) if a != b),
|
||||
None,
|
||||
)
|
||||
if position is None:
|
||||
assert len(base.token_ids) == len(other.token_ids), (
|
||||
f"{context}: one completion is a strict prefix of the other"
|
||||
)
|
||||
assert (base.finish_reason, base.stop_reason) == (
|
||||
other.finish_reason,
|
||||
other.stop_reason,
|
||||
), f"{context}: identical tokens have different stopping reasons"
|
||||
return
|
||||
|
||||
assert params.logprobs is not None and params.logprobs > 0, context
|
||||
assert params.temperature == 0.0, context
|
||||
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
|
||||
assert not params.logit_bias, context
|
||||
a, b = base.token_ids[position], other.token_ids[position]
|
||||
counts = Counter(base.token_ids[:position])
|
||||
context = (
|
||||
f"{context}, first divergence position={position}, "
|
||||
f"baseline token={a}, actual token={b}"
|
||||
)
|
||||
for side, completion, selected, alternative in (
|
||||
("baseline", base, a, b),
|
||||
("actual", other, b, a),
|
||||
):
|
||||
assert completion.logprobs is not None, context
|
||||
assert len(completion.logprobs) == len(completion.token_ids), context
|
||||
scores = completion.logprobs[position]
|
||||
assert selected in scores, f"{context}, {side}: missing selected token score"
|
||||
chosen = scores[selected].logprob
|
||||
assert math.isfinite(chosen), f"{context}, {side}: non-finite selected score"
|
||||
known = alternative in scores
|
||||
if known:
|
||||
competing = scores[alternative].logprob
|
||||
assert math.isfinite(competing), (
|
||||
f"{context}, {side}: divergent token has a non-finite score"
|
||||
)
|
||||
else:
|
||||
# The sampled token may be returned in addition to the requested
|
||||
# top-k. An omitted token's raw score is bounded by the kth score.
|
||||
top_scores = [
|
||||
score.logprob
|
||||
for token, score in scores.items()
|
||||
if len(scores) == params.logprobs or token != selected
|
||||
]
|
||||
assert len(top_scores) == params.logprobs, context
|
||||
assert not any(math.isnan(score) for score in top_scores), context
|
||||
competing = min(top_scores)
|
||||
|
||||
# Both candidates were emitted with the same history and constraints;
|
||||
# frequency penalties are the only supported transform changing their
|
||||
# finite score difference. Prompt tokens do not contribute to counts.
|
||||
chosen -= params.frequency_penalty * counts[selected]
|
||||
competing -= params.frequency_penalty * counts[alternative]
|
||||
gap = chosen - competing
|
||||
detail = (
|
||||
f"{context}, {side}: selected={selected}, alternative={alternative}, "
|
||||
f"{'gap' if known else 'gap lower bound'}={gap}"
|
||||
)
|
||||
if known:
|
||||
# Log-softmax and reconstructing penalties may round in FP32, but
|
||||
# a near tie cannot excuse selecting the engine's own worse token.
|
||||
assert gap >= -1e-5, f"{detail}: selected token is below its alternative"
|
||||
# Same FP32 rounding slack as above, applied to the upper bound.
|
||||
assert gap <= tolerance.greedy_atol + 1e-5, (
|
||||
f"{detail}: divergence exceeds near-tie bound="
|
||||
f"{tolerance.greedy_atol} (+1e-5 slack)"
|
||||
)
|
||||
|
||||
|
||||
def check_logprobs(
|
||||
scores: dict[int, Logprob],
|
||||
reference: torch.Tensor,
|
||||
token: int,
|
||||
requested: int,
|
||||
tolerance: AccuracyTolerance,
|
||||
context: str,
|
||||
) -> torch.Tensor:
|
||||
"""Check every score, reported rank, and the complete requested top-k."""
|
||||
assert all(0 <= token_id < reference.numel() for token_id in scores), context
|
||||
assert token in scores, f"{context}: missing score for token {token}"
|
||||
assert max(1, requested) <= len(scores) <= requested + 1, context
|
||||
assert not torch.isnan(reference).any(), context
|
||||
assert all(s.rank is not None and s.rank >= 1 for s in scores.values()), context
|
||||
ids = torch.tensor(list(scores), device=reference.device)
|
||||
actual = torch.tensor(
|
||||
[score.logprob for score in scores.values()], device=reference.device
|
||||
)
|
||||
expected = reference[ids]
|
||||
finite = torch.isfinite(expected)
|
||||
assert torch.equal(torch.isfinite(actual), finite), (
|
||||
f"{context}: finite/masked logprobs differ: {scores}"
|
||||
)
|
||||
assert torch.equal(actual[~finite], expected[~finite]), context
|
||||
assert (actual[finite] <= 0).all(), f"{context}: positive log probability"
|
||||
errors = (actual[finite] - expected[finite]).abs()
|
||||
bounds = tolerance.logprob_error(expected[finite])
|
||||
assert (errors <= bounds).all(), (
|
||||
f"{context}: token IDs={ids[finite].tolist()}, "
|
||||
f"actual={actual[finite].tolist()}, reference={expected[finite].tolist()}, "
|
||||
f"error={errors.tolist()}, bound={bounds.tolist()}"
|
||||
)
|
||||
|
||||
for token_id, score in scores.items():
|
||||
value = reference[token_id]
|
||||
if not torch.isfinite(value):
|
||||
continue
|
||||
delta = tolerance.logprob_error(value)
|
||||
lower = 1 + int((reference > value + 2 * delta).sum())
|
||||
upper = max(1, int((reference >= value - 2 * delta).sum()))
|
||||
assert score.rank is not None and lower <= score.rank <= upper, (
|
||||
f"{context}: token={token_id}, rank={score.rank}, "
|
||||
f"reference rank interval=[{lower}, {upper}]"
|
||||
)
|
||||
|
||||
if requested:
|
||||
# The sampled token can be outside top-k even when it ties the kth
|
||||
# score. Its strict-greater rank can therefore duplicate a top-k rank.
|
||||
top_ids = (
|
||||
list(scores)
|
||||
if len(scores) == requested
|
||||
else [t for t in scores if t != token]
|
||||
)
|
||||
assert len(top_ids) == requested, f"{context}: incomplete top-k"
|
||||
assert {scores[t].rank for t in top_ids} == set(range(1, requested + 1)), (
|
||||
context
|
||||
)
|
||||
ordered = sorted(top_ids, key=lambda t: scores[t].rank)
|
||||
assert all(
|
||||
scores[a].logprob >= scores[b].logprob for a, b in zip(ordered, ordered[1:])
|
||||
), f"{context}: top-k scores disagree with their reported ranks"
|
||||
boundary = reference.topk(requested).values[-1]
|
||||
if torch.isfinite(boundary):
|
||||
delta = tolerance.logprob_error(boundary)
|
||||
required = (reference > boundary + 2 * delta).nonzero().flatten()
|
||||
assert set(required.tolist()) <= scores.keys(), (
|
||||
f"{context}: missing an unambiguously top-{requested} token"
|
||||
)
|
||||
assert (reference[top_ids] >= boundary - 2 * delta).all(), (
|
||||
f"{context}: returned token below the top-{requested} boundary"
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def check_greedy_token(
|
||||
logits: torch.Tensor,
|
||||
token: int,
|
||||
tolerance: AccuracyTolerance,
|
||||
context: str,
|
||||
) -> float:
|
||||
assert not torch.isnan(logits).any(), context
|
||||
assert torch.isfinite(logits[token]), (
|
||||
f"{context}: selected token {token} is forbidden by the sampling parameters"
|
||||
)
|
||||
best = int(logits.argmax())
|
||||
gap = float(logits[best] - logits[token])
|
||||
# FP32 rounding can push a true near-tie fractionally past the bound.
|
||||
assert gap <= tolerance.greedy_atol + 1e-5, (
|
||||
f"{context}: selected token={token}, reference best={best}, "
|
||||
f"logit gap={gap}, bound={tolerance.greedy_atol} (+1e-5 slack)"
|
||||
)
|
||||
return gap
|
||||
|
||||
|
||||
def check_accuracy_budget(errors, gaps, tolerance, context):
|
||||
"""Reject systematic sub-bound errors within each request and score stream."""
|
||||
if errors:
|
||||
finite_errors = torch.cat(errors)
|
||||
if finite_errors.numel():
|
||||
mean_error = float(finite_errors.mean())
|
||||
assert mean_error <= tolerance.logprob_mean_atol, (
|
||||
f"{context}: mean logprob error={mean_error}, "
|
||||
f"bound={tolerance.logprob_mean_atol}"
|
||||
)
|
||||
assert sum(gaps) <= tolerance.greedy_total_atol, (
|
||||
f"{context}: total greedy logit gap={sum(gaps)}, "
|
||||
f"bound={tolerance.greedy_total_atol}"
|
||||
)
|
||||
|
||||
|
||||
def _check_decoded_tokens(processor, scores, history, context):
|
||||
ids = list(scores)
|
||||
decoded = convert_ids_list_to_tokens(processor.tokenizer, ids)
|
||||
decoded = processor._verify_tokens(decoded, ids, context_token_ids=history[-4:])
|
||||
for token, text in zip(ids, decoded, strict=True):
|
||||
assert scores[token].decoded_token == text, (
|
||||
f"{context}: incorrect decoded text for token {token}"
|
||||
)
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def check_request_accuracy(
|
||||
hf: HfRunner,
|
||||
request: RequestOutput,
|
||||
params: SamplingParams,
|
||||
tolerance: AccuracyTolerance,
|
||||
context: str,
|
||||
) -> None:
|
||||
"""Score the actual continuation, including positions after any divergence."""
|
||||
assert request.finished and len(request.outputs) == 1, context
|
||||
(completion,) = request.outputs
|
||||
prompt = request.prompt_token_ids
|
||||
assert prompt is not None and len(prompt) > 0, context
|
||||
tokens = list(completion.token_ids)
|
||||
assert params.max_tokens is not None and 0 < len(tokens) <= params.max_tokens, (
|
||||
context
|
||||
)
|
||||
# Incremental decoding buffers incomplete UTF-8; decoding the final token
|
||||
# list in one call can incorrectly append a replacement character.
|
||||
stream = DecodeStream(skip_special_tokens=params.skip_special_tokens)
|
||||
tokenizer = hf.tokenizer.backend_tokenizer
|
||||
for token in prompt:
|
||||
stream.step(tokenizer, token)
|
||||
visible = tokens
|
||||
if completion.finish_reason == "stop" and not params.include_stop_str_in_output:
|
||||
visible = tokens[:-1]
|
||||
expected_text = "".join(stream.step(tokenizer, token) or "" for token in visible)
|
||||
assert completion.text == expected_text, (
|
||||
f"{context}: decoded text does not match generated token IDs"
|
||||
)
|
||||
inputs = torch.tensor([prompt + tokens], device=hf.device)
|
||||
logits = hf.model(input_ids=inputs, use_cache=False).logits[0].float()
|
||||
# Use the existing byte-fallback handling with an independent request
|
||||
# history; numerical scores always come from the HF model above.
|
||||
decoder = LogprobsProcessor(
|
||||
tokenizer=hf.tokenizer,
|
||||
logprobs=None,
|
||||
prompt_logprobs=None,
|
||||
cumulative_logprob=None,
|
||||
num_logprobs=None,
|
||||
num_prompt_logprobs=None,
|
||||
)
|
||||
# Prompt token i is predicted by the causal logits at position i - 1.
|
||||
if params.prompt_logprobs is None:
|
||||
assert request.prompt_logprobs is None, context
|
||||
else:
|
||||
assert request.prompt_logprobs is not None, context
|
||||
assert len(request.prompt_logprobs) == len(prompt), context
|
||||
assert request.prompt_logprobs[0] is None, context
|
||||
errors = []
|
||||
for i, scores in enumerate(request.prompt_logprobs[1:], 1):
|
||||
assert scores is not None, context
|
||||
_check_decoded_tokens(decoder, scores, prompt[1:i], context)
|
||||
errors.append(
|
||||
check_logprobs(
|
||||
scores,
|
||||
logits[i - 1].log_softmax(-1),
|
||||
prompt[i],
|
||||
params.prompt_logprobs,
|
||||
tolerance,
|
||||
f"{context}, prompt position={i}",
|
||||
)
|
||||
)
|
||||
check_accuracy_budget(errors, [], tolerance, f"{context}, prompt logprobs")
|
||||
|
||||
if params.logprobs is None:
|
||||
assert completion.logprobs is None, context
|
||||
else:
|
||||
assert completion.logprobs is not None, context
|
||||
assert len(completion.logprobs) == len(tokens), context
|
||||
|
||||
reference = SamplingReference(
|
||||
hf.tokenizer,
|
||||
logits.shape[-1],
|
||||
hf.model.generation_config.to_dict(),
|
||||
params,
|
||||
)
|
||||
errors = []
|
||||
gaps = []
|
||||
for i, token in enumerate(tokens):
|
||||
raw, processed = reference.distributions(
|
||||
logits[len(prompt) + i - 1], tokens[:i]
|
||||
)
|
||||
position = f"{context}, generated position={i}"
|
||||
gaps.append(check_greedy_token(processed, token, tolerance, position))
|
||||
if completion.logprobs is not None:
|
||||
_check_decoded_tokens(decoder, completion.logprobs[i], tokens[:i], position)
|
||||
errors.append(
|
||||
check_logprobs(
|
||||
completion.logprobs[i],
|
||||
raw.log_softmax(-1),
|
||||
token,
|
||||
params.logprobs,
|
||||
tolerance,
|
||||
position,
|
||||
)
|
||||
)
|
||||
check_accuracy_budget(errors, gaps, tolerance, f"{context}, completion")
|
||||
# Advance the grammar through the last token too; an incomplete JSON prefix
|
||||
# is allowed at max_tokens, but every emitted token must remain valid.
|
||||
reference.accept_history(tokens)
|
||||
check_stopping(
|
||||
tokens,
|
||||
completion.finish_reason,
|
||||
reference.stop_ids,
|
||||
params,
|
||||
context,
|
||||
eos_token_id=hf.tokenizer.eos_token_id,
|
||||
stop_reason=completion.stop_reason,
|
||||
)
|
||||
|
||||
|
||||
def check_stopping(
|
||||
tokens,
|
||||
finish_reason,
|
||||
stop_ids,
|
||||
params,
|
||||
context,
|
||||
*,
|
||||
eos_token_id: int | None,
|
||||
stop_reason: int | str | None,
|
||||
):
|
||||
assert not params.ignore_eos and not params.stop, context
|
||||
assert not stop_ids.intersection(tokens[:-1]), (
|
||||
f"{context}: generation continued after a stop token"
|
||||
)
|
||||
if tokens[-1] in stop_ids:
|
||||
assert finish_reason == "stop", (
|
||||
f"{context}: stop token did not terminate output"
|
||||
)
|
||||
expected_stop_reason = None if tokens[-1] == eos_token_id else tokens[-1]
|
||||
assert stop_reason == expected_stop_reason, (
|
||||
f"{context}: stop reason={stop_reason}, expected={expected_stop_reason}"
|
||||
)
|
||||
else:
|
||||
assert finish_reason == "length" and len(tokens) == params.max_tokens, context
|
||||
assert stop_reason is None, f"{context}: length cap has a stop reason"
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _compiler(tokenizer, vocab_size: int):
|
||||
info = xgr.TokenizerInfo.from_huggingface(tokenizer, vocab_size=vocab_size)
|
||||
return xgr.GrammarCompiler(info, max_threads=1, cache_enabled=True)
|
||||
|
||||
|
||||
class SamplingReference:
|
||||
"""One request's reference; histories must grow without changing their prefix."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer,
|
||||
vocab_size: int,
|
||||
generation_config: dict,
|
||||
params: "SamplingParams",
|
||||
):
|
||||
assert params.temperature == 0.0, "Only the original greedy matrix is supported"
|
||||
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
|
||||
assert params.allowed_token_ids is None and not params.logit_bias
|
||||
self.vocab_size = vocab_size
|
||||
self.min_tokens = params.min_tokens
|
||||
self.frequency_penalty = params.frequency_penalty
|
||||
self.stop_ids = set(params.stop_token_ids or [])
|
||||
for eos in (tokenizer.eos_token_id, generation_config.get("eos_token_id")):
|
||||
if eos is not None:
|
||||
self.stop_ids.update([eos] if isinstance(eos, int) else eos)
|
||||
assert all(0 <= token < vocab_size for token in self.stop_ids)
|
||||
|
||||
# Match public bad-word tokenization semantics without using sampler code.
|
||||
self.bad_words: list[list[int]] = []
|
||||
for word in params.bad_words or []:
|
||||
plain = tokenizer.encode(word.lstrip(), add_special_tokens=False)
|
||||
spaced = tokenizer.encode(" " + word.lstrip(), add_special_tokens=False)
|
||||
assert plain, f"Empty bad-word tokenization: {word!r}"
|
||||
self.bad_words.append(plain)
|
||||
if spaced and len(spaced) == len(plain) and spaced[0] != plain[0]:
|
||||
self.bad_words.append(spaced)
|
||||
|
||||
self.history: list[int] = []
|
||||
self.matcher = None
|
||||
self.bitmask = None
|
||||
if params.structured_outputs is not None:
|
||||
schema = params.structured_outputs.json
|
||||
assert schema is not None, "Only the original JSON schema is supported"
|
||||
# Preserve dictionary order: xgrammar's default grammar orders fields.
|
||||
schema = schema if isinstance(schema, str) else json.dumps(schema)
|
||||
compiled = _compiler(tokenizer, vocab_size).compile_json_schema(
|
||||
schema, any_whitespace=True
|
||||
)
|
||||
self.matcher = xgr.GrammarMatcher(
|
||||
compiled, override_stop_tokens=sorted(self.stop_ids) or None
|
||||
)
|
||||
self.bitmask = xgr.allocate_token_bitmask(1, vocab_size)
|
||||
|
||||
def accept_history(self, generated_ids: list[int]) -> bool:
|
||||
"""Validate newly generated grammar tokens, including the final EOS.
|
||||
|
||||
Return whether the grammar has terminated. Use this after the final
|
||||
output token; no next-token distribution exists after termination.
|
||||
"""
|
||||
assert generated_ids[: len(self.history)] == self.history, (
|
||||
"Each reference belongs to one monotonically growing request history"
|
||||
)
|
||||
if self.matcher is not None:
|
||||
for token in generated_ids[len(self.history) :]:
|
||||
assert self.matcher.accept_token(token), (
|
||||
f"Grammar rejected token {token} at position {len(self.history)}"
|
||||
)
|
||||
self.history.append(token)
|
||||
return self.matcher.is_terminated()
|
||||
else:
|
||||
self.history = generated_ids.copy()
|
||||
return False
|
||||
|
||||
def distributions(
|
||||
self, raw_logits: torch.Tensor, generated_ids: list[int]
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Return FP32 logits before and after non-grammar sampling transforms.
|
||||
|
||||
``raw_logits`` scores the next token after the prompt and
|
||||
``generated_ids``. Returned tensors do not alias the model's tensor.
|
||||
Normalize the first result to check reported completion logprobs;
|
||||
the second supplies the greedy decision reference.
|
||||
"""
|
||||
assert raw_logits.shape == (self.vocab_size,)
|
||||
assert not self.accept_history(generated_ids), (
|
||||
"Cannot generate a distribution after grammar EOS"
|
||||
)
|
||||
|
||||
grammar_logits = raw_logits.float().clone()
|
||||
if self.matcher is not None:
|
||||
assert self.bitmask is not None
|
||||
self.matcher.fill_next_token_bitmask(self.bitmask)
|
||||
words = self.bitmask[0, :, None]
|
||||
allowed = ((words >> torch.arange(32)) & 1).flatten()
|
||||
allowed = allowed[: self.vocab_size].bool().to(raw_logits.device)
|
||||
grammar_logits.masked_fill_(~allowed, -torch.inf)
|
||||
|
||||
processed = grammar_logits.clone()
|
||||
for bad_word in self.bad_words:
|
||||
prefix = bad_word[:-1]
|
||||
if not prefix or generated_ids[-len(prefix) :] == prefix:
|
||||
processed[bad_word[-1]] = -torch.inf
|
||||
|
||||
if len(generated_ids) < self.min_tokens and self.stop_ids:
|
||||
stop_ids = sorted(self.stop_ids)
|
||||
stop_scores = processed[stop_ids].clone()
|
||||
processed[stop_ids] = -torch.inf
|
||||
# A completed grammar may have no continuation except a stop token.
|
||||
if self.matcher is not None and torch.isneginf(processed).all():
|
||||
processed[stop_ids] = stop_scores
|
||||
|
||||
if self.frequency_penalty:
|
||||
for token, count in Counter(generated_ids).items():
|
||||
processed[token] -= self.frequency_penalty * count
|
||||
return grammar_logits, processed
|
||||
@@ -1,450 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import os
|
||||
from itertools import repeat
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch._dynamo.config as dynamo_config
|
||||
|
||||
from tests.utils import (
|
||||
large_gpu_mark,
|
||||
single_gpu_only,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
from vllm.v1.metrics.reader import Metric
|
||||
|
||||
from ....conftest import VllmRunner
|
||||
from ....models.utils import check_outputs_equal
|
||||
|
||||
MODEL = "Qwen/Qwen3-0.6B"
|
||||
MTP_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
|
||||
# Need to enforce eager for MRV2 while we sort out cudagraph issues.
|
||||
ENFORCE_EAGER = os.getenv("ENFORCE_EAGER", "0") == "1"
|
||||
|
||||
first_prompt = (
|
||||
"The following numbers of the sequence "
|
||||
+ ", ".join(str(i) for i in range(10))
|
||||
+ " are:"
|
||||
)
|
||||
example_prompts = [first_prompt, "In one word, the capital of France is "] + [
|
||||
f"Tell me about the number {i}: " for i in range(32)
|
||||
]
|
||||
|
||||
default_params = dict(
|
||||
temperature=0.0, # greedy
|
||||
max_tokens=30,
|
||||
min_tokens=28,
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_without_spec_decoding(
|
||||
sample_json_schema,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""Test consistency of combos of async scheduling, preemption,
|
||||
uni/multiproc executor, prefill chunking."""
|
||||
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
|
||||
test_sampling_params: list[dict[str, Any]] = [
|
||||
dict(),
|
||||
# dict(min_tokens=20),
|
||||
dict(frequency_penalty=-1.0),
|
||||
dict(bad_words=["the", " the"]),
|
||||
dict(logprobs=2),
|
||||
dict(logprobs=2, frequency_penalty=-1.0),
|
||||
dict(prompt_logprobs=2),
|
||||
dict(prompt_logprobs=2, logprobs=2),
|
||||
dict(structured_outputs=struct_outputs),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
]
|
||||
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(True, "mp", False, None, True),
|
||||
(False, "mp", True, None, False),
|
||||
(False, "uni", True, None, False),
|
||||
(True, "mp", True, None, False),
|
||||
(True, "uni", True, None, False),
|
||||
(False, "mp", True, None, True),
|
||||
(True, "mp", True, None, True),
|
||||
(True, "uni", True, None, True),
|
||||
]
|
||||
|
||||
if current_platform.is_rocm():
|
||||
# On ROCm, Only test with structured_outputs (deterministic)
|
||||
# and skip chunk_prefill (more variable).
|
||||
test_configs = [
|
||||
cfg
|
||||
for cfg in test_configs
|
||||
if not cfg[4] # skip chunk_prefill=True
|
||||
]
|
||||
test_sampling_params = [
|
||||
p for p in test_sampling_params if p.get("structured_outputs") is not None
|
||||
]
|
||||
|
||||
run_tests(monkeypatch, MODEL, test_configs, test_sampling_params)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@large_gpu_mark(min_gb=16)
|
||||
def test_with_eagle3_spec_decoding(sample_json_schema, monkeypatch: pytest.MonkeyPatch):
|
||||
"""Test consistency and acceptance rates with some different combos of
|
||||
preemption, executor, async scheduling, prefill chunking,
|
||||
spec decoding model length.
|
||||
"""
|
||||
spec_config = {
|
||||
"method": "eagle3",
|
||||
"num_speculative_tokens": 2,
|
||||
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
|
||||
}
|
||||
# Set small draft model len to force doesn't-fit-in-drafter case.
|
||||
spec_config_short = spec_config | {"max_model_len": 50}
|
||||
|
||||
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
|
||||
|
||||
test_sampling_params = [
|
||||
dict(),
|
||||
dict(frequency_penalty=-1.0),
|
||||
dict(bad_words=["the", " the"]),
|
||||
dict(logprobs=2),
|
||||
dict(logprobs=2, frequency_penalty=-1.0),
|
||||
dict(prompt_logprobs=2),
|
||||
dict(prompt_logprobs=2, logprobs=2),
|
||||
dict(structured_outputs=struct_outputs),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
]
|
||||
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(False, "mp", False, spec_config, False),
|
||||
(True, "mp", False, spec_config, True),
|
||||
(True, "uni", False, spec_config_short, True),
|
||||
(False, "mp", True, spec_config, False),
|
||||
(True, "mp", True, spec_config, False),
|
||||
(False, "mp", True, spec_config_short, True),
|
||||
(True, "uni", True, spec_config, False),
|
||||
(True, "uni", True, spec_config_short, False),
|
||||
(True, "mp", True, spec_config, True),
|
||||
(True, "uni", True, spec_config_short, True),
|
||||
]
|
||||
|
||||
run_tests(monkeypatch, MTP_MODEL, test_configs, test_sampling_params)
|
||||
|
||||
|
||||
@pytest.mark.flaky(reruns=2, only_on=current_platform.is_rocm())
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_xpu(),
|
||||
reason=("XPU matmul/attention kernels are not batch-invariant"),
|
||||
)
|
||||
def test_with_ngram_gpu_spec_decoding(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Test ngram_gpu speculative decoding with different configurations.
|
||||
|
||||
This test specifically validates ngram_gpu behavior with various:
|
||||
- Number of speculative tokens (2-6)
|
||||
- Prompt lookup window sizes (min/max)
|
||||
- Async scheduling enabled (as in production)
|
||||
- Different executors and chunking settings
|
||||
"""
|
||||
# Variant with larger speculation window
|
||||
ngram_gpu_config = {
|
||||
"method": "ngram_gpu",
|
||||
"num_speculative_tokens": 3,
|
||||
"prompt_lookup_max": 3,
|
||||
"prompt_lookup_min": 2,
|
||||
}
|
||||
|
||||
# Test configurations covering various scenarios
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(False, "mp", False, ngram_gpu_config, False),
|
||||
(True, "mp", False, ngram_gpu_config, True),
|
||||
(False, "mp", True, ngram_gpu_config, False),
|
||||
(True, "mp", True, ngram_gpu_config, False),
|
||||
(True, "uni", True, ngram_gpu_config, False),
|
||||
(True, "mp", True, ngram_gpu_config, True),
|
||||
]
|
||||
|
||||
# Use MODEL (Qwen) for ngram_gpu tests as it's lighter weight
|
||||
# and ngram_gpu doesn't require a specific draft model
|
||||
run_tests(monkeypatch, MODEL, test_configs, [{}])
|
||||
|
||||
|
||||
@dynamo_config.patch(cache_size_limit=16)
|
||||
def run_tests(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
model: str,
|
||||
test_configs: list[tuple],
|
||||
test_sampling_params: list[dict[str, Any]],
|
||||
):
|
||||
"""Test consistency of combos of async scheduling, preemption,
|
||||
uni/multiproc executor with spec decoding."""
|
||||
# Flex attention supports float32.
|
||||
attention_config = {"backend": "FLEX_ATTENTION"}
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
# lock matmul precision to full FP32 (IEEE)
|
||||
m.setenv("VLLM_FLOAT32_MATMUL_PRECISION", "highest")
|
||||
outputs: list[tuple[str, list, list]] = []
|
||||
for n, (
|
||||
test_preemption,
|
||||
executor,
|
||||
async_scheduling,
|
||||
spec_config,
|
||||
test_prefill_chunking,
|
||||
) in enumerate(test_configs, 1):
|
||||
test_str = f"{n}/{len(test_configs)}"
|
||||
test_results = run_test(
|
||||
model,
|
||||
test_str,
|
||||
test_sampling_params,
|
||||
test_preemption,
|
||||
executor,
|
||||
async_scheduling,
|
||||
spec_config,
|
||||
test_prefill_chunking=test_prefill_chunking,
|
||||
attention_config=attention_config,
|
||||
)
|
||||
outputs.append(test_results)
|
||||
|
||||
baseline_config, baseline_tests, _ = outputs[0]
|
||||
_, _, baseline_acceptances = next(
|
||||
(o for o in outputs if o[2] is not None), (None, None, None)
|
||||
)
|
||||
|
||||
print(f"BASELINE: config=[{baseline_config}], accept_rates={baseline_acceptances}")
|
||||
|
||||
failure = None
|
||||
for test_config, test_outputs, test_acceptance_rates in outputs[1:]:
|
||||
for (base_outs, base_logprobs), base_acceptance_rate, (
|
||||
test_outs,
|
||||
test_logprobs,
|
||||
), test_acceptance_rate, params in zip(
|
||||
baseline_tests,
|
||||
baseline_acceptances or repeat(None),
|
||||
test_outputs,
|
||||
test_acceptance_rates or repeat(None),
|
||||
test_sampling_params,
|
||||
):
|
||||
reason = None
|
||||
try:
|
||||
check_outputs_equal(
|
||||
outputs_0_lst=base_outs,
|
||||
outputs_1_lst=test_outs,
|
||||
name_0=f"baseline=[{baseline_config}], params={params}",
|
||||
name_1=f"config=[{test_config}], params={params}",
|
||||
)
|
||||
except AssertionError as e:
|
||||
reason = "outputs ", e
|
||||
|
||||
if reason is None:
|
||||
try:
|
||||
assert _all_logprobs_match(base_logprobs, test_logprobs)
|
||||
except AssertionError as e:
|
||||
reason = "logprobs", e
|
||||
|
||||
if reason is None:
|
||||
try:
|
||||
if (
|
||||
base_acceptance_rate is not None
|
||||
and test_acceptance_rate is not None
|
||||
):
|
||||
if "spec_mml=None" in test_config:
|
||||
# Preemption causes more variance in acceptance rates
|
||||
if (
|
||||
current_platform.is_rocm()
|
||||
and "preemption=True" in test_config
|
||||
):
|
||||
tolerance = 0.10
|
||||
else:
|
||||
tolerance = 0.05
|
||||
assert (
|
||||
test_acceptance_rate > base_acceptance_rate
|
||||
or test_acceptance_rate
|
||||
== pytest.approx(base_acceptance_rate, rel=tolerance)
|
||||
)
|
||||
else:
|
||||
# Currently the reported acceptance rate is expected to be
|
||||
# lower when we sometimes skip drafting altogether.
|
||||
assert test_acceptance_rate > 0.1
|
||||
except AssertionError as e:
|
||||
reason = "accept ", e
|
||||
|
||||
if reason is None:
|
||||
print(
|
||||
f"\033[32mPASSED\033[0m: "
|
||||
f"config=[{test_config}], params={params}"
|
||||
f" accept_rate={test_acceptance_rate}"
|
||||
)
|
||||
else:
|
||||
reason_str, _ = reason
|
||||
print(
|
||||
f"\033[31mFAILED\033[0m({reason_str}): "
|
||||
f"config=[{test_config}], params={params}"
|
||||
f" accept_rate={test_acceptance_rate}"
|
||||
)
|
||||
if failure is None:
|
||||
_, failure = reason
|
||||
|
||||
if failure is not None:
|
||||
raise failure
|
||||
|
||||
|
||||
def run_test(
|
||||
model: str,
|
||||
test_str: str,
|
||||
sampling_param_tests: list[dict[str, Any]],
|
||||
test_preemption: bool,
|
||||
executor: str,
|
||||
async_scheduling: bool,
|
||||
spec_config: dict[str, Any] | None,
|
||||
test_prefill_chunking: bool,
|
||||
attention_config: dict[str, Any] | None = None,
|
||||
):
|
||||
spec_decoding = spec_config is not None
|
||||
cache_arg: dict[str, Any] = (
|
||||
# Force preemptions: with 33 blocks (one is the reserved null block)
|
||||
# the cache holds at most a single max-length request, so the ~34
|
||||
# concurrent prompts contend and trigger preemption. (Prompts here are
|
||||
# << max_model_len, so dropping max_model_len from 4096 to 512 doesn't
|
||||
# change generation behavior.)
|
||||
dict(num_gpu_blocks_override=33, max_model_len=512)
|
||||
if test_preemption
|
||||
else dict(gpu_memory_utilization=0.9, max_model_len=4096)
|
||||
)
|
||||
spec_mml = (spec_config or {}).get("max_model_len")
|
||||
spec_method = (spec_config or {}).get("method", "none")
|
||||
test_config = (
|
||||
f"executor={executor}, preemption={test_preemption}, "
|
||||
f"async_sched={async_scheduling}, "
|
||||
f"chunk_prefill={test_prefill_chunking}, "
|
||||
f"spec_decoding={spec_decoding}, spec_method={spec_method}, spec_mml={spec_mml}"
|
||||
)
|
||||
print("-" * 80)
|
||||
print(f"---- TESTING {test_str}: {test_config}")
|
||||
print("-" * 80)
|
||||
|
||||
with VllmRunner(
|
||||
model,
|
||||
enable_chunked_prefill=test_prefill_chunking,
|
||||
# Force prefill chunking
|
||||
max_num_batched_tokens=48 if test_prefill_chunking else None,
|
||||
enforce_eager=ENFORCE_EAGER,
|
||||
async_scheduling=async_scheduling,
|
||||
distributed_executor_backend=executor,
|
||||
dtype="float32",
|
||||
speculative_config=spec_config,
|
||||
disable_log_stats=False,
|
||||
attention_config=attention_config,
|
||||
enable_prefix_caching=False if current_platform.is_rocm() else None,
|
||||
**cache_arg,
|
||||
) as vllm_model:
|
||||
results = []
|
||||
acceptance_rates: list[float] | None = [] if spec_decoding else None
|
||||
for override_params in sampling_param_tests:
|
||||
metrics_before = vllm_model.llm.get_metrics()
|
||||
print(f"----------- RUNNING PARAMS: {override_params}")
|
||||
results.append(
|
||||
vllm_model.generate(
|
||||
example_prompts,
|
||||
sampling_params=SamplingParams(**default_params, **override_params),
|
||||
return_logprobs=True,
|
||||
)
|
||||
)
|
||||
metrics_after = vllm_model.llm.get_metrics()
|
||||
if acceptance_rates is not None:
|
||||
acceptance_rate = _get_acceptance_rate(metrics_before, metrics_after)
|
||||
acceptance_rates.append(acceptance_rate)
|
||||
print(f"ACCEPTANCE RATE {acceptance_rate}")
|
||||
|
||||
if test_preemption:
|
||||
preemptions = _get_count(
|
||||
metrics_before, metrics_after, "vllm:num_preemptions"
|
||||
)
|
||||
assert preemptions > 0, "preemption test had no preemptions"
|
||||
|
||||
if len(results) > 1:
|
||||
# First check that the different parameter configs
|
||||
# actually result in different output.
|
||||
for (other_test_outs, other_test_logprobs), params in zip(
|
||||
results[1:], sampling_param_tests[1:]
|
||||
):
|
||||
with pytest.raises(AssertionError):
|
||||
check_outputs_equal(
|
||||
outputs_0_lst=results[0][0],
|
||||
outputs_1_lst=other_test_outs,
|
||||
name_0=f"baseline params={params}",
|
||||
name_1=f"other params={params}",
|
||||
)
|
||||
assert _all_logprobs_match(results[0][1], other_test_logprobs)
|
||||
|
||||
return test_config, results, acceptance_rates
|
||||
|
||||
|
||||
def _all_logprobs_match(req_a, req_b) -> bool:
|
||||
return (
|
||||
req_a == req_b
|
||||
or len(req_a) == len(req_b)
|
||||
and all(
|
||||
len(seq_a) == len(seq_b)
|
||||
and all(_logprobs_match(a, b) for a, b in zip(seq_a, seq_b))
|
||||
for seq_a, seq_b in zip(req_a, req_b)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _logprobs_match(
|
||||
lps_a: dict[int, Logprob] | None,
|
||||
lps_b: dict[int, Logprob] | None,
|
||||
) -> bool:
|
||||
if lps_a is None or lps_b is None:
|
||||
return lps_a is lps_b
|
||||
rel_tol, abs_tol = 1e-3, 1e-6
|
||||
return (
|
||||
len(lps_a) == len(lps_b)
|
||||
and lps_a.keys() == lps_b.keys()
|
||||
and all(
|
||||
a.decoded_token == b.decoded_token
|
||||
and a.rank == pytest.approx(b.rank, rel=0.005)
|
||||
and a.logprob == pytest.approx(b.logprob, rel=rel_tol, abs=abs_tol)
|
||||
for a, b in ((lps_a[x], lps_b[x]) for x in lps_a)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _get_acceptance_rate(before: list[Metric], after: list[Metric]) -> float:
|
||||
draft = _get_count(before, after, "vllm:spec_decode_num_draft_tokens")
|
||||
accept = _get_count(before, after, "vllm:spec_decode_num_accepted_tokens")
|
||||
return accept / draft if draft > 0 else 0.0
|
||||
|
||||
|
||||
def _get_count(before: list[Metric], after: list[Metric], name: str) -> int:
|
||||
before_val = next(m.value for m in before if m.name == name)
|
||||
after_val = next(m.value for m in after if m.name == name)
|
||||
return after_val - before_val
|
||||
@@ -1,632 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Accuracy with automatic attention selection and the model's normal dtype.
|
||||
|
||||
Complements the strict Flex/FP32 invariance checks in test_async_scheduling.py.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from tests.conftest import HfRunner, VllmRunner
|
||||
from tests.utils import (
|
||||
large_gpu_mark,
|
||||
single_gpu_only,
|
||||
)
|
||||
from tests.v1.e2e.general.accuracy_utils import (
|
||||
AccuracyTolerance,
|
||||
check_accuracy_budget,
|
||||
check_first_divergence,
|
||||
check_greedy_token,
|
||||
check_logprobs,
|
||||
check_request_accuracy,
|
||||
check_stopping,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.metrics.reader import Metric
|
||||
|
||||
MODEL = "Qwen/Qwen3-0.6B"
|
||||
EAGLE3_TARGET_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
|
||||
# Need to enforce eager for MRV2 while we sort out cudagraph issues.
|
||||
ENFORCE_EAGER = os.getenv("ENFORCE_EAGER", "0") == "1"
|
||||
|
||||
first_prompt = (
|
||||
"The following numbers of the sequence "
|
||||
+ ", ".join(str(i) for i in range(10))
|
||||
+ " are:"
|
||||
)
|
||||
example_prompts = [first_prompt, "In one word, the capital of France is "] + [
|
||||
f"Tell me about the number {i}: " for i in range(32)
|
||||
]
|
||||
|
||||
default_params = dict(
|
||||
temperature=0.0, # greedy
|
||||
max_tokens=30,
|
||||
min_tokens=28,
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_without_spec_decoding(
|
||||
vllm_runner: type[VllmRunner],
|
||||
hf_runner: type[HfRunner],
|
||||
sample_json_schema,
|
||||
):
|
||||
"""Check target-model accuracy across scheduling and executor configurations."""
|
||||
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
|
||||
test_sampling_params: list[dict[str, Any]] = [
|
||||
dict(),
|
||||
dict(frequency_penalty=-1.0),
|
||||
dict(bad_words=["the", " the"]),
|
||||
dict(bad_words=["the", " the"], logprobs=2),
|
||||
dict(logprobs=2),
|
||||
dict(logprobs=2, frequency_penalty=-1.0),
|
||||
dict(prompt_logprobs=2),
|
||||
dict(prompt_logprobs=2, logprobs=2),
|
||||
dict(structured_outputs=struct_outputs),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
]
|
||||
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(True, "mp", False, None, True),
|
||||
(False, "mp", True, None, False),
|
||||
(False, "uni", True, None, False),
|
||||
(True, "mp", True, None, False),
|
||||
(True, "uni", True, None, False),
|
||||
(False, "mp", True, None, True),
|
||||
(True, "mp", True, None, True),
|
||||
(True, "uni", True, None, True),
|
||||
]
|
||||
|
||||
run_tests(vllm_runner, hf_runner, MODEL, test_configs, test_sampling_params)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@large_gpu_mark(min_gb=16)
|
||||
def test_with_eagle3_spec_decoding(
|
||||
vllm_runner: type[VllmRunner],
|
||||
hf_runner: type[HfRunner],
|
||||
sample_json_schema,
|
||||
):
|
||||
"""Check accuracy and acceptance, including drafts that exceed model length."""
|
||||
spec_config = {
|
||||
"method": "eagle3",
|
||||
"num_speculative_tokens": 2,
|
||||
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
|
||||
}
|
||||
# Set small draft model len to force doesn't-fit-in-drafter case.
|
||||
spec_config_short = spec_config | {"max_model_len": 50}
|
||||
|
||||
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
|
||||
|
||||
test_sampling_params: list[dict[str, Any]] = [
|
||||
dict(),
|
||||
dict(frequency_penalty=-1.0),
|
||||
dict(bad_words=["the", " the"]),
|
||||
dict(bad_words=["the", " the"], logprobs=2),
|
||||
dict(logprobs=2),
|
||||
dict(logprobs=2, frequency_penalty=-1.0),
|
||||
dict(prompt_logprobs=2),
|
||||
dict(prompt_logprobs=2, logprobs=2),
|
||||
dict(structured_outputs=struct_outputs),
|
||||
dict(
|
||||
structured_outputs=struct_outputs,
|
||||
logprobs=2,
|
||||
frequency_penalty=-1.0,
|
||||
),
|
||||
]
|
||||
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(False, "mp", False, spec_config, False),
|
||||
(True, "mp", False, spec_config, True),
|
||||
(True, "uni", False, spec_config_short, True),
|
||||
(False, "mp", True, spec_config, False),
|
||||
(True, "mp", True, spec_config, False),
|
||||
(False, "mp", True, spec_config_short, True),
|
||||
(True, "uni", True, spec_config, False),
|
||||
(True, "uni", True, spec_config_short, False),
|
||||
(True, "mp", True, spec_config, True),
|
||||
(True, "uni", True, spec_config_short, True),
|
||||
]
|
||||
|
||||
run_tests(
|
||||
vllm_runner, hf_runner, EAGLE3_TARGET_MODEL, test_configs, test_sampling_params
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_xpu(),
|
||||
reason=("XPU matmul/attention kernels are not batch-invariant"),
|
||||
)
|
||||
def test_with_ngram_gpu_spec_decoding(
|
||||
vllm_runner: type[VllmRunner],
|
||||
hf_runner: type[HfRunner],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""Check ngram accuracy and acceptance across scheduling configurations."""
|
||||
if current_platform.is_rocm():
|
||||
# hipBLASLt picks GEMM solutions by batch shape, so sync and async runs
|
||||
# can flip near-tie greedy tokens and shift ngram acceptance.
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
ngram_gpu_config = {
|
||||
"method": "ngram_gpu",
|
||||
"num_speculative_tokens": 3,
|
||||
"prompt_lookup_max": 3,
|
||||
"prompt_lookup_min": 2,
|
||||
}
|
||||
|
||||
# test_preemption, executor, async_scheduling,
|
||||
# spec_config, test_prefill_chunking
|
||||
test_configs = [
|
||||
(False, "mp", False, None, False),
|
||||
(False, "mp", False, ngram_gpu_config, False),
|
||||
(True, "mp", False, ngram_gpu_config, True),
|
||||
(False, "mp", True, ngram_gpu_config, False),
|
||||
(True, "mp", True, ngram_gpu_config, False),
|
||||
(True, "uni", True, ngram_gpu_config, False),
|
||||
(True, "mp", True, ngram_gpu_config, True),
|
||||
]
|
||||
|
||||
run_tests(vllm_runner, hf_runner, MODEL, test_configs, [{}, dict(logprobs=2)])
|
||||
|
||||
|
||||
def run_tests(
|
||||
vllm_runner: type[VllmRunner],
|
||||
hf_runner: type[HfRunner],
|
||||
model: str,
|
||||
test_configs: list[tuple],
|
||||
test_sampling_params: list[dict[str, Any]],
|
||||
):
|
||||
"""Compare the shared prefix and independently validate every continuation."""
|
||||
assert test_configs[0] == (False, "mp", False, None, False), (
|
||||
"The baseline must use synchronous target-only decoding"
|
||||
)
|
||||
outputs = []
|
||||
for n, config in enumerate(test_configs, 1):
|
||||
outputs.append(
|
||||
run_test(
|
||||
vllm_runner,
|
||||
model,
|
||||
f"{n}/{len(test_configs)}",
|
||||
test_sampling_params,
|
||||
*config,
|
||||
)
|
||||
)
|
||||
|
||||
baseline_config, baseline_batches, _ = outputs[0]
|
||||
# Compare vLLM's own decisions at the first divergence, where histories
|
||||
# still match. HF then scores each continuation, including after divergence.
|
||||
# Neither engine forces an attention backend, dtype, or matmul precision.
|
||||
# Qwen/Llama BF16 controls and Qwen holdouts measured max score error <0.38,
|
||||
# per-stream request mean <0.073, max greedy gap 0.125, and request sum 0.25.
|
||||
# Per-request budgets also reject systematic errors below the scalar bounds.
|
||||
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
|
||||
# These short CPU reductions cost more to distribute across a thread pool.
|
||||
with set_default_torch_num_threads(1), hf_runner(model) as hf:
|
||||
hf.model.eval()
|
||||
for config, batches, _ in outputs:
|
||||
assert len(batches) == len(test_sampling_params)
|
||||
for baseline_batch, batch, overrides in zip(
|
||||
baseline_batches, batches, test_sampling_params, strict=True
|
||||
):
|
||||
assert len(batch) == len(example_prompts), config
|
||||
params = SamplingParams(**default_params, **overrides)
|
||||
for i, (baseline, request, prompt) in enumerate(
|
||||
zip(baseline_batch, batch, example_prompts, strict=True)
|
||||
):
|
||||
assert request.prompt_token_ids == hf.tokenizer.encode(prompt)
|
||||
context = f"config=[{config}], params={overrides}, request={i}"
|
||||
if params.logprobs is not None:
|
||||
check_first_divergence(
|
||||
baseline,
|
||||
request,
|
||||
params,
|
||||
tolerance,
|
||||
f"baseline=[{baseline_config}], {context}",
|
||||
)
|
||||
check_request_accuracy(
|
||||
hf,
|
||||
request,
|
||||
params,
|
||||
tolerance,
|
||||
context,
|
||||
)
|
||||
print(f"ACCURACY PASSED: config=[{config}], params={overrides}")
|
||||
|
||||
baseline_acceptances = next((o[2] for o in outputs if o[2] is not None), None)
|
||||
if baseline_acceptances is not None:
|
||||
for settings, (config, _, acceptances) in zip(
|
||||
test_configs, outputs, strict=True
|
||||
):
|
||||
if acceptances is None:
|
||||
continue
|
||||
test_preemption, _, _, spec_config, _ = settings
|
||||
assert spec_config is not None
|
||||
for baseline, actual, params in zip(
|
||||
baseline_acceptances, acceptances, test_sampling_params, strict=True
|
||||
):
|
||||
context = f"config=[{config}], params={params}"
|
||||
if spec_config.get("max_model_len") is None:
|
||||
# Keep the original acceptance-quality floor per batch.
|
||||
# Preemption recomputes requests and loses n-gram drafts,
|
||||
# so allow a larger drop there.
|
||||
relative_drop = 0.10 if test_preemption else 0.05
|
||||
assert actual >= baseline * (1 - relative_drop), (
|
||||
f"{context}: acceptance={actual}, baseline={baseline}"
|
||||
)
|
||||
else:
|
||||
assert actual > 0.1, f"{context}: acceptance={actual}"
|
||||
|
||||
|
||||
def run_test(
|
||||
vllm_runner: type[VllmRunner],
|
||||
model: str,
|
||||
test_str: str,
|
||||
sampling_param_tests: list[dict[str, Any]],
|
||||
test_preemption: bool,
|
||||
executor: str,
|
||||
async_scheduling: bool,
|
||||
spec_config: dict[str, Any] | None,
|
||||
test_prefill_chunking: bool,
|
||||
):
|
||||
spec_decoding = spec_config is not None
|
||||
spec_method = (spec_config or {}).get("method", "none")
|
||||
# Chunked ngram decoding admits fewer concurrent requests under the
|
||||
# 48-token budget. Its original 33-block cache did not preempt on ROCm.
|
||||
# A 17-block cache forces contention while every original request fits
|
||||
# comfortably within 256 tokens (the longest prompt plus output is 67).
|
||||
cache_blocks = 17 if test_prefill_chunking and spec_method == "ngram_gpu" else 33
|
||||
cache_arg: dict[str, Any] = (
|
||||
dict(
|
||||
num_gpu_blocks_override=cache_blocks,
|
||||
max_model_len=(cache_blocks - 1) * 16,
|
||||
)
|
||||
if test_preemption
|
||||
else dict(gpu_memory_utilization=0.9, max_model_len=4096)
|
||||
)
|
||||
spec_mml = (spec_config or {}).get("max_model_len")
|
||||
test_config = (
|
||||
f"executor={executor}, preemption={test_preemption}, "
|
||||
f"async_sched={async_scheduling}, "
|
||||
f"chunk_prefill={test_prefill_chunking}, "
|
||||
f"spec_decoding={spec_decoding}, spec_method={spec_method}, spec_mml={spec_mml}"
|
||||
)
|
||||
print("-" * 80)
|
||||
print(f"---- TESTING {test_str}: {test_config}")
|
||||
print("-" * 80)
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
enable_chunked_prefill=test_prefill_chunking,
|
||||
# Force prefill chunking
|
||||
max_num_batched_tokens=48 if test_prefill_chunking else None,
|
||||
enforce_eager=ENFORCE_EAGER,
|
||||
async_scheduling=async_scheduling,
|
||||
distributed_executor_backend=executor,
|
||||
speculative_config=spec_config,
|
||||
disable_log_stats=False,
|
||||
enable_prefix_caching=False if current_platform.is_rocm() else None,
|
||||
**cache_arg,
|
||||
) as vllm_model:
|
||||
results = []
|
||||
acceptance_rates: list[float] | None = [] if spec_decoding else None
|
||||
for override_params in sampling_param_tests:
|
||||
metrics_before = vllm_model.llm.get_metrics()
|
||||
print(f"----------- RUNNING PARAMS: {override_params}")
|
||||
results.append(
|
||||
vllm_model.llm.generate(
|
||||
vllm_model.get_inputs(example_prompts),
|
||||
sampling_params=SamplingParams(**default_params, **override_params),
|
||||
)
|
||||
)
|
||||
metrics_after = vllm_model.llm.get_metrics()
|
||||
if acceptance_rates is not None:
|
||||
acceptance_rate = _get_acceptance_rate(metrics_before, metrics_after)
|
||||
acceptance_rates.append(acceptance_rate)
|
||||
print(f"ACCEPTANCE RATE {acceptance_rate}")
|
||||
|
||||
if test_preemption:
|
||||
preemptions = _get_count(
|
||||
metrics_before, metrics_after, "vllm:num_preemptions"
|
||||
)
|
||||
assert preemptions > 0, "preemption test had no preemptions"
|
||||
|
||||
# Preserve the original parameter-effect checks across repeated batches.
|
||||
if len(results) > 1:
|
||||
baseline = _result_signature(results[0])
|
||||
for outputs, params in zip(results[1:], sampling_param_tests[1:], strict=True):
|
||||
assert _result_signature(outputs) != baseline, (
|
||||
f"{test_config}: sampling parameters had no observable effect: {params}"
|
||||
)
|
||||
# The old ROCm filter used schema-only as its first parameter set.
|
||||
# Retain those comparisons after restoring the ordinary cases too.
|
||||
schema_batches = [
|
||||
batch
|
||||
for batch, params in zip(results, sampling_param_tests, strict=True)
|
||||
if params.get("structured_outputs") is not None
|
||||
]
|
||||
for batch in schema_batches[1:]:
|
||||
assert _result_signature(batch) != _result_signature(schema_batches[0]), (
|
||||
f"{test_config}: structured sampling parameters had no effect"
|
||||
)
|
||||
|
||||
return test_config, results, acceptance_rates
|
||||
|
||||
|
||||
def _result_signature(requests):
|
||||
return [
|
||||
(
|
||||
list(request.outputs[0].token_ids),
|
||||
request.outputs[0].text,
|
||||
request.prompt_logprobs,
|
||||
request.outputs[0].logprobs,
|
||||
)
|
||||
for request in requests
|
||||
]
|
||||
|
||||
|
||||
def _get_acceptance_rate(before: list[Metric], after: list[Metric]) -> float:
|
||||
draft = _get_count(before, after, "vllm:spec_decode_num_draft_tokens")
|
||||
accept = _get_count(before, after, "vllm:spec_decode_num_accepted_tokens")
|
||||
assert draft > 0, "speculative test did not draft any tokens"
|
||||
assert 0 <= accept <= draft, f"invalid acceptance counters: {accept=}, {draft=}"
|
||||
return accept / draft
|
||||
|
||||
|
||||
def _get_count(before: list[Metric], after: list[Metric], name: str) -> int:
|
||||
before_val = next(m.value for m in before if m.name == name)
|
||||
after_val = next(m.value for m in after if m.name == name)
|
||||
return after_val - before_val
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"corruption", ["score", "rank", "top_k", "missing", "nan", "positive", "order"]
|
||||
)
|
||||
def test_accuracy_checks_reject_incorrect_logprobs(corruption):
|
||||
second = 2.875 if corruption == "order" else 1.0
|
||||
reference = torch.tensor([3.0, second, -2.0, -5.0]).log_softmax(-1)
|
||||
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
|
||||
scores = {
|
||||
0: Logprob(logprob=float(reference[0]), rank=1, decoded_token="a"),
|
||||
1: Logprob(logprob=float(reference[1]), rank=2, decoded_token="b"),
|
||||
}
|
||||
check_logprobs(scores, reference, 0, 2, tolerance, "control")
|
||||
if corruption == "score":
|
||||
scores[0] = replace(scores[0], logprob=scores[0].logprob - 1.0)
|
||||
elif corruption == "rank":
|
||||
scores[1] = replace(scores[1], rank=1)
|
||||
elif corruption == "top_k":
|
||||
del scores[1]
|
||||
scores[3] = Logprob(logprob=float(reference[3]), rank=2, decoded_token="d")
|
||||
elif corruption == "missing":
|
||||
del scores[0]
|
||||
elif corruption == "positive":
|
||||
scores[0] = replace(scores[0], logprob=0.1)
|
||||
elif corruption == "order":
|
||||
scores[0] = replace(scores[0], rank=2)
|
||||
scores[1] = replace(scores[1], rank=1)
|
||||
else:
|
||||
scores[0] = replace(scores[0], logprob=float("nan"))
|
||||
with pytest.raises(AssertionError):
|
||||
check_logprobs(scores, reference, 0, 2, tolerance, corruption)
|
||||
|
||||
|
||||
def test_accuracy_checks_distinguish_ties_from_wrong_tokens():
|
||||
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
|
||||
logits = torch.tensor([3.0, 2.875, -2.0, -torch.inf])
|
||||
check_greedy_token(logits, 0, tolerance, "best")
|
||||
check_greedy_token(logits, 1, tolerance, "near tie")
|
||||
for token in (2, 3):
|
||||
with pytest.raises(AssertionError):
|
||||
check_greedy_token(logits, token, tolerance, "incorrect token")
|
||||
|
||||
# top-k may omit a sampled token tied at its boundary. The sampled rank
|
||||
# can duplicate a sequential top-k rank without corrupting the result.
|
||||
reference = torch.zeros(4).log_softmax(-1)
|
||||
scores = {
|
||||
token: Logprob(logprob=float(reference[token]), rank=rank)
|
||||
for token, rank in [(3, 1), (0, 1), (1, 2)]
|
||||
}
|
||||
check_logprobs(scores, reference, 3, 2, tolerance, "tied top-k")
|
||||
|
||||
# A grammar with one allowed token still returns the requested top-k,
|
||||
# including masked entries whose score is exactly negative infinity.
|
||||
reference = torch.tensor([0.0, -torch.inf, -torch.inf])
|
||||
scores = {0: Logprob(0.0, 1), 1: Logprob(-float("inf"), 2)}
|
||||
check_logprobs(scores, reference, 0, 2, tolerance, "masked top-k")
|
||||
|
||||
|
||||
def test_accuracy_checks_reject_incorrect_stopping():
|
||||
params = SamplingParams(max_tokens=3)
|
||||
stop_ids = {2, 3}
|
||||
for tokens, reason, stop_reason in [
|
||||
([0, 1, 2], "stop", None),
|
||||
([0, 1, 3], "stop", 3),
|
||||
([0, 1, 0], "length", None),
|
||||
]:
|
||||
check_stopping(
|
||||
tokens,
|
||||
reason,
|
||||
stop_ids,
|
||||
params,
|
||||
"valid stopping at length cap",
|
||||
eos_token_id=2,
|
||||
stop_reason=stop_reason,
|
||||
)
|
||||
for tokens, reason, stop_reason in [
|
||||
([0, 2, 1], "length", None),
|
||||
([0, 1, 2], "length", None),
|
||||
([0, 1, 2], "stop", 2),
|
||||
([0, 1, 3], "stop", None),
|
||||
([0, 1, 3], "stop", 2),
|
||||
([0, 1, 0], "length", 3),
|
||||
]:
|
||||
with pytest.raises(AssertionError):
|
||||
check_stopping(
|
||||
tokens,
|
||||
reason,
|
||||
stop_ids,
|
||||
params,
|
||||
"incorrect stopping",
|
||||
eos_token_id=2,
|
||||
stop_reason=stop_reason,
|
||||
)
|
||||
|
||||
|
||||
def test_accuracy_checks_reject_systematic_sub_bound_errors():
|
||||
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
|
||||
reference = torch.tensor([3.0, 2.75, -2.0]).log_softmax(-1)
|
||||
scores = {i: Logprob(float(reference[i]) - 0.4, i + 1) for i in (0, 1)}
|
||||
# Each corrupted score fits the scalar bound, but the bias must not pass.
|
||||
errors = check_logprobs(scores, reference, 0, 2, tolerance, "biased scores")
|
||||
with pytest.raises(AssertionError, match="mean logprob error"):
|
||||
check_accuracy_budget([errors], [], tolerance, "biased scores")
|
||||
|
||||
gap = check_greedy_token(reference, 1, tolerance, "one ambiguous choice")
|
||||
with pytest.raises(AssertionError, match="total greedy logit gap"):
|
||||
check_accuracy_budget([], [gap] * 30, tolerance, "systematically worse choices")
|
||||
check_accuracy_budget(
|
||||
[torch.tensor([0.03, 0.07])], [0.125, 0.125], tolerance, "control variation"
|
||||
)
|
||||
|
||||
|
||||
def _divergence_request(
|
||||
tokens: list[int], scores: dict[int, float], position: int = 0
|
||||
) -> RequestOutput:
|
||||
logprobs: list[dict[int, Logprob]] = [{} for _ in tokens]
|
||||
logprobs[position] = {
|
||||
token: Logprob(score, rank)
|
||||
for rank, (token, score) in enumerate(
|
||||
sorted(scores.items(), key=lambda item: item[1], reverse=True), 1
|
||||
)
|
||||
}
|
||||
return RequestOutput(
|
||||
request_id="test",
|
||||
prompt=None,
|
||||
prompt_token_ids=[0, 0, 0],
|
||||
prompt_logprobs=None,
|
||||
outputs=[
|
||||
CompletionOutput(
|
||||
index=0,
|
||||
text="",
|
||||
token_ids=tokens,
|
||||
cumulative_logprob=None,
|
||||
logprobs=logprobs,
|
||||
finish_reason="length",
|
||||
)
|
||||
],
|
||||
finished=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"base_scores,actual_scores,error",
|
||||
[
|
||||
({0: -0.8, 1: -0.9}, {0: -0.9, 1: -0.8}, None),
|
||||
({0: -0.8, 1: -0.8}, {0: -0.8, 1: -0.8}, None),
|
||||
({0: -0.8, 1: -0.9}, {0: -0.8, 1: -0.9}, "actual.*below"),
|
||||
({0: -0.9, 1: -0.8}, {0: -0.9, 1: -0.8}, "baseline.*below"),
|
||||
({0: -0.8, 1: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*near-tie"),
|
||||
({0: -0.8, 1: -0.9}, {0: -1.1, 1: -0.8}, "actual.*near-tie"),
|
||||
({0: -0.8, 2: -0.9}, {0: -0.9, 1: -0.8}, None),
|
||||
({0: -0.8, 2: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*lower bound"),
|
||||
({0: -0.8, 1: -0.9}, {1: -0.8, 2: -1.1}, "actual.*lower bound"),
|
||||
],
|
||||
ids=[
|
||||
"near-tie-rank-reversal",
|
||||
"exact-tie",
|
||||
"wrong-near-tie-actual-choice",
|
||||
"wrong-near-tie-baseline-choice",
|
||||
"decisive-baseline",
|
||||
"decisive-actual",
|
||||
"missing-candidate-inconclusive",
|
||||
"missing-candidate-decisive-baseline",
|
||||
"missing-candidate-decisive-actual",
|
||||
],
|
||||
)
|
||||
def test_first_divergence_checks_engine_preferences(base_scores, actual_scores, error):
|
||||
baseline = _divergence_request([0], base_scores)
|
||||
actual = _divergence_request([1], actual_scores)
|
||||
args = (
|
||||
baseline,
|
||||
actual,
|
||||
SamplingParams(temperature=0, logprobs=2),
|
||||
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
|
||||
"paired engines",
|
||||
)
|
||||
if error is None:
|
||||
check_first_divergence(*args)
|
||||
else:
|
||||
with pytest.raises(AssertionError, match=error):
|
||||
check_first_divergence(*args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing_alternative", [False, True])
|
||||
def test_first_divergence_uses_generated_penalty_history(missing_alternative):
|
||||
# Raw ordering favors token 1; one generated 0 reverses the penalized order.
|
||||
# The prompt contains three more 0s which must not contribute to penalties.
|
||||
base_scores = {0: -1.5, 1: -0.6}
|
||||
if missing_alternative:
|
||||
# The selected 0 is outside top-2. Use the top-k boundary (-0.6),
|
||||
# excluding the additional sampled token (-1.5), for the missing 1.
|
||||
base_scores = {0: -1.5, 2: -0.5, 3: -0.6}
|
||||
baseline = _divergence_request([0, 0, 2], base_scores, position=1)
|
||||
actual = _divergence_request([0, 1, 3, 4], {0: -1.6, 1: -0.5}, position=1)
|
||||
check_first_divergence(
|
||||
baseline,
|
||||
actual,
|
||||
SamplingParams(temperature=0, logprobs=2, frequency_penalty=-1),
|
||||
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
|
||||
"different later histories are validated separately",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mismatch", ["length", "finish_reason", "prompt"])
|
||||
def test_first_divergence_rejects_mismatches_without_a_token_change(mismatch):
|
||||
baseline = _divergence_request([0, 1], {})
|
||||
actual = _divergence_request([0, 1], {})
|
||||
if mismatch == "length":
|
||||
actual.outputs[0].token_ids = [0]
|
||||
elif mismatch == "finish_reason":
|
||||
actual.outputs[0].finish_reason = "stop"
|
||||
else:
|
||||
actual.prompt_token_ids = [1]
|
||||
with pytest.raises(AssertionError):
|
||||
check_first_divergence(
|
||||
baseline,
|
||||
actual,
|
||||
SamplingParams(temperature=0, logprobs=2),
|
||||
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
|
||||
mismatch,
|
||||
)
|
||||
@@ -1,94 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""End-to-end checks that ``backend_per_kind`` selects the requested attention
|
||||
backend for each KV-cache group at runtime.
|
||||
|
||||
Uses ``google/gemma-3-1b-it``, which interleaves full-attention and
|
||||
sliding-window layers, so the model produces separate ``full_attention`` and
|
||||
``sliding_window`` KV-cache groups.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.config.attention import AttentionConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL = "google/gemma-3-1b-it"
|
||||
|
||||
|
||||
def _collect_group_backends(worker) -> list[tuple[str, str]]:
|
||||
"""Runs on the worker: returns (spec_kind, backend_name) per attn group."""
|
||||
from vllm.v1.kv_cache_interface import get_kv_cache_spec_kind
|
||||
|
||||
out: list[tuple[str, str]] = []
|
||||
for kv_group in worker.model_runner.attn_groups:
|
||||
for attn_group in kv_group:
|
||||
kind = get_kv_cache_spec_kind(attn_group.kv_cache_spec)
|
||||
out.append((kind.value, attn_group.backend.get_name()))
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="backend names are CUDA-specific"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"backend_per_kind",
|
||||
[
|
||||
{"full_attention": "FLASH_ATTN", "sliding_window": "TRITON_ATTN"},
|
||||
# Swapped, to prove the mapping is causal rather than the default.
|
||||
{"full_attention": "TRITON_ATTN", "sliding_window": "FLASH_ATTN"},
|
||||
],
|
||||
)
|
||||
def test_backend_per_kind_splits_groups(backend_per_kind, monkeypatch):
|
||||
# collective_rpc ships the callable to the EngineCore subprocess; the
|
||||
# secure msgpack encoder can't serialize functions, so opt into the
|
||||
# pickle fallback (same pattern as test_pooling_chunked_prefill).
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
attention_config=AttentionConfig(backend_per_kind=backend_per_kind),
|
||||
enforce_eager=True,
|
||||
max_model_len=2048,
|
||||
gpu_memory_utilization=0.4,
|
||||
)
|
||||
|
||||
group_backends = llm.llm_engine.collective_rpc(_collect_group_backends)[0]
|
||||
kinds = {kind for kind, _ in group_backends}
|
||||
|
||||
# gemma3 must actually split into both kinds for this test to be meaningful.
|
||||
assert "full_attention" in kinds
|
||||
assert "sliding_window" in kinds
|
||||
|
||||
for kind, backend_name in group_backends:
|
||||
if kind in backend_per_kind:
|
||||
assert backend_name == backend_per_kind[kind], (
|
||||
f"{kind} group used {backend_name}, expected {backend_per_kind[kind]}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="backend names are CUDA-specific"
|
||||
)
|
||||
def test_backend_per_kind_overrides_global_backend(monkeypatch):
|
||||
"""A per-kind entry wins over the global ``backend`` for its kind; other
|
||||
kinds fall back to the global backend."""
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
attention_config=AttentionConfig(
|
||||
backend="FLASH_ATTN",
|
||||
backend_per_kind={"sliding_window": "TRITON_ATTN"},
|
||||
),
|
||||
enforce_eager=True,
|
||||
max_model_len=2048,
|
||||
gpu_memory_utilization=0.4,
|
||||
)
|
||||
|
||||
group_backends = llm.llm_engine.collective_rpc(_collect_group_backends)[0]
|
||||
|
||||
for kind, backend_name in group_backends:
|
||||
if kind == "sliding_window":
|
||||
assert backend_name == "TRITON_ATTN"
|
||||
elif kind == "full_attention":
|
||||
assert backend_name == "FLASH_ATTN"
|
||||
@@ -1,130 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....utils import check_answers, prep_prompts
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestConfig:
|
||||
sliding_window: int
|
||||
ln_range: tuple[int, int]
|
||||
|
||||
|
||||
model_config = {
|
||||
"bigcode/starcoder2-3b": TestConfig(4096, (800, 1100)),
|
||||
"google/gemma-3-1b-it": TestConfig(4096, (400, 800)),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
"bigcode/starcoder2-3b", # sliding window only
|
||||
"google/gemma-3-1b-it", # sliding window + full attention
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("batch_size", [5])
|
||||
@pytest.mark.parametrize("seed", [1])
|
||||
@pytest.mark.parametrize("disable_hybrid_kv_cache_manager", [True, False])
|
||||
def test_sliding_window_retrieval(
|
||||
model, batch_size, seed, disable_hybrid_kv_cache_manager, vllm_runner
|
||||
):
|
||||
"""The test does a bunch of assignments "x1 = 10\nx2 = 33\n..." and then
|
||||
asks for value of one of them (which is outside the sliding window).
|
||||
If we tell it upfront which we are going to be looking for, then
|
||||
it answers correctly (mostly).
|
||||
"""
|
||||
# NOTE: For ROCm, we have to enforce eager mode to use custom kernel
|
||||
# implementation of GELU with tanh approximation, as PyTorch's native
|
||||
# implementation is currently unstable with torch.compile and produces garbage.
|
||||
enforce_eager = current_platform.is_rocm()
|
||||
|
||||
test_config = model_config[model]
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
max_model_len=None,
|
||||
enable_chunked_prefill=None,
|
||||
disable_hybrid_kv_cache_manager=disable_hybrid_kv_cache_manager,
|
||||
enforce_eager=enforce_eager,
|
||||
) as runner:
|
||||
llm = runner.get_llm()
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=100)
|
||||
|
||||
prompts, answer, indices = prep_prompts(
|
||||
batch_size, ln_range=test_config.ln_range
|
||||
)
|
||||
|
||||
check_length(prompts, llm, test_config.sliding_window)
|
||||
|
||||
# Fresh generation
|
||||
responses = llm.generate(prompts, sampling_params)
|
||||
check_answers(
|
||||
indices,
|
||||
answer,
|
||||
[response.outputs[0].text for response in responses],
|
||||
accept_rate=1.0,
|
||||
)
|
||||
|
||||
# Re-generate with the same prompts to test prefix caching
|
||||
responses = llm.generate(prompts, sampling_params)
|
||||
check_answers(
|
||||
indices,
|
||||
answer,
|
||||
[response.outputs[0].text for response in responses],
|
||||
accept_rate=1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["google/gemma-3-1b-it"])
|
||||
def test_hybrid_kv_cache_manager_output_equivalence(model, vllm_runner):
|
||||
"""Disabling the hybrid KV cache manager must not change what the model
|
||||
computes: it promotes the sliding-window layers to full-attention *storage*
|
||||
only, so the global layers must keep attending globally.
|
||||
|
||||
Guards against the group's KV cache spec, which then covers windowed and
|
||||
global layers alike, imposing its window on the global layers too.
|
||||
"""
|
||||
prompts, _, _ = prep_prompts(2, ln_range=model_config[model].ln_range)
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=32)
|
||||
enforce_eager = current_platform.is_rocm()
|
||||
|
||||
outputs = []
|
||||
for disable_hybrid in (False, True):
|
||||
with vllm_runner(
|
||||
model,
|
||||
max_model_len=None,
|
||||
enable_chunked_prefill=None,
|
||||
disable_hybrid_kv_cache_manager=disable_hybrid,
|
||||
enforce_eager=enforce_eager,
|
||||
) as runner:
|
||||
responses = runner.get_llm().generate(prompts, sampling_params)
|
||||
outputs.append([response.outputs[0].text for response in responses])
|
||||
|
||||
assert outputs[0] == outputs[1]
|
||||
|
||||
|
||||
def check_length(prompts: list[str], llm: LLM, sliding_window: int):
|
||||
"""Check if the prompt length is valid, i.e., longer than the sliding window
|
||||
size and shorter than the model's max length.
|
||||
|
||||
Args:
|
||||
prompts: list of prompts
|
||||
llm: LLM object
|
||||
sliding_window: Sliding window size
|
||||
|
||||
"""
|
||||
tokenizer = llm.get_tokenizer()
|
||||
max_model_len = llm.llm_engine.model_config.max_model_len
|
||||
assert any(len(tokenizer.encode(prompt)) > sliding_window for prompt in prompts), (
|
||||
"Prompt is too short for test"
|
||||
)
|
||||
assert all(len(tokenizer.encode(prompt)) <= max_model_len for prompt in prompts), (
|
||||
"Prompt is too long for test"
|
||||
)
|
||||
@@ -1,122 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.config import CompilationConfig, CompilationMode
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....utils import check_answers, fork_new_process_for_each_test, prep_prompts
|
||||
|
||||
# global seed
|
||||
SEED = 42
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_prompts():
|
||||
"""Adapted from tests/v1/e2e/spec_decode/utils.py."""
|
||||
prompt_types = ["repeat", "sentence"]
|
||||
# Setting higher num prompts increases the chance of numerics mismatch
|
||||
# due to matrix multiplication numerics depending on batch dimension
|
||||
num_prompts = 10
|
||||
prompts = []
|
||||
|
||||
random.seed(0)
|
||||
random_prompt_type_choices = random.choices(prompt_types, k=num_prompts)
|
||||
|
||||
for kind in random_prompt_type_choices:
|
||||
word_choices = ["test", "temp", "hello", "where"]
|
||||
word = random.choice(word_choices)
|
||||
if kind == "repeat":
|
||||
prompt = f"""please repeat the word '{word}' 10 times."""
|
||||
elif kind == "sentence":
|
||||
prompt = f"""please give a ten-word sentence that
|
||||
uses the word {word} at least once."""
|
||||
else:
|
||||
raise ValueError(f"Unknown prompt type: {kind}")
|
||||
prompts.append(prompt)
|
||||
|
||||
return prompts
|
||||
|
||||
|
||||
use_fork_for_test = (
|
||||
fork_new_process_for_each_test
|
||||
if not (current_platform.is_rocm() or current_platform.is_xpu())
|
||||
else lambda x: x
|
||||
)
|
||||
|
||||
|
||||
@use_fork_for_test
|
||||
@pytest.mark.parametrize(
|
||||
"kv_sharing_fast_prefill,use_v2_model_runner",
|
||||
[
|
||||
(False, False),
|
||||
(True, False),
|
||||
(True, True),
|
||||
# (False, True) omitted: fast-prefill-off behavior is runner-generic,
|
||||
# and skipping it saves ~9 min of mostly torch.compile time in CI. The
|
||||
# no-silent-fallback assertion below is exercised by the V2 cases.
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("enforce_eager", [True, False])
|
||||
def test_kv_sharing_fast_prefill(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
kv_sharing_fast_prefill: bool,
|
||||
enforce_eager: bool,
|
||||
use_v2_model_runner: bool,
|
||||
):
|
||||
if not enforce_eager and current_platform.is_rocm():
|
||||
# Relevant context: https://github.com/vllm-project/vllm/pull/29244
|
||||
pytest.skip(
|
||||
"ROCm: torch.compile produces incorrect output for gemma-3n's GELU "
|
||||
"with tanh approximation. Use enforce_eager=True instead."
|
||||
)
|
||||
if not enforce_eager and not use_v2_model_runner and current_platform.is_cuda():
|
||||
pytest.skip(
|
||||
"cublasCreate fails with CUBLAS_STATUS_ALLOC_FAILED during memory "
|
||||
"profiling with torch 2.14: "
|
||||
"https://github.com/pytorch/pytorch/issues/199944"
|
||||
)
|
||||
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=100)
|
||||
compilation_config = CompilationConfig(
|
||||
# This allows vLLM compilation backend to handle allocating and
|
||||
# managing buffers for cudagraph
|
||||
cudagraph_copy_inputs=True,
|
||||
mode=CompilationMode.VLLM_COMPILE
|
||||
if not enforce_eager
|
||||
else CompilationMode.NONE,
|
||||
)
|
||||
batch_size = 10
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
# Make scheduling deterministic for reproducibility
|
||||
if current_platform.is_rocm():
|
||||
# Use spawn to prevent cuda re-initialization error
|
||||
m.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
else:
|
||||
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
m.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_model_runner else "0")
|
||||
|
||||
prompts, answer, indices = prep_prompts(batch_size)
|
||||
|
||||
llm = LLM(
|
||||
model="google/gemma-3n-E2B-it",
|
||||
enforce_eager=enforce_eager,
|
||||
compilation_config=compilation_config,
|
||||
seed=SEED,
|
||||
kv_sharing_fast_prefill=kv_sharing_fast_prefill,
|
||||
attention_backend="TRITON_ATTN",
|
||||
)
|
||||
# Guard against a silent fallback to the other model runner.
|
||||
assert llm.llm_engine.vllm_config.use_v2_model_runner == use_v2_model_runner
|
||||
responses = llm.generate(prompts, sampling_params)
|
||||
check_answers(
|
||||
indices,
|
||||
answer,
|
||||
[response.outputs[0].text for response in responses],
|
||||
accept_rate=1.0,
|
||||
)
|
||||
@@ -1,521 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Comprehensive end-to-end tests for `min_tokens` in the V1 engine.
|
||||
|
||||
Addresses #21950: verify and add CI coverage.
|
||||
|
||||
Covers:
|
||||
1) Basic functionality
|
||||
2) Stop strings with `min_tokens` (bug #21987; fix in PR #22014)
|
||||
3) EOS behavior with `min_tokens` (potential logits-processor bug)
|
||||
4) Edge cases (min_tokens == max_tokens, min_tokens == 0)
|
||||
5) Multiple stop conditions
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
|
||||
# Test configuration
|
||||
TEST_MODEL = "facebook/opt-125m" # Small model for fast CI execution
|
||||
GREEDY = 0.0 # Deterministic generation for consistent testing
|
||||
|
||||
|
||||
class MinTokensTestCase:
|
||||
"""Data class for min_tokens test scenarios."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
min_tokens: int,
|
||||
max_tokens: int,
|
||||
stop: str | list[str] | None = None,
|
||||
expected_min_len: int | None = None,
|
||||
expected_exact_len: int | None = None,
|
||||
):
|
||||
self.name = name
|
||||
self.min_tokens = min_tokens
|
||||
self.max_tokens = max_tokens
|
||||
self.stop = stop
|
||||
self.expected_min_len = expected_min_len or min_tokens
|
||||
self.expected_exact_len = expected_exact_len
|
||||
|
||||
def __str__(self):
|
||||
return (
|
||||
f"{self.name}: min={self.min_tokens}, "
|
||||
f"max={self.max_tokens}, stop={self.stop}"
|
||||
)
|
||||
|
||||
|
||||
# Test scenarios covering all critical cases
|
||||
MIN_TOKENS_TEST_CASES = [
|
||||
# === BASIC FUNCTIONALITY (should work) ===
|
||||
MinTokensTestCase(
|
||||
name="basic_min_tokens_no_stop",
|
||||
min_tokens=8,
|
||||
max_tokens=20,
|
||||
stop=None,
|
||||
expected_min_len=8,
|
||||
),
|
||||
MinTokensTestCase(
|
||||
name="min_tokens_zero",
|
||||
min_tokens=0,
|
||||
max_tokens=10,
|
||||
stop=None,
|
||||
expected_min_len=0,
|
||||
),
|
||||
MinTokensTestCase(
|
||||
name="min_equals_max_no_stop",
|
||||
min_tokens=15,
|
||||
max_tokens=15,
|
||||
stop=None,
|
||||
expected_exact_len=15,
|
||||
),
|
||||
# === STOP STRINGS WITH MIN_TOKENS ===
|
||||
# These tests expose the detokenizer bug where stop strings
|
||||
# bypass min_tokens
|
||||
# Using mathematically guaranteed approach with wide stop nets
|
||||
pytest.param(
|
||||
MinTokensTestCase(
|
||||
name="min_tokens_with_comprehensive_stops",
|
||||
min_tokens=5,
|
||||
max_tokens=20,
|
||||
stop=[
|
||||
"a",
|
||||
"e",
|
||||
"i",
|
||||
"o",
|
||||
"u",
|
||||
"t",
|
||||
"n",
|
||||
"s",
|
||||
"r",
|
||||
"l",
|
||||
" ",
|
||||
],
|
||||
expected_min_len=5,
|
||||
),
|
||||
marks=pytest.mark.xfail(
|
||||
reason=(
|
||||
"Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"
|
||||
),
|
||||
strict=False,
|
||||
),
|
||||
id="min_tokens_with_comprehensive_stops",
|
||||
),
|
||||
pytest.param(
|
||||
MinTokensTestCase(
|
||||
name="min_tokens_with_simple_char_stop",
|
||||
min_tokens=3,
|
||||
max_tokens=15,
|
||||
stop=["e", "a", " "],
|
||||
expected_min_len=3,
|
||||
),
|
||||
marks=pytest.mark.xfail(
|
||||
reason=(
|
||||
"Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"
|
||||
),
|
||||
strict=False,
|
||||
),
|
||||
id="min_tokens_with_simple_char_stop",
|
||||
),
|
||||
# === EOS TOKEN WITH MIN_TOKENS (potential LogitsProcessor bug) ===
|
||||
# These test the MinTokensLogitsProcessor handling of EOS tokens
|
||||
pytest.param(
|
||||
MinTokensTestCase(
|
||||
name="min_equals_max_eos_only",
|
||||
min_tokens=20,
|
||||
max_tokens=20,
|
||||
stop=None, # Relies on default EOS token behavior
|
||||
expected_exact_len=20,
|
||||
),
|
||||
marks=pytest.mark.xfail(
|
||||
reason=("Potential logits-processor bug: EOS tokens may bypass min_tokens"),
|
||||
strict=False,
|
||||
),
|
||||
id="min_equals_max_eos_only",
|
||||
),
|
||||
# === EDGE CASES ===
|
||||
MinTokensTestCase(
|
||||
name="large_min_tokens",
|
||||
min_tokens=50,
|
||||
max_tokens=60,
|
||||
stop=None,
|
||||
expected_min_len=50,
|
||||
),
|
||||
MinTokensTestCase(
|
||||
name="min_tokens_with_empty_stop_list",
|
||||
min_tokens=5,
|
||||
max_tokens=15,
|
||||
stop=[], # Empty stop list
|
||||
expected_min_len=5,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def llm_v1():
|
||||
"""Create V1 LLM instance for testing."""
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=1024, # Small context for fast testing
|
||||
enforce_eager=True, # Avoid graph compilation overhead
|
||||
)
|
||||
return llm
|
||||
|
||||
|
||||
def test_min_tokens_with_terminal_structured_output(llm_v1: LLM):
|
||||
"""A grammar whose only legal continuation is EOS must stop under
|
||||
min_tokens instead of sampling outside the grammar."""
|
||||
params = SamplingParams(
|
||||
temperature=GREEDY,
|
||||
min_tokens=20,
|
||||
max_tokens=40,
|
||||
structured_outputs=StructuredOutputsParams(
|
||||
json=json.dumps({"type": "boolean"})
|
||||
),
|
||||
)
|
||||
|
||||
output = llm_v1.generate("Answer:", params)[0].outputs[0]
|
||||
eos_token_id = llm_v1.get_tokenizer().eos_token_id
|
||||
|
||||
assert output.finish_reason == "stop"
|
||||
assert isinstance(json.loads(output.text), bool)
|
||||
assert output.token_ids[-1] == eos_token_id
|
||||
assert len(output.token_ids) < params.min_tokens
|
||||
|
||||
|
||||
def get_token_count(output: RequestOutput) -> int:
|
||||
"""Extract token count from LLM output."""
|
||||
if not output.outputs:
|
||||
return 0
|
||||
return len(output.outputs[0].token_ids)
|
||||
|
||||
|
||||
def assert_min_tokens_satisfied(
|
||||
output: RequestOutput, test_case: MinTokensTestCase
|
||||
) -> None:
|
||||
"""Assert that min_tokens requirement is satisfied."""
|
||||
token_count = get_token_count(output)
|
||||
stop_reason = output.outputs[0].stop_reason if output.outputs else "no output"
|
||||
|
||||
if test_case.expected_exact_len is not None:
|
||||
# Exact length requirement
|
||||
assert token_count == test_case.expected_exact_len, (
|
||||
f"Expected exactly {test_case.expected_exact_len} tokens, "
|
||||
f"got {token_count} tokens. "
|
||||
f"Stop reason: {stop_reason}"
|
||||
)
|
||||
else:
|
||||
# Minimum length requirement
|
||||
assert token_count >= (test_case.expected_min_len or 0), (
|
||||
f"Expected at least {test_case.expected_min_len} tokens, "
|
||||
f"got {token_count} tokens. "
|
||||
f"Stop reason: {stop_reason}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"test_case",
|
||||
MIN_TOKENS_TEST_CASES,
|
||||
ids=lambda tc: tc.name,
|
||||
)
|
||||
def test_min_tokens_comprehensive(llm_v1: LLM, test_case: MinTokensTestCase):
|
||||
"""Comprehensive test for min_tokens functionality in V1 engine.
|
||||
|
||||
This test covers all critical scenarios for min_tokens:
|
||||
- Basic functionality (should work)
|
||||
- Stop strings with min_tokens (known bug)
|
||||
- EOS tokens with min_tokens (potential bug)
|
||||
- Edge cases
|
||||
|
||||
Args:
|
||||
llm_v1: V1 LLM instance
|
||||
test_case: Test scenario parameters
|
||||
|
||||
"""
|
||||
# Known failing cases are handled via param-level xfail marks above.
|
||||
|
||||
# Create sampling parameters
|
||||
sampling_params = SamplingParams(
|
||||
min_tokens=test_case.min_tokens,
|
||||
max_tokens=test_case.max_tokens,
|
||||
stop=test_case.stop,
|
||||
temperature=GREEDY,
|
||||
include_stop_str_in_output=True, # Include stop strings for debugging
|
||||
)
|
||||
|
||||
# Use simple prompt. Comprehensive stop lists should catch any generation
|
||||
prompt = "Hello"
|
||||
|
||||
# Generate output
|
||||
outputs = llm_v1.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1, "Expected exactly one output"
|
||||
output = outputs[0]
|
||||
|
||||
# Debug information
|
||||
token_count = get_token_count(output)
|
||||
generated_text = output.outputs[0].text if output.outputs else ""
|
||||
stop_reason = output.outputs[0].stop_reason if output.outputs else "unknown"
|
||||
|
||||
print(f"\nTest: {test_case.name}")
|
||||
print(f"Generated {token_count} tokens")
|
||||
print(f"Stop reason: {stop_reason}")
|
||||
print(f"Generated text: {repr(generated_text)}")
|
||||
print(f"Expected min: {test_case.expected_min_len}")
|
||||
if test_case.expected_exact_len:
|
||||
print(f"Expected exact: {test_case.expected_exact_len}")
|
||||
|
||||
# Validate min_tokens requirement
|
||||
assert_min_tokens_satisfied(output, test_case)
|
||||
|
||||
|
||||
def test_min_tokens_basic_functionality(llm_v1: LLM):
|
||||
"""Test basic min_tokens functionality without stop conditions.
|
||||
|
||||
This is a baseline test that should always pass and validates
|
||||
that min_tokens works correctly in the simple case.
|
||||
"""
|
||||
sampling_params = SamplingParams(min_tokens=10, max_tokens=20, temperature=GREEDY)
|
||||
|
||||
prompt = "Once upon a time"
|
||||
outputs = llm_v1.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1
|
||||
token_count = get_token_count(outputs[0])
|
||||
|
||||
assert token_count >= 10, f"Expected at least 10 tokens, got {token_count}"
|
||||
assert token_count <= 20, f"Expected at most 20 tokens, got {token_count}"
|
||||
|
||||
|
||||
@pytest.mark.xfail(
|
||||
reason=("Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"),
|
||||
strict=False,
|
||||
)
|
||||
def test_min_tokens_stop_strings_bug(llm_v1: LLM):
|
||||
"""Test the specific bug where stop strings bypass min_tokens.
|
||||
|
||||
This test specifically reproduces the bug Calvin is fixing in PR #22014.
|
||||
It should fail until that fix is merged.
|
||||
|
||||
Strategy: Use guaranteed stop characters that will appear
|
||||
in any generated text.
|
||||
"""
|
||||
# If the bug is fixed upstream, this test will XPASS
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
min_tokens=15,
|
||||
max_tokens=50,
|
||||
# Common letter; likely appears early
|
||||
stop=["e"],
|
||||
temperature=GREEDY,
|
||||
include_stop_str_in_output=True,
|
||||
)
|
||||
|
||||
# Simple prompt that will generate text containing "e"
|
||||
prompt = "The quick brown fox"
|
||||
outputs = llm_v1.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1
|
||||
token_count = get_token_count(outputs[0])
|
||||
generated_text = outputs[0].outputs[0].text if outputs[0].outputs else ""
|
||||
|
||||
# Debug info to understand what happened
|
||||
print(f"Generated text: {repr(generated_text)}")
|
||||
print(f"Token count: {token_count}")
|
||||
print(f"Contains 'e': {'e' in generated_text}")
|
||||
|
||||
# This assertion should fail due to the bug - if stop string is found early,
|
||||
# the model should still continue generating until min_tokens is reached
|
||||
stop_reason = (
|
||||
outputs[0].outputs[0].stop_reason if outputs[0].outputs else "no output"
|
||||
)
|
||||
assert token_count >= 15, (
|
||||
"Bug confirmed: "
|
||||
f"{token_count} tokens < min_tokens=15. "
|
||||
f"Reason: {stop_reason}. "
|
||||
f"Text: {repr(generated_text)}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.xfail(
|
||||
reason=("Known bug #21987: stop strings bypass min_tokens (fixed by PR #22014)"),
|
||||
strict=False,
|
||||
)
|
||||
def test_min_tokens_stop_strings_guaranteed_early_trigger(llm_v1: LLM):
|
||||
"""Guaranteed test for stop strings bypassing min_tokens bug.
|
||||
|
||||
Strategy: Use very low temperature and multiple common stop strings
|
||||
to virtually guarantee early detection, combined with long min_tokens
|
||||
to ensure the bug is exposed regardless of model behavior.
|
||||
"""
|
||||
# If the bug is fixed upstream, this test will XPASS
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
min_tokens=50, # Set high min_tokens to ensure bug detection
|
||||
max_tokens=200,
|
||||
# Use multiple very common patterns - at least one will appear
|
||||
stop=["e", "a", "i", "o", "u", " ", "t", "n", "s", "r"],
|
||||
temperature=GREEDY,
|
||||
include_stop_str_in_output=True,
|
||||
)
|
||||
|
||||
# Simple prompt that will generate some text
|
||||
prompt = "The cat"
|
||||
outputs = llm_v1.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1
|
||||
token_count = get_token_count(outputs[0])
|
||||
generated_text = outputs[0].outputs[0].text if outputs[0].outputs else ""
|
||||
stop_reason = outputs[0].outputs[0].stop_reason if outputs[0].outputs else "unknown"
|
||||
|
||||
print(f"Generated text: {repr(generated_text)}")
|
||||
print(f"Token count: {token_count}")
|
||||
print(f"Stop reason: {stop_reason}")
|
||||
|
||||
# With the bug, this will fail because ANY of the common characters
|
||||
# will trigger early termination before min_tokens=50 is reached
|
||||
# It's virtually impossible to generate 50 tokens without hitting
|
||||
# at least one of: e, a, i, o, u, space, t, n, s, r
|
||||
finish_reason = (
|
||||
outputs[0].outputs[0].finish_reason if outputs[0].outputs else "unknown"
|
||||
)
|
||||
|
||||
print(f"Finish reason: {finish_reason}")
|
||||
|
||||
if finish_reason == "stop":
|
||||
assert token_count >= 50, (
|
||||
"Bug confirmed: "
|
||||
f"{token_count} tokens < min_tokens=50. "
|
||||
f"Reason: {finish_reason}. "
|
||||
f"Text: {repr(generated_text)}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.xfail(
|
||||
reason=("Potential logits-processor bug: EOS tokens may bypass min_tokens"),
|
||||
strict=False,
|
||||
)
|
||||
def test_min_tokens_eos_behavior(llm_v1: LLM):
|
||||
"""Verify EOS handling with and without min_tokens.
|
||||
|
||||
- Without min_tokens: expect early EOS -> finish_reason == "stop",
|
||||
stop_reason is None, and generated tokens < max_tokens (25).
|
||||
- With min_tokens: EOS should be blocked until min_tokens is reached
|
||||
(finish_reason == "length"); verify that eos_token_id does not appear
|
||||
in generated token_ids.
|
||||
"""
|
||||
# tokenizer + eos id
|
||||
tokenizer = llm_v1.get_tokenizer()
|
||||
eos_token_id = tokenizer.eos_token_id
|
||||
|
||||
prompt = "Give a file extension."
|
||||
max_toks = 32
|
||||
|
||||
# Case 1: WITHOUT min_tokens
|
||||
sp_no_min = SamplingParams(
|
||||
max_tokens=max_toks,
|
||||
temperature=GREEDY,
|
||||
)
|
||||
out_no_min = llm_v1.generate([prompt], sp_no_min)
|
||||
assert len(out_no_min) == 1
|
||||
choice_no_min = out_no_min[0].outputs[0]
|
||||
|
||||
ids_no_min = choice_no_min.token_ids or []
|
||||
finish_no_min = choice_no_min.finish_reason
|
||||
stop_no_min = choice_no_min.stop_reason
|
||||
|
||||
print(
|
||||
"[no-min] tokens=",
|
||||
len(ids_no_min),
|
||||
" finish=",
|
||||
finish_no_min,
|
||||
" stop_reason=",
|
||||
stop_no_min,
|
||||
)
|
||||
|
||||
assert finish_no_min == "stop", (
|
||||
f"Expected finish_reason 'stop' without min_tokens, got {finish_no_min}"
|
||||
)
|
||||
assert stop_no_min is None, (
|
||||
"For EOS-based stop (no user stop strings), stop_reason should be None."
|
||||
)
|
||||
assert len(ids_no_min) < max_toks, (
|
||||
f"Expected early EOS with < {max_toks} tokens, got {len(ids_no_min)}"
|
||||
)
|
||||
|
||||
# Case 2: WITH min_tokens
|
||||
sp_with_min = SamplingParams(
|
||||
min_tokens=max_toks,
|
||||
max_tokens=max_toks,
|
||||
temperature=GREEDY,
|
||||
)
|
||||
out_with_min = llm_v1.generate([prompt], sp_with_min)
|
||||
assert len(out_with_min) == 1
|
||||
choice_with_min = out_with_min[0].outputs[0]
|
||||
|
||||
ids_with_min = choice_with_min.token_ids or []
|
||||
finish_with_min = choice_with_min.finish_reason
|
||||
stop_with_min = choice_with_min.stop_reason
|
||||
|
||||
print(
|
||||
"[with-min] tokens=",
|
||||
len(ids_with_min),
|
||||
" finish=",
|
||||
finish_with_min,
|
||||
" stop_reason=",
|
||||
stop_with_min,
|
||||
)
|
||||
|
||||
# Exact length reached; EOS should have been blocked
|
||||
assert len(ids_with_min) == max_toks, (
|
||||
f"Expected exactly {max_toks} tokens with min_tokens; got {len(ids_with_min)}"
|
||||
)
|
||||
assert finish_with_min == "length", (
|
||||
f"Expected finish_reason 'length'; got {finish_with_min}"
|
||||
)
|
||||
assert eos_token_id not in ids_with_min, (
|
||||
"EOS token id should not appear when min_tokens prevents early EOS."
|
||||
)
|
||||
|
||||
|
||||
def test_min_tokens_validation():
|
||||
"""Test that SamplingParams correctly validates min_tokens parameters.
|
||||
|
||||
This tests the parameter validation logic in SamplingParams.
|
||||
"""
|
||||
# Valid cases
|
||||
SamplingParams(min_tokens=0, max_tokens=10)
|
||||
SamplingParams(min_tokens=5, max_tokens=10)
|
||||
SamplingParams(min_tokens=10, max_tokens=10)
|
||||
|
||||
# Invalid cases
|
||||
with pytest.raises(
|
||||
VLLMValidationError,
|
||||
match="min_tokens must be greater than or equal to 0",
|
||||
):
|
||||
SamplingParams(min_tokens=-1, max_tokens=10)
|
||||
|
||||
with pytest.raises(
|
||||
VLLMValidationError,
|
||||
match="min_tokens must be less than or equal to max_tokens",
|
||||
):
|
||||
SamplingParams(min_tokens=15, max_tokens=10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""
|
||||
Run tests locally for development.
|
||||
|
||||
Usage:
|
||||
cd vllm/
|
||||
python -m pytest tests/v1/e2e/general/test_min_tokens.py -v
|
||||
"""
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -1,166 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import pytest
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
prompt = """
|
||||
Generals gathered in their masses
|
||||
Just like witches at black masses
|
||||
Evil minds that plot destruction
|
||||
Sorcerer of death's construction
|
||||
In the fields, the bodies burning
|
||||
As the war machine keeps turning
|
||||
Death and hatred to mankind
|
||||
Poisoning their brainwashed minds
|
||||
Oh, Lord, yeah
|
||||
|
||||
Politicians hide themselves away
|
||||
They only started the war
|
||||
Why should they go out to fight?
|
||||
They leave that all to the poor, yeah
|
||||
Time will tell on their power minds
|
||||
Making war just for fun
|
||||
Treating people just like pawns in chess
|
||||
Wait till their judgment day comes, yeah
|
||||
|
||||
Now, in darkness, world stops turning
|
||||
Ashes where their bodies burning
|
||||
No more war pigs have the power
|
||||
Hand of God has struck the hour
|
||||
Day of Judgment, God is calling
|
||||
On their knees, the war pigs crawling
|
||||
Begging mercies for their sins
|
||||
Satan, laughing, spreads his wings
|
||||
Oh, Lord, yeah
|
||||
"""
|
||||
|
||||
|
||||
class WrapperPooler(nn.Module):
|
||||
def __init__(self, pooler):
|
||||
super().__init__()
|
||||
self.pooler = pooler
|
||||
self.chunks = []
|
||||
|
||||
def get_pooling_updates(self, task):
|
||||
return self.pooler.get_pooling_updates(task)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states,
|
||||
pooling_metadata,
|
||||
):
|
||||
self.chunks.append(hidden_states.shape[0])
|
||||
return self.pooler(hidden_states, pooling_metadata)
|
||||
|
||||
|
||||
def inject_pooler(self):
|
||||
model = self.get_model()
|
||||
wrapper = WrapperPooler(model.pooler)
|
||||
model.pooler = wrapper
|
||||
|
||||
|
||||
def retrieve_chunks(self):
|
||||
model = self.get_model()
|
||||
chunks = model.pooler.chunks
|
||||
model.pooler.chunks = []
|
||||
return chunks
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available")
|
||||
def test_pooling_chunked_prefill(vllm_runner, monkeypatch):
|
||||
"""Test chunked prefill for pooling models with LastPool."""
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
model_id = "Qwen/Qwen3-Embedding-0.6B"
|
||||
|
||||
chunk_size = 10
|
||||
|
||||
# Cap the token budget to force chunked prefill; the
|
||||
# long_prefill_token_threshold is not applied to a lone request.
|
||||
with vllm_runner(
|
||||
model_id,
|
||||
runner="pooling",
|
||||
max_num_batched_tokens=chunk_size,
|
||||
max_num_seqs=1,
|
||||
tensor_parallel_size=1,
|
||||
enforce_eager=True,
|
||||
enable_chunked_prefill=True,
|
||||
) as llm:
|
||||
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
|
||||
|
||||
tokenizer = llm.get_llm().get_tokenizer()
|
||||
tokens = tokenizer(prompt)["input_ids"]
|
||||
prompt_len = len(tokens)
|
||||
full_chunks, last_chunk = divmod(prompt_len, chunk_size)
|
||||
expected_chunks = [chunk_size] * full_chunks
|
||||
if last_chunk:
|
||||
expected_chunks.append(last_chunk)
|
||||
llm.embed([prompt])
|
||||
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
|
||||
|
||||
# Check that PoolerWrapper was called and chunks were received
|
||||
assert len(chunks) > 1
|
||||
assert chunks == expected_chunks
|
||||
|
||||
# Disable chunked prefill
|
||||
with vllm_runner(
|
||||
model_id,
|
||||
runner="pooling",
|
||||
tensor_parallel_size=1,
|
||||
enforce_eager=True,
|
||||
) as llm:
|
||||
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
|
||||
llm.embed([prompt])
|
||||
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
|
||||
|
||||
# Check that PoolerWrapper was called and no chunks were received
|
||||
assert len(chunks) == 1
|
||||
assert chunks[0] == prompt_len
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA not available")
|
||||
def test_pooling_prefix_cache(vllm_runner, monkeypatch):
|
||||
"""Test chunked prefill for pooling models with LastPool."""
|
||||
verses = prompt.split("\n\n")
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
model_id = "Qwen/Qwen3-Embedding-0.6B"
|
||||
|
||||
with vllm_runner(
|
||||
model_id,
|
||||
runner="pooling",
|
||||
enable_prefix_caching=True,
|
||||
tensor_parallel_size=1,
|
||||
enforce_eager=True,
|
||||
) as llm:
|
||||
llm.get_llm().llm_engine.collective_rpc(inject_pooler)
|
||||
tokenizer = llm.get_llm().get_tokenizer()
|
||||
|
||||
prompt1 = "\n\n".join([verses[0], verses[1]])
|
||||
prompt2 = "\n\n".join([verses[0], verses[2]])
|
||||
tokens1 = tokenizer(prompt1)["input_ids"]
|
||||
tokens2 = tokenizer(prompt2)["input_ids"]
|
||||
prompt1_len = len(tokens1)
|
||||
prompt2_len = len(tokens2)
|
||||
|
||||
llm.embed([prompt1])
|
||||
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
|
||||
|
||||
assert len(chunks) == 1
|
||||
assert chunks[0] == prompt1_len
|
||||
|
||||
llm.embed([prompt2])
|
||||
chunks = llm.get_llm().llm_engine.collective_rpc(retrieve_chunks)[0]
|
||||
|
||||
assert len(chunks) == 1
|
||||
assert chunks[0] <= prompt1_len
|
||||
assert chunks[0] < prompt2_len
|
||||
|
||||
vllm_config = llm.get_llm().llm_engine.vllm_config
|
||||
cache_config = vllm_config.cache_config
|
||||
print(f"{cache_config=}")
|
||||
# Prefixes are cached in blocks
|
||||
assert (prompt2_len - chunks[0]) % cache_config.block_size == 0
|
||||
@@ -1,118 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found, rocm_aiter_ops
|
||||
from vllm.config import CompilationConfig, CompilationMode, CUDAGraphMode
|
||||
from vllm.envs import disable_envs_cache
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ....conftest import VllmRunner
|
||||
from ....utils import (
|
||||
assert_rocm_custom_allreduce_backend_state_on_worker,
|
||||
multi_gpu_test,
|
||||
)
|
||||
|
||||
PROMPTS = ["Hello, my name is", "The capital of France is"]
|
||||
|
||||
|
||||
def _run_generation(
|
||||
vllm_runner: type[VllmRunner],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
compilation_config: CompilationConfig,
|
||||
*,
|
||||
model: str,
|
||||
max_tokens: int,
|
||||
use_aiter_custom_ar: bool,
|
||||
quick_reduce_quantization: str,
|
||||
) -> list[tuple[list[int], str]]:
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
m.setenv("VLLM_ROCM_USE_AITER", "1")
|
||||
m.setenv(
|
||||
"VLLM_ROCM_USE_AITER_CUSTOM_AR",
|
||||
"1" if use_aiter_custom_ar else "0",
|
||||
)
|
||||
m.setenv("VLLM_ROCM_QUICK_REDUCE_QUANTIZATION", quick_reduce_quantization)
|
||||
disable_envs_cache()
|
||||
rocm_aiter_ops.refresh_env_variables()
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
dtype="half",
|
||||
tensor_parallel_size=2,
|
||||
compilation_config=compilation_config,
|
||||
max_model_len=256,
|
||||
max_num_seqs=len(PROMPTS),
|
||||
gpu_memory_utilization=0.7,
|
||||
) as llm:
|
||||
llm.get_llm().collective_rpc(
|
||||
assert_rocm_custom_allreduce_backend_state_on_worker,
|
||||
args=(use_aiter_custom_ar, quick_reduce_quantization),
|
||||
)
|
||||
|
||||
return llm.generate_greedy(PROMPTS, max_tokens)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm-only")
|
||||
@pytest.mark.skipif(not is_aiter_found(), reason="AITER is not installed")
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
@pytest.mark.parametrize(
|
||||
"quick_reduce_quantization",
|
||||
[
|
||||
pytest.param("FP", id="quick-reduce-on"),
|
||||
pytest.param("NONE", id="quick-reduce-off"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode",
|
||||
[
|
||||
pytest.param(CUDAGraphMode.NONE, id="cudagraph-none"),
|
||||
pytest.param(CUDAGraphMode.FULL, id="cudagraph-full"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"model,max_tokens",
|
||||
[
|
||||
pytest.param("facebook/opt-125m", 8, id="opt-125m"),
|
||||
],
|
||||
)
|
||||
def test_rocm_aiter_custom_ar_e2e(
|
||||
vllm_runner: type[VllmRunner],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
cudagraph_mode: CUDAGraphMode,
|
||||
quick_reduce_quantization: str,
|
||||
model: str,
|
||||
max_tokens: int,
|
||||
):
|
||||
compilation_mode = (
|
||||
CompilationMode.NONE
|
||||
if cudagraph_mode == CUDAGraphMode.NONE
|
||||
else CompilationMode.VLLM_COMPILE
|
||||
)
|
||||
compilation_config = CompilationConfig(
|
||||
mode=compilation_mode,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
)
|
||||
|
||||
baseline_generations = _run_generation(
|
||||
vllm_runner,
|
||||
monkeypatch,
|
||||
compilation_config,
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
use_aiter_custom_ar=False,
|
||||
quick_reduce_quantization=quick_reduce_quantization,
|
||||
)
|
||||
aiter_custom_ar_generations = _run_generation(
|
||||
vllm_runner,
|
||||
monkeypatch,
|
||||
compilation_config,
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
use_aiter_custom_ar=True,
|
||||
quick_reduce_quantization=quick_reduce_quantization,
|
||||
)
|
||||
|
||||
assert aiter_custom_ar_generations == baseline_generations
|
||||
@@ -1,328 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Batch-sharded sampling must be a drop-in for replicated sampling.
|
||||
|
||||
The two boots are compared token for token, which is only meaningful because
|
||||
both schedule the same batches. With the engine in the caller's process every
|
||||
request is queued before the first step, so the first prefill has the same
|
||||
shape in both runs. Give the engine its own process and the comparison turns
|
||||
into a coin toss: prefill starts before the last requests arrive over IPC, so
|
||||
one boot batches two requests where the other batches one. The batch shape
|
||||
sets the GEMM reduction order and can make near-ties flip. A real sharding
|
||||
bug — rows routed to the wrong request, misaligned gathers — produces
|
||||
many-nats divergence and scrambled top-k sets."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import multi_gpu_test
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.distributed import (
|
||||
cleanup_dist_env_and_memory,
|
||||
tensor_model_parallel_all_gather,
|
||||
)
|
||||
from vllm.logprobs import Logprob, LogprobsOnePosition
|
||||
|
||||
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
GPT_OSS_MODEL = "trl-internal-testing/tiny-GptOssForCausalLM"
|
||||
GPT_OSS_REVISION = "e82685101216af1953707faa42567d232a5e4d45"
|
||||
|
||||
# Misrouted rows move logprobs by nats; anything under this is float noise.
|
||||
LOGPROB_TOL = 0.5
|
||||
|
||||
PROMPTS = [
|
||||
"The capital of France is",
|
||||
"The three primary colors are",
|
||||
"Write a haiku about the ocean.",
|
||||
"1, 1, 2, 3, 5, 8,",
|
||||
"The chemical symbol for gold is",
|
||||
"Once upon a time, in a distant kingdom,",
|
||||
"Python's GIL stands for",
|
||||
"The fastest land animal is",
|
||||
]
|
||||
|
||||
# Exercise greedy, seeded random, top-k/top-p, penalties, and logprobs.
|
||||
SAMPLING_PARAMS = [
|
||||
SamplingParams(temperature=0.0, max_tokens=32, logprobs=5, prompt_logprobs=1),
|
||||
SamplingParams(temperature=0.8, seed=42, top_p=0.9, max_tokens=32, logprobs=3),
|
||||
SamplingParams(temperature=0.7, seed=7, top_k=50, min_p=0.05, max_tokens=32),
|
||||
SamplingParams(
|
||||
temperature=0.9,
|
||||
seed=123,
|
||||
frequency_penalty=0.5,
|
||||
repetition_penalty=1.2,
|
||||
max_tokens=32,
|
||||
logprobs=2,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _is_sharded_sampling_active(worker) -> bool:
|
||||
return worker.model_runner.batch_sharder is not None
|
||||
|
||||
|
||||
def _local_logits_match_full(worker) -> dict[str, bool]:
|
||||
"""Reassemble rank-local logits and compare with the full path."""
|
||||
model = worker.model_runner.model
|
||||
hidden_size = model.config.hidden_size
|
||||
dtype = model.lm_head.weight.dtype
|
||||
hidden_states = torch.linspace(
|
||||
-1,
|
||||
1,
|
||||
steps=2 * hidden_size,
|
||||
device=worker.model_runner.device,
|
||||
dtype=dtype,
|
||||
).view(2, hidden_size)
|
||||
|
||||
full_logits = model.compute_logits(hidden_states)
|
||||
local_logits = model.compute_logits_local(hidden_states)
|
||||
assert local_logits.shape[-1] == model.lm_head.num_embeddings_per_partition
|
||||
gathered_logits = tensor_model_parallel_all_gather(local_logits)
|
||||
gathered_logits = gathered_logits[..., : model.config.vocab_size]
|
||||
|
||||
has_full_logits = full_logits is not None
|
||||
return {
|
||||
"has_full_logits": has_full_logits,
|
||||
"matches": not has_full_logits or torch.equal(full_logits, gathered_logits),
|
||||
}
|
||||
|
||||
|
||||
def _sampling_params(num_prompts: int) -> list[SamplingParams]:
|
||||
return [SAMPLING_PARAMS[i % len(SAMPLING_PARAMS)] for i in range(num_prompts)]
|
||||
|
||||
|
||||
def _generate(
|
||||
disable_sharding: bool,
|
||||
model: str,
|
||||
prompts: list[str],
|
||||
sampling_params: list[SamplingParams],
|
||||
revision: str | None,
|
||||
):
|
||||
llm = LLM(
|
||||
model=model,
|
||||
revision=revision,
|
||||
tokenizer_revision=revision,
|
||||
tensor_parallel_size=2,
|
||||
enable_batch_sharded_sampling=not disable_sharding,
|
||||
max_model_len=1024,
|
||||
# Keep capacity at least as large as the TP size. The actual request
|
||||
# count may be smaller to exercise an empty rank.
|
||||
max_num_seqs=len(PROMPTS),
|
||||
enforce_eager=True,
|
||||
enable_prefix_caching=False,
|
||||
gpu_memory_utilization=0.7,
|
||||
# Timing-based kernel selection is the dominant source of cross-boot
|
||||
# numeric noise; disable it so the comparison bounds stay tight.
|
||||
kernel_config={"enable_flashinfer_autotune": False},
|
||||
)
|
||||
try:
|
||||
# Guard against a vacuous comparison: verify every worker is in the
|
||||
# intended sampling mode.
|
||||
modes = llm.llm_engine.collective_rpc(_is_sharded_sampling_active)
|
||||
assert all(mode == (not disable_sharding) for mode in modes), modes
|
||||
if not disable_sharding:
|
||||
logits_checks = llm.llm_engine.collective_rpc(_local_logits_match_full)
|
||||
assert any(check["has_full_logits"] for check in logits_checks)
|
||||
assert all(check["matches"] for check in logits_checks)
|
||||
# The second wave reuses request slots freed by the first,
|
||||
# covering the cross-rank slot-recycling path that ownership uses.
|
||||
wave1 = llm.generate(prompts, sampling_params)
|
||||
wave2 = llm.generate(prompts[::-1], sampling_params[::-1])
|
||||
return wave1 + wave2
|
||||
finally:
|
||||
del llm
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
|
||||
def _requested_top_k(lps: LogprobsOnePosition, num_logprobs: int) -> set[int]:
|
||||
"""Exclude the extra sampled/prompt token, including at rank k+1."""
|
||||
top = {
|
||||
token_id
|
||||
for token_id, logprob in lps.items()
|
||||
if logprob.rank is not None and 1 <= logprob.rank <= num_logprobs
|
||||
}
|
||||
assert len(top) == num_logprobs, (
|
||||
f"expected {num_logprobs} ranked top-k entries, got {len(top)}"
|
||||
)
|
||||
return top
|
||||
|
||||
|
||||
def _assert_logprob_dicts_close(
|
||||
ref_lps: LogprobsOnePosition,
|
||||
out_lps: LogprobsOnePosition,
|
||||
what: str,
|
||||
num_logprobs: int,
|
||||
) -> None:
|
||||
# Allow one boundary entry of the top-k set to swap at a near-tie. Compare
|
||||
# the top-k alone: counting the sampled token would spend that allowance
|
||||
# on the extra entry itself whenever only one side carries one.
|
||||
ref_top = _requested_top_k(ref_lps, num_logprobs)
|
||||
out_top = _requested_top_k(out_lps, num_logprobs)
|
||||
shared_top = ref_top & out_top
|
||||
assert len(shared_top) >= num_logprobs - 1, (
|
||||
f"{what}: top-k token sets diverge: {sorted(ref_top)} vs {sorted(out_top)}"
|
||||
)
|
||||
# Values are comparable for every shared token, sampled one included.
|
||||
for token_id in set(ref_lps) & set(out_lps):
|
||||
diff = abs(ref_lps[token_id].logprob - out_lps[token_id].logprob)
|
||||
assert diff <= LOGPROB_TOL, (
|
||||
f"{what}[{token_id}]: logprob diff {diff} "
|
||||
f"({ref_lps[token_id].logprob} vs {out_lps[token_id].logprob})"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
("num_logprobs", "ref_ranks", "out_ranks"),
|
||||
[
|
||||
(2, {0: 1, 1: 2, 2: 3}, {0: 1, 3: 2, 2: 4}),
|
||||
(1, {0: 1, 1: 2}, {2: 1, 1: 3}),
|
||||
(2, {0: 1, 1: 2}, {0: 1, 2: 2, 1: 3}),
|
||||
(2, {0: 1, 1: 2, 2: 4}, {0: 1, 1: 2, 2: 5}),
|
||||
(0, {0: 2}, {0: 3}),
|
||||
],
|
||||
ids=["decode-boundary", "prompt-boundary", "sampled-in-top-k", "gap", "zero"],
|
||||
)
|
||||
def test_logprob_comparison_allows_sampled_token_rank_changes(
|
||||
num_logprobs: int, ref_ranks: dict[int, int], out_ranks: dict[int, int]
|
||||
):
|
||||
ref_lps, out_lps = (
|
||||
{token: Logprob(-2.0 - rank / 100, rank=rank) for token, rank in ranks.items()}
|
||||
for ranks in (ref_ranks, out_ranks)
|
||||
)
|
||||
_assert_logprob_dicts_close(ref_lps, out_lps, "boundary swap", num_logprobs)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_logprob_comparison_rejects_multiple_top_k_swaps():
|
||||
ref = {0: Logprob(-2.0, rank=1), 1: Logprob(-2.01, rank=2)}
|
||||
out = {2: Logprob(-2.0, rank=1), 3: Logprob(-2.01, rank=2)}
|
||||
with pytest.raises(AssertionError, match="top-k token sets diverge"):
|
||||
_assert_logprob_dicts_close(ref, out, "misrouted top-k", num_logprobs=2)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_logprob_comparison_checks_extra_sampled_token_value():
|
||||
ref = {0: Logprob(-1.0, rank=1), 1: Logprob(-3.0, rank=3)}
|
||||
out = {0: Logprob(-1.0, rank=1), 1: Logprob(-4.0, rank=3)}
|
||||
with pytest.raises(AssertionError, match="logprob diff"):
|
||||
_assert_logprob_dicts_close(ref, out, "sampled token", num_logprobs=1)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize("rank", [None, 2])
|
||||
def test_logprob_comparison_rejects_missing_top_k_rank(rank: int | None):
|
||||
lps = {0: Logprob(-1.0, rank=rank)}
|
||||
with pytest.raises(AssertionError, match="expected 1 ranked top-k entries"):
|
||||
_assert_logprob_dicts_close(lps, lps, "missing rank", num_logprobs=1)
|
||||
|
||||
|
||||
def _assert_outputs_match(ref_outputs, shard_outputs, params) -> None:
|
||||
assert len(ref_outputs) == len(shard_outputs) == len(params)
|
||||
divergent = []
|
||||
for i, (ref, out, sampling_params) in enumerate(
|
||||
zip(ref_outputs, shard_outputs, params)
|
||||
):
|
||||
ref_completion = ref.outputs[0]
|
||||
out_completion = out.outputs[0]
|
||||
ref_ids = list(ref_completion.token_ids)
|
||||
out_ids = list(out_completion.token_ids)
|
||||
|
||||
# Logits are only comparable at positions whose context (prompt +
|
||||
# previously sampled tokens) is identical: every position up to and
|
||||
# including the first divergence.
|
||||
prefix = 0
|
||||
while prefix < min(len(ref_ids), len(out_ids)):
|
||||
if ref_ids[prefix] != out_ids[prefix]:
|
||||
break
|
||||
prefix += 1
|
||||
if ref_ids != out_ids:
|
||||
divergent.append((i, prefix))
|
||||
|
||||
if ref_completion.logprobs is not None:
|
||||
assert out_completion.logprobs is not None
|
||||
assert sampling_params.logprobs is not None
|
||||
comparable = min(prefix + 1, len(ref_ids), len(out_ids))
|
||||
for pos in range(comparable):
|
||||
_assert_logprob_dicts_close(
|
||||
ref_completion.logprobs[pos],
|
||||
out_completion.logprobs[pos],
|
||||
f"prompt {i} logprobs[{pos}]",
|
||||
sampling_params.logprobs,
|
||||
)
|
||||
|
||||
# The prompt is fixed, so every prompt-logprob position is comparable.
|
||||
if ref.prompt_logprobs is not None:
|
||||
assert out.prompt_logprobs is not None
|
||||
assert sampling_params.prompt_logprobs is not None
|
||||
for pos, (ref_lps, out_lps) in enumerate(
|
||||
zip(ref.prompt_logprobs, out.prompt_logprobs)
|
||||
):
|
||||
if ref_lps is None or out_lps is None:
|
||||
assert ref_lps is None and out_lps is None
|
||||
continue
|
||||
_assert_logprob_dicts_close(
|
||||
ref_lps,
|
||||
out_lps,
|
||||
f"prompt {i} prompt_logprobs[{pos}]",
|
||||
sampling_params.prompt_logprobs,
|
||||
)
|
||||
|
||||
assert not divergent, (
|
||||
f"{len(divergent)}/{len(params)} completions diverged at "
|
||||
f"(prompt, position) {divergent}; the sampling modes did not agree "
|
||||
"token for token with in-process scheduling"
|
||||
)
|
||||
|
||||
|
||||
def _configure_test_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
# Required for the collective_rpc mode check below.
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
# Queue every request before the first step, so both boots schedule the
|
||||
# same batches -- see the module docstring.
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
@pytest.mark.parametrize(
|
||||
("model", "revision", "prompts"),
|
||||
[
|
||||
pytest.param(MODEL, None, PROMPTS, id="llama"),
|
||||
pytest.param(MODEL, None, PROMPTS[:1], id="llama-empty-rank"),
|
||||
pytest.param(
|
||||
GPT_OSS_MODEL,
|
||||
GPT_OSS_REVISION,
|
||||
PROMPTS,
|
||||
id="gpt-oss",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_sharded_sampling_outputs_match(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
model: str,
|
||||
revision: str | None,
|
||||
prompts: list[str],
|
||||
):
|
||||
"""Generation, logprobs, and prompt logprobs match between batch-sharded
|
||||
sampling and the replicated fallback."""
|
||||
_configure_test_environment(monkeypatch)
|
||||
sampling_params = _sampling_params(len(prompts))
|
||||
|
||||
ref_outputs = _generate(
|
||||
disable_sharding=True,
|
||||
model=model,
|
||||
prompts=prompts,
|
||||
sampling_params=sampling_params,
|
||||
revision=revision,
|
||||
)
|
||||
shard_outputs = _generate(
|
||||
disable_sharding=False,
|
||||
model=model,
|
||||
prompts=prompts,
|
||||
sampling_params=sampling_params,
|
||||
revision=revision,
|
||||
)
|
||||
|
||||
expected_params = sampling_params + sampling_params[::-1]
|
||||
_assert_outputs_match(ref_outputs, shard_outputs, expected_params)
|
||||
@@ -1,661 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""End-to-end tests for the streaming input feature in AsyncLLM.
|
||||
|
||||
These tests verify that:
|
||||
1. Streaming inputs work correctly with bunched inputs (queued)
|
||||
2. Streaming inputs work correctly with spaced out inputs
|
||||
3. Outputs are equivalent whether inputs are bunched or spaced
|
||||
4. Cancelling the output stream correctly aborts the session
|
||||
5. Closing the input stream correctly signals completion
|
||||
6. Queued inputs are cancelled when the session is aborted
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.engine.protocol import StreamingInput
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
|
||||
|
||||
# Use a small model that doesn't require authentication for fast tests
|
||||
MODEL = "facebook/opt-125m"
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(scope="module", loop_scope="module")
|
||||
async def engine():
|
||||
"""Create an AsyncLLM engine for the test.
|
||||
|
||||
Note: Using function scope because pytest_asyncio creates a new event loop
|
||||
for each test, and the output_handler task gets cancelled between tests
|
||||
with module scope.
|
||||
"""
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
|
||||
engine_args = AsyncEngineArgs(
|
||||
model=MODEL, enforce_eager=True, gpu_memory_utilization=0.7
|
||||
)
|
||||
with set_default_torch_num_threads(1):
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
try:
|
||||
yield engine
|
||||
finally:
|
||||
engine.shutdown()
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
def get_sampling_params(max_tokens: int = 20) -> SamplingParams:
|
||||
"""Create sampling params for streaming input tests."""
|
||||
return SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.DELTA,
|
||||
temperature=0.0, # Deterministic for reproducibility
|
||||
)
|
||||
|
||||
|
||||
async def collect_outputs(
|
||||
output_gen: AsyncGenerator[RequestOutput, None],
|
||||
) -> tuple[list[RequestOutput], str]:
|
||||
"""Collect all outputs from a generate call, return outputs and full text."""
|
||||
outputs: list[RequestOutput] = []
|
||||
full_text = ""
|
||||
async for output in output_gen:
|
||||
outputs.append(output)
|
||||
if output.outputs and output.outputs[0].text:
|
||||
full_text += output.outputs[0].text
|
||||
return outputs, full_text
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_bunched(engine: AsyncLLM):
|
||||
"""Test streaming input where all inputs are sent at once (bunched/queued).
|
||||
|
||||
This tests the case where multiple inputs arrive before any completes.
|
||||
The inputs should be queued and processed in sequence.
|
||||
"""
|
||||
request_id = "test_bunched"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
# Create an input generator that yields all inputs quickly
|
||||
async def bunched_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
# Send multiple inputs rapidly - they should be queued
|
||||
yield StreamingInput(prompt="Hello, my name is")
|
||||
yield StreamingInput(prompt=" Alice and I like")
|
||||
yield StreamingInput(prompt=" to code in Python")
|
||||
|
||||
outputs, full_text = await collect_outputs(
|
||||
engine.generate(
|
||||
bunched_input_generator(),
|
||||
sampling_params,
|
||||
request_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Verify we got outputs
|
||||
assert len(outputs) > 0, "Should have received outputs"
|
||||
|
||||
# Verify the final output is marked as finished
|
||||
assert outputs[-1].finished, "Last output should be marked as finished"
|
||||
|
||||
# Verify intermediate outputs are not marked as finished
|
||||
for output in outputs[:-1]:
|
||||
assert not output.finished, "Intermediate outputs should not be finished"
|
||||
|
||||
# Verify we generated some text
|
||||
assert len(full_text) > 0, "Should have generated text"
|
||||
print(f"Bunched test generated: {full_text}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_spaced(engine: AsyncLLM):
|
||||
"""Test streaming input where inputs are spaced out.
|
||||
|
||||
This tests the case where each input completes processing before the
|
||||
next one is sent. Each chunk should be prefilled, generate tokens,
|
||||
then the next chunk should be processed.
|
||||
"""
|
||||
request_id = "test_spaced"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
# Track when each input is sent
|
||||
input_times: list[float] = []
|
||||
outputs_per_chunk: list[int] = [0, 0, 0]
|
||||
current_chunk = 0
|
||||
|
||||
async def spaced_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
nonlocal current_chunk
|
||||
import time
|
||||
|
||||
# First input
|
||||
input_times.append(time.time())
|
||||
yield StreamingInput(prompt="Hello, my name is")
|
||||
current_chunk = 0
|
||||
|
||||
# Wait for some outputs to be generated
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Second input
|
||||
input_times.append(time.time())
|
||||
current_chunk = 1
|
||||
yield StreamingInput(prompt=" Alice and I like")
|
||||
|
||||
# Wait for some outputs
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Third input
|
||||
input_times.append(time.time())
|
||||
current_chunk = 2
|
||||
yield StreamingInput(prompt=" to code in Python")
|
||||
|
||||
outputs: list[RequestOutput] = []
|
||||
full_text = ""
|
||||
|
||||
async for output in engine.generate(
|
||||
spaced_input_generator(),
|
||||
sampling_params,
|
||||
request_id,
|
||||
):
|
||||
outputs.append(output)
|
||||
if output.outputs and output.outputs[0].text:
|
||||
full_text += output.outputs[0].text
|
||||
outputs_per_chunk[current_chunk] += 1
|
||||
|
||||
# Verify we got outputs
|
||||
assert len(outputs) > 0, "Should have received outputs"
|
||||
|
||||
# Verify the final output is marked as finished
|
||||
assert outputs[-1].finished, "Last output should be marked as finished"
|
||||
|
||||
# Verify we received outputs from multiple chunks
|
||||
# (with spaced inputs, we should see outputs distributed across chunks)
|
||||
chunks_with_outputs = sum(1 for c in outputs_per_chunk if c > 0)
|
||||
assert chunks_with_outputs >= 1, "Should have outputs from at least one chunk"
|
||||
|
||||
print(f"Spaced test generated: {full_text}")
|
||||
print(f"Outputs per chunk: {outputs_per_chunk}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_output_equivalence(engine: AsyncLLM):
|
||||
"""Test that bunched and spaced inputs produce equivalent outputs.
|
||||
|
||||
When the same prompts are provided either bunched or spaced,
|
||||
the final concatenated output should be the same (with deterministic
|
||||
sampling).
|
||||
"""
|
||||
prompts = ["Hello, my name is", " Bob and I work", " at Anthropic"]
|
||||
sampling_params = get_sampling_params(max_tokens=15)
|
||||
|
||||
# Test bunched inputs
|
||||
async def bunched_gen() -> AsyncGenerator[StreamingInput, None]:
|
||||
for prompt in prompts:
|
||||
yield StreamingInput(prompt=prompt)
|
||||
|
||||
_, bunched_text = await collect_outputs(
|
||||
engine.generate(bunched_gen(), sampling_params, "equiv_bunched")
|
||||
)
|
||||
|
||||
# Test spaced inputs (same prompts, but with delays)
|
||||
async def spaced_gen() -> AsyncGenerator[StreamingInput, None]:
|
||||
for prompt in prompts:
|
||||
yield StreamingInput(prompt=prompt)
|
||||
await asyncio.sleep(0.3)
|
||||
|
||||
_, spaced_text = await collect_outputs(
|
||||
engine.generate(spaced_gen(), sampling_params, "equiv_spaced")
|
||||
)
|
||||
|
||||
# Both should produce the same output since we use temperature=0
|
||||
assert bunched_text == spaced_text, (
|
||||
f"Bunched and spaced should produce same output.\n"
|
||||
f"Bunched: {bunched_text!r}\n"
|
||||
f"Spaced: {spaced_text!r}"
|
||||
)
|
||||
|
||||
print(f"Equivalence test passed. Generated: {bunched_text}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_cancel_output_stream(engine: AsyncLLM):
|
||||
"""Test that cancelling the output stream aborts the entire session.
|
||||
|
||||
When the consumer cancels iteration over the output generator,
|
||||
the session should be aborted including any queued inputs.
|
||||
"""
|
||||
request_id = "test_cancel_output"
|
||||
sampling_params = get_sampling_params(max_tokens=1000)
|
||||
|
||||
input_completed = asyncio.Event()
|
||||
input_task_cancelled = False
|
||||
|
||||
async def slow_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
nonlocal input_task_cancelled
|
||||
try:
|
||||
yield StreamingInput(prompt="Tell me a very long story about")
|
||||
yield StreamingInput(prompt=" a dragon and a knight")
|
||||
|
||||
# This should be cancelled before we get here
|
||||
await asyncio.sleep(10)
|
||||
yield StreamingInput(prompt=" who become friends")
|
||||
input_completed.set()
|
||||
except asyncio.CancelledError:
|
||||
input_task_cancelled = True
|
||||
raise
|
||||
|
||||
outputs_received = 0
|
||||
output_gen = engine.generate(slow_input_generator(), sampling_params, request_id)
|
||||
|
||||
# Collect a few outputs then cancel
|
||||
try:
|
||||
async for output in output_gen:
|
||||
outputs_received += 1
|
||||
if outputs_received >= 5:
|
||||
# Cancel by breaking out of the loop (generator will be GC'd)
|
||||
break
|
||||
finally:
|
||||
# Explicitly close the generator to ensure cleanup
|
||||
await output_gen.aclose()
|
||||
|
||||
# Give time for cleanup
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Verify we got some outputs before cancelling
|
||||
assert outputs_received >= 5, "Should have received outputs before cancel"
|
||||
|
||||
# Verify the input task was cancelled
|
||||
assert input_task_cancelled, "Input task should have been cancelled"
|
||||
|
||||
# Verify the session is properly cleaned up
|
||||
assert not engine.output_processor.has_unfinished_requests(), (
|
||||
"Should have no unfinished requests after cancel"
|
||||
)
|
||||
|
||||
print(f"Cancel test passed. Received {outputs_received} outputs before cancel")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_close_signals_completion(engine: AsyncLLM):
|
||||
"""Test that closing the input stream signals completion.
|
||||
|
||||
When the input generator finishes (naturally or via return),
|
||||
the session should complete with finished=True on the last output.
|
||||
"""
|
||||
request_id = "test_close_completion"
|
||||
sampling_params = get_sampling_params(max_tokens=15)
|
||||
|
||||
input_generator_finished = False
|
||||
|
||||
async def limited_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
nonlocal input_generator_finished
|
||||
yield StreamingInput(prompt="What is 2 + 2? The answer is")
|
||||
# Generator finishes naturally here
|
||||
input_generator_finished = True
|
||||
|
||||
outputs, _ = await collect_outputs(
|
||||
engine.generate(limited_input_generator(), sampling_params, request_id)
|
||||
)
|
||||
|
||||
# Verify the input generator completed
|
||||
assert input_generator_finished, "Input generator should have finished"
|
||||
|
||||
# Verify we got a finished output
|
||||
assert len(outputs) > 0, "Should have received outputs"
|
||||
assert outputs[-1].finished, "Last output should be marked as finished"
|
||||
|
||||
# Verify the session is cleaned up
|
||||
assert not engine.output_processor.has_unfinished_requests(), (
|
||||
"Should have no unfinished requests"
|
||||
)
|
||||
|
||||
print("Close completion test passed")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_abort_queued_inputs(engine: AsyncLLM):
|
||||
"""Test that aborting the session cancels queued inputs.
|
||||
|
||||
When multiple inputs are queued and the session is aborted,
|
||||
all pending inputs should be cancelled.
|
||||
"""
|
||||
request_id = "test_abort_queued"
|
||||
# Use large max_tokens to ensure we have time to queue inputs
|
||||
sampling_params = get_sampling_params(max_tokens=2000)
|
||||
|
||||
inputs_sent = 0
|
||||
input_cancelled = False
|
||||
|
||||
async def many_inputs_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
nonlocal inputs_sent, input_cancelled
|
||||
try:
|
||||
# Send several inputs to fill the queue
|
||||
for i in range(10):
|
||||
yield StreamingInput(prompt=f" Part {i}: Tell me about the number {i}.")
|
||||
inputs_sent += 1
|
||||
# Small delay to interleave with output processing
|
||||
await asyncio.sleep(0.05)
|
||||
except asyncio.CancelledError:
|
||||
input_cancelled = True
|
||||
raise
|
||||
|
||||
outputs_received = 0
|
||||
output_gen = engine.generate(many_inputs_generator(), sampling_params, request_id)
|
||||
|
||||
try:
|
||||
async for output in output_gen:
|
||||
outputs_received += 1
|
||||
# Cancel after receiving some outputs
|
||||
if outputs_received >= 10:
|
||||
break
|
||||
finally:
|
||||
await output_gen.aclose()
|
||||
|
||||
# Give time for cleanup
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
# Verify we received some outputs
|
||||
assert outputs_received >= 10, "Should have received outputs before abort"
|
||||
|
||||
# Verify the input generator was cancelled OR finished naturally
|
||||
# (it might finish naturally if all inputs were sent before cancel)
|
||||
assert input_cancelled or inputs_sent == 10, (
|
||||
f"Input generator should have been cancelled or completed. "
|
||||
f"cancelled={input_cancelled}, inputs_sent={inputs_sent}"
|
||||
)
|
||||
|
||||
# Verify the session is cleaned up
|
||||
assert not engine.output_processor.has_unfinished_requests(), (
|
||||
"Should have no unfinished requests after abort"
|
||||
)
|
||||
|
||||
print(
|
||||
f"Abort queued test passed. Sent {inputs_sent} inputs, "
|
||||
f"received {outputs_received} outputs"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_error_propagation(engine: AsyncLLM):
|
||||
"""Test that errors in the input generator are propagated to the caller."""
|
||||
request_id = "test_error_propagation"
|
||||
sampling_params = get_sampling_params(max_tokens=20)
|
||||
|
||||
class InputError(Exception):
|
||||
pass
|
||||
|
||||
async def error_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
yield StreamingInput(prompt="Start with this")
|
||||
await asyncio.sleep(0.1)
|
||||
raise InputError("Simulated input error")
|
||||
|
||||
# Note: The current implementation catches exceptions and puts them
|
||||
# in the queue, so we should get the error when iterating outputs
|
||||
with pytest.raises(InputError, match="Simulated input error"):
|
||||
async for _ in engine.generate(
|
||||
error_input_generator(), sampling_params, request_id
|
||||
):
|
||||
pass
|
||||
|
||||
# Give time for cleanup
|
||||
await asyncio.sleep(0.3)
|
||||
|
||||
# Verify the session is cleaned up
|
||||
assert not engine.output_processor.has_unfinished_requests(), (
|
||||
"Should have no unfinished requests after error"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_multiple_concurrent_sessions(engine: AsyncLLM):
|
||||
"""Test multiple concurrent streaming input sessions.
|
||||
|
||||
Multiple streaming sessions should be able to run concurrently
|
||||
without interfering with each other.
|
||||
"""
|
||||
num_sessions = 3
|
||||
results: list[tuple[str, str]] = []
|
||||
|
||||
async def run_session(session_id: int) -> tuple[str, str]:
|
||||
request_id = f"test_concurrent_{session_id}"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
prompts = [f"Session {session_id}: Hello", f" world from session {session_id}"]
|
||||
|
||||
async def input_gen() -> AsyncGenerator[StreamingInput, None]:
|
||||
for prompt in prompts:
|
||||
yield StreamingInput(prompt=prompt)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
_, text = await collect_outputs(
|
||||
engine.generate(input_gen(), sampling_params, request_id)
|
||||
)
|
||||
return request_id, text
|
||||
|
||||
# Run sessions concurrently
|
||||
tasks = [asyncio.create_task(run_session(i)) for i in range(num_sessions)]
|
||||
results = await asyncio.gather(*tasks)
|
||||
|
||||
# Verify all sessions completed
|
||||
assert len(results) == num_sessions
|
||||
|
||||
for request_id, text in results:
|
||||
assert len(text) > 0, f"Session {request_id} should have generated text"
|
||||
print(f"{request_id}: {text}")
|
||||
|
||||
# Verify cleanup
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_per_chunk_sampling_params(engine: AsyncLLM):
|
||||
"""Test that per-chunk sampling params are respected.
|
||||
|
||||
Each StreamingInput can have its own sampling_params.
|
||||
"""
|
||||
request_id = "test_per_chunk_params"
|
||||
base_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
async def variable_params_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
# First chunk with base params
|
||||
yield StreamingInput(prompt="Count to five:", sampling_params=base_params)
|
||||
|
||||
# Second chunk with different max_tokens
|
||||
chunk_params = get_sampling_params(max_tokens=5)
|
||||
yield StreamingInput(
|
||||
prompt=" Now count backwards:", sampling_params=chunk_params
|
||||
)
|
||||
|
||||
outputs, full_text = await collect_outputs(
|
||||
engine.generate(variable_params_generator(), base_params, request_id)
|
||||
)
|
||||
|
||||
assert len(outputs) > 0, "Should have received outputs"
|
||||
assert outputs[-1].finished, "Last output should be finished"
|
||||
assert len(full_text) > 0, "Should have generated text"
|
||||
|
||||
print(f"Per-chunk params test generated: {full_text}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_empty_generator(engine: AsyncLLM):
|
||||
"""Test behavior when the input generator yields nothing.
|
||||
|
||||
An empty generator should finish without producing output.
|
||||
"""
|
||||
request_id = "test_empty_generator"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
async def empty_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
# Don't yield anything
|
||||
return
|
||||
yield # Make it a generator
|
||||
|
||||
outputs: list[RequestOutput] = []
|
||||
async for output in engine.generate(empty_generator(), sampling_params, request_id):
|
||||
outputs.append(output)
|
||||
|
||||
assert outputs == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_single_chunk(engine: AsyncLLM):
|
||||
"""Test streaming input with a single chunk.
|
||||
|
||||
This is effectively the same as a regular non-streaming request,
|
||||
but using the streaming input API.
|
||||
"""
|
||||
request_id = "test_single_chunk"
|
||||
sampling_params = get_sampling_params(max_tokens=15)
|
||||
|
||||
async def single_chunk_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
yield StreamingInput(prompt="What color is the sky? The sky is")
|
||||
|
||||
outputs, full_text = await collect_outputs(
|
||||
engine.generate(single_chunk_generator(), sampling_params, request_id)
|
||||
)
|
||||
|
||||
assert len(outputs) > 0
|
||||
assert outputs[-1].finished
|
||||
assert "blue" in full_text.lower() or len(full_text) > 0
|
||||
|
||||
print(f"Single chunk test generated: {full_text}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_reuse_request_id(engine: AsyncLLM):
|
||||
"""Test that request IDs can be reused after a session completes."""
|
||||
request_id = "test_reuse_id"
|
||||
sampling_params = get_sampling_params(max_tokens=5)
|
||||
|
||||
# First session
|
||||
async def gen1() -> AsyncGenerator[StreamingInput, None]:
|
||||
yield StreamingInput(prompt="First session")
|
||||
|
||||
_, text1 = await collect_outputs(
|
||||
engine.generate(gen1(), sampling_params, request_id)
|
||||
)
|
||||
|
||||
# Second session with same ID
|
||||
async def gen2() -> AsyncGenerator[StreamingInput, None]:
|
||||
yield StreamingInput(prompt="Second session")
|
||||
|
||||
_, text2 = await collect_outputs(
|
||||
engine.generate(gen2(), sampling_params, request_id)
|
||||
)
|
||||
|
||||
assert len(text1) > 0
|
||||
assert len(text2) > 0
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
print(f"Reuse ID test: session 1: {text1}, session 2: {text2}")
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_validation_errors(engine: AsyncLLM):
|
||||
"""Test that invalid configurations raise appropriate errors."""
|
||||
|
||||
async def dummy_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
yield StreamingInput(prompt="test")
|
||||
|
||||
# Test n > 1 is rejected
|
||||
with pytest.raises(
|
||||
VLLMValidationError, match="Input streaming not currently supported"
|
||||
):
|
||||
params_n2 = SamplingParams(max_tokens=10, n=2)
|
||||
async for _ in engine.generate(dummy_generator(), params_n2, "test_n2"):
|
||||
pass
|
||||
|
||||
# Test FINAL_ONLY is rejected
|
||||
with pytest.raises(
|
||||
VLLMValidationError, match="Input streaming not currently supported"
|
||||
):
|
||||
params_final = SamplingParams(
|
||||
max_tokens=10, output_kind=RequestOutputKind.FINAL_ONLY
|
||||
)
|
||||
async for _ in engine.generate(dummy_generator(), params_final, "test_final"):
|
||||
pass
|
||||
|
||||
# Test stop strings are rejected
|
||||
with pytest.raises(
|
||||
VLLMValidationError, match="Input streaming not currently supported"
|
||||
):
|
||||
params_stop = SamplingParams(max_tokens=10, stop=["stop"])
|
||||
async for _ in engine.generate(dummy_generator(), params_stop, "test_stop"):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
async def test_streaming_input_delayed_generator_exit(engine: AsyncLLM):
|
||||
"""Test that output generator exits when input generator closes after outputs.
|
||||
|
||||
This tests the case where:
|
||||
1. Multiple inputs are sent and fully processed
|
||||
2. The engine has finished
|
||||
3. The input generator doesn't exit until after the engine finishes
|
||||
4. The output generator should exit properly once the input generator exits
|
||||
"""
|
||||
request_id = "test_delayed_exit"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
|
||||
engine_finished_event = asyncio.Event()
|
||||
input_generator_exited = False
|
||||
finish_count = 0
|
||||
|
||||
async def delayed_exit_input_generator() -> AsyncGenerator[StreamingInput, None]:
|
||||
nonlocal input_generator_exited
|
||||
# Send all inputs immediately
|
||||
yield StreamingInput(prompt="Hello, my name is")
|
||||
yield StreamingInput(prompt=" Alice")
|
||||
|
||||
# Wait until the engine has finished generating before exiting
|
||||
await engine_finished_event.wait()
|
||||
|
||||
# Add a small delay to ensure we're testing the "delayed exit" case
|
||||
await asyncio.sleep(0.1)
|
||||
input_generator_exited = True
|
||||
|
||||
outputs: list[RequestOutput] = []
|
||||
full_text = ""
|
||||
|
||||
async for output in engine.generate(
|
||||
delayed_exit_input_generator(), sampling_params, request_id
|
||||
):
|
||||
outputs.append(output)
|
||||
if output.outputs and output.outputs[0].text:
|
||||
full_text += output.outputs[0].text
|
||||
|
||||
# Signal when the engine finishes both input chunks (each gets a finish_reason)
|
||||
# Note: output.finished will be False while input stream is open
|
||||
if output.outputs and output.outputs[0].finish_reason is not None:
|
||||
finish_count += 1
|
||||
if finish_count == 2:
|
||||
engine_finished_event.set()
|
||||
|
||||
# Verify the input generator exited properly
|
||||
assert input_generator_exited, (
|
||||
"Input generator should have exited after engine finished"
|
||||
)
|
||||
|
||||
# Verify we got outputs
|
||||
assert len(outputs) > 0, "Should have received outputs"
|
||||
|
||||
# Verify we generated some text
|
||||
assert len(full_text) > 0, "Should have generated text"
|
||||
|
||||
# Verify the session is cleaned up
|
||||
assert not engine.output_processor.has_unfinished_requests(), (
|
||||
"Should have no unfinished requests"
|
||||
)
|
||||
|
||||
print(f"Delayed exit test passed. Generated: {full_text}")
|
||||
@@ -1,156 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.evals.gsm8k.gsm8k_eval import evaluate_gsm8k_offline
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ...utils import compute_acceptance_len, compute_acceptance_rate
|
||||
|
||||
REGRESSION_TOLERANCE = 0.95
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DSparkCorrectnessConfig:
|
||||
model: str
|
||||
draft_model: str
|
||||
reference_accuracy: float
|
||||
reference_acceptance_rate: float
|
||||
reference_acceptance_len: float
|
||||
num_speculative_tokens: int = 7
|
||||
max_model_len: int = 4096
|
||||
max_num_seqs: int | None = None
|
||||
num_questions: int = 1319
|
||||
max_tokens: int = 256
|
||||
use_chat_completions: bool = False
|
||||
chat_template_kwargs: dict[str, object] | None = None
|
||||
attention_backend: str | None = None
|
||||
gpu_memory_utilization: float = 0.92
|
||||
enforce_eager: bool = False
|
||||
disable_flashinfer_sampler: bool = False
|
||||
language_model_only: bool = False
|
||||
|
||||
|
||||
# References from 12 full GSM8K runs at temperature 1.0: accuracy 0.782-0.814,
|
||||
# acceptance rate 0.418-0.434, acceptance length 3.928-4.037.
|
||||
QWEN3_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
|
||||
model="Qwen/Qwen3-4B-FP8",
|
||||
draft_model="deepseek-ai/dspark_qwen3_4b_block7",
|
||||
reference_accuracy=0.801,
|
||||
reference_acceptance_rate=0.428,
|
||||
reference_acceptance_len=3.994,
|
||||
attention_backend="FLASH_ATTN",
|
||||
)
|
||||
|
||||
# References from five 200-question runs at temperature 1.0: accuracy
|
||||
# 0.900-0.955, acceptance rate 0.578-0.595, acceptance length 5.044-5.167.
|
||||
GEMMA4_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
|
||||
model="RedHatAI/gemma-4-12B-it-NVFP4",
|
||||
draft_model="deepseek-ai/dspark_gemma4_12b_block7",
|
||||
reference_accuracy=0.92,
|
||||
reference_acceptance_rate=0.58,
|
||||
reference_acceptance_len=5.0,
|
||||
max_num_seqs=32,
|
||||
num_questions=200,
|
||||
use_chat_completions=True,
|
||||
gpu_memory_utilization=0.85,
|
||||
enforce_eager=True,
|
||||
disable_flashinfer_sampler=True,
|
||||
language_model_only=True,
|
||||
)
|
||||
|
||||
# Reference from 200 GSM8K questions at temperature 1.0.
|
||||
QWEN3_6_DSPARK_SPECULATORS = DSparkCorrectnessConfig(
|
||||
model="RedHatAI/Qwen3.6-35B-A3B-NVFP4",
|
||||
draft_model="RedHatAI/Qwen3.6-35B-A3B-speculator.dspark",
|
||||
reference_accuracy=0.85,
|
||||
reference_acceptance_rate=0.41,
|
||||
reference_acceptance_len=4.25,
|
||||
num_speculative_tokens=8,
|
||||
max_num_seqs=32,
|
||||
num_questions=200,
|
||||
use_chat_completions=True,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
gpu_memory_utilization=0.85,
|
||||
language_model_only=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config",
|
||||
[
|
||||
pytest.param(QWEN3_DSPARK_DEEPSPEC, id="qwen3-deepspec"),
|
||||
pytest.param(GEMMA4_DSPARK_DEEPSPEC, id="gemma4-deepspec"),
|
||||
pytest.param(QWEN3_6_DSPARK_SPECULATORS, id="qwen3.6-speculators"),
|
||||
],
|
||||
)
|
||||
def test_dspark_correctness_and_acceptance_rate(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config: DSparkCorrectnessConfig,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Guard GSM8K accuracy and acceptance metrics for DSpark models."""
|
||||
if config.disable_flashinfer_sampler:
|
||||
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
||||
|
||||
speculative_config = {
|
||||
"method": "dspark",
|
||||
"model": config.draft_model,
|
||||
"num_speculative_tokens": config.num_speculative_tokens,
|
||||
"draft_sample_method": "probabilistic",
|
||||
}
|
||||
if config.attention_backend is not None and current_platform.is_cuda():
|
||||
speculative_config["attention_backend"] = config.attention_backend
|
||||
|
||||
runner_config = {
|
||||
"block_size": None,
|
||||
"trust_remote_code": True,
|
||||
"speculative_config": speculative_config,
|
||||
"max_model_len": config.max_model_len,
|
||||
"gpu_memory_utilization": config.gpu_memory_utilization,
|
||||
"enforce_eager": config.enforce_eager,
|
||||
"enable_chunked_prefill": None,
|
||||
"enable_prefix_caching": False,
|
||||
"disable_log_stats": False,
|
||||
"compilation_config": CompilationConfig(),
|
||||
}
|
||||
if config.max_num_seqs is not None:
|
||||
runner_config["max_num_seqs"] = config.max_num_seqs
|
||||
if config.language_model_only:
|
||||
runner_config["language_model_only"] = True
|
||||
|
||||
with vllm_runner(config.model, **runner_config) as spec_runner:
|
||||
spec_llm = spec_runner.llm
|
||||
results = evaluate_gsm8k_offline(
|
||||
spec_llm,
|
||||
num_questions=config.num_questions,
|
||||
max_tokens=config.max_tokens,
|
||||
temperature=1.0,
|
||||
use_chat_completions=config.use_chat_completions,
|
||||
chat_template_kwargs=config.chat_template_kwargs,
|
||||
)
|
||||
accuracy = results["accuracy"]
|
||||
metrics = spec_llm.get_metrics()
|
||||
acceptance_rate = compute_acceptance_rate(metrics)
|
||||
acceptance_len = compute_acceptance_len(metrics)
|
||||
context = f"DSpark target={config.model}, draft={config.draft_model}"
|
||||
metrics_summary = (
|
||||
f"gsm8k_accuracy={accuracy:.3f}, "
|
||||
f"acceptance_rate={acceptance_rate:.3f}, "
|
||||
f"acceptance_len={acceptance_len:.3f}"
|
||||
)
|
||||
print(f"{context}: {metrics_summary}")
|
||||
|
||||
assert accuracy >= config.reference_accuracy * REGRESSION_TOLERANCE, (
|
||||
f"{context}: {metrics_summary}"
|
||||
)
|
||||
assert (
|
||||
acceptance_rate >= config.reference_acceptance_rate * REGRESSION_TOLERANCE
|
||||
), f"{context}: {metrics_summary}"
|
||||
assert (
|
||||
acceptance_len >= config.reference_acceptance_len * REGRESSION_TOLERANCE
|
||||
), f"{context}: {metrics_summary}"
|
||||
@@ -1,56 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
|
||||
from ...utils import compute_acceptance_len, get_test_prompts
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_synthetic_acceptance_rate(vllm_runner):
|
||||
"""Verify that synthetic rejection sampling produces an acceptance
|
||||
length close to the requested mean acceptance length."""
|
||||
num_spec_tokens = 3
|
||||
expected_acceptance_len = 1.875
|
||||
tolerance = 0.15
|
||||
|
||||
with vllm_runner(
|
||||
"meta-llama/Llama-3.2-1B-Instruct",
|
||||
block_size=None,
|
||||
trust_remote_code=True,
|
||||
speculative_config={
|
||||
"method": "eagle3",
|
||||
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
|
||||
"num_speculative_tokens": num_spec_tokens,
|
||||
"max_model_len": 2048,
|
||||
"rejection_sample_method": "synthetic",
|
||||
"synthetic_acceptance_length": expected_acceptance_len,
|
||||
},
|
||||
max_model_len=2048,
|
||||
enforce_eager=True,
|
||||
enable_chunked_prefill=None,
|
||||
disable_log_stats=False,
|
||||
compilation_config=CompilationConfig(),
|
||||
) as spec_runner:
|
||||
spec_llm = spec_runner.llm
|
||||
|
||||
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=50)
|
||||
spec_llm.chat(
|
||||
test_prompts,
|
||||
SamplingParams(temperature=0, max_tokens=64, ignore_eos=True),
|
||||
)
|
||||
|
||||
metrics = spec_llm.get_metrics()
|
||||
acceptance_len = compute_acceptance_len(metrics)
|
||||
|
||||
print(
|
||||
f"Synthetic acceptance length: {acceptance_len:.3f}"
|
||||
f" (expected={expected_acceptance_len:.3f},"
|
||||
f" tolerance=±{tolerance})"
|
||||
)
|
||||
assert abs(acceptance_len - expected_acceptance_len) <= tolerance, (
|
||||
f"Synthetic acceptance length {acceptance_len:.3f} is not within"
|
||||
f" ±{tolerance} of expected {expected_acceptance_len:.3f}"
|
||||
)
|
||||
@@ -1,102 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
|
||||
from ..utils import compute_acceptance_len
|
||||
|
||||
|
||||
def load_and_process_dataset(data_name: str):
|
||||
from datasets import load_dataset
|
||||
|
||||
if data_name == "gsm8k":
|
||||
dataset = load_dataset("openai/gsm8k", "main", split="test")
|
||||
prompt_fmt = (
|
||||
"{question}\nPlease reason step by step,"
|
||||
" and put your final answer within \\boxed{{}}."
|
||||
)
|
||||
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
|
||||
elif data_name == "mt-bench":
|
||||
dataset = load_dataset("HuggingFaceH4/mt_bench_prompts", split="train")
|
||||
dataset = dataset.map(lambda x: {"turns": x["prompt"]})
|
||||
elif data_name == "humaneval":
|
||||
dataset = load_dataset("openai/openai_humaneval", split="test")
|
||||
prompt_fmt = (
|
||||
"Write a solution to the following problem and make sure"
|
||||
" that it passes the tests:\n```python\n{prompt}\n```"
|
||||
)
|
||||
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
|
||||
|
||||
return dataset
|
||||
|
||||
|
||||
def run_acceptance_length_eval(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
vllm_runner,
|
||||
spec_config: dict[str, Any],
|
||||
expected_acceptance_lengths: dict[str, float],
|
||||
chat_template_kwargs: dict[str, Any],
|
||||
use_mrv2: bool,
|
||||
):
|
||||
"""E2E acceptance-rate validation for speculative decoding.
|
||||
|
||||
Drives one or more datasets (keyed in ``expected_acceptance_lengths``)
|
||||
through the spec decode engine and asserts the mean acceptance length
|
||||
stays within tolerance of the reference figure for each dataset.
|
||||
"""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if use_mrv2 else "0")
|
||||
runner_config = spec_config.copy()
|
||||
model = runner_config.pop("model")
|
||||
runner_config.setdefault("block_size", None)
|
||||
runner_config.setdefault("enable_chunked_prefill", None)
|
||||
runner_config.setdefault("compilation_config", CompilationConfig())
|
||||
with vllm_runner(model, **runner_config) as spec_runner:
|
||||
spec_llm = spec_runner.llm
|
||||
# MT-Bench has 80 prompts and HumanEval has 164; truncate GSM8K.
|
||||
max_prompts_per_dataset = 200
|
||||
|
||||
tokenizer = spec_llm.get_tokenizer()
|
||||
for dataset_name, expected_len in expected_acceptance_lengths.items():
|
||||
dataset = load_and_process_dataset(dataset_name)
|
||||
prev_metrics = None
|
||||
acceptance_lengths = []
|
||||
for i in range(min(max_prompts_per_dataset, len(dataset))):
|
||||
user_content = dataset[i]["turns"][0]
|
||||
prompt_text = tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": user_content}],
|
||||
tokenize=False,
|
||||
add_generation_prompt=True,
|
||||
**chat_template_kwargs,
|
||||
)
|
||||
|
||||
# Greedy (temp=0) so acceptance length is deterministic and comparable
|
||||
# across runs.
|
||||
spec_llm.generate(
|
||||
[prompt_text],
|
||||
SamplingParams(temperature=0, max_tokens=2048),
|
||||
use_tqdm=False,
|
||||
)
|
||||
current_metrics = spec_llm.get_metrics()
|
||||
acceptance_len = compute_acceptance_len(current_metrics, prev_metrics)
|
||||
prev_metrics = current_metrics
|
||||
acceptance_lengths.append(acceptance_len)
|
||||
|
||||
mean_acceptance_length = sum(acceptance_lengths) / len(acceptance_lengths)
|
||||
# Fairly tight tolerance of 95% against the reference figures,
|
||||
# watching for regressions. Can be relaxed if test is flaky but be sure to
|
||||
# check for genuine issues such as #40727.
|
||||
expected_len = expected_len * 0.95
|
||||
print(
|
||||
f"acceptance_len for {dataset_name}: {mean_acceptance_length:.2f}"
|
||||
f" (expected at least {expected_len:.2f})"
|
||||
)
|
||||
|
||||
assert mean_acceptance_length >= expected_len, (
|
||||
f"acceptance_len for {dataset_name} is below expected threshold: "
|
||||
f"{mean_acceptance_length:.2f} < {expected_len:.2f}"
|
||||
)
|
||||
@@ -1,96 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for sync-free speculative decoding with async scheduling."""
|
||||
|
||||
import pytest
|
||||
|
||||
# Test configurations: (model, spec_model, method, num_spec_tokens, backend_env)
|
||||
SPEC_DECODE_CONFIGS = [
|
||||
pytest.param(
|
||||
"meta-llama/Llama-3.2-1B-Instruct",
|
||||
"nm-testing/Llama3_2_1B_speculator.eagle3",
|
||||
"eagle3",
|
||||
2,
|
||||
id="eagle3-llama",
|
||||
),
|
||||
pytest.param(
|
||||
"eagle618/deepseek-v3-random",
|
||||
"eagle618/eagle-deepseek-v3-random",
|
||||
"eagle",
|
||||
2,
|
||||
id="eagle-mla-deepseek",
|
||||
),
|
||||
pytest.param(
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
"mtp",
|
||||
1,
|
||||
id="mtp-qwen3_5-hybrid",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model,spec_model,method,num_spec_tokens",
|
||||
SPEC_DECODE_CONFIGS,
|
||||
)
|
||||
def test_no_sync_with_spec_decode(
|
||||
model: str,
|
||||
spec_model: str,
|
||||
method: str,
|
||||
num_spec_tokens: int,
|
||||
monkeypatch,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Test generation while the worker rejects unintended GPU-CPU syncs."""
|
||||
monkeypatch.setenv("VLLM_GPU_SYNC_CHECK", "error")
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
|
||||
# Qwen3.5 is a VLM; without this, profile_run runs the ViT warmup
|
||||
# and peaks well above the 18GB MIG slice used by one of the CI lanes.
|
||||
# This test only exercises text generation, so the vision tower is
|
||||
# never needed.
|
||||
extra_kwargs: dict = {}
|
||||
if "Qwen3.5" in model:
|
||||
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
|
||||
|
||||
with vllm_runner(
|
||||
model,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
max_model_len=256,
|
||||
speculative_config={
|
||||
"method": method,
|
||||
"num_speculative_tokens": num_spec_tokens,
|
||||
"model": spec_model,
|
||||
},
|
||||
enforce_eager=True,
|
||||
async_scheduling=True,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**extra_kwargs,
|
||||
) as runner:
|
||||
llm = runner.llm
|
||||
|
||||
# Assert async scheduling is actually active before running inference.
|
||||
assert llm.llm_engine.vllm_config.scheduler_config.async_scheduling, (
|
||||
f"Expected async_scheduling=True for spec decode, got False. "
|
||||
f"method={method}, target={model}, draft={spec_model}"
|
||||
)
|
||||
|
||||
outputs = llm.generate(
|
||||
["Hello, my name is"],
|
||||
SamplingParams(temperature=0, max_tokens=10),
|
||||
)
|
||||
|
||||
assert len(outputs) == 1, (
|
||||
f"{method} target={model}: expected one request output, got {len(outputs)}"
|
||||
)
|
||||
assert outputs[0].outputs, (
|
||||
f"{method} target={model}: request output has no completion candidates"
|
||||
)
|
||||
assert outputs[0].outputs[0].text, (
|
||||
f"{method} target={model}: generated completion text is empty"
|
||||
)
|
||||
@@ -1,423 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import multi_gpu_only, single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig, VllmConfig, replace
|
||||
from vllm.config.kernel import MoEBackend
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.spec_decode.draft_model import DraftModelProposer
|
||||
|
||||
from ..utils import (
|
||||
Messages,
|
||||
compute_acceptance_len,
|
||||
compute_acceptance_rate,
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_instruct_coder_messages,
|
||||
get_test_prompts,
|
||||
greedy_sampling,
|
||||
stochastic_sampling,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArgsTest:
|
||||
target_model: str
|
||||
draft_model: str
|
||||
sampling_config: SamplingParams
|
||||
num_speculative_tokens: int
|
||||
expected_acceptance_rate: float
|
||||
expected_acceptance_len: float
|
||||
expected_gsm8k_accuracy: float = 0.0 # skip by default
|
||||
# Defaults
|
||||
enforce_eager: bool = True
|
||||
parallel_drafting: bool = False
|
||||
target_tensor_parallel_size: int = 1
|
||||
draft_tensor_parallel_size: int = 1
|
||||
max_model_len: int = 2048
|
||||
gpu_memory_utilization: float = 0.5
|
||||
dataset: str = "test_prompts"
|
||||
# Doubling 100 to 200 reduces sampling standard error by about 29%.
|
||||
num_prompts: int = 200
|
||||
|
||||
|
||||
def get_messages(dataset: str, n: int) -> list[Messages]:
|
||||
if dataset == "test_prompts":
|
||||
return get_test_prompts(mm_enabled=False, num_prompts=n)
|
||||
if dataset == "likaixin/InstructCoder":
|
||||
return get_instruct_coder_messages(n=n)
|
||||
raise NotImplementedError(f"Dataset '{dataset}' not implemented")
|
||||
|
||||
|
||||
def some_high_acceptance_metrics() -> dict:
|
||||
return {
|
||||
"sampling_config": greedy_sampling(),
|
||||
"num_speculative_tokens": 3,
|
||||
"expected_acceptance_len": 3.4, # ref: 3.75
|
||||
"expected_acceptance_rate": 0.8, # ref: 0.9
|
||||
}
|
||||
|
||||
|
||||
cases = [
|
||||
# Same model for draft and target, greedy sampling.
|
||||
ArgsTest(
|
||||
target_model="Qwen/Qwen3-0.6B",
|
||||
draft_model="Qwen/Qwen3-0.6B",
|
||||
sampling_config=greedy_sampling(),
|
||||
num_speculative_tokens=3, # K
|
||||
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
|
||||
expected_acceptance_rate=0.98, # slight epsilon
|
||||
expected_gsm8k_accuracy=0.25, # ref: 35-40%
|
||||
),
|
||||
# Smaller draft model, stochastic sampling.
|
||||
ArgsTest(
|
||||
target_model="Qwen/Qwen3-1.7B",
|
||||
draft_model="Qwen/Qwen3-0.6B",
|
||||
sampling_config=stochastic_sampling(),
|
||||
num_speculative_tokens=3,
|
||||
expected_acceptance_len=3.4, # ref: 3.7
|
||||
expected_acceptance_rate=0.80, # ref: 0.90
|
||||
expected_gsm8k_accuracy=0.5, # ref: 60%. Note gsm8k always runs greedy sampling
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", cases)
|
||||
@pytest.mark.parametrize("enforce_eager", [True, False])
|
||||
@single_gpu_only
|
||||
def test_draft_model_correctness(args: ArgsTest, enforce_eager: bool, vllm_runner):
|
||||
args.enforce_eager = enforce_eager
|
||||
assert_draft_model_correctness(args, vllm_runner)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_draft_model_realistic_example(vllm_runner):
|
||||
args = ArgsTest(
|
||||
target_model="Qwen/Qwen3-1.7B",
|
||||
draft_model="Qwen/Qwen3-0.6B",
|
||||
dataset="likaixin/InstructCoder",
|
||||
num_speculative_tokens=3,
|
||||
sampling_config=greedy_sampling(),
|
||||
enforce_eager=False,
|
||||
expected_acceptance_len=2.6, # ref: 2.86
|
||||
expected_acceptance_rate=0.5, # ref: 0.62
|
||||
)
|
||||
assert_draft_model_correctness(args, vllm_runner)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_draft_model_parallel_drafting(vllm_runner):
|
||||
args = ArgsTest(
|
||||
target_model="Qwen/Qwen3-1.7B",
|
||||
draft_model="amd/PARD-Qwen3-0.6B",
|
||||
dataset="likaixin/InstructCoder",
|
||||
num_speculative_tokens=3,
|
||||
sampling_config=greedy_sampling(),
|
||||
parallel_drafting=True,
|
||||
enforce_eager=False,
|
||||
expected_acceptance_len=2.3, # ref: 2.52
|
||||
expected_acceptance_rate=0.4, # ref: 0.51
|
||||
)
|
||||
assert_draft_model_correctness(args, vllm_runner)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"models",
|
||||
[
|
||||
# target_model, draft_model
|
||||
("Qwen/Qwen3-1.7B-FP8", "Qwen/Qwen3-0.6B"), # target quantized
|
||||
("Qwen/Qwen3-1.7B", "Qwen/Qwen3-0.6B-FP8"), # draft quantized
|
||||
],
|
||||
ids=["target_quantized", "draft_quantized"],
|
||||
)
|
||||
@pytest.mark.parametrize("enforce_eager", [True, False])
|
||||
@single_gpu_only
|
||||
def test_draft_model_quantization(
|
||||
models: tuple[str, str], enforce_eager: bool, vllm_runner
|
||||
):
|
||||
tgt_model, draft_model = models
|
||||
sd_case = ArgsTest(
|
||||
target_model=tgt_model,
|
||||
draft_model=draft_model,
|
||||
**some_high_acceptance_metrics(),
|
||||
enforce_eager=enforce_eager,
|
||||
)
|
||||
assert_draft_model_correctness(sd_case, vllm_runner)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_draft_model_transformers_backend(vllm_runner):
|
||||
"""Ensure that Attention prefixes don't collide between the target and
|
||||
draft models when both models use the Transformers modelling backend."""
|
||||
sd_case = ArgsTest(
|
||||
target_model="allenai/OLMo-2-0425-1B-Instruct",
|
||||
draft_model="allenai/OLMo-2-0425-1B-Instruct",
|
||||
sampling_config=greedy_sampling(),
|
||||
num_speculative_tokens=3,
|
||||
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
|
||||
expected_acceptance_rate=0.98, # slight epsilon
|
||||
)
|
||||
assert_draft_model_correctness(sd_case, vllm_runner)
|
||||
|
||||
|
||||
@multi_gpu_only(num_gpus=2)
|
||||
def test_draft_model_tensor_parallelism(vllm_runner):
|
||||
"""Ensure spec decode works when running with TP > 1."""
|
||||
sd_case = ArgsTest(
|
||||
target_model="Qwen/Qwen3-1.7B",
|
||||
target_tensor_parallel_size=2,
|
||||
draft_model="Qwen/Qwen3-0.6B",
|
||||
draft_tensor_parallel_size=2,
|
||||
**some_high_acceptance_metrics(),
|
||||
enforce_eager=False,
|
||||
expected_gsm8k_accuracy=0.5,
|
||||
)
|
||||
assert_draft_model_correctness(sd_case, vllm_runner)
|
||||
|
||||
|
||||
@multi_gpu_only(num_gpus=2)
|
||||
def test_draft_model_engine_args_tensor_parallelism():
|
||||
"""Ensure the vllm_config for the draft model is created correctly,
|
||||
and independently of the target model (quantization, TP, etc.)"""
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B-FP8", # <<< tgt quantized
|
||||
tensor_parallel_size=2,
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B", # <<< draft not quantized
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
"draft_tensor_parallel_size": 1, # <<< valid arg name
|
||||
},
|
||||
)
|
||||
target_config: VllmConfig = engine_args.create_engine_config()
|
||||
assert target_config.parallel_config.tensor_parallel_size == 2
|
||||
assert target_config.quant_config.get_name() == "fp8"
|
||||
|
||||
speculative_config = target_config.speculative_config
|
||||
draft_config: VllmConfig = replace(
|
||||
target_config,
|
||||
quant_config=None,
|
||||
parallel_config=replace(
|
||||
speculative_config.draft_parallel_config,
|
||||
rank=target_config.parallel_config.rank,
|
||||
),
|
||||
model_config=speculative_config.draft_model_config,
|
||||
)
|
||||
assert draft_config.parallel_config.tensor_parallel_size == 1
|
||||
assert draft_config.quant_config is None
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize("dcp_size", [1, 2])
|
||||
def test_draft_model_inherits_target_dcp_config(monkeypatch, dcp_size):
|
||||
monkeypatch.setattr(current_platform, "device_count", lambda: 16)
|
||||
target_config = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B",
|
||||
tensor_parallel_size=16,
|
||||
decode_context_parallel_size=dcp_size,
|
||||
cp_kv_cache_interleave_size=16,
|
||||
dcp_comm_backend="ag_rs",
|
||||
distributed_executor_backend="mp",
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B",
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
).create_engine_config()
|
||||
proposer = object.__new__(DraftModelProposer)
|
||||
proposer.vllm_config = target_config
|
||||
proposer.speculative_config = target_config.speculative_config
|
||||
draft_config = proposer._create_draft_vllm_config()
|
||||
draft_parallel = draft_config.parallel_config
|
||||
assert draft_parallel.decode_context_parallel_size == dcp_size
|
||||
assert draft_parallel.cp_kv_cache_interleave_size == 16
|
||||
assert draft_parallel.dcp_comm_backend == "ag_rs"
|
||||
assert (
|
||||
draft_parallel.dcp_q_replicate == target_config.parallel_config.dcp_q_replicate
|
||||
)
|
||||
assert draft_parallel is not target_config.parallel_config
|
||||
assert target_config.parallel_config.decode_context_parallel_size == dcp_size
|
||||
|
||||
|
||||
def _apply_draft_moe_backend(vllm_config: VllmConfig) -> VllmConfig:
|
||||
"""Replicate SpecDecodeBaseProposer._create_draft_vllm_config logic
|
||||
so we can test it without instantiating a full proposer."""
|
||||
spec_cfg = vllm_config.speculative_config
|
||||
if spec_cfg.moe_backend is not None:
|
||||
return replace(
|
||||
vllm_config,
|
||||
kernel_config=replace(
|
||||
vllm_config.kernel_config,
|
||||
moe_backend=spec_cfg.moe_backend,
|
||||
),
|
||||
)
|
||||
return vllm_config
|
||||
|
||||
|
||||
def _platform_moe_backend(monkeypatch: pytest.MonkeyPatch) -> MoEBackend:
|
||||
if current_platform.is_rocm():
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "1")
|
||||
return "aiter"
|
||||
if current_platform.is_cuda():
|
||||
return "flashinfer_trtllm"
|
||||
return "auto"
|
||||
|
||||
|
||||
def test_draft_model_moe_backend_override(monkeypatch: pytest.MonkeyPatch):
|
||||
"""When moe_backend is set in speculative_config, the draft VllmConfig
|
||||
should use it while the target keeps its own setting."""
|
||||
target_moe_backend = _platform_moe_backend(monkeypatch)
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B",
|
||||
tensor_parallel_size=1,
|
||||
moe_backend=target_moe_backend,
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B",
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
"moe_backend": "triton",
|
||||
},
|
||||
)
|
||||
tgt_config: VllmConfig = engine_args.create_engine_config()
|
||||
assert tgt_config.kernel_config.moe_backend == target_moe_backend
|
||||
assert tgt_config.speculative_config.moe_backend == "triton"
|
||||
|
||||
draft_config = _apply_draft_moe_backend(tgt_config)
|
||||
assert draft_config.kernel_config.moe_backend == "triton"
|
||||
# Target config must be unaffected.
|
||||
assert tgt_config.kernel_config.moe_backend == target_moe_backend
|
||||
|
||||
|
||||
def test_draft_model_moe_backend_inherits_target(monkeypatch: pytest.MonkeyPatch):
|
||||
"""When moe_backend is not set in speculative_config, the draft should
|
||||
inherit the target's moe_backend."""
|
||||
target_moe_backend = _platform_moe_backend(monkeypatch)
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B",
|
||||
tensor_parallel_size=1,
|
||||
moe_backend=target_moe_backend,
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B",
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
)
|
||||
tgt_config: VllmConfig = engine_args.create_engine_config()
|
||||
assert tgt_config.kernel_config.moe_backend == target_moe_backend
|
||||
assert tgt_config.speculative_config.moe_backend is None
|
||||
|
||||
draft_config = _apply_draft_moe_backend(tgt_config)
|
||||
assert draft_config.kernel_config.moe_backend == target_moe_backend
|
||||
assert draft_config is tgt_config
|
||||
|
||||
|
||||
def test_draft_model_moe_backend_default_auto():
|
||||
"""When neither target nor draft set moe_backend explicitly, both should
|
||||
default to 'auto'."""
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B",
|
||||
tensor_parallel_size=1,
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B",
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
)
|
||||
tgt_config: VllmConfig = engine_args.create_engine_config()
|
||||
assert tgt_config.kernel_config.moe_backend == "auto"
|
||||
assert tgt_config.speculative_config.moe_backend is None
|
||||
|
||||
draft_config = _apply_draft_moe_backend(tgt_config)
|
||||
assert draft_config.kernel_config.moe_backend == "auto"
|
||||
assert draft_config is tgt_config
|
||||
|
||||
|
||||
def test_draft_model_engine_args_rejects_invalid_tp_argname():
|
||||
"""The user should pass "draft_tensor_parallel_size" rather than
|
||||
"tensor_parallel_size". We enforce this with validation."""
|
||||
engine_args = EngineArgs(
|
||||
model="Qwen/Qwen3-1.7B",
|
||||
tensor_parallel_size=1,
|
||||
speculative_config={
|
||||
"model": "Qwen/Qwen3-0.6B",
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": 3,
|
||||
"tensor_parallel_size": 1, # <<< invalid arg name
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValueError, match="draft_tensor_parallel_size"):
|
||||
engine_args.create_engine_config()
|
||||
|
||||
|
||||
def assert_draft_model_correctness(args: ArgsTest, vllm_runner):
|
||||
"""Compare the outputs using and not using speculative decoding.
|
||||
In the greedy decoding case, the outputs must match EXACTLY."""
|
||||
test_prompts: list[Messages] = get_messages(
|
||||
dataset=args.dataset, n=args.num_prompts
|
||||
)
|
||||
|
||||
with vllm_runner(
|
||||
args.target_model,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
speculative_config={
|
||||
"model": args.draft_model,
|
||||
"method": "draft_model",
|
||||
"num_speculative_tokens": args.num_speculative_tokens,
|
||||
"max_model_len": args.max_model_len,
|
||||
"enforce_eager": args.enforce_eager,
|
||||
"draft_tensor_parallel_size": args.draft_tensor_parallel_size,
|
||||
"parallel_drafting": args.parallel_drafting,
|
||||
},
|
||||
max_num_seqs=100, # limit cudagraph capture runtime
|
||||
max_model_len=args.max_model_len,
|
||||
gpu_memory_utilization=args.gpu_memory_utilization,
|
||||
tensor_parallel_size=args.target_tensor_parallel_size,
|
||||
enforce_eager=args.enforce_eager,
|
||||
disable_log_stats=False, # enables get_metrics()
|
||||
) as spec_runner:
|
||||
spec_llm = spec_runner.llm
|
||||
|
||||
# we don't check the outputs, only check the metrics
|
||||
spec_llm.chat(test_prompts, args.sampling_config)
|
||||
metrics = spec_llm.get_metrics()
|
||||
acceptance_rate: float = compute_acceptance_rate(metrics)
|
||||
acceptance_len: float = compute_acceptance_len(metrics)
|
||||
|
||||
# Need to evaluate after getting metrics to avoid polluting the AR
|
||||
evaluate_llm_for_gsm8k(
|
||||
spec_llm, expected_accuracy_threshold=args.expected_gsm8k_accuracy
|
||||
)
|
||||
|
||||
print(
|
||||
f"spec-decode: target={args.target_model}, draft={args.draft_model}, "
|
||||
f"temperature={args.sampling_config.temperature:.2f}, "
|
||||
f"acceptance_rate={acceptance_rate:.2f}, "
|
||||
f"acceptance_len={acceptance_len:.2f}, "
|
||||
)
|
||||
|
||||
context = (
|
||||
f"draft_model target={args.target_model}, draft={args.draft_model}, "
|
||||
f"eager={args.enforce_eager}, "
|
||||
f"acceptance_rate={acceptance_rate:.3f}, "
|
||||
f"acceptance_len={acceptance_len:.3f}"
|
||||
)
|
||||
assert acceptance_rate >= args.expected_acceptance_rate, (
|
||||
f"{context}; expected acceptance_rate >= "
|
||||
f"{args.expected_acceptance_rate:.3f}"
|
||||
)
|
||||
assert acceptance_len >= args.expected_acceptance_len, (
|
||||
f"{context}; expected acceptance_len >= {args.expected_acceptance_len:.3f}"
|
||||
)
|
||||
# draft_model supports async scheduling; assert it is active by default.
|
||||
has_async = spec_llm.llm_engine.vllm_config.scheduler_config.async_scheduling
|
||||
|
||||
assert has_async, "Expected async_scheduling=True for draft_model spec decode"
|
||||
@@ -1,134 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""This script contains:
|
||||
1. test lora with speculative decoding for batch inference
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import set_random_seed
|
||||
|
||||
from ..utils import assert_request_outputs_match
|
||||
|
||||
LORA_TEST_PROMPT_MAP: dict[str, str] = {}
|
||||
|
||||
LORA_TEST_PROMPT_MAP["premjatin/qwen-linear-algebra-coder"] = """
|
||||
### INSTRUCTION:
|
||||
You are an AI assistant that generates Python code to solve linear
|
||||
algebra problems.
|
||||
|
||||
### PROBLEM:
|
||||
Find the eigenvalues and eigenvectors of the following 3x3 matrix:
|
||||
[[3, 2, 0],
|
||||
[2, 3, 0],
|
||||
[0, 0, 2]]
|
||||
|
||||
### OUTPUT FORMAT (STRICT):
|
||||
Numbers should be represented as integers only.
|
||||
|
||||
### PYTHON SOLUTION:
|
||||
"""
|
||||
|
||||
SEED = 42
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_setup",
|
||||
[
|
||||
(
|
||||
"eagle3",
|
||||
"Qwen/Qwen3-1.7B",
|
||||
"AngelSlim/Qwen3-1.7B_eagle3",
|
||||
"premjatin/qwen-linear-algebra-coder",
|
||||
1,
|
||||
)
|
||||
],
|
||||
)
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(), reason="Requires CUDA or ROCm"
|
||||
)
|
||||
def test_batch_inference_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
model_setup: tuple[str, str, str, str, int],
|
||||
vllm_runner,
|
||||
):
|
||||
"""Compare the outputs of a LLM with only Lora and a LLM with both SD and Lora.
|
||||
Should be the same and no failure when doing batch inference.
|
||||
model_setup: (method, model_name, spec_model_name, lora_path, tp_size)
|
||||
"""
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
m.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
set_random_seed(SEED)
|
||||
m.setattr(torch.backends.cudnn, "benchmark", False)
|
||||
m.setattr(torch.backends.cudnn, "deterministic", True)
|
||||
|
||||
method, model_name, spec_model_name, lora_path, tp_size = model_setup
|
||||
|
||||
prompts = [LORA_TEST_PROMPT_MAP[lora_path]] * 100
|
||||
lora_request = LoRARequest("adapter", 1, lora_path)
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0, top_p=1.0, top_k=-1, seed=SEED, max_tokens=128
|
||||
)
|
||||
|
||||
# without speculative decoding
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=True,
|
||||
tensor_parallel_size=tp_size,
|
||||
max_model_len=2048,
|
||||
max_num_seqs=4,
|
||||
enable_lora=True,
|
||||
max_loras=1,
|
||||
max_cpu_loras=1,
|
||||
max_lora_rank=16,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
) as ref_runner:
|
||||
ref_outputs = ref_runner.llm.generate(
|
||||
prompts, sampling_params, lora_request=lora_request
|
||||
)
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=True,
|
||||
tensor_parallel_size=tp_size,
|
||||
speculative_config={
|
||||
"method": method,
|
||||
"model": spec_model_name,
|
||||
"num_speculative_tokens": 3,
|
||||
"max_model_len": 2048,
|
||||
},
|
||||
max_model_len=2048,
|
||||
max_num_seqs=4,
|
||||
enable_lora=True,
|
||||
max_loras=1,
|
||||
max_cpu_loras=1,
|
||||
max_lora_rank=16,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
) as spec_runner:
|
||||
lora_spec_outputs = spec_runner.llm.generate(
|
||||
prompts, sampling_params, lora_request=lora_request
|
||||
)
|
||||
|
||||
# Under greedy verification, the spec-decode output should equal the
|
||||
# non-spec output (modulo FP noise from the target's verify-path matmul
|
||||
# running at seqlen num_speculative_tokens+1 vs 1). 90% leaves slack.
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
lora_spec_outputs,
|
||||
required_matches=int(0.90 * len(ref_outputs)) + 1,
|
||||
context=(
|
||||
f"LoRA + {method}: target={model_name}, draft={spec_model_name}, "
|
||||
f"adapter={lora_path}"
|
||||
),
|
||||
)
|
||||
@@ -1,59 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import torch
|
||||
|
||||
from tests.utils import multi_gpu_test
|
||||
from tests.v1.e2e.spec_decode.utils import compute_acceptance_len
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
|
||||
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
DRAFT = "nm-testing/Llama3_2_1B_speculator.eagle3"
|
||||
PROMPTS = [
|
||||
"The capital of France is",
|
||||
"2 + 2 equals",
|
||||
"In one word, the color of the sky is",
|
||||
"Q: If a train travels 60 miles in 1.5 hours, what is its average speed?\nA:",
|
||||
]
|
||||
|
||||
ACCEPTANCE_TOLERANCE = 0.95
|
||||
|
||||
|
||||
def _run(pp_size: int) -> float:
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
tensor_parallel_size=1,
|
||||
pipeline_parallel_size=pp_size,
|
||||
max_model_len=512,
|
||||
gpu_memory_utilization=0.45,
|
||||
disable_log_stats=False,
|
||||
compilation_config={"cudagraph_mode": "FULL_AND_PIECEWISE"},
|
||||
speculative_config={
|
||||
"method": "eagle3",
|
||||
"model": DRAFT,
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
)
|
||||
try:
|
||||
llm.generate(
|
||||
PROMPTS,
|
||||
SamplingParams(temperature=0.0, max_tokens=32, ignore_eos=True),
|
||||
)
|
||||
acceptance = compute_acceptance_len(llm.get_metrics())
|
||||
assert acceptance > 1
|
||||
return acceptance
|
||||
finally:
|
||||
del llm
|
||||
torch.accelerator.empty_cache()
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_eagle3_pipeline_parallel_acceptance():
|
||||
baseline = _run(1)
|
||||
for pp_size in (2, 4):
|
||||
parallel = _run(pp_size)
|
||||
assert parallel >= baseline * ACCEPTANCE_TOLERANCE, (
|
||||
f"PP={pp_size} acceptance regressed: {parallel:.3f} < "
|
||||
f"{baseline:.3f} * {ACCEPTANCE_TOLERANCE}"
|
||||
)
|
||||
@@ -1,172 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import (
|
||||
get_attn_backend_list_based_on_platform,
|
||||
single_gpu_only,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from .utils import _run_eagle_correctness
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_device_capability_family(100),
|
||||
reason="DeepSeek head_dim=192 not supported on SM100/SM110 (Blackwell)",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
[
|
||||
"model_setup",
|
||||
"mm_enabled",
|
||||
"enable_chunked_prefill",
|
||||
"model_impl",
|
||||
"expected_accuracy_threshold",
|
||||
],
|
||||
[
|
||||
(
|
||||
(
|
||||
"eagle",
|
||||
"eagle618/deepseek-v3-random",
|
||||
"eagle618/eagle-deepseek-v3-random",
|
||||
1,
|
||||
),
|
||||
False,
|
||||
False,
|
||||
"auto",
|
||||
0.0,
|
||||
),
|
||||
],
|
||||
ids=["deepseek_eagle"],
|
||||
)
|
||||
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
|
||||
def test_eagle_correctness_light(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, str, int],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
enable_chunked_prefill: bool,
|
||||
model_impl: str,
|
||||
attn_backend: str,
|
||||
vllm_runner,
|
||||
):
|
||||
_run_eagle_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
enable_chunked_prefill,
|
||||
model_impl,
|
||||
attn_backend,
|
||||
vllm_runner,
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@pytest.mark.parametrize(
|
||||
[
|
||||
"model_setup",
|
||||
"mm_enabled",
|
||||
"enable_chunked_prefill",
|
||||
"model_impl",
|
||||
"expected_accuracy_threshold",
|
||||
],
|
||||
[
|
||||
(
|
||||
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
|
||||
False,
|
||||
False,
|
||||
"auto",
|
||||
0.8,
|
||||
),
|
||||
pytest.param(
|
||||
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
|
||||
False,
|
||||
False,
|
||||
"transformers",
|
||||
0.8,
|
||||
# TODO(hmellor): figure out why memory usage is so high
|
||||
marks=pytest.mark.skipif(
|
||||
not current_platform.is_rocm(),
|
||||
reason="Feature is experimental and uses too much memory in CUDA CI",
|
||||
),
|
||||
),
|
||||
(
|
||||
(
|
||||
"eagle3",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"taobao-mnn/Qwen3-VL-8B-Instruct-Eagle3",
|
||||
1,
|
||||
),
|
||||
False,
|
||||
False,
|
||||
"auto",
|
||||
0.8,
|
||||
),
|
||||
pytest.param(
|
||||
(
|
||||
"eagle3",
|
||||
"Qwen/Qwen2.5-VL-7B-Instruct",
|
||||
"Rayzl/qwen2.5-vl-7b-eagle3-sgl",
|
||||
1,
|
||||
),
|
||||
False,
|
||||
False,
|
||||
"auto",
|
||||
0.7,
|
||||
# TODO: Re-measure the reference threshold when re-enabling this case.
|
||||
# Text-only mode starts but loses target correctness with ROCm/TRITON;
|
||||
# full multimodal profiling currently fails during engine startup.
|
||||
marks=pytest.mark.skip(
|
||||
reason="Qwen2.5-VL Eagle3 is not yet reliable in this test setup"
|
||||
),
|
||||
),
|
||||
(
|
||||
(
|
||||
"eagle3",
|
||||
"meta-llama/Llama-3.1-8B-Instruct",
|
||||
"yuhuili/EAGLE3-LLaMA3.1-Instruct-8B",
|
||||
1,
|
||||
),
|
||||
False,
|
||||
False,
|
||||
"auto",
|
||||
0.7,
|
||||
),
|
||||
],
|
||||
ids=[
|
||||
"qwen3_eagle3",
|
||||
"qwen3_eagle3-transformers",
|
||||
"qwen3_vl_eagle3",
|
||||
"qwen2_5_vl_eagle3",
|
||||
"llama3_eagle3",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
|
||||
def test_eagle_correctness_medium(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, str, int],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
enable_chunked_prefill: bool,
|
||||
model_impl: str,
|
||||
attn_backend: str,
|
||||
vllm_runner,
|
||||
):
|
||||
_run_eagle_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
enable_chunked_prefill,
|
||||
model_impl,
|
||||
attn_backend,
|
||||
vllm_runner,
|
||||
)
|
||||
@@ -1,135 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ..utils import (
|
||||
_skip_if_insufficient_gpus_for_tp,
|
||||
assert_request_outputs_match,
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_test_prompts,
|
||||
)
|
||||
|
||||
|
||||
def _run_eagle_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, str, int],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
enable_chunked_prefill: bool,
|
||||
model_impl: str,
|
||||
attn_backend: str,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Compare the outputs of an original LLM and a speculative LLM
|
||||
which should be the same when using eagle speculative decoding.
|
||||
"""
|
||||
method, model_name, spec_model_name, tp_size = model_setup
|
||||
_skip_if_insufficient_gpus_for_tp(tp_size)
|
||||
|
||||
test_prompts = get_test_prompts(mm_enabled)
|
||||
|
||||
extra_kwargs: dict[str, Any] = {}
|
||||
if not mm_enabled and "Qwen3-VL" in model_name:
|
||||
# These cases only exercise text generation. Avoid profiling an unused
|
||||
# vision tower, which adds substantial memory to both reference runs.
|
||||
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
|
||||
|
||||
if "Llama-4-Scout" in model_name and attn_backend == "FLASH_ATTN":
|
||||
if current_platform.is_rocm():
|
||||
print(
|
||||
"FLASH_ATTN for spec_decode not supported on "
|
||||
"ROCm currently. Changing to FLEX_ATTENTION backend."
|
||||
)
|
||||
attention_config = {"backend": "FLEX_ATTENTION"}
|
||||
else:
|
||||
attention_config = None
|
||||
else:
|
||||
attention_config = {"backend": attn_backend}
|
||||
|
||||
if attn_backend == "TRITON_ATTN" and not current_platform.is_rocm():
|
||||
pytest.skip(
|
||||
"TRITON_ATTN does not support "
|
||||
"multi-token eagle spec decode on current platform"
|
||||
)
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_MLA_DISABLE", "1")
|
||||
|
||||
if attn_backend == "ROCM_AITER_FA" and current_platform.is_rocm():
|
||||
if "deepseek" in model_name.lower():
|
||||
m.setenv("VLLM_ROCM_USE_AITER", "1")
|
||||
m.delenv("VLLM_MLA_DISABLE", raising=False)
|
||||
attention_config = {"backend": "ROCM_AITER_MLA"}
|
||||
else:
|
||||
m.setenv("VLLM_ROCM_USE_AITER", "1")
|
||||
|
||||
max_model_len = 2048
|
||||
max_num_batched_tokens = 128 if enable_chunked_prefill else max_model_len
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
max_model_len=max_model_len,
|
||||
tensor_parallel_size=tp_size,
|
||||
attention_config=attention_config,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**extra_kwargs,
|
||||
) as ref_runner:
|
||||
evaluate_llm_for_gsm8k(
|
||||
ref_runner.llm,
|
||||
expected_accuracy_threshold=expected_accuracy_threshold,
|
||||
)
|
||||
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=True,
|
||||
tensor_parallel_size=tp_size,
|
||||
speculative_config={
|
||||
"method": method,
|
||||
"model": spec_model_name,
|
||||
"num_speculative_tokens": 3,
|
||||
"max_model_len": max_model_len,
|
||||
},
|
||||
max_model_len=max_model_len,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
enable_chunked_prefill=enable_chunked_prefill,
|
||||
model_impl=model_impl,
|
||||
attention_config=attention_config,
|
||||
compilation_config=CompilationConfig(),
|
||||
**extra_kwargs,
|
||||
) as spec_runner:
|
||||
# EAGLE/EAGLE3 supports async scheduling by default.
|
||||
has_async = (
|
||||
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
|
||||
)
|
||||
assert has_async, (
|
||||
f"Expected async scheduling for {method}: target={model_name}, "
|
||||
f"draft={spec_model_name}, backend={attn_backend}; got {has_async}"
|
||||
)
|
||||
evaluate_llm_for_gsm8k(
|
||||
spec_runner.llm,
|
||||
expected_accuracy_threshold=expected_accuracy_threshold,
|
||||
)
|
||||
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
|
||||
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
spec_outputs,
|
||||
required_matches=int(0.6 * len(ref_outputs)) + 1,
|
||||
context=(
|
||||
f"{method} target={model_name}, draft={spec_model_name}, "
|
||||
f"backend={attn_backend}"
|
||||
),
|
||||
)
|
||||
@@ -1,110 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ..utils import (
|
||||
_skip_if_insufficient_gpus_for_tp,
|
||||
assert_request_outputs_match,
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_test_prompts,
|
||||
)
|
||||
|
||||
|
||||
def check_mtp_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, int, str | None],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Compare the outputs of a original LLM and a speculative LLM
|
||||
which should be the same when using MTP speculative decoding. Due to some variance
|
||||
in the engine, it is possible for some outputs to differ, so we expect that at least
|
||||
6/10 output tokens match exactly, and that the GSM8k accuracy is above a precomputed
|
||||
reference threshold for each model.
|
||||
"""
|
||||
method, model_name, tp_size, draft_model = model_setup
|
||||
_skip_if_insufficient_gpus_for_tp(tp_size)
|
||||
|
||||
# Generate test prompts inside the function instead of using fixture
|
||||
test_prompts = get_test_prompts(mm_enabled)
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_MLA_DISABLE", "1")
|
||||
|
||||
attn_backend = "TRITON_ATTN" if current_platform.is_rocm() else "auto"
|
||||
|
||||
# Skip multimodal profiling for models that don't need it in this test.
|
||||
extra_kwargs: dict[str, Any] = {}
|
||||
if "Qwen3.5" in model_name:
|
||||
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
|
||||
elif "gemma-4" in model_name:
|
||||
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "audio": 0}
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
max_model_len=2048,
|
||||
tensor_parallel_size=tp_size,
|
||||
trust_remote_code=True,
|
||||
attention_backend=attn_backend,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**extra_kwargs,
|
||||
) as ref_runner:
|
||||
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
|
||||
evaluate_llm_for_gsm8k(
|
||||
ref_runner.llm,
|
||||
expected_accuracy_threshold=expected_accuracy_threshold,
|
||||
)
|
||||
|
||||
speculative_config: dict[str, Any] = {
|
||||
"method": method,
|
||||
"num_speculative_tokens": 1,
|
||||
"max_model_len": 2048,
|
||||
}
|
||||
if draft_model is not None:
|
||||
speculative_config["model"] = draft_model
|
||||
speculative_config["num_speculative_tokens"] = 2
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=True,
|
||||
tensor_parallel_size=tp_size,
|
||||
speculative_config=speculative_config,
|
||||
max_model_len=2048,
|
||||
attention_backend=attn_backend,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**extra_kwargs,
|
||||
) as spec_runner:
|
||||
# MTP supports async scheduling by default.
|
||||
has_async = (
|
||||
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
|
||||
)
|
||||
assert has_async, (
|
||||
f"Expected async scheduling for {method}: target={model_name}, "
|
||||
f"draft={draft_model}; got {has_async}"
|
||||
)
|
||||
evaluate_llm_for_gsm8k(
|
||||
spec_runner.llm,
|
||||
expected_accuracy_threshold=expected_accuracy_threshold,
|
||||
)
|
||||
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
|
||||
|
||||
# Heuristic: expect at least 80% of the prompts to match exactly
|
||||
# Upon failure, inspect the outputs to check for inaccuracy.
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
spec_outputs,
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context=f"{method} target={model_name}, draft={draft_model}",
|
||||
)
|
||||
@@ -1,44 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from .._correctness import check_mtp_correctness
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
|
||||
[
|
||||
pytest.param(
|
||||
("mtp", "ZixiQi/DeepSeek-V3-4layers-MTP-FP8", 1, None),
|
||||
False,
|
||||
0.0,
|
||||
marks=pytest.mark.skipif(
|
||||
current_platform.is_device_capability_family(100),
|
||||
reason="DeepSeek MTP: TRTLLM MoE top_k check fails on Blackwell",
|
||||
),
|
||||
), # dummy model
|
||||
],
|
||||
ids=["deepseek"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_mtp_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, int, str | None],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
check_mtp_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
vllm_runner,
|
||||
)
|
||||
@@ -1,39 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
|
||||
from .._correctness import check_mtp_correctness
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
|
||||
[
|
||||
(
|
||||
("mtp", "google/gemma-4-E4B-it", 1, "google/gemma-4-E4B-it-assistant"),
|
||||
False,
|
||||
0.50,
|
||||
), # gemma4 MTP with assistant model, ref: ~62%
|
||||
],
|
||||
ids=["gemma4-e4b"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_mtp_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, int, str | None],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
check_mtp_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
vllm_runner,
|
||||
)
|
||||
@@ -1,36 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
|
||||
from .._correctness import check_mtp_correctness
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
|
||||
[
|
||||
# Reference accuracy: 65%-70%.
|
||||
(("mtp", "XiaomiMiMo/MiMo-7B-Base", 1, None), False, 0.5),
|
||||
],
|
||||
ids=["mimo"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_mtp_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, int, str | None],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
check_mtp_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
vllm_runner,
|
||||
)
|
||||
@@ -1,149 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ...utils import (
|
||||
assert_request_outputs_match,
|
||||
compute_acceptance_len,
|
||||
get_test_prompts,
|
||||
)
|
||||
from .._correctness import check_mtp_correctness
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
|
||||
[
|
||||
(
|
||||
("mtp", "Qwen/Qwen3.5-0.8B-Base", 1, None),
|
||||
False,
|
||||
0.20,
|
||||
), # hybrid + MTP, ref: ~34%-35%
|
||||
],
|
||||
ids=["qwen3_5-hybrid"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_mtp_correctness(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_setup: tuple[str, str, int, str | None],
|
||||
mm_enabled: bool,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
check_mtp_correctness(
|
||||
monkeypatch,
|
||||
sampling_config,
|
||||
model_setup,
|
||||
mm_enabled,
|
||||
expected_accuracy_threshold,
|
||||
vllm_runner,
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_mtp_draft_lm_head_quantization(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
vllm_runner,
|
||||
):
|
||||
"""A quantized draft copy of the shared lm_head only changes drafting:
|
||||
greedy outputs match stock MTP and acceptance stays within 10%."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
prompts = get_test_prompts(mm_enabled=False)
|
||||
results = {}
|
||||
# NVFP4 needs a CUDA W4A16 kernel.
|
||||
quants = (None, "fp8", "nvfp4") if current_platform.is_cuda() else (None, "fp8")
|
||||
for quant in quants:
|
||||
with vllm_runner(
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
max_model_len=2048,
|
||||
limit_mm_per_prompt={"image": 0, "video": 0},
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 3,
|
||||
"draft_lm_head_quantization": quant,
|
||||
},
|
||||
disable_log_stats=False,
|
||||
) as runner:
|
||||
outputs = runner.llm.chat(prompts, sampling_config)
|
||||
results[quant] = (outputs, compute_acceptance_len(runner.llm.get_metrics()))
|
||||
|
||||
ref_outputs, ref_al = results.pop(None)
|
||||
for quant, (outputs, al) in results.items():
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
# Not bit-exact: a different acceptance length changes the target's
|
||||
# verify batch shapes, which can flip a near-tied greedy token.
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context=f"draft_lm_head_quantization={quant}",
|
||||
)
|
||||
assert al >= 0.9 * ref_al, (
|
||||
f"{quant}: acceptance length {al:.3f} vs {ref_al:.3f}"
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
|
||||
)
|
||||
def test_mtp_draft_lm_head_quantization_survives_sleep_and_reload(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
vllm_runner,
|
||||
):
|
||||
"""The quantized draft head is derived from the target head: it must come
|
||||
back intact after a level 1 sleep and be re-derived after a target weight
|
||||
reload, so outputs and acceptance match the run before."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
prompts = get_test_prompts(mm_enabled=False)
|
||||
with vllm_runner(
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
max_model_len=2048,
|
||||
limit_mm_per_prompt={"image": 0, "video": 0},
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 3,
|
||||
"draft_lm_head_quantization": "nvfp4",
|
||||
},
|
||||
enable_sleep_mode=True,
|
||||
disable_log_stats=False,
|
||||
) as runner:
|
||||
llm = runner.llm
|
||||
|
||||
def run():
|
||||
before = llm.get_metrics()
|
||||
outputs = llm.chat(prompts, sampling_config)
|
||||
return outputs, compute_acceptance_len(llm.get_metrics(), before)
|
||||
|
||||
ref_outputs, ref_al = run()
|
||||
|
||||
llm.sleep(level=1)
|
||||
llm.wake_up()
|
||||
outputs, al = run()
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context="after level 1 sleep",
|
||||
)
|
||||
assert al == pytest.approx(ref_al, rel=0.03)
|
||||
|
||||
llm.collective_rpc("reload_weights")
|
||||
outputs, al = run()
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context="after weight reload",
|
||||
)
|
||||
assert al == pytest.approx(ref_al, rel=0.03)
|
||||
@@ -1,115 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig, CUDAGraphMode
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ...utils import get_spec_decode_metric_value
|
||||
|
||||
PLACEHOLDER_REGRESSION_MODEL = "Qwen/Qwen3.5-0.8B-Base"
|
||||
PLACEHOLDER_REGRESSION_PROMPT = "The capital of France is"
|
||||
PLACEHOLDER_REGRESSION_MAX_TOKENS = 16
|
||||
PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID = 42
|
||||
PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS = 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode",
|
||||
[CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL_AND_PIECEWISE],
|
||||
ids=["piecewise", "full-and-piecewise"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_mtp_rejected_placeholders_match_greedy_token_ids(
|
||||
cudagraph_mode: CUDAGraphMode,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Rejected MTP padding must not alter the non-speculative token stream."""
|
||||
common_kwargs: dict[str, Any] = {
|
||||
"block_size": None,
|
||||
"max_model_len": 256,
|
||||
"max_num_seqs": 1,
|
||||
"trust_remote_code": True,
|
||||
"enable_chunked_prefill": None,
|
||||
"limit_mm_per_prompt": {"image": 0, "video": 0},
|
||||
"attention_backend": ("TRITON_ATTN" if current_platform.is_rocm() else "auto"),
|
||||
}
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=PLACEHOLDER_REGRESSION_MAX_TOKENS,
|
||||
ignore_eos=True,
|
||||
allowed_token_ids=[PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID],
|
||||
logprobs=1,
|
||||
)
|
||||
|
||||
def generate_token_ids(runner) -> tuple[int, ...]:
|
||||
outputs = runner.llm.generate([PLACEHOLDER_REGRESSION_PROMPT], sampling_params)
|
||||
assert outputs and outputs[0].outputs, "Expected one completion"
|
||||
token_ids = tuple(outputs[0].outputs[0].token_ids)
|
||||
assert len(token_ids) == PLACEHOLDER_REGRESSION_MAX_TOKENS
|
||||
return token_ids
|
||||
|
||||
def compilation_config() -> CompilationConfig:
|
||||
return CompilationConfig(
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
cudagraph_capture_sizes=[1, PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS + 1],
|
||||
)
|
||||
|
||||
with vllm_runner(
|
||||
PLACEHOLDER_REGRESSION_MODEL,
|
||||
compilation_config=compilation_config(),
|
||||
**common_kwargs,
|
||||
) as ref_runner:
|
||||
ref_mode = (
|
||||
ref_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
|
||||
)
|
||||
assert ref_mode == cudagraph_mode
|
||||
ref_token_ids = generate_token_ids(ref_runner)
|
||||
expected_token_ids = (PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID,) * (
|
||||
PLACEHOLDER_REGRESSION_MAX_TOKENS
|
||||
)
|
||||
assert ref_token_ids == expected_token_ids
|
||||
|
||||
with vllm_runner(
|
||||
PLACEHOLDER_REGRESSION_MODEL,
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
|
||||
"max_model_len": 256,
|
||||
"rejection_sample_method": "synthetic",
|
||||
"synthetic_acceptance_rates": [0.0]
|
||||
* PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
|
||||
},
|
||||
disable_log_stats=False,
|
||||
compilation_config=compilation_config(),
|
||||
**common_kwargs,
|
||||
) as spec_runner:
|
||||
spec_mode = (
|
||||
spec_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
|
||||
)
|
||||
assert spec_mode == cudagraph_mode
|
||||
spec_token_ids = generate_token_ids(spec_runner)
|
||||
metrics = spec_runner.llm.get_metrics()
|
||||
num_drafts = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_drafts"
|
||||
)
|
||||
num_draft_tokens = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_draft_tokens"
|
||||
)
|
||||
num_accepted_tokens = get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
|
||||
assert num_drafts > 0, "MTP drafter did not run"
|
||||
assert num_draft_tokens > 0, "MTP drafter did not produce draft tokens"
|
||||
assert num_accepted_tokens == 0, "Synthetic sampler accepted a draft token"
|
||||
assert spec_token_ids == ref_token_ids, (
|
||||
f"MTP changed greedy token ids under {cudagraph_mode.name}:\n"
|
||||
f" reference={ref_token_ids}\n"
|
||||
f" speculative={spec_token_ids}"
|
||||
)
|
||||
@@ -1,173 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ..utils import (
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_spec_decode_metric_value,
|
||||
get_test_prompts,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def disable_vllm_compile_cache_on_rocm(request: pytest.FixtureRequest) -> None:
|
||||
if current_platform.is_rocm():
|
||||
request.getfixturevalue("disable_vllm_compile_cache")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"speculative_config",
|
||||
[
|
||||
{
|
||||
"method": "ngram",
|
||||
"prompt_lookup_max": 5,
|
||||
"prompt_lookup_min": 3,
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
{
|
||||
"method": "suffix",
|
||||
"suffix_decoding_max_spec_factor": 2.0,
|
||||
},
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("disable_vllm_compile_cache_on_rocm")
|
||||
@single_gpu_only
|
||||
def test_ngram_and_suffix_correctness(
|
||||
speculative_config: dict,
|
||||
model_name: str,
|
||||
vllm_runner,
|
||||
):
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
# Keep LLM defaults; VllmRunner only provides lifecycle cleanup here.
|
||||
trust_remote_code=False,
|
||||
enable_chunked_prefill=None,
|
||||
speculative_config=speculative_config,
|
||||
max_model_len=4096,
|
||||
# Preserve LLM's default compilation/cudagraph configuration. Without
|
||||
# this, VllmRunner injects its reduced test-only capture sizes.
|
||||
compilation_config=CompilationConfig(),
|
||||
) as runner:
|
||||
evaluate_llm_for_gsm8k(runner.llm)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_scheduling", [True], ids=["async"])
|
||||
@single_gpu_only
|
||||
def test_ngram_gpu_default_with_async_scheduling(
|
||||
async_scheduling: bool,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Test ngram_gpu speculative decoding (k=3) correctness with and without
|
||||
async scheduling, validated via GSM8K accuracy.
|
||||
Uses Qwen/Qwen3-8B (ref GSM8K accuracy: 87%-92%).
|
||||
"""
|
||||
qwen3_model = "Qwen/Qwen3-8B"
|
||||
with vllm_runner(
|
||||
qwen3_model,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
speculative_config={
|
||||
"method": "ngram_gpu",
|
||||
"prompt_lookup_max": 3,
|
||||
"prompt_lookup_min": 2,
|
||||
"num_speculative_tokens": 2,
|
||||
},
|
||||
max_model_len=4096,
|
||||
async_scheduling=async_scheduling,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
) as spec_runner:
|
||||
# Assert the resolved async_scheduling config matches what was requested.
|
||||
assert (
|
||||
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
|
||||
== async_scheduling
|
||||
)
|
||||
evaluate_llm_for_gsm8k(spec_runner.llm, expected_accuracy_threshold=0.8)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_suffix_decoding_acceptance(
|
||||
sampling_config: SamplingParams,
|
||||
model_name: str,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Check that suffix decoding caching takes effect and improves acceptance
|
||||
lengths and acceptance rates over multiple runs of the same prompts.
|
||||
"""
|
||||
test_prompts = get_test_prompts(mm_enabled=False)
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
speculative_config={
|
||||
"method": "suffix",
|
||||
"suffix_decoding_max_spec_factor": 2.0,
|
||||
"suffix_decoding_max_cached_requests": 1000,
|
||||
},
|
||||
max_model_len=1024,
|
||||
disable_log_stats=False,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
) as spec_runner:
|
||||
# Run several times and check that the accepted tokens increase.
|
||||
num_draft = []
|
||||
num_accept = []
|
||||
for _ in range(10): # Run multiple times to warm up the cache.
|
||||
spec_runner.llm.chat(test_prompts, sampling_config)
|
||||
# Collect draft and acceptance stats.
|
||||
metrics = spec_runner.llm.get_metrics()
|
||||
num_draft.append(
|
||||
get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_draft_tokens"
|
||||
)
|
||||
)
|
||||
num_accept.append(
|
||||
get_spec_decode_metric_value(
|
||||
metrics, "vllm:spec_decode_num_accepted_tokens"
|
||||
)
|
||||
)
|
||||
|
||||
# Calculate the acceptance rates for the first and last runs.
|
||||
first_accept_tokens = num_accept[0]
|
||||
first_draft_tokens = num_draft[0]
|
||||
assert first_draft_tokens > 0, (
|
||||
"Suffix decoder produced no draft tokens on the first run: "
|
||||
f"accepted={first_accept_tokens}, drafted={first_draft_tokens}"
|
||||
)
|
||||
first_accept_rate = first_accept_tokens / first_draft_tokens
|
||||
|
||||
# Take the diff since the stats are cumulative.
|
||||
last_accept_tokens = num_accept[-1] - num_accept[-2]
|
||||
last_draft_tokens = num_draft[-1] - num_draft[-2]
|
||||
assert last_draft_tokens > 0, (
|
||||
"Suffix decoder produced no draft tokens on the last run: "
|
||||
f"accepted_delta={last_accept_tokens}, drafted_delta={last_draft_tokens}; "
|
||||
f"cumulative_drafted={num_draft[-2:]}"
|
||||
)
|
||||
last_accept_rate = last_accept_tokens / last_draft_tokens
|
||||
summary = (
|
||||
f"first accepted/drafted={first_accept_tokens}/{first_draft_tokens} "
|
||||
f"(rate={first_accept_rate:.3f}); last delta accepted/drafted="
|
||||
f"{last_accept_tokens}/{last_draft_tokens} (rate={last_accept_rate:.3f})"
|
||||
)
|
||||
|
||||
# Expect the acceptance length to improve.
|
||||
assert first_accept_tokens < last_accept_tokens, (
|
||||
f"Expected accepted tokens to increase after cache warmup; {summary}"
|
||||
)
|
||||
|
||||
# Expect the acceptance rate to improve.
|
||||
assert first_accept_rate < last_accept_rate, (
|
||||
f"Expected acceptance rate to increase after cache warmup; {summary}"
|
||||
)
|
||||
|
||||
# Heuristic: expect at least 80.0% acceptance rate at the end.
|
||||
assert last_accept_rate > 0.80, f"Expected final acceptance rate > 0.80; {summary}"
|
||||
@@ -1,106 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
|
||||
from ..utils import (
|
||||
assert_request_outputs_match,
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_test_prompts,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_path", "expected_accuracy_threshold"],
|
||||
[
|
||||
# Measured reference: 75%-80%.
|
||||
("RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3", 0.72),
|
||||
# Measured reference: 87%-92%.
|
||||
("RedHatAI/Qwen3-8B-speculator.eagle3", 0.84),
|
||||
],
|
||||
ids=["llama3_eagle3_speculator", "qwen3_eagle3_speculator"],
|
||||
)
|
||||
@single_gpu_only
|
||||
def test_speculators_model_integration(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
model_path: str,
|
||||
expected_accuracy_threshold: float,
|
||||
vllm_runner,
|
||||
):
|
||||
"""Test that speculators models work with the simplified integration.
|
||||
|
||||
This verifies the `vllm serve <speculator-model>` use case where
|
||||
speculative config is automatically detected from the model config
|
||||
without requiring explicit --speculative-config argument.
|
||||
|
||||
Tests:
|
||||
1. Speculator model is correctly detected
|
||||
2. Verifier model is extracted from speculator config
|
||||
3. Speculative decoding is automatically enabled
|
||||
4. Text generation works correctly
|
||||
5. GSM8k accuracy of the model passes a sanity check when speculative decoding on
|
||||
6. Output matches reference (non-speculative) generation
|
||||
"""
|
||||
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
|
||||
# Generate test prompts
|
||||
test_prompts = get_test_prompts(mm_enabled=False)
|
||||
|
||||
# First run: Direct speculator model (simplified integration)
|
||||
with vllm_runner(
|
||||
model_path,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
max_model_len=4096,
|
||||
gpu_memory_utilization=0.92,
|
||||
) as spec_runner:
|
||||
evaluate_llm_for_gsm8k(
|
||||
spec_runner.llm, expected_accuracy_threshold=expected_accuracy_threshold
|
||||
)
|
||||
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
|
||||
|
||||
# Verify speculative config was auto-detected
|
||||
assert spec_runner.llm.llm_engine.vllm_config.speculative_config is not None, (
|
||||
f"Speculative config should be auto-detected for {model_path}"
|
||||
)
|
||||
|
||||
spec_config = spec_runner.llm.llm_engine.vllm_config.speculative_config
|
||||
assert spec_config.num_speculative_tokens > 0, (
|
||||
f"Expected positive speculative tokens, "
|
||||
f"got {spec_config.num_speculative_tokens}"
|
||||
)
|
||||
|
||||
# Verify draft model is set to the speculator model
|
||||
assert spec_config.model == model_path, (
|
||||
f"Draft model should be {model_path}, got {spec_config.model}"
|
||||
)
|
||||
|
||||
# Extract verifier model for reference run
|
||||
verifier_model = spec_runner.llm.llm_engine.vllm_config.model_config.model
|
||||
|
||||
# Second run: Reference without speculative decoding
|
||||
with vllm_runner(
|
||||
verifier_model,
|
||||
block_size=None,
|
||||
trust_remote_code=False,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
max_model_len=4096,
|
||||
gpu_memory_utilization=0.92,
|
||||
) as ref_runner:
|
||||
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
|
||||
|
||||
# Heuristic: expect at least 66% of prompts to match exactly
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
spec_outputs,
|
||||
required_matches=int(0.66 * len(ref_outputs)),
|
||||
context=f"speculator={model_path}, verifier={verifier_model}",
|
||||
)
|
||||
@@ -1,268 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import asyncio
|
||||
from contextlib import AsyncExitStack
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import multi_gpu_marks
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.config import CompilationConfig
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.metrics.reader import Metric
|
||||
|
||||
DEEPSEEK_MTP_MAIN_RANDOM = "luccafong/deepseek_mtp_main_random"
|
||||
DEEPSEEK_MTP_DRAFT_RANDOM = "luccafong/deepseek_mtp_draft_random"
|
||||
|
||||
PROMPT = "The capital of France is"
|
||||
MAX_TOKENS = 8
|
||||
MAX_MODEL_LEN = 2048
|
||||
GPU_MEM_UTIL = 0.85
|
||||
# Spec / no-spec greedy output should match, but exact match is not guaranteed
|
||||
# across parallelism layouts (reduction order can flip near-tie argmaxes), so
|
||||
# gate on a similarity ratio like the spec-decode E2E tests.
|
||||
MIN_MATCH_RATIO = 0.8
|
||||
|
||||
|
||||
def _token_match_ratio(a: tuple[int, ...], b: tuple[int, ...]) -> float:
|
||||
n = min(len(a), len(b))
|
||||
return sum(x == y for x, y in zip(a, b)) / n if n else 0.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InlineConfig:
|
||||
id: str
|
||||
tp_size: int = 1
|
||||
pp_size: int = 1
|
||||
enable_expert_parallel: bool = False
|
||||
enable_eplb: bool = False
|
||||
skip_reason: str | None = None
|
||||
|
||||
|
||||
INLINE_CONFIGS = [
|
||||
InlineConfig(id="tp2", tp_size=2),
|
||||
InlineConfig(id="ep2", tp_size=2, enable_expert_parallel=True),
|
||||
InlineConfig(
|
||||
id="ep2_eplb",
|
||||
tp_size=2,
|
||||
enable_expert_parallel=True,
|
||||
enable_eplb=True,
|
||||
),
|
||||
InlineConfig(id="pp2", pp_size=2),
|
||||
]
|
||||
|
||||
|
||||
def _inline_kwargs(config: InlineConfig, *, with_spec: bool) -> dict[str, Any]:
|
||||
kwargs: dict[str, Any] = {
|
||||
"model": DEEPSEEK_MTP_MAIN_RANDOM,
|
||||
"tensor_parallel_size": config.tp_size,
|
||||
"pipeline_parallel_size": config.pp_size,
|
||||
"enable_expert_parallel": config.enable_expert_parallel,
|
||||
"max_model_len": MAX_MODEL_LEN,
|
||||
"gpu_memory_utilization": GPU_MEM_UTIL,
|
||||
"enforce_eager": True,
|
||||
"trust_remote_code": True,
|
||||
"disable_log_stats": False,
|
||||
# MLA + batch invariance currently disables prefix caching at runtime
|
||||
# (see vllm/v1/attention/backends/mla/common.py); set explicitly so the
|
||||
# configuration is unambiguous.
|
||||
"enable_prefix_caching": False,
|
||||
}
|
||||
if config.enable_eplb:
|
||||
kwargs["enable_eplb"] = True
|
||||
# Rearrangement first fires after step_interval // 4 forward steps
|
||||
# (the step counter starts at 3/4 of step_interval, see
|
||||
# vllm/distributed/eplb/eplb_state.py). Keep these small so the EPLB
|
||||
# routine actually runs within the short MAX_TOKENS generation instead
|
||||
# of never triggering.
|
||||
kwargs["eplb_config"] = {
|
||||
"num_redundant_experts": config.tp_size,
|
||||
"window_size": 2,
|
||||
"step_interval": 4,
|
||||
"log_balancedness": False,
|
||||
}
|
||||
if with_spec:
|
||||
kwargs["speculative_config"] = {
|
||||
"method": "mtp",
|
||||
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
|
||||
"num_speculative_tokens": 1,
|
||||
}
|
||||
return kwargs
|
||||
|
||||
|
||||
def _generate_token_ids_inline(llm: LLM) -> tuple[int, ...]:
|
||||
outputs = llm.generate(
|
||||
[PROMPT],
|
||||
SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS, ignore_eos=True),
|
||||
)
|
||||
assert outputs and outputs[0].outputs, "expected one completion"
|
||||
token_ids = tuple(outputs[0].outputs[0].token_ids)
|
||||
assert len(token_ids) == MAX_TOKENS, (
|
||||
f"expected {MAX_TOKENS} generated tokens, got {len(token_ids)}: {token_ids}"
|
||||
)
|
||||
return token_ids
|
||||
|
||||
|
||||
def _spec_decode_num_drafts(metrics: list[Metric]) -> int:
|
||||
name2metric = {m.name: m for m in metrics}
|
||||
counter = name2metric.get("vllm:spec_decode_num_drafts")
|
||||
assert counter is not None, (
|
||||
"spec_decode_num_drafts metric missing; check disable_log_stats=False"
|
||||
)
|
||||
return int(counter.value)
|
||||
|
||||
|
||||
def _enable_batch_invariance(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# This test exercises DeepSeek MLA prefill. ROCm's upstream FlashAttention
|
||||
# varlen API lacks the num_splits argument used by batch invariance, so
|
||||
# explicitly override any ambient setting on that path.
|
||||
if current_platform.is_cuda():
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
else:
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config",
|
||||
[
|
||||
pytest.param(c, id=c.id, marks=multi_gpu_marks(num_gpus=2))
|
||||
for c in INLINE_CONFIGS
|
||||
],
|
||||
)
|
||||
def test_deepseek_mtp_load_inline(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config: InlineConfig,
|
||||
vllm_runner,
|
||||
):
|
||||
"""MTP loads and drafts under TP/EP/EPLB; spec output matches no-spec greedy."""
|
||||
if config.skip_reason is not None:
|
||||
pytest.skip(config.skip_reason)
|
||||
|
||||
# Reduces run-to-run nondeterminism so spec / no-spec stay close;
|
||||
# see tests/v1/distributed/test_eagle_dp.py for the same pattern.
|
||||
_enable_batch_invariance(monkeypatch)
|
||||
|
||||
spec_kwargs = _inline_kwargs(config, with_spec=True)
|
||||
spec_model = spec_kwargs.pop("model")
|
||||
with vllm_runner(
|
||||
spec_model,
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**spec_kwargs,
|
||||
) as spec_runner:
|
||||
spec_tokens = _generate_token_ids_inline(spec_runner.llm)
|
||||
n_drafts = _spec_decode_num_drafts(spec_runner.llm.get_metrics())
|
||||
|
||||
no_spec_kwargs = _inline_kwargs(config, with_spec=False)
|
||||
no_spec_model = no_spec_kwargs.pop("model")
|
||||
with vllm_runner(
|
||||
no_spec_model,
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
compilation_config=CompilationConfig(),
|
||||
**no_spec_kwargs,
|
||||
) as no_spec_runner:
|
||||
no_spec_tokens = _generate_token_ids_inline(no_spec_runner.llm)
|
||||
|
||||
# Non-vacuity: a silently-broken MTP drafter that falls back to
|
||||
# verifier-only decoding would still produce matching output below.
|
||||
assert n_drafts > 0, (
|
||||
f"MTP drafter never fired under {config.id}: vllm:spec_decode_num_drafts == 0"
|
||||
)
|
||||
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
|
||||
print(f"\n{config.id}: spec/no-spec match_ratio={match_ratio:.3f}")
|
||||
assert match_ratio >= MIN_MATCH_RATIO, (
|
||||
f"Spec / no-spec output divergence under {config.id}: "
|
||||
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
|
||||
f" spec_tokens = {spec_tokens}\n"
|
||||
f" no_spec_tokens= {no_spec_tokens}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"dp_size",
|
||||
[
|
||||
pytest.param(2, marks=pytest.mark.distributed(num_gpus=2), id="dp2"),
|
||||
pytest.param(1, id="dp1"),
|
||||
],
|
||||
)
|
||||
async def test_deepseek_mtp_load_dp(monkeypatch: pytest.MonkeyPatch, dp_size: int):
|
||||
"""MTP loads under DP (on and off) via AsyncLLM; spec matches no-spec greedy."""
|
||||
if torch.accelerator.device_count() < dp_size:
|
||||
pytest.skip(f"dp{dp_size} requires at least {dp_size} GPUs")
|
||||
|
||||
_enable_batch_invariance(monkeypatch)
|
||||
|
||||
base_args = AsyncEngineArgs(
|
||||
model=DEEPSEEK_MTP_MAIN_RANDOM,
|
||||
tensor_parallel_size=1,
|
||||
data_parallel_size=dp_size,
|
||||
data_parallel_backend="mp",
|
||||
max_model_len=MAX_MODEL_LEN,
|
||||
gpu_memory_utilization=GPU_MEM_UTIL,
|
||||
enforce_eager=True,
|
||||
trust_remote_code=True,
|
||||
enable_prefix_caching=False,
|
||||
)
|
||||
spec_args = replace(
|
||||
base_args,
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
|
||||
"num_speculative_tokens": 1,
|
||||
},
|
||||
)
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=MAX_TOKENS,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.FINAL_ONLY,
|
||||
temperature=0.0,
|
||||
)
|
||||
|
||||
async def _generate(args: AsyncEngineArgs, request_id: str) -> tuple[int, ...]:
|
||||
try:
|
||||
async with AsyncExitStack() as stack:
|
||||
engine = AsyncLLM.from_engine_args(args)
|
||||
stack.callback(engine.shutdown)
|
||||
async for out in engine.generate(
|
||||
request_id=request_id,
|
||||
prompt=PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
token_ids = tuple(out.outputs[0].token_ids)
|
||||
assert len(token_ids) == MAX_TOKENS, (
|
||||
f"{request_id}: expected {MAX_TOKENS} generated tokens, "
|
||||
f"got {len(token_ids)}: {token_ids}"
|
||||
)
|
||||
return token_ids
|
||||
raise AssertionError("AsyncLLM produced no output")
|
||||
finally:
|
||||
torch.accelerator.empty_cache()
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
spec_tokens = await asyncio.wait_for(
|
||||
_generate(spec_args, f"deepseek-mtp-dp{dp_size}-spec"), timeout=600
|
||||
)
|
||||
no_spec_tokens = await asyncio.wait_for(
|
||||
_generate(base_args, f"deepseek-mtp-dp{dp_size}-no-spec"), timeout=600
|
||||
)
|
||||
|
||||
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
|
||||
print(f"\ndp{dp_size}: spec/no-spec match_ratio={match_ratio:.3f}")
|
||||
assert match_ratio >= MIN_MATCH_RATIO, (
|
||||
f"Spec / no-spec output divergence under dp{dp_size}: "
|
||||
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
|
||||
f" spec_tokens = {spec_tokens}\n"
|
||||
f" no_spec_tokens= {no_spec_tokens}"
|
||||
)
|
||||
@@ -1,103 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Batch-sharded sampling must be a drop-in for replicated sampling under
|
||||
speculative decoding.
|
||||
|
||||
The non-spec arm of this claim lives in tests/v1/e2e/general/
|
||||
test_sharded_sampling.py. Spec decode is the harder case: draft tokens give
|
||||
each request a different number of logits rows, so the shard plan's
|
||||
per-request arithmetic and the rejection sampler are both exercised.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import wait_for_memory_to_settle
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
|
||||
from .utils import _skip_if_insufficient_gpus_for_tp, get_test_prompts, greedy_sampling
|
||||
|
||||
# Even with in-process scheduling, near-tie tokens still flip on up to 3 of 20
|
||||
# prompts in CI, greedy and seeded. A sharding bug diverges wholesale instead.
|
||||
MAX_DIVERGENT_PROMPTS = 3
|
||||
|
||||
|
||||
def _is_sharded_sampling_active(worker) -> bool:
|
||||
return worker.model_runner.batch_sharder is not None
|
||||
|
||||
|
||||
def test_mtp_sharded_sampling_equivalence(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Batch-sharded sampling must match replicated sampling under MTP spec
|
||||
decoding, up to measured near-tie noise."""
|
||||
tp_size = 2
|
||||
_skip_if_insufficient_gpus_for_tp(tp_size)
|
||||
model_name = "Qwen/Qwen3.5-0.8B-Base"
|
||||
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=20)
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
# Batch-sharded sampling only exists in the V2 model runner.
|
||||
m.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
# Required for the collective_rpc mode check below.
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
# Queue every request before the first step, so both boots schedule
|
||||
# the same batches -- see tests/v1/e2e/general/test_sharded_sampling.py.
|
||||
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
|
||||
def run(disable_sharding: bool):
|
||||
llm = LLM(
|
||||
model=model_name,
|
||||
tensor_parallel_size=tp_size,
|
||||
enable_batch_sharded_sampling=not disable_sharding,
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 1,
|
||||
"max_model_len": 2048,
|
||||
},
|
||||
max_model_len=2048,
|
||||
limit_mm_per_prompt={"image": 0, "video": 0},
|
||||
# More requests than ranks, so round-robin slot ownership
|
||||
# splits the batch across both ranks.
|
||||
max_num_seqs=len(test_prompts),
|
||||
# Timing-based kernel selection is the dominant source of
|
||||
# cross-boot numeric noise; disable for a tight comparison.
|
||||
kernel_config={"enable_flashinfer_autotune": False},
|
||||
)
|
||||
try:
|
||||
# Guard against a vacuous comparison: verify every worker is
|
||||
# in the intended sampling mode.
|
||||
modes = llm.llm_engine.collective_rpc(_is_sharded_sampling_active)
|
||||
assert all(mode == (not disable_sharding) for mode in modes)
|
||||
greedy = llm.chat(test_prompts, greedy_sampling())
|
||||
seeded = llm.chat(
|
||||
test_prompts,
|
||||
SamplingParams(temperature=1.0, seed=33, max_tokens=10),
|
||||
)
|
||||
return greedy, seeded
|
||||
finally:
|
||||
del llm
|
||||
torch.accelerator.empty_cache()
|
||||
cleanup_dist_env_and_memory()
|
||||
wait_for_memory_to_settle()
|
||||
|
||||
ref_greedy, ref_seeded = run(disable_sharding=True)
|
||||
shard_greedy, shard_seeded = run(disable_sharding=False)
|
||||
|
||||
# A sharding bug shows up as wholesale divergence, not isolated flips.
|
||||
for name, ref_outputs, shard_outputs in (
|
||||
("greedy", ref_greedy, shard_greedy),
|
||||
("seeded", ref_seeded, shard_seeded),
|
||||
):
|
||||
divergent = []
|
||||
for i, (ref, out) in enumerate(zip(ref_outputs, shard_outputs)):
|
||||
if list(ref.outputs[0].token_ids) != list(out.outputs[0].token_ids):
|
||||
divergent.append(i)
|
||||
print(
|
||||
f"{name} prompt {i} diverged:\n"
|
||||
f" replicated: {ref.outputs[0].text!r}\n"
|
||||
f" sharded: {out.outputs[0].text!r}"
|
||||
)
|
||||
assert len(divergent) <= MAX_DIVERGENT_PROMPTS, (
|
||||
f"{name}: {len(divergent)}/{len(ref_outputs)} prompts diverged "
|
||||
f"at {divergent}, beyond near-tie noise"
|
||||
)
|
||||
@@ -1,136 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU chunked-prefill / prefix-caching correctness for linear-attention models."""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.models.utils import check_logprobs_close
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TokensPrompt
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.cpu_model
|
||||
|
||||
if not current_platform.is_cpu():
|
||||
pytest.skip("skipping CPU-only tests", allow_module_level=True)
|
||||
|
||||
# Bound the KV cache so the run does not scale with host memory; these engines
|
||||
# only need a few thousand tokens.
|
||||
os.environ.setdefault("VLLM_CPU_KVCACHE_SPACE", "1")
|
||||
|
||||
MODEL = "Qwen/Qwen3.5-0.8B"
|
||||
CHUNK_TOKENS = 128 # max_num_batched_tokens for the chunked engine
|
||||
NUM_LOGPROBS = 5
|
||||
SP = SamplingParams(max_tokens=32, temperature=0, logprobs=NUM_LOGPROBS)
|
||||
|
||||
|
||||
def _long_prompt(repeat: int) -> str:
|
||||
return "Solve the following arithmetic step by step. " * repeat + "What is 7*8?"
|
||||
|
||||
|
||||
# Prompts long enough to span several CHUNK_TOKENS-sized chunks; a single-chunk
|
||||
# prompt is bit-identical to full prefill regardless of the bug.
|
||||
PROMPTS = [_long_prompt(r) for r in (40, 60, 80)]
|
||||
# Spans several full cache blocks; prefix caching only reuses complete blocks.
|
||||
PREFIX_PROMPT = "You are a helpful assistant. " * 230 + " Now answer: what is 2+2?"
|
||||
|
||||
|
||||
def _make_llm(**overrides) -> LLM:
|
||||
base = dict(
|
||||
model=MODEL,
|
||||
dtype="bfloat16",
|
||||
max_model_len=2048,
|
||||
enforce_eager=True,
|
||||
trust_remote_code=True,
|
||||
)
|
||||
base.update(overrides)
|
||||
return LLM(**base)
|
||||
|
||||
|
||||
def _tuples(outputs) -> list[tuple[list[int], str, object]]:
|
||||
"""(token_ids, text, sample_logprobs) per request, for check_logprobs_close."""
|
||||
return [
|
||||
(list(o.outputs[0].token_ids), o.outputs[0].text, o.outputs[0].logprobs)
|
||||
for o in outputs
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def full_prefill_refs():
|
||||
"""Reference (ids, text, logprobs) for PROMPTS and PREFIX_PROMPT, full prefill."""
|
||||
llm = _make_llm(enable_chunked_prefill=False, enable_prefix_caching=False)
|
||||
refs = _tuples(llm.generate(PROMPTS, SP))
|
||||
prefix_ref = _tuples(llm.generate([PREFIX_PROMPT], SP))[0]
|
||||
del llm
|
||||
return refs, prefix_ref
|
||||
|
||||
|
||||
def test_chunked_prefill_matches_full_prefill(full_prefill_refs):
|
||||
"""Batched multi-chunk prefill must stay close to per-prompt full prefill.
|
||||
|
||||
Prompts are scheduled together so the scheduler interleaves prefill chunks
|
||||
across requests (the cross-request path where the accuracy gap was strongest).
|
||||
"""
|
||||
refs, _ = full_prefill_refs
|
||||
llm = _make_llm(
|
||||
enable_chunked_prefill=True,
|
||||
max_num_batched_tokens=CHUNK_TOKENS,
|
||||
enable_prefix_caching=False,
|
||||
)
|
||||
got = _tuples(llm.generate(PROMPTS, SP))
|
||||
del llm
|
||||
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=refs,
|
||||
outputs_1_lst=got,
|
||||
name_0="full_prefill",
|
||||
name_1="chunked_prefill",
|
||||
)
|
||||
|
||||
|
||||
def test_prefix_cache_hit_matches_cold_cache(full_prefill_refs):
|
||||
"""A prefix-cache hit must stay close to the cold-cache (reference) output.
|
||||
|
||||
The warm run continues prefill from the restored GDN state; the
|
||||
num_cached_tokens check guards against a vacuous (no-hit) pass.
|
||||
"""
|
||||
_, ref = full_prefill_refs
|
||||
llm = _make_llm(enable_prefix_caching=True)
|
||||
llm.generate([PREFIX_PROMPT], SP) # prime the cache
|
||||
warm_out = llm.generate([PREFIX_PROMPT], SP)[0]
|
||||
warm = _tuples([warm_out])[0]
|
||||
del llm
|
||||
|
||||
assert warm_out.num_cached_tokens > 0, (
|
||||
"expected a prefix-cache hit but num_cached_tokens=0; "
|
||||
"PREFIX_PROMPT may be shorter than one cache block"
|
||||
)
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=[ref],
|
||||
outputs_1_lst=[warm],
|
||||
name_0="cold_cache",
|
||||
name_1="warm_cache",
|
||||
)
|
||||
|
||||
|
||||
def test_prefix_cache_hit_reaches_last_full_block():
|
||||
"""A repeated prompt must hit every full block of the hybrid block size.
|
||||
|
||||
The workers raise the block size to fit the GDN state pages, and the
|
||||
engine core reruns its config checks after its handshake; the raised size
|
||||
must survive them, or the prefill's state checkpoint misses the block
|
||||
boundaries and nothing is reused. One chunk holds the whole prompt.
|
||||
"""
|
||||
llm = _make_llm(enable_prefix_caching=True, max_num_batched_tokens=2048)
|
||||
block_size = llm.llm_engine.vllm_config.cache_config.block_size
|
||||
# Ends mid-block: only the last full block's state can be reused.
|
||||
num_tokens = block_size + block_size // 2
|
||||
assert num_tokens <= 2048
|
||||
prompt = TokensPrompt(prompt_token_ids=[1000 + i for i in range(num_tokens)])
|
||||
sp = SamplingParams(max_tokens=1)
|
||||
hits = [llm.generate(prompt, sp)[0].num_cached_tokens for _ in range(2)]
|
||||
del llm
|
||||
|
||||
assert hits == [0, block_size]
|
||||
@@ -1,167 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU speculative-decoding end-to-end correctness."""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.models.utils import check_logprobs_close
|
||||
from tests.v1.e2e.spec_decode.utils import compute_acceptance_len
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
pytestmark = pytest.mark.cpu_model
|
||||
|
||||
if not current_platform.is_cpu():
|
||||
pytest.skip("skipping CPU-only tests", allow_module_level=True)
|
||||
|
||||
# Bound the KV cache so the run does not scale with host memory.
|
||||
os.environ.setdefault("VLLM_CPU_KVCACHE_SPACE", "1")
|
||||
|
||||
MODEL = "Qwen/Qwen3-0.6B"
|
||||
NUM_LOGPROBS = 5
|
||||
SP = SamplingParams(max_tokens=48, temperature=0, logprobs=NUM_LOGPROBS)
|
||||
|
||||
# Repetitive prompts so the ngram proposer finds matches and actually drafts;
|
||||
# without hits the run is indistinguishable from plain decoding.
|
||||
PROMPTS = [
|
||||
"The capital of France is Paris. The capital of Italy is Rome. "
|
||||
"The capital of Spain is Madrid. The capital of France is",
|
||||
"def add(a, b):\n return a + b\n\ndef sub(a, b):\n return a - b\n\n"
|
||||
"def mul(a, b):\n return",
|
||||
"one two three four five one two three four five one two three four",
|
||||
]
|
||||
|
||||
|
||||
def _make_llm(**overrides) -> LLM:
|
||||
base = dict(
|
||||
model=MODEL,
|
||||
dtype="bfloat16",
|
||||
max_model_len=1024,
|
||||
disable_log_stats=False,
|
||||
)
|
||||
base.update(overrides)
|
||||
return LLM(**base)
|
||||
|
||||
|
||||
def _tuples(outputs) -> list[tuple[list[int], str, object]]:
|
||||
return [
|
||||
(list(o.outputs[0].token_ids), o.outputs[0].text, o.outputs[0].logprobs)
|
||||
for o in outputs
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def baseline_refs():
|
||||
llm = _make_llm()
|
||||
refs = _tuples(llm.generate(PROMPTS, SP))
|
||||
del llm
|
||||
return refs
|
||||
|
||||
|
||||
def _spec_metric(llm: LLM, name: str) -> float:
|
||||
for metric in llm.get_metrics():
|
||||
if metric.name == name:
|
||||
return float(getattr(metric, "value", 0.0))
|
||||
return 0.0
|
||||
|
||||
|
||||
def test_ngram_spec_decode_matches_baseline(baseline_refs):
|
||||
"""Greedy output must be unchanged by speculative decoding.
|
||||
|
||||
The drafted-token check keeps the test from passing vacuously when the
|
||||
proposer silently produces nothing.
|
||||
"""
|
||||
llm = _make_llm(
|
||||
speculative_config={
|
||||
"method": "ngram",
|
||||
"prompt_lookup_max": 5,
|
||||
"prompt_lookup_min": 3,
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
)
|
||||
got = _tuples(llm.generate(PROMPTS, SP))
|
||||
drafted = _spec_metric(llm, "vllm:spec_decode_num_draft_tokens")
|
||||
accepted = _spec_metric(llm, "vllm:spec_decode_num_accepted_tokens")
|
||||
del llm
|
||||
|
||||
assert drafted > 0, "ngram proposer drafted no tokens; the test would be vacuous"
|
||||
assert accepted > 0, f"no draft tokens accepted out of {drafted} drafted"
|
||||
|
||||
check_logprobs_close(
|
||||
outputs_0_lst=baseline_refs,
|
||||
outputs_1_lst=got,
|
||||
name_0="no_spec_decode",
|
||||
name_1="ngram_spec_decode",
|
||||
)
|
||||
|
||||
|
||||
SMOKE_PROMPTS = [
|
||||
"The capital of France is",
|
||||
"2 + 2 equals",
|
||||
"In one word, the color of the sky is",
|
||||
"Q: If a train travels 60 miles in 1.5 hours, what is its average speed?\nA:",
|
||||
]
|
||||
SMOKE_SP = SamplingParams(temperature=0.0, max_tokens=32, ignore_eos=True)
|
||||
|
||||
# Methods routed to the V2 runner, using the same target/draft pairs as the GPU
|
||||
# suite. MTP needs no separate draft checkpoint: its speculator layer is
|
||||
# trained jointly with, and shipped inside, the target model's own weights.
|
||||
SMOKE_CONFIGS = [
|
||||
pytest.param(
|
||||
"meta-llama/Llama-3.2-1B-Instruct",
|
||||
{
|
||||
"method": "eagle3",
|
||||
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
id="eagle3",
|
||||
),
|
||||
pytest.param(
|
||||
"Qwen/Qwen3-4B",
|
||||
{
|
||||
"method": "dflash",
|
||||
"model": "z-lab/Qwen3-4B-DFlash-b16",
|
||||
# The checkpoint allows 16, but accepted tokens plateau around 64
|
||||
# regardless, so a larger draft only burns CPU on rejected tokens.
|
||||
"num_speculative_tokens": 4,
|
||||
},
|
||||
id="dflash",
|
||||
),
|
||||
pytest.param(
|
||||
"Qwen/Qwen3.5-0.8B",
|
||||
{
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 3,
|
||||
},
|
||||
id="mtp",
|
||||
),
|
||||
]
|
||||
|
||||
# Measured 1.85 (eagle3), 1.99 (dflash), 2.29 (mtp) on CPU; this floor leaves
|
||||
# room for numeric drift while still failing if speculation stops paying off.
|
||||
MIN_ACCEPTANCE_LEN = 1.5
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not HAS_TRITON, reason="the V2 runner needs triton-cpu, which CI builds"
|
||||
)
|
||||
@pytest.mark.parametrize("model,speculative_config", SMOKE_CONFIGS)
|
||||
def test_v2_speculator_smoke(model: str, speculative_config: dict):
|
||||
"""Gates that drafts are accepted often enough for speculation to pay off."""
|
||||
llm = _make_llm(model=model, speculative_config=speculative_config)
|
||||
try:
|
||||
assert llm.llm_engine.vllm_config.use_v2_model_runner, (
|
||||
f"{speculative_config['method']} fell back to the V1 runner; "
|
||||
"this test is meant to cover the V2 path"
|
||||
)
|
||||
llm.generate(SMOKE_PROMPTS, SMOKE_SP)
|
||||
acceptance = compute_acceptance_len(llm.get_metrics())
|
||||
assert acceptance >= MIN_ACCEPTANCE_LEN, (
|
||||
f"acceptance length {acceptance:.3f} below {MIN_ACCEPTANCE_LEN}; "
|
||||
"drafts are being rejected far more than expected"
|
||||
)
|
||||
finally:
|
||||
del llm
|
||||
@@ -1,212 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
from ...utils import large_gpu_mark
|
||||
|
||||
QWEN_MODEL = "Qwen/Qwen3.5-4B"
|
||||
QWEN_KV_CACHE_BYTES = 12 << 30
|
||||
HYBRID_MTP_MODELS = [
|
||||
pytest.param(
|
||||
QWEN_MODEL,
|
||||
marks=[large_gpu_mark(min_gb=30)],
|
||||
id="qwen",
|
||||
),
|
||||
pytest.param(
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4",
|
||||
marks=[large_gpu_mark(min_gb=80)]
|
||||
+ [
|
||||
pytest.mark.skipif(
|
||||
not current_platform.is_cuda(),
|
||||
reason="modelopt quantization is supported only on CUDA",
|
||||
)
|
||||
],
|
||||
id="nemotron",
|
||||
),
|
||||
]
|
||||
|
||||
# A trivial request with a short prompt to ensure we run a mixed batch
|
||||
SMALL_MESSAGE = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "The secret beta value is 64. What is the secret beta?",
|
||||
}
|
||||
]
|
||||
|
||||
# Sample prompt with a bunch of filler in between the critical fact and the request.
|
||||
# Both parts need to be processed properly for the model to generate the correct answer
|
||||
MESSAGES = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
"Important: The secret number is 42. "
|
||||
"The sky is green in this hypothetical world. "
|
||||
"Apples grow on trees in the forest. "
|
||||
"Rivers flow through the valleys and mountains. "
|
||||
"Birds sing songs in the early morning light. "
|
||||
"The weather today is sunny with clear skies ahead. "
|
||||
"Flowers bloom in the garden during spring season. "
|
||||
"Now answer with ONLY the number and nothing else: "
|
||||
"What is the secret number plus one?"
|
||||
),
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_name",
|
||||
HYBRID_MTP_MODELS,
|
||||
)
|
||||
@pytest.mark.parametrize("enable_prefix_caching", [False, True])
|
||||
def test_mtp_speculative_mixed_batch_short_prefill(
|
||||
vllm_runner, model_name, enable_prefix_caching
|
||||
):
|
||||
"""Test to ensure MTP speculative decoding correctly handles
|
||||
short prefill chunks that fall below the reorder_batch_threshold."""
|
||||
# Set so large that both prefills will be classified as decodes in a mixed batch
|
||||
# note, with prefix caching we require chunk_size >= mamba_block_size
|
||||
chunk_size = 256 if not enable_prefix_caching else 2048
|
||||
num_draft_tokens = 100
|
||||
|
||||
with vllm_runner(
|
||||
model_name,
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": num_draft_tokens,
|
||||
},
|
||||
max_num_batched_tokens=chunk_size,
|
||||
max_num_seqs=4,
|
||||
max_model_len=512,
|
||||
kv_cache_memory_bytes=QWEN_KV_CACHE_BYTES if model_name == QWEN_MODEL else None,
|
||||
enforce_eager=True,
|
||||
tensor_parallel_size=1,
|
||||
trust_remote_code=True,
|
||||
enable_chunked_prefill=True,
|
||||
enable_prefix_caching=enable_prefix_caching,
|
||||
) as llm:
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=128,
|
||||
)
|
||||
|
||||
# First small message gets prefilled first, under normal conditions since the
|
||||
# batch is not yet mixed. Then the second prefill arrives as a mixed batch, but
|
||||
# is shorter than num_speculative_tokens, so it gets misclassified as a decode
|
||||
# and processed with the wrong state management logic, causing the critical
|
||||
# fact from the first chunk to be lost and the model to generate nonsense.
|
||||
outputs = llm.get_llm().chat(
|
||||
[SMALL_MESSAGE, MESSAGES],
|
||||
sampling_params,
|
||||
chat_template_kwargs={"enable_thinking": False},
|
||||
)
|
||||
|
||||
responses = []
|
||||
for output in outputs:
|
||||
generated_text = output.outputs[0].text
|
||||
print(f"Generated text: {generated_text!r}")
|
||||
responses.append(generated_text)
|
||||
|
||||
assert "64" in responses[0], (
|
||||
"The first response should contain the correct value of 64."
|
||||
)
|
||||
assert "43" in responses[1], (
|
||||
"The second response should contain the correct value of 42+1=43."
|
||||
)
|
||||
|
||||
|
||||
def _get_mamba_block_size(llm) -> int:
|
||||
scheduler = llm.llm_engine.engine_core.engine_core.scheduler
|
||||
block_sizes = {
|
||||
group.kv_cache_spec.block_size
|
||||
for group in scheduler.kv_cache_config.kv_cache_groups
|
||||
if isinstance(group.kv_cache_spec, MambaSpec)
|
||||
}
|
||||
assert len(block_sizes) == 1
|
||||
block_size = block_sizes.pop()
|
||||
assert scheduler.cache_config.block_size == block_size
|
||||
return block_size
|
||||
|
||||
|
||||
def _build_access_code_manual(tokenizer, target_tokens: int) -> tuple[str, list[str]]:
|
||||
codes = ["605341", "693278", "597596", "751982"]
|
||||
header = "Memorize this facility manual and its access codes.\n\n"
|
||||
facts = "".join(
|
||||
f"The access code for vault-{i:02d} is {code}.\n"
|
||||
for i, code in enumerate(codes)
|
||||
)
|
||||
filler = "Routine facility inspections are recorded in the audit ledger every day. "
|
||||
manual = header + facts
|
||||
while len(tokenizer.encode(manual)) < target_tokens:
|
||||
manual = header + filler + manual.removeprefix(header)
|
||||
return manual, codes
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=30)
|
||||
def test_qwen_mtp_mamba_prefix_cache_hit_is_bounded(vllm_runner, monkeypatch):
|
||||
"""MTP must not extend a hybrid Mamba hit past the attention hit."""
|
||||
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
|
||||
|
||||
with vllm_runner(
|
||||
QWEN_MODEL,
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=8192,
|
||||
kv_cache_memory_bytes=QWEN_KV_CACHE_BYTES,
|
||||
block_size=None,
|
||||
enforce_eager=True,
|
||||
enable_chunked_prefill=True,
|
||||
enable_prefix_caching=True,
|
||||
speculative_config={"method": "mtp", "num_speculative_tokens": 2},
|
||||
) as runner:
|
||||
llm = runner.get_llm()
|
||||
block_size = _get_mamba_block_size(llm)
|
||||
manual, codes = _build_access_code_manual(
|
||||
llm.get_tokenizer(), 2 * block_size - 192
|
||||
)
|
||||
manual_tokens = len(llm.get_tokenizer().encode(manual))
|
||||
assert block_size < manual_tokens < 2 * block_size
|
||||
|
||||
wave1_prompts = [
|
||||
manual
|
||||
+ f"\nDescribe the audit procedure for vault-{i:02d} in detail.\nAnswer:"
|
||||
for i in range(len(codes))
|
||||
]
|
||||
decode_tokens = 2 * block_size - manual_tokens + 96
|
||||
wave1_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
min_tokens=decode_tokens,
|
||||
max_tokens=decode_tokens,
|
||||
ignore_eos=True,
|
||||
)
|
||||
wave1_outputs = llm.generate(wave1_prompts, wave1_params)
|
||||
|
||||
wave2_prompts = [
|
||||
prompt
|
||||
+ output.outputs[0].text
|
||||
+ f"\n\nWhat is the access code for vault-{i:02d}? Answer:"
|
||||
for i, (prompt, output) in enumerate(zip(wave1_prompts, wave1_outputs))
|
||||
]
|
||||
warm_params = SamplingParams(temperature=0.0, max_tokens=24, stop=["\n"])
|
||||
cold_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=24,
|
||||
stop=["\n"],
|
||||
skip_reading_prefix_cache=True,
|
||||
)
|
||||
warm_outputs = llm.generate(wave2_prompts, warm_params)
|
||||
cold_outputs = llm.generate(wave2_prompts, cold_params)
|
||||
|
||||
cached_tokens = [output.num_cached_tokens for output in warm_outputs]
|
||||
assert max(cached_tokens) == block_size
|
||||
|
||||
for arm, outputs in (("warm", warm_outputs), ("cold", cold_outputs)):
|
||||
missed = [
|
||||
i
|
||||
for i, (code, output) in enumerate(zip(codes, outputs))
|
||||
if code not in output.outputs[0].text
|
||||
]
|
||||
assert not missed, f"{arm} cache missed access codes for prompts {missed}"
|
||||
@@ -1,202 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NIXL request failure isolation with real E/PD servers and an injected NACK.
|
||||
|
||||
Requires two CUDA GPUs and NIXL. Set MODEL to override the small default model.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
import msgspec
|
||||
import pytest
|
||||
import zmq
|
||||
import zmq.asyncio
|
||||
from PIL import Image
|
||||
|
||||
from examples.disaggregated.disaggregated_encoder.disagg_epd_proxy import (
|
||||
rewrite_for_decode,
|
||||
)
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.protocol import (
|
||||
XferAck,
|
||||
XferReq,
|
||||
XferStatus,
|
||||
)
|
||||
from vllm.multimodal.utils import encode_image_url
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
|
||||
MODEL = os.environ.get("MODEL", "Qwen/Qwen2.5-VL-3B-Instruct")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def servers():
|
||||
pytest.importorskip("nixl")
|
||||
if not current_platform.is_cuda() or current_platform.device_count() < 2:
|
||||
pytest.skip("Requires two CUDA GPUs")
|
||||
devices = os.environ.get("CUDA_VISIBLE_DEVICES", "0,1").split(",")
|
||||
common = [
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--max-model-len",
|
||||
"4096",
|
||||
"--max-num-seqs",
|
||||
"4",
|
||||
"--gpu-memory-utilization",
|
||||
"0.7",
|
||||
"--no-enable-prefix-caching",
|
||||
]
|
||||
|
||||
def config(role):
|
||||
return json.dumps(
|
||||
{
|
||||
"ec_connector": "ECCPUConnector",
|
||||
"ec_role": role,
|
||||
"ec_connector_extra_config": {
|
||||
"ec_enable_nixl": True,
|
||||
"ec_cpu_bytes": 64 << 20,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
with (
|
||||
RemoteOpenAIServer(
|
||||
MODEL,
|
||||
common
|
||||
+ [
|
||||
"--mm-encoder-only",
|
||||
"--disable-hybrid-kv-cache-manager",
|
||||
"--ec-transfer-config",
|
||||
config("ec_producer"),
|
||||
],
|
||||
env_dict={
|
||||
"CUDA_VISIBLE_DEVICES": devices[0],
|
||||
"VLLM_EC_SIDE_CHANNEL_HOST": "127.0.0.1",
|
||||
"VLLM_EC_SIDE_CHANNEL_PORT": str(get_open_port()),
|
||||
},
|
||||
) as encoder,
|
||||
RemoteOpenAIServer(
|
||||
MODEL,
|
||||
common
|
||||
+ ["--enable-mm-embeds", "--ec-transfer-config", config("ec_consumer")],
|
||||
env_dict={"CUDA_VISIBLE_DEVICES": devices[1]},
|
||||
) as consumer,
|
||||
):
|
||||
yield encoder, consumer
|
||||
|
||||
|
||||
async def _post(session, server, body):
|
||||
async with session.post(server.url_for("v1/chat/completions"), json=body) as r:
|
||||
return r.status, await r.json()
|
||||
|
||||
|
||||
async def _encode(session, encoder):
|
||||
image = Image.open(Path(__file__).with_name("hato.jpg")).convert("RGB")
|
||||
image.thumbnail((224, 224))
|
||||
item_uuid = uuid.uuid4().hex # Avoid both EC and processor cache hits.
|
||||
body = {
|
||||
"model": MODEL,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": encode_image_url(image)},
|
||||
"uuid": item_uuid,
|
||||
},
|
||||
{"type": "text", "text": "Describe the image briefly."},
|
||||
],
|
||||
}
|
||||
],
|
||||
"max_tokens": 16,
|
||||
"temperature": 0,
|
||||
"chat_template_kwargs": {"enable_thinking": False},
|
||||
}
|
||||
status, result = await _post(session, encoder, body)
|
||||
assert status == 200, result
|
||||
params = result["ec_transfer_params"]
|
||||
assert len(params) == 1, params
|
||||
((mm_hash, handle),) = params.items()
|
||||
assert handle["metadata"] and handle["peer_host"] and handle["size_bytes"] > 0
|
||||
rewritten = rewrite_for_decode(
|
||||
body,
|
||||
{
|
||||
0: {
|
||||
**handle["metadata"],
|
||||
"mm_hash": item_uuid,
|
||||
"ec_mm_hash": mm_hash,
|
||||
}
|
||||
},
|
||||
)
|
||||
assert rewritten["messages"][0]["content"][0]["type"] == "image_embeds"
|
||||
for request in (body, rewritten):
|
||||
request["ec_transfer_params"] = {item_uuid: copy.deepcopy(handle)}
|
||||
return body, rewritten, item_uuid
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("local_image", [False, True], ids=["metadata-only", "pixels"])
|
||||
async def test_missing_remote_encoding_is_request_scoped(servers, local_image):
|
||||
"""A terminal NACK must preserve local fallback and subsequent serving."""
|
||||
encoder, consumer = servers
|
||||
timeout = aiohttp.ClientTimeout(total=120)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
original, rewritten, mm_hash = await _encode(session, encoder)
|
||||
request = original if local_image else rewritten
|
||||
|
||||
# Keep the real encoder's shape/metadata; replace only the control peer.
|
||||
# The socket stays bound until completion, so no port or timing race is
|
||||
# needed to make the consumer receive NACK_MISSING.
|
||||
with zmq.asyncio.Context() as ctx, ctx.socket(zmq.ROUTER) as router:
|
||||
router.setsockopt(zmq.LINGER, 0)
|
||||
port = router.bind_to_random_port("tcp://127.0.0.1")
|
||||
request["ec_transfer_params"][mm_hash].update(
|
||||
peer_host="127.0.0.1", peer_port=port
|
||||
)
|
||||
|
||||
async def reject_read():
|
||||
identity, delimiter, payload = await router.recv_multipart()
|
||||
req = msgspec.msgpack.decode(payload, type=XferReq)
|
||||
assert req.mm_hash == mm_hash
|
||||
ack = XferAck(
|
||||
mm_hash=req.mm_hash,
|
||||
status=XferStatus.NACK_MISSING,
|
||||
session_id=req.session_id,
|
||||
)
|
||||
await router.send_multipart(
|
||||
[identity, delimiter, msgspec.msgpack.encode(ack)]
|
||||
)
|
||||
|
||||
rejection = asyncio.create_task(asyncio.wait_for(reject_read(), 30))
|
||||
try:
|
||||
status, result = await _post(session, consumer, request)
|
||||
# A frontend rejection must not count as successful injection.
|
||||
await rejection
|
||||
finally:
|
||||
rejection.cancel()
|
||||
await asyncio.gather(rejection, return_exceptions=True)
|
||||
|
||||
if local_image:
|
||||
assert status == 200, result
|
||||
assert result["choices"][0]["message"]["content"], result
|
||||
else:
|
||||
assert status == 500, result
|
||||
assert result["error"]["type"] == "InternalServerError", result
|
||||
|
||||
async with session.get(consumer.url_for("health")) as health:
|
||||
assert health.status == 200, "The failed read killed EngineCore"
|
||||
# A fresh metadata-only image must cross the real NIXL data path after
|
||||
# the fault, not just pass a frontend health check or hit a local cache.
|
||||
_, healthy, _ = await _encode(session, encoder)
|
||||
status, result = await _post(session, consumer, healthy)
|
||||
assert status == 200, result
|
||||
assert result["choices"][0]["message"]["content"], result
|
||||
@@ -1,974 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for ECCPUWorker.
|
||||
|
||||
The byte-level tests exercise real accelerator (CUDA/XPU/...) stream/event
|
||||
coordination against a real ``ECSharedRegion`` mmap and are skipped on hosts
|
||||
without an accelerator. The lifecycle tests don't fire any
|
||||
``current_platform.*`` device primitives and run anywhere.
|
||||
|
||||
Mocking policy
|
||||
--------------
|
||||
- ``create_ec_shared_region`` is patched to inject a real ``ECSharedRegion``
|
||||
(mmap backed) with deterministic small dimensions, so byte assertions
|
||||
hit the actual mmap. The real responsibility of the worker — block
|
||||
index → mmap byte mapping, stream coordination, dtype/shape — is
|
||||
exercised end to end against a real GPU.
|
||||
- ``is_pin_memory_available`` is patched per-test so the rank-gating
|
||||
path can be probed deterministically without depending on host caps.
|
||||
- The shutdown test bypasses ``__init__`` via ``object.__new__`` and
|
||||
injects a ``MagicMock`` region.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from collections import deque
|
||||
from unittest.mock import MagicMock, Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.ec_connector.unit.utils import create_ec_vllm_config
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.common import (
|
||||
ECCPUConnectorMetadata,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.ec_shared_region import (
|
||||
ECSharedRegion,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.worker import (
|
||||
ECCPUTransferDirection,
|
||||
ECCPUWorker,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# ── shape constants ──────────────────────────────────────────────────────────
|
||||
|
||||
# hidden_dim=8, dtype=fp16 (2 bytes) → block_size_bytes = 16, so one row of
|
||||
# encoder output fits in exactly one block.
|
||||
_HIDDEN_DIM = 8
|
||||
_DTYPE = torch.float16
|
||||
_BLOCK_SIZE_BYTES = _HIDDEN_DIM * _DTYPE.itemsize
|
||||
_NUM_BLOCKS = 8
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
_requires_accelerator = pytest.mark.skipif(
|
||||
not (current_platform.is_cuda() or current_platform.is_xpu()),
|
||||
reason="exercises real accelerator stream/event coordination in ECCPUWorker",
|
||||
)
|
||||
|
||||
# The memory-lifetime tests hold a copy back with `torch.cuda._sleep`, which the
|
||||
# CUDA-like platforms provide but XPU does not.
|
||||
_requires_cuda_alike = pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="stalling the compute stream requires a CUDA-like platform",
|
||||
)
|
||||
|
||||
_requires_swap_blocks_batch = pytest.mark.skipif(
|
||||
not hasattr(torch.ops._C_cache_ops, "swap_blocks_batch"),
|
||||
reason=(
|
||||
"installed vllm C++ extension predates the swap_blocks_batch op "
|
||||
"flush_saves/start_load_caches use; rebuild the extension to run this"
|
||||
),
|
||||
)
|
||||
|
||||
# Cycles to stall the compute stream for. Must comfortably outlast the host-side
|
||||
# work the lifetime tests do while a copy is deliberately held back — ~0.5 s on
|
||||
# a current datacenter GPU.
|
||||
_STALL_CYCLES = 1_000_000_000
|
||||
|
||||
|
||||
def _make_region() -> ECSharedRegion:
|
||||
"""Fresh region backed by a real per-test mmap file."""
|
||||
return ECSharedRegion(
|
||||
engine_id=str(uuid.uuid4()),
|
||||
num_blocks=_NUM_BLOCKS,
|
||||
block_size_bytes=_BLOCK_SIZE_BYTES,
|
||||
)
|
||||
|
||||
|
||||
def _vllm_config(rank: int = 0) -> Mock:
|
||||
config = create_ec_vllm_config(rank=rank, dtype=_DTYPE)
|
||||
config.model_config.get_inputs_embeds_size.return_value = _HIDDEN_DIM
|
||||
return config
|
||||
|
||||
|
||||
def _meta(
|
||||
*, saves: dict | None = None, loads: dict | None = None
|
||||
) -> ECCPUConnectorMetadata:
|
||||
"""Build step metadata from plain `{mm_hash: block_ids}` dicts.
|
||||
|
||||
Load transfer ids are synthesized here so tests can keep naming loads by
|
||||
mm_hash; `_load_id` recovers the id the worker will report.
|
||||
"""
|
||||
return ECCPUConnectorMetadata(
|
||||
saves=saves or {},
|
||||
loads={
|
||||
mm_hash: (idx, block_ids, (len(block_ids), _HIDDEN_DIM))
|
||||
for idx, (mm_hash, block_ids) in enumerate((loads or {}).items())
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _load_id(meta: ECCPUConnectorMetadata, mm_hash: str) -> int:
|
||||
return meta.loads[mm_hash][0]
|
||||
|
||||
|
||||
# ── fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_worker():
|
||||
"""Factory that builds an ``ECCPUWorker`` over a real ``ECSharedRegion``.
|
||||
|
||||
Tracks the workers and regions it creates and tears them down at the
|
||||
end of the test, so each test starts from a fresh /dev/shm file.
|
||||
"""
|
||||
workers: list[ECCPUWorker] = []
|
||||
regions: list[ECSharedRegion] = []
|
||||
|
||||
def factory(
|
||||
*,
|
||||
rank: int = 0,
|
||||
tp_rank: int = 0,
|
||||
pcp_rank: int = 0,
|
||||
pin_memory_available: bool = False,
|
||||
) -> ECCPUWorker:
|
||||
region = _make_region()
|
||||
regions.append(region)
|
||||
pcp_group = Mock()
|
||||
pcp_group.rank_in_group = pcp_rank
|
||||
with (
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.create_ec_shared_region",
|
||||
return_value=region,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.is_pin_memory_available",
|
||||
return_value=pin_memory_available,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.get_tensor_model_parallel_rank",
|
||||
return_value=tp_rank,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.get_pcp_group",
|
||||
return_value=pcp_group,
|
||||
),
|
||||
):
|
||||
worker = ECCPUWorker(_vllm_config(rank=rank))
|
||||
workers.append(worker)
|
||||
return worker
|
||||
|
||||
yield factory
|
||||
|
||||
for worker in workers:
|
||||
with contextlib.suppress(Exception):
|
||||
worker.shutdown()
|
||||
for region in regions:
|
||||
with contextlib.suppress(Exception):
|
||||
region.cleanup()
|
||||
|
||||
|
||||
def _wait_for_completion(
|
||||
worker: ECCPUWorker, expected, direction: str, timeout_s: float = 30.0
|
||||
) -> None:
|
||||
"""Poll ``build_connector_worker_meta`` until ``expected`` is reported done.
|
||||
|
||||
Saves are reported by mm_hash, loads by transfer id.
|
||||
"""
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
meta = worker.build_connector_worker_meta()
|
||||
if meta is not None and expected in getattr(meta, f"completed_{direction}"):
|
||||
return
|
||||
time.sleep(0.001)
|
||||
raise AssertionError(f"{direction} for {expected!r} never reported complete")
|
||||
|
||||
|
||||
def _warm_up_stream_pools(worker: ECCPUWorker) -> None:
|
||||
"""Run one throwaway save so the stream and event pools are populated.
|
||||
|
||||
The first CUDA stream creation in a process blocks the host for ~0.5 s on
|
||||
driver initialization, which would swallow the stall the lifetime tests
|
||||
below install. One flush puts a stream and its events in the worker's pools,
|
||||
matching the steady state every step after the first sees.
|
||||
"""
|
||||
scratch = torch.zeros(_HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
worker.save_caches({"w": scratch}, "w", _meta(saves={"w": [0]}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "w", "saves")
|
||||
assert worker._stream_pool, "warm-up did not recycle a stream"
|
||||
|
||||
|
||||
# ── backend extension points ────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_save_path_delegates_transfer_submission(make_worker):
|
||||
worker = make_worker()
|
||||
stream = Mock()
|
||||
worker._acquire_stream = Mock(return_value=stream)
|
||||
worker._acquire_event = Mock(side_effect=[Mock(), Mock()])
|
||||
worker._submit_transfer = Mock()
|
||||
|
||||
src = MagicMock()
|
||||
src.numel.return_value = _HIDDEN_DIM
|
||||
src.element_size.return_value = _DTYPE.itemsize
|
||||
src.view.return_value = src
|
||||
src.data_ptr.return_value = 1000
|
||||
|
||||
platform = Mock()
|
||||
platform.current_stream.return_value = Mock()
|
||||
platform.stream.return_value = contextlib.nullcontext()
|
||||
with patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.current_platform",
|
||||
platform,
|
||||
):
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": [3]}))
|
||||
worker.flush_saves()
|
||||
|
||||
worker._submit_transfer.assert_called_once()
|
||||
_, count, direction = worker._submit_transfer.call_args.args
|
||||
assert count == 1
|
||||
assert direction == ECCPUTransferDirection.DEVICE_TO_HOST
|
||||
|
||||
|
||||
def test_load_path_delegates_transfer_submission(make_worker):
|
||||
worker = make_worker()
|
||||
stream = Mock()
|
||||
compute_stream = Mock()
|
||||
worker._acquire_stream = Mock(return_value=stream)
|
||||
worker._acquire_event = Mock(side_effect=[Mock(), Mock()])
|
||||
worker._submit_transfer = Mock()
|
||||
|
||||
dst_buf = MagicMock()
|
||||
dst_buf.data_ptr.return_value = 1000
|
||||
|
||||
platform = Mock()
|
||||
platform.device_type = "cpu"
|
||||
platform.current_stream.return_value = compute_stream
|
||||
platform.stream.return_value = contextlib.nullcontext()
|
||||
with (
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.current_platform",
|
||||
platform,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.torch.empty",
|
||||
return_value=dst_buf,
|
||||
),
|
||||
):
|
||||
worker.start_load_caches({}, _meta(loads={"h": [3]}))
|
||||
|
||||
worker._submit_transfer.assert_called_once()
|
||||
_, count, direction = worker._submit_transfer.call_args.args
|
||||
assert count == 1
|
||||
assert direction == ECCPUTransferDirection.HOST_TO_DEVICE
|
||||
|
||||
|
||||
# ── save_caches ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
@pytest.mark.parametrize(
|
||||
"n_elements,block_ids",
|
||||
[
|
||||
(3 * _HIDDEN_DIM, [7, 2, 5]), # exact fit: 3 full blocks, no remainder
|
||||
(3 * _HIDDEN_DIM + 4, [7, 2, 5, 0]), # partial last block: 4 fp16 trail
|
||||
(3 * _HIDDEN_DIM, [2, 3, 4]), # adjacent: one coalesced copy
|
||||
(3 * _HIDDEN_DIM + 4, [2, 3, 4, 6]), # coalesced run, then a gap
|
||||
],
|
||||
ids=["exact-fit", "partial-last-block", "adjacent-blocks", "run-then-gap"],
|
||||
)
|
||||
def test_save_caches_writes_to_assigned_blocks(make_worker, n_elements, block_ids):
|
||||
"""``save_caches`` + ``flush_saves`` copies the source GPU tensor's bytes
|
||||
into the block IDs named by ``meta.saves``, in the order they appear,
|
||||
via a single batched GPU→CPU copy.
|
||||
|
||||
When ``total_bytes`` is not a multiple of ``block_size_bytes`` the last
|
||||
block is partially written; the unwritten tail must remain whatever
|
||||
was there before. Blocks not named in ``meta.saves`` must be untouched.
|
||||
Blocks adjacent in the region share one descriptor, which must land the
|
||||
same bytes in the same blocks as one descriptor per block does.
|
||||
"""
|
||||
worker = make_worker()
|
||||
sentinel = 0x5A
|
||||
worker._region.blocks.fill_(sentinel)
|
||||
|
||||
src = torch.arange(n_elements, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
expected_bytes = src.cpu().reshape(-1).view(torch.uint8)
|
||||
total_bytes = n_elements * _DTYPE.itemsize
|
||||
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": block_ids}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "h", "saves")
|
||||
|
||||
for slot, block_idx in enumerate(block_ids):
|
||||
block_byte_start = slot * _BLOCK_SIZE_BYTES
|
||||
block_byte_end = min(block_byte_start + _BLOCK_SIZE_BYTES, total_bytes)
|
||||
n_written = block_byte_end - block_byte_start
|
||||
actual_bytes = worker._region.blocks[block_idx, :n_written].view(torch.uint8)
|
||||
assert torch.equal(
|
||||
actual_bytes, expected_bytes[block_byte_start:block_byte_end]
|
||||
), f"block {block_idx} (slot {slot}) bytes mismatch"
|
||||
if n_written < _BLOCK_SIZE_BYTES:
|
||||
tail = worker._region.blocks[block_idx, n_written:]
|
||||
assert torch.all(tail == sentinel), (
|
||||
f"block {block_idx} tail was overwritten"
|
||||
)
|
||||
|
||||
for idx in set(range(_NUM_BLOCKS)) - set(block_ids):
|
||||
assert torch.all(worker._region.blocks[idx] == sentinel), (
|
||||
f"block {idx} (unassigned) was overwritten"
|
||||
)
|
||||
|
||||
|
||||
@_requires_accelerator
|
||||
@pytest.mark.parametrize(
|
||||
"n_elements,block_ids,expected_sizes",
|
||||
[
|
||||
(3 * _HIDDEN_DIM, [2, 3, 4], [3 * _BLOCK_SIZE_BYTES]),
|
||||
(3 * _HIDDEN_DIM, [7, 2, 5], [_BLOCK_SIZE_BYTES] * 3),
|
||||
(3 * _HIDDEN_DIM, [2, 3, 6], [2 * _BLOCK_SIZE_BYTES, _BLOCK_SIZE_BYTES]),
|
||||
(2 * _HIDDEN_DIM + 4, [2, 3, 4], [(2 * _HIDDEN_DIM + 4) * _DTYPE.itemsize]),
|
||||
(_HIDDEN_DIM, [2, 3, 4], [_BLOCK_SIZE_BYTES]),
|
||||
],
|
||||
ids=[
|
||||
"one-run",
|
||||
"no-run",
|
||||
"run-then-gap",
|
||||
"run-stops-at-output",
|
||||
"blocks-past-output-skipped",
|
||||
],
|
||||
)
|
||||
def test_save_caches_coalesces_only_adjacent_blocks(
|
||||
make_worker, n_elements, block_ids, expected_sizes
|
||||
):
|
||||
"""One descriptor per run of region-adjacent blocks, not one per block.
|
||||
|
||||
Per-descriptor overhead dominates these copies, so the byte tests above
|
||||
would pass either way; this pins the descriptor layout that makes them
|
||||
fast. A coalesced copy also stops at the encoder output, since entries are
|
||||
sized by placeholder count, which can exceed the number of embeddings.
|
||||
"""
|
||||
worker = make_worker()
|
||||
src = torch.arange(n_elements, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": block_ids}))
|
||||
|
||||
assert worker._save_bufs.sizes[: worker._save_count].tolist() == expected_sizes
|
||||
|
||||
|
||||
def test_save_caches_noop_when_mm_hash_not_in_saves(make_worker):
|
||||
"""When the scheduler hasn't pre-allocated blocks for ``mm_hash``,
|
||||
``save_caches`` + ``flush_saves`` is a pure no-op."""
|
||||
worker = make_worker()
|
||||
sentinel = 0x42
|
||||
worker._region.blocks.fill_(sentinel)
|
||||
|
||||
worker.save_caches({}, "h", _meta(saves={}))
|
||||
worker.flush_saves()
|
||||
|
||||
assert torch.all(worker._region.blocks == sentinel)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tp_rank,pcp_rank",
|
||||
[(1, 0), (0, 1), (1, 1)],
|
||||
ids=["tp1-pcp0", "tp0-pcp1", "tp1-pcp1"],
|
||||
)
|
||||
def test_save_caches_noop_for_non_save_rank(make_worker, tp_rank, pcp_rank):
|
||||
"""Only TP rank 0 + PCP rank 0 writes to mmap. All other combinations
|
||||
must skip the save entirely."""
|
||||
worker = make_worker(tp_rank=tp_rank, pcp_rank=pcp_rank)
|
||||
sentinel = 0x42
|
||||
worker._region.blocks.fill_(sentinel)
|
||||
|
||||
worker.save_caches(
|
||||
{"h": torch.zeros(8, dtype=_DTYPE)}, "h", _meta(saves={"h": [0]})
|
||||
)
|
||||
worker.flush_saves()
|
||||
|
||||
assert torch.all(worker._region.blocks == sentinel)
|
||||
|
||||
|
||||
def test_save_caches_raises_when_allocated_blocks_too_small(make_worker):
|
||||
"""``save_caches`` must raise ``AssertionError`` when the encoder output
|
||||
is larger than the allocated block space."""
|
||||
worker = make_worker()
|
||||
src = torch.zeros(3 * _HIDDEN_DIM, dtype=_DTYPE)
|
||||
with pytest.raises(AssertionError, match="exceeds allocated blocks"):
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": [0, 1]}))
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_save_caches_batches_multiple_hashes(make_worker):
|
||||
"""Multiple save_caches calls are batched into a single flush."""
|
||||
worker = make_worker()
|
||||
sentinel = 0x5A
|
||||
worker._region.blocks.fill_(sentinel)
|
||||
|
||||
src_a = torch.arange(_HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
src_b = torch.arange(_HIDDEN_DIM, 2 * _HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
|
||||
cache = {"a": src_a, "b": src_b}
|
||||
worker.save_caches(cache, "a", _meta(saves={"a": [1], "b": [3]}))
|
||||
worker.save_caches(cache, "b", _meta(saves={"a": [1], "b": [3]}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "a", "saves")
|
||||
|
||||
expected_a = src_a.cpu().view(torch.uint8)
|
||||
expected_b = src_b.cpu().view(torch.uint8)
|
||||
actual_a = worker._region.blocks[1].view(torch.uint8)
|
||||
actual_b = worker._region.blocks[3].view(torch.uint8)
|
||||
assert torch.equal(actual_a, expected_a)
|
||||
assert torch.equal(actual_b, expected_b)
|
||||
|
||||
# Unassigned blocks untouched.
|
||||
for idx in (0, 2, 4, 5, 6, 7):
|
||||
assert torch.all(worker._region.blocks[idx] == sentinel)
|
||||
|
||||
|
||||
class _HighAddress:
|
||||
"""A device tensor reporting an address with the high bit set.
|
||||
|
||||
XPU USM allocations live up there and no host allocator will hand out such
|
||||
an address, so naming one is the only way to reach the arithmetic. Every
|
||||
attribute other than the address comes from the real tensor.
|
||||
"""
|
||||
|
||||
def __init__(self, real: torch.Tensor, address: int):
|
||||
self._real = real
|
||||
self._address = address
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._real, name)
|
||||
|
||||
def view(self, *args):
|
||||
return self
|
||||
|
||||
def data_ptr(self) -> int:
|
||||
return self._address
|
||||
|
||||
|
||||
@_requires_accelerator
|
||||
def test_save_descriptors_hold_high_bit_source_addresses(make_worker):
|
||||
"""Source addresses >= 2**63 survive into the descriptor buffers."""
|
||||
worker = make_worker()
|
||||
real = torch.zeros(2 * _HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
address = 2**64 - 8 * _BLOCK_SIZE_BYTES
|
||||
|
||||
# Two runs, so the second descriptor's address is an offset off the base.
|
||||
worker.save_caches(
|
||||
{"a": _HighAddress(real, address)}, "a", _meta(saves={"a": [1, 5]})
|
||||
)
|
||||
|
||||
assert worker._save_count == 2
|
||||
stored = worker._save_bufs.src_np[:2].astype(np.uint64)
|
||||
assert list(stored) == [address, address + _BLOCK_SIZE_BYTES]
|
||||
|
||||
# The batch describes an address nothing may read from; drop it unflushed.
|
||||
worker._save_bufs = None
|
||||
worker._save_count = 0
|
||||
worker._save_mm_hashes = []
|
||||
|
||||
|
||||
# ── start_load_caches ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_start_load_caches_copies_with_correct_shape_dtype_and_bytes(make_worker):
|
||||
"""Single batched load across all hashes with correct byte→dtype→shape."""
|
||||
worker = make_worker()
|
||||
n_blocks = 3
|
||||
src_orig = torch.arange(n_blocks * _HIDDEN_DIM, dtype=_DTYPE).reshape(
|
||||
n_blocks, _HIDDEN_DIM
|
||||
)
|
||||
src_int8 = src_orig.view(torch.int8).reshape(n_blocks, _BLOCK_SIZE_BYTES)
|
||||
|
||||
block_ids = [3, 1, 6]
|
||||
for i, idx in enumerate(block_ids):
|
||||
worker._region.blocks[idx].copy_(src_int8[i])
|
||||
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
worker.start_load_caches(encoder_cache, _meta(loads={"h": block_ids}))
|
||||
|
||||
out = encoder_cache["h"]
|
||||
assert out.device.type == DEVICE_TYPE, (
|
||||
"consumer worker must place the tensor on the accelerator"
|
||||
)
|
||||
assert out.shape == (n_blocks, _HIDDEN_DIM)
|
||||
assert out.dtype == _DTYPE
|
||||
assert torch.equal(out.cpu(), src_orig)
|
||||
|
||||
|
||||
@_requires_accelerator
|
||||
@pytest.mark.parametrize(
|
||||
"loads,expected_sizes",
|
||||
[
|
||||
({"a": [2, 3], "b": [4, 5]}, [4 * _BLOCK_SIZE_BYTES]),
|
||||
({"b": [4, 5], "a": [2, 3]}, [4 * _BLOCK_SIZE_BYTES]),
|
||||
({"a": [2, 3], "b": [6, 7]}, [2 * _BLOCK_SIZE_BYTES] * 2),
|
||||
],
|
||||
ids=["adjacent-entries", "adjacent-entries-reversed", "gap-between-entries"],
|
||||
)
|
||||
def test_start_load_caches_coalesces_across_entries(make_worker, loads, expected_sizes):
|
||||
"""Blocks adjacent in the region share a descriptor across entries too.
|
||||
|
||||
Entries are ordered by first block, so whether they coalesce follows from
|
||||
the region layout rather than the order the scheduler dispatched them.
|
||||
"""
|
||||
worker = make_worker()
|
||||
captured: list[list[int]] = []
|
||||
|
||||
with patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.swap_blocks_batch",
|
||||
side_effect=lambda src, dst, sizes, **kw: captured.append(sizes.tolist()),
|
||||
):
|
||||
worker.start_load_caches({}, _meta(loads=loads))
|
||||
|
||||
assert captured == [expected_sizes]
|
||||
|
||||
|
||||
@_requires_accelerator
|
||||
def test_start_load_caches_noop_when_loads_is_empty(make_worker):
|
||||
"""When ``meta.loads`` is empty the early-return must fire."""
|
||||
worker = make_worker()
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
worker.start_load_caches(encoder_cache, _meta(loads={}))
|
||||
|
||||
assert encoder_cache == {}
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_start_load_caches_skips_cached_and_loads_new_in_same_step(make_worker):
|
||||
"""Every hash in ``meta.loads`` is copied from mmap, including one whose
|
||||
key is already resident in ``encoder_cache`` — there is no worker-side
|
||||
skip."""
|
||||
worker = make_worker()
|
||||
n_blocks = 3
|
||||
src_orig = torch.arange(n_blocks * _HIDDEN_DIM, dtype=_DTYPE).reshape(
|
||||
n_blocks, _HIDDEN_DIM
|
||||
)
|
||||
src_int8 = src_orig.view(torch.int8).reshape(n_blocks, _BLOCK_SIZE_BYTES)
|
||||
block_ids = [0, 4, 2]
|
||||
for i, idx in enumerate(block_ids):
|
||||
worker._region.blocks[idx].copy_(src_int8[i])
|
||||
|
||||
cached_tensor = torch.full((1, _HIDDEN_DIM), 99.0, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
encoder_cache: dict[str, torch.Tensor] = {"cached_h": cached_tensor}
|
||||
worker.start_load_caches(
|
||||
encoder_cache,
|
||||
_meta(loads={"resident_h": [block_ids[0]], "new_h": block_ids[1:]}),
|
||||
)
|
||||
|
||||
resident = encoder_cache["resident_h"]
|
||||
assert resident is not cached_tensor, "resident entry must be reloaded, not skipped"
|
||||
assert torch.equal(resident.cpu(), src_orig[:1])
|
||||
|
||||
new = encoder_cache["new_h"]
|
||||
assert new.shape == (2, _HIDDEN_DIM)
|
||||
assert new.dtype == _DTYPE
|
||||
assert torch.equal(new.cpu(), src_orig[1:])
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
@pytest.mark.parametrize(
|
||||
"tp_rank,pcp_rank",
|
||||
[(0, 0), (1, 0), (0, 1), (1, 1)],
|
||||
ids=["tp0-pcp0", "tp1-pcp0", "tp0-pcp1", "tp1-pcp1"],
|
||||
)
|
||||
def test_start_load_caches_works_on_all_ranks(make_worker, tp_rank, pcp_rank):
|
||||
"""All TP/PCP ranks must load from mmap — loads are NOT gated like saves."""
|
||||
worker = make_worker(tp_rank=tp_rank, pcp_rank=pcp_rank)
|
||||
n_blocks = 2
|
||||
src_orig = torch.arange(n_blocks * _HIDDEN_DIM, dtype=_DTYPE).reshape(
|
||||
n_blocks, _HIDDEN_DIM
|
||||
)
|
||||
src_int8 = src_orig.view(torch.int8).reshape(n_blocks, _BLOCK_SIZE_BYTES)
|
||||
block_ids = [1, 3]
|
||||
for i, idx in enumerate(block_ids):
|
||||
worker._region.blocks[idx].copy_(src_int8[i])
|
||||
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
worker.start_load_caches(encoder_cache, _meta(loads={"h": block_ids}))
|
||||
|
||||
out = encoder_cache["h"]
|
||||
assert out.device.type == DEVICE_TYPE
|
||||
assert torch.equal(out.cpu(), src_orig)
|
||||
|
||||
|
||||
# ── round-trip ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_save_then_load_round_trips_bytes(make_worker):
|
||||
"""Full producer→mmap→consumer byte path in one shot."""
|
||||
worker = make_worker()
|
||||
n_blocks = 3
|
||||
block_ids = [5, 1, 6]
|
||||
|
||||
src = torch.arange(
|
||||
n_blocks * _HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE
|
||||
).reshape(n_blocks, _HIDDEN_DIM)
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": block_ids}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "h", "saves")
|
||||
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
worker.start_load_caches(encoder_cache, _meta(loads={"h": block_ids}))
|
||||
|
||||
out = encoder_cache["h"]
|
||||
assert out.shape == src.shape
|
||||
assert out.dtype == src.dtype
|
||||
assert torch.equal(out.cpu(), src.cpu())
|
||||
|
||||
|
||||
# ── memory lifetime across in-flight copies ─────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_cuda_alike
|
||||
def test_save_survives_encoder_cache_free_before_copy_runs(make_worker):
|
||||
"""The bytes handed to ``save_caches`` must reach the mmap intact even when
|
||||
the caller drops its ``encoder_cache`` reference before the copy has run.
|
||||
|
||||
The model runner pops encoder cache entries on whatever step the scheduler
|
||||
asks it to, with no dependency on the save copy having landed. Dropping the
|
||||
last reference hands the GPU memory back to the caching allocator, which is
|
||||
free to reuse it for the next same-sized allocation on the compute stream —
|
||||
the copy reads that memory on a different stream, so the allocator has no
|
||||
reason to hold it back.
|
||||
|
||||
The stall makes the hazard deterministic rather than timing-dependent: the
|
||||
save copy is gated behind the compute stream, so it provably has not started
|
||||
while the overwrite (issued on an ungated stream and waited on) completes.
|
||||
|
||||
The mmap must be pinned, as it is in production: a copy into pageable host
|
||||
memory blocks the host until it lands, which would hide the hazard.
|
||||
"""
|
||||
worker = make_worker(pin_memory_available=True)
|
||||
_warm_up_stream_pools(worker)
|
||||
worker._region.blocks.fill_(0x5A)
|
||||
|
||||
block_ids = [0, 1, 2]
|
||||
saved = torch.full(
|
||||
(len(block_ids), _HIDDEN_DIM), 1.0, dtype=_DTYPE, device=DEVICE_TYPE
|
||||
)
|
||||
expected = saved.cpu().reshape(-1).view(torch.uint8)
|
||||
|
||||
encoder_cache = {"h": saved}
|
||||
worker.save_caches(encoder_cache, "h", _meta(saves={"h": block_ids}))
|
||||
|
||||
torch.cuda._sleep(_STALL_CYCLES)
|
||||
worker.flush_saves()
|
||||
|
||||
saved_ptr = saved.data_ptr()
|
||||
del saved
|
||||
encoder_cache.clear()
|
||||
|
||||
# Same size on the same stream, so the allocator hands back the block just
|
||||
# freed. Overwriting it from an ungated stream — and waiting for that write
|
||||
# — orders the overwrite strictly before the still-stalled save copy.
|
||||
overwrite = torch.empty(
|
||||
(len(block_ids), _HIDDEN_DIM), dtype=_DTYPE, device=DEVICE_TYPE
|
||||
)
|
||||
reused = overwrite.data_ptr() == saved_ptr
|
||||
other_stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(other_stream):
|
||||
overwrite.fill_(-1.0)
|
||||
other_stream.synchronize()
|
||||
|
||||
_wait_for_completion(worker, "h", "saves")
|
||||
|
||||
actual = worker._region.blocks[block_ids].reshape(-1).view(torch.uint8)
|
||||
assert torch.equal(actual, expected), (
|
||||
"mmap holds bytes written after save_caches was called; the copy read "
|
||||
f"freed source memory (allocator reused the freed block: {reused})"
|
||||
)
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_cuda_alike
|
||||
def test_load_buffer_survives_eviction_while_consumer_read_is_queued(make_worker):
|
||||
"""A loaded encoder cache entry must keep its bytes for a consumer already
|
||||
queued on the compute stream, even after the entry is dropped and another
|
||||
load is dispatched.
|
||||
|
||||
``start_load_caches`` allocates its destination inside the load stream's
|
||||
context, which ties that memory to the load stream in the caching allocator.
|
||||
Dropping the encoder cache entry returns it to the load stream's pool, where
|
||||
the next load can claim it — while the model's read of it is still queued on
|
||||
the compute stream.
|
||||
"""
|
||||
worker = make_worker(pin_memory_available=True)
|
||||
_warm_up_stream_pools(worker)
|
||||
a_blocks, b_blocks = [4, 5], [6, 7]
|
||||
for block_idx, fill in zip(a_blocks + b_blocks, (0x11, 0x12, 0x21, 0x22)):
|
||||
worker._region.blocks[block_idx].fill_(fill)
|
||||
expected_a = worker._region.blocks[a_blocks].reshape(-1).clone()
|
||||
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
meta_a = _meta(loads={"a": a_blocks})
|
||||
worker.start_load_caches(encoder_cache, meta_a)
|
||||
loaded_a = encoder_cache["a"]
|
||||
|
||||
# Queue a consumer of the loaded entry on the compute stream behind a stall,
|
||||
# the way the model reads the encoder cache later in the step.
|
||||
torch.cuda._sleep(_STALL_CYCLES)
|
||||
consumed = loaded_a.clone()
|
||||
|
||||
# Draining the completion report recycles the load stream into the pool, so
|
||||
# the next load allocates from the same allocator pool the entry was freed to.
|
||||
_wait_for_completion(worker, _load_id(meta_a, "a"), "loads")
|
||||
|
||||
loaded_a_ptr = loaded_a.data_ptr()
|
||||
del loaded_a
|
||||
encoder_cache.clear()
|
||||
|
||||
worker.start_load_caches(encoder_cache, _meta(loads={"b": b_blocks}))
|
||||
reused = encoder_cache["b"].data_ptr() == loaded_a_ptr
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.equal(consumed.cpu().reshape(-1).view(torch.int8), expected_a), (
|
||||
"queued consumer read bytes from a later load; the load destination was "
|
||||
f"recycled while still in use (allocator reused the buffer: {reused})"
|
||||
)
|
||||
|
||||
|
||||
# ── buffer recycling ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_buffer_pool_is_reused_across_save_steps(make_worker):
|
||||
"""Once a save copy completes its descriptor buffers return to the pool and
|
||||
are reused by the next flush — no reallocation.
|
||||
|
||||
The buffers hold the addresses the copy reads, so they stay out of the pool
|
||||
until the transfer's end event fires.
|
||||
"""
|
||||
worker = make_worker()
|
||||
src = torch.arange(_HIDDEN_DIM, dtype=_DTYPE, device=DEVICE_TYPE)
|
||||
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": [0]}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "h", "saves")
|
||||
|
||||
assert len(worker._buf_pool._pool) == 1
|
||||
buf_id = id(worker._buf_pool._pool[0].src_ptrs)
|
||||
|
||||
# Second step reuses the same buffer.
|
||||
worker.save_caches({"h": src}, "h", _meta(saves={"h": [1]}))
|
||||
worker.flush_saves()
|
||||
_wait_for_completion(worker, "h", "saves")
|
||||
|
||||
assert len(worker._buf_pool._pool) == 1
|
||||
assert id(worker._buf_pool._pool[0].src_ptrs) == buf_id
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_buffer_pool_is_reused_across_load_steps(make_worker):
|
||||
"""Once a load copy completes its descriptor buffers return to the pool and
|
||||
are reused by the next call — no reallocation."""
|
||||
worker = make_worker()
|
||||
worker._region.blocks[0].fill_(0x01)
|
||||
worker._region.blocks[1].fill_(0x02)
|
||||
|
||||
encoder_cache: dict[str, torch.Tensor] = {}
|
||||
meta = _meta(loads={"a": [0]})
|
||||
worker.start_load_caches(encoder_cache, meta)
|
||||
_wait_for_completion(worker, _load_id(meta, "a"), "loads")
|
||||
|
||||
assert len(worker._buf_pool._pool) == 1
|
||||
buf_id = id(worker._buf_pool._pool[0].src_ptrs)
|
||||
|
||||
encoder_cache2: dict[str, torch.Tensor] = {}
|
||||
meta2 = _meta(loads={"b": [1]})
|
||||
worker.start_load_caches(encoder_cache2, meta2)
|
||||
_wait_for_completion(worker, _load_id(meta2, "b"), "loads")
|
||||
|
||||
assert len(worker._buf_pool._pool) == 1
|
||||
assert id(worker._buf_pool._pool[0].src_ptrs) == buf_id
|
||||
|
||||
|
||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pin_available,expected_pinned",
|
||||
[
|
||||
(True, True),
|
||||
(False, False),
|
||||
],
|
||||
ids=["available", "unavailable"],
|
||||
)
|
||||
def test_init_pins_memory_when_available(pin_available, expected_pinned):
|
||||
"""Every worker must call ``pin_memory()`` when the platform allows it."""
|
||||
region = _make_region()
|
||||
region.pin_memory = MagicMock() # type: ignore[method-assign]
|
||||
|
||||
pcp_group = Mock()
|
||||
pcp_group.rank_in_group = 0
|
||||
with (
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.create_ec_shared_region",
|
||||
return_value=region,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.is_pin_memory_available",
|
||||
return_value=pin_available,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.get_tensor_model_parallel_rank",
|
||||
return_value=0,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.ec_transfer.ec_connector.cpu.worker.get_pcp_group",
|
||||
return_value=pcp_group,
|
||||
),
|
||||
):
|
||||
ECCPUWorker(_vllm_config(rank=0))
|
||||
|
||||
try:
|
||||
if expected_pinned:
|
||||
region.pin_memory.assert_called_once()
|
||||
else:
|
||||
region.pin_memory.assert_not_called()
|
||||
finally:
|
||||
region.cleanup()
|
||||
|
||||
|
||||
def test_shutdown_calls_region_cleanup_and_swallows_errors(caplog_vllm):
|
||||
"""``shutdown`` must always call ``region.cleanup`` — and must never
|
||||
raise."""
|
||||
worker = object.__new__(ECCPUWorker)
|
||||
mock_region = Mock(spec=ECSharedRegion)
|
||||
worker._region = mock_region
|
||||
worker._save_bufs = None
|
||||
worker._save_count = 0
|
||||
worker._save_mm_hashes = []
|
||||
worker._inflight_saves = deque()
|
||||
worker._inflight_loads = deque()
|
||||
worker._stream_pool = []
|
||||
worker._event_pool = []
|
||||
worker._shutdown_transfer_backend = MagicMock()
|
||||
|
||||
worker.shutdown()
|
||||
worker._shutdown_transfer_backend.assert_called_once()
|
||||
mock_region.cleanup.assert_called_once()
|
||||
|
||||
mock_region.cleanup.side_effect = RuntimeError("boom")
|
||||
with caplog_vllm.at_level(logging.DEBUG, logger="vllm"):
|
||||
worker.shutdown() # exception must be swallowed
|
||||
|
||||
assert mock_region.cleanup.call_count == 2
|
||||
assert any(
|
||||
"worker region cleanup failed" in r.message
|
||||
for r in caplog_vllm.records
|
||||
if r.levelno == logging.DEBUG
|
||||
)
|
||||
|
||||
|
||||
# ── e2e: scheduler + worker pipeline ────────────────────────────────────────
|
||||
|
||||
|
||||
@_requires_swap_blocks_batch
|
||||
@_requires_accelerator
|
||||
def test_e2e_scheduler_worker_save_then_load(make_worker, monkeypatch):
|
||||
"""Full pipeline: scheduler allocates blocks, worker saves a GPU tensor to
|
||||
mmap via flush_saves, the worker's completion report marks the entry ready,
|
||||
the worker loads from mmap back to GPU, and the result matches the original.
|
||||
|
||||
Exercises the real scheduler + worker cooperation through a shared
|
||||
ECSharedRegion, with real accelerator transfers and stream coordination,
|
||||
and the event-driven mark_ready path.
|
||||
"""
|
||||
import vllm.distributed.ec_transfer.ec_connector.cpu.scheduler as sched_mod
|
||||
from vllm.distributed.ec_transfer.ec_connector.cpu.scheduler import (
|
||||
ECCPUScheduler,
|
||||
)
|
||||
|
||||
# Build worker first (gets us a real region).
|
||||
worker = make_worker()
|
||||
region = worker._region
|
||||
|
||||
# Build scheduler sharing the same region.
|
||||
monkeypatch.setattr(sched_mod, "create_ec_shared_region", lambda cfg: region)
|
||||
|
||||
config = _vllm_config()
|
||||
# DeepStack-wide output: each embedding spans four blocks.
|
||||
width = 4 * _HIDDEN_DIM
|
||||
config.ec_transfer_config.mm_encoder_output_widths = {"image": width}
|
||||
scheduler = ECCPUScheduler(config)
|
||||
|
||||
# -- Step 1: scheduler allocates, worker saves --
|
||||
n_tokens = 2
|
||||
src = torch.arange(n_tokens * width, dtype=_DTYPE, device=DEVICE_TYPE).reshape(
|
||||
n_tokens, width
|
||||
)
|
||||
|
||||
class _Pos:
|
||||
offset = 0
|
||||
length = n_tokens
|
||||
|
||||
def get_num_embeds(self):
|
||||
return self.length
|
||||
|
||||
class _Feature:
|
||||
identifier = "img_001"
|
||||
mm_position = _Pos()
|
||||
modality = "image"
|
||||
|
||||
class _Request:
|
||||
request_id = "req_e2e"
|
||||
mm_features = [_Feature()]
|
||||
|
||||
scheduler.update_state_after_alloc(_Request(), 0)
|
||||
meta_save = scheduler.build_connector_meta(scheduler_output=None)
|
||||
assert "img_001" in meta_save.saves
|
||||
|
||||
encoder_cache = {"img_001": src}
|
||||
worker.save_caches(encoder_cache, "img_001", meta_save)
|
||||
worker.flush_saves()
|
||||
|
||||
# -- Step 2: worker reports the save memcpy complete → scheduler marks ready --
|
||||
torch.accelerator.synchronize()
|
||||
worker_meta = worker.build_connector_worker_meta()
|
||||
assert worker_meta is not None
|
||||
assert "img_001" in worker_meta.completed_saves
|
||||
|
||||
class _Output:
|
||||
ec_connector_worker_meta = worker_meta
|
||||
|
||||
scheduler.update_connector_output(_Output())
|
||||
assert scheduler.has_cache_item("img_001") is True
|
||||
|
||||
# -- Step 3: scheduler emits load, worker loads --
|
||||
scheduler.update_state_after_alloc(_Request(), 0)
|
||||
meta_load = scheduler.build_connector_meta(scheduler_output=None)
|
||||
assert "img_001" in meta_load.loads
|
||||
_, load_blocks, shape = meta_load.loads["img_001"]
|
||||
assert load_blocks == meta_save.saves["img_001"]
|
||||
assert shape == tuple(src.shape)
|
||||
|
||||
load_cache: dict[str, torch.Tensor] = {}
|
||||
worker.start_load_caches(load_cache, meta_load)
|
||||
|
||||
out = load_cache["img_001"]
|
||||
assert out.device.type == DEVICE_TYPE
|
||||
assert out.shape == src.shape
|
||||
assert out.dtype == src.dtype
|
||||
assert torch.equal(out.cpu(), src.cpu())
|
||||
|
||||
scheduler.shutdown()
|
||||
@@ -1,754 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import ctypes
|
||||
import gc
|
||||
import struct
|
||||
import threading
|
||||
import weakref
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.ec_connector.unit.utils import create_ec_vllm_config
|
||||
from vllm.config import MultiModalConfig
|
||||
from vllm.distributed.ec_transfer.ec_connector.base import ECConnectorRole
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake.config import MooncakeECConfig
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake.metadata import (
|
||||
ECMooncakeConnectorMetadata,
|
||||
ECMooncakePushSpec,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_ec_connector import (
|
||||
ECMooncakeConnector,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding import (
|
||||
backend as store_backend,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding import (
|
||||
store_client,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding.data import (
|
||||
TensorSpec,
|
||||
build_embedding_namespace,
|
||||
make_embedding_key,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
KEY = (
|
||||
"test@embedding@model:model@revision:revision"
|
||||
"@encoder:encoder@dtype:torch.float32@protocol:v3"
|
||||
)
|
||||
SPEC = TensorSpec((2, 2), "torch.float32", 16)
|
||||
|
||||
|
||||
def test_push_shapes_follow_each_modality(monkeypatch):
|
||||
"""Each push is sized at its modality's measured encoder output width."""
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake import scheduler
|
||||
|
||||
monkeypatch.setattr(scheduler, "ensure_mooncake_available", lambda: None)
|
||||
widths = {"image": 8192, "audio": 2048}
|
||||
config = create_ec_vllm_config(ec_role="ec_producer", encoder_output_widths=widths)
|
||||
request = SimpleNamespace(
|
||||
request_id="mixed",
|
||||
mm_features=[SimpleNamespace(identifier=m, modality=m) for m in widths],
|
||||
get_num_encoder_embeds=lambda index: 2,
|
||||
ec_transfer_params={
|
||||
"consumer_zmq": "tcp://consumer:1234",
|
||||
"ec_items": [{"mm_hash": m, "transfer_id": m} for m in widths],
|
||||
},
|
||||
)
|
||||
instance = scheduler.ECMooncakeScheduler(config)
|
||||
try:
|
||||
for index in range(len(widths)):
|
||||
instance.update_state_after_alloc(request, index)
|
||||
metadata = instance.build_connector_meta(
|
||||
SimpleNamespace(free_encoder_mm_hashes=[], preempted_req_ids=set())
|
||||
)
|
||||
assert [spec.shape for spec in metadata.pushes] == [(2, 8192), (2, 2048)]
|
||||
finally:
|
||||
instance.close()
|
||||
|
||||
|
||||
def test_embedding_key_combines_namespace_and_identifier():
|
||||
config = create_ec_vllm_config(ec_role="ec_producer")
|
||||
config.ec_transfer_config.ec_connector_extra_config.update(
|
||||
embedding_cache_prefix="team@cache", embedding_model_identity="shared/model"
|
||||
)
|
||||
config.model_config.revision = "rev:1"
|
||||
config.model_config.dtype = torch.float32
|
||||
config.model_config.multimodal_config = None
|
||||
assert make_embedding_key(build_embedding_namespace(config), "image@1") == (
|
||||
"team@cache@embedding@model:shared/model@revision:rev:1"
|
||||
"@encoder:encoder:default@dtype:torch.float32@protocol:v3@id:image@1"
|
||||
)
|
||||
|
||||
|
||||
def test_shared_reuse_requires_content_stable_identifiers():
|
||||
"""Encoder-only cache-off rendering uses process-local counter identifiers."""
|
||||
config = create_ec_vllm_config(ec_role="ec_producer")
|
||||
config.ec_transfer_config.ec_connector = "ECMooncakeConnector"
|
||||
config.ec_transfer_config.ec_connector_extra_config["cross_encoder_cache"] = True
|
||||
config.model_config.multimodal_config = MultiModalConfig(mm_processor_cache_gb=0)
|
||||
config.use_v2_model_runner = True
|
||||
config.lora_config = None
|
||||
with pytest.raises(ValueError, match="mm_processor_cache_gb"):
|
||||
MooncakeECConfig.from_vllm_config(config)
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
"""Only the native boundary is faked; codec, resolver and publisher are real."""
|
||||
|
||||
def __init__(self):
|
||||
self.objects: dict[str, bytes] = {}
|
||||
self.registered: dict[int, int] = {}
|
||||
|
||||
def close(self):
|
||||
return 0
|
||||
|
||||
def batch_is_exist(self, keys):
|
||||
return [int(k in self.objects) for k in keys]
|
||||
|
||||
def register_buffer(self, addr, size):
|
||||
self.registered[addr] = size
|
||||
return 0
|
||||
|
||||
def unregister_buffer(self, addr):
|
||||
del self.registered[addr]
|
||||
return 0
|
||||
|
||||
def batch_put_from_multi_buffers(self, keys, pointers, sizes, config):
|
||||
[key], [ptrs], [lengths] = keys, pointers, sizes
|
||||
self.objects[key] = b"".join(
|
||||
ctypes.string_at(p, n) for p, n in zip(ptrs, lengths, strict=True)
|
||||
)
|
||||
return [0]
|
||||
|
||||
def batch_get_into(self, keys, pointers, sizes):
|
||||
results = []
|
||||
for key, ptr, size in zip(keys, pointers, sizes, strict=True):
|
||||
assert any(
|
||||
base <= ptr and ptr + size <= base + capacity
|
||||
for base, capacity in self.registered.items()
|
||||
)
|
||||
obj = self.objects.get(key)
|
||||
if obj is None:
|
||||
results.append(-704)
|
||||
elif len(obj) > size:
|
||||
results.append(-600)
|
||||
else:
|
||||
ctypes.memmove(ptr, obj, len(obj))
|
||||
results.append(len(obj))
|
||||
return results
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def backend():
|
||||
instance = store_backend.MooncakeEmbeddingStoreBackend(
|
||||
store_client.MooncakeEmbeddingStoreClient(
|
||||
MemoryStore(), read_buffer_bytes=1024
|
||||
),
|
||||
KEY,
|
||||
max_pending_items=32,
|
||||
max_pending_bytes=2 * 1024**3,
|
||||
)
|
||||
yield instance
|
||||
# Some tests deliberately poison I/O; always stop the Python executor.
|
||||
instance._executor.shutdown(wait=True)
|
||||
if not instance.store_client._poisoned and (
|
||||
instance.store_client._read_buffer is not None
|
||||
or instance.store_client._put_header is not None
|
||||
):
|
||||
instance.store_client.close()
|
||||
|
||||
|
||||
def test_tensor_round_trip(backend):
|
||||
client, native = backend.store_client, backend.store_client.store
|
||||
native.register_buffer = MagicMock(wraps=native.register_buffer)
|
||||
header_ptr = None
|
||||
for index, dtype in enumerate((torch.float16, torch.bfloat16, torch.float32)):
|
||||
tensor = torch.arange(6, dtype=dtype).reshape(index + 1, -1)
|
||||
key = make_embedding_key(KEY, str(dtype))
|
||||
client.put_tensor(key, tensor)
|
||||
pointer = ctypes.addressof(client._put_header)
|
||||
header_ptr = header_ptr or pointer
|
||||
assert pointer == header_ptr
|
||||
expected = TensorSpec(tuple(tensor.shape), str(dtype), tensor.nbytes)
|
||||
with torch.device("meta"):
|
||||
loaded = client.load_tensors({key: expected}, "cpu")[key]
|
||||
assert client._read_buffer.device.type == "cpu"
|
||||
assert loaded.dtype == dtype and torch.equal(loaded, tensor)
|
||||
assert len(native.objects[key]) == 24 + tensor.nbytes
|
||||
assert (
|
||||
sum(c.args[0] == header_ptr for c in native.register_buffer.call_args_list) == 1
|
||||
)
|
||||
assert len(native.registered) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capacity", [80, 120])
|
||||
def test_batch_reads_reuse_registration_without_aliasing_outputs(backend, capacity):
|
||||
client, native = backend.store_client, backend.store_client.store
|
||||
client._read_buffer_bytes = capacity
|
||||
tensors = {key: torch.full((2, 2), float(i)) for i, key in enumerate("abc")}
|
||||
for key, tensor in tensors.items():
|
||||
client.put_tensor(key, tensor)
|
||||
native.register_buffer = MagicMock(wraps=native.register_buffer)
|
||||
native.unregister_buffer = MagicMock(wraps=native.unregister_buffer)
|
||||
native.batch_get_into = MagicMock(wraps=native.batch_get_into)
|
||||
expected = dict.fromkeys(tensors, SPEC)
|
||||
first = client.load_tensors(expected, "cpu")
|
||||
for key, tensor in tensors.items():
|
||||
native.objects[key] = native.objects[key][:24] + struct.pack(
|
||||
"<4f", *[tensor[0, 0].item() + 10] * 4
|
||||
)
|
||||
second = client.load_tensors(expected, "cpu")
|
||||
assert all(torch.equal(first[key], tensor) for key, tensor in tensors.items())
|
||||
assert all(torch.equal(second[key], tensor + 10) for key, tensor in tensors.items())
|
||||
assert native.batch_get_into.call_count == (4 if capacity == 80 else 2)
|
||||
native.register_buffer.assert_called_once()
|
||||
native.unregister_buffer.assert_not_called()
|
||||
client.close()
|
||||
assert native.unregister_buffer.call_count == 2
|
||||
assert not native.registered
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["miss", "oversized"])
|
||||
def test_unloadable_inputs_do_not_allocate_staging(backend, mode):
|
||||
client, native = backend.store_client, backend.store_client.store
|
||||
client._read_buffer_bytes = 39
|
||||
if mode == "oversized":
|
||||
client.put_tensor(make_embedding_key(KEY, "a"), torch.ones(2, 2))
|
||||
native.register_buffer = MagicMock(wraps=native.register_buffer)
|
||||
assert not backend.resolve_inputs({"a": SPEC}, {}, "cpu")
|
||||
assert client._read_buffer is None
|
||||
if mode == "miss":
|
||||
assert client._put_header is None
|
||||
client.close()
|
||||
native.register_buffer.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"results", [[40, -800], [40], [40, True], [[40], [40]], None, [40, 41]]
|
||||
)
|
||||
def test_unsafe_batch_result_retains_whole_staging(backend, results):
|
||||
client, native = backend.store_client, backend.store_client.store
|
||||
native.batch_get_into = MagicMock(return_value=results)
|
||||
native.unregister_buffer = MagicMock(wraps=native.unregister_buffer)
|
||||
for _ in range(2):
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unconfirmed"):
|
||||
client.load_tensors(dict.fromkeys("ab", SPEC), "cpu")
|
||||
native.batch_get_into.assert_called_once()
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unconfirmed"):
|
||||
client.close()
|
||||
native.unregister_buffer.assert_not_called()
|
||||
assert client._read_buffer is client._unsafe_owners[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["allocation", "copy", "record", "completion"])
|
||||
def test_copy_failure_preserves_staging_lifetime(backend, failure):
|
||||
"""Emulate CUDA allocation/event boundaries without requiring a GPU."""
|
||||
client = backend.store_client
|
||||
for key in "ab":
|
||||
client.put_tensor(key, torch.ones(2, 2))
|
||||
allocate, copy = torch.empty, torch.Tensor.copy_
|
||||
targets: list[torch.Tensor] = []
|
||||
copies: list[torch.Tensor] = []
|
||||
ready = MagicMock()
|
||||
if failure == "record":
|
||||
ready.record.side_effect = RuntimeError("record failure")
|
||||
elif failure == "completion":
|
||||
ready.synchronize.side_effect = RuntimeError("copy failure")
|
||||
|
||||
def allocate_on_cpu(*args, **kwargs):
|
||||
is_target = kwargs.get("device") == torch.device("cuda")
|
||||
if is_target and targets and failure == "allocation":
|
||||
raise torch.OutOfMemoryError("allocation failure")
|
||||
kwargs.update(device="cpu", pin_memory=False)
|
||||
tensor = allocate(*args, **kwargs)
|
||||
if is_target:
|
||||
targets.append(tensor)
|
||||
return tensor
|
||||
|
||||
def record_copy(target, source, **kwargs):
|
||||
if copies and failure == "copy":
|
||||
raise RuntimeError("copy failure")
|
||||
copies.append(target)
|
||||
return copy(target, source, **kwargs)
|
||||
|
||||
with (
|
||||
patch.object(torch, "empty", side_effect=allocate_on_cpu),
|
||||
patch.object(torch, "Event", return_value=ready),
|
||||
patch.object(torch.accelerator, "current_stream"),
|
||||
patch.object(torch.Tensor, "copy_", new=record_copy),
|
||||
pytest.raises(RuntimeError, match="allocation failure|unconfirmed"),
|
||||
):
|
||||
client.load_tensors(dict.fromkeys("ab", SPEC), "cuda")
|
||||
if failure == "allocation":
|
||||
assert not copies and not client._poisoned
|
||||
else:
|
||||
assert len(copies) == (1 if failure == "copy" else 2)
|
||||
assert client._poisoned
|
||||
assert any(owner is client._read_buffer for owner in client._unsafe_owners)
|
||||
assert any(owner is ready for owner in client._unsafe_owners)
|
||||
assert all(
|
||||
any(owner is target for owner in client._unsafe_owners)
|
||||
for target in targets
|
||||
)
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unconfirmed"):
|
||||
client.close()
|
||||
|
||||
|
||||
def test_non_matrix_output_is_rejected_before_registration(backend):
|
||||
client = backend.store_client
|
||||
client.store.register_buffer = MagicMock()
|
||||
with pytest.raises(store_client.EmbeddingStoreOperationError, match="2D"):
|
||||
client.put_tensor(make_embedding_key(KEY, "a"), torch.ones(2, 2, 2))
|
||||
client.store.register_buffer.assert_not_called()
|
||||
|
||||
|
||||
def make_worker(backend):
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake.worker import (
|
||||
ECMooncakeWorker,
|
||||
)
|
||||
|
||||
worker = object.__new__(ECMooncakeWorker)
|
||||
worker.is_producer = True
|
||||
worker.is_consumer = False
|
||||
worker._output_store = backend
|
||||
worker._buffer_device = "cpu"
|
||||
worker._producer_pushes = MagicMock()
|
||||
worker._producer_pushes.reserve.return_value = (MagicMock(), True)
|
||||
worker._producer_pushes.poll.return_value = []
|
||||
worker._producer_pushes.cancel_requests.return_value = []
|
||||
worker._producer_pushes.pending = False
|
||||
worker._control_executor = MagicMock()
|
||||
worker._consumer_memory = MagicMock()
|
||||
worker._consumer_memory.drain_reclaimed.return_value = set()
|
||||
worker._completed_loads = set()
|
||||
worker._failed_loads = set()
|
||||
worker._failed_saves = set()
|
||||
worker._push_ready = threading.Event()
|
||||
worker._flush_pending_pushes = MagicMock()
|
||||
worker._bind_push_source = MagicMock()
|
||||
connector = object.__new__(ECMooncakeConnector)
|
||||
connector._worker = worker
|
||||
connector._role = ECConnectorRole.WORKER
|
||||
connector._is_producer = True
|
||||
connector._is_consumer = False
|
||||
connector._connector_metadata = None
|
||||
return connector
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mode",
|
||||
[
|
||||
"miss",
|
||||
"legacy",
|
||||
"hit",
|
||||
"partial",
|
||||
"get-failure",
|
||||
"short-data",
|
||||
"lease-expired",
|
||||
"registration-failure",
|
||||
],
|
||||
)
|
||||
def test_reuse_pipeline(backend, mode):
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalKwargsItem,
|
||||
PlaceholderRange,
|
||||
)
|
||||
from vllm.v1.worker.gpu.ec_connector import ActiveECConnector
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.mm.encoder_runner import EncoderRunner
|
||||
from vllm.v1.worker.gpu.model_states.interface import ModelState
|
||||
|
||||
native = backend.store_client.store
|
||||
values = {"a": 1.0, "b": 2.0, "c": 3.0}
|
||||
if mode == "legacy":
|
||||
old_namespace = KEY.replace("@protocol:v3", "@protocol:v2")
|
||||
for key in "abc":
|
||||
native.objects[make_embedding_key(old_namespace, key)] = b"old format"
|
||||
if mode == "partial":
|
||||
hits = {"a", "c"}
|
||||
elif mode not in ("miss", "legacy"):
|
||||
hits = set("abc")
|
||||
else:
|
||||
hits = set()
|
||||
for key in hits:
|
||||
backend.store_client.put_tensor(
|
||||
make_embedding_key(KEY, key), torch.full((2, 2), values[key])
|
||||
)
|
||||
if mode == "short-data":
|
||||
key = make_embedding_key(KEY, "b")
|
||||
native.objects[key] = native.objects[key][:-1]
|
||||
hits.remove("b")
|
||||
if mode in ("get-failure", "lease-expired"):
|
||||
read = native.batch_get_into
|
||||
|
||||
def failed_read(keys, pointers, sizes):
|
||||
results = read(keys, pointers, sizes)
|
||||
results[keys.index(make_embedding_key(KEY, "b"))] = (
|
||||
-707 if mode == "lease-expired" else -704
|
||||
)
|
||||
return results
|
||||
|
||||
native.batch_get_into = failed_read
|
||||
hits.remove("b")
|
||||
if mode == "registration-failure":
|
||||
native.register_buffer = MagicMock(return_value=-500)
|
||||
hits.clear()
|
||||
connector = make_worker(backend)
|
||||
metadata = ECMooncakeConnectorMetadata(
|
||||
store_candidates=dict.fromkeys("abc", SPEC),
|
||||
pushes=[
|
||||
ECMooncakePushSpec(
|
||||
mm_hash=k,
|
||||
shape=(2, 2),
|
||||
dtype="float32",
|
||||
nbytes=16,
|
||||
consumer_zmq="ipc:///tmp/test",
|
||||
transfer_id=k,
|
||||
request_id="req",
|
||||
)
|
||||
for k in "abc"
|
||||
],
|
||||
)
|
||||
cache = EncoderCache()
|
||||
cache.mm_features["req"] = [
|
||||
MultiModalFeatureSpec(
|
||||
data=MultiModalKwargsItem({}),
|
||||
modality="image",
|
||||
identifier=k,
|
||||
mm_position=PlaceholderRange(offset=i * 2, length=2),
|
||||
)
|
||||
for i, k in enumerate("abc")
|
||||
]
|
||||
runner = EncoderRunner(
|
||||
model=None,
|
||||
max_num_tokens=8,
|
||||
hidden_size=2,
|
||||
encoder_cache=cache,
|
||||
dtype=torch.float32,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
runner.enable_timing = False
|
||||
missing = [k for k in "abc" if k not in hits]
|
||||
runner.execute_mm_encoder = MagicMock(
|
||||
return_value=[torch.full((2, 2), values[k] + 10) for k in missing]
|
||||
)
|
||||
state = SimpleNamespace(encoder_runner=runner, encoder_cache=cache)
|
||||
with patch(
|
||||
"vllm.v1.worker.gpu.ec_connector.get_ec_transfer", return_value=connector
|
||||
):
|
||||
adapter = ActiveECConnector(SimpleNamespace(), cache.encoder_outputs)
|
||||
with adapter.maybe_get_output(
|
||||
SimpleNamespace(ec_connector_metadata=metadata, finished_req_ids=set())
|
||||
) as output:
|
||||
assert runner.prepare_mm_inputs({"req": [0, 1, 2]})[0] == missing
|
||||
ModelState.execute_mm_encoder(state, {"req": [0, 1, 2]})
|
||||
assert runner.execute_mm_encoder.call_count == bool(missing)
|
||||
assert output.ec_connector_worker_meta.pending_saves is False
|
||||
assert all(
|
||||
torch.equal(
|
||||
cache.encoder_outputs[k],
|
||||
torch.full((2, 2), values[k] + (0 if k in hits else 10)),
|
||||
)
|
||||
for k in "abc"
|
||||
)
|
||||
assert {
|
||||
c.args[1] for c in connector._worker._bind_push_source.call_args_list
|
||||
} == set("abc")
|
||||
backend.shutdown()
|
||||
assert not native.registered
|
||||
if mode in ("miss", "legacy"):
|
||||
other = store_backend.MooncakeEmbeddingStoreBackend(
|
||||
store_client.MooncakeEmbeddingStoreClient(native, read_buffer_bytes=1024),
|
||||
KEY,
|
||||
max_pending_items=32,
|
||||
max_pending_bytes=2 * 1024**3,
|
||||
)
|
||||
try:
|
||||
loaded: dict[str, torch.Tensor] = {}
|
||||
assert other.resolve_inputs(
|
||||
dict.fromkeys("abc", SPEC),
|
||||
loaded,
|
||||
"cpu",
|
||||
) == set("abc")
|
||||
assert all(torch.equal(loaded[k], cache.encoder_outputs[k]) for k in "abc")
|
||||
finally:
|
||||
other.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mismatch",
|
||||
["revision", "shape", "dtype", "magic", "short-header", "short-data", "long-data"],
|
||||
)
|
||||
def test_incompatible_output_is_a_miss(backend, mismatch):
|
||||
key = make_embedding_key(KEY, "a")
|
||||
dtype = torch.float16 if mismatch == "dtype" else torch.float32
|
||||
backend.store_client.put_tensor(key, torch.ones(2, 2, dtype=dtype))
|
||||
if mismatch == "revision":
|
||||
backend.namespace = KEY.replace("@revision:revision", "@revision:other")
|
||||
objects = backend.store_client.store.objects
|
||||
if mismatch == "magic":
|
||||
objects[key] = b"\0" * 4 + objects[key][4:]
|
||||
elif mismatch == "short-header":
|
||||
objects[key] = objects[key][:23]
|
||||
elif mismatch == "short-data":
|
||||
objects[key] = objects[key][:-1]
|
||||
elif mismatch == "long-data":
|
||||
objects[key] += b"extra"
|
||||
expected = replace(SPEC, shape=(4, 1)) if mismatch == "shape" else SPEC
|
||||
outputs: dict[str, torch.Tensor] = {}
|
||||
assert not backend.resolve_inputs({"a": expected}, outputs, "cpu")
|
||||
assert not outputs
|
||||
tensor = torch.ones(2, 2)
|
||||
backend.store_client.put_tensor(
|
||||
make_embedding_key(backend.namespace, "valid"), tensor
|
||||
)
|
||||
assert backend.resolve_inputs({"valid": SPEC}, outputs, "cpu") == {"valid"}
|
||||
assert torch.equal(outputs["valid"], tensor)
|
||||
assert len(backend.store_client.store.registered) == 2
|
||||
|
||||
|
||||
def test_partial_registration_rejection_releases_publication(backend):
|
||||
"""A rejected header registration must not prevent a later publication."""
|
||||
native = backend.store_client.store
|
||||
register = native.register_buffer
|
||||
put = native.batch_put_from_multi_buffers
|
||||
native.register_buffer = lambda addr, size: (
|
||||
-500 if size == 24 else register(addr, size)
|
||||
)
|
||||
native.batch_put_from_multi_buffers = MagicMock()
|
||||
tensor = torch.ones(2, 2)
|
||||
owner = weakref.ref(tensor)
|
||||
assert backend._enqueue_save("a", tensor)
|
||||
storage_owner = weakref.ref(tensor.untyped_storage())
|
||||
future = backend._pending["a"][0]
|
||||
with pytest.raises(store_client.EmbeddingStoreOperationError, match="register"):
|
||||
future.result(timeout=5)
|
||||
del tensor
|
||||
gc.collect()
|
||||
assert owner() is None and not native.registered
|
||||
native.batch_put_from_multi_buffers.assert_not_called()
|
||||
backend.resolve_inputs({}, {}, "cpu")
|
||||
assert backend._pending_bytes == 0
|
||||
gc.collect()
|
||||
assert storage_owner() is None # The failed Future is still alive.
|
||||
assert backend.store_client._put_header is None
|
||||
native.register_buffer = register
|
||||
native.batch_put_from_multi_buffers = put
|
||||
backend.store_client.put_tensor("retry", torch.ones(2, 2))
|
||||
assert len(native.registered) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"operation",
|
||||
["read-unregister", "header-unregister", "put", "rejected-put", "unregister"],
|
||||
)
|
||||
def test_native_io_owners(backend, operation):
|
||||
"""Uncertain I/O retains owners; completed rejection frees them even via Future."""
|
||||
native, client = backend.store_client.store, backend.store_client
|
||||
put = native.batch_put_from_multi_buffers
|
||||
backend.max_pending_bytes = SPEC.nbytes
|
||||
tensor = torch.ones(2, 2)
|
||||
owner = weakref.ref(tensor)
|
||||
rejected = operation == "rejected-put"
|
||||
if operation in ("read-unregister", "header-unregister"):
|
||||
key = make_embedding_key(KEY, "a")
|
||||
client.put_tensor(key, tensor)
|
||||
if operation == "read-unregister":
|
||||
client.load_tensors({key: SPEC}, "cpu")
|
||||
native.unregister_buffer = MagicMock(return_value=-500)
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unregister"):
|
||||
client.close()
|
||||
owner = weakref.ref(
|
||||
client._read_buffer
|
||||
if operation == "read-unregister"
|
||||
else client._put_header
|
||||
)
|
||||
else:
|
||||
if operation == "unregister":
|
||||
native.unregister_buffer = MagicMock(return_value=-500)
|
||||
else:
|
||||
native.batch_put_from_multi_buffers = MagicMock(
|
||||
return_value=[-1700 if rejected else -800]
|
||||
)
|
||||
assert backend._enqueue_save("a", tensor)
|
||||
future = backend._pending["a"][0]
|
||||
with pytest.raises(store_client.EmbeddingStoreError):
|
||||
future.result(timeout=5)
|
||||
del tensor
|
||||
gc.collect()
|
||||
if rejected:
|
||||
assert owner() is None # A live Future must not retain the tensor.
|
||||
tensor = torch.ones(4, 4) # Too large for admission after reaping.
|
||||
caller_owner = weakref.ref(tensor)
|
||||
backend._step_candidates = {"next"}
|
||||
backend.save_output("next", tensor)
|
||||
del tensor
|
||||
gc.collect()
|
||||
assert caller_owner() is None
|
||||
assert backend._pending_bytes == 0 and len(native.registered) == 1
|
||||
header = client._put_header
|
||||
native.batch_put_from_multi_buffers = put
|
||||
client.put_tensor("retry", torch.ones(1, 4))
|
||||
assert client._put_header is header
|
||||
else:
|
||||
assert owner() is not None and native.registered
|
||||
header = bytes(client._put_header)
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unconfirmed"):
|
||||
client.put_tensor("retry", torch.ones(1, 4))
|
||||
assert bytes(client._put_header) == header
|
||||
with pytest.raises(store_client.EmbeddingStoreError, match="unconfirmed"):
|
||||
client.close()
|
||||
|
||||
|
||||
def test_publication_budget_charges_and_releases_backing_storage(backend):
|
||||
tensor = torch.arange(16, dtype=torch.float32)[:4].view(2, 2)
|
||||
owner = weakref.ref(tensor)
|
||||
future: Future[None] = Future()
|
||||
backend.max_pending_items = 1
|
||||
backend.max_pending_bytes = tensor.nbytes
|
||||
with patch.object(backend._executor, "submit", return_value=future):
|
||||
assert not backend._enqueue_save("a", tensor)
|
||||
backend.max_pending_bytes = 64
|
||||
assert backend._enqueue_save("a", tensor)
|
||||
storage_owner = weakref.ref(tensor.untyped_storage())
|
||||
assert not backend._enqueue_save("b", tensor)
|
||||
del tensor
|
||||
gc.collect()
|
||||
backend.reap() # The final step-end poll precedes publication completion.
|
||||
assert owner() is not None
|
||||
backend._save(make_embedding_key(KEY, "a"), backend._pending["a"][1])
|
||||
future.set_result(None)
|
||||
assert owner() is None and storage_owner() is not None
|
||||
|
||||
def load_after_reaping(*args):
|
||||
assert not backend._pending and backend._pending_bytes == 0
|
||||
assert storage_owner() is None
|
||||
return {}
|
||||
|
||||
with patch.object(backend.store_client, "load_tensors", load_after_reaping):
|
||||
assert not backend.resolve_inputs({"b": SPEC}, {}, "cpu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rejected", [False, True])
|
||||
def test_shared_storage_budget_is_released_after_last_publication(backend, rejected):
|
||||
batch = torch.arange(16, dtype=torch.float32).view(4, 4)
|
||||
first: Future[None] = Future()
|
||||
last: Future[None] = Future()
|
||||
separate: Future[None] = Future()
|
||||
backend.max_pending_items = 2
|
||||
backend.max_pending_bytes = batch.nbytes
|
||||
with patch.object(backend._executor, "submit", side_effect=[first, last, separate]):
|
||||
assert backend._enqueue_save("a", batch[:2])
|
||||
assert backend._enqueue_save("b", batch[2:])
|
||||
assert backend._pending_bytes == batch.nbytes
|
||||
assert not backend._enqueue_save("a", batch[:2])
|
||||
assert not backend._enqueue_save("extra", batch[:1])
|
||||
if rejected:
|
||||
first.set_exception(store_client.EmbeddingStoreOperationError("rejected"))
|
||||
else:
|
||||
first.set_result(None)
|
||||
backend.reap()
|
||||
assert backend._pending_bytes == batch.nbytes
|
||||
assert not backend._enqueue_save("c", torch.ones(2, 2))
|
||||
last.set_result(None)
|
||||
backend.reap()
|
||||
assert backend._pending_bytes == 0
|
||||
assert backend._enqueue_save("c", torch.ones(2, 2))
|
||||
assert backend._pending_bytes == 16
|
||||
separate.set_result(None)
|
||||
backend.reap()
|
||||
assert backend._pending_bytes == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shared_storage", [False, True])
|
||||
def test_completion_race_preserves_failure_and_reclaims_other_items(
|
||||
backend, shared_storage
|
||||
):
|
||||
class RacingFuture(Future[None]):
|
||||
def done(self):
|
||||
observed = super().done()
|
||||
if not observed:
|
||||
self.set_exception(store_client.EmbeddingStoreError("uncertain"))
|
||||
return observed
|
||||
|
||||
racing = RacingFuture()
|
||||
other: Future[None] = Future()
|
||||
tensor = torch.ones(2, 2)
|
||||
other_tensor = tensor[:1] if shared_storage else torch.ones(2, 2)
|
||||
with patch.object(backend._executor, "submit", side_effect=[racing, other]):
|
||||
assert backend._enqueue_save("race", tensor)
|
||||
assert backend._enqueue_save("other", other_tensor)
|
||||
backend.reap()
|
||||
assert backend._pending_bytes == (16 if shared_storage else 32)
|
||||
other.set_result(None)
|
||||
with pytest.raises(store_client.EmbeddingStoreError):
|
||||
backend.reap()
|
||||
assert backend._pending_bytes == 16
|
||||
with pytest.raises(store_client.EmbeddingStoreError):
|
||||
backend._enqueue_save("later", torch.ones(2, 2))
|
||||
|
||||
|
||||
def test_readiness_and_shutdown_do_not_block_p2p_completion(backend):
|
||||
ready, waiting, entered = [threading.Event() for _ in range(3)]
|
||||
|
||||
original = backend._executor.shutdown
|
||||
|
||||
def closing(*args, **kwargs):
|
||||
entered.set()
|
||||
return original(*args, **kwargs)
|
||||
|
||||
native = backend.store_client.store
|
||||
|
||||
def close_store():
|
||||
assert ready.is_set() and not native.registered
|
||||
assert backend._pending_bytes == 0
|
||||
return 0
|
||||
|
||||
native.close = MagicMock(side_effect=close_store)
|
||||
put = native.batch_put_from_multi_buffers
|
||||
|
||||
def waiting_put(*args):
|
||||
waiting.set()
|
||||
assert ready.wait(5)
|
||||
assert backend.store_client._put_header is not None and native.registered
|
||||
return put(*args)
|
||||
|
||||
native.batch_put_from_multi_buffers = waiting_put
|
||||
connector = make_worker(backend)
|
||||
connector.bind_connector_metadata(
|
||||
ECMooncakeConnectorMetadata(store_candidates={"a": SPEC})
|
||||
)
|
||||
cache: dict[str, torch.Tensor] = {}
|
||||
with (
|
||||
patch.object(
|
||||
store_backend, "_record_tensor_ready_event", return_value=MagicMock()
|
||||
),
|
||||
patch.object(backend._executor, "shutdown", side_effect=closing),
|
||||
ThreadPoolExecutor(max_workers=1) as closer,
|
||||
):
|
||||
connector.start_save_caches(encoder_cache=cache)
|
||||
cache["a"] = torch.arange(4, dtype=torch.float32).view(2, 2)
|
||||
connector.save_caches(cache, "a")
|
||||
assert connector.build_connector_worker_meta().pending_saves is False
|
||||
assert waiting.wait(5) and not backend.store_client.store.objects
|
||||
close = closer.submit(backend.shutdown)
|
||||
try:
|
||||
assert entered.wait(5) and not close.done()
|
||||
assert not backend._enqueue_save("late", torch.ones(2, 2))
|
||||
finally:
|
||||
ready.set()
|
||||
close.result(timeout=5)
|
||||
native.close.assert_called_once_with()
|
||||
assert not backend.store_client.store.registered and backend._pending_bytes == 0
|
||||
|
||||
assert backend.store_client.store.objects[make_embedding_key(KEY, "a")][
|
||||
24:
|
||||
] == struct.pack("<4f", 0, 1, 2, 3)
|
||||
@@ -1,161 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""E2E test for the ECCPUConnector.
|
||||
|
||||
Verifies:
|
||||
- Accuracy: outputs from EC CPU cache match fresh encoder computation.
|
||||
- Latency: loading from EC CPU cache is faster than a cold encoder run.
|
||||
|
||||
Requires a CUDA or XPU GPU and the Qwen2-VL-2B-Instruct model.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from tqdm import tqdm
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.assets.image import ImageAsset
|
||||
from vllm.config import ECTransferConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL = "Qwen/Qwen2-VL-2B-Instruct"
|
||||
EC_CPU_BYTES = 500 << 20 # 500 MiB
|
||||
|
||||
|
||||
def _build_image_prompt(image):
|
||||
"""Build a Qwen2-VL prompt with a single image."""
|
||||
return {
|
||||
"prompt": (
|
||||
"<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
|
||||
"<|im_start|>user\n"
|
||||
"<|vision_start|><|image_pad|><|vision_end|>"
|
||||
"Describe this image briefly.<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
),
|
||||
"multi_modal_data": {"image": image},
|
||||
}
|
||||
|
||||
|
||||
def _make_unique_image(base_image, iteration: int):
|
||||
"""Create a unique image by modifying a pixel to change the mm_hash."""
|
||||
img = base_image.copy()
|
||||
img.putpixel((0, 0), (iteration % 256, iteration // 256 % 256, 0))
|
||||
return img
|
||||
|
||||
|
||||
def _wait_for_ec_ready(llm: LLM) -> None:
|
||||
"""Send a dummy request to force a scheduler step.
|
||||
|
||||
When generate() returns, the save copy has been issued to the GPU but its
|
||||
completion event may fire on a later step, so the entry is not yet marked
|
||||
ready. This extra step lets the scheduler poll the worker's completion
|
||||
report and mark the entry ready.
|
||||
"""
|
||||
llm.generate("hi", SamplingParams(max_tokens=1), use_tqdm=False)
|
||||
|
||||
|
||||
def _latency_test(llm: LLM) -> None:
|
||||
"""Verify EC CPU cache hit is faster than cold encoder computation."""
|
||||
if not (current_platform.is_cuda() or current_platform.is_xpu()):
|
||||
pytest.skip("Latency test requires an accelerator (CUDA or XPU)")
|
||||
|
||||
sampling_params = SamplingParams(max_tokens=1, temperature=0)
|
||||
base_image = ImageAsset("stop_sign").pil_image
|
||||
|
||||
num_times_ec_better_than_cold = 0
|
||||
num_tests = 10
|
||||
total_cold_time = 0.0
|
||||
total_ec_hit_time = 0.0
|
||||
|
||||
for i in tqdm(range(num_tests), desc="EC latency test"):
|
||||
# Use a unique image each iteration so the cold run is truly cold
|
||||
# (EC has never seen this mm_hash before).
|
||||
image = _make_unique_image(base_image, i)
|
||||
prompt = _build_image_prompt(image)
|
||||
|
||||
# Cold run: encoder computes from scratch, saves to EC CPU.
|
||||
llm.llm_engine.reset_encoder_cache()
|
||||
start_time = time.time()
|
||||
llm.generate([prompt], sampling_params, use_tqdm=False)
|
||||
cold_time = time.time() - start_time
|
||||
total_cold_time += cold_time
|
||||
|
||||
# Ensure EC entry is marked ready.
|
||||
_wait_for_ec_ready(llm)
|
||||
|
||||
# Clear GPU encoder cache but keep EC CPU cache intact.
|
||||
llm.llm_engine.reset_encoder_cache()
|
||||
|
||||
# EC hit: scheduler loads from CPU mmap instead of re-encoding.
|
||||
start_time = time.time()
|
||||
llm.generate([prompt], sampling_params, use_tqdm=False)
|
||||
ec_hit_time = time.time() - start_time
|
||||
total_ec_hit_time += ec_hit_time
|
||||
|
||||
if ec_hit_time < cold_time:
|
||||
num_times_ec_better_than_cold += 1
|
||||
|
||||
print("Average times:")
|
||||
print(f" Cold: {total_cold_time * 1000 / num_tests:.2f}ms")
|
||||
print(f" EC hit: {total_ec_hit_time * 1000 / num_tests:.2f}ms")
|
||||
|
||||
assert num_times_ec_better_than_cold >= 0.8 * num_tests, (
|
||||
f"EC hit was faster only {num_times_ec_better_than_cold}/{num_tests} "
|
||||
f"times (expected >= 80%)"
|
||||
)
|
||||
|
||||
|
||||
def _accuracy_test(llm: LLM) -> None:
|
||||
"""Verify EC CPU cache produces correct outputs."""
|
||||
sampling_params = SamplingParams(max_tokens=8, temperature=0)
|
||||
image = ImageAsset("stop_sign").pil_image
|
||||
prompt = _build_image_prompt(image)
|
||||
|
||||
# Seed: generate with fresh encoder to establish baseline output.
|
||||
llm.llm_engine.reset_encoder_cache()
|
||||
baseline = llm.generate([prompt], sampling_params, use_tqdm=False)
|
||||
baseline_text = baseline[0].outputs[0].text
|
||||
|
||||
# Ensure EC entry is marked ready.
|
||||
_wait_for_ec_ready(llm)
|
||||
|
||||
# Clear GPU encoder cache so subsequent runs go through EC CPU path.
|
||||
llm.llm_engine.reset_encoder_cache()
|
||||
|
||||
# Generate multiple times from EC cache and check correctness.
|
||||
test_count = 20
|
||||
results = llm.generate([prompt] * test_count, sampling_params, use_tqdm=False)
|
||||
|
||||
success_count = sum(1 for r in results if r.outputs[0].text == baseline_text)
|
||||
assert success_count >= 0.5 * test_count, (
|
||||
f"Only {success_count}/{test_count} outputs matched baseline "
|
||||
f"(expected >= 50%). Baseline: {baseline_text!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not (current_platform.is_cuda() or current_platform.is_xpu()),
|
||||
reason="Requires an accelerator (CUDA or XPU)",
|
||||
)
|
||||
def test_ec_cpu_offloading() -> None:
|
||||
"""Tests ECCPUConnector accuracy and latency with a VLM model."""
|
||||
ec_transfer_config = ECTransferConfig(
|
||||
ec_connector="ECCPUConnector",
|
||||
ec_role="ec_both",
|
||||
ec_connector_extra_config={"ec_cpu_bytes": EC_CPU_BYTES},
|
||||
)
|
||||
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
max_model_len=2048,
|
||||
gpu_memory_utilization=0.5,
|
||||
enforce_eager=True,
|
||||
ec_transfer_config=ec_transfer_config,
|
||||
)
|
||||
|
||||
try:
|
||||
_latency_test(llm)
|
||||
_accuracy_test(llm)
|
||||
finally:
|
||||
del llm
|
||||
@@ -1,92 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Startup measurement of the encoder output width EC producers size by."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.ec_connector.unit.utils import create_ec_vllm_config
|
||||
from vllm.distributed.ec_transfer.ec_connector import encoder_output_width as eow
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
|
||||
class _DeepStackModel:
|
||||
"""Emits each modality at its own width, as Qwen3-Omni does."""
|
||||
|
||||
widths = {"image": 4 * 16, "audio": 16}
|
||||
|
||||
def embed_multimodal(self, *, modality):
|
||||
return [torch.zeros(3, self.widths[modality])]
|
||||
|
||||
|
||||
class _Budget:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.mm_max_toks_per_item = dict.fromkeys(_DeepStackModel.widths, 8)
|
||||
|
||||
def get_dummy_encoder_profile_inputs(self, modality, max_items_per_batch):
|
||||
assert max_items_per_batch == 1
|
||||
return [(modality, None)]
|
||||
|
||||
|
||||
def _worker(first_pp_rank=True, supports_mm=True):
|
||||
runner = SimpleNamespace(
|
||||
supports_mm_inputs=supports_mm,
|
||||
get_model=_DeepStackModel,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
pp_group = SimpleNamespace(is_first_rank=first_pp_rank)
|
||||
return SimpleNamespace(model_runner=runner, vllm_config=None), pp_group
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def patched(monkeypatch):
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.multimodal.encoder_budget as budget_mod
|
||||
import vllm.multimodal.utils as mm_utils
|
||||
|
||||
monkeypatch.setattr(budget_mod, "MultiModalBudget", _Budget)
|
||||
monkeypatch.setattr(
|
||||
mm_utils,
|
||||
"group_and_batch_mm_kwargs",
|
||||
lambda items, **_: iter([(items[0][0], 1, {"modality": items[0][0]})]),
|
||||
)
|
||||
return lambda group: monkeypatch.setattr(ps, "get_pp_group", lambda: group)
|
||||
|
||||
|
||||
def test_worker_reports_the_encoder_output_width_per_modality(patched):
|
||||
"""The width comes from the tensor the encoder emits, not from config."""
|
||||
worker, group = _worker()
|
||||
patched(group)
|
||||
assert eow._measure_on_worker(worker) == {"image": 64, "audio": 16}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("first_pp_rank, supports_mm", [(False, True), (True, False)])
|
||||
def test_ranks_without_an_encoder_report_nothing(patched, first_pp_rank, supports_mm):
|
||||
worker, group = _worker(first_pp_rank, supports_mm)
|
||||
patched(group)
|
||||
assert eow._measure_on_worker(worker) == {}
|
||||
|
||||
|
||||
def test_producer_records_the_widths_its_encoder_ranks_agree_on():
|
||||
config = create_ec_vllm_config(ec_role="ec_producer", encoder_output_widths={})
|
||||
reports = [{"image": 64}, {}, {"image": 64}]
|
||||
eow.measure_encoder_output_widths(config, lambda fn: reports)
|
||||
assert config.ec_transfer_config.mm_encoder_output_widths == {"image": 64}
|
||||
assert eow.get_encoder_output_width(config, "image") == 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reports, match",
|
||||
[
|
||||
([{}, {}], "could not measure"),
|
||||
([{"image": 64}, {"image": 16}], "disagree"),
|
||||
],
|
||||
ids=["no-encoder", "disagree"],
|
||||
)
|
||||
def test_producer_refuses_to_start_without_a_trustworthy_width(reports, match):
|
||||
config = create_ec_vllm_config(ec_role="ec_producer", encoder_output_widths={})
|
||||
with pytest.raises(ValueError, match=match):
|
||||
eow.measure_encoder_output_widths(config, lambda fn: reports)
|
||||
@@ -1,332 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Test for the fix in PR #29987: Eagerly abort cancelled final-step requests.
|
||||
|
||||
This test verifies that when a request is aborted during its final execution
|
||||
step (when it would naturally complete), it is properly marked as aborted
|
||||
rather than being treated as normally completed.
|
||||
|
||||
The test uses a dummy KV connector to verify that the connector receives
|
||||
the correct finish status (FINISHED_ABORTED, not FINISHED_LENGTH_CAPPED).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorBase_V1,
|
||||
KVConnectorMetadata,
|
||||
KVConnectorRole,
|
||||
)
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.request import Request
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
|
||||
|
||||
TEXT_PROMPT = "Hello"
|
||||
|
||||
|
||||
class DummyKVConnectorMetadata(KVConnectorMetadata):
|
||||
"""Dummy metadata for the test connector."""
|
||||
|
||||
def __init__(self):
|
||||
self.requests: list = []
|
||||
|
||||
|
||||
class DummyKVConnector(KVConnectorBase_V1):
|
||||
"""Dummy KV connector that captures request finish statuses to a file.
|
||||
This is used to verify the fix - without the fix, a request aborted
|
||||
during its final step would be captured as FINISHED_LENGTH_CAPPED
|
||||
instead of FINISHED_ABORTED.
|
||||
|
||||
The connector runs in a separate process, so we write statuses to a file
|
||||
that can be read by the test process.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
role: KVConnectorRole,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
):
|
||||
super().__init__(vllm_config, role, kv_cache_config)
|
||||
# Get the status file path from extra config
|
||||
extra_config = vllm_config.kv_transfer_config.kv_connector_extra_config or {}
|
||||
self.status_file = extra_config.get("status_file")
|
||||
# Log that we were initialized
|
||||
if self.status_file:
|
||||
try:
|
||||
with open(self.status_file, "a") as f:
|
||||
f.write(f"INIT:{role.name}\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def get_num_new_matched_tokens(
|
||||
self,
|
||||
request: Request,
|
||||
num_computed_tokens: int,
|
||||
) -> tuple[int | None, bool]:
|
||||
return (0, False)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self,
|
||||
request: Request,
|
||||
blocks: Any,
|
||||
num_external_tokens: int,
|
||||
):
|
||||
pass
|
||||
|
||||
def build_connector_meta(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> KVConnectorMetadata:
|
||||
return DummyKVConnectorMetadata()
|
||||
|
||||
def request_finished(
|
||||
self,
|
||||
request: Request,
|
||||
block_ids: list[int],
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
"""Capture the request status when finished by writing to a file."""
|
||||
if self.status_file:
|
||||
try:
|
||||
with open(self.status_file, "a") as f:
|
||||
# Write the status name (e.g., "FINISHED_ABORTED")
|
||||
f.write(f"{request.status.name}\n")
|
||||
except Exception as e:
|
||||
# Log but don't fail - this is just test instrumentation
|
||||
print(f"[DummyKVConnector] Failed to write status: {e}")
|
||||
return False, None
|
||||
|
||||
def start_load_kv(self, forward_context: Any, **kwargs: Any) -> None:
|
||||
pass
|
||||
|
||||
def wait_for_layer_load(self, layer_name: str) -> None:
|
||||
pass
|
||||
|
||||
def save_kv_layer(
|
||||
self,
|
||||
layer_name: str,
|
||||
kv_layer: Any,
|
||||
attn_metadata: Any,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def wait_for_save(self):
|
||||
pass
|
||||
|
||||
|
||||
# Register the dummy connector
|
||||
KVConnectorFactory.register_connector(
|
||||
"DummyKVConnector", __name__, DummyKVConnector.__name__
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_scheduling", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_abort_during_final_step(async_scheduling: bool):
|
||||
"""Test that a request aborted during its final execution step is treated as
|
||||
aborted rather than completed.
|
||||
|
||||
This test:
|
||||
1. Monkeypatches execute_model to wait for a file to be deleted
|
||||
2. Configures a dummy KV connector to capture finish statuses
|
||||
3. Starts a request with max_tokens=1 (will complete on first decode step)
|
||||
4. Aborts the request, then deletes the file to unblock execute_model
|
||||
5. Verifies the KV connector received FINISHED_ABORTED not FINISHED_LENGTH_CAPPED
|
||||
|
||||
See https://github.com/vllm-project/vllm/pull/29987.
|
||||
|
||||
Without the fix, the KV connector would see FINISHED_LENGTH_CAPPED because
|
||||
update_from_output() would mark the request as completed before processing
|
||||
the abort. This causes KV cache blocks to not be freed properly in
|
||||
disaggregated prefill scenarios.
|
||||
|
||||
With the fix, _process_aborts_queue() runs before update_from_output(), so the
|
||||
abort takes precedence and the KV connector sees FINISHED_ABORTED.
|
||||
"""
|
||||
# Create three temporary files:
|
||||
# 1. ready_file: deleted by execute_model to signal it has started
|
||||
# 2. block_file: execute_model waits for this to be deleted
|
||||
# 3. status_file: KV connector writes finish statuses here
|
||||
with tempfile.NamedTemporaryFile(delete=False) as f:
|
||||
ready_file = Path(f.name)
|
||||
with tempfile.NamedTemporaryFile(delete=False) as f2:
|
||||
block_file = Path(f2.name)
|
||||
with tempfile.NamedTemporaryFile(delete=False, mode="w") as f3:
|
||||
status_file = Path(f3.name)
|
||||
|
||||
try:
|
||||
# Get the original execute_model method
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
original_execute_model = Worker.execute_model
|
||||
|
||||
def execute_model_with_wait(self, scheduler_output):
|
||||
# V2's `gpu_worker.compile_or_warm_up_model` calls
|
||||
# `warmup_kernels(...)` during engine init, which itself calls
|
||||
# `Worker.execute_model` three times (prefill / decode / cleanup)
|
||||
# to JIT compile triton kernels. None of those carry the test's
|
||||
# request id, so we only stall when our actual request is being
|
||||
# processed.
|
||||
scheduled = scheduler_output.num_scheduled_tokens or {}
|
||||
finished = scheduler_output.finished_req_ids or set()
|
||||
|
||||
def is_target_request(req_ids):
|
||||
return any(
|
||||
rid == request_id or rid.startswith(f"{request_id}-")
|
||||
for rid in req_ids
|
||||
)
|
||||
|
||||
if is_target_request(scheduled) or is_target_request(finished):
|
||||
# Signal that execute_model has been called by deleting ready_file
|
||||
if ready_file.exists():
|
||||
ready_file.unlink()
|
||||
|
||||
# Wait for the block file to be deleted (triggered from test after
|
||||
# abort). This runs in the worker process (after fork), so we poll
|
||||
# the filesystem.
|
||||
while block_file.exists():
|
||||
time.sleep(0.01)
|
||||
return original_execute_model(self, scheduler_output)
|
||||
|
||||
# Patch execute_model to inject the wait
|
||||
# This happens before the worker process is forked, so the patch applies there
|
||||
with patch.object(Worker, "execute_model", execute_model_with_wait):
|
||||
request_id = "test-abort-final-step"
|
||||
|
||||
# Configure engine with dummy KV connector
|
||||
# Pass the status file path so the connector can write to it
|
||||
kv_transfer_config = KVTransferConfig(
|
||||
kv_connector="DummyKVConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"status_file": str(status_file)},
|
||||
)
|
||||
engine_args = AsyncEngineArgs(
|
||||
model="meta-llama/Llama-3.2-1B-Instruct",
|
||||
enforce_eager=True,
|
||||
async_scheduling=async_scheduling,
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
|
||||
try:
|
||||
# Create a request that will complete after just 1 token
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=1,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.DELTA,
|
||||
)
|
||||
|
||||
# Start generation in a task
|
||||
outputs = []
|
||||
|
||||
async def generate():
|
||||
async for output in engine.generate(
|
||||
request_id=request_id,
|
||||
prompt=TEXT_PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
outputs.append(output)
|
||||
|
||||
gen_task = asyncio.create_task(generate())
|
||||
|
||||
# Wait for execute_model to signal it has started (with timeout)
|
||||
timeout = 5.0 # 5 second timeout
|
||||
start_time = time.time()
|
||||
while ready_file.exists():
|
||||
if time.time() - start_time > timeout:
|
||||
raise TimeoutError(
|
||||
"Timeout waiting for execute_model to start. "
|
||||
"The monkeypatch may not be working correctly, "
|
||||
"for example if spawn was used instead of fork."
|
||||
)
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
# Abort the request while execute_model is blocked
|
||||
await engine.abort(request_id)
|
||||
|
||||
# Now unblock execute_model by deleting the file
|
||||
# The abort should be processed before the model output
|
||||
block_file.unlink()
|
||||
|
||||
# Wait for generation to complete
|
||||
await gen_task
|
||||
|
||||
# Poll for the KV connector to record the finish status
|
||||
timeout = 5.0
|
||||
start = time.time()
|
||||
captured_statuses = []
|
||||
while time.time() - start < timeout:
|
||||
with open(status_file) as f4:
|
||||
status_lines = f4.read().strip().split("\n")
|
||||
captured_statuses = [
|
||||
line
|
||||
for line in status_lines
|
||||
if line and line.startswith("FINISHED_")
|
||||
]
|
||||
if captured_statuses:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
else:
|
||||
raise TimeoutError(
|
||||
"Timeout waiting for KV connector to record finish status."
|
||||
)
|
||||
|
||||
# Verify we got output
|
||||
assert len(outputs) > 0, "Should have received at least one output"
|
||||
|
||||
# The final output should have finish_reason="abort"
|
||||
final_output = outputs[-1]
|
||||
assert final_output.finished, (
|
||||
"Final output should be marked as finished"
|
||||
)
|
||||
assert final_output.outputs[0].finish_reason == "abort", (
|
||||
f"Expected finish_reason='abort' but got "
|
||||
f"'{final_output.outputs[0].finish_reason}'. "
|
||||
)
|
||||
|
||||
assert len(captured_statuses) >= 1, (
|
||||
f"Expected at least 1 captured finish status, got "
|
||||
f"{len(captured_statuses)}. File content: {status_lines}"
|
||||
)
|
||||
|
||||
assert "FINISHED_ABORTED" in captured_statuses, (
|
||||
f"KV connector should see FINISHED_ABORTED but got "
|
||||
f"{captured_statuses}. "
|
||||
)
|
||||
|
||||
# Verify cleanup
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
finally:
|
||||
# Shutdown the engine
|
||||
engine.shutdown()
|
||||
|
||||
finally:
|
||||
# Clean up temporary files if they still exist
|
||||
if ready_file.exists():
|
||||
ready_file.unlink()
|
||||
if block_file.exists():
|
||||
block_file.unlink()
|
||||
if status_file.exists():
|
||||
status_file.unlink()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,794 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import copy
|
||||
import time
|
||||
import uuid
|
||||
from collections import deque
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
ECTransferConfig,
|
||||
KVTransferConfig,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.engine import EngineCoreRequest, EngineCoreRequestType
|
||||
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore, EngineCoreProc
|
||||
from vllm.v1.executor.abstract import Executor
|
||||
from vllm.v1.executor.uniproc_executor import UniProcExecutor
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
|
||||
from ...utils import create_new_process_for_each_test, multi_gpu_test
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
|
||||
|
||||
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
TOKENIZER = AutoTokenizer.from_pretrained(MODEL_NAME)
|
||||
# test_engine_core_concurrent_batches assumes exactly 12 tokens per prompt.
|
||||
# Adjust prompt if changing model to maintain 12-token length.
|
||||
PROMPT = "I am Gyoubu Masataka Oniwa"
|
||||
PROMPT_TOKENS = TOKENIZER(PROMPT).input_ids
|
||||
|
||||
_REQUEST_COUNTER = 0
|
||||
|
||||
|
||||
def make_request() -> EngineCoreRequest:
|
||||
global _REQUEST_COUNTER
|
||||
_REQUEST_COUNTER += 1
|
||||
request_id = f"request-{_REQUEST_COUNTER}"
|
||||
return EngineCoreRequest(
|
||||
request_id=request_id,
|
||||
external_req_id=f"{request_id}-{uuid.uuid4()}",
|
||||
prompt_token_ids=PROMPT_TOKENS,
|
||||
mm_features=None,
|
||||
sampling_params=SamplingParams(),
|
||||
pooling_params=None,
|
||||
arrival_time=time.time(),
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core():
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
"""Test basic request lifecycle."""
|
||||
|
||||
# First request.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
|
||||
# Second request.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
# Add two requests in a row.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 2
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 4
|
||||
|
||||
# Loop through until they are all done.
|
||||
while (outs := engine_core.step_fn()[0].get(0)) and outs.outputs:
|
||||
pass
|
||||
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
"""Test abort cycle."""
|
||||
|
||||
# Basic abort.
|
||||
req = make_request()
|
||||
request_id = req.request_id
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
assert engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
assert engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
engine_core.abort_requests([request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
assert not engine_core.scheduler.has_unfinished_requests()
|
||||
assert engine_core.scheduler.has_finished_requests()
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert not engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
# Add, step, abort 1 of the 3.
|
||||
req0 = make_request()
|
||||
req1 = make_request()
|
||||
req2 = make_request()
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
assert len(engine_core.scheduler.waiting) == 2
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req2))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 3
|
||||
|
||||
# Abort just one.
|
||||
engine_core.abort_requests([req1.request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
# Abort the other requests at the same time.
|
||||
engine_core.abort_requests([req2.request_id, req0.request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
# Sending duplicate requests with same request_id
|
||||
req0 = make_request()
|
||||
req1 = make_request()
|
||||
req0.request_id = req1.request_id = "test"
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_advanced_sampling():
|
||||
"""A basic end-to-end test to verify that the engine functions correctly
|
||||
when additional sampling parameters, such as top_p, min_tokens, and
|
||||
presence_penalty, are set.
|
||||
"""
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
"""Test basic request lifecycle."""
|
||||
# First request.
|
||||
request: EngineCoreRequest = make_request()
|
||||
request.sampling_params = SamplingParams(
|
||||
min_tokens=4,
|
||||
presence_penalty=1.0,
|
||||
frequency_penalty=1.0,
|
||||
repetition_penalty=0.1,
|
||||
stop_token_ids=[1001, 1002],
|
||||
)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(request))
|
||||
|
||||
def _check_engine_state():
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
# Loop through until they are all done.
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_check_engine_state()
|
||||
|
||||
# Second request.
|
||||
request2 = make_request()
|
||||
request2.sampling_params = SamplingParams(
|
||||
top_p=0.99,
|
||||
top_k=50,
|
||||
)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(request2))
|
||||
_check_engine_state()
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_concurrent_batches():
|
||||
"""Test that the engine can handle multiple concurrent batches."""
|
||||
|
||||
def make_request_with_max_tokens(req_id: str, max_tokens: int) -> EngineCoreRequest:
|
||||
request = make_request()
|
||||
request.request_id = req_id
|
||||
request.sampling_params.max_tokens = max_tokens
|
||||
return request
|
||||
|
||||
class DummyExecutor(UniProcExecutor):
|
||||
def initialize_from_config(self, kv_cache_configs: list[KVCacheConfig]) -> None:
|
||||
super().initialize_from_config(kv_cache_configs)
|
||||
|
||||
# Create a thread pool with a single worker
|
||||
self.thread_pool = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def execute_model(
|
||||
self,
|
||||
scheduler_output,
|
||||
non_block=False,
|
||||
) -> Future[ModelRunnerOutput | None]:
|
||||
"""Make execute_model non-blocking."""
|
||||
# DummyExecutor used only for testing async case.
|
||||
assert non_block
|
||||
|
||||
def _execute():
|
||||
output = self.collective_rpc("execute_model", args=(scheduler_output,))
|
||||
# Make a copy because output[0] may be reused
|
||||
# by the next batch.
|
||||
return copy.deepcopy(output[0])
|
||||
|
||||
# Use the thread pool instead of creating a new thread
|
||||
return self.thread_pool.submit(_execute)
|
||||
|
||||
def sample_tokens(
|
||||
self, grammar_output, non_block=False
|
||||
) -> Future[ModelRunnerOutput]:
|
||||
"""Make sample_tokens non-blocking."""
|
||||
# DummyExecutor used only for testing async case.
|
||||
assert non_block
|
||||
|
||||
def _execute():
|
||||
output = self.collective_rpc("sample_tokens", args=(grammar_output,))
|
||||
# Make a copy because output[0] may be reused
|
||||
# by the next batch.
|
||||
return copy.deepcopy(output[0])
|
||||
|
||||
# Use the thread pool instead of creating a new thread
|
||||
return self.thread_pool.submit(_execute)
|
||||
|
||||
def shutdown(self):
|
||||
if hasattr(self, "thread_pool"):
|
||||
self.thread_pool.shutdown(wait=False)
|
||||
|
||||
engine_args = EngineArgs(
|
||||
model=MODEL_NAME,
|
||||
# To test concurrent batches.
|
||||
max_num_seqs=2,
|
||||
# Avoid all requests being scheduled once.
|
||||
enable_prefix_caching=False,
|
||||
max_num_batched_tokens=10,
|
||||
# Reduce startup time.
|
||||
enforce_eager=True,
|
||||
# Test concurrent batch behaviour independently of async scheduling.
|
||||
async_scheduling=False,
|
||||
)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
# Force two concurrent batches to exercise the batch queue independently
|
||||
# of async scheduling (which is disabled above).
|
||||
with (
|
||||
set_default_torch_num_threads(1),
|
||||
patch.object(
|
||||
VllmConfig,
|
||||
"max_concurrent_batches",
|
||||
new_callable=PropertyMock,
|
||||
return_value=2,
|
||||
),
|
||||
):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, log_stats=False, executor_class=DummyExecutor
|
||||
)
|
||||
assert engine_core.batch_queue is not None
|
||||
|
||||
# Add two requests in a row. Each request have 12 prompt tokens.
|
||||
req0 = make_request_with_max_tokens("0", 5)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
req1 = make_request_with_max_tokens("1", 5)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
|
||||
# Schedule Batch 1: (10, req0)
|
||||
assert engine_core.step_with_batch_queue()[0] is None
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 10
|
||||
# num_computed_tokens should have been updated immediately.
|
||||
assert engine_core.scheduler.requests[req0.request_id].num_computed_tokens == 10
|
||||
|
||||
# Schedule Batch 2: (2, req0), (8, req1)
|
||||
assert engine_core.step_with_batch_queue()[0] == {}
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 2
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 8
|
||||
# num_computed_tokens should have been updated immediately.
|
||||
assert engine_core.scheduler.requests["0"].num_computed_tokens == 12
|
||||
assert engine_core.scheduler.requests["1"].num_computed_tokens == 8
|
||||
|
||||
assert engine_core.scheduler.get_num_unfinished_requests() == 2
|
||||
|
||||
# Finish Batch 1 and schedule Batch 3: (4, req1).
|
||||
# Note that req0 cannot be scheduled
|
||||
# because it is in the decoding stage now.
|
||||
engine_core.step_with_batch_queue()
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 4
|
||||
|
||||
# Finish Batch 2. Get first token of req0.
|
||||
# Schedule Batch 4: (1, req0).
|
||||
output = engine_core.step_with_batch_queue()[0].get(0)
|
||||
assert output is not None
|
||||
assert len(output.outputs) == 1
|
||||
assert engine_core.scheduler.requests[req0.request_id].num_tokens == 13
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 1
|
||||
|
||||
# Finish Batch 3. Get first token of req1. Schedule Batch 5: (1, req1).
|
||||
output = engine_core.step_with_batch_queue()[0].get(0)
|
||||
assert output is not None
|
||||
assert len(output.outputs) == 1
|
||||
assert engine_core.scheduler.requests[req1.request_id].num_tokens == 13
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 1
|
||||
|
||||
# Loop until req0 is finished.
|
||||
req_id = 0
|
||||
expected_num_tokens = [
|
||||
engine_core.scheduler.requests["0"].num_tokens + 1,
|
||||
engine_core.scheduler.requests["1"].num_tokens + 1,
|
||||
]
|
||||
while engine_core.scheduler.get_num_unfinished_requests() == 2:
|
||||
output = engine_core.step_with_batch_queue()[0]
|
||||
# Every step consumes an output.
|
||||
assert output is not None
|
||||
assert len(output[0].outputs) == 1
|
||||
if req_id in engine_core.scheduler.requests:
|
||||
assert (
|
||||
engine_core.scheduler.requests[req_id].num_tokens
|
||||
== expected_num_tokens[req_id]
|
||||
)
|
||||
expected_num_tokens[req_id] += 1
|
||||
req_id = (req_id + 1) % 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoder_only", [True, False])
|
||||
def test_async_step_skips_sampling_for_mm_encoder_only(encoder_only):
|
||||
"""Encoder outputs are complete; only language-model steps need sampling."""
|
||||
core = MagicMock()
|
||||
core.batch_queue = deque()
|
||||
core.batch_queue_size = 2
|
||||
core.is_mm_encoder_only = encoder_only
|
||||
core.is_pooling_model = False
|
||||
core.scheduler.has_requests.side_effect = [True, False, False]
|
||||
scheduled = core.scheduler.schedule.return_value
|
||||
scheduled.total_num_scheduled_tokens = 16
|
||||
scheduled.pending_structured_output_tokens = False
|
||||
|
||||
output = MagicMock()
|
||||
executed: Future[ModelRunnerOutput | None] = Future()
|
||||
executed.set_result(output if encoder_only else None)
|
||||
sampled: Future[ModelRunnerOutput | None] = Future()
|
||||
sampled.set_result(None if encoder_only else output)
|
||||
core.model_executor.execute_model.return_value = executed
|
||||
core.model_executor.sample_tokens.return_value = sampled
|
||||
|
||||
EngineCore.step_with_batch_queue(core)
|
||||
if core.batch_queue:
|
||||
EngineCore.step_with_batch_queue(core)
|
||||
|
||||
core.scheduler.update_from_output.assert_called_once_with(scheduled, output)
|
||||
if encoder_only:
|
||||
core.model_executor.sample_tokens.assert_not_called()
|
||||
else:
|
||||
core.model_executor.sample_tokens.assert_called_once()
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
def test_engine_core_tp():
|
||||
"""Test engine can initialize worker in tp properly."""
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(
|
||||
model=MODEL_NAME,
|
||||
tensor_parallel_size=2,
|
||||
# Reduce startup time.
|
||||
enforce_eager=True,
|
||||
)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
def get_worker_cache_config_field(worker, key: str):
|
||||
return getattr(worker.cache_config, key)
|
||||
|
||||
num_gpu_blocks = engine_core.collective_rpc(
|
||||
get_worker_cache_config_field, args=("num_gpu_blocks",)
|
||||
)
|
||||
num_cpu_blocks = engine_core.collective_rpc(
|
||||
get_worker_cache_config_field, args=("num_cpu_blocks",)
|
||||
)
|
||||
assert all(x is not None for x in num_gpu_blocks)
|
||||
assert all(x is not None for x in num_cpu_blocks)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_invalid_request_id_type():
|
||||
"""Test that engine raises TypeError for non-string request_id."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
# Test with UUID object (common mistake)
|
||||
uuid_request = make_request()
|
||||
uuid_request.request_id = uuid.uuid4() # UUID object instead of string
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*UUID"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(uuid_request))
|
||||
|
||||
# Test with integer
|
||||
int_request = make_request()
|
||||
int_request.request_id = 12345
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*int"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(int_request))
|
||||
|
||||
# Test with None
|
||||
none_request = make_request()
|
||||
none_request.request_id = None
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*NoneType"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(none_request))
|
||||
|
||||
# Verify engine is still functional after errors
|
||||
valid_request = make_request()
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(valid_request))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
@pytest.mark.parametrize(
|
||||
("ec_role", "gpu_memory_utilization", "enable_prefix_caching"),
|
||||
[
|
||||
("ec_producer", 0.01, False),
|
||||
# NOTE: ec_producer never allows prefix caching
|
||||
("ec_consumer", 0.7, True),
|
||||
("ec_consumer", 0.7, False),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_kv_connector", [False, True])
|
||||
def test_encoder_instance_zero_kv_cache(
|
||||
ec_role: str,
|
||||
gpu_memory_utilization: float,
|
||||
enable_prefix_caching: bool,
|
||||
use_kv_connector: bool,
|
||||
):
|
||||
"""EPD (Encoder-Prefill-Decode) Encoder-cache-specific tests.
|
||||
|
||||
This test verifies encoder-only instance initializes with 0 KV cache blocks.
|
||||
Under EPD disagg mode, Encoder instances (EC producer role) only execute
|
||||
vision encoder, so they don't need KV cache for text generation.
|
||||
"""
|
||||
# Form vllm config
|
||||
model_config = ModelConfig(
|
||||
model="llava-hf/llava-1.5-7b-hf", # Multimodal model
|
||||
enforce_eager=True,
|
||||
trust_remote_code=True,
|
||||
dtype="float16",
|
||||
seed=42,
|
||||
)
|
||||
scheduler_config = SchedulerConfig(
|
||||
max_num_seqs=10,
|
||||
max_num_batched_tokens=512,
|
||||
max_model_len=512,
|
||||
disable_hybrid_kv_cache_manager=True,
|
||||
is_encoder_decoder=model_config.is_encoder_decoder,
|
||||
)
|
||||
cache_config = CacheConfig(
|
||||
block_size=16,
|
||||
gpu_memory_utilization=gpu_memory_utilization,
|
||||
cache_dtype="auto",
|
||||
enable_prefix_caching=enable_prefix_caching,
|
||||
)
|
||||
kv_transfer_config = (
|
||||
KVTransferConfig(
|
||||
kv_connector="ExampleConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"shared_storage_path": "local_storage"},
|
||||
)
|
||||
if use_kv_connector
|
||||
else None
|
||||
)
|
||||
ec_transfer_config = ECTransferConfig(
|
||||
ec_connector="ECExampleConnector",
|
||||
ec_role=ec_role,
|
||||
ec_connector_extra_config={"shared_storage_path": "/tmp/ec_test_encoder"},
|
||||
)
|
||||
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
cache_config=cache_config,
|
||||
scheduler_config=scheduler_config,
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
ec_transfer_config=ec_transfer_config,
|
||||
)
|
||||
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
print(f"executor_class: {executor_class}")
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
# Check encoder cache manager exists
|
||||
assert engine_core.scheduler.encoder_cache_manager is not None, (
|
||||
"encoder_cache_manager should exist"
|
||||
)
|
||||
|
||||
if ec_role == "ec_producer":
|
||||
# Check 1: num_blocks should be 0
|
||||
# NOTE: num_blocks=1 as BlockPool always needs a null_block.
|
||||
kv_cache_config = engine_core.scheduler.kv_cache_manager.kv_cache_config
|
||||
print(f"kv_cache_config: {kv_cache_config}")
|
||||
assert kv_cache_config.num_blocks == 1, (
|
||||
f"ec_producer should only have 1 KV blocks, "
|
||||
f"got {kv_cache_config.num_blocks}"
|
||||
)
|
||||
|
||||
# Check 2: kv_cache_groups should be empty
|
||||
assert len(kv_cache_config.kv_cache_groups) == 0, (
|
||||
f"ec_producer should have 0 KV cache groups, "
|
||||
f"got {len(kv_cache_config.kv_cache_groups)}"
|
||||
)
|
||||
|
||||
# Check 3: kv_cache_tensors should be empty
|
||||
assert len(kv_cache_config.kv_cache_tensors) == 0, (
|
||||
f"Encoder instance should have 0 KV cache tensors, "
|
||||
f"got {len(kv_cache_config.kv_cache_tensors)}"
|
||||
)
|
||||
|
||||
# Check 4: Verify EC connector is initialized and is producer
|
||||
assert engine_core.scheduler.ec_connector is not None, (
|
||||
"Encoder instance should have EC connector"
|
||||
)
|
||||
assert engine_core.scheduler.ec_connector.is_producer, (
|
||||
"Encoder instance EC connector should be producer"
|
||||
)
|
||||
|
||||
# Check 5: Verify chunked prefill is disabled
|
||||
assert not vllm_config.scheduler_config.enable_chunked_prefill, (
|
||||
"Encoder instance should disable chunked prefill (no KV cache)"
|
||||
)
|
||||
|
||||
elif ec_role == "ec_consumer":
|
||||
# Check 1: num_blocks should be > 1
|
||||
kv_cache_config = engine_core.scheduler.kv_cache_manager.kv_cache_config
|
||||
print(f"kv_cache_config: {kv_cache_config}")
|
||||
assert kv_cache_config.num_blocks > 1, (
|
||||
f"ec_consumer should have >1 KV blocks, got {kv_cache_config.num_blocks}"
|
||||
)
|
||||
|
||||
# Check 2: kv_cache_groups should NOT be empty
|
||||
assert len(kv_cache_config.kv_cache_groups) > 0, (
|
||||
f"ec_consumer should have KV cache groups, "
|
||||
f"got {len(kv_cache_config.kv_cache_groups)}"
|
||||
)
|
||||
|
||||
# Check 3: Verify EC connector is consumer
|
||||
assert engine_core.scheduler.ec_connector is not None, (
|
||||
"Consumer instance should have EC connector"
|
||||
)
|
||||
assert not engine_core.scheduler.ec_connector.is_producer, (
|
||||
"Consumer instance EC connector should be consumer"
|
||||
)
|
||||
|
||||
|
||||
def _cadenced_dp_engine_core(
|
||||
monkeypatch, results: list[tuple[bool, bool]], dp_sync_interval: int = 32
|
||||
):
|
||||
"""A bare DPEngineCoreProc whose all-reduce is scripted by `results`;
|
||||
returns the core and the step numbers at which the all-reduce ran."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.dp_group = object()
|
||||
core.dp_sync_interval = dp_sync_interval
|
||||
core.step_counter = 0
|
||||
core.pending_pause = False
|
||||
core.ignore_start_dp_wave = False
|
||||
synced: list[int] = []
|
||||
|
||||
def scripted_sync(dp_group, has_unfinished, pending_pause):
|
||||
synced.append(core.step_counter)
|
||||
return results.pop(0)
|
||||
|
||||
monkeypatch.setattr(ParallelConfig, "sync_dp_state", staticmethod(scripted_sync))
|
||||
return core, synced
|
||||
|
||||
|
||||
def test_dp_sync_interval_default_is_16():
|
||||
"""Regression pin: lowering the default narrows the mid-wave pause tail
|
||||
for async RL, where the engine is rarely idle when pause lands."""
|
||||
assert ParallelConfig.dp_sync_interval == 16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dp_sync_interval", [32, 16])
|
||||
def test_dp_sync_interval_normal_wave(monkeypatch, dp_sync_interval: int):
|
||||
"""First all-reduce of a wave after one step, then every N."""
|
||||
core, synced = _cadenced_dp_engine_core(
|
||||
monkeypatch, [(True, False)] * 3, dp_sync_interval=dp_sync_interval
|
||||
)
|
||||
for _ in range(dp_sync_interval * 2 + 6):
|
||||
assert DPEngineCoreProc._has_global_unfinished_reqs(core, True)
|
||||
assert synced == [1, dp_sync_interval, dp_sync_interval * 2]
|
||||
|
||||
|
||||
def test_dp_sync_interval_idle_pause_consensus_on_first_step(monkeypatch):
|
||||
"""A pause of an idle engine arms every rank before its kick-started
|
||||
first step, so the step-1 sync reaches consensus after one dummy batch
|
||||
regardless of the configured cadence."""
|
||||
core, synced = _cadenced_dp_engine_core(
|
||||
monkeypatch, [(False, True)], dp_sync_interval=32
|
||||
)
|
||||
core.pending_pause = True
|
||||
assert DPEngineCoreProc._has_global_unfinished_reqs(core, False) is False
|
||||
assert synced == [1]
|
||||
assert core.ignore_start_dp_wave
|
||||
assert not core.pending_pause
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"request_wave,engines_running,pause_state,announces",
|
||||
[
|
||||
pytest.param(3, False, PauseState.UNPAUSED, True, id="current-wave"),
|
||||
pytest.param(2, False, PauseState.UNPAUSED, True, id="stale-wave"),
|
||||
pytest.param(4, False, PauseState.UNPAUSED, True, id="newer-wave"),
|
||||
pytest.param(3, True, PauseState.UNPAUSED, False, id="running"),
|
||||
pytest.param(3, False, PauseState.PAUSED_ALL, False, id="paused"),
|
||||
],
|
||||
)
|
||||
def test_idle_dp_rank_announces_wave_for_new_work(
|
||||
request_wave, engines_running, pause_state, announces
|
||||
):
|
||||
"""An idle rank handed work announces the wave itself, since only engines
|
||||
start waves; a paused rank waits for resume."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.has_coordinator = True
|
||||
core.current_wave = 3
|
||||
core.engines_running = engines_running
|
||||
core.scheduler = MagicMock(pause_state=pause_state)
|
||||
core.output_queue = MagicMock()
|
||||
|
||||
with patch.object(EngineCore, "add_request"):
|
||||
core.add_request(MagicMock(), request_wave)
|
||||
|
||||
if announces:
|
||||
assert core.engines_running
|
||||
_, outputs = core.output_queue.put_nowait.call_args.args[0]
|
||||
assert outputs.start_wave == max(request_wave, 3)
|
||||
else:
|
||||
core.output_queue.put_nowait.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("paused", [False, True])
|
||||
def test_paused_dp_rank_ignores_start_wave(paused):
|
||||
"""A START_DP_WAVE still in flight when the pause completes must not wake
|
||||
the paused rank."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.ignore_start_dp_wave = paused
|
||||
core.engine_index = 0
|
||||
core.current_wave = 3
|
||||
core.engines_running = False
|
||||
|
||||
core._handle_client_request(EngineCoreRequestType.START_DP_WAVE, (3, 1))
|
||||
|
||||
assert core.engines_running != paused
|
||||
|
||||
|
||||
def _pausable_engine_core_proc() -> EngineCoreProc:
|
||||
"""A bare EngineCoreProc holding just the state pause_scheduler touches."""
|
||||
core = object.__new__(EngineCoreProc)
|
||||
core.model_executor = MagicMock()
|
||||
core.scheduler = MagicMock()
|
||||
core.scheduler.has_requests.return_value = False
|
||||
core.batch_queue = None
|
||||
core.engines_running = False
|
||||
core._idle_state_callbacks = []
|
||||
return core
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pause_state,has_requests,has_batches",
|
||||
[
|
||||
pytest.param(PauseState.UNPAUSED, False, False, id="not-paused"),
|
||||
pytest.param(PauseState.PAUSED_ALL, True, False, id="pending-requests"),
|
||||
pytest.param(PauseState.PAUSED_ALL, False, True, id="pending-batches"),
|
||||
],
|
||||
)
|
||||
def test_kv_cache_release_rejects_unsafe_state(pause_state, has_requests, has_batches):
|
||||
"""Reject release before touching caches or memory if work can still use KV."""
|
||||
core = _pausable_engine_core_proc()
|
||||
core.scheduler.pause_state = pause_state
|
||||
core.scheduler.has_requests.return_value = has_requests
|
||||
core.batch_queue = [object()] if has_batches else None
|
||||
core._reset_caches = MagicMock()
|
||||
|
||||
with pytest.raises(RuntimeError, match="requires a completed pause"):
|
||||
core.release_kv_cache_memory()
|
||||
|
||||
core._reset_caches.assert_not_called()
|
||||
core.model_executor.discard.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deferred", [False, True])
|
||||
def test_pause_synchronizes_device_before_cache_reset(deferred: bool):
|
||||
"""A resolved pause promises an idle device: the barrier must run before
|
||||
caches are cleared and before the caller is unblocked."""
|
||||
core = _pausable_engine_core_proc()
|
||||
core.engines_running = deferred
|
||||
order: list[str] = []
|
||||
core.model_executor.collective_rpc.side_effect = lambda method: order.append(method)
|
||||
core._reset_caches = lambda: order.append("reset_caches")
|
||||
|
||||
result = EngineCoreProc.pause_scheduler(core, mode="keep", clear_cache=True)
|
||||
if deferred:
|
||||
assert isinstance(result, Future)
|
||||
assert not result.done() and order == []
|
||||
core.engines_running = False
|
||||
core._notify_idle_state_callbacks()
|
||||
assert result.result(timeout=0) is None
|
||||
else:
|
||||
assert result is None
|
||||
assert order == ["synchronize_device", "reset_caches"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,118 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.v1.core.sched.utils import check_stop
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
def _make_request(params: SamplingParams) -> Request:
|
||||
return Request(
|
||||
request_id="req-0",
|
||||
client_index=0,
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=params,
|
||||
pooling_params=None,
|
||||
arrival_time=time.time(),
|
||||
)
|
||||
|
||||
|
||||
def _normalize(params: SamplingParams, prompt_len: int, max_model_len: int) -> None:
|
||||
processor = SimpleNamespace(
|
||||
model_config=SimpleNamespace(max_model_len=max_model_len)
|
||||
)
|
||||
InputProcessor._normalize_trace_replay_params(processor, params, prompt_len)
|
||||
|
||||
|
||||
def test_normalize_trace_replay_params():
|
||||
params = SamplingParams(
|
||||
max_tokens=16,
|
||||
min_tokens=10,
|
||||
stop_token_ids=[20],
|
||||
trace_decode_token_ids=[10, 20, 30],
|
||||
)
|
||||
params.update_from_generation_config({}, eos_token_id=20)
|
||||
|
||||
_normalize(params, prompt_len=3, max_model_len=128)
|
||||
|
||||
assert params.max_tokens == 3
|
||||
assert params.min_tokens == 0
|
||||
assert params.ignore_eos is True
|
||||
assert params.eos_token_id is None
|
||||
assert params.stop_token_ids == []
|
||||
assert params.all_stop_token_ids == set()
|
||||
|
||||
request = _make_request(params)
|
||||
assert request.max_tokens == 3
|
||||
request.append_output_token_ids([10, 20, 30])
|
||||
assert check_stop(request, max_model_len=128)
|
||||
assert request.status == RequestStatus.FINISHED_LENGTH_CAPPED
|
||||
|
||||
|
||||
def test_trace_longer_than_remaining_context_is_truncated():
|
||||
"""The trace is staged into a max_model_len-wide row, so it must be cut.
|
||||
|
||||
An explicitly set max_tokens is never clamped to max_model_len, so it cannot
|
||||
bound the staged write.
|
||||
"""
|
||||
params = SamplingParams(max_tokens=100, trace_decode_token_ids=list(range(20)))
|
||||
|
||||
_normalize(params, prompt_len=6, max_model_len=10)
|
||||
|
||||
assert params.trace_decode_token_ids == [0, 1, 2, 3]
|
||||
assert params.max_tokens == 4
|
||||
|
||||
|
||||
def _validate(enable_trace_replay: bool) -> None:
|
||||
"""Run _validate_params' trace gating with the rest of verify() stubbed."""
|
||||
processor = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
return_sampling_mask=False,
|
||||
enable_trace_replay=enable_trace_replay,
|
||||
is_diffusion=False,
|
||||
),
|
||||
vllm_config=SimpleNamespace(
|
||||
reasoning_config=None,
|
||||
# Engine has no watermark configuration.
|
||||
_check_supports_watermarking=lambda params: False,
|
||||
),
|
||||
resolve_watermarking=lambda params: False,
|
||||
speculative_config=None,
|
||||
structured_outputs_config=None,
|
||||
diffusion_config=None,
|
||||
tokenizer=None,
|
||||
validate_logits_processors_params=lambda params: None,
|
||||
)
|
||||
params = SamplingParams(trace_decode_token_ids=[1, 2, 3])
|
||||
with patch.object(SamplingParams, "verify"):
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
|
||||
|
||||
def test_trace_request_rejected_when_feature_disabled():
|
||||
with pytest.raises(VLLMValidationError, match="--enable-trace-replay"):
|
||||
_validate(enable_trace_replay=False)
|
||||
|
||||
|
||||
def test_trace_request_accepted_when_feature_enabled():
|
||||
_validate(enable_trace_replay=True)
|
||||
|
||||
|
||||
def test_trace_replay_requires_v2_model_runner():
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(enable_trace_replay=True),
|
||||
use_v2_model_runner=False,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="trace replay requires Model Runner V2"):
|
||||
VllmConfig._verify_trace_replay_config(config)
|
||||
@@ -1,299 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import random
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.exceptions import ProfilerAlreadyActiveError
|
||||
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
|
||||
from vllm.v1.engine.llm_engine import LLMEngine
|
||||
from vllm.v1.metrics.reader import Counter, Gauge, Histogram, Metric, Vector
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from tests.conftest import VllmRunner
|
||||
else:
|
||||
VllmRunner = object
|
||||
|
||||
MODEL = "facebook/opt-125m"
|
||||
DTYPE = "half"
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_step_invalidates_mm_processor_cache_misses():
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.should_execute_dummy_batch = False
|
||||
engine.log_stats = False
|
||||
engine.logger_manager = None
|
||||
|
||||
mm_processor_cache = MagicMock()
|
||||
engine.renderer = MagicMock(mm_processor_cache=mm_processor_cache)
|
||||
|
||||
engine_core_output = MagicMock(
|
||||
mm_cache_miss_hashes=["missing-hash-1", "missing-hash-2"]
|
||||
)
|
||||
outputs = MagicMock(
|
||||
outputs=[engine_core_output],
|
||||
timestamp=0.0,
|
||||
scheduler_stats=None,
|
||||
)
|
||||
engine.engine_core = MagicMock()
|
||||
engine.engine_core.get_output.return_value = outputs
|
||||
|
||||
processed_outputs = MagicMock(reqs_to_abort=[], request_outputs=[])
|
||||
engine.output_processor = MagicMock()
|
||||
engine.output_processor.process_outputs.return_value = processed_outputs
|
||||
|
||||
assert engine.step() == []
|
||||
assert mm_processor_cache.invalidate.call_args_list == [
|
||||
call("missing-hash-1"),
|
||||
call("missing-hash-2"),
|
||||
]
|
||||
|
||||
|
||||
def test_duplicate_profile_start_rejected_before_engine_core_dispatch():
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.engine_core = MagicMock()
|
||||
engine._profile_session_active = False
|
||||
|
||||
engine.start_profile("first")
|
||||
|
||||
with pytest.raises(ProfilerAlreadyActiveError):
|
||||
engine.start_profile("duplicate")
|
||||
|
||||
engine.engine_core.profile.assert_called_once_with(True, "first", None, None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs",
|
||||
[
|
||||
{"profile_prefix": "../trace"},
|
||||
{"delay_iterations": -1},
|
||||
{"max_iterations": -1},
|
||||
],
|
||||
)
|
||||
def test_invalid_profile_controls_rejected_before_engine_core_dispatch(kwargs):
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.engine_core = MagicMock()
|
||||
engine._profile_session_active = False
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
engine.start_profile(**kwargs)
|
||||
|
||||
engine.engine_core.profile.assert_not_called()
|
||||
|
||||
|
||||
def _vllm_model(
|
||||
apc: bool,
|
||||
vllm_runner: type[VllmRunner],
|
||||
*,
|
||||
skip_tokenizer_init: bool = False,
|
||||
):
|
||||
"""Set up VllmRunner instance."""
|
||||
return vllm_runner(
|
||||
MODEL,
|
||||
dtype=DTYPE,
|
||||
max_model_len=128,
|
||||
enforce_eager=True,
|
||||
enable_prefix_caching=apc,
|
||||
gpu_memory_utilization=0.5,
|
||||
skip_tokenizer_init=skip_tokenizer_init,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
# Function scope decouples tests & allows
|
||||
# env var adjustment via monkeypatch
|
||||
scope="function",
|
||||
# Prefix caching
|
||||
params=[False, True],
|
||||
)
|
||||
def vllm_model(vllm_runner, request):
|
||||
"""VllmRunner test fixture parameterized by APC True/False."""
|
||||
with _vllm_model(request.param, vllm_runner) as vllm_model:
|
||||
yield vllm_model
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
# Function scope decouples tests & allows
|
||||
# env var adjustment via monkeypatch
|
||||
scope="function",
|
||||
# Prefix caching
|
||||
params=[False, True],
|
||||
)
|
||||
def vllm_model_skip_tokenizer_init(vllm_runner, request):
|
||||
"""VllmRunner test fixture with APC."""
|
||||
with _vllm_model(
|
||||
request.param,
|
||||
vllm_runner,
|
||||
skip_tokenizer_init=True,
|
||||
) as vllm_model:
|
||||
yield vllm_model
|
||||
|
||||
|
||||
def _get_test_sampling_params(
|
||||
prompt_list: list[str],
|
||||
seed: int | None = 42,
|
||||
structured_outputs: bool = False,
|
||||
) -> tuple[list[SamplingParams], list[int]]:
|
||||
"""Generate random sampling params for a batch."""
|
||||
rng = random.Random(seed)
|
||||
|
||||
def get_mostly_n_gt1() -> int:
|
||||
r"""Mostly n \in [2,20], ~1/3 n=1."""
|
||||
x = rng.randint(0, 28)
|
||||
if x < 10:
|
||||
return 1
|
||||
else:
|
||||
return x - 8
|
||||
|
||||
n_list = [get_mostly_n_gt1() for _ in range(len(prompt_list))]
|
||||
# High temperature to maximize the chance of unique completions
|
||||
return [
|
||||
SamplingParams(
|
||||
temperature=0.95,
|
||||
top_p=0.95,
|
||||
n=n,
|
||||
seed=seed,
|
||||
structured_outputs=StructuredOutputsParams(regex="[0-9]+")
|
||||
if structured_outputs
|
||||
else None,
|
||||
)
|
||||
for n in n_list
|
||||
], n_list
|
||||
|
||||
|
||||
def test_compatibility_with_skip_tokenizer_init(
|
||||
vllm_model_skip_tokenizer_init: VllmRunner,
|
||||
example_prompts: list[str],
|
||||
):
|
||||
# Case 1: Structured output request should raise an error.
|
||||
sampling_params_list, _ = _get_test_sampling_params(
|
||||
example_prompts,
|
||||
structured_outputs=True,
|
||||
)
|
||||
llm: LLM = vllm_model_skip_tokenizer_init.llm
|
||||
with pytest.raises(ValueError):
|
||||
_ = llm.generate(example_prompts, sampling_params_list)
|
||||
|
||||
|
||||
def test_parallel_sampling(vllm_model, example_prompts) -> None:
|
||||
"""Test passes if parallel sampling `n>1` yields `n` unique completions.
|
||||
|
||||
Args:
|
||||
vllm_model: VllmRunner instance under test.
|
||||
example_prompt: test fixture providing prompts for testing.
|
||||
|
||||
"""
|
||||
sampling_params_list, n_list = _get_test_sampling_params(example_prompts)
|
||||
llm: LLM = vllm_model.llm
|
||||
outputs = llm.generate(example_prompts, sampling_params_list)
|
||||
|
||||
# Validate each request response
|
||||
for out, n in zip(outputs, n_list):
|
||||
completion_counts: dict[str, int] = {}
|
||||
# Assert correct number of completions
|
||||
assert len(out.outputs) == n, f"{len(out.outputs)} completions; {n} expected."
|
||||
for idx in range(n):
|
||||
comp = out.outputs[idx]
|
||||
# Assert correct completion indices
|
||||
assert comp.index == idx, f"Index {comp.index}; expected {idx}."
|
||||
text = comp.text
|
||||
completion_counts[text] = completion_counts.get(text, 0) + 1
|
||||
# Assert unique completions
|
||||
if len(completion_counts) != n:
|
||||
repeats = {txt: num for (txt, num) in completion_counts.items() if num > 1}
|
||||
raise AssertionError(
|
||||
f"{len(completion_counts)} unique completions; expected"
|
||||
f" {n}. Repeats: {repeats}"
|
||||
)
|
||||
|
||||
|
||||
def test_engine_metrics(vllm_runner, example_prompts):
|
||||
max_tokens = 100
|
||||
# Use spec decoding to test num_accepted_tokens_per_pos
|
||||
speculative_config = {
|
||||
"method": "ngram",
|
||||
"prompt_lookup_max": 5,
|
||||
"prompt_lookup_min": 3,
|
||||
"num_speculative_tokens": 5,
|
||||
}
|
||||
|
||||
with vllm_runner(
|
||||
MODEL,
|
||||
speculative_config=speculative_config,
|
||||
disable_log_stats=False,
|
||||
) as vllm_model:
|
||||
llm: LLM = vllm_model.llm
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
|
||||
outputs = llm.generate(example_prompts, sampling_params)
|
||||
|
||||
n_prompts = len(example_prompts)
|
||||
assert len(outputs) == n_prompts
|
||||
|
||||
total_tokens = 0
|
||||
for out in outputs:
|
||||
assert len(out.outputs) == 1
|
||||
total_tokens += len(out.outputs[0].token_ids)
|
||||
assert total_tokens == max_tokens * n_prompts
|
||||
|
||||
metrics = llm.get_metrics()
|
||||
|
||||
def find_metric(name) -> list[Metric]:
|
||||
found = []
|
||||
for metric in metrics:
|
||||
if metric.name == name:
|
||||
found.append(metric)
|
||||
return found
|
||||
|
||||
num_requests_running = find_metric("vllm:num_requests_running")
|
||||
assert len(num_requests_running) == 1
|
||||
assert isinstance(num_requests_running[0], Gauge)
|
||||
assert num_requests_running[0].value == 0.0
|
||||
|
||||
generation_tokens = find_metric("vllm:generation_tokens")
|
||||
assert len(generation_tokens) == 1
|
||||
assert isinstance(generation_tokens[0], Counter)
|
||||
assert generation_tokens[0].value == total_tokens
|
||||
|
||||
request_generation_tokens = find_metric("vllm:request_generation_tokens")
|
||||
assert len(request_generation_tokens) == 1
|
||||
assert isinstance(request_generation_tokens[0], Histogram)
|
||||
assert "+Inf" in request_generation_tokens[0].buckets
|
||||
assert request_generation_tokens[0].buckets["+Inf"] == n_prompts
|
||||
assert request_generation_tokens[0].count == n_prompts
|
||||
assert request_generation_tokens[0].sum == total_tokens
|
||||
|
||||
num_accepted_tokens_per_pos = find_metric(
|
||||
"vllm:spec_decode_num_accepted_tokens_per_pos"
|
||||
)
|
||||
assert len(num_accepted_tokens_per_pos) == 1
|
||||
assert isinstance(num_accepted_tokens_per_pos[0], Vector)
|
||||
assert len(num_accepted_tokens_per_pos[0].values) == 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["meta-llama/Llama-3.2-1B-Instruct"])
|
||||
def test_skip_tokenizer_initialization(model: str):
|
||||
# This test checks if the flag skip_tokenizer_init skips the initialization
|
||||
# of tokenizer and detokenizer. The generated output is expected to contain
|
||||
# token ids.
|
||||
llm = LLM(
|
||||
model=model,
|
||||
skip_tokenizer_init=True,
|
||||
enforce_eager=True,
|
||||
)
|
||||
sampling_params = SamplingParams(prompt_logprobs=True, detokenize=True)
|
||||
|
||||
with pytest.raises(ValueError, match="`skip_tokenizer_init=True`"):
|
||||
llm.generate("abc", sampling_params)
|
||||
|
||||
outputs = llm.generate(
|
||||
{"prompt_token_ids": [1, 2, 3]}, sampling_params=sampling_params
|
||||
)
|
||||
assert len(outputs) > 0
|
||||
completions = outputs[0].outputs
|
||||
assert len(completions) > 0
|
||||
assert completions[0].text == ""
|
||||
assert completions[0].token_ids
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,99 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from copy import copy
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.outputs import CompletionOutput
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.parallel_sampling import ParentRequest
|
||||
|
||||
|
||||
def test_parent_request_to_output_stream() -> None:
|
||||
parent_request = ParentRequest(make_request(SamplingParams(n=2)))
|
||||
parent_request.child_requests = {"child_id_0", "child_id_1"}
|
||||
output_0 = CompletionOutput(
|
||||
index=0, text="child 0", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
output_1 = CompletionOutput(
|
||||
index=1, text="child 1", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
# Request not finished
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
|
||||
# output_1 finished
|
||||
output_1.finish_reason = "ended"
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
# Finished output_1 had already returned, DO NOT returned again
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
|
||||
# output_0 finished
|
||||
output_0.finish_reason = "ended"
|
||||
assert ([output_0], True) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], True)
|
||||
# Finished output_0 had already returned, DO NOT returned again
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], True)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], True)
|
||||
|
||||
|
||||
def test_parent_request_to_output_final_only() -> None:
|
||||
parent_request = ParentRequest(
|
||||
make_request(SamplingParams(n=2, output_kind=RequestOutputKind.FINAL_ONLY))
|
||||
)
|
||||
parent_request.child_requests = {"child_id_0", "child_id_1"}
|
||||
output_0 = CompletionOutput(
|
||||
index=0, text="child 0", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
output_1 = CompletionOutput(
|
||||
index=1, text="child 1", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
# Request not finished, return nothing
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], False)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
# output_1 finished, but outputs won't be returned until all child requests finished
|
||||
output_1.finish_reason = "ended"
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], False)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
# output_0 finished, as all child requests finished, the output would be returned
|
||||
output_0.finish_reason = "ended"
|
||||
assert ([output_0, output_1], True) == parent_request.get_outputs(
|
||||
"child_id_0", output_0
|
||||
)
|
||||
assert ([output_0, output_1], True) == parent_request.get_outputs(
|
||||
"child_id_1", output_1
|
||||
)
|
||||
|
||||
|
||||
def test_parallel_sampling_child_requests_preserve_session_id() -> None:
|
||||
request = make_request(SamplingParams(n=2))
|
||||
request.session_id = "session-1"
|
||||
parent_request = ParentRequest(request)
|
||||
|
||||
for idx in range(parent_request.n):
|
||||
request_id, child_params = parent_request.get_child_info(idx)
|
||||
child_request = request if idx == parent_request.n - 1 else copy(request)
|
||||
child_request.request_id = request_id
|
||||
child_request.sampling_params = child_params
|
||||
|
||||
assert child_request.session_id == "session-1"
|
||||
|
||||
|
||||
def make_request(sampling_params: SamplingParams) -> EngineCoreRequest:
|
||||
return EngineCoreRequest(
|
||||
request_id="parent_id",
|
||||
external_req_id="ext_parent_id",
|
||||
prompt_token_ids=None,
|
||||
mm_features=None,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
arrival_time=0.0,
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
)
|
||||
@@ -1,62 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch.cuda
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.core import EngineCore
|
||||
|
||||
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
|
||||
|
||||
def test_preprocess_error_handling(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Test that preprocessing errors are handled gracefully."""
|
||||
if current_platform.is_rocm() or current_platform.is_xpu():
|
||||
pytest.skip(
|
||||
"Skipped on ROCm/XPU: this test only works with 'fork', "
|
||||
"but ROCm/XPU uses 'spawn'."
|
||||
)
|
||||
|
||||
assert not torch.cuda.is_initialized(), (
|
||||
"fork needs to be used for the engine "
|
||||
"core process and this isn't possible if cuda is already initialized"
|
||||
)
|
||||
|
||||
# Store original method to call for non-failing requests
|
||||
original_preprocess = EngineCore.preprocess_add_request
|
||||
|
||||
# Monkeypatch to make preprocess_add_request raise an exception
|
||||
# only for requests with "FAIL" in the first token
|
||||
def conditional_failing_preprocess(self, request: EngineCoreRequest):
|
||||
# Fail if the first token id is 333
|
||||
if request.prompt_token_ids and request.prompt_token_ids[0] == 333:
|
||||
raise ValueError("Simulated preprocessing error!")
|
||||
return original_preprocess(self, request)
|
||||
|
||||
monkeypatch.setattr(
|
||||
EngineCore, "preprocess_add_request", conditional_failing_preprocess
|
||||
)
|
||||
|
||||
llm = LLM(model=MODEL_NAME)
|
||||
|
||||
# Create a failing request by crafting a request with an invalid token
|
||||
# We need to use a direct approach since LLM.generate tokenizes for us
|
||||
from vllm.inputs import TokensPrompt
|
||||
|
||||
# This should raise an exception due to the preprocessing failure
|
||||
# Special token id to trigger the failure
|
||||
failing_prompt = TokensPrompt(prompt_token_ids=[333])
|
||||
outputs = llm.generate(failing_prompt, SamplingParams(max_tokens=10)) # type: ignore
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0].outputs[0].token_ids) == 0
|
||||
assert outputs[0].finished
|
||||
assert outputs[0].outputs[0].finish_reason == "error"
|
||||
|
||||
# Verify the engine is still functional with a normal request
|
||||
outputs = llm.generate("Hello, my name is", SamplingParams(max_tokens=10))
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0].outputs[0].token_ids) > 0
|
||||
assert outputs[0].outputs[0].finish_reason in ("stop", "length")
|
||||
@@ -1,321 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
from contextlib import nullcontext
|
||||
from multiprocessing import connection
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import zmq
|
||||
|
||||
import vllm.platforms as platforms
|
||||
from vllm.utils import torch_utils
|
||||
from vllm.v1.engine import core as core_module
|
||||
from vllm.v1.engine import utils as engine_utils
|
||||
from vllm.v1.engine.core import EngineCoreProc, EngineShutdownState
|
||||
from vllm.v1.engine.utils import (
|
||||
CoreEngine,
|
||||
CoreEngineLaunch,
|
||||
CoreEngineProcManager,
|
||||
EngineZmqAddresses,
|
||||
wait_for_engine_startup,
|
||||
)
|
||||
from vllm.v1.executor import UniProcExecutor, multiproc_executor
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"executor_class",
|
||||
"local_engine_count",
|
||||
"initial_threads",
|
||||
"user_threads",
|
||||
"fail_start",
|
||||
"expected",
|
||||
),
|
||||
[
|
||||
(UniProcExecutor, 1, 192, None, False, (12, "12", "1")),
|
||||
(UniProcExecutor, 2, 192, None, False, (6, "6", "1")),
|
||||
(UniProcExecutor, 2, 192, None, True, (6, "6", "1")),
|
||||
(UniProcExecutor, 2, 5, None, False, (5, "5", "1")),
|
||||
(UniProcExecutor, 2, 1, None, False, (1, "1", "1")),
|
||||
(UniProcExecutor, 2, 5, "5", False, (5, "5", None)),
|
||||
(
|
||||
multiproc_executor.MultiprocExecutor,
|
||||
2,
|
||||
192,
|
||||
None,
|
||||
False,
|
||||
(192, None, None),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_engine_core_startup_threads_are_scoped_to_launch(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
executor_class,
|
||||
local_engine_count: int,
|
||||
initial_threads: int,
|
||||
user_threads: str | None,
|
||||
fail_start: bool,
|
||||
expected: tuple[int, str | None, str | None],
|
||||
):
|
||||
"""UniProc workers inherit their CPU share and restore the parent."""
|
||||
marker = torch_utils.OMP_NUM_THREADS_SET_BY_VLLM
|
||||
monkeypatch.delenv(marker, raising=False)
|
||||
monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
|
||||
if user_threads is not None:
|
||||
monkeypatch.setenv("OMP_NUM_THREADS", user_threads)
|
||||
monkeypatch.setattr(torch_utils, "available_cpu_count", lambda: 12)
|
||||
platform = SimpleNamespace(
|
||||
is_cpu=lambda: False, is_cuda_alike=lambda: True, is_xpu=lambda: False
|
||||
)
|
||||
monkeypatch.setattr(engine_utils, "current_platform", platform)
|
||||
threads = SimpleNamespace(count=initial_threads)
|
||||
setter_calls = []
|
||||
|
||||
def set_threads(count):
|
||||
setter_calls.append(count)
|
||||
threads.count = count
|
||||
|
||||
monkeypatch.setattr(torch, "get_num_threads", lambda: threads.count)
|
||||
monkeypatch.setattr(torch, "set_num_threads", set_threads)
|
||||
start_states = []
|
||||
|
||||
def thread_state():
|
||||
return (
|
||||
threads.count,
|
||||
os.environ.get("OMP_NUM_THREADS"),
|
||||
os.environ.get(marker),
|
||||
)
|
||||
|
||||
def start_process():
|
||||
start_states.append(thread_state())
|
||||
if fail_start:
|
||||
raise RuntimeError("start failed")
|
||||
|
||||
def get_context():
|
||||
assert thread_state() == (initial_threads, user_threads, None)
|
||||
return SimpleNamespace(
|
||||
Process=lambda **kwargs: SimpleNamespace(
|
||||
name=kwargs["name"],
|
||||
exitcode=1 if fail_start else None,
|
||||
start=start_process,
|
||||
)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(engine_utils, "get_mp_context", get_context)
|
||||
monkeypatch.setattr(engine_utils, "shutdown", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
engine_utils.numa_utils,
|
||||
"configure_subprocess",
|
||||
lambda *args, **kwargs: nullcontext(),
|
||||
)
|
||||
with (
|
||||
pytest.raises(RuntimeError, match="start failed")
|
||||
if fail_start
|
||||
else nullcontext()
|
||||
):
|
||||
manager = CoreEngineProcManager(
|
||||
local_engine_count=local_engine_count,
|
||||
start_index=0,
|
||||
local_start_index=0,
|
||||
vllm_config=SimpleNamespace(
|
||||
shutdown_timeout=0,
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_size=local_engine_count,
|
||||
assigned_physical_gpu_ids=None,
|
||||
use_ray=False,
|
||||
),
|
||||
),
|
||||
local_client=True,
|
||||
handshake_address="unused",
|
||||
executor_class=executor_class,
|
||||
log_stats=False,
|
||||
)
|
||||
manager._finalizer.detach()
|
||||
assert start_states == [expected] * (1 if fail_start else local_engine_count)
|
||||
assert thread_state() == (initial_threads, user_threads, None)
|
||||
assert setter_calls == (
|
||||
[expected[0], initial_threads]
|
||||
if executor_class is UniProcExecutor and expected[0] < initial_threads
|
||||
else []
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("is_rocm", "request_timeout", "manager_timeout", "process_timeout"),
|
||||
[
|
||||
(True, 0, 0, 15.0),
|
||||
(True, 0, 7, 7),
|
||||
(True, 0, None, None),
|
||||
(False, 0, 0, 0),
|
||||
(True, 7, 0, 0),
|
||||
],
|
||||
)
|
||||
def test_engine_core_process_shutdown_timeout(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
is_rocm: bool,
|
||||
request_timeout: float | None,
|
||||
manager_timeout: float | None,
|
||||
process_timeout: float | None,
|
||||
):
|
||||
manager = object.__new__(CoreEngineProcManager)
|
||||
manager._request_shutdown_timeout = request_timeout
|
||||
manager.manager_stopped = Event()
|
||||
manager.processes = [object()]
|
||||
detach_results = iter((object(), None))
|
||||
manager._finalizer = SimpleNamespace(detach=lambda: next(detach_results))
|
||||
|
||||
shutdown_calls = []
|
||||
monkeypatch.setattr(
|
||||
engine_utils,
|
||||
"current_platform",
|
||||
SimpleNamespace(is_rocm=lambda: is_rocm),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
engine_utils,
|
||||
"shutdown",
|
||||
lambda processes, timeout: shutdown_calls.append((processes, timeout)),
|
||||
)
|
||||
|
||||
manager.shutdown(timeout=manager_timeout)
|
||||
manager.shutdown(timeout=manager_timeout)
|
||||
|
||||
assert manager.manager_stopped.is_set()
|
||||
assert shutdown_calls == [(manager.processes, process_timeout)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"is_rocm",
|
||||
"shutdown_state",
|
||||
"has_work",
|
||||
"shutdown_timeout",
|
||||
"exit_code",
|
||||
"expected_calls",
|
||||
),
|
||||
[
|
||||
(
|
||||
True,
|
||||
EngineShutdownState.SHUTTING_DOWN,
|
||||
False,
|
||||
0,
|
||||
None,
|
||||
["shutdown", "freeze"],
|
||||
),
|
||||
(False, EngineShutdownState.SHUTTING_DOWN, False, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.RUNNING, False, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, True, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, False, 7, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, False, 0, 1, ["shutdown"]),
|
||||
],
|
||||
)
|
||||
def test_freeze_gc_after_clean_rocm_engine_core_shutdown(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
is_rocm: bool,
|
||||
shutdown_state: EngineShutdownState,
|
||||
has_work: bool,
|
||||
shutdown_timeout: int,
|
||||
exit_code: int | None,
|
||||
expected_calls: list[str],
|
||||
):
|
||||
calls: list[str] = []
|
||||
vllm_config = SimpleNamespace(shutdown_timeout=shutdown_timeout)
|
||||
proc = SimpleNamespace(
|
||||
shutdown_state=EngineShutdownState.RUNNING,
|
||||
has_work=lambda: has_work,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
def run_busy_loop():
|
||||
proc.shutdown_state = shutdown_state
|
||||
raise SystemExit(exit_code)
|
||||
|
||||
proc.run_busy_loop = run_busy_loop
|
||||
proc.shutdown = lambda: calls.append("shutdown")
|
||||
parallel_config = SimpleNamespace(
|
||||
data_parallel_size=1,
|
||||
numa_bind=False,
|
||||
reconfigure_for_independent_dp_rank=lambda: None,
|
||||
)
|
||||
vllm_config.parallel_config = parallel_config
|
||||
|
||||
for name in (
|
||||
"maybe_register_config_serialize_by_value",
|
||||
"set_process_title",
|
||||
"maybe_init_worker_tracer",
|
||||
"decorate_logs",
|
||||
):
|
||||
monkeypatch.setattr(core_module, name, lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(core_module, "EngineCoreProc", lambda *args, **kwargs: proc)
|
||||
monkeypatch.setattr(
|
||||
core_module,
|
||||
"SignalCallback",
|
||||
lambda callback: SimpleNamespace(trigger=lambda: None, stop=lambda: None),
|
||||
)
|
||||
monkeypatch.setattr(core_module.signal, "signal", lambda *args: None)
|
||||
monkeypatch.setattr(
|
||||
platforms, "current_platform", SimpleNamespace(is_rocm=lambda: is_rocm)
|
||||
)
|
||||
monkeypatch.setattr(core_module.gc, "freeze", lambda: calls.append("freeze"))
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
EngineCoreProc.run_engine_core(vllm_config=vllm_config)
|
||||
|
||||
assert calls == expected_calls
|
||||
|
||||
|
||||
class _FinishedProcess:
|
||||
name = "RustFrontend"
|
||||
|
||||
def __init__(self, sentinel):
|
||||
self.sentinel = sentinel
|
||||
|
||||
@property
|
||||
def exitcode(self):
|
||||
return 1
|
||||
|
||||
|
||||
def test_wait_for_engine_startup_reports_watched_process_exit():
|
||||
"""Update the startup test argument so it reaches frontend failure handling."""
|
||||
ctx = zmq.Context()
|
||||
handshake_socket = ctx.socket(zmq.ROUTER)
|
||||
recv, send = connection.Pipe(duplex=False)
|
||||
send.close()
|
||||
|
||||
parallel_config = SimpleNamespace(
|
||||
data_parallel_size_local=1,
|
||||
data_parallel_hybrid_lb=False,
|
||||
data_parallel_external_lb=False,
|
||||
)
|
||||
|
||||
try:
|
||||
launch = CoreEngineLaunch(
|
||||
engine_manager=None,
|
||||
coordinator=None,
|
||||
addresses=EngineZmqAddresses(inputs=[], outputs=[]),
|
||||
tensor_queue=None,
|
||||
)
|
||||
launch.watched_frontend_processes = [_FinishedProcess(recv)]
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
wait_for_engine_startup(
|
||||
handshake_socket,
|
||||
[CoreEngine()],
|
||||
parallel_config,
|
||||
coordinated_dp=False,
|
||||
cache_config=None,
|
||||
launch=launch,
|
||||
)
|
||||
finally:
|
||||
recv.close()
|
||||
handshake_socket.close(linger=0)
|
||||
ctx.term()
|
||||
|
||||
assert "Frontend process failed during engine core initialization" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert "Failed frontend proc(s): {'RustFrontend': 1}" in str(exc_info.value)
|
||||
@@ -1,352 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.utils import create_new_process_for_each_test, multi_gpu_test
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1 import (
|
||||
example_hidden_states_connector,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
|
||||
def get_and_check_output(output, expected_shape):
|
||||
assert output.kv_transfer_params is not None
|
||||
hidden_states_path = output.kv_transfer_params.get("hidden_states_path")
|
||||
assert hidden_states_path is not None
|
||||
|
||||
obj = example_hidden_states_connector.load_hidden_states(hidden_states_path)
|
||||
token_ids = obj["token_ids"]
|
||||
hidden_states = obj["hidden_states"]
|
||||
|
||||
prompt_token_ids = output.prompt_token_ids
|
||||
assert torch.equal(token_ids, torch.tensor(prompt_token_ids))
|
||||
|
||||
assert hidden_states.shape == expected_shape
|
||||
|
||||
# Verify hidden_states are not all zeros (i.e., they were actually computed)
|
||||
assert not torch.allclose(hidden_states, torch.zeros_like(hidden_states))
|
||||
|
||||
return token_ids, hidden_states
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def predictable_llama_config_path(tmp_path_factory):
|
||||
"""Create a minimal LlamaConfig for PredictableLlamaForCausalLM."""
|
||||
from transformers import LlamaConfig, LlamaTokenizerFast
|
||||
|
||||
config_dir = tmp_path_factory.mktemp("predictable_llama")
|
||||
|
||||
# Create a minimal Llama config with small dimensions
|
||||
config = LlamaConfig(
|
||||
vocab_size=1000,
|
||||
hidden_size=256,
|
||||
intermediate_size=512,
|
||||
num_hidden_layers=24, # Enough layers to test various layer_ids
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=4,
|
||||
max_position_embeddings=1024,
|
||||
architectures=["PredictableLlamaForCausalLM"],
|
||||
)
|
||||
|
||||
# Save config
|
||||
config.save_pretrained(config_dir)
|
||||
|
||||
# Create a simple tokenizer
|
||||
tokenizer = LlamaTokenizerFast.from_pretrained(
|
||||
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
||||
cache_dir=os.path.expanduser("~/.cache/huggingface"),
|
||||
)
|
||||
tokenizer.save_pretrained(config_dir)
|
||||
|
||||
return str(config_dir)
|
||||
|
||||
|
||||
# Need for Python 3.14 compatibility, vLLM with force spawn due to CUDA
|
||||
# reinitialization, and register will not persist.
|
||||
PREDICTABLE_LLAMA_MODEL_CLS = (
|
||||
"tests.v1.kv_connector.extract_hidden_states_integration"
|
||||
".predictable_llama:PredictableLlamaForCausalLM"
|
||||
)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_extract_hidden_states_with_predictable_dummy_model(
|
||||
predictable_llama_config_path, tmp_path, monkeypatch
|
||||
):
|
||||
"""Test hidden-state extraction with a predictable dummy model.
|
||||
|
||||
Tests 3 scenarios:
|
||||
|
||||
1. **Basic extraction**: unsorted layer selection, multiple prompts
|
||||
of varying length — verifies correct layer association and
|
||||
deterministic values.
|
||||
2. **Chunked prefill**: max_num_batched_tokens=128 with ~500-token
|
||||
prompts so each is split across multiple scheduler iterations —
|
||||
verifies hidden states are reassembled correctly.
|
||||
3. **Per-request options**: custom hidden_states_path and
|
||||
include_output_tokens — verifies per-request kv_transfer_params
|
||||
plumbing.
|
||||
"""
|
||||
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "fork")
|
||||
|
||||
layer_ids = [5, 2, 10]
|
||||
expected_layer_ids = sorted(layer_ids)
|
||||
num_layers = len(layer_ids)
|
||||
max_num_batched_tokens = 128
|
||||
|
||||
llm = LLM(
|
||||
model=predictable_llama_config_path,
|
||||
model_class_overrides={
|
||||
"PredictableLlamaForCausalLM": PREDICTABLE_LLAMA_MODEL_CLS,
|
||||
},
|
||||
speculative_config={
|
||||
"method": "extract_hidden_states",
|
||||
"num_speculative_tokens": 1,
|
||||
"draft_model_config": {
|
||||
"hf_config": {"eagle_aux_hidden_state_layer_ids": layer_ids}
|
||||
},
|
||||
},
|
||||
kv_transfer_config={
|
||||
"kv_connector": "ExampleHiddenStatesConnector",
|
||||
"kv_role": "kv_producer",
|
||||
"kv_connector_extra_config": {
|
||||
"shared_storage_path": tmp_path,
|
||||
"allow_custom_save_path": True,
|
||||
},
|
||||
},
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
enforce_eager=True,
|
||||
trust_remote_code=True,
|
||||
load_format="dummy",
|
||||
)
|
||||
|
||||
hidden_size = llm.llm_engine.model_config.get_hidden_size()
|
||||
|
||||
# --- Scenario 1: basic extraction with non-sequential layers ----------
|
||||
prompts = [
|
||||
"Short",
|
||||
"Medium length",
|
||||
"Much longer prompt with many tokens",
|
||||
"Much longer prompt with many tokens", # repeated prompt
|
||||
]
|
||||
sampling_params = SamplingParams(max_tokens=1, temperature=0.0)
|
||||
outputs = llm.generate(prompts, sampling_params)
|
||||
|
||||
assert len(outputs) == len(prompts)
|
||||
for output in outputs:
|
||||
expected_shape = (
|
||||
len(output.prompt_token_ids),
|
||||
num_layers,
|
||||
hidden_size,
|
||||
)
|
||||
_token_ids, hidden_states = get_and_check_output(output, expected_shape)
|
||||
|
||||
for idx, layer_id in enumerate(expected_layer_ids):
|
||||
layer_hidden = hidden_states[:, idx, :]
|
||||
assert torch.allclose(
|
||||
layer_hidden,
|
||||
torch.full_like(layer_hidden, layer_id),
|
||||
atol=1e-5,
|
||||
), (
|
||||
f"Layer {layer_id} at position {idx} should output "
|
||||
f"{float(layer_id)}, but got mean="
|
||||
f"{layer_hidden.mean():.3f}, min="
|
||||
f"{layer_hidden.min():.3f}, max={layer_hidden.max():.3f}"
|
||||
)
|
||||
|
||||
# --- Scenario 2: chunked prefill with long prompts --------------------
|
||||
long_prompt = " ".join(["word"] * 500)
|
||||
chunked_prompts = [
|
||||
long_prompt,
|
||||
long_prompt + " extra tokens here",
|
||||
"Short",
|
||||
]
|
||||
outputs = llm.generate(chunked_prompts, sampling_params)
|
||||
|
||||
assert len(outputs) == len(chunked_prompts)
|
||||
for output in outputs:
|
||||
prompt_len = len(output.prompt_token_ids)
|
||||
expected_shape = (prompt_len, num_layers, hidden_size)
|
||||
_token_ids, hidden_states = get_and_check_output(output, expected_shape)
|
||||
|
||||
for idx, layer_id in enumerate(expected_layer_ids):
|
||||
layer_hidden = hidden_states[:, idx, :]
|
||||
assert torch.allclose(
|
||||
layer_hidden,
|
||||
torch.full_like(layer_hidden, layer_id),
|
||||
atol=1e-5,
|
||||
), (
|
||||
f"Layer {layer_id} at position {idx} should output "
|
||||
f"{float(layer_id)}, but got mean="
|
||||
f"{layer_hidden.mean():.3f}, min="
|
||||
f"{layer_hidden.min():.3f}, max="
|
||||
f"{layer_hidden.max():.3f}. "
|
||||
f"prompt_len={prompt_len}, "
|
||||
f"max_num_batched_tokens={max_num_batched_tokens}"
|
||||
)
|
||||
|
||||
# --- Scenario 3: per-request options ----------------------------------
|
||||
max_tokens = 5
|
||||
custom_path = os.path.join(tmp_path, "subdir", "custom.safetensors")
|
||||
|
||||
sampling_params_list = [
|
||||
SamplingParams(max_tokens=max_tokens, temperature=0.0),
|
||||
SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
temperature=0.0,
|
||||
extra_args={
|
||||
"kv_transfer_params": {
|
||||
"hidden_states_path": custom_path,
|
||||
"include_output_tokens": True,
|
||||
}
|
||||
},
|
||||
),
|
||||
]
|
||||
per_req_prompts = ["Short", "Medium length"]
|
||||
outputs = llm.generate(per_req_prompts, sampling_params_list)
|
||||
|
||||
# First output: prompt-only hidden states, default path
|
||||
out0 = outputs[0]
|
||||
path0 = out0.kv_transfer_params["hidden_states_path"]
|
||||
assert path0 != custom_path
|
||||
obj0 = example_hidden_states_connector.load_hidden_states(path0)
|
||||
assert torch.equal(obj0["token_ids"], torch.tensor(out0.prompt_token_ids))
|
||||
assert obj0["hidden_states"].shape == (
|
||||
len(out0.prompt_token_ids),
|
||||
num_layers,
|
||||
hidden_size,
|
||||
)
|
||||
example_hidden_states_connector.cleanup_hidden_states(path0)
|
||||
|
||||
# Second output: prompt + output tokens, custom path
|
||||
out1 = outputs[1]
|
||||
assert out1.kv_transfer_params["hidden_states_path"] == custom_path
|
||||
obj1 = example_hidden_states_connector.load_hidden_states(custom_path)
|
||||
token_ids = obj1["token_ids"]
|
||||
hidden_states = obj1["hidden_states"]
|
||||
# The final output token was never an input to the model, so its hidden
|
||||
# state is not in the cache — hence the -1.
|
||||
total_tokens = len(out1.prompt_token_ids) + len(out1.outputs[0].token_ids) - 1
|
||||
assert token_ids.shape[0] == total_tokens
|
||||
assert hidden_states.shape == (total_tokens, num_layers, hidden_size)
|
||||
|
||||
# Verify predictable layer values hold for all tokens (prompt + output)
|
||||
for idx, layer_id in enumerate(expected_layer_ids):
|
||||
layer_hidden = hidden_states[:, idx, :]
|
||||
assert torch.allclose(
|
||||
layer_hidden,
|
||||
torch.full_like(layer_hidden, layer_id),
|
||||
atol=1e-5,
|
||||
)
|
||||
example_hidden_states_connector.cleanup_hidden_states(custom_path)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_extract_hidden_states_qwen35_hybrid_smoke(tmp_path):
|
||||
"""Smoke test for Qwen3.5 hybrid (mamba + full-attention) models.
|
||||
Uses load_format="dummy" to just check shape/plumbing.
|
||||
"""
|
||||
layer_ids = [5, 11, 17]
|
||||
hidden_size = 1024 # Qwen/Qwen3.5-0.8B hidden_size
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen3.5-0.8B",
|
||||
speculative_config={
|
||||
"method": "extract_hidden_states",
|
||||
"num_speculative_tokens": 1,
|
||||
"draft_model_config": {
|
||||
"hf_config": {"eagle_aux_hidden_state_layer_ids": layer_ids}
|
||||
},
|
||||
},
|
||||
kv_transfer_config={
|
||||
"kv_connector": "ExampleHiddenStatesConnector",
|
||||
"kv_role": "kv_producer",
|
||||
"kv_connector_extra_config": {"shared_storage_path": str(tmp_path)},
|
||||
},
|
||||
max_model_len=256,
|
||||
enforce_eager=True,
|
||||
gpu_memory_utilization=0.4,
|
||||
load_format="dummy",
|
||||
)
|
||||
|
||||
prompts = ["Hello world", "Test prompt with several tokens"]
|
||||
sampling_params = SamplingParams(max_tokens=1, temperature=0.0)
|
||||
outputs = llm.generate(prompts, sampling_params)
|
||||
|
||||
assert len(outputs) == len(prompts)
|
||||
for output in outputs:
|
||||
assert output.kv_transfer_params is not None
|
||||
hidden_states_path = output.kv_transfer_params.get("hidden_states_path")
|
||||
assert hidden_states_path is not None
|
||||
|
||||
obj = example_hidden_states_connector.load_hidden_states(hidden_states_path)
|
||||
token_ids = obj["token_ids"]
|
||||
hidden_states = obj["hidden_states"]
|
||||
|
||||
assert torch.equal(token_ids, torch.tensor(output.prompt_token_ids))
|
||||
assert hidden_states.shape == (
|
||||
len(output.prompt_token_ids),
|
||||
len(layer_ids),
|
||||
hidden_size,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.timeout(
|
||||
240 if current_platform.is_rocm() or current_platform.is_xpu() else 120
|
||||
)
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
@create_new_process_for_each_test()
|
||||
def test_extract_hidden_states_tp2():
|
||||
"""Test that hidden states extraction works with tensor_parallel_size=2."""
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
layer_ids = [5, 11, 17]
|
||||
hidden_size = 1024 # Qwen/Qwen3-0.6B hidden_size
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen3-0.6B",
|
||||
tensor_parallel_size=2,
|
||||
speculative_config={
|
||||
"method": "extract_hidden_states",
|
||||
"num_speculative_tokens": 1,
|
||||
"draft_model_config": {
|
||||
"hf_config": {"eagle_aux_hidden_state_layer_ids": layer_ids}
|
||||
},
|
||||
},
|
||||
kv_transfer_config={
|
||||
"kv_connector": "ExampleHiddenStatesConnector",
|
||||
"kv_role": "kv_producer",
|
||||
"kv_connector_extra_config": {"shared_storage_path": tmp_dir},
|
||||
},
|
||||
max_model_len=256,
|
||||
enforce_eager=True,
|
||||
gpu_memory_utilization=0.4,
|
||||
load_format="dummy",
|
||||
)
|
||||
|
||||
prompts = ["Hello world", "Test prompt with several tokens"]
|
||||
sampling_params = SamplingParams(max_tokens=1, temperature=0.0)
|
||||
outputs = llm.generate(prompts, sampling_params)
|
||||
|
||||
assert len(outputs) == len(prompts)
|
||||
for output in outputs:
|
||||
assert output.kv_transfer_params is not None
|
||||
hidden_states_path = output.kv_transfer_params.get("hidden_states_path")
|
||||
assert hidden_states_path is not None
|
||||
|
||||
obj = example_hidden_states_connector.load_hidden_states(hidden_states_path)
|
||||
token_ids = obj["token_ids"]
|
||||
hidden_states = obj["hidden_states"]
|
||||
|
||||
assert torch.equal(token_ids, torch.tensor(output.prompt_token_ids))
|
||||
assert hidden_states.shape == (
|
||||
len(output.prompt_token_ids),
|
||||
len(layer_ids),
|
||||
hidden_size,
|
||||
)
|
||||
@@ -1,29 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Mooncake P/D accuracy with same-host HIP transport on ROCm."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import spawn_new_process_for_each_test
|
||||
from tests.v1.kv_connector.rocm_pd_accuracy_utils import (
|
||||
QWEN_MODEL,
|
||||
run_rocm_pd_accuracy,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm P/D equivalents"),
|
||||
pytest.mark.distributed(num_gpus=4),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model,prefill_tp,decode_tp",
|
||||
[
|
||||
pytest.param(QWEN_MODEL, 1, 1, id="mooncake-hip-qwen-p1-d1"),
|
||||
pytest.param(QWEN_MODEL, 2, 2, id="mooncake-hip-qwen-p2-d2"),
|
||||
],
|
||||
)
|
||||
@spawn_new_process_for_each_test
|
||||
def test_rocm_pd_accuracy(model, prefill_tp, decode_tp, monkeypatch):
|
||||
run_rocm_pd_accuracy("mooncake", model, prefill_tp, decode_tp, monkeypatch)
|
||||
@@ -1,736 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Single-node MoRIIO WRITE P/D checks on dummy weights.
|
||||
|
||||
Each case serves a real model architecture with ``--load-format dummy``, widened
|
||||
by ``moriio_wide_dummy`` (see ``DUMMY_WEIGHT_RANGE``): the
|
||||
config keeps the real hidden size, head geometry, MLA ranks and recurrent-state
|
||||
shapes, so the connector registers and transfers exactly the production cache
|
||||
layout, but the layer stack is cut to a few layers that still contain every
|
||||
cache-group kind and the MoE is cut to a handful of experts. Dummy weights are
|
||||
seeded, so the prefill, decode and reference servers hold identical weights.
|
||||
Cases marked ``HMA_off`` run every server with
|
||||
``--disable-hybrid-kv-cache-manager``, so all layers, sliding-window ones
|
||||
included, share a single cache group.
|
||||
|
||||
Prefill runs on one GPU, decode on another, and MoRI moves the KV over xGMI.
|
||||
Either way decode computes the last prompt token itself. For hybrid models
|
||||
prefill computes only the first ``n - 1`` tokens and transfers the KV and the
|
||||
recurrent state after them. For attention-only models prefill computes and
|
||||
transfers all ``n``, and decode's scheduler, seeing the whole prompt cached,
|
||||
recomputes the last token. A direct serve splits the same prompt the same way
|
||||
when the first ``n - 1`` tokens end on a chunk boundary that both servers share,
|
||||
so the prompts are chosen to make that happen: one is a single chunk plus one
|
||||
token, the others are a whole number of hybrid cache blocks plus one token
|
||||
(prefix caching ends chunks on block boundaries) or, for attention-only models,
|
||||
a whole number of chunks plus one token. With the split matched, a correct
|
||||
transfer reproduces the direct serve's first-token log-probabilities exactly,
|
||||
so the comparison needs no noise allowance. The
|
||||
servers compile with Inductor's deterministic mode, since otherwise each one
|
||||
benchmarks its own reduction launch configs and separately started servers
|
||||
can drift apart by a few bf16 logit steps. Guards:
|
||||
|
||||
* decode must report an external prefix-cache hit for every transferred token
|
||||
of every prompt, so the match is not a local recompute;
|
||||
* changing the first half of a prompt must move the direct serve's log-probs by
|
||||
at least ``MIN_CONTEXT_EFFECT``, so a wrong prefix would be visible;
|
||||
* ``test_corrupted_prefill_state_is_detected`` makes prefill compute its KV with
|
||||
a different norm epsilon (same shapes, different values) and requires every
|
||||
prompt to fail the comparison.
|
||||
"""
|
||||
|
||||
import atexit
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from collections.abc import Callable, Iterator
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
|
||||
_ROOT = Path(__file__).resolve().parents[4]
|
||||
_PROXY = (
|
||||
_ROOT / "examples/disaggregated/disaggregated_serving/moriio_toy_proxy_server.py"
|
||||
)
|
||||
|
||||
# Max allowed difference between centered first-token log-probabilities of the
|
||||
# P/D and direct outputs, over the direct serve's top-k tokens. The split is
|
||||
# matched, so correct transfers produce identical logits; this only absorbs the
|
||||
# fp32 rounding of the log-softmax (~1e-7), far below one bf16 logit step.
|
||||
TOLERANCE = float(os.getenv("MORIIO_DUMMY_E2E_TOL", "1e-5"))
|
||||
# Several bf16 steps of the logits at DUMMY_WEIGHT_RANGE.
|
||||
MIN_CONTEXT_EFFECT = 0.05
|
||||
# Half-width of the uniform dummy init for 16/32-bit float weights, applied in
|
||||
# every server worker by moriio_wide_dummy.py. The loader default (1e-3) shrinks
|
||||
# every activation so far that a context change moves the first-token log-probs
|
||||
# by ~1e-4; at 0.1 it moves them by >0.1 and a corrupted prefill changes the
|
||||
# top-k set entirely.
|
||||
DUMMY_WEIGHT_RANGE = 0.1
|
||||
_WIDE_DUMMY_DIR = Path(__file__).resolve().parent
|
||||
TOP_K = 20
|
||||
MAX_TOKENS = 4
|
||||
MAX_MODEL_LEN = 4096
|
||||
|
||||
# Prefill token budget of every server. Prompts longer than it are chunked, so
|
||||
# the final-chunk save path runs; the short prompt fills exactly one chunk.
|
||||
PREFILL_CHUNK = 299
|
||||
SHORT_PROMPT_LEN = PREFILL_CHUNK + 1
|
||||
# Hybrid blocks per aligned prompt, before the trailing token.
|
||||
ALIGNED_BLOCKS = (1, 2)
|
||||
# Prefill chunks per long attention-only prompt, before the trailing token.
|
||||
ALIGNED_CHUNKS = (2, 4)
|
||||
|
||||
|
||||
def _mori_available() -> bool:
|
||||
try:
|
||||
import mori.io # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(
|
||||
not current_platform.is_rocm() or not _mori_available(),
|
||||
reason="MoRIIO P/D needs ROCm and MoRI",
|
||||
),
|
||||
pytest.mark.skipif(
|
||||
current_platform.is_rocm() and current_platform.device_count() < 2,
|
||||
reason="needs one GPU for prefill and one for decode",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Model architectures
|
||||
|
||||
|
||||
def _kimi_linear_overrides(cfg) -> dict[str, Any]:
|
||||
# 3 KDA layers then 1 MLA layer; layer 0 stays dense (first_k_dense_replace).
|
||||
linear = dict(cfg.linear_attn_config)
|
||||
linear["kda_layers"] = [1, 2, 3]
|
||||
linear["full_attn_layers"] = [4]
|
||||
groups = max(1, cfg.num_expert_group)
|
||||
return {
|
||||
"num_hidden_layers": 4,
|
||||
"linear_attn_config": linear,
|
||||
"num_experts": 2 * groups,
|
||||
"num_experts_per_token": 2,
|
||||
"topk_group": min(cfg.topk_group, groups),
|
||||
}
|
||||
|
||||
|
||||
def _qwen3_5_moe_overrides(cfg) -> dict[str, Any]:
|
||||
# 3 Gated DeltaNet layers then 1 full-attention layer.
|
||||
return {
|
||||
"text_config": {
|
||||
"num_hidden_layers": 4,
|
||||
"layer_types": ["linear_attention"] * 3 + ["full_attention"],
|
||||
"num_experts": 4,
|
||||
"num_experts_per_tok": 2,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _qwen3_dense_overrides(cfg) -> dict[str, Any]:
|
||||
# Attention-only: decode gets the KV for the whole prompt.
|
||||
return {"num_hidden_layers": 4}
|
||||
|
||||
|
||||
def _deepseek_v3_overrides(cfg) -> dict[str, Any]:
|
||||
# MLA attention-only: layer 0 dense, layer 1 MoE, no MTP layer.
|
||||
return {
|
||||
"num_hidden_layers": 2,
|
||||
"first_k_dense_replace": 1,
|
||||
"n_routed_experts": 8,
|
||||
"num_experts_per_tok": 2,
|
||||
"n_group": 1,
|
||||
"topk_group": 1,
|
||||
"num_nextn_predict_layers": 0,
|
||||
}
|
||||
|
||||
|
||||
def _gemma3_overrides(cfg) -> dict[str, Any]:
|
||||
# Five sliding-window layers then one global layer, as in the real
|
||||
# 5:1 pattern. Without the hybrid KV cache manager vLLM gives the sliding
|
||||
# layers full-attention cache specs, so all six share one group.
|
||||
return {
|
||||
"num_hidden_layers": 6,
|
||||
"layer_types": ["sliding_attention"] * 5 + ["full_attention"],
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArchCase:
|
||||
model: str
|
||||
overrides: Callable[[Any], dict[str, Any]]
|
||||
# Norm-epsilon override that perturbs every computed KV/state value
|
||||
# without changing a single shape. Used by the corruption control.
|
||||
corrupt_overrides: dict[str, Any]
|
||||
env: dict[str, str] = field(default_factory=dict)
|
||||
args: tuple[str, ...] = ()
|
||||
# Has recurrent-state (mamba-style) layers, so prefill stops at n - 1.
|
||||
hybrid: bool = True
|
||||
|
||||
|
||||
ARCHS: dict[str, ArchCase] = {
|
||||
"kimi_linear": ArchCase(
|
||||
model="moonshotai/Kimi-Linear-48B-A3B-Instruct",
|
||||
overrides=_kimi_linear_overrides,
|
||||
corrupt_overrides={"rms_norm_eps": 1.0},
|
||||
env={"VLLM_ROCM_USE_AITER": "1"},
|
||||
args=("--trust-remote-code", "--mamba-ssm-cache-dtype", "float32"),
|
||||
),
|
||||
"qwen3_5_moe": ArchCase(
|
||||
model="Qwen/Qwen3.5-35B-A3B",
|
||||
overrides=_qwen3_5_moe_overrides,
|
||||
corrupt_overrides={"text_config": {"rms_norm_eps": 1.0}},
|
||||
# AITER's GDN conv-update kernel rejects the DS conv-state layout that
|
||||
# MoRIIO's recurrent-state transfer requires.
|
||||
env={"VLLM_ROCM_USE_AITER": "0"},
|
||||
args=("--language-model-only",),
|
||||
),
|
||||
"qwen3_dense": ArchCase(
|
||||
model="Qwen/Qwen3-32B",
|
||||
overrides=_qwen3_dense_overrides,
|
||||
corrupt_overrides={"rms_norm_eps": 1.0},
|
||||
env={"VLLM_ROCM_USE_AITER": "0"},
|
||||
hybrid=False,
|
||||
),
|
||||
"deepseek_v3": ArchCase(
|
||||
model="deepseek-ai/DeepSeek-V3",
|
||||
overrides=_deepseek_v3_overrides,
|
||||
corrupt_overrides={"rms_norm_eps": 1.0},
|
||||
env={"VLLM_ROCM_USE_AITER": "1"},
|
||||
hybrid=False,
|
||||
),
|
||||
# Text-only Gemma 3. The multimodal Gemma3ForConditionalGeneration takes
|
||||
# the inputs_embeds path on KV consumers (enable_mm_embeds is forced on
|
||||
# there) and computes differently from a direct serve without any transfer.
|
||||
"gemma3": ArchCase(
|
||||
model="google/gemma-3-1b-it",
|
||||
overrides=_gemma3_overrides,
|
||||
corrupt_overrides={"rms_norm_eps": 1.0},
|
||||
env={"VLLM_ROCM_USE_AITER": "0"},
|
||||
hybrid=False,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _arch_overrides(arch: ArchCase) -> dict[str, Any]:
|
||||
from vllm.transformers_utils.config import get_config
|
||||
|
||||
return arch.overrides(get_config(arch.model, trust_remote_code=True))
|
||||
|
||||
|
||||
def _merge(base: dict[str, Any], extra: dict[str, Any]) -> dict[str, Any]:
|
||||
merged = dict(base)
|
||||
for key, value in extra.items():
|
||||
if isinstance(value, dict) and isinstance(merged.get(key), dict):
|
||||
merged[key] = _merge(merged[key], value)
|
||||
else:
|
||||
merged[key] = value
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Serving
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Case:
|
||||
arch: str
|
||||
attention_backend: str
|
||||
prefill_graph: str
|
||||
decode_graph: str
|
||||
# Run every server of the case without the hybrid KV cache manager.
|
||||
hma_off: bool = False
|
||||
|
||||
@property
|
||||
def extra_args(self) -> tuple[str, ...]:
|
||||
return ("--disable-hybrid-kv-cache-manager",) if self.hma_off else ()
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
return (
|
||||
f"{self.arch}-{self.attention_backend}-"
|
||||
f"P_{self.prefill_graph}-D_{self.decode_graph}"
|
||||
+ ("-HMA_off" if self.hma_off else "")
|
||||
)
|
||||
|
||||
|
||||
_DEFAULT = "FULL_AND_PIECEWISE"
|
||||
CASES = [
|
||||
# Kimi-Linear: KDA + MLA groups.
|
||||
Case("kimi_linear", "ROCM_AITER_MLA", _DEFAULT, _DEFAULT),
|
||||
Case("kimi_linear", "ROCM_AITER_MLA", "NONE", "NONE"),
|
||||
Case("kimi_linear", "ROCM_AITER_MLA", "PIECEWISE", "PIECEWISE"),
|
||||
Case("kimi_linear", "ROCM_AITER_MLA", _DEFAULT, "FULL_DECODE_ONLY"),
|
||||
Case("kimi_linear", "TRITON_MLA", _DEFAULT, _DEFAULT),
|
||||
# Qwen3.5: Gated DeltaNet + full-attention groups.
|
||||
Case("qwen3_5_moe", "TRITON_ATTN", _DEFAULT, _DEFAULT),
|
||||
Case("qwen3_5_moe", "TRITON_ATTN", "NONE", "NONE"),
|
||||
Case("qwen3_5_moe", "TRITON_ATTN", "PIECEWISE", "PIECEWISE"),
|
||||
Case("qwen3_5_moe", "TRITON_ATTN", _DEFAULT, "FULL_DECODE_ONLY"),
|
||||
# ROCM_ATTN keeps a (2, num_blocks, ...) KV layout and opts out of KV
|
||||
# connectors, so the second ROCm attention backend is the unified one.
|
||||
Case("qwen3_5_moe", "ROCM_AITER_UNIFIED_ATTN", _DEFAULT, _DEFAULT),
|
||||
# Attention-only: prefill transfers the whole prompt.
|
||||
Case("qwen3_dense", "TRITON_ATTN", _DEFAULT, _DEFAULT),
|
||||
Case("qwen3_dense", "ROCM_AITER_UNIFIED_ATTN", _DEFAULT, _DEFAULT),
|
||||
# Without the hybrid KV cache manager: one cache group per model.
|
||||
Case("qwen3_dense", "TRITON_ATTN", _DEFAULT, _DEFAULT, hma_off=True),
|
||||
Case("deepseek_v3", "ROCM_AITER_MLA", _DEFAULT, _DEFAULT, hma_off=True),
|
||||
Case("gemma3", "TRITON_ATTN", _DEFAULT, _DEFAULT, hma_off=True),
|
||||
]
|
||||
|
||||
|
||||
def _graph_args(mode: str) -> list[str]:
|
||||
if mode == "NONE":
|
||||
return ["--enforce-eager"]
|
||||
# Inductor otherwise picks reduction launch configs by timing them, so each
|
||||
# separately compiled server may sum in a different order and drift by a
|
||||
# few bf16 logit steps; deterministic mode fixes the choice.
|
||||
config = {
|
||||
"cudagraph_mode": mode,
|
||||
"inductor_compile_config": {"deterministic": True},
|
||||
}
|
||||
return ["--compilation-config", json.dumps(config)]
|
||||
|
||||
|
||||
def _visible_devices() -> tuple[str, list[str]]:
|
||||
selectors = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
|
||||
selector = next((k for k in selectors if k in os.environ), selectors[0])
|
||||
visible = os.getenv(selector)
|
||||
devices = (
|
||||
visible.split(",")
|
||||
if visible
|
||||
else [str(i) for i in range(current_platform.device_count())]
|
||||
)
|
||||
return selector, devices
|
||||
|
||||
|
||||
def _device_env(selector: str, device: str) -> dict[str, str]:
|
||||
# vLLM mirrors HIP_VISIBLE_DEVICES into CUDA_VISIBLE_DEVICES at import, so
|
||||
# the test process carries both; pin every selector or the server refuses
|
||||
# the mismatch. ROCR narrows the set first, so HIP/CUDA then index into it.
|
||||
env = {selector: device}
|
||||
for key in ("HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
|
||||
if key != selector:
|
||||
env[key] = "0" if selector == "ROCR_VISIBLE_DEVICES" else device
|
||||
return env
|
||||
|
||||
|
||||
# KV consumers force enable_mm_embeds on, which moves multimodal-capable models
|
||||
# (Qwen3.5) from input_ids to inputs_embeds, but the AOT compile-cache key does
|
||||
# not cover it, so a consumer can load a producer's graph and crash in
|
||||
# profile_run. Keep each role's compile cache apart until
|
||||
# vllm-project/vllm#54642 lands (vllm-project/vllm#50891).
|
||||
_CACHE_ROOT = Path(tempfile.mkdtemp(prefix="moriio_dummy_e2e_cache_"))
|
||||
atexit.register(shutil.rmtree, _CACHE_ROOT, ignore_errors=True)
|
||||
|
||||
|
||||
def _server(
|
||||
arch: ArchCase,
|
||||
overrides: dict[str, Any],
|
||||
backend: str,
|
||||
graph: str,
|
||||
device: str,
|
||||
selector: str,
|
||||
*,
|
||||
port: int | None = None,
|
||||
extra_args: tuple[str, ...] = (),
|
||||
kv_transfer_config: dict[str, Any] | None = None,
|
||||
) -> RemoteOpenAIServer:
|
||||
port = port or get_open_port()
|
||||
args = [
|
||||
*arch.args,
|
||||
*extra_args,
|
||||
"--port",
|
||||
str(port),
|
||||
"--load-format",
|
||||
"dummy",
|
||||
"--worker-extension-cls",
|
||||
"moriio_wide_dummy.WideDummyWeights",
|
||||
"--hf-overrides",
|
||||
json.dumps(overrides),
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--attention-backend",
|
||||
backend,
|
||||
"--max-model-len",
|
||||
str(MAX_MODEL_LEN),
|
||||
"--max-num-batched-tokens",
|
||||
str(PREFILL_CHUNK),
|
||||
"--max-num-seqs",
|
||||
"16",
|
||||
"--kv-cache-memory-bytes",
|
||||
str(2 * 1024**3),
|
||||
"--gpu-memory-utilization",
|
||||
"0.5",
|
||||
"--enable-prefix-caching",
|
||||
*_graph_args(graph),
|
||||
]
|
||||
role = "direct"
|
||||
if kv_transfer_config is not None:
|
||||
args += ["--kv-transfer-config", json.dumps(kv_transfer_config)]
|
||||
role = kv_transfer_config["kv_role"]
|
||||
env = {
|
||||
"PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"],
|
||||
**_device_env(selector, device),
|
||||
"VLLM_HOST_IP": "127.0.0.1",
|
||||
"VLLM_PORT": str(get_open_port()),
|
||||
"VLLM_WORKER_MULTIPROC_METHOD": "spawn",
|
||||
"VLLM_SSM_CONV_STATE_LAYOUT": "DS",
|
||||
"VLLM_CACHE_ROOT": str(_CACHE_ROOT / role),
|
||||
# Only this directory, so the source tree cannot shadow installed vllm.
|
||||
"PYTHONPATH": os.pathsep.join(
|
||||
filter(None, [str(_WIDE_DUMMY_DIR), os.environ.get("PYTHONPATH")])
|
||||
),
|
||||
"MORIIO_DUMMY_WEIGHT_RANGE": str(DUMMY_WEIGHT_RANGE),
|
||||
**arch.env,
|
||||
}
|
||||
return RemoteOpenAIServer(
|
||||
arch.model, args, env_dict=env, auto_port=False, max_wait_seconds=900
|
||||
)
|
||||
|
||||
|
||||
def _moriio_config(role: str, http_port: int, ping_port: int) -> dict[str, Any]:
|
||||
return {
|
||||
"kv_connector": "MoRIIOConnector",
|
||||
"kv_role": role,
|
||||
"kv_connector_extra_config": {
|
||||
"backend": "xgmi",
|
||||
"read_mode": False,
|
||||
"host_ip": "127.0.0.1",
|
||||
"proxy_ip": "127.0.0.1",
|
||||
"proxy_ping_port": str(ping_port),
|
||||
"http_port": str(http_port),
|
||||
"handshake_port": str(get_open_port()),
|
||||
"notify_port": str(get_open_port()),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _proxy(ping_port: int) -> Iterator[str]:
|
||||
# Free ports for both sockets, so cases from parallel shards on one host
|
||||
# do not collide.
|
||||
port = get_open_port()
|
||||
process = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(_PROXY),
|
||||
"--port",
|
||||
str(port),
|
||||
"--service-discovery-port",
|
||||
str(ping_port),
|
||||
],
|
||||
start_new_session=True,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, "MoRIIO proxy exited during startup"
|
||||
try:
|
||||
requests.get(f"http://127.0.0.1:{port}/", timeout=1)
|
||||
break
|
||||
except requests.ConnectionError:
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError("MoRIIO proxy did not start")
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _pd_pair(
|
||||
arch: ArchCase,
|
||||
prefill_overrides: dict[str, Any],
|
||||
decode_overrides: dict[str, Any],
|
||||
case: Case,
|
||||
) -> Iterator[tuple[str, RemoteOpenAIServer]]:
|
||||
selector, devices = _visible_devices()
|
||||
assert len(devices) >= 2, "needs one GPU for prefill and one for decode"
|
||||
prefill_port, decode_port, ping_port = (get_open_port() for _ in range(3))
|
||||
with _proxy(ping_port) as proxy_url, contextlib.ExitStack() as stack:
|
||||
servers: list[RemoteOpenAIServer] = []
|
||||
stack.callback(RemoteOpenAIServer.shutdown_many, servers)
|
||||
with ThreadPoolExecutor(2) as pool:
|
||||
futures = [
|
||||
pool.submit(
|
||||
_server,
|
||||
arch,
|
||||
prefill_overrides,
|
||||
case.attention_backend,
|
||||
case.prefill_graph,
|
||||
devices[0],
|
||||
selector,
|
||||
port=prefill_port,
|
||||
extra_args=case.extra_args,
|
||||
kv_transfer_config=_moriio_config(
|
||||
"kv_producer", prefill_port, ping_port
|
||||
),
|
||||
),
|
||||
pool.submit(
|
||||
_server,
|
||||
arch,
|
||||
decode_overrides,
|
||||
case.attention_backend,
|
||||
case.decode_graph,
|
||||
devices[1],
|
||||
selector,
|
||||
port=decode_port,
|
||||
extra_args=case.extra_args,
|
||||
kv_transfer_config=_moriio_config(
|
||||
"kv_consumer", decode_port, ping_port
|
||||
),
|
||||
),
|
||||
]
|
||||
for future in futures:
|
||||
servers.append(future.result())
|
||||
_wait_for_registration(proxy_url, arch.model)
|
||||
yield proxy_url, servers[1]
|
||||
|
||||
|
||||
def _wait_for_registration(proxy_url: str, model: str) -> None:
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline:
|
||||
# The proxy hands decode max_tokens - 1 (prefill emits the first
|
||||
# token), so the probe needs at least 2 for decode to accept it.
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{proxy_url}/v1/completions",
|
||||
json={"model": model, "prompt": [1000, 1001], "max_tokens": 2},
|
||||
timeout=300,
|
||||
)
|
||||
# The proxy streams the decode body, so a decode-side error can
|
||||
# surface as a truncated response rather than a status code.
|
||||
if response.status_code == 200 and response.json()["choices"]:
|
||||
return
|
||||
except requests.RequestException:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise TimeoutError("prefill/decode never registered with the MoRIIO proxy")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Measurement
|
||||
|
||||
|
||||
def _metric(server: RemoteOpenAIServer, name: str) -> list[Any]:
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
response = requests.get(server.url_for("metrics"), timeout=10)
|
||||
response.raise_for_status()
|
||||
return [
|
||||
sample
|
||||
for family in text_string_to_metric_families(response.text)
|
||||
for sample in family.samples
|
||||
if sample.name == name
|
||||
]
|
||||
|
||||
|
||||
def _block_size(server: RemoteOpenAIServer) -> int:
|
||||
# Hybrid models pad the attention block to the recurrent-state page, so the
|
||||
# effective size is only known once the server has started.
|
||||
sizes = {
|
||||
int(sample.labels["block_size"])
|
||||
for sample in _metric(server, "vllm:cache_config_info")
|
||||
}
|
||||
assert len(sizes) == 1, f"expected one cache block size, got {sizes}"
|
||||
return sizes.pop()
|
||||
|
||||
|
||||
def _prompt_lengths(arch: ArchCase, server: RemoteOpenAIServer) -> list[int]:
|
||||
# Hybrid chunks end on cache-block boundaries; attention-only chunks end on
|
||||
# the prefill budget, so the last token is computed on its own either way.
|
||||
if arch.hybrid:
|
||||
unit, counts = _block_size(server), ALIGNED_BLOCKS
|
||||
else:
|
||||
unit, counts = PREFILL_CHUNK, ALIGNED_CHUNKS
|
||||
aligned = [
|
||||
k * unit + 1 for k in counts if k * unit + 1 + MAX_TOKENS <= MAX_MODEL_LEN
|
||||
]
|
||||
assert aligned, f"alignment unit {unit} leaves no aligned prompt"
|
||||
return [SHORT_PROMPT_LEN, *aligned]
|
||||
|
||||
|
||||
def _prompts(lengths: list[int]) -> list[list[int]]:
|
||||
rng = random.Random(0)
|
||||
return [[rng.randrange(1000, 30000) for _ in range(n)] for n in lengths]
|
||||
|
||||
|
||||
def _first_step(url: str, model: str, prompt: list[int]) -> dict[str, float]:
|
||||
response = requests.post(
|
||||
f"{url}/v1/completions",
|
||||
json={
|
||||
"model": model,
|
||||
"prompt": prompt,
|
||||
"max_tokens": MAX_TOKENS,
|
||||
"temperature": 0,
|
||||
"logprobs": TOP_K,
|
||||
"return_tokens_as_token_ids": True,
|
||||
},
|
||||
timeout=600,
|
||||
)
|
||||
response.raise_for_status()
|
||||
top = response.json()["choices"][0]["logprobs"]["top_logprobs"]
|
||||
assert top, "server returned no logprobs"
|
||||
return top[0]
|
||||
|
||||
|
||||
def _distance(ref: dict[str, float], got: dict[str, float]) -> float:
|
||||
"""Max difference of centered log-probs over the shared top-k tokens.
|
||||
|
||||
Centering removes the log-sum-exp offset, leaving the logit differences the
|
||||
KV actually determines.
|
||||
"""
|
||||
common = sorted(ref.keys() & got.keys())
|
||||
if len(common) < len(ref) // 2:
|
||||
return float("inf")
|
||||
ref_mean = sum(ref[t] for t in common) / len(common)
|
||||
got_mean = sum(got[t] for t in common) / len(common)
|
||||
return max(abs((ref[t] - ref_mean) - (got[t] - got_mean)) for t in common)
|
||||
|
||||
|
||||
def _external_hits(server: RemoteOpenAIServer) -> float:
|
||||
samples = _metric(server, "vllm:external_prefix_cache_hits_total")
|
||||
return sum(sample.value for sample in samples)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Reference:
|
||||
prompts: list[list[int]]
|
||||
logprobs: list[dict[str, float]]
|
||||
hybrid: bool
|
||||
|
||||
@property
|
||||
def expected_external_hits(self) -> int:
|
||||
# Hybrid prefill stops one token short; attention-only prefill hands
|
||||
# decode the whole prompt.
|
||||
return sum(len(p) - int(self.hybrid) for p in self.prompts)
|
||||
|
||||
|
||||
def _reference(arch: ArchCase, overrides: dict[str, Any], case: Case) -> Reference:
|
||||
"""Direct serve; also checks that the comparison can see a wrong prefix."""
|
||||
selector, devices = _visible_devices()
|
||||
# Prefill graphs run the chunks and the decode-only last step runs the same
|
||||
# captured graph in every decode mode used here, so the prefill mode
|
||||
# reproduces both halves of the P/D computation.
|
||||
with _server(
|
||||
arch,
|
||||
overrides,
|
||||
case.attention_backend,
|
||||
case.prefill_graph,
|
||||
devices[0],
|
||||
selector,
|
||||
extra_args=case.extra_args,
|
||||
) as server:
|
||||
url = server.url_root
|
||||
lengths = _prompt_lengths(arch, server)
|
||||
prompts = _prompts(lengths)
|
||||
refs = [_first_step(url, arch.model, p) for p in prompts]
|
||||
# Same tail, different early context: the comparison has to see it.
|
||||
for prompt, ref in zip(prompts, refs):
|
||||
altered = [t + 1 for t in prompt[: len(prompt) // 2]]
|
||||
altered += prompt[len(prompt) // 2 :]
|
||||
moved = _distance(ref, _first_step(url, arch.model, altered))
|
||||
print(f"[sensitivity] len={len(prompt)} context-change distance={moved}")
|
||||
assert moved >= MIN_CONTEXT_EFFECT, (
|
||||
f"first-token log-probs barely depend on the context (moved "
|
||||
f"{moved:.4g} for len {len(prompt)}); a wrong prefix would go "
|
||||
"unnoticed"
|
||||
)
|
||||
# Determinism of the reference itself (served from its prefix cache).
|
||||
again = _first_step(url, arch.model, prompts[-1])
|
||||
print(f"[noise] repeat distance={_distance(refs[-1], again)}")
|
||||
return Reference(prompts, refs, arch.hybrid)
|
||||
|
||||
|
||||
def _pd_distances(
|
||||
arch: ArchCase,
|
||||
prefill_overrides: dict[str, Any],
|
||||
decode_overrides: dict[str, Any],
|
||||
case: Case,
|
||||
ref: Reference,
|
||||
) -> tuple[list[float], float]:
|
||||
with _pd_pair(arch, prefill_overrides, decode_overrides, case) as (
|
||||
proxy_url,
|
||||
decode,
|
||||
):
|
||||
hits_before = _external_hits(decode)
|
||||
distances = [
|
||||
_distance(expected, _first_step(proxy_url, arch.model, prompt))
|
||||
for prompt, expected in zip(ref.prompts, ref.logprobs)
|
||||
]
|
||||
hits = _external_hits(decode) - hits_before
|
||||
lengths = [len(p) for p in ref.prompts]
|
||||
print(f"[pd] {case.id} lens={lengths} distances={distances} external_hits={hits}")
|
||||
return distances, hits
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", CASES, ids=lambda c: c.id)
|
||||
def test_write_matches_direct_serve(case: Case):
|
||||
arch = ARCHS[case.arch]
|
||||
overrides = _arch_overrides(arch)
|
||||
ref = _reference(arch, overrides, case)
|
||||
distances, hits = _pd_distances(arch, overrides, overrides, case, ref)
|
||||
|
||||
# Every transferred token of every prompt must come from prefill.
|
||||
assert hits == ref.expected_external_hits, (
|
||||
f"decode reported {hits} external prefix-cache hits, expected "
|
||||
f"{ref.expected_external_hits}; it did not use all the transferred KV"
|
||||
)
|
||||
lengths = [len(p) for p in ref.prompts]
|
||||
bad = {n: d for n, d in zip(lengths, distances) if not d <= TOLERANCE}
|
||||
assert not bad, f"P/D first-token log-probs differ from direct serve: {bad}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arch_name", sorted(ARCHS))
|
||||
def test_corrupted_prefill_state_is_detected(arch_name: str):
|
||||
"""Negative control: KV computed with different values must fail."""
|
||||
arch = ARCHS[arch_name]
|
||||
default = next(c for c in CASES if c.arch == arch_name)
|
||||
case = Case(
|
||||
arch_name, default.attention_backend, _DEFAULT, _DEFAULT, default.hma_off
|
||||
)
|
||||
overrides = _arch_overrides(arch)
|
||||
ref = _reference(arch, overrides, case)
|
||||
corrupted = _merge(overrides, arch.corrupt_overrides)
|
||||
distances, hits = _pd_distances(arch, corrupted, overrides, case, ref)
|
||||
|
||||
assert hits == ref.expected_external_hits, (
|
||||
"decode did not use the transferred KV; the control proves nothing"
|
||||
)
|
||||
assert all(d > TOLERANCE for d in distances), (
|
||||
f"P/D outputs with wrongly computed prefill KV still matched the "
|
||||
f"reference (distances {distances}); the comparison cannot detect "
|
||||
"transfer corruption"
|
||||
)
|
||||
@@ -1,34 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""NIXL P/D accuracy with AITER unified attention on ROCm."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import spawn_new_process_for_each_test
|
||||
from tests.v1.kv_connector.rocm_pd_accuracy_utils import (
|
||||
DEEPSEEK_MODEL,
|
||||
QWEN_MODEL,
|
||||
run_rocm_pd_accuracy,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm P/D equivalents"),
|
||||
pytest.mark.distributed(num_gpus=4),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model,prefill_tp,decode_tp",
|
||||
[
|
||||
pytest.param(QWEN_MODEL, 2, 2, id="nixl-aiter-qwen-p2-d2"),
|
||||
pytest.param(QWEN_MODEL, 1, 2, id="nixl-aiter-qwen-p1-d2"),
|
||||
pytest.param(QWEN_MODEL, 2, 1, id="nixl-aiter-qwen-p2-d1"),
|
||||
pytest.param(DEEPSEEK_MODEL, 1, 1, id="nixl-aiter-deepseek-p1-d1"),
|
||||
pytest.param(DEEPSEEK_MODEL, 1, 2, id="nixl-aiter-deepseek-p1-d2"),
|
||||
pytest.param(DEEPSEEK_MODEL, 2, 1, id="nixl-aiter-deepseek-p2-d1"),
|
||||
],
|
||||
)
|
||||
@spawn_new_process_for_each_test
|
||||
def test_rocm_pd_accuracy(model, prefill_tp, decode_tp, monkeypatch):
|
||||
run_rocm_pd_accuracy("nixl", model, prefill_tp, decode_tp, monkeypatch)
|
||||
@@ -1,263 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared ROCm P/D accuracy harness for Mooncake and NIXL integration tests.
|
||||
|
||||
Keep the models, TP pairs, full GSM8K workload, and acceptance checks of the
|
||||
Mooncake and FlashInfer/NIXL sweeps. Mooncake uses same-host HIP IPC; NIXL uses
|
||||
AITER unified attention. These cases do not exercise RDMA or FlashInfer.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
|
||||
_ROOT = Path(__file__).resolve().parents[3]
|
||||
QWEN_MODEL = "Qwen/Qwen3-0.6B"
|
||||
DEEPSEEK_MODEL = "deepseek-ai/deepseek-vl2-tiny"
|
||||
_REVISIONS = {
|
||||
QWEN_MODEL: "c1899de289a04d12100db370d81485cdf75e47ca",
|
||||
DEEPSEEK_MODEL: "66c54660eae7e90c9ba259bfdf92d07d6e3ce8aa",
|
||||
}
|
||||
|
||||
|
||||
def _metric_total(server, name: str, **labels: str) -> float:
|
||||
response = requests.get(server.url_for("metrics"), timeout=10)
|
||||
response.raise_for_status()
|
||||
return sum(
|
||||
sample.value
|
||||
for family in text_string_to_metric_families(response.text)
|
||||
for sample in family.samples
|
||||
if sample.name == name
|
||||
and all(sample.labels.get(key) == value for key, value in labels.items())
|
||||
)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _proxy(connector: str, prefill, decode, bootstrap_port: int):
|
||||
port = get_open_port()
|
||||
if connector == "mooncake":
|
||||
script = (
|
||||
_ROOT / "examples/disaggregated/mooncake_connector/"
|
||||
"mooncake_connector_proxy.py"
|
||||
)
|
||||
args = [
|
||||
"--prefill",
|
||||
prefill.url_root,
|
||||
str(bootstrap_port),
|
||||
"--decode",
|
||||
decode.url_root,
|
||||
]
|
||||
else:
|
||||
script = Path(__file__).parent / "nixl_integration/toy_proxy_server.py"
|
||||
args = [
|
||||
"--prefiller-hosts",
|
||||
"127.0.0.1",
|
||||
"--prefiller-ports",
|
||||
str(prefill.port),
|
||||
"--decoder-hosts",
|
||||
"127.0.0.1",
|
||||
"--decoder-ports",
|
||||
str(decode.port),
|
||||
]
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, str(script), "--port", str(port), *args],
|
||||
start_new_session=True,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, "P/D proxy exited during startup"
|
||||
try:
|
||||
requests.get(f"http://127.0.0.1:{port}/", timeout=1)
|
||||
break
|
||||
except requests.ConnectionError:
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError("P/D proxy did not start")
|
||||
yield f"http://127.0.0.1:{port}/v1"
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
def run_rocm_pd_accuracy(connector, model, prefill_tp, decode_tp, monkeypatch):
|
||||
"""Transferred KV must feed decoding while full upstream accuracy holds."""
|
||||
# Preserve the caller's allocation instead of querying host-wide SMI indices.
|
||||
selectors = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
|
||||
selector = next((key for key in selectors if key in os.environ), selectors[0])
|
||||
visible = os.getenv(selector)
|
||||
devices = (
|
||||
visible.split(",")
|
||||
if visible is not None
|
||||
else [str(i) for i in range(current_platform.device_count())]
|
||||
)
|
||||
assert len(devices) >= prefill_tp + decode_tp, "Insufficient allocated GPUs"
|
||||
for key in selectors:
|
||||
if key != selector:
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
|
||||
if connector == "mooncake":
|
||||
import mooncake.engine
|
||||
|
||||
assert mooncake.engine.SUPPORT_HIP, "Mooncake requires its ROCm/HIP build"
|
||||
connector_name = "MooncakeConnector"
|
||||
extra = {"mooncake_protocol": "hip", "device_name": ""}
|
||||
else:
|
||||
from vllm.distributed.nixl_utils import NixlWrapper
|
||||
|
||||
assert NixlWrapper is not None, "NIXL ROCm bindings must import"
|
||||
connector_name = "NixlConnector"
|
||||
extra = {}
|
||||
|
||||
common_args = [
|
||||
"--revision",
|
||||
_REVISIONS[model],
|
||||
"--dtype",
|
||||
"bfloat16",
|
||||
"--enforce-eager",
|
||||
"--distributed-executor-backend",
|
||||
"mp",
|
||||
"--block-size",
|
||||
"128",
|
||||
"--max-num-seqs",
|
||||
"128",
|
||||
"--max-num-batched-tokens",
|
||||
"4096",
|
||||
"--gpu-memory-utilization",
|
||||
"0.2",
|
||||
"--kv-cache-memory-bytes",
|
||||
str(8 * 1024**3),
|
||||
"--moe-backend",
|
||||
"triton",
|
||||
"--attention-backend",
|
||||
"ROCM_AITER_UNIFIED_ATTN",
|
||||
]
|
||||
common_env = {
|
||||
"PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"],
|
||||
"VLLM_HOST_IP": "127.0.0.1",
|
||||
"VLLM_WORKER_MULTIPROC_METHOD": "spawn",
|
||||
"VLLM_USE_V2_MODEL_RUNNER": "1",
|
||||
"VLLM_ROCM_USE_AITER": "1",
|
||||
"VLLM_KV_CACHE_LAYOUT": "HND",
|
||||
}
|
||||
with contextlib.ExitStack() as stack:
|
||||
bootstrap_port = 0
|
||||
if connector == "mooncake":
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_utils import ( # noqa: E501
|
||||
MooncakeBootstrapServer,
|
||||
)
|
||||
|
||||
bootstrap = MooncakeBootstrapServer("127.0.0.1", 0)
|
||||
stack.callback(bootstrap.shutdown)
|
||||
bootstrap.start()
|
||||
bootstrap_port = bootstrap.port
|
||||
extra["bootstrap_server_address"] = f"127.0.0.1:{bootstrap_port}"
|
||||
servers: list[RemoteOpenAIServer] = []
|
||||
stack.callback(RemoteOpenAIServer.shutdown_many, servers)
|
||||
for role, tp, assigned in (
|
||||
("kv_producer", prefill_tp, devices[:prefill_tp]),
|
||||
("kv_consumer", decode_tp, devices[prefill_tp : prefill_tp + decode_tp]),
|
||||
):
|
||||
config = {
|
||||
"kv_connector": connector_name,
|
||||
"kv_role": role,
|
||||
"kv_connector_extra_config": extra,
|
||||
}
|
||||
env = {
|
||||
**common_env,
|
||||
selector: ",".join(assigned),
|
||||
"VLLM_PORT": str(get_open_port()),
|
||||
"VLLM_NIXL_SIDE_CHANNEL_PORT": str(get_open_port()),
|
||||
}
|
||||
servers.append(
|
||||
RemoteOpenAIServer(
|
||||
model,
|
||||
[
|
||||
*common_args,
|
||||
"--tensor-parallel-size",
|
||||
str(tp),
|
||||
"--kv-transfer-config",
|
||||
json.dumps(config),
|
||||
],
|
||||
env_dict=env,
|
||||
max_wait_seconds=1200,
|
||||
)
|
||||
)
|
||||
prefill, decode = servers
|
||||
proxy_url = stack.enter_context(
|
||||
_proxy(connector, prefill, decode, bootstrap_port)
|
||||
)
|
||||
|
||||
# Reuse the full upstream evaluation and its model-specific assertions.
|
||||
accuracy = importlib.import_module(
|
||||
f"tests.v1.kv_connector.{connector}_integration.test_accuracy"
|
||||
)
|
||||
monkeypatch.setattr(accuracy, "MODEL_NAME", model)
|
||||
monkeypatch.setattr(accuracy, "BASE_URL", proxy_url)
|
||||
assert model in accuracy.EXPECTED_VALUES
|
||||
|
||||
def transfer_totals():
|
||||
totals = {
|
||||
"external_tokens": _metric_total(
|
||||
decode,
|
||||
"vllm:prompt_tokens_by_source_total",
|
||||
source="external_kv_transfer",
|
||||
)
|
||||
}
|
||||
if connector == "nixl":
|
||||
totals["nixl_bytes"] = _metric_total(
|
||||
decode, "vllm:nixl_bytes_transferred_sum"
|
||||
)
|
||||
return totals
|
||||
|
||||
simple_evaluate = accuracy.lm_eval.simple_evaluate
|
||||
|
||||
def evaluate_with_transfer_checks(*args, **kwargs):
|
||||
# The upstream helper runs a smoke prompt before GSM8K. Wait until
|
||||
# its counters appear, then require new transfers during evaluation.
|
||||
deadline = time.monotonic() + 15
|
||||
before = transfer_totals()
|
||||
while not all(value > 0 for value in before.values()):
|
||||
assert time.monotonic() < deadline, (
|
||||
f"Smoke prompt did not transfer KV: {before}"
|
||||
)
|
||||
time.sleep(1)
|
||||
before = transfer_totals()
|
||||
|
||||
# The API adapter loads a local tokenizer because these proxies do
|
||||
# not expose /tokenize. Match it to the server's pinned checkpoint.
|
||||
kwargs["model_args"] += f",revision={_REVISIONS[model]}"
|
||||
results = simple_evaluate(*args, **kwargs)
|
||||
deadline = time.monotonic() + 15
|
||||
after = transfer_totals()
|
||||
while not all(after[key] > value for key, value in before.items()):
|
||||
assert time.monotonic() < deadline, (
|
||||
f"GSM8K did not transfer KV: before={before}, after={after}"
|
||||
)
|
||||
time.sleep(1)
|
||||
after = transfer_totals()
|
||||
print(f"GSM8K transfer counters: before={before}, after={after}")
|
||||
return results
|
||||
|
||||
monkeypatch.setattr(
|
||||
accuracy.lm_eval, "simple_evaluate", evaluate_with_transfer_checks
|
||||
)
|
||||
accuracy.test_accuracy()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,712 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.kv_connector.unit.utils import (
|
||||
EOS_TOKEN_ID,
|
||||
create_model_runner_output,
|
||||
create_vllm_config,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import (
|
||||
KVEventsConfig,
|
||||
KVTransferConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.common import (
|
||||
OffloadingConnectorMetadata,
|
||||
OffloadingWorkerMetadata,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading_connector import (
|
||||
OffloadingConnector,
|
||||
)
|
||||
from vllm.forward_context import ForwardContext
|
||||
from vllm.utils.hashing import sha256
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
get_request_block_hasher,
|
||||
init_none_hash,
|
||||
resolve_kv_cache_block_sizes,
|
||||
)
|
||||
from vllm.v1.core.sched.async_scheduler import AsyncScheduler
|
||||
from vllm.v1.core.sched.scheduler import Scheduler
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
)
|
||||
from vllm.v1.kv_offload.base import (
|
||||
CanonicalKVCaches,
|
||||
GPULoadStoreSpec,
|
||||
LoadStoreSpec,
|
||||
LookupResult,
|
||||
OffloadingManager,
|
||||
OffloadingSpec,
|
||||
OffloadingWorker,
|
||||
OffloadKey,
|
||||
PrepareStoreOutput,
|
||||
RequestOffloadingContext,
|
||||
TransferResult,
|
||||
make_offload_key,
|
||||
)
|
||||
from vllm.v1.kv_offload.config import OffloadingConfig
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.request import Request
|
||||
from vllm.v1.structured_output import StructuredOutputManager
|
||||
|
||||
|
||||
def to_key(int_hash: int) -> OffloadKey:
|
||||
return make_offload_key(str(int_hash).encode(), 0)
|
||||
|
||||
|
||||
def to_keys(int_hashes: Iterable[int]) -> list[OffloadKey]:
|
||||
return [to_key(i) for i in int_hashes]
|
||||
|
||||
|
||||
class MockLoadStoreSpec(LoadStoreSpec):
|
||||
def __init__(self, offload_keys: Iterable[OffloadKey]):
|
||||
self.offload_keys: list[OffloadKey] = list(offload_keys)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return repr(self.offload_keys)
|
||||
|
||||
|
||||
class MockOffloadingWorker(OffloadingWorker):
|
||||
def __init__(self):
|
||||
self.transfer_specs: dict[int, tuple[LoadStoreSpec, LoadStoreSpec]] = {}
|
||||
self.completed_transfers: list[TransferResult] = []
|
||||
self.waiting_jobs: set[int] = set()
|
||||
self.completed_jobs: list[int] = []
|
||||
self.flushed_jobs: set[int] = set()
|
||||
|
||||
def get_finished(self) -> list[TransferResult]:
|
||||
finished = self.completed_transfers
|
||||
self.completed_transfers = []
|
||||
return finished
|
||||
|
||||
def submit_store(
|
||||
self, job_id: int, src_spec: LoadStoreSpec, dst_spec: LoadStoreSpec
|
||||
) -> bool: # type: ignore[override]
|
||||
self.transfer_specs[job_id] = (src_spec, dst_spec)
|
||||
self.waiting_jobs.add(job_id)
|
||||
return True
|
||||
|
||||
def submit_load(
|
||||
self, job_id: int, src_spec: LoadStoreSpec, dst_spec: LoadStoreSpec
|
||||
) -> bool: # type: ignore[override]
|
||||
self.transfer_specs[job_id] = (src_spec, dst_spec)
|
||||
self.waiting_jobs.add(job_id)
|
||||
return True
|
||||
|
||||
def complete_jobs(self, job_ids: set[int]) -> None:
|
||||
for job_id in job_ids:
|
||||
if job_id in self.waiting_jobs:
|
||||
self.waiting_jobs.remove(job_id)
|
||||
self.completed_jobs.append(job_id)
|
||||
result = TransferResult(
|
||||
job_id=job_id,
|
||||
success=True,
|
||||
transfer_size=None,
|
||||
transfer_time=None,
|
||||
)
|
||||
self.completed_transfers.append(result)
|
||||
|
||||
def wait(self, job_ids: set[int]) -> None:
|
||||
self.flushed_jobs |= job_ids
|
||||
self.complete_jobs(job_ids)
|
||||
|
||||
|
||||
class MockOffloadingSpec(OffloadingSpec):
|
||||
def __init__(self, config: OffloadingConfig):
|
||||
super().__init__(config)
|
||||
|
||||
self.manager = MagicMock(spec=OffloadingManager)
|
||||
self.manager.prepare_load = lambda keys, req_context: MockLoadStoreSpec(keys)
|
||||
self.manager.lookup.return_value = LookupResult.MISS
|
||||
self.manager.get_load_source.return_value = CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
self.manager.get_stats.return_value = None
|
||||
self.manager.config_info.return_value = [{}]
|
||||
self.manager.on_new_request.return_value = RequestOffloadingContext()
|
||||
self.handler = MockOffloadingWorker()
|
||||
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
return self.manager
|
||||
|
||||
def get_worker(self, _: CanonicalKVCaches) -> OffloadingWorker:
|
||||
return self.handler
|
||||
|
||||
def complete_transfers(self):
|
||||
self.handler.complete_jobs(self.handler.waiting_jobs.copy())
|
||||
|
||||
def get_completed_transfers(self) -> list[tuple[LoadStoreSpec, LoadStoreSpec]]:
|
||||
specs = [
|
||||
self.handler.transfer_specs[job_id]
|
||||
for job_id in self.handler.completed_jobs
|
||||
]
|
||||
self.handler.completed_jobs.clear()
|
||||
return specs
|
||||
|
||||
def get_flushed_transfers(self) -> list[tuple[LoadStoreSpec, LoadStoreSpec]]:
|
||||
specs = [
|
||||
self.handler.transfer_specs[job_id] for job_id in self.handler.flushed_jobs
|
||||
]
|
||||
self.handler.flushed_jobs.clear()
|
||||
return specs
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GPUBlock:
|
||||
group_idx: int
|
||||
request_block_offset: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class TransferSummary:
|
||||
gpu_blocks: list[GPUBlock]
|
||||
offload_addresses: list[Any]
|
||||
|
||||
|
||||
class RequestRunner:
|
||||
def __init__(
|
||||
self,
|
||||
block_size: int,
|
||||
num_gpu_blocks: int,
|
||||
blocks_per_chunk: int = 1,
|
||||
async_scheduling: bool = True,
|
||||
kv_cache_groups: list[KVCacheGroupSpec] | None = None,
|
||||
extra_config_overrides: dict[str, Any] | None = None,
|
||||
worker_count: int = 1,
|
||||
retention_interval: int | None = None,
|
||||
speculative_config: Any | None = None,
|
||||
):
|
||||
assert blocks_per_chunk == 1 or kv_cache_groups is None, (
|
||||
"blocks_per_chunk > 1 requires all groups to have the same "
|
||||
"block size, so kv_cache_groups must be None (use default group)"
|
||||
)
|
||||
|
||||
self.blocks_per_chunk: int = blocks_per_chunk
|
||||
self.block_size: int = block_size
|
||||
self.num_gpu_blocks: int = num_gpu_blocks
|
||||
self.async_scheduling: bool = async_scheduling
|
||||
|
||||
self.req_id: int = -1
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
block_size=block_size,
|
||||
max_num_batched_tokens=1000,
|
||||
disable_hybrid_kv_cache_manager=False,
|
||||
)
|
||||
vllm_config.scheduler_config.async_scheduling = async_scheduling
|
||||
vllm_config.parallel_config.world_size = worker_count
|
||||
vllm_config.cache_config.prefix_cache_retention_interval = retention_interval
|
||||
if speculative_config is not None:
|
||||
vllm_config.speculative_config = speculative_config
|
||||
|
||||
extra_config: dict[str, Any] = {
|
||||
"spec_name": "MockOffloadingSpec",
|
||||
"spec_module_path": "tests.v1.kv_connector.unit.offloading_connector.utils", # noqa: E501
|
||||
# Preserve legacy behavior for tests; new opt-in tests override.
|
||||
"offload_prompt_only": False,
|
||||
# Exercise the self-describing KV events path by default;
|
||||
# opt-out tests override this to cover the legacy placeholders.
|
||||
"self_describing_kv_events": True,
|
||||
}
|
||||
if blocks_per_chunk > 1:
|
||||
extra_config["block_size"] = block_size * blocks_per_chunk
|
||||
if extra_config_overrides:
|
||||
extra_config.update(extra_config_overrides)
|
||||
|
||||
vllm_config.kv_transfer_config = KVTransferConfig(
|
||||
kv_connector="OffloadingConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config=extra_config,
|
||||
)
|
||||
vllm_config.kv_events_config = KVEventsConfig(
|
||||
# Enable so the offloading events tracker is active, but use the
|
||||
# null publisher: these tests drain take_events directly and a
|
||||
# real ZMQ publisher would bind a port per test.
|
||||
enable_kv_cache_events=True,
|
||||
publisher="null",
|
||||
)
|
||||
|
||||
if kv_cache_groups is None:
|
||||
kv_cache_groups = [
|
||||
KVCacheGroupSpec(
|
||||
["layer"],
|
||||
FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
)
|
||||
]
|
||||
|
||||
# Groups overlay one allocation, sized by the largest group.
|
||||
block_stride = max(
|
||||
group.kv_cache_spec.page_size_bytes * len(group.layer_names)
|
||||
for group in kv_cache_groups
|
||||
)
|
||||
kv_cache_tensors = [
|
||||
KVCacheTensor(
|
||||
size=block_stride * num_gpu_blocks,
|
||||
layers=list(group.layer_names),
|
||||
layer_stride=group.kv_cache_spec.page_size_bytes * num_gpu_blocks,
|
||||
block_stride=group.kv_cache_spec.page_size_bytes,
|
||||
)
|
||||
for group in kv_cache_groups
|
||||
]
|
||||
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=num_gpu_blocks,
|
||||
kv_cache_tensors=kv_cache_tensors,
|
||||
kv_cache_groups=kv_cache_groups,
|
||||
)
|
||||
vllm_config.cache_config.num_gpu_blocks = num_gpu_blocks
|
||||
self.num_kv_groups = len(kv_cache_config.kv_cache_groups)
|
||||
|
||||
scheduler_block_size, hash_block_size = resolve_kv_cache_block_sizes(
|
||||
kv_cache_config, vllm_config
|
||||
)
|
||||
|
||||
scheduler_cls = AsyncScheduler if async_scheduling else Scheduler
|
||||
self.scheduler = scheduler_cls(
|
||||
vllm_config=vllm_config,
|
||||
kv_cache_config=kv_cache_config,
|
||||
log_stats=True,
|
||||
structured_output_manager=StructuredOutputManager(vllm_config),
|
||||
block_size=scheduler_block_size,
|
||||
hash_block_size=hash_block_size,
|
||||
)
|
||||
|
||||
self.worker_connector = OffloadingConnector(
|
||||
vllm_config, KVConnectorRole.WORKER, kv_cache_config
|
||||
)
|
||||
|
||||
# register worker kv_caches to enable OffloadingWorker creations
|
||||
kv_caches: dict[str, torch.Tensor] = {}
|
||||
for group in kv_cache_groups:
|
||||
spec = group.kv_cache_spec
|
||||
for layer_name in group.layer_names:
|
||||
# Shape follows FlashAttention layout:
|
||||
# Shape: (num_blocks, 2, block_size, num_kv_heads, head_size)
|
||||
kv_caches[layer_name] = torch.empty(
|
||||
num_gpu_blocks,
|
||||
2,
|
||||
spec.block_size,
|
||||
spec.num_kv_heads,
|
||||
spec.head_size,
|
||||
dtype=spec.dtype,
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config):
|
||||
self.worker_connector.register_kv_caches(kv_caches)
|
||||
|
||||
# extract connector of scheduler
|
||||
scheduler_connector = self.scheduler.connector
|
||||
assert scheduler_connector is not None
|
||||
assert isinstance(scheduler_connector, OffloadingConnector)
|
||||
self.scheduler_connector: OffloadingConnector = scheduler_connector
|
||||
|
||||
# extract mocked OffloadingManager of scheduler connector
|
||||
self.connector_scheduler = scheduler_connector.connector_scheduler
|
||||
assert self.connector_scheduler is not None
|
||||
manager = self.connector_scheduler.manager
|
||||
assert isinstance(manager, MagicMock)
|
||||
self.manager: MagicMock = manager
|
||||
|
||||
num_kv_groups = len(kv_cache_config.kv_cache_groups)
|
||||
assert len(self.connector_scheduler.config.kv_group_configs) == num_kv_groups
|
||||
for group_config, kv_cache_group in zip(
|
||||
self.connector_scheduler.config.kv_group_configs,
|
||||
kv_cache_config.kv_cache_groups,
|
||||
):
|
||||
tokens_per_block = kv_cache_group.kv_cache_spec.block_size
|
||||
assert group_config.tokens_per_block == tokens_per_block
|
||||
assert group_config.tokens_per_chunk == tokens_per_block * blocks_per_chunk
|
||||
|
||||
# extract OffloadingSpec of worker_connector
|
||||
connector_worker = self.worker_connector.connector_worker
|
||||
assert connector_worker is not None
|
||||
offloading_spec = connector_worker.spec
|
||||
assert isinstance(offloading_spec, MockOffloadingSpec)
|
||||
self.offloading_spec: MockOffloadingSpec = offloading_spec
|
||||
|
||||
# mapping (offloading address) -> GPUBlock
|
||||
self.offloaded: dict[Any, GPUBlock] = {}
|
||||
|
||||
self.completed_loads: list[TransferSummary] = []
|
||||
self.completed_stores: list[TransferSummary] = []
|
||||
self.flushed_gpu_blocks: set[GPUBlock] = set()
|
||||
self.kv_connector_stats: list[Any] = []
|
||||
|
||||
# block_id -> GPUBlock
|
||||
self.gpu_blocks: dict[int, GPUBlock] = {}
|
||||
|
||||
init_none_hash(sha256)
|
||||
self._block_hasher = get_request_block_hasher(block_size, sha256)
|
||||
|
||||
self._dummy_ctx: ForwardContext = ForwardContext(
|
||||
no_compile_layers={},
|
||||
attn_metadata={},
|
||||
slot_mapping={},
|
||||
)
|
||||
|
||||
def _record_kv_connector_stats(self, engine_outputs: dict[int, Any]) -> None:
|
||||
for output in engine_outputs.values():
|
||||
scheduler_stats = output.scheduler_stats
|
||||
if scheduler_stats is not None and scheduler_stats.kv_connector_stats:
|
||||
self.kv_connector_stats.append(scheduler_stats.kv_connector_stats)
|
||||
|
||||
def new_request(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
kv_transfer_params: dict | None = None,
|
||||
skip_reading_prefix_cache: bool = False,
|
||||
):
|
||||
self.req_id += 1
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=1000,
|
||||
skip_reading_prefix_cache=skip_reading_prefix_cache or None,
|
||||
)
|
||||
sampling_params.update_from_generation_config({}, EOS_TOKEN_ID)
|
||||
|
||||
req = Request(
|
||||
request_id=str(self.req_id),
|
||||
prompt_token_ids=token_ids,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
block_hasher=self._block_hasher,
|
||||
)
|
||||
if kv_transfer_params is not None:
|
||||
req.kv_transfer_params = kv_transfer_params
|
||||
|
||||
self.scheduler.add_request(req)
|
||||
|
||||
def _parse_transfers(self):
|
||||
for src_spec, dst_spec in self.offloading_spec.get_flushed_transfers():
|
||||
if isinstance(src_spec, GPULoadStoreSpec):
|
||||
# store flush
|
||||
for block_id in src_spec.block_ids:
|
||||
self.flushed_gpu_blocks.add(self.gpu_blocks[block_id.item()])
|
||||
else:
|
||||
# load flush
|
||||
for block_id in dst_spec.block_ids:
|
||||
self.flushed_gpu_blocks.add(self.gpu_blocks[block_id.item()])
|
||||
|
||||
blocks_per_chunk = self.blocks_per_chunk
|
||||
|
||||
for src_spec, dst_spec in self.offloading_spec.get_completed_transfers():
|
||||
if isinstance(src_spec, GPULoadStoreSpec):
|
||||
store = True
|
||||
gpu_spec = src_spec
|
||||
offload_spec = dst_spec
|
||||
else:
|
||||
store = False
|
||||
gpu_spec = dst_spec
|
||||
offload_spec = src_spec
|
||||
|
||||
assert isinstance(offload_spec, MockLoadStoreSpec)
|
||||
assert isinstance(gpu_spec, GPULoadStoreSpec)
|
||||
assert len(gpu_spec.group_sizes) == self.num_kv_groups
|
||||
|
||||
gpu_blocks: list[GPUBlock] = []
|
||||
for block_id in gpu_spec.block_ids:
|
||||
gpu_blocks.append(self.gpu_blocks[block_id.item()])
|
||||
|
||||
# list of (offload_key, sub_block_offset)
|
||||
offload_addresses: list[Any] = []
|
||||
for offload_key in offload_spec.offload_keys:
|
||||
for sub_block_idx in range(blocks_per_chunk):
|
||||
offload_addresses.append((offload_key, sub_block_idx))
|
||||
|
||||
assert gpu_spec.block_indices is not None
|
||||
assert len(gpu_spec.block_indices) == self.num_kv_groups
|
||||
|
||||
gpu_block_offset = 0
|
||||
offload_address_offset = 0
|
||||
for group_size, logical_offset in zip(
|
||||
gpu_spec.group_sizes, gpu_spec.block_indices
|
||||
):
|
||||
gpu_block_end_offset = gpu_block_offset + group_size
|
||||
assert gpu_block_end_offset <= len(gpu_blocks)
|
||||
|
||||
offload_addresses_to_skip = logical_offset % blocks_per_chunk
|
||||
offload_addresses_end_offset = (
|
||||
offload_address_offset + offload_addresses_to_skip + group_size
|
||||
)
|
||||
assert offload_addresses_end_offset <= len(offload_addresses)
|
||||
|
||||
offload_addresses = (
|
||||
offload_addresses[:offload_address_offset]
|
||||
+ offload_addresses[
|
||||
offload_address_offset + offload_addresses_to_skip :
|
||||
]
|
||||
)
|
||||
|
||||
gpu_block_offset += group_size
|
||||
offload_address_offset += group_size
|
||||
|
||||
assert gpu_block_offset == len(gpu_blocks)
|
||||
assert offload_address_offset == len(offload_addresses)
|
||||
|
||||
transfer_summary = TransferSummary(gpu_blocks, offload_addresses)
|
||||
if store:
|
||||
self.completed_stores.append(transfer_summary)
|
||||
else:
|
||||
self.completed_loads.append(transfer_summary)
|
||||
|
||||
def _update_gpu_blocks(self):
|
||||
for group_idx, manager in enumerate(
|
||||
self.scheduler.kv_cache_manager.coordinator.single_type_managers
|
||||
):
|
||||
for blocks in manager.req_to_blocks.values():
|
||||
for block_idx, block in enumerate(blocks):
|
||||
self.gpu_blocks[block.block_id] = GPUBlock(group_idx, block_idx)
|
||||
|
||||
def _run(
|
||||
self,
|
||||
decoded_tokens: list[int],
|
||||
complete_transfers: bool,
|
||||
post_step_fn: Callable[[], None] | None = None,
|
||||
):
|
||||
"""Runs multiple engine (scheduler + worker) steps.
|
||||
Assumes a single request is running.
|
||||
|
||||
Args:
|
||||
decoded_tokens: the tokens to yield at each step.
|
||||
complete_transfers: complete transfers immediately
|
||||
post_step_fn: optional callback invoked after each step's
|
||||
update_from_output(), before the next schedule().
|
||||
|
||||
"""
|
||||
tokens_iter = iter(decoded_tokens)
|
||||
token_id = next(tokens_iter, None)
|
||||
prev_scheduler_output = None
|
||||
prev_model_runner_output = None
|
||||
while True:
|
||||
# Strict-always-False frees the request immediately on EOS, but
|
||||
# the worker may still have a deferred store queued. In production
|
||||
# the next request's step drains it; in single-request tests we
|
||||
# must keep stepping until the scheduler sees no in-flight jobs
|
||||
# and no pending finished_req_ids awaiting build_connector_meta.
|
||||
if (
|
||||
not self.scheduler.requests
|
||||
and not self.connector_scheduler._jobs
|
||||
and not self.scheduler.finished_req_ids
|
||||
):
|
||||
break
|
||||
|
||||
scheduler_output = self.scheduler.schedule()
|
||||
self._update_gpu_blocks()
|
||||
|
||||
kv_connector_metadata = scheduler_output.kv_connector_metadata
|
||||
assert kv_connector_metadata is not None
|
||||
assert isinstance(kv_connector_metadata, OffloadingConnectorMetadata)
|
||||
|
||||
self.worker_connector.handle_preemptions(kv_connector_metadata)
|
||||
|
||||
self.worker_connector.bind_connector_metadata(kv_connector_metadata)
|
||||
self.worker_connector.start_load_kv(self._dummy_ctx)
|
||||
|
||||
if complete_transfers:
|
||||
self.offloading_spec.complete_transfers()
|
||||
|
||||
self.worker_connector.wait_for_save()
|
||||
finished_sending, finished_recving = self.worker_connector.get_finished(
|
||||
scheduler_output.finished_req_ids
|
||||
)
|
||||
worker_meta = (
|
||||
self.worker_connector.build_connector_worker_meta()
|
||||
or OffloadingWorkerMetadata()
|
||||
)
|
||||
|
||||
self.worker_connector.clear_connector_metadata()
|
||||
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=self.scheduler.running,
|
||||
finished_sending=finished_sending,
|
||||
finished_recving=finished_recving,
|
||||
token_id=token_id or 0,
|
||||
kv_connector_worker_meta=worker_meta,
|
||||
)
|
||||
|
||||
prev_token_id = token_id
|
||||
if self.scheduler.running:
|
||||
token_id = next(tokens_iter, None)
|
||||
|
||||
if self.async_scheduling:
|
||||
# in async scheduling we update the output of the previous step
|
||||
if prev_model_runner_output is not None:
|
||||
engine_outputs = self.scheduler.update_from_output(
|
||||
prev_scheduler_output, prev_model_runner_output
|
||||
)
|
||||
self._record_kv_connector_stats(engine_outputs)
|
||||
prev_scheduler_output = scheduler_output
|
||||
prev_model_runner_output = model_runner_output
|
||||
else:
|
||||
engine_outputs = self.scheduler.update_from_output(
|
||||
scheduler_output, model_runner_output
|
||||
)
|
||||
self._record_kv_connector_stats(engine_outputs)
|
||||
|
||||
if post_step_fn is not None:
|
||||
post_step_fn()
|
||||
|
||||
if (
|
||||
prev_token_id == EOS_TOKEN_ID
|
||||
and prev_token_id != token_id
|
||||
and (
|
||||
self.scheduler.requests
|
||||
or self.connector_scheduler._jobs
|
||||
or self.scheduler.finished_req_ids
|
||||
)
|
||||
):
|
||||
# continue for one more step to allow offloading to kick off
|
||||
continue
|
||||
|
||||
if token_id is None:
|
||||
if self.async_scheduling:
|
||||
# Flush the previous step's output.
|
||||
engine_outputs = self.scheduler.update_from_output(
|
||||
prev_scheduler_output, prev_model_runner_output
|
||||
)
|
||||
self._record_kv_connector_stats(engine_outputs)
|
||||
prev_model_runner_output = None
|
||||
if self.scheduler.requests:
|
||||
# Request still running, just exhausted decoded_tokens.
|
||||
break
|
||||
if not self.scheduler.finished_req_ids and (
|
||||
not complete_transfers or not self.connector_scheduler._jobs
|
||||
):
|
||||
break
|
||||
|
||||
self._parse_transfers()
|
||||
|
||||
if EOS_TOKEN_ID in decoded_tokens:
|
||||
assert not self.scheduler.running
|
||||
|
||||
def _to_gpu_blocks(
|
||||
self, blocks: tuple[int | tuple[int, int], ...]
|
||||
) -> list[GPUBlock]:
|
||||
gpu_blocks: list[GPUBlock] = []
|
||||
for block in blocks:
|
||||
if isinstance(block, int):
|
||||
for group_idx in range(self.num_kv_groups):
|
||||
gpu_blocks.append(
|
||||
GPUBlock(group_idx=group_idx, request_block_offset=block)
|
||||
)
|
||||
else:
|
||||
group_idx, offset = block
|
||||
gpu_blocks.append(
|
||||
GPUBlock(group_idx=group_idx, request_block_offset=offset)
|
||||
)
|
||||
return gpu_blocks
|
||||
|
||||
def run(
|
||||
self,
|
||||
decoded_tokens: list[int],
|
||||
complete_transfers: bool = True,
|
||||
expected_stored: tuple[int | tuple[int, int], ...] = (),
|
||||
expected_loaded: tuple[int | tuple[int, int], ...] = (),
|
||||
expected_flushed: tuple[int | tuple[int, int], ...] = (),
|
||||
post_step_fn: Callable[[], None] | None = None,
|
||||
):
|
||||
"""Runs multiple engine (scheduler + worker) steps.
|
||||
Assumes a single request is running.
|
||||
|
||||
Args:
|
||||
decoded_tokens: the tokens to yield at each step.
|
||||
complete_transfers: complete transfers immediately
|
||||
expected_stored: GPU blocks
|
||||
that are expected to be written during the run.
|
||||
expected_loaded: GPU blocks
|
||||
that are expected to be loaded during the run.
|
||||
expected_flushed: GPU blocks
|
||||
that are expected to be flushed during the run.
|
||||
|
||||
A GPU block is either a (group_idx: int, request_block_offset: int)
|
||||
or just request_block_offset: int.
|
||||
The latter case is a convenience for representing all groups.
|
||||
|
||||
"""
|
||||
expected_stored_gpu_blocks = self._to_gpu_blocks(expected_stored)
|
||||
expected_loaded_gpu_blocks = self._to_gpu_blocks(expected_loaded)
|
||||
expected_flushed_gpu_blocks = self._to_gpu_blocks(expected_flushed)
|
||||
|
||||
self.manager.reset_mock()
|
||||
self._run(decoded_tokens, complete_transfers, post_step_fn=post_step_fn)
|
||||
|
||||
loaded_gpu_blocks: set[GPUBlock] = set()
|
||||
for transfer in self.completed_loads:
|
||||
for gpu_block, offloaded_address in zip(
|
||||
transfer.gpu_blocks, transfer.offload_addresses
|
||||
):
|
||||
loaded_gpu_blocks.add(gpu_block)
|
||||
assert gpu_block == self.offloaded[offloaded_address]
|
||||
|
||||
assert set(expected_loaded_gpu_blocks) == loaded_gpu_blocks
|
||||
self.completed_loads.clear()
|
||||
|
||||
stored_gpu_blocks: set[GPUBlock] = set()
|
||||
for transfer in self.completed_stores:
|
||||
for gpu_block, offloaded_address in zip(
|
||||
transfer.gpu_blocks, transfer.offload_addresses
|
||||
):
|
||||
stored_gpu_blocks.add(gpu_block)
|
||||
self.offloaded[offloaded_address] = gpu_block
|
||||
|
||||
assert set(expected_stored_gpu_blocks) == stored_gpu_blocks
|
||||
self.completed_stores.clear()
|
||||
|
||||
assert set(expected_flushed_gpu_blocks) == self.flushed_gpu_blocks
|
||||
self.flushed_gpu_blocks.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def request_runner():
|
||||
runners = []
|
||||
|
||||
def runner_factory(
|
||||
block_size,
|
||||
num_gpu_blocks,
|
||||
async_scheduling,
|
||||
blocks_per_chunk=1,
|
||||
kv_cache_groups=None,
|
||||
extra_config_overrides=None,
|
||||
worker_count=1,
|
||||
retention_interval=None,
|
||||
speculative_config=None,
|
||||
):
|
||||
runner = RequestRunner(
|
||||
block_size=block_size,
|
||||
num_gpu_blocks=num_gpu_blocks,
|
||||
blocks_per_chunk=blocks_per_chunk,
|
||||
async_scheduling=async_scheduling,
|
||||
kv_cache_groups=kv_cache_groups,
|
||||
extra_config_overrides=extra_config_overrides,
|
||||
worker_count=worker_count,
|
||||
retention_interval=retention_interval,
|
||||
speculative_config=speculative_config,
|
||||
)
|
||||
runners.append(runner)
|
||||
return runner
|
||||
|
||||
yield runner_factory # pass factory to the test
|
||||
|
||||
|
||||
def generate_store_output(keys: Iterable[OffloadKey]):
|
||||
keys = list(keys)
|
||||
return PrepareStoreOutput(
|
||||
keys_to_store=list(keys),
|
||||
store_spec=MockLoadStoreSpec(keys),
|
||||
evicted_keys=[],
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,249 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.assets.image import ImageAsset
|
||||
from vllm.config import AttentionConfig, KVTransferConfig
|
||||
from vllm.multimodal.utils import encode_image_url
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
MODEL_NAME = "RedHatAI/Qwen2.5-VL-3B-Instruct-quantized.w8a8"
|
||||
|
||||
SAMPLING_PARAMS = SamplingParams(temperature=0.0, top_k=1, max_tokens=128)
|
||||
|
||||
TEXT_PROMPTS = [
|
||||
"What's in the image(s)? Around 30 words. What's special in 2nd image?",
|
||||
"The future of AI is",
|
||||
]
|
||||
|
||||
|
||||
class InputCase(NamedTuple):
|
||||
text: str
|
||||
img: list[Image]
|
||||
expected_len: int
|
||||
info: str
|
||||
|
||||
|
||||
def _check_path_len(path):
|
||||
"""Return the latest length in path."""
|
||||
return len(list(path.iterdir()))
|
||||
|
||||
|
||||
def _list_path(path):
|
||||
"""Return the list of foldername (hashes generated) under the path."""
|
||||
return list(path.iterdir())
|
||||
|
||||
|
||||
def run_test(
|
||||
tmp_path,
|
||||
processor,
|
||||
llm: LLM,
|
||||
question: str,
|
||||
image_urls: list[Image],
|
||||
expected_len: int,
|
||||
info: str,
|
||||
):
|
||||
"""One individual test to process the prompt and output base on 1 set of input
|
||||
Then check if the length in the storage path matches the expected length
|
||||
`info` introduces details or purpose of the individual test
|
||||
"""
|
||||
print(f"***info: {info}***")
|
||||
print(f"**Expected storage path length after llm generate: {expected_len}**")
|
||||
process_prompt(processor, llm, question, image_urls)
|
||||
|
||||
print(f"Path matched expected length: {_check_path_len(tmp_path)}")
|
||||
print(f"Hashes under the storage path: {_list_path(tmp_path)}")
|
||||
|
||||
assert _check_path_len(tmp_path) == expected_len, (
|
||||
f"Expect storage path length {expected_len} ;",
|
||||
f"but end up {_check_path_len(tmp_path)} instead. ",
|
||||
f"Info: {info}",
|
||||
)
|
||||
|
||||
|
||||
def process_prompt(processor, llm: LLM, question: str, image_urls: list[Image]):
|
||||
"""Form the prompt based on the text and image input, then llm generate output."""
|
||||
placeholders = [
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": encode_image_url(image_pil)},
|
||||
}
|
||||
for image_pil in image_urls
|
||||
]
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
*placeholders,
|
||||
{"type": "text", "text": question},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
prompt = processor.apply_chat_template(
|
||||
messages, tokenize=False, add_generation_prompt=True
|
||||
)
|
||||
|
||||
outputs = llm.generate(
|
||||
{
|
||||
"prompt": prompt,
|
||||
**({"multi_modal_data": {"image": [*image_urls]}} if image_urls else {}),
|
||||
},
|
||||
sampling_params=SAMPLING_PARAMS,
|
||||
)
|
||||
|
||||
print("-" * 50)
|
||||
print("Output:")
|
||||
for o in outputs:
|
||||
generated_text = o.outputs[0].text
|
||||
print(generated_text)
|
||||
print("-" * 50)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"attn_backend",
|
||||
(
|
||||
["FLASH_ATTN", "TRITON_ATTN"]
|
||||
if current_platform.is_cuda()
|
||||
else ["TRITON_ATTN"]
|
||||
if current_platform.is_rocm() or current_platform.is_xpu()
|
||||
else []
|
||||
),
|
||||
)
|
||||
def test_shared_storage_connector_hashes(tmp_path, attn_backend):
|
||||
"""Tests that ExampleConnector saves KV to the storage locations
|
||||
with proper hashes; that are unique for inputs with identical text but
|
||||
different images (same size), or same multiple images but different orders.
|
||||
"""
|
||||
# Using tmp_path as the storage path to store KV
|
||||
print(f"KV storage path at: {str(tmp_path)}")
|
||||
|
||||
# don't put this import at the top level
|
||||
# it will call torch.accelerator.device_count()
|
||||
from transformers import AutoProcessor
|
||||
|
||||
# Create processor to handle the chat prompt
|
||||
processor = AutoProcessor.from_pretrained(MODEL_NAME)
|
||||
|
||||
# Prepare images for the tests
|
||||
# Resize to the same size to check hashes correctness
|
||||
image_1 = ImageAsset("stop_sign").pil_image.resize((1280, 720))
|
||||
image_2 = ImageAsset("cherry_blossom").pil_image.resize((1280, 720))
|
||||
|
||||
# Make sure that they are not the same picture
|
||||
assert image_1 != image_2, "The images should not be identical"
|
||||
|
||||
# Create the LLM instance
|
||||
llm = LLM(
|
||||
model=MODEL_NAME,
|
||||
max_model_len=8192,
|
||||
max_num_seqs=1,
|
||||
gpu_memory_utilization=0.4,
|
||||
attention_config=AttentionConfig(backend=attn_backend),
|
||||
enforce_eager=True,
|
||||
kv_transfer_config=KVTransferConfig(
|
||||
kv_connector="ExampleConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"shared_storage_path": str(tmp_path)},
|
||||
),
|
||||
limit_mm_per_prompt={"image": 2},
|
||||
)
|
||||
|
||||
# Prepare the input cases
|
||||
input_cases = [
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_1],
|
||||
expected_len=1,
|
||||
info="image_1 single input the first time.",
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_2],
|
||||
expected_len=2,
|
||||
info=(
|
||||
"image_2 single input the first time. "
|
||||
"It is in same pixel size with image_1, yet it "
|
||||
"should be able to form a new unique hash."
|
||||
),
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_1],
|
||||
expected_len=2,
|
||||
info=(
|
||||
"image_1 single input the 2nd time. "
|
||||
"It should not form another new hash."
|
||||
),
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_2],
|
||||
expected_len=2,
|
||||
info=(
|
||||
"image_2 single input the 2nd time. "
|
||||
"It should not form another new hash."
|
||||
),
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_1, image_2],
|
||||
expected_len=3,
|
||||
info="image_1 with image_2 input the first time.",
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_2, image_1],
|
||||
expected_len=4,
|
||||
info="The image order is swapped. Should form new hash.",
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_1, image_2],
|
||||
expected_len=4,
|
||||
info=(
|
||||
"[image_1, image_2] input the 2nd time. "
|
||||
"It should not form another new hash."
|
||||
),
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[image_2, image_1],
|
||||
expected_len=4,
|
||||
info=(
|
||||
"[image_2, image_1] input the 2nd time. "
|
||||
"It should not form another new hash."
|
||||
),
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[],
|
||||
expected_len=5,
|
||||
info="Pure text input test as a case-control",
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[0],
|
||||
img=[],
|
||||
expected_len=5,
|
||||
info="Identical pure text input as a case-control",
|
||||
),
|
||||
InputCase(
|
||||
text=TEXT_PROMPTS[1],
|
||||
img=[],
|
||||
expected_len=6,
|
||||
info="Another pure text input as a case-control",
|
||||
),
|
||||
]
|
||||
|
||||
# Run tests
|
||||
for case_id, (text, img, expected_len, info) in enumerate(input_cases):
|
||||
print("\n", "=" * 25, f"Below running input case: {case_id}", "=" * 25)
|
||||
run_test(tmp_path, processor, llm, text, img, expected_len, info)
|
||||
|
||||
print("All tests passed successfully!")
|
||||
@@ -1,232 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for FlexKVConnectorV1.
|
||||
|
||||
These tests mock the ``flexkv`` package so they can run without a real FlexKV
|
||||
installation. They verify:
|
||||
|
||||
1. That ``FlexKVConnectorV1`` raises a helpful ``ImportError`` when FlexKV is
|
||||
not installed.
|
||||
2. That all public methods are correctly delegated to the underlying
|
||||
``FlexKVConnectorV1Impl``.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import types
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
from .utils import create_vllm_config
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_vllm_config(
|
||||
kv_connector: str = "FlexKVConnectorV1",
|
||||
kv_role: str = "kv_both",
|
||||
) -> VllmConfig:
|
||||
"""Return a minimal VllmConfig with a KVTransferConfig attached."""
|
||||
vllm_config = create_vllm_config(block_size=16, max_num_batched_tokens=512)
|
||||
vllm_config.kv_transfer_config = KVTransferConfig(
|
||||
kv_connector=kv_connector,
|
||||
kv_role=kv_role,
|
||||
)
|
||||
return vllm_config
|
||||
|
||||
|
||||
def _make_kv_cache_config() -> KVCacheConfig:
|
||||
return MagicMock(spec=KVCacheConfig)
|
||||
|
||||
|
||||
def _make_flexkv_module(
|
||||
impl_mock: MagicMock,
|
||||
) -> tuple[types.ModuleType, types.ModuleType]:
|
||||
"""Build a fake ``flexkv`` package hierarchy that returns *impl_mock*
|
||||
when ``FlexKVConnectorV1Impl`` is instantiated."""
|
||||
flexkv_mod = types.ModuleType("flexkv")
|
||||
integration_mod = types.ModuleType("flexkv.integration")
|
||||
vllm_mod = types.ModuleType("flexkv.integration.vllm")
|
||||
adapter_mod = types.ModuleType("flexkv.integration.vllm.vllm_v1_adapter")
|
||||
|
||||
# Make FlexKVConnectorV1Impl() return our mock instance.
|
||||
# The "# type: ignore" markers below are needed because ModuleType does
|
||||
# not declare these attributes statically; they are set dynamically.
|
||||
FlexKVConnectorV1ImplCls = MagicMock(return_value=impl_mock)
|
||||
adapter_mod.FlexKVConnectorV1Impl = FlexKVConnectorV1ImplCls # type: ignore
|
||||
|
||||
flexkv_mod.integration = integration_mod # type: ignore
|
||||
integration_mod.vllm = vllm_mod # type: ignore
|
||||
vllm_mod.vllm_v1_adapter = adapter_mod # type: ignore
|
||||
|
||||
return flexkv_mod, adapter_mod
|
||||
|
||||
|
||||
def _install_flexkv_mock(impl_mock: MagicMock):
|
||||
"""Insert fake flexkv modules into sys.modules and return a context that
|
||||
cleans them up afterwards."""
|
||||
flexkv_mod, adapter_mod = _make_flexkv_module(impl_mock)
|
||||
mods = {
|
||||
"flexkv": flexkv_mod,
|
||||
"flexkv.integration": flexkv_mod.integration,
|
||||
"flexkv.integration.vllm": flexkv_mod.integration.vllm,
|
||||
"flexkv.integration.vllm.vllm_v1_adapter": adapter_mod,
|
||||
}
|
||||
return patch.dict(sys.modules, mods)
|
||||
|
||||
|
||||
def _build_connector(vllm_config: VllmConfig, impl_mock: MagicMock):
|
||||
"""Instantiate FlexKVConnectorV1 with faked flexkv modules."""
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.flexkv_connector import (
|
||||
FlexKVConnectorV1,
|
||||
)
|
||||
|
||||
with _install_flexkv_mock(impl_mock):
|
||||
connector = FlexKVConnectorV1(
|
||||
vllm_config=vllm_config,
|
||||
role=KVConnectorRole.WORKER,
|
||||
kv_cache_config=_make_kv_cache_config(),
|
||||
)
|
||||
return connector
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFlexKVConnectorImportError:
|
||||
"""FlexKVConnectorV1 should fail with a helpful message when flexkv is
|
||||
absent."""
|
||||
|
||||
def test_import_error_message(self):
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.flexkv_connector import (
|
||||
FlexKVConnectorV1,
|
||||
)
|
||||
|
||||
# Ensure flexkv is NOT in sys.modules
|
||||
for key in list(sys.modules):
|
||||
if key.startswith("flexkv"):
|
||||
del sys.modules[key]
|
||||
|
||||
with pytest.raises(ImportError, match="(?i)flexkv") as exc_info:
|
||||
FlexKVConnectorV1(
|
||||
vllm_config=_make_vllm_config(),
|
||||
role=KVConnectorRole.WORKER,
|
||||
kv_cache_config=_make_kv_cache_config(),
|
||||
)
|
||||
|
||||
assert "https://github.com/taco-project/FlexKV" in str(exc_info.value)
|
||||
|
||||
|
||||
class TestFlexKVConnectorDelegation:
|
||||
"""All public API methods should be forwarded to the impl."""
|
||||
|
||||
@pytest.fixture()
|
||||
def connector_and_impl(self):
|
||||
impl = MagicMock()
|
||||
cfg = _make_vllm_config()
|
||||
connector = _build_connector(cfg, impl)
|
||||
return connector, impl
|
||||
|
||||
def test_shutdown(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
connector.shutdown()
|
||||
impl.shutdown.assert_called_once()
|
||||
|
||||
def test_start_load_kv(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
ctx = MagicMock()
|
||||
connector.start_load_kv(ctx, extra_arg="x")
|
||||
impl.start_load_kv.assert_called_once_with(ctx, extra_arg="x")
|
||||
|
||||
def test_save_kv_layer(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
kv_layer = torch.zeros(4, 4)
|
||||
attn_meta = MagicMock()
|
||||
connector.save_kv_layer("layer_0", kv_layer, attn_meta)
|
||||
impl.save_kv_layer.assert_called_once_with("layer_0", kv_layer, attn_meta)
|
||||
|
||||
def test_wait_for_save(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
connector.wait_for_save()
|
||||
impl.wait_for_save.assert_called_once()
|
||||
|
||||
def test_get_finished(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
impl.get_finished.return_value = ({"req1"}, None)
|
||||
result = connector.get_finished({"req1"})
|
||||
impl.get_finished.assert_called_once_with({"req1"})
|
||||
assert result == ({"req1"}, None)
|
||||
|
||||
def test_register_kv_caches(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
kv_caches = {"layer_0": torch.zeros(1)}
|
||||
connector.register_kv_caches(kv_caches)
|
||||
impl.register_kv_caches.assert_called_once_with(kv_caches)
|
||||
|
||||
def test_get_num_new_matched_tokens(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
req = MagicMock()
|
||||
impl.get_num_new_matched_tokens.return_value = (10, False)
|
||||
result = connector.get_num_new_matched_tokens(req, 5)
|
||||
impl.get_num_new_matched_tokens.assert_called_once_with(req, 5)
|
||||
assert result == (10, False)
|
||||
|
||||
def test_update_state_after_alloc(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
req = MagicMock()
|
||||
blocks = MagicMock()
|
||||
connector.update_state_after_alloc(req, blocks, 4)
|
||||
impl.update_state_after_alloc.assert_called_once_with(req, blocks, 4)
|
||||
|
||||
def test_build_connector_meta(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
sched_out = MagicMock()
|
||||
connector.build_connector_meta(sched_out)
|
||||
impl.build_connector_meta.assert_called_once_with(sched_out)
|
||||
|
||||
def test_update_connector_output(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
out = MagicMock()
|
||||
connector.update_connector_output(out)
|
||||
impl.update_connector_output.assert_called_once_with(out)
|
||||
|
||||
def test_request_finished(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
req = MagicMock()
|
||||
impl.request_finished.return_value = (True, {"key": "val"})
|
||||
result = connector.request_finished(req, [1, 2, 3])
|
||||
impl.request_finished.assert_called_once_with(req, [1, 2, 3])
|
||||
assert result == (True, {"key": "val"})
|
||||
|
||||
def test_take_events(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
impl.take_events.return_value = iter([])
|
||||
list(connector.take_events())
|
||||
impl.take_events.assert_called_once()
|
||||
|
||||
def test_get_kv_connector_stats(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
impl.get_kv_connector_stats.return_value = None
|
||||
result = connector.get_kv_connector_stats()
|
||||
impl.get_kv_connector_stats.assert_called_once()
|
||||
assert result is None
|
||||
|
||||
def test_get_block_ids_with_load_errors(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
impl.get_block_ids_with_load_errors.return_value = {7, 8}
|
||||
result = connector.get_block_ids_with_load_errors()
|
||||
assert result == {7, 8}
|
||||
|
||||
def test_wait_for_layer_load(self, connector_and_impl):
|
||||
connector, impl = connector_and_impl
|
||||
connector.wait_for_layer_load("layer_0")
|
||||
impl.wait_for_layer_load.assert_called_once_with("layer_0")
|
||||
@@ -1,107 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Regression tests for HMA auto-disable with KV transfer connectors."""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.config import DeviceConfig, KVTransferConfig, SchedulerConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_hybrid_kv_cache_supported(monkeypatch):
|
||||
monkeypatch.setattr(current_platform, "support_hybrid_kv_cache", lambda: True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kv_transfer_config,expect_disabled",
|
||||
[
|
||||
( # HMA-supporting connector → HMA stays enabled
|
||||
KVTransferConfig(
|
||||
kv_connector="SimpleCPUOffloadConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"cpu_bytes_to_use": 1 << 30},
|
||||
),
|
||||
False,
|
||||
),
|
||||
( # Non-HMA connector → HMA is auto-disabled
|
||||
KVTransferConfig(kv_connector="ExampleConnector", kv_role="kv_both"),
|
||||
True,
|
||||
),
|
||||
( # MultiConnector: all HMA children → HMA stays enabled
|
||||
KVTransferConfig(
|
||||
kv_connector="MultiConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={
|
||||
"connectors": [
|
||||
{
|
||||
"kv_connector": "SimpleCPUOffloadConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"cpu_bytes_to_use": 1 << 30},
|
||||
},
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"cpu_bytes_to_use": 1 << 30},
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
False,
|
||||
),
|
||||
( # MultiConnector: mixed children → HMA is auto-disabled
|
||||
KVTransferConfig(
|
||||
kv_connector="MultiConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={
|
||||
"connectors": [
|
||||
{
|
||||
"kv_connector": "SimpleCPUOffloadConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"cpu_bytes_to_use": 1 << 30},
|
||||
},
|
||||
{"kv_connector": "ExampleConnector", "kv_role": "kv_both"},
|
||||
]
|
||||
},
|
||||
),
|
||||
True,
|
||||
),
|
||||
],
|
||||
ids=["hma_connector", "non_hma_connector", "multi_all_hma", "multi_mixed"],
|
||||
)
|
||||
def test_hma_auto_config(kv_transfer_config, expect_disabled):
|
||||
vllm_config = VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
)
|
||||
assert (
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager is expect_disabled
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_hma_with_non_hma_connector_errors_at_factory():
|
||||
vllm_config = VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
scheduler_config=SchedulerConfig(
|
||||
max_model_len=16,
|
||||
is_encoder_decoder=False,
|
||||
disable_hybrid_kv_cache_manager=False,
|
||||
),
|
||||
kv_transfer_config=KVTransferConfig(
|
||||
kv_connector="ExampleConnector",
|
||||
kv_role="kv_both",
|
||||
),
|
||||
)
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[]
|
||||
)
|
||||
with pytest.raises(ValueError, match="does not support HMA but HMA is enabled"):
|
||||
KVConnectorFactory.create_connector(
|
||||
vllm_config, KVConnectorRole.SCHEDULER, kv_cache_config
|
||||
)
|
||||
@@ -1,816 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Iterator
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_events import BlockStored
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorMetadata
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.lmcache_connector import (
|
||||
LMCacheConnectorV1,
|
||||
LMCacheKVEvents,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_lmcache_engine_event():
|
||||
"""Create a mock event object that mimics what the lmcache engine returns."""
|
||||
|
||||
class MockEvent:
|
||||
def __init__(
|
||||
self,
|
||||
block_hashes,
|
||||
parent_block_hash,
|
||||
token_ids,
|
||||
lora_id,
|
||||
block_size,
|
||||
medium,
|
||||
lora_name,
|
||||
):
|
||||
self.block_hashes = block_hashes
|
||||
self.parent_block_hash = parent_block_hash
|
||||
self.token_ids = token_ids
|
||||
self.lora_id = lora_id
|
||||
self.block_size = block_size
|
||||
self.medium = medium
|
||||
self.lora_name = lora_name
|
||||
|
||||
return MockEvent(
|
||||
block_hashes=["hash1", "hash2"],
|
||||
parent_block_hash="parent_hash",
|
||||
token_ids=[1, 2, 3, 4],
|
||||
lora_id=None,
|
||||
block_size=16,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_connector():
|
||||
"""Create a mock LMCacheConnectorV1 instance with mocked dependencies."""
|
||||
connector = MagicMock(spec=LMCacheConnectorV1)
|
||||
connector._kv_cache_events = None
|
||||
connector._lmcache_engine = MagicMock()
|
||||
|
||||
# Make the methods use the real implementation
|
||||
connector.get_kv_connector_kv_cache_events = (
|
||||
LMCacheConnectorV1.get_kv_connector_kv_cache_events.__get__(
|
||||
connector, LMCacheConnectorV1
|
||||
)
|
||||
)
|
||||
connector.update_connector_output = (
|
||||
LMCacheConnectorV1.update_connector_output.__get__(
|
||||
connector, LMCacheConnectorV1
|
||||
)
|
||||
)
|
||||
connector.take_events = LMCacheConnectorV1.take_events.__get__(
|
||||
connector, LMCacheConnectorV1
|
||||
)
|
||||
|
||||
return connector
|
||||
|
||||
|
||||
class TestGetKVConnectorKVCacheEvents:
|
||||
"""Test get_kv_connector_kv_cache_events method."""
|
||||
|
||||
def test_returns_none_when_no_events(self, mock_connector):
|
||||
"""Test that None is returned when lmcache engine has no events."""
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = None
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert result is None
|
||||
mock_connector._lmcache_engine.get_kv_events.assert_called_once()
|
||||
|
||||
def test_returns_none_when_empty_list(self, mock_connector):
|
||||
"""Test that None is returned when lmcache engine returns empty list."""
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = []
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_converts_single_event(self, mock_connector, mock_lmcache_engine_event):
|
||||
"""Test conversion of a single event from lmcache engine format."""
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
mock_lmcache_engine_event
|
||||
]
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert result is not None
|
||||
assert isinstance(result, LMCacheKVEvents)
|
||||
assert result.get_number_of_workers() == 1
|
||||
|
||||
events = result.get_all_events()
|
||||
assert len(events) == 1
|
||||
assert isinstance(events[0], BlockStored)
|
||||
assert events[0].block_hashes == ["hash1", "hash2"]
|
||||
assert events[0].parent_block_hash == "parent_hash"
|
||||
assert events[0].token_ids == [1, 2, 3, 4]
|
||||
assert events[0].lora_id is None
|
||||
assert events[0].block_size == 16
|
||||
assert events[0].medium == "GPU"
|
||||
assert events[0].lora_name is None
|
||||
|
||||
def test_converts_multiple_events(self, mock_connector):
|
||||
"""Test conversion of multiple events from lmcache engine format."""
|
||||
|
||||
class MockEvent:
|
||||
def __init__(self, i):
|
||||
self.block_hashes = [f"hash{i}"]
|
||||
self.parent_block_hash = f"parent{i}"
|
||||
self.token_ids = [i]
|
||||
self.lora_id = None
|
||||
self.block_size = 16
|
||||
self.medium = "GPU"
|
||||
self.lora_name = None
|
||||
|
||||
events = [MockEvent(i) for i in range(5)]
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = events
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert result is not None
|
||||
assert isinstance(result, LMCacheKVEvents)
|
||||
|
||||
converted_events = result.get_all_events()
|
||||
assert len(converted_events) == 5
|
||||
|
||||
for i, event in enumerate(converted_events):
|
||||
assert isinstance(event, BlockStored)
|
||||
assert event.block_hashes == [f"hash{i}"]
|
||||
assert event.parent_block_hash == f"parent{i}"
|
||||
assert event.token_ids == [i]
|
||||
|
||||
def test_preserves_event_attributes(self, mock_connector):
|
||||
"""Test that all event attributes are correctly preserved."""
|
||||
|
||||
class MockEventWithLora:
|
||||
def __init__(self):
|
||||
self.block_hashes = ["hash_a", "hash_b", "hash_c"]
|
||||
self.parent_block_hash = "parent_xyz"
|
||||
self.token_ids = [100, 200, 300]
|
||||
self.lora_id = 42
|
||||
self.block_size = 32
|
||||
self.medium = "DISK"
|
||||
self.lora_name = "lora_example"
|
||||
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
MockEventWithLora()
|
||||
]
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
events = result.get_all_events()
|
||||
event = events[0]
|
||||
|
||||
assert event.block_hashes == ["hash_a", "hash_b", "hash_c"]
|
||||
assert event.parent_block_hash == "parent_xyz"
|
||||
assert event.token_ids == [100, 200, 300]
|
||||
assert event.lora_id == 42
|
||||
assert event.block_size == 32
|
||||
assert event.medium == "DISK"
|
||||
assert event.lora_name == "lora_example"
|
||||
|
||||
def test_handles_none_parent_block_hash(self, mock_connector):
|
||||
"""Test handling of events with None parent_block_hash."""
|
||||
|
||||
class MockEventNoParent:
|
||||
def __init__(self):
|
||||
self.block_hashes = ["hash1"]
|
||||
self.parent_block_hash = None
|
||||
self.token_ids = [1, 2]
|
||||
self.lora_id = None
|
||||
self.block_size = 16
|
||||
self.medium = "GPU"
|
||||
self.lora_name = None
|
||||
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
MockEventNoParent()
|
||||
]
|
||||
|
||||
result = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
events = result.get_all_events()
|
||||
assert events[0].parent_block_hash is None
|
||||
|
||||
|
||||
class TestUpdateConnectorOutput:
|
||||
"""Test update_connector_output method."""
|
||||
|
||||
def test_does_nothing_when_kv_cache_events_is_none(self, mock_connector):
|
||||
"""Test that method returns early when kv_cache_events is None."""
|
||||
connector_output = KVConnectorOutput(kv_cache_events=None)
|
||||
|
||||
mock_connector.update_connector_output(connector_output)
|
||||
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_does_nothing_when_kv_cache_events_is_not_lmcache_kv_events(
|
||||
self, mock_connector
|
||||
):
|
||||
"""Test that method returns early when kv_cache_events is not
|
||||
LMCacheKVEvents."""
|
||||
# Create a mock object that is not LMCacheKVEvents
|
||||
fake_events = MagicMock()
|
||||
connector_output = KVConnectorOutput(kv_cache_events=fake_events)
|
||||
|
||||
mock_connector.update_connector_output(connector_output)
|
||||
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_sets_kv_cache_events_when_none(self, mock_connector):
|
||||
"""Test that _kv_cache_events is set when it was None."""
|
||||
kv_events = LMCacheKVEvents(num_workers=1)
|
||||
event = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1, 2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
kv_events.add_events([event])
|
||||
|
||||
connector_output = KVConnectorOutput(kv_cache_events=kv_events)
|
||||
|
||||
mock_connector.update_connector_output(connector_output)
|
||||
|
||||
assert mock_connector._kv_cache_events is kv_events
|
||||
|
||||
def test_adds_events_when_kv_cache_events_already_exists(self, mock_connector):
|
||||
"""Test that events are added when _kv_cache_events already exists."""
|
||||
# Set up existing events
|
||||
existing_events = LMCacheKVEvents(num_workers=2)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
existing_events.add_events([event1])
|
||||
existing_events.add_events([event1]) # Simulate 2 workers reporting
|
||||
|
||||
mock_connector._kv_cache_events = existing_events
|
||||
|
||||
# Create new events to add
|
||||
new_events = LMCacheKVEvents(num_workers=1)
|
||||
event2 = BlockStored(
|
||||
block_hashes=["hash2"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
new_events.add_events([event2])
|
||||
|
||||
connector_output = KVConnectorOutput(kv_cache_events=new_events)
|
||||
|
||||
mock_connector.update_connector_output(connector_output)
|
||||
|
||||
# Check that events were added
|
||||
all_events = mock_connector._kv_cache_events.get_all_events()
|
||||
assert len(all_events) == 3 # 2 from existing + 1 from new
|
||||
assert event1 in all_events
|
||||
assert event2 in all_events
|
||||
|
||||
def test_increments_workers_when_kv_cache_events_already_exists(
|
||||
self, mock_connector
|
||||
):
|
||||
"""Test that worker count is incremented correctly."""
|
||||
# Set up existing events with 2 workers
|
||||
existing_events = LMCacheKVEvents(num_workers=2)
|
||||
mock_connector._kv_cache_events = existing_events
|
||||
|
||||
# Create new events from 3 workers
|
||||
new_events = LMCacheKVEvents(num_workers=3)
|
||||
event = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
new_events.add_events([event])
|
||||
|
||||
connector_output = KVConnectorOutput(kv_cache_events=new_events)
|
||||
|
||||
mock_connector.update_connector_output(connector_output)
|
||||
|
||||
# Worker count should be 2 + 3 = 5
|
||||
assert mock_connector._kv_cache_events.get_number_of_workers() == 5
|
||||
|
||||
def test_multiple_updates(self, mock_connector):
|
||||
"""Test multiple consecutive updates."""
|
||||
# First update
|
||||
events1 = LMCacheKVEvents(num_workers=1)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
events1.add_events([event1])
|
||||
output1 = KVConnectorOutput(kv_cache_events=events1)
|
||||
mock_connector.update_connector_output(output1)
|
||||
|
||||
# Second update
|
||||
events2 = LMCacheKVEvents(num_workers=2)
|
||||
event2 = BlockStored(
|
||||
block_hashes=["hash2"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
events2.add_events([event2])
|
||||
output2 = KVConnectorOutput(kv_cache_events=events2)
|
||||
mock_connector.update_connector_output(output2)
|
||||
|
||||
# Third update
|
||||
events3 = LMCacheKVEvents(num_workers=1)
|
||||
event3 = BlockStored(
|
||||
block_hashes=["hash3"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[3],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
events3.add_events([event3])
|
||||
output3 = KVConnectorOutput(kv_cache_events=events3)
|
||||
mock_connector.update_connector_output(output3)
|
||||
|
||||
# Check final state
|
||||
all_events = mock_connector._kv_cache_events.get_all_events()
|
||||
assert len(all_events) == 3
|
||||
assert mock_connector._kv_cache_events.get_number_of_workers() == 4 # 1+2+1
|
||||
|
||||
def test_updates_with_empty_events(self, mock_connector):
|
||||
"""Test updating with empty event lists."""
|
||||
# First update with actual events
|
||||
events1 = LMCacheKVEvents(num_workers=1)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
events1.add_events([event1])
|
||||
output1 = KVConnectorOutput(kv_cache_events=events1)
|
||||
mock_connector.update_connector_output(output1)
|
||||
|
||||
# Second update with empty events
|
||||
events2 = LMCacheKVEvents(num_workers=2)
|
||||
# No events added
|
||||
output2 = KVConnectorOutput(kv_cache_events=events2)
|
||||
mock_connector.update_connector_output(output2)
|
||||
|
||||
# Should still have the original event
|
||||
all_events = mock_connector._kv_cache_events.get_all_events()
|
||||
assert len(all_events) == 1
|
||||
assert mock_connector._kv_cache_events.get_number_of_workers() == 3
|
||||
|
||||
|
||||
class TestTakeEvents:
|
||||
"""Test take_events method."""
|
||||
|
||||
def test_yields_nothing_when_kv_cache_events_is_none(self, mock_connector):
|
||||
"""Test that nothing is yielded when _kv_cache_events is None."""
|
||||
mock_connector._kv_cache_events = None
|
||||
|
||||
events = list(mock_connector.take_events())
|
||||
|
||||
assert events == []
|
||||
|
||||
def test_yields_events_and_clears(self, mock_connector):
|
||||
"""Test that events are yielded and then cleared."""
|
||||
# Set up events
|
||||
kv_events = LMCacheKVEvents(num_workers=1)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
event2 = BlockStored(
|
||||
block_hashes=["hash2"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
kv_events.add_events([event1, event2])
|
||||
mock_connector._kv_cache_events = kv_events
|
||||
|
||||
# Take events
|
||||
events = list(mock_connector.take_events())
|
||||
|
||||
# Check that events were yielded
|
||||
assert len(events) == 2
|
||||
assert event1 in events
|
||||
assert event2 in events
|
||||
|
||||
# Check that _kv_cache_events was cleared
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_aggregates_before_yielding(self, mock_connector):
|
||||
"""Test that events are aggregated before yielding."""
|
||||
# Set up events from multiple workers
|
||||
kv_events = LMCacheKVEvents(num_workers=3)
|
||||
common_event = BlockStored(
|
||||
block_hashes=["hash_common"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
uncommon_event = BlockStored(
|
||||
block_hashes=["hash_uncommon"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
# All 3 workers report common_event
|
||||
kv_events.add_events([common_event])
|
||||
kv_events.add_events([common_event])
|
||||
kv_events.add_events([common_event])
|
||||
|
||||
# Only 1 worker reports uncommon_event
|
||||
kv_events.add_events([uncommon_event])
|
||||
|
||||
mock_connector._kv_cache_events = kv_events
|
||||
|
||||
# Take events
|
||||
events = list(mock_connector.take_events())
|
||||
|
||||
# Only the common event should be yielded
|
||||
assert len(events) == 1
|
||||
assert events[0] == common_event
|
||||
|
||||
def test_multiple_take_events_calls(self, mock_connector):
|
||||
"""Test calling take_events multiple times."""
|
||||
# First call with events
|
||||
kv_events1 = LMCacheKVEvents(num_workers=1)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
kv_events1.add_events([event1])
|
||||
mock_connector._kv_cache_events = kv_events1
|
||||
|
||||
events1 = list(mock_connector.take_events())
|
||||
assert len(events1) == 1
|
||||
assert events1[0] == event1
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
# Second call with no events
|
||||
events2 = list(mock_connector.take_events())
|
||||
assert events2 == []
|
||||
|
||||
# Third call after adding new events
|
||||
kv_events2 = LMCacheKVEvents(num_workers=1)
|
||||
event2 = BlockStored(
|
||||
block_hashes=["hash2"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
kv_events2.add_events([event2])
|
||||
mock_connector._kv_cache_events = kv_events2
|
||||
|
||||
events3 = list(mock_connector.take_events())
|
||||
assert len(events3) == 1
|
||||
assert events3[0] == event2
|
||||
|
||||
def test_yields_empty_after_aggregation_removes_all(self, mock_connector):
|
||||
"""Test that nothing is yielded if aggregation removes all events."""
|
||||
# Set up events from 2 workers with no common events
|
||||
kv_events = LMCacheKVEvents(num_workers=2)
|
||||
event1 = BlockStored(
|
||||
block_hashes=["hash1"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[1],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
event2 = BlockStored(
|
||||
block_hashes=["hash2"],
|
||||
parent_block_hash=None,
|
||||
token_ids=[2],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
# Worker 1 reports event1
|
||||
kv_events.add_events([event1])
|
||||
# Worker 2 reports event2
|
||||
kv_events.add_events([event2])
|
||||
|
||||
mock_connector._kv_cache_events = kv_events
|
||||
|
||||
# Take events
|
||||
events = list(mock_connector.take_events())
|
||||
|
||||
# No common events, so nothing should be yielded
|
||||
assert events == []
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
|
||||
class TestIntegrationScenarios:
|
||||
"""Test integration scenarios."""
|
||||
|
||||
def test_full_workflow(self, mock_connector, mock_lmcache_engine_event):
|
||||
"""Test a complete workflow from getting events to taking them."""
|
||||
# Step 1: Get events from lmcache engine
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
mock_lmcache_engine_event
|
||||
]
|
||||
kv_events = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert kv_events is not None
|
||||
assert len(kv_events.get_all_events()) == 1
|
||||
|
||||
# Step 2: Update connector output (simulate receiving from worker)
|
||||
output1 = KVConnectorOutput(kv_cache_events=kv_events)
|
||||
mock_connector.update_connector_output(output1)
|
||||
|
||||
assert mock_connector._kv_cache_events is not None
|
||||
|
||||
# Step 3: Take events
|
||||
taken_events = list(mock_connector.take_events())
|
||||
|
||||
assert len(taken_events) == 1
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_multiple_workers_workflow(self, mock_connector):
|
||||
"""Test workflow with multiple workers."""
|
||||
|
||||
class MockEvent:
|
||||
def __init__(self, hash_val):
|
||||
self.block_hashes = [hash_val]
|
||||
self.parent_block_hash = None
|
||||
self.token_ids = [1]
|
||||
self.lora_id = None
|
||||
self.block_size = 16
|
||||
self.medium = "GPU"
|
||||
self.lora_name = None
|
||||
|
||||
# Worker 1
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
MockEvent("hash_common"),
|
||||
MockEvent("hash_worker1"),
|
||||
]
|
||||
kv_events1 = mock_connector.get_kv_connector_kv_cache_events()
|
||||
output1 = KVConnectorOutput(kv_cache_events=kv_events1)
|
||||
mock_connector.update_connector_output(output1)
|
||||
|
||||
# Worker 2
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
MockEvent("hash_common"),
|
||||
MockEvent("hash_worker2"),
|
||||
]
|
||||
kv_events2 = mock_connector.get_kv_connector_kv_cache_events()
|
||||
output2 = KVConnectorOutput(kv_cache_events=kv_events2)
|
||||
mock_connector.update_connector_output(output2)
|
||||
|
||||
# Take events (should only get common events)
|
||||
taken_events = list(mock_connector.take_events())
|
||||
|
||||
# With aggregation, only events reported by both workers should be present
|
||||
# In this case, hash_common was reported by both
|
||||
event_hashes = [e.block_hashes[0] for e in taken_events]
|
||||
assert "hash_common" in event_hashes
|
||||
|
||||
def test_empty_workflow(self, mock_connector):
|
||||
"""Test workflow when there are no events at any stage."""
|
||||
# Get events returns None
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = None
|
||||
kv_events = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
assert kv_events is None
|
||||
|
||||
# Update with None
|
||||
output = KVConnectorOutput(kv_cache_events=None)
|
||||
mock_connector.update_connector_output(output)
|
||||
|
||||
# Take events
|
||||
taken_events = list(mock_connector.take_events())
|
||||
|
||||
assert taken_events == []
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_repeated_cycles(self, mock_connector):
|
||||
"""Test multiple cycles of the complete workflow."""
|
||||
|
||||
class MockEvent:
|
||||
def __init__(self, cycle_num):
|
||||
self.block_hashes = [f"hash_cycle_{cycle_num}"]
|
||||
self.parent_block_hash = None
|
||||
self.token_ids = [cycle_num]
|
||||
self.lora_id = None
|
||||
self.block_size = 16
|
||||
self.medium = "GPU"
|
||||
self.lora_name = None
|
||||
|
||||
for cycle in range(3):
|
||||
# Get events
|
||||
mock_connector._lmcache_engine.get_kv_events.return_value = [
|
||||
MockEvent(cycle)
|
||||
]
|
||||
kv_events = mock_connector.get_kv_connector_kv_cache_events()
|
||||
|
||||
# Update
|
||||
output = KVConnectorOutput(kv_cache_events=kv_events)
|
||||
mock_connector.update_connector_output(output)
|
||||
|
||||
# Take
|
||||
taken_events = list(mock_connector.take_events())
|
||||
|
||||
# Verify
|
||||
assert len(taken_events) == 1
|
||||
assert taken_events[0].block_hashes[0] == f"hash_cycle_{cycle}"
|
||||
assert mock_connector._kv_cache_events is None
|
||||
|
||||
def test_lmcache_kv_events_aggregation(self):
|
||||
"""Test LMCacheKVEvents aggregation across TP ranks using
|
||||
KVOutputAggregator (used by MultiprocExecutor).
|
||||
"""
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import KVOutputAggregator
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
|
||||
# Create KVOutputAggregator for 3 workers (simulating TP=3)
|
||||
aggregator = KVOutputAggregator(expected_finished_count=3)
|
||||
|
||||
# Define common and unique events
|
||||
common_event = BlockStored(
|
||||
block_hashes=["hash_common"],
|
||||
parent_block_hash="parent_common",
|
||||
token_ids=[1, 2, 3],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
worker1_unique_event = BlockStored(
|
||||
block_hashes=["hash_worker1"],
|
||||
parent_block_hash="parent_w1",
|
||||
token_ids=[4, 5],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
worker2_unique_event = BlockStored(
|
||||
block_hashes=["hash_worker2"],
|
||||
parent_block_hash="parent_w2",
|
||||
token_ids=[6, 7],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
worker3_unique_event = BlockStored(
|
||||
block_hashes=["hash_worker3"],
|
||||
parent_block_hash="parent_w3",
|
||||
token_ids=[8, 9],
|
||||
block_size=16,
|
||||
lora_id=None,
|
||||
medium="GPU",
|
||||
lora_name=None,
|
||||
)
|
||||
|
||||
# Create events for each worker
|
||||
# Worker 0: reports common event and its unique event
|
||||
worker0_events = LMCacheKVEvents(num_workers=1)
|
||||
worker0_events.add_events([common_event, worker1_unique_event])
|
||||
|
||||
# Worker 1: reports common event and its unique event
|
||||
worker1_events = LMCacheKVEvents(num_workers=1)
|
||||
worker1_events.add_events([common_event, worker2_unique_event])
|
||||
|
||||
# Worker 2: reports common event and its unique event
|
||||
worker2_events = LMCacheKVEvents(num_workers=1)
|
||||
worker2_events.add_events([common_event, worker3_unique_event])
|
||||
|
||||
# Create ModelRunnerOutput instances for each worker
|
||||
worker_outputs = []
|
||||
for i, worker_events in enumerate(
|
||||
[worker0_events, worker1_events, worker2_events]
|
||||
):
|
||||
output = ModelRunnerOutput(
|
||||
req_ids=[f"req_{i}"],
|
||||
req_id_to_index={f"req_{i}": 0},
|
||||
sampled_token_ids=[[123]], # dummy token
|
||||
logprobs=None,
|
||||
prompt_logprobs_dict={},
|
||||
pooler_output=[None],
|
||||
kv_connector_output=KVConnectorOutput(
|
||||
finished_sending=set([f"req_{i}_send"])
|
||||
if i < 2
|
||||
else None, # Workers 0,1 finished sending
|
||||
finished_recving=set([f"req_{i}_recv"])
|
||||
if i > 0
|
||||
else None, # Workers 1,2 finished receiving
|
||||
kv_cache_events=worker_events,
|
||||
),
|
||||
)
|
||||
worker_outputs.append(output)
|
||||
|
||||
# Use the real aggregation mechanism (like MultiprocExecutor.execute_model)
|
||||
aggregated_output = aggregator.aggregate(worker_outputs, output_rank=0)
|
||||
kv_cache_events = aggregated_output.kv_connector_output.kv_cache_events
|
||||
|
||||
assert isinstance(kv_cache_events, LMCacheKVEvents)
|
||||
|
||||
# After aggregation, events should be combined from all workers
|
||||
# The aggregator doesn't automatically aggregate events, so we need to call
|
||||
# aggregate() to get only common events
|
||||
kv_cache_events.aggregate()
|
||||
aggregated_events = kv_cache_events.get_all_events()
|
||||
|
||||
# Only the common event should remain after aggregation
|
||||
# because it's the only event reported by all 3 workers
|
||||
assert len(aggregated_events) == 1
|
||||
assert aggregated_events[0] == common_event
|
||||
|
||||
# Verify the common event properties
|
||||
assert aggregated_events[0].block_hashes == ["hash_common"]
|
||||
assert aggregated_events[0].parent_block_hash == "parent_common"
|
||||
assert aggregated_events[0].token_ids == [1, 2, 3]
|
||||
|
||||
|
||||
def test_legacy_layerwise_engine_does_not_reuse_storers_on_empty_steps():
|
||||
"""Empty steps must not advance generators exhausted by the last forward."""
|
||||
|
||||
class LegacyLayerwiseEngine:
|
||||
layerwise_storers: list[Iterator[None]]
|
||||
|
||||
def save_kv_layer(self, *args, **kwargs):
|
||||
self.layerwise_storers.append(iter([None]))
|
||||
|
||||
def wait_for_save(self):
|
||||
for storer in self.layerwise_storers:
|
||||
next(storer)
|
||||
|
||||
connector = LMCacheConnectorV1.__new__(LMCacheConnectorV1)
|
||||
connector._lmcache_engine = LegacyLayerwiseEngine()
|
||||
metadata = KVConnectorMetadata()
|
||||
connector.bind_connector_metadata(metadata)
|
||||
connector.save_kv_layer("layer", MagicMock(), MagicMock())
|
||||
connector.wait_for_save()
|
||||
connector.clear_connector_metadata()
|
||||
|
||||
for _ in range(2):
|
||||
connector.bind_connector_metadata(metadata)
|
||||
connector.wait_for_save()
|
||||
connector.clear_connector_metadata()
|
||||
|
||||
assert connector._lmcache_engine.layerwise_storers == []
|
||||
@@ -1,229 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# NOTE: if your PR has broken one of the tests here (sorry),
|
||||
# kindly patch the corresponding integration in
|
||||
# /vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/vllm_v1_adapter.py
|
||||
# or reach out to @aposataC for assistance
|
||||
|
||||
# Assumption vs. Correctness Tests:
|
||||
# these unit tests do *not* test correctness of LMCache-side or vLLM-side logic
|
||||
# it is to ensure that assumptions LMCache makes about vLLM's interface are stable
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
|
||||
def assumes(obj, attr, is_callable=False, is_instance_of=None):
|
||||
import inspect
|
||||
from dataclasses import is_dataclass
|
||||
|
||||
assumption_msg = (
|
||||
f"LMCache connector currently assumes that {obj} has a(n) {attr} attribute"
|
||||
)
|
||||
if hasattr(obj, attr):
|
||||
attr_value = getattr(obj, attr)
|
||||
elif is_dataclass(obj) and attr in getattr(obj, "__dataclass_fields__", {}):
|
||||
field = obj.__dataclass_fields__[attr]
|
||||
field_type = field.type
|
||||
origin = getattr(field_type, "__origin__", None)
|
||||
if origin is not None:
|
||||
field_type = origin
|
||||
attr_value = field_type
|
||||
else:
|
||||
raise AssertionError(assumption_msg)
|
||||
if is_callable:
|
||||
assumption_msg += f" and that {obj}.{attr} is a callable"
|
||||
assert callable(attr_value), assumption_msg
|
||||
if is_instance_of:
|
||||
assumption_msg += f" and that {obj}.{attr} is an instance of {is_instance_of}"
|
||||
if isinstance(attr_value, property):
|
||||
fget = attr_value.fget
|
||||
assert fget is not None, f"Property {obj}.{attr} has no fget"
|
||||
sig = inspect.signature(fget)
|
||||
ret_anno = sig.return_annotation
|
||||
assert ret_anno is not inspect._empty, (
|
||||
f"Property {obj}.{attr} has no return annotation"
|
||||
)
|
||||
assert ret_anno == is_instance_of, assumption_msg
|
||||
else:
|
||||
if isinstance(attr_value, type):
|
||||
assert attr_value is is_instance_of, assumption_msg
|
||||
else:
|
||||
assert isinstance(attr_value, is_instance_of), assumption_msg
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_rocm(), reason="Requires libcudart.so, not available on ROCm"
|
||||
)
|
||||
def test_multimodal_interface():
|
||||
# protect against interface changes
|
||||
from vllm.multimodal.inputs import PlaceholderRange
|
||||
|
||||
assumes(PlaceholderRange, "offset")
|
||||
assumes(PlaceholderRange, "length")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_rocm(), reason="Requires libcudart.so, not available on ROCm"
|
||||
)
|
||||
def test_config_interface():
|
||||
# protect against interface changes
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheConfig
|
||||
from vllm.config.kv_transfer import KVTransferConfig
|
||||
from vllm.config.model import ModelConfig
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
|
||||
assumes(VllmConfig, "model_config")
|
||||
assumes(VllmConfig, "cache_config")
|
||||
assumes(VllmConfig, "parallel_config")
|
||||
assumes(VllmConfig, "kv_transfer_config")
|
||||
|
||||
assumes(KVTransferConfig, "kv_role")
|
||||
assumes(KVTransferConfig, "kv_connector_extra_config")
|
||||
|
||||
assumes(ModelConfig, "use_mla", is_instance_of=bool)
|
||||
assumes(ModelConfig, "dtype")
|
||||
assumes(ModelConfig, "max_model_len")
|
||||
assumes(ModelConfig, "get_vocab_size", is_callable=True)
|
||||
assumes(ModelConfig, "get_num_attention_heads", is_callable=True)
|
||||
assumes(ModelConfig, "get_num_kv_heads", is_callable=True)
|
||||
assumes(ModelConfig, "get_head_size", is_callable=True)
|
||||
assumes(ModelConfig, "get_num_layers", is_callable=True)
|
||||
assumes(ModelConfig, "get_num_kv_heads", is_callable=True)
|
||||
assumes(ModelConfig, "model")
|
||||
|
||||
assumes(ParallelConfig, "world_size")
|
||||
assumes(ParallelConfig, "rank")
|
||||
assumes(ParallelConfig, "tensor_parallel_size")
|
||||
assumes(ParallelConfig, "pipeline_parallel_size")
|
||||
assumes(ParallelConfig, "data_parallel_size_local")
|
||||
assumes(ParallelConfig, "data_parallel_rank_local")
|
||||
|
||||
assumes(CacheConfig, "cache_dtype")
|
||||
assumes(CacheConfig, "block_size")
|
||||
assumes(CacheConfig, "gpu_memory_utilization")
|
||||
|
||||
# kv metadata minimal case
|
||||
from vllm.utils.torch_utils import get_kv_cache_torch_dtype
|
||||
|
||||
model_config = ModelConfig(dtype="bfloat16")
|
||||
parallel_config = ParallelConfig()
|
||||
cache_config = CacheConfig(cache_dtype="bfloat16")
|
||||
kv_dtype = get_kv_cache_torch_dtype(cache_config.cache_dtype, model_config.dtype)
|
||||
use_mla = False
|
||||
chunk_size = 256
|
||||
num_layer = model_config.get_num_layers(parallel_config)
|
||||
num_kv_head = model_config.get_num_kv_heads(parallel_config)
|
||||
head_size = model_config.get_head_size()
|
||||
kv_shape = (num_layer, 1 if use_mla else 2, chunk_size, num_kv_head, head_size)
|
||||
|
||||
# dummy lmcache metadata creation example
|
||||
_ = (
|
||||
model_config.model,
|
||||
parallel_config.world_size,
|
||||
parallel_config.rank,
|
||||
"vllm",
|
||||
kv_dtype,
|
||||
kv_shape,
|
||||
use_mla,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
current_platform.is_rocm(), reason="Requires libcudart.so, not available on ROCm"
|
||||
)
|
||||
def test_request_interface():
|
||||
# protect against interface changes
|
||||
from types import NoneType
|
||||
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.request import Request
|
||||
|
||||
sampling_params = SamplingParams(max_tokens=10)
|
||||
sampling_params.update_from_generation_config({}, eos_token_id=100)
|
||||
|
||||
req = Request(
|
||||
request_id="test_request",
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
lora_request=None,
|
||||
)
|
||||
assumes(req, "mm_features", is_instance_of=(list, NoneType))
|
||||
assumes(req, "request_id")
|
||||
assumes(req, "priority")
|
||||
assumes(req, "prompt_token_ids")
|
||||
assumes(req, "sampling_params")
|
||||
assumes(req, "num_tokens")
|
||||
assumes(req, "kv_transfer_params", is_instance_of=(dict, NoneType))
|
||||
|
||||
from vllm.multimodal.inputs import MultiModalFeatureSpec
|
||||
|
||||
assumes(MultiModalFeatureSpec, "identifier")
|
||||
assumes(MultiModalFeatureSpec, "mm_position")
|
||||
|
||||
|
||||
def test_new_request_interface():
|
||||
# protect against interface changes
|
||||
from vllm.v1.core.sched.output import NewRequestData
|
||||
|
||||
assumes(NewRequestData, "req_id")
|
||||
assumes(NewRequestData, "block_ids")
|
||||
assumes(NewRequestData, "prompt_token_ids")
|
||||
assumes(NewRequestData, "sampling_params")
|
||||
|
||||
|
||||
def test_sampling_params_interface():
|
||||
# protect against interface changes
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
assumes(SamplingParams, "extra_args")
|
||||
|
||||
# dumb example use case in LMCache
|
||||
kv_transfer_params = {
|
||||
"lmcache.tag.user": "example_user_1",
|
||||
"lmcache.ttl": 60,
|
||||
}
|
||||
sampling_params = SamplingParams(
|
||||
extra_args={"kv_transfer_params": kv_transfer_params}
|
||||
)
|
||||
assert sampling_params.extra_args["kv_transfer_params"] == kv_transfer_params
|
||||
|
||||
|
||||
def test_tp_interface():
|
||||
# protect against interface changes
|
||||
import inspect
|
||||
|
||||
from vllm.distributed.parallel_state import get_tp_group
|
||||
|
||||
sig = inspect.signature(get_tp_group)
|
||||
GroupCoordinator = sig.return_annotation
|
||||
|
||||
assumes(GroupCoordinator, "broadcast", is_callable=True)
|
||||
assumes(GroupCoordinator, "broadcast_object", is_callable=True)
|
||||
|
||||
|
||||
def test_forward_context_interface():
|
||||
# protect against interface changes
|
||||
from vllm.forward_context import ForwardContext
|
||||
|
||||
assumes(ForwardContext, "no_compile_layers", is_instance_of=dict)
|
||||
assumes(ForwardContext, "attn_metadata")
|
||||
|
||||
|
||||
def test_scheduler_output_interface():
|
||||
# protect against interface changes
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
|
||||
assumes(SchedulerOutput, "finished_req_ids")
|
||||
assumes(SchedulerOutput, "scheduled_new_reqs", is_instance_of=list)
|
||||
assumes(SchedulerOutput, "num_scheduled_tokens", is_instance_of=dict)
|
||||
assumes(SchedulerOutput, "scheduled_cached_reqs")
|
||||
|
||||
from vllm.v1.core.sched.output import CachedRequestData
|
||||
|
||||
assumes(CachedRequestData, "req_ids", is_instance_of=list)
|
||||
assumes(CachedRequestData, "new_block_ids", is_instance_of=list)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,555 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for MooncakeConnector HMA (Hybrid Memory Architecture) support.
|
||||
|
||||
Covers sliding-window clipping, multi-group metadata shape, multi-group
|
||||
send trimming, and group-count invariant checking in _build_transfer_params.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import (
|
||||
KVConnectorRole,
|
||||
MooncakeConnector,
|
||||
MooncakeConnectorMetadata,
|
||||
MooncakeConnectorScheduler,
|
||||
MooncakeXferMetadata,
|
||||
PullReqMeta,
|
||||
SendBlockMeta,
|
||||
TransferRegion,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
)
|
||||
|
||||
from .test_mooncake_connector import FakeMooncakeWrapper, patch_worker_dependencies
|
||||
from .utils import (
|
||||
create_request,
|
||||
create_vllm_config,
|
||||
make_kv_cache_config,
|
||||
maybe_update_block_size,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_sw_sizes: blocks_per_sw computed from KVCacheConfig
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
"swa_enabled,expected_blocks_per_sw",
|
||||
[
|
||||
# SWA enabled: FullAttentionSpec (0) + SlidingWindowSpec (2048/16=128+1)
|
||||
(True, [0, 128 + 1]),
|
||||
# SWA disabled: only FullAttentionSpec (0)
|
||||
(False, [0]),
|
||||
],
|
||||
)
|
||||
def test_sw_sizes(swa_enabled, expected_blocks_per_sw):
|
||||
"""blocks_per_sw is correctly computed based on SWA enabled/disabled."""
|
||||
block_size = 16
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_both",
|
||||
block_size=block_size,
|
||||
)
|
||||
# Override so HMA detection works
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=block_size, swa_enabled=swa_enabled, sw_size=2048
|
||||
)
|
||||
|
||||
scheduler = MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
assert scheduler.blocks_per_sw == expected_blocks_per_sw
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_is_hma_required: derived from kv_cache_config groups
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
"swa_enabled,disable_hma,expected_is_hma",
|
||||
[
|
||||
(True, False, True), # SWA group present, HMA enabled
|
||||
(True, True, False), # SWA group present, but HMA disabled
|
||||
(False, False, False), # FA only, HMA not needed
|
||||
],
|
||||
)
|
||||
def test_is_hma_required(swa_enabled, disable_hma, expected_is_hma):
|
||||
"""_is_hma_required is correctly derived from kv_cache_config."""
|
||||
block_size = 16
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_both",
|
||||
block_size=block_size,
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = disable_hma
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=block_size, swa_enabled=swa_enabled
|
||||
)
|
||||
|
||||
scheduler = MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
assert scheduler._is_hma_required is expected_is_hma
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_get_sw_clipped_blocks: sliding-window clipping logic
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.cpu_test
|
||||
def test_get_sw_clipped_blocks():
|
||||
"""get_sw_clipped_blocks clips SWA group but keeps FA group intact."""
|
||||
block_size = 16
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_both",
|
||||
block_size=block_size,
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
# SW=128 tokens → 128/16 = 8 blocks + 1 = 9 blocks_per_sw
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=block_size, swa_enabled=True, sw_size=128
|
||||
)
|
||||
|
||||
scheduler = MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
assert scheduler.blocks_per_sw == [0, 9]
|
||||
|
||||
# FA group: 20 blocks, SW group: 20 blocks (exceeds window)
|
||||
fa_blocks = list(range(20))
|
||||
sw_blocks = list(range(100, 120))
|
||||
block_ids = (fa_blocks, sw_blocks)
|
||||
|
||||
clipped = scheduler.get_sw_clipped_blocks(block_ids)
|
||||
|
||||
# FA: untouched (blocks_per_sw[0] = 0)
|
||||
assert clipped[0] == fa_blocks
|
||||
# SW: clipped to last 9 blocks
|
||||
assert clipped[1] == sw_blocks[-9:]
|
||||
assert len(clipped[1]) == 9
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_get_sw_clipped_blocks_noop_no_hma():
|
||||
"""get_sw_clipped_blocks is a no-op when HMA is not required."""
|
||||
block_size = 16
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_both",
|
||||
block_size=block_size,
|
||||
)
|
||||
# FA only → _is_hma_required = False
|
||||
kv_cache_config = make_kv_cache_config(block_size=block_size, swa_enabled=False)
|
||||
|
||||
scheduler = MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
assert scheduler._is_hma_required is False
|
||||
|
||||
block_ids = ([1, 2, 3],)
|
||||
clipped = scheduler.get_sw_clipped_blocks(block_ids)
|
||||
assert clipped == [[1, 2, 3]]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_metadata_hma_block_ids: MooncakeConnectorMetadata stores per-group IDs
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.cpu_test
|
||||
def test_metadata_hma_block_ids():
|
||||
"""MooncakeConnectorMetadata.add_new_req stores per-group block IDs."""
|
||||
metadata = MooncakeConnectorMetadata()
|
||||
|
||||
# FA group: 6 blocks, SW group: 3 blocks (clipped)
|
||||
fa_blocks = [0, 1, 2, 3, 4, 5]
|
||||
sw_blocks = [10, 11, 12]
|
||||
|
||||
# Test recv path
|
||||
metadata.add_new_req(
|
||||
request_id="recv-req",
|
||||
local_block_ids=[fa_blocks, sw_blocks],
|
||||
kv_transfer_params={
|
||||
"transfer_id": "recv-req",
|
||||
"remote_engine_id": "remote-engine",
|
||||
"remote_bootstrap_addr": "http://bootstrap:33333",
|
||||
},
|
||||
load_remote_cache=True,
|
||||
)
|
||||
|
||||
assert "recv-req" in metadata.reqs_to_recv["remote-engine"]
|
||||
req_meta = metadata.reqs_to_recv["remote-engine"]["recv-req"]
|
||||
assert len(req_meta.local_block_ids) == 2
|
||||
assert req_meta.local_block_ids[0] == fa_blocks
|
||||
assert req_meta.local_block_ids[1] == sw_blocks
|
||||
|
||||
# Test send path
|
||||
metadata.add_new_req(
|
||||
request_id="send-req",
|
||||
local_block_ids=[fa_blocks, sw_blocks],
|
||||
kv_transfer_params={
|
||||
"transfer_id": "send-req",
|
||||
},
|
||||
load_remote_cache=False,
|
||||
)
|
||||
|
||||
assert "send-req" in metadata.reqs_to_send
|
||||
transfer_id, stored_blocks = metadata.reqs_to_send["send-req"]
|
||||
assert transfer_id == "send-req"
|
||||
assert len(stored_blocks) == 2
|
||||
assert stored_blocks[0] == fa_blocks
|
||||
assert stored_blocks[1] == sw_blocks
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_build_transfer_params_multi_group_trimming
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".mooncake_connector.TransferEngine",
|
||||
FakeMooncakeWrapper,
|
||||
)
|
||||
async def test_build_transfer_params_multi_group_trimming(monkeypatch):
|
||||
"""_build_transfer_params trims per-group blocks when local > remote."""
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
block_size = maybe_update_block_size(16)
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector", kv_role="kv_producer", block_size=block_size
|
||||
)
|
||||
kv_cache_config = make_kv_cache_config(block_size=block_size, swa_enabled=True)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config, KVConnectorRole.WORKER, kv_cache_config
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
block_len = 4096
|
||||
# Call _build_transfer_params directly (avoids send_kv_to_decode
|
||||
# async event loop complexity).
|
||||
transfer_id = "xfer-hma-trim"
|
||||
send_meta = SendBlockMeta(
|
||||
p_req_id="p-trim",
|
||||
transfer_id=transfer_id,
|
||||
# FA: 4 blocks, SW: 3 blocks (producer has more)
|
||||
local_block_ids=[[10, 11, 12, 13], [20, 21, 22]],
|
||||
ready=asyncio.Event(),
|
||||
)
|
||||
|
||||
xfer_meta = MooncakeXferMetadata(
|
||||
remote_hostname="consumer-host",
|
||||
remote_port=54321,
|
||||
remote_tp_size=1,
|
||||
remote_tp_rank=0,
|
||||
req_blocks={
|
||||
"d-trim": (
|
||||
transfer_id,
|
||||
# FA: 2 blocks, SW: 2 blocks (consumer needs fewer)
|
||||
[[30, 31], [40, 41]],
|
||||
)
|
||||
},
|
||||
kv_caches_base_addr=[0x2000],
|
||||
block_lens=[block_len],
|
||||
kv_block_lens=[block_len],
|
||||
)
|
||||
|
||||
local_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x1000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
),
|
||||
]
|
||||
remote_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x2000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
),
|
||||
]
|
||||
|
||||
ready_reqs = [("d-trim", send_meta)]
|
||||
(
|
||||
src_ptrs,
|
||||
dst_ptrs,
|
||||
lengths,
|
||||
err_reqs,
|
||||
err_msg,
|
||||
) = await worker._build_transfer_params(
|
||||
ready_reqs, xfer_meta, local_regions, remote_regions
|
||||
)
|
||||
|
||||
# No errors
|
||||
assert err_reqs == []
|
||||
assert err_msg is None
|
||||
# After trimming: FA [10..13] → last 2 → [12,13]; SW [20..22] → last 2 → [21,22]
|
||||
# Flattened: [12,13,21,22] = 4 blocks → coalesced into some transfers
|
||||
assert len(src_ptrs) > 0
|
||||
assert len(dst_ptrs) == len(src_ptrs)
|
||||
assert len(lengths) == len(src_ptrs)
|
||||
|
||||
worker.shutdown()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_build_transfer_params_group_count_mismatch
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.asyncio
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".mooncake_connector.TransferEngine",
|
||||
FakeMooncakeWrapper,
|
||||
)
|
||||
async def test_build_transfer_params_group_count_mismatch(monkeypatch):
|
||||
"""_build_transfer_params reports an error when group counts differ."""
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
block_size = maybe_update_block_size(16)
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector", kv_role="kv_producer", block_size=block_size
|
||||
)
|
||||
kv_cache_config = make_kv_cache_config(block_size=block_size, swa_enabled=True)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config, KVConnectorRole.WORKER, kv_cache_config
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
block_len = 4096
|
||||
transfer_id = "xfer-mismatch"
|
||||
send_meta = SendBlockMeta(
|
||||
p_req_id="p-mismatch",
|
||||
transfer_id=transfer_id,
|
||||
# Producer has 2 groups
|
||||
local_block_ids=[[10, 11], [20, 21]],
|
||||
ready=asyncio.Event(),
|
||||
)
|
||||
|
||||
# Consumer has only 1 group — group count mismatch
|
||||
xfer_meta = MooncakeXferMetadata(
|
||||
remote_hostname="consumer-host",
|
||||
remote_port=54321,
|
||||
remote_tp_size=1,
|
||||
remote_tp_rank=0,
|
||||
req_blocks={
|
||||
"d-mismatch": (transfer_id, [[30, 31]]),
|
||||
},
|
||||
kv_caches_base_addr=[0x2000],
|
||||
block_lens=[block_len],
|
||||
kv_block_lens=[block_len],
|
||||
)
|
||||
|
||||
local_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x1000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
),
|
||||
]
|
||||
remote_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x2000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
),
|
||||
]
|
||||
|
||||
ready_reqs = [("d-mismatch", send_meta)]
|
||||
(
|
||||
src_ptrs,
|
||||
dst_ptrs,
|
||||
lengths,
|
||||
err_reqs,
|
||||
err_msg,
|
||||
) = await worker._build_transfer_params(
|
||||
ready_reqs, xfer_meta, local_regions, remote_regions
|
||||
)
|
||||
|
||||
# Mismatched req is reported via err_reqs/err_msg with no transfers built.
|
||||
assert err_reqs == ["d-mismatch"]
|
||||
assert err_msg == "KV group count mismatch"
|
||||
assert src_ptrs == []
|
||||
assert dst_ptrs == []
|
||||
assert lengths == []
|
||||
|
||||
worker.shutdown()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# test_request_finished_with_hma_groups
|
||||
# ---------------------------------------------------------------------------
|
||||
@pytest.mark.cpu_test
|
||||
def test_request_finished_with_hma_groups():
|
||||
"""request_finished correctly handles per-group block_ids."""
|
||||
block_size = 16
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_producer",
|
||||
block_size=block_size,
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=block_size, swa_enabled=True, sw_size=128
|
||||
)
|
||||
|
||||
scheduler = MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
|
||||
request = create_request(request_id=1, do_remote_decode=True)
|
||||
request.kv_transfer_params["transfer_id"] = request.request_id
|
||||
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
request.status = RequestStatus.FINISHED_LENGTH_CAPPED
|
||||
|
||||
# 2 groups: FA with 10 blocks, SW with 20 blocks (will be clipped)
|
||||
fa_blocks = list(range(10))
|
||||
sw_blocks = list(range(100, 120))
|
||||
block_ids = (fa_blocks, sw_blocks)
|
||||
|
||||
delay_free, _ = scheduler.request_finished(request, block_ids)
|
||||
assert delay_free is True
|
||||
assert request.request_id in scheduler._reqs_need_send
|
||||
|
||||
_, stored_blocks = scheduler._reqs_need_send[request.request_id]
|
||||
# FA: untouched
|
||||
assert stored_blocks[0] == fa_blocks
|
||||
# SW: clipped to last 9 blocks (sw_size=128, block_size=16 → 8+1=9)
|
||||
assert stored_blocks[1] == sw_blocks[-9:]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Worker-side load-failure reporting (HMA vs non-HMA)
|
||||
# ---------------------------------------------------------------------------
|
||||
def _make_kv_consumer_worker(
|
||||
swa_enabled: bool = False, kv_cache_config: KVCacheConfig | None = None
|
||||
):
|
||||
block_size = maybe_update_block_size(16)
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_consumer",
|
||||
block_size=block_size,
|
||||
)
|
||||
if kv_cache_config is None:
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=block_size, swa_enabled=swa_enabled
|
||||
)
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config, KVConnectorRole.WORKER, kv_cache_config
|
||||
)
|
||||
return connector.connector_worker
|
||||
|
||||
|
||||
def _make_pull_meta(d_req_id: str, local_block_ids: list[list[int]]) -> PullReqMeta:
|
||||
return PullReqMeta(
|
||||
d_req_id=d_req_id,
|
||||
transfer_id="tx-1",
|
||||
local_block_ids=local_block_ids,
|
||||
remote_engine_id="engine-0",
|
||||
remote_bootstrap_addr="127.0.0.1:1234",
|
||||
)
|
||||
|
||||
|
||||
# The tests below construct a MooncakeConnectorWorker, whose __init__
|
||||
# requires an accelerator device, so (like the worker tests in
|
||||
# test_mooncake_connector.py) they run on the GPU KV-connectors job only.
|
||||
@pytest.mark.parametrize(
|
||||
"swa_enabled,expected_is_hma",
|
||||
[
|
||||
(True, True), # multiple groups (FA + SWA)
|
||||
(False, False), # single group, block-level reporting is unambiguous
|
||||
],
|
||||
)
|
||||
def test_worker_is_hma_required(swa_enabled, expected_is_hma):
|
||||
"""Worker-side _is_hma_required mirrors the scheduler's condition."""
|
||||
worker = _make_kv_consumer_worker(swa_enabled=swa_enabled)
|
||||
assert worker._is_hma_required is expected_is_hma
|
||||
|
||||
|
||||
def test_worker_is_hma_required_multiple_full_attention_groups():
|
||||
"""Two full-attention groups with different block sizes also select
|
||||
request-level failure reporting, matching the scheduler."""
|
||||
block_size = maybe_update_block_size(16)
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=100,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
["layer0"],
|
||||
FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=4,
|
||||
head_size=16,
|
||||
dtype=torch.float16,
|
||||
),
|
||||
),
|
||||
KVCacheGroupSpec(
|
||||
["layer1"],
|
||||
FullAttentionSpec(
|
||||
block_size=2 * block_size,
|
||||
num_kv_heads=4,
|
||||
head_size=16,
|
||||
dtype=torch.float16,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
worker = _make_kv_consumer_worker(kv_cache_config=kv_cache_config)
|
||||
assert worker._is_hma_required
|
||||
|
||||
|
||||
def test_worker_failed_recv_reports_request_level_failure_with_hma():
|
||||
"""With HMA, load failures report the request, not ambiguous block IDs."""
|
||||
worker = _make_kv_consumer_worker(swa_enabled=True)
|
||||
assert worker._is_hma_required
|
||||
|
||||
pull_meta = _make_pull_meta("d-req-1", [[1, 2], [3, 4]])
|
||||
worker._handle_failed_recv({"p-req-1": pull_meta}, ["p-req-1"], "boom")
|
||||
|
||||
assert worker.get_block_ids_with_load_errors() == set()
|
||||
results = worker.get_transfer_results()
|
||||
assert results.failed_recving == {"d-req-1"}
|
||||
assert results.finished_recving == {"d-req-1"}
|
||||
|
||||
|
||||
def test_worker_failed_recv_reports_block_ids_without_hma():
|
||||
"""Without HMA, load failures keep reporting block-level errors."""
|
||||
worker = _make_kv_consumer_worker(swa_enabled=False)
|
||||
assert not worker._is_hma_required
|
||||
|
||||
pull_meta = _make_pull_meta("d-req-1", [[1, 2], [3, 4]])
|
||||
worker._handle_failed_recv({"p-req-1": pull_meta}, ["p-req-1"], "boom")
|
||||
|
||||
assert worker.get_block_ids_with_load_errors() == {1, 2, 3, 4}
|
||||
results = worker.get_transfer_results()
|
||||
assert results.failed_recving == set()
|
||||
assert results.finished_recving == {"d-req-1"}
|
||||
@@ -1,619 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for MooncakeConnector hybrid FA + GDN support.
|
||||
|
||||
GDN is represented as a MambaSpec in vLLM, so these tests exercise the
|
||||
Mooncake MambaSpec path with mamba_type=GDN_ATTN. Mamba2 is intentionally not
|
||||
validated by this test module.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections import OrderedDict
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import dense_kv_cache_views
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import (
|
||||
KVConnectorRole,
|
||||
MooncakeConnector,
|
||||
MooncakeConnectorScheduler,
|
||||
MooncakeConnectorWorker,
|
||||
MooncakeXferMetadata,
|
||||
SendBlockMeta,
|
||||
TransferRegion,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
MambaSpec,
|
||||
)
|
||||
|
||||
from .test_mooncake_connector import patch_worker_dependencies
|
||||
from .utils import create_request, create_vllm_config, maybe_update_block_size
|
||||
|
||||
|
||||
def noop_shutdown():
|
||||
pass
|
||||
|
||||
|
||||
def make_hybrid_gdn_kv_cache_config(block_size: int) -> KVCacheConfig:
|
||||
gdn_spec = MambaSpec(
|
||||
block_size=block_size,
|
||||
shapes=((6, 3), (1, 2, 2)),
|
||||
dtypes=(torch.float16, torch.float16),
|
||||
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
|
||||
)
|
||||
assert gdn_spec.mamba_type == MambaAttentionBackendEnum.GDN_ATTN
|
||||
return KVCacheConfig(
|
||||
num_blocks=16,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
["model.layers.0.self_attn"],
|
||||
FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.float16,
|
||||
),
|
||||
),
|
||||
KVCacheGroupSpec(
|
||||
["model.layers.1.linear_attn"],
|
||||
gdn_spec,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def make_hybrid_gdn_scheduler(kv_role: str) -> MooncakeConnectorScheduler:
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role=kv_role,
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
return MooncakeConnectorScheduler(
|
||||
vllm_config=vllm_config,
|
||||
engine_id="test-engine",
|
||||
kv_cache_config=make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_hybrid_gdn_remote_prefill_uses_mamba_n_minus_one():
|
||||
scheduler = make_hybrid_gdn_scheduler(kv_role="kv_consumer")
|
||||
request = create_request(num_tokens=10, do_remote_prefill=True)
|
||||
|
||||
num_new_tokens, is_async = scheduler.get_num_new_matched_tokens(
|
||||
request, num_computed_tokens=0
|
||||
)
|
||||
|
||||
assert num_new_tokens == request.num_prompt_tokens - 1
|
||||
assert is_async is True
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_hybrid_gdn_remote_decode_truncates_prefill_before_cache_lookup():
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_producer",
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.SCHEDULER,
|
||||
make_hybrid_gdn_kv_cache_config(vllm_config.cache_config.block_size),
|
||||
)
|
||||
scheduler = connector.connector_scheduler
|
||||
assert scheduler is not None
|
||||
request = create_request(num_tokens=10, do_remote_decode=True)
|
||||
original_tokens = list(request.prompt_token_ids)
|
||||
|
||||
connector.on_new_request(request)
|
||||
assert request.prompt_token_ids == original_tokens[:-1]
|
||||
assert request._all_token_ids == original_tokens[:-1]
|
||||
assert request.num_prompt_tokens == len(original_tokens) - 1
|
||||
assert request.max_tokens == 1
|
||||
assert request.kv_transfer_params["_p_side_truncated"] is True
|
||||
|
||||
# Re-adding or rescheduling the request must not truncate another token.
|
||||
scheduler.on_new_request(request)
|
||||
assert request.prompt_token_ids == original_tokens[:-1]
|
||||
|
||||
# Prefix-cache matching must not mutate the request after its local lookup.
|
||||
with patch.object(
|
||||
scheduler,
|
||||
"_truncate_mamba_request_for_prefill",
|
||||
side_effect=AssertionError("late Mamba truncation"),
|
||||
):
|
||||
num_new_tokens, is_async = scheduler.get_num_new_matched_tokens(
|
||||
request, num_computed_tokens=0
|
||||
)
|
||||
|
||||
assert num_new_tokens == 0
|
||||
assert is_async is False
|
||||
|
||||
|
||||
def test_register_kv_caches_emits_fa_and_gdn_regions(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_consumer",
|
||||
block_size=maybe_update_block_size(16),
|
||||
)
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.WORKER,
|
||||
kv_cache_config,
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
num_blocks = kv_cache_config.num_blocks
|
||||
fa_spec = kv_cache_config.kv_cache_groups[0].kv_cache_spec
|
||||
gdn_spec = kv_cache_config.kv_cache_groups[1].kv_cache_spec
|
||||
fa_raw = torch.empty(num_blocks * fa_spec.page_size_bytes, dtype=torch.int8)
|
||||
gdn_block_stride = gdn_spec.page_size_bytes + 64
|
||||
gdn_raw = torch.empty(num_blocks, gdn_block_stride, dtype=torch.int8)
|
||||
(fa_cache,) = dense_kv_cache_views(
|
||||
fa_raw, fa_spec, num_blocks, 1, KVCacheLayout.LBHNC
|
||||
)
|
||||
gdn_cache = gdn_raw[:, : gdn_spec.page_size_bytes]
|
||||
|
||||
worker.register_kv_caches(
|
||||
{
|
||||
"model.layers.0.self_attn": fa_cache,
|
||||
"model.layers.1.linear_attn": gdn_cache,
|
||||
}
|
||||
)
|
||||
|
||||
assert worker.transfer_topo.is_mamba is True
|
||||
assert worker.registered_layer_names == [
|
||||
"model.layers.0.self_attn",
|
||||
"model.layers.1.linear_attn",
|
||||
]
|
||||
assert worker.kv_block_len_per_layer == [
|
||||
fa_spec.page_size_bytes,
|
||||
gdn_spec.page_size_bytes,
|
||||
]
|
||||
assert worker.registered_group_indices == [0, 1]
|
||||
assert worker.kv_caches_base_addr == [
|
||||
fa_cache.data_ptr(),
|
||||
gdn_cache.data_ptr(),
|
||||
]
|
||||
|
||||
worker.shutdown()
|
||||
worker.shutdown = noop_shutdown
|
||||
connector.connector_worker = None
|
||||
|
||||
|
||||
def test_register_kv_caches_scales_attention_len_to_kernel_block(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_consumer",
|
||||
block_size=maybe_update_block_size(16),
|
||||
)
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.WORKER,
|
||||
kv_cache_config,
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
factor = 4
|
||||
worker._physical_blocks_per_logical_kv_block = factor
|
||||
|
||||
fa_spec = kv_cache_config.kv_cache_groups[0].kv_cache_spec
|
||||
physical_page_bytes = fa_spec.page_size_bytes // factor
|
||||
fa_cache = torch.empty(
|
||||
kv_cache_config.num_blocks * factor,
|
||||
physical_page_bytes,
|
||||
dtype=torch.uint8,
|
||||
)
|
||||
|
||||
worker.register_kv_caches({"model.layers.0.self_attn": fa_cache})
|
||||
|
||||
assert worker.block_len_per_layer == [physical_page_bytes]
|
||||
assert worker.kv_block_len_per_layer == [physical_page_bytes]
|
||||
|
||||
worker.shutdown()
|
||||
worker.shutdown = noop_shutdown
|
||||
connector.connector_worker = None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_transfer_params_uses_non_overlapping_physical_pages():
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(block_size=16)
|
||||
worker = object.__new__(MooncakeConnectorWorker)
|
||||
worker.shutdown = noop_shutdown
|
||||
# __new__ skips __init__, where these caches are created.
|
||||
worker._prepared_transfer_regions = {}
|
||||
worker._layout_by_peer = OrderedDict()
|
||||
worker._acked_layout_peers = set()
|
||||
worker.use_mla = False
|
||||
worker.engine = SimpleNamespace(batch_register_memory=lambda *_: 0)
|
||||
worker.is_kv_consumer = True
|
||||
worker.tp_rank = 0
|
||||
worker.tp_size = 1
|
||||
worker.transfer_topo = SimpleNamespace(local_replicates_kv_cache=False)
|
||||
worker.kv_cache_config = kv_cache_config
|
||||
worker._layer_specs = {
|
||||
layer_name: group.kv_cache_spec
|
||||
for group in kv_cache_config.kv_cache_groups
|
||||
for layer_name in group.layer_names
|
||||
}
|
||||
worker._layer_group_indices = {
|
||||
layer_name: group_index
|
||||
for group_index, group in enumerate(kv_cache_config.kv_cache_groups)
|
||||
for layer_name in group.layer_names
|
||||
}
|
||||
|
||||
ratio = 4
|
||||
worker._physical_blocks_per_logical_kv_block = ratio
|
||||
fa_spec = kv_cache_config.kv_cache_groups[0].kv_cache_spec
|
||||
physical_page_bytes = fa_spec.page_size_bytes // ratio
|
||||
fa_cache = torch.empty(
|
||||
kv_cache_config.num_blocks * ratio,
|
||||
physical_page_bytes,
|
||||
dtype=torch.uint8,
|
||||
)
|
||||
worker.register_kv_caches({"model.layers.0.self_attn": fa_cache})
|
||||
|
||||
local_regions = worker._get_transfer_regions(
|
||||
worker.kv_caches_base_addr,
|
||||
worker.block_len_per_layer,
|
||||
worker.kv_block_len_per_layer,
|
||||
worker.registered_layer_names,
|
||||
worker.registered_layer_indices,
|
||||
worker.registered_group_indices,
|
||||
)
|
||||
remote_base_addr = 0x100000
|
||||
remote_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=remote_base_addr,
|
||||
block_len=physical_page_bytes,
|
||||
kv_block_len=physical_page_bytes,
|
||||
group_index=0,
|
||||
)
|
||||
]
|
||||
|
||||
local_logical_block = 2
|
||||
remote_logical_block = 5
|
||||
transfer_id = "xfer-physical-attention-pages"
|
||||
send_meta = SendBlockMeta(
|
||||
p_req_id="p-physical-attention-pages",
|
||||
transfer_id=transfer_id,
|
||||
local_block_ids=[[local_logical_block], []],
|
||||
ready=asyncio.Event(),
|
||||
)
|
||||
xfer_meta = MooncakeXferMetadata(
|
||||
remote_hostname="consumer-host",
|
||||
remote_port=54321,
|
||||
remote_tp_size=1,
|
||||
remote_tp_rank=0,
|
||||
req_blocks={
|
||||
"d-physical-attention-pages": (
|
||||
transfer_id,
|
||||
[[remote_logical_block], []],
|
||||
)
|
||||
},
|
||||
kv_caches_base_addr=[],
|
||||
block_lens=[],
|
||||
kv_block_lens=[],
|
||||
)
|
||||
|
||||
(
|
||||
src_ptrs,
|
||||
dst_ptrs,
|
||||
lengths,
|
||||
err_reqs,
|
||||
err_msg,
|
||||
) = await worker._build_transfer_params(
|
||||
[("d-physical-attention-pages", send_meta)],
|
||||
xfer_meta,
|
||||
local_regions,
|
||||
remote_regions,
|
||||
)
|
||||
|
||||
assert err_reqs == []
|
||||
assert err_msg is None
|
||||
assert src_ptrs == [
|
||||
fa_cache.data_ptr() + local_logical_block * ratio * physical_page_bytes
|
||||
]
|
||||
assert dst_ptrs == [
|
||||
remote_base_addr + remote_logical_block * ratio * physical_page_bytes
|
||||
]
|
||||
assert lengths == [ratio * physical_page_bytes]
|
||||
|
||||
def split_contiguous_blocks(src_ids, dst_ids):
|
||||
return [[block_id] for block_id in src_ids], [
|
||||
[block_id] for block_id in dst_ids
|
||||
]
|
||||
|
||||
with patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake."
|
||||
"mooncake_connector.group_concurrent_contiguous",
|
||||
side_effect=split_contiguous_blocks,
|
||||
):
|
||||
(
|
||||
src_ptrs,
|
||||
dst_ptrs,
|
||||
lengths,
|
||||
err_reqs,
|
||||
err_msg,
|
||||
) = await worker._build_transfer_params(
|
||||
[("d-physical-attention-pages", send_meta)],
|
||||
xfer_meta,
|
||||
local_regions,
|
||||
remote_regions,
|
||||
)
|
||||
|
||||
expected_src_ptrs = [
|
||||
fa_cache.data_ptr()
|
||||
+ (local_logical_block * ratio + offset) * physical_page_bytes
|
||||
for offset in range(ratio)
|
||||
]
|
||||
expected_dst_ptrs = [
|
||||
remote_base_addr + (remote_logical_block * ratio + offset) * physical_page_bytes
|
||||
for offset in range(ratio)
|
||||
]
|
||||
assert err_reqs == []
|
||||
assert err_msg is None
|
||||
assert src_ptrs == expected_src_ptrs
|
||||
assert dst_ptrs == expected_dst_ptrs
|
||||
assert lengths == [physical_page_bytes] * ratio
|
||||
assert all(
|
||||
next_ptr - ptr == physical_page_bytes
|
||||
for ptr, next_ptr in zip(src_ptrs, src_ptrs[1:])
|
||||
)
|
||||
assert all(
|
||||
next_ptr - ptr == physical_page_bytes
|
||||
for ptr, next_ptr in zip(dst_ptrs, dst_ptrs[1:])
|
||||
)
|
||||
|
||||
|
||||
def test_register_kv_caches_deduplicates_shared_backing_memory(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_consumer",
|
||||
block_size=maybe_update_block_size(16),
|
||||
)
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.WORKER,
|
||||
kv_cache_config,
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
fa_spec = kv_cache_config.kv_cache_groups[0].kv_cache_spec
|
||||
fa_cache_width = (
|
||||
fa_spec.page_size_bytes
|
||||
// torch.tensor([], dtype=torch.float16).element_size()
|
||||
)
|
||||
backing = torch.empty((4, fa_cache_width), dtype=torch.float16)
|
||||
fa_cache = backing[:2]
|
||||
gdn_cache = backing[:3]
|
||||
|
||||
with patch.object(
|
||||
worker.engine, "batch_register_memory", return_value=0
|
||||
) as batch_register_memory:
|
||||
worker.register_kv_caches(
|
||||
{
|
||||
"model.layers.0.self_attn": fa_cache,
|
||||
"model.layers.1.linear_attn": gdn_cache,
|
||||
}
|
||||
)
|
||||
|
||||
assert worker.kv_caches_base_addr == [
|
||||
fa_cache.data_ptr(),
|
||||
gdn_cache.data_ptr(),
|
||||
]
|
||||
batch_register_memory.assert_called_once()
|
||||
registered_ptrs, registered_lens = batch_register_memory.call_args[0]
|
||||
assert registered_ptrs == [backing.data_ptr()]
|
||||
assert registered_lens == [backing.untyped_storage().nbytes()]
|
||||
|
||||
worker.shutdown()
|
||||
worker.shutdown = noop_shutdown
|
||||
connector.connector_worker = None
|
||||
|
||||
|
||||
def test_hybrid_gdn_transfer_params_preserve_group_identity(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_producer",
|
||||
block_size=maybe_update_block_size(16),
|
||||
)
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.WORKER,
|
||||
kv_cache_config,
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
block_len = 0x100
|
||||
transfer_id = "xfer-hybrid-gdn"
|
||||
|
||||
async def build_transfer_params():
|
||||
send_meta = SendBlockMeta(
|
||||
p_req_id="p-hybrid-gdn",
|
||||
transfer_id=transfer_id,
|
||||
local_block_ids=[
|
||||
[10, 11],
|
||||
[NULL_BLOCK_ID, 4],
|
||||
],
|
||||
ready=asyncio.Event(),
|
||||
)
|
||||
return await worker._build_transfer_params(
|
||||
[("d-hybrid-gdn", send_meta)],
|
||||
xfer_meta,
|
||||
local_regions,
|
||||
remote_regions,
|
||||
)
|
||||
|
||||
xfer_meta = MooncakeXferMetadata(
|
||||
remote_hostname="consumer-host",
|
||||
remote_port=54321,
|
||||
remote_tp_size=1,
|
||||
remote_tp_rank=0,
|
||||
req_blocks={
|
||||
"d-hybrid-gdn": (
|
||||
transfer_id,
|
||||
[
|
||||
[30, 31],
|
||||
[NULL_BLOCK_ID, 7],
|
||||
],
|
||||
)
|
||||
},
|
||||
kv_caches_base_addr=[],
|
||||
block_lens=[],
|
||||
kv_block_lens=[],
|
||||
)
|
||||
|
||||
local_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.1.linear_attn",
|
||||
layer_index=1,
|
||||
base_addr=0x5000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
group_index=1,
|
||||
),
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x1000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
group_index=0,
|
||||
),
|
||||
]
|
||||
remote_regions = [
|
||||
TransferRegion(
|
||||
layer_name="model.layers.1.linear_attn",
|
||||
layer_index=1,
|
||||
base_addr=0x6000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
group_index=1,
|
||||
),
|
||||
TransferRegion(
|
||||
layer_name="model.layers.0.self_attn",
|
||||
layer_index=0,
|
||||
base_addr=0x2000,
|
||||
block_len=block_len,
|
||||
kv_block_len=block_len,
|
||||
group_index=0,
|
||||
),
|
||||
]
|
||||
|
||||
src_ptrs, dst_ptrs, lengths, err_reqs, err_msg = asyncio.run(
|
||||
build_transfer_params()
|
||||
)
|
||||
|
||||
assert err_reqs == []
|
||||
assert err_msg is None
|
||||
assert src_ptrs == [
|
||||
0x5000 + 4 * block_len,
|
||||
0x1000 + 10 * block_len,
|
||||
]
|
||||
assert dst_ptrs == [
|
||||
0x6000 + 7 * block_len,
|
||||
0x2000 + 30 * block_len,
|
||||
]
|
||||
assert lengths == [block_len, 2 * block_len]
|
||||
|
||||
worker.shutdown()
|
||||
worker.shutdown = noop_shutdown
|
||||
connector.connector_worker = None
|
||||
|
||||
|
||||
def test_logical_to_kernel_block_ids_expands_fa_not_gdn():
|
||||
worker = object.__new__(MooncakeConnectorWorker)
|
||||
worker.shutdown = noop_shutdown
|
||||
worker._physical_blocks_per_logical_kv_block = 17
|
||||
worker.kv_cache_config = make_hybrid_gdn_kv_cache_config(block_size=544)
|
||||
|
||||
block_ids = [[2], [2]]
|
||||
kernel_block_ids = worker._logical_to_kernel_block_ids(block_ids)
|
||||
|
||||
assert kernel_block_ids == [list(range(34, 51)), [2]]
|
||||
|
||||
|
||||
def test_hybrid_gdn_keeps_packed_fa_and_gdn_regions_whole(
|
||||
monkeypatch,
|
||||
):
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="MooncakeConnector",
|
||||
kv_role="kv_producer",
|
||||
block_size=maybe_update_block_size(16),
|
||||
)
|
||||
kv_cache_config = make_hybrid_gdn_kv_cache_config(
|
||||
vllm_config.cache_config.block_size
|
||||
)
|
||||
|
||||
with set_current_vllm_config(vllm_config), patch_worker_dependencies():
|
||||
connector = MooncakeConnector(
|
||||
vllm_config,
|
||||
KVConnectorRole.WORKER,
|
||||
kv_cache_config,
|
||||
)
|
||||
worker = connector.connector_worker
|
||||
|
||||
worker.transfer_topo = SimpleNamespace(is_kv_layout_blocks_first=False)
|
||||
regions = worker._get_transfer_regions(
|
||||
base_addrs=[0x1000, 0x2000],
|
||||
block_lens=[0x100, 0x100],
|
||||
kv_block_lens=[0x40, 0x100],
|
||||
layer_names=[
|
||||
"model.layers.0.self_attn",
|
||||
"model.layers.1.linear_attn",
|
||||
],
|
||||
layer_indices=[0, 1],
|
||||
group_indices=[0, 1],
|
||||
)
|
||||
|
||||
assert [
|
||||
(region.group_index, region.base_addr, region.kv_block_len)
|
||||
for region in regions
|
||||
] == [
|
||||
(0, 0x1000, 0x40),
|
||||
(1, 0x2000, 0x100),
|
||||
]
|
||||
|
||||
worker.shutdown()
|
||||
worker.shutdown = noop_shutdown
|
||||
connector.connector_worker = None
|
||||
@@ -1,286 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import threading
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import (
|
||||
MooncakeConnector,
|
||||
MooncakeConnectorWorker,
|
||||
SendBlockMeta,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.stats import (
|
||||
MooncakeKVConnectorStats,
|
||||
)
|
||||
|
||||
|
||||
def test_is_empty_on_fresh_stats():
|
||||
stats = MooncakeKVConnectorStats()
|
||||
assert stats.is_empty()
|
||||
assert stats.num_successful_transfers == 0
|
||||
|
||||
|
||||
def test_record_transfer_and_reduce():
|
||||
stats = MooncakeKVConnectorStats()
|
||||
# 1 MB transfer in 1 ms -> 1000 MB/s throughput
|
||||
stats.record_transfer(duration_s=0.001, total_bytes=1 * 2**20, num_descs=4)
|
||||
# 2 MB transfer in 2 ms
|
||||
stats.record_transfer(duration_s=0.002, total_bytes=2 * 2**20, num_descs=6)
|
||||
assert not stats.is_empty()
|
||||
assert stats.num_successful_transfers == 2
|
||||
|
||||
reduced = stats.reduce()
|
||||
assert reduced["Num successful transfers"] == 2
|
||||
# avg = (1 + 2) / 2 = 1.5 ms
|
||||
assert reduced["Avg xfer time (ms)"] == 1.5
|
||||
assert reduced["Avg MB per transfer"] == 1.5
|
||||
# 3 MB total / 3 ms total = 1000 MB/s
|
||||
assert reduced["Throughput (MB/s)"] == 1000.0
|
||||
assert reduced["Avg number of descriptors"] == 5.0
|
||||
assert reduced["Num failed transfers"] == 0
|
||||
assert reduced["Num failed recvs"] == 0
|
||||
assert reduced["Num KV expired reqs"] == 0
|
||||
# Reduced values must be plain Python scalars so CLI logging renders
|
||||
# them without numpy reprs (eg np.float64(...)).
|
||||
assert all(not isinstance(v, np.generic) for v in reduced.values())
|
||||
|
||||
|
||||
def test_record_failures_keeps_stats_non_empty():
|
||||
stats = MooncakeKVConnectorStats()
|
||||
stats.record_failed_transfer()
|
||||
stats.record_failed_recv()
|
||||
stats.record_kv_expired_req()
|
||||
assert not stats.is_empty()
|
||||
|
||||
reduced = stats.reduce()
|
||||
# No successful transfers -> latency/throughput all zero, but failure
|
||||
# counters still surface.
|
||||
assert reduced["Num successful transfers"] == 0
|
||||
assert reduced["Num failed transfers"] == 1
|
||||
assert reduced["Num failed recvs"] == 1
|
||||
assert reduced["Num KV expired reqs"] == 1
|
||||
|
||||
|
||||
def test_aggregate_sums_observations():
|
||||
a = MooncakeKVConnectorStats()
|
||||
b = MooncakeKVConnectorStats()
|
||||
a.record_transfer(duration_s=0.001, total_bytes=1 * 2**20, num_descs=1)
|
||||
b.record_transfer(duration_s=0.002, total_bytes=2 * 2**20, num_descs=2)
|
||||
b.record_failed_transfer()
|
||||
|
||||
a.aggregate(b)
|
||||
|
||||
assert a.num_successful_transfers == 2
|
||||
reduced = a.reduce()
|
||||
assert reduced["Num successful transfers"] == 2
|
||||
assert reduced["Num failed transfers"] == 1
|
||||
|
||||
|
||||
def test_aggregate_with_empty_other_is_noop():
|
||||
a = MooncakeKVConnectorStats()
|
||||
a.record_transfer(duration_s=0.001, total_bytes=1, num_descs=1)
|
||||
b = MooncakeKVConnectorStats()
|
||||
|
||||
a.aggregate(b)
|
||||
|
||||
assert a.num_successful_transfers == 1
|
||||
|
||||
|
||||
def test_getstate_drops_lock_and_setstate_recreates_it():
|
||||
# KVConnectorStats subclasses must be picklable (worker→scheduler IPC),
|
||||
# but threading.Lock isn't — so __getstate__ strips it and __setstate__
|
||||
# rebuilds a fresh per-process lock.
|
||||
original = MooncakeKVConnectorStats()
|
||||
original.record_transfer(duration_s=0.01, total_bytes=2048, num_descs=3)
|
||||
|
||||
state = original.__getstate__()
|
||||
assert "_lock" not in state
|
||||
|
||||
rebuilt = MooncakeKVConnectorStats.__new__(MooncakeKVConnectorStats)
|
||||
rebuilt.__setstate__(state)
|
||||
assert rebuilt.data == original.data
|
||||
# Lock works on the receiver side.
|
||||
rebuilt.record_transfer(duration_s=0.02, total_bytes=4096, num_descs=5)
|
||||
assert rebuilt.num_successful_transfers == 2
|
||||
|
||||
|
||||
def test_concurrent_writers_keep_row_lengths_aligned():
|
||||
# Multiple writers + a snapshot reader must never produce a snapshot
|
||||
# with mismatched column lengths — reduce()'s
|
||||
# len(descs) == num_successful_transfers assertion would fire.
|
||||
stats = MooncakeKVConnectorStats()
|
||||
stop = threading.Event()
|
||||
writer_count = 4
|
||||
snapshots: list[MooncakeKVConnectorStats] = []
|
||||
|
||||
def writer():
|
||||
i = 0
|
||||
while not stop.is_set():
|
||||
stats.record_transfer(
|
||||
duration_s=0.001 + i * 1e-9,
|
||||
total_bytes=1024 + i,
|
||||
num_descs=1 + (i % 8),
|
||||
)
|
||||
i += 1
|
||||
|
||||
def snapper():
|
||||
while not stop.is_set():
|
||||
snap = stats.clone_and_reset()
|
||||
if not snap.is_empty():
|
||||
# Force the same path the logger walks; reduce() will
|
||||
# blow up on torn rows via its internal assert.
|
||||
snap.reduce()
|
||||
snapshots.append(snap)
|
||||
|
||||
threads = [threading.Thread(target=writer) for _ in range(writer_count)]
|
||||
snapshotter = threading.Thread(target=snapper)
|
||||
for t in threads:
|
||||
t.start()
|
||||
snapshotter.start()
|
||||
# Short fixed window — long enough to interleave thousands of ops.
|
||||
threading.Event().wait(0.2)
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join()
|
||||
snapshotter.join()
|
||||
|
||||
# Final drain so we don't lose the in-flight tail.
|
||||
final = stats.clone_and_reset()
|
||||
if not final.is_empty():
|
||||
final.reduce()
|
||||
snapshots.append(final)
|
||||
|
||||
# Every snapshot's columns must have identical lengths (the invariant
|
||||
# the lock protects), and the union must contain at least one row.
|
||||
total_rows = 0
|
||||
for snap in snapshots:
|
||||
n = len(snap.data["transfer_duration"])
|
||||
assert len(snap.data["bytes_transferred"]) == n
|
||||
assert len(snap.data["num_descriptors"]) == n
|
||||
total_rows += n
|
||||
assert total_rows > 0
|
||||
|
||||
|
||||
def test_clone_and_reset_hands_off_old_data():
|
||||
stats = MooncakeKVConnectorStats()
|
||||
stats.record_transfer(duration_s=0.001, total_bytes=1, num_descs=1)
|
||||
stats.record_failed_recv()
|
||||
|
||||
snapshot = stats.clone_and_reset()
|
||||
|
||||
assert snapshot.num_successful_transfers == 1
|
||||
assert not snapshot.is_empty()
|
||||
# Original is now empty.
|
||||
assert stats.is_empty()
|
||||
assert stats.num_successful_transfers == 0
|
||||
# Recording on the original does not mutate the snapshot.
|
||||
stats.record_transfer(duration_s=0.005, total_bytes=2, num_descs=2)
|
||||
assert snapshot.num_successful_transfers == 1
|
||||
|
||||
|
||||
def test_build_kv_connector_stats_none_returns_empty_instance():
|
||||
out = MooncakeConnector.build_kv_connector_stats()
|
||||
assert isinstance(out, MooncakeKVConnectorStats)
|
||||
assert out.is_empty()
|
||||
|
||||
|
||||
def test_build_kv_connector_stats_with_data_round_trips():
|
||||
original = MooncakeKVConnectorStats()
|
||||
original.record_transfer(duration_s=0.01, total_bytes=1024, num_descs=3)
|
||||
original.record_failed_transfer()
|
||||
|
||||
# Serialized form is the .data dict; build should reconstruct an instance
|
||||
# that behaves the same.
|
||||
rebuilt = MooncakeConnector.build_kv_connector_stats(data=original.data)
|
||||
|
||||
assert isinstance(rebuilt, MooncakeKVConnectorStats)
|
||||
assert rebuilt.num_successful_transfers == 1
|
||||
assert rebuilt.reduce()["Num failed transfers"] == 1
|
||||
|
||||
|
||||
def _bare_worker() -> MooncakeConnectorWorker:
|
||||
"""Construct a MooncakeConnectorWorker skipping __init__ (full init requires
|
||||
a live TransferEngine). Only the attributes touched by the methods under
|
||||
test are populated; role flags and async_zmq_ctx keep __del__'s shutdown
|
||||
path a no-op."""
|
||||
worker = MooncakeConnectorWorker.__new__(MooncakeConnectorWorker)
|
||||
worker.xfer_stats = MooncakeKVConnectorStats()
|
||||
worker.engine = MagicMock()
|
||||
worker.async_zmq_ctx = MagicMock()
|
||||
worker.is_kv_consumer = True
|
||||
worker.is_kv_producer = True
|
||||
return worker
|
||||
|
||||
|
||||
def test_send_blocks_records_success():
|
||||
worker = _bare_worker()
|
||||
worker.engine.batch_transfer_sync_write.return_value = 0
|
||||
|
||||
ret = worker._send_blocks(
|
||||
"host:1234",
|
||||
src_ptrs=[0x1000, 0x2000],
|
||||
dst_ptrs=[0x3000, 0x4000],
|
||||
lengths=[1024, 2048],
|
||||
)
|
||||
|
||||
assert ret == 0
|
||||
assert worker.xfer_stats.num_successful_transfers == 1
|
||||
data = worker.xfer_stats.data
|
||||
assert data["bytes_transferred"] == [1024 + 2048]
|
||||
assert data["num_descriptors"] == [2]
|
||||
assert data["num_failed_transfers"] == []
|
||||
|
||||
|
||||
def test_send_blocks_records_failure():
|
||||
worker = _bare_worker()
|
||||
worker.engine.batch_transfer_sync_write.return_value = 1 # non-zero = fail
|
||||
|
||||
ret = worker._send_blocks("host:1234", [0x1000], [0x2000], [4096])
|
||||
|
||||
assert ret == 1
|
||||
assert worker.xfer_stats.num_successful_transfers == 0
|
||||
assert worker.xfer_stats.data["num_failed_transfers"] == [1]
|
||||
|
||||
|
||||
def test_get_kv_connector_stats_returns_none_when_empty():
|
||||
worker = _bare_worker()
|
||||
|
||||
assert worker.get_kv_connector_stats() is None
|
||||
|
||||
|
||||
def test_get_kv_connector_stats_returns_and_resets():
|
||||
worker = _bare_worker()
|
||||
worker.engine.batch_transfer_sync_write.return_value = 0
|
||||
worker._send_blocks("host:1234", [0x1000], [0x2000], [4096])
|
||||
|
||||
snapshot = worker.get_kv_connector_stats()
|
||||
assert isinstance(snapshot, MooncakeKVConnectorStats)
|
||||
assert snapshot.num_successful_transfers == 1
|
||||
|
||||
# Second call returns None because the worker's stats were reset.
|
||||
assert worker.get_kv_connector_stats() is None
|
||||
|
||||
|
||||
def test_expired_request_bumps_counter():
|
||||
import asyncio
|
||||
|
||||
worker = _bare_worker()
|
||||
worker.reqs_need_send = {
|
||||
"tid1": SendBlockMeta(
|
||||
p_req_id="req1",
|
||||
transfer_id="tid1",
|
||||
local_block_ids=[0, 1],
|
||||
ready=asyncio.Event(),
|
||||
expire_time=-1.0, # Already expired.
|
||||
sending=0,
|
||||
),
|
||||
}
|
||||
worker.finished_sending_reqs = set()
|
||||
|
||||
asyncio.run(worker.fetch_finished_sending_reqs())
|
||||
|
||||
assert worker.xfer_stats.data["num_kv_expired_reqs"] == [1]
|
||||
# Expired transfer also cleaned out of reqs_need_send.
|
||||
assert "tid1" not in worker.reqs_need_send
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,720 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from math import lcm
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.coordinator import ( # noqa: E501
|
||||
ExternalCachedBlockPool,
|
||||
MooncakeStoreCoordinator,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.data import (
|
||||
chunk_hashes_for_block_size,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import BlockHash
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheGroupSpec,
|
||||
MambaSpec,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
|
||||
|
||||
def _mamba_align(block_size=32):
|
||||
return MambaSpec(
|
||||
block_size=block_size,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
|
||||
|
||||
def _make_coord(
|
||||
groups,
|
||||
hash_block_size,
|
||||
use_eagle=False,
|
||||
retention_interval=None,
|
||||
enable_partial_hash_hits=False,
|
||||
):
|
||||
"""Construct a coordinator using the natural LCM of group block sizes as
|
||||
the scheduler block size — mirrors ``resolve_kv_cache_block_sizes`` for
|
||||
the test fixtures."""
|
||||
block_sizes = [g.kv_cache_spec.block_size for g in groups]
|
||||
scheduler_block_size = lcm(*block_sizes)
|
||||
return MooncakeStoreCoordinator(
|
||||
groups,
|
||||
scheduler_block_size=scheduler_block_size,
|
||||
hash_block_size=hash_block_size,
|
||||
use_eagle=use_eagle,
|
||||
retention_interval=retention_interval,
|
||||
enable_partial_hash_hits=enable_partial_hash_hits,
|
||||
)
|
||||
|
||||
|
||||
# ----- ExternalCachedBlockPool -----
|
||||
|
||||
|
||||
def test_external_cached_block_pool_tautological_returns_present_for_any_hash():
|
||||
cmap = ExternalCachedBlockPool(16)
|
||||
h = BlockHash(b"\xaa" * 4)
|
||||
res = cmap.get_cached_block(h, [0, 1])
|
||||
assert res is not None
|
||||
assert len(res) == 2
|
||||
assert res[0] is not cmap.null_block
|
||||
assert res[1] is not cmap.null_block
|
||||
|
||||
|
||||
def test_external_cached_block_pool_hit_all_groups():
|
||||
h = BlockHash(b"\x11\x22\x33\x44")
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h)), (1, bytes(h))})
|
||||
res = cmap.get_cached_block(h, [0, 1])
|
||||
assert res is not None
|
||||
assert len(res) == 2
|
||||
assert res[0] is not cmap.null_block
|
||||
assert res[1] is not cmap.null_block
|
||||
|
||||
|
||||
def test_external_cached_block_pool_miss_one_group():
|
||||
h = BlockHash(b"\x11\x22\x33\x44")
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h))})
|
||||
assert cmap.get_cached_block(h, [0, 1]) is None
|
||||
|
||||
|
||||
def test_external_cached_block_pool_unknown_hash():
|
||||
h_known = BlockHash(b"\x01" * 4)
|
||||
h_unknown = BlockHash(b"\x02" * 4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h_known))})
|
||||
assert cmap.get_cached_block(h_unknown, [0]) is None
|
||||
|
||||
|
||||
# ----- Helpers -----
|
||||
|
||||
|
||||
def _full(block_size=16, sliding_window=None):
|
||||
return FullAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=8,
|
||||
head_size=64,
|
||||
dtype=None,
|
||||
sliding_window=sliding_window,
|
||||
)
|
||||
|
||||
|
||||
def _swa(block_size=16, sliding_window=32):
|
||||
return SlidingWindowSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=8,
|
||||
head_size=64,
|
||||
dtype=None,
|
||||
sliding_window=sliding_window,
|
||||
)
|
||||
|
||||
|
||||
def _hashes(n: int) -> list[BlockHash]:
|
||||
return [BlockHash(bytes([i + 1]) * 4) for i in range(n)]
|
||||
|
||||
|
||||
# ----- Single-group coordinator -----
|
||||
|
||||
|
||||
def test_coordinator_single_full_attention_all_hits():
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h)) for h in hs})
|
||||
masks, hit = coord.find_longest_cache_hit(hs, max_length=64, cached_block_pool=cmap)
|
||||
assert hit == 64
|
||||
assert masks[0] == [True, True, True, True]
|
||||
|
||||
|
||||
def test_coordinator_single_full_attention_partial_prefix():
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(hs[0])), (0, bytes(hs[1]))})
|
||||
masks, hit = coord.find_longest_cache_hit(hs, max_length=64, cached_block_pool=cmap)
|
||||
assert hit == 32
|
||||
assert masks[0] == [True, True]
|
||||
|
||||
|
||||
def test_coordinator_single_full_attention_no_hits():
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, set())
|
||||
masks, hit = coord.find_longest_cache_hit(hs, max_length=64, cached_block_pool=cmap)
|
||||
assert hit == 0
|
||||
assert masks[0] == []
|
||||
|
||||
|
||||
def test_coordinator_single_swa_tautological_pool_masks_pre_window():
|
||||
"""SWA tautological-pool: hit_length spans full prefix, mask is
|
||||
tail-window only."""
|
||||
groups = [KVCacheGroupSpec(["L0"], _swa(block_size=16, sliding_window=32))]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4) # 4 chunks * 16 tokens
|
||||
cmap = ExternalCachedBlockPool(16)
|
||||
masks, hit = coord.find_longest_cache_hit(hs, max_length=64, cached_block_pool=cmap)
|
||||
assert hit == 64
|
||||
# ceil((sw-1)/block_size) = ceil(31/16) = 2 tail blocks.
|
||||
assert masks[0][-2:] == [True, True]
|
||||
assert all(not m for m in masks[0][:-2])
|
||||
|
||||
|
||||
# ----- Hybrid coordinator (single-group worker, multi-group coordinator) -----
|
||||
|
||||
|
||||
def test_coordinator_hybrid_full_plus_swa_all_hit():
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _swa(16, 32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(g, bytes(h)) for g in (0, 1) for h in hs})
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 64
|
||||
|
||||
|
||||
def test_coordinator_hybrid_hole_in_full_clips_both():
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _swa(16, 32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
exists = {(0, bytes(hs[0])), (0, bytes(hs[2])), (0, bytes(hs[3]))}
|
||||
exists |= {(1, bytes(h)) for h in hs}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 16
|
||||
|
||||
|
||||
def test_coordinator_group_block_size_double_hash():
|
||||
"""Group block_size=32 over hash_block_size=16 hashes: adjacent
|
||||
hashes merge before pool lookup."""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _full(32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
big_hashes = list(chunk_hashes_for_block_size(hs, 16, 32))
|
||||
exists = {(0, bytes(h)) for h in hs}
|
||||
exists |= {(1, bytes(bh)) for bh in big_hashes}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 64
|
||||
assert hit % 32 == 0
|
||||
|
||||
|
||||
# ----- Fine-grained partial hits (full attention + mamba "align") -----
|
||||
|
||||
|
||||
def test_coordinator_fine_grained_partial_tail_hit():
|
||||
"""K3 shape: FA + mamba-align, block_size=32 over hash_block_size=16. When
|
||||
both groups have the sub-block boundary hash, the reconciled hit lands on
|
||||
the hash boundary (48), not the block boundary (32)."""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(32)),
|
||||
KVCacheGroupSpec(["L1"], _mamba_align(32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16, enable_partial_hash_hits=True)
|
||||
hs = _hashes(4) # 4 hash units of 16 = 64 tokens; block 0 = [0,32), etc.
|
||||
# Both groups: full block 0 (key = last sub-hash hs[1]) + partial boundary
|
||||
# at token 48 (key = hs[2]). No hs[3] -> block 1 is not full.
|
||||
exists = {(g, bytes(h)) for g in (0, 1) for h in (hs[1], hs[2])}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 48
|
||||
|
||||
|
||||
def test_coordinator_fine_grained_clips_when_one_group_missing_tail():
|
||||
"""If only one group has the sub-block boundary, min-convergence clips the
|
||||
reconciled hit back to the block boundary (32)."""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(32)),
|
||||
KVCacheGroupSpec(["L1"], _mamba_align(32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
hs = _hashes(4)
|
||||
# Full block 0 for both; partial boundary hs[2] only for FA (group 0).
|
||||
exists = {(g, bytes(hs[1])) for g in (0, 1)}
|
||||
exists |= {(0, bytes(hs[2]))}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 32
|
||||
|
||||
|
||||
# ----- store_mask -----
|
||||
|
||||
|
||||
def test_store_mask_full_attention_all_true():
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
masks = coord.store_mask(64)
|
||||
assert masks == (None,)
|
||||
|
||||
|
||||
def test_store_mask_zero_aligned_returns_empty_per_group():
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _swa(16, 32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
masks = coord.store_mask(0)
|
||||
assert masks == (None, None)
|
||||
|
||||
|
||||
def test_store_mask_swa_only_window_around_each_lcm_boundary():
|
||||
"""Hybrid full-attn(block=32) + SWA(block=8, sw=8). lcm=32. With
|
||||
aligned=64 the SWA group should mark exactly the blocks ending at 32
|
||||
and 64 (i.e. blocks 3 and 7 at block_size=8); the rest can never
|
||||
participate in any future hit."""
|
||||
full = _full(32)
|
||||
swa = _swa(block_size=8, sliding_window=8)
|
||||
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
|
||||
coord = _make_coord(groups, hash_block_size=8)
|
||||
masks = coord.store_mask(64)
|
||||
# Full-attn: 2 chunks * 32 tokens.
|
||||
assert masks[0] is None
|
||||
# SWA: 8 chunks * 8 tokens. Only chunks ending at 32 and 64 are stored.
|
||||
assert masks[1] == [False, False, False, True, False, False, False, True]
|
||||
|
||||
|
||||
def test_store_mask_swa_wider_window_covers_more_blocks_per_lcm():
|
||||
"""Same hybrid layout but sliding_window=16 (= 2 SWA blocks). Each lcm
|
||||
boundary should now span two SWA tail blocks."""
|
||||
full = _full(32)
|
||||
swa = _swa(block_size=8, sliding_window=16)
|
||||
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
|
||||
coord = _make_coord(groups, hash_block_size=8)
|
||||
masks = coord.store_mask(64)
|
||||
assert masks[0] is None
|
||||
# Boundary at 32: blocks ending in [16, 32) — chunks 2 and 3.
|
||||
# Boundary at 64: chunks 6 and 7. Others stay False.
|
||||
assert masks[1] == [False, False, True, True, False, False, True, True]
|
||||
|
||||
|
||||
def test_store_mask_swa_prefix_stable_as_aligned_length_grows():
|
||||
full = _full(32)
|
||||
swa = _swa(block_size=8, sliding_window=8)
|
||||
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
|
||||
coord = _make_coord(groups, hash_block_size=8)
|
||||
|
||||
shorter = coord.store_mask(64)[1]
|
||||
longer = coord.store_mask(128)[1]
|
||||
|
||||
assert shorter is not None
|
||||
assert longer is not None
|
||||
assert longer[: len(shorter)] == shorter
|
||||
|
||||
|
||||
def test_store_mask_dsv4_5_groups_full_mla_plus_4_swa():
|
||||
"""DSV4-shaped: full-MLA(B=256) + 4 SWA groups with B in {64, 64, 4, 8}
|
||||
and varied sliding windows. lcm=256, hash_block_size=4. Two lcm segments
|
||||
(aligned_len=512). Validates that the tile-once strategy produces the
|
||||
expected per-segment tail-window pattern, repeated."""
|
||||
full_mla = _full(block_size=256)
|
||||
swa_64_sw128 = _swa(block_size=64, sliding_window=128)
|
||||
swa_64_sw512 = _swa(block_size=64, sliding_window=512)
|
||||
swa_4_sw16 = _swa(block_size=4, sliding_window=16)
|
||||
swa_8_sw64 = _swa(block_size=8, sliding_window=64)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], full_mla),
|
||||
KVCacheGroupSpec(["L1"], swa_64_sw128),
|
||||
KVCacheGroupSpec(["L2"], swa_64_sw512),
|
||||
KVCacheGroupSpec(["L3"], swa_4_sw16),
|
||||
KVCacheGroupSpec(["L4"], swa_8_sw64),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=4)
|
||||
assert coord.lcm_block_size == 256
|
||||
masks = coord.store_mask(512)
|
||||
|
||||
# Full-MLA: 2 chunks of 256, both stored.
|
||||
assert masks[0] is None
|
||||
# SWA(64, sw=128): tail = ceil(127/64) = 2; C = 256/64 = 4.
|
||||
# Per-segment template = [F,F,T,T]; tiled twice.
|
||||
assert masks[1] == [False, False, True, True] * 2
|
||||
# SWA(64, sw=512): tail = 8 >= C = 4 → entire segment True.
|
||||
assert masks[2] is None
|
||||
# SWA(4, sw=16): tail = ceil(15/4) = 4; C = 256/4 = 64.
|
||||
# Last 4 of each 64-chunk segment True.
|
||||
assert masks[3] == ([False] * 60 + [True] * 4) * 2
|
||||
# SWA(8, sw=64): tail = ceil(63/8) = 8; C = 256/8 = 32.
|
||||
# Last 8 of each 32-chunk segment True.
|
||||
assert masks[4] == ([False] * 24 + [True] * 8) * 2
|
||||
|
||||
|
||||
def test_store_mask_fast_path_all_block_sizes_equal_lcm():
|
||||
"""When every non-full-attn group already aligns to lcm_block_size, the
|
||||
fast path returns all-True without invoking find_longest_cache_hit."""
|
||||
full = _full(block_size=64)
|
||||
swa = _swa(block_size=64, sliding_window=128)
|
||||
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
|
||||
coord = _make_coord(groups, hash_block_size=64)
|
||||
assert coord.lcm_block_size == 64
|
||||
masks = coord.store_mask(256)
|
||||
# Every block in every group is True — no sub-lcm filtering possible.
|
||||
assert masks == (None, None)
|
||||
|
||||
|
||||
def test_store_mask_fast_path_single_attention_group():
|
||||
"""Two groups sharing the same SWA spec collapse to one attention group;
|
||||
no lcm filter applies, every chunk is True."""
|
||||
swa = _swa(block_size=16, sliding_window=32)
|
||||
groups = [KVCacheGroupSpec(["L0"], swa), KVCacheGroupSpec(["L1"], swa)]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
assert len(coord.attention_groups) == 1
|
||||
masks = coord.store_mask(64)
|
||||
assert masks == (None, None)
|
||||
|
||||
|
||||
# ----- store_mask with retention_interval (DSV4 sparse SWA checkpointing) -----
|
||||
|
||||
|
||||
def _retention_groups():
|
||||
"""Hybrid full-attn(block=32) + SWA(block=8, sw=8); lcm=32. The SWA group
|
||||
densely keeps one tail block per 32-token boundary."""
|
||||
full = _full(32)
|
||||
swa = _swa(block_size=8, sliding_window=8)
|
||||
return [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
|
||||
|
||||
|
||||
def test_store_mask_dense_default_matches_every_lcm_boundary():
|
||||
"""retention_interval=None (default) keeps the SWA tail at every lcm
|
||||
boundary: tokens 32/64/96/128 -> chunks 3/7/11/15."""
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8)
|
||||
masks = coord.store_mask(128)
|
||||
assert masks[0] is None
|
||||
assert masks[1] == [i % 4 == 3 for i in range(16)]
|
||||
|
||||
|
||||
def test_store_mask_retention_interval_sparsifies_swa_tails():
|
||||
"""retention_interval=64 keeps an SWA tail once per 64-token segment
|
||||
(chunks 7 and 15) instead of every 32 tokens, dropping the mid-segment
|
||||
boundaries at 32 and 96."""
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=64)
|
||||
masks = coord.store_mask(128)
|
||||
assert masks[0] is None # full attn unaffected
|
||||
assert masks[1] == [i in (7, 15) for i in range(16)]
|
||||
|
||||
|
||||
def test_store_mask_retention_interval_zero_keeps_only_replay_boundary():
|
||||
"""retention_interval=0 drops all segment tails; only the latest replay
|
||||
boundary (capped at num_prompt-1, aligned down to lcm) is retained."""
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=0)
|
||||
# No replay info -> nothing reachable for the SWA group.
|
||||
assert coord.store_mask(128)[1] == [False] * 16
|
||||
# num_prompt=100 -> latest hit boundary = (100-1)//32*32 = 96 -> chunk 11.
|
||||
masks = coord.store_mask(128, num_prompt_tokens=100)
|
||||
assert masks[1] == [i == 11 for i in range(16)]
|
||||
|
||||
|
||||
def test_store_mask_retention_interval_zero_eagle_keeps_lookup_tail():
|
||||
"""With EAGLE the replay boundary sits one scheduler block lower, as in
|
||||
core's ``replay_boundaries``: the lookup matches that block and drops
|
||||
back from it. The retained SWA tail must span the ``need`` contiguous
|
||||
blocks the lookup requires (cdiv(8 - 1, 8) + 1 = 2 here); the non-EAGLE
|
||||
boundary leaves only one of them inside the saved prefix."""
|
||||
coord = _make_coord(
|
||||
_retention_groups(), hash_block_size=8, use_eagle=True, retention_interval=0
|
||||
)
|
||||
# num_prompt=100 -> boundary 64 -> chunks 7, 8 (8 is the EAGLE peek).
|
||||
masks = coord.store_mask(96, num_prompt_tokens=100)
|
||||
assert masks[0] is None
|
||||
assert masks[1] == [i in (7, 8) for i in range(12)]
|
||||
# Aligned num_prompt=96 -> boundaries 32 (resend) and 64 (longer sibling).
|
||||
masks = coord.store_mask(96, num_prompt_tokens=96)
|
||||
assert masks[1] == [i in (3, 4, 7, 8) for i in range(12)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_prompt_tokens", [100, 96])
|
||||
def test_store_mask_retention_interval_zero_eagle_round_trip(num_prompt_tokens):
|
||||
"""Everything store_mask keeps is in the store; the EAGLE lookup of the
|
||||
same prompt must then reach the full block below the one it drops (64 of
|
||||
96). The unaligned prompt hit 0 before the fix; the aligned one already
|
||||
hit."""
|
||||
groups = _retention_groups()
|
||||
coord = _make_coord(groups, hash_block_size=8, use_eagle=True, retention_interval=0)
|
||||
hashes = _hashes(96 // coord.hash_block_size)
|
||||
exists: set[tuple[int, bytes]] = set()
|
||||
store_masks = coord.store_mask(96, num_prompt_tokens=num_prompt_tokens)
|
||||
for gid, (group, mask) in enumerate(zip(groups, store_masks, strict=True)):
|
||||
group_hashes = coord.block_hashes_for_spec(hashes, group.kv_cache_spec)
|
||||
for chunk_id, block_hash in enumerate(group_hashes):
|
||||
if mask is None or mask[chunk_id]:
|
||||
exists.add((gid, bytes(block_hash)))
|
||||
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hashes,
|
||||
max_length=96,
|
||||
cached_block_pool=ExternalCachedBlockPool(coord.hash_block_size, exists),
|
||||
)
|
||||
assert hit == 64
|
||||
|
||||
|
||||
def test_store_mask_retention_interval_keeps_segment_and_replay_tails():
|
||||
"""Sparse segment tails (interval=64 -> chunks 7,15) plus the replay
|
||||
boundary tail (num_prompt=100 -> chunk 11) coexist."""
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=64)
|
||||
masks = coord.store_mask(128, num_prompt_tokens=100)
|
||||
assert masks[1] == [i in (7, 11, 15) for i in range(16)]
|
||||
|
||||
|
||||
def test_store_mask_suffix_matches_full_mask_tail():
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=64)
|
||||
full = coord.store_mask(128, num_prompt_tokens=100)
|
||||
suffix = coord.store_mask(128, start_token=64, num_prompt_tokens=100)
|
||||
|
||||
for g_idx, cache_group in enumerate(coord.kv_cache_groups):
|
||||
block_size = cache_group.kv_cache_spec.block_size
|
||||
start_chunk = 64 // block_size
|
||||
end_chunk = 128 // block_size
|
||||
full_mask = full[g_idx]
|
||||
if full_mask is None:
|
||||
assert suffix[g_idx] is None
|
||||
else:
|
||||
assert suffix[g_idx] == full_mask[start_chunk:end_chunk]
|
||||
|
||||
|
||||
def test_store_mask_retention_prefix_stable_as_aligned_length_grows():
|
||||
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=0)
|
||||
|
||||
shorter = coord.store_mask(64, num_prompt_tokens=100)[1]
|
||||
longer = coord.store_mask(128, num_prompt_tokens=100)[1]
|
||||
|
||||
assert shorter is not None
|
||||
assert longer is not None
|
||||
assert longer[: len(shorter)] == shorter
|
||||
|
||||
|
||||
def test_store_mask_excludes_mamba_groups_lookup_unaffected():
|
||||
"""Align-mode mamba block tables are not append-only (interior states are
|
||||
nulled/freed; speculative blocks relocate), so the positional normal save
|
||||
must never cover mamba chunks — regardless of retention. Lookups still
|
||||
probe mamba boundaries: their keys come from the pinned snapshot/CoW
|
||||
hand-off path instead."""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _mamba_align(16)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16)
|
||||
masks = coord.store_mask(64)
|
||||
assert masks[0] is None # full attn stays dense
|
||||
assert masks[1] == [False] * 4
|
||||
|
||||
coord = _make_coord(groups, hash_block_size=16, retention_interval=32)
|
||||
assert coord.store_mask(64)[1] == [False] * 4
|
||||
|
||||
assert coord.lookup_mask(64)[1] is None
|
||||
|
||||
|
||||
# ----- Eagle / MTP interaction with load_mask -----
|
||||
|
||||
|
||||
def test_lookup_with_eagle_pops_last_full_attention_block():
|
||||
"""Sanity: with use_eagle, find_longest_cache_hit drops the last block.
|
||||
Pairs with the load_mask test below to lock the round-trip contract."""
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h)) for h in hs})
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
# 4 blocks present, eagle pops 1 → 3 blocks = 48 tokens.
|
||||
assert hit == 48
|
||||
|
||||
|
||||
def test_load_mask_with_eagle_does_not_double_prune_full_attention():
|
||||
"""Regression for silent KV corruption with MTP/EAGLE-3.
|
||||
|
||||
The recv side calls ``load_mask(block_hashes, token_len)`` where
|
||||
``token_len`` is already the eagle-pruned hit length from ``lookup``.
|
||||
A second eagle pop here used to shorten the mask by one extra block;
|
||||
``process_tokens`` then yielded a chunk past the mask, which the worker
|
||||
silently skipped — leaving the trailing block of the loaded prefix
|
||||
uninitialized in local KV.
|
||||
"""
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h)) for h in hs})
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 48 # eagle popped 1 block
|
||||
|
||||
masks = coord.load_mask(hs, token_len=hit)
|
||||
# Every chunk that process_tokens(token_len=48, ...) would yield must
|
||||
# have a corresponding mask slot. process_tokens emits chunk_id 0..2
|
||||
# (start=0, 16, 32), so the mask must be length 3, all True.
|
||||
assert masks[0] == [True, True, True]
|
||||
|
||||
|
||||
def test_load_mask_with_eagle_hybrid_full_plus_swa():
|
||||
"""Hybrid (FullAttn + SWA) with eagle: load_mask must cover every chunk
|
||||
in [0, token_len) for the FullAttn group; SWA group keeps its
|
||||
tail-window mask."""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _swa(16, 32)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
|
||||
hs = _hashes(4)
|
||||
exists = {(g, bytes(h)) for g in (0, 1) for h in hs}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
# FullAttn dictates the convergence; eagle pops one block off it.
|
||||
assert hit == 48
|
||||
|
||||
masks = coord.load_mask(hs, token_len=hit)
|
||||
# FullAttn: all chunks populated locally.
|
||||
assert masks[0] == [True, True, True]
|
||||
# SWA: tail-window only (ceil((32-1)/16) = 2 trailing blocks).
|
||||
assert masks[1][-2:] == [True, True]
|
||||
|
||||
|
||||
def test_load_mask_without_eagle_unchanged():
|
||||
"""Sanity: when eagle is off, load_mask is identical to the pre-fix path."""
|
||||
groups = [KVCacheGroupSpec(["L0"], _full(16))]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=False)
|
||||
hs = _hashes(4)
|
||||
cmap = ExternalCachedBlockPool(16, {(0, bytes(h)) for h in hs})
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
assert hit == 64
|
||||
masks = coord.load_mask(hs, token_len=hit)
|
||||
assert masks[0] == [True, True, True, True]
|
||||
|
||||
|
||||
def _mamba(block_size=16):
|
||||
return MambaSpec(
|
||||
block_size=block_size,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
|
||||
|
||||
def test_lookup_with_eagle_hybrid_full_plus_mamba_no_overrun():
|
||||
"""Full+Mamba with eagle must not overrun the attention-verified hit.
|
||||
|
||||
``MambaManager`` ignores ``drop_eagle_block`` (a Mamba block at position
|
||||
p IS the recurrent state after (p + 1) * block_size tokens; there is
|
||||
nothing to recompute), so granting the Mamba group the one-block eagle
|
||||
peek margin lets it match one block PAST the eagle-pruned full-attention
|
||||
hit, and adopting that length resumes the recurrent state ahead of the
|
||||
verified token prefix (#43559). Gating the margin on ``not
|
||||
isinstance(spec, MambaSpec)`` pins the hit to the attention-verified 48.
|
||||
"""
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(16)),
|
||||
KVCacheGroupSpec(["L1"], _mamba(16)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
|
||||
hs = _hashes(4)
|
||||
exists = {(g, bytes(h)) for g in (0, 1) for h in hs}
|
||||
cmap = ExternalCachedBlockPool(16, exists)
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=64, cached_block_pool=cmap
|
||||
)
|
||||
# FullAttn matches 4 blocks, eagle pops 1 -> 48 verified tokens. The
|
||||
# Mamba group must serve its state@48 snapshot, not peek to state@64.
|
||||
assert hit == 48
|
||||
|
||||
|
||||
def test_eagle_flag_propagates_to_all_merged_swa_groups():
|
||||
"""Regression for MTP x PD external-store 0% prefix hit.
|
||||
|
||||
DSV4 splits SWA layers into several KV cache groups sharing one spec, and
|
||||
only the group containing the MTP layer is annotated ``is_eagle_group``.
|
||||
The lookup merges equal-spec groups, applies the eagle drop to the merged
|
||||
group, and requires each chunk hash to exist in EVERY member group — so
|
||||
the save-side masks must eagle-shift every member, not just the annotated
|
||||
one. Without propagation the non-annotated groups never store the eagle
|
||||
proof-run chunks and every external lookup returns 0.
|
||||
"""
|
||||
swa = _swa(block_size=16, sliding_window=32)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], _full(64)),
|
||||
KVCacheGroupSpec(["L1"], swa),
|
||||
KVCacheGroupSpec(["L2"], swa, is_eagle_group=True),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
|
||||
assert coord.eagle_group_ids == {1, 2}
|
||||
|
||||
# Save side: both SWA groups must produce identical (eagle-shifted) masks.
|
||||
masks = coord.store_mask(128, num_prompt_tokens=130)
|
||||
assert masks[1] == masks[2]
|
||||
|
||||
# Round trip: everything store_mask kept is in the store; the eagle
|
||||
# lookup must then serve a non-zero hit (it was 0 before the fix).
|
||||
hs = _hashes(128 // 16)
|
||||
exists = set()
|
||||
for g_idx, g in enumerate(groups):
|
||||
ghashes = chunk_hashes_for_block_size(hs, 16, g.kv_cache_spec.block_size)
|
||||
mask = masks[g_idx]
|
||||
for i in range(128 // g.kv_cache_spec.block_size):
|
||||
if mask is None or mask[i]:
|
||||
exists.add((g_idx, bytes(ghashes[i])))
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hs, max_length=128, cached_block_pool=ExternalCachedBlockPool(16, exists)
|
||||
)
|
||||
assert hit == 64
|
||||
|
||||
|
||||
def test_dsv4_five_group_eagle_store_lookup_round_trip():
|
||||
"""Cover the five KV groups observed with DeepSeek-V4-Flash + MTP.
|
||||
|
||||
The two 64-token SWA groups have identical specs, but only one owns the
|
||||
EAGLE layer. Saving each group through its store mask must still leave a
|
||||
prefix that the merged SWA lookup can consume.
|
||||
"""
|
||||
swa_64_sw128 = _swa(block_size=64, sliding_window=128)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["full_mla"], _full(block_size=256)),
|
||||
KVCacheGroupSpec(["swa"], swa_64_sw128),
|
||||
KVCacheGroupSpec(["mtp"], swa_64_sw128, is_eagle_group=True),
|
||||
KVCacheGroupSpec(["c4_state"], _swa(block_size=4, sliding_window=8)),
|
||||
KVCacheGroupSpec(["c128_state"], _swa(block_size=8, sliding_window=128)),
|
||||
]
|
||||
coord = _make_coord(groups, hash_block_size=4, use_eagle=True)
|
||||
token_len = 768
|
||||
hashes = _hashes(token_len // coord.hash_block_size)
|
||||
|
||||
# Mirror MooncakeStoreWorker's aligned save: only keys selected by each
|
||||
# group's store mask are visible to the external lookup.
|
||||
exists: set[tuple[int, bytes]] = set()
|
||||
store_masks = coord.store_mask(token_len)
|
||||
for gid, (group, mask) in enumerate(zip(groups, store_masks, strict=True)):
|
||||
group_hashes = coord.block_hashes_for_spec(hashes, group.kv_cache_spec)
|
||||
for chunk_id, block_hash in enumerate(group_hashes):
|
||||
if mask is None or mask[chunk_id]:
|
||||
exists.add((gid, bytes(block_hash)))
|
||||
|
||||
_masks, hit = coord.find_longest_cache_hit(
|
||||
hashes,
|
||||
max_length=token_len,
|
||||
cached_block_pool=ExternalCachedBlockPool(coord.hash_block_size, exists),
|
||||
)
|
||||
|
||||
# The final 256-token segment has no lookahead block, so EAGLE falls back
|
||||
# to the previous aligned boundary instead of consuming all 768 tokens.
|
||||
assert hit == 512
|
||||
@@ -1,934 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""End-to-end save->lookup test for MooncakeStoreConnector on a hybrid
|
||||
(SWA + Full) attention config, using a dict-backed mock store."""
|
||||
|
||||
import sys
|
||||
import threading
|
||||
import types
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import dense_kv_cache_views
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store import (
|
||||
worker as mooncake_store_worker,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.coordinator import ( # noqa: E501
|
||||
MooncakeStoreCoordinator,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.data import (
|
||||
BoundaryPut,
|
||||
ChunkedTokenDatabase,
|
||||
KeyMetadata,
|
||||
LoadSpec,
|
||||
ReqMeta,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.scheduler import ( # noqa: E501
|
||||
_partial_tail_non_mamba_puts,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.worker import ( # noqa: E501
|
||||
KVCacheStoreRecvingThread,
|
||||
KVCacheStoreSendingThread,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import BlockHash
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
MambaSpec,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
|
||||
class _DictStore:
|
||||
"""In-memory MooncakeDistributedStore stand-in."""
|
||||
|
||||
def __init__(self):
|
||||
self._data: dict[str, bytes] = {}
|
||||
|
||||
def setup(self, *_args, **_kwargs):
|
||||
return 0
|
||||
|
||||
def register_buffer(self, addr, length):
|
||||
return 0
|
||||
|
||||
def batch_is_exist(self, keys):
|
||||
return [1 if k in self._data else 0 for k in keys]
|
||||
|
||||
def batch_put_from_multi_buffers(self, keys, addrs, sizes, *_args, **_kwargs):
|
||||
for k in keys:
|
||||
self._data[k] = b"x"
|
||||
return [0] * len(keys)
|
||||
|
||||
def batch_get_into_multi_buffers(self, keys, addrs, sizes, *_args, **_kwargs):
|
||||
return [0 if k in self._data else -1 for k in keys]
|
||||
|
||||
|
||||
def _minimal_vllm_config(cache_block_size=16):
|
||||
cfg = MagicMock()
|
||||
cfg.cache_config.block_size = cache_block_size
|
||||
cfg.cache_config.num_gpu_blocks = 4
|
||||
cfg.cache_config.hash_block_size = None
|
||||
cfg.cache_config.prefix_match_unit = None
|
||||
cfg.cache_config.enable_prefix_caching = True
|
||||
cfg.parallel_config.prefill_context_parallel_size = 1
|
||||
cfg.parallel_config.decode_context_parallel_size = 1
|
||||
cfg.parallel_config.pipeline_parallel_size = 1
|
||||
cfg.parallel_config.world_size = 1
|
||||
cfg.parallel_config.rank = 0
|
||||
cfg.parallel_config.data_parallel_rank_local = 0
|
||||
cfg.parallel_config.data_parallel_size_local = 1
|
||||
cfg.kv_transfer_config.kv_role = "kv_both"
|
||||
cfg.kv_transfer_config.kv_connector_extra_config = {}
|
||||
cfg.kv_events_config = None
|
||||
cfg.model_config.model = "/tmp/m"
|
||||
cfg.model_config.use_mla = False
|
||||
cfg.model_config.get_num_layers.return_value = 2
|
||||
cfg.model_config.get_total_num_kv_heads.return_value = 8
|
||||
cfg.model_config.max_model_len = 4096
|
||||
cfg.scheduler_config.max_num_batched_tokens = 8192
|
||||
# Without this, MagicMock's truthy use_eagle() triggers the coordinator's
|
||||
# "use_eagle && nothing annotated → flag all groups" fallback.
|
||||
cfg.speculative_config = None
|
||||
return cfg
|
||||
|
||||
|
||||
def _build_worker_with_dict_store(vllm_config, kv_cache_config, store):
|
||||
"""Build a MooncakeStoreWorker patching all distributed dependencies."""
|
||||
fake_mooncake_store = types.ModuleType("mooncake.store")
|
||||
fake_mooncake_store.MooncakeDistributedStore = lambda: store # type: ignore[attr-defined]
|
||||
fake_mooncake_store.ReplicateConfig = MagicMock # type: ignore[attr-defined]
|
||||
with (
|
||||
patch.dict(sys.modules, {"mooncake.store": fake_mooncake_store}),
|
||||
patch.object(mooncake_store_worker, "MooncakeStoreConfig") as MCfg,
|
||||
patch.object(mooncake_store_worker, "LookupKeyServer"),
|
||||
):
|
||||
sc = MCfg.load_from_config.return_value
|
||||
sc.metadata_server = ""
|
||||
sc.global_segment_size = 1 << 20
|
||||
sc.local_buffer_size = 1 << 20
|
||||
sc.protocol = "tcp"
|
||||
sc.device_name = ""
|
||||
sc.master_server_address = ""
|
||||
sc.mode = "embedded"
|
||||
sc.enable_offload = False
|
||||
with (
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".store.worker.get_tensor_model_parallel_rank",
|
||||
return_value=0,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".store.worker.get_tensor_model_parallel_world_size",
|
||||
return_value=1,
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".store.worker.get_pcp_group"
|
||||
) as mock_pcp,
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".store.worker.get_dcp_group"
|
||||
) as mock_dcp,
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake"
|
||||
".store.worker.get_ip",
|
||||
return_value="127.0.0.1",
|
||||
),
|
||||
):
|
||||
mock_pcp.return_value.world_size = 1
|
||||
mock_dcp.return_value.world_size = 1
|
||||
worker = mooncake_store_worker.MooncakeStoreWorker(
|
||||
vllm_config, kv_cache_config=kv_cache_config
|
||||
)
|
||||
return worker
|
||||
|
||||
|
||||
def test_e2e_swa_plus_full_save_then_lookup_hits():
|
||||
"""E2E: build a SWA+Full hybrid worker, save all blocks via the sending
|
||||
thread (synchronously), then verify lookup returns the full hit length.
|
||||
Also verify that evicting SWA's early blocks (outside its window) still
|
||||
allows a full hit because the window covers the tail.
|
||||
"""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
swa = SlidingWindowSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=8,
|
||||
head_size=64,
|
||||
dtype=None,
|
||||
sliding_window=32,
|
||||
)
|
||||
cfg = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=4 * full.page_size_bytes,
|
||||
layers=["L0"],
|
||||
layer_stride=4 * full.page_size_bytes,
|
||||
block_stride=full.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=4 * swa.page_size_bytes,
|
||||
layers=["L1"],
|
||||
layer_stride=4 * swa.page_size_bytes,
|
||||
block_stride=swa.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], swa),
|
||||
],
|
||||
)
|
||||
vllm_config = _minimal_vllm_config(cache_block_size=16)
|
||||
store = _DictStore()
|
||||
|
||||
worker = _build_worker_with_dict_store(vllm_config, cfg, store)
|
||||
worker.tp_size = 1
|
||||
worker.pp_size = 1
|
||||
worker.num_kv_head = 8
|
||||
|
||||
# Register kv_caches using mocked thread classes so register_kv_caches
|
||||
# doesn't try to start real background threads (which set ready_event).
|
||||
raw_full = torch.zeros(4 * full.page_size_bytes, dtype=torch.int8)
|
||||
raw_swa = torch.zeros(4 * swa.page_size_bytes, dtype=torch.int8)
|
||||
kv_caches = {
|
||||
"L0": dense_kv_cache_views(raw_full, full, 4, 1, KVCacheLayout.LBNHC)[0],
|
||||
"L1": dense_kv_cache_views(raw_swa, swa, 4, 1, KVCacheLayout.LBNHC)[0],
|
||||
}
|
||||
|
||||
def _fake_thread_init(*args, **kwargs):
|
||||
"""Mock thread that sets all threading.Event args so waits don't block."""
|
||||
for v in list(args) + list(kwargs.values()):
|
||||
if isinstance(v, threading.Event):
|
||||
v.set()
|
||||
m = MagicMock()
|
||||
m.start = lambda: None
|
||||
return m
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
mooncake_store_worker,
|
||||
"KVCacheStoreSendingThread",
|
||||
side_effect=_fake_thread_init,
|
||||
),
|
||||
patch.object(
|
||||
mooncake_store_worker,
|
||||
"KVCacheStoreRecvingThread",
|
||||
side_effect=_fake_thread_init,
|
||||
),
|
||||
):
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
# Now build a real sending thread (no .start()) over the worker's token_dbs
|
||||
# and the dict-backed store, so _handle_request runs synchronously.
|
||||
ready = threading.Event()
|
||||
send_thread = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
token_databases=worker.token_dbs,
|
||||
block_size=worker.block_size,
|
||||
coord=worker.coord,
|
||||
tp_rank=worker.tp_rank,
|
||||
group_put_steps=worker._group_tp_replication_factors,
|
||||
kv_role=worker.kv_role,
|
||||
ready_event=ready,
|
||||
enable_kv_event=False,
|
||||
)
|
||||
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(4)]
|
||||
# 1-based: block 0 is the reserved null block and the save skips it.
|
||||
save_req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=64,
|
||||
# Block 0 is reserved as NULL_BLOCK_ID by the production block pool.
|
||||
block_ids=([1, 2, 3, 4], [1, 2, 3, 4]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
store_job_id=1,
|
||||
)
|
||||
# add_request also queues the job, so task_done() doesn't underflow.
|
||||
send_thread.add_request(save_req)
|
||||
send_thread._handle_request(send_thread.request_queue.get())
|
||||
|
||||
# Point worker.store at the dict store (the worker constructor captured
|
||||
# the MagicMock; replace with the real dict store for lookup).
|
||||
worker.store = store
|
||||
|
||||
# Both groups stored all 4 blocks -> full hit.
|
||||
assert worker.lookup(num_tokens=65, block_hashes=hs).hit_length == 64
|
||||
# Exact-multiple prompt: the full hit is re-derived one block lower,
|
||||
# where both groups' stored blocks still cover the SWA window.
|
||||
assert worker.lookup(num_tokens=64, block_hashes=hs).hit_length == 48
|
||||
|
||||
# Evict SWA's first two blocks (outside its window of 32 tokens = 2 blocks).
|
||||
swa_keys_outside_window = [
|
||||
k
|
||||
for k in list(store._data.keys())
|
||||
if "@group:1" in k and (("@" + hs[0].hex()) in k or ("@" + hs[1].hex()) in k)
|
||||
]
|
||||
for k in swa_keys_outside_window:
|
||||
del store._data[k]
|
||||
|
||||
# SWA window=32 -> only last 2 blocks must be present in SWA group.
|
||||
# Full has all 4. Coordinator should still return 64.
|
||||
assert worker.lookup(num_tokens=65, block_hashes=hs).hit_length == 64
|
||||
# Exact-multiple prompt after eviction: the boundary one block lower
|
||||
# needs SWA block 1, which is gone — no usable stored boundary remains
|
||||
# (the pre-fix arithmetic clamp would have returned 48 and livelocked
|
||||
# on load failure -> recompute -> same lookup).
|
||||
assert worker.lookup(num_tokens=64, block_hashes=hs).hit_length == 0
|
||||
|
||||
|
||||
def test_recv_skips_swa_blocks_before_window():
|
||||
"""Producer stored every block for both groups; consumer must only fetch
|
||||
SWA blocks within the sliding window, not the head."""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
# sliding_window=32, block_size=16 → 2 contiguous blocks within window.
|
||||
swa = SlidingWindowSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=8,
|
||||
head_size=64,
|
||||
dtype=None,
|
||||
sliding_window=32,
|
||||
)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], swa),
|
||||
]
|
||||
md0 = KeyMetadata("m", 0, 0, 0, 0, group_id=0)
|
||||
md1 = KeyMetadata("m", 0, 0, 0, 0, group_id=1)
|
||||
db_full = ChunkedTokenDatabase(md0, block_size=16, hash_block_size=16)
|
||||
db_swa = ChunkedTokenDatabase(md1, block_size=16, hash_block_size=16)
|
||||
db_full.set_kv_caches_base_addr([0])
|
||||
db_full.set_block_len([1024])
|
||||
db_swa.set_kv_caches_base_addr([1 << 20])
|
||||
db_swa.set_block_len([1024])
|
||||
|
||||
requested_keys: list[str] = []
|
||||
|
||||
class _CapturingStore:
|
||||
def batch_get_into_multi_buffers(self, keys, addrs, sizes):
|
||||
requested_keys.extend(keys)
|
||||
return [0] * len(keys)
|
||||
|
||||
ready = threading.Event()
|
||||
coord = MooncakeStoreCoordinator(
|
||||
groups, scheduler_block_size=16, hash_block_size=16
|
||||
)
|
||||
recv = KVCacheStoreRecvingThread(
|
||||
store=_CapturingStore(),
|
||||
token_databases=[db_full, db_swa],
|
||||
block_size=16,
|
||||
tp_rank=0,
|
||||
ready_event=ready,
|
||||
coord=coord,
|
||||
)
|
||||
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(4)]
|
||||
req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=64,
|
||||
block_ids=([0, 1, 2, 3], [0, 1, 2, 3]),
|
||||
block_hashes=hs,
|
||||
load_spec=LoadSpec(
|
||||
vllm_cached_tokens=0, kvpool_cached_tokens=64, can_load=True, token_len=64
|
||||
),
|
||||
)
|
||||
recv.request_queue.put(req)
|
||||
recv._handle_request(recv.request_queue.get())
|
||||
|
||||
full_keys = [k for k in requested_keys if "@group:0" in k]
|
||||
swa_keys = [k for k in requested_keys if "@group:1" in k]
|
||||
# Full attention: load every block (4).
|
||||
assert len(full_keys) == 4
|
||||
# SWA: only the 2 tail-window blocks (hashes hs[2], hs[3]).
|
||||
assert len(swa_keys) == 2
|
||||
swa_hashes = {k.rsplit("@", 1)[-1] for k in swa_keys}
|
||||
assert swa_hashes == {hs[2].hex(), hs[3].hex()}
|
||||
|
||||
|
||||
def test_chunked_token_database_hash_block_size_smaller_than_block_size():
|
||||
"""DSv4-style: hash_block_size=4, group block_size=16 — process_tokens
|
||||
keys each chunk by its ending fine hash, including a partial tail."""
|
||||
md = KeyMetadata("m", 0, 0, 0, 0, group_id=3)
|
||||
db = ChunkedTokenDatabase(md, block_size=16, hash_block_size=4)
|
||||
db.set_kv_caches_base_addr([0])
|
||||
db.set_block_len([512])
|
||||
fine_hashes = [BlockHash(bytes([i + 1]) * 4) for i in range(8)]
|
||||
|
||||
# 8 fine-grained hashes (32 tokens at hash_block_size=4) → 2 group chunks.
|
||||
out = list(db.process_tokens(token_len=32, block_hashes=fine_hashes))
|
||||
assert len(out) == 2
|
||||
assert out[0][0] == 0 and out[0][1] == 16
|
||||
assert out[1][0] == 16 and out[1][1] == 32
|
||||
# Each chunk's hash is its last (4th) fine hash, which already chains the
|
||||
# prior three.
|
||||
assert out[0][2].hex() == fine_hashes[3].hex()
|
||||
assert out[1][2].hex() == fine_hashes[7].hex()
|
||||
|
||||
# Sub-block hit: emit the partial chunk under its ending fine hash.
|
||||
out = list(db.process_tokens(token_len=12, block_hashes=fine_hashes[:3]))
|
||||
assert [(s, e) for s, e, _ in out] == [(0, 12)]
|
||||
assert out[0][2].hex() == fine_hashes[2].hex()
|
||||
|
||||
# Cross-block hit: emit both the full chunk and its partial tail.
|
||||
out = list(db.process_tokens(token_len=28, block_hashes=fine_hashes[:7]))
|
||||
assert [(s, e) for s, e, _ in out] == [(0, 16), (16, 28)]
|
||||
assert out[0][2].hex() == fine_hashes[3].hex()
|
||||
assert out[1][2].hex() == fine_hashes[6].hex()
|
||||
|
||||
|
||||
def _resolve_partial_tail(thread, req: ReqMeta) -> ReqMeta:
|
||||
"""Add the tail's non-Mamba puts as the scheduler does before the worker."""
|
||||
req.boundary_puts = [BoundaryPut(*put) for put in req.boundary_puts or []]
|
||||
req.boundary_puts[:0] = _partial_tail_non_mamba_puts(
|
||||
thread.coord, req, [db.block_size for db in thread.token_databases]
|
||||
)
|
||||
return req
|
||||
|
||||
|
||||
def test_sub_block_partial_tail_offload_reads_cow_block():
|
||||
"""Sub-block prompt (the 900/128/1536 shape, scaled to 12/4/16): the
|
||||
partial tail is offloaded for both groups under the boundary sub-hash. The
|
||||
full-attention block is read from the request block table; the mamba block
|
||||
is the core-provided CoW target, not block_ids."""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
mamba = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], mamba),
|
||||
]
|
||||
coord = MooncakeStoreCoordinator(
|
||||
groups,
|
||||
scheduler_block_size=16,
|
||||
hash_block_size=4,
|
||||
enable_partial_hash_hits=True,
|
||||
)
|
||||
assert coord.enable_partial_hash_hits
|
||||
|
||||
class _RecordingStore(_DictStore):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.puts: dict[str, list[int]] = {}
|
||||
|
||||
def batch_put_from_multi_buffers(self, keys, addrs, sizes, *a, **k):
|
||||
for key, addr in zip(keys, addrs):
|
||||
self.puts[key] = addr
|
||||
return super().batch_put_from_multi_buffers(keys, addrs, sizes, *a, **k)
|
||||
|
||||
store = _RecordingStore()
|
||||
token_dbs = []
|
||||
for g_idx in range(2):
|
||||
db = ChunkedTokenDatabase(
|
||||
KeyMetadata("m", 0, 0, 0, 0, group_id=g_idx),
|
||||
block_size=16,
|
||||
hash_block_size=4,
|
||||
)
|
||||
db.set_kv_caches_base_addr([g_idx * 10_000])
|
||||
db.set_block_len([512])
|
||||
token_dbs.append(db)
|
||||
|
||||
send = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
coord=coord,
|
||||
token_databases=token_dbs,
|
||||
block_size=16,
|
||||
tp_rank=0,
|
||||
group_put_steps=[1, 1],
|
||||
kv_role="kv_both",
|
||||
ready_event=threading.Event(),
|
||||
replicate_config=MagicMock(),
|
||||
)
|
||||
|
||||
# The surrounding metadata may describe a longer resumed replay, but the
|
||||
# handoff identifies the exact state boundary to persist.
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(5)]
|
||||
mamba_cow_block = 7
|
||||
req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=0,
|
||||
block_ids=([1], [2]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
num_prompt_tokens=13,
|
||||
prefill_end_tokens=20,
|
||||
completed_token_len=20,
|
||||
boundary_puts=[(1, mamba_cow_block, 12)],
|
||||
)
|
||||
|
||||
send._maybe_offload_boundary_states(_resolve_partial_tail(send, req))
|
||||
|
||||
# boundary = 12 // 4 * 4 = 12 -> keyed by hs[12 // 4 - 1] = hs[2].
|
||||
partial_hash = hs[2]
|
||||
fa_key = token_dbs[0].key_for(partial_hash)
|
||||
mamba_key = token_dbs[1].key_for(partial_hash)
|
||||
assert set(store.puts) == {fa_key, mamba_key}
|
||||
# FA reads block_ids[0][0] = block 1: addr = base(0) + 1 * 512.
|
||||
assert store.puts[fa_key] == [512]
|
||||
# Mamba reads the CoW block 7, not block_ids[1][0]=2.
|
||||
assert store.puts[mamba_key] == [10_000 + mamba_cow_block * 512]
|
||||
|
||||
|
||||
def test_offload_syncs_event_before_put():
|
||||
"""An offload-carrying meta synchronizes its CoW-fence event before the
|
||||
store put reads the blocks, then completes in one pass and drains the
|
||||
completion counter."""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
mamba = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], mamba),
|
||||
]
|
||||
coord = MooncakeStoreCoordinator(
|
||||
groups,
|
||||
scheduler_block_size=16,
|
||||
hash_block_size=4,
|
||||
enable_partial_hash_hits=True,
|
||||
)
|
||||
event = MagicMock()
|
||||
|
||||
class _FencedStore(_DictStore):
|
||||
def batch_put_from_multi_buffers(self, keys, addrs, sizes, *a, **k):
|
||||
assert event.synchronize.called, "put must run after the event sync"
|
||||
return super().batch_put_from_multi_buffers(keys, addrs, sizes, *a, **k)
|
||||
|
||||
store = _FencedStore()
|
||||
token_dbs = []
|
||||
for g_idx in range(2):
|
||||
db = ChunkedTokenDatabase(
|
||||
KeyMetadata("m", 0, 0, 0, 0, group_id=g_idx),
|
||||
block_size=16,
|
||||
hash_block_size=4,
|
||||
)
|
||||
db.set_kv_caches_base_addr([g_idx * 10_000])
|
||||
db.set_block_len([512])
|
||||
token_dbs.append(db)
|
||||
|
||||
send = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
coord=coord,
|
||||
token_databases=token_dbs,
|
||||
block_size=16,
|
||||
tp_rank=0,
|
||||
group_put_steps=[1, 1],
|
||||
kv_role="kv_both",
|
||||
ready_event=threading.Event(),
|
||||
replicate_config=MagicMock(),
|
||||
)
|
||||
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(3)]
|
||||
req = ReqMeta(
|
||||
req_id="r1",
|
||||
token_len_chunk=0,
|
||||
block_ids=([1], [2]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
num_prompt_tokens=12,
|
||||
completed_token_len=12,
|
||||
store_job_id=1,
|
||||
boundary_puts=[(1, 7, 8)],
|
||||
)
|
||||
req.current_event = event
|
||||
|
||||
send.add_request(_resolve_partial_tail(send, req))
|
||||
send._handle_request(send.request_queue.get())
|
||||
assert send.request_queue.qsize() == 0
|
||||
assert store._data
|
||||
assert send.stored_requests["r1"] == set()
|
||||
event.synchronize.assert_called_once()
|
||||
|
||||
|
||||
def test_sub_block_partial_tail_offload_covers_smaller_group_blocks():
|
||||
"""The K3-shaped 900/128/1536 scenario scaled to 12/4/16, with a
|
||||
full-attention group whose block (4) is smaller than the lcm (16): the
|
||||
offload must persist every FA block up to the boundary — the normal save
|
||||
floors to the lcm, so those blocks are otherwise never written and the
|
||||
consumer's per-group lookup would miss. The mamba boundary block still
|
||||
reads the core-provided CoW target. Without EAGLE, the 12-token prompt's
|
||||
resend-safe checkpoint is 8, leaving two attention blocks to save."""
|
||||
full = FullAttentionSpec(block_size=4, num_kv_heads=8, head_size=64, dtype=None)
|
||||
mamba = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
groups = [
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], mamba),
|
||||
]
|
||||
coord = MooncakeStoreCoordinator(
|
||||
groups,
|
||||
scheduler_block_size=16,
|
||||
hash_block_size=4,
|
||||
enable_partial_hash_hits=True,
|
||||
)
|
||||
assert coord.enable_partial_hash_hits
|
||||
|
||||
class _RecordingStore(_DictStore):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.puts: dict[str, list[int]] = {}
|
||||
|
||||
def batch_put_from_multi_buffers(self, keys, addrs, sizes, *a, **k):
|
||||
for key, addr in zip(keys, addrs):
|
||||
self.puts[key] = addr
|
||||
return super().batch_put_from_multi_buffers(keys, addrs, sizes, *a, **k)
|
||||
|
||||
store = _RecordingStore()
|
||||
token_dbs = []
|
||||
for g_idx, block_size in enumerate([4, 16]):
|
||||
db = ChunkedTokenDatabase(
|
||||
KeyMetadata("m", 0, 0, 0, 0, group_id=g_idx),
|
||||
block_size=block_size,
|
||||
hash_block_size=4,
|
||||
)
|
||||
db.set_kv_caches_base_addr([g_idx * 10_000])
|
||||
db.set_block_len([512])
|
||||
token_dbs.append(db)
|
||||
|
||||
send = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
coord=coord,
|
||||
token_databases=token_dbs,
|
||||
block_size=16,
|
||||
tp_rank=0,
|
||||
group_put_steps=[1, 1],
|
||||
kv_role="kv_both",
|
||||
ready_event=threading.Event(),
|
||||
replicate_config=MagicMock(),
|
||||
)
|
||||
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(3)] # 3 hash units = 12 tok
|
||||
mamba_cow_block = 7
|
||||
req = ReqMeta(
|
||||
req_id="r2",
|
||||
token_len_chunk=0,
|
||||
block_ids=([1, 2, 3], [4]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
num_prompt_tokens=12,
|
||||
completed_token_len=12,
|
||||
boundary_puts=[(1, mamba_cow_block, 8)],
|
||||
)
|
||||
|
||||
send._maybe_offload_boundary_states(_resolve_partial_tail(send, req))
|
||||
|
||||
# FA (block 4): full blocks ending at 4 and 8, keyed by their normal
|
||||
# block-end hashes; mamba (block 16): the partial boundary block under
|
||||
# the boundary sub-hash, read from the CoW target.
|
||||
expected = {
|
||||
token_dbs[0].key_for(hs[0]): [1 * 512],
|
||||
token_dbs[0].key_for(hs[1]): [2 * 512],
|
||||
token_dbs[1].key_for(hs[1]): [10_000 + mamba_cow_block * 512],
|
||||
}
|
||||
assert store.puts == expected
|
||||
|
||||
|
||||
def test_worker_lookup_hits_sub_block_partial_tail():
|
||||
"""worker.lookup must query sub-block keys when partial hash hits are on.
|
||||
|
||||
Regression test: ``lookup`` hard-coded ``fine_grained = False``, so the
|
||||
partial tail's sub-block keys were never probed and partial prefix hits
|
||||
silently returned 0 while the store side kept writing them. Here the
|
||||
mamba block (16) exceeds the hash unit (4), so ``enable_partial_hash_hits``
|
||||
is on and the lookup must find the stored boundary at 8.
|
||||
"""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
mamba = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
cfg = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=4 * full.page_size_bytes,
|
||||
layers=["L0"],
|
||||
layer_stride=4 * full.page_size_bytes,
|
||||
block_stride=full.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=4 * mamba.page_size_bytes,
|
||||
layers=["L1"],
|
||||
layer_stride=4 * mamba.page_size_bytes,
|
||||
block_stride=mamba.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], mamba),
|
||||
],
|
||||
# The hit alignment the engine core resolves for this config.
|
||||
cache_hit_alignment_tokens=4,
|
||||
)
|
||||
vllm_config = _minimal_vllm_config(cache_block_size=16)
|
||||
# Hash unit 4 < mamba block 16 -> partial hash hits are enabled.
|
||||
vllm_config.cache_config.prefix_match_unit = 4
|
||||
store = _DictStore()
|
||||
|
||||
worker = _build_worker_with_dict_store(vllm_config, cfg, store)
|
||||
worker.tp_size = 1
|
||||
worker.pp_size = 1
|
||||
worker.num_kv_head = 8
|
||||
assert worker.coord.enable_partial_hash_hits
|
||||
|
||||
for g_idx, db in enumerate(worker.token_dbs):
|
||||
db.set_kv_caches_base_addr([g_idx * 10_000])
|
||||
db.set_block_len([512])
|
||||
|
||||
send_thread = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
token_databases=worker.token_dbs,
|
||||
block_size=worker.block_size,
|
||||
coord=worker.coord,
|
||||
tp_rank=0,
|
||||
group_put_steps=[1, 1],
|
||||
kv_role="kv_both",
|
||||
ready_event=threading.Event(),
|
||||
replicate_config=MagicMock(),
|
||||
)
|
||||
|
||||
# A 12-token prompt leaves a resend-safe sub-block checkpoint at 8.
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(5)]
|
||||
req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=0,
|
||||
block_ids=([1], [2]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
num_prompt_tokens=12,
|
||||
completed_token_len=12,
|
||||
boundary_puts=[(1, 7, 8)],
|
||||
)
|
||||
send_thread._maybe_offload_boundary_states(_resolve_partial_tail(send_thread, req))
|
||||
|
||||
worker.store = store
|
||||
|
||||
# A 13-token prompt sharing the prefix must hit the stored boundary at 8.
|
||||
assert worker.lookup(num_tokens=13, block_hashes=hs).hit_length == 8
|
||||
|
||||
|
||||
def test_worker_setup_tolerates_finer_scratch_group():
|
||||
"""Setup and lookup must tolerate a non-prefix-cacheable scratch group.
|
||||
|
||||
Regression: GLM-5.3-Flash carries a kpool-tail scratch group whose block
|
||||
size (``index_kpool`` tokens) is finer than the hash unit, so the
|
||||
coordinator's divisibility assert and the scratch group's
|
||||
``ChunkedTokenDatabase`` both rejected worker setup for any hash unit the
|
||||
scratch block does not divide. Scratch groups never participate in
|
||||
store/load/lookup, so setup must skip them and lookup must still hit
|
||||
stored sub-block boundaries on the participating groups.
|
||||
"""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
mamba = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((1, 1),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
# Scratch block 4 is not divisible by the hash unit 8 below.
|
||||
scratch = CircularBufferSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=2,
|
||||
head_size=64,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
cfg = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=4 * full.page_size_bytes,
|
||||
layers=["L0"],
|
||||
layer_stride=4 * full.page_size_bytes,
|
||||
block_stride=full.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=4 * mamba.page_size_bytes,
|
||||
layers=["L1"],
|
||||
layer_stride=4 * mamba.page_size_bytes,
|
||||
block_stride=mamba.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=4 * scratch.page_size_bytes,
|
||||
layers=["L2"],
|
||||
layer_stride=4 * scratch.page_size_bytes,
|
||||
block_stride=scratch.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], mamba),
|
||||
KVCacheGroupSpec(["L2"], scratch),
|
||||
],
|
||||
# The hit alignment the engine core resolves for this config.
|
||||
cache_hit_alignment_tokens=8,
|
||||
)
|
||||
vllm_config = _minimal_vllm_config(cache_block_size=16)
|
||||
# Hash unit 8 divides the participating groups (16) but not the scratch
|
||||
# group (4); mamba block 16 > 8 keeps partial hash hits on.
|
||||
vllm_config.cache_config.prefix_match_unit = 8
|
||||
store = _DictStore()
|
||||
|
||||
worker = _build_worker_with_dict_store(vllm_config, cfg, store)
|
||||
worker.tp_size = 1
|
||||
worker.pp_size = 1
|
||||
worker.num_kv_head = 8
|
||||
assert worker.coord.enable_partial_hash_hits
|
||||
# Only the participating full-attention and Mamba groups are registered.
|
||||
assert len(worker.token_dbs) == 2
|
||||
assert all(db.hash_block_size == 8 for db in worker.token_dbs)
|
||||
|
||||
for g_idx, db in enumerate(worker.token_dbs):
|
||||
db.set_kv_caches_base_addr([g_idx * 10_000])
|
||||
db.set_block_len([512])
|
||||
|
||||
send_thread = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
token_databases=worker.token_dbs,
|
||||
block_size=worker.block_size,
|
||||
coord=worker.coord,
|
||||
tp_rank=0,
|
||||
group_put_steps=[1, 1],
|
||||
kv_role="kv_both",
|
||||
ready_event=threading.Event(),
|
||||
replicate_config=MagicMock(),
|
||||
group_participates=[True, True],
|
||||
)
|
||||
|
||||
# Persist the sub-block partial tail at boundary 8 (keyed by hs[8//8-1]).
|
||||
hs = [BlockHash(bytes([i + 1]) * 8) for i in range(3)]
|
||||
req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=0,
|
||||
block_ids=([1], [2]),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
num_prompt_tokens=12,
|
||||
completed_token_len=12,
|
||||
boundary_puts=[(1, 7, 8)],
|
||||
)
|
||||
send_thread._maybe_offload_boundary_states(_resolve_partial_tail(send_thread, req))
|
||||
|
||||
worker.store = store
|
||||
|
||||
# A 13-token prompt sharing the prefix must hit the first hash unit.
|
||||
assert worker.lookup(num_tokens=13, block_hashes=hs).hit_length == 8
|
||||
# The scratch group's namespace never enters the store.
|
||||
assert not any("@group:2" in key for key in store._data)
|
||||
|
||||
|
||||
def test_ring_scratch_group_is_never_stored_and_does_not_block_hits():
|
||||
"""A per-request ring group (CircularBufferSpec, capacity as block_size)
|
||||
sits beside the paged group: worker setup tolerates its block size (the
|
||||
DeepSeek-V4.1 compressor ring is 8 rows), saving a request stores paged
|
||||
blocks only, and lookup hits on the paged group alone."""
|
||||
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
|
||||
ring = CircularBufferSpec(
|
||||
block_size=8, num_kv_heads=1, head_size=64, head_size_v=0, dtype=torch.uint8
|
||||
)
|
||||
cfg = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=4 * full.page_size_bytes,
|
||||
layers=["L0"],
|
||||
layer_stride=4 * full.page_size_bytes,
|
||||
block_stride=full.page_size_bytes,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=4 * ring.page_size_bytes,
|
||||
layers=["L1"],
|
||||
layer_stride=4 * ring.page_size_bytes,
|
||||
block_stride=ring.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["L0"], full),
|
||||
KVCacheGroupSpec(["L1"], ring),
|
||||
],
|
||||
)
|
||||
vllm_config = _minimal_vllm_config(cache_block_size=16)
|
||||
store = _DictStore()
|
||||
|
||||
worker = _build_worker_with_dict_store(vllm_config, cfg, store)
|
||||
worker.tp_size = 1
|
||||
worker.pp_size = 1
|
||||
worker.num_kv_head = 8
|
||||
assert len(worker.token_dbs) == 1
|
||||
assert worker.token_dbs[0].hash_block_size == 16
|
||||
|
||||
raw_full = torch.zeros(4 * full.page_size_bytes, dtype=torch.int8)
|
||||
raw_ring = torch.zeros(4 * ring.page_size_bytes, dtype=torch.int8)
|
||||
kv_caches = {
|
||||
"L0": dense_kv_cache_views(raw_full, full, 4, 1, KVCacheLayout.LBNHC)[0],
|
||||
"L1": dense_kv_cache_views(raw_ring, ring, 4, 1, KVCacheLayout.LBNHC)[0],
|
||||
}
|
||||
|
||||
def _fake_thread_init(*args, **kwargs):
|
||||
for v in list(args) + list(kwargs.values()):
|
||||
if isinstance(v, threading.Event):
|
||||
v.set()
|
||||
m = MagicMock()
|
||||
m.start = lambda: None
|
||||
return m
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
mooncake_store_worker,
|
||||
"KVCacheStoreSendingThread",
|
||||
side_effect=_fake_thread_init,
|
||||
),
|
||||
patch.object(
|
||||
mooncake_store_worker,
|
||||
"KVCacheStoreRecvingThread",
|
||||
side_effect=_fake_thread_init,
|
||||
),
|
||||
):
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
send_thread = KVCacheStoreSendingThread(
|
||||
store=store,
|
||||
token_databases=worker.token_dbs,
|
||||
block_size=worker.block_size,
|
||||
coord=worker.coord,
|
||||
tp_rank=worker.tp_rank,
|
||||
group_put_steps=worker._group_tp_replication_factors,
|
||||
kv_role=worker.kv_role,
|
||||
ready_event=threading.Event(),
|
||||
enable_kv_event=False,
|
||||
group_participates=[True],
|
||||
)
|
||||
hs = [BlockHash(bytes([i + 1]) * 4) for i in range(4)]
|
||||
save_req = ReqMeta(
|
||||
req_id="r0",
|
||||
token_len_chunk=64,
|
||||
# Scheduler metadata is projected to the participating store groups.
|
||||
block_ids=([1, 2, 3, 4],),
|
||||
block_hashes=hs,
|
||||
can_save=True,
|
||||
store_job_id=1,
|
||||
)
|
||||
send_thread.add_request(save_req)
|
||||
send_thread._handle_request(send_thread.request_queue.get())
|
||||
worker.store = store
|
||||
|
||||
assert worker.lookup(num_tokens=65, block_hashes=hs).hit_length == 64
|
||||
assert not any("@group:1" in key for key in store._data)
|
||||
@@ -1,180 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for Mooncake Store payload layouts."""
|
||||
|
||||
import ctypes
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.data import (
|
||||
ChunkedTokenDatabase,
|
||||
KeyMetadata,
|
||||
LBHNCStoreLayout,
|
||||
LBNHCStoreLayout,
|
||||
RankLocalStoreLayout,
|
||||
)
|
||||
from vllm.utils.math_utils import cdiv
|
||||
|
||||
BLOCK_SIZE = 128
|
||||
|
||||
|
||||
def _rank_local_layout(num_regions: int, num_block_lens: int) -> RankLocalStoreLayout:
|
||||
metadata = KeyMetadata("test-model", 1, 0, 0, 0)
|
||||
layout = RankLocalStoreLayout(metadata, BLOCK_SIZE, BLOCK_SIZE)
|
||||
layout.set_kv_caches_base_addr(
|
||||
[0x7F00_0000_0000 + i * (1 << 30) for i in range(num_regions)]
|
||||
)
|
||||
layout.set_block_len([30_208 + 512 * i for i in range(num_block_lens)])
|
||||
return layout
|
||||
|
||||
|
||||
def _rank_local_reference(
|
||||
layout: RankLocalStoreLayout, start: int, end: int, block_ids: list[int]
|
||||
) -> tuple[list[int], list[int], int]:
|
||||
block_id = block_ids[start // layout.block_size]
|
||||
length = len(layout.block_len)
|
||||
addrs = [
|
||||
base_addr + block_id * layout.block_len[index % length]
|
||||
for index, base_addr in enumerate(layout.kv_caches_base_addr)
|
||||
]
|
||||
sizes = [
|
||||
layout.block_len[index % length] * cdiv(end - start, layout.block_size)
|
||||
for index in range(len(layout.kv_caches_base_addr))
|
||||
]
|
||||
return addrs, sizes, block_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_regions,num_block_lens", [(96, 96), (96, 2), (1, 1)])
|
||||
def test_rank_local_descriptors_match_reference(num_regions: int, num_block_lens: int):
|
||||
layout = _rank_local_layout(num_regions, num_block_lens)
|
||||
rng = random.Random(0)
|
||||
block_ids = [rng.randrange(0, 1 << 20) for _ in range(300)]
|
||||
chunks = []
|
||||
block = 0
|
||||
while block < len(block_ids) - 4:
|
||||
span = rng.choice([1, 1, 1, 2, 4])
|
||||
chunks.append((block * BLOCK_SIZE, (block + span) * BLOCK_SIZE))
|
||||
block += span + rng.choice([0, 1])
|
||||
|
||||
addrs, sizes, selected_blocks = layout.prepare_values(
|
||||
chunks, block_ids, [0] * len(chunks)
|
||||
)
|
||||
|
||||
for chunk, chunk_addrs, chunk_sizes, block_id in zip(
|
||||
chunks, addrs, sizes, selected_blocks, strict=True
|
||||
):
|
||||
assert (chunk_addrs, chunk_sizes, block_id) == _rank_local_reference(
|
||||
layout, *chunk, block_ids
|
||||
)
|
||||
assert all(type(addr) is int for addr in chunk_addrs)
|
||||
assert type(block_id) is int
|
||||
|
||||
|
||||
def test_rank_local_descriptors_handle_empty_and_invalid_chunks():
|
||||
layout = _rank_local_layout(4, 4)
|
||||
assert layout.prepare_values([], [1, 2, 3], []) == ([], [], [])
|
||||
with pytest.raises(AssertionError):
|
||||
layout.prepare_values([(0, BLOCK_SIZE + 1)], [0, 1], [0])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("layout_cls", "store_format"),
|
||||
[
|
||||
(LBHNCStoreLayout, "tp_shared_lbhnc"),
|
||||
(LBNHCStoreLayout, "tp_shared_lbnhc"),
|
||||
],
|
||||
)
|
||||
def test_tp_shared_layout_owns_store_namespace(layout_cls, store_format):
|
||||
assert (
|
||||
layout_cls.shared_namespace(4, 2)
|
||||
== f"@store_tp:4@store_pp:2@store_format:{store_format}"
|
||||
)
|
||||
|
||||
|
||||
def test_rank_local_database_api_rejects_tp_shared_layout():
|
||||
metadata = KeyMetadata("test-model", 0, 0, 0, 0)
|
||||
layout = LBHNCStoreLayout(
|
||||
metadata,
|
||||
block_size=16,
|
||||
hash_block_size=16,
|
||||
local_tp_size=2,
|
||||
store_tp_size=4,
|
||||
tp_rank=0,
|
||||
num_kv_heads=8,
|
||||
)
|
||||
database = ChunkedTokenDatabase(metadata, 16, store_layout=layout)
|
||||
|
||||
with pytest.raises(RuntimeError, match="rank-local"):
|
||||
database.prepare_value_for_block(0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("layout_cls", "producer_strides", "consumer_strides"),
|
||||
[
|
||||
(LBHNCStoreLayout, (128, 64, 4, 1), (256, 64, 4, 1)),
|
||||
(LBNHCStoreLayout, (128, 4, 8, 1), (256, 4, 16, 1)),
|
||||
],
|
||||
)
|
||||
def test_tp_shared_layout_round_trip_across_tp_sizes(
|
||||
layout_cls, producer_strides, consumer_strides
|
||||
):
|
||||
block_size = 16
|
||||
shape = (1, 2, block_size, 4)
|
||||
stored: dict[int, bytes] = {}
|
||||
producer_tensors = []
|
||||
|
||||
for tp_rank in range(4):
|
||||
tensor = torch.empty_strided(shape, producer_strides, dtype=torch.float16)
|
||||
tensor.copy_(
|
||||
torch.arange(128, dtype=torch.float16).view(shape) + tp_rank * 1000
|
||||
)
|
||||
producer_tensors.append(tensor)
|
||||
metadata = KeyMetadata("test-model", tp_rank, 0, 0, 0)
|
||||
layout = layout_cls(
|
||||
metadata,
|
||||
block_size,
|
||||
block_size,
|
||||
local_tp_size=4,
|
||||
store_tp_size=4,
|
||||
tp_rank=tp_rank,
|
||||
num_kv_heads=8,
|
||||
)
|
||||
layout.register_kv_caches([tensor], 1)
|
||||
addrs, sizes, _ = layout.prepare_values([(0, block_size)], [0], [tp_rank])
|
||||
stored[tp_rank] = b"".join(
|
||||
ctypes.string_at(addr, size)
|
||||
for addr, size in zip(addrs[0], sizes[0], strict=True)
|
||||
)
|
||||
|
||||
for tp_rank in range(2):
|
||||
tensor = torch.empty_strided(
|
||||
(1, 4, block_size, 4), consumer_strides, dtype=torch.float16
|
||||
)
|
||||
tensor.zero_()
|
||||
metadata = KeyMetadata("test-model", tp_rank, 0, 0, 0)
|
||||
layout = layout_cls(
|
||||
metadata,
|
||||
block_size,
|
||||
block_size,
|
||||
local_tp_size=2,
|
||||
store_tp_size=4,
|
||||
tp_rank=tp_rank,
|
||||
num_kv_heads=8,
|
||||
)
|
||||
layout.register_kv_caches([tensor], 1)
|
||||
shard_ids = layout.local_shard_ids
|
||||
addrs, sizes, _ = layout.prepare_values(
|
||||
[(0, block_size)] * len(shard_ids), [0], shard_ids
|
||||
)
|
||||
for shard_id, shard_addrs, shard_sizes in zip(
|
||||
shard_ids, addrs, sizes, strict=True
|
||||
):
|
||||
offset = 0
|
||||
for addr, size in zip(shard_addrs, shard_sizes, strict=True):
|
||||
ctypes.memmove(addr, stored[shard_id][offset : offset + size], size)
|
||||
offset += size
|
||||
|
||||
expected = torch.cat(producer_tensors[tp_rank * 2 : tp_rank * 2 + 2], dim=1)
|
||||
torch.testing.assert_close(tensor, expected)
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user