[Mini-VLLM] Cut dead subsystems across serving, connectors, parsers
- Remove P/D transfer connectors: nixl, nixl_chat, mooncake x2, hf3fs, moriio, hisparse, example and hidden-states connectors - Reduce weight_transfer to the base API used by model loading - Remove kv_offload tiering, simple_kv_offload, ec cpu/example, snapshot command, engine snapshot server - Remove transformers model fallback, dsv4 tokenizers, dead platforms cpu/tpu/xpu, flashmla third_party, dsa, megamoe/flydsl, dead attn ops, dead layers (short_conv, fused_embed_norm, indexer_topk, relu2 gemma_ar, lightning_attn, minimax_rms_norm), gemm_rs_ar - Keep MoE LoRA op (imported eagerly by punica_gpu); drop fp8 variant - Rebuild parser hubs around Qwen3 adapters only (36 dead adapters) - Remove dead tests with the code they covered Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -24,12 +24,7 @@ from vllm.distributed.aux_output_connector.connector import (
|
||||
AuxRequestOutput,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.metrics import ECConnectorStats
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.connector import (
|
||||
HiSparseConnector,
|
||||
HiSparseConnectorScheduler,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalKwargsItem,
|
||||
@@ -49,7 +44,6 @@ from vllm.v1.core.single_type_kv_cache_manager import register_all_kvcache_specs
|
||||
from vllm.v1.engine import FinishReason
|
||||
from vllm.v1.engine.core import EngineCore
|
||||
from vllm.v1.executor.uniproc_executor import UniProcExecutor
|
||||
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
@@ -219,30 +213,6 @@ def test_max_num_active_seqs_caps_admission():
|
||||
assert scheduler.max_num_running_reqs == 16
|
||||
|
||||
|
||||
def _bind_hisparse_connector(scheduler):
|
||||
connector = object.__new__(HiSparseConnector)
|
||||
connector.connector_scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
from tests.v1.core.test_prefix_caching import make_hisparse_kv_cache_manager
|
||||
|
||||
coordinator = get_hisparse_coordinator(make_hisparse_kv_cache_manager(16, 16))
|
||||
connector.connector_scheduler.bind_coordinator(coordinator)
|
||||
composite = object.__new__(MultiConnector)
|
||||
composite._connectors = (connector,)
|
||||
scheduler.connector = composite
|
||||
return coordinator
|
||||
|
||||
|
||||
def test_pending_hisparse_spill_keeps_scheduler_alive():
|
||||
"""A final host spill must complete after the last request finishes."""
|
||||
scheduler = create_scheduler()
|
||||
coordinator = _bind_hisparse_connector(scheduler)
|
||||
pending = coordinator.pending_spills
|
||||
pending[0] = Mock()
|
||||
assert scheduler.has_requests()
|
||||
pending.clear()
|
||||
assert not scheduler.has_requests()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"enable_prefix_caching, prompt_logprobs",
|
||||
[
|
||||
@@ -1776,45 +1746,6 @@ def test_preempt_during_execution():
|
||||
assert requests[1].output_token_ids[0] == 42
|
||||
|
||||
|
||||
def test_pending_hisparse_reclamation_defers_preemption(monkeypatch):
|
||||
"""Pending reclamation must stall rather than preempt its owning request."""
|
||||
scheduler = create_scheduler(enable_prefix_caching=False)
|
||||
request = create_requests(num_requests=1, num_tokens=16, block_size=16)[0]
|
||||
scheduler.add_request(request)
|
||||
scheduler_output = scheduler.schedule()
|
||||
scheduler.update_from_output(
|
||||
scheduler_output,
|
||||
ModelRunnerOutput(
|
||||
req_ids=[request.request_id],
|
||||
req_id_to_index={request.request_id: 0},
|
||||
sampled_token_ids=[[0]],
|
||||
logprobs=None,
|
||||
prompt_logprobs_dict={},
|
||||
pooler_output=[],
|
||||
),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
scheduler.kv_cache_manager, "allocate_slots", Mock(return_value=None)
|
||||
)
|
||||
coordinator = _bind_hisparse_connector(scheduler)
|
||||
monkeypatch.setattr(
|
||||
scheduler.connector, "build_connector_meta", Mock(return_value=None)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
coordinator,
|
||||
"has_pending_reclamation",
|
||||
Mock(return_value=True),
|
||||
)
|
||||
|
||||
deferred_output = scheduler.schedule()
|
||||
|
||||
assert not deferred_output.num_scheduled_tokens
|
||||
assert scheduler.running == [request]
|
||||
assert request.status == RequestStatus.RUNNING
|
||||
assert request.num_preemptions == 0
|
||||
|
||||
|
||||
def test_prefix_cache_query_not_inflated_by_connector_defer():
|
||||
"""The GPU prefix-cache query is recorded at admission, so a request the
|
||||
connector defers several times is counted once, not once per retry."""
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,283 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for resource management in hf3fs_client.py: constructor failure cleanup
|
||||
and idempotent close(). Tests use mock to replace real I/O operations
|
||||
(hf3fs_fuse.io, SharedMemory, os, CUDA).
|
||||
Requires hf3fs_fuse.io to be installed; skipped otherwise.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
HF3FS_AVAILABLE = True
|
||||
try:
|
||||
from hf3fs_fuse.io import ( # noqa: F401
|
||||
deregister_fd,
|
||||
extract_mount_point,
|
||||
make_ioring,
|
||||
make_iovec,
|
||||
register_fd,
|
||||
)
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hf3fs.hf3fs_client import (
|
||||
Hf3fsClient,
|
||||
)
|
||||
except Exception:
|
||||
HF3FS_AVAILABLE = False
|
||||
|
||||
requires_hf3fs = pytest.mark.skipif(
|
||||
not HF3FS_AVAILABLE,
|
||||
reason="hf3fs_fuse.io is not available on this machine",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _FakeShm:
|
||||
"""Shared-memory stub matching the multiprocessing.shared_memory.SharedMemory
|
||||
interface used by Hf3fsClient:
|
||||
|
||||
Attributes accessed by the constructor:
|
||||
.buf – memoryview / buffer-protocol object consumed by torch.frombuffer
|
||||
Methods called during normal lifetime:
|
||||
.unlink() – called right after the iovec is set up
|
||||
.close() – called in _release_resources()
|
||||
"""
|
||||
|
||||
def __init__(self, size: int = 1024):
|
||||
self._data = bytearray(size)
|
||||
self.buf = memoryview(self._data)
|
||||
self.closed = False
|
||||
self.close_call_count = 0
|
||||
self.unlink_call_count = 0
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
self.close_call_count += 1
|
||||
|
||||
def unlink(self):
|
||||
self.unlink_call_count += 1
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestHf3fsClientResourceManagement
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@requires_hf3fs
|
||||
class TestHf3fsClientResourceManagement:
|
||||
"""Tests for constructor failure cleanup and idempotent close()."""
|
||||
|
||||
_MOD = "vllm.distributed.kv_transfer.kv_connector.v1.hf3fs.hf3fs_client"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helper: build a minimal Hf3fsClient bypassing all real I/O so that
|
||||
# we can fully control its internal state.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _make_client(self, tmp_path):
|
||||
"""Return a fully-mocked Hf3fsClient with controllable internals."""
|
||||
fake_shm_r = _FakeShm()
|
||||
fake_shm_w = _FakeShm()
|
||||
|
||||
patcher_list: list[Any] = [
|
||||
patch(f"{self._MOD}.HF3FS_AVAILABLE", True),
|
||||
patch(f"{self._MOD}.register_fd"),
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch(f"{self._MOD}.extract_mount_point", return_value="/mnt/hf3fs"),
|
||||
patch(f"{self._MOD}.make_ioring", return_value=MagicMock()),
|
||||
patch(f"{self._MOD}.make_iovec", return_value=MagicMock()),
|
||||
patch(
|
||||
"multiprocessing.shared_memory.SharedMemory",
|
||||
side_effect=[fake_shm_r, fake_shm_w],
|
||||
),
|
||||
patch("os.open", return_value=99),
|
||||
patch("os.ftruncate"),
|
||||
patch("os.close"),
|
||||
patch("os.fsync"),
|
||||
patch("torch.cuda.Stream", return_value=MagicMock()),
|
||||
patch("torch.frombuffer", return_value=MagicMock()),
|
||||
patch("torch.empty", return_value=MagicMock()),
|
||||
]
|
||||
for p in patcher_list:
|
||||
p.start()
|
||||
|
||||
try:
|
||||
client = Hf3fsClient(
|
||||
path=str(tmp_path / "test.bin"),
|
||||
size=1024,
|
||||
bytes_per_page=256,
|
||||
entries=4,
|
||||
)
|
||||
finally:
|
||||
for p in patcher_list:
|
||||
p.stop()
|
||||
|
||||
# Manually point internal handles to our controllable fakes so that
|
||||
# assertions after close() can inspect them directly.
|
||||
client.shm_r = fake_shm_r
|
||||
client.shm_w = fake_shm_w
|
||||
client.file = 99
|
||||
return client, fake_shm_r, fake_shm_w
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# close() idempotency
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_close_idempotent_and_handles_cleared(self, tmp_path):
|
||||
"""Multiple close() calls must not raise; deregister_fd called exactly
|
||||
once, all handles set to None, shm.close() invoked."""
|
||||
client, shm_r, shm_w = self._make_client(tmp_path)
|
||||
|
||||
with (
|
||||
patch(f"{self._MOD}.deregister_fd") as mock_dereg,
|
||||
patch("os.close"),
|
||||
):
|
||||
client.close() # first close
|
||||
client.close() # second close — must be no-op
|
||||
client.close() # third close — must be no-op
|
||||
|
||||
assert client._closed is True
|
||||
assert mock_dereg.call_count == 1, (
|
||||
f"deregister_fd called {mock_dereg.call_count} times; expected 1"
|
||||
)
|
||||
for attr in ("iov_r", "iov_w", "ior_r", "ior_w", "shm_r", "shm_w", "file"):
|
||||
assert getattr(client, attr) is None, f"{attr} should be None after close()"
|
||||
assert shm_r.closed is True
|
||||
assert shm_w.closed is True
|
||||
|
||||
def test_flush_after_close_is_noop(self, tmp_path):
|
||||
"""flush() after close() must silently do nothing (no fsync call)."""
|
||||
client, _, _ = self._make_client(tmp_path)
|
||||
|
||||
with (
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch("os.close"),
|
||||
patch("os.fsync") as mock_fsync,
|
||||
):
|
||||
client.close()
|
||||
client.flush()
|
||||
|
||||
mock_fsync.assert_not_called()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Constructor failure leaves no leaked resources
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_constructor_failure_after_file_open_cleans_file(self, tmp_path):
|
||||
"""If the constructor raises after os.open(), the fd must be closed."""
|
||||
with (
|
||||
patch(f"{self._MOD}.HF3FS_AVAILABLE", True),
|
||||
patch(f"{self._MOD}.register_fd"),
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch(
|
||||
f"{self._MOD}.extract_mount_point",
|
||||
side_effect=RuntimeError("mount point not found"),
|
||||
),
|
||||
patch("os.open", return_value=55),
|
||||
patch("os.ftruncate"),
|
||||
patch("os.close") as mock_os_close,
|
||||
patch("torch.cuda.Stream", return_value=MagicMock()),
|
||||
pytest.raises(RuntimeError, match="mount point not found"),
|
||||
):
|
||||
Hf3fsClient(
|
||||
path=str(tmp_path / "fail.bin"),
|
||||
size=1024,
|
||||
bytes_per_page=256,
|
||||
entries=4,
|
||||
)
|
||||
|
||||
mock_os_close.assert_called_once_with(55)
|
||||
|
||||
def test_constructor_failure_after_shm_alloc_closes_shm(self, tmp_path):
|
||||
"""Constructor raises after SharedMemory creation → both shm objects closed."""
|
||||
fake_shm_r = _FakeShm()
|
||||
fake_shm_w = _FakeShm()
|
||||
|
||||
with (
|
||||
patch(f"{self._MOD}.HF3FS_AVAILABLE", True),
|
||||
patch(f"{self._MOD}.register_fd"),
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch(f"{self._MOD}.extract_mount_point", return_value="/mnt/hf3fs"),
|
||||
patch(
|
||||
"multiprocessing.shared_memory.SharedMemory",
|
||||
side_effect=[fake_shm_r, fake_shm_w],
|
||||
),
|
||||
patch("os.open", return_value=66),
|
||||
patch("os.ftruncate"),
|
||||
patch("os.close"),
|
||||
patch("torch.frombuffer", return_value=MagicMock()),
|
||||
patch("torch.empty", return_value=MagicMock()),
|
||||
patch(
|
||||
f"{self._MOD}.make_ioring",
|
||||
side_effect=RuntimeError("ioring init failed"),
|
||||
),
|
||||
patch(f"{self._MOD}.make_iovec", return_value=MagicMock()),
|
||||
patch("torch.cuda.Stream", return_value=MagicMock()),
|
||||
pytest.raises(RuntimeError, match="ioring init failed"),
|
||||
):
|
||||
Hf3fsClient(
|
||||
path=str(tmp_path / "fail2.bin"),
|
||||
size=1024,
|
||||
bytes_per_page=256,
|
||||
entries=4,
|
||||
)
|
||||
|
||||
assert fake_shm_r.closed is True, (
|
||||
"shm_r was not closed after constructor failure"
|
||||
)
|
||||
assert fake_shm_w.closed is True, (
|
||||
"shm_w was not closed after constructor failure"
|
||||
)
|
||||
|
||||
def test_constructor_failure_does_not_close_unallocated_shm(self, tmp_path):
|
||||
"""Failure before SharedMemory is created must not raise AttributeError
|
||||
or TypeError from cleanup."""
|
||||
with (
|
||||
patch(f"{self._MOD}.HF3FS_AVAILABLE", True),
|
||||
patch(f"{self._MOD}.register_fd"),
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch(
|
||||
f"{self._MOD}.extract_mount_point",
|
||||
side_effect=RuntimeError("early failure"),
|
||||
),
|
||||
patch("os.open", return_value=77),
|
||||
patch("os.ftruncate"),
|
||||
patch("os.close"),
|
||||
patch("torch.cuda.Stream", return_value=MagicMock()),
|
||||
pytest.raises(RuntimeError, match="early failure"),
|
||||
):
|
||||
Hf3fsClient(
|
||||
path=str(tmp_path / "early_fail.bin"),
|
||||
size=1024,
|
||||
bytes_per_page=256,
|
||||
entries=4,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# _release_resources on already-cleared state must be a no-op
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_release_resources_on_empty_state_is_safe(self, tmp_path):
|
||||
"""_release_resources() on a fully-cleared client must not raise."""
|
||||
client, _, _ = self._make_client(tmp_path)
|
||||
|
||||
with (
|
||||
patch(f"{self._MOD}.deregister_fd"),
|
||||
patch("os.close"),
|
||||
):
|
||||
client.close() # clears all handles
|
||||
|
||||
with (
|
||||
patch(f"{self._MOD}.deregister_fd") as mock_dereg2,
|
||||
patch("os.close") as mock_os_close2,
|
||||
):
|
||||
client._release_resources() # must not raise
|
||||
|
||||
mock_dereg2.assert_not_called()
|
||||
mock_os_close2.assert_not_called()
|
||||
@@ -1,233 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for HF3FS KV Connector high-level components:
|
||||
- TestHf3fsMockClient : file-backed mock client I/O correctness
|
||||
- TestHF3FSKVConnectorStats: metric collection, aggregation, serialisation
|
||||
"""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hf3fs.hf3fs_connector import (
|
||||
HF3FSKVConnectorStats,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hf3fs.utils.hf3fs_mock_client import (
|
||||
Hf3fsClient as MockHf3fsClient,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hf3fs_stats():
|
||||
"""Fresh HF3FSKVConnectorStats instance."""
|
||||
return HF3FSKVConnectorStats()
|
||||
|
||||
|
||||
def _make_cuda_event():
|
||||
"""Return a real CUDA event when available, otherwise a MagicMock."""
|
||||
if torch.cuda.is_available():
|
||||
return torch.cuda.Event()
|
||||
return MagicMock()
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestHf3fsMockClient
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestHf3fsMockClient:
|
||||
"""Tests for hf3fs_mock_client.Hf3fsClient (file-backend mock)."""
|
||||
|
||||
def test_init_creates_file(self, tmp_path):
|
||||
"""Initializing the client should create the backing file."""
|
||||
path = str(tmp_path / "test_file")
|
||||
client = MockHf3fsClient(path=path, size=4096, bytes_per_page=512, entries=4)
|
||||
assert os.path.exists(path), "Backing file should be created on init"
|
||||
assert os.path.getsize(path) == 4096
|
||||
client.close()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dtype, bytes_per_page",
|
||||
[
|
||||
(torch.float32, 512),
|
||||
(torch.float16, 256),
|
||||
(torch.bfloat16, 256),
|
||||
],
|
||||
ids=["float32", "float16", "bfloat16"],
|
||||
)
|
||||
def test_batch_write_and_read_dtype(self, tmp_path, dtype, bytes_per_page):
|
||||
"""Write a tensor of the given dtype and verify round-trip correctness."""
|
||||
path = str(tmp_path / f"rw_{dtype}")
|
||||
client = MockHf3fsClient(
|
||||
path=path, size=bytes_per_page * 8, bytes_per_page=bytes_per_page, entries=4
|
||||
)
|
||||
elem_size = torch.tensor([], dtype=dtype).element_size()
|
||||
numel = bytes_per_page // elem_size
|
||||
tensor_write = torch.arange(numel, dtype=dtype)
|
||||
event = _make_cuda_event()
|
||||
|
||||
results = client.batch_write([0], [tensor_write], event)
|
||||
assert results == [bytes_per_page], f"Write should succeed, got {results}"
|
||||
|
||||
tensor_read = torch.zeros(numel, dtype=dtype)
|
||||
results = client.batch_read([0], [tensor_read])
|
||||
assert results == [bytes_per_page], f"Read should succeed, got {results}"
|
||||
assert torch.equal(tensor_write, tensor_read), (
|
||||
"Read tensor should match written tensor"
|
||||
)
|
||||
client.close()
|
||||
|
||||
def test_batch_read_empty_file_returns_error(self, tmp_path):
|
||||
"""Reading out-of-bounds offset should return -1."""
|
||||
bytes_per_page = 128
|
||||
size = bytes_per_page * 4
|
||||
path = str(tmp_path / "empty_read")
|
||||
client = MockHf3fsClient(
|
||||
path=path, size=size, bytes_per_page=bytes_per_page, entries=4
|
||||
)
|
||||
numel = bytes_per_page // 4
|
||||
tensor_read = torch.zeros(numel, dtype=torch.float32)
|
||||
results = client.batch_read([size], [tensor_read]) # offset == size => OOB
|
||||
assert results[0] == -1, "Out-of-bounds read should return -1"
|
||||
client.close()
|
||||
|
||||
def test_batch_write_out_of_bounds_returns_error(self, tmp_path):
|
||||
"""Writing at an offset beyond file size should return -1."""
|
||||
bytes_per_page = 128
|
||||
size = bytes_per_page * 4
|
||||
path = str(tmp_path / "oob_write")
|
||||
client = MockHf3fsClient(
|
||||
path=path, size=size, bytes_per_page=bytes_per_page, entries=4
|
||||
)
|
||||
numel = bytes_per_page // 4
|
||||
tensor = torch.ones(numel, dtype=torch.float32)
|
||||
event = _make_cuda_event()
|
||||
results = client.batch_write([size], [tensor], event) # OOB offset
|
||||
assert results[0] == -1, "Out-of-bounds write should return -1"
|
||||
client.close()
|
||||
|
||||
def test_multiple_tensors_rw(self, tmp_path):
|
||||
"""Write multiple tensors at different offsets, then read all back."""
|
||||
bytes_per_page = 128
|
||||
n = 4
|
||||
path = str(tmp_path / "multi_rw")
|
||||
client = MockHf3fsClient(
|
||||
path=path,
|
||||
size=bytes_per_page * n * 2,
|
||||
bytes_per_page=bytes_per_page,
|
||||
entries=8,
|
||||
)
|
||||
tensors_write = [
|
||||
torch.full((bytes_per_page // 4,), float(i), dtype=torch.float32)
|
||||
for i in range(n)
|
||||
]
|
||||
offsets = [i * bytes_per_page for i in range(n)]
|
||||
event = _make_cuda_event()
|
||||
|
||||
results = client.batch_write(offsets, tensors_write, event)
|
||||
assert all(r == bytes_per_page for r in results)
|
||||
|
||||
tensors_read = [
|
||||
torch.zeros(bytes_per_page // 4, dtype=torch.float32) for _ in range(n)
|
||||
]
|
||||
results = client.batch_read(offsets, tensors_read)
|
||||
assert all(r == bytes_per_page for r in results)
|
||||
|
||||
for i, (tw, tr) in enumerate(zip(tensors_write, tensors_read)):
|
||||
assert torch.allclose(tw, tr), f"Tensor {i} mismatch after round-trip"
|
||||
client.close()
|
||||
|
||||
def test_flush_and_close_no_error(self, tmp_path):
|
||||
"""flush() and close() should not raise exceptions."""
|
||||
path = str(tmp_path / "flush_close")
|
||||
client = MockHf3fsClient(path=path, size=1024, bytes_per_page=128, entries=4)
|
||||
client.flush()
|
||||
client.close()
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestHF3FSKVConnectorStats
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestHF3FSKVConnectorStats:
|
||||
"""Tests for HF3FSKVConnectorStats metric collection and aggregation."""
|
||||
|
||||
def test_initial_is_empty(self, hf3fs_stats):
|
||||
"""Fresh stats object should report is_empty() == True."""
|
||||
assert hf3fs_stats.is_empty() is True
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"task_type, duration_key",
|
||||
[
|
||||
("Saved", "save_duration"),
|
||||
("Loaded", "load_duration"),
|
||||
],
|
||||
ids=["save", "load"],
|
||||
)
|
||||
def test_record_success_duration(self, hf3fs_stats, task_type, duration_key):
|
||||
"""Recording a successful task should update duration list and total count."""
|
||||
hf3fs_stats.record_success_task_duration(task_type, 0.5)
|
||||
assert not hf3fs_stats.is_empty()
|
||||
assert len(hf3fs_stats.data[duration_key]) == 1
|
||||
assert hf3fs_stats.data[duration_key][0] == pytest.approx(0.5)
|
||||
assert hf3fs_stats.data["num_transfer_task"] == 1
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"task_type, failed_key",
|
||||
[
|
||||
("Saved", "num_failed_save"),
|
||||
("Loaded", "num_failed_load"),
|
||||
],
|
||||
ids=["save", "load"],
|
||||
)
|
||||
def test_record_failed_task(self, hf3fs_stats, task_type, failed_key):
|
||||
"""Recording a failed task should increment the corresponding counter."""
|
||||
hf3fs_stats.record_failed_task_count(task_type)
|
||||
assert hf3fs_stats.data[failed_key] == 1
|
||||
assert hf3fs_stats.data["num_transfer_task"] == 1
|
||||
|
||||
def test_aggregate_two_stats(self):
|
||||
"""aggregate() should merge save/load duration lists and sum counters."""
|
||||
stats1 = HF3FSKVConnectorStats()
|
||||
stats1.record_success_task_duration("Saved", 0.1)
|
||||
stats1.record_success_task_duration("Loaded", 0.2)
|
||||
|
||||
stats2 = HF3FSKVConnectorStats()
|
||||
stats2.record_success_task_duration("Saved", 0.3)
|
||||
stats2.record_failed_task_count("Loaded")
|
||||
|
||||
stats1.aggregate(stats2)
|
||||
assert stats1.data["save_duration"] == pytest.approx([0.1, 0.3])
|
||||
assert stats1.data["load_duration"] == pytest.approx([0.2])
|
||||
assert stats1.data["num_failed_load"] == 1
|
||||
assert stats1.data["num_transfer_task"] == 4
|
||||
|
||||
def test_reduce_with_data(self):
|
||||
"""reduce() computes correct averages when data is present."""
|
||||
stats = HF3FSKVConnectorStats()
|
||||
stats.record_success_task_duration("Saved", 1.0)
|
||||
stats.record_success_task_duration("Saved", 3.0)
|
||||
result = stats.reduce()
|
||||
assert result["Num save task success"] == pytest.approx(2.0, rel=0.01)
|
||||
assert result["Num save task failed"] == pytest.approx(0.0, rel=0.01)
|
||||
assert result["Avg save duration (ms)"] == pytest.approx(2000.0, rel=0.01)
|
||||
# Reduced values must be plain Python scalars so CLI logging renders
|
||||
# them without numpy reprs (eg np.float64(...)).
|
||||
assert all(not isinstance(v, np.generic) for v in result.values())
|
||||
|
||||
def test_clone_and_reset(self, hf3fs_stats):
|
||||
"""clone_and_reset() returns a copy with data and resets the original."""
|
||||
hf3fs_stats.record_success_task_duration("Saved", 0.7)
|
||||
hf3fs_stats.record_success_task_duration("Loaded", 0.4)
|
||||
|
||||
clone = hf3fs_stats.clone_and_reset()
|
||||
assert clone.data["num_transfer_task"] == 2
|
||||
assert hf3fs_stats.is_empty()
|
||||
@@ -1,192 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for HF3FS metadata server data structures and allocation logic:
|
||||
- RankFileMetadata : page allocation / release primitives
|
||||
- KeyMetadata : per-key rank-page tracking and completion detection
|
||||
- GlobalMetadataState : coordinated allocation with cache-hit semantics
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hf3fs.hf3fs_metadata_server import (
|
||||
GlobalMetadataState,
|
||||
KeyMetadata,
|
||||
RankFileMetadata,
|
||||
)
|
||||
|
||||
# ===========================================================================
|
||||
# TestRankFileMetadata
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestRankFileMetadata:
|
||||
"""Unit tests for RankFileMetadata page allocation primitives."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"alloc_count, expected_pages",
|
||||
[(3, 3), (5, 0)],
|
||||
ids=["alloc_partial", "alloc_exceeds"],
|
||||
)
|
||||
def test_allocate_pages(self, alloc_count, expected_pages):
|
||||
"""allocate_pages returns correct pages or empty list when insufficient."""
|
||||
rank_meta = RankFileMetadata(rank_id=0, num_pages=3, free_pages=list(range(3)))
|
||||
pages = rank_meta.allocate_pages(alloc_count)
|
||||
assert len(pages) == expected_pages
|
||||
if expected_pages > 0:
|
||||
rank_meta.release_pages(pages)
|
||||
assert rank_meta.get_free_page_count() == 3
|
||||
|
||||
def test_release_pages_restores_count(self):
|
||||
"""Releasing allocated pages returns them to the free pool."""
|
||||
rank_meta = RankFileMetadata(rank_id=0, num_pages=4, free_pages=list(range(4)))
|
||||
pages = rank_meta.allocate_pages(2)
|
||||
assert rank_meta.get_free_page_count() == 2
|
||||
rank_meta.release_pages(pages)
|
||||
assert rank_meta.get_free_page_count() == 4
|
||||
|
||||
def test_release_pages_no_duplicates(self):
|
||||
"""Releasing the same page twice must not create duplicates."""
|
||||
rank_meta = RankFileMetadata(rank_id=0, num_pages=3, free_pages=list(range(3)))
|
||||
rank_meta.allocate_pages(1) # takes page 0
|
||||
rank_meta.release_pages([0])
|
||||
rank_meta.release_pages([0]) # second release of the same page
|
||||
assert rank_meta.get_free_page_count() == 3
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestKeyMetadata
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestKeyMetadata:
|
||||
"""Unit tests for KeyMetadata completion tracking."""
|
||||
|
||||
def test_is_complete_false_until_all_ranks(self):
|
||||
"""is_complete() returns True only when all ranks confirmed."""
|
||||
key_meta = KeyMetadata(key="k", rank_to_page={}, tp_world_size=2)
|
||||
assert key_meta.is_complete() is False
|
||||
key_meta.add_rank_page(0, 5)
|
||||
assert key_meta.is_complete() is False
|
||||
key_meta.add_rank_page(1, 10)
|
||||
assert key_meta.is_complete() is True
|
||||
|
||||
def test_get_rank_page_returns_none_for_missing_rank(self):
|
||||
"""get_rank_page() returns None when the rank has no entry."""
|
||||
key_meta = KeyMetadata(key="k", rank_to_page={0: 3}, tp_world_size=2)
|
||||
assert key_meta.get_rank_page(0) == 3
|
||||
assert key_meta.get_rank_page(1) is None
|
||||
|
||||
def test_get_all_pages(self):
|
||||
"""get_all_pages() returns all (rank, page) pairs."""
|
||||
key_meta = KeyMetadata(key="k", rank_to_page={0: 1, 1: 2}, tp_world_size=2)
|
||||
pairs = key_meta.get_all_pages()
|
||||
assert set(pairs) == {(0, 1), (1, 2)}
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestGlobalMetadataStateAllocation
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
class TestGlobalMetadataStateAllocation:
|
||||
"""Tests for GlobalMetadataState allocation and cache-hit semantics."""
|
||||
|
||||
def test_uninitialized_rank_raises_on_allocate(self):
|
||||
"""allocate_pages_for_keys raises ValueError for unknown rank."""
|
||||
state = GlobalMetadataState()
|
||||
with pytest.raises((ValueError, Exception)):
|
||||
state.allocate_pages_for_keys(99, [("key", "")])
|
||||
|
||||
def test_uninitialized_rank_raises_on_get_locations(self):
|
||||
"""get_key_locations raises ValueError for unknown rank."""
|
||||
state = GlobalMetadataState()
|
||||
with pytest.raises((ValueError, Exception)):
|
||||
state.get_key_locations(99, ["any_key"])
|
||||
|
||||
def test_basic_allocation_and_confirm(self):
|
||||
"""Allocating a page and confirming it marks the key as complete."""
|
||||
state = GlobalMetadataState()
|
||||
state.initialize_rank(0, 4)
|
||||
|
||||
results = state.allocate_pages_for_keys(0, [("K", "")])
|
||||
assert results["K"] >= 0
|
||||
|
||||
state.confirm_write_for_keys(0, [("K", results["K"])])
|
||||
assert state.batch_key_exists(["K"]) == [True]
|
||||
locations = state.get_key_locations(0, ["K"])
|
||||
assert locations == [results["K"]]
|
||||
|
||||
def test_allocate_pages_cache_hit_does_not_leak_pages(self):
|
||||
"""Cache-hit key must not consume a page from the free pool;
|
||||
the pre-allocated slot must be returned before reusing the existing page.
|
||||
"""
|
||||
state = GlobalMetadataState()
|
||||
state.initialize_rank(0, 5) # 5 free pages: [0,1,2,3,4]
|
||||
|
||||
# Simulate a key that has already been fully written and confirmed.
|
||||
state.key_metadata["K_cached"] = KeyMetadata(
|
||||
key="K_cached", rank_to_page={0: 2}, tp_world_size=1
|
||||
)
|
||||
|
||||
free_before = state.rank_metadata[0].get_free_page_count() # 5
|
||||
|
||||
results = state.allocate_pages_for_keys(0, [("K_cached", ""), ("K_new", "")])
|
||||
|
||||
free_after = state.rank_metadata[0].get_free_page_count()
|
||||
|
||||
# Cache-hit key must reuse its existing page.
|
||||
assert results["K_cached"] == 2, (
|
||||
f"Cache-hit key should reuse page 2, got {results['K_cached']}"
|
||||
)
|
||||
# New key must receive a valid page.
|
||||
assert results["K_new"] >= 0, (
|
||||
f"New key should get a valid page, got {results['K_new']}"
|
||||
)
|
||||
# Exactly one page consumed from the free pool.
|
||||
assert free_before - free_after == 1, (
|
||||
f"Expected 1 page consumed, got delta={free_before - free_after}"
|
||||
)
|
||||
|
||||
def test_allocate_pages_all_cache_hits_frees_all_slots(self):
|
||||
"""When every key in the batch is a cache hit, no pages are consumed."""
|
||||
state = GlobalMetadataState()
|
||||
state.initialize_rank(0, 5)
|
||||
|
||||
for key, page in (("K1", 0), ("K2", 1)):
|
||||
state.key_metadata[key] = KeyMetadata(
|
||||
key=key, rank_to_page={0: page}, tp_world_size=1
|
||||
)
|
||||
|
||||
free_before = state.rank_metadata[0].get_free_page_count()
|
||||
results = state.allocate_pages_for_keys(0, [("K1", ""), ("K2", "")])
|
||||
free_after = state.rank_metadata[0].get_free_page_count()
|
||||
|
||||
assert results["K1"] == 0
|
||||
assert results["K2"] == 1
|
||||
assert free_after == free_before, (
|
||||
f"All-cache-hit batch must not consume free pages; "
|
||||
f"before={free_before}, after={free_after}"
|
||||
)
|
||||
|
||||
def test_allocate_returns_minus_one_when_pool_exhausted(self):
|
||||
"""If the free pool is exhausted, all new keys receive -1."""
|
||||
state = GlobalMetadataState()
|
||||
state.initialize_rank(0, 1) # only 1 free page
|
||||
|
||||
results = state.allocate_pages_for_keys(0, [("K1", ""), ("K2", "")])
|
||||
# allocate_pages uses all-or-nothing: 2 needed but only 1 available → []
|
||||
assert all(v == -1 for v in results.values()), f"Expected all -1, got {results}"
|
||||
|
||||
def test_confirm_write_releases_pages(self):
|
||||
"""confirm_write_for_keys with pages_to_release returns them to pool."""
|
||||
state = GlobalMetadataState()
|
||||
state.initialize_rank(0, 3)
|
||||
|
||||
results = state.allocate_pages_for_keys(0, [("K", "")])
|
||||
page = results["K"]
|
||||
free_after_alloc = state.rank_metadata[0].get_free_page_count()
|
||||
|
||||
state.confirm_write_for_keys(0, [("K", page)], pages_to_release=[page])
|
||||
free_after_release = state.rank_metadata[0].get_free_page_count()
|
||||
|
||||
assert free_after_release == free_after_alloc + 1
|
||||
@@ -1,158 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.connector import (
|
||||
HiSparseConnector,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.stats import (
|
||||
HiSparseKVConnectorStats,
|
||||
)
|
||||
|
||||
|
||||
def test_is_empty_on_fresh_stats():
|
||||
stats = HiSparseKVConnectorStats()
|
||||
assert stats.is_empty()
|
||||
|
||||
|
||||
def test_record_snapshot_and_reduce():
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_snapshot(hits=7, misses=3, host_to_device_bytes=48)
|
||||
stats.record_snapshot(hits=5, misses=1, host_to_device_bytes=16)
|
||||
assert not stats.is_empty()
|
||||
|
||||
reduced = stats.reduce()
|
||||
assert reduced["HiSparse hot-buffer hits"] == 12
|
||||
assert reduced["HiSparse hot-buffer misses"] == 4
|
||||
assert reduced["HiSparse host-to-device bytes"] == 64
|
||||
|
||||
|
||||
def test_record_host_usage_reports_latest_level():
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_host_usage(usage=0.4, pending_page_transfers=2)
|
||||
stats.record_host_usage(usage=0.8, pending_page_transfers=0)
|
||||
|
||||
reduced = stats.reduce()
|
||||
assert reduced["HiSparse host KV cache usage %"] == 80.0
|
||||
|
||||
|
||||
def test_aggregate_keeps_latest_host_usage_level():
|
||||
first = HiSparseKVConnectorStats()
|
||||
first.record_host_usage(usage=0.4, pending_page_transfers=2)
|
||||
second = HiSparseKVConnectorStats()
|
||||
second.record_host_usage(usage=0.8, pending_page_transfers=0)
|
||||
second.record_host_usage(usage=0.6, pending_page_transfers=1)
|
||||
|
||||
first.aggregate(second)
|
||||
|
||||
assert first.data["host_cache_usage_perc"] == [0.4, 0.6]
|
||||
assert first.data["pending_page_transfers"] == [2, 1]
|
||||
|
||||
|
||||
def test_aggregate_extends_snapshot_deltas():
|
||||
first = HiSparseKVConnectorStats()
|
||||
first.record_snapshot(hits=7, misses=3, host_to_device_bytes=48)
|
||||
second = HiSparseKVConnectorStats()
|
||||
second.record_snapshot(hits=5, misses=1, host_to_device_bytes=16)
|
||||
|
||||
first.aggregate(second)
|
||||
|
||||
assert first.data["cache_hits"] == [7, 5]
|
||||
assert first.data["cache_misses"] == [3, 1]
|
||||
assert first.data["host_to_device_bytes"] == [48, 16]
|
||||
|
||||
|
||||
def test_aggregate_skips_empty_stats():
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_snapshot(hits=2, misses=1, host_to_device_bytes=16)
|
||||
|
||||
stats.aggregate(HiSparseKVConnectorStats())
|
||||
|
||||
assert stats.data["cache_hits"] == [2]
|
||||
|
||||
|
||||
def test_build_kv_connector_stats_round_trip():
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_snapshot(hits=12, misses=4, host_to_device_bytes=64)
|
||||
payload = stats.to_dict()
|
||||
|
||||
rebuilt = HiSparseConnector.build_kv_connector_stats(data=payload)
|
||||
|
||||
assert rebuilt is not None
|
||||
assert isinstance(rebuilt, HiSparseKVConnectorStats)
|
||||
assert rebuilt.reduce() == stats.reduce()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_metrics", [True, False])
|
||||
def test_prom_metrics_observe_host_metrics(kv_cache_metrics: bool):
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from prometheus_client import Counter, Gauge, Histogram
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.stats import (
|
||||
HiSparsePromMetrics,
|
||||
)
|
||||
from vllm.v1.metrics.stats import KVCacheEvictionEvent
|
||||
|
||||
class _FakeMetric:
|
||||
def __init__(self, **kwargs: Any):
|
||||
self.kwargs = kwargs
|
||||
self.increments: list[int | float] = []
|
||||
self.set_values: list[int | float] = []
|
||||
self.observed: list[float] = []
|
||||
|
||||
def labels(self, *labelvalues: object) -> "_FakeMetric":
|
||||
return self
|
||||
|
||||
def inc(self, value: int | float) -> None:
|
||||
self.increments.append(value)
|
||||
|
||||
def set(self, value: int | float) -> None:
|
||||
self.set_values.append(value)
|
||||
|
||||
def observe(self, value: float) -> None:
|
||||
self.observed.append(value)
|
||||
|
||||
created: dict[str, _FakeMetric] = {}
|
||||
|
||||
class _NamedFake(_FakeMetric):
|
||||
def __init__(self, **kwargs: Any):
|
||||
super().__init__(**kwargs)
|
||||
created[kwargs["name"]] = self
|
||||
|
||||
prom = HiSparsePromMetrics(
|
||||
vllm_config=SimpleNamespace(
|
||||
kv_transfer_config=None,
|
||||
observability_config=SimpleNamespace(
|
||||
kv_cache_metrics=kv_cache_metrics, custom_histogram_buckets=None
|
||||
),
|
||||
),
|
||||
metric_types={Gauge: _NamedFake, Counter: _NamedFake, Histogram: _NamedFake},
|
||||
labelnames=["model_name"],
|
||||
per_engine_labelvalues={0: ["model"]},
|
||||
)
|
||||
|
||||
stats = HiSparseKVConnectorStats()
|
||||
stats.record_snapshot(hits=3, misses=2, host_to_device_bytes=32)
|
||||
stats.record_host_usage(usage=0.5, pending_page_transfers=1)
|
||||
stats.record_host_usage(usage=0.75, pending_page_transfers=3)
|
||||
stats.record_host_evictions([KVCacheEvictionEvent(5.0, 2.0, (1.0, 2.0))])
|
||||
later = HiSparseKVConnectorStats()
|
||||
later.record_host_evictions([KVCacheEvictionEvent(3.0, 3.0, ())])
|
||||
prom.observe(stats.aggregate(later).to_dict())
|
||||
|
||||
assert created["vllm:hisparse_cache_hits"].increments == [3]
|
||||
assert created["vllm:hisparse_host_to_device_bytes"].increments == [32]
|
||||
assert created["vllm:hisparse_host_cache_usage_perc"].set_values == [0.75]
|
||||
assert created["vllm:hisparse_pending_page_transfers"].set_values == [3]
|
||||
if not kv_cache_metrics:
|
||||
assert not any("host_block" in name for name in created)
|
||||
return
|
||||
assert created["vllm:hisparse_host_block_lifetime_seconds"].observed == [5.0, 3.0]
|
||||
assert created["vllm:hisparse_host_block_idle_before_evict_seconds"].observed == [
|
||||
2.0,
|
||||
3.0,
|
||||
]
|
||||
assert created["vllm:hisparse_host_block_reuse_gap_seconds"].observed == [1.0, 2.0]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,335 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Hardware-fair request routing in the MoRIIO toy P/D proxy.
|
||||
|
||||
Exercises the REAL ``flat_interleaved_dp_route`` from the toy proxy (loaded from
|
||||
its ``examples/`` path with heavy deps stubbed) — no routing logic is copied
|
||||
here. This is the request-distribution half of end-to-end fairness: the proxy
|
||||
must hand every prefill/decode (instance, dp_rank) slot an equal share so no GPU
|
||||
is starved. The connector-side read routing is covered in
|
||||
``test_moriio_routing_fairness.py``.
|
||||
|
||||
Regression target: the previous scheme derived ``instance = req % n_instances``
|
||||
and ``dp_rank = req % dp_size`` from the same counter, so when
|
||||
``n_instances | dp_size`` each instance was locked to a stride-``n`` subset of
|
||||
its ranks — e.g. 2 prefill instances x DP8 stranded 4 of every node's 8 GPUs.
|
||||
``flat_interleaved_dp_route`` walks ONE counter over the full
|
||||
``(instance, dp_rank)`` slot space, so the two selections can never alias.
|
||||
|
||||
Role shapes below are exactly those in the RFC (#46107) deployments:
|
||||
(1, 1) 1P/1D TP8 (2, 1) 2P/2D TP8 (4, 1) 4D TP8
|
||||
(1, 8) 1D DP8EP (2, 8) 2P DP8EP (3, 8) 3D DP8EP
|
||||
"""
|
||||
|
||||
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()
|
||||
|
||||
PROXY_REL = "examples/disaggregated/disaggregated_serving/moriio_toy_proxy_server.py"
|
||||
|
||||
|
||||
def _module(name, **attrs):
|
||||
module = types.ModuleType(name)
|
||||
for attr, value in attrs.items():
|
||||
setattr(module, attr, value)
|
||||
return module
|
||||
|
||||
|
||||
def _package(name):
|
||||
module = _module(name)
|
||||
module.__path__ = []
|
||||
return module
|
||||
|
||||
|
||||
class _QuartStub:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def route(self, *a, **k):
|
||||
return lambda fn: fn
|
||||
|
||||
def post(self, *a, **k):
|
||||
return self.route()
|
||||
|
||||
|
||||
async def _make_response_stub(value):
|
||||
return value
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _proxy_import_stubs():
|
||||
"""Stub the proxy's external deps so the module imports for a pure unit test.
|
||||
|
||||
Only third-party/vllm imports are stubbed; the routing function under test
|
||||
is executed as-is from the real module.
|
||||
"""
|
||||
common = "vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common"
|
||||
|
||||
class _MoRIIOConstants:
|
||||
TRANSFER_PREFIX = "moriio-transfer"
|
||||
|
||||
stubs = {
|
||||
"aiohttp": _module("aiohttp"),
|
||||
"msgpack": _module("msgpack"),
|
||||
"zmq": _module("zmq"),
|
||||
"quart": _module(
|
||||
"quart",
|
||||
Quart=_QuartStub,
|
||||
Request=object,
|
||||
make_response=_make_response_stub,
|
||||
request=object(),
|
||||
),
|
||||
"vllm": _package("vllm"),
|
||||
"vllm.distributed": _package("vllm.distributed"),
|
||||
"vllm.distributed.kv_transfer": _package("vllm.distributed.kv_transfer"),
|
||||
"vllm.distributed.kv_transfer.kv_connector": _package(
|
||||
"vllm.distributed.kv_transfer.kv_connector"
|
||||
),
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1": _package(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1"
|
||||
),
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.moriio": _package(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.moriio"
|
||||
),
|
||||
common: _module(common, MoRIIOConstants=_MoRIIOConstants),
|
||||
}
|
||||
saved = {}
|
||||
for name, module in stubs.items():
|
||||
if name not in sys.modules:
|
||||
saved[name] = _MISSING
|
||||
sys.modules[name] = module
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name, previous in saved.items():
|
||||
if previous is _MISSING:
|
||||
sys.modules.pop(name, None)
|
||||
else:
|
||||
sys.modules[name] = cast(types.ModuleType, previous)
|
||||
|
||||
|
||||
def _load_proxy_module():
|
||||
path = Path(__file__).parents[4] / PROXY_REL
|
||||
spec = importlib.util.spec_from_file_location("moriio_proxy_under_test", path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
with _proxy_import_stubs():
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def route():
|
||||
return _load_proxy_module().flat_interleaved_dp_route
|
||||
|
||||
|
||||
def _instances(n: int, dp_size: int):
|
||||
# Only dp_size is read by the router; tp_size carried for realism.
|
||||
return [{"dp_size": dp_size, "tp_size": 8 // dp_size} for _ in range(n)]
|
||||
|
||||
|
||||
# (n_instances, dp_size) for every distinct P/D role shape in the RFC configs.
|
||||
ROLE_SHAPES = [(1, 1), (2, 1), (4, 1), (1, 8), (2, 8), (3, 8)]
|
||||
SHAPE_IDS = [f"n{n}_dp{dp}" for n, dp in ROLE_SHAPES]
|
||||
|
||||
|
||||
def _route_n(route, instances, count):
|
||||
# Proxy uses 1-indexed request numbers (slot = (request_number - 1) % ...).
|
||||
return [route(rn, instances) for rn in range(1, count + 1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("n", "dp"), ROLE_SHAPES, ids=SHAPE_IDS)
|
||||
def test_full_slot_space_is_covered_uniformly(route, n, dp):
|
||||
instances = _instances(n, dp)
|
||||
period = n * dp
|
||||
# Three full cycles -> every (instance, dp_rank) slot must be hit the same
|
||||
# number of times (exactly uniform, no starved slot, no aliasing).
|
||||
hits = Counter(_route_n(route, instances, period * 3))
|
||||
|
||||
expected: set[tuple[int, int | None]]
|
||||
if dp == 1:
|
||||
expected = {(inst, None) for inst in range(n)}
|
||||
else:
|
||||
expected = {(inst, r) for inst in range(n) for r in range(dp)}
|
||||
assert set(hits) == expected, f"missing slots: {expected - set(hits)}"
|
||||
assert max(hits.values()) == min(hits.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("n", "dp"), ROLE_SHAPES, ids=SHAPE_IDS)
|
||||
def test_instance_and_dp_rank_marginals_are_balanced(route, n, dp):
|
||||
instances = _instances(n, dp)
|
||||
routed = _route_n(route, instances, n * dp * 5)
|
||||
|
||||
inst_counts = Counter(inst for inst, _ in routed)
|
||||
assert set(inst_counts) == set(range(n))
|
||||
assert max(inst_counts.values()) == min(inst_counts.values())
|
||||
|
||||
dp_counts = Counter(r for _, r in routed)
|
||||
if dp == 1:
|
||||
assert set(dp_counts) == {None}
|
||||
else:
|
||||
assert set(dp_counts) == set(range(dp))
|
||||
assert max(dp_counts.values()) == min(dp_counts.values())
|
||||
|
||||
|
||||
def test_tp_instance_forwards_no_dp_rank(route):
|
||||
# dp_size == 1 (a TP instance) must yield dp_rank None so the proxy never
|
||||
# forwards an out-of-range data-parallel rank.
|
||||
assert all(r is None for _, r in _route_n(route, _instances(2, 1), 8))
|
||||
|
||||
|
||||
def test_two_instance_dp8_gives_every_node_all_ranks(route):
|
||||
# Direct regression for the stranded-GPU bug: with 2 prefill instances x DP8
|
||||
# each instance must receive ALL 8 dp ranks (16 distinct slots), not a
|
||||
# stride-2 subset of 4.
|
||||
routed = _route_n(route, _instances(2, 8), 2 * 8)
|
||||
per_instance: dict[int, set] = {0: set(), 1: set()}
|
||||
for inst, dp_rank in routed:
|
||||
per_instance[inst].add(dp_rank)
|
||||
assert per_instance[0] == set(range(8))
|
||||
assert per_instance[1] == set(range(8))
|
||||
|
||||
|
||||
def test_consecutive_requests_alternate_instances(route):
|
||||
# Interleaved order spreads consecutive requests across instances rather
|
||||
# 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()
|
||||
@@ -1,98 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for MoRIIO router-authoritative DP-rank routing.
|
||||
|
||||
These lock in the redesign that addresses the PR #45043 review feedback
|
||||
(njhill): the connector must NOT self-derive a DP rank, and the prefill leg
|
||||
must *return* the rank it actually ran on via ``request_finished`` so the
|
||||
decode->prefill notify is routed by pure propagation (READ / serial WRITE),
|
||||
not by an independent hash on each side.
|
||||
|
||||
Following test_moriio_unmap.py, we bind the unbound method to a lightweight
|
||||
stand-in rather than constructing a full scheduler.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
|
||||
MoRIIOConnectorScheduler,
|
||||
)
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
_request_finished = MoRIIOConnectorScheduler.request_finished
|
||||
_clip_blocks = MoRIIOConnectorScheduler.get_exchange_clipped_blocks
|
||||
|
||||
|
||||
def _producer(global_dp_rank: int, dp_size: int, dp_size_local: int):
|
||||
"""Minimal prefill-side (producer) scheduler stand-in for request_finished."""
|
||||
s = SimpleNamespace(
|
||||
is_producer=True,
|
||||
_is_hma_required=False,
|
||||
_has_mamba=False,
|
||||
blocks_per_sw=[0],
|
||||
_global_dp_rank=global_dp_rank,
|
||||
engine_id="engine-abc",
|
||||
host_ip="10.0.0.1",
|
||||
handshake_port=6300,
|
||||
side_notify_port=7300,
|
||||
vllm_config=SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_size=dp_size,
|
||||
data_parallel_size_local=dp_size_local,
|
||||
tensor_parallel_size=1,
|
||||
)
|
||||
),
|
||||
)
|
||||
s.get_exchange_clipped_blocks = _clip_blocks.__get__(s)
|
||||
return s
|
||||
|
||||
|
||||
def _req(
|
||||
request_id: str, params: dict | None, status=RequestStatus.FINISHED_LENGTH_CAPPED
|
||||
):
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
kv_transfer_params=params,
|
||||
status=status,
|
||||
)
|
||||
|
||||
|
||||
def test_request_finished_returns_prefill_rank_for_propagation():
|
||||
# 2P2D: global rank 11 lives on pod 1 (ranks 8..15), local size 8.
|
||||
s = _producer(global_dp_rank=11, dp_size=16, dp_size_local=8)
|
||||
req = _req("r1", {"do_remote_decode": True, "transfer_id": "t1"})
|
||||
|
||||
delay_free, params = _request_finished(s, req, block_ids=[])
|
||||
|
||||
# The prefill leg returns the rank IT actually ran on, marked authoritative,
|
||||
# so the router forwards it to decode and the notify propagates (no hashing).
|
||||
assert params is not None
|
||||
assert params["remote_dp_rank"] == 11
|
||||
assert params["remote_dp_rank_override"] is True
|
||||
assert params["remote_dp_size"] == 16
|
||||
assert params["remote_dp_size_local"] == 8
|
||||
assert params["transfer_id"] == "t1"
|
||||
# Empty block_ids => nothing deferred, blocks freed immediately.
|
||||
assert delay_free is False
|
||||
|
||||
|
||||
def test_request_finished_rank_tracks_the_actual_rank():
|
||||
# A different rank must be echoed verbatim -- the value is the producer's
|
||||
# own rank, never a recomputation of the request id.
|
||||
s = _producer(global_dp_rank=4, dp_size=8, dp_size_local=8)
|
||||
req = _req("r2", {"do_remote_decode": True, "transfer_id": "t2"})
|
||||
|
||||
_, params = _request_finished(s, req, block_ids=[])
|
||||
|
||||
assert params["remote_dp_rank"] == 4
|
||||
assert params["remote_dp_size_local"] == 8
|
||||
|
||||
|
||||
def test_request_finished_no_kv_params_is_noop():
|
||||
s = _producer(global_dp_rank=0, dp_size=16, dp_size_local=8)
|
||||
req = _req("r3", None)
|
||||
|
||||
delay_free, params = _request_finished(s, req, block_ids=[])
|
||||
|
||||
assert delay_free is False
|
||||
assert params is None
|
||||
@@ -1,210 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Hardware-fair KV-read routing across MoRIIO heterogeneous P/D configs.
|
||||
|
||||
Dependency-light (no GPU / ROCm / mori): builds bare ``MoRIIOConnectorWorker``
|
||||
instances via ``object.__new__`` and drives the REAL read-source routing
|
||||
decision (``_resolve_read_source`` / ``_next_flex_tp_rank``) directly -- no
|
||||
routing logic is re-implemented here, so a future change to those functions is
|
||||
what these tests exercise.
|
||||
|
||||
Scope -- the CONNECTOR (decode-side) read routing. The connector never selects
|
||||
the prefill instance; the proxy does and hands the connector a ``remote_host`` +
|
||||
``remote_dp_rank`` per request. The connector's only fairness lever is WHICH
|
||||
prefill (dp, tp) rank each read targets, and the RFC's deployments collapse to
|
||||
three real connector behaviours:
|
||||
|
||||
symmetric TP (TP prefill + TP decode) -> decode tp_k reads prefill tp_k
|
||||
flexible (TP prefill + DP decode) -> round-robin over prefill tp0..N-1
|
||||
owner DP (DP prefill, any decode) -> read the owner rank, tp0
|
||||
|
||||
These assume the proxy delivers a FAIR request stream (each prefill instance +
|
||||
owner dp-rank an equal share) and verify the connector never re-introduces a
|
||||
bottleneck. That proxy contract is checked separately against the real
|
||||
``flat_interleaved_dp_route`` in the toy-proxy tests (PR #46115).
|
||||
|
||||
A node runs one of two modes (8 GPUs each):
|
||||
* TP8 -> (dp_size, tp_size) = (1, 8); MLA latent KV REPLICATED on all ranks.
|
||||
* DP8EP -> (dp_size, tp_size) = (8, 1); KV PARTITIONED, one owner rank/request.
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
ReqMeta,
|
||||
get_port_offset,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
|
||||
MoRIIOConnectorWorker,
|
||||
)
|
||||
|
||||
MODE_DIMS = {"TP8": (1, 8), "DP8EP": (8, 1)} # (dp_size, tp_size), 8 GPUs/node
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PDConfig:
|
||||
name: str
|
||||
p_mode: str
|
||||
d_mode: str
|
||||
|
||||
@property
|
||||
def p_dp(self) -> int:
|
||||
return MODE_DIMS[self.p_mode][0]
|
||||
|
||||
@property
|
||||
def p_tp(self) -> int:
|
||||
return MODE_DIMS[self.p_mode][1]
|
||||
|
||||
@property
|
||||
def d_dp(self) -> int:
|
||||
return MODE_DIMS[self.d_mode][0]
|
||||
|
||||
@property
|
||||
def d_tp(self) -> int:
|
||||
return MODE_DIMS[self.d_mode][1]
|
||||
|
||||
@property
|
||||
def n_prefill_gpus(self) -> int:
|
||||
return self.p_dp * self.p_tp
|
||||
|
||||
|
||||
CONFIGS = [
|
||||
PDConfig("1P_TP8:1D_TP8", "TP8", "TP8"),
|
||||
PDConfig("2P_TP8:1D_DP8EP", "TP8", "DP8EP"),
|
||||
PDConfig("2P_TP8:2D_TP8", "TP8", "TP8"),
|
||||
PDConfig("2P_DP8EP:3D_DP8EP", "DP8EP", "DP8EP"),
|
||||
PDConfig("2P_DP8EP:4D_TP8", "DP8EP", "TP8"),
|
||||
]
|
||||
CONFIG_IDS = [c.name for c in CONFIGS]
|
||||
|
||||
|
||||
def make_decode_worker(*, world_size: int, tp_rank: int, dp_rank: int):
|
||||
w = object.__new__(MoRIIOConnectorWorker)
|
||||
w.world_size = world_size
|
||||
w.tp_rank = tp_rank
|
||||
w.dp_rank = dp_rank
|
||||
w.use_mla = True
|
||||
return w
|
||||
|
||||
|
||||
def make_meta(*, p_tp: int, p_dp: int, remote_dp_rank: int, host: str = "phost0"):
|
||||
return ReqMeta(
|
||||
transfer_id="t",
|
||||
local_block_ids=[1],
|
||||
remote_block_ids=[2],
|
||||
remote_host=host,
|
||||
remote_port=1234,
|
||||
remote_handshake_port=6301,
|
||||
remote_notify_port=61005,
|
||||
remote_engine_id=f"{host}:6301",
|
||||
tp_size=p_tp,
|
||||
remote_dp_size=p_dp,
|
||||
remote_dp_rank=remote_dp_rank,
|
||||
)
|
||||
|
||||
|
||||
def build_decode_workers(cfg: PDConfig) -> list:
|
||||
"""Decode workers that issue reads for one prefill instance. A TP decode
|
||||
instance reads from every tp rank; a DP decode instance from each dp-rank
|
||||
worker. Reused across requests so per-worker round-robin state advances."""
|
||||
if cfg.d_tp > 1:
|
||||
return [
|
||||
make_decode_worker(world_size=cfg.d_tp, tp_rank=r, dp_rank=0)
|
||||
for r in range(cfg.d_tp)
|
||||
]
|
||||
return [
|
||||
make_decode_worker(world_size=1, tp_rank=0, dp_rank=d) for d in range(cfg.d_dp)
|
||||
]
|
||||
|
||||
|
||||
def prefill_target_multiset(cfg: PDConfig, rounds: int) -> Counter:
|
||||
"""Drive the REAL _resolve_read_source over a fair input stream; tally which
|
||||
prefill GPU each read targets. The only modelled assumption is the proxy
|
||||
contract -- each owner dp-rank delivered equally (``for owner_dp in
|
||||
range(p_dp)``); no proxy algorithm is reproduced."""
|
||||
workers = build_decode_workers(cfg)
|
||||
hits: Counter = Counter()
|
||||
for _ in range(rounds):
|
||||
for owner_dp in range(cfg.p_dp):
|
||||
for worker in workers:
|
||||
meta = make_meta(p_tp=cfg.p_tp, p_dp=cfg.p_dp, remote_dp_rank=owner_dp)
|
||||
chosen_tp, _flexible = worker._resolve_read_source(meta)
|
||||
target = get_port_offset(owner_dp, chosen_tp, cfg.p_tp)
|
||||
assert 0 <= target < cfg.n_prefill_gpus
|
||||
hits[target] += 1
|
||||
return hits
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cfg", CONFIGS, ids=CONFIG_IDS)
|
||||
def test_kv_read_load_is_hardware_fair(cfg: PDConfig) -> None:
|
||||
# rounds a multiple of p_tp so the round-robin closes on an exact cycle.
|
||||
hits = prefill_target_multiset(cfg, rounds=16)
|
||||
gpus = set(range(cfg.n_prefill_gpus))
|
||||
assert set(hits) == gpus, f"unused prefill GPUs: {sorted(gpus - set(hits))}"
|
||||
assert max(hits.values()) == min(hits.values()), dict(sorted(hits.items()))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cfg", CONFIGS, ids=CONFIG_IDS)
|
||||
def test_flexible_gate_fires_only_for_tp_prefill_dp_decode(cfg: PDConfig) -> None:
|
||||
flags = set()
|
||||
for worker in build_decode_workers(cfg):
|
||||
meta = make_meta(p_tp=cfg.p_tp, p_dp=cfg.p_dp, remote_dp_rank=0)
|
||||
_chosen, flexible = worker._resolve_read_source(meta)
|
||||
flags.add(flexible)
|
||||
is_mirror = cfg.d_tp == 1 and cfg.p_dp == 1 and cfg.p_tp > 1
|
||||
assert flags == {is_mirror}
|
||||
|
||||
|
||||
def test_symmetric_tp_is_a_bijection() -> None:
|
||||
targets = []
|
||||
for tp_rank in range(8):
|
||||
worker = make_decode_worker(world_size=8, tp_rank=tp_rank, dp_rank=0)
|
||||
chosen_tp, flexible = worker._resolve_read_source(
|
||||
make_meta(p_tp=8, p_dp=1, remote_dp_rank=0)
|
||||
)
|
||||
assert not flexible
|
||||
targets.append(chosen_tp)
|
||||
assert sorted(targets) == list(range(8))
|
||||
|
||||
|
||||
def test_owner_dp_read_is_faithful_and_covers_every_rank() -> None:
|
||||
worker = make_decode_worker(world_size=8, tp_rank=3, dp_rank=0)
|
||||
targets = []
|
||||
for owner_dp in range(8):
|
||||
chosen_tp, flexible = worker._resolve_read_source(
|
||||
make_meta(p_tp=1, p_dp=8, remote_dp_rank=owner_dp)
|
||||
)
|
||||
assert not flexible
|
||||
assert chosen_tp == 0 # p_tp == 1, only tp0 exists
|
||||
targets.append(get_port_offset(owner_dp, chosen_tp, 1))
|
||||
assert sorted(targets) == list(range(8))
|
||||
|
||||
|
||||
def test_flexible_round_robin_is_deterministic_uniform_and_staggered() -> None:
|
||||
w0 = make_decode_worker(world_size=1, tp_rank=0, dp_rank=0)
|
||||
seq = [w0._next_flex_tp_rank(8) for _ in range(64)]
|
||||
assert seq[:8] == list(range(8))
|
||||
assert Counter(seq) == Counter({t: 8 for t in range(8)})
|
||||
|
||||
first_pick = [
|
||||
make_decode_worker(world_size=1, tp_rank=0, dp_rank=d)._next_flex_tp_rank(8)
|
||||
for d in range(8)
|
||||
]
|
||||
assert sorted(first_pick) == list(range(8))
|
||||
|
||||
|
||||
def test_read_blocks_for_req_threads_chosen_tp() -> None:
|
||||
# The resolved (chosen_tp, flexible) must reach _read_blocks, which keys the
|
||||
# session AND the notify port off that single value -- so a read and its
|
||||
# completion notify address the same prefill rank.
|
||||
worker = make_decode_worker(world_size=1, tp_rank=0, dp_rank=3)
|
||||
worker._read_blocks = MagicMock()
|
||||
worker._read_blocks_for_req("r", make_meta(p_tp=8, p_dp=1, remote_dp_rank=0))
|
||||
kw = worker._read_blocks.call_args.kwargs
|
||||
assert kw["flexible"] is True
|
||||
assert kw["chosen_tp"] == 3 # first flexible pick = dp_rank seed
|
||||
assert get_port_offset(0, kw["chosen_tp"], 8) == 3
|
||||
@@ -1,494 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
MoRIIOMode,
|
||||
MoRIIOTransferAck,
|
||||
TransferError,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
|
||||
MoRIIOConnector,
|
||||
MoRIIOConnectorWorker,
|
||||
get_moriio_expected_ack_count,
|
||||
get_moriio_remote_tp_rank,
|
||||
resolve_moriio_transfer_ack,
|
||||
validate_moriio_heterogeneous_tp_kv_heads,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_engine import (
|
||||
MoRIIOWrapper,
|
||||
)
|
||||
|
||||
|
||||
def test_remote_tp_rank_same_tp_maps_to_self():
|
||||
assert [get_moriio_remote_tp_rank(rank, 4, 4) for rank in range(4)] == [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
]
|
||||
|
||||
|
||||
def test_remote_tp_rank_p4_d8_floor_maps_decode_to_prefill():
|
||||
assert [get_moriio_remote_tp_rank(rank, 8, 4) for rank in range(8)] == [
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
2,
|
||||
2,
|
||||
3,
|
||||
3,
|
||||
]
|
||||
|
||||
|
||||
def test_remote_tp_rank_p8_d4_maps_to_first_prefill_rank_per_pair():
|
||||
assert [get_moriio_remote_tp_rank(rank, 4, 8) for rank in range(4)] == [
|
||||
0,
|
||||
2,
|
||||
4,
|
||||
6,
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("local_tp_rank", "local_tp_size", "remote_tp_size"),
|
||||
[
|
||||
(0, 6, 4),
|
||||
(0, 4, 6),
|
||||
],
|
||||
)
|
||||
def test_remote_tp_rank_invalid_non_multiple_tp_raises(
|
||||
local_tp_rank: int, local_tp_size: int, remote_tp_size: int
|
||||
):
|
||||
with pytest.raises(ValueError, match="multiple"):
|
||||
get_moriio_remote_tp_rank(local_tp_rank, local_tp_size, remote_tp_size)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("local_tp_size", "remote_tp_size", "total_num_kv_heads"),
|
||||
[
|
||||
(4, 4, 8),
|
||||
(8, 4, 4),
|
||||
(4, 8, 4),
|
||||
],
|
||||
)
|
||||
def test_heterogeneous_tp_head_guard_allows_supported_layouts(
|
||||
local_tp_size: int, remote_tp_size: int, total_num_kv_heads: int
|
||||
):
|
||||
validate_moriio_heterogeneous_tp_kv_heads(
|
||||
local_tp_size,
|
||||
remote_tp_size,
|
||||
total_num_kv_heads,
|
||||
is_mla=False,
|
||||
)
|
||||
|
||||
|
||||
def test_heterogeneous_tp_head_guard_allows_mla_layouts():
|
||||
validate_moriio_heterogeneous_tp_kv_heads(
|
||||
local_tp_size=2,
|
||||
remote_tp_size=4,
|
||||
total_num_kv_heads=4,
|
||||
is_mla=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("local_tp_size", "remote_tp_size", "total_num_kv_heads"),
|
||||
[
|
||||
(4, 2, 4),
|
||||
(2, 4, 4),
|
||||
],
|
||||
)
|
||||
def test_heterogeneous_tp_head_guard_rejects_split_kv_heads(
|
||||
local_tp_size: int, remote_tp_size: int, total_num_kv_heads: int
|
||||
):
|
||||
with pytest.raises(NotImplementedError, match="replicated KV heads"):
|
||||
validate_moriio_heterogeneous_tp_kv_heads(
|
||||
local_tp_size,
|
||||
remote_tp_size,
|
||||
total_num_kv_heads,
|
||||
is_mla=False,
|
||||
)
|
||||
|
||||
|
||||
def test_expected_ack_count_for_homogeneous_or_smaller_consumer_tp_is_one():
|
||||
assert get_moriio_expected_ack_count(4, 4) == 1
|
||||
assert get_moriio_expected_ack_count(8, 4) == 1
|
||||
|
||||
|
||||
def test_expected_ack_count_for_decode_fan_in():
|
||||
assert get_moriio_expected_ack_count(4, 8) == 2
|
||||
|
||||
|
||||
def test_expected_ack_count_rejects_non_multiple_fan_in():
|
||||
with pytest.raises(ValueError, match="multiple"):
|
||||
get_moriio_expected_ack_count(4, 6)
|
||||
|
||||
|
||||
def test_plain_string_ack_is_backward_compatible_single_ack():
|
||||
notification_counts: dict[str, int] = {}
|
||||
completed_transfer_ids: set[str] = set()
|
||||
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
"tx-plain",
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-plain"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
== "tx-plain"
|
||||
)
|
||||
assert notification_counts == {}
|
||||
assert completed_transfer_ids == {"tx-plain"}
|
||||
|
||||
|
||||
def test_structured_release_ack_waits_for_all_expected_acks():
|
||||
ack = MoRIIOTransferAck("tx-fanin", consumer_tp_size=8)
|
||||
notification_counts: dict[str, int] = {}
|
||||
completed_transfer_ids: set[str] = set()
|
||||
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
ack,
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-fanin"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert notification_counts == {"tx-fanin": 1}
|
||||
assert completed_transfer_ids == set()
|
||||
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
ack,
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-fanin"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
== "tx-fanin"
|
||||
)
|
||||
assert notification_counts == {}
|
||||
assert completed_transfer_ids == {"tx-fanin"}
|
||||
|
||||
|
||||
def test_duplicate_ack_after_completion_does_not_resolve_twice():
|
||||
ack = MoRIIOTransferAck("tx-dup", consumer_tp_size=8)
|
||||
notification_counts: dict[str, int] = {}
|
||||
completed_transfer_ids: set[str] = set()
|
||||
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
ack,
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-dup"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
ack,
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-dup"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
== "tx-dup"
|
||||
)
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
ack,
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-dup"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert notification_counts == {}
|
||||
assert completed_transfer_ids == {"tx-dup"}
|
||||
|
||||
|
||||
def test_ack_for_non_live_transfer_is_ignored():
|
||||
notification_counts: dict[str, int] = {}
|
||||
completed_transfer_ids: set[str] = set()
|
||||
|
||||
assert (
|
||||
resolve_moriio_transfer_ack(
|
||||
MoRIIOTransferAck("tx-stale", consumer_tp_size=8),
|
||||
producer_tp_size=4,
|
||||
live_transfer_ids={"tx-live"},
|
||||
notification_counts=notification_counts,
|
||||
completed_transfer_ids=completed_transfer_ids,
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert notification_counts == {}
|
||||
assert completed_transfer_ids == set()
|
||||
|
||||
|
||||
def test_worker_get_finished_counts_structured_release_fan_in():
|
||||
class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.batches = [
|
||||
[MoRIIOTransferAck("tx-fanin", consumer_tp_size=8)],
|
||||
[MoRIIOTransferAck("tx-fanin", consumer_tp_size=8)],
|
||||
]
|
||||
|
||||
def pop_finished_req_ids(self):
|
||||
return self.batches.pop(0)
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker.is_producer = True
|
||||
worker.mode = MoRIIOMode.READ
|
||||
worker.world_size = 4
|
||||
worker.moriio_wrapper = FakeWrapper()
|
||||
worker.transfer_id_to_request_id = {"tx-fanin": "req-fanin"}
|
||||
worker._consumer_notification_counts = {}
|
||||
worker._completed_consumer_notifications = set()
|
||||
worker._pending_unmapped_acks = []
|
||||
|
||||
assert worker.get_finished() == (set(), set())
|
||||
assert worker._consumer_notification_counts == {"tx-fanin": 1}
|
||||
|
||||
assert worker.get_finished() == ({"req-fanin"}, set())
|
||||
assert worker._consumer_notification_counts == {}
|
||||
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):
|
||||
return True
|
||||
|
||||
def Failed(self):
|
||||
return False
|
||||
|
||||
class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.sent = []
|
||||
|
||||
# Exercise the real batch verdict rather than restating it here.
|
||||
poll_transfer_batch = MoRIIOWrapper.poll_transfer_batch
|
||||
|
||||
def send_notify(
|
||||
self,
|
||||
transfer_id,
|
||||
host,
|
||||
port,
|
||||
message_type=None,
|
||||
message_fields=None,
|
||||
):
|
||||
self.sent.append((transfer_id, host, port, message_type, message_fields))
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker.world_size = 8
|
||||
worker.moriio_config = SimpleNamespace(recv_abort_timeout=600.0)
|
||||
worker.moriio_wrapper = FakeWrapper()
|
||||
# A layer maps to the list of reads posted for it (a KDA layer posts two).
|
||||
worker._recving_transfers = {"req": {"layer0": [DoneStatus(), DoneStatus()]}}
|
||||
worker._recving_transfers_callback_addr = {
|
||||
"req": ("127.0.0.1", "7000", "tx-release")
|
||||
}
|
||||
# Transfer-timeout reaping state consulted by _pop_done_transfers.
|
||||
worker._recving_transfers_start = {}
|
||||
# Load-error bookkeeping cleared alongside a completed transfer.
|
||||
worker._recving_local_blocks = {}
|
||||
worker._invalid_block_ids = set()
|
||||
|
||||
assert worker._pop_done_transfers() == {"tx-release"}
|
||||
assert worker.moriio_wrapper.sent == [
|
||||
(
|
||||
"tx-release",
|
||||
"127.0.0.1",
|
||||
"7000",
|
||||
"release",
|
||||
{"consumer_tp_size": 8},
|
||||
)
|
||||
]
|
||||
assert worker._recving_transfers == {}
|
||||
assert worker._recving_transfers_callback_addr == {}
|
||||
|
||||
|
||||
def test_aborted_read_without_local_blocks_only_releases_remote_blocks():
|
||||
class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def send_notify(
|
||||
self,
|
||||
transfer_id,
|
||||
host,
|
||||
port,
|
||||
message_type=None,
|
||||
message_fields=None,
|
||||
):
|
||||
self.sent.append((transfer_id, host, port, message_type, message_fields))
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker.mode = MoRIIOMode.READ
|
||||
worker.world_size = 8
|
||||
worker.moriio_wrapper = FakeWrapper()
|
||||
|
||||
worker._read_blocks(
|
||||
local_block_ids=[],
|
||||
remote_block_ids=[[10, 11], [90]],
|
||||
dst_engine_id="prefill",
|
||||
request_id="req-aborted",
|
||||
transfer_id="tx-aborted",
|
||||
remote_host="127.0.0.1",
|
||||
remote_notify_port=7000,
|
||||
remote_tp_size=8,
|
||||
remote_dp_rank=0,
|
||||
chosen_tp=2,
|
||||
)
|
||||
|
||||
assert worker.moriio_wrapper.sent == [
|
||||
(
|
||||
"tx-aborted",
|
||||
"127.0.0.1",
|
||||
"7002",
|
||||
"release",
|
||||
{"consumer_tp_size": 8},
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_read_completion_waits_for_every_posted_read():
|
||||
class Status:
|
||||
def __init__(self, done: bool):
|
||||
self.done = done
|
||||
|
||||
def Succeeded(self):
|
||||
return self.done
|
||||
|
||||
def Failed(self):
|
||||
return False
|
||||
|
||||
class FakeWrapper:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.sent = []
|
||||
|
||||
poll_transfer_batch = MoRIIOWrapper.poll_transfer_batch
|
||||
|
||||
def send_notify(self, *args, **kwargs):
|
||||
self.sent.append((args, kwargs))
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker.world_size = 8
|
||||
worker.moriio_config = SimpleNamespace(recv_abort_timeout=600.0)
|
||||
worker.moriio_wrapper = FakeWrapper()
|
||||
worker._recving_transfers = {
|
||||
"req": {"kda_layer": [Status(done=True), Status(done=False)]}
|
||||
}
|
||||
worker._recving_transfers_callback_addr = {
|
||||
"req": ("127.0.0.1", "7000", "tx-pending")
|
||||
}
|
||||
worker._recving_transfers_start = {"req": float("inf")}
|
||||
worker._recving_local_blocks = {"req": [1, 2]}
|
||||
worker._invalid_block_ids = set()
|
||||
|
||||
assert worker._pop_done_transfers() == set()
|
||||
assert "req" in worker._recving_transfers
|
||||
assert worker.moriio_wrapper.sent == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("has_mamba", "expected_invalid"),
|
||||
[(False, {1, 2}), (True, set())],
|
||||
)
|
||||
def test_failed_read_reports_blocks_only_without_hma(has_mamba, expected_invalid):
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker._has_mamba = has_mamba
|
||||
worker._recving_local_blocks = {"req": [1, 2]}
|
||||
worker._invalid_block_ids = set()
|
||||
|
||||
worker._record_failed_recv("req")
|
||||
|
||||
assert worker.get_block_ids_with_load_errors() == expected_invalid
|
||||
|
||||
|
||||
def test_hybrid_step_barrier_fails_closed(monkeypatch):
|
||||
class FailingWrapper:
|
||||
def waiting_for_transfer_complete(self, _statuses):
|
||||
raise TransferError("failed")
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker._has_mamba = True
|
||||
worker._reads_issued_this_step = [object()]
|
||||
worker._mamba_reads_this_step = [object()]
|
||||
worker.moriio_wrapper = FailingWrapper()
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector.get_forward_context",
|
||||
lambda: SimpleNamespace(cudagraph_runtime_mode=None),
|
||||
)
|
||||
|
||||
with pytest.raises(TransferError, match="failed"):
|
||||
worker._await_reads_issued_this_step()
|
||||
|
||||
|
||||
def test_requested_cudagraph_mode_is_never_overridden():
|
||||
# The configured cudagraph mode is always honored: the barrier fires when
|
||||
# the operator sets cudagraph_mode=PIECEWISE, and READ mode with full
|
||||
# graphs only warns instead of silently forcing PIECEWISE.
|
||||
assert (
|
||||
MoRIIOConnector.requires_piecewise_for_cudagraph({"read_mode": True}) is False
|
||||
)
|
||||
assert (
|
||||
MoRIIOConnector.requires_piecewise_for_cudagraph({"read_mode": False}) is False
|
||||
)
|
||||
@@ -1,68 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for MoRIIOConnectorScheduler.{map,unmap}_request_id.
|
||||
|
||||
vLLM's input_processor mutates a request_id after the connector has stored it
|
||||
(e.g. ``cmpl-abc-0`` -> ``cmpl-abc-0-956053a4``), so an exact-match unmap can
|
||||
miss. These tests cover the stable-``transfer_id`` fallback that handles that
|
||||
case (and the clean exact-match and miss paths).
|
||||
|
||||
The map/unmap methods touch only the two id<->id dicts, so we bind them to a
|
||||
lightweight stand-in rather than constructing a full scheduler.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
|
||||
MoRIIOConnectorScheduler,
|
||||
)
|
||||
|
||||
_map = MoRIIOConnectorScheduler.map_request_id
|
||||
_unmap = MoRIIOConnectorScheduler.unmap_request_id
|
||||
|
||||
|
||||
def _sched():
|
||||
return SimpleNamespace(
|
||||
transfer_id_to_request_id={},
|
||||
request_id_to_transfer_id={},
|
||||
)
|
||||
|
||||
|
||||
def test_exact_match_unmap_clears_both_tables():
|
||||
s = _sched()
|
||||
_map(s, "rid-1", "tid-1")
|
||||
_unmap(s, "rid-1")
|
||||
assert s.request_id_to_transfer_id == {}
|
||||
assert s.transfer_id_to_request_id == {}
|
||||
|
||||
|
||||
def test_unmap_via_transfer_id_after_request_id_mutation():
|
||||
s = _sched()
|
||||
# Connector stores the ORIGINAL request_id at map time.
|
||||
_map(s, "cmpl-abc-0", "tid-42")
|
||||
# input_processor later mutates the rid; exact match would miss, so the
|
||||
# stable transfer_id is used to find and clear the original entry.
|
||||
_unmap(s, "cmpl-abc-0-956053a4", transfer_id="tid-42")
|
||||
assert s.request_id_to_transfer_id == {}
|
||||
assert s.transfer_id_to_request_id == {}
|
||||
|
||||
|
||||
def test_unmap_miss_is_noop_and_does_not_raise():
|
||||
s = _sched()
|
||||
_map(s, "rid-1", "tid-1")
|
||||
# Unknown rid and unknown/None transfer_id: must not raise, must not touch
|
||||
# the existing (unrelated) mapping.
|
||||
_unmap(s, "rid-unknown", transfer_id=None)
|
||||
_unmap(s, "rid-unknown", transfer_id="tid-unknown")
|
||||
assert s.request_id_to_transfer_id == {"rid-1": "tid-1"}
|
||||
assert s.transfer_id_to_request_id == {"tid-1": "rid-1"}
|
||||
|
||||
|
||||
def test_exact_match_preferred_over_transfer_id_fallback():
|
||||
s = _sched()
|
||||
_map(s, "rid-1", "tid-1")
|
||||
# Exact rid is present, so it is removed directly even if a transfer_id is
|
||||
# also supplied; no stale entries left behind.
|
||||
_unmap(s, "rid-1", transfer_id="tid-1")
|
||||
assert s.request_id_to_transfer_id == {}
|
||||
assert s.transfer_id_to_request_id == {}
|
||||
@@ -1,449 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for mori-io write_done routing (#51681)."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio import moriio_engine
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
ROLE,
|
||||
LayerTransferPlan,
|
||||
MoRIIOError,
|
||||
MoRIIOMode,
|
||||
RemoteAllocInfo,
|
||||
ReqMeta,
|
||||
WriteTask,
|
||||
get_port_offset,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
|
||||
MoRIIOConnectorScheduler,
|
||||
MoRIIOConnectorWorker,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_engine import (
|
||||
MoRIIOWrapper,
|
||||
)
|
||||
|
||||
from .utils import make_moriio_writer
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
|
||||
def _fake_worker(
|
||||
alloc: dict[str, Any],
|
||||
*,
|
||||
tp_rank: int = 0,
|
||||
set_remote_dp_size_local: int | None = None,
|
||||
) -> Any:
|
||||
wrapper = SimpleNamespace(
|
||||
done_remote_allocate_req_dict=alloc,
|
||||
lock=threading.Lock(),
|
||||
done_req_ids=[],
|
||||
sent_notifies=[],
|
||||
)
|
||||
wrapper.send_notify = lambda transfer_id, remote_ip, remote_port, message_type: (
|
||||
wrapper.sent_notifies.append(
|
||||
(transfer_id, remote_ip, remote_port, message_type)
|
||||
)
|
||||
)
|
||||
wrapper.waiting_for_transfer_complete = lambda statuses: None
|
||||
wrapper._mark_transfer_terminal_locked = lambda transfer_id: None
|
||||
wrapper._is_transfer_terminal_locked = lambda transfer_id: False
|
||||
worker = SimpleNamespace(moriio_wrapper=wrapper, tp_rank=tp_rank)
|
||||
if set_remote_dp_size_local is not None:
|
||||
worker.remote_dp_size_local = set_remote_dp_size_local
|
||||
return worker
|
||||
|
||||
|
||||
def _req_meta(
|
||||
*,
|
||||
transfer_id: str = "tA",
|
||||
remote_host: str = "10.0.0.1",
|
||||
multi_pod_hosts: list[str] | None = None,
|
||||
remote_dp_size: int = 16,
|
||||
remote_dp_size_local: int = 8,
|
||||
) -> ReqMeta:
|
||||
return ReqMeta(
|
||||
transfer_id=transfer_id,
|
||||
local_block_ids=[[1]],
|
||||
remote_block_ids=[[2]],
|
||||
remote_host=remote_host,
|
||||
remote_port=1,
|
||||
remote_handshake_port=2,
|
||||
remote_notify_port=20000,
|
||||
remote_engine_id="remote-engine",
|
||||
tp_size=1,
|
||||
remote_dp_size=remote_dp_size,
|
||||
multi_pod_hosts=list(multi_pod_hosts or []),
|
||||
remote_dp_size_local=remote_dp_size_local,
|
||||
)
|
||||
|
||||
|
||||
def _write_task(
|
||||
transfer_id: str,
|
||||
remote_ip: str,
|
||||
*,
|
||||
multi_pod_hosts: list[str] | None = None,
|
||||
remote_dp_size_local: int = 0,
|
||||
remote_dp_size: int = 1,
|
||||
request_id: str = "req",
|
||||
) -> WriteTask:
|
||||
return WriteTask(
|
||||
request_id=request_id,
|
||||
transfer_id=transfer_id,
|
||||
dst_engine_id="remote-engine",
|
||||
local_block_ids=[[1, 3]],
|
||||
remote_block_ids_hint=None,
|
||||
layer_name="layer0",
|
||||
event=None,
|
||||
remote_notify_port=20000,
|
||||
remote_ip=remote_ip,
|
||||
multi_pod_hosts=multi_pod_hosts or [],
|
||||
remote_dp_size_local=remote_dp_size_local,
|
||||
remote_dp_size=remote_dp_size,
|
||||
)
|
||||
|
||||
|
||||
def _real_wrapper() -> MoRIIOWrapper:
|
||||
wrapper = MoRIIOWrapper.__new__(MoRIIOWrapper)
|
||||
wrapper.lock = threading.Lock()
|
||||
wrapper.done_req_ids = []
|
||||
wrapper.done_remote_allocate_req_dict = {}
|
||||
wrapper.done_write_cache_req_ids = []
|
||||
wrapper.failed_write_cache_req_ids = []
|
||||
wrapper._terminal_transfer_ids = OrderedDict()
|
||||
return wrapper
|
||||
|
||||
|
||||
def test_execute_write_task_ip_is_per_task_under_overwrite():
|
||||
alloc = {"tA": RemoteAllocInfo(block_ids=None, decode_dp_rank=0)}
|
||||
worker = _fake_worker(alloc)
|
||||
worker.multi_pod_hosts = ["10.0.0.2"]
|
||||
worker.remote_dp_size_local = 1
|
||||
|
||||
writer = make_moriio_writer(worker)
|
||||
task_a = _write_task(
|
||||
"tA", "10.0.0.1", multi_pod_hosts=["10.0.0.1"], remote_dp_size_local=1
|
||||
)
|
||||
writer._execute_write_task(task_a)
|
||||
|
||||
assert alloc["tA"].completion_remote_ip == "10.0.0.1"
|
||||
assert alloc["tA"].completion_remote_ip != "10.0.0.2"
|
||||
|
||||
|
||||
def test_deferred_task_ip_is_per_task_under_overwrite():
|
||||
alloc = {"tA": RemoteAllocInfo(block_ids=None, decode_dp_rank=0)}
|
||||
worker = _fake_worker(alloc)
|
||||
worker.multi_pod_hosts = ["10.0.0.2"]
|
||||
worker.remote_dp_size_local = 1
|
||||
|
||||
writer = make_moriio_writer(worker)
|
||||
task_a = _write_task(
|
||||
"tA", "10.0.0.1", multi_pod_hosts=["10.0.0.1"], remote_dp_size_local=1
|
||||
)
|
||||
writer._deferred_tasks.append(task_a)
|
||||
writer._process_deferred_tasks()
|
||||
|
||||
assert alloc["tA"].completion_remote_ip == "10.0.0.1"
|
||||
assert writer._deferred_tasks == []
|
||||
|
||||
|
||||
def test_two_requests_resolve_distinct_hosts():
|
||||
alloc = {
|
||||
"tA": RemoteAllocInfo(block_ids=None, decode_dp_rank=0),
|
||||
"tB": RemoteAllocInfo(block_ids=None, decode_dp_rank=3),
|
||||
}
|
||||
worker = _fake_worker(alloc)
|
||||
writer = make_moriio_writer(worker)
|
||||
|
||||
task_a = _write_task(
|
||||
"tA", "10.0.0.1", multi_pod_hosts=["10.0.0.1"], remote_dp_size_local=1
|
||||
)
|
||||
task_b = _write_task(
|
||||
"tB", "10.0.0.2", multi_pod_hosts=["10.0.0.2"], remote_dp_size_local=1
|
||||
)
|
||||
worker.multi_pod_hosts = ["10.0.0.2"]
|
||||
writer._execute_write_task(task_a)
|
||||
writer._execute_write_task(task_b)
|
||||
|
||||
assert alloc["tA"].completion_remote_ip == "10.0.0.1"
|
||||
assert alloc["tB"].completion_remote_ip == "10.0.0.2"
|
||||
|
||||
|
||||
def test_finalize_notify_port_uses_pod_local_rank():
|
||||
base = 20000
|
||||
info = RemoteAllocInfo(block_ids=None, decode_dp_rank=9)
|
||||
alloc = {"tA": info}
|
||||
worker = _fake_worker(alloc, tp_rank=0)
|
||||
writer = make_moriio_writer(worker)
|
||||
|
||||
task = _write_task(
|
||||
"tA",
|
||||
"10.0.0.1",
|
||||
multi_pod_hosts=["10.0.0.1", "10.0.0.2"],
|
||||
remote_dp_size_local=8,
|
||||
)
|
||||
writer._execute_write_task(task)
|
||||
assert info.completion_remote_ip == "10.0.0.2"
|
||||
|
||||
info.writes_expected = 1
|
||||
info.writes_done = 1
|
||||
writer._finalize_if_complete("tA", info)
|
||||
|
||||
assert worker.moriio_wrapper.sent_notifies
|
||||
_tid, ip, port, mtype = worker.moriio_wrapper.sent_notifies[-1]
|
||||
assert mtype == "write_done"
|
||||
assert ip == "10.0.0.2"
|
||||
assert port == base + get_port_offset(9 % 8, 0)
|
||||
|
||||
|
||||
def test_finalize_port_ignores_stale_worker_dp_local():
|
||||
base = 20000
|
||||
info = RemoteAllocInfo(block_ids=None, decode_dp_rank=9)
|
||||
alloc = {"tA": info}
|
||||
worker = _fake_worker(alloc, tp_rank=0, set_remote_dp_size_local=1)
|
||||
writer = make_moriio_writer(worker)
|
||||
|
||||
task = _write_task(
|
||||
"tA",
|
||||
"10.0.0.1",
|
||||
multi_pod_hosts=["10.0.0.1", "10.0.0.2"],
|
||||
remote_dp_size_local=8,
|
||||
)
|
||||
writer._execute_write_task(task)
|
||||
assert info.completion_notify_port == base + get_port_offset(9 % 8, 0)
|
||||
|
||||
info.writes_expected = 1
|
||||
info.writes_done = 1
|
||||
writer._finalize_if_complete("tA", info)
|
||||
|
||||
_tid, _ip, port, mtype = worker.moriio_wrapper.sent_notifies[-1]
|
||||
assert mtype == "write_done"
|
||||
assert port == base + get_port_offset(9 % 8, 0)
|
||||
assert port != base + get_port_offset(9 % 1, 0)
|
||||
|
||||
|
||||
def test_finalize_single_pod_port_uses_global_rank():
|
||||
base = 20000
|
||||
info = RemoteAllocInfo(block_ids=None, decode_dp_rank=3)
|
||||
alloc = {"tA": info}
|
||||
worker = _fake_worker(alloc, tp_rank=2)
|
||||
writer = make_moriio_writer(worker)
|
||||
|
||||
task = _write_task("tA", "10.0.0.1", multi_pod_hosts=[], remote_dp_size_local=0)
|
||||
writer._execute_write_task(task)
|
||||
assert info.completion_remote_ip == "10.0.0.1"
|
||||
assert info.completion_notify_port == base + get_port_offset(3, 2)
|
||||
|
||||
info.writes_expected = 1
|
||||
info.writes_done = 1
|
||||
writer._finalize_if_complete("tA", info)
|
||||
|
||||
_tid, _ip, port, _mtype = worker.moriio_wrapper.sent_notifies[-1]
|
||||
assert port == base + get_port_offset(3, 2)
|
||||
|
||||
|
||||
def test_write_blocks_for_req_forwards_routing_to_schedule_write():
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker._has_mamba = False
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def _capture_schedule_write_blocks(**kwargs: Any) -> None:
|
||||
captured.update(kwargs)
|
||||
|
||||
worker.schedule_write_blocks = _capture_schedule_write_blocks # type: ignore[method-assign]
|
||||
|
||||
meta = _req_meta(
|
||||
remote_host="10.0.0.1",
|
||||
multi_pod_hosts=["10.0.0.1", "10.0.0.2"],
|
||||
remote_dp_size_local=8,
|
||||
)
|
||||
worker._write_blocks_for_req("req-a", meta, "layer0", kv_layer=None)
|
||||
|
||||
assert captured["multi_pod_hosts"] == ["10.0.0.1", "10.0.0.2"]
|
||||
assert captured["remote_dp_size_local"] == 8
|
||||
assert captured["remote_ip"] == "10.0.0.1"
|
||||
assert captured["local_block_ids"] == [[1]]
|
||||
assert captured["remote_block_ids"] == [[2]]
|
||||
assert not hasattr(worker, "multi_pod_hosts")
|
||||
|
||||
|
||||
def test_write_blocks_for_req_falls_back_when_multi_pod_hosts_empty():
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker._has_mamba = False
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def _capture_schedule_write_blocks(**kwargs: Any) -> None:
|
||||
captured.update(kwargs)
|
||||
|
||||
worker.schedule_write_blocks = _capture_schedule_write_blocks # type: ignore[method-assign]
|
||||
|
||||
meta = _req_meta(
|
||||
remote_host="10.0.0.9",
|
||||
multi_pod_hosts=[],
|
||||
remote_dp_size=4,
|
||||
remote_dp_size_local=0,
|
||||
)
|
||||
worker._write_blocks_for_req("req-b", meta, "layer0", kv_layer=None)
|
||||
|
||||
assert captured["multi_pod_hosts"] == ["10.0.0.9"]
|
||||
assert captured["remote_dp_size_local"] == 4
|
||||
assert captured["local_block_ids"] == [[1]]
|
||||
assert captured["remote_block_ids"] == [[2]]
|
||||
|
||||
|
||||
def test_deferred_write_timeout_fails_transfer_on_every_decode_rank():
|
||||
wrapper = _real_wrapper()
|
||||
sent: list[tuple[str, int, str]] = []
|
||||
wrapper.send_notify = lambda tid, ip, port, message_type: sent.append(
|
||||
(ip, port, message_type)
|
||||
)
|
||||
writer = make_moriio_writer(SimpleNamespace(moriio_wrapper=wrapper, tp_rank=0))
|
||||
task = _write_task(
|
||||
"tA",
|
||||
"10.0.0.1",
|
||||
multi_pod_hosts=["10.0.0.1", "10.0.0.2"],
|
||||
remote_dp_size_local=2,
|
||||
remote_dp_size=4,
|
||||
)
|
||||
task.enqueue_time = time.perf_counter() - 2 * writer._defer_timeout
|
||||
writer._deferred_tasks.append(task)
|
||||
|
||||
writer._process_deferred_tasks()
|
||||
|
||||
assert writer._deferred_tasks == []
|
||||
assert [ack.transfer_id for ack in wrapper.done_req_ids] == ["tA"]
|
||||
# Global DP ranks 0-3, two per pod: the owning rank is unknown.
|
||||
assert sent == [
|
||||
(host, 20000 + get_port_offset(local_rank, 0), "write_failed")
|
||||
for host in ("10.0.0.1", "10.0.0.2")
|
||||
for local_rank in (0, 1)
|
||||
]
|
||||
|
||||
# A late decode allocation must not resurrect a write into freed blocks.
|
||||
with patch.object(moriio_engine, "get_role", return_value=ROLE.PRODUCER):
|
||||
wrapper._handle_remote_blocks_message(
|
||||
{"transfer_id": "tA", "block_notify_list": [7], "decode_rank": 1}
|
||||
)
|
||||
assert wrapper.done_remote_allocate_req_dict == {}
|
||||
|
||||
|
||||
def test_write_scheduler_waits_for_worker_ack_past_defer_deadline():
|
||||
scheduler = SimpleNamespace(
|
||||
is_producer=True,
|
||||
mode=MoRIIOMode.WRITE,
|
||||
_defer_timeout=60.0,
|
||||
_deferred_send_deadlines={"req-1": (time.monotonic() - 1.0, "tA")},
|
||||
_pending_sent_acks={},
|
||||
unmap_request_id=lambda *args, **kwargs: None,
|
||||
)
|
||||
output = SimpleNamespace(finished_sending=set())
|
||||
|
||||
MoRIIOConnectorScheduler.update_connector_output(scheduler, output)
|
||||
assert output.finished_sending is None
|
||||
assert "req-1" in scheduler._deferred_send_deadlines
|
||||
|
||||
output.finished_sending = {"req-1"}
|
||||
MoRIIOConnectorScheduler.update_connector_output(scheduler, output)
|
||||
assert output.finished_sending == {"req-1"}
|
||||
assert scheduler._deferred_send_deadlines == {}
|
||||
|
||||
|
||||
def test_write_failed_is_reported_as_failed_recving_on_owning_rank():
|
||||
wrapper = _real_wrapper()
|
||||
with patch.object(moriio_engine, "get_role", return_value=ROLE.CONSUMER):
|
||||
for tid in ("tA", "tOtherRank"):
|
||||
wrapper._handle_structured_message(
|
||||
{"type": "write_failed", "transfer_id": tid}
|
||||
)
|
||||
worker = SimpleNamespace(
|
||||
mode=MoRIIOMode.WRITE,
|
||||
is_producer=False,
|
||||
moriio_wrapper=wrapper,
|
||||
transfer_id_to_request_id={"tA": "req-1"},
|
||||
_unmatched_write_failures=OrderedDict(),
|
||||
get_finished=lambda: (set(), set()),
|
||||
)
|
||||
|
||||
results = MoRIIOConnectorWorker.get_transfer_results(worker)
|
||||
|
||||
assert results.finished_recving == {"req-1"}
|
||||
assert results.failed_recving == {"req-1"}
|
||||
assert wrapper.pop_finished_write_req_ids() == set()
|
||||
assert list(worker._unmatched_write_failures) == ["tOtherRank"]
|
||||
|
||||
|
||||
def test_hybrid_write_rejects_unequal_tp_before_scheduling_any_layer():
|
||||
from unittest.mock import Mock
|
||||
|
||||
worker = MoRIIOConnectorWorker.__new__(MoRIIOConnectorWorker)
|
||||
worker._has_mamba = True
|
||||
worker.world_size = 2
|
||||
worker.schedule_write_blocks = Mock()
|
||||
|
||||
with pytest.raises(NotImplementedError, match="heterogeneous-TP"):
|
||||
worker._write_blocks_for_req("req", _req_meta(), "attention", kv_layer=None)
|
||||
|
||||
worker.schedule_write_blocks.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"notify,expected",
|
||||
[
|
||||
# Plain WRITE peers still send one flat attention list.
|
||||
([7, 8], [[7, 8]]),
|
||||
# Hybrid WRITE sends one list per transfer group, kept as-is even
|
||||
# when the first group is empty (full attention hit, state only).
|
||||
([[7], [9]], [[7], [9]]),
|
||||
([[], [9]], [[], [9]]),
|
||||
],
|
||||
)
|
||||
def test_remote_blocks_message_normalizes_to_grouped_block_ids(notify, expected):
|
||||
wrapper = _real_wrapper()
|
||||
with patch.object(moriio_engine, "get_role", return_value=ROLE.PRODUCER):
|
||||
wrapper._handle_remote_blocks_message(
|
||||
{"transfer_id": "tA", "block_notify_list": notify, "decode_rank": 2}
|
||||
)
|
||||
info = wrapper.done_remote_allocate_req_dict["tA"]
|
||||
assert info.block_ids == expected
|
||||
assert info.decode_dp_rank == 2
|
||||
|
||||
|
||||
def test_empty_layer_plan_posts_no_rdma_write():
|
||||
from unittest.mock import Mock
|
||||
|
||||
wrapper = SimpleNamespace(write_remote_data=Mock(), write_remote_data_single=Mock())
|
||||
writer = make_moriio_writer(SimpleNamespace(moriio_wrapper=wrapper))
|
||||
plan = LayerTransferPlan(
|
||||
request_id="req",
|
||||
transfer_id="tA",
|
||||
layer_name="layer0",
|
||||
sess_idx=0,
|
||||
transfer_local_offsets=[],
|
||||
transfer_remote_offsets=[],
|
||||
transfer_sizes=[],
|
||||
)
|
||||
|
||||
assert writer._do_layer_write(plan, ["session"]) == []
|
||||
wrapper.write_remote_data.assert_not_called()
|
||||
wrapper.write_remote_data_single.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("local_state", [[], [1, 2]])
|
||||
def test_hybrid_write_requires_exactly_one_running_state_slot(local_state):
|
||||
worker = SimpleNamespace(
|
||||
_mamba_blocks_for_layer=lambda layer_name, block_ids: block_ids[1],
|
||||
)
|
||||
writer = make_moriio_writer(worker)
|
||||
task = _write_task("tA", "10.0.0.1")
|
||||
task.layer_name = "kda"
|
||||
task.local_block_ids = [[], local_state]
|
||||
|
||||
with pytest.raises(MoRIIOError, match="one running-state slot"):
|
||||
writer._prepare_mamba_transfer_plans(task, RemoteAllocInfo(block_ids=[[], [9]]))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,253 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for the scheduler-driven heartbeat / lease-renewal system."""
|
||||
|
||||
import time
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
from .utils import create_request, make_nixl_scheduler
|
||||
|
||||
_ENGINE_A = "my-engine-id"
|
||||
|
||||
|
||||
def _sched(kv_lease_duration: int = 30):
|
||||
return make_nixl_scheduler(heartbeat=True, kv_lease_duration=kv_lease_duration)
|
||||
|
||||
|
||||
def _req(request_id: int = 1):
|
||||
return create_request(request_id=request_id, do_remote_prefill=True)
|
||||
|
||||
|
||||
def _worker_stub():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
|
||||
NixlConnectorWorker,
|
||||
)
|
||||
|
||||
w = object.__new__(NixlConnectorWorker)
|
||||
w._reqs_to_send = {}
|
||||
w._lease_extension = 20
|
||||
w._reqs_to_process = set()
|
||||
w.consumer_notification_counts_by_req = {}
|
||||
w.expected_consumer_notifications_by_req = {}
|
||||
w.xfer_stats = MagicMock()
|
||||
return w
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Scheduler: on_new_request
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def test_on_new_request_tracks_and_groups():
|
||||
"""Add two reqs to same engine, one to another; verify grouping."""
|
||||
s = _sched()
|
||||
s.on_new_request(_req(1))
|
||||
s.on_new_request(_req(2))
|
||||
|
||||
assert s._heartbeat_by_engine[_ENGINE_A].req_ids == {"prefill-1", "prefill-2"}
|
||||
info = s._heartbeat_by_engine[_ENGINE_A]
|
||||
assert (info.host, info.port, info.tp_size) == ("my-host", 1234, 1)
|
||||
assert s._heartbeat_req_engine["id-1"] == (_ENGINE_A, "prefill-1")
|
||||
|
||||
# Different engine.
|
||||
r3 = _req(3)
|
||||
r3.kv_transfer_params["remote_engine_id"] = "engine-b"
|
||||
s.on_new_request(r3)
|
||||
assert len(s._heartbeat_by_engine) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"make_req",
|
||||
[
|
||||
lambda: create_request(request_id=2, do_remote_decode=True),
|
||||
lambda: create_request(request_id=3), # no kv_transfer_params
|
||||
],
|
||||
ids=["decode", "plain"],
|
||||
)
|
||||
def test_on_new_request_ignores_non_prefill(make_req):
|
||||
s = _sched()
|
||||
s.on_new_request(make_req())
|
||||
assert len(s._heartbeat_by_engine) == 0
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Scheduler: _stop_heartbeat
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def test_stop_heartbeat_partial_and_full():
|
||||
"""Stop one of two reqs on same engine, then stop the other."""
|
||||
s = _sched()
|
||||
s.on_new_request(_req(1))
|
||||
s.on_new_request(_req(2))
|
||||
|
||||
s._stop_heartbeat("id-1")
|
||||
assert s._heartbeat_by_engine[_ENGINE_A].req_ids == {"prefill-2"}
|
||||
assert "id-1" not in s._heartbeat_req_engine
|
||||
|
||||
s._stop_heartbeat("id-2")
|
||||
assert len(s._heartbeat_by_engine) == 0
|
||||
assert len(s._heartbeat_req_engine) == 0
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Scheduler: build_connector_meta throttling
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def test_build_connector_meta_heartbeat_throttling():
|
||||
# kv_lease_duration=30 => _heartbeat_interval = 30 // 6 = 5
|
||||
s = _sched(kv_lease_duration=30)
|
||||
s.on_new_request(_req(1))
|
||||
|
||||
# Ensure the first call triggers by placing last_heartbeat far in the past.
|
||||
s._last_heartbeat_time = time.perf_counter() - 10
|
||||
meta1 = s.build_connector_meta(MagicMock())
|
||||
assert _ENGINE_A in meta1.heartbeat_by_engine
|
||||
|
||||
# Immediate second call is throttled (< 5s since last).
|
||||
meta2 = s.build_connector_meta(MagicMock())
|
||||
assert len(meta2.heartbeat_by_engine) == 0
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Scheduler: cleanup paths (update_connector_output / request_finished)
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def test_update_connector_output_stops_heartbeat():
|
||||
s = _sched()
|
||||
s.on_new_request(_req(1))
|
||||
|
||||
s.update_connector_output(
|
||||
KVConnectorOutput(
|
||||
finished_sending=None,
|
||||
finished_recving={"id-1"},
|
||||
invalid_block_ids=set(),
|
||||
)
|
||||
)
|
||||
|
||||
assert len(s._heartbeat_by_engine) == 0
|
||||
assert len(s._heartbeat_req_engine) == 0
|
||||
|
||||
|
||||
def test_request_finished_stops_heartbeat():
|
||||
s = _sched()
|
||||
r = _req(1)
|
||||
s.on_new_request(r)
|
||||
|
||||
# Simulate update_state_after_alloc having consumed do_remote_prefill.
|
||||
r.kv_transfer_params["do_remote_prefill"] = False
|
||||
s.request_finished(r, block_ids=())
|
||||
|
||||
assert len(s._heartbeat_by_engine) == 0
|
||||
assert len(s._heartbeat_req_engine) == 0
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Worker: _handle_heartbeat
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def test_handle_heartbeat():
|
||||
w = _worker_stub()
|
||||
far_future = time.perf_counter() + 99999
|
||||
w._reqs_to_send = {"req-a": 100.0, "req-b": far_future}
|
||||
|
||||
before = time.perf_counter()
|
||||
w._handle_heartbeat("req-a,req-b,req-unknown")
|
||||
|
||||
# req-a: pushed forward to ~now+20.
|
||||
assert w._reqs_to_send["req-a"] >= before + 20
|
||||
# req-b: already far out, max() keeps it.
|
||||
assert w._reqs_to_send["req-b"] >= far_future
|
||||
# req-unknown: not added.
|
||||
assert "req-unknown" not in w._reqs_to_send
|
||||
|
||||
|
||||
def test_reaper_reclaims_expired_leases_behind_heartbeated_head(monkeypatch):
|
||||
"""A heartbeated head entry must not strand expired leases behind it.
|
||||
|
||||
Mirrors the stdlib repro in https://github.com/vllm-project/vllm/issues/58222:
|
||||
A is inserted first and kept alive via heartbeats; B and C expire and
|
||||
must still be reaped. The old early-exit scan returned nothing here.
|
||||
"""
|
||||
w = _worker_stub()
|
||||
w._reqs_to_process.update(("A", "B", "C"))
|
||||
# Insertion order is A, B, C. Heartbeats will keep A at the head.
|
||||
w._reqs_to_send = {"A": 30.0, "B": 32.0, "C": 34.0}
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker
|
||||
|
||||
now = {"t": 0.0}
|
||||
monkeypatch.setattr(base_worker.time, "perf_counter", lambda: now["t"])
|
||||
for t in (20.0, 40.0, 60.0, 80.0):
|
||||
now["t"] = t
|
||||
w._handle_heartbeat("A")
|
||||
|
||||
# A was renewed in place: still the dict head, expiry 100.
|
||||
assert next(iter(w._reqs_to_send)) == "A"
|
||||
assert w._reqs_to_send["A"] == pytest.approx(100.0)
|
||||
|
||||
done: set[str] = set()
|
||||
now["t"] = 50.0
|
||||
w._reap_expired_send_leases(done)
|
||||
|
||||
assert done == {"B", "C"}
|
||||
assert list(w._reqs_to_send) == ["A"]
|
||||
assert w._reqs_to_process == {"A"}
|
||||
assert w.xfer_stats.record_kv_expired_req.call_count == 2
|
||||
|
||||
# now == expires is expired (now >= expires): A is due at 100.
|
||||
done_eq: set[str] = set()
|
||||
now["t"] = 100.0
|
||||
w._reap_expired_send_leases(done_eq)
|
||||
assert done_eq == {"A"}
|
||||
assert not w._reqs_to_send
|
||||
assert not w._reqs_to_process
|
||||
assert w.xfer_stats.record_kv_expired_req.call_count == 3
|
||||
|
||||
|
||||
def test_reaper_reclaims_when_now_equals_expiry(monkeypatch):
|
||||
"""The reaper must reclaim on the now == expires boundary."""
|
||||
w = _worker_stub()
|
||||
w._reqs_to_process.add("eq")
|
||||
w._reqs_to_send = {"eq": 50.0}
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker
|
||||
|
||||
monkeypatch.setattr(base_worker.time, "perf_counter", lambda: 50.0)
|
||||
|
||||
done: set[str] = set()
|
||||
w._reap_expired_send_leases(done)
|
||||
|
||||
assert done == {"eq"}
|
||||
assert not w._reqs_to_send
|
||||
assert not w._reqs_to_process
|
||||
w.xfer_stats.record_kv_expired_req.assert_called_once()
|
||||
|
||||
|
||||
def test_reaper_reclaims_shorter_lease_behind_later_deadline(monkeypatch):
|
||||
"""A later-inserted longer TTL must not block an earlier-expiring entry.
|
||||
|
||||
Delete+reinsert on heartbeat cannot restore expiry order in this case
|
||||
(issue #58222), so the reaper must scan the whole map.
|
||||
"""
|
||||
w = _worker_stub()
|
||||
w._reqs_to_process.update(("X", "Y"))
|
||||
w._reqs_to_send = {"X": 55.0, "Y": 46.0}
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker
|
||||
|
||||
monkeypatch.setattr(base_worker.time, "perf_counter", lambda: 50.0)
|
||||
|
||||
done: set[str] = set()
|
||||
w._reap_expired_send_leases(done)
|
||||
|
||||
assert done == {"Y"}
|
||||
assert list(w._reqs_to_send) == ["X"]
|
||||
assert w._reqs_to_process == {"X"}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,977 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import copy
|
||||
from dataclasses import replace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.v1.metrics.stats import KV_FETCH_STAGES
|
||||
from vllm.v1.outputs import (
|
||||
EMPTY_MODEL_RUNNER_OUTPUT,
|
||||
KVConnectorOutput,
|
||||
ModelRunnerOutput,
|
||||
)
|
||||
from vllm.v1.request import FinishReason, RequestStatus
|
||||
|
||||
from .utils import (
|
||||
assert_scheduler_empty,
|
||||
create_model_runner_output,
|
||||
create_request,
|
||||
create_scheduler,
|
||||
create_vllm_config,
|
||||
make_kv_cache_config,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
|
||||
def _num_waiting_requests(scheduler) -> int:
|
||||
return len(scheduler.waiting) + len(scheduler.kv_holding_waiting)
|
||||
|
||||
|
||||
def _kv_fetch_stages(scheduler) -> tuple[int, ...]:
|
||||
"""(waiting_to_start, in_progress, completed_waiting) request counts."""
|
||||
return tuple(scheduler._kv_fetch_counts[s] for s in KV_FETCH_STAGES)
|
||||
|
||||
|
||||
def test_basic_lifecycle():
|
||||
"""Test lifecycle of a remote prefill."""
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
|
||||
# 2 Full Blocks and 1 Half Block.
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
NUM_EXTERNAL_FULL_BLOCKS = 2
|
||||
NUM_TOKENS = int(BLOCK_SIZE * (NUM_EXTERNAL_FULL_BLOCKS + 0.5))
|
||||
START_FREE_BLOCK_QUEUE_SIZE = (
|
||||
scheduler.kv_cache_manager.block_pool.free_block_queue.num_free_blocks
|
||||
)
|
||||
|
||||
request = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
|
||||
scheduler.add_request(request)
|
||||
request_id = request.request_id
|
||||
assert _kv_fetch_stages(scheduler) == (1, 0, 0)
|
||||
|
||||
# STEP (1):
|
||||
# (1a): schedule()
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert _kv_fetch_stages(scheduler) == (0, 1, 0)
|
||||
|
||||
# Nothing running and empty scheduler output.
|
||||
assert len(scheduler.running) == 0
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 0
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 0
|
||||
assert len(scheduler_output.num_scheduled_tokens) == 0
|
||||
assert scheduler_output.total_num_scheduled_tokens == 0
|
||||
|
||||
# Req waiting for KVs with no computed/scheduled toks ...
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert request in scheduler.kv_holding_waiting
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert request.num_computed_tokens == NUM_TOKENS
|
||||
|
||||
# ... but should have (uncached) blocks allocated to it.
|
||||
block_pool = scheduler.kv_cache_manager.block_pool
|
||||
assert block_pool.free_block_queue.num_free_blocks < START_FREE_BLOCK_QUEUE_SIZE
|
||||
assert len(block_pool.cached_block_hash_to_block) == 0
|
||||
blocks = scheduler.kv_cache_manager.coordinator.single_type_managers[
|
||||
0
|
||||
].req_to_blocks[request_id]
|
||||
for block in blocks:
|
||||
assert block._block_hash is None
|
||||
|
||||
# (1b): forward()
|
||||
model_runner_output = EMPTY_MODEL_RUNNER_OUTPUT
|
||||
|
||||
# (1c): update_from_output()
|
||||
engine_core_outputs = scheduler.update_from_output(
|
||||
scheduler_output, model_runner_output
|
||||
)
|
||||
assert not engine_core_outputs or not engine_core_outputs[0].outputs
|
||||
|
||||
# STEP (2):
|
||||
# (2a): schedule(): nothing happens!
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert len(scheduler.running) == 0
|
||||
|
||||
# (2b): forward(): request finishes recv.
|
||||
model_runner_output = copy.deepcopy(EMPTY_MODEL_RUNNER_OUTPUT)
|
||||
model_runner_output.kv_connector_output = KVConnectorOutput(
|
||||
finished_recving={request_id}
|
||||
)
|
||||
|
||||
# (2c): update_from_output():
|
||||
engine_core_outputs = scheduler.update_from_output(
|
||||
scheduler_output, model_runner_output
|
||||
)
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert request_id in scheduler.finished_recving_kv_req_ids
|
||||
assert _kv_fetch_stages(scheduler) == (0, 0, 1)
|
||||
|
||||
# STEP (3):
|
||||
# (3a): schedule(): this should actually schedule.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 1
|
||||
assert _kv_fetch_stages(scheduler) == (0, 0, 0)
|
||||
|
||||
# Confirm the block are actually allocated.
|
||||
num_hashed_blocks = 0
|
||||
blocks = scheduler.kv_cache_manager.coordinator.single_type_managers[
|
||||
0
|
||||
].req_to_blocks[request_id]
|
||||
for block in blocks:
|
||||
assert block.ref_cnt == 1
|
||||
num_hashed_blocks += 1 if block._block_hash is not None else 0
|
||||
assert num_hashed_blocks == NUM_EXTERNAL_FULL_BLOCKS
|
||||
|
||||
# Confirm the rest of the prompt is scheduled in this step.
|
||||
scheduled_req = scheduler_output.scheduled_new_reqs[0]
|
||||
num_scheduled_tokens = scheduler_output.num_scheduled_tokens[request_id]
|
||||
num_computed_tokens = scheduled_req.num_computed_tokens
|
||||
total_prompt_tokens = len(scheduled_req.prompt_token_ids)
|
||||
assert num_scheduled_tokens == total_prompt_tokens - num_computed_tokens
|
||||
|
||||
# (3b): execute_model()
|
||||
model_runner_output = create_model_runner_output([request])
|
||||
# (3c): update_from_output()
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# Step (4): Hit EOS.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output([request], use_eos=True)
|
||||
engine_core_outputs = scheduler.update_from_output(
|
||||
scheduler_output, model_runner_output
|
||||
)
|
||||
scheduler.schedule()
|
||||
|
||||
outputs = engine_core_outputs[0].outputs
|
||||
assert len(outputs) == 1
|
||||
output = outputs[0]
|
||||
assert output.finish_reason == FinishReason.STOP
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
def test_interleaved_lifecycle():
|
||||
"""Test Remote Prefills Work Well With Other Requests."""
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
|
||||
# 2 Full Blocks and 1 Half Block.
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
NUM_EXTERNAL_FULL_BLOCKS = 2
|
||||
NUM_TOKENS = int(BLOCK_SIZE * (NUM_EXTERNAL_FULL_BLOCKS + 0.5))
|
||||
|
||||
request_remote = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
request_local_a = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
)
|
||||
request_local_b = create_request(
|
||||
request_id=3,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
)
|
||||
|
||||
# STEP 1: Regular request is running.
|
||||
scheduler.add_request(request_local_a)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 1
|
||||
|
||||
model_runner_output = create_model_runner_output([request_local_a])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# STEP 2: Add a local and remote request.
|
||||
scheduler.add_request(request_local_b)
|
||||
scheduler.add_request(request_remote)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 2
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 1
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 1
|
||||
|
||||
model_runner_output = create_model_runner_output([request_local_a, request_local_b])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# STEP 3: continue running, KVs not arrived yet.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 2
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 0
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 2
|
||||
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_local_a, request_local_b]
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 2
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 0
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 2
|
||||
|
||||
# STEP 4: KVs arrive.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 2
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 0
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 2
|
||||
|
||||
model_runner_output = create_model_runner_output(
|
||||
[request_local_a, request_local_b], finished_recving={request_remote.request_id}
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# STEP 5: RECVed KVs are sent to ModelRunner.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 3
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
assert len(scheduler_output.scheduled_new_reqs) == 1
|
||||
assert scheduler_output.scheduled_cached_reqs.num_reqs == 2
|
||||
|
||||
model_runner_output = create_model_runner_output(
|
||||
[request_local_a, request_local_b, request_remote]
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# STEP 6: Hit EOS and free.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
[request_local_a, request_local_b, request_remote],
|
||||
use_eos=True,
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
scheduler.schedule()
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
def test_no_spurious_prefix_caching():
|
||||
"""With P/D, blocks can be allocated but uncomputed for
|
||||
multiple engine steps. This test confirms that we do
|
||||
not accidentally have cache hits against uncomputed
|
||||
blocks.
|
||||
"""
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
|
||||
# 2 and a half full external blocks.
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
NUM_EXTERNAL_FULL_BLOCKS = 2
|
||||
NUM_TOKENS = int(BLOCK_SIZE * (NUM_EXTERNAL_FULL_BLOCKS + 0.5))
|
||||
|
||||
# Both of these requests have prompts like [1,1,1,1,1, ...]
|
||||
request_remote = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
common_prefix_len=NUM_TOKENS,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
|
||||
request_local = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
common_prefix_len=NUM_TOKENS,
|
||||
do_remote_prefill=False,
|
||||
)
|
||||
|
||||
# Schedule the remote prefill request. This should not
|
||||
# cause any blocks to be cached.
|
||||
scheduler.add_request(request_remote)
|
||||
scheduler_output = scheduler.schedule()
|
||||
scheduler.update_from_output(scheduler_output, EMPTY_MODEL_RUNNER_OUTPUT)
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Schedule the local prefill request. This should
|
||||
# cause blocks to be cached, but separately from
|
||||
scheduler.add_request(request_local)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
local_blocks = scheduler.kv_cache_manager.coordinator.single_type_managers[
|
||||
0
|
||||
].req_to_blocks[request_local.request_id]
|
||||
remote_blocks = scheduler.kv_cache_manager.coordinator.single_type_managers[
|
||||
0
|
||||
].req_to_blocks[request_remote.request_id]
|
||||
|
||||
# Local should have cached blocks (but not all due to preallocate).
|
||||
num_hashed_blocks = 0
|
||||
for block in local_blocks:
|
||||
assert block.ref_cnt == 1
|
||||
num_hashed_blocks += 1 if block._block_hash is not None else 0
|
||||
assert num_hashed_blocks > 0
|
||||
|
||||
# Remote blocks should not be cached.
|
||||
for block in remote_blocks:
|
||||
assert block.ref_cnt == 1
|
||||
assert block._block_hash is None
|
||||
|
||||
|
||||
def test_full_block_prompt():
|
||||
"""Test that we handle a prompt that is the full block size."""
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
|
||||
# 2 Full Blocks and 1 Half Block.
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
NUM_EXTERNAL_FULL_BLOCKS = 2
|
||||
NUM_TOKENS = int(BLOCK_SIZE * NUM_EXTERNAL_FULL_BLOCKS)
|
||||
|
||||
request = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
|
||||
scheduler.add_request(request)
|
||||
request_id = request.request_id
|
||||
|
||||
# STEP (1): Initialize a recv.
|
||||
scheduler_output = scheduler.schedule()
|
||||
# All blocks should be allocated.
|
||||
num_blocks = len(
|
||||
scheduler.kv_cache_manager.coordinator.single_type_managers[0].req_to_blocks[
|
||||
request_id
|
||||
]
|
||||
)
|
||||
assert num_blocks == NUM_EXTERNAL_FULL_BLOCKS
|
||||
model_runner_output = EMPTY_MODEL_RUNNER_OUTPUT
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# # STEP (2): Recv.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = copy.deepcopy(EMPTY_MODEL_RUNNER_OUTPUT)
|
||||
model_runner_output.kv_connector_output = KVConnectorOutput(
|
||||
finished_recving={request_id}
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert request_id in scheduler.finished_recving_kv_req_ids
|
||||
|
||||
# # STEP (3): Run as usual.
|
||||
scheduler_output = scheduler.schedule()
|
||||
|
||||
# We need to recompute the final token of the prompt to generate
|
||||
# the first new token, so we should not have a new block.
|
||||
num_blocks = len(
|
||||
scheduler.kv_cache_manager.coordinator.single_type_managers[0].req_to_blocks[
|
||||
request_id
|
||||
]
|
||||
)
|
||||
assert num_blocks == NUM_EXTERNAL_FULL_BLOCKS
|
||||
assert scheduler_output.scheduled_new_reqs[0].num_computed_tokens == NUM_TOKENS - 1
|
||||
assert scheduler_output.num_scheduled_tokens[request_id] == 1
|
||||
|
||||
model_runner_output = create_model_runner_output([request])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
|
||||
# # Step (4): Hit EOS.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output([request], use_eos=True)
|
||||
engine_core_outputs = scheduler.update_from_output(
|
||||
scheduler_output, model_runner_output
|
||||
)
|
||||
scheduler.schedule()
|
||||
|
||||
outputs = engine_core_outputs[0].outputs
|
||||
assert len(outputs) == 1
|
||||
output = outputs[0]
|
||||
assert output.finish_reason == FinishReason.STOP
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
def test_cannot_schedule_after_recv():
|
||||
"""Test that we can handle no schedule after recv due to not
|
||||
enough remaining KV blocks.
|
||||
"""
|
||||
# NOTE: the KVCacheManager will use 1 null block.
|
||||
# So there are 5 total working blocks.
|
||||
TOTAL_NUM_BLOCKS = 6
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=TOTAL_NUM_BLOCKS)
|
||||
|
||||
# Prime the KVCache.
|
||||
NUM_PROMPT_BLOCKS = 2
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
# Prompt will use 2 blocks + 1 block after we schedule.
|
||||
NUM_TOKENS_LOCAL = int(BLOCK_SIZE * NUM_PROMPT_BLOCKS)
|
||||
NUM_TOKENS_REMOTE = int(BLOCK_SIZE * NUM_PROMPT_BLOCKS)
|
||||
|
||||
request_normal = create_request(
|
||||
request_id=1, block_size=BLOCK_SIZE, num_tokens=NUM_TOKENS_LOCAL
|
||||
)
|
||||
request_remote = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS_REMOTE,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
|
||||
# STEP 1: 3 blocks are in use (2 for prompt, 1 for decode).
|
||||
scheduler.add_request(request_normal)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_normal])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
|
||||
# Step 2: 5 blocks are in use (2 new for remote blocks).
|
||||
scheduler.add_request(request_remote)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_normal])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 3: finish recving (5 blocks in use)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_normal], finished_recving={request_remote.request_id}
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 4: try to schedule, remote request is put to running list
|
||||
# because the transfer is completed.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_normal, request_remote]
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 2
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
|
||||
# Step 5: Remote request will be put back to waiting list
|
||||
# because it needs new block to hold generated token.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_normal])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 6: finish the request, free it.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_normal], use_eos=True
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 0
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 7: now we can schedule (with 2 blocks computed),
|
||||
# request is retrieved from preempted list.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_remote])
|
||||
# V2 emits a resumed (previously preempted) request as a NewRequestData
|
||||
# rather than a cached request.
|
||||
if scheduler.use_v2_model_runner:
|
||||
num_computed = scheduler_output.scheduled_new_reqs[0].num_computed_tokens
|
||||
else:
|
||||
cached = scheduler_output.scheduled_cached_reqs
|
||||
num_computed = cached.num_computed_tokens[0]
|
||||
assert num_computed == NUM_PROMPT_BLOCKS * BLOCK_SIZE
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
|
||||
# Step 8: free everything.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_remote], use_eos=True
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
_ = scheduler.schedule()
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
def test_cannot_recv():
|
||||
"""Test that we can handle no schedule KV block transfer due to not
|
||||
enough remaining KV blocks.
|
||||
"""
|
||||
# NOTE: the KVCacheManager will use 1 null block.
|
||||
# So there are 5 total working blocks.
|
||||
TOTAL_NUM_BLOCKS = 6
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=TOTAL_NUM_BLOCKS)
|
||||
|
||||
# Prime the KVCache.
|
||||
NUM_PROMPT_BLOCKS = 2
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
# Prompt will use 2 blocks + 1 block after we schedule.
|
||||
NUM_TOKENS_LOCAL = int(BLOCK_SIZE * NUM_PROMPT_BLOCKS)
|
||||
NUM_TOKENS_REMOTE = int(BLOCK_SIZE * (NUM_PROMPT_BLOCKS + 0.5))
|
||||
|
||||
request_normal = create_request(
|
||||
request_id=1, block_size=BLOCK_SIZE, num_tokens=NUM_TOKENS_LOCAL
|
||||
)
|
||||
request_remote = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=NUM_TOKENS_REMOTE,
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
|
||||
# STEP 1: 3 blocks are in use (2 for prompt, 1 for decode).
|
||||
scheduler.add_request(request_normal)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_normal])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
|
||||
# Step 2: 3 blocks are in use,
|
||||
# need 3 new for remote blocks but only 2 are available.
|
||||
scheduler.add_request(request_remote)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_normal])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
# Should not have KV transfer in progress.
|
||||
assert request_remote.status != RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
|
||||
# Step 3: finish the request, free it.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_normal], use_eos=True
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 0
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 4: now we can initiate KV transfer (with 2 blocks computed).
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 0
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert request_remote.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
|
||||
# Step 5: finish recving (5 blocks in use)
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[], finished_recving={request_remote.request_id}
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 0
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
|
||||
# Step 6: schedule remote request
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(reqs=[request_remote])
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
assert len(scheduler.running) == 1
|
||||
assert _num_waiting_requests(scheduler) == 0
|
||||
|
||||
# Step 7: free everything.
|
||||
scheduler_output = scheduler.schedule()
|
||||
model_runner_output = create_model_runner_output(
|
||||
reqs=[request_remote], use_eos=True
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, model_runner_output)
|
||||
_ = scheduler.schedule()
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
def test_kv_fetch_stages_cleared_on_abort():
|
||||
vllm_config = create_vllm_config()
|
||||
scheduler = create_scheduler(vllm_config)
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
request = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=int(BLOCK_SIZE * 2.5),
|
||||
do_remote_prefill=True,
|
||||
)
|
||||
scheduler.add_request(request)
|
||||
scheduler.schedule()
|
||||
assert _kv_fetch_stages(scheduler) == (0, 1, 0)
|
||||
|
||||
scheduler.finish_requests(request.request_id, RequestStatus.FINISHED_ABORTED)
|
||||
assert _kv_fetch_stages(scheduler) == (0, 0, 0)
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_scheduler.current_platform"
|
||||
)
|
||||
def test_p_side_chunked_prefill_mamba(mock_platform):
|
||||
"""P-side integration: Mamba N-1 truncation + chunked prefill completes.
|
||||
|
||||
A 64-token P-side request is truncated to 63 by the N-1 fix, then
|
||||
chunked into two prefill steps (32 + 31) and finishes with
|
||||
LENGTH_CAPPED because max_tokens is set to 1.
|
||||
"""
|
||||
mock_platform.device_type = "cpu"
|
||||
|
||||
BATCH_SIZE = 32
|
||||
NUM_TOKENS = 64
|
||||
BLOCK_SIZE = 16
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
max_num_batched_tokens=BATCH_SIZE,
|
||||
block_size=BLOCK_SIZE,
|
||||
)
|
||||
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
# mamba_cache_mode "none" only runs without prefix caching.
|
||||
vllm_config.cache_config.enable_prefix_caching = False
|
||||
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size=BLOCK_SIZE,
|
||||
mamba_enabled=True,
|
||||
num_blocks=10000,
|
||||
)
|
||||
|
||||
scheduler = create_scheduler(vllm_config, kv_cache_config=kv_cache_config)
|
||||
|
||||
request = create_request(
|
||||
num_tokens=NUM_TOKENS,
|
||||
do_remote_decode=True,
|
||||
block_size=BLOCK_SIZE,
|
||||
)
|
||||
request.max_tokens = 128
|
||||
scheduler.add_request(request)
|
||||
request_id = request.request_id
|
||||
|
||||
# ── Step 1: first chunk ──
|
||||
scheduler_output = scheduler.schedule()
|
||||
|
||||
assert len(request.prompt_token_ids) == NUM_TOKENS - 1
|
||||
assert request.max_tokens == 1
|
||||
assert scheduler_output.num_scheduled_tokens[request_id] == BATCH_SIZE
|
||||
assert request.num_computed_tokens == BATCH_SIZE
|
||||
|
||||
# Model returns no tokens for intermediate prefill chunk
|
||||
intermediate_output = ModelRunnerOutput(
|
||||
req_ids=[request.request_id],
|
||||
req_id_to_index={request.request_id: 0},
|
||||
sampled_token_ids=[[]],
|
||||
)
|
||||
scheduler.update_from_output(scheduler_output, intermediate_output)
|
||||
|
||||
# ── Step 2: remaining chunk ──
|
||||
scheduler_output = scheduler.schedule()
|
||||
|
||||
remaining = NUM_TOKENS - 1 - BATCH_SIZE # 31
|
||||
assert scheduler_output.num_scheduled_tokens[request_id] == remaining
|
||||
assert request.num_computed_tokens == NUM_TOKENS - 1
|
||||
|
||||
# Prefill complete: model generates 1 decode token
|
||||
final_output = create_model_runner_output([request])
|
||||
engine_core_outputs = scheduler.update_from_output(scheduler_output, final_output)
|
||||
|
||||
# max_tokens=1 → request finishes with LENGTH
|
||||
outputs = engine_core_outputs[0].outputs
|
||||
assert len(outputs) == 1
|
||||
assert outputs[0].finish_reason == FinishReason.LENGTH
|
||||
|
||||
|
||||
def test_async_load_reserves_blocks_for_inflight():
|
||||
"""A second async KV-connector load is not admitted if its initial
|
||||
allocation would consume blocks reserved for an already in-flight sequence.
|
||||
|
||||
req_a gets a 1-block prefix (full sequence = 4 blocks), reserving 3 more.
|
||||
req_b would need a 4-block initial allocation, but only
|
||||
(free - req_a's 3-block reservation) = 3 blocks are available to it, so it is
|
||||
held back in WAITING (holding no blocks) rather than wedging req_a.
|
||||
"""
|
||||
vllm_config = create_vllm_config()
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=8) # usable = 7
|
||||
|
||||
req_a = create_request(
|
||||
request_id=1,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=BLOCK_SIZE * 4,
|
||||
do_remote_prefill=True,
|
||||
num_remote_blocks=1,
|
||||
)
|
||||
req_b = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=BLOCK_SIZE * 5,
|
||||
do_remote_prefill=True,
|
||||
num_remote_blocks=1,
|
||||
)
|
||||
scheduler.add_request(req_a)
|
||||
scheduler.add_request(req_b)
|
||||
|
||||
# Partial external matches: req_a loads 1 block, req_b loads 4 blocks.
|
||||
with patch.object(
|
||||
scheduler.connector,
|
||||
"get_num_new_matched_tokens",
|
||||
side_effect=[(BLOCK_SIZE, True), (BLOCK_SIZE * 4, True)],
|
||||
):
|
||||
scheduler.schedule()
|
||||
|
||||
assert req_a.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert req_b.status == RequestStatus.WAITING
|
||||
|
||||
req_to_blocks = scheduler.kv_cache_manager.coordinator.single_type_managers[
|
||||
0
|
||||
].req_to_blocks
|
||||
assert req_a.request_id in req_to_blocks
|
||||
assert req_b.request_id not in req_to_blocks
|
||||
|
||||
|
||||
def test_async_loads_both_admitted_when_pool_fits():
|
||||
"""Sanity: with a pool large enough, the reservation gate admits both async
|
||||
loads (it is not over-conservative)."""
|
||||
vllm_config = create_vllm_config()
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=64)
|
||||
|
||||
reqs = [
|
||||
create_request(
|
||||
request_id=i,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=BLOCK_SIZE * 5,
|
||||
do_remote_prefill=True,
|
||||
num_remote_blocks=1,
|
||||
)
|
||||
for i in (1, 2)
|
||||
]
|
||||
for req in reqs:
|
||||
scheduler.add_request(req)
|
||||
|
||||
with patch.object(
|
||||
scheduler.connector,
|
||||
"get_num_new_matched_tokens",
|
||||
side_effect=[(BLOCK_SIZE, True), (BLOCK_SIZE, True)],
|
||||
):
|
||||
scheduler.schedule()
|
||||
|
||||
for req in reqs:
|
||||
assert req.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("swa_enabled", "block_size", "num_spec_tokens", "num_blocks"),
|
||||
[(False, 16, 3, 8), (True, 16, 3, 17), (True, 64, 31, 40)],
|
||||
ids=["single-group", "multiple-groups", "different-block-sizes"],
|
||||
)
|
||||
def test_async_load_reserves_blocks_for_promotion_margin(
|
||||
swa_enabled, block_size, num_spec_tokens, num_blocks
|
||||
):
|
||||
"""Async loads must leave enough blocks for promotion in every cache group.
|
||||
|
||||
Otherwise two loads can fill the pool and prevent the head from being
|
||||
promoted, with nothing running to free blocks and break the deadlock.
|
||||
"""
|
||||
vllm_config = create_vllm_config(
|
||||
block_size=block_size,
|
||||
num_speculative_tokens=num_spec_tokens,
|
||||
disable_hybrid_kv_cache_manager=False,
|
||||
)
|
||||
hash_block_size = 16
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
hash_block_size, swa_enabled=swa_enabled, sw_size=4096, num_blocks=num_blocks
|
||||
)
|
||||
full_group = kv_cache_config.kv_cache_groups[0]
|
||||
full_group.kv_cache_spec = replace(full_group.kv_cache_spec, block_size=block_size)
|
||||
if swa_enabled:
|
||||
sliding_group = kv_cache_config.kv_cache_groups[-1]
|
||||
sliding_group.kv_cache_spec = replace(
|
||||
sliding_group.kv_cache_spec,
|
||||
page_size_padded=full_group.kv_cache_spec.page_size_bytes,
|
||||
)
|
||||
scheduler = create_scheduler(
|
||||
vllm_config,
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_config=kv_cache_config,
|
||||
hash_block_size=hash_block_size,
|
||||
)
|
||||
|
||||
req_a = create_request(
|
||||
request_id=1,
|
||||
block_size=hash_block_size,
|
||||
num_tokens=block_size * 4,
|
||||
do_remote_prefill=True,
|
||||
max_tokens=1,
|
||||
)
|
||||
req_b = create_request(
|
||||
request_id=2,
|
||||
block_size=hash_block_size,
|
||||
num_tokens=block_size * 3,
|
||||
do_remote_prefill=True,
|
||||
max_tokens=1,
|
||||
)
|
||||
scheduler.add_request(req_a)
|
||||
scheduler.add_request(req_b)
|
||||
|
||||
# Both get a full external hit, so each would hold its whole prompt.
|
||||
with patch.object(
|
||||
scheduler.connector,
|
||||
"get_num_new_matched_tokens",
|
||||
side_effect=[(block_size * 4, True), (block_size * 3, True)],
|
||||
):
|
||||
scheduler.schedule()
|
||||
|
||||
assert req_a.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert req_b.status == RequestStatus.WAITING
|
||||
assert not any(scheduler.kv_cache_manager.get_block_ids(req_b.request_id))
|
||||
|
||||
# req_a's load lands: it must be promotable and actually get scheduled.
|
||||
scheduler.update_from_output(
|
||||
scheduler.schedule(),
|
||||
create_model_runner_output([], finished_recving={req_a.request_id}),
|
||||
)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_a.request_id] > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mamba_cache_mode", "mamba_block_size", "num_blocks"),
|
||||
[("none", 128, 18), ("align", 16, 18)],
|
||||
)
|
||||
def test_async_load_does_not_double_reserve_mamba_spec_blocks(
|
||||
mamba_cache_mode, mamba_block_size, num_blocks
|
||||
):
|
||||
"""Two hybrid loads fit when Mamba's speculative states are counted once."""
|
||||
block_size = 16
|
||||
num_spec_tokens = 3
|
||||
vllm_config = create_vllm_config(
|
||||
block_size=mamba_block_size,
|
||||
max_model_len=128,
|
||||
num_speculative_tokens=num_spec_tokens,
|
||||
disable_hybrid_kv_cache_manager=False,
|
||||
)
|
||||
vllm_config.cache_config.mamba_cache_mode = mamba_cache_mode
|
||||
vllm_config.cache_config.enable_prefix_caching = mamba_cache_mode == "align"
|
||||
kv_cache_config = make_kv_cache_config(
|
||||
block_size,
|
||||
mamba_enabled=True,
|
||||
mamba_cache_mode=mamba_cache_mode,
|
||||
num_blocks=num_blocks,
|
||||
)
|
||||
mamba_group = kv_cache_config.kv_cache_groups[-1]
|
||||
mamba_group.kv_cache_spec = replace(
|
||||
mamba_group.kv_cache_spec,
|
||||
block_size=mamba_block_size,
|
||||
num_speculative_blocks=num_spec_tokens,
|
||||
)
|
||||
scheduler = create_scheduler(
|
||||
vllm_config,
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_config=kv_cache_config,
|
||||
hash_block_size=block_size,
|
||||
)
|
||||
reqs = [
|
||||
create_request(
|
||||
request_id=i,
|
||||
block_size=block_size,
|
||||
num_tokens=num_tokens,
|
||||
do_remote_prefill=True,
|
||||
max_tokens=1,
|
||||
)
|
||||
for i, num_tokens in enumerate((64, 48), 1)
|
||||
]
|
||||
for req in reqs:
|
||||
scheduler.add_request(req)
|
||||
|
||||
with patch.object(
|
||||
scheduler.connector,
|
||||
"get_num_new_matched_tokens",
|
||||
side_effect=[(req.num_tokens, True) for req in reqs],
|
||||
):
|
||||
scheduler.schedule()
|
||||
|
||||
assert all(req.status == RequestStatus.WAITING_FOR_REMOTE_KVS for req in reqs)
|
||||
scheduler.update_from_output(
|
||||
scheduler.schedule(),
|
||||
create_model_runner_output(
|
||||
[], finished_recving={req.request_id for req in reqs}
|
||||
),
|
||||
)
|
||||
output = scheduler.schedule()
|
||||
for req in reqs:
|
||||
assert req.status == RequestStatus.RUNNING
|
||||
assert output.num_scheduled_tokens[req.request_id] > 0
|
||||
|
||||
|
||||
def test_deferred_lookup_does_not_block_parked_load():
|
||||
"""A request with a deferred connector lookup must not strand an async
|
||||
load queued behind it.
|
||||
|
||||
req_a's lookup is deferred (connector returns None), so it is parked in
|
||||
waiting holding no blocks; req_b is then admitted as an async
|
||||
load holding most of the pool. Once req_a's lookup resolves it cannot
|
||||
allocate, and the waiting scan stops at it every step. The parked load
|
||||
must still be promotable: it lives in the KV-holding queue
|
||||
that is drained first, so it runs, finishes, and frees its blocks for
|
||||
req_a.
|
||||
"""
|
||||
vllm_config = create_vllm_config()
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=8) # usable = 7
|
||||
|
||||
req_a = create_request(
|
||||
request_id=1, block_size=BLOCK_SIZE, num_tokens=BLOCK_SIZE * 4, max_tokens=1
|
||||
)
|
||||
req_b = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=BLOCK_SIZE * 5,
|
||||
do_remote_prefill=True,
|
||||
max_tokens=1,
|
||||
)
|
||||
scheduler.add_request(req_a)
|
||||
scheduler.add_request(req_b)
|
||||
|
||||
deferrals = [(None, False)]
|
||||
|
||||
def lookup(request, num_computed_tokens):
|
||||
if request is req_b:
|
||||
return BLOCK_SIZE * 5, True
|
||||
return deferrals.pop() if deferrals else (0, False)
|
||||
|
||||
with patch.object(
|
||||
scheduler.connector, "get_num_new_matched_tokens", side_effect=lookup
|
||||
):
|
||||
# Step 1: req_a's lookup is deferred; req_b is admitted as an async
|
||||
# load holding 5 of 7 usable blocks.
|
||||
scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.WAITING
|
||||
assert req_b.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
|
||||
# req_a's lookup resolves (no hit) while req_b's transfer is in
|
||||
# flight; req_a needs 4 blocks but only 2 are free, so the waiting
|
||||
# scan stops at it. req_b's transfer then finishes.
|
||||
scheduler.update_from_output(
|
||||
scheduler.schedule(),
|
||||
create_model_runner_output([], finished_recving={req_b.request_id}),
|
||||
)
|
||||
|
||||
# req_b must still be reached, promoted, and scheduled despite the
|
||||
# scan stopping at req_a.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_b.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_b.request_id] > 0
|
||||
|
||||
# req_b finishes and frees its blocks; now req_a fits and runs.
|
||||
scheduler.update_from_output(
|
||||
scheduler_output, create_model_runner_output([req_b])
|
||||
)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_a.request_id] > 0
|
||||
@@ -1,149 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for SimpleCPUOffloadConnector-level behavior."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.v1.kv_connector.unit.utils import create_vllm_config
|
||||
from tests.v1.simple_kv_offload.test_scheduler import (
|
||||
_BYTES_PER_BLOCK,
|
||||
BLOCK_SIZE,
|
||||
DTYPE,
|
||||
HEAD_SIZE,
|
||||
NUM_KV_HEADS,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
|
||||
SimpleCPUOffloadConnector,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
)
|
||||
|
||||
|
||||
def _make_kv_cache_config(num_blocks: int = 16) -> KVCacheConfig:
|
||||
fa_layers = ["layer0"]
|
||||
spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
groups = [KVCacheGroupSpec(fa_layers, spec)]
|
||||
size = _BYTES_PER_BLOCK * num_blocks
|
||||
tensors = [
|
||||
KVCacheTensor(
|
||||
size=size,
|
||||
layers=fa_layers,
|
||||
layer_stride=size,
|
||||
block_stride=_BYTES_PER_BLOCK,
|
||||
)
|
||||
]
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=tensors,
|
||||
kv_cache_groups=groups,
|
||||
)
|
||||
|
||||
|
||||
def _make_connector(
|
||||
extra_config: dict | None = None,
|
||||
num_gpu_blocks: int = 16,
|
||||
cpu_bytes: int = _BYTES_PER_BLOCK * 8,
|
||||
) -> SimpleCPUOffloadConnector:
|
||||
kv_cache_config = _make_kv_cache_config(num_gpu_blocks)
|
||||
config_dict = {
|
||||
"cpu_bytes_to_use": cpu_bytes,
|
||||
}
|
||||
if extra_config:
|
||||
config_dict.update(extra_config)
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="SimpleCPUOffloadConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config=config_dict,
|
||||
)
|
||||
connector = SimpleCPUOffloadConnector(
|
||||
vllm_config=vllm_config,
|
||||
role=KVConnectorRole.SCHEDULER,
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
return connector
|
||||
|
||||
|
||||
def test_disk_mode_rejects_non_positive_capacity() -> None:
|
||||
"""Disk mode with disk_capacity_bytes <= 0 raises ValueError.
|
||||
|
||||
Without this guard, the worker operates in disk mode but the scheduler
|
||||
classifies events as MEDIUM_CPU instead of MEDIUM_STORAGE, silently
|
||||
mislabeling events.
|
||||
"""
|
||||
with pytest.raises(ValueError, match="disk_capacity_bytes > 0"):
|
||||
_make_connector(
|
||||
extra_config={
|
||||
"kv_offload_backend": "disk",
|
||||
"disk_path": "/tmp/fake",
|
||||
"disk_capacity_bytes": 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _make_ring_kv_cache_config(num_blocks: int = 16) -> KVCacheConfig:
|
||||
"""A paged full-attention group beside a per-request ring group."""
|
||||
full = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
ring = CircularBufferSpec(
|
||||
block_size=6, num_kv_heads=1, head_size=32, head_size_v=0, dtype=DTYPE
|
||||
)
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=_BYTES_PER_BLOCK * num_blocks,
|
||||
layers=["attn"],
|
||||
layer_stride=_BYTES_PER_BLOCK * num_blocks,
|
||||
block_stride=_BYTES_PER_BLOCK,
|
||||
),
|
||||
KVCacheTensor(
|
||||
size=ring.page_size_bytes * num_blocks,
|
||||
layers=["ring"],
|
||||
layer_stride=ring.page_size_bytes * num_blocks,
|
||||
block_stride=ring.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["attn"], full),
|
||||
KVCacheGroupSpec(["ring"], ring),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_ring_scratch_group_is_accepted_and_never_offloaded() -> None:
|
||||
"""The ring group's capacity is not a token granularity, it holds no
|
||||
hashed blocks, and it never participates in CPU hits."""
|
||||
vllm_config = create_vllm_config(
|
||||
kv_connector="SimpleCPUOffloadConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"cpu_bytes_to_use": _BYTES_PER_BLOCK * 8},
|
||||
)
|
||||
connector = SimpleCPUOffloadConnector(
|
||||
vllm_config=vllm_config,
|
||||
role=KVConnectorRole.SCHEDULER,
|
||||
kv_cache_config=_make_ring_kv_cache_config(),
|
||||
)
|
||||
scheduler = connector.scheduler_manager
|
||||
assert scheduler.fa_gidx == 0
|
||||
cpu_groups = scheduler.cpu_kv_cache_config.kv_cache_groups
|
||||
assert [g.kv_cache_spec.prefix_cacheable for g in cpu_groups] == [True, False]
|
||||
# Only the paged group takes part in CPU-side hit lookup.
|
||||
attention_groups = scheduler.cpu_coordinator.attention_groups
|
||||
assert [g.group_ids for g in attention_groups] == [[0]]
|
||||
@@ -1,466 +0,0 @@
|
||||
# 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}
|
||||
@@ -1,316 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for TP mapping and transfer plan utilities.
|
||||
|
||||
These tests verify that TP mapping produces correct outputs
|
||||
(source ranks, split handles, desc IDs).
|
||||
No GPU or NIXL required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import TransferTopology
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.tp_mapping import (
|
||||
TPMapping,
|
||||
compute_tp_mapping,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
|
||||
NixlConnectorWorker,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, MambaSpec
|
||||
|
||||
# ======================================================================
|
||||
# Test fixtures / helpers
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _compute_mapping(
|
||||
tp_rank: int = 0,
|
||||
tp_size: int = 1,
|
||||
remote_tp_size: int = 1,
|
||||
is_mla: bool = False,
|
||||
num_kv_heads: int = 8,
|
||||
group_spec_types: tuple[type, ...] = (FullAttentionSpec,),
|
||||
dcp_size: int = 1,
|
||||
remote_dcp_size: int = 1,
|
||||
) -> TPMapping:
|
||||
transfer_topology = object.__new__(TransferTopology)
|
||||
transfer_topology.tp_rank = tp_rank
|
||||
transfer_topology.tp_size = tp_size
|
||||
transfer_topology.is_mla = is_mla
|
||||
transfer_topology.total_num_kv_heads = num_kv_heads
|
||||
transfer_topology.dcp_size = dcp_size
|
||||
return compute_tp_mapping(
|
||||
transfer_topology=transfer_topology,
|
||||
remote_tp_size=remote_tp_size,
|
||||
group_spec_types=group_spec_types,
|
||||
remote_dcp_size=remote_dcp_size,
|
||||
)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# TP mapping structure tests
|
||||
# ======================================================================
|
||||
|
||||
|
||||
class TestTPMappingStructure:
|
||||
def test_source_ranks_homogeneous(self):
|
||||
m = _compute_mapping(tp_size=2, tp_rank=1, remote_tp_size=2)
|
||||
assert m.all_source_ranks == (1,)
|
||||
|
||||
def test_source_ranks_d_gt_p(self):
|
||||
m = _compute_mapping(tp_size=4, tp_rank=2, remote_tp_size=2)
|
||||
assert m.all_source_ranks == (1,)
|
||||
|
||||
def test_source_ranks_p_gt_d(self):
|
||||
m = _compute_mapping(tp_size=1, tp_rank=0, remote_tp_size=2)
|
||||
assert m.all_source_ranks == (0, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tp_rank,tp_size,remote_tp_size,dcp_size,remote_dcp_size,expected_ranks",
|
||||
[
|
||||
(0, 1, 8, 1, 8, tuple(range(8))),
|
||||
(0, 4, 4, 1, 4, (0, 1, 2, 3)),
|
||||
(2, 4, 4, 4, 4, (2,)),
|
||||
(0, 2, 4, 2, 4, (0, 2)),
|
||||
(3, 4, 2, 4, 2, (1,)),
|
||||
],
|
||||
)
|
||||
def test_mla_dcp_source_ranks(
|
||||
tp_rank,
|
||||
tp_size,
|
||||
remote_tp_size,
|
||||
dcp_size,
|
||||
remote_dcp_size,
|
||||
expected_ranks,
|
||||
):
|
||||
mapping = _compute_mapping(
|
||||
tp_rank=tp_rank,
|
||||
tp_size=tp_size,
|
||||
remote_tp_size=remote_tp_size,
|
||||
is_mla=True,
|
||||
num_kv_heads=1,
|
||||
dcp_size=dcp_size,
|
||||
remote_dcp_size=remote_dcp_size,
|
||||
)
|
||||
|
||||
assert mapping.all_source_ranks == expected_ranks
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tp_size,remote_tp_size,dcp_size,remote_dcp_size",
|
||||
[
|
||||
(4, 2, 4, 2),
|
||||
(4, 4, 4, 4),
|
||||
(4, 1, 4, 1),
|
||||
(4, 4, 1, 4),
|
||||
(2, 4, 2, 4),
|
||||
],
|
||||
)
|
||||
def test_dcp_consumer_count_matches_readers(
|
||||
tp_size, remote_tp_size, dcp_size, remote_dcp_size
|
||||
):
|
||||
"""Each producer waits for exactly the local ranks that read from it."""
|
||||
mappings = [
|
||||
_compute_mapping(
|
||||
tp_rank=tp_rank,
|
||||
tp_size=tp_size,
|
||||
remote_tp_size=remote_tp_size,
|
||||
is_mla=True,
|
||||
num_kv_heads=1,
|
||||
dcp_size=dcp_size,
|
||||
remote_dcp_size=remote_dcp_size,
|
||||
)
|
||||
for tp_rank in range(tp_size)
|
||||
]
|
||||
|
||||
for remote_rank in range(remote_tp_size):
|
||||
readers = [m for m in mappings if remote_rank in m.all_source_ranks]
|
||||
for mapping in readers:
|
||||
assert mapping.local_consumers == len(readers)
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Split handle tests
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _make_mock_worker_for_splits(group_spec_types):
|
||||
"""Build a mock NixlConnectorWorker with _group_spec_types for split tests.
|
||||
|
||||
No per-region replicate flags are configured (``block_len_per_layer`` empty
|
||||
and ``num_regions == 0``), so ``_build_local_splits_from_plan`` treats every
|
||||
FA descriptor as SPLIT, matching the legacy behavior these tests assert.
|
||||
"""
|
||||
worker = object.__new__(NixlConnectorWorker)
|
||||
worker._group_spec_types = group_spec_types
|
||||
worker.transfer_topo = SimpleNamespace(virtually_split_kv_in_blocks=False)
|
||||
worker.block_len_per_layer = []
|
||||
worker.num_regions = 0
|
||||
worker._region_is_mla = []
|
||||
worker._conv_decomp = SimpleNamespace(local_conv_offsets=())
|
||||
worker._ssm_region_indices = [0] if MambaSpec in group_spec_types else []
|
||||
worker._ple_region_index = None
|
||||
return worker
|
||||
|
||||
|
||||
class TestBuildSrcSplitHandles:
|
||||
@pytest.mark.parametrize("remote_tp_size", [2, 4])
|
||||
def test_build_src_split_handles(self, remote_tp_size):
|
||||
tp_rank = 0
|
||||
tp_size = 1
|
||||
|
||||
plan = _compute_mapping(
|
||||
tp_rank=tp_rank,
|
||||
tp_size=tp_size,
|
||||
remote_tp_size=remote_tp_size,
|
||||
)
|
||||
|
||||
worker = _make_mock_worker_for_splits((FullAttentionSpec,))
|
||||
# One region of 8 dense 1024-byte blocks as a single strided run.
|
||||
src_blocks_data = np.array([(0x2000, 1024, 0, 1024, 8)], dtype=np.uint64)
|
||||
num_descs = 8
|
||||
splits = list(
|
||||
worker._build_local_splits_from_plan(
|
||||
plan,
|
||||
src_blocks_data,
|
||||
num_descs,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(splits) == remote_tp_size
|
||||
for handle in splits:
|
||||
assert handle.shape == src_blocks_data.shape
|
||||
# The head slice shrinks the length; block stride and count are kept.
|
||||
assert handle[:, 1].tolist() == [1024 // remote_tp_size]
|
||||
assert handle[:, 3:].tolist() == [[1024, 8]]
|
||||
|
||||
|
||||
class TestMambaPlanSplitHandles:
|
||||
"""Verify split handles for Mamba with FA/SSM distinction."""
|
||||
|
||||
def test_fa_and_ssm_different_split_factors(self):
|
||||
"""Section 0 split by num_attn_reads, section 1 by abs_tp."""
|
||||
fa_readers = (0,)
|
||||
ssm_readers = (0, 1)
|
||||
plan = TPMapping(
|
||||
source_ranks_per_group=(fa_readers, ssm_readers),
|
||||
all_source_ranks=(0, 1),
|
||||
rank_to_attention_slot={0: 0, 1: 0},
|
||||
rank_offset_factor=0,
|
||||
)
|
||||
|
||||
worker = _make_mock_worker_for_splits((FullAttentionSpec, MambaSpec))
|
||||
# 2 FA runs + 1 SSM run of one block each: (addr, len, dev, stride, count)
|
||||
src_blocks_data = np.array(
|
||||
[
|
||||
(1000, 200, 0, 200, 1), # FA desc 0
|
||||
(2000, 200, 0, 200, 1), # FA desc 1
|
||||
(3000, 400, 0, 400, 1), # SSM desc 0
|
||||
],
|
||||
dtype=np.uint64,
|
||||
)
|
||||
|
||||
splits = list(worker._build_local_splits_from_plan(plan, src_blocks_data, 2))
|
||||
|
||||
assert len(splits) == 2 # 2 source ranks
|
||||
|
||||
# Rank 0 (FA source, p_idx=0):
|
||||
# FA: chunk=200//1=200, slot=0 → (1000, 200), (2000, 200)
|
||||
# SSM: chunk=400//2=200, idx=0 → (3000, 200); block stride stays 400
|
||||
assert splits[0].tolist() == [
|
||||
[1000, 200, 0, 200, 1],
|
||||
[2000, 200, 0, 200, 1],
|
||||
[3000, 200, 0, 400, 1],
|
||||
]
|
||||
|
||||
# Rank 1 (not FA source, p_idx=1):
|
||||
# FA: chunk=200//1=200, slot=0 (skip_fa) → (1000, 200), (2000, 200)
|
||||
# SSM: chunk=400//2=200, idx=1 → (3200, 200); block stride stays 400
|
||||
assert splits[1].tolist() == [
|
||||
[1000, 200, 0, 200, 1],
|
||||
[2000, 200, 0, 200, 1],
|
||||
[3200, 200, 0, 400, 1],
|
||||
]
|
||||
|
||||
def test_hetero_block_size_splits(self):
|
||||
"""With a block-size ratio, single-source FA sub-block descs pass
|
||||
through whole; SSM descs are unexpanded and split per source."""
|
||||
plan = TPMapping(
|
||||
source_ranks_per_group=((0,), (0, 1)),
|
||||
all_source_ranks=(0, 1),
|
||||
rank_to_attention_slot={0: 0, 1: 0},
|
||||
rank_offset_factor=0,
|
||||
)
|
||||
|
||||
worker = _make_mock_worker_for_splits((FullAttentionSpec, MambaSpec))
|
||||
# 2 FA blocks x ratio 2 sub-blocks (one run of 2 per block) + 1 SSM desc
|
||||
# (never expanded).
|
||||
src_blocks_data = np.array(
|
||||
[
|
||||
(1000, 100, 0, 100, 2),
|
||||
(2000, 100, 0, 100, 2),
|
||||
(3000, 400, 0, 400, 1),
|
||||
],
|
||||
dtype=np.uint64,
|
||||
)
|
||||
|
||||
splits = list(worker._build_local_splits_from_plan(plan, src_blocks_data, 4, 2))
|
||||
|
||||
assert len(splits) == 2
|
||||
fa_passthrough = [[1000, 100, 0, 100, 2], [2000, 100, 0, 100, 2]]
|
||||
assert splits[0].tolist() == fa_passthrough + [[3000, 200, 0, 400, 1]]
|
||||
assert splits[1].tolist() == fa_passthrough + [[3200, 200, 0, 400, 1]]
|
||||
|
||||
def test_hetero_block_size_head_sharded_asserts(self):
|
||||
"""Head-sharded FA reads (multiple FA sources) are incompatible with
|
||||
a block-size mismatch and must fail loudly."""
|
||||
plan = TPMapping(
|
||||
source_ranks_per_group=((0, 1), (0, 1)),
|
||||
all_source_ranks=(0, 1),
|
||||
rank_to_attention_slot={0: 0, 1: 1},
|
||||
rank_offset_factor=0,
|
||||
)
|
||||
|
||||
worker = _make_mock_worker_for_splits((FullAttentionSpec, MambaSpec))
|
||||
src_blocks_data = np.array(
|
||||
[(1000, 100, 0, 100, 2), (3000, 400, 0, 400, 1)],
|
||||
dtype=np.uint64,
|
||||
)
|
||||
|
||||
with pytest.raises(AssertionError, match="Head-sharded"):
|
||||
list(worker._build_local_splits_from_plan(plan, src_blocks_data, 2, 2))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("total_kv_heads", "local_tp", "remote_tp", "compatible"),
|
||||
[
|
||||
# 2 heads: TP1 packs both heads into a page, TP >= 2 packs one.
|
||||
(2, 1, 2, False),
|
||||
(2, 2, 1, False),
|
||||
(2, 1, 1, True),
|
||||
(2, 2, 4, True),
|
||||
(2, 4, 2, True),
|
||||
# 4 heads: the boundary moves with the head count.
|
||||
(4, 2, 4, False),
|
||||
(4, 2, 2, True),
|
||||
(4, 4, 8, True),
|
||||
],
|
||||
)
|
||||
def test_csa_linear_tp_layout_boundary(total_kv_heads, local_tp, remote_tp, compatible):
|
||||
worker = object.__new__(NixlConnectorWorker)
|
||||
worker.world_size = local_tp
|
||||
worker._is_csa_linear = True
|
||||
worker.transfer_topo = SimpleNamespace(total_num_kv_heads=total_kv_heads)
|
||||
|
||||
if compatible:
|
||||
worker._validate_csa_linear_tp_layout(remote_tp)
|
||||
else:
|
||||
with pytest.raises(ValueError, match="KV-head sharding boundary"):
|
||||
worker._validate_csa_linear_tp_layout(remote_tp)
|
||||
@@ -537,154 +537,6 @@ def make_kv_cache_config(
|
||||
)
|
||||
|
||||
|
||||
def make_nixl_scheduler(
|
||||
has_mamba: bool = False,
|
||||
is_hma_required: bool = False,
|
||||
bounded_replay: bool = False,
|
||||
heartbeat: bool = False,
|
||||
kv_lease_duration: int = 30,
|
||||
):
|
||||
"""Create a NixlConnectorScheduler via __new__ (skipping __init__).
|
||||
|
||||
Only sets the flags needed by the tests. When *heartbeat=True* the
|
||||
scheduler-side heartbeat bookkeeping fields are also initialised.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.scheduler import (
|
||||
NixlConnectorScheduler,
|
||||
)
|
||||
|
||||
sched = object.__new__(NixlConnectorScheduler)
|
||||
sched._has_mamba = has_mamba
|
||||
sched._bounded_replay = bounded_replay
|
||||
sched._is_hma_required = is_hma_required
|
||||
sched.kv_cache_config = make_kv_cache_config(
|
||||
block_size=16,
|
||||
mamba_enabled=has_mamba,
|
||||
)
|
||||
sched.vllm_config = SimpleNamespace(num_prefill_lookahead_tokens=0)
|
||||
|
||||
if heartbeat:
|
||||
sched._heartbeat_by_engine = {}
|
||||
sched._heartbeat_req_engine = {}
|
||||
sched._last_heartbeat_time = 0.0
|
||||
sched._kv_lease_duration = kv_lease_duration
|
||||
sched._heartbeat_interval = kv_lease_duration // 6
|
||||
# Fields touched by build_connector_meta / request_finished:
|
||||
sched._reqs_need_recv = {}
|
||||
sched._hisparse_host_blocks_to_recv = {}
|
||||
sched._reqs_need_send = {}
|
||||
sched._reqs_in_batch = set()
|
||||
sched._reqs_not_processed = set()
|
||||
sched._reqs_need_save = {}
|
||||
sched.use_host_buffer = False
|
||||
sched.engine_id = "test-engine"
|
||||
sched.transfer_tp_size = 1
|
||||
sched.side_channel_host = "localhost"
|
||||
sched.side_channel_port = 5555
|
||||
sched.blocks_per_sw = []
|
||||
sched.is_bidirectional_kv_xfer_enabled = False
|
||||
return sched
|
||||
|
||||
|
||||
def make_nixl_push_scheduler(
|
||||
*,
|
||||
decoder_kv_blocks_ttl: float = 30.0,
|
||||
push_registration_timeout: float | None = None,
|
||||
is_bidirectional_kv_xfer_enabled: bool = False,
|
||||
has_mamba: bool = False,
|
||||
):
|
||||
"""Create a NixlPushConnectorScheduler via __new__ (skipping __init__).
|
||||
|
||||
The push scheduler can't reuse :func:`make_nixl_scheduler` because it
|
||||
is a different class (``NixlPushConnectorScheduler`` vs
|
||||
``NixlConnectorScheduler``) and carries push-specific state. Only the
|
||||
fields touched by the unit tests are populated.
|
||||
"""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_scheduler import (
|
||||
NixlPushConnectorScheduler,
|
||||
)
|
||||
|
||||
sched = object.__new__(NixlPushConnectorScheduler)
|
||||
|
||||
# Base scheduler fields (shared with pull / heartbeat path).
|
||||
sched._reqs_need_recv = {}
|
||||
sched._reqs_need_send = {}
|
||||
sched._reqs_in_batch = set()
|
||||
sched._reqs_not_processed = set()
|
||||
sched._reqs_need_save = {}
|
||||
sched._kv_lease_duration = 30
|
||||
sched.decoder_kv_blocks_ttl = decoder_kv_blocks_ttl
|
||||
sched.use_host_buffer = False
|
||||
sched.engine_id = "decode-engine"
|
||||
sched.transfer_tp_size = 1
|
||||
sched.side_channel_host = "127.0.0.1"
|
||||
sched.side_channel_port = 5600
|
||||
sched.is_bidirectional_kv_xfer_enabled = is_bidirectional_kv_xfer_enabled
|
||||
sched._has_mamba = has_mamba
|
||||
sched._bounded_replay = False
|
||||
sched.kv_cache_config = make_kv_cache_config(
|
||||
block_size=16,
|
||||
mamba_enabled=has_mamba,
|
||||
)
|
||||
|
||||
# vllm_config is consulted for parallel_config.tensor_parallel_size, and by
|
||||
# `_prefill_backoff` on both the P and D prefill paths.
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.parallel_config.tensor_parallel_size = 1
|
||||
vllm_config.num_prefill_lookahead_tokens = 0
|
||||
sched.vllm_config = vllm_config
|
||||
|
||||
# Push-specific state.
|
||||
sched._push_pending_registrations = {}
|
||||
sched._push_registration_deadlines = {}
|
||||
sched._finished_request_blocks = {}
|
||||
sched._newly_finished_push_blocks = {}
|
||||
sched._push_registration_timeout = (
|
||||
push_registration_timeout
|
||||
if push_registration_timeout is not None
|
||||
else decoder_kv_blocks_ttl
|
||||
)
|
||||
|
||||
# Heartbeat fields touched by base request_finished /
|
||||
# update_connector_output.
|
||||
sched._heartbeat_by_engine = {}
|
||||
sched._heartbeat_req_engine = {}
|
||||
sched._last_heartbeat_time = 0.0
|
||||
sched.blocks_per_sw = []
|
||||
|
||||
return sched
|
||||
|
||||
|
||||
def make_moriio_writer(fake_worker: Any) -> Any:
|
||||
"""Build a MoRIIOWriter with internals stubbed for unit tests.
|
||||
|
||||
Bypasses ``__init__`` and wires only the write/finalize state the tests
|
||||
touch, including the deferred-task fields used by the routing suite.
|
||||
"""
|
||||
import threading
|
||||
from queue import Queue
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_engine import (
|
||||
MoRIIOWriter,
|
||||
)
|
||||
|
||||
writer = MoRIIOWriter.__new__(MoRIIOWriter)
|
||||
writer._worker_ref = lambda: fake_worker
|
||||
writer._write_task_q = Queue()
|
||||
writer._write_state_lock = threading.Lock()
|
||||
writer._scheduled_writes = defaultdict(int)
|
||||
writer._scheduled_layers = defaultdict(set)
|
||||
writer._sealed_writes = {}
|
||||
writer._deferred_tasks = []
|
||||
writer._defer_timeout = 60.0
|
||||
writer.ensure_worker_started = lambda: None
|
||||
return writer
|
||||
|
||||
|
||||
def expand_strided_descs(strided_descs: np.ndarray) -> np.ndarray:
|
||||
"""Expand Nx5 (addr, len, dev, stride, count) rows to one row per block.
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user