[KVOffload][P2P] Well-known default host/port env vars and per-DP-rank control port (#47636)

Signed-off-by: Liran Schour <lirans@il.ibm.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
liranschour
2026-07-15 15:22:56 +03:00
committed by GitHub
co-authored by mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent 5811ed6a05
commit 615834ee58
13 changed files with 413 additions and 61 deletions
+12
View File
@@ -36,6 +36,18 @@ def test_nixl_side_channel_host_is_not_compile_factor(
assert "VLLM_NIXL_SIDE_CHANNEL_HOST" not in envs.compile_factors()
def test_p2p_side_channel_defaults_and_override(monkeypatch: pytest.MonkeyPatch):
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_HOST", raising=False)
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_PORT", raising=False)
assert envs.VLLM_P2P_SIDE_CHANNEL_HOST == "localhost"
assert envs.VLLM_P2P_SIDE_CHANNEL_PORT == 5710
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_HOST", "10.0.0.20")
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_PORT", "5799")
assert envs.VLLM_P2P_SIDE_CHANNEL_HOST == "10.0.0.20"
assert envs.VLLM_P2P_SIDE_CHANNEL_PORT == 5799
def test_getattr_with_cache(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("VLLM_HOST_IP", "1.1.1.1")
monkeypatch.setenv("VLLM_PORT", "1234")
@@ -14,7 +14,7 @@ Usage:
--port 8192 \
--prefiller-host 127.0.0.1 --prefiller-port 8100 \
--decoder-host 127.0.0.1 --decoder-port 8200 \
--p2p-connector-host 127.0.0.1 --p2p-connector-port 7777
--p2p-connector-host 127.0.0.1 --p2p-connector-port 5710
"""
import argparse
@@ -73,14 +73,23 @@ async def lifespan(app: FastAPI):
app.state.prefill_iterator = itertools.cycle(range(len(app.state.prefill_clients)))
app.state.decode_iterator = itertools.cycle(range(len(app.state.decode_clients)))
# Round-robin over each role's data-parallel replicas (independent of the
# instance iterators above). For dp_size=1 these yield only rank 0.
app.state.prefill_dp_iterator = itertools.cycle(
range(global_args.prefiller_dp_size)
)
app.state.decode_dp_iterator = itertools.cycle(range(global_args.decoder_dp_size))
mode = "decoder-first" if global_args.decoder_first else "prefiller-first"
pd_host = global_args.p2p_connector_host
pd_port = global_args.p2p_connector_port
n_pref = len(app.state.prefill_clients)
n_dec = len(app.state.decode_clients)
print(
f"Proxy ready [{mode}]: "
f"{len(app.state.prefill_clients)} prefiller(s), "
f"{len(app.state.decode_clients)} decoder(s). "
f"P2PConnector at {pd_host}:{pd_port}"
f"{n_pref} prefiller(s) x dp={global_args.prefiller_dp_size}, "
f"{n_dec} decoder(s) x dp={global_args.decoder_dp_size}. "
f"P2PConnector base at {pd_host}:{pd_port}"
)
yield
@@ -111,8 +120,9 @@ def parse_args():
p.add_argument(
"--p2p-connector-port",
type=int,
default=7777,
help="Port of the prefiller's P2PConnector ZMQ socket",
default=int(os.getenv("VLLM_P2P_SIDE_CHANNEL_PORT", "5710")),
help="Port of the prefiller's P2PConnector ZMQ socket "
"(default: $VLLM_P2P_SIDE_CHANNEL_PORT or 5710)",
)
# P2PConnector coordinates of the decoder — injected into prefill requests
# so the prefiller's submit_store can resolve the peer to push KV to.
@@ -125,8 +135,9 @@ def parse_args():
p.add_argument(
"--decoder-p2p-connector-port",
type=int,
default=7778,
help="Port of the decoder's P2PConnector ZMQ socket",
default=int(os.getenv("VLLM_P2P_SIDE_CHANNEL_PORT", "5710")) + 1,
help="Port of the decoder's P2PConnector ZMQ socket "
"(default: $VLLM_P2P_SIDE_CHANNEL_PORT + 1 or 5711)",
)
p.add_argument(
"--decoder-first",
@@ -134,6 +145,23 @@ def parse_args():
help="Send decode request before prefill so decoder is already "
"waiting when KV blocks arrive (decoder-first mode)",
)
p.add_argument(
"--prefiller-dp-size",
type=int,
default=1,
help="Data-parallel replica count of the prefiller. When >1 the proxy "
"round-robins prefill across ranks via the X-data-parallel-rank header "
"and injects remote_port = p2p-connector-port + rank into the decode "
"request so the decoder pulls KV from that replica's control socket. "
"Assumes a single prefiller instance (one host/port fronting N replicas).",
)
p.add_argument(
"--decoder-dp-size",
type=int,
default=1,
help="Data-parallel replica count of the decoder. When >1 the proxy "
"round-robins decode across ranks via the X-data-parallel-rank header.",
)
args = p.parse_args()
if len(args.prefiller_hosts) != len(args.prefiller_ports):
raise ValueError("Prefiller host/port count mismatch")
@@ -150,6 +178,23 @@ def _get_next(app, service: str):
return app.state.decode_clients[next(app.state.decode_iterator)]
def _next_dp_rank(app, service: str):
"""Advance the round-robin DP cursor for a role.
Returns (rank, header_rank). ``rank`` (0..dp_size-1) is always used for the
P2P remote_port arithmetic; ``header_rank`` is the same value when the role
has dp_size>1 and None otherwise (so dp=1 sends no header, matching the
single-replica behavior).
"""
if service == "prefill":
rank = next(app.state.prefill_dp_iterator)
dp_size = global_args.prefiller_dp_size
else:
rank = next(app.state.decode_dp_iterator)
dp_size = global_args.decoder_dp_size
return rank, (rank if dp_size > 1 else None)
def _auth_headers(request_id: str) -> dict:
headers: dict = {"X-Request-Id": request_id}
api_key = os.environ.get("OPENAI_API_KEY", "")
@@ -158,7 +203,7 @@ def _auth_headers(request_id: str) -> dict:
return headers
async def _prefill(client_info, endpoint, req_data, request_id):
async def _prefill(client_info, endpoint, req_data, request_id, dp_rank=None):
"""Send a prefill-only request (max_tokens=1) to the prefiller."""
data = req_data.copy()
data["kv_transfer_params"] = {
@@ -174,14 +219,21 @@ async def _prefill(client_info, endpoint, req_data, request_id):
data.pop("min_completion_tokens", None)
headers = _auth_headers(request_id)
if dp_rank is not None:
# Pin this prefill to a specific DP replica so its P2PConnector (bound
# at base_port + data_parallel_index) holds the produced KV blocks.
headers["X-data-parallel-rank"] = str(dp_rank)
resp = await client_info["client"].post(endpoint, json=data, headers=headers)
resp.raise_for_status()
await resp.aread()
return resp
async def _stream_decode(client_info, endpoint, req_data, request_id):
async def _stream_decode(client_info, endpoint, req_data, request_id, dp_rank=None):
headers = _auth_headers(request_id)
if dp_rank is not None:
# Round-robin this decode onto a specific DP replica of the decoder.
headers["X-data-parallel-rank"] = str(dp_rank)
async with client_info["client"].stream(
"POST", endpoint, json=req_data, headers=headers
) as resp:
@@ -195,24 +247,39 @@ async def _handle_completions(api: str, request: Request):
req_data = await request.json()
request_id = str(uuid.uuid4())
# Pick DP replicas for both roles up front (before any await) so the
# two round-robin advances are atomic together. Header rank is None for
# a role with dp_size==1 (no header → single replica, unchanged).
prefill_rank, prefill_hdr = _next_dp_rank(request.app, "prefill")
decode_rank, decode_hdr = _next_dp_rank(request.app, "decode")
prefill_client = _get_next(request.app, "prefill")
await _prefill(prefill_client, api, req_data, request_id)
await _prefill(prefill_client, api, req_data, request_id, dp_rank=prefill_hdr)
# Inject the prefiller's P2PConnector address so the decoder can pull
# KV blocks from it via the P2PConnector transport.
# KV blocks from it. remote_port = base + prefill_rank targets the
# replica that produced the KV (base+0 == base when dp=1).
req_data["kv_transfer_params"] = {
"prefill": {
"kv_request_id": request_id,
"remote_host": global_args.p2p_connector_host,
"remote_port": global_args.p2p_connector_port,
"remote_port": global_args.p2p_connector_port + prefill_rank,
},
}
decode_client = _get_next(request.app, "decode")
logger.debug("prefill=%s decode=%s", prefill_client, decode_client)
logger.debug(
"prefill=%s dp=%s decode=%s dp=%s",
prefill_client,
prefill_rank,
decode_client,
decode_rank,
)
async def generate():
async for chunk in _stream_decode(decode_client, api, req_data, request_id):
async for chunk in _stream_decode(
decode_client, api, req_data, request_id, dp_rank=decode_hdr
):
yield chunk
return StreamingResponse(generate(), media_type="application/json")
@@ -237,6 +304,10 @@ async def _handle_completions_decoder_first(api: str, request: Request):
req_data = await request.json()
request_id = str(uuid.uuid4())
# Pick DP replicas up front (see _handle_completions for rationale).
prefill_rank, prefill_hdr = _next_dp_rank(request.app, "prefill")
decode_rank, decode_hdr = _next_dp_rank(request.app, "decode")
prefill_client = _get_next(request.app, "prefill")
decode_client = _get_next(request.app, "decode")
@@ -245,7 +316,7 @@ async def _handle_completions_decoder_first(api: str, request: Request):
"prefill": {
"kv_request_id": request_id,
"remote_host": global_args.p2p_connector_host,
"remote_port": global_args.p2p_connector_port,
"remote_port": global_args.p2p_connector_port + prefill_rank,
},
}
@@ -255,7 +326,7 @@ async def _handle_completions_decoder_first(api: str, request: Request):
async def _run_decode():
try:
async for chunk in _stream_decode(
decode_client, api, decode_data, request_id
decode_client, api, decode_data, request_id, dp_rank=decode_hdr
):
await queue.put(("data", chunk))
except Exception as exc:
@@ -268,7 +339,9 @@ async def _handle_completions_decoder_first(api: str, request: Request):
# 2. Send prefill — blocks are computed and pushed to the decoder
try:
await _prefill(prefill_client, api, req_data, request_id)
await _prefill(
prefill_client, api, req_data, request_id, dp_rank=prefill_hdr
)
except Exception as exc:
logger.warning("decoder-first: prefill failed: %s", exc)
@@ -16,6 +16,12 @@
# NUM_DECODE_INSTANCES default 1
# PREFILLER_TP_SIZE default 1
# DECODER_TP_SIZE default 1
# DP_EP when set, deploy the decoder in DP-EP attention
# mode (dp=DECODER_TP_SIZE, tp=1,
# --enable-expert-parallel) instead of tensor
# parallel; the proxy round-robins decode across
# the DP replicas. Mirrors
# nixl_integration/run_accuracy_test.sh.
# GPU_MEMORY_UTILIZATION default 0.45
# MAX_MODEL_LEN default 512
# PREFILL_BLOCK_SIZE default 128
@@ -29,6 +35,8 @@
# NUM_PREFILL_INSTANCES=2 NUM_DECODE_INSTANCES=2 \
# bash tests/v1/kv_offload/tiering/p2p/run_accuracy_test.sh
# bash tests/v1/kv_offload/tiering/p2p/run_accuracy_test.sh --decoder-first
# DP_EP=1 DECODER_TP_SIZE=2 \
# bash tests/v1/kv_offload/tiering/p2p/run_accuracy_test.sh
set -xe
@@ -71,6 +79,14 @@ NUM_PREFILL_INSTANCES=${NUM_PREFILL_INSTANCES:-1}
NUM_DECODE_INSTANCES=${NUM_DECODE_INSTANCES:-1}
PREFILLER_TP_SIZE=${PREFILLER_TP_SIZE:-1}
DECODER_TP_SIZE=${DECODER_TP_SIZE:-1}
# DP-EP attention mode (see header). When DP_EP is set the decoder uses
# data-parallel replicas (dp=DECODER_TP_SIZE) that the proxy round-robins over.
DP_EP=${DP_EP:-}
if [[ -n "$DP_EP" ]]; then
DECODER_DP_SIZE=${DECODER_TP_SIZE}
else
DECODER_DP_SIZE=1
fi
GPU_MEMORY_UTILIZATION=${GPU_MEMORY_UTILIZATION:-0.45}
MAX_MODEL_LEN=${MAX_MODEL_LEN:-512}
PREFILL_BLOCK_SIZE=${PREFILL_BLOCK_SIZE:-128}
@@ -162,7 +178,11 @@ run_tests_for_model() {
echo "================================"
echo "Testing model: $model_name"
echo " prefillers=${NUM_PREFILL_INSTANCES} (tp=${PREFILLER_TP_SIZE})"
echo " decoders=${NUM_DECODE_INSTANCES} (tp=${DECODER_TP_SIZE})"
if [[ -n "$DP_EP" ]]; then
echo " decoders=${NUM_DECODE_INSTANCES} (dp-ep=${DECODER_TP_SIZE}, tp=1)"
else
echo " decoders=${NUM_DECODE_INSTANCES} (tp=${DECODER_TP_SIZE})"
fi
echo " decoder_first=${DECODER_FIRST}"
echo "================================"
@@ -241,9 +261,19 @@ run_tests_for_model() {
--block-size ${DECODE_BLOCK_SIZE} \
--gpu-memory-utilization ${GPU_MEMORY_UTILIZATION} \
--max-model-len ${MAX_MODEL_LEN} \
--tensor-parallel-size ${DECODER_TP_SIZE} \
--kv-transfer-config '${kv_cfg}'"
# DP-EP attention mode: data-parallel + expert-parallel decode replicas
# (dp=DECODER_TP_SIZE, tp=1) instead of tensor parallel. Mirrors
# nixl_integration/run_accuracy_test.sh.
if [[ -z "$DP_EP" ]]; then
BASE_CMD="${BASE_CMD} --tensor-parallel-size ${DECODER_TP_SIZE}"
else
echo "DP-EP Attention enabled, deploying decoder with dp=${DECODER_TP_SIZE} and tp=1"
BASE_CMD="${BASE_CMD} --data-parallel-size ${DECODER_TP_SIZE} \
--tensor-parallel-size 1 --enable-expert-parallel"
fi
if [[ -n "$VLLM_SERVE_EXTRA_ARGS" ]]; then
IFS=',' read -r -a extra_args <<< "$VLLM_SERVE_EXTRA_ARGS"
for arg in "${extra_args[@]}"; do
@@ -282,7 +312,8 @@ run_tests_for_model() {
--p2p-connector-host ${P2P_HOST} \
--p2p-connector-port ${PREFILL_PD_PORTS[0]} \
--decoder-p2p-connector-host ${P2P_HOST} \
--decoder-p2p-connector-port ${DECODE_PD_PORTS[0]}"
--decoder-p2p-connector-port ${DECODE_PD_PORTS[0]} \
--decoder-dp-size ${DECODER_DP_SIZE}"
if [[ "${DECODER_FIRST}" == "true" ]]; then
PROXY_CMD="${PROXY_CMD} --decoder-first"
@@ -183,6 +183,35 @@ class TestNixlTransportWithMockedAgent:
assert result.done == ()
assert result.failed == ()
def test_poll_peer_id_scopes_to_peer(self):
"""poll(peer_id) drains only that peer's transfers.
Regression: the transport is shared across peer sessions (e.g. a
single prefiller serving a DP>1 decoder). An unscoped poll by one
session used to consume and discard sibling sessions' completions,
starving them until timeout. poll(peer_id) must leave other peers'
transfers inflight.
"""
transport = self._make_transport()
transport.add_remote_peer("peer:1", b"meta", 0x1000, 8, 1024)
transport.add_remote_peer("peer:2", b"meta", 0x2000, 8, 1024)
tid1 = transport.write_blocks("peer:1", [0], [1])
tid2 = transport.write_blocks("peer:2", [2], [3])
transport._agent.check_xfer_state.return_value = "DONE"
# Polling peer:1 must not consume peer:2's completed transfer.
result = transport.poll(peer_id="peer:1")
assert tid1 in result.done
assert tid2 not in result.done
assert tid1 not in transport._inflight
assert tid2 in transport._inflight
# peer:2 sees its own completion when it polls.
result2 = transport.poll(peer_id="peer:2")
assert tid2 in result2.done
assert tid2 not in transport._inflight
def test_cancel_removes_inflight(self):
"""cancel removes transfers and releases handles."""
transport = self._make_transport()
+116 -2
View File
@@ -9,9 +9,11 @@ using fake transport and session objects.
from __future__ import annotations
import time
import uuid
from types import SimpleNamespace
import numpy as np
import pytest
from vllm.v1.kv_offload.base import LookupResult, ReqContext, ScheduleEndContext
from vllm.v1.kv_offload.tiering.base import JobMetadata, JobResult
@@ -598,7 +600,7 @@ class _ShutdownFakeData:
return list(self._still_queue[0])
return []
def poll(self):
def poll(self, peer_id=None):
self.poll_calls += 1
class _Empty:
@@ -831,7 +833,7 @@ class _FakeData:
self._inflight_done.append(tid)
return tid
def poll(self):
def poll(self, peer_id=None):
from vllm.v1.kv_offload.tiering.p2p.data.base import PollResult
done = self._inflight_done[:]
@@ -1373,3 +1375,115 @@ class TestConnectionDeathMidTransfer:
assert (900, False) not in finishes
assert (900, True) not in finishes
assert "req-store" in mgr_a._unbound_stores
# ---------------------------------------------------------------------------
# Tests for host/port resolution in __init__ (env-var defaults)
# ---------------------------------------------------------------------------
class TestBindHostPortDefaults:
"""host/port fall back to VLLM_P2P_SIDE_CHANNEL_* when not in config."""
@staticmethod
def _construct(monkeypatch, dp_index=0, **kwargs) -> P2PSecondaryTierManager:
"""Build a manager with the transports/file-mapper stubbed out.
The host is used verbatim (no resolution). The transport constructor
args are recorded on ``mgr._test_calls`` so tests can assert the ZMQ
identity (``host:port``) stays decoupled from the NIXL agent name
(a uuid).
"""
monkeypatch.setattr(
manager_module,
"FileMapper",
SimpleNamespace(
from_offloading_spec=lambda **_: SimpleNamespace(
get_run_config=lambda: {}
)
),
)
calls: dict = {}
monkeypatch.setattr(
manager_module,
"NixlTransport",
lambda agent_name, *a, **k: calls.update(nixl_name=agent_name)
or SimpleNamespace(),
)
monkeypatch.setattr(
manager_module,
"ZmqTransport",
lambda local_id, host, port, *a, **k: calls.update(
zmq_id=local_id, zmq_host=host, zmq_port=port
)
or SimpleNamespace(),
)
spec = SimpleNamespace(
block_size_factor=1,
vllm_config=SimpleNamespace(
parallel_config=SimpleNamespace(data_parallel_index=dp_index)
),
)
mgr = P2PSecondaryTierManager(spec, memoryview(b""), **kwargs)
mgr._test_calls = calls
return mgr
def test_defaults_from_env_unset(self, monkeypatch):
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_HOST", raising=False)
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_PORT", raising=False)
mgr = self._construct(monkeypatch)
# localhost default is used verbatim as the dial-back identity.
assert mgr._local_id == "localhost:5710"
def test_env_override(self, monkeypatch):
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_HOST", "10.1.2.3")
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_PORT", "5799")
mgr = self._construct(monkeypatch)
assert mgr._local_id == "10.1.2.3:5799"
def test_explicit_config_wins(self, monkeypatch):
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_HOST", "10.1.2.3")
monkeypatch.setenv("VLLM_P2P_SIDE_CHANNEL_PORT", "5799")
mgr = self._construct(monkeypatch, host="192.0.2.5", port=6001)
assert mgr._local_id == "192.0.2.5:6001"
def test_dp_index_offsets_default_port(self, monkeypatch):
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_HOST", raising=False)
monkeypatch.delenv("VLLM_P2P_SIDE_CHANNEL_PORT", raising=False)
mgr = self._construct(monkeypatch, dp_index=2)
assert mgr._local_id == "localhost:5712"
def test_dp_index_offsets_explicit_port(self, monkeypatch):
mgr = self._construct(monkeypatch, dp_index=1, host="192.0.2.5", port=6000)
assert mgr._local_id == "192.0.2.5:6001"
@pytest.mark.parametrize(
"bind_host", ["localhost", "127.0.0.1", "::1", "0.0.0.0", "::", "192.0.2.5"]
)
def test_host_used_verbatim(self, monkeypatch, bind_host):
# The host is never rewritten — loopbacks and wildcards alike become
# the dial-back identity verbatim (mirrors the NIXL connector).
mgr = self._construct(monkeypatch, host=bind_host, port=5710)
assert mgr._local_id == f"{bind_host}:5710"
def test_nixl_name_decoupled_from_identity(self, monkeypatch):
# The ZMQ identity is the verbatim host:port; the NIXL agent name is a
# uuid, distinct from the identity and never used as an address.
mgr = self._construct(monkeypatch, host="127.0.0.1", port=5710)
assert mgr._test_calls["zmq_host"] == "127.0.0.1"
assert mgr._test_calls["zmq_port"] == 5710
assert mgr._test_calls["zmq_id"] == "127.0.0.1:5710"
assert mgr._local_id == "127.0.0.1:5710"
# nixl_name is a valid uuid4 and not the host:port identity.
nixl_name = mgr._test_calls["nixl_name"]
assert nixl_name != mgr._local_id
assert uuid.UUID(nixl_name).version == 4
def test_same_host_port_gets_distinct_nixl_names(self, monkeypatch):
# The original collision: two peers sharing a host:port must still get
# distinct NIXL agent names so add_remote_agent doesn't reject a remote
# whose name equals the local. The per-process uuid guarantees this.
mgr_a = self._construct(monkeypatch, host="localhost", port=5710)
mgr_b = self._construct(monkeypatch, host="localhost", port=5710)
assert mgr_a._local_id == mgr_b._local_id == "localhost:5710"
assert mgr_a._nixl_agent_name != mgr_b._nixl_agent_name
@@ -110,7 +110,7 @@ class FakeDataTransport:
self._transfers[tid] = (peer_id, local_idxs, remote_idxs)
return tid
def poll(self):
def poll(self, peer_id=None):
from vllm.v1.kv_offload.tiering.p2p.data.base import PollResult
result = PollResult(done=list(self._poll_done), failed=list(self._poll_failed))