Merge remote-tracking branch 'upstream/main' into patches
This commit is contained in:
@@ -19,7 +19,12 @@ from tests.v1.attention.utils import (
|
||||
try_backend_includes_kv_cache_update,
|
||||
try_get_attention_backend,
|
||||
)
|
||||
from vllm.config import ModelConfig, set_current_vllm_config
|
||||
from vllm.config import (
|
||||
DiffusionConfig,
|
||||
ModelConfig,
|
||||
SpeculativeConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import (
|
||||
@@ -942,8 +947,6 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa
|
||||
impl.o_sf_scale = None
|
||||
impl.window_left = -1
|
||||
impl.sinks = None
|
||||
impl.cache_config = unittest.mock.Mock()
|
||||
impl.cache_config.get_resolved_kv_cache_layout.return_value = KVCacheLayout.LBHNC
|
||||
|
||||
layer = unittest.mock.Mock(
|
||||
_q_scale=torch.tensor(1.0),
|
||||
@@ -959,6 +962,7 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa
|
||||
q_len_per_req=1,
|
||||
)
|
||||
attn_metadata = flashinfer_backend.FlashInferMetadata(
|
||||
kv_cache_layout=KVCacheLayout.LBHNC,
|
||||
num_actual_tokens=2,
|
||||
slot_mapping=torch.empty(0, dtype=torch.int64),
|
||||
q_data_type_prefill=torch.bfloat16,
|
||||
@@ -1070,6 +1074,87 @@ def test_flashinfer_trtllm_gen_padded_decode_uses_varlen_offsets(
|
||||
assert q_cu_seq_lens.tolist() == qo_indptr_values
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda()
|
||||
or AttentionBackendEnum.FLASHINFER not in BACKENDS_TO_TEST,
|
||||
reason="FlashInfer with CUDA is required.",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"runner_type,spec_kind,has_upper_bound,expected_copies",
|
||||
[
|
||||
("generate", None, True, 0),
|
||||
("pooling", None, True, 0),
|
||||
("generate", None, False, 1),
|
||||
("generate", "spec_decode", True, 1),
|
||||
("generate", "diffusion", True, 1),
|
||||
],
|
||||
)
|
||||
def test_flashinfer_avoids_seq_lens_copy_without_spec_tokens(
|
||||
monkeypatch, runner_type, spec_kind, has_upper_bound, expected_copies
|
||||
):
|
||||
"""Planning reuses the host seq_lens bound only when it is exact.
|
||||
|
||||
Without speculative token accounting (no spec-decode drafts, no dLLM
|
||||
canvas tokens) scheduled tokens always land in KV, so the CPU upper bound
|
||||
is exact regardless of runner type. Any speculative accounting keeps the
|
||||
bound optimistic (rejected tokens are in-flight) and forces the copy.
|
||||
"""
|
||||
import unittest.mock
|
||||
|
||||
from vllm.v1.attention.backends import flashinfer as flashinfer_backend
|
||||
from vllm.v1.attention.backends.utils import PerLayerParameters
|
||||
|
||||
monkeypatch.setattr(
|
||||
flashinfer_backend,
|
||||
"get_per_layer_parameters",
|
||||
lambda *args: {
|
||||
"layer.0": PerLayerParameters(
|
||||
window_left=-1, logits_soft_cap=0.0, sm_scale=0.125
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
config = create_vllm_config(
|
||||
model_name="Qwen/Qwen3-0.6B", max_model_len=64, max_num_seqs=3
|
||||
)
|
||||
config.model_config.runner_type = runner_type
|
||||
config.attention_config.use_trtllm_attention = False
|
||||
if spec_kind == "spec_decode":
|
||||
config.speculative_config = SpeculativeConfig(
|
||||
method="ngram", num_speculative_tokens=3
|
||||
)
|
||||
elif spec_kind == "diffusion":
|
||||
config.diffusion_config = DiffusionConfig(canvas_length=8)
|
||||
device = torch.device(f"{DEVICE_TYPE}:0")
|
||||
# Include a one-token final chunk and both partial and full KV pages.
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
BatchSpec(seq_lens=[17, 20, 32], query_lens=[1, 4, 16]), 16, device
|
||||
)
|
||||
if not has_upper_bound:
|
||||
common_attn_metadata.seq_lens_cpu_upper_bound = None
|
||||
elif spec_kind is not None:
|
||||
# Simulate rejected speculative tokens: CPU says 18, GPU says 17.
|
||||
assert common_attn_metadata.seq_lens_cpu_upper_bound is not None
|
||||
common_attn_metadata.seq_lens_cpu_upper_bound[0] += 1
|
||||
|
||||
with set_current_vllm_config(config):
|
||||
builder = flashinfer_backend.FlashInferMetadataBuilder(
|
||||
create_standard_kv_cache_spec(config), ["layer.0"], config, device
|
||||
)
|
||||
with unittest.mock.patch.object(
|
||||
common_attn_metadata.seq_lens,
|
||||
"cpu",
|
||||
wraps=common_attn_metadata.seq_lens.cpu,
|
||||
) as copy_to_cpu:
|
||||
metadata = builder.build(0, common_attn_metadata)
|
||||
|
||||
assert copy_to_cpu.call_count == expected_copies
|
||||
assert metadata.num_decodes == 1
|
||||
assert metadata.num_prefills == 2
|
||||
assert builder.paged_kv_indptr.cpu[:4].tolist() == [0, 2, 4, 6]
|
||||
assert builder.paged_kv_last_page_len.cpu[:3].tolist() == [1, 4, 16]
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
AttentionBackendEnum.FLASHINFER not in BACKENDS_TO_TEST,
|
||||
reason="FlashInfer is not available.",
|
||||
|
||||
@@ -25,6 +25,9 @@ from vllm.v1.attention.backends.mla.prefill.cpu_sdpa import (
|
||||
from vllm.v1.attention.backends.mla.prefill.selector import (
|
||||
get_mla_prefill_backend,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.prefill.zen_cpu_sdpa import (
|
||||
ZenCPUSDPAMLAPrefillBackend,
|
||||
)
|
||||
|
||||
|
||||
def _reference_ragged_attention(
|
||||
@@ -157,8 +160,10 @@ def test_cpu_mla_backend_smoke(tmp_path) -> None:
|
||||
def test_cpu_mla_prefill_backend_selected() -> None:
|
||||
# On CPU (no device capability) the MLA prefill backend must be the
|
||||
# SDPA-based CPU backend, not flash-attn which is unavailable on CPU.
|
||||
# Accelerator-specific subclasses (e.g. the zentorch-backed Zen CPU
|
||||
# backend) are also valid selections.
|
||||
backend_cls = get_mla_prefill_backend(None)
|
||||
assert backend_cls is CPUSDPAMLAPrefillBackend
|
||||
assert issubclass(backend_cls, CPUSDPAMLAPrefillBackend)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
@@ -248,3 +253,64 @@ def test_cpu_mla_prefill_context_chunk() -> None:
|
||||
assert lse.float().allclose(ref_lse.float(), atol=2e-2)
|
||||
assert out.shape == (5, 4, 16)
|
||||
assert lse.shape == (4, 5)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
|
||||
@pytest.mark.skipif(
|
||||
not ZenCPUSDPAMLAPrefillBackend.is_available(),
|
||||
reason="requires a Zen CPU with the zentorch_sdpa op registered",
|
||||
)
|
||||
def test_zen_cpu_mla_prefill_new_tokens() -> None:
|
||||
# Runs the zentorch kernel itself. The head dims are deliberately
|
||||
# asymmetric (v_head_dim < qk_head_dim, as in real MLA) so that the V
|
||||
# padding and output slicing are exercised; the generic-CPU cases above
|
||||
# use equal dims and never reach that code.
|
||||
qk_head_dim = 24
|
||||
v_head_dim = 16
|
||||
backend = ZenCPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=None,
|
||||
)
|
||||
|
||||
class _PrefillMeta:
|
||||
query_start_loc = torch.tensor([0, 3, 6], dtype=torch.int32)
|
||||
|
||||
backend.prepare_metadata(_PrefillMeta())
|
||||
q = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
|
||||
k = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
|
||||
v = torch.randn(6, 4, v_head_dim, dtype=torch.bfloat16)
|
||||
|
||||
out = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=False)
|
||||
ref, _ = _reference_ragged_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
_PrefillMeta.query_start_loc,
|
||||
_PrefillMeta.query_start_loc,
|
||||
scale=0.25,
|
||||
causal=True,
|
||||
)
|
||||
assert out.shape == (6, 4, v_head_dim)
|
||||
assert out.float().allclose(ref.float(), atol=2e-2)
|
||||
|
||||
# zentorch_sdpa does not return a usable LSE, so that path must fall back
|
||||
# to the fp32 reference and match the generic backend exactly.
|
||||
generic = CPUSDPAMLAPrefillBackend(
|
||||
num_heads=4,
|
||||
scale=0.25,
|
||||
kv_lora_rank=16,
|
||||
qk_nope_head_dim=16,
|
||||
qk_rope_head_dim=8,
|
||||
v_head_dim=v_head_dim,
|
||||
vllm_config=None,
|
||||
)
|
||||
generic.prepare_metadata(_PrefillMeta())
|
||||
zen_out, zen_lse = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
|
||||
gen_out, gen_lse = generic.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
|
||||
assert torch.equal(zen_out, gen_out)
|
||||
assert torch.equal(zen_lse, gen_lse)
|
||||
|
||||
@@ -9,6 +9,7 @@ causality), ckv/kpe cache splitting, and the backend's model-shape gates.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -50,6 +51,8 @@ class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.plan_args = None
|
||||
self.run_args = None
|
||||
self._plan_info: Any = None
|
||||
self._planned_backend: Any = None
|
||||
|
||||
def plan(self, *args, **kwargs):
|
||||
self.plan_args = (args, kwargs)
|
||||
@@ -69,8 +72,11 @@ class FakeState:
|
||||
self.kv_indptr = torch.zeros(max_tokens + 1, dtype=torch.int32)
|
||||
self.wrapper = FakeWrapper()
|
||||
self.plan_calls = []
|
||||
self.index_topk = 2048
|
||||
self.index_kpool = 4
|
||||
self.max_valid = 2051
|
||||
|
||||
def plan(self, num_tokens, kv_lens):
|
||||
def plan(self, num_tokens, kv_lens, cam, req_id_per_token):
|
||||
self.plan_calls.append((num_tokens, kv_lens))
|
||||
|
||||
def pack_indices(self, slots):
|
||||
@@ -168,13 +174,12 @@ def test_forward_wiring(monkeypatch, qk_rope, kv_dtype):
|
||||
def test_builder_plans_only_rows_dispatched_to_mqa(monkeypatch, use_mha, num_decodes):
|
||||
"""MHA prefill rows must not make the MQA kernel read beyond its query."""
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
builder._index_topk = 2048
|
||||
builder._index_kpool = 4
|
||||
builder._async_scheduling = False
|
||||
builder._adaptive_verification = False
|
||||
builder.state = FakeState(TOPK)
|
||||
builder._attention_layer = SimpleNamespace(_use_sparse_mha=lambda _: use_mha)
|
||||
metadata = object.__new__(sm90_mod.FlashInferMLASparseSM90Metadata)
|
||||
metadata.state = None
|
||||
metadata.req_id_per_token = None
|
||||
metadata.num_prefills = 1
|
||||
metadata.num_decode_tokens = num_decodes
|
||||
monkeypatch.setattr(
|
||||
@@ -206,12 +211,17 @@ def test_builder_plans_only_rows_dispatched_to_mqa(monkeypatch, use_mha, num_dec
|
||||
def test_plan_uses_state_params(monkeypatch):
|
||||
"""The NoPE/rope dims and scale live on the builder state, not the layer.
|
||||
|
||||
plan() takes exact per-row KV lengths; the schedule is rebuilt on every
|
||||
call (contexts grow between steps) and the indptrs are always full-size
|
||||
Without a device batch layout plan() takes exact per-row KV lengths and
|
||||
rebuilds the schedule on every call; the indptrs are always full-size
|
||||
with zero-query padding rows past num_tokens.
|
||||
"""
|
||||
impl, rows = make_impl(64, "auto")
|
||||
wrapper = FakeWrapper()
|
||||
plan_info = [0] * sm90_mod._PLAN_INFO_LEN
|
||||
plan_info[sm90_mod._PI_KV_INDPTR] = 64 * 4
|
||||
wrapper._plan_info = torch.tensor(plan_info)
|
||||
wrapper._planned_backend = SimpleNamespace(
|
||||
_int_workspace_buffer=torch.zeros(64, dtype=torch.int32)
|
||||
)
|
||||
state = sm90_mod._SM90State.__new__(sm90_mod._SM90State)
|
||||
state.device = torch.device("cpu")
|
||||
state.wrapper = wrapper
|
||||
@@ -227,8 +237,9 @@ def test_plan_uses_state_params(monkeypatch):
|
||||
state._qo_cpu = torch.empty(5, dtype=torch.int32)
|
||||
state._kv_cpu = torch.empty(5, dtype=torch.int32)
|
||||
state._lens_cpu = torch.full((4,), TOPK, dtype=torch.int32)
|
||||
state._saved_kv_end = torch.empty(0, dtype=torch.int32)
|
||||
|
||||
state.plan(3, torch.tensor([2, 5, 7], dtype=torch.int32))
|
||||
state.plan(3, torch.tensor([2, 5, 7], dtype=torch.int32), None, None)
|
||||
assert wrapper.plan_args is not None
|
||||
args, kwargs = wrapper.plan_args
|
||||
(qo, kv, indices, kv_len, heads, ckv, kpe, page, causal, scale) = args
|
||||
@@ -241,10 +252,10 @@ def test_plan_uses_state_params(monkeypatch):
|
||||
assert kwargs["kv_data_type"] == torch.bfloat16
|
||||
|
||||
# Replanning a smaller batch must clear the previous rows' lengths.
|
||||
state.plan(1, torch.tensor([TOPK], dtype=torch.int32))
|
||||
state.plan(1, torch.tensor([TOPK], dtype=torch.int32), None, None)
|
||||
assert state._kv_cpu.tolist() == [0, TOPK, TOPK, TOPK, TOPK]
|
||||
assert state._lens_cpu.tolist() == [TOPK, 0, 0, 0]
|
||||
state.plan(0, torch.empty(0, dtype=torch.int32))
|
||||
state.plan(0, torch.empty(0, dtype=torch.int32), None, None)
|
||||
assert state._kv_cpu.tolist() == [0, 0, 0, 0, 0]
|
||||
assert state._lens_cpu.tolist() == [0, 0, 0, 0]
|
||||
|
||||
@@ -279,38 +290,49 @@ def test_pack_indices_replays_with_updated_offsets(width):
|
||||
assert (state.kv_indices[expected.numel() :] == -99).all()
|
||||
|
||||
|
||||
def test_kv_lens_host_formula():
|
||||
@pytest.mark.parametrize("adaptive", [False, True])
|
||||
def test_kv_lens_host_formula(adaptive):
|
||||
"""Per-row host lengths: context == position + 1; capped at
|
||||
index_topk + trailing-pool remainder past the sparse threshold."""
|
||||
index_topk + trailing-pool remainder past the sparse threshold.
|
||||
|
||||
Exact (synced) without a host upper bound; with one, a sync-free bound
|
||||
capped at the largest valid count, which the plan clamps on device.
|
||||
"""
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
builder._index_topk = 2048
|
||||
builder._index_kpool = 4
|
||||
builder._async_scheduling = False
|
||||
builder.state = FakeState(TOPK)
|
||||
builder._adaptive_verification = adaptive
|
||||
seq_lens = torch.tensor([100, 9, 3000], dtype=torch.int32)
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=3,
|
||||
query_start_loc_cpu=torch.tensor([0, 5, 7, 10], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([100, 9, 3000], dtype=torch.int32),
|
||||
seq_lens_cpu_upper_bound=torch.tensor([100, 9, 3000], dtype=torch.int32),
|
||||
positions=None,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
)
|
||||
num_rows, lens = builder._kv_lens_host(cam)
|
||||
assert num_rows == 10
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 10 and exact
|
||||
# req0: positions 95..99 -> ctx 96..100 (all <= 2048: full context)
|
||||
# req1: positions 7,8 -> ctx 8,9
|
||||
# req2: positions 2997..2999 -> ctx 2998..3000 (> 2048: topk + ctx%4)
|
||||
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2050, 2051, 2048]
|
||||
|
||||
cam.seq_lens_cpu_upper_bound = seq_lens
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 10 and not exact
|
||||
if adaptive:
|
||||
# Host query split may differ from the device one: batch-wide bound.
|
||||
assert lens.tolist() == [2051] * 10
|
||||
else:
|
||||
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2051, 2051, 2051]
|
||||
|
||||
|
||||
def test_kv_lens_host_empty():
|
||||
builder = object.__new__(FlashInferMLASparseSM90Builder)
|
||||
builder._index_topk = 2048
|
||||
builder._index_kpool = 4
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=0,
|
||||
query_start_loc_cpu=torch.tensor([0], dtype=torch.int32),
|
||||
seq_lens=torch.zeros(0, dtype=torch.int32),
|
||||
)
|
||||
num_rows, lens = builder._kv_lens_host(cam)
|
||||
num_rows, lens, _ = builder._kv_lens_host(cam)
|
||||
assert num_rows == 0 and lens.numel() == 0
|
||||
|
||||
|
||||
@@ -334,7 +356,13 @@ def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens)
|
||||
"__init__",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(sm90_mod, "_SM90State", lambda *_args, **_kwargs: None)
|
||||
|
||||
class _RecordingState:
|
||||
def __init__(self, *_args, **kwargs):
|
||||
self.index_topk = kwargs["index_topk"]
|
||||
self.index_kpool = kwargs["index_kpool"]
|
||||
|
||||
monkeypatch.setattr(sm90_mod, "_SM90State", _RecordingState)
|
||||
impl, _ = make_impl(64)
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=BLOCK_SIZE, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
|
||||
@@ -351,6 +379,7 @@ def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens)
|
||||
max_num_batched_tokens=64, async_scheduling=False
|
||||
),
|
||||
model_config=SimpleNamespace(hf_text_config=hf_config),
|
||||
speculative_config=None,
|
||||
)
|
||||
builder = FlashInferMLASparseSM90Builder(
|
||||
spec, ["attn"], vllm_config, torch.device("cpu")
|
||||
@@ -359,14 +388,138 @@ def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens)
|
||||
cam = SimpleNamespace(
|
||||
num_reqs=2,
|
||||
query_start_loc_cpu=torch.tensor([0, 4, 6], dtype=torch.int32),
|
||||
seq_lens_cpu_upper_bound=torch.tensor([42295, 100], dtype=torch.int32),
|
||||
positions=None,
|
||||
seq_lens=torch.tensor([42295, 100], dtype=torch.int32),
|
||||
seq_lens_cpu_upper_bound=None,
|
||||
)
|
||||
num_rows, lens = builder._kv_lens_host(cam)
|
||||
assert num_rows == 6
|
||||
num_rows, lens, exact = builder._kv_lens_host(cam)
|
||||
assert num_rows == 6 and exact
|
||||
assert lens.tolist() == prefill_lens + [99, 100]
|
||||
|
||||
|
||||
def _sm90_flashinfer_available():
|
||||
return (
|
||||
torch.cuda.is_available()
|
||||
and torch.cuda.get_device_capability()[0] == 9
|
||||
and sm90_mod.has_flashinfer_sm90_nope_mla()
|
||||
)
|
||||
|
||||
|
||||
SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH = 16, 2048, 4, 2176
|
||||
|
||||
|
||||
def _real_state(rows):
|
||||
return sm90_mod._SM90State(
|
||||
torch.device("cuda"),
|
||||
SM90_HEADS,
|
||||
torch.bfloat16,
|
||||
rows,
|
||||
SM90_WIDTH,
|
||||
HEAD,
|
||||
0,
|
||||
HEAD**-0.5,
|
||||
SM90_TOPK,
|
||||
SM90_KPOOL,
|
||||
)
|
||||
|
||||
|
||||
def _clamp_batch(num_reqs, q_per_req, lo, hi, topk, kpool, width):
|
||||
"""Random batch: per-row contexts, device layout, and top-k slots."""
|
||||
last = torch.randint(lo + q_per_req, hi, (num_reqs,))
|
||||
ctx = (last[:, None] + torch.arange(1 - q_per_req, 1)).reshape(-1)
|
||||
valid = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
|
||||
cam = SimpleNamespace(
|
||||
seq_lens=last.to(torch.int32).cuda(),
|
||||
query_start_loc=(torch.arange(num_reqs + 1) * q_per_req).to(torch.int32).cuda(),
|
||||
)
|
||||
req_id = torch.arange(num_reqs, dtype=torch.int32).repeat_interleave(q_per_req)
|
||||
slots = torch.randint(0, 1 << 16, (ctx.numel(), width), dtype=torch.int32)
|
||||
slots[torch.arange(width) >= valid[:, None]] = -1
|
||||
return ctx, valid.to(torch.int32), cam, req_id.cuda(), slots.cuda()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"num_reqs,q_per_req,lo,hi",
|
||||
[
|
||||
(64, 1, 1, 3000),
|
||||
(16, 6, 2030, 2070), # MTP-style rows straddling index_topk
|
||||
(4096, 1, 1, 3000), # clamp spans several program blocks
|
||||
],
|
||||
)
|
||||
def test_upper_bound_plan_matches_exact(num_reqs, q_per_req, lo, hi):
|
||||
"""Sync-free planning from optimistic host bounds (async spec decode)
|
||||
must match exact planning: the device clamp trims every work item back
|
||||
to its row's valid count, so no -1 slot is read."""
|
||||
torch.manual_seed(0)
|
||||
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
|
||||
ctx, valid, cam, req_id, slots = _clamp_batch(
|
||||
num_reqs, q_per_req, lo, hi, topk, kpool, width
|
||||
)
|
||||
rows = ctx.numel()
|
||||
|
||||
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
q_pe = q.new_empty(rows, heads, 0)
|
||||
|
||||
def run(state):
|
||||
state.pack_indices(slots)
|
||||
return state.wrapper.run(q, q_pe, kv, kv[..., :0])
|
||||
|
||||
exact = _real_state(rows)
|
||||
exact.plan(rows, valid, None, None)
|
||||
ub = _real_state(rows)
|
||||
host_bound = torch.clamp(ctx + torch.randint(0, 7, (rows,)), max=ub.max_valid)
|
||||
ub.plan(rows, host_bound, cam, req_id)
|
||||
out = run(ub)
|
||||
assert not out.isnan().any()
|
||||
torch.testing.assert_close(out, run(exact), atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
|
||||
)
|
||||
def test_upper_bound_plan_reused_across_steps(monkeypatch):
|
||||
"""Growing contexts (draft/decode steps) reuse the padded plan and only
|
||||
re-clamp on device, matching an exact replan every step."""
|
||||
torch.manual_seed(0)
|
||||
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
|
||||
rows = 48
|
||||
ctx, _, _, req_id, _ = _clamp_batch(rows, 1, 1, 3000, topk, kpool, width)
|
||||
|
||||
exact, ub = _real_state(rows), _real_state(rows)
|
||||
replans: list[int] = []
|
||||
plan_fn = ub._plan
|
||||
|
||||
def counting_plan(num_tokens, kv_lens):
|
||||
replans.append(num_tokens)
|
||||
plan_fn(num_tokens, kv_lens)
|
||||
|
||||
monkeypatch.setattr(ub, "_plan", counting_plan)
|
||||
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
for step in range(5):
|
||||
step_ctx = ctx + step
|
||||
valid = torch.where(step_ctx <= topk, step_ctx, topk + step_ctx % kpool)
|
||||
slots = torch.randint(0, 1 << 16, (rows, width), dtype=torch.int32)
|
||||
slots[torch.arange(width) >= valid[:, None]] = -1
|
||||
slots = slots.cuda()
|
||||
cam = SimpleNamespace(
|
||||
seq_lens=step_ctx.to(torch.int32).cuda(),
|
||||
query_start_loc=torch.arange(rows + 1, dtype=torch.int32).cuda(),
|
||||
)
|
||||
num_plans = len(replans)
|
||||
ub.plan(rows, torch.clamp(step_ctx + 5, max=ub.max_valid), cam, req_id)
|
||||
assert len(replans) - num_plans == (1 if step == 0 else 0)
|
||||
exact.plan(rows, valid.to(torch.int32), None, None)
|
||||
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
|
||||
outs = []
|
||||
for state in (ub, exact):
|
||||
state.pack_indices(slots)
|
||||
outs.append(state.wrapper.run(q, q[..., :0], kv, kv[..., :0]))
|
||||
torch.testing.assert_close(outs[0], outs[1], atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
def test_supports_combination_gates(monkeypatch, default_vllm_config):
|
||||
monkeypatch.setattr(sm90_mod, "has_flashinfer_sm90_nope_mla", lambda: True)
|
||||
call = lambda **kw: FlashInferMLASparseSM90Backend.supports_combination(
|
||||
|
||||
@@ -21,6 +21,7 @@ from vllm.v1.attention.backends.gdn_attn import (
|
||||
GDNAttentionMetadata,
|
||||
GDNAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import mamba_get_block_table_tensor
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
@@ -75,6 +76,17 @@ GDN_BUILD_TEST_CASES = {
|
||||
expected_num_prefill_tokens=0,
|
||||
expected_num_spec_decodes=0,
|
||||
),
|
||||
# No speculative config, decode alongside prefill
|
||||
"regular_decode_with_prefill": GDNBuildTestCase(
|
||||
seq_lens=[40, 100],
|
||||
query_lens=[1, 50],
|
||||
num_decode_draft_tokens=None,
|
||||
num_speculative_tokens=0,
|
||||
expected_num_decodes=1,
|
||||
expected_num_prefills=1,
|
||||
expected_num_prefill_tokens=50,
|
||||
expected_num_spec_decodes=0,
|
||||
),
|
||||
# Multi-token prefill alongside spec decode — no decode to reclassify
|
||||
"spec_decode_with_real_prefill": GDNBuildTestCase(
|
||||
seq_lens=[100, 20],
|
||||
@@ -155,9 +167,12 @@ def _build(
|
||||
builder: GDNAttentionMetadataBuilder,
|
||||
batch_spec: BatchSpec,
|
||||
num_decode_draft_tokens: list[int] | None = None,
|
||||
block_table: torch.Tensor | None = None,
|
||||
) -> GDNAttentionMetadata:
|
||||
"""Build GDN attention metadata, optionally with spec-decode kwargs."""
|
||||
common = create_common_attn_metadata(batch_spec, BLOCK_SIZE, DEVICE)
|
||||
if block_table is not None:
|
||||
common = common.replace(block_table_tensor=block_table)
|
||||
kwargs: dict = {}
|
||||
if num_decode_draft_tokens is not None:
|
||||
kwargs["num_decode_draft_tokens_cpu"] = torch.tensor(
|
||||
@@ -184,6 +199,54 @@ def test_gdn_build_classification(test_case: GDNBuildTestCase):
|
||||
assert meta.num_spec_decodes == test_case.expected_num_spec_decodes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mamba_cache_mode", ["none", "align"])
|
||||
@pytest.mark.parametrize("full_cuda_graph", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"test_case", GDN_BUILD_TEST_CASES.values(), ids=GDN_BUILD_TEST_CASES.keys()
|
||||
)
|
||||
def test_update_block_table_matches_build(
|
||||
test_case: GDNBuildTestCase, full_cuda_graph: bool, mamba_cache_mode: str
|
||||
):
|
||||
"""update_block_table() on another group's metadata matches build()."""
|
||||
batch = BatchSpec(seq_lens=test_case.seq_lens, query_lens=test_case.query_lens)
|
||||
src, dst, ref = (
|
||||
_create_gdn_builder(test_case.num_speculative_tokens, full_cuda_graph)
|
||||
for _ in range(3)
|
||||
)
|
||||
for builder in (src, dst, ref):
|
||||
builder.vllm_config.cache_config.mamba_cache_mode = mamba_cache_mode
|
||||
common = create_common_attn_metadata(batch, BLOCK_SIZE, DEVICE)
|
||||
if mamba_cache_mode == "align":
|
||||
# MRV2 precomputes these for every Mamba group each step.
|
||||
dst.mamba_aligned_state_indices = ref.mamba_aligned_state_indices = (
|
||||
mamba_get_block_table_tensor(
|
||||
common.block_table_tensor, common.seq_lens, ref.kv_cache_spec, "align"
|
||||
)
|
||||
)
|
||||
draft_tokens = test_case.num_decode_draft_tokens
|
||||
expected = _build(ref, batch, draft_tokens, common.block_table_tensor)
|
||||
source = _build(src, batch, draft_tokens)
|
||||
fields = (
|
||||
"spec_state_indices_tensor",
|
||||
"non_spec_state_indices_tensor",
|
||||
"prefill_state_indices",
|
||||
)
|
||||
source_indices = [getattr(source, f) for f in fields]
|
||||
source_indices = [t if t is None else t.clone() for t in source_indices]
|
||||
meta = dst.update_block_table(
|
||||
source, common.block_table_tensor, common.slot_mapping
|
||||
)
|
||||
|
||||
for field, source_index in zip(fields, source_indices):
|
||||
actual = getattr(meta, field)
|
||||
torch.testing.assert_close(actual, getattr(expected, field))
|
||||
# The source group's indices are untouched.
|
||||
torch.testing.assert_close(getattr(source, field), source_index)
|
||||
# FULL graph state indices land in this group's own buffers.
|
||||
if full_cuda_graph and meta.num_prefills == 0 and actual is not None:
|
||||
assert actual.data_ptr() == getattr(dst, field).data_ptr()
|
||||
|
||||
|
||||
def test_has_initial_state_after_reclassification():
|
||||
"""After reclassification, num_prefills > 0 so the prefill kernel path
|
||||
should compute has_initial_state. For the reclassified request with
|
||||
|
||||
@@ -101,6 +101,7 @@ def test_flash_attention_geometry_comes_from_the_group():
|
||||
num_kv_heads=2,
|
||||
head_size=64,
|
||||
dtype=torch.bfloat16,
|
||||
dcp_sharded=True,
|
||||
)
|
||||
|
||||
with (
|
||||
|
||||
@@ -60,10 +60,43 @@ class TestGetMLAPrefillBackend:
|
||||
|
||||
def test_cpu_uses_sdpa_prefill(self):
|
||||
vllm_config = _make_vllm_config()
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
|
||||
# A Zen CPU with zentorch selects the Zen backend, so expect whichever
|
||||
# one this host offers.
|
||||
expected = (
|
||||
zen_cls if zen_cls.is_available() else MLAPrefillBackendEnum.CPU.get_class()
|
||||
)
|
||||
|
||||
with patch("vllm.platforms.current_platform") as mock_platform:
|
||||
mock_platform.is_cpu.return_value = True
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend is expected
|
||||
|
||||
def test_zen_cpu_prefers_zentorch_prefill(self):
|
||||
vllm_config = _make_vllm_config()
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.current_platform") as mock_platform,
|
||||
patch.object(zen_cls, "is_available", return_value=True),
|
||||
):
|
||||
mock_platform.is_cpu.return_value = True
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend is zen_cls
|
||||
|
||||
def test_zen_cpu_falls_back_when_zentorch_unavailable(self):
|
||||
vllm_config = _make_vllm_config()
|
||||
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
|
||||
|
||||
with (
|
||||
patch("vllm.platforms.current_platform") as mock_platform,
|
||||
patch.object(zen_cls, "is_available", return_value=False),
|
||||
):
|
||||
mock_platform.is_cpu.return_value = True
|
||||
|
||||
backend = get_mla_prefill_backend(vllm_config)
|
||||
assert backend is MLAPrefillBackendEnum.CPU.get_class()
|
||||
|
||||
|
||||
@@ -1599,19 +1599,142 @@ def test_project_kv_cache_groups_to_worker():
|
||||
assert set(proj_spec.kv_cache_specs.keys()) == {"layer1", "layer3"}
|
||||
|
||||
|
||||
def test_dcp_world_size_for_kv_cache_spec_shards_full_attention_only():
|
||||
dcp = 8
|
||||
full = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=1, dtype=torch.float32
|
||||
@pytest.mark.parametrize("sliding_window", [None, 256])
|
||||
@pytest.mark.parametrize("disable_hybrid", [False, True])
|
||||
@pytest.mark.parametrize("pcp_size", [1, 4])
|
||||
def test_dcp_target_allocates_replicated_draft_independently(
|
||||
monkeypatch, sliding_window, disable_hybrid, pcp_size
|
||||
):
|
||||
"""A draft must retain all positions even when the target shards them."""
|
||||
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
|
||||
|
||||
monkeypatch.delenv("VLLM_KV_CACHE_LAYOUT", raising=False)
|
||||
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
|
||||
config.parallel_config.decode_context_parallel_size = 4
|
||||
config.parallel_config.prefill_context_parallel_size = pcp_size
|
||||
config.scheduler_config.disable_hybrid_kv_cache_manager = disable_hybrid
|
||||
config.cache_config.block_size = 16
|
||||
config.cache_config.kv_cache_layout = None
|
||||
draft_args = dict(
|
||||
block_size=16,
|
||||
num_kv_heads=8,
|
||||
head_size=64,
|
||||
dtype=torch.bfloat16,
|
||||
dcp_sharded=False,
|
||||
)
|
||||
mla = new_mla_spec()
|
||||
mamba = new_mamba_spec()
|
||||
uniform_mla = UniformTypeKVCacheSpecs(block_size=16, kv_cache_specs={"layer": mla})
|
||||
assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(full, dcp) == dcp
|
||||
assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(mla, dcp) == dcp
|
||||
assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(uniform_mla, dcp) == dcp
|
||||
assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(mamba, dcp) == 1
|
||||
assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(full, 1) == 1
|
||||
draft = (
|
||||
FullAttentionSpec(**draft_args)
|
||||
if sliding_window is None
|
||||
else SlidingWindowSpec(**draft_args, sliding_window=sliding_window)
|
||||
)
|
||||
specs = {"target": new_mla_spec(), "draft": draft}
|
||||
layout = resolve_kv_cache_layout(config, [["LBHNC", "BLHNC"]], specs.values())
|
||||
assert layout == KVCacheLayout.BLHNC
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
assert [group.layer_names for group in groups] == [["target"], ["draft"]]
|
||||
widths = [g.kv_cache_spec.max_num_blocks_per_req(config, 1024) for g in groups]
|
||||
assert widths == [16, 64]
|
||||
|
||||
cache_config = kv_cache_utils.get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=16 * 1024 * 1024
|
||||
)
|
||||
scheduler_config = generate_scheduler_kv_cache_config([cache_config])
|
||||
assert get_max_concurrency_for_kv_cache_config(config, cache_config) > 0
|
||||
assert get_max_concurrency_for_kv_cache_config(config, cache_config) == (
|
||||
get_max_concurrency_for_kv_cache_config(config, scheduler_config)
|
||||
)
|
||||
manager = KVCacheManager(
|
||||
scheduler_config,
|
||||
max_model_len=1024,
|
||||
hash_block_size=16,
|
||||
scheduler_block_size=64,
|
||||
dcp_world_size=4,
|
||||
pcp_world_size=pcp_size,
|
||||
enable_caching=True,
|
||||
)
|
||||
assert manager.coordinator.group_block_sizes == (64, 16)
|
||||
request = make_request("replicated-draft", [1] * 65, block_size=16, hash_fn=sha256)
|
||||
blocks = manager.allocate_slots(request, 65)
|
||||
assert blocks is not None
|
||||
assert [len(group) for group in blocks.blocks] == [2, 5]
|
||||
manager.cache_blocks(request, 64)
|
||||
cached_request = make_request(
|
||||
"cached-draft", [1] * 65, block_size=16, hash_fn=sha256
|
||||
)
|
||||
cached_blocks, num_cached, _ = manager.get_computed_blocks(cached_request)
|
||||
assert num_cached == 64
|
||||
assert [len(group) for group in cached_blocks.blocks] == [1, 4]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_mla", [False, True])
|
||||
def test_full_attention_merge_preserves_replicated_cache_geometry(use_mla):
|
||||
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
|
||||
config.parallel_config.decode_context_parallel_size = 4
|
||||
draft = replace(
|
||||
new_mla_spec() if use_mla else new_kv_cache_spec(),
|
||||
block_size=16,
|
||||
dcp_sharded=False,
|
||||
)
|
||||
merged = type(draft).merge([draft, draft])
|
||||
wrapped = UniformTypeKVCacheSpecs.from_specs({"draft": merged})
|
||||
assert wrapped is not None and not wrapped.dcp_sharded
|
||||
assert merged.max_num_blocks_per_req(config, 1024) == 64
|
||||
assert merged.max_memory_usage_bytes(config) == 64 * draft.page_size_bytes
|
||||
assert kv_cache_utils.resolve_dcp_kv_block_size(merged, 4) == 16
|
||||
with pytest.raises(AssertionError):
|
||||
type(draft).merge([draft, replace(draft, dcp_sharded=True)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_draft", [False, True])
|
||||
@pytest.mark.parametrize("indexer_alignment", [None, 512])
|
||||
def test_sparse_mla_preserves_physical_row_addressing(with_draft, indexer_alignment):
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view
|
||||
from vllm.v1.worker.utils import allocate_kv_cache
|
||||
|
||||
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
|
||||
config.cache_config.kv_cache_layout = "BLHNC"
|
||||
config.parallel_config.decode_context_parallel_size = 4
|
||||
common = dict(block_size=64, num_kv_heads=1, dtype=torch.uint8)
|
||||
specs = {
|
||||
"target": MLAAttentionSpec(
|
||||
**common,
|
||||
head_size=576,
|
||||
state_content_bytes=656,
|
||||
block_stride_alignment=656,
|
||||
cache_dtype_str="fp8_ds_mla",
|
||||
is_index_group_leader=True,
|
||||
),
|
||||
"indexer": MLAAttentionSpec(
|
||||
**common,
|
||||
head_size=132,
|
||||
cache_role=SparseCacheRole.INDEXER,
|
||||
block_stride_alignment=indexer_alignment,
|
||||
),
|
||||
"draft": SlidingWindowSpec(
|
||||
block_size=64,
|
||||
num_kv_heads=64,
|
||||
head_size=64,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=2048,
|
||||
dcp_sharded=False,
|
||||
),
|
||||
}
|
||||
if not with_draft:
|
||||
del specs["draft"]
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
cache_config = kv_cache_utils.get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * 1024 * 1024
|
||||
)
|
||||
caches = allocate_kv_cache(
|
||||
cache_config, torch.device("cpu"), KVCacheLayout.BLHNC, [64] * len(groups)
|
||||
)
|
||||
cache = caches["target"].squeeze(1)
|
||||
if indexer_alignment is not None:
|
||||
assert caches["indexer"].stride(0) % indexer_alignment == 0
|
||||
rows, stride_rows = flat_kv_row_view(cache, 64)
|
||||
cache[1, 0].fill_(7)
|
||||
torch.testing.assert_close(rows[stride_rows], cache[1, 0])
|
||||
assert torch.all(rows[stride_rows] == 7)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -3815,6 +3938,8 @@ def test_unify_hybrid_kv_cache_specs():
|
||||
"layer_1": before_spec_1,
|
||||
"layer_2": before_spec_2,
|
||||
}
|
||||
kv_cache_spec["draft_layer_1"] = replace(before_spec_1, dcp_sharded=False)
|
||||
kv_cache_spec["draft_layer_2"] = replace(before_spec_2, dcp_sharded=False)
|
||||
kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec)
|
||||
expected_spec_1 = new_kv_cache_spec(block_size=64)
|
||||
expected_spec_2 = new_kv_cache_spec(
|
||||
@@ -3823,6 +3948,7 @@ def test_unify_hybrid_kv_cache_specs():
|
||||
assert kv_cache_spec["layer_1"] == expected_spec_1
|
||||
assert kv_cache_spec["layer_2"] == expected_spec_2
|
||||
assert kv_cache_spec["layer_2"].page_size_bytes == 64 * 1024
|
||||
assert kv_cache_spec["draft_layer_2"] == replace(expected_spec_2, dcp_sharded=False)
|
||||
|
||||
# 2. has_full_attention and has_chunked_local_attention
|
||||
before_spec_1 = new_kv_cache_spec()
|
||||
@@ -3874,6 +4000,11 @@ def test_unify_hybrid_kv_cache_specs():
|
||||
with pytest.raises(ValueError):
|
||||
kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec)
|
||||
|
||||
# Replicated Mamba state still requires the hybrid cache manager.
|
||||
kv_cache_spec = {"attention": new_kv_cache_spec(), "mamba": new_mamba_spec()}
|
||||
with pytest.raises(ValueError):
|
||||
kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec)
|
||||
|
||||
|
||||
def test_unify_kv_cache_spec_page_size_mamba():
|
||||
"""Regression test for https://github.com/vllm-project/vllm/issues/43626.
|
||||
|
||||
@@ -1336,12 +1336,12 @@ def make_kv_cache_config_three_types(
|
||||
)
|
||||
|
||||
|
||||
def test_prefix_cache_hit_uses_per_group_dcp_geometry():
|
||||
@pytest.mark.parametrize("draft_sharded", [True, False])
|
||||
def test_prefix_cache_hit_uses_per_group_dcp_geometry(draft_sharded):
|
||||
"""Prefix lookup must use each group's DCP size, not the process-wide one.
|
||||
|
||||
Target and draft MLA are both sharded (DCP=8); Mamba stays replicated
|
||||
(DCP=1). Hits then align to the sharded full-attention block, not the
|
||||
unsharded page size.
|
||||
Target MLA is sharded; draft MLA can opt out and Mamba stays replicated.
|
||||
Hits must align to the target block in either case.
|
||||
"""
|
||||
block_size = 16
|
||||
dcp = 8
|
||||
@@ -1362,6 +1362,7 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry():
|
||||
KVCacheGroupSpec(
|
||||
["draft_mla"],
|
||||
MLAAttentionSpec(
|
||||
dcp_sharded=draft_sharded,
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
@@ -1388,10 +1389,10 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry():
|
||||
)
|
||||
target_mgr, draft_mgr, mamba_mgr = manager.coordinator.single_type_managers
|
||||
assert target_mgr.dcp_world_size == dcp
|
||||
assert draft_mgr.dcp_world_size == dcp
|
||||
assert draft_mgr.dcp_world_size == (dcp if draft_sharded else 1)
|
||||
assert mamba_mgr.dcp_world_size == 1
|
||||
assert target_mgr.block_size == sharded_block
|
||||
assert draft_mgr.block_size == sharded_block
|
||||
assert draft_mgr.block_size == (sharded_block if draft_sharded else block_size)
|
||||
assert mamba_mgr.block_size == block_size
|
||||
|
||||
hash_fn = sha256
|
||||
@@ -1407,7 +1408,11 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry():
|
||||
req1 = make_request("1", common_token_ids + [100] * 5, block_size, hash_fn)
|
||||
computed_blocks, num_computed_tokens, _ = manager.get_computed_blocks(req1)
|
||||
assert num_computed_tokens == 2 * sharded_block
|
||||
assert [len(group) for group in computed_blocks.blocks] == [2, 2, 16]
|
||||
assert [len(group) for group in computed_blocks.blocks] == [
|
||||
2,
|
||||
2 if draft_sharded else 16,
|
||||
16,
|
||||
]
|
||||
|
||||
manager.free(req0)
|
||||
manager.free(req1)
|
||||
|
||||
@@ -11,6 +11,7 @@ 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,
|
||||
@@ -196,6 +197,38 @@ def test_draft_model_engine_args_tensor_parallelism():
|
||||
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."""
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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}
|
||||
|
||||
if draft_model is not None and "gemma-4" in draft_model:
|
||||
import transformers
|
||||
from packaging.version import Version
|
||||
|
||||
if Version(transformers.__version__) < Version("5.8.0"):
|
||||
pytest.skip(
|
||||
"Gemma4 MTP assistant requires transformers>=5.8.0, "
|
||||
f"got {transformers.__version__}"
|
||||
)
|
||||
|
||||
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}",
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,44 @@
|
||||
# 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,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,36 @@
|
||||
# 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,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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", "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,
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
# 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,252 +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 (
|
||||
_skip_if_insufficient_gpus_for_tp,
|
||||
assert_request_outputs_match,
|
||||
evaluate_llm_for_gsm8k,
|
||||
get_spec_decode_metric_value,
|
||||
get_test_prompts,
|
||||
)
|
||||
|
||||
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}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
|
||||
[
|
||||
# Reference accuracy: 65%-70%.
|
||||
(("mtp", "XiaomiMiMo/MiMo-7B-Base", 1, None), False, 0.5),
|
||||
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
|
||||
(
|
||||
("mtp", "Qwen/Qwen3.5-0.8B-Base", 1, None),
|
||||
False,
|
||||
0.20,
|
||||
), # hybrid + MTP, ref: ~34%-35%
|
||||
(
|
||||
("mtp", "google/gemma-4-E4B-it", 1, "google/gemma-4-E4B-it-assistant"),
|
||||
False,
|
||||
0.50,
|
||||
), # gemma4 MTP with assistant model, ref: ~62%
|
||||
],
|
||||
ids=["mimo", "deepseek", "qwen3_5-hybrid", "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,
|
||||
):
|
||||
"""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}
|
||||
|
||||
if draft_model is not None and "gemma-4" in draft_model:
|
||||
import transformers
|
||||
from packaging.version import Version
|
||||
|
||||
if Version(transformers.__version__) < Version("5.8.0"):
|
||||
pytest.skip(
|
||||
"Gemma4 MTP assistant requires transformers>=5.8.0, "
|
||||
f"got {transformers.__version__}"
|
||||
)
|
||||
|
||||
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}",
|
||||
)
|
||||
@@ -4,6 +4,7 @@
|
||||
import copy
|
||||
import time
|
||||
import uuid
|
||||
from collections import deque
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
|
||||
@@ -395,6 +396,38 @@ def test_engine_core_concurrent_batches():
|
||||
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."""
|
||||
|
||||
@@ -500,7 +500,7 @@ def test_decode_bench_connector_skips_null_padding():
|
||||
|
||||
|
||||
def test_decode_bench_connector_uses_per_group_dcp_block_sizes():
|
||||
"""DCP scales full-attention blocks but not sliding-window blocks."""
|
||||
"""DCP scales target blocks but not the replicated draft's window."""
|
||||
block_size = 16
|
||||
dcp_world_size = 2
|
||||
vllm_config = create_vllm_config(
|
||||
@@ -515,6 +515,7 @@ def test_decode_bench_connector_uses_per_group_dcp_block_sizes():
|
||||
dtype=torch.float32,
|
||||
)
|
||||
sliding_window = SlidingWindowSpec(
|
||||
dcp_sharded=False,
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
|
||||
@@ -99,6 +99,7 @@ def _run_engine_core_handshake(
|
||||
),
|
||||
speculative_config=None,
|
||||
ec_transfer_config=None,
|
||||
is_mm_encoder_only=False,
|
||||
max_concurrent_batches=1,
|
||||
model_config=SimpleNamespace(
|
||||
runner_type="generate",
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import torch
|
||||
import zmq.asyncio
|
||||
@@ -14,6 +16,7 @@ import zmq.asyncio
|
||||
from tests.v1.attention.utils import dense_kv_cache_views
|
||||
from vllm import envs
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake import mooncake_connector
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import (
|
||||
KVConnectorRole,
|
||||
MooncakeConnector,
|
||||
@@ -33,6 +36,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector im
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_utils import (
|
||||
MooncakeBootstrapServer,
|
||||
RegisterWorkerPayload,
|
||||
)
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
@@ -538,6 +542,46 @@ def bootstrap_server():
|
||||
server.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_worker_recovers_from_slow_bootstrap_server(monkeypatch):
|
||||
"""End-to-end: a real HTTP server that responds slower than the configured
|
||||
timeout must be retried on the wire, not treated as fatal."""
|
||||
original = MooncakeBootstrapServer.register_worker
|
||||
state = {"done": False, "calls": 0}
|
||||
|
||||
async def slow_register(self, payload: RegisterWorkerPayload):
|
||||
state["calls"] += 1
|
||||
if not state["done"]:
|
||||
state["done"] = True
|
||||
# Record the worker first, then stall past the client timeout, so
|
||||
# the retry exercises the duplicate-registration path.
|
||||
response = await original(self, payload)
|
||||
await asyncio.sleep(1.5)
|
||||
return response
|
||||
return await original(self, payload)
|
||||
|
||||
monkeypatch.setattr(MooncakeBootstrapServer, "register_worker", slow_register)
|
||||
|
||||
port = get_open_port()
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_BOOTSTRAP_PORT", str(port))
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_CONNECTOR_TIMEOUT", "0.5")
|
||||
monkeypatch.setattr(mooncake_connector, "_BOOTSTRAP_MAX_ATTEMPTS", 5)
|
||||
|
||||
server = MooncakeBootstrapServer("127.0.0.1", port)
|
||||
server.start()
|
||||
try:
|
||||
worker = _make_local_register_worker_stub()
|
||||
await MooncakeConnectorWorker.register_worker_with_bootstrap(worker)
|
||||
assert state["calls"] == 2
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(f"http://127.0.0.1:{port}/query")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["0"]["engine_id"] == "eng-1"
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bootstrap_server(bootstrap_server: MooncakeBootstrapServer):
|
||||
"""Tests the bootstrap server's api for worker registration and querying.
|
||||
@@ -589,9 +633,16 @@ async def test_bootstrap_server(bootstrap_server: MooncakeBootstrapServer):
|
||||
assert data["0"]["worker_addr"]["0"]["0"] == "tcp://1.1.1.1:1111"
|
||||
assert data["0"]["worker_addr"]["0"]["1"] == "tcp://2.2.2.2:2222"
|
||||
|
||||
# Test failure: re-registering the same worker
|
||||
# Re-registering the identical payload is idempotent.
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(f"{base_url}/register", json=payload1)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
|
||||
# Test failure: same ranks, conflicting address
|
||||
payload1_conflict = dict(payload1, addr="tcp://9.9.9.9:9999")
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(f"{base_url}/register", json=payload1_conflict)
|
||||
assert response.status_code == 400
|
||||
assert "is already registered" in response.text
|
||||
|
||||
@@ -628,6 +679,137 @@ def _make_bootstrap_vllm_config(
|
||||
)
|
||||
|
||||
|
||||
def _make_local_register_worker_stub():
|
||||
return SimpleNamespace(
|
||||
vllm_config=SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
local_engines_only=False,
|
||||
data_parallel_rank_local=0,
|
||||
data_parallel_index=0,
|
||||
nnodes_within_dp=1,
|
||||
master_addr="127.0.0.1",
|
||||
data_parallel_master_ip="127.0.0.1",
|
||||
)
|
||||
),
|
||||
hostname="127.0.0.1",
|
||||
side_channel_port=1234,
|
||||
engine_id="eng-1",
|
||||
dp_rank=0,
|
||||
tp_rank=0,
|
||||
pp_rank=0,
|
||||
)
|
||||
|
||||
|
||||
def _make_register_worker_stub():
|
||||
return SimpleNamespace(
|
||||
vllm_config=_make_bootstrap_vllm_config(),
|
||||
hostname="127.0.0.1",
|
||||
side_channel_port=1234,
|
||||
engine_id="eng-1",
|
||||
dp_rank=0,
|
||||
tp_rank=0,
|
||||
pp_rank=0,
|
||||
)
|
||||
|
||||
|
||||
class _FlakyAsyncClient:
|
||||
"""httpx.AsyncClient stub that read-times-out `failures` times first."""
|
||||
|
||||
def __init__(self, failures: int, calls: list[int], **kwargs):
|
||||
self.failures = failures
|
||||
self.calls = calls
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc_info):
|
||||
return False
|
||||
|
||||
async def post(self, url, json=None):
|
||||
self.calls.append(1)
|
||||
if len(self.calls) <= self.failures:
|
||||
raise httpx.ReadTimeout("simulated slow bootstrap server")
|
||||
response = MagicMock()
|
||||
response.raise_for_status = MagicMock()
|
||||
return response
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_worker_retries_on_read_timeout(monkeypatch):
|
||||
"""A slow rank-0 bootstrap response must be retried, not treated as fatal."""
|
||||
monkeypatch.setattr(mooncake_connector, "_BOOTSTRAP_MAX_ATTEMPTS", 5)
|
||||
monkeypatch.setattr(asyncio, "sleep", AsyncMock())
|
||||
|
||||
calls: list[int] = []
|
||||
monkeypatch.setattr(
|
||||
httpx,
|
||||
"AsyncClient",
|
||||
lambda **kwargs: _FlakyAsyncClient(2, calls),
|
||||
)
|
||||
|
||||
worker = _make_register_worker_stub()
|
||||
await MooncakeConnectorWorker.register_worker_with_bootstrap(worker)
|
||||
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_register_worker_raises_after_max_attempts(monkeypatch):
|
||||
"""Terminal registration failure must raise, not loop forever."""
|
||||
monkeypatch.setattr(mooncake_connector, "_BOOTSTRAP_MAX_ATTEMPTS", 3)
|
||||
monkeypatch.setattr(asyncio, "sleep", AsyncMock())
|
||||
|
||||
calls: list[int] = []
|
||||
monkeypatch.setattr(
|
||||
httpx,
|
||||
"AsyncClient",
|
||||
lambda **kwargs: _FlakyAsyncClient(99, calls),
|
||||
)
|
||||
|
||||
worker = _make_register_worker_stub()
|
||||
with pytest.raises(RuntimeError, match="after 3 attempts"):
|
||||
await MooncakeConnectorWorker.register_worker_with_bootstrap(worker)
|
||||
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sender_listener_failure_propagates_to_caller(monkeypatch):
|
||||
"""A terminal registration failure must surface via the Future rather than
|
||||
leaving register_kv_caches blocked on its ready event."""
|
||||
monkeypatch.setenv("VLLM_MOONCAKE_CONNECTOR_TIMEOUT", "0.1")
|
||||
monkeypatch.setattr(mooncake_connector, "_BOOTSTRAP_MAX_ATTEMPTS", 1)
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
thread = threading.Thread(target=loop.run_forever, daemon=True)
|
||||
thread.start()
|
||||
|
||||
async def failing_listener(ready_event):
|
||||
raise RuntimeError("simulated terminal registration failure")
|
||||
|
||||
try:
|
||||
ready_event = threading.Event()
|
||||
fut = asyncio.run_coroutine_threadsafe(failing_listener(ready_event), loop)
|
||||
|
||||
deadline = time.monotonic() + 10.0
|
||||
raised = None
|
||||
while not ready_event.wait(timeout=0.1):
|
||||
if fut.done():
|
||||
try:
|
||||
fut.result()
|
||||
except RuntimeError as e:
|
||||
raised = e
|
||||
break
|
||||
assert time.monotonic() < deadline, "caller blocked past its deadline"
|
||||
|
||||
assert raised is not None
|
||||
assert "simulated terminal registration failure" in str(raised)
|
||||
finally:
|
||||
loop.call_soon_threadsafe(loop.stop)
|
||||
thread.join(timeout=5)
|
||||
loop.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"tp_rank",
|
||||
|
||||
@@ -290,6 +290,8 @@ class _FakeKVTransferConfig:
|
||||
class _FakeModelConfig:
|
||||
model = "test-model"
|
||||
use_mla = False
|
||||
enable_sleep_mode = False
|
||||
enable_cumem_allocator = False
|
||||
|
||||
def get_num_layers(self, parallel_config) -> int:
|
||||
return 1
|
||||
@@ -432,6 +434,64 @@ def _patch_worker_runtime(
|
||||
monkeypatch.setattr(worker, "LookupKeyServer", MagicMock())
|
||||
|
||||
|
||||
def test_create_mem_pool_returns_none_when_unconfigured():
|
||||
assert worker.MooncakeStoreWorker._create_mem_pool({}, _FakeModelConfig()) is None
|
||||
|
||||
|
||||
def test_create_mem_pool_rejects_unknown_pool():
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="Unsupported custom_mem_pool='UNKNOWN'",
|
||||
):
|
||||
worker.MooncakeStoreWorker._create_mem_pool(
|
||||
{"custom_mem_pool": "unknown"}, _FakeModelConfig()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"conflicting_option", ["enable_sleep_mode", "enable_cumem_allocator"]
|
||||
)
|
||||
def test_create_mem_pool_rejects_cumem_conflicts(conflicting_option):
|
||||
model_config = _FakeModelConfig()
|
||||
setattr(model_config, conflicting_option, True)
|
||||
|
||||
with pytest.raises(ValueError, match="custom_mem_pool is incompatible"):
|
||||
worker.MooncakeStoreWorker._create_mem_pool(
|
||||
{"custom_mem_pool": "NVLINK"}, model_config
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pool_type", "allocator_name"),
|
||||
[("nvlink", "NVLinkAllocator"), ("barex", "BarexAllocator")],
|
||||
)
|
||||
def test_create_mem_pool_uses_mooncake_allocator(
|
||||
monkeypatch, pool_type, allocator_name
|
||||
):
|
||||
allocator_cls = MagicMock()
|
||||
allocator = allocator_cls.get_allocator.return_value
|
||||
allocator_module = types.ModuleType("mooncake.allocator")
|
||||
setattr(allocator_module, allocator_name, allocator_cls)
|
||||
mooncake_module = types.ModuleType("mooncake")
|
||||
mooncake_module.allocator = allocator_module # type: ignore[attr-defined]
|
||||
monkeypatch.setitem(sys.modules, "mooncake", mooncake_module)
|
||||
monkeypatch.setitem(sys.modules, "mooncake.allocator", allocator_module)
|
||||
|
||||
monkeypatch.setattr(torch.accelerator, "current_device_index", lambda: 2)
|
||||
mem_pool = MagicMock()
|
||||
mem_pool_ctor = MagicMock(return_value=mem_pool)
|
||||
monkeypatch.setattr(torch.cuda, "MemPool", mem_pool_ctor)
|
||||
|
||||
result = worker.MooncakeStoreWorker._create_mem_pool(
|
||||
{"custom_mem_pool": pool_type}, _FakeModelConfig()
|
||||
)
|
||||
|
||||
assert result is mem_pool
|
||||
allocator_cls.get_allocator.assert_called_once_with(torch.device("cuda", 2))
|
||||
allocator.allocator.assert_called_once_with()
|
||||
mem_pool_ctor.assert_called_once_with(allocator.allocator.return_value)
|
||||
|
||||
|
||||
def test_pool_key_to_string_without_prefix_is_unchanged():
|
||||
"""Default (empty) cache_prefix keeps keys byte-identical to the
|
||||
historical unprefixed format so existing deployments keep their hits."""
|
||||
|
||||
@@ -68,6 +68,7 @@ class MockConnector(KVConnectorBase_V1):
|
||||
# Override just build_kv_connector_stats
|
||||
mock.build_kv_connector_stats = cls.build_kv_connector_stats
|
||||
mock.get_kv_connector_stats.return_value = None
|
||||
mock.get_mem_pool_context.return_value = None
|
||||
return mock
|
||||
|
||||
@classmethod
|
||||
@@ -201,6 +202,36 @@ def mc() -> MultiConnector:
|
||||
return mc
|
||||
|
||||
|
||||
def test_multi_connector_mem_pool_context_none(mc: MultiConnector):
|
||||
assert mc.get_mem_pool_context() is None
|
||||
|
||||
|
||||
def test_multi_connector_forwards_mem_pool_context(mc: MultiConnector):
|
||||
context = MagicMock()
|
||||
provider = MagicMock(spec_set=KVConnectorBase_V1)
|
||||
provider.get_mem_pool_context.return_value = context
|
||||
mc._connectors = [mc._connectors[0], provider]
|
||||
|
||||
assert mc.get_mem_pool_context() is context
|
||||
provider.get_mem_pool_context.assert_called_once_with()
|
||||
|
||||
|
||||
def test_multi_connector_rejects_multiple_mem_pool_contexts(mc: MultiConnector):
|
||||
providers = [
|
||||
MagicMock(spec_set=KVConnectorBase_V1),
|
||||
MagicMock(spec_set=KVConnectorBase_V1),
|
||||
]
|
||||
for provider in providers:
|
||||
provider.get_mem_pool_context.return_value = MagicMock()
|
||||
mc._connectors = providers
|
||||
|
||||
with pytest.raises(
|
||||
ValueError,
|
||||
match="Multiple connectors provide a KV cache memory pool",
|
||||
):
|
||||
mc.get_mem_pool_context()
|
||||
|
||||
|
||||
# Helper function to compare directories recursively
|
||||
def _compare_directories(dir1: Path, dir2: Path) -> bool:
|
||||
"""Compares two directories recursively for identical content."""
|
||||
@@ -320,6 +351,7 @@ def test_multi_example_connector_consistency():
|
||||
# First three events are from initialization. Layer hooks run before the
|
||||
# deferred load starts after the forward pass.
|
||||
expected_worker_prefix = [
|
||||
"get_mem_pool_context",
|
||||
"register_kv_caches",
|
||||
"set_host_xfer_buffer_ops",
|
||||
"get_handshake_metadata",
|
||||
|
||||
@@ -7,6 +7,7 @@ import os
|
||||
import queue
|
||||
import tempfile
|
||||
import textwrap
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
@@ -49,6 +50,8 @@ from vllm.distributed.kv_transfer.kv_connector.v1.nixl import (
|
||||
NixlKVConnectorStats,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
RemoteMeta,
|
||||
ReqMeta,
|
||||
compute_nixl_compatibility_hash,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_transfer_state import (
|
||||
@@ -2087,6 +2090,10 @@ def recv_worker():
|
||||
worker._recving_transfers = defaultdict(list)
|
||||
worker._failed_recv_reqs = queue.Queue()
|
||||
worker._recv_failures = set()
|
||||
worker._handshake_lock = threading.RLock()
|
||||
worker._handshake_futures = {}
|
||||
worker._remote_agents = {}
|
||||
worker._engine_by_address = {}
|
||||
worker._replicated_pcp_done_sending = set()
|
||||
worker._invalid_block_ids = queue.Queue()
|
||||
worker._pending_recv_notifs = {}
|
||||
@@ -2681,6 +2688,174 @@ def test_engine_ttl_disabled(default_vllm_config, dist_init):
|
||||
assert engine_id in worker.dst_xfer_side_handles
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
class TestPeerReplacement:
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup(self, monkeypatch):
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker as bw
|
||||
from vllm.v1.attention.backends.flash_attn import FlashAttentionBackend
|
||||
|
||||
config = create_vllm_config(kv_connector_extra_config={"engine_ttl": 0})
|
||||
config.kv_transfer_config.kv_buffer_device = "cpu"
|
||||
platform = SimpleNamespace(
|
||||
device_type="cpu",
|
||||
discover_numa_topology=lambda: [],
|
||||
get_nixl_memory_type=lambda: "DRAM",
|
||||
is_rocm=lambda: False,
|
||||
)
|
||||
with (
|
||||
patch.object(bw, "NixlWrapper", FakeNixlWrapper),
|
||||
patch.object(bw, "current_platform", platform),
|
||||
patch.object(bw, "get_tensor_model_parallel_rank", return_value=0),
|
||||
patch.object(bw, "get_tensor_model_parallel_world_size", return_value=1),
|
||||
patch.object(
|
||||
bw, "get_current_attn_backends", return_value=[FlashAttentionBackend]
|
||||
),
|
||||
):
|
||||
self.worker = FakeNixlConnectorWorker(config, "local", hand_shake_latency=0)
|
||||
self.nixl = self.worker.nixl_wrapper
|
||||
self.transport = MagicMock(wraps=self.nixl)
|
||||
self.worker.nixl_wrapper = self.transport
|
||||
monkeypatch.setattr(
|
||||
self.worker._handshake_initiation_executor,
|
||||
"submit",
|
||||
lambda *args: Future(),
|
||||
)
|
||||
self._connect("old")
|
||||
yield
|
||||
self.worker.shutdown()
|
||||
|
||||
def _connect(self, engine_id="new", host="localhost", port=1234):
|
||||
future = self.worker._ensure_handshake(engine_id, host, port, 1)
|
||||
self.worker.REMOTE_ENGINE_ID = engine_id
|
||||
self.nixl.REMOTE_AGENT_NAME = engine_id
|
||||
future.set_result(self.worker._nixl_handshake(host, port, 1, engine_id))
|
||||
|
||||
def _request(self, engine_id="new", blocks=(1,), awaiting_kvs=True):
|
||||
metadata = NixlConnectorMetadata()
|
||||
metadata.reqs_to_recv[f"{engine_id}-req"] = ReqMeta(
|
||||
local_block_ids=(blocks,),
|
||||
local_physical_block_ids=(blocks,),
|
||||
tp_size=1,
|
||||
remote=RemoteMeta(
|
||||
([2],), "localhost", 1234, engine_id, f"{engine_id}-prefill"
|
||||
),
|
||||
awaiting_kvs=awaiting_kvs,
|
||||
)
|
||||
return metadata
|
||||
|
||||
def test_cleans_old_peer_after_confirmed_handshake(self):
|
||||
self._connect("healthy", host="other-host")
|
||||
old_handle = self.worker.dst_xfer_side_handles["old"][0]
|
||||
self.worker.start_load_kv(self._request())
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
self._connect()
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.release_dlist_handle.assert_called_once_with(old_handle)
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
assert set(self.worker._remote_agents) == {"new", "healthy"}
|
||||
assert self.worker._engine_by_address == {
|
||||
("localhost", 1234): "new",
|
||||
("other-host", 1234): "healthy",
|
||||
}
|
||||
with pytest.raises(KeyError):
|
||||
self.worker.transfer_topo.get_engine_info("old")
|
||||
|
||||
self.worker.start_load_kv(NixlConnectorMetadata())
|
||||
assert self.worker.get_transfer_results().finished_recving == {"new-req"}
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
|
||||
@pytest.mark.parametrize("host,port", [("other-host", 1234), ("localhost", 5678)])
|
||||
def test_preserves_other_addresses(self, host, port):
|
||||
self._connect(host=host, port=port)
|
||||
self.worker.get_transfer_results()
|
||||
assert "old" in self.worker._remote_agents
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
def test_preserves_old_peer_when_handshake_fails(self):
|
||||
self.worker.start_load_kv(self._request())
|
||||
self.worker._handshake_futures["new"].set_exception(
|
||||
RuntimeError("handshake failed")
|
||||
)
|
||||
assert self.worker.get_transfer_results().failed_recving == {"new-req"}
|
||||
assert "old" in self.worker._remote_agents
|
||||
assert self.worker._engine_by_address == {("localhost", 1234): "old"}
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"states,failed",
|
||||
[
|
||||
(["PROC", "DONE"], False),
|
||||
(["ERR", "PROC", "DONE"], True),
|
||||
(["ERR", "PROC", "ERR"], True),
|
||||
],
|
||||
ids=["healthy", "failed-sibling-completes", "failed-sibling-fails"],
|
||||
)
|
||||
def test_waits_for_reads_before_cleanup_and_failure_reporting(self, states, failed):
|
||||
self.worker._recving_metadata.update(self._request("old").reqs_to_recv)
|
||||
self.worker._recving_transfers["old-req"] = [1, 2] if failed else [1]
|
||||
self.transport.check_xfer_state.side_effect = states
|
||||
self._connect()
|
||||
|
||||
result = self.worker.get_transfer_results()
|
||||
assert result.finished_recving == result.failed_recving == set()
|
||||
assert self.worker.get_block_ids_with_load_errors() == set()
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
result = self.worker.get_transfer_results()
|
||||
assert result.finished_recving == {"old-req"}
|
||||
assert result.failed_recving == ({"old-req"} if failed else set())
|
||||
assert self.worker.get_block_ids_with_load_errors() == (
|
||||
{1} if failed else set()
|
||||
)
|
||||
assert self.transport.release_xfer_handle.call_count == (2 if failed else 1)
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
|
||||
def test_waits_for_queued_notification(self):
|
||||
metadata = self._request("old", blocks=())
|
||||
self.worker._recving_metadata.update(metadata.reqs_to_recv)
|
||||
self.worker._background_nixl_handshake(
|
||||
"old-req", "old", metadata.reqs_to_recv["old-req"]
|
||||
)
|
||||
self._connect()
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
self.worker.start_load_kv(NixlConnectorMetadata())
|
||||
self.transport.send_notif.assert_called_once_with(
|
||||
"old", notif_msg=b"old-prefill:1"
|
||||
)
|
||||
result = self.worker.get_transfer_results()
|
||||
assert result.finished_recving == {"old-req"}
|
||||
assert result.failed_recving == set()
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
|
||||
def test_waits_for_other_handshakes(self):
|
||||
self.worker._ensure_handshake("other", "other-host", 1234, 1)
|
||||
self._connect()
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.remove_remote_agent.assert_not_called()
|
||||
|
||||
self._connect("other", host="other-host")
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
|
||||
def test_rehandshakes_queued_request_for_released_engine(self):
|
||||
# A request queued after its engine's handshake, but drained only after
|
||||
# that engine was replaced and released, must not read from it.
|
||||
metadata = self._request("old", blocks=(), awaiting_kvs=False)
|
||||
self.worker._ready_requests.put(("old-req", metadata.reqs_to_recv["old-req"]))
|
||||
self._connect()
|
||||
self.worker.get_transfer_results()
|
||||
self.transport.remove_remote_agent.assert_called_once_with("old")
|
||||
|
||||
self.worker.start_load_kv(NixlConnectorMetadata())
|
||||
assert "old" in self.worker._handshake_futures
|
||||
self.transport.send_notif.assert_not_called()
|
||||
|
||||
|
||||
def test_transfer_topology_unregister():
|
||||
"""TransferTopology.unregister_remote_engine removes the engine."""
|
||||
from vllm.v1.attention.backends.flash_attn import FlashAttentionBackend
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import gc
|
||||
import queue
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -54,6 +55,9 @@ def region_pull_worker():
|
||||
worker.enable_permute_local_kv = False
|
||||
worker.enable_heterogeneous_attn_post_process = False
|
||||
worker._engine_last_active = {}
|
||||
worker._handshake_lock = threading.RLock()
|
||||
worker._handshake_futures = {}
|
||||
worker._transfer_layer_group_ids = ()
|
||||
worker._bidirectional_kv_xfer_enabled = False
|
||||
worker._recving_transfers = {}
|
||||
worker.use_mla, worker._has_mamba = True, False
|
||||
@@ -94,6 +98,7 @@ def region_pull_worker():
|
||||
worker.dst_num_blocks = {"P": 100, "D": 100}
|
||||
worker.dst_region_num_blocks = {"P": [100, 100], "D": [100, 100]}
|
||||
worker._remote_agents = {"P": {(0, 0): "P-rank0"}}
|
||||
worker._engine_by_address = {("localhost", 1): "P"}
|
||||
worker._read_blocks_mixed = MagicMock()
|
||||
worker.nixl_wrapper = MagicMock()
|
||||
return worker
|
||||
|
||||
@@ -395,6 +395,7 @@ class _StubWriterWorker(NixlPushConnectorWorker):
|
||||
w._group_spec_types = (FullAttentionSpec,)
|
||||
w._engine_ttl = 0.0
|
||||
w._engine_last_active = {}
|
||||
w._engine_by_address = {}
|
||||
|
||||
# Track _do_start_push_kv invocations.
|
||||
calls: list[tuple[str, Any, dict[str, Any]]] = []
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for SimpleCPUOffloadConnector metrics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from prometheus_client import Counter, Gauge, Histogram
|
||||
|
||||
from tests.v1.kv_connector.unit.test_simple_cpu_offload_connector import (
|
||||
_make_connector,
|
||||
)
|
||||
from tests.v1.simple_kv_offload.test_scheduler import (
|
||||
make_request,
|
||||
make_scheduler,
|
||||
make_scheduler_output,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
|
||||
SimpleCPUOffloadConnector,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.simple_kv_offload.manager import (
|
||||
BoundaryStoreStats,
|
||||
LoadRequestState,
|
||||
TransferMeta,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.metrics import (
|
||||
INFO_LABELS,
|
||||
OUTCOME_TO_FIELD,
|
||||
MetricName,
|
||||
SimpleCPUOffloadStats,
|
||||
_MetricType,
|
||||
_StatsKey,
|
||||
)
|
||||
|
||||
SAVE_OUTCOMES = MetricName.SAVE_OUTCOMES
|
||||
LOAD_BLOCKS = MetricName.LOAD_BLOCKS
|
||||
USED_BLOCKS = MetricName.USED_BLOCKS
|
||||
PENDING_STORE_BLOCKS = MetricName.PENDING_STORE_BLOCKS
|
||||
INFO = MetricName.INFO
|
||||
|
||||
|
||||
class _FakeMetric:
|
||||
def __init__(self, **kwargs: Any):
|
||||
self.kwargs = kwargs
|
||||
self.children: list[_FakeMetric] = []
|
||||
self.observed: list[int | float] = []
|
||||
self.increments: list[int | float] = []
|
||||
self.set_values: list[int | float] = []
|
||||
self.labelvalues: tuple[object, ...] = ()
|
||||
|
||||
def labels(self, *labelvalues: object) -> _FakeMetric:
|
||||
child = _FakeMetric(**self.kwargs)
|
||||
child.labelvalues = labelvalues
|
||||
self.children.append(child)
|
||||
return child
|
||||
|
||||
def observe(self, value: int | float) -> None:
|
||||
self.observed.append(value)
|
||||
|
||||
def inc(self, value: int | float) -> None:
|
||||
self.increments.append(value)
|
||||
|
||||
def set(self, value: int | float) -> None:
|
||||
self.set_values.append(value)
|
||||
|
||||
|
||||
def _fake_metric_types() -> dict[type, type]:
|
||||
return {Gauge: _FakeMetric, Counter: _FakeMetric, Histogram: _FakeMetric}
|
||||
|
||||
|
||||
def _make_prom_metrics(per_engine: dict[int, list[object]] | None = None) -> Any:
|
||||
from vllm.v1.simple_kv_offload.metrics import SimpleCPUOffloadPromMetrics
|
||||
|
||||
return SimpleCPUOffloadPromMetrics(
|
||||
vllm_config=SimpleNamespace(kv_transfer_config=None),
|
||||
metric_types=_fake_metric_types(),
|
||||
labelnames=["model_name", "engine"],
|
||||
per_engine_labelvalues=per_engine or {0: ["model", "0"]},
|
||||
)
|
||||
|
||||
|
||||
def _stats_payload(types: dict, data: dict) -> dict[str, Any]:
|
||||
return {_StatsKey.TYPES: types, _StatsKey.DATA: data}
|
||||
|
||||
|
||||
def _values(stats: SimpleCPUOffloadStats, name: str) -> dict:
|
||||
return stats.data[_StatsKey.DATA][name]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stats class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_build_kv_connector_stats_none_and_empty() -> None:
|
||||
stats = SimpleCPUOffloadConnector.build_kv_connector_stats(data=None)
|
||||
assert isinstance(stats, SimpleCPUOffloadStats)
|
||||
assert stats.is_empty()
|
||||
|
||||
stats = SimpleCPUOffloadConnector.build_kv_connector_stats(data={})
|
||||
assert isinstance(stats, SimpleCPUOffloadStats)
|
||||
assert stats.is_empty()
|
||||
|
||||
|
||||
def test_stats_round_trip_through_serialized_dict() -> None:
|
||||
stats = SimpleCPUOffloadStats()
|
||||
stats.increase_counter(SAVE_OUTCOMES, 3, ("stored",))
|
||||
stats.increase_counter(LOAD_BLOCKS, 4)
|
||||
stats.set_gauge(USED_BLOCKS, 7)
|
||||
stats.set_gauge(INFO, 1, ("cpu", "false", "false", "64"))
|
||||
|
||||
rebuilt = SimpleCPUOffloadConnector.build_kv_connector_stats(data=stats.to_dict())
|
||||
assert isinstance(rebuilt, SimpleCPUOffloadStats)
|
||||
assert _values(rebuilt, SAVE_OUTCOMES) == {("stored",): 3}
|
||||
assert _values(rebuilt, LOAD_BLOCKS) == {(): 4}
|
||||
assert _values(rebuilt, USED_BLOCKS) == {(): 7}
|
||||
assert _values(rebuilt, INFO) == {("cpu", "false", "false", "64"): 1}
|
||||
|
||||
|
||||
def test_stats_aggregate_sums_counters_and_keeps_latest_gauge() -> None:
|
||||
stats1 = SimpleCPUOffloadStats()
|
||||
stats1.increase_counter(SAVE_OUTCOMES, 3, ("stored",))
|
||||
stats1.increase_counter(SAVE_OUTCOMES, 1, ("dropped_cpu_full",))
|
||||
stats1.set_gauge(USED_BLOCKS, 7)
|
||||
|
||||
stats2 = SimpleCPUOffloadStats()
|
||||
stats2.increase_counter(SAVE_OUTCOMES, 4, ("stored",))
|
||||
stats2.set_gauge(USED_BLOCKS, 2)
|
||||
|
||||
result = stats1.aggregate(stats2)
|
||||
assert result is stats1
|
||||
outcomes = _values(stats1, SAVE_OUTCOMES)
|
||||
assert outcomes == {("stored",): 7, ("dropped_cpu_full",): 1}
|
||||
assert _values(stats1, USED_BLOCKS) == {(): 2}
|
||||
|
||||
|
||||
def test_stats_aggregate_merges_types_from_other() -> None:
|
||||
stats1 = SimpleCPUOffloadStats()
|
||||
stats1.set_gauge(USED_BLOCKS, 1)
|
||||
|
||||
stats2 = SimpleCPUOffloadStats()
|
||||
stats2.increase_counter(LOAD_BLOCKS, 2)
|
||||
|
||||
stats1.aggregate(stats2)
|
||||
assert stats1.data[_StatsKey.TYPES][LOAD_BLOCKS] == _MetricType.COUNTER
|
||||
assert _values(stats1, LOAD_BLOCKS) == {(): 2}
|
||||
|
||||
|
||||
def test_stats_reduce_and_reset() -> None:
|
||||
stats = SimpleCPUOffloadStats()
|
||||
stats.increase_counter(SAVE_OUTCOMES, 3, ("stored",))
|
||||
stats.set_gauge(PENDING_STORE_BLOCKS, 4)
|
||||
stats.increase_counter(LOAD_BLOCKS, 9)
|
||||
stats.set_gauge(INFO, 1, ("cpu", "false", "false", "64"))
|
||||
|
||||
reduced = stats.reduce()
|
||||
assert reduced[f"{SAVE_OUTCOMES}:{('stored',)}"] == 3
|
||||
assert reduced[PENDING_STORE_BLOCKS] == 4
|
||||
assert reduced[LOAD_BLOCKS] == 9
|
||||
assert not any(key.startswith(INFO) for key in reduced)
|
||||
|
||||
stats.reset()
|
||||
assert stats.is_empty()
|
||||
|
||||
|
||||
def test_outcome_labels_match_boundary_store_stats_fields() -> None:
|
||||
"""Every outcome label maps 1:1 to a BoundaryStoreStats counter field."""
|
||||
boundary_fields = {
|
||||
f.name for f in dataclasses.fields(BoundaryStoreStats) if f.name != "published"
|
||||
}
|
||||
assert set(OUTCOME_TO_FIELD.values()) == boundary_fields
|
||||
assert len(set(OUTCOME_TO_FIELD.values())) == len(OUTCOME_TO_FIELD)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prom metrics class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_prom_metrics_registers_tier1_metrics() -> None:
|
||||
prom = _make_prom_metrics()
|
||||
defs = prom._defs
|
||||
assert set(defs) == {
|
||||
SAVE_OUTCOMES,
|
||||
LOAD_BLOCKS,
|
||||
USED_BLOCKS,
|
||||
PENDING_STORE_BLOCKS,
|
||||
INFO,
|
||||
}
|
||||
# The prom class registers literal names (required by the docs
|
||||
# generator); they must stay in sync with the emission-side constants.
|
||||
assert {m.kwargs["name"] for m in defs.values()} == {
|
||||
SAVE_OUTCOMES,
|
||||
LOAD_BLOCKS,
|
||||
USED_BLOCKS,
|
||||
PENDING_STORE_BLOCKS,
|
||||
INFO,
|
||||
}
|
||||
for metric in defs.values():
|
||||
assert metric.kwargs["documentation"]
|
||||
assert metric.kwargs["labelnames"][:2] == ["model_name", "engine"]
|
||||
|
||||
assert defs[SAVE_OUTCOMES].kwargs["labelnames"] == [
|
||||
"model_name",
|
||||
"engine",
|
||||
"outcome",
|
||||
]
|
||||
assert defs[LOAD_BLOCKS].kwargs["labelnames"] == ["model_name", "engine"]
|
||||
assert defs[INFO].kwargs["labelnames"] == [
|
||||
"model_name",
|
||||
"engine",
|
||||
*INFO_LABELS,
|
||||
]
|
||||
assert defs[USED_BLOCKS].kwargs["labelnames"] == ["model_name", "engine"]
|
||||
|
||||
# mostrecent: multiprocess scrapes expose one series per label set, not
|
||||
# one pid-tagged series per writer process.
|
||||
for gauge in (USED_BLOCKS, PENDING_STORE_BLOCKS, INFO):
|
||||
assert defs[gauge].kwargs["multiprocess_mode"] == "mostrecent"
|
||||
|
||||
|
||||
def test_prom_metrics_observe_routes_each_series() -> None:
|
||||
prom = _make_prom_metrics()
|
||||
prom.observe(
|
||||
_stats_payload(
|
||||
types={
|
||||
SAVE_OUTCOMES: _MetricType.COUNTER,
|
||||
LOAD_BLOCKS: _MetricType.COUNTER,
|
||||
USED_BLOCKS: _MetricType.GAUGE,
|
||||
PENDING_STORE_BLOCKS: _MetricType.GAUGE,
|
||||
INFO: _MetricType.GAUGE,
|
||||
},
|
||||
data={
|
||||
SAVE_OUTCOMES: {("stored",): 3},
|
||||
LOAD_BLOCKS: {(): 4},
|
||||
USED_BLOCKS: {(): 5},
|
||||
PENDING_STORE_BLOCKS: {(): 1},
|
||||
INFO: {("cpu", "false", "false", "64"): 1},
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
assert prom._metrics[(0, SAVE_OUTCOMES, ("stored",))].increments == [3]
|
||||
assert prom._metrics[(0, LOAD_BLOCKS, ())].increments == [4]
|
||||
assert prom._metrics[(0, USED_BLOCKS, ())].set_values == [5]
|
||||
assert prom._metrics[(0, PENDING_STORE_BLOCKS, ())].set_values == [1]
|
||||
assert prom._metrics[(0, INFO, ("cpu", "false", "false", "64"))].set_values == [1]
|
||||
assert prom._metrics[(0, SAVE_OUTCOMES, ("stored",))].labelvalues == (
|
||||
"model",
|
||||
"0",
|
||||
"stored",
|
||||
)
|
||||
assert prom._metrics[(0, INFO, ("cpu", "false", "false", "64"))].labelvalues == (
|
||||
"model",
|
||||
"0",
|
||||
"cpu",
|
||||
"false",
|
||||
"false",
|
||||
"64",
|
||||
)
|
||||
|
||||
|
||||
def test_prom_metrics_reuses_bound_children() -> None:
|
||||
prom = _make_prom_metrics()
|
||||
payload = _stats_payload(
|
||||
types={SAVE_OUTCOMES: _MetricType.COUNTER},
|
||||
data={SAVE_OUTCOMES: {("stored",): 1}},
|
||||
)
|
||||
prom.observe(payload)
|
||||
prom.observe(payload)
|
||||
|
||||
child = prom._metrics[(0, SAVE_OUTCOMES, ("stored",))]
|
||||
assert child.increments == [1, 1]
|
||||
assert len(prom._defs[SAVE_OUTCOMES].children) == 1
|
||||
|
||||
|
||||
def test_prom_metrics_rejects_unknown_metric() -> None:
|
||||
prom = _make_prom_metrics()
|
||||
with pytest.raises(AssertionError, match="Unknown"):
|
||||
prom.observe(
|
||||
_stats_payload(
|
||||
types={"vllm:not_a_metric": _MetricType.COUNTER},
|
||||
data={"vllm:not_a_metric": {(): 1}},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_prom_metrics_rejects_wrong_label_count() -> None:
|
||||
prom = _make_prom_metrics()
|
||||
with pytest.raises(AssertionError, match="labels"):
|
||||
prom.observe(
|
||||
_stats_payload(
|
||||
types={SAVE_OUTCOMES: _MetricType.COUNTER},
|
||||
data={SAVE_OUTCOMES: {("stored", "extra"): 1}},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_prom_metrics_routes_per_engine() -> None:
|
||||
prom = _make_prom_metrics(per_engine={0: ["model", "0"], 1: ["model", "1"]})
|
||||
prom.observe(
|
||||
_stats_payload(
|
||||
types={USED_BLOCKS: _MetricType.GAUGE}, data={USED_BLOCKS: {(): 3}}
|
||||
),
|
||||
engine_idx=1,
|
||||
)
|
||||
assert (0, USED_BLOCKS, ()) not in prom._metrics
|
||||
assert prom._metrics[(1, USED_BLOCKS, ())].set_values == [3]
|
||||
|
||||
|
||||
def test_connector_build_prom_metrics() -> None:
|
||||
from vllm.v1.simple_kv_offload.metrics import SimpleCPUOffloadPromMetrics
|
||||
|
||||
prom = SimpleCPUOffloadConnector.build_prom_metrics(
|
||||
vllm_config=SimpleNamespace(kv_transfer_config=None),
|
||||
metric_types=_fake_metric_types(),
|
||||
labelnames=["model_name", "engine"],
|
||||
per_engine_labelvalues={0: ["model", "0"]},
|
||||
)
|
||||
assert isinstance(prom, SimpleCPUOffloadPromMetrics)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Manager: interval stats
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_manager_get_stats_reports_outcome_deltas_per_interval() -> None:
|
||||
fixture = make_scheduler()
|
||||
sched = fixture.scheduler
|
||||
|
||||
sched.boundary_store_stats.stored += 3
|
||||
sched.boundary_store_stats.dropped_cpu_full += 2
|
||||
sched.boundary_store_stats.skipped_in_flight += 1
|
||||
|
||||
stats = sched.get_stats()
|
||||
assert _values(stats, SAVE_OUTCOMES) == {
|
||||
("stored",): 3,
|
||||
("dropped_cpu_full",): 2,
|
||||
("skipped_in_flight",): 1,
|
||||
}
|
||||
|
||||
# Deltas are per-interval: a second drain reports no new outcomes.
|
||||
stats2 = sched.get_stats()
|
||||
assert SAVE_OUTCOMES not in stats2.data[_StatsKey.DATA]
|
||||
|
||||
|
||||
def test_manager_reset_preserves_undrained_outcome_deltas() -> None:
|
||||
fixture = make_scheduler()
|
||||
sched = fixture.scheduler
|
||||
|
||||
sched.boundary_store_stats.stored += 3
|
||||
sched.reset()
|
||||
|
||||
stats = sched.get_stats()
|
||||
assert _values(stats, SAVE_OUTCOMES) == {("stored",): 3}
|
||||
|
||||
|
||||
def test_manager_get_stats_gauges_and_info_labels() -> None:
|
||||
fixture = make_scheduler(num_cpu_blocks=8)
|
||||
sched = fixture.scheduler
|
||||
|
||||
sched._store_event_to_blocks[0] = TransferMeta([10], [11])
|
||||
sched._pending_finished_stores.append(TransferMeta([12], [13]))
|
||||
sched._abandoned_store_event_to_blocks[1] = TransferMeta([14], [15])
|
||||
|
||||
stats = sched.get_stats()
|
||||
assert _values(stats, PENDING_STORE_BLOCKS) == {(): 3}
|
||||
used = _values(stats, USED_BLOCKS)[()]
|
||||
assert used == sched.num_cpu_blocks - sched.cpu_block_pool.get_num_free_blocks()
|
||||
|
||||
info = _values(stats, INFO)
|
||||
assert info == {("cpu", "false", "false", str(sched.num_cpu_blocks)): 1}
|
||||
|
||||
# Gauges are re-reported every drain.
|
||||
stats2 = sched.get_stats()
|
||||
assert _values(stats2, PENDING_STORE_BLOCKS) == {(): 3}
|
||||
|
||||
|
||||
def test_manager_info_labels_reflect_disk_mode() -> None:
|
||||
connector = _make_connector(
|
||||
extra_config={
|
||||
"kv_offload_backend": "disk",
|
||||
"disk_path": "/tmp/fake-disk-metrics",
|
||||
"disk_capacity_bytes": 1024**3,
|
||||
"use_page_cache": True,
|
||||
}
|
||||
)
|
||||
sched = connector.scheduler_manager
|
||||
assert sched is not None
|
||||
assert sched._info_labelvalues[0] == "disk"
|
||||
assert sched._info_labelvalues[1] == "true"
|
||||
stats = sched.get_stats()
|
||||
assert set(_values(stats, INFO)) == {sched._info_labelvalues}
|
||||
|
||||
|
||||
def test_manager_info_labels_page_cache_false_for_cpu_backend() -> None:
|
||||
"""CPU backend ignores use_page_cache; the info gauge must not claim it."""
|
||||
connector = _make_connector(extra_config={"use_page_cache": True})
|
||||
sched = connector.scheduler_manager
|
||||
assert sched is not None
|
||||
assert sched._info_labelvalues[:2] == ("cpu", "false")
|
||||
stats = sched.get_stats()
|
||||
assert set(_values(stats, INFO)) == {sched._info_labelvalues}
|
||||
|
||||
|
||||
def test_manager_counts_load_blocks_completed() -> None:
|
||||
fixture = make_scheduler(num_cpu_blocks=8)
|
||||
sched = fixture.scheduler
|
||||
|
||||
request = make_request(num_blocks=2)
|
||||
gpu_blocks = fixture.gpu_block_pool.get_new_blocks(2)
|
||||
cpu_blocks = sched.cpu_block_pool.get_new_blocks(2)
|
||||
sched._reqs_to_load[request.request_id] = LoadRequestState(
|
||||
request=request,
|
||||
transfer_meta=TransferMeta(
|
||||
[b.block_id for b in gpu_blocks], [b.block_id for b in cpu_blocks]
|
||||
),
|
||||
)
|
||||
|
||||
sched.build_connector_meta(make_scheduler_output({}))
|
||||
stats = sched.get_stats()
|
||||
assert LOAD_BLOCKS not in stats.data[_StatsKey.DATA]
|
||||
|
||||
sched.update_connector_output(
|
||||
KVConnectorOutput(finished_recving={request.request_id})
|
||||
)
|
||||
stats = sched.get_stats()
|
||||
assert _values(stats, LOAD_BLOCKS) == {(): 2}
|
||||
|
||||
|
||||
def test_manager_abandoned_load_counts_as_completed_after_reset() -> None:
|
||||
"""Loads abandoned by reset() that still finish on the worker are
|
||||
counted as loaded blocks.
|
||||
"""
|
||||
fixture = make_scheduler(num_cpu_blocks=8)
|
||||
sched = fixture.scheduler
|
||||
|
||||
request = make_request(num_blocks=2)
|
||||
gpu_blocks = fixture.gpu_block_pool.get_new_blocks(2)
|
||||
cpu_blocks = sched.cpu_block_pool.get_new_blocks(2)
|
||||
sched._reqs_to_load[request.request_id] = LoadRequestState(
|
||||
request=request,
|
||||
transfer_meta=TransferMeta(
|
||||
[b.block_id for b in gpu_blocks], [b.block_id for b in cpu_blocks]
|
||||
),
|
||||
)
|
||||
|
||||
sched.build_connector_meta(make_scheduler_output({}))
|
||||
stats = sched.get_stats()
|
||||
assert LOAD_BLOCKS not in stats.data[_StatsKey.DATA]
|
||||
|
||||
assert sched.reset() is False
|
||||
assert set(sched._abandoned_reqs_to_load) == {request.request_id}
|
||||
|
||||
sched.update_connector_output(
|
||||
KVConnectorOutput(finished_recving={request.request_id})
|
||||
)
|
||||
assert sched._abandoned_reqs_to_load == {}
|
||||
stats = sched.get_stats()
|
||||
assert _values(stats, LOAD_BLOCKS) == {(): 2}
|
||||
@@ -2316,8 +2316,8 @@ def _make_hybrid_attention_mamba_scheduler(
|
||||
def test_hybrid_store_uses_resolved_group_block_sizes() -> None:
|
||||
"""Replicated groups must not be scaled by the DCP world size.
|
||||
|
||||
``dcp_world_size_for_kv_cache_spec`` gives full attention the process DCP
|
||||
size and every other spec 1. Reconstructing a group's geometry as
|
||||
The spec's ``dcp_sharded`` flag controls its effective block size.
|
||||
Reconstructing a group's geometry as
|
||||
``spec.block_size * cp_world_size`` over-scales the replicated groups, so
|
||||
the eager store scan believes far fewer of their blocks are ready and
|
||||
silently offloads only a fraction of them.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
@@ -9,7 +10,7 @@ import torch
|
||||
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import (
|
||||
prepare_dflash_inputs,
|
||||
DFlashSpeculator,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
@@ -24,6 +25,7 @@ def _run_prepare(
|
||||
cp_rank: int = 0,
|
||||
cp_size: int = 1,
|
||||
cp_interleave: int = 1,
|
||||
draft_dcp_size: int | None = None,
|
||||
):
|
||||
device = torch.device("cuda")
|
||||
max_num_reqs = 4
|
||||
@@ -40,7 +42,9 @@ def _run_prepare(
|
||||
)
|
||||
input_batch = SimpleNamespace(
|
||||
num_reqs=1,
|
||||
num_tokens=4,
|
||||
num_scheduled_tokens=np.array([4], dtype=np.int32),
|
||||
seq_lens_cpu_upper_bound=torch.tensor([target_positions[-1] + 1]),
|
||||
positions=torch.tensor(target_positions, dtype=torch.int64, device=device),
|
||||
query_start_loc=torch.tensor([0, 4], dtype=torch.int32, device=device),
|
||||
idx_mapping=torch.tensor([2], dtype=torch.int32, device=device),
|
||||
@@ -74,36 +78,65 @@ def _run_prepare(
|
||||
next_prefill_tokens = torch.zeros_like(last_sampled)
|
||||
block_table = torch.tensor([block_table_values], dtype=torch.int32, device=device)
|
||||
|
||||
prepare_dflash_inputs(
|
||||
input_buffers,
|
||||
query_slot_mapping,
|
||||
context_positions,
|
||||
context_slot_mapping,
|
||||
sample_indices,
|
||||
sample_pos,
|
||||
sample_idx_mapping,
|
||||
temperature,
|
||||
seeds,
|
||||
input_batch,
|
||||
torch.tensor([1], dtype=torch.int32, device=device),
|
||||
torch.tensor([2], dtype=torch.int32, device=device),
|
||||
last_sampled,
|
||||
next_prefill_tokens,
|
||||
input_temperature,
|
||||
input_seeds,
|
||||
block_table,
|
||||
4,
|
||||
cp_rank,
|
||||
cp_size,
|
||||
cp_interleave,
|
||||
123,
|
||||
num_speculative_steps,
|
||||
num_speculative_steps,
|
||||
max_num_reqs,
|
||||
max_num_tokens,
|
||||
128,
|
||||
class InputsPrepared(Exception):
|
||||
pass
|
||||
|
||||
draft = SimpleNamespace(
|
||||
input_buffers=input_buffers,
|
||||
context_positions=context_positions,
|
||||
_context_slot_mappings=context_slot_mapping.unsqueeze(0),
|
||||
sample_indices=sample_indices,
|
||||
sample_pos=sample_pos,
|
||||
sample_idx_mapping=sample_idx_mapping,
|
||||
temperature=temperature,
|
||||
seeds=seeds,
|
||||
hidden_states=torch.zeros(4, 1, device=device),
|
||||
prepare_context_anchor=lambda *args: None,
|
||||
query_cudagraph_manager=None,
|
||||
dp_size=1,
|
||||
dp_rank=0,
|
||||
pcp_manager=None,
|
||||
draft_kv_cache_group_id=0,
|
||||
draft_kv_cache_group_ids=[0],
|
||||
_layer_group_idx=None,
|
||||
block_tables=SimpleNamespace(
|
||||
slot_mappings=query_slot_mapping.unsqueeze(0),
|
||||
input_block_tables=[block_table],
|
||||
kernel_block_sizes=[4],
|
||||
cp_rank=cp_rank,
|
||||
cp_size=cp_size,
|
||||
cp_interleave=cp_interleave,
|
||||
),
|
||||
dcp_size=cp_size if draft_dcp_size is None else draft_dcp_size,
|
||||
parallel_drafting_token_id=123,
|
||||
num_query_per_req=num_speculative_steps,
|
||||
num_speculative_steps=num_speculative_steps,
|
||||
max_num_reqs=max_num_reqs,
|
||||
max_num_tokens=max_num_tokens,
|
||||
max_model_len=128,
|
||||
sample_from_anchor=True,
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"vllm.v1.worker.gpu.spec_decode.dflash.speculator.dispatch_cg_and_sync_dp",
|
||||
side_effect=InputsPrepared,
|
||||
),
|
||||
pytest.raises(InputsPrepared),
|
||||
):
|
||||
DFlashSpeculator.propose(
|
||||
draft,
|
||||
input_batch,
|
||||
{},
|
||||
{},
|
||||
draft.hidden_states,
|
||||
None,
|
||||
torch.tensor([1], dtype=torch.int32, device=device),
|
||||
torch.tensor([2], dtype=torch.int32, device=device),
|
||||
last_sampled,
|
||||
next_prefill_tokens,
|
||||
input_temperature,
|
||||
input_seeds,
|
||||
)
|
||||
torch.accelerator.synchronize()
|
||||
return SimpleNamespace(
|
||||
input_buffers=input_buffers,
|
||||
@@ -118,12 +151,17 @@ def _run_prepare(
|
||||
)
|
||||
|
||||
|
||||
def test_prepare_dflash_inputs_excludes_rejected_context_suffix():
|
||||
@pytest.mark.parametrize("cp_rank,cp_size", [(0, 1), (0, 2), (1, 2)])
|
||||
def test_prepare_dflash_inputs_excludes_rejected_context_suffix(cp_rank, cp_size):
|
||||
# Positions 10/11 use physical block 7. Rejected positions 12/13 would use
|
||||
# block 8, but must be PAD context rather than contaminating draft KV.
|
||||
out = _run_prepare(
|
||||
target_positions=[10, 11, 12, 13],
|
||||
block_table_values=[0, 0, 7, 8, 9, 10, 11, 12],
|
||||
cp_rank=cp_rank,
|
||||
cp_size=cp_size,
|
||||
cp_interleave=2,
|
||||
draft_dcp_size=1,
|
||||
)
|
||||
|
||||
assert out.context_positions[:4].tolist() == [10, 11, 0, 0]
|
||||
|
||||
@@ -17,6 +17,7 @@ from types import MethodType, SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
@@ -53,6 +54,7 @@ def _make_fake_speculator(
|
||||
arange_np=np.arange(max_num_reqs + 1, dtype=np.int32),
|
||||
draft_is_prefilling=torch.zeros(max_num_reqs, dtype=torch.bool),
|
||||
block_tables=fake_block_tables,
|
||||
dcp_size=1,
|
||||
input_buffers=fake_input_buffers,
|
||||
attn_groups=[],
|
||||
kv_cache_config=SimpleNamespace(kv_cache_groups=[]),
|
||||
@@ -152,14 +154,17 @@ def test_build_draft_attn_metadata_clamps_to_max_model_len():
|
||||
assert torch.equal(bound, torch.tensor([1024, 503], dtype=torch.int32))
|
||||
|
||||
|
||||
def test_build_draft_attn_metadata_recomputes_dcp_local_seq_lens():
|
||||
@pytest.mark.parametrize("draft_dcp_size", [1, 2])
|
||||
def test_build_draft_attn_metadata_recomputes_dcp_local_seq_lens(draft_dcp_size):
|
||||
fake = _make_fake_speculator()
|
||||
fake.dcp_size = draft_dcp_size
|
||||
fake.block_tables.cp_size = 2
|
||||
fake.block_tables.cp_rank = 1
|
||||
fake.block_tables.cp_interleave = 4
|
||||
fake.input_buffers.seq_lens[:3] = torch.tensor([5, 9, 16])
|
||||
|
||||
def fake_prepare(out, seq_lens, num_reqs, dcp_size, dcp_rank, cp_interleave):
|
||||
assert draft_dcp_size > 1
|
||||
assert seq_lens is fake.input_buffers.seq_lens
|
||||
assert (num_reqs, dcp_size, dcp_rank, cp_interleave) == (3, 2, 1, 4)
|
||||
out[:num_reqs].copy_(torch.tensor([1, 4, 8], dtype=torch.int32))
|
||||
@@ -176,6 +181,9 @@ def test_build_draft_attn_metadata_recomputes_dcp_local_seq_lens():
|
||||
)
|
||||
|
||||
local = captured["dcp_local_seq_lens"]
|
||||
if draft_dcp_size == 1:
|
||||
assert local is None
|
||||
return
|
||||
assert isinstance(local, torch.Tensor)
|
||||
assert local.data_ptr() == fake.input_buffers.dcp_local_seq_lens.data_ptr()
|
||||
assert local.tolist() == [1, 4, 8, 0]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
@@ -7,6 +9,38 @@ from vllm.v1.attention.backends.utils import get_dcp_local_seq_lens
|
||||
from vllm.v1.worker.cp_utils import should_skip_dcp_context_attention
|
||||
|
||||
|
||||
def test_cp_checks_allow_a_replicated_draft_backend_without_dcp(monkeypatch):
|
||||
from vllm.v1.worker import cp_utils
|
||||
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=1,
|
||||
decode_context_parallel_size=4,
|
||||
cp_kv_cache_interleave_size=16,
|
||||
),
|
||||
speculative_config=object(),
|
||||
)
|
||||
target = SimpleNamespace(
|
||||
impl=SimpleNamespace(
|
||||
dcp_world_size=4,
|
||||
supports_mtp_with_cp_non_trivial_interleave_size=True,
|
||||
need_to_return_lse_for_decode=True,
|
||||
)
|
||||
)
|
||||
draft = SimpleNamespace(
|
||||
impl=SimpleNamespace(
|
||||
dcp_world_size=1,
|
||||
supports_mtp_with_cp_non_trivial_interleave_size=False,
|
||||
need_to_return_lse_for_decode=False,
|
||||
)
|
||||
)
|
||||
layers = {"target": target, "draft": draft}
|
||||
monkeypatch.setattr(cp_utils, "get_layers_from_vllm_config", lambda *args: layers)
|
||||
cp_utils.check_attention_cp_compatibility(config, target_layer_names={"target"})
|
||||
with pytest.raises(AssertionError, match="MTP with cp_kv_cache_interleave_size"):
|
||||
cp_utils.check_attention_cp_compatibility(config)
|
||||
|
||||
|
||||
def test_skip_gate_only_for_zero_context():
|
||||
assert should_skip_dcp_context_attention(torch.zeros(3, dtype=torch.int32))
|
||||
assert not should_skip_dcp_context_attention(
|
||||
|
||||
@@ -2,8 +2,17 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
from vllm.v1.worker.gpu import model_runner
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dspark.utils import _get_dspark_parallel_config
|
||||
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -49,3 +58,86 @@ def test_dspark_parallel_config_disables_eplb_atomically():
|
||||
assert draft_config.eplb_config.num_redundant_experts == 0
|
||||
assert not draft_config.enable_elastic_ep
|
||||
assert draft_config.eplb_config is not target_config.eplb_config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pcp_size", [1, 4])
|
||||
@pytest.mark.parametrize("dcp_size", [1, 4])
|
||||
@pytest.mark.parametrize("use_mla", [False, True])
|
||||
def test_draft_context_parallelism_without_changing_target(
|
||||
monkeypatch, pcp_size, dcp_size, use_mla
|
||||
):
|
||||
target_parallel = ParallelConfig(
|
||||
tensor_parallel_size=4,
|
||||
prefill_context_parallel_size=pcp_size,
|
||||
decode_context_parallel_size=dcp_size,
|
||||
cp_kv_cache_interleave_size=16,
|
||||
distributed_executor_backend="mp",
|
||||
)
|
||||
target_config = SimpleNamespace(
|
||||
parallel_config=target_parallel,
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(use_mla=use_mla)
|
||||
),
|
||||
)
|
||||
|
||||
class CapturedConfig(Exception):
|
||||
pass
|
||||
|
||||
def capture_init(self, config, device):
|
||||
raise CapturedConfig(config)
|
||||
|
||||
monkeypatch.setattr(DraftModelSpeculator, "__init__", capture_init)
|
||||
with pytest.raises(CapturedConfig) as captured:
|
||||
DFlashSpeculator(target_config, device=None)
|
||||
draft_parallel = captured.value.args[0].parallel_config
|
||||
assert draft_parallel.tensor_parallel_size == 4
|
||||
assert draft_parallel.prefill_context_parallel_size == 1
|
||||
assert draft_parallel.decode_context_parallel_size == (dcp_size if use_mla else 1)
|
||||
assert draft_parallel.cp_kv_cache_interleave_size == 16
|
||||
assert target_parallel.prefill_context_parallel_size == pcp_size
|
||||
assert target_parallel.decode_context_parallel_size == dcp_size
|
||||
assert target_parallel.cp_kv_cache_interleave_size == 16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("configured_dcp", [1, 4])
|
||||
def test_attention_uses_draft_dcp_setting_inside_target_process_group(
|
||||
monkeypatch, configured_dcp
|
||||
):
|
||||
import vllm.config as config_module
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.v1.attention.backend import AttentionImplBase
|
||||
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(decode_context_parallel_size=configured_dcp)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
config_module, "get_current_vllm_config_or_none", lambda: config
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_DCP", SimpleNamespace(world_size=4, rank_in_group=2)
|
||||
)
|
||||
impl = AttentionImplBase()
|
||||
assert impl.dcp_world_size == configured_dcp
|
||||
assert impl.dcp_rank == (0 if configured_dcp == 1 else 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft_dcp_size", [1, 4])
|
||||
def test_runner_marks_only_replicated_draft_caches(monkeypatch, draft_dcp_size):
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=64, dtype=torch.bfloat16
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
model_runner, "get_kv_cache_spec", lambda _: {"target": spec, "draft": spec}
|
||||
)
|
||||
runner = object.__new__(model_runner.GPUModelRunner)
|
||||
runner.vllm_config = None
|
||||
runner.dcp_size = 4
|
||||
runner.speculator = object.__new__(DFlashSpeculator)
|
||||
runner.speculator.dcp_size = draft_dcp_size
|
||||
runner.speculator.draft_attn_layer_names = {"draft"}
|
||||
|
||||
specs = runner.get_kv_cache_spec()
|
||||
|
||||
assert specs["target"].dcp_sharded
|
||||
assert specs["draft"].dcp_sharded == (draft_dcp_size == 4)
|
||||
|
||||
@@ -88,6 +88,7 @@ def test_pcp_draft_metadata_keeps_graph_padding_in_decode(cg_mode):
|
||||
query_start_loc=torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([11, 21, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
speculator.dcp_size = 1
|
||||
speculator.block_tables = SimpleNamespace(
|
||||
cp_size=1,
|
||||
input_block_tables=[torch.zeros(4, 1, dtype=torch.int32)],
|
||||
@@ -97,7 +98,9 @@ def test_pcp_draft_metadata_keeps_graph_padding_in_decode(cg_mode):
|
||||
speculator.attn_groups = [
|
||||
[
|
||||
SimpleNamespace(
|
||||
get_metadata_builder=lambda _: SimpleNamespace(build=build),
|
||||
get_metadata_builder=lambda _: SimpleNamespace(
|
||||
build=build, supports_update_block_table=False
|
||||
),
|
||||
layer_names=["draft"],
|
||||
)
|
||||
]
|
||||
@@ -183,6 +186,7 @@ def test_speculator_uses_draft_model_hidden_size(monkeypatch, hc_mult, expected)
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_size=1,
|
||||
data_parallel_rank=0,
|
||||
decode_context_parallel_size=1,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -171,22 +171,23 @@ def test_block_tables_skip_custom_slot_mapping_groups():
|
||||
|
||||
@pytest.mark.parametrize("cp_rank", range(4))
|
||||
def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int):
|
||||
"""DCP interleave is expressed in logical-block token coordinates."""
|
||||
"""Only sharded groups use DCP interleave in logical-block coordinates."""
|
||||
device = torch.device("cuda")
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[128],
|
||||
block_sizes=[128, 128],
|
||||
max_num_reqs=1,
|
||||
max_num_batched_tokens=1024,
|
||||
max_num_blocks_per_group=[2],
|
||||
max_num_blocks_per_group=[2, 8],
|
||||
device=device,
|
||||
kernel_block_sizes=[64],
|
||||
kernel_block_sizes=[64, 64],
|
||||
dcp_sharded=[True, False],
|
||||
cp_size=4,
|
||||
cp_rank=cp_rank,
|
||||
cp_interleave=128,
|
||||
)
|
||||
block_tables.append_block_ids(
|
||||
req_index=0,
|
||||
new_block_ids=([5, 9],),
|
||||
new_block_ids=([5, 9], list(range(10, 18))),
|
||||
overwrite=True,
|
||||
)
|
||||
block_tables.apply_staged_writes()
|
||||
@@ -199,7 +200,7 @@ def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int):
|
||||
query_start_loc,
|
||||
positions,
|
||||
num_tokens_padded=1024,
|
||||
)[0]
|
||||
)
|
||||
|
||||
expected = torch.full((1024,), -1, dtype=torch.int64, device=device)
|
||||
first_start = cp_rank * 128
|
||||
@@ -210,7 +211,8 @@ def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int):
|
||||
expected[second_start : second_start + 128] = torch.arange(
|
||||
9 * 128, 10 * 128, dtype=torch.int64, device=device
|
||||
)
|
||||
assert torch.equal(actual, expected)
|
||||
assert torch.equal(actual[0], expected)
|
||||
assert torch.equal(actual[1], positions + 10 * 128)
|
||||
|
||||
|
||||
def test_v1_block_table_move_row_clears_vacated_row():
|
||||
|
||||
@@ -372,6 +372,62 @@ def test_swap_states_in_input_batch(device: str, batch_size: int, swap_list: lis
|
||||
_compare_objs(input_batch, ref_input_batch)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
def test_condense_clears_stale_allowed_token_ids_mask(device: str):
|
||||
"""condense() must clear the mask row a constrained request is moved out
|
||||
of. Otherwise a later request that reuses that row without
|
||||
allowed_token_ids inherits the stale whitelist.
|
||||
See https://github.com/vllm-project/vllm/issues/43894.
|
||||
"""
|
||||
batch_size = 4
|
||||
allowed_token_id = 13
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=batch_size,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[1],
|
||||
kernel_block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
|
||||
def _make_req(suffix: int, allowed_token_ids=None) -> CachedRequestState:
|
||||
return CachedRequestState(
|
||||
req_id=f"req_id_{suffix}",
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(allowed_token_ids=allowed_token_ids),
|
||||
pooling_params=None,
|
||||
mm_features=[],
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
# Only req_id_2 is constrained, and it lands on the highest row.
|
||||
assert input_batch.add_request(_make_req(0)) == 0
|
||||
assert input_batch.add_request(_make_req(1)) == 1
|
||||
assert input_batch.add_request(_make_req(2, [allowed_token_id])) == 2
|
||||
|
||||
mask = input_batch.allowed_token_ids_mask_cpu_tensor
|
||||
assert mask is not None
|
||||
# The constrained row masks every token except the single allowed id.
|
||||
assert not mask[2][allowed_token_id].item()
|
||||
assert int(mask[2].sum().item()) == VOCAB_SIZE - 1
|
||||
|
||||
# Free row 0, then condense: req_id_2 slides from row 2 down into row 0.
|
||||
input_batch.remove_request("req_id_0")
|
||||
input_batch.condense()
|
||||
assert input_batch.req_id_to_index["req_id_2"] == 0
|
||||
assert int(mask[2].sum().item()) == 0
|
||||
|
||||
# A new unrestricted request reuses row 2 and must stay unconstrained.
|
||||
assert input_batch.add_request(_make_req(3)) == 2
|
||||
assert "req_id_3" not in input_batch.has_allowed_token_ids
|
||||
assert int(mask[2].sum().item()) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
def test_swap_states_preserves_allowed_token_ids_mask(device: str):
|
||||
"""swap_states() must exchange the two allowed_token_ids_mask rows.
|
||||
|
||||
@@ -75,6 +75,24 @@ def test_validate_config_rejects_full_graph_for_prefills():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft_uses_mla", [False, True])
|
||||
@pytest.mark.parametrize("dcp_size", [1, 2, 4])
|
||||
def test_validate_config_dcp_for_dspark(draft_uses_mla, dcp_size):
|
||||
config = _make_config(CUDAGraphMode.NONE)
|
||||
config.parallel_config.prefill_context_parallel_size = 4
|
||||
config.parallel_config.decode_context_parallel_size = dcp_size
|
||||
config.model_config.hf_text_config.index_topk = 1
|
||||
config.speculative_config = SimpleNamespace(
|
||||
use_dspark=lambda: True,
|
||||
draft_model_config=SimpleNamespace(use_mla=draft_uses_mla),
|
||||
)
|
||||
if draft_uses_mla and dcp_size == 2:
|
||||
with pytest.raises(NotImplementedError, match="requires DCP=1 or DCP=PCP"):
|
||||
PCPManager.validate_config(config, supports_mm_inputs=False)
|
||||
return
|
||||
PCPManager.validate_config(config, supports_mm_inputs=False)
|
||||
|
||||
|
||||
def test_replicated_decode_piecewise_graph_padding(monkeypatch):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
|
||||
Reference in New Issue
Block a user