[Feature] Support Prefill-Decode disaggregation via vLLM KV transfer (#2220)

Signed-off-by: LiuBingyu <liubingyu62@gmail.com>
This commit is contained in:
Bingyu (Spencer) Liu authored and GitHub committed 2026-04-17 18:43:17 +08:00
1 parent b88d3ce75e
commit a5a4998ece
11 files changed
+1672 -48

No files matched your search

+46
View File
@@ -25,6 +25,7 @@ from typing import TYPE_CHECKING, Any
import janus
import torch
from omegaconf import OmegaConf
from vllm import envs as vllm_envs
from vllm.engine.arg_utils import EngineArgs
from vllm.inputs import PromptType
from vllm.logger import init_logger
@@ -79,6 +80,7 @@ from vllm_omni.engine.stage_init_utils import (
setup_stage_devices,
terminate_alive_proc,
)
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import (
inject_omni_kv_config,
load_and_resolve_stage_configs,
@@ -902,6 +904,7 @@ class AsyncOmniEngine:
self._initialize_janus_queues()
self._initialize_stages(stage_init_timeout)
pd_config = self._detect_pd_config()
orchestrator = Orchestrator(
request_async_queue=self.request_queue.async_q,
output_async_queue=self.output_queue.async_q,
@@ -910,6 +913,7 @@ class AsyncOmniEngine:
stage_clients=self.stage_clients,
output_processors=self.output_processors,
stage_vllm_configs=self.stage_vllm_configs,
pd_config=pd_config,
)
if not startup_future.done():
startup_future.set_result(asyncio.get_running_loop())
@@ -1131,6 +1135,48 @@ class AsyncOmniEngine:
cache_config = AsyncOmniEngine._get_default_cache_config(cache_backend)
return cache_config
def _detect_pd_config(self) -> dict[str, Any] | None:
"""Detect PD (Prefill-Decode) disaggregation config from stage_configs.
Returns a dict with 'pd_pair' and 'bootstrap_addr', or None.
"""
pd_pair = PDDisaggregationMixin.detect_pd_separation_from_stage_configs(self.stage_configs)
if pd_pair is None:
return None
prefill_idx, decode_idx = pd_pair
# Extract bootstrap address from prefill stage engine_args
bootstrap_addr: str | None = None
try:
prefill_cfg = self.stage_configs[prefill_idx]
ea = getattr(prefill_cfg, "engine_args", None)
kv_cfg = getattr(ea, "kv_transfer_config", None) if ea is not None else None
if kv_cfg is not None:
port = vllm_envs.VLLM_MOONCAKE_BOOTSTRAP_PORT
kv_ip = getattr(kv_cfg, "kv_ip", None) or "127.0.0.1"
bootstrap_addr = f"http://{kv_ip}:{port}"
except Exception as exc:
logger.warning("[AsyncOmniEngine] Could not extract PD bootstrap address: %s", exc)
logger.info(
"[AsyncOmniEngine] PD disaggregation detected: prefill=stage-%d, decode=stage-%d, bootstrap=%s",
prefill_idx,
decode_idx,
bootstrap_addr,
)
prefill_engine_id: str | None = None
try:
prefill_client = self.stage_clients[prefill_idx]
kv_cfg = getattr(getattr(prefill_client, "vllm_config", None), "kv_transfer_config", None)
prefill_engine_id = getattr(kv_cfg, "engine_id", None)
except Exception as exc:
logger.warning("[AsyncOmniEngine] Could not extract prefill engine_id: %s", exc)
return {
"pd_pair": (prefill_idx, decode_idx),
"bootstrap_addr": bootstrap_addr,
"prefill_engine_id": prefill_engine_id,
}
@staticmethod
def _create_default_diffusion_stage_cfg(kwargs: dict[str, Any]) -> list:
"""Create a default single-stage diffusion config from kwargs."""
+131 -1
View File
@@ -42,6 +42,7 @@ def build_engine_core_request_from_tokens(
params: SamplingParams | PoolingParams,
arrival_time: float | None = None,
model_config: ModelConfig | None = None,
mm_features: list | None = None,
) -> OmniEngineCoreRequest:
"""Build an OmniEngineCoreRequest directly from an OmniTokensPrompt.
@@ -76,7 +77,7 @@ def build_engine_core_request_from_tokens(
return OmniEngineCoreRequest(
request_id=request_id,
prompt_token_ids=prompt_token_ids,
mm_features=None,
mm_features=mm_features,
sampling_params=sampling_params,
pooling_params=pooling_params,
arrival_time=arrival_time,
@@ -104,6 +105,8 @@ class OrchestratorRequestState:
# Metrics: timestamp when request was submitted to each stage
stage_submit_ts: dict[int, float] = field(default_factory=dict)
mm_processor_kwargs: dict | None = None
mm_features: list | None = None
class Orchestrator:
@@ -123,6 +126,7 @@ class Orchestrator:
stage_vllm_configs: list[Any],
*,
async_chunk: bool = False,
pd_config: dict[str, Any] | None = None,
) -> None:
self.request_async_queue = request_async_queue
self.output_async_queue = output_async_queue
@@ -135,6 +139,16 @@ class Orchestrator:
self.output_processors: list[Any] = output_processors
self.stage_vllm_configs: list[Any] = stage_vllm_configs
# PD disaggregation state
self._pd_pair: tuple[int, int] | None = None
self._pd_bootstrap_addr: str | None = None
self._pd_prefill_engine_id: str | None = None
self._pd_kv_params: dict[str, Any] = {}
if pd_config is not None:
self._pd_pair = pd_config.get("pd_pair")
self._pd_bootstrap_addr = pd_config.get("bootstrap_addr")
self._pd_prefill_engine_id = pd_config.get("prefill_engine_id")
# Per-request state
self.request_states: dict[str, OrchestratorRequestState] = {}
@@ -359,6 +373,23 @@ class Orchestrator:
}
)
# PD disaggregation: extract KV transfer params from prefill stage output
if self._pd_pair is not None and finished and stage_id == self._pd_pair[0]:
kv_params = getattr(output, "kv_transfer_params", None)
if kv_params is not None:
self._pd_kv_params[req_id] = kv_params if isinstance(kv_params, dict) else dict(kv_params)
logger.debug(
"[Orchestrator][PD] stored kv_transfer_params for req=%s (keys=%s)",
req_id,
list(self._pd_kv_params[req_id].keys()),
)
else:
logger.warning(
"[Orchestrator][PD] prefill stage output for req=%s has no kv_transfer_params; "
"KV transfer may fail. Ensure apply_mooncake_connector_patch() was called.",
req_id,
)
if (
finished
and stage_id < req_state.final_stage_id
@@ -371,6 +402,8 @@ class Orchestrator:
await self._forward_to_next_stage(req_id, stage_id, output, req_state)
if finished and stage_id == req_state.final_stage_id:
# PD: clean up any lingering KV params for this request
self._pd_kv_params.pop(req_id, None)
self._cfg_tracker.cleanup_parent(req_id)
self.request_states.pop(req_id, None)
@@ -418,6 +451,51 @@ class Orchestrator:
else:
await self._forward_to_next_stage(req_id, stage_id, raw_output, req_state)
def _build_pd_decode_params(self, req_id: str, sp: Any) -> Any:
"""Build decode-side sampling params with KV transfer params for PD routing.
Clones the sampling params and injects kv_transfer_params that tell the
decode engine where to pull the KV cache from (prefill engine's bootstrap addr).
"""
sp = sp.clone()
if sp.extra_args is None:
sp.extra_args = {}
# Get KV params captured from the prefill output (must include remote_request_id).
kv_prefill_params = self._pd_kv_params.pop(req_id, None)
if not kv_prefill_params or "remote_request_id" not in kv_prefill_params:
raise RuntimeError(
f"[Orchestrator][PD] Missing prefill kv_transfer_params.remote_request_id for req={req_id}"
)
decode_kv_params: dict[str, Any] = {
"transfer_id": f"xfer-{req_id}",
}
if self._pd_bootstrap_addr:
decode_kv_params["remote_bootstrap_addr"] = self._pd_bootstrap_addr
if self._pd_prefill_engine_id:
decode_kv_params["remote_engine_id"] = self._pd_prefill_engine_id
# Overlay params from prefill side (includes remote_request_id set by monkey patch).
decode_kv_params.update(kv_prefill_params)
# Ensure these flags are set correctly after any overlay.
decode_kv_params["do_remote_prefill"] = True
decode_kv_params["do_remote_decode"] = False
if not decode_kv_params.get("transfer_id"):
decode_kv_params["transfer_id"] = f"xfer-{req_id}"
sp.extra_args["kv_transfer_params"] = decode_kv_params
logger.debug(
"[Orchestrator][PD] decode kv_transfer_params for req=%s: %s",
req_id,
decode_kv_params,
)
return sp
def _build_stage_metrics(
self,
stage_id: int,
@@ -540,6 +618,52 @@ class Orchestrator:
req_state.stage_submit_ts[next_stage_id] = _time.time()
return
# PD disaggregation: prefill → decode routing uses original prompt + KV transfer params
if self._pd_pair is not None and (stage_id, next_stage_id) == self._pd_pair:
# Save prefill stage outputs so thinker2talker can merge embeddings later
self.stage_clients[stage_id].set_engine_outputs([output])
params = self._build_pd_decode_params(req_id, params)
# Use the original user prompt for the decode stage (not processed embeddings)
original_prompt = req_state.prompt
raw_decode_inputs = [original_prompt] if not isinstance(original_prompt, list) else original_prompt
decode_inputs: list[dict[str, Any]] = []
for decode_input in raw_decode_inputs:
if isinstance(decode_input, dict):
decode_inputs.append(decode_input)
continue
prompt_token_ids = getattr(decode_input, "prompt_token_ids", None)
if prompt_token_ids is None:
raise TypeError(
"[Orchestrator][PD] decode input must be dict or have prompt_token_ids, "
f"got {type(decode_input).__name__} for req={req_id}"
)
decode_inputs.append({"prompt_token_ids": list(prompt_token_ids)})
for decode_input in decode_inputs:
request = build_engine_core_request_from_tokens(
request_id=req_id,
prompt=decode_input,
params=params,
model_config=self.stage_vllm_configs[next_stage_id].model_config,
mm_features=req_state.mm_features, # Pass mm_features for M-RoPE
)
request.external_req_id = request.request_id
self.output_processors[next_stage_id].add_request(
request=request,
prompt=None,
parent_req=None,
request_index=0,
queue=None,
)
await next_client.add_request_async(request)
req_state.stage_submit_ts[next_stage_id] = _time.time()
return
self.stage_clients[stage_id].set_engine_outputs([output])
# Process inputs for next stage
@@ -558,11 +682,16 @@ class Orchestrator:
# Build and submit requests for each input
for next_input in next_inputs:
# Only AR thinker stages consume encoder mm_features; downstream
# (talker/code2wav/…) must not see them (avoids encoder-cache misses).
_ms = getattr(next_client, "model_stage", None)
_mm_features = req_state.mm_features if _ms == "thinker" else None
request = build_engine_core_request_from_tokens(
request_id=req_id,
prompt=next_input,
params=params,
model_config=self.stage_vllm_configs[next_stage_id].model_config,
mm_features=_mm_features,
)
# TODO: Here we directly use the req id to assign.
@@ -644,6 +773,7 @@ class Orchestrator:
prompt=original_prompt,
sampling_params_list=sampling_params_list,
final_stage_id=final_stage_id,
mm_features=getattr(prompt, "mm_features", None), # Save mm_features for PD
)
req_state.stage_submit_ts[stage_id] = _time.time()
self.request_states[request_id] = req_state
+2 -3
View File
@@ -233,10 +233,9 @@ class OmniRequestState(RequestState):
# Reuse base text/logprobs logic, then annotate with pooling_result.
base_output = super()._new_completion_output(token_ids, finish_reason, stop_reason, routed_experts)
try:
if not hasattr(base_output, "multimodal_output"):
setattr(base_output, "multimodal_output", {})
if self.mm_accumulated is not None:
# Attach accumulated multimodal dict on the completion output
if not hasattr(base_output, "multimodal_output"):
setattr(base_output, "multimodal_output", {})
mm_out = getattr(base_output, "multimodal_output")
if isinstance(mm_out, dict):
for k, v in self.mm_accumulated.items():