[3/5][core]refactor communication layer: PR 3 of 5, all other models in non async mode (#3719)

Signed-off-by: natureofnature <wzliu@connect.hku.hk>
This commit is contained in:
NATURE authored and GitHub committed 2026-05-28 14:06:41 +08:00
1 parent 0f3264a9c0
commit 3a347b10b0
38 files changed
+3021 -275

No files matched your search

+69 -6
View File
@@ -84,11 +84,23 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin):
self.inputs_embeds = self._make_buffer(self.max_num_tokens, self.hidden_size, dtype=self.dtype, numpy=False)
# Initialize KV cache manager (preserve vllm_config fallback behavior)
self.kv_transfer_manager = OmniKVTransferManager.from_vllm_config(self.vllm_config, self.model_config)
# Only Qwen3-Omni currently consumes the connector-based full-payload
# handoff added in this PR. Other model architectures (e.g. Bagel
# diffusion) retain their pre-existing runner behavior so this PR
# does not perturb them.
if getattr(self.model_config, "model_arch", None) == "Qwen3OmniMoeForConditionalGeneration":
# Worker-connector init is gated by a per-`model_arch` allowlist
# (covers both producer-side and consumer-side runners for the
# arches below). Consumer-wait stages must be registered
# separately as `(model_arch, model_stage)` tuples in
# `omni_scheduling_coordinator._FULL_PAYLOAD_INPUT_STAGES`;
# forgetting that produces a Stage-1 hang on the consumer.
_OMNI_CONNECTOR_INIT_ARCHS = {
"Qwen3OmniMoeForConditionalGeneration",
"Qwen2_5OmniForConditionalGeneration",
"CovoAudioForConditionalGeneration",
"MiMoAudioModel",
"Qwen3TTSTalkerForConditionalGeneration",
"Qwen3TTSCode2Wav",
"CosyVoice3Model",
"DyninOmniForConditionalGeneration",
}
if getattr(self.model_config, "model_arch", None) in _OMNI_CONNECTOR_INIT_ARCHS:
self.init_omni_connectors(
vllm_config=self.vllm_config,
model_config=self.model_config,
@@ -109,6 +121,57 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin):
with maybe_disable_pin_memory_for_ray(self, total_bytes):
return super()._make_buffer(*size, dtype=dtype, numpy=numpy)
def _build_model_sampler_output_token_ids(self) -> list[list[int]]:
"""Build decoded-token history for custom model samplers.
vLLM only populates sampling_metadata.output_token_ids when penalties or
logits processors require it. CosyVoice3's custom RAS sampler also
depends on this history, so we reconstruct it directly from the input
batch for prefer_model_sampler models.
"""
req_output_token_ids = getattr(self.input_batch, "req_output_token_ids", [])
req_ids = list(getattr(self.input_batch, "req_ids", []))
output_token_ids = [list(req_output_token_ids[idx] or []) for idx in range(len(req_ids))]
sampled_token_ids_cpu = getattr(self.input_batch, "sampled_token_ids_cpu", None)
async_copy_ready_event = getattr(self.input_batch, "async_copy_ready_event", None)
prev_req_id_to_index = getattr(self.input_batch, "prev_req_id_to_index", None)
if sampled_token_ids_cpu is None or not output_token_ids or prev_req_id_to_index is None:
return output_token_ids
sampled_token_ids: list[list[int]] | None = None
for index, req_id in enumerate(req_ids):
prev_index = prev_req_id_to_index.get(req_id)
if prev_index is None:
continue
req_history = output_token_ids[index]
if not req_history or req_history[-1] != -1:
continue
if sampled_token_ids is None:
assert async_copy_ready_event is not None
async_copy_ready_event.synchronize()
sampled_token_ids = sampled_token_ids_cpu.tolist()
new_ids = list(sampled_token_ids[prev_index])
if not new_ids:
continue
num_sampled_ids = len(new_ids) if new_ids[-1] != -1 else new_ids.index(-1)
first_placeholder = req_history.index(-1)
num_placeholders = len(req_history) - first_placeholder
num_to_replace = min(num_sampled_ids, num_placeholders)
req_history[first_placeholder : first_placeholder + num_to_replace] = new_ids[:num_to_replace]
for index, req_history in enumerate(output_token_ids):
if -1 in req_history:
output_token_ids[index] = req_history[: req_history.index(-1)]
return output_token_ids
def _sampling_metadata_for_model_sampler(self, sampling_metadata):
output_token_ids = self._build_model_sampler_output_token_ids()
if output_token_ids == sampling_metadata.output_token_ids:
return sampling_metadata
return replace(sampling_metadata, output_token_ids=output_token_ids)
def _request_final_stage_id(self, req_id: str) -> int | None:
info = self.model_intermediate_buffer.get(req_id)
if not isinstance(info, dict):
@@ -974,7 +1037,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin):
req_hidden_states_cpu[rid] = hidden_states[start:end].detach().to("cpu").contiguous()
pooler_output = []
for rid in req_ids_output_copy:
for out_idx, rid in enumerate(req_ids_output_copy):
if rid not in downstream_req_id_set:
pooler_output.append({})
continue
@@ -59,10 +59,18 @@ class GPUGenerationModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Scope full-payload connector init to Qwen3-Omni: other generation
# models (e.g. Bagel DiT) retain their pre-existing runner setup
# so this refactor does not perturb them.
if getattr(self.model_config, "model_arch", None) == "Qwen3OmniMoeForConditionalGeneration":
# Mirrors the init allowlist in gpu_ar_model_runner.py.
_OMNI_CONNECTOR_INIT_ARCHS = {
"Qwen3OmniMoeForConditionalGeneration",
"Qwen2_5OmniForConditionalGeneration",
"CovoAudioForConditionalGeneration",
"MiMoAudioModel",
"Qwen3TTSTalkerForConditionalGeneration",
"Qwen3TTSCode2Wav",
"CosyVoice3Model",
"DyninOmniForConditionalGeneration",
}
if getattr(self.model_config, "model_arch", None) in _OMNI_CONNECTOR_INIT_ARCHS:
self.init_omni_connectors(
vllm_config=self.vllm_config,
model_config=self.model_config,
@@ -299,7 +307,6 @@ class GPUGenerationModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin
num_tokens_padded,
intermediate_tensors,
)
# [Omni] Pass token counts per request for code2wav output slicing
model_kwargs["seq_token_counts"] = tokens
+8 -5
View File
@@ -361,12 +361,15 @@ class OmniGPUModelRunner(GPUModelRunner):
# Remove finished requests from the cached states.
# cleanup_finished_request lives on OmniConnectorModelRunnerMixin and
# is only safe to call once init_omni_connectors() has populated the
# mixin state. Archs that inherit the method via MRO without running
# that init must be skipped, so probe a mixin-owned attribute as the
# "state initialized" gate.
# is only safe to call once init_omni_connectors() has finished
# populating mixin state (it sets ``_omni_connector_initialized = True``
# at the very end). Archs that inherit the method via MRO without
# running that init must be skipped, so gate on the explicit flag
# rather than probing private attribute names.
cleanup_finished_request = (
getattr(self, "cleanup_finished_request", None) if hasattr(self, "_request_ids_mapping") else None
getattr(self, "cleanup_finished_request", None)
if getattr(self, "_omni_connector_initialized", False)
else None
)
for req_id in scheduler_output.finished_req_ids:
self.requests.pop(req_id, None)
@@ -46,6 +46,27 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
def should_accumulate_full_payload_output(model_config, custom_process_func) -> bool:
"""Producer-side structural gate.
Fires iff the stage explicitly declares a downstream full-payload
producer hook via ``custom_process_next_stage_input_func``. Consumer
stages may have ``custom_process_input_func`` values that can be
mechanically derived to ``*_full_payload`` helper names in the same
module; those are intentionally not enough to make the stage a producer.
"""
if custom_process_func is None:
return False
if getattr(model_config, "async_chunk", False):
return False
if getattr(model_config, "final_output", False):
return False
next_stage_func = getattr(model_config, "custom_process_next_stage_input_func", None)
if not isinstance(next_stage_func, str) or not next_stage_func:
return False
return getattr(model_config, "model_stage", None) is not None
class OmniConnectorModelRunnerMixin:
"""Unified data-plane communication mixin for Model Runners.
@@ -189,6 +210,13 @@ class OmniConnectorModelRunnerMixin:
)
self._save_thread.start()
# Explicit "fully initialised" marker so other parts of the runner
# (e.g. _update_states cleanup) can branch on a stable contract
# instead of probing for private mixin attribute names. Must be set
# only after every field above has been bound, so a partially
# constructed mixin is never observable as initialised.
self._omni_connector_initialized = True
def shutdown_omni_connectors(self) -> None:
"""Stop background threads and release connector resources."""
self._stop_event.set()
@@ -217,6 +245,30 @@ class OmniConnectorModelRunnerMixin:
saves is added to ``_deferred_send_cleanup`` so the bg save's
decrement path drains it without leaving orphans.
"""
# Force-flush any pending full-payload accumulator entry before
# cleanup proceeds. Without this, finished requests with no
# downstream consumer (e.g. text-only on multi-modal arch) leave
# the entry orphaned in _pending_full_payload_send across requests,
# which empirically destabilises subsequent thinker forwards by
# making prefix-cache reuse observe stale accumulator state. The
# flush is idempotent when the entry has already been flushed by the
# scheduler-driven path, but this cleanup path runs for every request,
# so skip it entirely when the request never accumulated a payload.
if req_id in self._pending_full_payload_send:
try:
self.flush_full_payload_outputs({req_id})
except Exception:
# Cleanup must still proceed regardless of flush errors here --
# we already gated on ``_omni_connector_initialized`` upstream,
# so any exception here reflects a real connector-side issue
# (shared memory corruption, background thread crash) worth
# surfacing rather than silently swallowing.
logger.warning(
"flush_full_payload_outputs(%s) raised during cleanup; continuing tear-down.",
req_id,
exc_info=True,
)
ext_id = self._request_ids_mapping.pop(req_id, None)
keys_to_clean: list[str] = [req_id]
if ext_id is not None and ext_id != req_id:
@@ -684,6 +736,27 @@ class OmniConnectorModelRunnerMixin:
_custom_process_func, both of which are set at init time. Avoid
the per-step dynamic import inside the model decode loop.
"""
if getattr(self, "_omni_connector", None) is None:
# No connector at all: send_full_payload_outputs would no-op.
# Skip the per-step accumulator+build that would otherwise be
# silently discarded. Defends against a terminal stage whose
# custom_process_input_func has a *_full_payload derivative in
# the same module (e.g. dynin stage 2 token2image_to_token2audio
# in pipelines that don't configure any connector at all).
#
# Known limitation: a *terminal-consumer* stage that has a
# connector configured for receiving upstream input is NOT
# caught here -- ``_omni_connector`` is non-None for it, and
# ``_load_custom_func`` may still resolve a ``*_full_payload``
# derivative from this stage's ``custom_process_input_func``.
# In that case the accumulator builds payloads that
# ``send_full_payload_outputs`` later drops via its own
# connector-side checks (wasted CPU, not a functional bug).
# A topology-aware gate (explicit producer field or pipeline
# is_terminal info) would close the gap; that change is out
# of scope for this PR.
self._should_accumulate_full_payload_output_cached = False
return False
cached = getattr(self, "_should_accumulate_full_payload_output_cached", None)
if cached is not None:
return cached
@@ -691,19 +764,12 @@ class OmniConnectorModelRunnerMixin:
if model_config is None:
self._should_accumulate_full_payload_output_cached = False
return False
if getattr(model_config, "model_arch", None) == "Qwen3OmniMoeForConditionalGeneration":
from vllm_omni.model_executor.stage_input_processors.qwen3_omni import (
should_accumulate_qwen3_omni_full_payload_output,
)
result = should_accumulate_qwen3_omni_full_payload_output(
model_config,
getattr(self, "_custom_process_func", None),
)
self._should_accumulate_full_payload_output_cached = result
return result
self._should_accumulate_full_payload_output_cached = False
return False
result = should_accumulate_full_payload_output(
model_config,
getattr(self, "_custom_process_func", None),
)
self._should_accumulate_full_payload_output_cached = result
return result
@staticmethod
def _new_full_payload_accumulator(output: dict[str, Any]):
@@ -729,6 +795,58 @@ class OmniConnectorModelRunnerMixin:
output[k] = tensors[0] if len(tensors) == 1 else torch.cat(tensors, dim=0)
return output, request
def _resolve_full_payload_replace_keys(self) -> frozenset:
"""Per-model REPLACE-key set for the full-payload accumulator.
Looked up from the stage-input-processor module that ships the model's sync builder
(`model_config.custom_process_input_func.__module__`). The module
declares ``_FULL_PAYLOAD_REPLACE_KEYS: frozenset[str]``; if absent,
returns the empty set.
Cached per instance. Keys in this set use REPLACE semantics in the
accumulator (subsequent emissions discard prior chunks) instead of
the default CONCAT semantics. Use for tensors that carry the full
result so far rather than per-step deltas (e.g. ``model_outputs``).
"""
cached = getattr(self, "_full_payload_replace_keys_cached", None)
if cached is not None:
return cached
proc = getattr(self, "_custom_process_func", None)
if proc is None:
self._full_payload_replace_keys_cached = frozenset()
return self._full_payload_replace_keys_cached
module_name = getattr(proc, "__module__", None)
if module_name is None:
self._full_payload_replace_keys_cached = frozenset()
return self._full_payload_replace_keys_cached
try:
import sys as _sys
mod = _sys.modules.get(module_name) or importlib.import_module(module_name)
keys = getattr(mod, "_FULL_PAYLOAD_REPLACE_KEYS", frozenset())
except ImportError:
logger.debug(
"Could not import stage input processor module %s while resolving "
"_FULL_PAYLOAD_REPLACE_KEYS; using CONCAT semantics for all keys.",
module_name,
exc_info=True,
)
keys = frozenset()
if not isinstance(keys, (frozenset, set)):
logger.debug(
"Ignoring non-set _FULL_PAYLOAD_REPLACE_KEYS from %s: %s",
module_name,
type(keys).__name__,
)
keys = frozenset()
self._full_payload_replace_keys_cached = frozenset(keys)
logger.debug(
"Resolved _FULL_PAYLOAD_REPLACE_KEYS for %s: %s",
module_name,
sorted(self._full_payload_replace_keys_cached),
)
return self._full_payload_replace_keys_cached
def accumulate_full_payload_output(
self,
req_id: str,
@@ -751,6 +869,7 @@ class OmniConnectorModelRunnerMixin:
The data is actually sent when ``flush_full_payload_outputs`` is called
with the finished request IDs from the next scheduler cycle.
"""
replace_keys = self._resolve_full_payload_replace_keys()
existing = self._pending_full_payload_send.get(req_id)
if existing is None:
@@ -766,6 +885,19 @@ class OmniConnectorModelRunnerMixin:
for k, v in pooler_output.items():
if v is None:
continue
if k in replace_keys:
# Explicit REPLACE semantics: the new value supersedes any
# prior chunks (e.g. `model_outputs` carries the full result
# so far, not an appendable per-step delta).
latest.pop(k, None)
if isinstance(v, torch.Tensor) and v.dim() >= 2:
chunks[k] = [v]
rows[k] = int(v.shape[0])
else:
chunks.pop(k, None)
rows.pop(k, None)
latest[k] = v
continue
if isinstance(v, torch.Tensor) and v.dim() >= 2:
if k in chunks and chunks[k] and v.shape[1:] == chunks[k][0].shape[1:]:
chunks[k].append(v)
@@ -783,6 +915,10 @@ class OmniConnectorModelRunnerMixin:
def flush_full_payload_outputs(self, finished_req_ids: set[str]) -> None:
"""Send accumulated full_payload outputs for requests that just finished."""
pending_req_ids = set(self._pending_full_payload_send.keys())
if not (finished_req_ids & pending_req_ids):
return
logger.info(
"[Stage-%s] flush_full_payload_outputs: finished_req_ids=%s, pending=%s",
self._stage_id,
@@ -927,11 +1063,11 @@ class OmniConnectorModelRunnerMixin:
if self._stage_id == 0:
return
request_id = request.request_id
self._request_ids_mapping[request_id] = getattr(
request,
"external_req_id",
request_id,
)
# Explicit external_req_id=None must fall back to request_id;
# otherwise recv keys become `None_<stage>_<chunk>` and collide
# across requests.
ext = getattr(request, "external_req_id", None)
self._request_ids_mapping[request_id] = ext if ext is not None else request_id
with self._lock:
if request_id in self._stage_recv_req_ids:
return
@@ -2115,7 +2251,10 @@ class OmniConnectorModelRunnerMixin:
if mapped is not None:
return mapped
if request is not None:
return getattr(request, "external_req_id", fallback_req_id)
# external_req_id may be explicitly None; fall back.
ext = getattr(request, "external_req_id", None)
if ext is not None:
return ext
return fallback_req_id
def _resolve_next_stage_id(self, model_config: Any) -> int: