Merge remote-tracking branch 'upstream/main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -23,6 +23,8 @@ from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
BuildPrefillChunkMetadataKernel,
|
||||
DeepseekV4IndexerBackend,
|
||||
DeepSeekV32IndexerDecodeMetadata,
|
||||
DeepseekV32IndexerMetadata,
|
||||
DeepseekV32IndexerMetadataBuilder,
|
||||
DeepseekV41IndexerBackend,
|
||||
get_max_prefill_buffer_size,
|
||||
@@ -99,6 +101,72 @@ def test_fused_indexer_decode_metadata(query_lens, padding):
|
||||
torch.testing.assert_close(per_req[:reqs], lengths)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_indexer_draft_decode_metadata_update_is_capture_safe():
|
||||
if not indexer_module.has_deep_gemm():
|
||||
pytest.skip("requires DeepGEMM")
|
||||
device = torch.device("cuda")
|
||||
num_reqs = 3
|
||||
seq_lens = torch.tensor([17, 33, 65], dtype=torch.int32, device=device)
|
||||
decode_seq_lens = torch.zeros((num_reqs, 1), dtype=torch.int32, device=device)
|
||||
block_table = torch.arange(num_reqs * 4, dtype=torch.int32, device=device).view(
|
||||
num_reqs, 4
|
||||
)
|
||||
num_sms = torch.cuda.get_device_properties(device).multi_processor_count
|
||||
schedule_metadata = indexer_module.get_paged_mqa_logits_metadata(
|
||||
torch.div(seq_lens, 16, rounding_mode="floor").unsqueeze(1),
|
||||
64,
|
||||
num_sms,
|
||||
).clone()
|
||||
|
||||
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
|
||||
builder.dcp_world_size = 1
|
||||
builder.compress_ratio = 16
|
||||
builder.num_sms = num_sms
|
||||
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
|
||||
builder.kv_cache_spec = SimpleNamespace(num_states=64)
|
||||
metadata = DeepseekV32IndexerMetadata(
|
||||
seq_lens=seq_lens,
|
||||
max_seq_len=128,
|
||||
slot_mapping=torch.zeros(num_reqs, dtype=torch.int64, device=device),
|
||||
num_decodes=num_reqs,
|
||||
num_decode_tokens=num_reqs,
|
||||
num_prefills=0,
|
||||
num_prefill_tokens=0,
|
||||
decode=DeepSeekV32IndexerDecodeMetadata(
|
||||
block_table=block_table,
|
||||
seq_lens=decode_seq_lens,
|
||||
decode_lens=torch.zeros(num_reqs, dtype=torch.int32, device=device),
|
||||
requires_padding=False,
|
||||
schedule_metadata=schedule_metadata,
|
||||
),
|
||||
)
|
||||
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
builder.update_draft_decode_metadata(metadata)
|
||||
|
||||
seq_lens.copy_(torch.tensor([32, 48, 80], dtype=torch.int32, device=device))
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected_decode_seq_lens = torch.div(seq_lens, 16, rounding_mode="floor")
|
||||
torch.testing.assert_close(decode_seq_lens.flatten(), expected_decode_seq_lens)
|
||||
torch.testing.assert_close(
|
||||
schedule_metadata,
|
||||
indexer_module.get_paged_mqa_logits_metadata(
|
||||
expected_decode_seq_lens.unsqueeze(1), 64, num_sms
|
||||
),
|
||||
)
|
||||
assert metadata.decode is not None
|
||||
assert torch.all(metadata.decode.decode_lens == 1)
|
||||
expected_slot_mapping = block_table[:, 0].to(torch.int64) * 64 + torch.tensor(
|
||||
[1, 2, 4], dtype=torch.int64, device=device
|
||||
)
|
||||
torch.testing.assert_close(metadata.slot_mapping, expected_slot_mapping)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize(
|
||||
"query_lens", [[1], [0, 257, 1, 0, 3], [6] * 64, [2, 6, 4, 0], [0, 0, 0]]
|
||||
|
||||
@@ -300,6 +300,16 @@ def test_builder_build_falls_back_without_positions():
|
||||
assert meta.slot_mapping is cam.slot_mapping
|
||||
|
||||
|
||||
def test_builder_updates_draft_mapping():
|
||||
builder = make_tail_builder()
|
||||
cam = make_common_metadata([[15], [16]], [5, 9])
|
||||
meta = KpoolTailMetadataBuilder.build(builder, 0, cam)
|
||||
assert cam.positions is not None
|
||||
cam.positions.add_(1)
|
||||
builder.update_draft_decode_metadata(meta)
|
||||
assert meta.slot_mapping[:2].tolist() == [5 * KPOOL, 9 * KPOOL + 1]
|
||||
|
||||
|
||||
def test_builder_reuses_slot_mapping_storage():
|
||||
builder = make_tail_builder()
|
||||
first = make_common_metadata([list(range(10))], [5])
|
||||
|
||||
@@ -65,6 +65,9 @@ from vllm.model_executor.layers.attention.sparse_mla_attention import (
|
||||
)
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import current_stream
|
||||
from vllm.v1.attention.backends.mla import (
|
||||
flashattn_mla_sparse as flashattn_sparse_module,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla import index_group as index_group_module
|
||||
from vllm.v1.attention.backends.mla.flashattn_mla_sparse import (
|
||||
FlashAttnMLASparseImpl,
|
||||
@@ -3405,6 +3408,129 @@ def test_flashinfer_hisparse_decode_runs_batched_attention():
|
||||
assert lse is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_device_capability_family(90),
|
||||
reason="FlashAttention MLA requires Hopper",
|
||||
)
|
||||
@pytest.mark.parametrize("use_cuda_graph", [False, True])
|
||||
@pytest.mark.parametrize("block_stride_rows", [64, 128])
|
||||
@pytest.mark.parametrize(
|
||||
"query_len,num_decode_tokens,max_decode_rows,num_layers",
|
||||
[
|
||||
pytest.param(1, 2, 2, 4, id="decode"),
|
||||
pytest.param(4, 8, 8, 4, id="mtp4"),
|
||||
pytest.param(6, 12, 12, 4, id="mtp6"),
|
||||
pytest.param(4, 8, 2, 4, id="scratch_overflow"),
|
||||
pytest.param(4, 4, 8, 4, id="mixed"),
|
||||
pytest.param(4, 0, 8, 4, id="prefill"),
|
||||
pytest.param(4, 8, 8, 1, id="single_layer"),
|
||||
],
|
||||
)
|
||||
def test_flashattn_shared_indices_match_independent_conversion(
|
||||
monkeypatch,
|
||||
query_len,
|
||||
num_decode_tokens,
|
||||
max_decode_rows,
|
||||
num_layers,
|
||||
block_stride_rows,
|
||||
use_cuda_graph,
|
||||
):
|
||||
"""Reuse must preserve attention outputs as requests and pages change."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
num_tokens, block_size, topk, seq_len = 2 * query_len, 64, 2048, 8192
|
||||
blocks_per_req = seq_len // block_size
|
||||
logical = torch.arange(
|
||||
0, seq_len, seq_len // topk, dtype=torch.int32, device=device
|
||||
).repeat(num_tokens, 1)
|
||||
logical[:, ::7] = -1
|
||||
builder = SparseMLAIndexGroupBuilder(logical, max_decode_rows=max_decode_rows)
|
||||
metadata = SimpleNamespace(
|
||||
block_table=torch.randperm(
|
||||
2 * blocks_per_req, dtype=torch.int32, device=device
|
||||
).view(2, blocks_per_req),
|
||||
block_size=block_size,
|
||||
req_id_per_token=torch.arange(
|
||||
2, dtype=torch.int32, device=device
|
||||
).repeat_interleave(query_len),
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
)
|
||||
q_nope = torch.randn(num_tokens, 8, 512, dtype=torch.bfloat16, device=device)
|
||||
q_rope = torch.randn(num_tokens, 8, 64, dtype=torch.bfloat16, device=device)
|
||||
caches = torch.randn(
|
||||
num_layers,
|
||||
2 * blocks_per_req,
|
||||
block_stride_rows,
|
||||
576,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)[:, :, :block_size]
|
||||
impls = []
|
||||
for i in range(num_layers):
|
||||
impl = object.__new__(FlashAttnMLASparseImpl)
|
||||
impl.topk_indices_buffer = logical
|
||||
impl.index_group, impl.index_group_index = builder.register_layer(i == 0)
|
||||
impl.dcp_world_size = 1
|
||||
impl.kv_lora_rank, impl.qk_rope_head_dim = 512, 64
|
||||
impl.scale = 256**-0.5
|
||||
impl.cu_seqlens_q_buffer = torch.arange(
|
||||
num_tokens + 1, dtype=torch.int32, device=device
|
||||
)
|
||||
impls.append(impl)
|
||||
|
||||
convert = triton_convert_req_index_to_global_index
|
||||
convert_spy = MagicMock(wraps=convert)
|
||||
for module in (index_group_module, flashattn_sparse_module):
|
||||
monkeypatch.setattr(
|
||||
module, "triton_convert_req_index_to_global_index", convert_spy
|
||||
)
|
||||
|
||||
def run():
|
||||
impls[0].record_logical_topk_ready()
|
||||
return [
|
||||
impl.forward_mqa((q_nope, q_rope), cache, metadata, None)[0]
|
||||
for impl, cache in zip(impls, caches)
|
||||
]
|
||||
|
||||
stream = torch.cuda.Stream(device=device)
|
||||
stream.wait_stream(current_stream())
|
||||
with torch.cuda.stream(stream):
|
||||
run() # Warm up the conversion and FA3 kernels before capture.
|
||||
stream.synchronize()
|
||||
convert_spy.reset_mock()
|
||||
if use_cuda_graph:
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph, stream=stream):
|
||||
outputs = run()
|
||||
else:
|
||||
outputs = run()
|
||||
reuse = num_decode_tokens == num_tokens and num_tokens <= max_decode_rows + 1
|
||||
assert convert_spy.call_count == (1 if reuse else num_layers)
|
||||
|
||||
for _ in range(2):
|
||||
metadata.req_id_per_token.copy_(metadata.req_id_per_token.flip(0))
|
||||
metadata.block_table.copy_(metadata.block_table.roll(1, dims=1))
|
||||
logical.copy_(torch.where(logical >= 0, (logical + 1) % seq_len, logical))
|
||||
if use_cuda_graph:
|
||||
graph.replay()
|
||||
else:
|
||||
outputs = run()
|
||||
physical, counts = convert(
|
||||
metadata.req_id_per_token,
|
||||
metadata.block_table,
|
||||
logical,
|
||||
BLOCK_SIZE=block_size,
|
||||
BLOCK_STRIDE_ROWS=block_stride_rows,
|
||||
NUM_TOPK_TOKENS=topk,
|
||||
return_valid_counts=True,
|
||||
)
|
||||
for impl, cache, actual in zip(impls, caches, outputs):
|
||||
expected = impl._run_mqa_kernel(
|
||||
q_nope, q_rope, cache, physical, counts, block_size
|
||||
)
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
stream.synchronize()
|
||||
|
||||
|
||||
def test_flashattn_hisparse_decode_uses_index_group():
|
||||
num_tokens = 4
|
||||
q_nope = torch.empty(num_tokens, 2, 3, device=DEVICE_TYPE)
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
the hit to rebuild the non-cacheable sliding-window group, keeps the hit's
|
||||
blocks, and hands the worker the replay start."""
|
||||
|
||||
import dataclasses
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
@@ -277,3 +279,53 @@ def test_hit_no_longer_than_window_is_ignored(via_connector):
|
||||
assert new_req.num_computed_tokens == 0
|
||||
assert new_req.replay_start == 0
|
||||
assert out.num_scheduled_tokens[request.request_id] == NUM_PROMPT_TOKENS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("is_async", [True, False])
|
||||
@pytest.mark.parametrize("loads_window", [True, False])
|
||||
def test_kv_load_zeroing_respects_loaded_groups(is_async, loads_window):
|
||||
"""Only groups restored by an async load skip zeroing. P/D loads include
|
||||
the non-cacheable window; stores leave it to be initialized locally."""
|
||||
local = 5 * BLOCK_SIZE
|
||||
scheduler = _replay_scheduler(use_kv_connector=MockKVConfig())
|
||||
if loads_window:
|
||||
scheduler.connector.get_loaded_kv_cache_group_ids = lambda request: (FULL, SWA)
|
||||
assert scheduler.needs_kv_cache_zeroing
|
||||
first = create_requests(
|
||||
num_requests=1, num_tokens=local, same_prompt=True, block_size=BLOCK_SIZE
|
||||
)[0]
|
||||
_prefill(scheduler, first)
|
||||
scheduler.connector.config = dataclasses.replace(
|
||||
scheduler.connector.config,
|
||||
matched_tokens=NUM_PROMPT_TOKENS - 1 - local,
|
||||
is_async=is_async,
|
||||
)
|
||||
request = create_requests(
|
||||
num_requests=1,
|
||||
num_tokens=NUM_PROMPT_TOKENS,
|
||||
same_prompt=True,
|
||||
block_size=BLOCK_SIZE,
|
||||
req_ids=["load"],
|
||||
)[0]
|
||||
scheduler.add_request(request)
|
||||
out = scheduler.schedule()
|
||||
|
||||
manager = scheduler.kv_cache_manager
|
||||
hit_ids = {
|
||||
b.block_id for g in manager.get_blocks(first.request_id).blocks for b in g
|
||||
}
|
||||
swa_blocks = manager.get_blocks(request.request_id).blocks[SWA]
|
||||
assert any(
|
||||
not b.is_null and b.block_id not in hit_ids
|
||||
for b in swa_blocks[: local // BLOCK_SIZE]
|
||||
)
|
||||
zeroed = set(out.new_block_ids_to_zero or ())
|
||||
for group_id, blocks in enumerate(manager.get_blocks(request.request_id).blocks):
|
||||
new_ids = {
|
||||
b.block_id for b in blocks if not b.is_null and b.block_id not in hit_ids
|
||||
}
|
||||
assert new_ids
|
||||
if is_async and (group_id == FULL or loads_window):
|
||||
assert not new_ids & zeroed
|
||||
else:
|
||||
assert new_ids <= zeroed
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
ChunkedLocalAttentionManager,
|
||||
CircularBufferManager,
|
||||
FullAttentionManager,
|
||||
KpoolTailManager,
|
||||
MambaManager,
|
||||
RSWAManager,
|
||||
SlidingWindowManager,
|
||||
@@ -24,6 +25,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
ChunkedLocalAttentionSpec,
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KpoolTailSpec,
|
||||
MambaSpec,
|
||||
RSWASpec,
|
||||
SlidingWindowSpec,
|
||||
@@ -332,6 +334,37 @@ def test_circular_buffer_allocates_one_block_for_the_request_lifetime():
|
||||
assert manager.req_to_blocks[request_id] == blocks
|
||||
|
||||
|
||||
@pytest.mark.parametrize("record_for_zeroing", [True, False])
|
||||
def test_external_kpool_tail_zeroing(record_for_zeroing):
|
||||
"""A transferred ring at index zero skips zeroing even with a local hit."""
|
||||
spec = KpoolTailSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=2,
|
||||
head_size=8,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=4,
|
||||
)
|
||||
manager = KpoolTailManager(
|
||||
spec,
|
||||
block_pool=BlockPool(10, enable_caching=True, hash_block_size=4),
|
||||
enable_caching=True,
|
||||
kv_cache_group_id=0,
|
||||
scheduler_block_size=4,
|
||||
needs_kv_cache_zeroing=True,
|
||||
max_admission_blocks_per_request=1,
|
||||
)
|
||||
manager.allocate_external_computed_blocks(
|
||||
"request", 16, 4, record_for_zeroing=record_for_zeroing
|
||||
)
|
||||
blocks = manager.req_to_blocks["request"]
|
||||
assert len(blocks) == 1
|
||||
assert manager.take_new_block_ids() == (
|
||||
[blocks[0].block_id] if record_for_zeroing else []
|
||||
)
|
||||
assert manager.allocate_new_blocks("request", 20, 20) == []
|
||||
assert manager.take_new_block_ids() == []
|
||||
|
||||
|
||||
def test_sliding_window_records_new_blocks_for_zeroing():
|
||||
block_size = 2
|
||||
spec = SlidingWindowSpec(
|
||||
|
||||
@@ -192,6 +192,7 @@ def get_fake_allocate_slots_fn(original_allocate_slots_fn: Callable):
|
||||
full_sequence_must_fit: bool = False,
|
||||
reserved_blocks: int = 0,
|
||||
has_scheduled_reqs: bool = True,
|
||||
skip_zeroing_group_ids: tuple[int, ...] = (),
|
||||
):
|
||||
ret = original_allocate_slots_fn(
|
||||
self,
|
||||
@@ -206,6 +207,7 @@ def get_fake_allocate_slots_fn(original_allocate_slots_fn: Callable):
|
||||
full_sequence_must_fit,
|
||||
reserved_blocks,
|
||||
has_scheduled_reqs,
|
||||
skip_zeroing_group_ids,
|
||||
)
|
||||
if cur_step_action is not None:
|
||||
cur_block_ids = self.coordinator.single_type_managers[0].req_to_blocks[
|
||||
|
||||
@@ -491,7 +491,7 @@ async def test_streaming_input_per_chunk_sampling_params(engine: AsyncLLM):
|
||||
async def test_streaming_input_empty_generator(engine: AsyncLLM):
|
||||
"""Test behavior when the input generator yields nothing.
|
||||
|
||||
An empty generator should still produce a finished output.
|
||||
An empty generator should finish without producing output.
|
||||
"""
|
||||
request_id = "test_empty_generator"
|
||||
sampling_params = get_sampling_params(max_tokens=10)
|
||||
@@ -505,9 +505,7 @@ async def test_streaming_input_empty_generator(engine: AsyncLLM):
|
||||
async for output in engine.generate(empty_generator(), sampling_params, request_id):
|
||||
outputs.append(output)
|
||||
|
||||
# Should still get a finished marker
|
||||
assert len(outputs) >= 1, "Should receive at least one output"
|
||||
assert outputs[-1].finished, "Should have a finished output"
|
||||
assert outputs == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="module")
|
||||
|
||||
@@ -150,6 +150,21 @@ def test_draft_model_quantization(
|
||||
assert_draft_model_correctness(sd_case, vllm_runner)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_draft_model_transformers_backend(vllm_runner):
|
||||
"""Ensure that Attention prefixes don't collide between the target and
|
||||
draft models when both models use the Transformers modelling backend."""
|
||||
sd_case = ArgsTest(
|
||||
target_model="allenai/OLMo-2-0425-1B-Instruct",
|
||||
draft_model="allenai/OLMo-2-0425-1B-Instruct",
|
||||
sampling_config=greedy_sampling(),
|
||||
num_speculative_tokens=3,
|
||||
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
|
||||
expected_acceptance_rate=0.98, # slight epsilon
|
||||
)
|
||||
assert_draft_model_correctness(sd_case, vllm_runner)
|
||||
|
||||
|
||||
@multi_gpu_only(num_gpus=2)
|
||||
def test_draft_model_tensor_parallelism(vllm_runner):
|
||||
"""Ensure spec decode works when running with TP > 1."""
|
||||
|
||||
@@ -48,16 +48,6 @@ def check_mtp_correctness(
|
||||
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,
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import random
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
|
||||
from vllm.v1.engine.llm_engine import LLMEngine
|
||||
from vllm.v1.metrics.reader import Counter, Gauge, Histogram, Metric, Vector
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -18,6 +20,38 @@ MODEL = "facebook/opt-125m"
|
||||
DTYPE = "half"
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_step_invalidates_mm_processor_cache_misses():
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.should_execute_dummy_batch = False
|
||||
engine.log_stats = False
|
||||
engine.logger_manager = None
|
||||
|
||||
mm_processor_cache = MagicMock()
|
||||
engine.renderer = MagicMock(mm_processor_cache=mm_processor_cache)
|
||||
|
||||
engine_core_output = MagicMock(
|
||||
mm_cache_miss_hashes=["missing-hash-1", "missing-hash-2"]
|
||||
)
|
||||
outputs = MagicMock(
|
||||
outputs=[engine_core_output],
|
||||
timestamp=0.0,
|
||||
scheduler_stats=None,
|
||||
)
|
||||
engine.engine_core = MagicMock()
|
||||
engine.engine_core.get_output.return_value = outputs
|
||||
|
||||
processed_outputs = MagicMock(reqs_to_abort=[], request_outputs=[])
|
||||
engine.output_processor = MagicMock()
|
||||
engine.output_processor.process_outputs.return_value = processed_outputs
|
||||
|
||||
assert engine.step() == []
|
||||
assert mm_processor_cache.invalidate.call_args_list == [
|
||||
call("missing-hash-1"),
|
||||
call("missing-hash-2"),
|
||||
]
|
||||
|
||||
|
||||
def _vllm_model(
|
||||
apc: bool,
|
||||
vllm_runner: type[VllmRunner],
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, Mock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.engine.utils import (
|
||||
NUM_PROMPT_LOGPROBS_UNDER_TEST,
|
||||
@@ -18,7 +19,12 @@ from tests.v1.engine.utils import (
|
||||
from vllm import PoolingParams
|
||||
from vllm.logprobs import FlatLogprobs, Logprob, PromptLogprobs, SampleLogprobs
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.outputs import CompletionOutput, RequestOutput, SamplingMask
|
||||
from vllm.outputs import (
|
||||
CompletionOutput,
|
||||
PoolingRequestOutput,
|
||||
RequestOutput,
|
||||
SamplingMask,
|
||||
)
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.v1.engine import (
|
||||
@@ -1630,3 +1636,92 @@ def test_request_output_add_merges_delta_sampling_masks():
|
||||
|
||||
assert merged.outputs[0].token_ids == [10, 20]
|
||||
assert merged.outputs[0].sampling_mask.token_ids == [[10, 11], [20]]
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_pooling_cache_miss_is_a_request_error_and_batch_continues():
|
||||
output_processor = OutputProcessor(tokenizer=None, log_stats=False)
|
||||
requests = [
|
||||
EngineCoreRequest(
|
||||
request_id=f"request-{idx}-int",
|
||||
external_req_id=f"request-{idx}",
|
||||
prompt_token_ids=[1, 2],
|
||||
mm_features=None,
|
||||
arrival_time=0,
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
sampling_params=None,
|
||||
pooling_params=PoolingParams(task="embed"),
|
||||
)
|
||||
for idx in range(2)
|
||||
]
|
||||
for request in requests:
|
||||
output_processor.add_request(request, prompt=None)
|
||||
|
||||
processed = output_processor.process_outputs(
|
||||
[
|
||||
EngineCoreOutput(
|
||||
request_id=requests[0].request_id,
|
||||
new_token_ids=[],
|
||||
finish_reason=FinishReason.ERROR,
|
||||
mm_cache_miss_hashes=["missing-hash"],
|
||||
),
|
||||
EngineCoreOutput(
|
||||
request_id=requests[1].request_id,
|
||||
new_token_ids=[],
|
||||
pooling_output=torch.tensor([1.0, 2.0]),
|
||||
finish_reason=FinishReason.STOP,
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
assert len(processed.request_outputs) == 2
|
||||
failed, succeeded = processed.request_outputs
|
||||
assert isinstance(failed, PoolingRequestOutput)
|
||||
assert failed.error is not None
|
||||
assert failed.error.code == "multimodal_cache_miss"
|
||||
assert failed.error.retryable
|
||||
assert isinstance(succeeded, PoolingRequestOutput)
|
||||
assert succeeded.error is None
|
||||
assert torch.equal(succeeded.outputs.data, torch.tensor([1.0, 2.0]))
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_async_pooling_cache_miss_does_not_fail_output_processor():
|
||||
output_processor = OutputProcessor(tokenizer=None, log_stats=False)
|
||||
request = EngineCoreRequest(
|
||||
request_id="request-int",
|
||||
external_req_id="request",
|
||||
prompt_token_ids=[1, 2],
|
||||
mm_features=None,
|
||||
arrival_time=0,
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
sampling_params=None,
|
||||
pooling_params=PoolingParams(task="embed"),
|
||||
)
|
||||
queue = RequestOutputCollector(
|
||||
output_kind=RequestOutputKind.FINAL_ONLY,
|
||||
request_id=request.request_id,
|
||||
)
|
||||
output_processor.add_request(request, prompt=None, queue=queue)
|
||||
|
||||
processed = output_processor.process_outputs(
|
||||
[
|
||||
EngineCoreOutput(
|
||||
request_id=request.request_id,
|
||||
new_token_ids=[],
|
||||
finish_reason=FinishReason.ERROR,
|
||||
mm_cache_miss_hashes=["missing-hash"],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
assert processed.request_outputs == []
|
||||
output = queue.get_nowait()
|
||||
assert isinstance(output, PoolingRequestOutput)
|
||||
assert output.error is not None
|
||||
assert output.error.retryable
|
||||
assert not output_processor.has_unfinished_requests()
|
||||
|
||||
@@ -111,6 +111,7 @@ def test_error_propagation_async_load(fail_scheduler: Scheduler):
|
||||
}
|
||||
|
||||
fail_scheduler.connector = Mock()
|
||||
fail_scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
|
||||
fail_scheduler.connector.get_num_new_matched_tokens.side_effect = (
|
||||
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, True)
|
||||
)
|
||||
|
||||
@@ -327,6 +327,7 @@ def test_async_recompute_blocks_not_cached_when_invalid(
|
||||
recompute_scheduler.connector.get_num_new_matched_tokens.side_effect = (
|
||||
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, True)
|
||||
)
|
||||
recompute_scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
|
||||
recompute_scheduler.connector.request_finished.return_value = (False, None)
|
||||
recompute_scheduler.connector.take_events.return_value = ()
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ def test_failed_receive_completion_honors_failure_policy(policy):
|
||||
request = create_request(num_tokens=3 * scheduler.block_size)
|
||||
scheduler.add_request(request)
|
||||
scheduler.connector = Mock()
|
||||
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
|
||||
scheduler.connector.get_num_new_matched_tokens.side_effect = [
|
||||
(2 * scheduler.block_size, True),
|
||||
(0, False),
|
||||
@@ -103,6 +104,7 @@ def test_async_load_failure(
|
||||
}
|
||||
|
||||
scheduler.connector = Mock()
|
||||
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
|
||||
scheduler.connector.get_num_new_matched_tokens.side_effect = (
|
||||
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True)
|
||||
)
|
||||
@@ -332,6 +334,7 @@ def test_async_progressive_load_failure(
|
||||
}
|
||||
|
||||
scheduler.connector = Mock()
|
||||
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
|
||||
scheduler.connector.get_num_new_matched_tokens.side_effect = (
|
||||
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True)
|
||||
)
|
||||
|
||||
@@ -1549,6 +1549,40 @@ async def test_kv_producer(monkeypatch):
|
||||
prefill_worker.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("local_block_ids", "expected_finished"),
|
||||
[
|
||||
([], set()),
|
||||
([[]], set()),
|
||||
([[100]], {"d-req-1"}),
|
||||
],
|
||||
)
|
||||
def test_pull_completion_requires_local_blocks(
|
||||
local_block_ids: list[list[int]],
|
||||
expected_finished: set[str],
|
||||
):
|
||||
worker = MooncakeConnectorWorker.__new__(MooncakeConnectorWorker)
|
||||
worker.shutdown = MagicMock()
|
||||
worker.finished_recving_reqs = set()
|
||||
pull_meta = PullReqMeta(
|
||||
d_req_id="d-req-1",
|
||||
transfer_id="xfer-req-1",
|
||||
local_block_ids=local_block_ids,
|
||||
remote_engine_id="p-engine",
|
||||
remote_bootstrap_addr="http://bootstrap:33333",
|
||||
pull_tasks_count=1,
|
||||
)
|
||||
response = MooncakeXferResponse(
|
||||
status=MooncakeXferResponseStatus.FINISH,
|
||||
ok_reqs=["d-req-1"],
|
||||
)
|
||||
|
||||
worker.process_pulling_result(response, {"d-req-1": pull_meta})
|
||||
|
||||
assert pull_meta.pull_tasks_count == 0
|
||||
assert worker.finished_recving_reqs == expected_finished
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_kv_consumuer(monkeypatch):
|
||||
"""Simulates a Consumer Worker (Decoder) initiating a pull from a Producer.
|
||||
|
||||
@@ -22,14 +22,20 @@ Role shapes below are exactly those in the RFC (#46107) deployments:
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import ctypes
|
||||
import importlib.util
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import types
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
import msgpack
|
||||
import pytest
|
||||
import zmq
|
||||
|
||||
_MISSING = object()
|
||||
|
||||
@@ -203,3 +209,127 @@ def test_consecutive_requests_alternate_instances(route):
|
||||
# than filling one instance's ranks before moving on.
|
||||
insts = [inst for inst, _ in _route_n(route, _instances(3, 8), 3)]
|
||||
assert insts == [0, 1, 2]
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="GIL probe uses libc.usleep")
|
||||
def test_discovery_heartbeat_progresses_while_worker_holds_gil():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_heartbeat import (
|
||||
MoRIIOHeartbeat,
|
||||
)
|
||||
|
||||
payload = {
|
||||
"type": "P",
|
||||
"http_address": "127.0.0.1:8000",
|
||||
"zmq_address": "host:127.0.0.1,handshake:6301,notify:61005",
|
||||
"dp_size": 1,
|
||||
"tp_size": 8,
|
||||
"transfer_mode": "READ",
|
||||
}
|
||||
with zmq.Context() as context, context.socket(zmq.ROUTER) as socket:
|
||||
port = socket.bind_to_random_port("tcp://127.0.0.1")
|
||||
heartbeat = MoRIIOHeartbeat(f"tcp://127.0.0.1:{port}", payload, 0.02)
|
||||
try:
|
||||
assert socket.poll(5000), "Discovery did not register"
|
||||
assert msgpack.unpackb(socket.recv_multipart()[1]) == payload
|
||||
# PyDLL retains the GIL throughout the native call.
|
||||
ctypes.PyDLL(None).usleep(300_000)
|
||||
received = 0
|
||||
while socket.poll(0):
|
||||
assert msgpack.unpackb(socket.recv_multipart()[1]) == payload
|
||||
received += 1
|
||||
assert received >= 3, "Discovery stalled while the worker held the GIL"
|
||||
finally:
|
||||
heartbeat.shutdown()
|
||||
heartbeat.shutdown()
|
||||
while socket.poll(0):
|
||||
socket.recv_multipart()
|
||||
assert not socket.poll(100), "Heartbeats continued after shutdown"
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="Checks child exit via procfs")
|
||||
def test_discovery_heartbeat_exits_when_worker_dies():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio import moriio_heartbeat
|
||||
|
||||
owner_code = """
|
||||
import runpy
|
||||
import sys
|
||||
Heartbeat = runpy.run_path(sys.argv[1])["MoRIIOHeartbeat"]
|
||||
heartbeat = Heartbeat(sys.argv[2], {"type": "D"}, 0.02)
|
||||
print(heartbeat._process.pid, flush=True)
|
||||
sys.stdin.read()
|
||||
"""
|
||||
with zmq.Context() as context, context.socket(zmq.ROUTER) as socket:
|
||||
port = socket.bind_to_random_port("tcp://127.0.0.1")
|
||||
owner = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
owner_code,
|
||||
moriio_heartbeat.__file__,
|
||||
f"tcp://127.0.0.1:{port}",
|
||||
],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
child_pid = None
|
||||
child_exited = False
|
||||
try:
|
||||
assert socket.poll(5000), "Discovery did not register"
|
||||
assert owner.stdout is not None
|
||||
child_pid = int(owner.stdout.readline())
|
||||
owner.kill()
|
||||
owner.wait(timeout=5)
|
||||
stat = Path(f"/proc/{child_pid}/stat")
|
||||
deadline = time.monotonic() + 5
|
||||
while stat.exists():
|
||||
# A terminated child may await reaping by the container's init.
|
||||
try:
|
||||
if stat.read_text().split(") ")[1].startswith("Z "):
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
assert time.monotonic() < deadline, "Orphan heartbeat survived worker"
|
||||
time.sleep(0.01)
|
||||
child_exited = True
|
||||
finally:
|
||||
if owner.poll() is None:
|
||||
owner.kill()
|
||||
owner.communicate(timeout=5)
|
||||
if child_pid is not None and not child_exited:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.kill(child_pid, 9)
|
||||
|
||||
|
||||
def test_discovery_heartbeat_recovers_after_router_outage(capfd):
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_heartbeat import (
|
||||
MoRIIOHeartbeat,
|
||||
)
|
||||
|
||||
payload = {"type": "P", "http_address": "127.0.0.1:8000"}
|
||||
with zmq.Context() as context:
|
||||
with context.socket(zmq.ROUTER) as socket:
|
||||
port = socket.bind_to_random_port("tcp://127.0.0.1")
|
||||
endpoint = f"tcp://127.0.0.1:{port}"
|
||||
heartbeat = MoRIIOHeartbeat(endpoint, payload, 0.001, max_retries=1)
|
||||
try:
|
||||
assert socket.poll(5000), "Discovery did not register"
|
||||
assert msgpack.unpackb(socket.recv_multipart()[1]) == payload
|
||||
except BaseException:
|
||||
heartbeat.shutdown()
|
||||
raise
|
||||
try:
|
||||
# Fill the real DEALER queue while discovery is unavailable.
|
||||
deadline = time.monotonic() + 10
|
||||
errors = ""
|
||||
while "heartbeat send failed" not in errors:
|
||||
errors += capfd.readouterr().err
|
||||
assert time.monotonic() < deadline, "No send timeout during outage"
|
||||
time.sleep(0.01)
|
||||
with context.socket(zmq.ROUTER) as socket:
|
||||
socket.bind(endpoint)
|
||||
assert socket.poll(5000), "Discovery did not recover after outage"
|
||||
assert msgpack.unpackb(socket.recv_multipart()[1]) == payload
|
||||
assert heartbeat._process.poll() is None
|
||||
finally:
|
||||
heartbeat.shutdown()
|
||||
|
||||
@@ -269,6 +269,34 @@ def test_worker_get_finished_counts_structured_release_fan_in():
|
||||
assert worker._completed_consumer_notifications == {"tx-fanin"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_kind", ["killed", "eof"])
|
||||
def test_worker_reports_unexpected_heartbeat_exit(exit_kind):
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_heartbeat import (
|
||||
MoRIIOHeartbeat,
|
||||
)
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker.is_producer = True
|
||||
worker.mode = MoRIIOMode.READ
|
||||
worker.moriio_wrapper = SimpleNamespace(
|
||||
pop_finished_req_ids=lambda: [], shutdown=lambda: None
|
||||
)
|
||||
worker._pending_unmapped_acks = []
|
||||
worker._heartbeat = MoRIIOHeartbeat("tcp://127.0.0.1:1", {"type": "P"}, 0.02)
|
||||
process = worker._heartbeat._process
|
||||
try:
|
||||
assert worker.get_finished() == (set(), set())
|
||||
if exit_kind == "killed":
|
||||
process.kill()
|
||||
else:
|
||||
process.stdin.close()
|
||||
returncode = process.wait(timeout=5)
|
||||
with pytest.raises(RuntimeError, match=f"heartbeat.*{returncode}"):
|
||||
worker.get_finished()
|
||||
finally:
|
||||
worker.shutdown()
|
||||
|
||||
|
||||
def test_read_completion_sends_structured_release_with_consumer_tp_size():
|
||||
class DoneStatus:
|
||||
def Succeeded(self):
|
||||
|
||||
@@ -202,6 +202,20 @@ def mc() -> MultiConnector:
|
||||
return mc
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chosen", [0, 1])
|
||||
def test_loaded_groups_follow_the_connector_serving_the_request(mc, chosen):
|
||||
request = MagicMock(request_id="request")
|
||||
for i, connector in enumerate(mc._connectors):
|
||||
connector.get_num_new_matched_tokens.return_value = (
|
||||
(16, True) if i == chosen else (0, False)
|
||||
)
|
||||
connector.get_loaded_kv_cache_group_ids.return_value = (i,)
|
||||
|
||||
assert mc.get_num_new_matched_tokens(request, 0) == (16, True)
|
||||
assert mc.get_loaded_kv_cache_group_ids(request) == (chosen,)
|
||||
mc._connectors[1 - chosen].get_loaded_kv_cache_group_ids.assert_not_called()
|
||||
|
||||
|
||||
def test_multi_connector_mem_pool_context_none(mc: MultiConnector):
|
||||
assert mc.get_mem_pool_context() is None
|
||||
|
||||
|
||||
@@ -1522,34 +1522,6 @@ def _make_fake_kv_cache_manager():
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_zeroing_block_ids_cover_only_loaded_attention_blocks():
|
||||
"""Only zero-recorded (attention) groups contribute, sliced to the
|
||||
externally-loaded token range; Mamba state blocks are never zeroed."""
|
||||
manager = _make_fake_kv_cache_manager()
|
||||
|
||||
# Tokens [0, 16) are locally cached; the load covers tokens [16, 56).
|
||||
assert manager.get_zeroing_block_ids_in_range("req-1", 16, 56) == [11, 12, 13]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_scheduler_filters_connector_loaded_blocks_from_zeroing():
|
||||
"""Blocks that will be loaded by the connector must not be zeroed."""
|
||||
from vllm.v1.core.sched.scheduler import Scheduler
|
||||
|
||||
class FakeKVCacheManager:
|
||||
def take_new_block_ids(self):
|
||||
return [9, 10, 11, 12]
|
||||
|
||||
scheduler = object.__new__(Scheduler)
|
||||
scheduler.needs_kv_cache_zeroing = True
|
||||
scheduler.kv_cache_manager = FakeKVCacheManager()
|
||||
scheduler._skip_zero_block_ids = {10, 12}
|
||||
|
||||
assert scheduler._get_new_block_ids_to_zero() == [9, 11]
|
||||
assert not scheduler._skip_zero_block_ids
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_failed_load_rezeroes_unwritten_skipped_blocks():
|
||||
"""A failed async load leaves zeroing-skipped blocks unwritten beyond
|
||||
@@ -1575,7 +1547,6 @@ def test_failed_load_rezeroes_unwritten_skipped_blocks():
|
||||
|
||||
# Attention blocks covering tokens >= 48 are re-recorded for zeroing
|
||||
# and flow into the next step's zero list; Mamba blocks are not.
|
||||
scheduler._skip_zero_block_ids = set()
|
||||
assert scheduler._get_new_block_ids_to_zero() == [13, 14, 15]
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from unittest.mock import patch
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from pydantic import TypeAdapter, ValidationError
|
||||
|
||||
from tests.utils import large_gpu_mark
|
||||
from tests.v1.sample.utils import (
|
||||
@@ -20,7 +21,7 @@ from tests.v1.sample.utils import (
|
||||
compute_correct_cumulative_logprob,
|
||||
get_test_batch,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm import SamplingParams, TokensPrompt
|
||||
from vllm.config.model import LogprobsMode
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
@@ -88,6 +89,7 @@ def hf_model(hf_runner) -> Generator[HfRunner, None, None]:
|
||||
def _model_config(vocab_size: int = 10, max_logprobs: int = 20):
|
||||
return SimpleNamespace(
|
||||
max_logprobs=max_logprobs,
|
||||
max_model_len=16,
|
||||
logits_processors=None,
|
||||
is_diffusion=False,
|
||||
get_vocab_size=lambda: vocab_size,
|
||||
@@ -443,24 +445,58 @@ def test_logprob_token_ids_validate_vocab_bounds_invalid(token_ids: list[int]):
|
||||
)
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_bounded_by_max_logprobs():
|
||||
"""The candidate count is bounded by max_logprobs."""
|
||||
def test_prompt_logprob_token_ids_validation():
|
||||
"""Rows may be ragged (-1 padded); the width is bounded by max_logprobs."""
|
||||
model_config = _model_config(vocab_size=100, max_logprobs=4)
|
||||
|
||||
def verify(**kwargs):
|
||||
SamplingParams(**kwargs).verify(
|
||||
params = SamplingParams(**kwargs)
|
||||
params.verify(
|
||||
model_config,
|
||||
speculative_config=None,
|
||||
structured_outputs_config=None,
|
||||
tokenizer=None,
|
||||
)
|
||||
return params.prompt_logprob_token_ids
|
||||
|
||||
verify(prompt_logprob_token_ids=[1, 2, 3, 4])
|
||||
assert verify(prompt_logprob_token_ids=[[], [1], [4, 3, 2, 1]]).tolist() == [
|
||||
[-1] * 4,
|
||||
[1, -1, -1, -1],
|
||||
[4, 3, 2, 1],
|
||||
]
|
||||
# Any integer layout is normalized to what the worker uploads:
|
||||
# C-contiguous native int32.
|
||||
odd = np.asfortranarray(np.array([[1, 2], [3, -1]], dtype=">i8"))
|
||||
ids = verify(prompt_logprob_token_ids=odd)
|
||||
assert ids.dtype == np.int32 and ids.flags.c_contiguous
|
||||
assert ids.tolist() == [[1, 2], [3, -1]]
|
||||
# The pydantic path (token-in/token-out API, /docs) takes strict integer lists.
|
||||
adapter = TypeAdapter(SamplingParams)
|
||||
for bad in ("[[1.5]]", '[["3"]]', "[[true]]", "[1, 2]"):
|
||||
with pytest.raises(ValidationError):
|
||||
adapter.validate_json(f'{{"prompt_logprob_token_ids": {bad}}}')
|
||||
|
||||
with pytest.raises(VLLMValidationError, match=r"shape \[num_rows, num_ids\]"):
|
||||
verify(prompt_logprob_token_ids=np.array([1, 2]))
|
||||
with pytest.raises(VLLMValidationError, match=r"shape \[num_rows, num_ids\]"):
|
||||
verify(prompt_logprob_token_ids=[1, 2])
|
||||
for bad_ids in ([[None]], [[2**63]], [[[1]]], [[[1], 2]]):
|
||||
with pytest.raises(VLLMValidationError, match="integer token ids"):
|
||||
verify(prompt_logprob_token_ids=bad_ids)
|
||||
with pytest.raises(VLLMValidationError, match="out-of-vocab"):
|
||||
verify(prompt_logprob_token_ids=np.array([[2**64 - 1]], dtype=np.uint64))
|
||||
# The error names the value to raise max_logprobs to.
|
||||
with pytest.raises(VLLMValidationError, match=r"max_logprobs.*at least 5"):
|
||||
verify(prompt_logprob_token_ids=[1, 2, 3, 4, 5])
|
||||
|
||||
verify(prompt_logprob_token_ids=[[1], [1, 2, 3, 4, 5]])
|
||||
with pytest.raises(VLLMValidationError, match="out-of-vocab"):
|
||||
verify(prompt_logprob_token_ids=[[1], [100]])
|
||||
with pytest.raises(VLLMValidationError, match="out-of-vocab"):
|
||||
verify(prompt_logprob_token_ids=[[1], [-2]])
|
||||
with pytest.raises(VLLMValidationError, match="non-empty"):
|
||||
verify(prompt_logprob_token_ids=[[], []])
|
||||
# Rows are bounded by max_model_len before the table is padded.
|
||||
with pytest.raises(VLLMValidationError, match="at most 15 scored rows"):
|
||||
verify(prompt_logprob_token_ids=[[]] * 15 + [[1]])
|
||||
# prompt_logprob_start alone is a caller mistake, not a silent no-op.
|
||||
with pytest.raises(VLLMValidationError, match="requires prompt_logprob_token_ids"):
|
||||
verify(prompt_logprob_start=3)
|
||||
@@ -483,7 +519,7 @@ def test_prompt_logprob_token_ids_require_v2_model_runner():
|
||||
tokenizer=None,
|
||||
validate_logits_processors_params=lambda params: None,
|
||||
)
|
||||
params = SamplingParams(prompt_logprob_token_ids=[1, 2])
|
||||
params = SamplingParams(prompt_logprob_token_ids=[[1, 2]])
|
||||
with patch.object(SamplingParams, "verify"):
|
||||
with pytest.raises(VLLMValidationError, match="V2 model runner"):
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
@@ -1369,7 +1405,7 @@ def test_prompt_logprobs_with_chunking_and_preemption():
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
"""Fixed-ID scores stay row-aligned across chunked prefill and preemption."""
|
||||
"""Per-row scores stay row-aligned across chunked prefill and preemption."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
|
||||
prompts = [
|
||||
@@ -1380,14 +1416,9 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
] + [f"Tell me about the number {i}: " for i in range(32)]
|
||||
|
||||
start = 2
|
||||
candidate_ids = [10, 100, 1000, 10000]
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=40,
|
||||
min_tokens=20,
|
||||
prompt_logprob_token_ids=candidate_ids,
|
||||
prompt_logprob_start=start,
|
||||
)
|
||||
|
||||
def candidate_ids(j):
|
||||
return [10 + j, 100 + j, 1000 + j, 10000 + j]
|
||||
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
@@ -1398,15 +1429,38 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
disable_log_stats=False,
|
||||
gpu_memory_utilization=0.25,
|
||||
) as vllm_model:
|
||||
tokenizer = vllm_model.llm.get_tokenizer()
|
||||
token_prompts = [
|
||||
TokensPrompt(prompt_token_ids=tokenizer(p).input_ids) for p in prompts
|
||||
]
|
||||
|
||||
def make_params(row_ids):
|
||||
return [
|
||||
SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=40,
|
||||
min_tokens=20,
|
||||
prompt_logprob_token_ids=[
|
||||
row_ids(j)
|
||||
for j in range(len(p["prompt_token_ids"]) - 1 - start)
|
||||
],
|
||||
prompt_logprob_start=start,
|
||||
)
|
||||
for p in token_prompts
|
||||
]
|
||||
|
||||
metrics_before = vllm_model.llm.get_metrics()
|
||||
outputs = vllm_model.llm.generate(prompts, sampling_params)
|
||||
full_params = make_params(candidate_ids)
|
||||
for params in full_params: # the array form, as a top-k tensor would be
|
||||
params.prompt_logprob_token_ids = np.array(params.prompt_logprob_token_ids)
|
||||
outputs = vllm_model.llm.generate(token_prompts, full_params)
|
||||
|
||||
for i, output in enumerate(outputs):
|
||||
scores = output.prompt_token_id_logprobs
|
||||
assert scores is not None, f"Output {i} missing fixed-ID scores"
|
||||
assert scores is not None, f"Output {i} missing per-row scores"
|
||||
expected_shape = (
|
||||
len(output.prompt_token_ids) - 1 - start,
|
||||
len(candidate_ids),
|
||||
4,
|
||||
)
|
||||
assert scores.shape == expected_shape, (
|
||||
f"Output {i} scored {scores.shape}, expected {expected_shape}"
|
||||
@@ -1414,6 +1468,23 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
assert math.isfinite(float(scores.min()))
|
||||
assert float(scores.max()) <= 1e-3, "logprobs must be <= 0"
|
||||
|
||||
# Ragged rows: each row keeps a prefix of the candidates and must
|
||||
# reproduce that prefix of the full scores, with -inf padding.
|
||||
ragged_params = make_params(lambda j: candidate_ids(j)[: 1 + j % 4])
|
||||
ragged_outputs = vllm_model.llm.generate(token_prompts, ragged_params)
|
||||
for output, ragged_output in zip(outputs, ragged_outputs):
|
||||
expected = np.full_like(output.prompt_token_id_logprobs, -np.inf)
|
||||
for j in range(len(expected)):
|
||||
n = 1 + j % 4
|
||||
expected[j, :n] = output.prompt_token_id_logprobs[j, :n]
|
||||
np.testing.assert_allclose(
|
||||
ragged_output.prompt_token_id_logprobs, expected, atol=1e-2
|
||||
)
|
||||
|
||||
# The row count is checked against the prompt at admission.
|
||||
with pytest.raises(VLLMValidationError, match="scored rows"):
|
||||
vllm_model.llm.generate(token_prompts[0], ragged_params[1])
|
||||
|
||||
metrics_after = vllm_model.llm.get_metrics()
|
||||
preemptions_before = next(
|
||||
(m.value for m in metrics_before if m.name == "vllm:num_preemptions"), 0
|
||||
@@ -1429,31 +1500,32 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
# unchunked, unpreempted run of the same requests. Batch composition moves
|
||||
# bf16 tail logprobs by a few percent; a misaligned row differs by nats.
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
max_model_len=512,
|
||||
max_logprobs=64,
|
||||
gpu_memory_utilization=0.25,
|
||||
"Qwen/Qwen3-0.6B", max_model_len=512, gpu_memory_utilization=0.25
|
||||
) as reference:
|
||||
reference_outputs = reference.llm.generate(prompts, sampling_params)
|
||||
own_ids = [list(dict.fromkeys(o.prompt_token_ids)) for o in reference_outputs]
|
||||
reference_outputs = reference.llm.generate(token_prompts, full_params)
|
||||
self_scored = reference.llm.generate(
|
||||
prompts,
|
||||
token_prompts,
|
||||
[
|
||||
SamplingParams(
|
||||
max_tokens=1, prompt_logprobs=0, prompt_logprob_token_ids=ids
|
||||
max_tokens=1,
|
||||
prompt_logprobs=0,
|
||||
prompt_logprob_token_ids=[[t] for t in p["prompt_token_ids"][1:]],
|
||||
)
|
||||
for ids in own_ids
|
||||
for p in token_prompts
|
||||
],
|
||||
)
|
||||
for output, ref in zip(outputs, reference_outputs):
|
||||
np.testing.assert_allclose(
|
||||
output.prompt_token_id_logprobs, ref.prompt_token_id_logprobs, rtol=0.1
|
||||
output.prompt_token_id_logprobs,
|
||||
ref.prompt_token_id_logprobs,
|
||||
rtol=0.1,
|
||||
atol=0.2,
|
||||
)
|
||||
for output, ids in zip(self_scored, own_ids):
|
||||
scores = output.prompt_token_id_logprobs
|
||||
for output in self_scored:
|
||||
scores = output.prompt_token_id_logprobs[:, 0]
|
||||
for row, target in enumerate(output.prompt_token_ids[1:]):
|
||||
expected = output.prompt_logprobs[row + 1][target].logprob
|
||||
assert scores[row, ids.index(target)] == pytest.approx(expected, abs=1e-3)
|
||||
assert scores[row] == pytest.approx(expected, abs=1e-3)
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_drop_partially_scored_prefills(monkeypatch):
|
||||
@@ -1465,13 +1537,7 @@ def test_prompt_logprob_token_ids_drop_partially_scored_prefills(monkeypatch):
|
||||
"""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
|
||||
prompt = "The capital of France is Paris. " * 20
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=1,
|
||||
prompt_logprob_token_ids=[10, 100, 1000],
|
||||
skip_reading_prefix_cache=False,
|
||||
)
|
||||
text = "The capital of France is Paris. " * 20
|
||||
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
@@ -1479,6 +1545,15 @@ def test_prompt_logprob_token_ids_drop_partially_scored_prefills(monkeypatch):
|
||||
enable_prefix_caching=True,
|
||||
gpu_memory_utilization=0.25,
|
||||
) as vllm_model:
|
||||
token_ids = vllm_model.llm.get_tokenizer()(text).input_ids
|
||||
prompt = TokensPrompt(prompt_token_ids=token_ids)
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=1,
|
||||
prompt_logprob_token_ids=np.tile([10, 100, 1000], (len(token_ids) - 1, 1)),
|
||||
skip_reading_prefix_cache=False,
|
||||
)
|
||||
|
||||
first = vllm_model.llm.generate([prompt], sampling_params)[0]
|
||||
assert first.prompt_token_id_logprobs is not None
|
||||
assert math.isfinite(float(first.prompt_token_id_logprobs.min()))
|
||||
|
||||
@@ -42,7 +42,9 @@ def test_sampling_params_trace_field_rejects_empty_list():
|
||||
|
||||
|
||||
def test_sampling_params_trace_field_rejects_prompt_scoring():
|
||||
params = SamplingParams(trace_decode_token_ids=[1], prompt_logprob_token_ids=[2, 3])
|
||||
params = SamplingParams(
|
||||
trace_decode_token_ids=[1], prompt_logprob_token_ids=[[2, 3]]
|
||||
)
|
||||
with pytest.raises(ValueError, match="prompt_logprob_token_ids"):
|
||||
params._validate_trace_replay(
|
||||
_make_model_config(vocab_size=100), speculative_config=None
|
||||
|
||||
@@ -39,6 +39,7 @@ def _make_fake_speculator(
|
||||
and a draft model.
|
||||
"""
|
||||
fake_input_buffers = SimpleNamespace(
|
||||
positions=torch.arange(max_num_tokens, dtype=torch.int64),
|
||||
query_start_loc=torch.zeros(max_num_reqs + 1, dtype=torch.int32),
|
||||
seq_lens=torch.zeros(max_num_reqs, dtype=torch.int32),
|
||||
dcp_local_seq_lens=torch.zeros(max_num_reqs, dtype=torch.int32),
|
||||
@@ -113,6 +114,7 @@ def test_build_draft_attn_metadata_sets_seq_lens_cpu_upper_bound():
|
||||
|
||||
captured = _run_build(fake, num_reqs=3, num_reqs_padded=4, base=base, step=2)
|
||||
|
||||
assert torch.equal(captured["positions"], fake.input_buffers.positions[:4])
|
||||
bound = captured["seq_lens_cpu_upper_bound"]
|
||||
assert isinstance(bound, torch.Tensor), (
|
||||
"seq_lens_cpu_upper_bound must be a tensor, not None"
|
||||
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from vllm.engine.protocol import StreamingInput
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.outputs import STREAM_FINISHED, RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.engine.output_processor import RequestOutputCollector
|
||||
@@ -170,3 +170,31 @@ async def test_generate_with_async_generator():
|
||||
assert outputs[2].finished is True
|
||||
# Both inputs were processed
|
||||
assert inputs_received == ["Hello", " world"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_input_stream_finishes_without_engine_request():
|
||||
llm = AsyncLLM.__new__(AsyncLLM)
|
||||
llm._validate_streaming_input_sampling_params = MagicMock()
|
||||
llm.get_supported_tasks = AsyncMock(return_value=("generate",))
|
||||
llm._run_output_handler = MagicMock()
|
||||
llm._add_request = AsyncMock()
|
||||
|
||||
final_req = MagicMock()
|
||||
final_req.request_id = "request-int"
|
||||
llm.input_processor = MagicMock()
|
||||
llm.input_processor.process_inputs.return_value = final_req
|
||||
|
||||
async def empty_stream():
|
||||
return
|
||||
yield # pragma: no cover
|
||||
|
||||
queue = await llm._add_streaming_input_request(
|
||||
"request", empty_stream(), SamplingParams(max_tokens=4)
|
||||
)
|
||||
task = queue._input_stream_task
|
||||
assert task is not None
|
||||
await task
|
||||
|
||||
assert queue.get_nowait() is STREAM_FINISHED
|
||||
llm._add_request.assert_not_awaited()
|
||||
|
||||
@@ -85,6 +85,7 @@ def test_pcp_draft_metadata_keeps_graph_padding_in_decode(cg_mode):
|
||||
speculator.max_model_len = speculator.draft_max_seq_len = 32
|
||||
speculator.draft_is_prefilling = torch.zeros(4, dtype=torch.bool)
|
||||
speculator.input_buffers = SimpleNamespace(
|
||||
positions=torch.arange(4, dtype=torch.int64),
|
||||
query_start_loc=torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([11, 21, 0, 0], dtype=torch.int32),
|
||||
)
|
||||
|
||||
@@ -137,6 +137,52 @@ def test_finished_request_releases_unscored_doc_use():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_release_queries_is_targeted_and_idempotent():
|
||||
runner = LateInteractionRunner()
|
||||
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
|
||||
|
||||
for query_key in ("query-release", "query-keep"):
|
||||
query_params = _make_pooling_params(
|
||||
build_late_interaction_query_params(query_key=query_key, query_uses=1)
|
||||
)
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[query_params],
|
||||
req_ids=[f"{query_key}-req"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
released_doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key="query-release")
|
||||
)
|
||||
kept_doc_params = _make_pooling_params(
|
||||
build_late_interaction_doc_params(query_key="query-keep")
|
||||
)
|
||||
runner.register_request("released-doc", released_doc_params)
|
||||
runner.register_request("kept-doc", kept_doc_params)
|
||||
|
||||
runner.release_queries(["query-release"])
|
||||
runner.release_queries(["query-release"])
|
||||
|
||||
with pytest.raises(ValueError, match="query cache miss"):
|
||||
runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[released_doc_params],
|
||||
req_ids=["released-doc"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
|
||||
kept_output = runner.postprocess_pooler_output(
|
||||
raw_pooler_output=[query_emb],
|
||||
pooling_params=[kept_doc_params],
|
||||
req_ids=["kept-doc"],
|
||||
finished_mask=[True],
|
||||
)
|
||||
assert isinstance(kept_output, list)
|
||||
assert kept_output[0] is not None
|
||||
|
||||
|
||||
def test_invalid_query_uses_raises():
|
||||
runner = LateInteractionRunner()
|
||||
bad_meta = LateInteractionParams(
|
||||
|
||||
Reference in New Issue
Block a user