[Model] YuE2: async single-stage synthesis and CUDA graph acceleration (#8407)
Signed-off-by: Sy03 <1370724210@qq.com> Signed-off-by: princepride <wangzhipeng628@gmail.com> Signed-off-by: Wang Zhipeng <wangzhipeng628@gmail.com> Co-authored-by: princepride <wangzhipeng628@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
12 files changed
+2182
-296
No files matched your search
@@ -0,0 +1,133 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Observe YuE2 lifecycle contracts inside a real engine worker."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.worker.gpu_ar_model_runner import GPUARModelRunner
|
||||
|
||||
|
||||
class Yue2LifecycleWorkerExtension:
|
||||
model_runner: "GPUARModelRunner"
|
||||
|
||||
def start_yue2_probe(self):
|
||||
from unittest.mock import patch
|
||||
|
||||
from vllm.compilation.cuda_graph import CUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import get_forward_context, is_forward_context_available
|
||||
|
||||
from vllm_omni.model_executor.models.yue2.yue2 import ABC_END, HOLD_TOKEN, MUSIC_END
|
||||
|
||||
model = self.model_runner.get_model()
|
||||
self.yue2_probe = {
|
||||
"preemptions": 0,
|
||||
"rollbacks": 0,
|
||||
"checked_rows": 0,
|
||||
"mixed_steps": 0,
|
||||
"synthesis_started": False,
|
||||
"ar_full_replays": 0,
|
||||
"ar_piecewise_replays": 0,
|
||||
}
|
||||
graph_call = CUDAGraphWrapper.__call__
|
||||
|
||||
def count_ar_replays(wrapper, *args, **kwargs):
|
||||
if is_forward_context_available():
|
||||
context = get_forward_context()
|
||||
mode = context.cudagraph_runtime_mode
|
||||
entry = wrapper.concrete_cudagraph_entries.get(context.batch_descriptor)
|
||||
if mode == wrapper.runtime_mode and entry is not None and entry.cudagraph is not None:
|
||||
if mode == CUDAGraphMode.FULL:
|
||||
self.yue2_probe["ar_full_replays"] += 1
|
||||
elif mode == CUDAGraphMode.PIECEWISE:
|
||||
self.yue2_probe["ar_piecewise_replays"] += 1
|
||||
return graph_call(wrapper, *args, **kwargs)
|
||||
|
||||
# This worker is created for this test and exits with the engine.
|
||||
# Count vLLM AR replays, separately from model-owned sampler/NAR graphs.
|
||||
self.yue2_graph_patch = patch.object(CUDAGraphWrapper, "__call__", count_ar_replays)
|
||||
self.yue2_graph_patch.start()
|
||||
self.yue2_cancel_job = None
|
||||
previous: dict[str, int] = {}
|
||||
prepare = model.prepare_runner_inputs
|
||||
reconcile = model._reconcile_history
|
||||
queue = model._queue_synthesis
|
||||
sample = model.sample
|
||||
resolve = model._resolve_pending
|
||||
emitted: dict[str, int] = {}
|
||||
|
||||
def resolve_pending():
|
||||
if model._pending is not None:
|
||||
event, host, states = model._pending
|
||||
event.synchronize()
|
||||
for state, token in zip(states, host[0].tolist()):
|
||||
end = ABC_END if state.constants.phase == "abc" else MUSIC_END
|
||||
expected = HOLD_TOKEN if token == end and not state.constants.skip_synthesis else token
|
||||
assert emitted[state.request_id] == expected, "engine token and model history disagree"
|
||||
resolve()
|
||||
|
||||
def sample_tokens(logits, sampling_metadata):
|
||||
result = sample(logits, sampling_metadata)
|
||||
phases = {model._states[rid].constants.phase for rid, _, _ in model._step_rows if rid in model._states}
|
||||
if len(phases) == 2:
|
||||
self.yue2_probe["mixed_steps"] += 1
|
||||
for (rid, _, _), row in zip(model._step_rows, result.sampled_token_ids.tolist()):
|
||||
emitted[rid] = row[0]
|
||||
return result
|
||||
|
||||
def prepare_inputs(**kwargs):
|
||||
for rid, computed in zip(kwargs["req_ids"], kwargs["num_computed_tokens"]):
|
||||
if int(computed) < previous.get(rid, 0):
|
||||
self.yue2_probe["preemptions"] += 1
|
||||
previous[rid] = int(computed)
|
||||
return prepare(**kwargs)
|
||||
|
||||
def reconcile_history(state, accepted):
|
||||
if len(state.history) + int(state.end_drawn) > accepted:
|
||||
self.yue2_probe["rollbacks"] += 1
|
||||
reconcile(state, accepted)
|
||||
assert len(state.history) + int(state.end_drawn) <= accepted
|
||||
if not state.finish_ready and state.job is None and not state.finished:
|
||||
assert len(state.history) == accepted
|
||||
assert not state.truncated and not state.end_drawn
|
||||
self.yue2_probe["checked_rows"] += 1
|
||||
|
||||
def queue_synthesis(state):
|
||||
queue(state)
|
||||
if "cancel-synthesis" in state.request_id:
|
||||
job = state.job
|
||||
assert job.started and job.work is not None and job.keep
|
||||
assert job.event is None, "test must intercept an active synthesis job"
|
||||
# Keep an actual NAR job active until the driver cancels it.
|
||||
# Its first work units ran normally; stop pumping later units
|
||||
# so cancellation cannot race against a short song finishing.
|
||||
self.yue2_cancel_advance = job.advance
|
||||
job.advance = lambda: None
|
||||
self.yue2_cancel_job = job
|
||||
self.yue2_probe["synthesis_started"] = True
|
||||
|
||||
model.prepare_runner_inputs = prepare_inputs
|
||||
model._reconcile_history = reconcile_history
|
||||
model._queue_synthesis = queue_synthesis
|
||||
model.sample = sample_tokens
|
||||
model._resolve_pending = resolve_pending
|
||||
return True
|
||||
|
||||
def get_yue2_probe(self):
|
||||
result = dict(self.yue2_probe)
|
||||
job = self.yue2_cancel_job
|
||||
if job is not None:
|
||||
if job.cancelled:
|
||||
# Exercise the original pump after cleanup: it must not submit
|
||||
# further units even though this test retains the job object.
|
||||
self.yue2_cancel_advance()
|
||||
model = self.model_runner.get_model()
|
||||
result["cancelled"] = job.cancelled
|
||||
result["released"] = job._released and job.work is None and not job.keep and job.stream is None
|
||||
result["removed"] = (
|
||||
job.request_id not in model._states
|
||||
and model._synthesis.active is not job
|
||||
and job not in model._synthesis.waiting
|
||||
)
|
||||
return result
|
||||
@@ -32,9 +32,9 @@ above the byte floor) and passes on that alone, following the MiniMax Music 3
|
||||
precedent.
|
||||
|
||||
Weekly rather than per-PR: each request is a 16 s song and the verification
|
||||
checkpoints add ~5.5 GB of downloads. Validated on a single RTX 4090
|
||||
(24 GB); the hardware mark targets an H100 because the CI fleet has no
|
||||
consumer cards.
|
||||
checkpoints add ~5.5 GB of downloads. The async/graph implementation was
|
||||
validated on H200; the hardware mark targets the CI fleet's H100. The older
|
||||
RTX 4090 result does not establish this implementation's memory requirements.
|
||||
"""
|
||||
|
||||
import concurrent.futures
|
||||
@@ -60,8 +60,7 @@ DEFAULT_AUDIO_SPEECH_TIMEOUT_S = 900.0
|
||||
# 400 frames = 16 s of song. The byte floor sits far below the observed
|
||||
# payload (~3.0 MB of 48 kHz stereo 16-bit) to leave room for an early EOS.
|
||||
_FRAMES = 400
|
||||
# Concurrent pair stays short: it exists to exercise row re-indexing, not
|
||||
# to double the wall time.
|
||||
# Short concurrent requests exercise row re-indexing as budgets differ.
|
||||
_CONCURRENT_FRAMES = 250
|
||||
_MIN_BYTES = 1_000_000
|
||||
|
||||
@@ -173,7 +172,7 @@ def test_yue2_metal_twinkle_001(omni_server, openai_client, tmp_path) -> None:
|
||||
# CI runs without the verification assets, so the structural checks below
|
||||
# are the only guard against the two real bugs this PR fixed during review:
|
||||
# mono/half-speed output (WAV header + duration bounds) and the int32
|
||||
# crash under concurrent row re-indexing (two simultaneous requests).
|
||||
# crash under concurrent row re-indexing (simultaneous requests).
|
||||
# Duration bounds: the end token is masked for the first 200 steps
|
||||
# (min_tokens), and the 400-frame budget caps the song, so a healthy
|
||||
# request lands in [8, 16.5] s; the half-speed bug produced ~32 s.
|
||||
@@ -190,13 +189,15 @@ def test_yue2_metal_twinkle_001(omni_server, openai_client, tmp_path) -> None:
|
||||
# (see _http_speech); the OpenAI SDK response does not expose headers.
|
||||
_http_speech(omni_server, seed=SEED, frames=_FRAMES)
|
||||
|
||||
# Two concurrent requests with different seeds: both must succeed and
|
||||
# produce different songs (the model-owned sampler re-indexes rows across
|
||||
# concurrent requests; a dtype mismatch here crashed the engine before).
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
||||
futures = [pool.submit(_http_speech, omni_server, seed=SEED + i, frames=_CONCURRENT_FRAMES) for i in range(2)]
|
||||
pair = [f.result() for f in futures]
|
||||
assert pair[0] != pair[1], "different seeds produced identical audio"
|
||||
# Different budgets exercise row re-indexing as shorter requests finish.
|
||||
# Compare the same-budget pair so length cannot hide an ignored seed.
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
futures = [
|
||||
pool.submit(_http_speech, omni_server, seed=SEED + i, frames=frames)
|
||||
for i, frames in enumerate((_CONCURRENT_FRAMES, _FRAMES, _CONCURRENT_FRAMES))
|
||||
]
|
||||
audios = [f.result() for f in futures]
|
||||
assert audios[0] != audios[2], "different seeds produced identical audio at the same frame budget"
|
||||
|
||||
# Without the verification assets the structural assertions above
|
||||
# (non-empty payload, byte floor) are the whole test — pass on them.
|
||||
@@ -235,3 +236,199 @@ def test_yue2_metal_twinkle_001(omni_server, openai_client, tmp_path) -> None:
|
||||
assert melody_score > control_score, (
|
||||
f"calibration: ABC-conditioned {melody_score:.3f} not above control {control_score:.3f}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards={"cuda": 1})
|
||||
@pytest.mark.parametrize("omni_server", tts_server_params, indirect=True)
|
||||
def test_yue2_abort_then_next_request_succeeds(omni_server) -> None:
|
||||
"""Serving smoke check after a client timeout, not proof of job cleanup."""
|
||||
# The chosen seed and budget time out on the tested cards. Require the
|
||||
# timeout so this cannot silently become another successful request;
|
||||
# whether it lands in AR or synthesis depends on the card.
|
||||
with pytest.raises(httpx.TimeoutException):
|
||||
httpx.post(
|
||||
f"http://{omni_server.host}:{omni_server.port}/v1/audio/speech",
|
||||
json={
|
||||
"model": omni_server.model,
|
||||
"input": LYRICS,
|
||||
"instructions": CAPTION,
|
||||
"seed": SEED + 2,
|
||||
"max_new_tokens": 3000,
|
||||
"stream": False,
|
||||
"response_format": "wav",
|
||||
"extra_params": {"cot": "off"},
|
||||
},
|
||||
timeout=1.0,
|
||||
)
|
||||
_http_speech(omni_server, seed=SEED + 3, frames=_CONCURRENT_FRAMES)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.tts
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("chunked", [True, False], ids=["chunked", "unchunked"])
|
||||
@pytest.mark.parametrize("enforce_eager", [True, False], ids=["eager", "ar-graphs"])
|
||||
async def test_yue2_preemption_and_synthesis_abort(chunked, enforce_eager, monkeypatch) -> None:
|
||||
"""Force real preemption and abort only after NAR work has been submitted."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from vllm import SamplingParams
|
||||
|
||||
from tests.helpers.runtime import get_model_prefix
|
||||
from tests.helpers.stage_config import modify_stage_config
|
||||
from vllm_omni.entrypoints.async_omni import AsyncOmni
|
||||
from vllm_omni.model_executor.models.yue2.yue2 import (
|
||||
ABC_END,
|
||||
EOD,
|
||||
KEY_MAX_AUDIO_FRAMES,
|
||||
KEY_MAX_HOLD_STEPS,
|
||||
KEY_MIN_TOKENS,
|
||||
KEY_PHASE,
|
||||
KEY_PREFIX_IDS,
|
||||
KEY_SEED,
|
||||
KEY_SKIP_SYNTHESIS,
|
||||
STOP_TOKEN_IDS,
|
||||
)
|
||||
from vllm_omni.tokenizers.yue2_prompt import abc_prefix_ids, semantic_frames, semantic_prefix_ids
|
||||
from vllm_omni.tokenizers.yue2_tokenizer import YuE2TextTokenizer
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
model_path = Path(os.environ.get("YUE2_MODEL_DIR", get_model_prefix() + MODEL))
|
||||
if not model_path.is_dir():
|
||||
model_path = Path(hf_api().snapshot_download(str(model_path)))
|
||||
tokenizer = YuE2TextTokenizer(model_path / "qwen.tiktoken")
|
||||
prefix = semantic_prefix_ids(tokenizer.encode, CAPTION, LYRICS, "off")
|
||||
frames = 256
|
||||
# Each song fits alone, but four full songs cannot fit in 64 KV blocks.
|
||||
# Chunked recompute also replays output tokens past the original prompt.
|
||||
deploy = modify_stage_config(
|
||||
get_deploy_config_path("yue2.yaml"),
|
||||
updates={
|
||||
"stages": {
|
||||
0: {
|
||||
"enforce_eager": enforce_eager,
|
||||
"compilation_config": {
|
||||
"cudagraph_mode": "NONE" if enforce_eager else "FULL_AND_PIECEWISE",
|
||||
},
|
||||
"enable_chunked_prefill": chunked,
|
||||
"async_scheduling": True,
|
||||
"max_num_batched_tokens": 256 if chunked else 1024,
|
||||
"max_model_len": 1000,
|
||||
"num_gpu_blocks_override": 64,
|
||||
"block_size": 16,
|
||||
"max_num_seqs": 4,
|
||||
"tokenizer": str(model_path),
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
engine = AsyncOmni(
|
||||
model=str(model_path),
|
||||
deploy_config=deploy,
|
||||
worker_extension_cls="tests.e2e.features.yue2.worker_extension.Yue2LifecycleWorkerExtension",
|
||||
stage_init_timeout=600,
|
||||
init_timeout=900,
|
||||
)
|
||||
|
||||
async def probe():
|
||||
return (await engine.collective_rpc("get_yue2_probe", stage_ids=[0]))[0][0]
|
||||
|
||||
async def song(request_id, seed):
|
||||
params = SamplingParams(
|
||||
max_tokens=1000 - len(prefix),
|
||||
stop_token_ids=STOP_TOKEN_IDS,
|
||||
detokenize=False,
|
||||
extra_args={
|
||||
KEY_PREFIX_IDS: prefix,
|
||||
KEY_SEED: seed,
|
||||
KEY_MAX_AUDIO_FRAMES: frames,
|
||||
KEY_MIN_TOKENS: frames,
|
||||
KEY_MAX_HOLD_STEPS: 1000 - len(prefix) - frames - 1,
|
||||
},
|
||||
)
|
||||
audio = []
|
||||
tokens = []
|
||||
async for output in engine.generate(
|
||||
{"prompt_token_ids": prefix}, request_id=request_id, sampling_params_list=[params]
|
||||
):
|
||||
tokens = list(output.outputs[0].token_ids)
|
||||
multimodal = getattr(output.outputs[0], "multimodal_output", None)
|
||||
if multimodal is not None and "audio" in multimodal:
|
||||
data = multimodal["audio"]
|
||||
audio.extend(data if isinstance(data, list) else [data])
|
||||
assert audio, "request completed without audio"
|
||||
waveform = torch.cat([part.detach().cpu().reshape(-1) for part in audio])
|
||||
assert torch.isfinite(waveform).all() and waveform.abs().max() > 0
|
||||
assert len(semantic_frames(tokens)) == frames
|
||||
# The VAE convolution trims a small number of boundary samples.
|
||||
assert waveform.numel() == pytest.approx(frames * 1920 * 2, abs=256)
|
||||
|
||||
async def plan():
|
||||
abc_prefix = abc_prefix_ids(tokenizer.encode, CAPTION, LYRICS, "melody")
|
||||
params = SamplingParams(
|
||||
max_tokens=64,
|
||||
stop_token_ids=STOP_TOKEN_IDS,
|
||||
detokenize=False,
|
||||
extra_args={
|
||||
KEY_PHASE: "abc",
|
||||
KEY_PREFIX_IDS: abc_prefix,
|
||||
KEY_SEED: SEED,
|
||||
KEY_SKIP_SYNTHESIS: True,
|
||||
},
|
||||
)
|
||||
tokens = []
|
||||
async for output in engine.generate(
|
||||
{"prompt_token_ids": abc_prefix}, request_id="abc-plan", sampling_params_list=[params]
|
||||
):
|
||||
tokens = list(output.outputs[0].token_ids)
|
||||
assert tokens and all(t < EOD or t == ABC_END for t in tokens)
|
||||
|
||||
tasks = []
|
||||
try:
|
||||
assert await engine.collective_rpc("start_yue2_probe", stage_ids=[0]) == [[True]]
|
||||
tasks = [asyncio.create_task(plan())]
|
||||
tasks.extend(asyncio.create_task(song(f"preempt-{i}", SEED + i)) for i in range(4))
|
||||
await asyncio.wait_for(asyncio.gather(*tasks), timeout=600)
|
||||
observations = await probe()
|
||||
assert observations["preemptions"] > 0, observations
|
||||
assert observations["rollbacks"] > 0, observations
|
||||
assert observations["checked_rows"] >= 4 * frames, observations
|
||||
assert observations["mixed_steps"] > 0, observations
|
||||
if enforce_eager:
|
||||
assert observations["ar_full_replays"] == 0, observations
|
||||
else:
|
||||
assert observations["ar_full_replays"] > 0, observations
|
||||
|
||||
cancelled = asyncio.create_task(song("cancel-synthesis", SEED + 7))
|
||||
tasks.append(cancelled)
|
||||
deadline = asyncio.get_running_loop().time() + 120
|
||||
while not (await probe())["synthesis_started"]:
|
||||
assert not cancelled.done(), "song finished before the active-job cancellation probe"
|
||||
assert asyncio.get_running_loop().time() < deadline, "NAR job never started"
|
||||
await asyncio.sleep(0.05)
|
||||
cancelled.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await cancelled
|
||||
deadline = asyncio.get_running_loop().time() + 30
|
||||
while True:
|
||||
observations = await probe()
|
||||
if observations.get("removed"):
|
||||
assert observations["cancelled"] and observations["released"], observations
|
||||
break
|
||||
assert asyncio.get_running_loop().time() < deadline, observations
|
||||
await asyncio.sleep(0.05)
|
||||
await asyncio.wait_for(song("after-cancel", SEED + 8), timeout=120)
|
||||
observations = await probe()
|
||||
assert observations["released"]
|
||||
print("YuE2 lifecycle:", observations)
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
engine.shutdown()
|
||||
Reference in new issue
Block a user