[Core] Extend the shared multi-stage execution framework for mixed V1/MRv2 pipelines (#8184)

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 authored and GitHub committed 2026-09-29 07:40:57 -07:00
1 parent 6b4173f50b
commit 001f8a80b9
42 files changed
+1792 -85

No files matched your search

@@ -94,3 +94,25 @@ def test_update_merge_semantics(monkeypatch):
assert stored is not tensor
assert torch.equal(stored, tensor)
assert "kv" in buf.buffers[0]
def test_add_request_merges_orchestrator_model_intermediate_buffer():
"""Stage bridges such as MiniCPM-o's llm2tts hand over ``model_intermediate_buffer``."""
buf = OmniIntermediateBuffer(max_num_reqs=2)
hidden = torch.randn(3, 4)
data = _make_new_req_data(
"talker-1",
additional_information={"meta": {"a": 1}},
model_intermediate_buffer={
"ids": {"tts": [1, 2, 3]},
"hidden_states": {"tts": hidden},
"meta": {"next_stage_prompt_len": 5},
"request_id": "thinker-1",
},
)
buf.add_request(0, data)
info = buf.buffers[0]
assert info["ids"]["tts"] == [1, 2, 3]
assert torch.equal(info["hidden_states"]["tts"], hidden)
assert info["meta"] == {"a": 1, "next_stage_prompt_len": 5}
assert info["request_id"] == "thinker-1" and info["req_id"] == "talker-1"
+70 -1
View File
@@ -185,6 +185,7 @@ def _start_save_thread(plane, connector):
_send_side_request_payload={},
_code_prompt_token_ids=defaultdict(list),
_work_available=threading.Event(),
_save_work_available=threading.Event(),
_stop_event=threading.Event(),
_MAX_SEND_RETRIES=0,
_can_send=True,
@@ -199,7 +200,7 @@ def _start_save_thread(plane, connector):
def _stop_save_thread(plane):
plane._stop_event.set()
plane._work_available.set()
plane._save_work_available.set()
plane._save_thread.join(timeout=2)
assert not plane._save_thread.is_alive()
@@ -551,3 +552,71 @@ def test_abort_before_first_chunk_cleans_receiver_state():
assert plane.abort_requests({"r"}) == 0
assert plane.abort_requests({"r"}) == 0
assert not plane._pending_load_reqs and not plane._request_ids_mapping and not plane._local_stage_payload_cache
def test_ar_receiver_accumulates_rows_and_replaces_chunk_metadata():
# A V1 upstream sender stamps scalar flags on every chunk; they describe
# the latest chunk and must not be concatenated like decode rows.
plane = _bare_plane()
plane._send_side_request_payload = {}
def chunk(rows, finished):
return {
"embed": {"decode": torch.ones((rows, 2))},
"meta": {"finished": torch.tensor(finished), "is_segment_finished": torch.tensor(False)},
}
plane._accumulate_payload("ext", chunk(1, False))
merged = plane._accumulate_payload("ext", chunk(2, True))
assert merged["embed"]["decode"].shape == (3, 2)
assert merged["meta"]["finished"].item() is True
assert merged["meta"]["is_segment_finished"].ndim == 0
def test_terminal_without_processor_payload_still_sends_finish_marker(raw_plane, monkeypatch):
# Qwen3-Omni's Talker processor returns None on the terminal call when the
# last frames ended exactly on a chunk boundary; Code2Wav must still learn
# that the stream finished, as with the V1 chunk adapter.
raw_plane._async_chunk = True
raw_plane._omni_connector = object()
raw_plane._request_ids_mapping = {}
raw_plane._custom_process_func = lambda transfer_manager, multimodal_output, request, is_finished=False: None
raw_plane._custom_process_batch_func = None
monkeypatch.setattr(raw_plane, "is_data_transfer_rank", lambda: True)
enqueued = []
def enqueue(request, payload, **_kw):
enqueued.append((request.request_id, payload))
return True, None
monkeypatch.setattr(raw_plane, "_enqueue_chunk_payload", enqueue)
raw_plane.register_request(_new_request())
_complete(raw_plane, [{"codes": {"audio": torch.ones((1, 16))}}])
assert enqueued == [] # a non-terminal None payload sends nothing
assert raw_plane.request_terminal({"internal"}) == 1
[(req_id, payload)] = enqueued
assert req_id == "internal"
assert payload["meta"]["finished"].item() is True
def test_payload_builders_see_stage_model_config(monkeypatch):
# Producer-side builders (Qwen3-Omni's Thinker reads
# hf_config.talker_config.accept_hidden_layer) resolve the stage config
# through _get_model_config(), as they do on the V1 runner mixin.
from vllm_omni.model_executor.stage_input_processors.qwen3_omni import _get_accept_hidden_layer_index
def init_connectors(self, *, model_config):
self._async_chunk = True
self._custom_process_func = None
monkeypatch.setattr(OmniRunnerDataPlane, "init_omni_connectors", init_connectors)
monkeypatch.setattr(OmniRunnerDataPlane, "_start_output_worker", lambda self, **_kw: None)
model_config = SimpleNamespace(hf_config=SimpleNamespace(talker_config=SimpleNamespace(accept_hidden_layer=24)))
vllm_config = SimpleNamespace(model_config=model_config)
plane = OmniRunnerDataPlane(vllm_config, model_config)
assert plane._get_model_config() is model_config
assert _get_accept_hidden_layer_index(plane) == 24
@@ -13,7 +13,7 @@ import torch
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.outputs import OmniModelRunnerOutput
from vllm_omni.worker_v2.omni_generation_model_runner import OmniGenerationModelRunner
from vllm_omni.worker_v2.omni_generation_model_runner import OmniGenerationModelRunner, check_exact_input_shape
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -182,3 +182,16 @@ def test_sample_tokens_uses_async_output_for_cuda_and_snapshots_req_ids(monkeypa
output_req_ids = captured["model_runner_output"].req_ids
input_batch.req_ids[0] = "reused" # snapshot must insulate the published output
assert output_req_ids == ["req-0"]
@pytest.mark.parametrize("exact", [True, False])
def test_exact_input_shape_models_reject_padded_batches(exact):
# Qwen3-Omni Code2Wav splits input_ids by seq_token_counts (#6712).
model = SimpleNamespace(requires_exact_input_shape=exact)
check_exact_input_shape(model, torch.zeros(32, dtype=torch.long), 32)
check_exact_input_shape(model, None, 16)
if exact:
with pytest.raises(RuntimeError, match="exact input shape"):
check_exact_input_shape(model, torch.zeros(48, dtype=torch.long), 32)
else:
check_exact_input_shape(model, torch.zeros(48, dtype=torch.long), 32)
@@ -181,6 +181,84 @@ def test_capture_contract_uses_model_declaration(stage, declared):
runner._configure_cudagraph_output_contract()
assert runner._model_returns_tuple is declared
assert runner._exclude_full_graph is declared
assert runner._full_graph_aux_outputs is False
def _aux_output(num_tokens):
hidden = torch.arange(num_tokens * 2, dtype=torch.float32).reshape(num_tokens, 2)
return hidden, {"hidden_states": {"layers": {0: hidden + 1, 24: hidden + 2}}}
def test_full_graph_aux_contract_keeps_full_and_round_trips_leaves():
runner = object.__new__(OmniGPUModelRunner)
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
runner._configure_cudagraph_output_contract()
assert runner._full_graph_aux_outputs and not runner._exclude_full_graph
calls = []
def forward(num_tokens=3):
calls.append(num_tokens)
return _aux_output(num_tokens)
runner.model.forward = forward
original_forward = runner.model.forward
runner.use_aux_hidden_state_outputs = False
full = SimpleNamespace(cg_mode=CUDAGraphMode.FULL)
runner.cudagraph_manager = SimpleNamespace(_capture_descs={CUDAGraphMode.FULL: [full]}, _candidates={})
runner.model_state = SimpleNamespace()
captured = {}
def capture(_self):
# The graph manager stores (hidden, leaves) in its aux buffers.
assert runner.use_aux_hidden_state_outputs is True
hidden, leaves = runner.model.forward(4)
captured["hidden"], captured["leaves"] = hidden, leaves
assert [tuple(leaf.shape) for leaf in leaves] == [(4, 2), (4, 2)]
runner.model.forward(2) # smaller capture, same structure
return 1
with patch.object(GPUModelRunner, "capture_model", capture):
assert runner.capture_model() == 1
assert runner.model.forward is original_forward and runner.use_aux_hidden_state_outputs is False
assert runner.cudagraph_manager._capture_descs == {CUDAGraphMode.FULL: [full]} # FULL kept
hidden, aux = runner._split_fullgraph_output((captured["hidden"], captured["leaves"]))
reference_hidden, reference_aux = _aux_output(4)
assert torch.equal(hidden, reference_hidden)
assert set(aux["hidden_states"]["layers"]) == {0, 24}
assert torch.equal(aux["hidden_states"]["layers"][24], reference_aux["hidden_states"]["layers"][24])
@pytest.mark.parametrize(
"aux",
[
{}, # no leaves
{"layers": {0: torch.zeros(5, 2)}}, # leaf not on the token axis
{"layers": {0: 1.0}}, # non-tensor leaf
],
)
def test_full_graph_aux_contract_rejects_invalid_outputs(aux):
runner = object.__new__(OmniGPUModelRunner)
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
runner._configure_cudagraph_output_contract()
with pytest.raises(RuntimeError, match="supports_mrv2_full_graph_aux_outputs"):
runner._flatten_capture_aux_output((torch.zeros(3, 2), aux))
def test_full_graph_aux_contract_rejects_structure_change():
runner = object.__new__(OmniGPUModelRunner)
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
runner._configure_cudagraph_output_contract()
runner._flatten_capture_aux_output((torch.zeros(3, 2), {"layers": {0: torch.zeros(3, 2)}}))
with pytest.raises(RuntimeError, match="structure changed"):
runner._flatten_capture_aux_output((torch.zeros(3, 2), {"layers": {1: torch.zeros(3, 2)}}))
def test_full_graph_output_without_contract_is_hidden_only():
runner = object.__new__(OmniGPUModelRunner)
hidden = torch.ones(2, 2)
assert runner._split_fullgraph_output(hidden) == (hidden, None)
@pytest.mark.parametrize("runner_kind", ["gpu", "ar", "generation"])
@@ -202,6 +280,7 @@ def test_dummy_forward_uses_upstream_execution_state(runner_kind, monkeypatch):
else hidden
)
runner._dummy_hidden = hidden
runner.model.requires_request_ids = False
runner.model_config = SimpleNamespace()
runner.vllm_config = SimpleNamespace()
runner.req_states = SimpleNamespace()
+57
View File
@@ -19,6 +19,8 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class _DummyInputBatch:
is_prefilling_np: np.ndarray
input_ids: SimpleNamespace
query_start_loc: torch.Tensor
@@ -592,3 +594,58 @@ def test_first_audio_marker_requires_accepted_delivery(monkeypatch, accepted):
# A missing route must leave the normal codec path responsible for frame 0;
# otherwise it skips the frame and the orchestrator waits forever for it.
assert outputs["meta"]["first_audio"].tolist() == ["r0" in accepted, "r1" in accepted]
class _FakeEvent:
def record(self, stream=None) -> None:
self.stream = stream
def test_publish_sampled_embeddings_for_rows_whose_sample_is_kept(monkeypatch) -> None:
monkeypatch.setattr(torch.cuda, "Event", _FakeEvent)
state = _make_state()
state.model.publishes_sampled_embeddings = True
state.model.embed_input_ids = lambda ids: ids.to(torch.float32).reshape(-1, 1).repeat(1, 3)
# Rows: final prefill chunk, decode, non-final prefill chunk, one-chunk prefill.
batch = SimpleNamespace(
num_reqs=4,
num_scheduled_tokens=[4, 1, 2, 6],
num_computed_prefill_tokens_np=np.array([2, 9, 0, 0], dtype=np.int32),
prefill_len_np=np.array([6, 9, 5, 6], dtype=np.int32),
is_prefilling_np=np.array([True, False, True, True]),
)
extra, _done = state.publish_sampled_embeddings(batch, torch.tensor([[11], [12], [13], [14]]))
sampled = extra["embed"]["sampled"]
# A non-final prefill chunk's sample is discarded, so it publishes nothing.
assert [tuple(row.shape) for row in sampled] == [(1, 3), (1, 3), (0,), (1, 3)]
assert [row.tolist() for row in sampled if row.numel()] == [[[v] * 3] for v in (11.0, 12.0, 14.0)]
# Speculative steps sample several tokens per row: not published.
assert state.publish_sampled_embeddings(batch, torch.tensor([[11, 1], [12, 1], [13, 1], [14, 1]])) is None
def test_publish_sampled_embeddings_is_opt_in() -> None:
state = _make_state()
state.model.publishes_sampled_embeddings = False
assert state.publish_sampled_embeddings(SimpleNamespace(num_reqs=1), torch.tensor([[1]])) is None
@pytest.mark.parametrize("prefilling", [False, True])
def test_identity_preprocess_skips_only_decode_rows(prefilling):
state = _make_state(has_preprocess=True)
state._decode_preprocess_is_identity = True
state._decode_preprocess = None
state.intermediate_buffer.buffers[0] = {"req_id": "r1"}
seen = []
def preprocess(input_ids, input_embeds, **info):
seen.append(info["req_id"])
return input_ids, input_embeds, {}
state.model.preprocess = preprocess
batch = _DummyInputBatch([0])
batch.is_prefilling_np = np.array([prefilling])
embeds = torch.ones(1, 4)
state.run_preprocess(batch, {"input_ids": torch.tensor([1]), "inputs_embeds": embeds})
assert seen == (["r1"] if prefilling else [])
assert torch.equal(embeds, torch.ones(1, 4))
@@ -0,0 +1,79 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Generic model opt-in contracts; no model checkpoints required."""
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.model_executor.models.output_templates import OmniOutput
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
from vllm_omni.worker_v2.omni_ar_model_runner import _merge_payload_trees
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def test_device_output_hook_receives_live_batch_and_request_state():
state = object.__new__(OmniModelState)
state.have_multimodal_outputs = True
batch, requests, buffers = object(), object(), [{"req_id": "r"}]
hidden = torch.ones(1, 2)
seen = []
def make_output(value, **kwargs):
seen.append((value, kwargs))
return OmniOutput(text_hidden_states=value, multimodal_outputs={"codes": {"audio": value}})
state.model = SimpleNamespace(make_omni_output_mrv2=make_output)
state.intermediate_buffer = SimpleNamespace(gather=lambda value: buffers)
result_hidden, payload = state.postprocess_model_output(hidden, batch, requests)
assert result_hidden is hidden
assert payload["codes"]["audio"] is hidden
assert seen == [(hidden, {"input_batch": batch, "req_states": requests, "model_intermediate_buffer": buffers})]
def test_sampled_embeddings_merge_preserves_sibling_fields_and_input():
prefill, sampled = torch.ones(2, 3), torch.zeros(1, 3)
base = {"embed": {"prefill": prefill}, "meta": {"finished": False}}
merged = _merge_payload_trees(base, {"embed": {"sampled": [sampled]}})
assert merged["embed"]["prefill"] is prefill
assert merged["embed"]["sampled"] == [sampled]
assert "sampled" not in base["embed"]
assert merged["meta"] == {"finished": False}
def test_custom_sampler_falls_back_to_parent(monkeypatch):
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
state = object.__new__(OmniModelState)
state.model = SimpleNamespace()
sampler, marker = object(), object()
monkeypatch.setattr(DefaultModelState, "custom_sampler", lambda self, original: (original, marker))
assert state.custom_sampler(sampler) == (sampler, marker)
def test_logits_vocab_is_adopted_before_parent_sampler_initialization(monkeypatch):
import vllm.v1.worker.gpu.model_runner as upstream
from vllm_omni.worker_v2 import omni_model_runner as module
runner = object.__new__(module.OmniGPUModelRunner)
runner.vocab_size = 100
runner.req_states = SimpleNamespace(vocab_size=100)
runner.model_config = SimpleNamespace(model_arch_config=SimpleNamespace(vocab_size=100))
model = SimpleNamespace(logits_vocab_size=32)
original_initializer = upstream.init_model_state
sentinel = object()
monkeypatch.setattr(module, "init_omni_model_state", lambda *args: sentinel)
def load(parent):
assert upstream.init_model_state(None, model, None, None) is sentinel
assert parent.vocab_size == parent.req_states.vocab_size == 32
assert parent.model_config.model_arch_config.vocab_size == 32
raise RuntimeError("stop before sampler allocation")
monkeypatch.setattr(upstream.GPUModelRunner, "load_model", load)
with pytest.raises(RuntimeError, match="stop before sampler allocation"):
runner.load_model()
assert upstream.init_model_state is original_initializer
+45
View File
@@ -0,0 +1,45 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Small CUDA correctness checks for shared stage output contracts."""
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.worker.gpu_generation_model_runner import _HostCopyBatch
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
pytestmark = [pytest.mark.core_model, pytest.mark.cuda]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_host_copy_batch_preserves_noncontiguous_outputs_on_current_stream():
stream = torch.cuda.Stream()
with torch.cuda.stream(stream):
source = torch.arange(24, device="cuda", dtype=torch.float32).reshape(4, 6)
copies = _HostCopyBatch(pin_memory=True)
first = copies.copy(source.t())
second = copies.copy(source + 10)
copies.wait()
assert first.is_contiguous() and first.is_pinned()
assert torch.equal(first, torch.arange(24, dtype=torch.float32).reshape(4, 6).t())
assert torch.equal(second, torch.arange(24, dtype=torch.float32).reshape(4, 6) + 10)
copies.wait() # no outstanding copies
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_aux_pytree_tracks_replayed_graph_values():
runner = object.__new__(OmniGPUModelRunner)
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
runner._configure_cudagraph_output_contract()
source = torch.ones((4, 3), device="cuda")
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = runner._flatten_capture_aux_output((source * 2, {"layers": [source + 1, source + 2]}))
source.fill_(7)
graph.replay()
hidden, aux = runner._split_fullgraph_output(captured)
assert torch.equal(hidden, torch.full_like(source, 14))
assert torch.equal(aux["layers"][0], torch.full_like(source, 8))
assert torch.equal(aux["layers"][1], torch.full_like(source, 9))