[Feature] Define the runner preprocess phase contract and regression coverage (#7136)

Signed-off-by: xiaobaixia222 <289982752@qq.com>
This commit is contained in:
Xiaobaixia authored and GitHub committed 2026-09-06 17:20:04 +00:00
1 parent ff6e906a25
commit 615f97b9c7
10 files changed
+619 -3

No files matched your search

@@ -0,0 +1,99 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""TCP completion must mean that the destination has applied the write."""
import multiprocessing
import os
import signal
import threading
import time
import pytest
import torch
from tests.helpers.mark import hardware_test
from vllm_omni.distributed.omni_connectors.connectors.mooncake_transfer_engine_connector import TransferEngine
pytestmark = [
pytest.mark.parallel,
pytest.mark.core_model,
pytest.mark.skipif(TransferEngine is None, reason="Mooncake TransferEngine not installed"),
pytest.mark.skipif(os.name != "posix", reason="Requires POSIX process suspension"),
]
def _tcp_receiver(pipe):
engine = TransferEngine()
assert engine.initialize("127.0.0.1", "P2PHANDSHAKE", "tcp", "") == 0
destination = torch.zeros(65536, dtype=torch.uint8).pin_memory()
assert engine.register_memory(destination.data_ptr(), destination.numel()) == 0
pipe.send((engine.get_rpc_port(), destination.data_ptr()))
while True:
value = pipe.recv()
if value is None:
return
deadline = time.monotonic() + 10
while not bool((destination == value).all()):
assert time.monotonic() < deadline, "Destination did not receive the expected bytes"
pipe.send(True)
@hardware_test(res={"cuda": "L4"}, num_cards=1)
def test_tcp_write_completion_waits_for_receiver(monkeypatch):
# Also exercise TCP on hosts where Mooncake would otherwise auto-select RDMA.
monkeypatch.setenv("MC_FORCE_TCP", "1")
context = multiprocessing.get_context("spawn")
parent, child = context.Pipe()
receiver = context.Process(target=_tcp_receiver, args=(child,))
receiver.start()
receiver_pid = receiver.pid
assert receiver_pid is not None
stopped = False
try:
assert parent.poll(120), "Receiver did not initialize"
port, address = parent.recv()
engine = TransferEngine()
assert engine.initialize("127.0.0.1", "P2PHANDSHAKE", "tcp", "") == 0
source = torch.ones(65536, dtype=torch.uint8).pin_memory()
assert engine.register_memory(source.data_ptr(), source.numel()) == 0
remote = f"127.0.0.1:{port}"
# Establish the data connection before suspending the receiver, so the
# second call tests data completion rather than RPC/connection setup.
assert engine.batch_transfer_sync_write(remote, [source.data_ptr()], [address], [source.numel()]) == 0
parent.send(1)
assert parent.poll(30) and parent.recv() is True
os.kill(receiver_pid, signal.SIGSTOP)
stopped = True
_, status = os.waitpid(receiver_pid, os.WUNTRACED)
assert os.WIFSTOPPED(status)
source.fill_(173)
completed = threading.Event()
result = []
def transfer():
result.append(engine.batch_transfer_sync_write(remote, [source.data_ptr()], [address], [source.numel()]))
completed.set()
thread = threading.Thread(target=transfer, daemon=True)
thread.start()
completed_while_stopped = completed.wait(0.5)
os.kill(receiver_pid, signal.SIGCONT)
stopped = False
thread.join(30)
assert result == [0], "Write did not complete successfully after resuming the receiver"
parent.send(173)
assert parent.poll(30) and parent.recv() is True
assert not completed_while_stopped, "TCP reported completion before destination memory could be updated"
finally:
if stopped:
os.kill(receiver_pid, signal.SIGCONT)
if receiver.is_alive():
parent.send(None)
receiver.join(10)
if receiver.is_alive():
receiver.terminate()
receiver.join(10)
parent.close()
child.close()
@@ -0,0 +1,120 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Real-weight regression: force a final one-token prefill chunk, then decode."""
import json
import os
from pathlib import Path
import pytest
import soundfile as sf
import torch
from transformers import AutoTokenizer
from tests.helpers.mark import hardware_test
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.model_executor.models.qwen3_tts.configuration_qwen3_tts import Qwen3TTSConfig
from vllm_omni.model_executor.models.qwen3_tts.prompt_embeds_builder import Qwen3TTSPromptEmbedsBuilder
pytestmark = [pytest.mark.advanced_model, pytest.mark.tts]
@hardware_test(res={"cuda": "L4"}, num_cards=1)
@pytest.mark.asyncio
async def test_one_token_prefill_tail_matches_unchunked_audio(tmp_path, monkeypatch):
# Greedy sampling alone does not make different prefill shapes numerically
# identical. Use invariant kernels for the exact codes/waveform comparison.
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
model = str(Path(os.environ.get("MODEL_PREFIX", "")) / "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice")
tokenizer = AutoTokenizer.from_pretrained(model)
config = Qwen3TTSConfig.from_pretrained(model)
info = {
"task_type": ["CustomVoice"],
"text": ["Hello, this is a test of speech generation."],
"language": ["English"],
"speaker": ["vivian"],
"max_new_tokens": [128],
}
prompt_len = Qwen3TTSPromptEmbedsBuilder.estimate_prompt_len_from_additional_information(
info,
task_type="CustomVoice",
tokenize_prompt=lambda text: tokenizer(text)["input_ids"],
codec_language_id=config.talker_config.codec_language_id,
spk_is_dialect=config.talker_config.spk_is_dialect,
)
assert prompt_len > 2
prompt = {"prompt_token_ids": [0] * prompt_len, "additional_information": info}
observations = []
audios = []
for chunked in (False, True):
deploy = modify_stage_config(
get_deploy_config_path("qwen3_tts.yaml"),
updates={
"async_chunk": False,
"stages": {
0: {
"enable_chunked_prefill": chunked,
"enable_prefix_caching": False,
"max_num_batched_tokens": prompt_len - 1 if chunked else 2048,
"max_model_len": 2048,
"max_num_seqs": 1,
"enforce_eager": True,
"async_scheduling": False,
"default_sampling_params.temperature": 0.0,
"default_sampling_params.max_tokens": 128,
"subtalker_sampling_params": {"do_sample": False},
},
1: {"enforce_eager": True, "async_scheduling": False},
},
},
)
engine = AsyncOmni(
model=model,
deploy_config=deploy,
worker_extension_cls=("tests.e2e.features.prefill_phase.worker_extension.PhaseContractWorkerExtension"),
stage_init_timeout=600,
init_timeout=900,
)
try:
assert await engine.collective_rpc("start_phase_contract_probe", stage_ids=[0]) == [[True]]
audio_parts = []
async for output in engine.generate(prompt, request_id=f"phase-{chunked}"):
if output.final_output_type == "audio":
multimodal = output.outputs[0].multimodal_output
assert (torch.as_tensor(multimodal["sr"]) == 24000).all()
audio = multimodal["audio"]
audio_parts.extend(audio if isinstance(audio, list) else [audio])
assert audio_parts, "pipeline returned no audio"
waveform = torch.cat([part.detach().cpu().reshape(-1) for part in audio_parts])
assert waveform.numel() > 0 and torch.isfinite(waveform).all()
assert waveform.abs().max() > 0
sf.write(tmp_path / f"chunked-{chunked}.wav", waveform.float().numpy(), 24000)
audios.append(waveform)
probe = await engine.collective_rpc("get_phase_contract_probe", stage_ids=[0])
observations.append(probe[0][0])
finally:
engine.shutdown()
baseline, chunked_probe = observations
evidence = {
"prompt_len": prompt_len,
"observations": observations,
"audio_samples": audios[0].numel(),
"chunked_audio_samples": audios[1].numel(),
"max_audio_difference": (
float((audios[1] - audios[0]).abs().max()) if audios[1].shape == audios[0].shape else None
),
}
evidence_path = tmp_path / "phase_contract.json"
evidence_path.write_text(json.dumps(evidence, indent=2))
print(f"Phase contract evidence: {evidence_path}")
# Preserve both observations even when a parity assertion fails in CI.
assert [prompt_len, 0, prompt_len, True] in baseline["events"]
assert [prompt_len, 0, prompt_len - 1, True] in chunked_probe["events"]
assert [prompt_len, prompt_len - 1, 1, True] in chunked_probe["events"]
assert baseline["codes"] and chunked_probe["codes"]
assert chunked_probe["codes"] == baseline["codes"]
torch.testing.assert_close(audios[1], audios[0], rtol=1e-4, atol=1e-5)
@@ -0,0 +1,59 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Observe the real runner/model boundary without replacing inference."""
from typing import TYPE_CHECKING
import torch
if TYPE_CHECKING:
from vllm_omni.worker.gpu_model_runner import OmniGPUModelRunner
class PhaseContractWorkerExtension:
model_runner: "OmniGPUModelRunner"
def start_phase_contract_probe(self):
runner = self.model_runner
self.phase_contract_events: list[tuple[int, int, int, bool]] = []
self.phase_contract_codes: list[list[list[int]]] = []
tail_embeddings = {}
original_preprocess = runner.model.preprocess
original_mtp = runner._talker_mtp_forward
def preprocess(input_ids, input_embeds, **info):
rid = info["request_id"]
index = runner.input_batch.req_id_to_index[rid]
prompt_len = len(runner.requests[rid].prompt_token_ids)
computed = int(runner.input_batch.num_computed_tokens_cpu[index])
assert info["_omni_prompt_len"] == prompt_len
assert info["_omni_num_computed_tokens"] == computed
assert info["_omni_is_prefill"] is (computed < prompt_len)
result = original_preprocess(input_ids=input_ids, input_embeds=input_embeds, **info)
span = input_ids.numel()
self.phase_contract_events.append((prompt_len, computed, span, info["_omni_is_prefill"]))
if computed == prompt_len - 1 and span == 1:
offset = int(runner.query_start_loc.cpu[index])
tail_embeddings[offset] = result[1].detach().clone()
return result
def mtp(decode_req_ids, inputs_embeds, start_offsets=None):
for rid in decode_req_ids:
index = runner.input_batch.req_id_to_index[rid]
assert int(runner.input_batch.num_computed_tokens_cpu[index]) >= len(
runner.requests[rid].prompt_token_ids
), "prefill row was routed through MTP"
original_mtp(decode_req_ids, inputs_embeds, start_offsets)
for offset, expected in tail_embeddings.items():
torch.testing.assert_close(inputs_embeds[offset : offset + 1], expected, rtol=0, atol=0)
tail_embeddings.clear()
for rid in decode_req_ids:
self.phase_contract_codes.append(runner.model_intermediate_buffer[rid]["codes"]["audio"].tolist())
runner.model.preprocess = preprocess
setattr(runner, "_talker_mtp_forward", mtp)
return True
def get_phase_contract_probe(self):
return {"events": self.phase_contract_events, "codes": self.phase_contract_codes}
+151 -1
View File
@@ -6,6 +6,7 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.v1.core.sched.output import CachedRequestData, SchedulerOutput
from vllm.v1.cudagraph_dispatcher import CUDAGraphMode
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
@@ -108,7 +109,8 @@ class DummyInputBatch:
class DummyReqState:
"""A minimal request state container."""
pass
mm_features: list[str]
additional_information_cpu: dict
def test_model_forward_passes_request_ids_to_decode_metadata(monkeypatch):
@@ -878,3 +880,151 @@ def test_maybe_attach_mimo_audio_req_infos_no_req_state_returns_input():
# When no req_state, helper should be a no-op.
assert result is req_infos
def _make_phase_runner(monkeypatch, rows, *, batched_decode):
"""Exercise real preprocessing and MTP routing with CPU model buffers.
Each row is (request id, prompt length, computed tokens, scheduled tokens).
Only model computation and the device forward context are replaced.
"""
import vllm_omni.worker.gpu_model_runner as mod
monkeypatch.setattr(mod, "get_pp_group", lambda: SimpleNamespace(is_first_rank=True))
monkeypatch.setattr(mod.current_omni_platform, "set_forward_context", _noop_forward_context)
runner = _make_runner(req_ids=tuple(row[0] for row in rows))
total = sum(row[3] for row in rows)
runner.supports_mm_inputs = False
runner.enable_prompt_embeds = False
runner.uses_mrope = False
runner.uses_xdrope_dim = 0
runner.has_talker_mtp = True
runner.model_config = SimpleNamespace(is_encoder_decoder=False)
runner.vllm_config.model_config.async_chunk = True
runner._init_model_kwargs = dict
runner.input_ids = DummyBuffer(torch.arange(total, dtype=torch.int64))
runner.inputs_embeds = DummyBuffer(torch.zeros(total, 4))
runner.positions = torch.arange(total)
runner.input_batch.num_computed_tokens_cpu = [row[2] for row in rows]
offsets = [0]
for rid, prompt_len, _, scheduled in rows:
runner.requests[rid].prompt_token_ids = list(range(prompt_len))
offsets.append(offsets[-1] + scheduled)
# Runner-owned metadata must override stale model/intermediate state.
runner.model_intermediate_buffer[rid] = {
"_omni_is_prefill": "stale",
"_omni_prompt_len": -1,
"_omni_num_computed_tokens": -1,
}
runner.query_start_loc.cpu = torch.tensor(offsets, dtype=torch.int32)
calls = []
batch_calls = []
def preprocess(input_ids, input_embeds, **info):
calls.append(("normal", dict(info)))
embeds = input_ids.float().view(-1, 1).expand(-1, 4).clone()
updates = {}
if not info["_omni_is_prefill"]:
updates["mtp_inputs"] = (torch.zeros_like(embeds), torch.zeros_like(embeds))
return input_ids, embeds, updates
def preprocess_decode_batch(input_ids, req_infos):
batch_calls.append([info["request_id"] for info in req_infos])
calls.extend(("batch", dict(info)) for info in req_infos)
embeds = input_ids.float().view(-1, 1).expand(-1, 4).clone()
return input_ids, embeds, torch.zeros_like(embeds), torch.zeros_like(embeds), [{} for _ in req_infos]
runner.model = SimpleNamespace(
has_preprocess=True,
preprocess=preprocess,
talker_mtp_output_key=("codes", "audio"),
)
if batched_decode:
runner.model.preprocess_decode_batch = preprocess_decode_batch
output = SchedulerOutput(
total_num_scheduled_tokens=total,
num_scheduled_tokens={row[0]: row[3] for row in rows},
scheduled_new_reqs=[],
scheduled_cached_reqs=CachedRequestData.make_empty(),
scheduled_spec_decode_tokens={},
scheduled_encoder_inputs={},
num_common_prefix_blocks=[],
finished_req_ids=set(),
free_encoder_mm_hashes=[],
)
return runner, output, calls, batch_calls
@pytest.mark.parametrize("batched_decode", [False, True], ids=["normal", "batch"])
@pytest.mark.parametrize("order", ["interleaved", "reversed", "adjacent"])
def test_preprocess_phase_contract_mixed_batch(monkeypatch, batched_decode, order):
rows = [
("decode-before", 5, 5, 1),
("tail", 5, 4, 1),
("decode-after", 5, 6, 1),
("single-prompt", 1, 0, 1),
("cached-prefill", 8, 4, 3),
("multi-token-decode", 5, 5, 2),
]
if order == "reversed":
rows.reverse()
elif order == "adjacent":
rows = [rows[1], rows[0], rows[2], *rows[3:]]
runner, scheduled, calls, batch_calls = _make_phase_runner(monkeypatch, rows, batched_decode=batched_decode)
_, embeds, *_ = runner._preprocess(scheduled, scheduled.total_num_scheduled_tokens)
if batched_decode:
decode_order = [rid for rid, _, _, _ in rows if rid.startswith("decode-")]
expected_batches = [decode_order] if order == "adjacent" else [[rid] for rid in decode_order]
assert batch_calls == expected_batches
else:
assert batch_calls == []
assert len(calls) == len(rows)
offset = 0
code_index = 0
for (route, info), (rid, prompt_len, computed, span) in zip(calls, rows, strict=True):
assert info["request_id"] == rid
assert type(info["_omni_prompt_len"]) is int
assert type(info["_omni_num_computed_tokens"]) is int
assert type(info["_omni_is_prefill"]) is bool
assert info["_omni_prompt_len"] == prompt_len
assert info["_omni_num_computed_tokens"] == computed
assert info["_omni_is_prefill"] == (computed < prompt_len)
mtp_eligible = rid in {"decode-before", "decode-after"}
assert route == ("batch" if batched_decode and mtp_eligible else "normal")
expected = torch.arange(offset, offset + span).float().view(-1, 1).expand(-1, 4)
torch.testing.assert_close(embeds[offset : offset + span], expected + int(mtp_eligible))
assert ("codes" in runner.model_intermediate_buffer[rid]) == mtp_eligible
if mtp_eligible:
torch.testing.assert_close(
runner.model_intermediate_buffer[rid]["codes"]["audio"],
torch.tensor([[code_index]], dtype=torch.int64),
rtol=0,
atol=0,
)
code_index += 1
offset += span
@pytest.mark.parametrize("batched_decode", [False, True], ids=["normal", "batch"])
def test_preprocess_one_token_chunked_prefill_tail_then_decode(monkeypatch, batched_decode):
# Replay a five-token prompt split at a four-token scheduling budget.
runner, scheduled, calls, _ = _make_phase_runner(monkeypatch, [("r", 5, 0, 4)], batched_decode=batched_decode)
runner._preprocess(scheduled, 4)
assert calls[-1][1]["_omni_is_prefill"] is True
assert "codes" not in runner.model_intermediate_buffer["r"]
for computed, is_prefill in [(4, True), (5, False)]:
runner.input_batch.num_computed_tokens_cpu = [computed]
scheduled.total_num_scheduled_tokens = 1
scheduled.num_scheduled_tokens = {"r": 1}
runner.query_start_loc.cpu = torch.tensor([0, 1], dtype=torch.int32)
runner.input_ids.gpu[0] = 42
_, embeds, *_ = runner._preprocess(scheduled, 1)
route, info = calls[-1]
assert info["_omni_is_prefill"] is is_prefill
assert info["_omni_num_computed_tokens"] == computed
assert info["_omni_prompt_len"] == 5
assert route == ("batch" if batched_decode and not is_prefill else "normal")
torch.testing.assert_close(embeds, torch.full((1, 4), 42.0 if is_prefill else 43.0))
assert ("codes" in runner.model_intermediate_buffer["r"]) == (not is_prefill)