[Feature] Support Prefill-Decode disaggregation via vLLM KV transfer (#2220)
Signed-off-by: LiuBingyu <liubingyu62@gmail.com>
This commit is contained in:
1 parent
b88d3ce75e
commit
a5a4998ece
11 files changed
+1672
-48
No files matched your search
@@ -891,10 +891,11 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
Returns:
|
||||
(input_ids, input_embeds) for talker
|
||||
"""
|
||||
target_len = thinker_result_ids.shape[-1]
|
||||
im_start_indexes = torch.cat(
|
||||
(
|
||||
torch.nonzero(input_ids[0] == self.config.im_start_token_id).squeeze(),
|
||||
torch.tensor([thinker_result_ids.shape[-1]], device=input_ids.device, dtype=input_ids.dtype),
|
||||
torch.tensor([target_len], device=input_ids.device, dtype=input_ids.dtype),
|
||||
),
|
||||
dim=-1,
|
||||
) # Shape [n_starts + 1]; Take batch 0 since batched inference is not supported here.
|
||||
@@ -1029,8 +1030,35 @@ class Qwen3OmniMoeForConditionalGeneration(
|
||||
return last_talker_hidden, text_step, update_dict
|
||||
|
||||
def _get_talker_user_parts(self, im_start_index, segment_end_index, multimodal_mask, thinker_hidden, thinker_embed):
|
||||
clamped = min(
|
||||
segment_end_index,
|
||||
multimodal_mask.shape[0],
|
||||
thinker_hidden.shape[0],
|
||||
thinker_embed.shape[0],
|
||||
)
|
||||
if clamped < segment_end_index:
|
||||
logger.warning(
|
||||
"_get_talker_user_parts: segment_end_index %d clamped to %d "
|
||||
"(embed=%d, hidden=%d, mask=%d). "
|
||||
"This usually means _merge_pd_embeddings failed to merge "
|
||||
"prefill embeddings – check PD prefill_mm keys.",
|
||||
segment_end_index,
|
||||
clamped,
|
||||
thinker_embed.shape[0],
|
||||
thinker_hidden.shape[0],
|
||||
multimodal_mask.shape[0],
|
||||
)
|
||||
segment_end_index = clamped
|
||||
seg_len = segment_end_index - im_start_index
|
||||
if seg_len <= 0:
|
||||
return torch.empty(
|
||||
(0, self.config.talker_config.text_config.hidden_size),
|
||||
device=thinker_hidden.device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
user_talker_part = torch.empty(
|
||||
(segment_end_index - im_start_index, self.config.talker_config.text_config.hidden_size),
|
||||
(seg_len, self.config.talker_config.text_config.hidden_size),
|
||||
device=thinker_hidden.device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# Copyright 2025 The Qwen team.
|
||||
"""Stage input processor for Qwen3 Omni MoE: Thinker → Talker transition."""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
@@ -18,6 +19,12 @@ from vllm_omni.model_executor.stage_input_processors.tts_utils import (
|
||||
extract_speaker_from_request,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Pooling output layer keys: "0" = word embedding, "24" = accept_hidden_layer
|
||||
_EMBED_LAYER_KEY = "0"
|
||||
_HIDDEN_LAYER_KEY = "24"
|
||||
|
||||
|
||||
def _compute_talker_prompt_ids_length(info, device: torch.device | str = "cuda") -> int:
|
||||
im_start_token_id = 151644
|
||||
@@ -84,6 +91,95 @@ def _validate_stage_inputs(stage_list, engine_input_source):
|
||||
return stage.engine_outputs
|
||||
|
||||
|
||||
# =========================
|
||||
# PD disaggregation helpers
|
||||
# =========================
|
||||
|
||||
|
||||
def _get_prefill_stage(stage_list: list[Any], source_stage_id: int) -> Any | None:
|
||||
if source_stage_id <= 0:
|
||||
return None
|
||||
source_stage = stage_list[source_stage_id]
|
||||
if not getattr(source_stage, "is_decode_only", False):
|
||||
return None
|
||||
prev_stage = stage_list[source_stage_id - 1]
|
||||
if getattr(prev_stage, "is_prefill_only", False) and prev_stage.engine_outputs is not None:
|
||||
return prev_stage
|
||||
return None
|
||||
|
||||
|
||||
def _merge_pd_embeddings(
|
||||
decode_emb: torch.Tensor,
|
||||
decode_hid: torch.Tensor,
|
||||
prefill_mm: dict[str, Any],
|
||||
device: torch.device,
|
||||
expected_total: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Merge prefill prompt embeddings with decode generated embeddings.
|
||||
|
||||
In PD mode the prefill engine processes the prompt and the decode engine
|
||||
generates tokens starting from position 1. This function concatenates
|
||||
them, removing the overlapping token(s):
|
||||
|
||||
merged = prefill[:P] + decode[overlap:]
|
||||
|
||||
where overlap = P + D - expected_total.
|
||||
"""
|
||||
try:
|
||||
p_emb = prefill_mm[_EMBED_LAYER_KEY].detach().to(device=device, dtype=torch.float)
|
||||
p_hid = prefill_mm[_HIDDEN_LAYER_KEY].detach().to(device=device, dtype=torch.float)
|
||||
except (KeyError, AttributeError, TypeError) as exc:
|
||||
available_keys = list(prefill_mm.keys()) if isinstance(prefill_mm, dict) else type(prefill_mm).__name__
|
||||
logger.error(
|
||||
"_merge_pd_embeddings: failed to extract prefill embeddings (%s). "
|
||||
"Expected keys %r and %r, got: %s. "
|
||||
"Falling back to decode-only embeddings – talker user-segment will be degraded.",
|
||||
exc,
|
||||
_EMBED_LAYER_KEY,
|
||||
_HIDDEN_LAYER_KEY,
|
||||
available_keys,
|
||||
)
|
||||
return decode_emb, decode_hid
|
||||
|
||||
if p_emb.shape[0] == 0 or decode_emb.shape[0] == 0:
|
||||
return decode_emb, decode_hid
|
||||
|
||||
raw_total = p_emb.shape[0] + decode_emb.shape[0]
|
||||
overlap = max(0, raw_total - expected_total) if expected_total is not None else 0
|
||||
|
||||
merged_emb = torch.cat([p_emb, decode_emb[overlap:]], dim=0)
|
||||
merged_hid = torch.cat([p_hid, decode_hid[overlap:]], dim=0)
|
||||
return merged_emb, merged_hid
|
||||
|
||||
|
||||
def _get_prefill_multimodal_output(prefill_stage: Any, output_index: int) -> dict[str, Any] | None:
|
||||
"""Return multimodal_output dict from the PD prefill stage for a given batch index."""
|
||||
try:
|
||||
prefill_eos = prefill_stage.engine_outputs
|
||||
prefill_eo = prefill_eos[min(output_index, len(prefill_eos) - 1)]
|
||||
return prefill_eo.outputs[0].multimodal_output
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_tts_token_embedding(
|
||||
key: str,
|
||||
*,
|
||||
thinker_mm: dict[str, Any],
|
||||
prefill_mm: dict[str, Any] | None,
|
||||
device: torch.device,
|
||||
) -> torch.Tensor | None:
|
||||
"""Return TTS BOS/EOS/PAD embedding tensors for the talker projection path.
|
||||
|
||||
Values are taken from the current thinker (decode) ``multimodal_output``; in
|
||||
PD mode, missing keys may be filled from the paired prefill stage output.
|
||||
"""
|
||||
val = thinker_mm.get(key)
|
||||
if val is None and prefill_mm is not None:
|
||||
val = prefill_mm.get(key)
|
||||
return val.detach().to(device=device, dtype=torch.float) if val is not None else None
|
||||
|
||||
|
||||
# =========================
|
||||
# Thinker -> Talker
|
||||
# =========================
|
||||
@@ -111,8 +207,8 @@ def thinker2talker_async_chunk(
|
||||
all_token_ids = _ensure_list(all_token_ids)
|
||||
prompt_token_ids = _ensure_list(prompt_token_ids)
|
||||
talker_additional_info = {
|
||||
"thinker_prefill_embeddings": pooling_output.get("0").detach().cpu(),
|
||||
"thinker_hidden_states": pooling_output.get("24").detach().cpu(),
|
||||
"thinker_prefill_embeddings": pooling_output.get(_EMBED_LAYER_KEY).detach().cpu(),
|
||||
"thinker_hidden_states": pooling_output.get(_HIDDEN_LAYER_KEY).detach().cpu(),
|
||||
"thinker_sequences": all_token_ids,
|
||||
"thinker_input_ids": prompt_token_ids,
|
||||
# Provide thinker-side TTS token embeddings for talker projection
|
||||
@@ -161,7 +257,7 @@ def thinker2talker_async_chunk(
|
||||
|
||||
if output_token_ids:
|
||||
talker_additional_info["override_keys"] = ["thinker_decode_embeddings", "thinker_output_token_ids"]
|
||||
talker_additional_info["thinker_decode_embeddings"] = pooling_output.get("0").detach().cpu()
|
||||
talker_additional_info["thinker_decode_embeddings"] = pooling_output.get(_EMBED_LAYER_KEY).detach().cpu()
|
||||
talker_additional_info["thinker_output_token_ids"] = output_token_ids
|
||||
else:
|
||||
# When prefilling a chunked thinker, thinker_hidden_states needs to be updated.
|
||||
@@ -185,6 +281,9 @@ def thinker2talker(
|
||||
2. Split hidden states into: prompt embeddings + generated embeddings
|
||||
3. Package for talker with additional information
|
||||
|
||||
In PD disaggregation mode, merges prefill-stage prompt embeddings with
|
||||
decode-stage generated embeddings before handing off to the talker.
|
||||
|
||||
Args:
|
||||
stage_list: List of stage objects
|
||||
engine_input_source: Source stage IDs (typically [0] for thinker)
|
||||
@@ -199,21 +298,49 @@ def thinker2talker(
|
||||
|
||||
device = torch.device(current_platform.device_type)
|
||||
|
||||
# PD disaggregation: look up the preceding prefill stage (if any)
|
||||
source_stage_id = engine_input_source[0]
|
||||
prefill_stage = _get_prefill_stage(stage_list, source_stage_id)
|
||||
|
||||
# Process each thinker output
|
||||
for i, thinker_output in enumerate(thinker_outputs):
|
||||
output = thinker_output.outputs[0]
|
||||
thinker_mm = output.multimodal_output
|
||||
# Full thinker embedding sequence for the talker: single thinker engine in the
|
||||
# non-PD path; after optional merge with prefill-side tensors in PD mode.
|
||||
thinker_emb = thinker_mm[_EMBED_LAYER_KEY].detach().to(device=device, dtype=torch.float)
|
||||
thinker_hid = thinker_mm[_HIDDEN_LAYER_KEY].detach().to(device=device, dtype=torch.float)
|
||||
|
||||
prefill_mm: dict[str, Any] | None = None
|
||||
if prefill_stage is not None:
|
||||
prefill_mm = _get_prefill_multimodal_output(prefill_stage, i)
|
||||
|
||||
if prefill_mm is not None:
|
||||
expected_total = len(thinker_output.prompt_token_ids) + len(output.token_ids)
|
||||
try:
|
||||
thinker_emb, thinker_hid = _merge_pd_embeddings(
|
||||
thinker_emb, thinker_hid, prefill_mm, device, expected_total=expected_total
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("[PD] Could not merge prefill embeddings: %s", exc)
|
||||
|
||||
info = {
|
||||
"thinker_prefill_embeddings": output.multimodal_output["0"].detach().to(device=device, dtype=torch.float),
|
||||
"thinker_hidden_states": output.multimodal_output["24"].detach().to(device=device, dtype=torch.float),
|
||||
"thinker_prefill_embeddings": thinker_emb,
|
||||
"thinker_hidden_states": thinker_hid,
|
||||
"thinker_sequences": (
|
||||
thinker_output.prompt_token_ids + output.token_ids
|
||||
), # the thinker_sequences is the whole ids
|
||||
"thinker_input_ids": thinker_output.prompt_token_ids,
|
||||
# Provide thinker-side TTS token embeddings for talker projection
|
||||
"tts_bos_embed": output.multimodal_output["tts_bos_embed"].detach().to(device=device, dtype=torch.float),
|
||||
"tts_eos_embed": output.multimodal_output["tts_eos_embed"].detach().to(device=device, dtype=torch.float),
|
||||
"tts_pad_embed": output.multimodal_output["tts_pad_embed"].detach().to(device=device, dtype=torch.float),
|
||||
"tts_bos_embed": _resolve_tts_token_embedding(
|
||||
"tts_bos_embed", thinker_mm=thinker_mm, prefill_mm=prefill_mm, device=device
|
||||
),
|
||||
"tts_eos_embed": _resolve_tts_token_embedding(
|
||||
"tts_eos_embed", thinker_mm=thinker_mm, prefill_mm=prefill_mm, device=device
|
||||
),
|
||||
"tts_pad_embed": _resolve_tts_token_embedding(
|
||||
"tts_pad_embed", thinker_mm=thinker_mm, prefill_mm=prefill_mm, device=device
|
||||
),
|
||||
}
|
||||
speaker = extract_speaker_from_prompt(prompt, index=i)
|
||||
if speaker is not None:
|
||||
|
||||
Reference in new issue
Block a user