[KV Connector]: Support KV push from Prefill to Decode node using Nixl KV Connector (#35264)
Signed-off-by: Sunita Nadampalli <nadampal@amazon.com> Signed-off-by: NickLucche <nlucches@redhat.com> Co-authored-by: Nicolò Lucchesi <nlucches@redhat.com>
This commit is contained in:
co-authored by
Nicolò Lucchesi
parent
a014dddbaa
commit
88ed636218
@@ -32,7 +32,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.connector import (
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import (
|
||||
NixlConnector,
|
||||
NixlConnectorMetadata,
|
||||
)
|
||||
@@ -436,7 +436,7 @@ def test_build_connector_meta_multiple_requests():
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_p_node_pull_kv_from_d(dist_init):
|
||||
@@ -450,7 +450,7 @@ def test_p_node_pull_kv_from_d(dist_init):
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_p_node_pull_then_send_kv(dist_init):
|
||||
@@ -472,7 +472,7 @@ def test_p_node_pull_then_send_kv(dist_init):
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_p_node_deferred_pull_on_no_handshake(dist_init):
|
||||
|
||||
@@ -366,7 +366,10 @@ def test_multi_example_connector_consistency():
|
||||
|
||||
|
||||
def _ignore_event_collection(events: list[str]) -> list[str]:
|
||||
return [event for event in events if event != "take_events"]
|
||||
# Filter out per-step polling hooks that the scheduler calls repeatedly
|
||||
# and which are not meaningful state transitions for these assertions.
|
||||
ignored = {"take_events", "has_pending_push_work"}
|
||||
return [event for event in events if event not in ignored]
|
||||
|
||||
|
||||
def get_connector_events() -> dict[str, list[str]]:
|
||||
@@ -1072,7 +1075,7 @@ def test_multi_connector_mixed_hma_disables_hybrid_kv_cache(monkeypatch):
|
||||
)
|
||||
|
||||
with patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
):
|
||||
llm = LLM(
|
||||
|
||||
@@ -344,7 +344,7 @@ def test_abort_immediately_remote_prefill_enqueues_empty_recv():
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_kv_transfer_handshake(dist_init):
|
||||
@@ -560,7 +560,7 @@ class FakeNixlConnectorWorker(NixlConnectorWorker):
|
||||
|
||||
class TestNixlHandshake:
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_multi_xfer_one_engine(
|
||||
@@ -643,7 +643,7 @@ class TestNixlHandshake:
|
||||
connector.clear_connector_metadata()
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
@@ -713,7 +713,7 @@ class TestNixlHandshake:
|
||||
raise TimeoutError("Took too long to complete async handshake.")
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
@pytest.mark.parametrize("local_tp_size", [1, 2])
|
||||
@@ -725,7 +725,7 @@ class TestNixlHandshake:
|
||||
remote configurations.
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.get_tensor_model_parallel_world_size",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.get_tensor_model_parallel_world_size",
|
||||
lambda: local_tp_size,
|
||||
)
|
||||
|
||||
@@ -784,7 +784,7 @@ class TestNixlHandshake:
|
||||
check_handshake(6)
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_prefill_tp_size_greater_than_decode_tp_size_mla(
|
||||
@@ -887,7 +887,7 @@ class TestNixlHandshake:
|
||||
assert req_id not in conn_p1.connector_worker._reqs_to_process
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_concurrent_load_kv(
|
||||
@@ -952,7 +952,7 @@ class TestNixlHandshake:
|
||||
raise TimeoutError("Took too long to complete async handshake.")
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_handshake_fails_on_kv_cache_layout_mismatch(
|
||||
@@ -967,7 +967,7 @@ class TestNixlHandshake:
|
||||
# Mock TP world size to 2 to force heterogeneous TP when
|
||||
# remote_tp_size=1
|
||||
with patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
return_value=2,
|
||||
):
|
||||
# Initialize connector and worker (with fake NIXL wrapper)
|
||||
@@ -1007,7 +1007,7 @@ class TestNixlHandshake:
|
||||
worker.add_remote_agent(meta, remote_tp_size=1)
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental(
|
||||
@@ -1022,7 +1022,7 @@ class TestNixlHandshake:
|
||||
# Mock TP world size to 2 to force heterogeneous TP when
|
||||
# remote_tp_size=1
|
||||
with patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
return_value=2,
|
||||
):
|
||||
# Initialize connector and worker (with fake NIXL wrapper)
|
||||
@@ -1064,7 +1064,7 @@ class TestNixlHandshake:
|
||||
worker.add_remote_agent(meta, remote_tp_size=1)
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_handshake_mixed_fa_mla_hetero_tp(self, default_vllm_config, dist_init):
|
||||
@@ -1074,7 +1074,7 @@ class TestNixlHandshake:
|
||||
"""
|
||||
vllm_config = create_vllm_config()
|
||||
with patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.get_tensor_model_parallel_world_size", # noqa: E501
|
||||
return_value=2,
|
||||
):
|
||||
connector = NixlConnector(
|
||||
@@ -1149,7 +1149,7 @@ class TestNixlHandshake:
|
||||
# we put here is important. First run ray, it will clean up the resources, then
|
||||
# the rest of the tests.
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_kv_connector_stats(default_vllm_config, dist_init):
|
||||
@@ -1363,7 +1363,7 @@ def test_multi_kv_connector_stats_aggregation():
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_scheduler_kv_connector_stats_aggregation():
|
||||
@@ -1428,7 +1428,7 @@ def test_scheduler_kv_connector_stats_aggregation():
|
||||
|
||||
@pytest.mark.parametrize("distributed_executor_backend", ["ray", None])
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_abort_timeout_on_prefiller(monkeypatch, distributed_executor_backend):
|
||||
@@ -1615,7 +1615,7 @@ def test_register_kv_caches(
|
||||
|
||||
backend_cls = TritonAttentionBackend
|
||||
|
||||
nixl_worker = "vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker"
|
||||
nixl_worker = "vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker"
|
||||
nixl_connector = "vllm.distributed.kv_transfer.kv_connector.v1.nixl.connector"
|
||||
with (
|
||||
patch(f"{nixl_worker}.NixlWrapper") as mock_nixl_wrapper,
|
||||
@@ -1865,15 +1865,17 @@ def test_kv_buffer_to_nixl_memory_types(
|
||||
_NIXL_SUPPORTED_DEVICE.update(FakePlatform.get_nixl_supported_devices())
|
||||
|
||||
with (
|
||||
patch("vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper"),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.threading.Event"
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper"
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.threading.Thread"
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.threading.Event"
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.current_platform",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.threading.Thread"
|
||||
),
|
||||
patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.current_platform",
|
||||
FakePlatform,
|
||||
),
|
||||
patch(
|
||||
@@ -1892,7 +1894,7 @@ def test_kv_buffer_to_nixl_memory_types(
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_shutdown_cleans_up_resources(default_vllm_config, dist_init):
|
||||
@@ -1991,7 +1993,7 @@ def _setup_worker_with_remote_engine(
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_engine_ttl_eviction(default_vllm_config, dist_init):
|
||||
@@ -2026,7 +2028,7 @@ def test_engine_ttl_eviction(default_vllm_config, dist_init):
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_engine_ttl_disabled(default_vllm_config, dist_init):
|
||||
@@ -2074,7 +2076,7 @@ def test_transfer_topology_unregister():
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_aborted_request_removed_from_worker_in_batch(default_vllm_config, dist_init):
|
||||
@@ -2194,7 +2196,7 @@ class FailingNixlWrapper(FakeNixlWrapper):
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FailingNixlWrapper,
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
@@ -2284,10 +2286,13 @@ def test_transfer_failure_logging(
|
||||
slot_mapping={},
|
||||
)
|
||||
|
||||
# Capture logs from the nixl.worker logger specifically
|
||||
# Capture logs from the nixl connector loggers
|
||||
# vLLM loggers have propagate=False, so we need to capture directly
|
||||
nixl_logger = logging.getLogger(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker"
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker"
|
||||
)
|
||||
pull_logger = logging.getLogger(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.pull_worker"
|
||||
)
|
||||
captured_logs: list[logging.LogRecord] = []
|
||||
|
||||
@@ -2298,6 +2303,7 @@ def test_transfer_failure_logging(
|
||||
handler = LogCapture()
|
||||
handler.setLevel(logging.ERROR)
|
||||
nixl_logger.addHandler(handler)
|
||||
pull_logger.addHandler(handler)
|
||||
|
||||
try:
|
||||
connector.start_load_kv(dummy_ctx)
|
||||
@@ -2313,6 +2319,7 @@ def test_transfer_failure_logging(
|
||||
connector.get_finished(finished_req_ids=set())
|
||||
finally:
|
||||
nixl_logger.removeHandler(handler)
|
||||
pull_logger.removeHandler(handler)
|
||||
|
||||
# Print logs for manual comparison between commits
|
||||
error_logs = [r for r in captured_logs if r.levelno >= logging.ERROR]
|
||||
@@ -2349,7 +2356,7 @@ def test_transfer_failure_logging(
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FailingNixlWrapper,
|
||||
)
|
||||
def test_handshake_failure_returns_finished(default_vllm_config, dist_init):
|
||||
@@ -2400,7 +2407,7 @@ def test_handshake_failure_returns_finished(default_vllm_config, dist_init):
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FailingNixlWrapper,
|
||||
)
|
||||
def test_transfer_setup_failure_returns_finished(default_vllm_config, dist_init):
|
||||
@@ -2454,7 +2461,7 @@ def test_transfer_setup_failure_returns_finished(default_vllm_config, dist_init)
|
||||
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FailingNixlWrapper,
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
@@ -2597,7 +2604,7 @@ def test_failed_request_skips_kv_postprocessing(
|
||||
],
|
||||
)
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_compatibility_hash_validation(
|
||||
@@ -2706,7 +2713,7 @@ def test_compatibility_hash_validation(
|
||||
# Patch zmq_ctx to return our mock socket
|
||||
with (
|
||||
patch.object(decode_worker, "add_remote_agent", return_value="fake_agent"),
|
||||
patch.object(nixl.worker, "zmq_ctx") as mock_zmq_ctx,
|
||||
patch.object(nixl.base_worker, "zmq_ctx") as mock_zmq_ctx,
|
||||
):
|
||||
mock_zmq_ctx.return_value.__enter__.return_value = mock_socket
|
||||
|
||||
@@ -2740,7 +2747,7 @@ def test_compatibility_hash_validation(
|
||||
],
|
||||
)
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_handshake_decode_errors(default_vllm_config, dist_init, error_scenario):
|
||||
@@ -2806,7 +2813,7 @@ def test_handshake_decode_errors(default_vllm_config, dist_init, error_scenario)
|
||||
mock_socket.recv.return_value = msg_bytes
|
||||
with (
|
||||
patch.object(decode_worker, "add_remote_agent", return_value="fake_agent"),
|
||||
patch.object(nixl.worker, "zmq_ctx") as mock_zmq_ctx,
|
||||
patch.object(nixl.base_worker, "zmq_ctx") as mock_zmq_ctx,
|
||||
):
|
||||
mock_zmq_ctx.return_value.__enter__.return_value = mock_socket
|
||||
|
||||
@@ -2819,7 +2826,7 @@ def test_handshake_decode_errors(default_vllm_config, dist_init, error_scenario)
|
||||
)
|
||||
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper",
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
|
||||
FakeNixlWrapper,
|
||||
)
|
||||
def test_mla_broadcast_notif_uses_remote_request_id(
|
||||
|
||||
@@ -34,7 +34,9 @@ from .utils import (
|
||||
(False, [0]),
|
||||
],
|
||||
)
|
||||
@patch("vllm.distributed.kv_transfer.kv_connector.v1.nixl.scheduler.current_platform")
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_scheduler.current_platform"
|
||||
)
|
||||
def test_sw_sizes(mock_platform, swa_enabled, expected_sw_sizes):
|
||||
"""Test sw_sizes is correctly computed based on SWA enabled/disabled."""
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.scheduler import (
|
||||
@@ -782,7 +784,9 @@ def test_mamba_n1_p_side_truncation():
|
||||
],
|
||||
ids=["fa_swa_mamba", "fa_swa_only", "fa_only"],
|
||||
)
|
||||
@patch("vllm.distributed.kv_transfer.kv_connector.v1.nixl.scheduler.current_platform")
|
||||
@patch(
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_scheduler.current_platform"
|
||||
)
|
||||
def test_has_mamba_init(
|
||||
mock_platform,
|
||||
swa_enabled,
|
||||
|
||||
@@ -0,0 +1,815 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for NixlPushConnector (scheduler + worker).
|
||||
|
||||
These tests cover the end-to-end mechanics of the push design without
|
||||
requiring a real NIXL agent or network:
|
||||
|
||||
* Scheduler stages D registrations on ``update_state_after_alloc`` and
|
||||
P finished blocks on ``request_finished``.
|
||||
* ``build_connector_meta`` drains them onto
|
||||
``meta.push_registrations`` / ``meta.push_finished_blocks``.
|
||||
* ``has_pending_push_work`` reports True/False over the lifecycle.
|
||||
* ``update_connector_output`` clears state on ``finished_sending`` and
|
||||
``finished_recving``.
|
||||
* The worker matches D registrations against P finished blocks (both
|
||||
scenario directions) and forwards non-PUSH_REG NIXL notifs to the main
|
||||
thread's ``_get_new_notifs``.
|
||||
* ``get_finished`` enqueues evictions for the writer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import msgspec
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
PUSH_REG_NOTIF_PREFIX,
|
||||
NixlConnectorMetadata,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker import (
|
||||
NixlPushConnectorWorker,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.utils import (
|
||||
get_base_request_id,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
from .utils import make_nixl_push_scheduler
|
||||
|
||||
# ----------------------------------------------------------------- #
|
||||
# Helpers / fakes #
|
||||
# ----------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _make_request(
|
||||
*,
|
||||
request_id: str,
|
||||
is_d_side: bool = True,
|
||||
remote_engine_id: str = "prefill-engine",
|
||||
remote_request_id: str | None = None,
|
||||
remote_host: str = "10.0.0.1",
|
||||
remote_port: int = 5601,
|
||||
tp_size: int = 1,
|
||||
finished: bool = True,
|
||||
) -> MagicMock:
|
||||
"""Build a minimal Request mock used by request_finished."""
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
req = MagicMock()
|
||||
req.request_id = request_id
|
||||
req.num_computed_tokens = 64
|
||||
|
||||
if is_d_side:
|
||||
# D-side request: do_remote_prefill=True -> prefill on a remote P.
|
||||
params: dict[str, Any] = {
|
||||
"do_remote_prefill": True,
|
||||
"do_remote_decode": False,
|
||||
"remote_engine_id": remote_engine_id,
|
||||
"remote_request_id": remote_request_id or f"prefill-{request_id}",
|
||||
"remote_host": remote_host,
|
||||
"remote_port": remote_port,
|
||||
"tp_size": tp_size,
|
||||
}
|
||||
else:
|
||||
# P-side request: do_remote_decode=True (we are the prefiller).
|
||||
params = {
|
||||
"do_remote_prefill": False,
|
||||
"do_remote_decode": True,
|
||||
}
|
||||
req.kv_transfer_params = params
|
||||
req.status = (
|
||||
RequestStatus.FINISHED_LENGTH_CAPPED if finished else RequestStatus.RUNNING
|
||||
)
|
||||
return req
|
||||
|
||||
|
||||
class _BlocksMock:
|
||||
"""Minimal stand-in for ``KVCacheBlocks`` used in update_state_after_alloc."""
|
||||
|
||||
def __init__(self, block_ids: tuple[list[int], ...]):
|
||||
self._block_ids = block_ids
|
||||
|
||||
def get_unhashed_block_ids_all_groups(self) -> tuple[list[int], ...]:
|
||||
return self._block_ids
|
||||
|
||||
|
||||
def _stub_sw_clipping(scheduler) -> None:
|
||||
"""Make ``get_sw_clipped_blocks`` a passthrough so tests don't need
|
||||
the full sliding-window machinery."""
|
||||
scheduler.get_sw_clipped_blocks = lambda block_ids: block_ids
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- #
|
||||
# Scheduler-side tests #
|
||||
# ----------------------------------------------------------------- #
|
||||
|
||||
|
||||
class TestPushScheduler:
|
||||
def test_d_side_update_state_after_alloc_stages_registration(self):
|
||||
"""D scheduler stashes registration data + arms watchdog deadline."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = _make_request(request_id="req-d-1")
|
||||
blocks = _BlocksMock(block_ids=([10, 11, 12],))
|
||||
|
||||
sched.update_state_after_alloc(request, blocks, num_external_tokens=48)
|
||||
|
||||
assert request.request_id in sched._push_pending_registrations
|
||||
reg = sched._push_pending_registrations[request.request_id]
|
||||
# ``request_id`` is D's own vLLM request id; plus our own (D) coords.
|
||||
assert reg["request_id"] == request.request_id
|
||||
assert reg["decode_engine_id"] == sched.engine_id
|
||||
assert reg["decode_host"] == sched.side_channel_host
|
||||
assert reg["decode_port"] == sched.side_channel_port
|
||||
assert reg["local_block_ids"] == ([10, 11, 12],)
|
||||
assert reg["remote_engine_id"] == "prefill-engine"
|
||||
|
||||
# Watchdog deadline set in the future.
|
||||
deadline = sched._push_registration_deadlines[request.request_id]
|
||||
assert deadline > time.perf_counter()
|
||||
# do_remote_prefill flipped off so the request isn't reprocessed.
|
||||
assert request.kv_transfer_params["do_remote_prefill"] is False
|
||||
# Tracked as awaiting a recv.
|
||||
assert request.request_id in sched._reqs_need_recv
|
||||
|
||||
def test_p_side_request_finished_stages_blocks(self):
|
||||
"""P scheduler pushes blocks into both _finished_request_blocks (lease)
|
||||
and _newly_finished_push_blocks (metadata for next step)."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = _make_request(request_id="req-p-1", is_d_side=False)
|
||||
block_ids = ([20, 21, 22, 23],)
|
||||
|
||||
delay, ret_params = sched.request_finished(request, block_ids)
|
||||
|
||||
assert delay is True
|
||||
assert ret_params is not None
|
||||
assert ret_params["do_remote_prefill"] is True
|
||||
assert ret_params["do_remote_decode"] is False
|
||||
assert request.request_id in sched._finished_request_blocks
|
||||
assert request.request_id in sched._newly_finished_push_blocks
|
||||
assert request.request_id in sched._reqs_need_send # lease armed
|
||||
|
||||
def test_build_connector_meta_drains_both_sides(self):
|
||||
"""meta.push_registrations and meta.push_finished_blocks are filled
|
||||
from the staging dicts and the staging dicts are cleared."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
# Stage one D registration and one P finished entry.
|
||||
d_req = _make_request(request_id="req-d-9")
|
||||
sched.update_state_after_alloc(
|
||||
d_req, _BlocksMock(([1, 2, 3],)), num_external_tokens=48
|
||||
)
|
||||
p_req = _make_request(request_id="req-p-9", is_d_side=False)
|
||||
sched.request_finished(p_req, ([4, 5, 6],))
|
||||
|
||||
scheduler_output = MagicMock()
|
||||
scheduler_output.scheduled_new_reqs = []
|
||||
scheduler_output.scheduled_cached_reqs = MagicMock(
|
||||
req_ids=[], resumed_req_ids=set()
|
||||
)
|
||||
|
||||
# Patch parent build_connector_meta so we don't have to set up
|
||||
# all the base scheduler plumbing.
|
||||
with patch.object(
|
||||
sched.__class__.__mro__[1],
|
||||
"build_connector_meta",
|
||||
return_value=NixlConnectorMetadata(),
|
||||
):
|
||||
meta = sched.build_connector_meta(scheduler_output)
|
||||
|
||||
assert isinstance(meta, NixlConnectorMetadata)
|
||||
assert "req-d-9" in meta.push_registrations
|
||||
assert "req-p-9" in meta.push_finished_blocks
|
||||
# Staging dicts cleared.
|
||||
assert sched._push_pending_registrations == {}
|
||||
assert sched._newly_finished_push_blocks == {}
|
||||
# Lease bookkeeping kept until the WRITE completes.
|
||||
assert "req-p-9" in sched._finished_request_blocks
|
||||
|
||||
def test_has_pending_push_work_lifecycle(self):
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
assert sched.has_pending_push_work() is False
|
||||
|
||||
# P finished blocks waiting for WRITE completion.
|
||||
p_req = _make_request(request_id="req-p-7", is_d_side=False)
|
||||
sched.request_finished(p_req, ([0, 1],))
|
||||
assert sched.has_pending_push_work() is True
|
||||
|
||||
# Drain via build_connector_meta - lease still pending until WRITE.
|
||||
scheduler_output = MagicMock()
|
||||
scheduler_output.scheduled_new_reqs = []
|
||||
scheduler_output.scheduled_cached_reqs = MagicMock(
|
||||
req_ids=[], resumed_req_ids=set()
|
||||
)
|
||||
with patch.object(
|
||||
sched.__class__.__mro__[1],
|
||||
"build_connector_meta",
|
||||
return_value=NixlConnectorMetadata(),
|
||||
):
|
||||
sched.build_connector_meta(scheduler_output)
|
||||
# Lease is pending until WRITE completes -> still True.
|
||||
assert sched.has_pending_push_work() is True
|
||||
|
||||
# Simulate WRITE completion via update_connector_output.
|
||||
sched.update_connector_output(
|
||||
KVConnectorOutput(
|
||||
finished_sending={"req-p-7"},
|
||||
finished_recving=set(),
|
||||
invalid_block_ids=set(),
|
||||
)
|
||||
)
|
||||
assert sched.has_pending_push_work() is False
|
||||
|
||||
def test_update_connector_output_clears_lease_and_watchdog(self):
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
d_req = _make_request(request_id="req-d-x")
|
||||
sched.update_state_after_alloc(
|
||||
d_req, _BlocksMock(([1, 2],)), num_external_tokens=32
|
||||
)
|
||||
p_req = _make_request(request_id="req-p-x", is_d_side=False)
|
||||
sched.request_finished(p_req, ([3, 4],))
|
||||
|
||||
sched.update_connector_output(
|
||||
KVConnectorOutput(
|
||||
finished_sending={"req-p-x"},
|
||||
finished_recving={"req-d-x"},
|
||||
invalid_block_ids=set(),
|
||||
)
|
||||
)
|
||||
assert "req-p-x" not in sched._finished_request_blocks
|
||||
assert "req-d-x" not in sched._push_registration_deadlines
|
||||
|
||||
def test_registration_watchdog_expires(self, caplog):
|
||||
"""Stale D registrations whose deadline has passed are dropped at
|
||||
``build_connector_meta`` time."""
|
||||
# Watchdog logs a WARNING when it drops the stale entry; that's
|
||||
# what this test is verifying, so silence it in the test report.
|
||||
caplog.set_level(
|
||||
logging.CRITICAL,
|
||||
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_scheduler"),
|
||||
)
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
d_req = _make_request(request_id="req-d-stale")
|
||||
sched.update_state_after_alloc(
|
||||
d_req, _BlocksMock(([7, 8],)), num_external_tokens=32
|
||||
)
|
||||
# Force the deadline into the past.
|
||||
sched._push_registration_deadlines[d_req.request_id] = time.perf_counter() - 1.0
|
||||
|
||||
scheduler_output = MagicMock()
|
||||
scheduler_output.scheduled_new_reqs = []
|
||||
scheduler_output.scheduled_cached_reqs = MagicMock(
|
||||
req_ids=[], resumed_req_ids=set()
|
||||
)
|
||||
with patch.object(
|
||||
sched.__class__.__mro__[1],
|
||||
"build_connector_meta",
|
||||
return_value=NixlConnectorMetadata(),
|
||||
):
|
||||
meta = sched.build_connector_meta(scheduler_output)
|
||||
|
||||
assert d_req.request_id not in sched._push_registration_deadlines
|
||||
assert d_req.request_id not in sched._push_pending_registrations
|
||||
assert d_req.request_id not in meta.push_registrations
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- #
|
||||
# Worker-side tests #
|
||||
# ----------------------------------------------------------------- #
|
||||
|
||||
|
||||
class _StubWriterWorker(NixlPushConnectorWorker):
|
||||
"""Construct a worker without invoking ``__init__`` so we can drive
|
||||
the matching/notif logic without bringing up NIXL or torch."""
|
||||
|
||||
@classmethod
|
||||
def fresh(cls) -> _StubWriterWorker:
|
||||
w = object.__new__(cls)
|
||||
|
||||
# Push-specific state managed by NixlPushConnectorWorker.
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
ReqId,
|
||||
TransferHandle,
|
||||
)
|
||||
|
||||
w._sending_transfers = defaultdict[ReqId, list[TransferHandle]](list)
|
||||
w._sending_transfers_lock = threading.Lock()
|
||||
w._push_finished_blocks = {}
|
||||
w._pending_d_registrations = {}
|
||||
w._reg_send_inbox = queue.Queue()
|
||||
w._finished_blocks_inbox = queue.Queue()
|
||||
w._pending_completion_notifs = queue.Queue()
|
||||
w._evict_finished_inbox = queue.Queue()
|
||||
w._push_writer_wake = threading.Event()
|
||||
w._push_writer_stop = threading.Event()
|
||||
w._push_writer_thread = None
|
||||
|
||||
# Base worker fields touched by start_load_kv / _get_new_notifs.
|
||||
w._recving_metadata = {}
|
||||
w._recving_transfers = defaultdict(list)
|
||||
w._reqs_to_process = set()
|
||||
w._reqs_to_send = {}
|
||||
w.consumer_notification_counts_by_req = defaultdict(int)
|
||||
w.tp_rank = 0
|
||||
w.world_size = 1
|
||||
w.engine_id = "test-decode-engine"
|
||||
w._remote_agents = {}
|
||||
|
||||
# Track _do_start_push_kv invocations.
|
||||
calls: list[tuple[str, Any, dict[str, Any]]] = []
|
||||
w.start_push_calls = calls
|
||||
return w
|
||||
|
||||
def _do_start_push_kv(
|
||||
self,
|
||||
request_id: str,
|
||||
local_block_ids,
|
||||
registration_data: dict[str, Any],
|
||||
) -> None: # pragma: no cover - exercised through tests
|
||||
# Track the call instead of issuing real WRITEs.
|
||||
self.start_push_calls.append((request_id, local_block_ids, registration_data))
|
||||
|
||||
|
||||
def _registration_data(
|
||||
request_id: str,
|
||||
*,
|
||||
decode_engine_id: str = "decode-engine",
|
||||
decode_host: str = "10.0.0.2",
|
||||
decode_port: int = 5602,
|
||||
decode_tp_size: int = 1,
|
||||
local_block_ids=((100, 101, 102),),
|
||||
remote_engine_id: str = "prefill-engine",
|
||||
remote_host: str = "10.0.0.1",
|
||||
remote_port: int = 5601,
|
||||
remote_tp_size: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"request_id": request_id,
|
||||
"decode_engine_id": decode_engine_id,
|
||||
"decode_host": decode_host,
|
||||
"decode_port": decode_port,
|
||||
"decode_tp_size": decode_tp_size,
|
||||
"local_block_ids": local_block_ids,
|
||||
"remote_engine_id": remote_engine_id,
|
||||
"remote_host": remote_host,
|
||||
"remote_port": remote_port,
|
||||
"remote_tp_size": remote_tp_size,
|
||||
}
|
||||
|
||||
|
||||
class TestPushWriterMatching:
|
||||
def test_handle_push_reg_matches_existing_finished_blocks(self):
|
||||
"""PUSH_REG arrives second (P finished first): match + fire."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
# P had already finished; its blocks were stashed via metadata.
|
||||
w._push_finished_blocks["req-A"] = ([200, 201, 202],)
|
||||
|
||||
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(
|
||||
_registration_data("req-A")
|
||||
)
|
||||
w._handle_push_reg_notif(notif)
|
||||
|
||||
assert len(w.start_push_calls) == 1
|
||||
rid, blocks, reg = w.start_push_calls[0]
|
||||
assert rid == "req-A"
|
||||
assert blocks == ([200, 201, 202],)
|
||||
assert reg["decode_engine_id"] == "decode-engine"
|
||||
# Finished blocks consumed.
|
||||
assert "req-A" not in w._push_finished_blocks
|
||||
assert w._pending_d_registrations == {}
|
||||
|
||||
def test_handle_push_reg_stashes_when_no_finished_blocks_yet(self):
|
||||
"""PUSH_REG arrives first (D registered first): stash, no fire."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
|
||||
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(
|
||||
_registration_data("req-B")
|
||||
)
|
||||
w._handle_push_reg_notif(notif)
|
||||
|
||||
assert len(w.start_push_calls) == 0
|
||||
assert "req-B" in w._pending_d_registrations
|
||||
|
||||
def test_handle_push_reg_matches_after_stripping_random_suffix(self):
|
||||
"""P and D assign the same logical request the same
|
||||
``cmpl-<uuid>-<index>`` but different per-engine random suffixes;
|
||||
the writer should still match P's finished blocks via the
|
||||
suffix-stripping fallback in ``_pop_matching_finished_blocks``.
|
||||
"""
|
||||
w = _StubWriterWorker.fresh()
|
||||
# Same base id + completion index; differ only in the trailing
|
||||
# ``-<8 hex>`` randomization suffix.
|
||||
p_id = "cmpl-12345678-aaaa-bbbb-cccc-1234567890ab-0-aaaaaaaa"
|
||||
d_id = "cmpl-12345678-aaaa-bbbb-cccc-1234567890ab-0-bbbbbbbb"
|
||||
# Sanity: same base id under the helper used by the connector.
|
||||
assert get_base_request_id(p_id) == get_base_request_id(d_id)
|
||||
|
||||
w._push_finished_blocks[p_id] = ([1, 2, 3],)
|
||||
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(_registration_data(d_id))
|
||||
w._handle_push_reg_notif(notif)
|
||||
|
||||
# Suffix-stripped fallback matched and fired.
|
||||
assert len(w.start_push_calls) == 1
|
||||
assert w.start_push_calls[0][0] == p_id
|
||||
assert p_id not in w._push_finished_blocks
|
||||
|
||||
def test_handle_push_reg_drops_malformed(self, caplog):
|
||||
# The writer logs WARNING/ERROR when it sees these bad payloads;
|
||||
# that's the desired behavior, so suppress the noise from test
|
||||
# output rather than letting it look like a failure.
|
||||
caplog.set_level(
|
||||
logging.CRITICAL,
|
||||
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
|
||||
)
|
||||
w = _StubWriterWorker.fresh()
|
||||
# Missing request_id -> should drop without raising.
|
||||
bad = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode({"decode_engine_id": "x"})
|
||||
w._handle_push_reg_notif(bad)
|
||||
assert w._pending_d_registrations == {}
|
||||
assert w.start_push_calls == []
|
||||
|
||||
# Undecodable payload also dropped.
|
||||
w._handle_push_reg_notif(PUSH_REG_NOTIF_PREFIX + b"\xff\xff\xff")
|
||||
assert w.start_push_calls == []
|
||||
|
||||
|
||||
class TestPushWriterStartLoadKv:
|
||||
def test_finished_blocks_inbox_matches_stashed_registration(self):
|
||||
"""Run the writer-loop's finished-blocks drain against a
|
||||
pre-populated _pending_d_registrations entry."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
w._pending_d_registrations["req-C"] = _registration_data("req-C")
|
||||
|
||||
# Simulate start_load_kv enqueuing finished blocks.
|
||||
w._finished_blocks_inbox.put(("req-C", ([10, 11, 12],)))
|
||||
|
||||
# Drain like the writer loop does.
|
||||
while True:
|
||||
try:
|
||||
rid, blocks = w._finished_blocks_inbox.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
matched = w._pop_matching_registration(rid)
|
||||
if matched is not None:
|
||||
w._do_start_push_kv(rid, blocks, matched)
|
||||
else:
|
||||
w._push_finished_blocks[rid] = blocks
|
||||
|
||||
assert len(w.start_push_calls) == 1
|
||||
assert w.start_push_calls[0][0] == "req-C"
|
||||
assert "req-C" not in w._pending_d_registrations
|
||||
|
||||
def test_start_load_kv_enqueues_to_writer(self):
|
||||
"""``start_load_kv`` should hand registrations + finished blocks
|
||||
to the writer queues without doing matching itself."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
# Stub heartbeats to a no-op; tests don't exercise the heartbeat
|
||||
# path here.
|
||||
w._send_heartbeats = lambda metadata: None
|
||||
# Stub logical-to-kernel mapping used by reqs_to_recv.
|
||||
w._logical_to_kernel_block_ids = lambda x: x
|
||||
|
||||
meta = NixlConnectorMetadata()
|
||||
meta.push_registrations = {
|
||||
"req-D": _registration_data("req-D"),
|
||||
}
|
||||
meta.push_finished_blocks = {
|
||||
"req-E": ([5, 6, 7],),
|
||||
}
|
||||
|
||||
w.start_load_kv(meta)
|
||||
|
||||
# Things are queued for the writer; nothing fires yet.
|
||||
assert w._reg_send_inbox.qsize() == 1
|
||||
assert w._finished_blocks_inbox.qsize() == 1
|
||||
assert w._push_writer_wake.is_set()
|
||||
assert w.start_push_calls == []
|
||||
|
||||
|
||||
class TestPushWriterNotifs:
|
||||
def test_get_new_notifs_processes_forwarded_completion_notif(self):
|
||||
"""Non-PUSH_REG notifs forwarded by the writer thread are drained
|
||||
on the engine main thread inside ``_get_new_notifs``."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
# Pretend the writer thread already forwarded a completion notif
|
||||
# for a request whose KV is being received.
|
||||
request_id = "req-recv-1"
|
||||
w._recving_metadata[request_id] = MagicMock()
|
||||
# Compose the standard completion notif: req_id:tp_size.
|
||||
notif_msg = f"{request_id}:1".encode()
|
||||
w._pending_completion_notifs.put(notif_msg)
|
||||
|
||||
# transfer_topo is consulted only for the producer-side path; we
|
||||
# make it a MagicMock because the D-side branch returns early.
|
||||
w.transfer_topo = MagicMock()
|
||||
|
||||
notified = w._get_new_notifs()
|
||||
|
||||
# Notif consumed; D-side just touches _recving_transfers.
|
||||
assert notified == set()
|
||||
assert request_id in w._recving_transfers
|
||||
|
||||
def test_get_finished_evicts_completed_state(self):
|
||||
"""``get_finished`` should enqueue evictions and wake the writer."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
|
||||
# Stub the base ``get_finished`` to return one done_sending entry.
|
||||
# Patch via the MRO's parent class.
|
||||
with patch.object(
|
||||
NixlPushConnectorWorker.__mro__[1],
|
||||
"get_finished",
|
||||
return_value=({"req-done"}, set()),
|
||||
):
|
||||
done_sending, done_recving = w.get_finished()
|
||||
|
||||
assert "req-done" in done_sending
|
||||
assert done_recving == set()
|
||||
# Eviction enqueued for the writer.
|
||||
evicted = []
|
||||
while True:
|
||||
try:
|
||||
evicted.append(w._evict_finished_inbox.get_nowait())
|
||||
except queue.Empty:
|
||||
break
|
||||
assert evicted == ["req-done"]
|
||||
assert w._push_writer_wake.is_set()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- #
|
||||
# Negative / error-path tests #
|
||||
# ----------------------------------------------------------------- #
|
||||
|
||||
|
||||
class TestPushSchedulerNegative:
|
||||
"""Failure / no-op paths on the scheduler side."""
|
||||
|
||||
def test_update_state_after_alloc_no_kv_transfer_params_is_noop(self):
|
||||
"""Requests without kv_transfer_params must not register anything."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = MagicMock()
|
||||
request.request_id = "req-no-params"
|
||||
request.kv_transfer_params = None
|
||||
|
||||
sched.update_state_after_alloc(
|
||||
request, _BlocksMock(([1, 2, 3],)), num_external_tokens=64
|
||||
)
|
||||
|
||||
assert sched._push_pending_registrations == {}
|
||||
assert sched._push_registration_deadlines == {}
|
||||
assert sched._reqs_need_recv == {}
|
||||
|
||||
def test_update_state_after_alloc_zero_external_tokens_does_not_register(self):
|
||||
"""num_external_tokens=0 should not stage a D registration."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = _make_request(request_id="req-zero-ext")
|
||||
sched.update_state_after_alloc(
|
||||
request, _BlocksMock(([1, 2, 3],)), num_external_tokens=0
|
||||
)
|
||||
|
||||
assert sched._push_pending_registrations == {}
|
||||
assert sched._push_registration_deadlines == {}
|
||||
|
||||
def test_request_finished_unfinished_status_does_not_stage(self):
|
||||
"""If a request is still RUNNING, request_finished must not stash
|
||||
blocks for the worker (no push needed)."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = _make_request(
|
||||
request_id="req-running", is_d_side=False, finished=False
|
||||
)
|
||||
|
||||
delay, ret = sched.request_finished(request, ([1, 2, 3],))
|
||||
|
||||
assert delay is False
|
||||
assert ret is None
|
||||
assert sched._finished_request_blocks == {}
|
||||
assert sched._newly_finished_push_blocks == {}
|
||||
|
||||
def test_request_finished_empty_blocks_does_not_arm_lease(self):
|
||||
"""Empty block-id groups should still complete cleanly without
|
||||
arming the lease/finished maps."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
request = _make_request(request_id="req-empty", is_d_side=False)
|
||||
delay, ret = sched.request_finished(request, ((),))
|
||||
|
||||
assert delay is False
|
||||
assert ret is not None
|
||||
assert "req-empty" not in sched._finished_request_blocks
|
||||
assert "req-empty" not in sched._newly_finished_push_blocks
|
||||
assert "req-empty" not in sched._reqs_need_send
|
||||
|
||||
def test_update_connector_output_unknown_request_is_noop(self):
|
||||
"""Idempotent cleanup: clearing a request that was never staged
|
||||
must not raise or mutate other state."""
|
||||
sched = make_nixl_push_scheduler()
|
||||
_stub_sw_clipping(sched)
|
||||
|
||||
# Stage one real request to ensure it's NOT touched.
|
||||
live = _make_request(request_id="req-live", is_d_side=False)
|
||||
sched.request_finished(live, ([1],))
|
||||
|
||||
sched.update_connector_output(
|
||||
KVConnectorOutput(
|
||||
finished_sending={"unknown-1"},
|
||||
finished_recving={"unknown-2"},
|
||||
invalid_block_ids=set(),
|
||||
)
|
||||
)
|
||||
|
||||
# Live entry untouched.
|
||||
assert "req-live" in sched._finished_request_blocks
|
||||
|
||||
|
||||
class TestPushWriterNegative:
|
||||
"""Failure / drop / idempotence paths in the writer thread."""
|
||||
|
||||
def test_pop_matching_registration_returns_none_when_empty(self):
|
||||
w = _StubWriterWorker.fresh()
|
||||
assert w._pop_matching_registration("nope") is None
|
||||
|
||||
def test_pop_matching_finished_blocks_returns_none_when_empty(self):
|
||||
w = _StubWriterWorker.fresh()
|
||||
assert w._pop_matching_finished_blocks("nope") is None
|
||||
|
||||
def test_pop_matching_registration_no_match_when_base_ids_differ(self):
|
||||
"""A registration whose base id (after stripping the random suffix)
|
||||
does NOT match the lookup request_id must not be popped."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
# Two unrelated requests: different base UUIDs, so stripping the
|
||||
# trailing ``-<8 hex>`` suffix still yields different base ids.
|
||||
unrelated_d = "cmpl-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa-0-11111111"
|
||||
lookup = "cmpl-bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb-0-22222222"
|
||||
assert get_base_request_id(unrelated_d) != get_base_request_id(lookup)
|
||||
|
||||
w._pending_d_registrations[unrelated_d] = _registration_data(unrelated_d)
|
||||
result = w._pop_matching_registration(lookup)
|
||||
assert result is None
|
||||
# Original entry untouched.
|
||||
assert unrelated_d in w._pending_d_registrations
|
||||
|
||||
def test_handle_push_reg_with_non_dict_payload_is_dropped(self, caplog):
|
||||
"""msgpack-encoded non-dict payload (e.g. a list) should be
|
||||
dropped without raising."""
|
||||
caplog.set_level(
|
||||
logging.CRITICAL,
|
||||
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
|
||||
)
|
||||
w = _StubWriterWorker.fresh()
|
||||
bad = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode([1, 2, 3])
|
||||
w._handle_push_reg_notif(bad)
|
||||
assert w._pending_d_registrations == {}
|
||||
assert w.start_push_calls == []
|
||||
|
||||
def test_handle_push_reg_with_non_string_request_id_is_dropped(self, caplog):
|
||||
"""request_id must be a str; integers, None, etc. must drop."""
|
||||
caplog.set_level(
|
||||
logging.CRITICAL,
|
||||
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
|
||||
)
|
||||
w = _StubWriterWorker.fresh()
|
||||
for bogus_rid in (123, None, 4.5, b"bytes-not-str"):
|
||||
payload = _registration_data("placeholder")
|
||||
payload["request_id"] = bogus_rid # type: ignore[assignment]
|
||||
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(payload)
|
||||
w._handle_push_reg_notif(notif)
|
||||
assert w._pending_d_registrations == {}
|
||||
assert w.start_push_calls == []
|
||||
|
||||
def test_handle_push_reg_idempotent_for_same_request_id(self):
|
||||
"""Receiving the same PUSH_REG twice (e.g. P retries after a
|
||||
flake) keeps the entry staged exactly once and never fires."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(
|
||||
_registration_data("req-dup")
|
||||
)
|
||||
w._handle_push_reg_notif(notif)
|
||||
w._handle_push_reg_notif(notif)
|
||||
assert "req-dup" in w._pending_d_registrations
|
||||
assert len(w._pending_d_registrations) == 1
|
||||
assert w.start_push_calls == []
|
||||
|
||||
def test_get_finished_enqueues_eviction_for_each_done_request(self):
|
||||
"""``get_finished`` must enqueue an eviction for every request
|
||||
in ``done_sending`` so the writer can drop stale matching state.
|
||||
Unlike the happy-path test, this verifies the *cardinality*: N
|
||||
completed requests -> N evictions, in order."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
with patch.object(
|
||||
NixlPushConnectorWorker.__mro__[1],
|
||||
"get_finished",
|
||||
return_value=({"req-1", "req-2", "req-3"}, set()),
|
||||
):
|
||||
done_sending, _ = w.get_finished()
|
||||
assert done_sending == {"req-1", "req-2", "req-3"}
|
||||
|
||||
evicted: list[str] = []
|
||||
while True:
|
||||
try:
|
||||
evicted.append(w._evict_finished_inbox.get_nowait())
|
||||
except queue.Empty:
|
||||
break
|
||||
assert sorted(evicted) == ["req-1", "req-2", "req-3"]
|
||||
|
||||
def test_get_finished_with_no_completions_does_not_enqueue_eviction(self):
|
||||
"""If there's nothing newly done, no eviction should be enqueued.
|
||||
The wake event IS still set because ``get_finished`` always wakes
|
||||
the writer to drain notifs."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
with patch.object(
|
||||
NixlPushConnectorWorker.__mro__[1],
|
||||
"get_finished",
|
||||
return_value=(set(), set()),
|
||||
):
|
||||
done_sending, done_recving = w.get_finished()
|
||||
assert done_sending == set()
|
||||
assert done_recving == set()
|
||||
assert w._evict_finished_inbox.qsize() == 0
|
||||
# Wake set so the writer drains NIXL notifs even when idle.
|
||||
assert w._push_writer_wake.is_set()
|
||||
|
||||
def test_get_new_notifs_unknown_request_is_logged_and_skipped(self, caplog):
|
||||
"""A completion notif for a request the worker doesn't know
|
||||
about should be logged but not crash."""
|
||||
caplog.set_level(
|
||||
logging.CRITICAL,
|
||||
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
|
||||
)
|
||||
w = _StubWriterWorker.fresh()
|
||||
w.transfer_topo = MagicMock()
|
||||
# Forward a completion notif for an unknown request_id.
|
||||
w._pending_completion_notifs.put(b"never-heard-of-you:1")
|
||||
|
||||
notified = w._get_new_notifs()
|
||||
assert notified == set()
|
||||
# Did not register anywhere.
|
||||
assert "never-heard-of-you" not in w._recving_transfers
|
||||
|
||||
def test_start_load_kv_with_empty_metadata_is_noop(self):
|
||||
"""Empty metadata must not wake the writer or enqueue anything."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
w._send_heartbeats = lambda metadata: None
|
||||
w._logical_to_kernel_block_ids = lambda x: x
|
||||
|
||||
meta = NixlConnectorMetadata()
|
||||
w.start_load_kv(meta)
|
||||
|
||||
assert w._reg_send_inbox.qsize() == 0
|
||||
assert w._finished_blocks_inbox.qsize() == 0
|
||||
# Wake should NOT be set if there was nothing to push.
|
||||
assert not w._push_writer_wake.is_set()
|
||||
|
||||
def test_get_new_notifs_extends_lease_on_heartbeat(self):
|
||||
"""``HB:`` notifs forwarded by the writer thread must extend the
|
||||
leases of tracked P-side requests on the engine main thread, and
|
||||
ignore request IDs that aren't being tracked."""
|
||||
w = _StubWriterWorker.fresh()
|
||||
w.transfer_topo = MagicMock()
|
||||
# _handle_heartbeat reads ``self._lease_extension`` (set in the
|
||||
# real ``__init__``).
|
||||
w._lease_extension = 10
|
||||
|
||||
# Tracked P-side requests with a lease about to expire.
|
||||
old_expiry = time.perf_counter() - 5.0
|
||||
w._reqs_to_send["req-a"] = old_expiry
|
||||
w._reqs_to_send["req-b"] = old_expiry
|
||||
|
||||
# Forwarded heartbeat covers a tracked request, an unknown one,
|
||||
# and another tracked one.
|
||||
w._pending_completion_notifs.put(b"HB:req-a,req-unknown,req-b")
|
||||
|
||||
notified = w._get_new_notifs()
|
||||
assert notified == set()
|
||||
|
||||
# Tracked leases were renewed strictly forward in time.
|
||||
now = time.perf_counter()
|
||||
for rid in ("req-a", "req-b"):
|
||||
assert w._reqs_to_send[rid] > old_expiry
|
||||
# New expiry must be roughly now + _lease_extension.
|
||||
assert w._reqs_to_send[rid] >= now
|
||||
# Unknown request must not be inserted by the heartbeat path.
|
||||
assert "req-unknown" not in w._reqs_to_send
|
||||
@@ -44,7 +44,7 @@ from vllm.v1.simple_kv_offload.metadata import (
|
||||
)
|
||||
|
||||
NIXL_WRAPPER_PATCH = (
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker.NixlWrapper"
|
||||
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -587,7 +587,9 @@ def test_cannot_recv():
|
||||
assert_scheduler_empty(scheduler)
|
||||
|
||||
|
||||
@patch("vllm.distributed.kv_transfer.kv_connector.v1.nixl.scheduler.current_platform")
|
||||
@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.
|
||||
|
||||
|
||||
@@ -524,3 +524,66 @@ def make_nixl_scheduler(
|
||||
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.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
|
||||
|
||||
# vllm_config is consulted for parallel_config.tensor_parallel_size.
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.parallel_config.tensor_parallel_size = 1
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user